1 //===- InputFiles.cpp -----------------------------------------------------===//
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 #include "InputFiles.h"
10 #include "Config.h"
11 #include "InputChunks.h"
12 #include "InputEvent.h"
13 #include "InputGlobal.h"
14 #include "OutputSegment.h"
15 #include "SymbolTable.h"
16 #include "lld/Common/ErrorHandler.h"
17 #include "lld/Common/Memory.h"
18 #include "lld/Common/Reproduce.h"
19 #include "llvm/Object/Binary.h"
20 #include "llvm/Object/Wasm.h"
21 #include "llvm/Support/TarWriter.h"
22 #include "llvm/Support/raw_ostream.h"
23
24 #define DEBUG_TYPE "lld"
25
26 using namespace llvm;
27 using namespace llvm::object;
28 using namespace llvm::wasm;
29
30 namespace lld {
31
32 // Returns a string in the format of "foo.o" or "foo.a(bar.o)".
toString(const wasm::InputFile * file)33 std::string toString(const wasm::InputFile *file) {
34 if (!file)
35 return "<internal>";
36
37 if (file->archiveName.empty())
38 return std::string(file->getName());
39
40 return (file->archiveName + "(" + file->getName() + ")").str();
41 }
42
43 namespace wasm {
44
checkArch(Triple::ArchType arch) const45 void InputFile::checkArch(Triple::ArchType arch) const {
46 bool is64 = arch == Triple::wasm64;
47 if (is64 && !config->is64.hasValue()) {
48 fatal(toString(this) +
49 ": must specify -mwasm64 to process wasm64 object files");
50 } else if (config->is64.getValueOr(false) != is64) {
51 fatal(toString(this) +
52 ": wasm32 object file can't be linked in wasm64 mode");
53 }
54 }
55
56 std::unique_ptr<llvm::TarWriter> tar;
57
readFile(StringRef path)58 Optional<MemoryBufferRef> readFile(StringRef path) {
59 log("Loading: " + path);
60
61 auto mbOrErr = MemoryBuffer::getFile(path);
62 if (auto ec = mbOrErr.getError()) {
63 error("cannot open " + path + ": " + ec.message());
64 return None;
65 }
66 std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
67 MemoryBufferRef mbref = mb->getMemBufferRef();
68 make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take MB ownership
69
70 if (tar)
71 tar->append(relativeToRoot(path), mbref.getBuffer());
72 return mbref;
73 }
74
createObjectFile(MemoryBufferRef mb,StringRef archiveName)75 InputFile *createObjectFile(MemoryBufferRef mb, StringRef archiveName) {
76 file_magic magic = identify_magic(mb.getBuffer());
77 if (magic == file_magic::wasm_object) {
78 std::unique_ptr<Binary> bin =
79 CHECK(createBinary(mb), mb.getBufferIdentifier());
80 auto *obj = cast<WasmObjectFile>(bin.get());
81 if (obj->isSharedObject())
82 return make<SharedFile>(mb);
83 return make<ObjFile>(mb, archiveName);
84 }
85
86 if (magic == file_magic::bitcode)
87 return make<BitcodeFile>(mb, archiveName);
88
89 fatal("unknown file type: " + mb.getBufferIdentifier());
90 }
91
dumpInfo() const92 void ObjFile::dumpInfo() const {
93 log("info for: " + toString(this) +
94 "\n Symbols : " + Twine(symbols.size()) +
95 "\n Function Imports : " + Twine(wasmObj->getNumImportedFunctions()) +
96 "\n Global Imports : " + Twine(wasmObj->getNumImportedGlobals()) +
97 "\n Event Imports : " + Twine(wasmObj->getNumImportedEvents()));
98 }
99
100 // Relocations contain either symbol or type indices. This function takes a
101 // relocation and returns relocated index (i.e. translates from the input
102 // symbol/type space to the output symbol/type space).
calcNewIndex(const WasmRelocation & reloc) const103 uint32_t ObjFile::calcNewIndex(const WasmRelocation &reloc) const {
104 if (reloc.Type == R_WASM_TYPE_INDEX_LEB) {
105 assert(typeIsUsed[reloc.Index]);
106 return typeMap[reloc.Index];
107 }
108 const Symbol *sym = symbols[reloc.Index];
109 if (auto *ss = dyn_cast<SectionSymbol>(sym))
110 sym = ss->getOutputSectionSymbol();
111 return sym->getOutputSymbolIndex();
112 }
113
114 // Relocations can contain addend for combined sections. This function takes a
115 // relocation and returns updated addend by offset in the output section.
calcNewAddend(const WasmRelocation & reloc) const116 uint64_t ObjFile::calcNewAddend(const WasmRelocation &reloc) const {
117 switch (reloc.Type) {
118 case R_WASM_MEMORY_ADDR_LEB:
119 case R_WASM_MEMORY_ADDR_LEB64:
120 case R_WASM_MEMORY_ADDR_SLEB64:
121 case R_WASM_MEMORY_ADDR_SLEB:
122 case R_WASM_MEMORY_ADDR_REL_SLEB:
123 case R_WASM_MEMORY_ADDR_REL_SLEB64:
124 case R_WASM_MEMORY_ADDR_I32:
125 case R_WASM_MEMORY_ADDR_I64:
126 case R_WASM_FUNCTION_OFFSET_I32:
127 case R_WASM_FUNCTION_OFFSET_I64:
128 return reloc.Addend;
129 case R_WASM_SECTION_OFFSET_I32:
130 return getSectionSymbol(reloc.Index)->section->outputOffset + reloc.Addend;
131 default:
132 llvm_unreachable("unexpected relocation type");
133 }
134 }
135
136 // Calculate the value we expect to find at the relocation location.
137 // This is used as a sanity check before applying a relocation to a given
138 // location. It is useful for catching bugs in the compiler and linker.
calcExpectedValue(const WasmRelocation & reloc) const139 uint64_t ObjFile::calcExpectedValue(const WasmRelocation &reloc) const {
140 switch (reloc.Type) {
141 case R_WASM_TABLE_INDEX_I32:
142 case R_WASM_TABLE_INDEX_I64:
143 case R_WASM_TABLE_INDEX_SLEB:
144 case R_WASM_TABLE_INDEX_SLEB64: {
145 const WasmSymbol &sym = wasmObj->syms()[reloc.Index];
146 return tableEntries[sym.Info.ElementIndex];
147 }
148 case R_WASM_TABLE_INDEX_REL_SLEB: {
149 const WasmSymbol &sym = wasmObj->syms()[reloc.Index];
150 return tableEntriesRel[sym.Info.ElementIndex];
151 }
152 case R_WASM_MEMORY_ADDR_LEB:
153 case R_WASM_MEMORY_ADDR_LEB64:
154 case R_WASM_MEMORY_ADDR_SLEB:
155 case R_WASM_MEMORY_ADDR_SLEB64:
156 case R_WASM_MEMORY_ADDR_REL_SLEB:
157 case R_WASM_MEMORY_ADDR_REL_SLEB64:
158 case R_WASM_MEMORY_ADDR_I32:
159 case R_WASM_MEMORY_ADDR_I64:
160 case R_WASM_MEMORY_ADDR_TLS_SLEB: {
161 const WasmSymbol &sym = wasmObj->syms()[reloc.Index];
162 if (sym.isUndefined())
163 return 0;
164 const WasmSegment &segment =
165 wasmObj->dataSegments()[sym.Info.DataRef.Segment];
166 if (segment.Data.Offset.Opcode == WASM_OPCODE_I32_CONST)
167 return segment.Data.Offset.Value.Int32 + sym.Info.DataRef.Offset +
168 reloc.Addend;
169 else if (segment.Data.Offset.Opcode == WASM_OPCODE_I64_CONST)
170 return segment.Data.Offset.Value.Int64 + sym.Info.DataRef.Offset +
171 reloc.Addend;
172 else
173 llvm_unreachable("unknown init expr opcode");
174 }
175 case R_WASM_FUNCTION_OFFSET_I32:
176 case R_WASM_FUNCTION_OFFSET_I64: {
177 const WasmSymbol &sym = wasmObj->syms()[reloc.Index];
178 InputFunction *f =
179 functions[sym.Info.ElementIndex - wasmObj->getNumImportedFunctions()];
180 return f->getFunctionInputOffset() + f->getFunctionCodeOffset() +
181 reloc.Addend;
182 }
183 case R_WASM_SECTION_OFFSET_I32:
184 return reloc.Addend;
185 case R_WASM_TYPE_INDEX_LEB:
186 return reloc.Index;
187 case R_WASM_FUNCTION_INDEX_LEB:
188 case R_WASM_GLOBAL_INDEX_LEB:
189 case R_WASM_GLOBAL_INDEX_I32:
190 case R_WASM_EVENT_INDEX_LEB: {
191 const WasmSymbol &sym = wasmObj->syms()[reloc.Index];
192 return sym.Info.ElementIndex;
193 }
194 default:
195 llvm_unreachable("unknown relocation type");
196 }
197 }
198
199 // Translate from the relocation's index into the final linked output value.
calcNewValue(const WasmRelocation & reloc,uint64_t tombstone) const200 uint64_t ObjFile::calcNewValue(const WasmRelocation &reloc, uint64_t tombstone) const {
201 const Symbol* sym = nullptr;
202 if (reloc.Type != R_WASM_TYPE_INDEX_LEB) {
203 sym = symbols[reloc.Index];
204
205 // We can end up with relocations against non-live symbols. For example
206 // in debug sections. We return a tombstone value in debug symbol sections
207 // so this will not produce a valid range conflicting with ranges of actual
208 // code. In other sections we return reloc.Addend.
209
210 if ((isa<FunctionSymbol>(sym) || isa<DataSymbol>(sym)) && !sym->isLive())
211 return tombstone ? tombstone : reloc.Addend;
212 }
213
214 switch (reloc.Type) {
215 case R_WASM_TABLE_INDEX_I32:
216 case R_WASM_TABLE_INDEX_I64:
217 case R_WASM_TABLE_INDEX_SLEB:
218 case R_WASM_TABLE_INDEX_SLEB64:
219 case R_WASM_TABLE_INDEX_REL_SLEB: {
220 if (!getFunctionSymbol(reloc.Index)->hasTableIndex())
221 return 0;
222 uint32_t index = getFunctionSymbol(reloc.Index)->getTableIndex();
223 if (reloc.Type == R_WASM_TABLE_INDEX_REL_SLEB)
224 index -= config->tableBase;
225 return index;
226
227 }
228 case R_WASM_MEMORY_ADDR_LEB:
229 case R_WASM_MEMORY_ADDR_LEB64:
230 case R_WASM_MEMORY_ADDR_SLEB:
231 case R_WASM_MEMORY_ADDR_SLEB64:
232 case R_WASM_MEMORY_ADDR_REL_SLEB:
233 case R_WASM_MEMORY_ADDR_REL_SLEB64:
234 case R_WASM_MEMORY_ADDR_I32:
235 case R_WASM_MEMORY_ADDR_I64: {
236 if (isa<UndefinedData>(sym) || sym->isUndefWeak())
237 return 0;
238 auto D = cast<DefinedData>(sym);
239 // Treat non-TLS relocation against symbols that live in the TLS segment
240 // like TLS relocations. This beaviour exists to support older object
241 // files created before we introduced TLS relocations.
242 // TODO(sbc): Remove this legacy behaviour one day. This will break
243 // backward compat with old object files built with `-fPIC`.
244 if (D->segment && D->segment->outputSeg->name == ".tdata")
245 return D->getOutputSegmentOffset() + reloc.Addend;
246 return D->getVirtualAddress() + reloc.Addend;
247 }
248 case R_WASM_MEMORY_ADDR_TLS_SLEB:
249 if (isa<UndefinedData>(sym) || sym->isUndefWeak())
250 return 0;
251 // TLS relocations are relative to the start of the TLS output segment
252 return cast<DefinedData>(sym)->getOutputSegmentOffset() + reloc.Addend;
253 case R_WASM_TYPE_INDEX_LEB:
254 return typeMap[reloc.Index];
255 case R_WASM_FUNCTION_INDEX_LEB:
256 return getFunctionSymbol(reloc.Index)->getFunctionIndex();
257 case R_WASM_GLOBAL_INDEX_LEB:
258 case R_WASM_GLOBAL_INDEX_I32:
259 if (auto gs = dyn_cast<GlobalSymbol>(sym))
260 return gs->getGlobalIndex();
261 return sym->getGOTIndex();
262 case R_WASM_EVENT_INDEX_LEB:
263 return getEventSymbol(reloc.Index)->getEventIndex();
264 case R_WASM_FUNCTION_OFFSET_I32:
265 case R_WASM_FUNCTION_OFFSET_I64: {
266 auto *f = cast<DefinedFunction>(sym);
267 return f->function->outputOffset +
268 (f->function->getFunctionCodeOffset() + reloc.Addend);
269 }
270 case R_WASM_SECTION_OFFSET_I32:
271 return getSectionSymbol(reloc.Index)->section->outputOffset + reloc.Addend;
272 default:
273 llvm_unreachable("unknown relocation type");
274 }
275 }
276
277 template <class T>
setRelocs(const std::vector<T * > & chunks,const WasmSection * section)278 static void setRelocs(const std::vector<T *> &chunks,
279 const WasmSection *section) {
280 if (!section)
281 return;
282
283 ArrayRef<WasmRelocation> relocs = section->Relocations;
284 assert(llvm::is_sorted(
285 relocs, [](const WasmRelocation &r1, const WasmRelocation &r2) {
286 return r1.Offset < r2.Offset;
287 }));
288 assert(llvm::is_sorted(chunks, [](InputChunk *c1, InputChunk *c2) {
289 return c1->getInputSectionOffset() < c2->getInputSectionOffset();
290 }));
291
292 auto relocsNext = relocs.begin();
293 auto relocsEnd = relocs.end();
294 auto relocLess = [](const WasmRelocation &r, uint32_t val) {
295 return r.Offset < val;
296 };
297 for (InputChunk *c : chunks) {
298 auto relocsStart = std::lower_bound(relocsNext, relocsEnd,
299 c->getInputSectionOffset(), relocLess);
300 relocsNext = std::lower_bound(
301 relocsStart, relocsEnd, c->getInputSectionOffset() + c->getInputSize(),
302 relocLess);
303 c->setRelocations(ArrayRef<WasmRelocation>(relocsStart, relocsNext));
304 }
305 }
306
parse(bool ignoreComdats)307 void ObjFile::parse(bool ignoreComdats) {
308 // Parse a memory buffer as a wasm file.
309 LLVM_DEBUG(dbgs() << "Parsing object: " << toString(this) << "\n");
310 std::unique_ptr<Binary> bin = CHECK(createBinary(mb), toString(this));
311
312 auto *obj = dyn_cast<WasmObjectFile>(bin.get());
313 if (!obj)
314 fatal(toString(this) + ": not a wasm file");
315 if (!obj->isRelocatableObject())
316 fatal(toString(this) + ": not a relocatable wasm file");
317
318 bin.release();
319 wasmObj.reset(obj);
320
321 checkArch(obj->getArch());
322
323 // Build up a map of function indices to table indices for use when
324 // verifying the existing table index relocations
325 uint32_t totalFunctions =
326 wasmObj->getNumImportedFunctions() + wasmObj->functions().size();
327 tableEntriesRel.resize(totalFunctions);
328 tableEntries.resize(totalFunctions);
329 for (const WasmElemSegment &seg : wasmObj->elements()) {
330 int64_t offset;
331 if (seg.Offset.Opcode == WASM_OPCODE_I32_CONST)
332 offset = seg.Offset.Value.Int32;
333 else if (seg.Offset.Opcode == WASM_OPCODE_I64_CONST)
334 offset = seg.Offset.Value.Int64;
335 else
336 fatal(toString(this) + ": invalid table elements");
337 for (size_t index = 0; index < seg.Functions.size(); index++) {
338 auto functionIndex = seg.Functions[index];
339 tableEntriesRel[functionIndex] = index;
340 tableEntries[functionIndex] = offset + index;
341 }
342 }
343
344 uint32_t sectionIndex = 0;
345
346 // Bool for each symbol, true if called directly. This allows us to implement
347 // a weaker form of signature checking where undefined functions that are not
348 // called directly (i.e. only address taken) don't have to match the defined
349 // function's signature. We cannot do this for directly called functions
350 // because those signatures are checked at validation times.
351 // See https://bugs.llvm.org/show_bug.cgi?id=40412
352 std::vector<bool> isCalledDirectly(wasmObj->getNumberOfSymbols(), false);
353 for (const SectionRef &sec : wasmObj->sections()) {
354 const WasmSection §ion = wasmObj->getWasmSection(sec);
355 // Wasm objects can have at most one code and one data section.
356 if (section.Type == WASM_SEC_CODE) {
357 assert(!codeSection);
358 codeSection = §ion;
359 } else if (section.Type == WASM_SEC_DATA) {
360 assert(!dataSection);
361 dataSection = §ion;
362 } else if (section.Type == WASM_SEC_CUSTOM) {
363 customSections.emplace_back(make<InputSection>(section, this));
364 customSections.back()->setRelocations(section.Relocations);
365 customSectionsByIndex[sectionIndex] = customSections.back();
366 }
367 sectionIndex++;
368 // Scans relocations to determine if a function symbol is called directly.
369 for (const WasmRelocation &reloc : section.Relocations)
370 if (reloc.Type == R_WASM_FUNCTION_INDEX_LEB)
371 isCalledDirectly[reloc.Index] = true;
372 }
373
374 typeMap.resize(getWasmObj()->types().size());
375 typeIsUsed.resize(getWasmObj()->types().size(), false);
376
377 ArrayRef<StringRef> comdats = wasmObj->linkingData().Comdats;
378 for (StringRef comdat : comdats) {
379 bool isNew = ignoreComdats || symtab->addComdat(comdat);
380 keptComdats.push_back(isNew);
381 }
382
383 // Populate `Segments`.
384 for (const WasmSegment &s : wasmObj->dataSegments()) {
385 auto* seg = make<InputSegment>(s, this);
386 seg->discarded = isExcludedByComdat(seg);
387 segments.emplace_back(seg);
388 }
389 setRelocs(segments, dataSection);
390
391 // Populate `Functions`.
392 ArrayRef<WasmFunction> funcs = wasmObj->functions();
393 ArrayRef<uint32_t> funcTypes = wasmObj->functionTypes();
394 ArrayRef<WasmSignature> types = wasmObj->types();
395 functions.reserve(funcs.size());
396
397 for (size_t i = 0, e = funcs.size(); i != e; ++i) {
398 auto* func = make<InputFunction>(types[funcTypes[i]], &funcs[i], this);
399 func->discarded = isExcludedByComdat(func);
400 functions.emplace_back(func);
401 }
402 setRelocs(functions, codeSection);
403
404 // Populate `Globals`.
405 for (const WasmGlobal &g : wasmObj->globals())
406 globals.emplace_back(make<InputGlobal>(g, this));
407
408 // Populate `Events`.
409 for (const WasmEvent &e : wasmObj->events())
410 events.emplace_back(make<InputEvent>(types[e.Type.SigIndex], e, this));
411
412 // Populate `Symbols` based on the symbols in the object.
413 symbols.reserve(wasmObj->getNumberOfSymbols());
414 for (const SymbolRef &sym : wasmObj->symbols()) {
415 const WasmSymbol &wasmSym = wasmObj->getWasmSymbol(sym.getRawDataRefImpl());
416 if (wasmSym.isDefined()) {
417 // createDefined may fail if the symbol is comdat excluded in which case
418 // we fall back to creating an undefined symbol
419 if (Symbol *d = createDefined(wasmSym)) {
420 symbols.push_back(d);
421 continue;
422 }
423 }
424 size_t idx = symbols.size();
425 symbols.push_back(createUndefined(wasmSym, isCalledDirectly[idx]));
426 }
427 }
428
isExcludedByComdat(InputChunk * chunk) const429 bool ObjFile::isExcludedByComdat(InputChunk *chunk) const {
430 uint32_t c = chunk->getComdat();
431 if (c == UINT32_MAX)
432 return false;
433 return !keptComdats[c];
434 }
435
getFunctionSymbol(uint32_t index) const436 FunctionSymbol *ObjFile::getFunctionSymbol(uint32_t index) const {
437 return cast<FunctionSymbol>(symbols[index]);
438 }
439
getGlobalSymbol(uint32_t index) const440 GlobalSymbol *ObjFile::getGlobalSymbol(uint32_t index) const {
441 return cast<GlobalSymbol>(symbols[index]);
442 }
443
getEventSymbol(uint32_t index) const444 EventSymbol *ObjFile::getEventSymbol(uint32_t index) const {
445 return cast<EventSymbol>(symbols[index]);
446 }
447
getSectionSymbol(uint32_t index) const448 SectionSymbol *ObjFile::getSectionSymbol(uint32_t index) const {
449 return cast<SectionSymbol>(symbols[index]);
450 }
451
getDataSymbol(uint32_t index) const452 DataSymbol *ObjFile::getDataSymbol(uint32_t index) const {
453 return cast<DataSymbol>(symbols[index]);
454 }
455
createDefined(const WasmSymbol & sym)456 Symbol *ObjFile::createDefined(const WasmSymbol &sym) {
457 StringRef name = sym.Info.Name;
458 uint32_t flags = sym.Info.Flags;
459
460 switch (sym.Info.Kind) {
461 case WASM_SYMBOL_TYPE_FUNCTION: {
462 InputFunction *func =
463 functions[sym.Info.ElementIndex - wasmObj->getNumImportedFunctions()];
464 if (sym.isBindingLocal())
465 return make<DefinedFunction>(name, flags, this, func);
466 if (func->discarded)
467 return nullptr;
468 return symtab->addDefinedFunction(name, flags, this, func);
469 }
470 case WASM_SYMBOL_TYPE_DATA: {
471 InputSegment *seg = segments[sym.Info.DataRef.Segment];
472 auto offset = sym.Info.DataRef.Offset;
473 auto size = sym.Info.DataRef.Size;
474 if (sym.isBindingLocal())
475 return make<DefinedData>(name, flags, this, seg, offset, size);
476 if (seg->discarded)
477 return nullptr;
478 return symtab->addDefinedData(name, flags, this, seg, offset, size);
479 }
480 case WASM_SYMBOL_TYPE_GLOBAL: {
481 InputGlobal *global =
482 globals[sym.Info.ElementIndex - wasmObj->getNumImportedGlobals()];
483 if (sym.isBindingLocal())
484 return make<DefinedGlobal>(name, flags, this, global);
485 return symtab->addDefinedGlobal(name, flags, this, global);
486 }
487 case WASM_SYMBOL_TYPE_SECTION: {
488 InputSection *section = customSectionsByIndex[sym.Info.ElementIndex];
489 assert(sym.isBindingLocal());
490 return make<SectionSymbol>(flags, section, this);
491 }
492 case WASM_SYMBOL_TYPE_EVENT: {
493 InputEvent *event =
494 events[sym.Info.ElementIndex - wasmObj->getNumImportedEvents()];
495 if (sym.isBindingLocal())
496 return make<DefinedEvent>(name, flags, this, event);
497 return symtab->addDefinedEvent(name, flags, this, event);
498 }
499 }
500 llvm_unreachable("unknown symbol kind");
501 }
502
createUndefined(const WasmSymbol & sym,bool isCalledDirectly)503 Symbol *ObjFile::createUndefined(const WasmSymbol &sym, bool isCalledDirectly) {
504 StringRef name = sym.Info.Name;
505 uint32_t flags = sym.Info.Flags | WASM_SYMBOL_UNDEFINED;
506
507 switch (sym.Info.Kind) {
508 case WASM_SYMBOL_TYPE_FUNCTION:
509 if (sym.isBindingLocal())
510 return make<UndefinedFunction>(name, sym.Info.ImportName,
511 sym.Info.ImportModule, flags, this,
512 sym.Signature, isCalledDirectly);
513 return symtab->addUndefinedFunction(name, sym.Info.ImportName,
514 sym.Info.ImportModule, flags, this,
515 sym.Signature, isCalledDirectly);
516 case WASM_SYMBOL_TYPE_DATA:
517 if (sym.isBindingLocal())
518 return make<UndefinedData>(name, flags, this);
519 return symtab->addUndefinedData(name, flags, this);
520 case WASM_SYMBOL_TYPE_GLOBAL:
521 if (sym.isBindingLocal())
522 return make<UndefinedGlobal>(name, sym.Info.ImportName,
523 sym.Info.ImportModule, flags, this,
524 sym.GlobalType);
525 return symtab->addUndefinedGlobal(name, sym.Info.ImportName,
526 sym.Info.ImportModule, flags, this,
527 sym.GlobalType);
528 case WASM_SYMBOL_TYPE_SECTION:
529 llvm_unreachable("section symbols cannot be undefined");
530 }
531 llvm_unreachable("unknown symbol kind");
532 }
533
parse()534 void ArchiveFile::parse() {
535 // Parse a MemoryBufferRef as an archive file.
536 LLVM_DEBUG(dbgs() << "Parsing library: " << toString(this) << "\n");
537 file = CHECK(Archive::create(mb), toString(this));
538
539 // Read the symbol table to construct Lazy symbols.
540 int count = 0;
541 for (const Archive::Symbol &sym : file->symbols()) {
542 symtab->addLazy(this, &sym);
543 ++count;
544 }
545 LLVM_DEBUG(dbgs() << "Read " << count << " symbols\n");
546 }
547
addMember(const Archive::Symbol * sym)548 void ArchiveFile::addMember(const Archive::Symbol *sym) {
549 const Archive::Child &c =
550 CHECK(sym->getMember(),
551 "could not get the member for symbol " + sym->getName());
552
553 // Don't try to load the same member twice (this can happen when members
554 // mutually reference each other).
555 if (!seen.insert(c.getChildOffset()).second)
556 return;
557
558 LLVM_DEBUG(dbgs() << "loading lazy: " << sym->getName() << "\n");
559 LLVM_DEBUG(dbgs() << "from archive: " << toString(this) << "\n");
560
561 MemoryBufferRef mb =
562 CHECK(c.getMemoryBufferRef(),
563 "could not get the buffer for the member defining symbol " +
564 sym->getName());
565
566 InputFile *obj = createObjectFile(mb, getName());
567 symtab->addFile(obj);
568 }
569
mapVisibility(GlobalValue::VisibilityTypes gvVisibility)570 static uint8_t mapVisibility(GlobalValue::VisibilityTypes gvVisibility) {
571 switch (gvVisibility) {
572 case GlobalValue::DefaultVisibility:
573 return WASM_SYMBOL_VISIBILITY_DEFAULT;
574 case GlobalValue::HiddenVisibility:
575 case GlobalValue::ProtectedVisibility:
576 return WASM_SYMBOL_VISIBILITY_HIDDEN;
577 }
578 llvm_unreachable("unknown visibility");
579 }
580
createBitcodeSymbol(const std::vector<bool> & keptComdats,const lto::InputFile::Symbol & objSym,BitcodeFile & f)581 static Symbol *createBitcodeSymbol(const std::vector<bool> &keptComdats,
582 const lto::InputFile::Symbol &objSym,
583 BitcodeFile &f) {
584 StringRef name = saver.save(objSym.getName());
585
586 uint32_t flags = objSym.isWeak() ? WASM_SYMBOL_BINDING_WEAK : 0;
587 flags |= mapVisibility(objSym.getVisibility());
588
589 int c = objSym.getComdatIndex();
590 bool excludedByComdat = c != -1 && !keptComdats[c];
591
592 if (objSym.isUndefined() || excludedByComdat) {
593 flags |= WASM_SYMBOL_UNDEFINED;
594 if (objSym.isExecutable())
595 return symtab->addUndefinedFunction(name, None, None, flags, &f, nullptr,
596 true);
597 return symtab->addUndefinedData(name, flags, &f);
598 }
599
600 if (objSym.isExecutable())
601 return symtab->addDefinedFunction(name, flags, &f, nullptr);
602 return symtab->addDefinedData(name, flags, &f, nullptr, 0, 0);
603 }
604
605 bool BitcodeFile::doneLTO = false;
606
parse()607 void BitcodeFile::parse() {
608 if (doneLTO) {
609 error(toString(this) + ": attempt to add bitcode file after LTO.");
610 return;
611 }
612
613 obj = check(lto::InputFile::create(MemoryBufferRef(
614 mb.getBuffer(), saver.save(archiveName + mb.getBufferIdentifier()))));
615 Triple t(obj->getTargetTriple());
616 if (!t.isWasm()) {
617 error(toString(this) + ": machine type must be wasm32 or wasm64");
618 return;
619 }
620 checkArch(t.getArch());
621 std::vector<bool> keptComdats;
622 for (StringRef s : obj->getComdatTable())
623 keptComdats.push_back(symtab->addComdat(s));
624
625 for (const lto::InputFile::Symbol &objSym : obj->symbols())
626 symbols.push_back(createBitcodeSymbol(keptComdats, objSym, *this));
627 }
628
629 } // namespace wasm
630 } // namespace lld
631