Path: blob/main/contrib/llvm-project/lld/COFF/InputFiles.cpp
34879 views
//===- InputFiles.cpp -----------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "InputFiles.h"9#include "COFFLinkerContext.h"10#include "Chunks.h"11#include "Config.h"12#include "DebugTypes.h"13#include "Driver.h"14#include "SymbolTable.h"15#include "Symbols.h"16#include "lld/Common/DWARF.h"17#include "llvm-c/lto.h"18#include "llvm/ADT/SmallVector.h"19#include "llvm/ADT/Twine.h"20#include "llvm/BinaryFormat/COFF.h"21#include "llvm/DebugInfo/CodeView/DebugSubsectionRecord.h"22#include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"23#include "llvm/DebugInfo/CodeView/SymbolRecord.h"24#include "llvm/DebugInfo/CodeView/TypeDeserializer.h"25#include "llvm/DebugInfo/PDB/Native/NativeSession.h"26#include "llvm/DebugInfo/PDB/Native/PDBFile.h"27#include "llvm/LTO/LTO.h"28#include "llvm/Object/Binary.h"29#include "llvm/Object/COFF.h"30#include "llvm/Support/Casting.h"31#include "llvm/Support/Endian.h"32#include "llvm/Support/Error.h"33#include "llvm/Support/ErrorOr.h"34#include "llvm/Support/FileSystem.h"35#include "llvm/Support/Path.h"36#include "llvm/Target/TargetOptions.h"37#include "llvm/TargetParser/Triple.h"38#include <cstring>39#include <optional>40#include <system_error>41#include <utility>4243using namespace llvm;44using namespace llvm::COFF;45using namespace llvm::codeview;46using namespace llvm::object;47using namespace llvm::support::endian;48using namespace lld;49using namespace lld::coff;5051using llvm::Triple;52using llvm::support::ulittle32_t;5354// Returns the last element of a path, which is supposed to be a filename.55static StringRef getBasename(StringRef path) {56return sys::path::filename(path, sys::path::Style::windows);57}5859// Returns a string in the format of "foo.obj" or "foo.obj(bar.lib)".60std::string lld::toString(const coff::InputFile *file) {61if (!file)62return "<internal>";63if (file->parentName.empty() || file->kind() == coff::InputFile::ImportKind)64return std::string(file->getName());6566return (getBasename(file->parentName) + "(" + getBasename(file->getName()) +67")")68.str();69}7071/// Checks that Source is compatible with being a weak alias to Target.72/// If Source is Undefined and has no weak alias set, makes it a weak73/// alias to Target.74static void checkAndSetWeakAlias(COFFLinkerContext &ctx, InputFile *f,75Symbol *source, Symbol *target) {76if (auto *u = dyn_cast<Undefined>(source)) {77if (u->weakAlias && u->weakAlias != target) {78// Weak aliases as produced by GCC are named in the form79// .weak.<weaksymbol>.<othersymbol>, where <othersymbol> is the name80// of another symbol emitted near the weak symbol.81// Just use the definition from the first object file that defined82// this weak symbol.83if (ctx.config.allowDuplicateWeak)84return;85ctx.symtab.reportDuplicate(source, f);86}87u->weakAlias = target;88}89}9091static bool ignoredSymbolName(StringRef name) {92return name == "@feat.00" || name == "@comp.id";93}9495ArchiveFile::ArchiveFile(COFFLinkerContext &ctx, MemoryBufferRef m)96: InputFile(ctx, ArchiveKind, m) {}9798void ArchiveFile::parse() {99// Parse a MemoryBufferRef as an archive file.100file = CHECK(Archive::create(mb), this);101102// Read the symbol table to construct Lazy objects.103for (const Archive::Symbol &sym : file->symbols())104ctx.symtab.addLazyArchive(this, sym);105}106107// Returns a buffer pointing to a member file containing a given symbol.108void ArchiveFile::addMember(const Archive::Symbol &sym) {109const Archive::Child &c =110CHECK(sym.getMember(),111"could not get the member for symbol " + toCOFFString(ctx, sym));112113// Return an empty buffer if we have already returned the same buffer.114if (!seen.insert(c.getChildOffset()).second)115return;116117ctx.driver.enqueueArchiveMember(c, sym, getName());118}119120std::vector<MemoryBufferRef> lld::coff::getArchiveMembers(Archive *file) {121std::vector<MemoryBufferRef> v;122Error err = Error::success();123for (const Archive::Child &c : file->children(err)) {124MemoryBufferRef mbref =125CHECK(c.getMemoryBufferRef(),126file->getFileName() +127": could not get the buffer for a child of the archive");128v.push_back(mbref);129}130if (err)131fatal(file->getFileName() +132": Archive::children failed: " + toString(std::move(err)));133return v;134}135136void ObjFile::parseLazy() {137// Native object file.138std::unique_ptr<Binary> coffObjPtr = CHECK(createBinary(mb), this);139COFFObjectFile *coffObj = cast<COFFObjectFile>(coffObjPtr.get());140uint32_t numSymbols = coffObj->getNumberOfSymbols();141for (uint32_t i = 0; i < numSymbols; ++i) {142COFFSymbolRef coffSym = check(coffObj->getSymbol(i));143if (coffSym.isUndefined() || !coffSym.isExternal() ||144coffSym.isWeakExternal())145continue;146StringRef name = check(coffObj->getSymbolName(coffSym));147if (coffSym.isAbsolute() && ignoredSymbolName(name))148continue;149ctx.symtab.addLazyObject(this, name);150i += coffSym.getNumberOfAuxSymbols();151}152}153154struct ECMapEntry {155ulittle32_t src;156ulittle32_t dst;157ulittle32_t type;158};159160void ObjFile::initializeECThunks() {161for (SectionChunk *chunk : hybmpChunks) {162if (chunk->getContents().size() % sizeof(ECMapEntry)) {163error("Invalid .hybmp chunk size " + Twine(chunk->getContents().size()));164continue;165}166167const uint8_t *end =168chunk->getContents().data() + chunk->getContents().size();169for (const uint8_t *iter = chunk->getContents().data(); iter != end;170iter += sizeof(ECMapEntry)) {171auto entry = reinterpret_cast<const ECMapEntry *>(iter);172switch (entry->type) {173case Arm64ECThunkType::Entry:174ctx.symtab.addEntryThunk(getSymbol(entry->src), getSymbol(entry->dst));175break;176case Arm64ECThunkType::Exit:177case Arm64ECThunkType::GuestExit:178break;179default:180warn("Ignoring unknown EC thunk type " + Twine(entry->type));181}182}183}184}185186void ObjFile::parse() {187// Parse a memory buffer as a COFF file.188std::unique_ptr<Binary> bin = CHECK(createBinary(mb), this);189190if (auto *obj = dyn_cast<COFFObjectFile>(bin.get())) {191bin.release();192coffObj.reset(obj);193} else {194fatal(toString(this) + " is not a COFF file");195}196197// Read section and symbol tables.198initializeChunks();199initializeSymbols();200initializeFlags();201initializeDependencies();202initializeECThunks();203}204205const coff_section *ObjFile::getSection(uint32_t i) {206auto sec = coffObj->getSection(i);207if (!sec)208fatal("getSection failed: #" + Twine(i) + ": " + toString(sec.takeError()));209return *sec;210}211212// We set SectionChunk pointers in the SparseChunks vector to this value213// temporarily to mark comdat sections as having an unknown resolution. As we214// walk the object file's symbol table, once we visit either a leader symbol or215// an associative section definition together with the parent comdat's leader,216// we set the pointer to either nullptr (to mark the section as discarded) or a217// valid SectionChunk for that section.218static SectionChunk *const pendingComdat = reinterpret_cast<SectionChunk *>(1);219220void ObjFile::initializeChunks() {221uint32_t numSections = coffObj->getNumberOfSections();222sparseChunks.resize(numSections + 1);223for (uint32_t i = 1; i < numSections + 1; ++i) {224const coff_section *sec = getSection(i);225if (sec->Characteristics & IMAGE_SCN_LNK_COMDAT)226sparseChunks[i] = pendingComdat;227else228sparseChunks[i] = readSection(i, nullptr, "");229}230}231232SectionChunk *ObjFile::readSection(uint32_t sectionNumber,233const coff_aux_section_definition *def,234StringRef leaderName) {235const coff_section *sec = getSection(sectionNumber);236237StringRef name;238if (Expected<StringRef> e = coffObj->getSectionName(sec))239name = *e;240else241fatal("getSectionName failed: #" + Twine(sectionNumber) + ": " +242toString(e.takeError()));243244if (name == ".drectve") {245ArrayRef<uint8_t> data;246cantFail(coffObj->getSectionContents(sec, data));247directives = StringRef((const char *)data.data(), data.size());248return nullptr;249}250251if (name == ".llvm_addrsig") {252addrsigSec = sec;253return nullptr;254}255256if (name == ".llvm.call-graph-profile") {257callgraphSec = sec;258return nullptr;259}260261// Object files may have DWARF debug info or MS CodeView debug info262// (or both).263//264// DWARF sections don't need any special handling from the perspective265// of the linker; they are just a data section containing relocations.266// We can just link them to complete debug info.267//268// CodeView needs linker support. We need to interpret debug info,269// and then write it to a separate .pdb file.270271// Ignore DWARF debug info unless requested to be included.272if (!ctx.config.includeDwarfChunks && name.starts_with(".debug_"))273return nullptr;274275if (sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE)276return nullptr;277SectionChunk *c;278if (isArm64EC(getMachineType()))279c = make<SectionChunkEC>(this, sec);280else281c = make<SectionChunk>(this, sec);282if (def)283c->checksum = def->CheckSum;284285// CodeView sections are stored to a different vector because they are not286// linked in the regular manner.287if (c->isCodeView())288debugChunks.push_back(c);289else if (name == ".gfids$y")290guardFidChunks.push_back(c);291else if (name == ".giats$y")292guardIATChunks.push_back(c);293else if (name == ".gljmp$y")294guardLJmpChunks.push_back(c);295else if (name == ".gehcont$y")296guardEHContChunks.push_back(c);297else if (name == ".sxdata")298sxDataChunks.push_back(c);299else if (isArm64EC(getMachineType()) && name == ".hybmp$x")300hybmpChunks.push_back(c);301else if (ctx.config.tailMerge && sec->NumberOfRelocations == 0 &&302name == ".rdata" && leaderName.starts_with("??_C@"))303// COFF sections that look like string literal sections (i.e. no304// relocations, in .rdata, leader symbol name matches the MSVC name mangling305// for string literals) are subject to string tail merging.306MergeChunk::addSection(ctx, c);307else if (name == ".rsrc" || name.starts_with(".rsrc$"))308resourceChunks.push_back(c);309else310chunks.push_back(c);311312return c;313}314315void ObjFile::includeResourceChunks() {316chunks.insert(chunks.end(), resourceChunks.begin(), resourceChunks.end());317}318319void ObjFile::readAssociativeDefinition(320COFFSymbolRef sym, const coff_aux_section_definition *def) {321readAssociativeDefinition(sym, def, def->getNumber(sym.isBigObj()));322}323324void ObjFile::readAssociativeDefinition(COFFSymbolRef sym,325const coff_aux_section_definition *def,326uint32_t parentIndex) {327SectionChunk *parent = sparseChunks[parentIndex];328int32_t sectionNumber = sym.getSectionNumber();329330auto diag = [&]() {331StringRef name = check(coffObj->getSymbolName(sym));332333StringRef parentName;334const coff_section *parentSec = getSection(parentIndex);335if (Expected<StringRef> e = coffObj->getSectionName(parentSec))336parentName = *e;337error(toString(this) + ": associative comdat " + name + " (sec " +338Twine(sectionNumber) + ") has invalid reference to section " +339parentName + " (sec " + Twine(parentIndex) + ")");340};341342if (parent == pendingComdat) {343// This can happen if an associative comdat refers to another associative344// comdat that appears after it (invalid per COFF spec) or to a section345// without any symbols.346diag();347return;348}349350// Check whether the parent is prevailing. If it is, so are we, and we read351// the section; otherwise mark it as discarded.352if (parent) {353SectionChunk *c = readSection(sectionNumber, def, "");354sparseChunks[sectionNumber] = c;355if (c) {356c->selection = IMAGE_COMDAT_SELECT_ASSOCIATIVE;357parent->addAssociative(c);358}359} else {360sparseChunks[sectionNumber] = nullptr;361}362}363364void ObjFile::recordPrevailingSymbolForMingw(365COFFSymbolRef sym, DenseMap<StringRef, uint32_t> &prevailingSectionMap) {366// For comdat symbols in executable sections, where this is the copy367// of the section chunk we actually include instead of discarding it,368// add the symbol to a map to allow using it for implicitly369// associating .[px]data$<func> sections to it.370// Use the suffix from the .text$<func> instead of the leader symbol371// name, for cases where the names differ (i386 mangling/decorations,372// cases where the leader is a weak symbol named .weak.func.default*).373int32_t sectionNumber = sym.getSectionNumber();374SectionChunk *sc = sparseChunks[sectionNumber];375if (sc && sc->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE) {376StringRef name = sc->getSectionName().split('$').second;377prevailingSectionMap[name] = sectionNumber;378}379}380381void ObjFile::maybeAssociateSEHForMingw(382COFFSymbolRef sym, const coff_aux_section_definition *def,383const DenseMap<StringRef, uint32_t> &prevailingSectionMap) {384StringRef name = check(coffObj->getSymbolName(sym));385if (name.consume_front(".pdata$") || name.consume_front(".xdata$") ||386name.consume_front(".eh_frame$")) {387// For MinGW, treat .[px]data$<func> and .eh_frame$<func> as implicitly388// associative to the symbol <func>.389auto parentSym = prevailingSectionMap.find(name);390if (parentSym != prevailingSectionMap.end())391readAssociativeDefinition(sym, def, parentSym->second);392}393}394395Symbol *ObjFile::createRegular(COFFSymbolRef sym) {396SectionChunk *sc = sparseChunks[sym.getSectionNumber()];397if (sym.isExternal()) {398StringRef name = check(coffObj->getSymbolName(sym));399if (sc)400return ctx.symtab.addRegular(this, name, sym.getGeneric(), sc,401sym.getValue());402// For MinGW symbols named .weak.* that point to a discarded section,403// don't create an Undefined symbol. If nothing ever refers to the symbol,404// everything should be fine. If something actually refers to the symbol405// (e.g. the undefined weak alias), linking will fail due to undefined406// references at the end.407if (ctx.config.mingw && name.starts_with(".weak."))408return nullptr;409return ctx.symtab.addUndefined(name, this, false);410}411if (sc)412return make<DefinedRegular>(this, /*Name*/ "", /*IsCOMDAT*/ false,413/*IsExternal*/ false, sym.getGeneric(), sc);414return nullptr;415}416417void ObjFile::initializeSymbols() {418uint32_t numSymbols = coffObj->getNumberOfSymbols();419symbols.resize(numSymbols);420421SmallVector<std::pair<Symbol *, uint32_t>, 8> weakAliases;422std::vector<uint32_t> pendingIndexes;423pendingIndexes.reserve(numSymbols);424425DenseMap<StringRef, uint32_t> prevailingSectionMap;426std::vector<const coff_aux_section_definition *> comdatDefs(427coffObj->getNumberOfSections() + 1);428429for (uint32_t i = 0; i < numSymbols; ++i) {430COFFSymbolRef coffSym = check(coffObj->getSymbol(i));431bool prevailingComdat;432if (coffSym.isUndefined()) {433symbols[i] = createUndefined(coffSym);434} else if (coffSym.isWeakExternal()) {435symbols[i] = createUndefined(coffSym);436uint32_t tagIndex = coffSym.getAux<coff_aux_weak_external>()->TagIndex;437weakAliases.emplace_back(symbols[i], tagIndex);438} else if (std::optional<Symbol *> optSym =439createDefined(coffSym, comdatDefs, prevailingComdat)) {440symbols[i] = *optSym;441if (ctx.config.mingw && prevailingComdat)442recordPrevailingSymbolForMingw(coffSym, prevailingSectionMap);443} else {444// createDefined() returns std::nullopt if a symbol belongs to a section445// that was pending at the point when the symbol was read. This can happen446// in two cases:447// 1) section definition symbol for a comdat leader;448// 2) symbol belongs to a comdat section associated with another section.449// In both of these cases, we can expect the section to be resolved by450// the time we finish visiting the remaining symbols in the symbol451// table. So we postpone the handling of this symbol until that time.452pendingIndexes.push_back(i);453}454i += coffSym.getNumberOfAuxSymbols();455}456457for (uint32_t i : pendingIndexes) {458COFFSymbolRef sym = check(coffObj->getSymbol(i));459if (const coff_aux_section_definition *def = sym.getSectionDefinition()) {460if (def->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)461readAssociativeDefinition(sym, def);462else if (ctx.config.mingw)463maybeAssociateSEHForMingw(sym, def, prevailingSectionMap);464}465if (sparseChunks[sym.getSectionNumber()] == pendingComdat) {466StringRef name = check(coffObj->getSymbolName(sym));467log("comdat section " + name +468" without leader and unassociated, discarding");469continue;470}471symbols[i] = createRegular(sym);472}473474for (auto &kv : weakAliases) {475Symbol *sym = kv.first;476uint32_t idx = kv.second;477checkAndSetWeakAlias(ctx, this, sym, symbols[idx]);478}479480// Free the memory used by sparseChunks now that symbol loading is finished.481decltype(sparseChunks)().swap(sparseChunks);482}483484Symbol *ObjFile::createUndefined(COFFSymbolRef sym) {485StringRef name = check(coffObj->getSymbolName(sym));486return ctx.symtab.addUndefined(name, this, sym.isWeakExternal());487}488489static const coff_aux_section_definition *findSectionDef(COFFObjectFile *obj,490int32_t section) {491uint32_t numSymbols = obj->getNumberOfSymbols();492for (uint32_t i = 0; i < numSymbols; ++i) {493COFFSymbolRef sym = check(obj->getSymbol(i));494if (sym.getSectionNumber() != section)495continue;496if (const coff_aux_section_definition *def = sym.getSectionDefinition())497return def;498}499return nullptr;500}501502void ObjFile::handleComdatSelection(503COFFSymbolRef sym, COMDATType &selection, bool &prevailing,504DefinedRegular *leader,505const llvm::object::coff_aux_section_definition *def) {506if (prevailing)507return;508// There's already an existing comdat for this symbol: `Leader`.509// Use the comdats's selection field to determine if the new510// symbol in `Sym` should be discarded, produce a duplicate symbol511// error, etc.512513SectionChunk *leaderChunk = leader->getChunk();514COMDATType leaderSelection = leaderChunk->selection;515516assert(leader->data && "Comdat leader without SectionChunk?");517if (isa<BitcodeFile>(leader->file)) {518// If the leader is only a LTO symbol, we don't know e.g. its final size519// yet, so we can't do the full strict comdat selection checking yet.520selection = leaderSelection = IMAGE_COMDAT_SELECT_ANY;521}522523if ((selection == IMAGE_COMDAT_SELECT_ANY &&524leaderSelection == IMAGE_COMDAT_SELECT_LARGEST) ||525(selection == IMAGE_COMDAT_SELECT_LARGEST &&526leaderSelection == IMAGE_COMDAT_SELECT_ANY)) {527// cl.exe picks "any" for vftables when building with /GR- and528// "largest" when building with /GR. To be able to link object files529// compiled with each flag, "any" and "largest" are merged as "largest".530leaderSelection = selection = IMAGE_COMDAT_SELECT_LARGEST;531}532533// GCCs __declspec(selectany) doesn't actually pick "any" but "same size as".534// Clang on the other hand picks "any". To be able to link two object files535// with a __declspec(selectany) declaration, one compiled with gcc and the536// other with clang, we merge them as proper "same size as"537if (ctx.config.mingw && ((selection == IMAGE_COMDAT_SELECT_ANY &&538leaderSelection == IMAGE_COMDAT_SELECT_SAME_SIZE) ||539(selection == IMAGE_COMDAT_SELECT_SAME_SIZE &&540leaderSelection == IMAGE_COMDAT_SELECT_ANY))) {541leaderSelection = selection = IMAGE_COMDAT_SELECT_SAME_SIZE;542}543544// Other than that, comdat selections must match. This is a bit more545// strict than link.exe which allows merging "any" and "largest" if "any"546// is the first symbol the linker sees, and it allows merging "largest"547// with everything (!) if "largest" is the first symbol the linker sees.548// Making this symmetric independent of which selection is seen first549// seems better though.550// (This behavior matches ModuleLinker::getComdatResult().)551if (selection != leaderSelection) {552log(("conflicting comdat type for " + toString(ctx, *leader) + ": " +553Twine((int)leaderSelection) + " in " + toString(leader->getFile()) +554" and " + Twine((int)selection) + " in " + toString(this))555.str());556ctx.symtab.reportDuplicate(leader, this);557return;558}559560switch (selection) {561case IMAGE_COMDAT_SELECT_NODUPLICATES:562ctx.symtab.reportDuplicate(leader, this);563break;564565case IMAGE_COMDAT_SELECT_ANY:566// Nothing to do.567break;568569case IMAGE_COMDAT_SELECT_SAME_SIZE:570if (leaderChunk->getSize() != getSection(sym)->SizeOfRawData) {571if (!ctx.config.mingw) {572ctx.symtab.reportDuplicate(leader, this);573} else {574const coff_aux_section_definition *leaderDef = nullptr;575if (leaderChunk->file)576leaderDef = findSectionDef(leaderChunk->file->getCOFFObj(),577leaderChunk->getSectionNumber());578if (!leaderDef || leaderDef->Length != def->Length)579ctx.symtab.reportDuplicate(leader, this);580}581}582break;583584case IMAGE_COMDAT_SELECT_EXACT_MATCH: {585SectionChunk newChunk(this, getSection(sym));586// link.exe only compares section contents here and doesn't complain587// if the two comdat sections have e.g. different alignment.588// Match that.589if (leaderChunk->getContents() != newChunk.getContents())590ctx.symtab.reportDuplicate(leader, this, &newChunk, sym.getValue());591break;592}593594case IMAGE_COMDAT_SELECT_ASSOCIATIVE:595// createDefined() is never called for IMAGE_COMDAT_SELECT_ASSOCIATIVE.596// (This means lld-link doesn't produce duplicate symbol errors for597// associative comdats while link.exe does, but associate comdats598// are never extern in practice.)599llvm_unreachable("createDefined not called for associative comdats");600601case IMAGE_COMDAT_SELECT_LARGEST:602if (leaderChunk->getSize() < getSection(sym)->SizeOfRawData) {603// Replace the existing comdat symbol with the new one.604StringRef name = check(coffObj->getSymbolName(sym));605// FIXME: This is incorrect: With /opt:noref, the previous sections606// make it into the final executable as well. Correct handling would607// be to undo reading of the whole old section that's being replaced,608// or doing one pass that determines what the final largest comdat609// is for all IMAGE_COMDAT_SELECT_LARGEST comdats and then reading610// only the largest one.611replaceSymbol<DefinedRegular>(leader, this, name, /*IsCOMDAT*/ true,612/*IsExternal*/ true, sym.getGeneric(),613nullptr);614prevailing = true;615}616break;617618case IMAGE_COMDAT_SELECT_NEWEST:619llvm_unreachable("should have been rejected earlier");620}621}622623std::optional<Symbol *> ObjFile::createDefined(624COFFSymbolRef sym,625std::vector<const coff_aux_section_definition *> &comdatDefs,626bool &prevailing) {627prevailing = false;628auto getName = [&]() { return check(coffObj->getSymbolName(sym)); };629630if (sym.isCommon()) {631auto *c = make<CommonChunk>(sym);632chunks.push_back(c);633return ctx.symtab.addCommon(this, getName(), sym.getValue(),634sym.getGeneric(), c);635}636637if (sym.isAbsolute()) {638StringRef name = getName();639640if (name == "@feat.00")641feat00Flags = sym.getValue();642// Skip special symbols.643if (ignoredSymbolName(name))644return nullptr;645646if (sym.isExternal())647return ctx.symtab.addAbsolute(name, sym);648return make<DefinedAbsolute>(ctx, name, sym);649}650651int32_t sectionNumber = sym.getSectionNumber();652if (sectionNumber == llvm::COFF::IMAGE_SYM_DEBUG)653return nullptr;654655if (llvm::COFF::isReservedSectionNumber(sectionNumber))656fatal(toString(this) + ": " + getName() +657" should not refer to special section " + Twine(sectionNumber));658659if ((uint32_t)sectionNumber >= sparseChunks.size())660fatal(toString(this) + ": " + getName() +661" should not refer to non-existent section " + Twine(sectionNumber));662663// Comdat handling.664// A comdat symbol consists of two symbol table entries.665// The first symbol entry has the name of the section (e.g. .text), fixed666// values for the other fields, and one auxiliary record.667// The second symbol entry has the name of the comdat symbol, called the668// "comdat leader".669// When this function is called for the first symbol entry of a comdat,670// it sets comdatDefs and returns std::nullopt, and when it's called for the671// second symbol entry it reads comdatDefs and then sets it back to nullptr.672673// Handle comdat leader.674if (const coff_aux_section_definition *def = comdatDefs[sectionNumber]) {675comdatDefs[sectionNumber] = nullptr;676DefinedRegular *leader;677678if (sym.isExternal()) {679std::tie(leader, prevailing) =680ctx.symtab.addComdat(this, getName(), sym.getGeneric());681} else {682leader = make<DefinedRegular>(this, /*Name*/ "", /*IsCOMDAT*/ false,683/*IsExternal*/ false, sym.getGeneric());684prevailing = true;685}686687if (def->Selection < (int)IMAGE_COMDAT_SELECT_NODUPLICATES ||688// Intentionally ends at IMAGE_COMDAT_SELECT_LARGEST: link.exe689// doesn't understand IMAGE_COMDAT_SELECT_NEWEST either.690def->Selection > (int)IMAGE_COMDAT_SELECT_LARGEST) {691fatal("unknown comdat type " + std::to_string((int)def->Selection) +692" for " + getName() + " in " + toString(this));693}694COMDATType selection = (COMDATType)def->Selection;695696if (leader->isCOMDAT)697handleComdatSelection(sym, selection, prevailing, leader, def);698699if (prevailing) {700SectionChunk *c = readSection(sectionNumber, def, getName());701sparseChunks[sectionNumber] = c;702if (!c)703return nullptr;704c->sym = cast<DefinedRegular>(leader);705c->selection = selection;706cast<DefinedRegular>(leader)->data = &c->repl;707} else {708sparseChunks[sectionNumber] = nullptr;709}710return leader;711}712713// Prepare to handle the comdat leader symbol by setting the section's714// ComdatDefs pointer if we encounter a non-associative comdat.715if (sparseChunks[sectionNumber] == pendingComdat) {716if (const coff_aux_section_definition *def = sym.getSectionDefinition()) {717if (def->Selection != IMAGE_COMDAT_SELECT_ASSOCIATIVE)718comdatDefs[sectionNumber] = def;719}720return std::nullopt;721}722723return createRegular(sym);724}725726MachineTypes ObjFile::getMachineType() {727if (coffObj)728return static_cast<MachineTypes>(coffObj->getMachine());729return IMAGE_FILE_MACHINE_UNKNOWN;730}731732ArrayRef<uint8_t> ObjFile::getDebugSection(StringRef secName) {733if (SectionChunk *sec = SectionChunk::findByName(debugChunks, secName))734return sec->consumeDebugMagic();735return {};736}737738// OBJ files systematically store critical information in a .debug$S stream,739// even if the TU was compiled with no debug info. At least two records are740// always there. S_OBJNAME stores a 32-bit signature, which is loaded into the741// PCHSignature member. S_COMPILE3 stores compile-time cmd-line flags. This is742// currently used to initialize the hotPatchable member.743void ObjFile::initializeFlags() {744ArrayRef<uint8_t> data = getDebugSection(".debug$S");745if (data.empty())746return;747748DebugSubsectionArray subsections;749750BinaryStreamReader reader(data, llvm::endianness::little);751ExitOnError exitOnErr;752exitOnErr(reader.readArray(subsections, data.size()));753754for (const DebugSubsectionRecord &ss : subsections) {755if (ss.kind() != DebugSubsectionKind::Symbols)756continue;757758unsigned offset = 0;759760// Only parse the first two records. We are only looking for S_OBJNAME761// and S_COMPILE3, and they usually appear at the beginning of the762// stream.763for (unsigned i = 0; i < 2; ++i) {764Expected<CVSymbol> sym = readSymbolFromStream(ss.getRecordData(), offset);765if (!sym) {766consumeError(sym.takeError());767return;768}769if (sym->kind() == SymbolKind::S_COMPILE3) {770auto cs =771cantFail(SymbolDeserializer::deserializeAs<Compile3Sym>(sym.get()));772hotPatchable =773(cs.Flags & CompileSym3Flags::HotPatch) != CompileSym3Flags::None;774}775if (sym->kind() == SymbolKind::S_OBJNAME) {776auto objName = cantFail(SymbolDeserializer::deserializeAs<ObjNameSym>(777sym.get()));778if (objName.Signature)779pchSignature = objName.Signature;780}781offset += sym->length();782}783}784}785786// Depending on the compilation flags, OBJs can refer to external files,787// necessary to merge this OBJ into the final PDB. We currently support two788// types of external files: Precomp/PCH OBJs, when compiling with /Yc and /Yu.789// And PDB type servers, when compiling with /Zi. This function extracts these790// dependencies and makes them available as a TpiSource interface (see791// DebugTypes.h). Both cases only happen with cl.exe: clang-cl produces regular792// output even with /Yc and /Yu and with /Zi.793void ObjFile::initializeDependencies() {794if (!ctx.config.debug)795return;796797bool isPCH = false;798799ArrayRef<uint8_t> data = getDebugSection(".debug$P");800if (!data.empty())801isPCH = true;802else803data = getDebugSection(".debug$T");804805// symbols but no types, make a plain, empty TpiSource anyway, because it806// simplifies adding the symbols later.807if (data.empty()) {808if (!debugChunks.empty())809debugTypesObj = makeTpiSource(ctx, this);810return;811}812813// Get the first type record. It will indicate if this object uses a type814// server (/Zi) or a PCH file (/Yu).815CVTypeArray types;816BinaryStreamReader reader(data, llvm::endianness::little);817cantFail(reader.readArray(types, reader.getLength()));818CVTypeArray::Iterator firstType = types.begin();819if (firstType == types.end())820return;821822// Remember the .debug$T or .debug$P section.823debugTypes = data;824825// This object file is a PCH file that others will depend on.826if (isPCH) {827debugTypesObj = makePrecompSource(ctx, this);828return;829}830831// This object file was compiled with /Zi. Enqueue the PDB dependency.832if (firstType->kind() == LF_TYPESERVER2) {833TypeServer2Record ts = cantFail(834TypeDeserializer::deserializeAs<TypeServer2Record>(firstType->data()));835debugTypesObj = makeUseTypeServerSource(ctx, this, ts);836enqueuePdbFile(ts.getName(), this);837return;838}839840// This object was compiled with /Yu. It uses types from another object file841// with a matching signature.842if (firstType->kind() == LF_PRECOMP) {843PrecompRecord precomp = cantFail(844TypeDeserializer::deserializeAs<PrecompRecord>(firstType->data()));845// We're better off trusting the LF_PRECOMP signature. In some cases the846// S_OBJNAME record doesn't contain a valid PCH signature.847if (precomp.Signature)848pchSignature = precomp.Signature;849debugTypesObj = makeUsePrecompSource(ctx, this, precomp);850// Drop the LF_PRECOMP record from the input stream.851debugTypes = debugTypes.drop_front(firstType->RecordData.size());852return;853}854855// This is a plain old object file.856debugTypesObj = makeTpiSource(ctx, this);857}858859// The casing of the PDB path stamped in the OBJ can differ from the actual path860// on disk. With this, we ensure to always use lowercase as a key for the861// pdbInputFileInstances map, at least on Windows.862static std::string normalizePdbPath(StringRef path) {863#if defined(_WIN32)864return path.lower();865#else // LINUX866return std::string(path);867#endif868}869870// If existing, return the actual PDB path on disk.871static std::optional<std::string>872findPdbPath(StringRef pdbPath, ObjFile *dependentFile, StringRef outputPath) {873// Ensure the file exists before anything else. In some cases, if the path874// points to a removable device, Driver::enqueuePath() would fail with an875// error (EAGAIN, "resource unavailable try again") which we want to skip876// silently.877if (llvm::sys::fs::exists(pdbPath))878return normalizePdbPath(pdbPath);879880StringRef objPath = !dependentFile->parentName.empty()881? dependentFile->parentName882: dependentFile->getName();883884// Currently, type server PDBs are only created by MSVC cl, which only runs885// on Windows, so we can assume type server paths are Windows style.886StringRef pdbName = sys::path::filename(pdbPath, sys::path::Style::windows);887888// Check if the PDB is in the same folder as the OBJ.889SmallString<128> path;890sys::path::append(path, sys::path::parent_path(objPath), pdbName);891if (llvm::sys::fs::exists(path))892return normalizePdbPath(path);893894// Check if the PDB is in the output folder.895path.clear();896sys::path::append(path, sys::path::parent_path(outputPath), pdbName);897if (llvm::sys::fs::exists(path))898return normalizePdbPath(path);899900return std::nullopt;901}902903PDBInputFile::PDBInputFile(COFFLinkerContext &ctx, MemoryBufferRef m)904: InputFile(ctx, PDBKind, m) {}905906PDBInputFile::~PDBInputFile() = default;907908PDBInputFile *PDBInputFile::findFromRecordPath(const COFFLinkerContext &ctx,909StringRef path,910ObjFile *fromFile) {911auto p = findPdbPath(path.str(), fromFile, ctx.config.outputFile);912if (!p)913return nullptr;914auto it = ctx.pdbInputFileInstances.find(*p);915if (it != ctx.pdbInputFileInstances.end())916return it->second;917return nullptr;918}919920void PDBInputFile::parse() {921ctx.pdbInputFileInstances[mb.getBufferIdentifier().str()] = this;922923std::unique_ptr<pdb::IPDBSession> thisSession;924Error E = pdb::NativeSession::createFromPdb(925MemoryBuffer::getMemBuffer(mb, false), thisSession);926if (E) {927loadErrorStr.emplace(toString(std::move(E)));928return; // fail silently at this point - the error will be handled later,929// when merging the debug type stream930}931932session.reset(static_cast<pdb::NativeSession *>(thisSession.release()));933934pdb::PDBFile &pdbFile = session->getPDBFile();935auto expectedInfo = pdbFile.getPDBInfoStream();936// All PDB Files should have an Info stream.937if (!expectedInfo) {938loadErrorStr.emplace(toString(expectedInfo.takeError()));939return;940}941debugTypesObj = makeTypeServerSource(ctx, this);942}943944// Used only for DWARF debug info, which is not common (except in MinGW945// environments). This returns an optional pair of file name and line946// number for where the variable was defined.947std::optional<std::pair<StringRef, uint32_t>>948ObjFile::getVariableLocation(StringRef var) {949if (!dwarf) {950dwarf = make<DWARFCache>(DWARFContext::create(*getCOFFObj()));951if (!dwarf)952return std::nullopt;953}954if (ctx.config.machine == I386)955var.consume_front("_");956std::optional<std::pair<std::string, unsigned>> ret =957dwarf->getVariableLoc(var);958if (!ret)959return std::nullopt;960return std::make_pair(saver().save(ret->first), ret->second);961}962963// Used only for DWARF debug info, which is not common (except in MinGW964// environments).965std::optional<DILineInfo> ObjFile::getDILineInfo(uint32_t offset,966uint32_t sectionIndex) {967if (!dwarf) {968dwarf = make<DWARFCache>(DWARFContext::create(*getCOFFObj()));969if (!dwarf)970return std::nullopt;971}972973return dwarf->getDILineInfo(offset, sectionIndex);974}975976void ObjFile::enqueuePdbFile(StringRef path, ObjFile *fromFile) {977auto p = findPdbPath(path.str(), fromFile, ctx.config.outputFile);978if (!p)979return;980auto it = ctx.pdbInputFileInstances.emplace(*p, nullptr);981if (!it.second)982return; // already scheduled for load983ctx.driver.enqueuePDB(*p);984}985986ImportFile::ImportFile(COFFLinkerContext &ctx, MemoryBufferRef m)987: InputFile(ctx, ImportKind, m), live(!ctx.config.doGC), thunkLive(live) {}988989void ImportFile::parse() {990const auto *hdr =991reinterpret_cast<const coff_import_header *>(mb.getBufferStart());992993// Check if the total size is valid.994if (mb.getBufferSize() < sizeof(*hdr) ||995mb.getBufferSize() != sizeof(*hdr) + hdr->SizeOfData)996fatal("broken import library");997998// Read names and create an __imp_ symbol.999StringRef buf = mb.getBuffer().substr(sizeof(*hdr));1000StringRef name = saver().save(buf.split('\0').first);1001StringRef impName = saver().save("__imp_" + name);1002buf = buf.substr(name.size() + 1);1003dllName = buf.split('\0').first;1004StringRef extName;1005switch (hdr->getNameType()) {1006case IMPORT_ORDINAL:1007extName = "";1008break;1009case IMPORT_NAME:1010extName = name;1011break;1012case IMPORT_NAME_NOPREFIX:1013extName = ltrim1(name, "?@_");1014break;1015case IMPORT_NAME_UNDECORATE:1016extName = ltrim1(name, "?@_");1017extName = extName.substr(0, extName.find('@'));1018break;1019case IMPORT_NAME_EXPORTAS:1020extName = buf.substr(dllName.size() + 1).split('\0').first;1021break;1022}10231024this->hdr = hdr;1025externalName = extName;10261027impSym = ctx.symtab.addImportData(impName, this);1028// If this was a duplicate, we logged an error but may continue;1029// in this case, impSym is nullptr.1030if (!impSym)1031return;10321033if (hdr->getType() == llvm::COFF::IMPORT_CONST)1034static_cast<void>(ctx.symtab.addImportData(name, this));10351036// If type is function, we need to create a thunk which jump to an1037// address pointed by the __imp_ symbol. (This allows you to call1038// DLL functions just like regular non-DLL functions.)1039if (hdr->getType() == llvm::COFF::IMPORT_CODE)1040thunkSym = ctx.symtab.addImportThunk(1041name, cast_or_null<DefinedImportData>(impSym), hdr->Machine);1042}10431044BitcodeFile::BitcodeFile(COFFLinkerContext &ctx, MemoryBufferRef mb,1045StringRef archiveName, uint64_t offsetInArchive,1046bool lazy)1047: InputFile(ctx, BitcodeKind, mb, lazy) {1048std::string path = mb.getBufferIdentifier().str();1049if (ctx.config.thinLTOIndexOnly)1050path = replaceThinLTOSuffix(mb.getBufferIdentifier(),1051ctx.config.thinLTOObjectSuffixReplace.first,1052ctx.config.thinLTOObjectSuffixReplace.second);10531054// ThinLTO assumes that all MemoryBufferRefs given to it have a unique1055// name. If two archives define two members with the same name, this1056// causes a collision which result in only one of the objects being taken1057// into consideration at LTO time (which very likely causes undefined1058// symbols later in the link stage). So we append file offset to make1059// filename unique.1060MemoryBufferRef mbref(mb.getBuffer(),1061saver().save(archiveName.empty()1062? path1063: archiveName +1064sys::path::filename(path) +1065utostr(offsetInArchive)));10661067obj = check(lto::InputFile::create(mbref));1068}10691070BitcodeFile::~BitcodeFile() = default;10711072void BitcodeFile::parse() {1073llvm::StringSaver &saver = lld::saver();10741075std::vector<std::pair<Symbol *, bool>> comdat(obj->getComdatTable().size());1076for (size_t i = 0; i != obj->getComdatTable().size(); ++i)1077// FIXME: Check nodeduplicate1078comdat[i] =1079ctx.symtab.addComdat(this, saver.save(obj->getComdatTable()[i].first));1080for (const lto::InputFile::Symbol &objSym : obj->symbols()) {1081StringRef symName = saver.save(objSym.getName());1082int comdatIndex = objSym.getComdatIndex();1083Symbol *sym;1084SectionChunk *fakeSC = nullptr;1085if (objSym.isExecutable())1086fakeSC = &ctx.ltoTextSectionChunk.chunk;1087else1088fakeSC = &ctx.ltoDataSectionChunk.chunk;1089if (objSym.isUndefined()) {1090sym = ctx.symtab.addUndefined(symName, this, false);1091if (objSym.isWeak())1092sym->deferUndefined = true;1093// If one LTO object file references (i.e. has an undefined reference to)1094// a symbol with an __imp_ prefix, the LTO compilation itself sees it1095// as unprefixed but with a dllimport attribute instead, and doesn't1096// understand the relation to a concrete IR symbol with the __imp_ prefix.1097//1098// For such cases, mark the symbol as used in a regular object (i.e. the1099// symbol must be retained) so that the linker can associate the1100// references in the end. If the symbol is defined in an import library1101// or in a regular object file, this has no effect, but if it is defined1102// in another LTO object file, this makes sure it is kept, to fulfill1103// the reference when linking the output of the LTO compilation.1104if (symName.starts_with("__imp_"))1105sym->isUsedInRegularObj = true;1106} else if (objSym.isCommon()) {1107sym = ctx.symtab.addCommon(this, symName, objSym.getCommonSize());1108} else if (objSym.isWeak() && objSym.isIndirect()) {1109// Weak external.1110sym = ctx.symtab.addUndefined(symName, this, true);1111std::string fallback = std::string(objSym.getCOFFWeakExternalFallback());1112Symbol *alias = ctx.symtab.addUndefined(saver.save(fallback));1113checkAndSetWeakAlias(ctx, this, sym, alias);1114} else if (comdatIndex != -1) {1115if (symName == obj->getComdatTable()[comdatIndex].first) {1116sym = comdat[comdatIndex].first;1117if (cast<DefinedRegular>(sym)->data == nullptr)1118cast<DefinedRegular>(sym)->data = &fakeSC->repl;1119} else if (comdat[comdatIndex].second) {1120sym = ctx.symtab.addRegular(this, symName, nullptr, fakeSC);1121} else {1122sym = ctx.symtab.addUndefined(symName, this, false);1123}1124} else {1125sym = ctx.symtab.addRegular(this, symName, nullptr, fakeSC, 0,1126objSym.isWeak());1127}1128symbols.push_back(sym);1129if (objSym.isUsed())1130ctx.config.gcroot.push_back(sym);1131}1132directives = saver.save(obj->getCOFFLinkerOpts());1133}11341135void BitcodeFile::parseLazy() {1136for (const lto::InputFile::Symbol &sym : obj->symbols())1137if (!sym.isUndefined())1138ctx.symtab.addLazyObject(this, sym.getName());1139}11401141MachineTypes BitcodeFile::getMachineType() {1142switch (Triple(obj->getTargetTriple()).getArch()) {1143case Triple::x86_64:1144return AMD64;1145case Triple::x86:1146return I386;1147case Triple::arm:1148case Triple::thumb:1149return ARMNT;1150case Triple::aarch64:1151return ARM64;1152default:1153return IMAGE_FILE_MACHINE_UNKNOWN;1154}1155}11561157std::string lld::coff::replaceThinLTOSuffix(StringRef path, StringRef suffix,1158StringRef repl) {1159if (path.consume_back(suffix))1160return (path + repl).str();1161return std::string(path);1162}11631164static bool isRVACode(COFFObjectFile *coffObj, uint64_t rva, InputFile *file) {1165for (size_t i = 1, e = coffObj->getNumberOfSections(); i <= e; i++) {1166const coff_section *sec = CHECK(coffObj->getSection(i), file);1167if (rva >= sec->VirtualAddress &&1168rva <= sec->VirtualAddress + sec->VirtualSize) {1169return (sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE) != 0;1170}1171}1172return false;1173}11741175void DLLFile::parse() {1176// Parse a memory buffer as a PE-COFF executable.1177std::unique_ptr<Binary> bin = CHECK(createBinary(mb), this);11781179if (auto *obj = dyn_cast<COFFObjectFile>(bin.get())) {1180bin.release();1181coffObj.reset(obj);1182} else {1183error(toString(this) + " is not a COFF file");1184return;1185}11861187if (!coffObj->getPE32Header() && !coffObj->getPE32PlusHeader()) {1188error(toString(this) + " is not a PE-COFF executable");1189return;1190}11911192for (const auto &exp : coffObj->export_directories()) {1193StringRef dllName, symbolName;1194uint32_t exportRVA;1195checkError(exp.getDllName(dllName));1196checkError(exp.getSymbolName(symbolName));1197checkError(exp.getExportRVA(exportRVA));11981199if (symbolName.empty())1200continue;12011202bool code = isRVACode(coffObj.get(), exportRVA, this);12031204Symbol *s = make<Symbol>();1205s->dllName = dllName;1206s->symbolName = symbolName;1207s->importType = code ? ImportType::IMPORT_CODE : ImportType::IMPORT_DATA;1208s->nameType = ImportNameType::IMPORT_NAME;12091210if (coffObj->getMachine() == I386) {1211s->symbolName = symbolName = saver().save("_" + symbolName);1212s->nameType = ImportNameType::IMPORT_NAME_NOPREFIX;1213}12141215StringRef impName = saver().save("__imp_" + symbolName);1216ctx.symtab.addLazyDLLSymbol(this, s, impName);1217if (code)1218ctx.symtab.addLazyDLLSymbol(this, s, symbolName);1219}1220}12211222MachineTypes DLLFile::getMachineType() {1223if (coffObj)1224return static_cast<MachineTypes>(coffObj->getMachine());1225return IMAGE_FILE_MACHINE_UNKNOWN;1226}12271228void DLLFile::makeImport(DLLFile::Symbol *s) {1229if (!seen.insert(s->symbolName).second)1230return;12311232size_t impSize = s->dllName.size() + s->symbolName.size() + 2; // +2 for NULs1233size_t size = sizeof(coff_import_header) + impSize;1234char *buf = bAlloc().Allocate<char>(size);1235memset(buf, 0, size);1236char *p = buf;1237auto *imp = reinterpret_cast<coff_import_header *>(p);1238p += sizeof(*imp);1239imp->Sig2 = 0xFFFF;1240imp->Machine = coffObj->getMachine();1241imp->SizeOfData = impSize;1242imp->OrdinalHint = 0; // Only linking by name1243imp->TypeInfo = (s->nameType << 2) | s->importType;12441245// Write symbol name and DLL name.1246memcpy(p, s->symbolName.data(), s->symbolName.size());1247p += s->symbolName.size() + 1;1248memcpy(p, s->dllName.data(), s->dllName.size());1249MemoryBufferRef mbref = MemoryBufferRef(StringRef(buf, size), s->dllName);1250ImportFile *impFile = make<ImportFile>(ctx, mbref);1251ctx.symtab.addFile(impFile);1252}125312541255