xref: /llvm-project/llvm/lib/ExecutionEngine/JITLink/COFFLinkGraphBuilder.cpp (revision bc24e6ab7c5ebb40045d0efe49da94b5ccc30b16)
1 //=--------- COFFLinkGraphBuilder.cpp - COFF LinkGraph builder ----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Generic COFF LinkGraph buliding code.
10 //
11 //===----------------------------------------------------------------------===//
12 #include "COFFLinkGraphBuilder.h"
13 
14 #define DEBUG_TYPE "jitlink"
15 
16 static const char *CommonSectionName = "__common";
17 
18 namespace llvm {
19 namespace jitlink {
20 
21 static Triple createTripleWithCOFFFormat(Triple T) {
22   T.setObjectFormat(Triple::COFF);
23   return T;
24 }
25 
26 COFFLinkGraphBuilder::COFFLinkGraphBuilder(
27     const object::COFFObjectFile &Obj, Triple TT,
28     LinkGraph::GetEdgeKindNameFunction GetEdgeKindName)
29     : Obj(Obj),
30       G(std::make_unique<LinkGraph>(Obj.getFileName().str(),
31                                     createTripleWithCOFFFormat(TT),
32                                     getPointerSize(Obj), getEndianness(Obj),
33                                     std::move(GetEdgeKindName))) {
34   LLVM_DEBUG({
35     dbgs() << "Created COFFLinkGraphBuilder for \"" << Obj.getFileName()
36            << "\"\n";
37   });
38 }
39 
40 COFFLinkGraphBuilder::~COFFLinkGraphBuilder() = default;
41 
42 unsigned
43 COFFLinkGraphBuilder::getPointerSize(const object::COFFObjectFile &Obj) {
44   return Obj.getBytesInAddress();
45 }
46 
47 support::endianness
48 COFFLinkGraphBuilder::getEndianness(const object::COFFObjectFile &Obj) {
49   return Obj.isLittleEndian() ? support::little : support::big;
50 }
51 
52 uint64_t COFFLinkGraphBuilder::getSectionSize(const object::COFFObjectFile &Obj,
53                                               const object::coff_section *Sec) {
54   // Consider the difference between executable form and object form.
55   // More information is inside COFFObjectFile::getSectionSize
56   if (Obj.getDOSHeader())
57     return std::min(Sec->VirtualSize, Sec->SizeOfRawData);
58   return Sec->SizeOfRawData;
59 }
60 
61 uint64_t
62 COFFLinkGraphBuilder::getSectionAddress(const object::COFFObjectFile &Obj,
63                                         const object::coff_section *Section) {
64   return Section->VirtualAddress + Obj.getImageBase();
65 }
66 
67 bool COFFLinkGraphBuilder::isComdatSection(
68     const object::coff_section *Section) {
69   return Section->Characteristics & COFF::IMAGE_SCN_LNK_COMDAT;
70 }
71 
72 Section &COFFLinkGraphBuilder::getCommonSection() {
73   if (!CommonSection)
74     CommonSection =
75         &G->createSection(CommonSectionName, MemProt::Read | MemProt::Write);
76   return *CommonSection;
77 }
78 
79 Expected<std::unique_ptr<LinkGraph>> COFFLinkGraphBuilder::buildGraph() {
80   if (!Obj.isRelocatableObject())
81     return make_error<JITLinkError>("Object is not a relocatable COFF file");
82 
83   if (auto Err = graphifySections())
84     return std::move(Err);
85 
86   if (auto Err = graphifySymbols())
87     return std::move(Err);
88 
89   if (auto Err = addRelocations())
90     return std::move(Err);
91 
92   return std::move(G);
93 }
94 
95 StringRef
96 COFFLinkGraphBuilder::getCOFFSectionName(COFFSectionIndex SectionIndex,
97                                          const object::coff_section *Sec,
98                                          object::COFFSymbolRef Sym) {
99   switch (SectionIndex) {
100   case COFF::IMAGE_SYM_UNDEFINED: {
101     if (Sym.getValue())
102       return "(common)";
103     else
104       return "(external)";
105   }
106   case COFF::IMAGE_SYM_ABSOLUTE:
107     return "(absolute)";
108   case COFF::IMAGE_SYM_DEBUG: {
109     // Used with .file symbol
110     return "(debug)";
111   }
112   default: {
113     // Non reserved regular section numbers
114     if (Expected<StringRef> SecNameOrErr = Obj.getSectionName(Sec))
115       return *SecNameOrErr;
116   }
117   }
118   return "";
119 }
120 
121 Error COFFLinkGraphBuilder::graphifySections() {
122   LLVM_DEBUG(dbgs() << "  Creating graph sections...\n");
123 
124   GraphBlocks.resize(Obj.getNumberOfSections() + 1);
125   // For each section...
126   for (COFFSectionIndex SecIndex = 1;
127        SecIndex <= static_cast<COFFSectionIndex>(Obj.getNumberOfSections());
128        SecIndex++) {
129     Expected<const object::coff_section *> Sec = Obj.getSection(SecIndex);
130     if (!Sec)
131       return Sec.takeError();
132 
133     StringRef SectionName;
134     if (Expected<StringRef> SecNameOrErr = Obj.getSectionName(*Sec))
135       SectionName = *SecNameOrErr;
136 
137     // FIXME: Skip debug info sections
138 
139     LLVM_DEBUG({
140       dbgs() << "    "
141              << "Creating section for \"" << SectionName << "\"\n";
142     });
143 
144     // Get the section's memory protection flags.
145     MemProt Prot = MemProt::Read;
146     if ((*Sec)->Characteristics & COFF::IMAGE_SCN_MEM_EXECUTE)
147       Prot |= MemProt::Exec;
148     if ((*Sec)->Characteristics & COFF::IMAGE_SCN_MEM_READ)
149       Prot |= MemProt::Read;
150     if ((*Sec)->Characteristics & COFF::IMAGE_SCN_MEM_WRITE)
151       Prot |= MemProt::Write;
152 
153     // Look for existing sections first.
154     auto *GraphSec = G->findSectionByName(SectionName);
155     if (!GraphSec)
156       GraphSec = &G->createSection(SectionName, Prot);
157     if (GraphSec->getMemProt() != Prot)
158       return make_error<JITLinkError>("MemProt should match");
159 
160     Block *B = nullptr;
161     if ((*Sec)->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)
162       B = &G->createZeroFillBlock(
163           *GraphSec, getSectionSize(Obj, *Sec),
164           orc::ExecutorAddr(getSectionAddress(Obj, *Sec)),
165           (*Sec)->getAlignment(), 0);
166     else {
167       ArrayRef<uint8_t> Data;
168       if (auto Err = Obj.getSectionContents(*Sec, Data))
169         return Err;
170 
171       auto CharData = ArrayRef<char>(
172           reinterpret_cast<const char *>(Data.data()), Data.size());
173 
174       if (SectionName == getDirectiveSectionName())
175         if (auto Err = handleDirectiveSection(
176                 StringRef(CharData.data(), CharData.size())))
177           return Err;
178 
179       B = &G->createContentBlock(
180           *GraphSec, CharData, orc::ExecutorAddr(getSectionAddress(Obj, *Sec)),
181           (*Sec)->getAlignment(), 0);
182     }
183 
184     setGraphBlock(SecIndex, B);
185   }
186 
187   return Error::success();
188 }
189 
190 Error COFFLinkGraphBuilder::graphifySymbols() {
191   LLVM_DEBUG(dbgs() << "  Creating graph symbols...\n");
192 
193   SymbolSets.resize(Obj.getNumberOfSections() + 1);
194   PendingComdatExports.resize(Obj.getNumberOfSections() + 1);
195   GraphSymbols.resize(Obj.getNumberOfSymbols());
196 
197   for (COFFSymbolIndex SymIndex = 0;
198        SymIndex < static_cast<COFFSymbolIndex>(Obj.getNumberOfSymbols());
199        SymIndex++) {
200     Expected<object::COFFSymbolRef> Sym = Obj.getSymbol(SymIndex);
201     if (!Sym)
202       return Sym.takeError();
203 
204     StringRef SymbolName;
205     if (Expected<StringRef> SymNameOrErr = Obj.getSymbolName(*Sym))
206       SymbolName = *SymNameOrErr;
207 
208     COFFSectionIndex SectionIndex = Sym->getSectionNumber();
209     const object::coff_section *Sec = nullptr;
210 
211     if (!COFF::isReservedSectionNumber(SectionIndex)) {
212       auto SecOrErr = Obj.getSection(SectionIndex);
213       if (!SecOrErr)
214         return make_error<JITLinkError>(
215             "Invalid COFF section number:" + formatv("{0:d}: ", SectionIndex) +
216             " (" + toString(SecOrErr.takeError()) + ")");
217       Sec = *SecOrErr;
218     }
219 
220     // Create jitlink symbol
221     jitlink::Symbol *GSym = nullptr;
222     if (Sym->isFileRecord())
223       LLVM_DEBUG({
224         dbgs() << "    " << SymIndex << ": Skipping FileRecord symbol \""
225                << SymbolName << "\" in "
226                << getCOFFSectionName(SectionIndex, Sec, *Sym)
227                << " (index: " << SectionIndex << ") \n";
228       });
229     else if (Sym->isUndefined()) {
230       GSym = createExternalSymbol(SymIndex, SymbolName, *Sym, Sec);
231     } else if (Sym->isWeakExternal()) {
232       auto *WeakExternal = Sym->getAux<object::coff_aux_weak_external>();
233       COFFSymbolIndex TagIndex = WeakExternal->TagIndex;
234       uint32_t Characteristics = WeakExternal->Characteristics;
235       WeakExternalRequests.push_back(
236           {SymIndex, TagIndex, Characteristics, SymbolName});
237     } else {
238       Expected<jitlink::Symbol *> NewGSym =
239           createDefinedSymbol(SymIndex, SymbolName, *Sym, Sec);
240       if (!NewGSym)
241         return NewGSym.takeError();
242       GSym = *NewGSym;
243       if (GSym) {
244         LLVM_DEBUG({
245           dbgs() << "    " << SymIndex
246                  << ": Creating defined graph symbol for COFF symbol \""
247                  << SymbolName << "\" in "
248                  << getCOFFSectionName(SectionIndex, Sec, *Sym)
249                  << " (index: " << SectionIndex << ") \n";
250           dbgs() << "      " << *GSym << "\n";
251         });
252       }
253     }
254 
255     // Register the symbol
256     if (GSym)
257       setGraphSymbol(SectionIndex, SymIndex, *GSym);
258     SymIndex += Sym->getNumberOfAuxSymbols();
259   }
260 
261   if (auto Err = flushWeakAliasRequests())
262     return Err;
263 
264   if (auto Err = handleAlternateNames())
265     return Err;
266 
267   if (auto Err = calculateImplicitSizeOfSymbols())
268     return Err;
269 
270   return Error::success();
271 }
272 
273 Error COFFLinkGraphBuilder::handleDirectiveSection(StringRef Str) {
274   auto Parsed = DirectiveParser.parse(Str);
275   if (!Parsed)
276     return Parsed.takeError();
277   for (auto *Arg : *Parsed) {
278     StringRef S = Arg->getValue();
279     switch (Arg->getOption().getID()) {
280     case COFF_OPT_alternatename: {
281       StringRef From, To;
282       std::tie(From, To) = S.split('=');
283       if (From.empty() || To.empty())
284         return make_error<JITLinkError>(
285             "Invalid COFF /alternatename directive");
286       AlternateNames[From] = To;
287       break;
288     }
289     case COFF_OPT_incl: {
290       auto DataCopy = G->allocateString(S);
291       StringRef StrCopy(DataCopy.data(), DataCopy.size());
292       ExternalSymbols[StrCopy] =
293           &G->addExternalSymbol(StrCopy, 0, Linkage::Strong);
294       ExternalSymbols[StrCopy]->setLive(true);
295       break;
296     }
297     case COFF_OPT_export:
298       break;
299     default: {
300       LLVM_DEBUG({
301         dbgs() << "Unknown coff directive: " << Arg->getSpelling() << "\n";
302       });
303       break;
304     }
305     }
306   }
307   return Error::success();
308 }
309 
310 Error COFFLinkGraphBuilder::flushWeakAliasRequests() {
311   // Export the weak external symbols and alias it
312   for (auto &WeakExternal : WeakExternalRequests) {
313     if (auto *Target = getGraphSymbol(WeakExternal.Target)) {
314       Expected<object::COFFSymbolRef> AliasSymbol =
315           Obj.getSymbol(WeakExternal.Alias);
316       if (!AliasSymbol)
317         return AliasSymbol.takeError();
318 
319       // FIXME: IMAGE_WEAK_EXTERN_SEARCH_NOLIBRARY and
320       // IMAGE_WEAK_EXTERN_SEARCH_LIBRARY are handled in the same way.
321       Scope S =
322           WeakExternal.Characteristics == COFF::IMAGE_WEAK_EXTERN_SEARCH_ALIAS
323               ? Scope::Default
324               : Scope::Local;
325 
326       auto NewSymbol =
327           createAliasSymbol(WeakExternal.SymbolName, Linkage::Weak, S, *Target);
328       if (!NewSymbol)
329         return NewSymbol.takeError();
330       setGraphSymbol(AliasSymbol->getSectionNumber(), WeakExternal.Alias,
331                      **NewSymbol);
332       LLVM_DEBUG({
333         dbgs() << "    " << WeakExternal.Alias
334                << ": Creating weak external symbol for COFF symbol \""
335                << WeakExternal.SymbolName << "\" in section "
336                << AliasSymbol->getSectionNumber() << "\n";
337         dbgs() << "      " << **NewSymbol << "\n";
338       });
339     } else
340       return make_error<JITLinkError>("Weak symbol alias requested but actual "
341                                       "symbol not found for symbol " +
342                                       formatv("{0:d}", WeakExternal.Alias));
343   }
344   return Error::success();
345 }
346 
347 Error COFFLinkGraphBuilder::handleAlternateNames() {
348   for (auto &KeyValue : AlternateNames)
349     if (DefinedSymbols.count(KeyValue.second) &&
350         ExternalSymbols.count(KeyValue.first)) {
351       auto *Target = DefinedSymbols[KeyValue.second];
352       auto *Alias = ExternalSymbols[KeyValue.first];
353       G->makeDefined(*Alias, Target->getBlock(), Target->getOffset(),
354                      Target->getSize(), Linkage::Weak, Scope::Local, false);
355     }
356   return Error::success();
357 }
358 
359 Symbol *COFFLinkGraphBuilder::createExternalSymbol(
360     COFFSymbolIndex SymIndex, StringRef SymbolName,
361     object::COFFSymbolRef Symbol, const object::coff_section *Section) {
362   if (!ExternalSymbols.count(SymbolName))
363     ExternalSymbols[SymbolName] =
364         &G->addExternalSymbol(SymbolName, Symbol.getValue(), Linkage::Strong);
365 
366   LLVM_DEBUG({
367     dbgs() << "    " << SymIndex
368            << ": Creating external graph symbol for COFF symbol \""
369            << SymbolName << "\" in "
370            << getCOFFSectionName(Symbol.getSectionNumber(), Section, Symbol)
371            << " (index: " << Symbol.getSectionNumber() << ") \n";
372   });
373   return ExternalSymbols[SymbolName];
374 }
375 
376 Expected<Symbol *> COFFLinkGraphBuilder::createAliasSymbol(StringRef SymbolName,
377                                                            Linkage L, Scope S,
378                                                            Symbol &Target) {
379   if (!Target.isDefined()) {
380     // FIXME: Support this when there's a way to handle this.
381     return make_error<JITLinkError>("Weak external symbol with external "
382                                     "symbol as alternative not supported.");
383   }
384   return &G->addDefinedSymbol(Target.getBlock(), Target.getOffset(), SymbolName,
385                               Target.getSize(), L, S, Target.isCallable(),
386                               false);
387 }
388 
389 // In COFF, most of the defined symbols don't contain the size information.
390 // Hence, we calculate the "implicit" size of symbol by taking the delta of
391 // offsets of consecutive symbols within a block. We maintain a balanced tree
392 // set of symbols sorted by offset per each block in order to achieve
393 // logarithmic time complexity of sorted symbol insertion. Symbol is inserted to
394 // the set once it's processed in graphifySymbols. In this function, we iterate
395 // each collected symbol in sorted order and calculate the implicit size.
396 Error COFFLinkGraphBuilder::calculateImplicitSizeOfSymbols() {
397   for (COFFSectionIndex SecIndex = 1;
398        SecIndex <= static_cast<COFFSectionIndex>(Obj.getNumberOfSections());
399        SecIndex++) {
400     auto &SymbolSet = SymbolSets[SecIndex];
401     if (SymbolSet.empty())
402       continue;
403     jitlink::Block *B = getGraphBlock(SecIndex);
404     orc::ExecutorAddrDiff LastOffset = B->getSize();
405     orc::ExecutorAddrDiff LastDifferentOffset = B->getSize();
406     orc::ExecutorAddrDiff LastSize = 0;
407     for (auto It = SymbolSet.rbegin(); It != SymbolSet.rend(); It++) {
408       orc::ExecutorAddrDiff Offset = It->first;
409       jitlink::Symbol *Symbol = It->second;
410       orc::ExecutorAddrDiff CandSize;
411       // Last offset can be same when aliasing happened
412       if (Symbol->getOffset() == LastOffset)
413         CandSize = LastSize;
414       else
415         CandSize = LastOffset - Offset;
416 
417       LLVM_DEBUG({
418         if (Offset + Symbol->getSize() > LastDifferentOffset)
419           dbgs() << "  Overlapping symbol range generated for the following "
420                     "symbol:"
421                  << "\n"
422                  << "    " << *Symbol << "\n";
423       });
424       (void)LastDifferentOffset;
425       if (LastOffset != Offset)
426         LastDifferentOffset = Offset;
427       LastSize = CandSize;
428       LastOffset = Offset;
429       if (Symbol->getSize()) {
430         // Non empty symbol can happen in COMDAT symbol.
431         // We don't consider the possibility of overlapping symbol range that
432         // could be introduced by disparity between inferred symbol size and
433         // defined symbol size because symbol size information is currently only
434         // used by jitlink-check where we have control to not make overlapping
435         // ranges.
436         continue;
437       }
438 
439       LLVM_DEBUG({
440         if (!CandSize)
441           dbgs() << "  Empty implicit symbol size generated for the following "
442                     "symbol:"
443                  << "\n"
444                  << "    " << *Symbol << "\n";
445       });
446 
447       Symbol->setSize(CandSize);
448     }
449   }
450   return Error::success();
451 }
452 
453 Expected<Symbol *> COFFLinkGraphBuilder::createDefinedSymbol(
454     COFFSymbolIndex SymIndex, StringRef SymbolName,
455     object::COFFSymbolRef Symbol, const object::coff_section *Section) {
456   if (Symbol.isCommon()) {
457     // FIXME: correct alignment
458     return &G->addCommonSymbol(SymbolName, Scope::Default, getCommonSection(),
459                                orc::ExecutorAddr(), Symbol.getValue(),
460                                Symbol.getValue(), false);
461   }
462   if (Symbol.isAbsolute())
463     return &G->addAbsoluteSymbol(SymbolName,
464                                  orc::ExecutorAddr(Symbol.getValue()), 0,
465                                  Linkage::Strong, Scope::Local, false);
466 
467   if (llvm::COFF::isReservedSectionNumber(Symbol.getSectionNumber()))
468     return make_error<JITLinkError>(
469         "Reserved section number used in regular symbol " +
470         formatv("{0:d}", SymIndex));
471 
472   Block *B = getGraphBlock(Symbol.getSectionNumber());
473   if (!B) {
474     LLVM_DEBUG({
475       dbgs() << "    " << SymIndex
476              << ": Skipping graph symbol since section was not created for "
477                 "COFF symbol \""
478              << SymbolName << "\" in section " << Symbol.getSectionNumber()
479              << "\n";
480     });
481     return nullptr;
482   }
483 
484   if (Symbol.isExternal()) {
485     // This is not a comdat sequence, export the symbol as it is
486     if (!isComdatSection(Section)) {
487       auto GSym = &G->addDefinedSymbol(
488           *B, Symbol.getValue(), SymbolName, 0, Linkage::Strong, Scope::Default,
489           Symbol.getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION, false);
490       DefinedSymbols[SymbolName] = GSym;
491       return GSym;
492     } else {
493       if (!PendingComdatExports[Symbol.getSectionNumber()])
494         return make_error<JITLinkError>("No pending COMDAT export for symbol " +
495                                         formatv("{0:d}", SymIndex));
496 
497       return exportCOMDATSymbol(SymIndex, SymbolName, Symbol);
498     }
499   }
500 
501   if (Symbol.getStorageClass() == COFF::IMAGE_SYM_CLASS_STATIC ||
502       Symbol.getStorageClass() == COFF::IMAGE_SYM_CLASS_LABEL) {
503     const object::coff_aux_section_definition *Definition =
504         Symbol.getSectionDefinition();
505     if (!Definition || !isComdatSection(Section)) {
506       // Handle typical static symbol
507       return &G->addDefinedSymbol(
508           *B, Symbol.getValue(), SymbolName, 0, Linkage::Strong, Scope::Local,
509           Symbol.getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION, false);
510     }
511     if (Definition->Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
512       auto Target = Definition->getNumber(Symbol.isBigObj());
513       auto GSym = &G->addDefinedSymbol(
514           *B, Symbol.getValue(), SymbolName, 0, Linkage::Strong, Scope::Local,
515           Symbol.getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION, false);
516       getGraphBlock(Target)->addEdge(Edge::KeepAlive, 0, *GSym, 0);
517       return GSym;
518     }
519     if (PendingComdatExports[Symbol.getSectionNumber()])
520       return make_error<JITLinkError>(
521           "COMDAT export request already exists before symbol " +
522           formatv("{0:d}", SymIndex));
523     return createCOMDATExportRequest(SymIndex, Symbol, Definition);
524   }
525   return make_error<JITLinkError>("Unsupported storage class " +
526                                   formatv("{0:d}", Symbol.getStorageClass()) +
527                                   " in symbol " + formatv("{0:d}", SymIndex));
528 }
529 
530 // COMDAT handling:
531 // When IMAGE_SCN_LNK_COMDAT flag is set in the flags of a section,
532 // the section is called a COMDAT section. It contains two symbols
533 // in a sequence that specifes the behavior. First symbol is the section
534 // symbol which contains the size and name of the section. It also contains
535 // selection type that specifies how duplicate of the symbol is handled.
536 // Second symbol is COMDAT symbol which usually defines the external name and
537 // data type.
538 //
539 // Since two symbols always come in a specific order, we initiate pending COMDAT
540 // export request when we encounter the first symbol and actually exports it
541 // when we process the second symbol.
542 //
543 // Process the first symbol of COMDAT sequence.
544 Expected<Symbol *> COFFLinkGraphBuilder::createCOMDATExportRequest(
545     COFFSymbolIndex SymIndex, object::COFFSymbolRef Symbol,
546     const object::coff_aux_section_definition *Definition) {
547   Linkage L = Linkage::Strong;
548   switch (Definition->Selection) {
549   case COFF::IMAGE_COMDAT_SELECT_NODUPLICATES: {
550     L = Linkage::Strong;
551     break;
552   }
553   case COFF::IMAGE_COMDAT_SELECT_ANY: {
554     L = Linkage::Weak;
555     break;
556   }
557   case COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH:
558   case COFF::IMAGE_COMDAT_SELECT_SAME_SIZE: {
559     // FIXME: Implement size/content validation when LinkGraph is able to
560     // handle this.
561     L = Linkage::Weak;
562     break;
563   }
564   case COFF::IMAGE_COMDAT_SELECT_LARGEST: {
565     // FIXME: Support IMAGE_COMDAT_SELECT_LARGEST properly when LinkGraph is
566     // able to handle this.
567     LLVM_DEBUG({
568       dbgs() << "    " << SymIndex
569              << ": Partially supported IMAGE_COMDAT_SELECT_LARGEST was used"
570                 " in section "
571              << Symbol.getSectionNumber() << " (size: " << Definition->Length
572              << ")\n";
573     });
574     L = Linkage::Weak;
575     break;
576   }
577   case COFF::IMAGE_COMDAT_SELECT_NEWEST: {
578     // Even link.exe doesn't support this selection properly.
579     return make_error<JITLinkError>(
580         "IMAGE_COMDAT_SELECT_NEWEST is not supported.");
581   }
582   default: {
583     return make_error<JITLinkError>("Invalid comdat selection type: " +
584                                     formatv("{0:d}", Definition->Selection));
585   }
586   }
587   PendingComdatExports[Symbol.getSectionNumber()] = {SymIndex, L,
588                                                      Definition->Length};
589   return nullptr;
590 }
591 
592 // Process the second symbol of COMDAT sequence.
593 Expected<Symbol *>
594 COFFLinkGraphBuilder::exportCOMDATSymbol(COFFSymbolIndex SymIndex,
595                                          StringRef SymbolName,
596                                          object::COFFSymbolRef Symbol) {
597   Block *B = getGraphBlock(Symbol.getSectionNumber());
598   auto &PendingComdatExport = PendingComdatExports[Symbol.getSectionNumber()];
599   // NOTE: ComdatDef->Legnth is the size of "section" not size of symbol.
600   // We use zero symbol size to not reach out of bound of block when symbol
601   // offset is non-zero.
602   auto GSym = &G->addDefinedSymbol(
603       *B, Symbol.getValue(), SymbolName, 0, PendingComdatExport->Linkage,
604       Scope::Default, Symbol.getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION,
605       false);
606   LLVM_DEBUG({
607     dbgs() << "    " << SymIndex
608            << ": Exporting COMDAT graph symbol for COFF symbol \"" << SymbolName
609            << "\" in section " << Symbol.getSectionNumber() << "\n";
610     dbgs() << "      " << *GSym << "\n";
611   });
612   setGraphSymbol(Symbol.getSectionNumber(), PendingComdatExport->SymbolIndex,
613                  *GSym);
614   DefinedSymbols[SymbolName] = GSym;
615   PendingComdatExport = None;
616   return GSym;
617 }
618 
619 } // namespace jitlink
620 } // namespace llvm
621