Index: vendor/lld/dist-release_60/COFF/Driver.cpp =================================================================== --- vendor/lld/dist-release_60/COFF/Driver.cpp (revision 328369) +++ vendor/lld/dist-release_60/COFF/Driver.cpp (revision 328370) @@ -1,1334 +1,1335 @@ //===- Driver.cpp ---------------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Driver.h" #include "Config.h" #include "InputFiles.h" #include "MinGW.h" #include "SymbolTable.h" #include "Symbols.h" #include "Writer.h" #include "lld/Common/Driver.h" #include "lld/Common/ErrorHandler.h" #include "lld/Common/Memory.h" #include "lld/Common/Version.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/BinaryFormat/Magic.h" #include "llvm/Object/ArchiveWriter.h" #include "llvm/Object/COFFImportFile.h" #include "llvm/Object/COFFModuleDefinition.h" #include "llvm/Option/Arg.h" #include "llvm/Option/ArgList.h" #include "llvm/Option/Option.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Path.h" #include "llvm/Support/Process.h" #include "llvm/Support/TarWriter.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/raw_ostream.h" #include "llvm/ToolDrivers/llvm-lib/LibDriver.h" #include #include #include using namespace llvm; using namespace llvm::object; using namespace llvm::COFF; using llvm::sys::Process; namespace lld { namespace coff { Configuration *Config; LinkerDriver *Driver; bool link(ArrayRef Args, bool CanExitEarly, raw_ostream &Diag) { errorHandler().LogName = Args[0]; errorHandler().ErrorOS = &Diag; errorHandler().ColorDiagnostics = Diag.has_colors(); errorHandler().ErrorLimitExceededMsg = "too many errors emitted, stopping now" " (use /ERRORLIMIT:0 to see all errors)"; + errorHandler().ExitEarly = CanExitEarly; Config = make(); Config->Argv = {Args.begin(), Args.end()}; Config->CanExitEarly = CanExitEarly; Symtab = make(); Driver = make(); Driver->link(Args); // Call exit() if we can to avoid calling destructors. if (CanExitEarly) exitLld(errorCount() ? 1 : 0); freeArena(); return !errorCount(); } // Drop directory components and replace extension with ".exe" or ".dll". static std::string getOutputPath(StringRef Path) { auto P = Path.find_last_of("\\/"); StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1); const char* E = Config->DLL ? ".dll" : ".exe"; return (S.substr(0, S.rfind('.')) + E).str(); } // ErrorOr is not default constructible, so it cannot be used as the type // parameter of a future. // FIXME: We could open the file in createFutureForFile and avoid needing to // return an error here, but for the moment that would cost us a file descriptor // (a limited resource on Windows) for the duration that the future is pending. typedef std::pair, std::error_code> MBErrPair; // Create a std::future that opens and maps a file using the best strategy for // the host platform. static std::future createFutureForFile(std::string Path) { #if LLVM_ON_WIN32 // On Windows, file I/O is relatively slow so it is best to do this // asynchronously. auto Strategy = std::launch::async; #else auto Strategy = std::launch::deferred; #endif return std::async(Strategy, [=]() { auto MBOrErr = MemoryBuffer::getFile(Path); if (!MBOrErr) return MBErrPair{nullptr, MBOrErr.getError()}; return MBErrPair{std::move(*MBOrErr), std::error_code()}; }); } MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr MB) { MemoryBufferRef MBRef = *MB; make>(std::move(MB)); // take ownership if (Driver->Tar) Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()), MBRef.getBuffer()); return MBRef; } void LinkerDriver::addBuffer(std::unique_ptr MB, bool WholeArchive) { MemoryBufferRef MBRef = takeBuffer(std::move(MB)); FilePaths.push_back(MBRef.getBufferIdentifier()); // File type is detected by contents, not by file extension. switch (identify_magic(MBRef.getBuffer())) { case file_magic::windows_resource: Resources.push_back(MBRef); break; case file_magic::archive: if (WholeArchive) { std::unique_ptr File = CHECK(Archive::create(MBRef), MBRef.getBufferIdentifier() + ": failed to parse archive"); for (MemoryBufferRef M : getArchiveMembers(File.get())) addArchiveBuffer(M, "", MBRef.getBufferIdentifier()); return; } Symtab->addFile(make(MBRef)); break; case file_magic::bitcode: Symtab->addFile(make(MBRef)); break; case file_magic::coff_cl_gl_object: error(MBRef.getBufferIdentifier() + ": is not a native COFF file. " "Recompile without /GL"); break; default: Symtab->addFile(make(MBRef)); break; } } void LinkerDriver::enqueuePath(StringRef Path, bool WholeArchive) { auto Future = std::make_shared>(createFutureForFile(Path)); std::string PathStr = Path; enqueueTask([=]() { auto MBOrErr = Future->get(); if (MBOrErr.second) error("could not open " + PathStr + ": " + MBOrErr.second.message()); else Driver->addBuffer(std::move(MBOrErr.first), WholeArchive); }); } void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName, StringRef ParentName) { file_magic Magic = identify_magic(MB.getBuffer()); if (Magic == file_magic::coff_import_library) { Symtab->addFile(make(MB)); return; } InputFile *Obj; if (Magic == file_magic::coff_object) { Obj = make(MB); } else if (Magic == file_magic::bitcode) { Obj = make(MB); } else { error("unknown file type: " + MB.getBufferIdentifier()); return; } Obj->ParentName = ParentName; Symtab->addFile(Obj); log("Loaded " + toString(Obj) + " for " + SymName); } void LinkerDriver::enqueueArchiveMember(const Archive::Child &C, StringRef SymName, StringRef ParentName) { if (!C.getParent()->isThin()) { MemoryBufferRef MB = CHECK( C.getMemoryBufferRef(), "could not get the buffer for the member defining symbol " + SymName); enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); }); return; } auto Future = std::make_shared>(createFutureForFile( CHECK(C.getFullName(), "could not get the filename for the member defining symbol " + SymName))); enqueueTask([=]() { auto MBOrErr = Future->get(); if (MBOrErr.second) fatal("could not get the buffer for the member defining " + SymName + ": " + MBOrErr.second.message()); Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName, ParentName); }); } static bool isDecorated(StringRef Sym) { return Sym.startswith("@") || Sym.contains("@@") || Sym.startswith("?") || (!Config->MinGW && Sym.contains('@')); } // Parses .drectve section contents and returns a list of files // specified by /defaultlib. void LinkerDriver::parseDirectives(StringRef S) { ArgParser Parser; // .drectve is always tokenized using Windows shell rules. opt::InputArgList Args = Parser.parseDirectives(S); for (auto *Arg : Args) { switch (Arg->getOption().getUnaliasedOption().getID()) { case OPT_aligncomm: parseAligncomm(Arg->getValue()); break; case OPT_alternatename: parseAlternateName(Arg->getValue()); break; case OPT_defaultlib: if (Optional Path = findLib(Arg->getValue())) enqueuePath(*Path, false); break; case OPT_entry: Config->Entry = addUndefined(mangle(Arg->getValue())); break; case OPT_export: { // If a common header file contains dllexported function // declarations, many object files may end up with having the // same /EXPORT options. In order to save cost of parsing them, // we dedup them first. if (!DirectivesExports.insert(Arg->getValue()).second) break; Export E = parseExport(Arg->getValue()); if (Config->Machine == I386 && Config->MinGW) { if (!isDecorated(E.Name)) E.Name = Saver.save("_" + E.Name); if (!E.ExtName.empty() && !isDecorated(E.ExtName)) E.ExtName = Saver.save("_" + E.ExtName); } E.Directives = true; Config->Exports.push_back(E); break; } case OPT_failifmismatch: checkFailIfMismatch(Arg->getValue()); break; case OPT_incl: addUndefined(Arg->getValue()); break; case OPT_merge: parseMerge(Arg->getValue()); break; case OPT_nodefaultlib: Config->NoDefaultLibs.insert(doFindLib(Arg->getValue())); break; case OPT_section: parseSection(Arg->getValue()); break; case OPT_subsystem: parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion, &Config->MinorOSVersion); break; case OPT_editandcontinue: case OPT_fastfail: case OPT_guardsym: case OPT_natvis: case OPT_throwingnew: break; default: error(Arg->getSpelling() + " is not allowed in .drectve"); } } } // Find file from search paths. You can omit ".obj", this function takes // care of that. Note that the returned path is not guaranteed to exist. StringRef LinkerDriver::doFindFile(StringRef Filename) { bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos); if (HasPathSep) return Filename; bool HasExt = Filename.contains('.'); for (StringRef Dir : SearchPaths) { SmallString<128> Path = Dir; sys::path::append(Path, Filename); if (sys::fs::exists(Path.str())) return Saver.save(Path.str()); if (!HasExt) { Path.append(".obj"); if (sys::fs::exists(Path.str())) return Saver.save(Path.str()); } } return Filename; } // Resolves a file path. This never returns the same path // (in that case, it returns None). Optional LinkerDriver::findFile(StringRef Filename) { StringRef Path = doFindFile(Filename); bool Seen = !VisitedFiles.insert(Path.lower()).second; if (Seen) return None; if (Path.endswith_lower(".lib")) VisitedLibs.insert(sys::path::filename(Path)); return Path; } // Find library file from search path. StringRef LinkerDriver::doFindLib(StringRef Filename) { // Add ".lib" to Filename if that has no file extension. bool HasExt = Filename.contains('.'); if (!HasExt) Filename = Saver.save(Filename + ".lib"); return doFindFile(Filename); } // Resolves a library path. /nodefaultlib options are taken into // consideration. This never returns the same path (in that case, // it returns None). Optional LinkerDriver::findLib(StringRef Filename) { if (Config->NoDefaultLibAll) return None; if (!VisitedLibs.insert(Filename.lower()).second) return None; StringRef Path = doFindLib(Filename); if (Config->NoDefaultLibs.count(Path)) return None; if (!VisitedFiles.insert(Path.lower()).second) return None; return Path; } // Parses LIB environment which contains a list of search paths. void LinkerDriver::addLibSearchPaths() { Optional EnvOpt = Process::GetEnv("LIB"); if (!EnvOpt.hasValue()) return; StringRef Env = Saver.save(*EnvOpt); while (!Env.empty()) { StringRef Path; std::tie(Path, Env) = Env.split(';'); SearchPaths.push_back(Path); } } Symbol *LinkerDriver::addUndefined(StringRef Name) { Symbol *B = Symtab->addUndefined(Name); if (!B->IsGCRoot) { B->IsGCRoot = true; Config->GCRoot.push_back(B); } return B; } // Symbol names are mangled by appending "_" prefix on x86. StringRef LinkerDriver::mangle(StringRef Sym) { assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN); if (Config->Machine == I386) return Saver.save("_" + Sym); return Sym; } // Windows specific -- find default entry point name. StringRef LinkerDriver::findDefaultEntry() { // User-defined main functions and their corresponding entry points. static const char *Entries[][2] = { {"main", "mainCRTStartup"}, {"wmain", "wmainCRTStartup"}, {"WinMain", "WinMainCRTStartup"}, {"wWinMain", "wWinMainCRTStartup"}, }; for (auto E : Entries) { StringRef Entry = Symtab->findMangle(mangle(E[0])); if (!Entry.empty() && !isa(Symtab->find(Entry))) return mangle(E[1]); } return ""; } WindowsSubsystem LinkerDriver::inferSubsystem() { if (Config->DLL) return IMAGE_SUBSYSTEM_WINDOWS_GUI; if (Symtab->findUnderscore("main") || Symtab->findUnderscore("wmain")) return IMAGE_SUBSYSTEM_WINDOWS_CUI; if (Symtab->findUnderscore("WinMain") || Symtab->findUnderscore("wWinMain")) return IMAGE_SUBSYSTEM_WINDOWS_GUI; return IMAGE_SUBSYSTEM_UNKNOWN; } static uint64_t getDefaultImageBase() { if (Config->is64()) return Config->DLL ? 0x180000000 : 0x140000000; return Config->DLL ? 0x10000000 : 0x400000; } static std::string createResponseFile(const opt::InputArgList &Args, ArrayRef FilePaths, ArrayRef SearchPaths) { SmallString<0> Data; raw_svector_ostream OS(Data); for (auto *Arg : Args) { switch (Arg->getOption().getID()) { case OPT_linkrepro: case OPT_INPUT: case OPT_defaultlib: case OPT_libpath: case OPT_manifest: case OPT_manifest_colon: case OPT_manifestdependency: case OPT_manifestfile: case OPT_manifestinput: case OPT_manifestuac: break; default: OS << toString(*Arg) << "\n"; } } for (StringRef Path : SearchPaths) { std::string RelPath = relativeToRoot(Path); OS << "/libpath:" << quote(RelPath) << "\n"; } for (StringRef Path : FilePaths) OS << quote(relativeToRoot(Path)) << "\n"; return Data.str(); } static unsigned getDefaultDebugType(const opt::InputArgList &Args) { unsigned DebugTypes = static_cast(DebugType::CV); if (Args.hasArg(OPT_driver)) DebugTypes |= static_cast(DebugType::PData); if (Args.hasArg(OPT_profile)) DebugTypes |= static_cast(DebugType::Fixup); return DebugTypes; } static unsigned parseDebugType(StringRef Arg) { SmallVector Types; Arg.split(Types, ',', /*KeepEmpty=*/false); unsigned DebugTypes = static_cast(DebugType::None); for (StringRef Type : Types) DebugTypes |= StringSwitch(Type.lower()) .Case("cv", static_cast(DebugType::CV)) .Case("pdata", static_cast(DebugType::PData)) .Case("fixup", static_cast(DebugType::Fixup)) .Default(0); return DebugTypes; } static std::string getMapFile(const opt::InputArgList &Args) { auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file); if (!Arg) return ""; if (Arg->getOption().getID() == OPT_lldmap_file) return Arg->getValue(); assert(Arg->getOption().getID() == OPT_lldmap); StringRef OutFile = Config->OutputFile; return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str(); } static std::string getImplibPath() { if (!Config->Implib.empty()) return Config->Implib; SmallString<128> Out = StringRef(Config->OutputFile); sys::path::replace_extension(Out, ".lib"); return Out.str(); } // // The import name is caculated as the following: // // | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY // -----+----------------+---------------------+------------------ // LINK | {value} | {value}.{.dll/.exe} | {output name} // LIB | {value} | {value}.dll | {output name}.dll // static std::string getImportName(bool AsLib) { SmallString<128> Out; if (Config->ImportName.empty()) { Out.assign(sys::path::filename(Config->OutputFile)); if (AsLib) sys::path::replace_extension(Out, ".dll"); } else { Out.assign(Config->ImportName); if (!sys::path::has_extension(Out)) sys::path::replace_extension(Out, (Config->DLL || AsLib) ? ".dll" : ".exe"); } return Out.str(); } static void createImportLibrary(bool AsLib) { std::vector Exports; for (Export &E1 : Config->Exports) { COFFShortExport E2; E2.Name = E1.Name; E2.SymbolName = E1.SymbolName; E2.ExtName = E1.ExtName; E2.Ordinal = E1.Ordinal; E2.Noname = E1.Noname; E2.Data = E1.Data; E2.Private = E1.Private; E2.Constant = E1.Constant; Exports.push_back(E2); } auto E = writeImportLibrary(getImportName(AsLib), getImplibPath(), Exports, Config->Machine, false); handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) { error(EIB.message()); }); } static void parseModuleDefs(StringRef Path) { std::unique_ptr MB = CHECK( MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path); COFFModuleDefinition M = check(parseCOFFModuleDefinition( MB->getMemBufferRef(), Config->Machine, Config->MinGW)); if (Config->OutputFile.empty()) Config->OutputFile = Saver.save(M.OutputFile); Config->ImportName = Saver.save(M.ImportName); if (M.ImageBase) Config->ImageBase = M.ImageBase; if (M.StackReserve) Config->StackReserve = M.StackReserve; if (M.StackCommit) Config->StackCommit = M.StackCommit; if (M.HeapReserve) Config->HeapReserve = M.HeapReserve; if (M.HeapCommit) Config->HeapCommit = M.HeapCommit; if (M.MajorImageVersion) Config->MajorImageVersion = M.MajorImageVersion; if (M.MinorImageVersion) Config->MinorImageVersion = M.MinorImageVersion; if (M.MajorOSVersion) Config->MajorOSVersion = M.MajorOSVersion; if (M.MinorOSVersion) Config->MinorOSVersion = M.MinorOSVersion; for (COFFShortExport E1 : M.Exports) { Export E2; E2.Name = Saver.save(E1.Name); if (E1.isWeak()) E2.ExtName = Saver.save(E1.ExtName); E2.Ordinal = E1.Ordinal; E2.Noname = E1.Noname; E2.Data = E1.Data; E2.Private = E1.Private; E2.Constant = E1.Constant; Config->Exports.push_back(E2); } } // A helper function for filterBitcodeFiles. static bool needsRebuilding(MemoryBufferRef MB) { // The MSVC linker doesn't support thin archives, so if it's a thin // archive, we always need to rebuild it. std::unique_ptr File = CHECK(Archive::create(MB), "Failed to read " + MB.getBufferIdentifier()); if (File->isThin()) return true; // Returns true if the archive contains at least one bitcode file. for (MemoryBufferRef Member : getArchiveMembers(File.get())) if (identify_magic(Member.getBuffer()) == file_magic::bitcode) return true; return false; } // Opens a given path as an archive file and removes bitcode files // from them if exists. This function is to appease the MSVC linker as // their linker doesn't like archive files containing non-native // object files. // // If a given archive doesn't contain bitcode files, the archive path // is returned as-is. Otherwise, a new temporary file is created and // its path is returned. static Optional filterBitcodeFiles(StringRef Path, std::vector &TemporaryFiles) { std::unique_ptr MB = CHECK( MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path); MemoryBufferRef MBRef = MB->getMemBufferRef(); file_magic Magic = identify_magic(MBRef.getBuffer()); if (Magic == file_magic::bitcode) return None; if (Magic != file_magic::archive) return Path.str(); if (!needsRebuilding(MBRef)) return Path.str(); std::unique_ptr File = CHECK(Archive::create(MBRef), MBRef.getBufferIdentifier() + ": failed to parse archive"); std::vector New; for (MemoryBufferRef Member : getArchiveMembers(File.get())) if (identify_magic(Member.getBuffer()) != file_magic::bitcode) New.emplace_back(Member); if (New.empty()) return None; log("Creating a temporary archive for " + Path + " to remove bitcode files"); SmallString<128> S; if (auto EC = sys::fs::createTemporaryFile("lld-" + sys::path::stem(Path), ".lib", S)) fatal("cannot create a temporary file: " + EC.message()); std::string Temp = S.str(); TemporaryFiles.push_back(Temp); Error E = llvm::writeArchive(Temp, New, /*WriteSymtab=*/true, Archive::Kind::K_GNU, /*Deterministics=*/true, /*Thin=*/false); handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) { error("failed to create a new archive " + S.str() + ": " + EI.message()); }); return Temp; } // Create response file contents and invoke the MSVC linker. void LinkerDriver::invokeMSVC(opt::InputArgList &Args) { std::string Rsp = "/nologo\n"; std::vector Temps; // Write out archive members that we used in symbol resolution and pass these // to MSVC before any archives, so that MSVC uses the same objects to satisfy // references. for (ObjFile *Obj : ObjFile::Instances) { if (Obj->ParentName.empty()) continue; SmallString<128> S; int Fd; if (auto EC = sys::fs::createTemporaryFile( "lld-" + sys::path::filename(Obj->ParentName), ".obj", Fd, S)) fatal("cannot create a temporary file: " + EC.message()); raw_fd_ostream OS(Fd, /*shouldClose*/ true); OS << Obj->MB.getBuffer(); Temps.push_back(S.str()); Rsp += quote(S) + "\n"; } for (auto *Arg : Args) { switch (Arg->getOption().getID()) { case OPT_linkrepro: case OPT_lldmap: case OPT_lldmap_file: case OPT_lldsavetemps: case OPT_msvclto: // LLD-specific options are stripped. break; case OPT_opt: if (!StringRef(Arg->getValue()).startswith("lld")) Rsp += toString(*Arg) + " "; break; case OPT_INPUT: { if (Optional Path = doFindFile(Arg->getValue())) { if (Optional S = filterBitcodeFiles(*Path, Temps)) Rsp += quote(*S) + "\n"; continue; } Rsp += quote(Arg->getValue()) + "\n"; break; } default: Rsp += toString(*Arg) + "\n"; } } std::vector ObjFiles = Symtab->compileBitcodeFiles(); runMSVCLinker(Rsp, ObjFiles); for (StringRef Path : Temps) sys::fs::remove(Path); } void LinkerDriver::enqueueTask(std::function Task) { TaskQueue.push_back(std::move(Task)); } bool LinkerDriver::run() { bool DidWork = !TaskQueue.empty(); while (!TaskQueue.empty()) { TaskQueue.front()(); TaskQueue.pop_front(); } return DidWork; } void LinkerDriver::link(ArrayRef ArgsArr) { // If the first command line argument is "/lib", link.exe acts like lib.exe. // We call our own implementation of lib.exe that understands bitcode files. if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) { if (llvm::libDriverMain(ArgsArr.slice(1)) != 0) fatal("lib failed"); return; } // Needed for LTO. InitializeAllTargetInfos(); InitializeAllTargets(); InitializeAllTargetMCs(); InitializeAllAsmParsers(); InitializeAllAsmPrinters(); InitializeAllDisassemblers(); // Parse command line options. ArgParser Parser; opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1)); // Parse and evaluate -mllvm options. std::vector V; V.push_back("lld-link (LLVM option parsing)"); for (auto *Arg : Args.filtered(OPT_mllvm)) V.push_back(Arg->getValue()); cl::ParseCommandLineOptions(V.size(), V.data()); // Handle /errorlimit early, because error() depends on it. if (auto *Arg = Args.getLastArg(OPT_errorlimit)) { int N = 20; StringRef S = Arg->getValue(); if (S.getAsInteger(10, N)) error(Arg->getSpelling() + " number expected, but got " + S); errorHandler().ErrorLimit = N; } // Handle /help if (Args.hasArg(OPT_help)) { printHelp(ArgsArr[0]); return; } // Handle --version, which is an lld extension. This option is a bit odd // because it doesn't start with "/", but we deliberately chose "--" to // avoid conflict with /version and for compatibility with clang-cl. if (Args.hasArg(OPT_dash_dash_version)) { outs() << getLLDVersion() << "\n"; return; } // Handle /lldmingw early, since it can potentially affect how other // options are handled. Config->MinGW = Args.hasArg(OPT_lldmingw); if (auto *Arg = Args.getLastArg(OPT_linkrepro)) { SmallString<64> Path = StringRef(Arg->getValue()); sys::path::append(Path, "repro.tar"); Expected> ErrOrWriter = TarWriter::create(Path, "repro"); if (ErrOrWriter) { Tar = std::move(*ErrOrWriter); } else { error("/linkrepro: failed to open " + Path + ": " + toString(ErrOrWriter.takeError())); } } if (!Args.hasArg(OPT_INPUT)) { if (Args.hasArg(OPT_deffile)) Config->NoEntry = true; else fatal("no input files"); } // Construct search path list. SearchPaths.push_back(""); for (auto *Arg : Args.filtered(OPT_libpath)) SearchPaths.push_back(Arg->getValue()); addLibSearchPaths(); // Handle /ignore for (auto *Arg : Args.filtered(OPT_ignore)) { if (StringRef(Arg->getValue()) == "4217") Config->WarnLocallyDefinedImported = false; // Other warning numbers are ignored. } // Handle /out if (auto *Arg = Args.getLastArg(OPT_out)) Config->OutputFile = Arg->getValue(); // Handle /verbose if (Args.hasArg(OPT_verbose)) Config->Verbose = true; errorHandler().Verbose = Config->Verbose; // Handle /force or /force:unresolved if (Args.hasArg(OPT_force, OPT_force_unresolved)) Config->Force = true; // Handle /debug if (Args.hasArg(OPT_debug, OPT_debug_dwarf, OPT_debug_ghash)) { Config->Debug = true; if (auto *Arg = Args.getLastArg(OPT_debugtype)) Config->DebugTypes = parseDebugType(Arg->getValue()); else Config->DebugTypes = getDefaultDebugType(Args); } // Handle /pdb bool ShouldCreatePDB = Args.hasArg(OPT_debug, OPT_debug_ghash); if (ShouldCreatePDB) if (auto *Arg = Args.getLastArg(OPT_pdb)) Config->PDBPath = Arg->getValue(); // Handle /noentry if (Args.hasArg(OPT_noentry)) { if (Args.hasArg(OPT_dll)) Config->NoEntry = true; else error("/noentry must be specified with /dll"); } // Handle /dll if (Args.hasArg(OPT_dll)) { Config->DLL = true; Config->ManifestID = 2; } // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase // because we need to explicitly check whether that option or its inverse was // present in the argument list in order to handle /fixed. auto *DynamicBaseArg = Args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no); if (DynamicBaseArg && DynamicBaseArg->getOption().getID() == OPT_dynamicbase_no) Config->DynamicBase = false; bool Fixed = Args.hasFlag(OPT_fixed, OPT_fixed_no, false); if (Fixed) { if (DynamicBaseArg && DynamicBaseArg->getOption().getID() == OPT_dynamicbase) { error("/fixed must not be specified with /dynamicbase"); } else { Config->Relocatable = false; Config->DynamicBase = false; } } // Handle /appcontainer Config->AppContainer = Args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false); // Handle /machine if (auto *Arg = Args.getLastArg(OPT_machine)) Config->Machine = getMachineType(Arg->getValue()); // Handle /nodefaultlib: for (auto *Arg : Args.filtered(OPT_nodefaultlib)) Config->NoDefaultLibs.insert(doFindLib(Arg->getValue())); // Handle /nodefaultlib if (Args.hasArg(OPT_nodefaultlib_all)) Config->NoDefaultLibAll = true; // Handle /base if (auto *Arg = Args.getLastArg(OPT_base)) parseNumbers(Arg->getValue(), &Config->ImageBase); // Handle /stack if (auto *Arg = Args.getLastArg(OPT_stack)) parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit); // Handle /heap if (auto *Arg = Args.getLastArg(OPT_heap)) parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit); // Handle /version if (auto *Arg = Args.getLastArg(OPT_version)) parseVersion(Arg->getValue(), &Config->MajorImageVersion, &Config->MinorImageVersion); // Handle /subsystem if (auto *Arg = Args.getLastArg(OPT_subsystem)) parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion, &Config->MinorOSVersion); // Handle /alternatename for (auto *Arg : Args.filtered(OPT_alternatename)) parseAlternateName(Arg->getValue()); // Handle /include for (auto *Arg : Args.filtered(OPT_incl)) addUndefined(Arg->getValue()); // Handle /implib if (auto *Arg = Args.getLastArg(OPT_implib)) Config->Implib = Arg->getValue(); // Handle /opt. bool DoGC = !Args.hasArg(OPT_debug); unsigned ICFLevel = 1; // 0: off, 1: limited, 2: on for (auto *Arg : Args.filtered(OPT_opt)) { std::string Str = StringRef(Arg->getValue()).lower(); SmallVector Vec; StringRef(Str).split(Vec, ','); for (StringRef S : Vec) { if (S == "ref") { DoGC = true; } else if (S == "noref") { DoGC = false; } else if (S == "icf" || S.startswith("icf=")) { ICFLevel = 2; } else if (S == "noicf") { ICFLevel = 0; } else if (S.startswith("lldlto=")) { StringRef OptLevel = S.substr(7); if (OptLevel.getAsInteger(10, Config->LTOOptLevel) || Config->LTOOptLevel > 3) error("/opt:lldlto: invalid optimization level: " + OptLevel); } else if (S.startswith("lldltojobs=")) { StringRef Jobs = S.substr(11); if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0) error("/opt:lldltojobs: invalid job count: " + Jobs); } else if (S.startswith("lldltopartitions=")) { StringRef N = S.substr(17); if (N.getAsInteger(10, Config->LTOPartitions) || Config->LTOPartitions == 0) error("/opt:lldltopartitions: invalid partition count: " + N); } else if (S != "lbr" && S != "nolbr") error("/opt: unknown option: " + S); } } // Limited ICF is enabled if GC is enabled and ICF was never mentioned // explicitly. // FIXME: LLD only implements "limited" ICF, i.e. it only merges identical // code. If the user passes /OPT:ICF explicitly, LLD should merge identical // comdat readonly data. if (ICFLevel == 1 && !DoGC) ICFLevel = 0; Config->DoGC = DoGC; Config->DoICF = ICFLevel > 0; // Handle /lldsavetemps if (Args.hasArg(OPT_lldsavetemps)) Config->SaveTemps = true; // Handle /lldltocache if (auto *Arg = Args.getLastArg(OPT_lldltocache)) Config->LTOCache = Arg->getValue(); // Handle /lldsavecachepolicy if (auto *Arg = Args.getLastArg(OPT_lldltocachepolicy)) Config->LTOCachePolicy = CHECK( parseCachePruningPolicy(Arg->getValue()), Twine("/lldltocachepolicy: invalid cache policy: ") + Arg->getValue()); // Handle /failifmismatch for (auto *Arg : Args.filtered(OPT_failifmismatch)) checkFailIfMismatch(Arg->getValue()); // Handle /merge for (auto *Arg : Args.filtered(OPT_merge)) parseMerge(Arg->getValue()); // Handle /section for (auto *Arg : Args.filtered(OPT_section)) parseSection(Arg->getValue()); // Handle /aligncomm for (auto *Arg : Args.filtered(OPT_aligncomm)) parseAligncomm(Arg->getValue()); // Handle /manifestdependency. This enables /manifest unless /manifest:no is // also passed. if (auto *Arg = Args.getLastArg(OPT_manifestdependency)) { Config->ManifestDependency = Arg->getValue(); Config->Manifest = Configuration::SideBySide; } // Handle /manifest and /manifest: if (auto *Arg = Args.getLastArg(OPT_manifest, OPT_manifest_colon)) { if (Arg->getOption().getID() == OPT_manifest) Config->Manifest = Configuration::SideBySide; else parseManifest(Arg->getValue()); } // Handle /manifestuac if (auto *Arg = Args.getLastArg(OPT_manifestuac)) parseManifestUAC(Arg->getValue()); // Handle /manifestfile if (auto *Arg = Args.getLastArg(OPT_manifestfile)) Config->ManifestFile = Arg->getValue(); // Handle /manifestinput for (auto *Arg : Args.filtered(OPT_manifestinput)) Config->ManifestInput.push_back(Arg->getValue()); if (!Config->ManifestInput.empty() && Config->Manifest != Configuration::Embed) { fatal("/MANIFESTINPUT: requires /MANIFEST:EMBED"); } // Handle miscellaneous boolean flags. Config->AllowBind = Args.hasFlag(OPT_allowbind, OPT_allowbind_no, true); Config->AllowIsolation = Args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true); Config->NxCompat = Args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true); Config->TerminalServerAware = Args.hasFlag(OPT_tsaware, OPT_tsaware_no, true); Config->DebugDwarf = Args.hasArg(OPT_debug_dwarf); Config->DebugGHashes = Args.hasArg(OPT_debug_ghash); Config->MapFile = getMapFile(Args); if (errorCount()) return; bool WholeArchiveFlag = Args.hasArg(OPT_wholearchive_flag); // Create a list of input files. Files can be given as arguments // for /defaultlib option. std::vector MBs; for (auto *Arg : Args.filtered(OPT_INPUT, OPT_wholearchive_file)) { switch (Arg->getOption().getID()) { case OPT_INPUT: if (Optional Path = findFile(Arg->getValue())) enqueuePath(*Path, WholeArchiveFlag); break; case OPT_wholearchive_file: if (Optional Path = findFile(Arg->getValue())) enqueuePath(*Path, true); break; } } for (auto *Arg : Args.filtered(OPT_defaultlib)) if (Optional Path = findLib(Arg->getValue())) enqueuePath(*Path, false); // Windows specific -- Create a resource file containing a manifest file. if (Config->Manifest == Configuration::Embed) addBuffer(createManifestRes(), false); // Read all input files given via the command line. run(); // We should have inferred a machine type by now from the input files, but if // not we assume x64. if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) { warn("/machine is not specified. x64 is assumed"); Config->Machine = AMD64; } // Input files can be Windows resource files (.res files). We use // WindowsResource to convert resource files to a regular COFF file, // then link the resulting file normally. if (!Resources.empty()) Symtab->addFile(make(convertResToCOFF(Resources))); if (Tar) Tar->append("response.txt", createResponseFile(Args, FilePaths, ArrayRef(SearchPaths).slice(1))); // Handle /largeaddressaware Config->LargeAddressAware = Args.hasFlag( OPT_largeaddressaware, OPT_largeaddressaware_no, Config->is64()); // Handle /highentropyva Config->HighEntropyVA = Config->is64() && Args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true); if (!Config->DynamicBase && (Config->Machine == ARMNT || Config->Machine == ARM64)) error("/dynamicbase:no is not compatible with " + machineToStr(Config->Machine)); // Handle /entry and /dll if (auto *Arg = Args.getLastArg(OPT_entry)) { Config->Entry = addUndefined(mangle(Arg->getValue())); } else if (!Config->Entry && !Config->NoEntry) { if (Args.hasArg(OPT_dll)) { StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12" : "_DllMainCRTStartup"; Config->Entry = addUndefined(S); } else { // Windows specific -- If entry point name is not given, we need to // infer that from user-defined entry name. StringRef S = findDefaultEntry(); if (S.empty()) fatal("entry point must be defined"); Config->Entry = addUndefined(S); log("Entry name inferred: " + S); } } // Handle /export for (auto *Arg : Args.filtered(OPT_export)) { Export E = parseExport(Arg->getValue()); if (Config->Machine == I386) { if (!isDecorated(E.Name)) E.Name = Saver.save("_" + E.Name); if (!E.ExtName.empty() && !isDecorated(E.ExtName)) E.ExtName = Saver.save("_" + E.ExtName); } Config->Exports.push_back(E); } // Handle /def if (auto *Arg = Args.getLastArg(OPT_deffile)) { // parseModuleDefs mutates Config object. parseModuleDefs(Arg->getValue()); } // Handle generation of import library from a def file. if (!Args.hasArg(OPT_INPUT)) { fixupExports(); createImportLibrary(/*AsLib=*/true); return; } // Handle /delayload for (auto *Arg : Args.filtered(OPT_delayload)) { Config->DelayLoads.insert(StringRef(Arg->getValue()).lower()); if (Config->Machine == I386) { Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8"); } else { Config->DelayLoadHelper = addUndefined("__delayLoadHelper2"); } } // Set default image name if neither /out or /def set it. if (Config->OutputFile.empty()) { Config->OutputFile = getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue()); } // Put the PDB next to the image if no /pdb flag was passed. if (ShouldCreatePDB && Config->PDBPath.empty()) { Config->PDBPath = Config->OutputFile; sys::path::replace_extension(Config->PDBPath, ".pdb"); } // Set default image base if /base is not given. if (Config->ImageBase == uint64_t(-1)) Config->ImageBase = getDefaultImageBase(); Symtab->addSynthetic(mangle("__ImageBase"), nullptr); if (Config->Machine == I386) { Symtab->addAbsolute("___safe_se_handler_table", 0); Symtab->addAbsolute("___safe_se_handler_count", 0); } // We do not support /guard:cf (control flow protection) yet. // Define CFG symbols anyway so that we can link MSVC 2015 CRT. Symtab->addAbsolute(mangle("__guard_fids_count"), 0); Symtab->addAbsolute(mangle("__guard_fids_table"), 0); Symtab->addAbsolute(mangle("__guard_flags"), 0x100); Symtab->addAbsolute(mangle("__guard_iat_count"), 0); Symtab->addAbsolute(mangle("__guard_iat_table"), 0); Symtab->addAbsolute(mangle("__guard_longjmp_count"), 0); Symtab->addAbsolute(mangle("__guard_longjmp_table"), 0); // Needed for MSVC 2017 15.5 CRT. Symtab->addAbsolute(mangle("__enclave_config"), 0); // This code may add new undefined symbols to the link, which may enqueue more // symbol resolution tasks, so we need to continue executing tasks until we // converge. do { // Windows specific -- if entry point is not found, // search for its mangled names. if (Config->Entry) Symtab->mangleMaybe(Config->Entry); // Windows specific -- Make sure we resolve all dllexported symbols. for (Export &E : Config->Exports) { if (!E.ForwardTo.empty()) continue; E.Sym = addUndefined(E.Name); if (!E.Directives) Symtab->mangleMaybe(E.Sym); } // Add weak aliases. Weak aliases is a mechanism to give remaining // undefined symbols final chance to be resolved successfully. for (auto Pair : Config->AlternateNames) { StringRef From = Pair.first; StringRef To = Pair.second; Symbol *Sym = Symtab->find(From); if (!Sym) continue; if (auto *U = dyn_cast(Sym)) if (!U->WeakAlias) U->WeakAlias = Symtab->addUndefined(To); } // Windows specific -- if __load_config_used can be resolved, resolve it. if (Symtab->findUnderscore("_load_config_used")) addUndefined(mangle("_load_config_used")); } while (run()); if (errorCount()) return; // If /msvclto is given, we use the MSVC linker to link LTO output files. // This is useful because MSVC link.exe can generate complete PDBs. if (Args.hasArg(OPT_msvclto)) { invokeMSVC(Args); return; } // Do LTO by compiling bitcode input files to a set of native COFF files then // link those files. Symtab->addCombinedLTOObjects(); run(); // Make sure we have resolved all symbols. Symtab->reportRemainingUndefines(); if (errorCount()) return; // Windows specific -- if no /subsystem is given, we need to infer // that from entry point name. if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) { Config->Subsystem = inferSubsystem(); if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) fatal("subsystem must be defined"); } // Handle /safeseh. if (Args.hasFlag(OPT_safeseh, OPT_safeseh_no, false)) { for (ObjFile *File : ObjFile::Instances) if (!File->SEHCompat) error("/safeseh: " + File->getName() + " is not compatible with SEH"); if (errorCount()) return; } // In MinGW, all symbols are automatically exported if no symbols // are chosen to be exported. if (Config->DLL && ((Config->MinGW && Config->Exports.empty()) || Args.hasArg(OPT_export_all_symbols))) { AutoExporter Exporter; Symtab->forEachSymbol([=](Symbol *S) { auto *Def = dyn_cast(S); if (!Exporter.shouldExport(Def)) return; Export E; E.Name = Def->getName(); E.Sym = Def; if (Def->getChunk() && !(Def->getChunk()->getPermissions() & IMAGE_SCN_MEM_EXECUTE)) E.Data = true; Config->Exports.push_back(E); }); } // Windows specific -- when we are creating a .dll file, we also // need to create a .lib file. if (!Config->Exports.empty() || Config->DLL) { fixupExports(); createImportLibrary(/*AsLib=*/false); assignExportOrdinals(); } // Handle /output-def (MinGW specific). if (auto *Arg = Args.getLastArg(OPT_output_def)) writeDefFile(Arg->getValue()); // Set extra alignment for .comm symbols for (auto Pair : Config->AlignComm) { StringRef Name = Pair.first; uint32_t Alignment = Pair.second; Symbol *Sym = Symtab->find(Name); if (!Sym) { warn("/aligncomm symbol " + Name + " not found"); continue; } auto *DC = dyn_cast(Sym); if (!DC) { warn("/aligncomm symbol " + Name + " of wrong kind"); continue; } CommonChunk *C = DC->getChunk(); C->Alignment = std::max(C->Alignment, Alignment); } // Windows specific -- Create a side-by-side manifest file. if (Config->Manifest == Configuration::SideBySide) createSideBySideManifest(); // Identify unreferenced COMDAT sections. if (Config->DoGC) markLive(Symtab->getChunks()); // Identify identical COMDAT sections to merge them. if (Config->DoICF) doICF(Symtab->getChunks()); // Write the result. writeResult(); } } // namespace coff } // namespace lld Index: vendor/lld/dist-release_60/ELF/LinkerScript.cpp =================================================================== --- vendor/lld/dist-release_60/ELF/LinkerScript.cpp (revision 328369) +++ vendor/lld/dist-release_60/ELF/LinkerScript.cpp (revision 328370) @@ -1,1022 +1,1026 @@ //===- LinkerScript.cpp ---------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains the parser/evaluator of the linker script. // //===----------------------------------------------------------------------===// #include "LinkerScript.h" #include "Config.h" #include "InputSection.h" #include "OutputSections.h" #include "Strings.h" #include "SymbolTable.h" #include "Symbols.h" #include "SyntheticSections.h" #include "Target.h" #include "Writer.h" #include "lld/Common/Memory.h" #include "lld/Common/Threads.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/BinaryFormat/ELF.h" #include "llvm/Support/Casting.h" #include "llvm/Support/Endian.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include #include #include #include #include #include #include #include using namespace llvm; using namespace llvm::ELF; using namespace llvm::object; using namespace llvm::support::endian; using namespace lld; using namespace lld::elf; LinkerScript *elf::Script; static uint64_t getOutputSectionVA(SectionBase *InputSec, StringRef Loc) { if (OutputSection *OS = InputSec->getOutputSection()) return OS->Addr; error(Loc + ": unable to evaluate expression: input section " + InputSec->Name + " has no output section assigned"); return 0; } uint64_t ExprValue::getValue() const { if (Sec) return alignTo(Sec->getOffset(Val) + getOutputSectionVA(Sec, Loc), Alignment); return alignTo(Val, Alignment); } uint64_t ExprValue::getSecAddr() const { if (Sec) return Sec->getOffset(0) + getOutputSectionVA(Sec, Loc); return 0; } uint64_t ExprValue::getSectionOffset() const { // If the alignment is trivial, we don't have to compute the full // value to know the offset. This allows this function to succeed in // cases where the output section is not yet known. if (Alignment == 1) return Val; return getValue() - getSecAddr(); } OutputSection *LinkerScript::createOutputSection(StringRef Name, StringRef Location) { OutputSection *&SecRef = NameToOutputSection[Name]; OutputSection *Sec; if (SecRef && SecRef->Location.empty()) { // There was a forward reference. Sec = SecRef; } else { Sec = make(Name, SHT_NOBITS, 0); if (!SecRef) SecRef = Sec; } Sec->Location = Location; return Sec; } OutputSection *LinkerScript::getOrCreateOutputSection(StringRef Name) { OutputSection *&CmdRef = NameToOutputSection[Name]; if (!CmdRef) CmdRef = make(Name, SHT_PROGBITS, 0); return CmdRef; } void LinkerScript::setDot(Expr E, const Twine &Loc, bool InSec) { uint64_t Val = E().getValue(); if (Val < Dot && InSec) error(Loc + ": unable to move location counter backward for: " + Ctx->OutSec->Name); Dot = Val; // Update to location counter means update to section size. if (InSec) Ctx->OutSec->Size = Dot - Ctx->OutSec->Addr; } // This function is called from processSectionCommands, // while we are fixing the output section layout. void LinkerScript::addSymbol(SymbolAssignment *Cmd) { if (Cmd->Name == ".") return; // If a symbol was in PROVIDE(), we need to define it only when // it is a referenced undefined symbol. Symbol *B = Symtab->find(Cmd->Name); if (Cmd->Provide && (!B || B->isDefined())) return; // Define a symbol. Symbol *Sym; uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT; std::tie(Sym, std::ignore) = Symtab->insert(Cmd->Name, /*Type*/ 0, Visibility, /*CanOmitFromDynSym*/ false, /*File*/ nullptr); ExprValue Value = Cmd->Expression(); SectionBase *Sec = Value.isAbsolute() ? nullptr : Value.Sec; // When this function is called, section addresses have not been // fixed yet. So, we may or may not know the value of the RHS // expression. // // For example, if an expression is `x = 42`, we know x is always 42. // However, if an expression is `x = .`, there's no way to know its // value at the moment. // // We want to set symbol values early if we can. This allows us to // use symbols as variables in linker scripts. Doing so allows us to // write expressions like this: `alignment = 16; . = ALIGN(., alignment)`. uint64_t SymValue = Value.Sec ? 0 : Value.getValue(); replaceSymbol(Sym, nullptr, Cmd->Name, STB_GLOBAL, Visibility, STT_NOTYPE, SymValue, 0, Sec); Cmd->Sym = cast(Sym); } // This function is called from assignAddresses, while we are // fixing the output section addresses. This function is supposed // to set the final value for a given symbol assignment. void LinkerScript::assignSymbol(SymbolAssignment *Cmd, bool InSec) { if (Cmd->Name == ".") { setDot(Cmd->Expression, Cmd->Location, InSec); return; } if (!Cmd->Sym) return; ExprValue V = Cmd->Expression(); if (V.isAbsolute()) { Cmd->Sym->Section = nullptr; Cmd->Sym->Value = V.getValue(); } else { Cmd->Sym->Section = V.Sec; Cmd->Sym->Value = V.getSectionOffset(); } } static std::string getFilename(InputFile *File) { if (!File) return ""; if (File->ArchiveName.empty()) return File->getName(); return (File->ArchiveName + "(" + File->getName() + ")").str(); } bool LinkerScript::shouldKeep(InputSectionBase *S) { if (KeptSections.empty()) return false; std::string Filename = getFilename(S->File); for (InputSectionDescription *ID : KeptSections) if (ID->FilePat.match(Filename)) for (SectionPattern &P : ID->SectionPatterns) if (P.SectionPat.match(S->Name)) return true; return false; } // A helper function for the SORT() command. static std::function getComparator(SortSectionPolicy K) { switch (K) { case SortSectionPolicy::Alignment: return [](InputSectionBase *A, InputSectionBase *B) { // ">" is not a mistake. Sections with larger alignments are placed // before sections with smaller alignments in order to reduce the // amount of padding necessary. This is compatible with GNU. return A->Alignment > B->Alignment; }; case SortSectionPolicy::Name: return [](InputSectionBase *A, InputSectionBase *B) { return A->Name < B->Name; }; case SortSectionPolicy::Priority: return [](InputSectionBase *A, InputSectionBase *B) { return getPriority(A->Name) < getPriority(B->Name); }; default: llvm_unreachable("unknown sort policy"); } } // A helper function for the SORT() command. static bool matchConstraints(ArrayRef Sections, ConstraintKind Kind) { if (Kind == ConstraintKind::NoConstraint) return true; bool IsRW = llvm::any_of( Sections, [](InputSection *Sec) { return Sec->Flags & SHF_WRITE; }); return (IsRW && Kind == ConstraintKind::ReadWrite) || (!IsRW && Kind == ConstraintKind::ReadOnly); } static void sortSections(MutableArrayRef Vec, SortSectionPolicy K) { if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None) std::stable_sort(Vec.begin(), Vec.end(), getComparator(K)); } // Sort sections as instructed by SORT-family commands and --sort-section // option. Because SORT-family commands can be nested at most two depth // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command // line option is respected even if a SORT command is given, the exact // behavior we have here is a bit complicated. Here are the rules. // // 1. If two SORT commands are given, --sort-section is ignored. // 2. If one SORT command is given, and if it is not SORT_NONE, // --sort-section is handled as an inner SORT command. // 3. If one SORT command is given, and if it is SORT_NONE, don't sort. // 4. If no SORT command is given, sort according to --sort-section. // 5. If no SORT commands are given and --sort-section is not specified, // apply sorting provided by --symbol-ordering-file if any exist. static void sortInputSections( MutableArrayRef Vec, const SectionPattern &Pat, const DenseMap &Order) { if (Pat.SortOuter == SortSectionPolicy::None) return; if (Pat.SortOuter == SortSectionPolicy::Default && Config->SortSection == SortSectionPolicy::Default) { // If -symbol-ordering-file was given, sort accordingly. // Usually, Order is empty. if (!Order.empty()) sortByOrder(Vec, [&](InputSectionBase *S) { return Order.lookup(S); }); return; } if (Pat.SortInner == SortSectionPolicy::Default) sortSections(Vec, Config->SortSection); else sortSections(Vec, Pat.SortInner); sortSections(Vec, Pat.SortOuter); } // Compute and remember which sections the InputSectionDescription matches. std::vector LinkerScript::computeInputSections(const InputSectionDescription *Cmd, const DenseMap &Order) { std::vector Ret; // Collects all sections that satisfy constraints of Cmd. for (const SectionPattern &Pat : Cmd->SectionPatterns) { size_t SizeBefore = Ret.size(); for (InputSectionBase *Sec : InputSections) { if (!Sec->Live || Sec->Assigned) continue; // For -emit-relocs we have to ignore entries like // .rela.dyn : { *(.rela.data) } // which are common because they are in the default bfd script. if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA) continue; std::string Filename = getFilename(Sec->File); if (!Cmd->FilePat.match(Filename) || Pat.ExcludedFilePat.match(Filename) || !Pat.SectionPat.match(Sec->Name)) continue; // It is safe to assume that Sec is an InputSection // because mergeable or EH input sections have already been // handled and eliminated. Ret.push_back(cast(Sec)); Sec->Assigned = true; } sortInputSections(MutableArrayRef(Ret).slice(SizeBefore), Pat, Order); } return Ret; } void LinkerScript::discard(ArrayRef V) { for (InputSection *S : V) { if (S == InX::ShStrTab || S == InX::Dynamic || S == InX::DynSymTab || S == InX::DynStrTab) error("discarding " + S->Name + " section is not allowed"); S->Assigned = false; S->Live = false; discard(S->DependentSections); } } std::vector LinkerScript::createInputSectionList( OutputSection &OutCmd, const DenseMap &Order) { std::vector Ret; for (BaseCommand *Base : OutCmd.SectionCommands) { if (auto *Cmd = dyn_cast(Base)) { Cmd->Sections = computeInputSections(Cmd, Order); Ret.insert(Ret.end(), Cmd->Sections.begin(), Cmd->Sections.end()); } } return Ret; } void LinkerScript::processSectionCommands() { // A symbol can be assigned before any section is mentioned in the linker // script. In an DSO, the symbol values are addresses, so the only important // section values are: // * SHN_UNDEF // * SHN_ABS // * Any value meaning a regular section. // To handle that, create a dummy aether section that fills the void before // the linker scripts switches to another section. It has an index of one // which will map to whatever the first actual section is. Aether = make("", 0, SHF_ALLOC); Aether->SectionIndex = 1; // Ctx captures the local AddressState and makes it accessible deliberately. // This is needed as there are some cases where we cannot just // thread the current state through to a lambda function created by the // script parser. auto Deleter = make_unique(); Ctx = Deleter.get(); Ctx->OutSec = Aether; size_t I = 0; DenseMap Order = buildSectionOrder(); // Add input sections to output sections. for (BaseCommand *Base : SectionCommands) { // Handle symbol assignments outside of any output section. if (auto *Cmd = dyn_cast(Base)) { addSymbol(Cmd); continue; } if (auto *Sec = dyn_cast(Base)) { std::vector V = createInputSectionList(*Sec, Order); // The output section name `/DISCARD/' is special. // Any input section assigned to it is discarded. if (Sec->Name == "/DISCARD/") { discard(V); continue; } // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input // sections satisfy a given constraint. If not, a directive is handled // as if it wasn't present from the beginning. // // Because we'll iterate over SectionCommands many more times, the easy // way to "make it as if it wasn't present" is to make it empty. if (!matchConstraints(V, Sec->Constraint)) { for (InputSectionBase *S : V) S->Assigned = false; Sec->SectionCommands.clear(); continue; } // A directive may contain symbol definitions like this: // ".foo : { ...; bar = .; }". Handle them. for (BaseCommand *Base : Sec->SectionCommands) if (auto *OutCmd = dyn_cast(Base)) addSymbol(OutCmd); // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign // is given, input sections are aligned to that value, whether the // given value is larger or smaller than the original section alignment. if (Sec->SubalignExpr) { uint32_t Subalign = Sec->SubalignExpr().getValue(); for (InputSectionBase *S : V) S->Alignment = Subalign; } // Add input sections to an output section. for (InputSection *S : V) Sec->addSection(S); Sec->SectionIndex = I++; if (Sec->Noload) Sec->Type = SHT_NOBITS; } } Ctx = nullptr; } static OutputSection *findByName(ArrayRef Vec, StringRef Name) { for (BaseCommand *Base : Vec) if (auto *Sec = dyn_cast(Base)) if (Sec->Name == Name) return Sec; return nullptr; } static OutputSection *createSection(InputSectionBase *IS, StringRef OutsecName) { OutputSection *Sec = Script->createOutputSection(OutsecName, ""); Sec->addSection(cast(IS)); return Sec; } static OutputSection *addInputSec(StringMap &Map, InputSectionBase *IS, StringRef OutsecName) { // Sections with SHT_GROUP or SHF_GROUP attributes reach here only when the -r // option is given. A section with SHT_GROUP defines a "section group", and // its members have SHF_GROUP attribute. Usually these flags have already been // stripped by InputFiles.cpp as section groups are processed and uniquified. // However, for the -r option, we want to pass through all section groups // as-is because adding/removing members or merging them with other groups // change their semantics. if (IS->Type == SHT_GROUP || (IS->Flags & SHF_GROUP)) return createSection(IS, OutsecName); // Imagine .zed : { *(.foo) *(.bar) } script. Both foo and bar may have // relocation sections .rela.foo and .rela.bar for example. Most tools do // not allow multiple REL[A] sections for output section. Hence we // should combine these relocation sections into single output. // We skip synthetic sections because it can be .rela.dyn/.rela.plt or any // other REL[A] sections created by linker itself. if (!isa(IS) && (IS->Type == SHT_REL || IS->Type == SHT_RELA)) { auto *Sec = cast(IS); OutputSection *Out = Sec->getRelocatedSection()->getOutputSection(); if (Out->RelocationSection) { Out->RelocationSection->addSection(Sec); return nullptr; } Out->RelocationSection = createSection(IS, OutsecName); return Out->RelocationSection; } // When control reaches here, mergeable sections have already been merged into // synthetic sections. For relocatable case we want to create one output // section per syntetic section so that they have a valid sh_entsize. if (Config->Relocatable && (IS->Flags & SHF_MERGE)) return createSection(IS, OutsecName); // The ELF spec just says // ---------------------------------------------------------------- // In the first phase, input sections that match in name, type and // attribute flags should be concatenated into single sections. // ---------------------------------------------------------------- // // However, it is clear that at least some flags have to be ignored for // section merging. At the very least SHF_GROUP and SHF_COMPRESSED have to be // ignored. We should not have two output .text sections just because one was // in a group and another was not for example. // // It also seems that that wording was a late addition and didn't get the // necessary scrutiny. // // Merging sections with different flags is expected by some users. One // reason is that if one file has // // int *const bar __attribute__((section(".foo"))) = (int *)0; // // gcc with -fPIC will produce a read only .foo section. But if another // file has // // int zed; // int *const bar __attribute__((section(".foo"))) = (int *)&zed; // // gcc with -fPIC will produce a read write section. // // Last but not least, when using linker script the merge rules are forced by // the script. Unfortunately, linker scripts are name based. This means that // expressions like *(.foo*) can refer to multiple input sections with // different flags. We cannot put them in different output sections or we // would produce wrong results for // // start = .; *(.foo.*) end = .; *(.bar) // // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to // another. The problem is that there is no way to layout those output // sections such that the .foo sections are the only thing between the start // and end symbols. // // Given the above issues, we instead merge sections by name and error on // incompatible types and flags. OutputSection *&Sec = Map[OutsecName]; if (Sec) { Sec->addSection(cast(IS)); return nullptr; } Sec = createSection(IS, OutsecName); return Sec; } // Add sections that didn't match any sections command. void LinkerScript::addOrphanSections() { unsigned End = SectionCommands.size(); StringMap Map; std::vector V; for (InputSectionBase *S : InputSections) { if (!S->Live || S->Parent) continue; StringRef Name = getOutputSectionName(S); if (Config->OrphanHandling == OrphanHandlingPolicy::Error) error(toString(S) + " is being placed in '" + Name + "'"); else if (Config->OrphanHandling == OrphanHandlingPolicy::Warn) warn(toString(S) + " is being placed in '" + Name + "'"); if (OutputSection *Sec = findByName(makeArrayRef(SectionCommands).slice(0, End), Name)) { Sec->addSection(cast(S)); continue; } if (OutputSection *OS = addInputSec(Map, S, Name)) V.push_back(OS); assert(S->getOutputSection()->SectionIndex == INT_MAX); } // If no SECTIONS command was given, we should insert sections commands // before others, so that we can handle scripts which refers them, // for example: "foo = ABSOLUTE(ADDR(.text)));". // When SECTIONS command is present we just add all orphans to the end. if (HasSectionsCommand) SectionCommands.insert(SectionCommands.end(), V.begin(), V.end()); else SectionCommands.insert(SectionCommands.begin(), V.begin(), V.end()); } uint64_t LinkerScript::advance(uint64_t Size, unsigned Alignment) { bool IsTbss = (Ctx->OutSec->Flags & SHF_TLS) && Ctx->OutSec->Type == SHT_NOBITS; uint64_t Start = IsTbss ? Dot + Ctx->ThreadBssOffset : Dot; Start = alignTo(Start, Alignment); uint64_t End = Start + Size; if (IsTbss) Ctx->ThreadBssOffset = End - Dot; else Dot = End; return End; } void LinkerScript::output(InputSection *S) { uint64_t Before = advance(0, 1); uint64_t Pos = advance(S->getSize(), S->Alignment); S->OutSecOff = Pos - S->getSize() - Ctx->OutSec->Addr; // Update output section size after adding each section. This is so that // SIZEOF works correctly in the case below: // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) } Ctx->OutSec->Size = Pos - Ctx->OutSec->Addr; // If there is a memory region associated with this input section, then // place the section in that region and update the region index. if (Ctx->MemRegion) { uint64_t &CurOffset = Ctx->MemRegionOffset[Ctx->MemRegion]; CurOffset += Pos - Before; uint64_t CurSize = CurOffset - Ctx->MemRegion->Origin; if (CurSize > Ctx->MemRegion->Length) { uint64_t OverflowAmt = CurSize - Ctx->MemRegion->Length; error("section '" + Ctx->OutSec->Name + "' will not fit in region '" + Ctx->MemRegion->Name + "': overflowed by " + Twine(OverflowAmt) + " bytes"); } } } void LinkerScript::switchTo(OutputSection *Sec) { if (Ctx->OutSec == Sec) return; Ctx->OutSec = Sec; Ctx->OutSec->Addr = advance(0, Ctx->OutSec->Alignment); - - // If neither AT nor AT> is specified for an allocatable section, the linker - // will set the LMA such that the difference between VMA and LMA for the - // section is the same as the preceding output section in the same region - // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html - if (Ctx->LMAOffset) - Ctx->OutSec->LMAOffset = Ctx->LMAOffset(); } // This function searches for a memory region to place the given output // section in. If found, a pointer to the appropriate memory region is // returned. Otherwise, a nullptr is returned. MemoryRegion *LinkerScript::findMemoryRegion(OutputSection *Sec) { // If a memory region name was specified in the output section command, // then try to find that region first. if (!Sec->MemoryRegionName.empty()) { auto It = MemoryRegions.find(Sec->MemoryRegionName); if (It != MemoryRegions.end()) return It->second; error("memory region '" + Sec->MemoryRegionName + "' not declared"); return nullptr; } // If at least one memory region is defined, all sections must // belong to some memory region. Otherwise, we don't need to do // anything for memory regions. if (MemoryRegions.empty()) return nullptr; // See if a region can be found by matching section flags. for (auto &Pair : MemoryRegions) { MemoryRegion *M = Pair.second; if ((M->Flags & Sec->Flags) && (M->NegFlags & Sec->Flags) == 0) return M; } // Otherwise, no suitable region was found. if (Sec->Flags & SHF_ALLOC) error("no memory region specified for section '" + Sec->Name + "'"); return nullptr; } // This function assigns offsets to input sections and an output section // for a single sections command (e.g. ".text { *(.text); }"). void LinkerScript::assignOffsets(OutputSection *Sec) { if (!(Sec->Flags & SHF_ALLOC)) Dot = 0; else if (Sec->AddrExpr) setDot(Sec->AddrExpr, Sec->Location, false); Ctx->MemRegion = Sec->MemRegion; if (Ctx->MemRegion) Dot = Ctx->MemRegionOffset[Ctx->MemRegion]; + switchTo(Sec); + if (Sec->LMAExpr) { uint64_t D = Dot; Ctx->LMAOffset = [=] { return Sec->LMAExpr().getValue() - D; }; } - switchTo(Sec); + if (!Sec->LMARegionName.empty()) { + if (MemoryRegion *MR = MemoryRegions.lookup(Sec->LMARegionName)) { + uint64_t Offset = MR->Origin - Dot; + Ctx->LMAOffset = [=] { return Offset; }; + } else { + error("memory region '" + Sec->LMARegionName + "' not declared"); + } + } - // We do not support custom layout for compressed debug sectons. - // At this point we already know their size and have compressed content. - if (Ctx->OutSec->Flags & SHF_COMPRESSED) - return; + // If neither AT nor AT> is specified for an allocatable section, the linker + // will set the LMA such that the difference between VMA and LMA for the + // section is the same as the preceding output section in the same region + // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html + if (Ctx->LMAOffset) + Ctx->OutSec->LMAOffset = Ctx->LMAOffset(); // The Size previously denoted how many InputSections had been added to this // section, and was used for sorting SHF_LINK_ORDER sections. Reset it to // compute the actual size value. Sec->Size = 0; // We visited SectionsCommands from processSectionCommands to // layout sections. Now, we visit SectionsCommands again to fix // section offsets. for (BaseCommand *Base : Sec->SectionCommands) { // This handles the assignments to symbol or to the dot. if (auto *Cmd = dyn_cast(Base)) { assignSymbol(Cmd, true); continue; } // Handle BYTE(), SHORT(), LONG(), or QUAD(). if (auto *Cmd = dyn_cast(Base)) { Cmd->Offset = Dot - Ctx->OutSec->Addr; Dot += Cmd->Size; if (Ctx->MemRegion) Ctx->MemRegionOffset[Ctx->MemRegion] += Cmd->Size; Ctx->OutSec->Size = Dot - Ctx->OutSec->Addr; continue; } // Handle ASSERT(). if (auto *Cmd = dyn_cast(Base)) { Cmd->Expression(); continue; } // Handle a single input section description command. // It calculates and assigns the offsets for each section and also // updates the output section size. auto *Cmd = cast(Base); for (InputSection *Sec : Cmd->Sections) { // We tentatively added all synthetic sections at the beginning and // removed empty ones afterwards (because there is no way to know // whether they were going be empty or not other than actually running // linker scripts.) We need to ignore remains of empty sections. if (auto *S = dyn_cast(Sec)) if (S->empty()) continue; if (!Sec->Live) continue; assert(Ctx->OutSec == Sec->getParent()); output(Sec); } } } void LinkerScript::removeEmptyCommands() { // It is common practice to use very generic linker scripts. So for any // given run some of the output sections in the script will be empty. // We could create corresponding empty output sections, but that would // clutter the output. // We instead remove trivially empty sections. The bfd linker seems even // more aggressive at removing them. llvm::erase_if(SectionCommands, [&](BaseCommand *Base) { if (auto *Sec = dyn_cast(Base)) return !Sec->Live; return false; }); } static bool isAllSectionDescription(const OutputSection &Cmd) { for (BaseCommand *Base : Cmd.SectionCommands) if (!isa(*Base)) return false; return true; } void LinkerScript::adjustSectionsBeforeSorting() { // If the output section contains only symbol assignments, create a // corresponding output section. The issue is what to do with linker script // like ".foo : { symbol = 42; }". One option would be to convert it to // "symbol = 42;". That is, move the symbol out of the empty section // description. That seems to be what bfd does for this simple case. The // problem is that this is not completely general. bfd will give up and // create a dummy section too if there is a ". = . + 1" inside the section // for example. // Given that we want to create the section, we have to worry what impact // it will have on the link. For example, if we just create a section with // 0 for flags, it would change which PT_LOADs are created. // We could remember that that particular section is dummy and ignore it in // other parts of the linker, but unfortunately there are quite a few places // that would need to change: // * The program header creation. // * The orphan section placement. // * The address assignment. // The other option is to pick flags that minimize the impact the section // will have on the rest of the linker. That is why we copy the flags from // the previous sections. Only a few flags are needed to keep the impact low. uint64_t Flags = SHF_ALLOC; for (BaseCommand *Cmd : SectionCommands) { auto *Sec = dyn_cast(Cmd); if (!Sec) continue; if (Sec->Live) { Flags = Sec->Flags & (SHF_ALLOC | SHF_WRITE | SHF_EXECINSTR); continue; } if (isAllSectionDescription(*Sec)) continue; Sec->Live = true; Sec->Flags = Flags; } } void LinkerScript::adjustSectionsAfterSorting() { // Try and find an appropriate memory region to assign offsets in. for (BaseCommand *Base : SectionCommands) { if (auto *Sec = dyn_cast(Base)) { if (!Sec->Live) continue; Sec->MemRegion = findMemoryRegion(Sec); // Handle align (e.g. ".foo : ALIGN(16) { ... }"). if (Sec->AlignExpr) Sec->Alignment = std::max(Sec->Alignment, Sec->AlignExpr().getValue()); } } // If output section command doesn't specify any segments, // and we haven't previously assigned any section to segment, // then we simply assign section to the very first load segment. // Below is an example of such linker script: // PHDRS { seg PT_LOAD; } // SECTIONS { .aaa : { *(.aaa) } } std::vector DefPhdrs; auto FirstPtLoad = std::find_if(PhdrsCommands.begin(), PhdrsCommands.end(), [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; }); if (FirstPtLoad != PhdrsCommands.end()) DefPhdrs.push_back(FirstPtLoad->Name); // Walk the commands and propagate the program headers to commands that don't // explicitly specify them. for (BaseCommand *Base : SectionCommands) { auto *Sec = dyn_cast(Base); if (!Sec) continue; if (Sec->Phdrs.empty()) { // To match the bfd linker script behaviour, only propagate program // headers to sections that are allocated. if (Sec->Flags & SHF_ALLOC) Sec->Phdrs = DefPhdrs; } else { DefPhdrs = Sec->Phdrs; } } } static OutputSection *findFirstSection(PhdrEntry *Load) { for (OutputSection *Sec : OutputSections) if (Sec->PtLoad == Load) return Sec; return nullptr; } // Try to find an address for the file and program headers output sections, // which were unconditionally added to the first PT_LOAD segment earlier. // // When using the default layout, we check if the headers fit below the first // allocated section. When using a linker script, we also check if the headers // are covered by the output section. This allows omitting the headers by not // leaving enough space for them in the linker script; this pattern is common // in embedded systems. // // If there isn't enough space for these sections, we'll remove them from the // PT_LOAD segment, and we'll also remove the PT_PHDR segment. void LinkerScript::allocateHeaders(std::vector &Phdrs) { uint64_t Min = std::numeric_limits::max(); for (OutputSection *Sec : OutputSections) if (Sec->Flags & SHF_ALLOC) Min = std::min(Min, Sec->Addr); auto It = llvm::find_if( Phdrs, [](const PhdrEntry *E) { return E->p_type == PT_LOAD; }); if (It == Phdrs.end()) return; PhdrEntry *FirstPTLoad = *It; uint64_t HeaderSize = getHeaderSize(); // When linker script with SECTIONS is being used, don't output headers // unless there's a space for them. uint64_t Base = HasSectionsCommand ? alignDown(Min, Config->MaxPageSize) : 0; if (HeaderSize <= Min - Base || Script->hasPhdrsCommands()) { Min = alignDown(Min - HeaderSize, Config->MaxPageSize); Out::ElfHeader->Addr = Min; Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size; return; } Out::ElfHeader->PtLoad = nullptr; Out::ProgramHeaders->PtLoad = nullptr; FirstPTLoad->FirstSec = findFirstSection(FirstPTLoad); llvm::erase_if(Phdrs, [](const PhdrEntry *E) { return E->p_type == PT_PHDR; }); } LinkerScript::AddressState::AddressState() { for (auto &MRI : Script->MemoryRegions) { const MemoryRegion *MR = MRI.second; MemRegionOffset[MR] = MR->Origin; } } static uint64_t getInitialDot() { // By default linker scripts use an initial value of 0 for '.', // but prefer -image-base if set. if (Script->HasSectionsCommand) return Config->ImageBase ? *Config->ImageBase : 0; uint64_t StartAddr = UINT64_MAX; // The Sections with -T
have been sorted in order of ascending // address. We must lower StartAddr if the lowest -T
as // calls to setDot() must be monotonically increasing. for (auto &KV : Config->SectionStartMap) StartAddr = std::min(StartAddr, KV.second); return std::min(StartAddr, Target->getImageBase() + elf::getHeaderSize()); } // Here we assign addresses as instructed by linker script SECTIONS // sub-commands. Doing that allows us to use final VA values, so here // we also handle rest commands like symbol assignments and ASSERTs. void LinkerScript::assignAddresses() { Dot = getInitialDot(); auto Deleter = make_unique(); Ctx = Deleter.get(); ErrorOnMissingSection = true; switchTo(Aether); for (BaseCommand *Base : SectionCommands) { if (auto *Cmd = dyn_cast(Base)) { assignSymbol(Cmd, false); continue; } if (auto *Cmd = dyn_cast(Base)) { Cmd->Expression(); continue; } assignOffsets(cast(Base)); } Ctx = nullptr; } // Creates program headers as instructed by PHDRS linker script command. std::vector LinkerScript::createPhdrs() { std::vector Ret; // Process PHDRS and FILEHDR keywords because they are not // real output sections and cannot be added in the following loop. for (const PhdrsCommand &Cmd : PhdrsCommands) { PhdrEntry *Phdr = make(Cmd.Type, Cmd.Flags ? *Cmd.Flags : PF_R); if (Cmd.HasFilehdr) Phdr->add(Out::ElfHeader); if (Cmd.HasPhdrs) Phdr->add(Out::ProgramHeaders); if (Cmd.LMAExpr) { Phdr->p_paddr = Cmd.LMAExpr().getValue(); Phdr->HasLMA = true; } Ret.push_back(Phdr); } // Add output sections to program headers. for (OutputSection *Sec : OutputSections) { // Assign headers specified by linker script for (size_t Id : getPhdrIndices(Sec)) { Ret[Id]->add(Sec); if (!PhdrsCommands[Id].Flags.hasValue()) Ret[Id]->p_flags |= Sec->getPhdrFlags(); } } return Ret; } // Returns true if we should emit an .interp section. // // We usually do. But if PHDRS commands are given, and // no PT_INTERP is there, there's no place to emit an // .interp, so we don't do that in that case. bool LinkerScript::needsInterpSection() { if (PhdrsCommands.empty()) return true; for (PhdrsCommand &Cmd : PhdrsCommands) if (Cmd.Type == PT_INTERP) return true; return false; } ExprValue LinkerScript::getSymbolValue(StringRef Name, const Twine &Loc) { if (Name == ".") { if (Ctx) return {Ctx->OutSec, false, Dot - Ctx->OutSec->Addr, Loc}; error(Loc + ": unable to get location counter value"); return 0; } if (Symbol *Sym = Symtab->find(Name)) { if (auto *DS = dyn_cast(Sym)) return {DS->Section, false, DS->Value, Loc}; if (auto *SS = dyn_cast(Sym)) if (!ErrorOnMissingSection || SS->CopyRelSec) return {SS->CopyRelSec, false, 0, Loc}; } error(Loc + ": symbol not found: " + Name); return 0; } // Returns the index of the segment named Name. static Optional getPhdrIndex(ArrayRef Vec, StringRef Name) { for (size_t I = 0; I < Vec.size(); ++I) if (Vec[I].Name == Name) return I; return None; } // Returns indices of ELF headers containing specific section. Each index is a // zero based number of ELF header listed within PHDRS {} script block. std::vector LinkerScript::getPhdrIndices(OutputSection *Cmd) { std::vector Ret; for (StringRef S : Cmd->Phdrs) { if (Optional Idx = getPhdrIndex(PhdrsCommands, S)) Ret.push_back(*Idx); else if (S != "NONE") error(Cmd->Location + ": section header '" + S + "' is not listed in PHDRS"); } return Ret; } Index: vendor/lld/dist-release_60/ELF/OutputSections.cpp =================================================================== --- vendor/lld/dist-release_60/ELF/OutputSections.cpp (revision 328369) +++ vendor/lld/dist-release_60/ELF/OutputSections.cpp (revision 328370) @@ -1,443 +1,434 @@ //===- OutputSections.cpp -------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "OutputSections.h" #include "Config.h" #include "LinkerScript.h" #include "Strings.h" #include "SymbolTable.h" #include "SyntheticSections.h" #include "Target.h" #include "lld/Common/Memory.h" #include "lld/Common/Threads.h" #include "llvm/BinaryFormat/Dwarf.h" #include "llvm/Support/Compression.h" #include "llvm/Support/MD5.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/SHA1.h" using namespace llvm; using namespace llvm::dwarf; using namespace llvm::object; using namespace llvm::support::endian; using namespace llvm::ELF; using namespace lld; using namespace lld::elf; uint8_t Out::First; OutputSection *Out::Opd; uint8_t *Out::OpdBuf; PhdrEntry *Out::TlsPhdr; OutputSection *Out::DebugInfo; OutputSection *Out::ElfHeader; OutputSection *Out::ProgramHeaders; OutputSection *Out::PreinitArray; OutputSection *Out::InitArray; OutputSection *Out::FiniArray; std::vector elf::OutputSections; uint32_t OutputSection::getPhdrFlags() const { uint32_t Ret = PF_R; if (Flags & SHF_WRITE) Ret |= PF_W; if (Flags & SHF_EXECINSTR) Ret |= PF_X; return Ret; } template void OutputSection::writeHeaderTo(typename ELFT::Shdr *Shdr) { Shdr->sh_entsize = Entsize; Shdr->sh_addralign = Alignment; Shdr->sh_type = Type; Shdr->sh_offset = Offset; Shdr->sh_flags = Flags; Shdr->sh_info = Info; Shdr->sh_link = Link; Shdr->sh_addr = Addr; Shdr->sh_size = Size; Shdr->sh_name = ShName; } OutputSection::OutputSection(StringRef Name, uint32_t Type, uint64_t Flags) : BaseCommand(OutputSectionKind), SectionBase(Output, Name, Flags, /*Entsize*/ 0, /*Alignment*/ 1, Type, /*Info*/ 0, /*Link*/ 0), SectionIndex(INT_MAX) { Live = false; } // We allow sections of types listed below to merged into a // single progbits section. This is typically done by linker // scripts. Merging nobits and progbits will force disk space // to be allocated for nobits sections. Other ones don't require // any special treatment on top of progbits, so there doesn't // seem to be a harm in merging them. static bool canMergeToProgbits(unsigned Type) { return Type == SHT_NOBITS || Type == SHT_PROGBITS || Type == SHT_INIT_ARRAY || Type == SHT_PREINIT_ARRAY || Type == SHT_FINI_ARRAY || Type == SHT_NOTE; } void OutputSection::addSection(InputSection *IS) { if (!Live) { // If IS is the first section to be added to this section, // initialize Type and Entsize from IS. Live = true; Type = IS->Type; Entsize = IS->Entsize; } else { // Otherwise, check if new type or flags are compatible with existing ones. if ((Flags & (SHF_ALLOC | SHF_TLS)) != (IS->Flags & (SHF_ALLOC | SHF_TLS))) error("incompatible section flags for " + Name + "\n>>> " + toString(IS) + ": 0x" + utohexstr(IS->Flags) + "\n>>> output section " + Name + ": 0x" + utohexstr(Flags)); if (Type != IS->Type) { if (!canMergeToProgbits(Type) || !canMergeToProgbits(IS->Type)) error("section type mismatch for " + IS->Name + "\n>>> " + toString(IS) + ": " + getELFSectionTypeName(Config->EMachine, IS->Type) + "\n>>> output section " + Name + ": " + getELFSectionTypeName(Config->EMachine, Type)); Type = SHT_PROGBITS; } } IS->Parent = this; Flags |= IS->Flags; Alignment = std::max(Alignment, IS->Alignment); IS->OutSecOff = Size++; // If this section contains a table of fixed-size entries, sh_entsize // holds the element size. If it contains elements of different size we // set sh_entsize to 0. if (Entsize != IS->Entsize) Entsize = 0; if (!IS->Assigned) { IS->Assigned = true; if (SectionCommands.empty() || !isa(SectionCommands.back())) SectionCommands.push_back(make("")); auto *ISD = cast(SectionCommands.back()); ISD->Sections.push_back(IS); } } void elf::sortByOrder(MutableArrayRef In, std::function Order) { typedef std::pair Pair; auto Comp = [](const Pair &A, const Pair &B) { return A.first < B.first; }; std::vector V; for (InputSection *S : In) V.push_back({Order(S), S}); std::stable_sort(V.begin(), V.end(), Comp); for (size_t I = 0; I < V.size(); ++I) In[I] = V[I].second; } uint64_t elf::getHeaderSize() { if (Config->OFormatBinary) return 0; return Out::ElfHeader->Size + Out::ProgramHeaders->Size; } bool OutputSection::classof(const BaseCommand *C) { return C->Kind == OutputSectionKind; } void OutputSection::sort(std::function Order) { assert(Live); assert(SectionCommands.size() == 1); sortByOrder(cast(SectionCommands[0])->Sections, Order); } // Fill [Buf, Buf + Size) with Filler. // This is used for linker script "=fillexp" command. static void fill(uint8_t *Buf, size_t Size, uint32_t Filler) { size_t I = 0; for (; I + 4 < Size; I += 4) memcpy(Buf + I, &Filler, 4); memcpy(Buf + I, &Filler, Size - I); } // Compress section contents if this section contains debug info. template void OutputSection::maybeCompress() { typedef typename ELFT::Chdr Elf_Chdr; // Compress only DWARF debug sections. if (!Config->CompressDebugSections || (Flags & SHF_ALLOC) || !Name.startswith(".debug_")) return; - // Calculate the section offsets and size pre-compression. - Size = 0; - for (BaseCommand *Cmd : SectionCommands) - if (auto *ISD = dyn_cast(Cmd)) - for (InputSection *IS : ISD->Sections) { - IS->OutSecOff = alignTo(Size, IS->Alignment); - this->Size = IS->OutSecOff + IS->getSize(); - } - // Create a section header. ZDebugHeader.resize(sizeof(Elf_Chdr)); auto *Hdr = reinterpret_cast(ZDebugHeader.data()); Hdr->ch_type = ELFCOMPRESS_ZLIB; Hdr->ch_size = Size; Hdr->ch_addralign = Alignment; // Write section contents to a temporary buffer and compress it. std::vector Buf(Size); writeTo(Buf.data()); if (Error E = zlib::compress(toStringRef(Buf), CompressedData)) fatal("compress failed: " + llvm::toString(std::move(E))); // Update section headers. Size = sizeof(Elf_Chdr) + CompressedData.size(); Flags |= SHF_COMPRESSED; } static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) { if (Size == 1) *Buf = Data; else if (Size == 2) write16(Buf, Data, Config->Endianness); else if (Size == 4) write32(Buf, Data, Config->Endianness); else if (Size == 8) write64(Buf, Data, Config->Endianness); else llvm_unreachable("unsupported Size argument"); } template void OutputSection::writeTo(uint8_t *Buf) { if (Type == SHT_NOBITS) return; Loc = Buf; // If -compress-debug-section is specified and if this is a debug seciton, // we've already compressed section contents. If that's the case, // just write it down. if (!CompressedData.empty()) { memcpy(Buf, ZDebugHeader.data(), ZDebugHeader.size()); memcpy(Buf + ZDebugHeader.size(), CompressedData.data(), CompressedData.size()); return; } // Write leading padding. std::vector Sections; for (BaseCommand *Cmd : SectionCommands) if (auto *ISD = dyn_cast(Cmd)) for (InputSection *IS : ISD->Sections) if (IS->Live) Sections.push_back(IS); uint32_t Filler = getFiller(); if (Filler) fill(Buf, Sections.empty() ? Size : Sections[0]->OutSecOff, Filler); parallelForEachN(0, Sections.size(), [&](size_t I) { InputSection *IS = Sections[I]; IS->writeTo(Buf); // Fill gaps between sections. if (Filler) { uint8_t *Start = Buf + IS->OutSecOff + IS->getSize(); uint8_t *End; if (I + 1 == Sections.size()) End = Buf + Size; else End = Buf + Sections[I + 1]->OutSecOff; fill(Start, End - Start, Filler); } }); // Linker scripts may have BYTE()-family commands with which you // can write arbitrary bytes to the output. Process them if any. for (BaseCommand *Base : SectionCommands) if (auto *Data = dyn_cast(Base)) writeInt(Buf + Data->Offset, Data->Expression().getValue(), Data->Size); } template static void finalizeShtGroup(OutputSection *OS, InputSection *Section) { assert(Config->Relocatable); // sh_link field for SHT_GROUP sections should contain the section index of // the symbol table. OS->Link = InX::SymTab->getParent()->SectionIndex; // sh_info then contain index of an entry in symbol table section which // provides signature of the section group. ObjFile *Obj = Section->getFile(); ArrayRef Symbols = Obj->getSymbols(); OS->Info = InX::SymTab->getSymbolIndex(Symbols[Section->Info]); } template void OutputSection::finalize() { InputSection *First = nullptr; for (BaseCommand *Base : SectionCommands) { if (auto *ISD = dyn_cast(Base)) { if (ISD->Sections.empty()) continue; if (First == nullptr) First = ISD->Sections.front(); } if (isa(Base) && Type == SHT_NOBITS) Type = SHT_PROGBITS; } if (Flags & SHF_LINK_ORDER) { // We must preserve the link order dependency of sections with the // SHF_LINK_ORDER flag. The dependency is indicated by the sh_link field. We // need to translate the InputSection sh_link to the OutputSection sh_link, // all InputSections in the OutputSection have the same dependency. if (auto *D = First->getLinkOrderDep()) Link = D->getParent()->SectionIndex; } if (Type == SHT_GROUP) { finalizeShtGroup(this, First); return; } if (!Config->CopyRelocs || (Type != SHT_RELA && Type != SHT_REL)) return; if (isa(First)) return; Link = InX::SymTab->getParent()->SectionIndex; // sh_info for SHT_REL[A] sections should contain the section header index of // the section to which the relocation applies. InputSectionBase *S = First->getRelocatedSection(); Info = S->getOutputSection()->SectionIndex; Flags |= SHF_INFO_LINK; } // Returns true if S matches /Filename.?\.o$/. static bool isCrtBeginEnd(StringRef S, StringRef Filename) { if (!S.endswith(".o")) return false; S = S.drop_back(2); if (S.endswith(Filename)) return true; return !S.empty() && S.drop_back().endswith(Filename); } static bool isCrtbegin(StringRef S) { return isCrtBeginEnd(S, "crtbegin"); } static bool isCrtend(StringRef S) { return isCrtBeginEnd(S, "crtend"); } // .ctors and .dtors are sorted by this priority from highest to lowest. // // 1. The section was contained in crtbegin (crtbegin contains // some sentinel value in its .ctors and .dtors so that the runtime // can find the beginning of the sections.) // // 2. The section has an optional priority value in the form of ".ctors.N" // or ".dtors.N" where N is a number. Unlike .{init,fini}_array, // they are compared as string rather than number. // // 3. The section is just ".ctors" or ".dtors". // // 4. The section was contained in crtend, which contains an end marker. // // In an ideal world, we don't need this function because .init_array and // .ctors are duplicate features (and .init_array is newer.) However, there // are too many real-world use cases of .ctors, so we had no choice to // support that with this rather ad-hoc semantics. static bool compCtors(const InputSection *A, const InputSection *B) { bool BeginA = isCrtbegin(A->File->getName()); bool BeginB = isCrtbegin(B->File->getName()); if (BeginA != BeginB) return BeginA; bool EndA = isCrtend(A->File->getName()); bool EndB = isCrtend(B->File->getName()); if (EndA != EndB) return EndB; StringRef X = A->Name; StringRef Y = B->Name; assert(X.startswith(".ctors") || X.startswith(".dtors")); assert(Y.startswith(".ctors") || Y.startswith(".dtors")); X = X.substr(6); Y = Y.substr(6); if (X.empty() && Y.empty()) return false; return X < Y; } // Sorts input sections by the special rules for .ctors and .dtors. // Unfortunately, the rules are different from the one for .{init,fini}_array. // Read the comment above. void OutputSection::sortCtorsDtors() { assert(SectionCommands.size() == 1); auto *ISD = cast(SectionCommands[0]); std::stable_sort(ISD->Sections.begin(), ISD->Sections.end(), compCtors); } // If an input string is in the form of "foo.N" where N is a number, // return N. Otherwise, returns 65536, which is one greater than the // lowest priority. int elf::getPriority(StringRef S) { size_t Pos = S.rfind('.'); if (Pos == StringRef::npos) return 65536; int V; if (!to_integer(S.substr(Pos + 1), V, 10)) return 65536; return V; } // Sorts input sections by section name suffixes, so that .foo.N comes // before .foo.M if N < M. Used to sort .{init,fini}_array.N sections. // We want to keep the original order if the priorities are the same // because the compiler keeps the original initialization order in a // translation unit and we need to respect that. // For more detail, read the section of the GCC's manual about init_priority. void OutputSection::sortInitFini() { // Sort sections by priority. sort([](InputSectionBase *S) { return getPriority(S->Name); }); } uint32_t OutputSection::getFiller() { if (Filler) return *Filler; if (Flags & SHF_EXECINSTR) return Target->TrapInstr; return 0; } template void OutputSection::writeHeaderTo(ELF32LE::Shdr *Shdr); template void OutputSection::writeHeaderTo(ELF32BE::Shdr *Shdr); template void OutputSection::writeHeaderTo(ELF64LE::Shdr *Shdr); template void OutputSection::writeHeaderTo(ELF64BE::Shdr *Shdr); template void OutputSection::writeTo(uint8_t *Buf); template void OutputSection::writeTo(uint8_t *Buf); template void OutputSection::writeTo(uint8_t *Buf); template void OutputSection::writeTo(uint8_t *Buf); template void OutputSection::maybeCompress(); template void OutputSection::maybeCompress(); template void OutputSection::maybeCompress(); template void OutputSection::maybeCompress(); template void OutputSection::finalize(); template void OutputSection::finalize(); template void OutputSection::finalize(); template void OutputSection::finalize(); Index: vendor/lld/dist-release_60/ELF/OutputSections.h =================================================================== --- vendor/lld/dist-release_60/ELF/OutputSections.h (revision 328369) +++ vendor/lld/dist-release_60/ELF/OutputSections.h (revision 328370) @@ -1,152 +1,153 @@ //===- OutputSections.h -----------------------------------------*- C++ -*-===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLD_ELF_OUTPUT_SECTIONS_H #define LLD_ELF_OUTPUT_SECTIONS_H #include "Config.h" #include "InputSection.h" #include "LinkerScript.h" #include "Relocations.h" #include "lld/Common/LLVM.h" #include "llvm/MC/StringTableBuilder.h" #include "llvm/Object/ELF.h" namespace lld { namespace elf { struct PhdrEntry; class Symbol; struct EhSectionPiece; class EhInputSection; class InputSection; class InputSectionBase; class MergeInputSection; class OutputSection; template class ObjFile; template class SharedFile; class SharedSymbol; class Defined; // This represents a section in an output file. // It is composed of multiple InputSections. // The writer creates multiple OutputSections and assign them unique, // non-overlapping file offsets and VAs. class OutputSection final : public BaseCommand, public SectionBase { public: OutputSection(StringRef Name, uint32_t Type, uint64_t Flags); static bool classof(const SectionBase *S) { return S->kind() == SectionBase::Output; } static bool classof(const BaseCommand *C); uint64_t getLMA() const { return Addr + LMAOffset; } template void writeHeaderTo(typename ELFT::Shdr *SHdr); unsigned SectionIndex; unsigned SortRank; uint32_t getPhdrFlags() const; // Pointer to the PT_LOAD segment, which this section resides in. This field // is used to correctly compute file offset of a section. When two sections // share the same load segment, difference between their file offsets should // be equal to difference between their virtual addresses. To compute some // section offset we use the following formula: Off = Off_first + VA - // VA_first, where Off_first and VA_first is file offset and VA of first // section in PT_LOAD. PhdrEntry *PtLoad = nullptr; // Pointer to a relocation section for this section. Usually nullptr because // we consume relocations, but if --emit-relocs is specified (which is rare), // it may have a non-null value. OutputSection *RelocationSection = nullptr; // Initially this field is the number of InputSections that have been added to // the OutputSection so far. Later on, after a call to assignAddresses, it // corresponds to the Elf_Shdr member. uint64_t Size = 0; // The following fields correspond to Elf_Shdr members. uint64_t Offset = 0; uint64_t LMAOffset = 0; uint64_t Addr = 0; uint32_t ShName = 0; void addSection(InputSection *IS); // Location in the output buffer. uint8_t *Loc = nullptr; // The following members are normally only used in linker scripts. MemoryRegion *MemRegion = nullptr; Expr AddrExpr; Expr AlignExpr; Expr LMAExpr; Expr SubalignExpr; std::vector SectionCommands; std::vector Phdrs; llvm::Optional Filler; ConstraintKind Constraint = ConstraintKind::NoConstraint; std::string Location; std::string MemoryRegionName; + std::string LMARegionName; bool Noload = false; template void finalize(); template void writeTo(uint8_t *Buf); template void maybeCompress(); void sort(std::function Order); void sortInitFini(); void sortCtorsDtors(); private: // Used for implementation of --compress-debug-sections option. std::vector ZDebugHeader; llvm::SmallVector CompressedData; uint32_t getFiller(); }; int getPriority(StringRef S); // All output sections that are handled by the linker specially are // globally accessible. Writer initializes them, so don't use them // until Writer is initialized. struct Out { static uint8_t First; static OutputSection *Opd; static uint8_t *OpdBuf; static PhdrEntry *TlsPhdr; static OutputSection *DebugInfo; static OutputSection *ElfHeader; static OutputSection *ProgramHeaders; static OutputSection *PreinitArray; static OutputSection *InitArray; static OutputSection *FiniArray; }; } // namespace elf } // namespace lld namespace lld { namespace elf { uint64_t getHeaderSize(); void sortByOrder(llvm::MutableArrayRef In, std::function Order); extern std::vector OutputSections; } // namespace elf } // namespace lld #endif Index: vendor/lld/dist-release_60/ELF/ScriptParser.cpp =================================================================== --- vendor/lld/dist-release_60/ELF/ScriptParser.cpp (revision 328369) +++ vendor/lld/dist-release_60/ELF/ScriptParser.cpp (revision 328370) @@ -1,1334 +1,1345 @@ //===- ScriptParser.cpp ---------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains a recursive-descendent parser for linker scripts. // Parsed results are stored to Config and Script global objects. // //===----------------------------------------------------------------------===// #include "ScriptParser.h" #include "Config.h" #include "Driver.h" #include "InputSection.h" #include "LinkerScript.h" #include "OutputSections.h" #include "ScriptLexer.h" #include "Symbols.h" #include "Target.h" #include "lld/Common/Memory.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/StringSet.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/BinaryFormat/ELF.h" #include "llvm/Support/Casting.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include #include #include using namespace llvm; using namespace llvm::ELF; using namespace llvm::support::endian; using namespace lld; using namespace lld::elf; static bool isUnderSysroot(StringRef Path); namespace { class ScriptParser final : ScriptLexer { public: ScriptParser(MemoryBufferRef MB) : ScriptLexer(MB), IsUnderSysroot(isUnderSysroot(MB.getBufferIdentifier())) {} void readLinkerScript(); void readVersionScript(); void readDynamicList(); void readDefsym(StringRef Name); private: void addFile(StringRef Path); void readAsNeeded(); void readEntry(); void readExtern(); void readGroup(); void readInclude(); void readMemory(); void readOutput(); void readOutputArch(); void readOutputFormat(); void readPhdrs(); void readRegionAlias(); void readSearchDir(); void readSections(); void readVersion(); void readVersionScriptCommand(); SymbolAssignment *readAssignment(StringRef Name); ByteCommand *readByteCommand(StringRef Tok); uint32_t readFill(); uint32_t parseFill(StringRef Tok); void readSectionAddressType(OutputSection *Cmd); OutputSection *readOutputSectionDescription(StringRef OutSec); std::vector readOutputSectionPhdrs(); InputSectionDescription *readInputSectionDescription(StringRef Tok); StringMatcher readFilePatterns(); std::vector readInputSectionsList(); InputSectionDescription *readInputSectionRules(StringRef FilePattern); unsigned readPhdrType(); SortSectionPolicy readSortKind(); SymbolAssignment *readProvideHidden(bool Provide, bool Hidden); SymbolAssignment *readProvideOrAssignment(StringRef Tok); void readSort(); AssertCommand *readAssert(); Expr readAssertExpr(); Expr readConstant(); Expr getPageSize(); uint64_t readMemoryAssignment(StringRef, StringRef, StringRef); std::pair readMemoryAttributes(); Expr readExpr(); Expr readExpr1(Expr Lhs, int MinPrec); StringRef readParenLiteral(); Expr readPrimary(); Expr readTernary(Expr Cond); Expr readParenExpr(); // For parsing version script. std::vector readVersionExtern(); void readAnonymousDeclaration(); void readVersionDeclaration(StringRef VerStr); std::pair, std::vector> readSymbols(); // True if a script being read is in a subdirectory specified by -sysroot. bool IsUnderSysroot; // A set to detect an INCLUDE() cycle. StringSet<> Seen; }; } // namespace static StringRef unquote(StringRef S) { if (S.startswith("\"")) return S.substr(1, S.size() - 2); return S; } static bool isUnderSysroot(StringRef Path) { if (Config->Sysroot == "") return false; for (; !Path.empty(); Path = sys::path::parent_path(Path)) if (sys::fs::equivalent(Config->Sysroot, Path)) return true; return false; } // Some operations only support one non absolute value. Move the // absolute one to the right hand side for convenience. static void moveAbsRight(ExprValue &A, ExprValue &B) { if (A.Sec == nullptr || (A.ForceAbsolute && !B.isAbsolute())) std::swap(A, B); if (!B.isAbsolute()) error(A.Loc + ": at least one side of the expression must be absolute"); } static ExprValue add(ExprValue A, ExprValue B) { moveAbsRight(A, B); return {A.Sec, A.ForceAbsolute, A.getSectionOffset() + B.getValue(), A.Loc}; } static ExprValue sub(ExprValue A, ExprValue B) { // The distance between two symbols in sections is absolute. if (!A.isAbsolute() && !B.isAbsolute()) return A.getValue() - B.getValue(); return {A.Sec, false, A.getSectionOffset() - B.getValue(), A.Loc}; } static ExprValue mul(ExprValue A, ExprValue B) { return A.getValue() * B.getValue(); } static ExprValue div(ExprValue A, ExprValue B) { if (uint64_t BV = B.getValue()) return A.getValue() / BV; error("division by zero"); return 0; } static ExprValue bitAnd(ExprValue A, ExprValue B) { moveAbsRight(A, B); return {A.Sec, A.ForceAbsolute, (A.getValue() & B.getValue()) - A.getSecAddr(), A.Loc}; } static ExprValue bitOr(ExprValue A, ExprValue B) { moveAbsRight(A, B); return {A.Sec, A.ForceAbsolute, (A.getValue() | B.getValue()) - A.getSecAddr(), A.Loc}; } void ScriptParser::readDynamicList() { Config->HasDynamicList = true; expect("{"); std::vector Locals; std::vector Globals; std::tie(Locals, Globals) = readSymbols(); expect(";"); if (!atEOF()) { setError("EOF expected, but got " + next()); return; } if (!Locals.empty()) { setError("\"local:\" scope not supported in --dynamic-list"); return; } for (SymbolVersion V : Globals) Config->DynamicList.push_back(V); } void ScriptParser::readVersionScript() { readVersionScriptCommand(); if (!atEOF()) setError("EOF expected, but got " + next()); } void ScriptParser::readVersionScriptCommand() { if (consume("{")) { readAnonymousDeclaration(); return; } while (!atEOF() && !errorCount() && peek() != "}") { StringRef VerStr = next(); if (VerStr == "{") { setError("anonymous version definition is used in " "combination with other version definitions"); return; } expect("{"); readVersionDeclaration(VerStr); } } void ScriptParser::readVersion() { expect("{"); readVersionScriptCommand(); expect("}"); } void ScriptParser::readLinkerScript() { while (!atEOF()) { StringRef Tok = next(); if (Tok == ";") continue; if (Tok == "ASSERT") { Script->SectionCommands.push_back(readAssert()); } else if (Tok == "ENTRY") { readEntry(); } else if (Tok == "EXTERN") { readExtern(); } else if (Tok == "GROUP" || Tok == "INPUT") { readGroup(); } else if (Tok == "INCLUDE") { readInclude(); } else if (Tok == "MEMORY") { readMemory(); } else if (Tok == "OUTPUT") { readOutput(); } else if (Tok == "OUTPUT_ARCH") { readOutputArch(); } else if (Tok == "OUTPUT_FORMAT") { readOutputFormat(); } else if (Tok == "PHDRS") { readPhdrs(); } else if (Tok == "REGION_ALIAS") { readRegionAlias(); } else if (Tok == "SEARCH_DIR") { readSearchDir(); } else if (Tok == "SECTIONS") { readSections(); } else if (Tok == "VERSION") { readVersion(); } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) { Script->SectionCommands.push_back(Cmd); } else { setError("unknown directive: " + Tok); } } } void ScriptParser::readDefsym(StringRef Name) { Expr E = readExpr(); if (!atEOF()) setError("EOF expected, but got " + next()); SymbolAssignment *Cmd = make(Name, E, getCurrentLocation()); Script->SectionCommands.push_back(Cmd); } void ScriptParser::addFile(StringRef S) { if (IsUnderSysroot && S.startswith("/")) { SmallString<128> PathData; StringRef Path = (Config->Sysroot + S).toStringRef(PathData); if (sys::fs::exists(Path)) { Driver->addFile(Saver.save(Path), /*WithLOption=*/false); return; } } if (S.startswith("/")) { Driver->addFile(S, /*WithLOption=*/false); } else if (S.startswith("=")) { if (Config->Sysroot.empty()) Driver->addFile(S.substr(1), /*WithLOption=*/false); else Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)), /*WithLOption=*/false); } else if (S.startswith("-l")) { Driver->addLibrary(S.substr(2)); } else if (sys::fs::exists(S)) { Driver->addFile(S, /*WithLOption=*/false); } else { if (Optional Path = findFromSearchPaths(S)) Driver->addFile(Saver.save(*Path), /*WithLOption=*/true); else setError("unable to find " + S); } } void ScriptParser::readAsNeeded() { expect("("); bool Orig = Config->AsNeeded; Config->AsNeeded = true; while (!errorCount() && !consume(")")) addFile(unquote(next())); Config->AsNeeded = Orig; } void ScriptParser::readEntry() { // -e takes predecence over ENTRY(). expect("("); StringRef Tok = next(); if (Config->Entry.empty()) Config->Entry = Tok; expect(")"); } void ScriptParser::readExtern() { expect("("); while (!errorCount() && !consume(")")) Config->Undefined.push_back(next()); } void ScriptParser::readGroup() { expect("("); while (!errorCount() && !consume(")")) { if (consume("AS_NEEDED")) readAsNeeded(); else addFile(unquote(next())); } } void ScriptParser::readInclude() { StringRef Tok = unquote(next()); if (!Seen.insert(Tok).second) { setError("there is a cycle in linker script INCLUDEs"); return; } if (Optional Path = searchLinkerScript(Tok)) { if (Optional MB = readFile(*Path)) tokenize(*MB); return; } setError("cannot find linker script " + Tok); } void ScriptParser::readOutput() { // -o takes predecence over OUTPUT(). expect("("); StringRef Tok = next(); if (Config->OutputFile.empty()) Config->OutputFile = unquote(Tok); expect(")"); } void ScriptParser::readOutputArch() { // OUTPUT_ARCH is ignored for now. expect("("); while (!errorCount() && !consume(")")) skip(); } void ScriptParser::readOutputFormat() { // Error checking only for now. expect("("); skip(); if (consume(")")) return; expect(","); skip(); expect(","); skip(); expect(")"); } void ScriptParser::readPhdrs() { expect("{"); while (!errorCount() && !consume("}")) { PhdrsCommand Cmd; Cmd.Name = next(); Cmd.Type = readPhdrType(); while (!errorCount() && !consume(";")) { if (consume("FILEHDR")) Cmd.HasFilehdr = true; else if (consume("PHDRS")) Cmd.HasPhdrs = true; else if (consume("AT")) Cmd.LMAExpr = readParenExpr(); else if (consume("FLAGS")) Cmd.Flags = readParenExpr()().getValue(); else setError("unexpected header attribute: " + next()); } Script->PhdrsCommands.push_back(Cmd); } } void ScriptParser::readRegionAlias() { expect("("); StringRef Alias = unquote(next()); expect(","); StringRef Name = next(); expect(")"); if (Script->MemoryRegions.count(Alias)) setError("redefinition of memory region '" + Alias + "'"); if (!Script->MemoryRegions.count(Name)) setError("memory region '" + Name + "' is not defined"); Script->MemoryRegions.insert({Alias, Script->MemoryRegions[Name]}); } void ScriptParser::readSearchDir() { expect("("); StringRef Tok = next(); if (!Config->Nostdlib) Config->SearchPaths.push_back(unquote(Tok)); expect(")"); } void ScriptParser::readSections() { Script->HasSectionsCommand = true; // -no-rosegment is used to avoid placing read only non-executable sections in // their own segment. We do the same if SECTIONS command is present in linker // script. See comment for computeFlags(). Config->SingleRoRx = true; expect("{"); while (!errorCount() && !consume("}")) { StringRef Tok = next(); BaseCommand *Cmd = readProvideOrAssignment(Tok); if (!Cmd) { if (Tok == "ASSERT") Cmd = readAssert(); else Cmd = readOutputSectionDescription(Tok); } Script->SectionCommands.push_back(Cmd); } } static int precedence(StringRef Op) { return StringSwitch(Op) .Cases("*", "/", 5) .Cases("+", "-", 4) .Cases("<<", ">>", 3) .Cases("<", "<=", ">", ">=", "==", "!=", 2) .Cases("&", "|", 1) .Default(-1); } StringMatcher ScriptParser::readFilePatterns() { std::vector V; while (!errorCount() && !consume(")")) V.push_back(next()); return StringMatcher(V); } SortSectionPolicy ScriptParser::readSortKind() { if (consume("SORT") || consume("SORT_BY_NAME")) return SortSectionPolicy::Name; if (consume("SORT_BY_ALIGNMENT")) return SortSectionPolicy::Alignment; if (consume("SORT_BY_INIT_PRIORITY")) return SortSectionPolicy::Priority; if (consume("SORT_NONE")) return SortSectionPolicy::None; return SortSectionPolicy::Default; } // Reads SECTIONS command contents in the following form: // // ::= * // ::= ? // ::= "EXCLUDE_FILE" "(" + ")" // // For example, // // *(.foo EXCLUDE_FILE (a.o) .bar EXCLUDE_FILE (b.o) .baz) // // is parsed as ".foo", ".bar" with "a.o", and ".baz" with "b.o". // The semantics of that is section .foo in any file, section .bar in // any file but a.o, and section .baz in any file but b.o. std::vector ScriptParser::readInputSectionsList() { std::vector Ret; while (!errorCount() && peek() != ")") { StringMatcher ExcludeFilePat; if (consume("EXCLUDE_FILE")) { expect("("); ExcludeFilePat = readFilePatterns(); } std::vector V; while (!errorCount() && peek() != ")" && peek() != "EXCLUDE_FILE") V.push_back(next()); if (!V.empty()) Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)}); else setError("section pattern is expected"); } return Ret; } // Reads contents of "SECTIONS" directive. That directive contains a // list of glob patterns for input sections. The grammar is as follows. // // ::= // | "(" ")" // | "(" "(" ")" ")" // // ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT" // | "SORT_BY_INIT_PRIORITY" | "SORT_NONE" // // is parsed by readInputSectionsList(). InputSectionDescription * ScriptParser::readInputSectionRules(StringRef FilePattern) { auto *Cmd = make(FilePattern); expect("("); while (!errorCount() && !consume(")")) { SortSectionPolicy Outer = readSortKind(); SortSectionPolicy Inner = SortSectionPolicy::Default; std::vector V; if (Outer != SortSectionPolicy::Default) { expect("("); Inner = readSortKind(); if (Inner != SortSectionPolicy::Default) { expect("("); V = readInputSectionsList(); expect(")"); } else { V = readInputSectionsList(); } expect(")"); } else { V = readInputSectionsList(); } for (SectionPattern &Pat : V) { Pat.SortInner = Inner; Pat.SortOuter = Outer; } std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns)); } return Cmd; } InputSectionDescription * ScriptParser::readInputSectionDescription(StringRef Tok) { // Input section wildcard can be surrounded by KEEP. // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep if (Tok == "KEEP") { expect("("); StringRef FilePattern = next(); InputSectionDescription *Cmd = readInputSectionRules(FilePattern); expect(")"); Script->KeptSections.push_back(Cmd); return Cmd; } return readInputSectionRules(Tok); } void ScriptParser::readSort() { expect("("); expect("CONSTRUCTORS"); expect(")"); } AssertCommand *ScriptParser::readAssert() { return make(readAssertExpr()); } Expr ScriptParser::readAssertExpr() { expect("("); Expr E = readExpr(); expect(","); StringRef Msg = unquote(next()); expect(")"); return [=] { if (!E().getValue()) error(Msg); return Script->getDot(); }; } // Reads a FILL(expr) command. We handle the FILL command as an // alias for =fillexp section attribute, which is different from // what GNU linkers do. // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html uint32_t ScriptParser::readFill() { expect("("); uint32_t V = parseFill(next()); expect(")"); return V; } // Reads an expression and/or the special directive "(NOLOAD)" for an // output section definition. // // An output section name can be followed by an address expression // and/or by "(NOLOAD)". This grammar is not LL(1) because "(" can be // interpreted as either the beginning of some expression or "(NOLOAD)". // // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html // https://sourceware.org/binutils/docs/ld/Output-Section-Type.html void ScriptParser::readSectionAddressType(OutputSection *Cmd) { if (consume("(")) { if (consume("NOLOAD")) { expect(")"); Cmd->Noload = true; return; } Cmd->AddrExpr = readExpr(); expect(")"); } else { Cmd->AddrExpr = readExpr(); } if (consume("(")) { expect("NOLOAD"); expect(")"); Cmd->Noload = true; } } static Expr checkAlignment(Expr E, std::string &Loc) { return [=] { uint64_t Alignment = std::max((uint64_t)1, E().getValue()); if (!isPowerOf2_64(Alignment)) { error(Loc + ": alignment must be power of 2"); return (uint64_t)1; // Return a dummy value. } return Alignment; }; } OutputSection *ScriptParser::readOutputSectionDescription(StringRef OutSec) { OutputSection *Cmd = Script->createOutputSection(OutSec, getCurrentLocation()); if (peek() != ":") readSectionAddressType(Cmd); expect(":"); std::string Location = getCurrentLocation(); if (consume("AT")) Cmd->LMAExpr = readParenExpr(); if (consume("ALIGN")) Cmd->AlignExpr = checkAlignment(readParenExpr(), Location); if (consume("SUBALIGN")) Cmd->SubalignExpr = checkAlignment(readParenExpr(), Location); // Parse constraints. if (consume("ONLY_IF_RO")) Cmd->Constraint = ConstraintKind::ReadOnly; if (consume("ONLY_IF_RW")) Cmd->Constraint = ConstraintKind::ReadWrite; expect("{"); while (!errorCount() && !consume("}")) { StringRef Tok = next(); if (Tok == ";") { // Empty commands are allowed. Do nothing here. } else if (SymbolAssignment *Assign = readProvideOrAssignment(Tok)) { Cmd->SectionCommands.push_back(Assign); } else if (ByteCommand *Data = readByteCommand(Tok)) { Cmd->SectionCommands.push_back(Data); } else if (Tok == "ASSERT") { Cmd->SectionCommands.push_back(readAssert()); expect(";"); } else if (Tok == "CONSTRUCTORS") { // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors // by name. This is for very old file formats such as ECOFF/XCOFF. // For ELF, we should ignore. } else if (Tok == "FILL") { Cmd->Filler = readFill(); } else if (Tok == "SORT") { readSort(); } else if (peek() == "(") { Cmd->SectionCommands.push_back(readInputSectionDescription(Tok)); } else { setError("unknown command " + Tok); } } if (consume(">")) Cmd->MemoryRegionName = next(); + if (consume("AT")) { + expect(">"); + Cmd->LMARegionName = next(); + } + + if (Cmd->LMAExpr && !Cmd->LMARegionName.empty()) + error("section can't have both LMA and a load region"); + Cmd->Phdrs = readOutputSectionPhdrs(); if (consume("=")) Cmd->Filler = parseFill(next()); else if (peek().startswith("=")) Cmd->Filler = parseFill(next().drop_front()); // Consume optional comma following output section command. consume(","); return Cmd; } // Parses a given string as a octal/decimal/hexadecimal number and // returns it as a big-endian number. Used for `=`. // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html // // When reading a hexstring, ld.bfd handles it as a blob of arbitrary // size, while ld.gold always handles it as a 32-bit big-endian number. // We are compatible with ld.gold because it's easier to implement. uint32_t ScriptParser::parseFill(StringRef Tok) { uint32_t V = 0; if (!to_integer(Tok, V)) setError("invalid filler expression: " + Tok); uint32_t Buf; write32be(&Buf, V); return Buf; } SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) { expect("("); SymbolAssignment *Cmd = readAssignment(next()); Cmd->Provide = Provide; Cmd->Hidden = Hidden; expect(")"); expect(";"); return Cmd; } SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) { SymbolAssignment *Cmd = nullptr; if (peek() == "=" || peek() == "+=") { Cmd = readAssignment(Tok); expect(";"); } else if (Tok == "PROVIDE") { Cmd = readProvideHidden(true, false); } else if (Tok == "HIDDEN") { Cmd = readProvideHidden(false, true); } else if (Tok == "PROVIDE_HIDDEN") { Cmd = readProvideHidden(true, true); } return Cmd; } SymbolAssignment *ScriptParser::readAssignment(StringRef Name) { StringRef Op = next(); assert(Op == "=" || Op == "+="); Expr E = readExpr(); if (Op == "+=") { std::string Loc = getCurrentLocation(); E = [=] { return add(Script->getSymbolValue(Name, Loc), E()); }; } return make(Name, E, getCurrentLocation()); } // This is an operator-precedence parser to parse a linker // script expression. Expr ScriptParser::readExpr() { // Our lexer is context-aware. Set the in-expression bit so that // they apply different tokenization rules. bool Orig = InExpr; InExpr = true; Expr E = readExpr1(readPrimary(), 0); InExpr = Orig; return E; } static Expr combine(StringRef Op, Expr L, Expr R) { if (Op == "+") return [=] { return add(L(), R()); }; if (Op == "-") return [=] { return sub(L(), R()); }; if (Op == "*") return [=] { return mul(L(), R()); }; if (Op == "/") return [=] { return div(L(), R()); }; if (Op == "<<") return [=] { return L().getValue() << R().getValue(); }; if (Op == ">>") return [=] { return L().getValue() >> R().getValue(); }; if (Op == "<") return [=] { return L().getValue() < R().getValue(); }; if (Op == ">") return [=] { return L().getValue() > R().getValue(); }; if (Op == ">=") return [=] { return L().getValue() >= R().getValue(); }; if (Op == "<=") return [=] { return L().getValue() <= R().getValue(); }; if (Op == "==") return [=] { return L().getValue() == R().getValue(); }; if (Op == "!=") return [=] { return L().getValue() != R().getValue(); }; if (Op == "&") return [=] { return bitAnd(L(), R()); }; if (Op == "|") return [=] { return bitOr(L(), R()); }; llvm_unreachable("invalid operator"); } // This is a part of the operator-precedence parser. This function // assumes that the remaining token stream starts with an operator. Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) { while (!atEOF() && !errorCount()) { // Read an operator and an expression. if (consume("?")) return readTernary(Lhs); StringRef Op1 = peek(); if (precedence(Op1) < MinPrec) break; skip(); Expr Rhs = readPrimary(); // Evaluate the remaining part of the expression first if the // next operator has greater precedence than the previous one. // For example, if we have read "+" and "3", and if the next // operator is "*", then we'll evaluate 3 * ... part first. while (!atEOF()) { StringRef Op2 = peek(); if (precedence(Op2) <= precedence(Op1)) break; Rhs = readExpr1(Rhs, precedence(Op2)); } Lhs = combine(Op1, Lhs, Rhs); } return Lhs; } Expr ScriptParser::getPageSize() { std::string Location = getCurrentLocation(); return [=]() -> uint64_t { if (Target) return Target->PageSize; error(Location + ": unable to calculate page size"); return 4096; // Return a dummy value. }; } Expr ScriptParser::readConstant() { StringRef S = readParenLiteral(); if (S == "COMMONPAGESIZE") return getPageSize(); if (S == "MAXPAGESIZE") return [] { return Config->MaxPageSize; }; setError("unknown constant: " + S); return {}; } // Parses Tok as an integer. It recognizes hexadecimal (prefixed with // "0x" or suffixed with "H") and decimal numbers. Decimal numbers may // have "K" (Ki) or "M" (Mi) suffixes. static Optional parseInt(StringRef Tok) { // Negative number if (Tok.startswith("-")) { if (Optional Val = parseInt(Tok.substr(1))) return -*Val; return None; } // Hexadecimal uint64_t Val; if (Tok.startswith_lower("0x")) { if (!to_integer(Tok.substr(2), Val, 16)) return None; return Val; } if (Tok.endswith_lower("H")) { if (!to_integer(Tok.drop_back(), Val, 16)) return None; return Val; } // Decimal if (Tok.endswith_lower("K")) { if (!to_integer(Tok.drop_back(), Val, 10)) return None; return Val * 1024; } if (Tok.endswith_lower("M")) { if (!to_integer(Tok.drop_back(), Val, 10)) return None; return Val * 1024 * 1024; } if (!to_integer(Tok, Val, 10)) return None; return Val; } ByteCommand *ScriptParser::readByteCommand(StringRef Tok) { int Size = StringSwitch(Tok) .Case("BYTE", 1) .Case("SHORT", 2) .Case("LONG", 4) .Case("QUAD", 8) .Default(-1); if (Size == -1) return nullptr; return make(readParenExpr(), Size); } StringRef ScriptParser::readParenLiteral() { expect("("); + bool Orig = InExpr; + InExpr = false; StringRef Tok = next(); + InExpr = Orig; expect(")"); return Tok; } static void checkIfExists(OutputSection *Cmd, StringRef Location) { if (Cmd->Location.empty() && Script->ErrorOnMissingSection) error(Location + ": undefined section " + Cmd->Name); } Expr ScriptParser::readPrimary() { if (peek() == "(") return readParenExpr(); if (consume("~")) { Expr E = readPrimary(); return [=] { return ~E().getValue(); }; } if (consume("!")) { Expr E = readPrimary(); return [=] { return !E().getValue(); }; } if (consume("-")) { Expr E = readPrimary(); return [=] { return -E().getValue(); }; } StringRef Tok = next(); std::string Location = getCurrentLocation(); // Built-in functions are parsed here. // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html. if (Tok == "ABSOLUTE") { Expr Inner = readParenExpr(); return [=] { ExprValue I = Inner(); I.ForceAbsolute = true; return I; }; } if (Tok == "ADDR") { StringRef Name = readParenLiteral(); OutputSection *Sec = Script->getOrCreateOutputSection(Name); return [=]() -> ExprValue { checkIfExists(Sec, Location); return {Sec, false, 0, Location}; }; } if (Tok == "ALIGN") { expect("("); Expr E = readExpr(); if (consume(")")) { E = checkAlignment(E, Location); return [=] { return alignTo(Script->getDot(), E().getValue()); }; } expect(","); Expr E2 = checkAlignment(readExpr(), Location); expect(")"); return [=] { ExprValue V = E(); V.Alignment = E2().getValue(); return V; }; } if (Tok == "ALIGNOF") { StringRef Name = readParenLiteral(); OutputSection *Cmd = Script->getOrCreateOutputSection(Name); return [=] { checkIfExists(Cmd, Location); return Cmd->Alignment; }; } if (Tok == "ASSERT") return readAssertExpr(); if (Tok == "CONSTANT") return readConstant(); if (Tok == "DATA_SEGMENT_ALIGN") { expect("("); Expr E = readExpr(); expect(","); readExpr(); expect(")"); return [=] { return alignTo(Script->getDot(), std::max((uint64_t)1, E().getValue())); }; } if (Tok == "DATA_SEGMENT_END") { expect("("); expect("."); expect(")"); return [] { return Script->getDot(); }; } if (Tok == "DATA_SEGMENT_RELRO_END") { // GNU linkers implements more complicated logic to handle // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and // just align to the next page boundary for simplicity. expect("("); readExpr(); expect(","); readExpr(); expect(")"); Expr E = getPageSize(); return [=] { return alignTo(Script->getDot(), E().getValue()); }; } if (Tok == "DEFINED") { StringRef Name = readParenLiteral(); return [=] { return Symtab->find(Name) ? 1 : 0; }; } if (Tok == "LENGTH") { StringRef Name = readParenLiteral(); if (Script->MemoryRegions.count(Name) == 0) setError("memory region not defined: " + Name); return [=] { return Script->MemoryRegions[Name]->Length; }; } if (Tok == "LOADADDR") { StringRef Name = readParenLiteral(); OutputSection *Cmd = Script->getOrCreateOutputSection(Name); return [=] { checkIfExists(Cmd, Location); return Cmd->getLMA(); }; } if (Tok == "ORIGIN") { StringRef Name = readParenLiteral(); if (Script->MemoryRegions.count(Name) == 0) setError("memory region not defined: " + Name); return [=] { return Script->MemoryRegions[Name]->Origin; }; } if (Tok == "SEGMENT_START") { expect("("); skip(); expect(","); Expr E = readExpr(); expect(")"); return [=] { return E(); }; } if (Tok == "SIZEOF") { StringRef Name = readParenLiteral(); OutputSection *Cmd = Script->getOrCreateOutputSection(Name); // Linker script does not create an output section if its content is empty. // We want to allow SIZEOF(.foo) where .foo is a section which happened to // be empty. return [=] { return Cmd->Size; }; } if (Tok == "SIZEOF_HEADERS") return [=] { return elf::getHeaderSize(); }; // Tok is the dot. if (Tok == ".") return [=] { return Script->getSymbolValue(Tok, Location); }; // Tok is a literal number. if (Optional Val = parseInt(Tok)) return [=] { return *Val; }; // Tok is a symbol name. if (!isValidCIdentifier(Tok)) setError("malformed number: " + Tok); Script->ReferencedSymbols.push_back(Tok); return [=] { return Script->getSymbolValue(Tok, Location); }; } Expr ScriptParser::readTernary(Expr Cond) { Expr L = readExpr(); expect(":"); Expr R = readExpr(); return [=] { return Cond().getValue() ? L() : R(); }; } Expr ScriptParser::readParenExpr() { expect("("); Expr E = readExpr(); expect(")"); return E; } std::vector ScriptParser::readOutputSectionPhdrs() { std::vector Phdrs; while (!errorCount() && peek().startswith(":")) { StringRef Tok = next(); Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1)); } return Phdrs; } // Read a program header type name. The next token must be a // name of a program header type or a constant (e.g. "0x3"). unsigned ScriptParser::readPhdrType() { StringRef Tok = next(); if (Optional Val = parseInt(Tok)) return *Val; unsigned Ret = StringSwitch(Tok) .Case("PT_NULL", PT_NULL) .Case("PT_LOAD", PT_LOAD) .Case("PT_DYNAMIC", PT_DYNAMIC) .Case("PT_INTERP", PT_INTERP) .Case("PT_NOTE", PT_NOTE) .Case("PT_SHLIB", PT_SHLIB) .Case("PT_PHDR", PT_PHDR) .Case("PT_TLS", PT_TLS) .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME) .Case("PT_GNU_STACK", PT_GNU_STACK) .Case("PT_GNU_RELRO", PT_GNU_RELRO) .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE) .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED) .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA) .Default(-1); if (Ret == (unsigned)-1) { setError("invalid program header type: " + Tok); return PT_NULL; } return Ret; } // Reads an anonymous version declaration. void ScriptParser::readAnonymousDeclaration() { std::vector Locals; std::vector Globals; std::tie(Locals, Globals) = readSymbols(); for (SymbolVersion V : Locals) { if (V.Name == "*") Config->DefaultSymbolVersion = VER_NDX_LOCAL; else Config->VersionScriptLocals.push_back(V); } for (SymbolVersion V : Globals) Config->VersionScriptGlobals.push_back(V); expect(";"); } // Reads a non-anonymous version definition, // e.g. "VerStr { global: foo; bar; local: *; };". void ScriptParser::readVersionDeclaration(StringRef VerStr) { // Read a symbol list. std::vector Locals; std::vector Globals; std::tie(Locals, Globals) = readSymbols(); for (SymbolVersion V : Locals) { if (V.Name == "*") Config->DefaultSymbolVersion = VER_NDX_LOCAL; else Config->VersionScriptLocals.push_back(V); } // Create a new version definition and add that to the global symbols. VersionDefinition Ver; Ver.Name = VerStr; Ver.Globals = Globals; // User-defined version number starts from 2 because 0 and 1 are // reserved for VER_NDX_LOCAL and VER_NDX_GLOBAL, respectively. Ver.Id = Config->VersionDefinitions.size() + 2; Config->VersionDefinitions.push_back(Ver); // Each version may have a parent version. For example, "Ver2" // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" // as a parent. This version hierarchy is, probably against your // instinct, purely for hint; the runtime doesn't care about it // at all. In LLD, we simply ignore it. if (peek() != ";") skip(); expect(";"); } static bool hasWildcard(StringRef S) { return S.find_first_of("?*[") != StringRef::npos; } // Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };". std::pair, std::vector> ScriptParser::readSymbols() { std::vector Locals; std::vector Globals; std::vector *V = &Globals; while (!errorCount()) { if (consume("}")) break; if (consumeLabel("local")) { V = &Locals; continue; } if (consumeLabel("global")) { V = &Globals; continue; } if (consume("extern")) { std::vector Ext = readVersionExtern(); V->insert(V->end(), Ext.begin(), Ext.end()); } else { StringRef Tok = next(); V->push_back({unquote(Tok), false, hasWildcard(Tok)}); } expect(";"); } return {Locals, Globals}; } // Reads an "extern C++" directive, e.g., // "extern "C++" { ns::*; "f(int, double)"; };" std::vector ScriptParser::readVersionExtern() { StringRef Tok = next(); bool IsCXX = Tok == "\"C++\""; if (!IsCXX && Tok != "\"C\"") setError("Unknown language"); expect("{"); std::vector Ret; while (!errorCount() && peek() != "}") { StringRef Tok = next(); bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok); Ret.push_back({unquote(Tok), IsCXX, HasWildcard}); expect(";"); } expect("}"); return Ret; } uint64_t ScriptParser::readMemoryAssignment(StringRef S1, StringRef S2, StringRef S3) { if (!consume(S1) && !consume(S2) && !consume(S3)) { setError("expected one of: " + S1 + ", " + S2 + ", or " + S3); return 0; } expect("="); return readExpr()().getValue(); } // Parse the MEMORY command as specified in: // https://sourceware.org/binutils/docs/ld/MEMORY.html // // MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... } void ScriptParser::readMemory() { expect("{"); while (!errorCount() && !consume("}")) { StringRef Name = next(); uint32_t Flags = 0; uint32_t NegFlags = 0; if (consume("(")) { std::tie(Flags, NegFlags) = readMemoryAttributes(); expect(")"); } expect(":"); uint64_t Origin = readMemoryAssignment("ORIGIN", "org", "o"); expect(","); uint64_t Length = readMemoryAssignment("LENGTH", "len", "l"); // Add the memory region to the region map. if (Script->MemoryRegions.count(Name)) setError("region '" + Name + "' already defined"); MemoryRegion *MR = make(); *MR = {Name, Origin, Length, Flags, NegFlags}; Script->MemoryRegions[Name] = MR; } } // This function parses the attributes used to match against section // flags when placing output sections in a memory region. These flags // are only used when an explicit memory region name is not used. std::pair ScriptParser::readMemoryAttributes() { uint32_t Flags = 0; uint32_t NegFlags = 0; bool Invert = false; for (char C : next().lower()) { uint32_t Flag = 0; if (C == '!') Invert = !Invert; else if (C == 'w') Flag = SHF_WRITE; else if (C == 'x') Flag = SHF_EXECINSTR; else if (C == 'a') Flag = SHF_ALLOC; else if (C != 'r') setError("invalid memory region attribute"); if (Invert) NegFlags |= Flag; else Flags |= Flag; } return {Flags, NegFlags}; } void elf::readLinkerScript(MemoryBufferRef MB) { ScriptParser(MB).readLinkerScript(); } void elf::readVersionScript(MemoryBufferRef MB) { ScriptParser(MB).readVersionScript(); } void elf::readDynamicList(MemoryBufferRef MB) { ScriptParser(MB).readDynamicList(); } void elf::readDefsym(StringRef Name, MemoryBufferRef MB) { ScriptParser(MB).readDefsym(Name); } Index: vendor/lld/dist-release_60/ELF/SymbolTable.cpp =================================================================== --- vendor/lld/dist-release_60/ELF/SymbolTable.cpp (revision 328369) +++ vendor/lld/dist-release_60/ELF/SymbolTable.cpp (revision 328370) @@ -1,835 +1,836 @@ //===- SymbolTable.cpp ----------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Symbol table is a bag of all known symbols. We put all symbols of // all input files to the symbol table. The symbol table is basically // a hash table with the logic to resolve symbol name conflicts using // the symbol types. // //===----------------------------------------------------------------------===// #include "SymbolTable.h" #include "Config.h" #include "LinkerScript.h" #include "Symbols.h" #include "SyntheticSections.h" #include "lld/Common/ErrorHandler.h" #include "lld/Common/Memory.h" #include "lld/Common/Strings.h" #include "llvm/ADT/STLExtras.h" using namespace llvm; using namespace llvm::object; using namespace llvm::ELF; using namespace lld; using namespace lld::elf; SymbolTable *elf::Symtab; static InputFile *getFirstElf() { if (!ObjectFiles.empty()) return ObjectFiles[0]; if (!SharedFiles.empty()) return SharedFiles[0]; return nullptr; } // All input object files must be for the same architecture // (e.g. it does not make sense to link x86 object files with // MIPS object files.) This function checks for that error. static bool isCompatible(InputFile *F) { if (!F->isElf() && !isa(F)) return true; if (F->EKind == Config->EKind && F->EMachine == Config->EMachine) { if (Config->EMachine != EM_MIPS) return true; if (isMipsN32Abi(F) == Config->MipsN32Abi) return true; } if (!Config->Emulation.empty()) error(toString(F) + " is incompatible with " + Config->Emulation); else error(toString(F) + " is incompatible with " + toString(getFirstElf())); return false; } // Add symbols in File to the symbol table. template void SymbolTable::addFile(InputFile *File) { if (!isCompatible(File)) return; // Binary file if (auto *F = dyn_cast(File)) { BinaryFiles.push_back(F); F->parse(); return; } // .a file if (auto *F = dyn_cast(File)) { F->parse(); return; } // Lazy object file if (auto *F = dyn_cast(File)) { F->parse(); return; } if (Config->Trace) message(toString(File)); // .so file if (auto *F = dyn_cast>(File)) { // DSOs are uniquified not by filename but by soname. F->parseSoName(); if (errorCount() || !SoNames.insert(F->SoName).second) return; SharedFiles.push_back(F); F->parseRest(); return; } // LLVM bitcode file if (auto *F = dyn_cast(File)) { BitcodeFiles.push_back(F); F->parse(ComdatGroups); return; } // Regular object file ObjectFiles.push_back(File); cast>(File)->parse(ComdatGroups); } // This function is where all the optimizations of link-time // optimization happens. When LTO is in use, some input files are // not in native object file format but in the LLVM bitcode format. // This function compiles bitcode files into a few big native files // using LLVM functions and replaces bitcode symbols with the results. // Because all bitcode files that consist of a program are passed // to the compiler at once, it can do whole-program optimization. template void SymbolTable::addCombinedLTOObject() { if (BitcodeFiles.empty()) return; // Compile bitcode files and replace bitcode symbols. LTO.reset(new BitcodeCompiler); for (BitcodeFile *F : BitcodeFiles) LTO->add(*F); for (InputFile *File : LTO->compile()) { DenseSet DummyGroups; cast>(File)->parse(DummyGroups); ObjectFiles.push_back(File); } } Defined *SymbolTable::addAbsolute(StringRef Name, uint8_t Visibility, uint8_t Binding) { Symbol *Sym = addRegular(Name, Visibility, STT_NOTYPE, 0, 0, Binding, nullptr, nullptr); return cast(Sym); } // Set a flag for --trace-symbol so that we can print out a log message // if a new symbol with the same name is inserted into the symbol table. void SymbolTable::trace(StringRef Name) { SymMap.insert({CachedHashStringRef(Name), -1}); } // Rename SYM as __wrap_SYM. The original symbol is preserved as __real_SYM. // Used to implement --wrap. template void SymbolTable::addSymbolWrap(StringRef Name) { Symbol *Sym = find(Name); if (!Sym) return; Symbol *Real = addUndefined(Saver.save("__real_" + Name)); Symbol *Wrap = addUndefined(Saver.save("__wrap_" + Name)); WrappedSymbols.push_back({Sym, Real, Wrap}); // We want to tell LTO not to inline symbols to be overwritten // because LTO doesn't know the final symbol contents after renaming. Real->CanInline = false; Sym->CanInline = false; // Tell LTO not to eliminate these symbols. Sym->IsUsedInRegularObj = true; Wrap->IsUsedInRegularObj = true; } // Apply symbol renames created by -wrap. The renames are created // before LTO in addSymbolWrap() to have a chance to inform LTO (if // LTO is running) not to include these symbols in IPO. Now that the // symbols are finalized, we can perform the replacement. void SymbolTable::applySymbolWrap() { // This function rotates 3 symbols: // // __real_sym becomes sym // sym becomes __wrap_sym // __wrap_sym becomes __real_sym // // The last part is special in that we don't want to change what references to // __wrap_sym point to, we just want have __real_sym in the symbol table. for (WrappedSymbol &W : WrappedSymbols) { // First, make a copy of __real_sym. Symbol *Real = nullptr; if (W.Real->isDefined()) { Real = (Symbol *)make(); memcpy(Real, W.Real, sizeof(SymbolUnion)); } // Replace __real_sym with sym and sym with __wrap_sym. memcpy(W.Real, W.Sym, sizeof(SymbolUnion)); memcpy(W.Sym, W.Wrap, sizeof(SymbolUnion)); // We now have two copies of __wrap_sym. Drop one. W.Wrap->IsUsedInRegularObj = false; if (Real) SymVector.push_back(Real); } } static uint8_t getMinVisibility(uint8_t VA, uint8_t VB) { if (VA == STV_DEFAULT) return VB; if (VB == STV_DEFAULT) return VA; return std::min(VA, VB); } // Find an existing symbol or create and insert a new one. std::pair SymbolTable::insert(StringRef Name) { // @@ means the symbol is the default version. In that // case @@ will be used to resolve references to . // // Since this is a hot path, the following string search code is // optimized for speed. StringRef::find(char) is much faster than // StringRef::find(StringRef). size_t Pos = Name.find('@'); if (Pos != StringRef::npos && Pos + 1 < Name.size() && Name[Pos + 1] == '@') Name = Name.take_front(Pos); auto P = SymMap.insert({CachedHashStringRef(Name), (int)SymVector.size()}); int &SymIndex = P.first->second; bool IsNew = P.second; bool Traced = false; if (SymIndex == -1) { SymIndex = SymVector.size(); IsNew = Traced = true; } Symbol *Sym; if (IsNew) { Sym = (Symbol *)make(); Sym->InVersionScript = false; Sym->Visibility = STV_DEFAULT; Sym->IsUsedInRegularObj = false; Sym->ExportDynamic = false; Sym->CanInline = true; Sym->Traced = Traced; Sym->VersionId = Config->DefaultSymbolVersion; SymVector.push_back(Sym); } else { Sym = SymVector[SymIndex]; } return {Sym, IsNew}; } // Find an existing symbol or create and insert a new one, then apply the given // attributes. std::pair SymbolTable::insert(StringRef Name, uint8_t Type, uint8_t Visibility, bool CanOmitFromDynSym, InputFile *File) { Symbol *S; bool WasInserted; std::tie(S, WasInserted) = insert(Name); // Merge in the new symbol's visibility. S->Visibility = getMinVisibility(S->Visibility, Visibility); if (!CanOmitFromDynSym && (Config->Shared || Config->ExportDynamic)) S->ExportDynamic = true; if (!File || File->kind() == InputFile::ObjKind) S->IsUsedInRegularObj = true; if (!WasInserted && S->Type != Symbol::UnknownType && ((Type == STT_TLS) != S->isTls())) { error("TLS attribute mismatch: " + toString(*S) + "\n>>> defined in " + toString(S->File) + "\n>>> defined in " + toString(File)); } return {S, WasInserted}; } template Symbol *SymbolTable::addUndefined(StringRef Name) { return addUndefined(Name, STB_GLOBAL, STV_DEFAULT, /*Type*/ 0, /*CanOmitFromDynSym*/ false, /*File*/ nullptr); } static uint8_t getVisibility(uint8_t StOther) { return StOther & 3; } template Symbol *SymbolTable::addUndefined(StringRef Name, uint8_t Binding, uint8_t StOther, uint8_t Type, bool CanOmitFromDynSym, InputFile *File) { Symbol *S; bool WasInserted; uint8_t Visibility = getVisibility(StOther); std::tie(S, WasInserted) = insert(Name, Type, Visibility, CanOmitFromDynSym, File); // An undefined symbol with non default visibility must be satisfied // in the same DSO. if (WasInserted || (isa(S) && Visibility != STV_DEFAULT)) { replaceSymbol(S, File, Name, Binding, StOther, Type); return S; } if (S->isShared() || S->isLazy() || (S->isUndefined() && Binding != STB_WEAK)) S->Binding = Binding; if (Binding != STB_WEAK) { if (auto *SS = dyn_cast(S)) if (!Config->GcSections) SS->getFile().IsNeeded = true; } if (auto *L = dyn_cast(S)) { // An undefined weak will not fetch archive members. See comment on Lazy in // Symbols.h for the details. if (Binding == STB_WEAK) L->Type = Type; else if (InputFile *F = L->fetch()) addFile(F); } return S; } // Using .symver foo,foo@@VER unfortunately creates two symbols: foo and // foo@@VER. We want to effectively ignore foo, so give precedence to // foo@@VER. // FIXME: If users can transition to using // .symver foo,foo@@@VER // we can delete this hack. static int compareVersion(Symbol *S, StringRef Name) { bool A = Name.contains("@@"); bool B = S->getName().contains("@@"); if (A && !B) return 1; if (!A && B) return -1; return 0; } // We have a new defined symbol with the specified binding. Return 1 if the new // symbol should win, -1 if the new symbol should lose, or 0 if both symbols are // strong defined symbols. static int compareDefined(Symbol *S, bool WasInserted, uint8_t Binding, StringRef Name) { if (WasInserted) return 1; if (!S->isDefined()) return 1; if (int R = compareVersion(S, Name)) return R; if (Binding == STB_WEAK) return -1; if (S->isWeak()) return 1; return 0; } // We have a new non-common defined symbol with the specified binding. Return 1 // if the new symbol should win, -1 if the new symbol should lose, or 0 if there // is a conflict. If the new symbol wins, also update the binding. static int compareDefinedNonCommon(Symbol *S, bool WasInserted, uint8_t Binding, bool IsAbsolute, uint64_t Value, StringRef Name) { if (int Cmp = compareDefined(S, WasInserted, Binding, Name)) return Cmp; if (auto *R = dyn_cast(S)) { if (R->Section && isa(R->Section)) { // Non-common symbols take precedence over common symbols. if (Config->WarnCommon) warn("common " + S->getName() + " is overridden"); return 1; } if (R->Section == nullptr && Binding == STB_GLOBAL && IsAbsolute && R->Value == Value) return -1; } return 0; } Symbol *SymbolTable::addCommon(StringRef N, uint64_t Size, uint32_t Alignment, uint8_t Binding, uint8_t StOther, uint8_t Type, InputFile &File) { Symbol *S; bool WasInserted; std::tie(S, WasInserted) = insert(N, Type, getVisibility(StOther), /*CanOmitFromDynSym*/ false, &File); int Cmp = compareDefined(S, WasInserted, Binding, N); if (Cmp > 0) { auto *Bss = make("COMMON", Size, Alignment); Bss->File = &File; Bss->Live = !Config->GcSections; InputSections.push_back(Bss); replaceSymbol(S, &File, N, Binding, StOther, Type, 0, Size, Bss); } else if (Cmp == 0) { auto *D = cast(S); auto *Bss = dyn_cast_or_null(D->Section); if (!Bss) { // Non-common symbols take precedence over common symbols. if (Config->WarnCommon) warn("common " + S->getName() + " is overridden"); return S; } if (Config->WarnCommon) warn("multiple common of " + D->getName()); Bss->Alignment = std::max(Bss->Alignment, Alignment); if (Size > Bss->Size) { D->File = Bss->File = &File; D->Size = Bss->Size = Size; } } return S; } static void warnOrError(const Twine &Msg) { if (Config->AllowMultipleDefinition) warn(Msg); else error(Msg); } static void reportDuplicate(Symbol *Sym, InputFile *NewFile) { warnOrError("duplicate symbol: " + toString(*Sym) + "\n>>> defined in " + toString(Sym->File) + "\n>>> defined in " + toString(NewFile)); } static void reportDuplicate(Symbol *Sym, InputSectionBase *ErrSec, uint64_t ErrOffset) { Defined *D = cast(Sym); if (!D->Section || !ErrSec) { reportDuplicate(Sym, ErrSec ? ErrSec->File : nullptr); return; } // Construct and print an error message in the form of: // // ld.lld: error: duplicate symbol: foo // >>> defined at bar.c:30 // >>> bar.o (/home/alice/src/bar.o) // >>> defined at baz.c:563 // >>> baz.o in archive libbaz.a auto *Sec1 = cast(D->Section); std::string Src1 = Sec1->getSrcMsg(*Sym, D->Value); std::string Obj1 = Sec1->getObjMsg(D->Value); std::string Src2 = ErrSec->getSrcMsg(*Sym, ErrOffset); std::string Obj2 = ErrSec->getObjMsg(ErrOffset); std::string Msg = "duplicate symbol: " + toString(*Sym) + "\n>>> defined at "; if (!Src1.empty()) Msg += Src1 + "\n>>> "; Msg += Obj1 + "\n>>> defined at "; if (!Src2.empty()) Msg += Src2 + "\n>>> "; Msg += Obj2; warnOrError(Msg); } Symbol *SymbolTable::addRegular(StringRef Name, uint8_t StOther, uint8_t Type, uint64_t Value, uint64_t Size, uint8_t Binding, SectionBase *Section, InputFile *File) { Symbol *S; bool WasInserted; std::tie(S, WasInserted) = insert(Name, Type, getVisibility(StOther), /*CanOmitFromDynSym*/ false, File); int Cmp = compareDefinedNonCommon(S, WasInserted, Binding, Section == nullptr, Value, Name); if (Cmp > 0) replaceSymbol(S, File, Name, Binding, StOther, Type, Value, Size, Section); else if (Cmp == 0) reportDuplicate(S, dyn_cast_or_null(Section), Value); return S; } template void SymbolTable::addShared(StringRef Name, SharedFile &File, const typename ELFT::Sym &Sym, uint32_t Alignment, uint32_t VerdefIndex) { // DSO symbols do not affect visibility in the output, so we pass STV_DEFAULT // as the visibility, which will leave the visibility in the symbol table // unchanged. Symbol *S; bool WasInserted; std::tie(S, WasInserted) = insert(Name, Sym.getType(), STV_DEFAULT, /*CanOmitFromDynSym*/ true, &File); // Make sure we preempt DSO symbols with default visibility. if (Sym.getVisibility() == STV_DEFAULT) S->ExportDynamic = true; // An undefined symbol with non default visibility must be satisfied // in the same DSO. if (WasInserted || ((S->isUndefined() || S->isLazy()) && S->getVisibility() == STV_DEFAULT)) { uint8_t Binding = S->Binding; + bool WasUndefined = S->isUndefined(); replaceSymbol(S, File, Name, Sym.getBinding(), Sym.st_other, Sym.getType(), Sym.st_value, Sym.st_size, Alignment, VerdefIndex); if (!WasInserted) { S->Binding = Binding; - if (!S->isWeak() && !Config->GcSections) + if (!S->isWeak() && !Config->GcSections && WasUndefined) File.IsNeeded = true; } } } Symbol *SymbolTable::addBitcode(StringRef Name, uint8_t Binding, uint8_t StOther, uint8_t Type, bool CanOmitFromDynSym, BitcodeFile &F) { Symbol *S; bool WasInserted; std::tie(S, WasInserted) = insert(Name, Type, getVisibility(StOther), CanOmitFromDynSym, &F); int Cmp = compareDefinedNonCommon(S, WasInserted, Binding, /*IsAbs*/ false, /*Value*/ 0, Name); if (Cmp > 0) replaceSymbol(S, &F, Name, Binding, StOther, Type, 0, 0, nullptr); else if (Cmp == 0) reportDuplicate(S, &F); return S; } Symbol *SymbolTable::find(StringRef Name) { auto It = SymMap.find(CachedHashStringRef(Name)); if (It == SymMap.end()) return nullptr; if (It->second == -1) return nullptr; return SymVector[It->second]; } template Symbol *SymbolTable::addLazyArchive(StringRef Name, ArchiveFile &F, const object::Archive::Symbol Sym) { Symbol *S; bool WasInserted; std::tie(S, WasInserted) = insert(Name); if (WasInserted) { replaceSymbol(S, F, Sym, Symbol::UnknownType); return S; } if (!S->isUndefined()) return S; // An undefined weak will not fetch archive members. See comment on Lazy in // Symbols.h for the details. if (S->isWeak()) { replaceSymbol(S, F, Sym, S->Type); S->Binding = STB_WEAK; return S; } std::pair MBInfo = F.getMember(&Sym); if (!MBInfo.first.getBuffer().empty()) addFile(createObjectFile(MBInfo.first, F.getName(), MBInfo.second)); return S; } template void SymbolTable::addLazyObject(StringRef Name, LazyObjFile &Obj) { Symbol *S; bool WasInserted; std::tie(S, WasInserted) = insert(Name); if (WasInserted) { replaceSymbol(S, Obj, Name, Symbol::UnknownType); return; } if (!S->isUndefined()) return; // See comment for addLazyArchive above. if (S->isWeak()) replaceSymbol(S, Obj, Name, S->Type); else if (InputFile *F = Obj.fetch()) addFile(F); } // If we already saw this symbol, force loading its file. template void SymbolTable::fetchIfLazy(StringRef Name) { if (Symbol *B = find(Name)) { // Mark the symbol not to be eliminated by LTO // even if it is a bitcode symbol. B->IsUsedInRegularObj = true; if (auto *L = dyn_cast(B)) if (InputFile *File = L->fetch()) addFile(File); } } // This function takes care of the case in which shared libraries depend on // the user program (not the other way, which is usual). Shared libraries // may have undefined symbols, expecting that the user program provides // the definitions for them. An example is BSD's __progname symbol. // We need to put such symbols to the main program's .dynsym so that // shared libraries can find them. // Except this, we ignore undefined symbols in DSOs. template void SymbolTable::scanShlibUndefined() { for (InputFile *F : SharedFiles) { for (StringRef U : cast>(F)->getUndefinedSymbols()) { Symbol *Sym = find(U); if (!Sym || !Sym->isDefined()) continue; Sym->ExportDynamic = true; // If -dynamic-list is given, the default version is set to // VER_NDX_LOCAL, which prevents a symbol to be exported via .dynsym. // Set to VER_NDX_GLOBAL so the symbol will be handled as if it were // specified by -dynamic-list. Sym->VersionId = VER_NDX_GLOBAL; } } } // Initialize DemangledSyms with a map from demangled symbols to symbol // objects. Used to handle "extern C++" directive in version scripts. // // The map will contain all demangled symbols. That can be very large, // and in LLD we generally want to avoid do anything for each symbol. // Then, why are we doing this? Here's why. // // Users can use "extern C++ {}" directive to match against demangled // C++ symbols. For example, you can write a pattern such as // "llvm::*::foo(int, ?)". Obviously, there's no way to handle this // other than trying to match a pattern against all demangled symbols. // So, if "extern C++" feature is used, we need to demangle all known // symbols. StringMap> &SymbolTable::getDemangledSyms() { if (!DemangledSyms) { DemangledSyms.emplace(); for (Symbol *Sym : SymVector) { if (!Sym->isDefined()) continue; if (Optional S = demangleItanium(Sym->getName())) (*DemangledSyms)[*S].push_back(Sym); else (*DemangledSyms)[Sym->getName()].push_back(Sym); } } return *DemangledSyms; } std::vector SymbolTable::findByVersion(SymbolVersion Ver) { if (Ver.IsExternCpp) return getDemangledSyms().lookup(Ver.Name); if (Symbol *B = find(Ver.Name)) if (B->isDefined()) return {B}; return {}; } std::vector SymbolTable::findAllByVersion(SymbolVersion Ver) { std::vector Res; StringMatcher M(Ver.Name); if (Ver.IsExternCpp) { for (auto &P : getDemangledSyms()) if (M.match(P.first())) Res.insert(Res.end(), P.second.begin(), P.second.end()); return Res; } for (Symbol *Sym : SymVector) if (Sym->isDefined() && M.match(Sym->getName())) Res.push_back(Sym); return Res; } // If there's only one anonymous version definition in a version // script file, the script does not actually define any symbol version, // but just specifies symbols visibilities. void SymbolTable::handleAnonymousVersion() { for (SymbolVersion &Ver : Config->VersionScriptGlobals) assignExactVersion(Ver, VER_NDX_GLOBAL, "global"); for (SymbolVersion &Ver : Config->VersionScriptGlobals) assignWildcardVersion(Ver, VER_NDX_GLOBAL); for (SymbolVersion &Ver : Config->VersionScriptLocals) assignExactVersion(Ver, VER_NDX_LOCAL, "local"); for (SymbolVersion &Ver : Config->VersionScriptLocals) assignWildcardVersion(Ver, VER_NDX_LOCAL); } // Handles -dynamic-list. void SymbolTable::handleDynamicList() { for (SymbolVersion &Ver : Config->DynamicList) { std::vector Syms; if (Ver.HasWildcard) Syms = findAllByVersion(Ver); else Syms = findByVersion(Ver); for (Symbol *B : Syms) { if (!Config->Shared) B->ExportDynamic = true; else if (B->includeInDynsym()) B->IsPreemptible = true; } } } // Set symbol versions to symbols. This function handles patterns // containing no wildcard characters. void SymbolTable::assignExactVersion(SymbolVersion Ver, uint16_t VersionId, StringRef VersionName) { if (Ver.HasWildcard) return; // Get a list of symbols which we need to assign the version to. std::vector Syms = findByVersion(Ver); if (Syms.empty()) { if (Config->NoUndefinedVersion) error("version script assignment of '" + VersionName + "' to symbol '" + Ver.Name + "' failed: symbol not defined"); return; } // Assign the version. for (Symbol *Sym : Syms) { // Skip symbols containing version info because symbol versions // specified by symbol names take precedence over version scripts. // See parseSymbolVersion(). if (Sym->getName().contains('@')) continue; if (Sym->InVersionScript) warn("duplicate symbol '" + Ver.Name + "' in version script"); Sym->VersionId = VersionId; Sym->InVersionScript = true; } } void SymbolTable::assignWildcardVersion(SymbolVersion Ver, uint16_t VersionId) { if (!Ver.HasWildcard) return; // Exact matching takes precendence over fuzzy matching, // so we set a version to a symbol only if no version has been assigned // to the symbol. This behavior is compatible with GNU. for (Symbol *B : findAllByVersion(Ver)) if (B->VersionId == Config->DefaultSymbolVersion) B->VersionId = VersionId; } // This function processes version scripts by updating VersionId // member of symbols. void SymbolTable::scanVersionScript() { // Handle edge cases first. handleAnonymousVersion(); handleDynamicList(); // Now we have version definitions, so we need to set version ids to symbols. // Each version definition has a glob pattern, and all symbols that match // with the pattern get that version. // First, we assign versions to exact matching symbols, // i.e. version definitions not containing any glob meta-characters. for (VersionDefinition &V : Config->VersionDefinitions) for (SymbolVersion &Ver : V.Globals) assignExactVersion(Ver, V.Id, V.Name); // Next, we assign versions to fuzzy matching symbols, // i.e. version definitions containing glob meta-characters. // Note that because the last match takes precedence over previous matches, // we iterate over the definitions in the reverse order. for (VersionDefinition &V : llvm::reverse(Config->VersionDefinitions)) for (SymbolVersion &Ver : V.Globals) assignWildcardVersion(Ver, V.Id); // Symbol themselves might know their versions because symbols // can contain versions in the form of @. // Let them parse and update their names to exclude version suffix. for (Symbol *Sym : SymVector) Sym->parseSymbolVersion(); } template void SymbolTable::addSymbolWrap(StringRef); template void SymbolTable::addSymbolWrap(StringRef); template void SymbolTable::addSymbolWrap(StringRef); template void SymbolTable::addSymbolWrap(StringRef); template Symbol *SymbolTable::addUndefined(StringRef); template Symbol *SymbolTable::addUndefined(StringRef); template Symbol *SymbolTable::addUndefined(StringRef); template Symbol *SymbolTable::addUndefined(StringRef); template Symbol *SymbolTable::addUndefined(StringRef, uint8_t, uint8_t, uint8_t, bool, InputFile *); template Symbol *SymbolTable::addUndefined(StringRef, uint8_t, uint8_t, uint8_t, bool, InputFile *); template Symbol *SymbolTable::addUndefined(StringRef, uint8_t, uint8_t, uint8_t, bool, InputFile *); template Symbol *SymbolTable::addUndefined(StringRef, uint8_t, uint8_t, uint8_t, bool, InputFile *); template void SymbolTable::addCombinedLTOObject(); template void SymbolTable::addCombinedLTOObject(); template void SymbolTable::addCombinedLTOObject(); template void SymbolTable::addCombinedLTOObject(); template Symbol * SymbolTable::addLazyArchive(StringRef, ArchiveFile &, const object::Archive::Symbol); template Symbol * SymbolTable::addLazyArchive(StringRef, ArchiveFile &, const object::Archive::Symbol); template Symbol * SymbolTable::addLazyArchive(StringRef, ArchiveFile &, const object::Archive::Symbol); template Symbol * SymbolTable::addLazyArchive(StringRef, ArchiveFile &, const object::Archive::Symbol); template void SymbolTable::addLazyObject(StringRef, LazyObjFile &); template void SymbolTable::addLazyObject(StringRef, LazyObjFile &); template void SymbolTable::addLazyObject(StringRef, LazyObjFile &); template void SymbolTable::addLazyObject(StringRef, LazyObjFile &); template void SymbolTable::addShared(StringRef, SharedFile &, const typename ELF32LE::Sym &, uint32_t Alignment, uint32_t); template void SymbolTable::addShared(StringRef, SharedFile &, const typename ELF32BE::Sym &, uint32_t Alignment, uint32_t); template void SymbolTable::addShared(StringRef, SharedFile &, const typename ELF64LE::Sym &, uint32_t Alignment, uint32_t); template void SymbolTable::addShared(StringRef, SharedFile &, const typename ELF64BE::Sym &, uint32_t Alignment, uint32_t); template void SymbolTable::fetchIfLazy(StringRef); template void SymbolTable::fetchIfLazy(StringRef); template void SymbolTable::fetchIfLazy(StringRef); template void SymbolTable::fetchIfLazy(StringRef); template void SymbolTable::scanShlibUndefined(); template void SymbolTable::scanShlibUndefined(); template void SymbolTable::scanShlibUndefined(); template void SymbolTable::scanShlibUndefined(); Index: vendor/lld/dist-release_60/ELF/SyntheticSections.cpp =================================================================== --- vendor/lld/dist-release_60/ELF/SyntheticSections.cpp (revision 328369) +++ vendor/lld/dist-release_60/ELF/SyntheticSections.cpp (revision 328370) @@ -1,2698 +1,2699 @@ //===- SyntheticSections.cpp ----------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains linker-synthesized sections. Currently, // synthetic sections are created either output sections or input sections, // but we are rewriting code so that all synthetic sections are created as // input sections. // //===----------------------------------------------------------------------===// #include "SyntheticSections.h" #include "Bits.h" #include "Config.h" #include "InputFiles.h" #include "LinkerScript.h" #include "OutputSections.h" #include "Strings.h" #include "SymbolTable.h" #include "Symbols.h" #include "Target.h" #include "Writer.h" #include "lld/Common/ErrorHandler.h" #include "lld/Common/Memory.h" #include "lld/Common/Threads.h" #include "lld/Common/Version.h" #include "llvm/BinaryFormat/Dwarf.h" #include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h" #include "llvm/Object/Decompressor.h" #include "llvm/Object/ELFObjectFile.h" #include "llvm/Support/Endian.h" #include "llvm/Support/LEB128.h" #include "llvm/Support/MD5.h" #include "llvm/Support/RandomNumberGenerator.h" #include "llvm/Support/SHA1.h" #include "llvm/Support/xxhash.h" #include #include using namespace llvm; using namespace llvm::dwarf; using namespace llvm::ELF; using namespace llvm::object; using namespace llvm::support; using namespace llvm::support::endian; using namespace lld; using namespace lld::elf; constexpr size_t MergeNoTailSection::NumShards; static void write32(void *Buf, uint32_t Val) { endian::write32(Buf, Val, Config->Endianness); } uint64_t SyntheticSection::getVA() const { if (OutputSection *Sec = getParent()) return Sec->Addr + OutSecOff; return 0; } // Returns an LLD version string. static ArrayRef getVersion() { // Check LLD_VERSION first for ease of testing. // You can get consitent output by using the environment variable. // This is only for testing. StringRef S = getenv("LLD_VERSION"); if (S.empty()) S = Saver.save(Twine("Linker: ") + getLLDVersion()); // +1 to include the terminating '\0'. return {(const uint8_t *)S.data(), S.size() + 1}; } // Creates a .comment section containing LLD version info. // With this feature, you can identify LLD-generated binaries easily // by "readelf --string-dump .comment ". // The returned object is a mergeable string section. MergeInputSection *elf::createCommentSection() { return make(SHF_MERGE | SHF_STRINGS, SHT_PROGBITS, 1, getVersion(), ".comment"); } // .MIPS.abiflags section. template MipsAbiFlagsSection::MipsAbiFlagsSection(Elf_Mips_ABIFlags Flags) : SyntheticSection(SHF_ALLOC, SHT_MIPS_ABIFLAGS, 8, ".MIPS.abiflags"), Flags(Flags) { this->Entsize = sizeof(Elf_Mips_ABIFlags); } template void MipsAbiFlagsSection::writeTo(uint8_t *Buf) { memcpy(Buf, &Flags, sizeof(Flags)); } template MipsAbiFlagsSection *MipsAbiFlagsSection::create() { Elf_Mips_ABIFlags Flags = {}; bool Create = false; for (InputSectionBase *Sec : InputSections) { if (Sec->Type != SHT_MIPS_ABIFLAGS) continue; Sec->Live = false; Create = true; std::string Filename = toString(Sec->File); const size_t Size = Sec->Data.size(); // Older version of BFD (such as the default FreeBSD linker) concatenate // .MIPS.abiflags instead of merging. To allow for this case (or potential // zero padding) we ignore everything after the first Elf_Mips_ABIFlags if (Size < sizeof(Elf_Mips_ABIFlags)) { error(Filename + ": invalid size of .MIPS.abiflags section: got " + Twine(Size) + " instead of " + Twine(sizeof(Elf_Mips_ABIFlags))); return nullptr; } auto *S = reinterpret_cast(Sec->Data.data()); if (S->version != 0) { error(Filename + ": unexpected .MIPS.abiflags version " + Twine(S->version)); return nullptr; } // LLD checks ISA compatibility in calcMipsEFlags(). Here we just // select the highest number of ISA/Rev/Ext. Flags.isa_level = std::max(Flags.isa_level, S->isa_level); Flags.isa_rev = std::max(Flags.isa_rev, S->isa_rev); Flags.isa_ext = std::max(Flags.isa_ext, S->isa_ext); Flags.gpr_size = std::max(Flags.gpr_size, S->gpr_size); Flags.cpr1_size = std::max(Flags.cpr1_size, S->cpr1_size); Flags.cpr2_size = std::max(Flags.cpr2_size, S->cpr2_size); Flags.ases |= S->ases; Flags.flags1 |= S->flags1; Flags.flags2 |= S->flags2; Flags.fp_abi = elf::getMipsFpAbiFlag(Flags.fp_abi, S->fp_abi, Filename); }; if (Create) return make>(Flags); return nullptr; } // .MIPS.options section. template MipsOptionsSection::MipsOptionsSection(Elf_Mips_RegInfo Reginfo) : SyntheticSection(SHF_ALLOC, SHT_MIPS_OPTIONS, 8, ".MIPS.options"), Reginfo(Reginfo) { this->Entsize = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo); } template void MipsOptionsSection::writeTo(uint8_t *Buf) { auto *Options = reinterpret_cast(Buf); Options->kind = ODK_REGINFO; Options->size = getSize(); if (!Config->Relocatable) Reginfo.ri_gp_value = InX::MipsGot->getGp(); memcpy(Buf + sizeof(Elf_Mips_Options), &Reginfo, sizeof(Reginfo)); } template MipsOptionsSection *MipsOptionsSection::create() { // N64 ABI only. if (!ELFT::Is64Bits) return nullptr; std::vector Sections; for (InputSectionBase *Sec : InputSections) if (Sec->Type == SHT_MIPS_OPTIONS) Sections.push_back(Sec); if (Sections.empty()) return nullptr; Elf_Mips_RegInfo Reginfo = {}; for (InputSectionBase *Sec : Sections) { Sec->Live = false; std::string Filename = toString(Sec->File); ArrayRef D = Sec->Data; while (!D.empty()) { if (D.size() < sizeof(Elf_Mips_Options)) { error(Filename + ": invalid size of .MIPS.options section"); break; } auto *Opt = reinterpret_cast(D.data()); if (Opt->kind == ODK_REGINFO) { if (Config->Relocatable && Opt->getRegInfo().ri_gp_value) error(Filename + ": unsupported non-zero ri_gp_value"); Reginfo.ri_gprmask |= Opt->getRegInfo().ri_gprmask; Sec->getFile()->MipsGp0 = Opt->getRegInfo().ri_gp_value; break; } if (!Opt->size) fatal(Filename + ": zero option descriptor size"); D = D.slice(Opt->size); } }; return make>(Reginfo); } // MIPS .reginfo section. template MipsReginfoSection::MipsReginfoSection(Elf_Mips_RegInfo Reginfo) : SyntheticSection(SHF_ALLOC, SHT_MIPS_REGINFO, 4, ".reginfo"), Reginfo(Reginfo) { this->Entsize = sizeof(Elf_Mips_RegInfo); } template void MipsReginfoSection::writeTo(uint8_t *Buf) { if (!Config->Relocatable) Reginfo.ri_gp_value = InX::MipsGot->getGp(); memcpy(Buf, &Reginfo, sizeof(Reginfo)); } template MipsReginfoSection *MipsReginfoSection::create() { // Section should be alive for O32 and N32 ABIs only. if (ELFT::Is64Bits) return nullptr; std::vector Sections; for (InputSectionBase *Sec : InputSections) if (Sec->Type == SHT_MIPS_REGINFO) Sections.push_back(Sec); if (Sections.empty()) return nullptr; Elf_Mips_RegInfo Reginfo = {}; for (InputSectionBase *Sec : Sections) { Sec->Live = false; if (Sec->Data.size() != sizeof(Elf_Mips_RegInfo)) { error(toString(Sec->File) + ": invalid size of .reginfo section"); return nullptr; } auto *R = reinterpret_cast(Sec->Data.data()); if (Config->Relocatable && R->ri_gp_value) error(toString(Sec->File) + ": unsupported non-zero ri_gp_value"); Reginfo.ri_gprmask |= R->ri_gprmask; Sec->getFile()->MipsGp0 = R->ri_gp_value; }; return make>(Reginfo); } InputSection *elf::createInterpSection() { // StringSaver guarantees that the returned string ends with '\0'. StringRef S = Saver.save(Config->DynamicLinker); ArrayRef Contents = {(const uint8_t *)S.data(), S.size() + 1}; auto *Sec = make(nullptr, SHF_ALLOC, SHT_PROGBITS, 1, Contents, ".interp"); Sec->Live = true; return Sec; } Symbol *elf::addSyntheticLocal(StringRef Name, uint8_t Type, uint64_t Value, uint64_t Size, InputSectionBase &Section) { auto *S = make(Section.File, Name, STB_LOCAL, STV_DEFAULT, Type, Value, Size, &Section); if (InX::SymTab) InX::SymTab->addSymbol(S); return S; } static size_t getHashSize() { switch (Config->BuildId) { case BuildIdKind::Fast: return 8; case BuildIdKind::Md5: case BuildIdKind::Uuid: return 16; case BuildIdKind::Sha1: return 20; case BuildIdKind::Hexstring: return Config->BuildIdVector.size(); default: llvm_unreachable("unknown BuildIdKind"); } } BuildIdSection::BuildIdSection() : SyntheticSection(SHF_ALLOC, SHT_NOTE, 4, ".note.gnu.build-id"), HashSize(getHashSize()) {} void BuildIdSection::writeTo(uint8_t *Buf) { write32(Buf, 4); // Name size write32(Buf + 4, HashSize); // Content size write32(Buf + 8, NT_GNU_BUILD_ID); // Type memcpy(Buf + 12, "GNU", 4); // Name string HashBuf = Buf + 16; } // Split one uint8 array into small pieces of uint8 arrays. static std::vector> split(ArrayRef Arr, size_t ChunkSize) { std::vector> Ret; while (Arr.size() > ChunkSize) { Ret.push_back(Arr.take_front(ChunkSize)); Arr = Arr.drop_front(ChunkSize); } if (!Arr.empty()) Ret.push_back(Arr); return Ret; } // Computes a hash value of Data using a given hash function. // In order to utilize multiple cores, we first split data into 1MB // chunks, compute a hash for each chunk, and then compute a hash value // of the hash values. void BuildIdSection::computeHash( llvm::ArrayRef Data, std::function Arr)> HashFn) { std::vector> Chunks = split(Data, 1024 * 1024); std::vector Hashes(Chunks.size() * HashSize); // Compute hash values. parallelForEachN(0, Chunks.size(), [&](size_t I) { HashFn(Hashes.data() + I * HashSize, Chunks[I]); }); // Write to the final output buffer. HashFn(HashBuf, Hashes); } BssSection::BssSection(StringRef Name, uint64_t Size, uint32_t Alignment) : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_NOBITS, Alignment, Name) { this->Bss = true; if (OutputSection *Sec = getParent()) Sec->Alignment = std::max(Sec->Alignment, Alignment); this->Size = Size; } void BuildIdSection::writeBuildId(ArrayRef Buf) { switch (Config->BuildId) { case BuildIdKind::Fast: computeHash(Buf, [](uint8_t *Dest, ArrayRef Arr) { write64le(Dest, xxHash64(toStringRef(Arr))); }); break; case BuildIdKind::Md5: computeHash(Buf, [](uint8_t *Dest, ArrayRef Arr) { memcpy(Dest, MD5::hash(Arr).data(), 16); }); break; case BuildIdKind::Sha1: computeHash(Buf, [](uint8_t *Dest, ArrayRef Arr) { memcpy(Dest, SHA1::hash(Arr).data(), 20); }); break; case BuildIdKind::Uuid: if (auto EC = getRandomBytes(HashBuf, HashSize)) error("entropy source failure: " + EC.message()); break; case BuildIdKind::Hexstring: memcpy(HashBuf, Config->BuildIdVector.data(), Config->BuildIdVector.size()); break; default: llvm_unreachable("unknown BuildIdKind"); } } EhFrameSection::EhFrameSection() : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame") {} // Search for an existing CIE record or create a new one. // CIE records from input object files are uniquified by their contents // and where their relocations point to. template CieRecord *EhFrameSection::addCie(EhSectionPiece &Cie, ArrayRef Rels) { auto *Sec = cast(Cie.Sec); if (read32(Cie.data().data() + 4, Config->Endianness) != 0) fatal(toString(Sec) + ": CIE expected at beginning of .eh_frame"); Symbol *Personality = nullptr; unsigned FirstRelI = Cie.FirstRelocation; if (FirstRelI != (unsigned)-1) Personality = &Sec->template getFile()->getRelocTargetSym(Rels[FirstRelI]); // Search for an existing CIE by CIE contents/relocation target pair. CieRecord *&Rec = CieMap[{Cie.data(), Personality}]; // If not found, create a new one. if (!Rec) { Rec = make(); Rec->Cie = &Cie; CieRecords.push_back(Rec); } return Rec; } // There is one FDE per function. Returns true if a given FDE // points to a live function. template bool EhFrameSection::isFdeLive(EhSectionPiece &Fde, ArrayRef Rels) { auto *Sec = cast(Fde.Sec); unsigned FirstRelI = Fde.FirstRelocation; // An FDE should point to some function because FDEs are to describe // functions. That's however not always the case due to an issue of // ld.gold with -r. ld.gold may discard only functions and leave their // corresponding FDEs, which results in creating bad .eh_frame sections. // To deal with that, we ignore such FDEs. if (FirstRelI == (unsigned)-1) return false; const RelTy &Rel = Rels[FirstRelI]; Symbol &B = Sec->template getFile()->getRelocTargetSym(Rel); // FDEs for garbage-collected or merged-by-ICF sections are dead. if (auto *D = dyn_cast(&B)) if (SectionBase *Sec = D->Section) return Sec->Live; return false; } // .eh_frame is a sequence of CIE or FDE records. In general, there // is one CIE record per input object file which is followed by // a list of FDEs. This function searches an existing CIE or create a new // one and associates FDEs to the CIE. template void EhFrameSection::addSectionAux(EhInputSection *Sec, ArrayRef Rels) { DenseMap OffsetToCie; for (EhSectionPiece &Piece : Sec->Pieces) { // The empty record is the end marker. if (Piece.Size == 4) return; size_t Offset = Piece.InputOff; uint32_t ID = read32(Piece.data().data() + 4, Config->Endianness); if (ID == 0) { OffsetToCie[Offset] = addCie(Piece, Rels); continue; } uint32_t CieOffset = Offset + 4 - ID; CieRecord *Rec = OffsetToCie[CieOffset]; if (!Rec) fatal(toString(Sec) + ": invalid CIE reference"); if (!isFdeLive(Piece, Rels)) continue; Rec->Fdes.push_back(&Piece); NumFdes++; } } template void EhFrameSection::addSection(InputSectionBase *C) { auto *Sec = cast(C); Sec->Parent = this; Alignment = std::max(Alignment, Sec->Alignment); Sections.push_back(Sec); for (auto *DS : Sec->DependentSections) DependentSections.push_back(DS); // .eh_frame is a sequence of CIE or FDE records. This function // splits it into pieces so that we can call // SplitInputSection::getSectionPiece on the section. Sec->split(); if (Sec->Pieces.empty()) return; if (Sec->AreRelocsRela) addSectionAux(Sec, Sec->template relas()); else addSectionAux(Sec, Sec->template rels()); } static void writeCieFde(uint8_t *Buf, ArrayRef D) { memcpy(Buf, D.data(), D.size()); size_t Aligned = alignTo(D.size(), Config->Wordsize); // Zero-clear trailing padding if it exists. memset(Buf + D.size(), 0, Aligned - D.size()); // Fix the size field. -4 since size does not include the size field itself. write32(Buf, Aligned - 4); } void EhFrameSection::finalizeContents() { if (this->Size) return; // Already finalized. size_t Off = 0; for (CieRecord *Rec : CieRecords) { Rec->Cie->OutputOff = Off; Off += alignTo(Rec->Cie->Size, Config->Wordsize); for (EhSectionPiece *Fde : Rec->Fdes) { Fde->OutputOff = Off; Off += alignTo(Fde->Size, Config->Wordsize); } } // The LSB standard does not allow a .eh_frame section with zero // Call Frame Information records. Therefore add a CIE record length // 0 as a terminator if this .eh_frame section is empty. if (Off == 0) Off = 4; this->Size = Off; } // Returns data for .eh_frame_hdr. .eh_frame_hdr is a binary search table // to get an FDE from an address to which FDE is applied. This function // returns a list of such pairs. std::vector EhFrameSection::getFdeData() const { uint8_t *Buf = getParent()->Loc + OutSecOff; std::vector Ret; for (CieRecord *Rec : CieRecords) { uint8_t Enc = getFdeEncoding(Rec->Cie); for (EhSectionPiece *Fde : Rec->Fdes) { uint32_t Pc = getFdePc(Buf, Fde->OutputOff, Enc); uint32_t FdeVA = getParent()->Addr + Fde->OutputOff; Ret.push_back({Pc, FdeVA}); } } return Ret; } static uint64_t readFdeAddr(uint8_t *Buf, int Size) { switch (Size) { case DW_EH_PE_udata2: return read16(Buf, Config->Endianness); case DW_EH_PE_udata4: return read32(Buf, Config->Endianness); case DW_EH_PE_udata8: return read64(Buf, Config->Endianness); case DW_EH_PE_absptr: return readUint(Buf); } fatal("unknown FDE size encoding"); } // Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to. // We need it to create .eh_frame_hdr section. uint64_t EhFrameSection::getFdePc(uint8_t *Buf, size_t FdeOff, uint8_t Enc) const { // The starting address to which this FDE applies is // stored at FDE + 8 byte. size_t Off = FdeOff + 8; uint64_t Addr = readFdeAddr(Buf + Off, Enc & 0x7); if ((Enc & 0x70) == DW_EH_PE_absptr) return Addr; if ((Enc & 0x70) == DW_EH_PE_pcrel) return Addr + getParent()->Addr + Off; fatal("unknown FDE size relative encoding"); } void EhFrameSection::writeTo(uint8_t *Buf) { // Write CIE and FDE records. for (CieRecord *Rec : CieRecords) { size_t CieOffset = Rec->Cie->OutputOff; writeCieFde(Buf + CieOffset, Rec->Cie->data()); for (EhSectionPiece *Fde : Rec->Fdes) { size_t Off = Fde->OutputOff; writeCieFde(Buf + Off, Fde->data()); // FDE's second word should have the offset to an associated CIE. // Write it. write32(Buf + Off + 4, Off + 4 - CieOffset); } } // Apply relocations. .eh_frame section contents are not contiguous // in the output buffer, but relocateAlloc() still works because // getOffset() takes care of discontiguous section pieces. for (EhInputSection *S : Sections) S->relocateAlloc(Buf, nullptr); } GotSection::GotSection() : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, Target->GotEntrySize, ".got") {} void GotSection::addEntry(Symbol &Sym) { Sym.GotIndex = NumEntries; ++NumEntries; } bool GotSection::addDynTlsEntry(Symbol &Sym) { if (Sym.GlobalDynIndex != -1U) return false; Sym.GlobalDynIndex = NumEntries; // Global Dynamic TLS entries take two GOT slots. NumEntries += 2; return true; } // Reserves TLS entries for a TLS module ID and a TLS block offset. // In total it takes two GOT slots. bool GotSection::addTlsIndex() { if (TlsIndexOff != uint32_t(-1)) return false; TlsIndexOff = NumEntries * Config->Wordsize; NumEntries += 2; return true; } uint64_t GotSection::getGlobalDynAddr(const Symbol &B) const { return this->getVA() + B.GlobalDynIndex * Config->Wordsize; } uint64_t GotSection::getGlobalDynOffset(const Symbol &B) const { return B.GlobalDynIndex * Config->Wordsize; } void GotSection::finalizeContents() { Size = NumEntries * Config->Wordsize; } bool GotSection::empty() const { // We need to emit a GOT even if it's empty if there's a relocation that is // relative to GOT(such as GOTOFFREL) or there's a symbol that points to a GOT // (i.e. _GLOBAL_OFFSET_TABLE_). return NumEntries == 0 && !HasGotOffRel && !ElfSym::GlobalOffsetTable; } void GotSection::writeTo(uint8_t *Buf) { // Buf points to the start of this section's buffer, // whereas InputSectionBase::relocateAlloc() expects its argument // to point to the start of the output section. relocateAlloc(Buf - OutSecOff, Buf - OutSecOff + Size); } MipsGotSection::MipsGotSection() : SyntheticSection(SHF_ALLOC | SHF_WRITE | SHF_MIPS_GPREL, SHT_PROGBITS, 16, ".got") {} void MipsGotSection::addEntry(Symbol &Sym, int64_t Addend, RelExpr Expr) { // For "true" local symbols which can be referenced from the same module // only compiler creates two instructions for address loading: // // lw $8, 0($gp) # R_MIPS_GOT16 // addi $8, $8, 0 # R_MIPS_LO16 // // The first instruction loads high 16 bits of the symbol address while // the second adds an offset. That allows to reduce number of required // GOT entries because only one global offset table entry is necessary // for every 64 KBytes of local data. So for local symbols we need to // allocate number of GOT entries to hold all required "page" addresses. // // All global symbols (hidden and regular) considered by compiler uniformly. // It always generates a single `lw` instruction and R_MIPS_GOT16 relocation // to load address of the symbol. So for each such symbol we need to // allocate dedicated GOT entry to store its address. // // If a symbol is preemptible we need help of dynamic linker to get its // final address. The corresponding GOT entries are allocated in the // "global" part of GOT. Entries for non preemptible global symbol allocated // in the "local" part of GOT. // // See "Global Offset Table" in Chapter 5: // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf if (Expr == R_MIPS_GOT_LOCAL_PAGE) { // At this point we do not know final symbol value so to reduce number // of allocated GOT entries do the following trick. Save all output // sections referenced by GOT relocations. Then later in the `finalize` // method calculate number of "pages" required to cover all saved output // section and allocate appropriate number of GOT entries. PageIndexMap.insert({Sym.getOutputSection(), 0}); return; } if (Sym.isTls()) { // GOT entries created for MIPS TLS relocations behave like // almost GOT entries from other ABIs. They go to the end // of the global offset table. Sym.GotIndex = TlsEntries.size(); TlsEntries.push_back(&Sym); return; } auto AddEntry = [&](Symbol &S, uint64_t A, GotEntries &Items) { if (S.isInGot() && !A) return; size_t NewIndex = Items.size(); if (!EntryIndexMap.insert({{&S, A}, NewIndex}).second) return; Items.emplace_back(&S, A); if (!A) S.GotIndex = NewIndex; }; if (Sym.IsPreemptible) { // Ignore addends for preemptible symbols. They got single GOT entry anyway. AddEntry(Sym, 0, GlobalEntries); Sym.IsInGlobalMipsGot = true; } else if (Expr == R_MIPS_GOT_OFF32) { AddEntry(Sym, Addend, LocalEntries32); Sym.Is32BitMipsGot = true; } else { // Hold local GOT entries accessed via a 16-bit index separately. // That allows to write them in the beginning of the GOT and keep // their indexes as less as possible to escape relocation's overflow. AddEntry(Sym, Addend, LocalEntries); } } bool MipsGotSection::addDynTlsEntry(Symbol &Sym) { if (Sym.GlobalDynIndex != -1U) return false; Sym.GlobalDynIndex = TlsEntries.size(); // Global Dynamic TLS entries take two GOT slots. TlsEntries.push_back(nullptr); TlsEntries.push_back(&Sym); return true; } // Reserves TLS entries for a TLS module ID and a TLS block offset. // In total it takes two GOT slots. bool MipsGotSection::addTlsIndex() { if (TlsIndexOff != uint32_t(-1)) return false; TlsIndexOff = TlsEntries.size() * Config->Wordsize; TlsEntries.push_back(nullptr); TlsEntries.push_back(nullptr); return true; } static uint64_t getMipsPageAddr(uint64_t Addr) { return (Addr + 0x8000) & ~0xffff; } static uint64_t getMipsPageCount(uint64_t Size) { return (Size + 0xfffe) / 0xffff + 1; } uint64_t MipsGotSection::getPageEntryOffset(const Symbol &B, int64_t Addend) const { const OutputSection *OutSec = B.getOutputSection(); uint64_t SecAddr = getMipsPageAddr(OutSec->Addr); uint64_t SymAddr = getMipsPageAddr(B.getVA(Addend)); uint64_t Index = PageIndexMap.lookup(OutSec) + (SymAddr - SecAddr) / 0xffff; assert(Index < PageEntriesNum); return (HeaderEntriesNum + Index) * Config->Wordsize; } uint64_t MipsGotSection::getSymEntryOffset(const Symbol &B, int64_t Addend) const { // Calculate offset of the GOT entries block: TLS, global, local. uint64_t Index = HeaderEntriesNum + PageEntriesNum; if (B.isTls()) Index += LocalEntries.size() + LocalEntries32.size() + GlobalEntries.size(); else if (B.IsInGlobalMipsGot) Index += LocalEntries.size() + LocalEntries32.size(); else if (B.Is32BitMipsGot) Index += LocalEntries.size(); // Calculate offset of the GOT entry in the block. if (B.isInGot()) Index += B.GotIndex; else { auto It = EntryIndexMap.find({&B, Addend}); assert(It != EntryIndexMap.end()); Index += It->second; } return Index * Config->Wordsize; } uint64_t MipsGotSection::getTlsOffset() const { return (getLocalEntriesNum() + GlobalEntries.size()) * Config->Wordsize; } uint64_t MipsGotSection::getGlobalDynOffset(const Symbol &B) const { return B.GlobalDynIndex * Config->Wordsize; } const Symbol *MipsGotSection::getFirstGlobalEntry() const { return GlobalEntries.empty() ? nullptr : GlobalEntries.front().first; } unsigned MipsGotSection::getLocalEntriesNum() const { return HeaderEntriesNum + PageEntriesNum + LocalEntries.size() + LocalEntries32.size(); } void MipsGotSection::finalizeContents() { updateAllocSize(); } bool MipsGotSection::updateAllocSize() { PageEntriesNum = 0; for (std::pair &P : PageIndexMap) { // For each output section referenced by GOT page relocations calculate // and save into PageIndexMap an upper bound of MIPS GOT entries required // to store page addresses of local symbols. We assume the worst case - // each 64kb page of the output section has at least one GOT relocation // against it. And take in account the case when the section intersects // page boundaries. P.second = PageEntriesNum; PageEntriesNum += getMipsPageCount(P.first->Size); } Size = (getLocalEntriesNum() + GlobalEntries.size() + TlsEntries.size()) * Config->Wordsize; return false; } bool MipsGotSection::empty() const { // We add the .got section to the result for dynamic MIPS target because // its address and properties are mentioned in the .dynamic section. return Config->Relocatable; } uint64_t MipsGotSection::getGp() const { return ElfSym::MipsGp->getVA(0); } void MipsGotSection::writeTo(uint8_t *Buf) { // Set the MSB of the second GOT slot. This is not required by any // MIPS ABI documentation, though. // // There is a comment in glibc saying that "The MSB of got[1] of a // gnu object is set to identify gnu objects," and in GNU gold it // says "the second entry will be used by some runtime loaders". // But how this field is being used is unclear. // // We are not really willing to mimic other linkers behaviors // without understanding why they do that, but because all files // generated by GNU tools have this special GOT value, and because // we've been doing this for years, it is probably a safe bet to // keep doing this for now. We really need to revisit this to see // if we had to do this. writeUint(Buf + Config->Wordsize, (uint64_t)1 << (Config->Wordsize * 8 - 1)); Buf += HeaderEntriesNum * Config->Wordsize; // Write 'page address' entries to the local part of the GOT. for (std::pair &L : PageIndexMap) { size_t PageCount = getMipsPageCount(L.first->Size); uint64_t FirstPageAddr = getMipsPageAddr(L.first->Addr); for (size_t PI = 0; PI < PageCount; ++PI) { uint8_t *Entry = Buf + (L.second + PI) * Config->Wordsize; writeUint(Entry, FirstPageAddr + PI * 0x10000); } } Buf += PageEntriesNum * Config->Wordsize; auto AddEntry = [&](const GotEntry &SA) { uint8_t *Entry = Buf; Buf += Config->Wordsize; const Symbol *Sym = SA.first; uint64_t VA = Sym->getVA(SA.second); if (Sym->StOther & STO_MIPS_MICROMIPS) VA |= 1; writeUint(Entry, VA); }; std::for_each(std::begin(LocalEntries), std::end(LocalEntries), AddEntry); std::for_each(std::begin(LocalEntries32), std::end(LocalEntries32), AddEntry); std::for_each(std::begin(GlobalEntries), std::end(GlobalEntries), AddEntry); // Initialize TLS-related GOT entries. If the entry has a corresponding // dynamic relocations, leave it initialized by zero. Write down adjusted // TLS symbol's values otherwise. To calculate the adjustments use offsets // for thread-local storage. // https://www.linux-mips.org/wiki/NPTL if (TlsIndexOff != -1U && !Config->Pic) writeUint(Buf + TlsIndexOff, 1); for (const Symbol *B : TlsEntries) { if (!B || B->IsPreemptible) continue; uint64_t VA = B->getVA(); if (B->GotIndex != -1U) { uint8_t *Entry = Buf + B->GotIndex * Config->Wordsize; writeUint(Entry, VA - 0x7000); } if (B->GlobalDynIndex != -1U) { uint8_t *Entry = Buf + B->GlobalDynIndex * Config->Wordsize; writeUint(Entry, 1); Entry += Config->Wordsize; writeUint(Entry, VA - 0x8000); } } } GotPltSection::GotPltSection() : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, Target->GotPltEntrySize, ".got.plt") {} void GotPltSection::addEntry(Symbol &Sym) { Sym.GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size(); Entries.push_back(&Sym); } size_t GotPltSection::getSize() const { return (Target->GotPltHeaderEntriesNum + Entries.size()) * Target->GotPltEntrySize; } void GotPltSection::writeTo(uint8_t *Buf) { Target->writeGotPltHeader(Buf); Buf += Target->GotPltHeaderEntriesNum * Target->GotPltEntrySize; for (const Symbol *B : Entries) { Target->writeGotPlt(Buf, *B); Buf += Config->Wordsize; } } // On ARM the IgotPltSection is part of the GotSection, on other Targets it is // part of the .got.plt IgotPltSection::IgotPltSection() : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, Target->GotPltEntrySize, Config->EMachine == EM_ARM ? ".got" : ".got.plt") {} void IgotPltSection::addEntry(Symbol &Sym) { Sym.IsInIgot = true; Sym.GotPltIndex = Entries.size(); Entries.push_back(&Sym); } size_t IgotPltSection::getSize() const { return Entries.size() * Target->GotPltEntrySize; } void IgotPltSection::writeTo(uint8_t *Buf) { for (const Symbol *B : Entries) { Target->writeIgotPlt(Buf, *B); Buf += Config->Wordsize; } } StringTableSection::StringTableSection(StringRef Name, bool Dynamic) : SyntheticSection(Dynamic ? (uint64_t)SHF_ALLOC : 0, SHT_STRTAB, 1, Name), Dynamic(Dynamic) { // ELF string tables start with a NUL byte. addString(""); } // Adds a string to the string table. If HashIt is true we hash and check for // duplicates. It is optional because the name of global symbols are already // uniqued and hashing them again has a big cost for a small value: uniquing // them with some other string that happens to be the same. unsigned StringTableSection::addString(StringRef S, bool HashIt) { if (HashIt) { auto R = StringMap.insert(std::make_pair(S, this->Size)); if (!R.second) return R.first->second; } unsigned Ret = this->Size; this->Size = this->Size + S.size() + 1; Strings.push_back(S); return Ret; } void StringTableSection::writeTo(uint8_t *Buf) { for (StringRef S : Strings) { memcpy(Buf, S.data(), S.size()); Buf[S.size()] = '\0'; Buf += S.size() + 1; } } // Returns the number of version definition entries. Because the first entry // is for the version definition itself, it is the number of versioned symbols // plus one. Note that we don't support multiple versions yet. static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; } template DynamicSection::DynamicSection() : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_DYNAMIC, Config->Wordsize, ".dynamic") { this->Entsize = ELFT::Is64Bits ? 16 : 8; // .dynamic section is not writable on MIPS and on Fuchsia OS // which passes -z rodynamic. // See "Special Section" in Chapter 4 in the following document: // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf if (Config->EMachine == EM_MIPS || Config->ZRodynamic) this->Flags = SHF_ALLOC; // Add strings to .dynstr early so that .dynstr's size will be // fixed early. for (StringRef S : Config->FilterList) addInt(DT_FILTER, InX::DynStrTab->addString(S)); for (StringRef S : Config->AuxiliaryList) addInt(DT_AUXILIARY, InX::DynStrTab->addString(S)); if (!Config->Rpath.empty()) addInt(Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH, InX::DynStrTab->addString(Config->Rpath)); for (InputFile *File : SharedFiles) { SharedFile *F = cast>(File); if (F->IsNeeded) addInt(DT_NEEDED, InX::DynStrTab->addString(F->SoName)); } if (!Config->SoName.empty()) addInt(DT_SONAME, InX::DynStrTab->addString(Config->SoName)); } template void DynamicSection::add(int32_t Tag, std::function Fn) { Entries.push_back({Tag, Fn}); } template void DynamicSection::addInt(int32_t Tag, uint64_t Val) { Entries.push_back({Tag, [=] { return Val; }}); } template void DynamicSection::addInSec(int32_t Tag, InputSection *Sec) { Entries.push_back( {Tag, [=] { return Sec->getParent()->Addr + Sec->OutSecOff; }}); } template void DynamicSection::addOutSec(int32_t Tag, OutputSection *Sec) { Entries.push_back({Tag, [=] { return Sec->Addr; }}); } template void DynamicSection::addSize(int32_t Tag, OutputSection *Sec) { Entries.push_back({Tag, [=] { return Sec->Size; }}); } template void DynamicSection::addSym(int32_t Tag, Symbol *Sym) { Entries.push_back({Tag, [=] { return Sym->getVA(); }}); } // Add remaining entries to complete .dynamic contents. template void DynamicSection::finalizeContents() { if (this->Size) return; // Already finalized. // Set DT_FLAGS and DT_FLAGS_1. uint32_t DtFlags = 0; uint32_t DtFlags1 = 0; if (Config->Bsymbolic) DtFlags |= DF_SYMBOLIC; if (Config->ZNodelete) DtFlags1 |= DF_1_NODELETE; if (Config->ZNodlopen) DtFlags1 |= DF_1_NOOPEN; if (Config->ZNow) { DtFlags |= DF_BIND_NOW; DtFlags1 |= DF_1_NOW; } if (Config->ZOrigin) { DtFlags |= DF_ORIGIN; DtFlags1 |= DF_1_ORIGIN; } if (DtFlags) addInt(DT_FLAGS, DtFlags); if (DtFlags1) addInt(DT_FLAGS_1, DtFlags1); // DT_DEBUG is a pointer to debug informaion used by debuggers at runtime. We // need it for each process, so we don't write it for DSOs. The loader writes // the pointer into this entry. // // DT_DEBUG is the only .dynamic entry that needs to be written to. Some // systems (currently only Fuchsia OS) provide other means to give the // debugger this information. Such systems may choose make .dynamic read-only. // If the target is such a system (used -z rodynamic) don't write DT_DEBUG. if (!Config->Shared && !Config->Relocatable && !Config->ZRodynamic) addInt(DT_DEBUG, 0); this->Link = InX::DynStrTab->getParent()->SectionIndex; if (!InX::RelaDyn->empty()) { addInSec(InX::RelaDyn->DynamicTag, InX::RelaDyn); addSize(InX::RelaDyn->SizeDynamicTag, InX::RelaDyn->getParent()); bool IsRela = Config->IsRela; addInt(IsRela ? DT_RELAENT : DT_RELENT, IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel)); // MIPS dynamic loader does not support RELCOUNT tag. // The problem is in the tight relation between dynamic // relocations and GOT. So do not emit this tag on MIPS. if (Config->EMachine != EM_MIPS) { size_t NumRelativeRels = InX::RelaDyn->getRelativeRelocCount(); if (Config->ZCombreloc && NumRelativeRels) addInt(IsRela ? DT_RELACOUNT : DT_RELCOUNT, NumRelativeRels); } } // .rel[a].plt section usually consists of two parts, containing plt and // iplt relocations. It is possible to have only iplt relocations in the // output. In that case RelaPlt is empty and have zero offset, the same offset // as RelaIplt have. And we still want to emit proper dynamic tags for that // case, so here we always use RelaPlt as marker for the begining of // .rel[a].plt section. if (InX::RelaPlt->getParent()->Live) { addInSec(DT_JMPREL, InX::RelaPlt); addSize(DT_PLTRELSZ, InX::RelaPlt->getParent()); switch (Config->EMachine) { case EM_MIPS: addInSec(DT_MIPS_PLTGOT, InX::GotPlt); break; case EM_SPARCV9: addInSec(DT_PLTGOT, InX::Plt); break; default: addInSec(DT_PLTGOT, InX::GotPlt); break; } addInt(DT_PLTREL, Config->IsRela ? DT_RELA : DT_REL); } addInSec(DT_SYMTAB, InX::DynSymTab); addInt(DT_SYMENT, sizeof(Elf_Sym)); addInSec(DT_STRTAB, InX::DynStrTab); addInt(DT_STRSZ, InX::DynStrTab->getSize()); if (!Config->ZText) addInt(DT_TEXTREL, 0); if (InX::GnuHashTab) addInSec(DT_GNU_HASH, InX::GnuHashTab); if (InX::HashTab) addInSec(DT_HASH, InX::HashTab); if (Out::PreinitArray) { addOutSec(DT_PREINIT_ARRAY, Out::PreinitArray); addSize(DT_PREINIT_ARRAYSZ, Out::PreinitArray); } if (Out::InitArray) { addOutSec(DT_INIT_ARRAY, Out::InitArray); addSize(DT_INIT_ARRAYSZ, Out::InitArray); } if (Out::FiniArray) { addOutSec(DT_FINI_ARRAY, Out::FiniArray); addSize(DT_FINI_ARRAYSZ, Out::FiniArray); } if (Symbol *B = Symtab->find(Config->Init)) if (B->isDefined()) addSym(DT_INIT, B); if (Symbol *B = Symtab->find(Config->Fini)) if (B->isDefined()) addSym(DT_FINI, B); bool HasVerNeed = In::VerNeed->getNeedNum() != 0; if (HasVerNeed || In::VerDef) addInSec(DT_VERSYM, In::VerSym); if (In::VerDef) { addInSec(DT_VERDEF, In::VerDef); addInt(DT_VERDEFNUM, getVerDefNum()); } if (HasVerNeed) { addInSec(DT_VERNEED, In::VerNeed); addInt(DT_VERNEEDNUM, In::VerNeed->getNeedNum()); } if (Config->EMachine == EM_MIPS) { addInt(DT_MIPS_RLD_VERSION, 1); addInt(DT_MIPS_FLAGS, RHF_NOTPOT); addInt(DT_MIPS_BASE_ADDRESS, Target->getImageBase()); addInt(DT_MIPS_SYMTABNO, InX::DynSymTab->getNumSymbols()); add(DT_MIPS_LOCAL_GOTNO, [] { return InX::MipsGot->getLocalEntriesNum(); }); if (const Symbol *B = InX::MipsGot->getFirstGlobalEntry()) addInt(DT_MIPS_GOTSYM, B->DynsymIndex); else addInt(DT_MIPS_GOTSYM, InX::DynSymTab->getNumSymbols()); addInSec(DT_PLTGOT, InX::MipsGot); if (InX::MipsRldMap) addInSec(DT_MIPS_RLD_MAP, InX::MipsRldMap); } addInt(DT_NULL, 0); getParent()->Link = this->Link; this->Size = Entries.size() * this->Entsize; } template void DynamicSection::writeTo(uint8_t *Buf) { auto *P = reinterpret_cast(Buf); for (std::pair> &KV : Entries) { P->d_tag = KV.first; P->d_un.d_val = KV.second(); ++P; } } uint64_t DynamicReloc::getOffset() const { return InputSec->getOutputSection()->Addr + InputSec->getOffset(OffsetInSec); } int64_t DynamicReloc::getAddend() const { if (UseSymVA) return Sym->getVA(Addend); return Addend; } uint32_t DynamicReloc::getSymIndex() const { if (Sym && !UseSymVA) return Sym->DynsymIndex; return 0; } RelocationBaseSection::RelocationBaseSection(StringRef Name, uint32_t Type, int32_t DynamicTag, int32_t SizeDynamicTag) : SyntheticSection(SHF_ALLOC, Type, Config->Wordsize, Name), DynamicTag(DynamicTag), SizeDynamicTag(SizeDynamicTag) {} void RelocationBaseSection::addReloc(const DynamicReloc &Reloc) { if (Reloc.Type == Target->RelativeRel) ++NumRelativeRelocs; Relocs.push_back(Reloc); } void RelocationBaseSection::finalizeContents() { // If all relocations are R_*_RELATIVE they don't refer to any // dynamic symbol and we don't need a dynamic symbol table. If that // is the case, just use 0 as the link. Link = InX::DynSymTab ? InX::DynSymTab->getParent()->SectionIndex : 0; // Set required output section properties. getParent()->Link = Link; } template static void encodeDynamicReloc(typename ELFT::Rela *P, const DynamicReloc &Rel) { if (Config->IsRela) P->r_addend = Rel.getAddend(); P->r_offset = Rel.getOffset(); if (Config->EMachine == EM_MIPS && Rel.getInputSec() == InX::MipsGot) // The MIPS GOT section contains dynamic relocations that correspond to TLS // entries. These entries are placed after the global and local sections of // the GOT. At the point when we create these relocations, the size of the // global and local sections is unknown, so the offset that we store in the // TLS entry's DynamicReloc is relative to the start of the TLS section of // the GOT, rather than being relative to the start of the GOT. This line of // code adds the size of the global and local sections to the virtual // address computed by getOffset() in order to adjust it into the TLS // section. P->r_offset += InX::MipsGot->getTlsOffset(); P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->IsMips64EL); } template RelocationSection::RelocationSection(StringRef Name, bool Sort) : RelocationBaseSection(Name, Config->IsRela ? SHT_RELA : SHT_REL, Config->IsRela ? DT_RELA : DT_REL, Config->IsRela ? DT_RELASZ : DT_RELSZ), Sort(Sort) { this->Entsize = Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel); } template static bool compRelocations(const RelTy &A, const RelTy &B) { bool AIsRel = A.getType(Config->IsMips64EL) == Target->RelativeRel; bool BIsRel = B.getType(Config->IsMips64EL) == Target->RelativeRel; if (AIsRel != BIsRel) return AIsRel; return A.getSymbol(Config->IsMips64EL) < B.getSymbol(Config->IsMips64EL); } template void RelocationSection::writeTo(uint8_t *Buf) { uint8_t *BufBegin = Buf; for (const DynamicReloc &Rel : Relocs) { encodeDynamicReloc(reinterpret_cast(Buf), Rel); Buf += Config->IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel); } if (Sort) { if (Config->IsRela) std::stable_sort((Elf_Rela *)BufBegin, (Elf_Rela *)BufBegin + Relocs.size(), compRelocations); else std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(), compRelocations); } } template unsigned RelocationSection::getRelocOffset() { return this->Entsize * Relocs.size(); } template AndroidPackedRelocationSection::AndroidPackedRelocationSection( StringRef Name) : RelocationBaseSection( Name, Config->IsRela ? SHT_ANDROID_RELA : SHT_ANDROID_REL, Config->IsRela ? DT_ANDROID_RELA : DT_ANDROID_REL, Config->IsRela ? DT_ANDROID_RELASZ : DT_ANDROID_RELSZ) { this->Entsize = 1; } template bool AndroidPackedRelocationSection::updateAllocSize() { // This function computes the contents of an Android-format packed relocation // section. // // This format compresses relocations by using relocation groups to factor out // fields that are common between relocations and storing deltas from previous // relocations in SLEB128 format (which has a short representation for small // numbers). A good example of a relocation type with common fields is // R_*_RELATIVE, which is normally used to represent function pointers in // vtables. In the REL format, each relative relocation has the same r_info // field, and is only different from other relative relocations in terms of // the r_offset field. By sorting relocations by offset, grouping them by // r_info and representing each relocation with only the delta from the // previous offset, each 8-byte relocation can be compressed to as little as 1 // byte (or less with run-length encoding). This relocation packer was able to // reduce the size of the relocation section in an Android Chromium DSO from // 2,911,184 bytes to 174,693 bytes, or 6% of the original size. // // A relocation section consists of a header containing the literal bytes // 'APS2' followed by a sequence of SLEB128-encoded integers. The first two // elements are the total number of relocations in the section and an initial // r_offset value. The remaining elements define a sequence of relocation // groups. Each relocation group starts with a header consisting of the // following elements: // // - the number of relocations in the relocation group // - flags for the relocation group // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is set) the r_offset delta // for each relocation in the group. // - (if RELOCATION_GROUPED_BY_INFO_FLAG is set) the value of the r_info // field for each relocation in the group. // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG and // RELOCATION_GROUPED_BY_ADDEND_FLAG are set) the r_addend delta for // each relocation in the group. // // Following the relocation group header are descriptions of each of the // relocations in the group. They consist of the following elements: // // - (if RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG is not set) the r_offset // delta for this relocation. // - (if RELOCATION_GROUPED_BY_INFO_FLAG is not set) the value of the r_info // field for this relocation. // - (if RELOCATION_GROUP_HAS_ADDEND_FLAG is set and // RELOCATION_GROUPED_BY_ADDEND_FLAG is not set) the r_addend delta for // this relocation. size_t OldSize = RelocData.size(); RelocData = {'A', 'P', 'S', '2'}; raw_svector_ostream OS(RelocData); auto Add = [&](int64_t V) { encodeSLEB128(V, OS); }; // The format header includes the number of relocations and the initial // offset (we set this to zero because the first relocation group will // perform the initial adjustment). Add(Relocs.size()); Add(0); std::vector Relatives, NonRelatives; for (const DynamicReloc &Rel : Relocs) { Elf_Rela R; encodeDynamicReloc(&R, Rel); if (R.getType(Config->IsMips64EL) == Target->RelativeRel) Relatives.push_back(R); else NonRelatives.push_back(R); } std::sort(Relatives.begin(), Relatives.end(), [](const Elf_Rel &A, const Elf_Rel &B) { return A.r_offset < B.r_offset; }); // Try to find groups of relative relocations which are spaced one word // apart from one another. These generally correspond to vtable entries. The // format allows these groups to be encoded using a sort of run-length // encoding, but each group will cost 7 bytes in addition to the offset from // the previous group, so it is only profitable to do this for groups of // size 8 or larger. std::vector UngroupedRelatives; std::vector> RelativeGroups; for (auto I = Relatives.begin(), E = Relatives.end(); I != E;) { std::vector Group; do { Group.push_back(*I++); } while (I != E && (I - 1)->r_offset + Config->Wordsize == I->r_offset); if (Group.size() < 8) UngroupedRelatives.insert(UngroupedRelatives.end(), Group.begin(), Group.end()); else RelativeGroups.emplace_back(std::move(Group)); } unsigned HasAddendIfRela = Config->IsRela ? RELOCATION_GROUP_HAS_ADDEND_FLAG : 0; uint64_t Offset = 0; uint64_t Addend = 0; // Emit the run-length encoding for the groups of adjacent relative // relocations. Each group is represented using two groups in the packed // format. The first is used to set the current offset to the start of the // group (and also encodes the first relocation), and the second encodes the // remaining relocations. for (std::vector &G : RelativeGroups) { // The first relocation in the group. Add(1); Add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG | RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela); Add(G[0].r_offset - Offset); Add(Target->RelativeRel); if (Config->IsRela) { Add(G[0].r_addend - Addend); Addend = G[0].r_addend; } // The remaining relocations. Add(G.size() - 1); Add(RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG | RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela); Add(Config->Wordsize); Add(Target->RelativeRel); if (Config->IsRela) { for (auto I = G.begin() + 1, E = G.end(); I != E; ++I) { Add(I->r_addend - Addend); Addend = I->r_addend; } } Offset = G.back().r_offset; } // Now the ungrouped relatives. if (!UngroupedRelatives.empty()) { Add(UngroupedRelatives.size()); Add(RELOCATION_GROUPED_BY_INFO_FLAG | HasAddendIfRela); Add(Target->RelativeRel); for (Elf_Rela &R : UngroupedRelatives) { Add(R.r_offset - Offset); Offset = R.r_offset; if (Config->IsRela) { Add(R.r_addend - Addend); Addend = R.r_addend; } } } // Finally the non-relative relocations. std::sort(NonRelatives.begin(), NonRelatives.end(), [](const Elf_Rela &A, const Elf_Rela &B) { return A.r_offset < B.r_offset; }); if (!NonRelatives.empty()) { Add(NonRelatives.size()); Add(HasAddendIfRela); for (Elf_Rela &R : NonRelatives) { Add(R.r_offset - Offset); Offset = R.r_offset; Add(R.r_info); if (Config->IsRela) { Add(R.r_addend - Addend); Addend = R.r_addend; } } } // Returns whether the section size changed. We need to keep recomputing both // section layout and the contents of this section until the size converges // because changing this section's size can affect section layout, which in // turn can affect the sizes of the LEB-encoded integers stored in this // section. return RelocData.size() != OldSize; } SymbolTableBaseSection::SymbolTableBaseSection(StringTableSection &StrTabSec) : SyntheticSection(StrTabSec.isDynamic() ? (uint64_t)SHF_ALLOC : 0, StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB, Config->Wordsize, StrTabSec.isDynamic() ? ".dynsym" : ".symtab"), StrTabSec(StrTabSec) {} // Orders symbols according to their positions in the GOT, // in compliance with MIPS ABI rules. // See "Global Offset Table" in Chapter 5 in the following document // for detailed description: // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf static bool sortMipsSymbols(const SymbolTableEntry &L, const SymbolTableEntry &R) { // Sort entries related to non-local preemptible symbols by GOT indexes. // All other entries go to the first part of GOT in arbitrary order. bool LIsInLocalGot = !L.Sym->IsInGlobalMipsGot; bool RIsInLocalGot = !R.Sym->IsInGlobalMipsGot; if (LIsInLocalGot || RIsInLocalGot) return !RIsInLocalGot; return L.Sym->GotIndex < R.Sym->GotIndex; } void SymbolTableBaseSection::finalizeContents() { getParent()->Link = StrTabSec.getParent()->SectionIndex; // If it is a .dynsym, there should be no local symbols, but we need // to do a few things for the dynamic linker. if (this->Type == SHT_DYNSYM) { // Section's Info field has the index of the first non-local symbol. // Because the first symbol entry is a null entry, 1 is the first. getParent()->Info = 1; if (InX::GnuHashTab) { // NB: It also sorts Symbols to meet the GNU hash table requirements. InX::GnuHashTab->addSymbols(Symbols); } else if (Config->EMachine == EM_MIPS) { std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols); } size_t I = 0; for (const SymbolTableEntry &S : Symbols) S.Sym->DynsymIndex = ++I; return; } } // The ELF spec requires that all local symbols precede global symbols, so we // sort symbol entries in this function. (For .dynsym, we don't do that because // symbols for dynamic linking are inherently all globals.) void SymbolTableBaseSection::postThunkContents() { if (this->Type == SHT_DYNSYM) return; // move all local symbols before global symbols. auto It = std::stable_partition( Symbols.begin(), Symbols.end(), [](const SymbolTableEntry &S) { return S.Sym->isLocal() || S.Sym->computeBinding() == STB_LOCAL; }); size_t NumLocals = It - Symbols.begin(); getParent()->Info = NumLocals + 1; } void SymbolTableBaseSection::addSymbol(Symbol *B) { // Adding a local symbol to a .dynsym is a bug. assert(this->Type != SHT_DYNSYM || !B->isLocal()); bool HashIt = B->isLocal(); Symbols.push_back({B, StrTabSec.addString(B->getName(), HashIt)}); } size_t SymbolTableBaseSection::getSymbolIndex(Symbol *Sym) { // Initializes symbol lookup tables lazily. This is used only // for -r or -emit-relocs. llvm::call_once(OnceFlag, [&] { SymbolIndexMap.reserve(Symbols.size()); size_t I = 0; for (const SymbolTableEntry &E : Symbols) { if (E.Sym->Type == STT_SECTION) SectionIndexMap[E.Sym->getOutputSection()] = ++I; else SymbolIndexMap[E.Sym] = ++I; } }); // Section symbols are mapped based on their output sections // to maintain their semantics. if (Sym->Type == STT_SECTION) return SectionIndexMap.lookup(Sym->getOutputSection()); return SymbolIndexMap.lookup(Sym); } template SymbolTableSection::SymbolTableSection(StringTableSection &StrTabSec) : SymbolTableBaseSection(StrTabSec) { this->Entsize = sizeof(Elf_Sym); } // Write the internal symbol table contents to the output symbol table. template void SymbolTableSection::writeTo(uint8_t *Buf) { // The first entry is a null entry as per the ELF spec. memset(Buf, 0, sizeof(Elf_Sym)); Buf += sizeof(Elf_Sym); auto *ESym = reinterpret_cast(Buf); for (SymbolTableEntry &Ent : Symbols) { Symbol *Sym = Ent.Sym; // Set st_info and st_other. ESym->st_other = 0; if (Sym->isLocal()) { ESym->setBindingAndType(STB_LOCAL, Sym->Type); } else { ESym->setBindingAndType(Sym->computeBinding(), Sym->Type); ESym->setVisibility(Sym->Visibility); } ESym->st_name = Ent.StrTabOffset; // Set a section index. BssSection *CommonSec = nullptr; if (!Config->DefineCommon) if (auto *D = dyn_cast(Sym)) CommonSec = dyn_cast_or_null(D->Section); if (CommonSec) ESym->st_shndx = SHN_COMMON; else if (const OutputSection *OutSec = Sym->getOutputSection()) ESym->st_shndx = OutSec->SectionIndex; else if (isa(Sym)) ESym->st_shndx = SHN_ABS; else ESym->st_shndx = SHN_UNDEF; // Copy symbol size if it is a defined symbol. st_size is not significant // for undefined symbols, so whether copying it or not is up to us if that's // the case. We'll leave it as zero because by not setting a value, we can // get the exact same outputs for two sets of input files that differ only // in undefined symbol size in DSOs. if (ESym->st_shndx == SHN_UNDEF) ESym->st_size = 0; else ESym->st_size = Sym->getSize(); // st_value is usually an address of a symbol, but that has a // special meaining for uninstantiated common symbols (this can // occur if -r is given). if (CommonSec) ESym->st_value = CommonSec->Alignment; else ESym->st_value = Sym->getVA(); ++ESym; } // On MIPS we need to mark symbol which has a PLT entry and requires // pointer equality by STO_MIPS_PLT flag. That is necessary to help // dynamic linker distinguish such symbols and MIPS lazy-binding stubs. // https://sourceware.org/ml/binutils/2008-07/txt00000.txt if (Config->EMachine == EM_MIPS) { auto *ESym = reinterpret_cast(Buf); for (SymbolTableEntry &Ent : Symbols) { Symbol *Sym = Ent.Sym; if (Sym->isInPlt() && Sym->NeedsPltAddr) ESym->st_other |= STO_MIPS_PLT; if (isMicroMips()) { // Set STO_MIPS_MICROMIPS flag and less-significant bit for // defined microMIPS symbols and shared symbols with PLT record. if ((Sym->isDefined() && (Sym->StOther & STO_MIPS_MICROMIPS)) || (Sym->isShared() && Sym->NeedsPltAddr)) { if (StrTabSec.isDynamic()) ESym->st_value |= 1; ESym->st_other |= STO_MIPS_MICROMIPS; } } if (Config->Relocatable) if (auto *D = dyn_cast(Sym)) if (isMipsPIC(D)) ESym->st_other |= STO_MIPS_PIC; ++ESym; } } } // .hash and .gnu.hash sections contain on-disk hash tables that map // symbol names to their dynamic symbol table indices. Their purpose // is to help the dynamic linker resolve symbols quickly. If ELF files // don't have them, the dynamic linker has to do linear search on all // dynamic symbols, which makes programs slower. Therefore, a .hash // section is added to a DSO by default. A .gnu.hash is added if you // give the -hash-style=gnu or -hash-style=both option. // // The Unix semantics of resolving dynamic symbols is somewhat expensive. // Each ELF file has a list of DSOs that the ELF file depends on and a // list of dynamic symbols that need to be resolved from any of the // DSOs. That means resolving all dynamic symbols takes O(m)*O(n) // where m is the number of DSOs and n is the number of dynamic // symbols. For modern large programs, both m and n are large. So // making each step faster by using hash tables substiantially // improves time to load programs. // // (Note that this is not the only way to design the shared library. // For instance, the Windows DLL takes a different approach. On // Windows, each dynamic symbol has a name of DLL from which the symbol // has to be resolved. That makes the cost of symbol resolution O(n). // This disables some hacky techniques you can use on Unix such as // LD_PRELOAD, but this is arguably better semantics than the Unix ones.) // // Due to historical reasons, we have two different hash tables, .hash // and .gnu.hash. They are for the same purpose, and .gnu.hash is a new // and better version of .hash. .hash is just an on-disk hash table, but // .gnu.hash has a bloom filter in addition to a hash table to skip // DSOs very quickly. If you are sure that your dynamic linker knows // about .gnu.hash, you want to specify -hash-style=gnu. Otherwise, a // safe bet is to specify -hash-style=both for backward compatibilty. GnuHashTableSection::GnuHashTableSection() : SyntheticSection(SHF_ALLOC, SHT_GNU_HASH, Config->Wordsize, ".gnu.hash") { } void GnuHashTableSection::finalizeContents() { getParent()->Link = InX::DynSymTab->getParent()->SectionIndex; // Computes bloom filter size in word size. We want to allocate 8 // bits for each symbol. It must be a power of two. if (Symbols.empty()) MaskWords = 1; else MaskWords = NextPowerOf2((Symbols.size() - 1) / Config->Wordsize); Size = 16; // Header Size += Config->Wordsize * MaskWords; // Bloom filter Size += NBuckets * 4; // Hash buckets Size += Symbols.size() * 4; // Hash values } void GnuHashTableSection::writeTo(uint8_t *Buf) { // The output buffer is not guaranteed to be zero-cleared because we pre- // fill executable sections with trap instructions. This is a precaution // for that case, which happens only when -no-rosegment is given. memset(Buf, 0, Size); // Write a header. write32(Buf, NBuckets); write32(Buf + 4, InX::DynSymTab->getNumSymbols() - Symbols.size()); write32(Buf + 8, MaskWords); write32(Buf + 12, getShift2()); Buf += 16; // Write a bloom filter and a hash table. writeBloomFilter(Buf); Buf += Config->Wordsize * MaskWords; writeHashTable(Buf); } // This function writes a 2-bit bloom filter. This bloom filter alone // usually filters out 80% or more of all symbol lookups [1]. // The dynamic linker uses the hash table only when a symbol is not // filtered out by a bloom filter. // // [1] Ulrich Drepper (2011), "How To Write Shared Libraries" (Ver. 4.1.2), // p.9, https://www.akkadia.org/drepper/dsohowto.pdf void GnuHashTableSection::writeBloomFilter(uint8_t *Buf) { const unsigned C = Config->Wordsize * 8; for (const Entry &Sym : Symbols) { size_t I = (Sym.Hash / C) & (MaskWords - 1); uint64_t Val = readUint(Buf + I * Config->Wordsize); Val |= uint64_t(1) << (Sym.Hash % C); Val |= uint64_t(1) << ((Sym.Hash >> getShift2()) % C); writeUint(Buf + I * Config->Wordsize, Val); } } void GnuHashTableSection::writeHashTable(uint8_t *Buf) { uint32_t *Buckets = reinterpret_cast(Buf); uint32_t OldBucket = -1; uint32_t *Values = Buckets + NBuckets; for (auto I = Symbols.begin(), E = Symbols.end(); I != E; ++I) { // Write a hash value. It represents a sequence of chains that share the // same hash modulo value. The last element of each chain is terminated by // LSB 1. uint32_t Hash = I->Hash; bool IsLastInChain = (I + 1) == E || I->BucketIdx != (I + 1)->BucketIdx; Hash = IsLastInChain ? Hash | 1 : Hash & ~1; write32(Values++, Hash); if (I->BucketIdx == OldBucket) continue; // Write a hash bucket. Hash buckets contain indices in the following hash // value table. write32(Buckets + I->BucketIdx, I->Sym->DynsymIndex); OldBucket = I->BucketIdx; } } static uint32_t hashGnu(StringRef Name) { uint32_t H = 5381; for (uint8_t C : Name) H = (H << 5) + H + C; return H; } // Add symbols to this symbol hash table. Note that this function // destructively sort a given vector -- which is needed because // GNU-style hash table places some sorting requirements. void GnuHashTableSection::addSymbols(std::vector &V) { // We cannot use 'auto' for Mid because GCC 6.1 cannot deduce // its type correctly. std::vector::iterator Mid = std::stable_partition(V.begin(), V.end(), [](const SymbolTableEntry &S) { // Shared symbols that this executable preempts are special. The dynamic // linker has to look them up, so they have to be in the hash table. if (auto *SS = dyn_cast(S.Sym)) return SS->CopyRelSec == nullptr && !SS->NeedsPltAddr; return !S.Sym->isDefined(); }); if (Mid == V.end()) return; // We chose load factor 4 for the on-disk hash table. For each hash // collision, the dynamic linker will compare a uint32_t hash value. // Since the integer comparison is quite fast, we believe we can make // the load factor even larger. 4 is just a conservative choice. NBuckets = std::max((V.end() - Mid) / 4, 1); for (SymbolTableEntry &Ent : llvm::make_range(Mid, V.end())) { Symbol *B = Ent.Sym; uint32_t Hash = hashGnu(B->getName()); uint32_t BucketIdx = Hash % NBuckets; Symbols.push_back({B, Ent.StrTabOffset, Hash, BucketIdx}); } std::stable_sort( Symbols.begin(), Symbols.end(), [](const Entry &L, const Entry &R) { return L.BucketIdx < R.BucketIdx; }); V.erase(Mid, V.end()); for (const Entry &Ent : Symbols) V.push_back({Ent.Sym, Ent.StrTabOffset}); } HashTableSection::HashTableSection() : SyntheticSection(SHF_ALLOC, SHT_HASH, 4, ".hash") { this->Entsize = 4; } void HashTableSection::finalizeContents() { getParent()->Link = InX::DynSymTab->getParent()->SectionIndex; unsigned NumEntries = 2; // nbucket and nchain. NumEntries += InX::DynSymTab->getNumSymbols(); // The chain entries. // Create as many buckets as there are symbols. NumEntries += InX::DynSymTab->getNumSymbols(); this->Size = NumEntries * 4; } void HashTableSection::writeTo(uint8_t *Buf) { + // See comment in GnuHashTableSection::writeTo. + memset(Buf, 0, Size); + unsigned NumSymbols = InX::DynSymTab->getNumSymbols(); uint32_t *P = reinterpret_cast(Buf); write32(P++, NumSymbols); // nbucket write32(P++, NumSymbols); // nchain uint32_t *Buckets = P; uint32_t *Chains = P + NumSymbols; for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) { Symbol *Sym = S.Sym; StringRef Name = Sym->getName(); unsigned I = Sym->DynsymIndex; uint32_t Hash = hashSysV(Name) % NumSymbols; Chains[I] = Buckets[Hash]; write32(Buckets + Hash, I); } } PltSection::PltSection(size_t S) : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, 16, ".plt"), HeaderSize(S) { // The PLT needs to be writable on SPARC as the dynamic linker will // modify the instructions in the PLT entries. if (Config->EMachine == EM_SPARCV9) this->Flags |= SHF_WRITE; } void PltSection::writeTo(uint8_t *Buf) { // At beginning of PLT but not the IPLT, we have code to call the dynamic // linker to resolve dynsyms at runtime. Write such code. if (HeaderSize != 0) Target->writePltHeader(Buf); size_t Off = HeaderSize; // The IPlt is immediately after the Plt, account for this in RelOff unsigned PltOff = getPltRelocOff(); for (auto &I : Entries) { const Symbol *B = I.first; unsigned RelOff = I.second + PltOff; uint64_t Got = B->getGotPltVA(); uint64_t Plt = this->getVA() + Off; Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff); Off += Target->PltEntrySize; } } template void PltSection::addEntry(Symbol &Sym) { Sym.PltIndex = Entries.size(); RelocationBaseSection *PltRelocSection = InX::RelaPlt; if (HeaderSize == 0) { PltRelocSection = InX::RelaIplt; Sym.IsInIplt = true; } unsigned RelOff = static_cast *>(PltRelocSection)->getRelocOffset(); Entries.push_back(std::make_pair(&Sym, RelOff)); } size_t PltSection::getSize() const { return HeaderSize + Entries.size() * Target->PltEntrySize; } // Some architectures such as additional symbols in the PLT section. For // example ARM uses mapping symbols to aid disassembly void PltSection::addSymbols() { // The PLT may have symbols defined for the Header, the IPLT has no header if (HeaderSize != 0) Target->addPltHeaderSymbols(*this); size_t Off = HeaderSize; for (size_t I = 0; I < Entries.size(); ++I) { Target->addPltSymbols(*this, Off); Off += Target->PltEntrySize; } } unsigned PltSection::getPltRelocOff() const { return (HeaderSize == 0) ? InX::Plt->getSize() : 0; } // The string hash function for .gdb_index. static uint32_t computeGdbHash(StringRef S) { uint32_t H = 0; for (uint8_t C : S) H = H * 67 + tolower(C) - 113; return H; } static std::vector readCuList(DWARFContext &Dwarf) { std::vector Ret; for (std::unique_ptr &Cu : Dwarf.compile_units()) Ret.push_back({Cu->getOffset(), Cu->getLength() + 4}); return Ret; } static std::vector readAddressAreas(DWARFContext &Dwarf, InputSection *Sec) { std::vector Ret; uint32_t CuIdx = 0; for (std::unique_ptr &Cu : Dwarf.compile_units()) { DWARFAddressRangesVector Ranges; Cu->collectAddressRanges(Ranges); ArrayRef Sections = Sec->File->getSections(); for (DWARFAddressRange &R : Ranges) { InputSectionBase *S = Sections[R.SectionIndex]; if (!S || S == &InputSection::Discarded || !S->Live) continue; // Range list with zero size has no effect. if (R.LowPC == R.HighPC) continue; auto *IS = cast(S); uint64_t Offset = IS->getOffsetInFile(); Ret.push_back({IS, R.LowPC - Offset, R.HighPC - Offset, CuIdx}); } ++CuIdx; } return Ret; } static std::vector readPubNamesAndTypes(DWARFContext &Dwarf) { StringRef Sec1 = Dwarf.getDWARFObj().getGnuPubNamesSection(); StringRef Sec2 = Dwarf.getDWARFObj().getGnuPubTypesSection(); std::vector Ret; for (StringRef Sec : {Sec1, Sec2}) { DWARFDebugPubTable Table(Sec, Config->IsLE, true); for (const DWARFDebugPubTable::Set &Set : Table.getData()) { for (const DWARFDebugPubTable::Entry &Ent : Set.Entries) { CachedHashStringRef S(Ent.Name, computeGdbHash(Ent.Name)); Ret.push_back({S, Ent.Descriptor.toBits()}); } } } return Ret; } static std::vector getDebugInfoSections() { std::vector Ret; for (InputSectionBase *S : InputSections) if (InputSection *IS = dyn_cast(S)) if (IS->Name == ".debug_info") Ret.push_back(IS); return Ret; } void GdbIndexSection::fixCuIndex() { uint32_t Idx = 0; for (GdbIndexChunk &Chunk : Chunks) { for (GdbIndexChunk::AddressEntry &Ent : Chunk.AddressAreas) Ent.CuIndex += Idx; Idx += Chunk.CompilationUnits.size(); } } std::vector> GdbIndexSection::createCuVectors() { std::vector> Ret; uint32_t Idx = 0; uint32_t Off = 0; for (GdbIndexChunk &Chunk : Chunks) { for (GdbIndexChunk::NameTypeEntry &Ent : Chunk.NamesAndTypes) { GdbSymbol *&Sym = Symbols[Ent.Name]; if (!Sym) { Sym = make(GdbSymbol{Ent.Name.hash(), Off, Ret.size()}); Off += Ent.Name.size() + 1; Ret.push_back({}); } // gcc 5.4.1 produces a buggy .debug_gnu_pubnames that contains // duplicate entries, so we want to dedup them. std::vector &Vec = Ret[Sym->CuVectorIndex]; uint32_t Val = (Ent.Type << 24) | Idx; if (Vec.empty() || Vec.back() != Val) Vec.push_back(Val); } Idx += Chunk.CompilationUnits.size(); } StringPoolSize = Off; return Ret; } template GdbIndexSection *elf::createGdbIndex() { // Gather debug info to create a .gdb_index section. std::vector Sections = getDebugInfoSections(); std::vector Chunks(Sections.size()); parallelForEachN(0, Chunks.size(), [&](size_t I) { ObjFile *File = Sections[I]->getFile(); DWARFContext Dwarf(make_unique>(File)); Chunks[I].DebugInfoSec = Sections[I]; Chunks[I].CompilationUnits = readCuList(Dwarf); Chunks[I].AddressAreas = readAddressAreas(Dwarf, Sections[I]); Chunks[I].NamesAndTypes = readPubNamesAndTypes(Dwarf); }); // .debug_gnu_pub{names,types} are useless in executables. // They are present in input object files solely for creating // a .gdb_index. So we can remove it from the output. for (InputSectionBase *S : InputSections) if (S->Name == ".debug_gnu_pubnames" || S->Name == ".debug_gnu_pubtypes") S->Live = false; // Create a .gdb_index and returns it. return make(std::move(Chunks)); } static size_t getCuSize(ArrayRef Arr) { size_t Ret = 0; for (const GdbIndexChunk &D : Arr) Ret += D.CompilationUnits.size(); return Ret; } static size_t getAddressAreaSize(ArrayRef Arr) { size_t Ret = 0; for (const GdbIndexChunk &D : Arr) Ret += D.AddressAreas.size(); return Ret; } std::vector GdbIndexSection::createGdbSymtab() { uint32_t Size = NextPowerOf2(Symbols.size() * 4 / 3); if (Size < 1024) Size = 1024; uint32_t Mask = Size - 1; std::vector Ret(Size); for (auto &KV : Symbols) { GdbSymbol *Sym = KV.second; uint32_t I = Sym->NameHash & Mask; uint32_t Step = ((Sym->NameHash * 17) & Mask) | 1; while (Ret[I]) I = (I + Step) & Mask; Ret[I] = Sym; } return Ret; } GdbIndexSection::GdbIndexSection(std::vector &&C) : SyntheticSection(0, SHT_PROGBITS, 1, ".gdb_index"), Chunks(std::move(C)) { fixCuIndex(); CuVectors = createCuVectors(); GdbSymtab = createGdbSymtab(); // Compute offsets early to know the section size. // Each chunk size needs to be in sync with what we write in writeTo. CuTypesOffset = CuListOffset + getCuSize(Chunks) * 16; SymtabOffset = CuTypesOffset + getAddressAreaSize(Chunks) * 20; ConstantPoolOffset = SymtabOffset + GdbSymtab.size() * 8; size_t Off = 0; for (ArrayRef Vec : CuVectors) { CuVectorOffsets.push_back(Off); Off += (Vec.size() + 1) * 4; } StringPoolOffset = ConstantPoolOffset + Off; } size_t GdbIndexSection::getSize() const { return StringPoolOffset + StringPoolSize; } void GdbIndexSection::writeTo(uint8_t *Buf) { // Write the section header. write32le(Buf, 7); write32le(Buf + 4, CuListOffset); write32le(Buf + 8, CuTypesOffset); write32le(Buf + 12, CuTypesOffset); write32le(Buf + 16, SymtabOffset); write32le(Buf + 20, ConstantPoolOffset); Buf += 24; // Write the CU list. for (GdbIndexChunk &D : Chunks) { for (GdbIndexChunk::CuEntry &Cu : D.CompilationUnits) { write64le(Buf, D.DebugInfoSec->OutSecOff + Cu.CuOffset); write64le(Buf + 8, Cu.CuLength); Buf += 16; } } // Write the address area. for (GdbIndexChunk &D : Chunks) { for (GdbIndexChunk::AddressEntry &E : D.AddressAreas) { uint64_t BaseAddr = E.Section->getParent()->Addr + E.Section->getOffset(0); write64le(Buf, BaseAddr + E.LowAddress); write64le(Buf + 8, BaseAddr + E.HighAddress); write32le(Buf + 16, E.CuIndex); Buf += 20; } } // Write the symbol table. for (GdbSymbol *Sym : GdbSymtab) { if (Sym) { write32le(Buf, Sym->NameOffset + StringPoolOffset - ConstantPoolOffset); write32le(Buf + 4, CuVectorOffsets[Sym->CuVectorIndex]); } Buf += 8; } // Write the CU vectors. for (ArrayRef Vec : CuVectors) { write32le(Buf, Vec.size()); Buf += 4; for (uint32_t Val : Vec) { write32le(Buf, Val); Buf += 4; } } // Write the string pool. for (auto &KV : Symbols) { CachedHashStringRef S = KV.first; GdbSymbol *Sym = KV.second; size_t Off = Sym->NameOffset; memcpy(Buf + Off, S.val().data(), S.size()); Buf[Off + S.size()] = '\0'; } } bool GdbIndexSection::empty() const { return !Out::DebugInfo; } EhFrameHeader::EhFrameHeader() : SyntheticSection(SHF_ALLOC, SHT_PROGBITS, 1, ".eh_frame_hdr") {} // .eh_frame_hdr contains a binary search table of pointers to FDEs. // Each entry of the search table consists of two values, // the starting PC from where FDEs covers, and the FDE's address. // It is sorted by PC. void EhFrameHeader::writeTo(uint8_t *Buf) { typedef EhFrameSection::FdeData FdeData; std::vector Fdes = InX::EhFrame->getFdeData(); // Sort the FDE list by their PC and uniqueify. Usually there is only // one FDE for a PC (i.e. function), but if ICF merges two functions // into one, there can be more than one FDEs pointing to the address. auto Less = [](const FdeData &A, const FdeData &B) { return A.Pc < B.Pc; }; std::stable_sort(Fdes.begin(), Fdes.end(), Less); auto Eq = [](const FdeData &A, const FdeData &B) { return A.Pc == B.Pc; }; Fdes.erase(std::unique(Fdes.begin(), Fdes.end(), Eq), Fdes.end()); Buf[0] = 1; Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4; Buf[2] = DW_EH_PE_udata4; Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4; write32(Buf + 4, InX::EhFrame->getParent()->Addr - this->getVA() - 4); write32(Buf + 8, Fdes.size()); Buf += 12; uint64_t VA = this->getVA(); for (FdeData &Fde : Fdes) { write32(Buf, Fde.Pc - VA); write32(Buf + 4, Fde.FdeVA - VA); Buf += 8; } } size_t EhFrameHeader::getSize() const { // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs. return 12 + InX::EhFrame->NumFdes * 8; } bool EhFrameHeader::empty() const { return InX::EhFrame->empty(); } template VersionDefinitionSection::VersionDefinitionSection() : SyntheticSection(SHF_ALLOC, SHT_GNU_verdef, sizeof(uint32_t), ".gnu.version_d") {} static StringRef getFileDefName() { if (!Config->SoName.empty()) return Config->SoName; return Config->OutputFile; } template void VersionDefinitionSection::finalizeContents() { FileDefNameOff = InX::DynStrTab->addString(getFileDefName()); for (VersionDefinition &V : Config->VersionDefinitions) V.NameOff = InX::DynStrTab->addString(V.Name); getParent()->Link = InX::DynStrTab->getParent()->SectionIndex; // sh_info should be set to the number of definitions. This fact is missed in // documentation, but confirmed by binutils community: // https://sourceware.org/ml/binutils/2014-11/msg00355.html getParent()->Info = getVerDefNum(); } template void VersionDefinitionSection::writeOne(uint8_t *Buf, uint32_t Index, StringRef Name, size_t NameOff) { auto *Verdef = reinterpret_cast(Buf); Verdef->vd_version = 1; Verdef->vd_cnt = 1; Verdef->vd_aux = sizeof(Elf_Verdef); Verdef->vd_next = sizeof(Elf_Verdef) + sizeof(Elf_Verdaux); Verdef->vd_flags = (Index == 1 ? VER_FLG_BASE : 0); Verdef->vd_ndx = Index; Verdef->vd_hash = hashSysV(Name); auto *Verdaux = reinterpret_cast(Buf + sizeof(Elf_Verdef)); Verdaux->vda_name = NameOff; Verdaux->vda_next = 0; } template void VersionDefinitionSection::writeTo(uint8_t *Buf) { writeOne(Buf, 1, getFileDefName(), FileDefNameOff); for (VersionDefinition &V : Config->VersionDefinitions) { Buf += sizeof(Elf_Verdef) + sizeof(Elf_Verdaux); writeOne(Buf, V.Id, V.Name, V.NameOff); } // Need to terminate the last version definition. Elf_Verdef *Verdef = reinterpret_cast(Buf); Verdef->vd_next = 0; } template size_t VersionDefinitionSection::getSize() const { return (sizeof(Elf_Verdef) + sizeof(Elf_Verdaux)) * getVerDefNum(); } template VersionTableSection::VersionTableSection() : SyntheticSection(SHF_ALLOC, SHT_GNU_versym, sizeof(uint16_t), ".gnu.version") { this->Entsize = sizeof(Elf_Versym); } template void VersionTableSection::finalizeContents() { // At the moment of june 2016 GNU docs does not mention that sh_link field // should be set, but Sun docs do. Also readelf relies on this field. getParent()->Link = InX::DynSymTab->getParent()->SectionIndex; } template size_t VersionTableSection::getSize() const { return sizeof(Elf_Versym) * (InX::DynSymTab->getSymbols().size() + 1); } template void VersionTableSection::writeTo(uint8_t *Buf) { auto *OutVersym = reinterpret_cast(Buf) + 1; for (const SymbolTableEntry &S : InX::DynSymTab->getSymbols()) { OutVersym->vs_index = S.Sym->VersionId; ++OutVersym; } } template bool VersionTableSection::empty() const { return !In::VerDef && In::VerNeed->empty(); } template VersionNeedSection::VersionNeedSection() : SyntheticSection(SHF_ALLOC, SHT_GNU_verneed, sizeof(uint32_t), ".gnu.version_r") { // Identifiers in verneed section start at 2 because 0 and 1 are reserved // for VER_NDX_LOCAL and VER_NDX_GLOBAL. // First identifiers are reserved by verdef section if it exist. NextIndex = getVerDefNum() + 1; } template void VersionNeedSection::addSymbol(SharedSymbol *SS) { SharedFile &File = SS->getFile(); const typename ELFT::Verdef *Ver = File.Verdefs[SS->VerdefIndex]; if (!Ver) { SS->VersionId = VER_NDX_GLOBAL; return; } // If we don't already know that we need an Elf_Verneed for this DSO, prepare // to create one by adding it to our needed list and creating a dynstr entry // for the soname. if (File.VerdefMap.empty()) Needed.push_back({&File, InX::DynStrTab->addString(File.SoName)}); typename SharedFile::NeededVer &NV = File.VerdefMap[Ver]; // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef, // prepare to create one by allocating a version identifier and creating a // dynstr entry for the version name. if (NV.Index == 0) { NV.StrTab = InX::DynStrTab->addString(File.getStringTable().data() + Ver->getAux()->vda_name); NV.Index = NextIndex++; } SS->VersionId = NV.Index; } template void VersionNeedSection::writeTo(uint8_t *Buf) { // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs. auto *Verneed = reinterpret_cast(Buf); auto *Vernaux = reinterpret_cast(Verneed + Needed.size()); for (std::pair *, size_t> &P : Needed) { // Create an Elf_Verneed for this DSO. Verneed->vn_version = 1; Verneed->vn_cnt = P.first->VerdefMap.size(); Verneed->vn_file = P.second; Verneed->vn_aux = reinterpret_cast(Vernaux) - reinterpret_cast(Verneed); Verneed->vn_next = sizeof(Elf_Verneed); ++Verneed; // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over // VerdefMap, which will only contain references to needed version // definitions. Each Elf_Vernaux is based on the information contained in // the Elf_Verdef in the source DSO. This loop iterates over a std::map of // pointers, but is deterministic because the pointers refer to Elf_Verdef // data structures within a single input file. for (auto &NV : P.first->VerdefMap) { Vernaux->vna_hash = NV.first->vd_hash; Vernaux->vna_flags = 0; Vernaux->vna_other = NV.second.Index; Vernaux->vna_name = NV.second.StrTab; Vernaux->vna_next = sizeof(Elf_Vernaux); ++Vernaux; } Vernaux[-1].vna_next = 0; } Verneed[-1].vn_next = 0; } template void VersionNeedSection::finalizeContents() { getParent()->Link = InX::DynStrTab->getParent()->SectionIndex; getParent()->Info = Needed.size(); } template size_t VersionNeedSection::getSize() const { unsigned Size = Needed.size() * sizeof(Elf_Verneed); for (const std::pair *, size_t> &P : Needed) Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux); return Size; } template bool VersionNeedSection::empty() const { return getNeedNum() == 0; } void MergeSyntheticSection::addSection(MergeInputSection *MS) { MS->Parent = this; Sections.push_back(MS); } MergeTailSection::MergeTailSection(StringRef Name, uint32_t Type, uint64_t Flags, uint32_t Alignment) : MergeSyntheticSection(Name, Type, Flags, Alignment), Builder(StringTableBuilder::RAW, Alignment) {} size_t MergeTailSection::getSize() const { return Builder.getSize(); } void MergeTailSection::writeTo(uint8_t *Buf) { Builder.write(Buf); } void MergeTailSection::finalizeContents() { // Add all string pieces to the string table builder to create section // contents. for (MergeInputSection *Sec : Sections) for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I) if (Sec->Pieces[I].Live) Builder.add(Sec->getData(I)); // Fix the string table content. After this, the contents will never change. Builder.finalize(); // finalize() fixed tail-optimized strings, so we can now get // offsets of strings. Get an offset for each string and save it // to a corresponding StringPiece for easy access. for (MergeInputSection *Sec : Sections) for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I) if (Sec->Pieces[I].Live) Sec->Pieces[I].OutputOff = Builder.getOffset(Sec->getData(I)); } void MergeNoTailSection::writeTo(uint8_t *Buf) { for (size_t I = 0; I < NumShards; ++I) Shards[I].write(Buf + ShardOffsets[I]); } // This function is very hot (i.e. it can take several seconds to finish) // because sometimes the number of inputs is in an order of magnitude of // millions. So, we use multi-threading. // // For any strings S and T, we know S is not mergeable with T if S's hash // value is different from T's. If that's the case, we can safely put S and // T into different string builders without worrying about merge misses. // We do it in parallel. void MergeNoTailSection::finalizeContents() { // Initializes string table builders. for (size_t I = 0; I < NumShards; ++I) Shards.emplace_back(StringTableBuilder::RAW, Alignment); // Concurrency level. Must be a power of 2 to avoid expensive modulo // operations in the following tight loop. size_t Concurrency = 1; if (ThreadsEnabled) Concurrency = std::min(PowerOf2Floor(hardware_concurrency()), NumShards); // Add section pieces to the builders. parallelForEachN(0, Concurrency, [&](size_t ThreadId) { for (MergeInputSection *Sec : Sections) { for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I) { - if (!Sec->Pieces[I].Live) - continue; size_t ShardId = getShardId(Sec->Pieces[I].Hash); - if ((ShardId & (Concurrency - 1)) == ThreadId) + if ((ShardId & (Concurrency - 1)) == ThreadId && Sec->Pieces[I].Live) Sec->Pieces[I].OutputOff = Shards[ShardId].add(Sec->getData(I)); } } }); // Compute an in-section offset for each shard. size_t Off = 0; for (size_t I = 0; I < NumShards; ++I) { Shards[I].finalizeInOrder(); if (Shards[I].getSize() > 0) Off = alignTo(Off, Alignment); ShardOffsets[I] = Off; Off += Shards[I].getSize(); } Size = Off; // So far, section pieces have offsets from beginning of shards, but // we want offsets from beginning of the whole section. Fix them. parallelForEach(Sections, [&](MergeInputSection *Sec) { for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I) if (Sec->Pieces[I].Live) Sec->Pieces[I].OutputOff += ShardOffsets[getShardId(Sec->Pieces[I].Hash)]; }); } static MergeSyntheticSection *createMergeSynthetic(StringRef Name, uint32_t Type, uint64_t Flags, uint32_t Alignment) { bool ShouldTailMerge = (Flags & SHF_STRINGS) && Config->Optimize >= 2; if (ShouldTailMerge) return make(Name, Type, Flags, Alignment); return make(Name, Type, Flags, Alignment); } // Debug sections may be compressed by zlib. Uncompress if exists. void elf::decompressSections() { parallelForEach(InputSections, [](InputSectionBase *Sec) { if (Sec->Live) Sec->maybeUncompress(); }); } // This function scans over the inputsections to create mergeable // synthetic sections. // // It removes MergeInputSections from the input section array and adds // new synthetic sections at the location of the first input section // that it replaces. It then finalizes each synthetic section in order // to compute an output offset for each piece of each input section. void elf::mergeSections() { // splitIntoPieces needs to be called on each MergeInputSection // before calling finalizeContents(). Do that first. parallelForEach(InputSections, [](InputSectionBase *Sec) { if (Sec->Live) if (auto *S = dyn_cast(Sec)) S->splitIntoPieces(); }); std::vector MergeSections; for (InputSectionBase *&S : InputSections) { MergeInputSection *MS = dyn_cast(S); if (!MS) continue; // We do not want to handle sections that are not alive, so just remove // them instead of trying to merge. if (!MS->Live) continue; StringRef OutsecName = getOutputSectionName(MS); uint32_t Alignment = std::max(MS->Alignment, MS->Entsize); auto I = llvm::find_if(MergeSections, [=](MergeSyntheticSection *Sec) { // While we could create a single synthetic section for two different // values of Entsize, it is better to take Entsize into consideration. // // With a single synthetic section no two pieces with different Entsize // could be equal, so we may as well have two sections. // // Using Entsize in here also allows us to propagate it to the synthetic // section. return Sec->Name == OutsecName && Sec->Flags == MS->Flags && Sec->Entsize == MS->Entsize && Sec->Alignment == Alignment; }); if (I == MergeSections.end()) { MergeSyntheticSection *Syn = createMergeSynthetic(OutsecName, MS->Type, MS->Flags, Alignment); MergeSections.push_back(Syn); I = std::prev(MergeSections.end()); S = Syn; Syn->Entsize = MS->Entsize; } else { S = nullptr; } (*I)->addSection(MS); } for (auto *MS : MergeSections) MS->finalizeContents(); std::vector &V = InputSections; V.erase(std::remove(V.begin(), V.end(), nullptr), V.end()); } MipsRldMapSection::MipsRldMapSection() : SyntheticSection(SHF_ALLOC | SHF_WRITE, SHT_PROGBITS, Config->Wordsize, ".rld_map") {} ARMExidxSentinelSection::ARMExidxSentinelSection() : SyntheticSection(SHF_ALLOC | SHF_LINK_ORDER, SHT_ARM_EXIDX, Config->Wordsize, ".ARM.exidx") {} // Write a terminating sentinel entry to the end of the .ARM.exidx table. // This section will have been sorted last in the .ARM.exidx table. // This table entry will have the form: // | PREL31 upper bound of code that has exception tables | EXIDX_CANTUNWIND | // The sentinel must have the PREL31 value of an address higher than any // address described by any other table entry. void ARMExidxSentinelSection::writeTo(uint8_t *Buf) { assert(Highest); uint64_t S = Highest->getParent()->Addr + Highest->getOffset(Highest->getSize()); uint64_t P = getVA(); Target->relocateOne(Buf, R_ARM_PREL31, S - P); write32le(Buf + 4, 1); } // The sentinel has to be removed if there are no other .ARM.exidx entries. bool ARMExidxSentinelSection::empty() const { OutputSection *OS = getParent(); for (auto *B : OS->SectionCommands) if (auto *ISD = dyn_cast(B)) for (auto *S : ISD->Sections) if (!isa(S)) return false; return true; } ThunkSection::ThunkSection(OutputSection *OS, uint64_t Off) : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS, Config->Wordsize, ".text.thunk") { this->Parent = OS; this->OutSecOff = Off; } void ThunkSection::addThunk(Thunk *T) { uint64_t Off = alignTo(Size, T->Alignment); T->Offset = Off; Thunks.push_back(T); T->addSymbols(*this); Size = Off + T->size(); } void ThunkSection::writeTo(uint8_t *Buf) { for (const Thunk *T : Thunks) T->writeTo(Buf + T->Offset, *this); } InputSection *ThunkSection::getTargetInputSection() const { if (Thunks.empty()) return nullptr; const Thunk *T = Thunks.front(); return T->getTargetInputSection(); } InputSection *InX::ARMAttributes; BssSection *InX::Bss; BssSection *InX::BssRelRo; BuildIdSection *InX::BuildId; EhFrameHeader *InX::EhFrameHdr; EhFrameSection *InX::EhFrame; SyntheticSection *InX::Dynamic; StringTableSection *InX::DynStrTab; SymbolTableBaseSection *InX::DynSymTab; InputSection *InX::Interp; GdbIndexSection *InX::GdbIndex; GotSection *InX::Got; GotPltSection *InX::GotPlt; GnuHashTableSection *InX::GnuHashTab; HashTableSection *InX::HashTab; IgotPltSection *InX::IgotPlt; MipsGotSection *InX::MipsGot; MipsRldMapSection *InX::MipsRldMap; PltSection *InX::Plt; PltSection *InX::Iplt; RelocationBaseSection *InX::RelaDyn; RelocationBaseSection *InX::RelaPlt; RelocationBaseSection *InX::RelaIplt; StringTableSection *InX::ShStrTab; StringTableSection *InX::StrTab; SymbolTableBaseSection *InX::SymTab; template GdbIndexSection *elf::createGdbIndex(); template GdbIndexSection *elf::createGdbIndex(); template GdbIndexSection *elf::createGdbIndex(); template GdbIndexSection *elf::createGdbIndex(); template void EhFrameSection::addSection(InputSectionBase *); template void EhFrameSection::addSection(InputSectionBase *); template void EhFrameSection::addSection(InputSectionBase *); template void EhFrameSection::addSection(InputSectionBase *); template void PltSection::addEntry(Symbol &Sym); template void PltSection::addEntry(Symbol &Sym); template void PltSection::addEntry(Symbol &Sym); template void PltSection::addEntry(Symbol &Sym); template class elf::MipsAbiFlagsSection; template class elf::MipsAbiFlagsSection; template class elf::MipsAbiFlagsSection; template class elf::MipsAbiFlagsSection; template class elf::MipsOptionsSection; template class elf::MipsOptionsSection; template class elf::MipsOptionsSection; template class elf::MipsOptionsSection; template class elf::MipsReginfoSection; template class elf::MipsReginfoSection; template class elf::MipsReginfoSection; template class elf::MipsReginfoSection; template class elf::DynamicSection; template class elf::DynamicSection; template class elf::DynamicSection; template class elf::DynamicSection; template class elf::RelocationSection; template class elf::RelocationSection; template class elf::RelocationSection; template class elf::RelocationSection; template class elf::AndroidPackedRelocationSection; template class elf::AndroidPackedRelocationSection; template class elf::AndroidPackedRelocationSection; template class elf::AndroidPackedRelocationSection; template class elf::SymbolTableSection; template class elf::SymbolTableSection; template class elf::SymbolTableSection; template class elf::SymbolTableSection; template class elf::VersionTableSection; template class elf::VersionTableSection; template class elf::VersionTableSection; template class elf::VersionTableSection; template class elf::VersionNeedSection; template class elf::VersionNeedSection; template class elf::VersionNeedSection; template class elf::VersionNeedSection; template class elf::VersionDefinitionSection; template class elf::VersionDefinitionSection; template class elf::VersionDefinitionSection; template class elf::VersionDefinitionSection; Index: vendor/lld/dist-release_60/ELF/Writer.cpp =================================================================== --- vendor/lld/dist-release_60/ELF/Writer.cpp (revision 328369) +++ vendor/lld/dist-release_60/ELF/Writer.cpp (revision 328370) @@ -1,2070 +1,2071 @@ //===- Writer.cpp ---------------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Writer.h" #include "AArch64ErrataFix.h" #include "Config.h" #include "Filesystem.h" #include "LinkerScript.h" #include "MapFile.h" #include "OutputSections.h" #include "Relocations.h" #include "Strings.h" #include "SymbolTable.h" #include "Symbols.h" #include "SyntheticSections.h" #include "Target.h" #include "lld/Common/Memory.h" #include "lld/Common/Threads.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringSwitch.h" #include using namespace llvm; using namespace llvm::ELF; using namespace llvm::object; using namespace llvm::support; using namespace llvm::support::endian; using namespace lld; using namespace lld::elf; namespace { // The writer writes a SymbolTable result to a file. template class Writer { public: Writer() : Buffer(errorHandler().OutputBuffer) {} typedef typename ELFT::Shdr Elf_Shdr; typedef typename ELFT::Ehdr Elf_Ehdr; typedef typename ELFT::Phdr Elf_Phdr; void run(); private: void copyLocalSymbols(); void addSectionSymbols(); void forEachRelSec(std::function Fn); void sortSections(); void resolveShfLinkOrder(); void sortInputSections(); void finalizeSections(); void setReservedSymbolSections(); std::vector createPhdrs(); void removeEmptyPTLoad(); void addPtArmExid(std::vector &Phdrs); void assignFileOffsets(); void assignFileOffsetsBinary(); void setPhdrs(); void fixSectionAlignments(); void openFile(); void writeTrapInstr(); void writeHeader(); void writeSections(); void writeSectionsBinary(); void writeBuildId(); std::unique_ptr &Buffer; void addRelIpltSymbols(); void addStartEndSymbols(); void addStartStopSymbols(OutputSection *Sec); uint64_t getEntryAddr(); std::vector Phdrs; uint64_t FileSize; uint64_t SectionHeaderOff; bool HasGotBaseSym = false; }; } // anonymous namespace StringRef elf::getOutputSectionName(InputSectionBase *S) { // ".zdebug_" is a prefix for ZLIB-compressed sections. // Because we decompressed input sections, we want to remove 'z'. if (S->Name.startswith(".zdebug_")) return Saver.save("." + S->Name.substr(2)); if (Config->Relocatable) return S->Name; // This is for --emit-relocs. If .text.foo is emitted as .text.bar, we want // to emit .rela.text.foo as .rela.text.bar for consistency (this is not // technically required, but not doing it is odd). This code guarantees that. if ((S->Type == SHT_REL || S->Type == SHT_RELA) && !isa(S)) { OutputSection *Out = cast(S)->getRelocatedSection()->getOutputSection(); if (S->Type == SHT_RELA) return Saver.save(".rela" + Out->Name); return Saver.save(".rel" + Out->Name); } for (StringRef V : {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.rel.ro.", ".bss.", ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.", ".gcc_except_table.", ".tdata.", ".ARM.exidx.", ".ARM.extab."}) { StringRef Prefix = V.drop_back(); if (S->Name.startswith(V) || S->Name == Prefix) return Prefix; } // CommonSection is identified as "COMMON" in linker scripts. // By default, it should go to .bss section. if (S->Name == "COMMON") return ".bss"; return S->Name; } static bool needsInterpSection() { return !SharedFiles.empty() && !Config->DynamicLinker.empty() && Script->needsInterpSection(); } template void elf::writeResult() { Writer().run(); } template void Writer::removeEmptyPTLoad() { llvm::erase_if(Phdrs, [&](const PhdrEntry *P) { if (P->p_type != PT_LOAD) return false; if (!P->FirstSec) return true; uint64_t Size = P->LastSec->Addr + P->LastSec->Size - P->FirstSec->Addr; return Size == 0; }); } template static void combineEhFrameSections() { for (InputSectionBase *&S : InputSections) { EhInputSection *ES = dyn_cast(S); if (!ES || !ES->Live) continue; InX::EhFrame->addSection(ES); S = nullptr; } std::vector &V = InputSections; V.erase(std::remove(V.begin(), V.end(), nullptr), V.end()); } static Defined *addOptionalRegular(StringRef Name, SectionBase *Sec, uint64_t Val, uint8_t StOther = STV_HIDDEN, uint8_t Binding = STB_GLOBAL) { Symbol *S = Symtab->find(Name); if (!S || S->isDefined()) return nullptr; Symbol *Sym = Symtab->addRegular(Name, StOther, STT_NOTYPE, Val, /*Size=*/0, Binding, Sec, /*File=*/nullptr); return cast(Sym); } // The linker is expected to define some symbols depending on // the linking result. This function defines such symbols. void elf::addReservedSymbols() { if (Config->EMachine == EM_MIPS) { // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer // so that it points to an absolute address which by default is relative // to GOT. Default offset is 0x7ff0. // See "Global Data Symbols" in Chapter 6 in the following document: // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf ElfSym::MipsGp = Symtab->addAbsolute("_gp", STV_HIDDEN, STB_GLOBAL); // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between // start of function and 'gp' pointer into GOT. if (Symtab->find("_gp_disp")) ElfSym::MipsGpDisp = Symtab->addAbsolute("_gp_disp", STV_HIDDEN, STB_GLOBAL); // The __gnu_local_gp is a magic symbol equal to the current value of 'gp' // pointer. This symbol is used in the code generated by .cpload pseudo-op // in case of using -mno-shared option. // https://sourceware.org/ml/binutils/2004-12/msg00094.html if (Symtab->find("__gnu_local_gp")) ElfSym::MipsLocalGp = Symtab->addAbsolute("__gnu_local_gp", STV_HIDDEN, STB_GLOBAL); } ElfSym::GlobalOffsetTable = addOptionalRegular( "_GLOBAL_OFFSET_TABLE_", Out::ElfHeader, Target->GotBaseSymOff); // __ehdr_start is the location of ELF file headers. Note that we define // this symbol unconditionally even when using a linker script, which // differs from the behavior implemented by GNU linker which only define // this symbol if ELF headers are in the memory mapped segment. // __executable_start is not documented, but the expectation of at // least the android libc is that it points to the elf header too. // __dso_handle symbol is passed to cxa_finalize as a marker to identify // each DSO. The address of the symbol doesn't matter as long as they are // different in different DSOs, so we chose the start address of the DSO. for (const char *Name : {"__ehdr_start", "__executable_start", "__dso_handle"}) addOptionalRegular(Name, Out::ElfHeader, 0, STV_HIDDEN); // If linker script do layout we do not need to create any standart symbols. if (Script->HasSectionsCommand) return; auto Add = [](StringRef S, int64_t Pos) { return addOptionalRegular(S, Out::ElfHeader, Pos, STV_DEFAULT); }; ElfSym::Bss = Add("__bss_start", 0); ElfSym::End1 = Add("end", -1); ElfSym::End2 = Add("_end", -1); ElfSym::Etext1 = Add("etext", -1); ElfSym::Etext2 = Add("_etext", -1); ElfSym::Edata1 = Add("edata", -1); ElfSym::Edata2 = Add("_edata", -1); } static OutputSection *findSection(StringRef Name) { for (BaseCommand *Base : Script->SectionCommands) if (auto *Sec = dyn_cast(Base)) if (Sec->Name == Name) return Sec; return nullptr; } // Initialize Out members. template static void createSyntheticSections() { // Initialize all pointers with NULL. This is needed because // you can call lld::elf::main more than once as a library. memset(&Out::First, 0, sizeof(Out)); auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); }; InX::DynStrTab = make(".dynstr", true); InX::Dynamic = make>(); if (Config->AndroidPackDynRelocs) { InX::RelaDyn = make>( Config->IsRela ? ".rela.dyn" : ".rel.dyn"); } else { InX::RelaDyn = make>( Config->IsRela ? ".rela.dyn" : ".rel.dyn", Config->ZCombreloc); } InX::ShStrTab = make(".shstrtab", false); Out::ProgramHeaders = make("", 0, SHF_ALLOC); Out::ProgramHeaders->Alignment = Config->Wordsize; if (needsInterpSection()) { InX::Interp = createInterpSection(); Add(InX::Interp); } else { InX::Interp = nullptr; } if (Config->Strip != StripPolicy::All) { InX::StrTab = make(".strtab", false); InX::SymTab = make>(*InX::StrTab); } if (Config->BuildId != BuildIdKind::None) { InX::BuildId = make(); Add(InX::BuildId); } InX::Bss = make(".bss", 0, 1); Add(InX::Bss); // If there is a SECTIONS command and a .data.rel.ro section name use name // .data.rel.ro.bss so that we match in the .data.rel.ro output section. // This makes sure our relro is contiguous. bool HasDataRelRo = Script->HasSectionsCommand && findSection(".data.rel.ro"); InX::BssRelRo = make( HasDataRelRo ? ".data.rel.ro.bss" : ".bss.rel.ro", 0, 1); Add(InX::BssRelRo); // Add MIPS-specific sections. if (Config->EMachine == EM_MIPS) { if (!Config->Shared && Config->HasDynSymTab) { InX::MipsRldMap = make(); Add(InX::MipsRldMap); } if (auto *Sec = MipsAbiFlagsSection::create()) Add(Sec); if (auto *Sec = MipsOptionsSection::create()) Add(Sec); if (auto *Sec = MipsReginfoSection::create()) Add(Sec); } if (Config->HasDynSymTab) { InX::DynSymTab = make>(*InX::DynStrTab); Add(InX::DynSymTab); In::VerSym = make>(); Add(In::VerSym); if (!Config->VersionDefinitions.empty()) { In::VerDef = make>(); Add(In::VerDef); } In::VerNeed = make>(); Add(In::VerNeed); if (Config->GnuHash) { InX::GnuHashTab = make(); Add(InX::GnuHashTab); } if (Config->SysvHash) { InX::HashTab = make(); Add(InX::HashTab); } Add(InX::Dynamic); Add(InX::DynStrTab); Add(InX::RelaDyn); } // Add .got. MIPS' .got is so different from the other archs, // it has its own class. if (Config->EMachine == EM_MIPS) { InX::MipsGot = make(); Add(InX::MipsGot); } else { InX::Got = make(); Add(InX::Got); } InX::GotPlt = make(); Add(InX::GotPlt); InX::IgotPlt = make(); Add(InX::IgotPlt); if (Config->GdbIndex) { InX::GdbIndex = createGdbIndex(); Add(InX::GdbIndex); } // We always need to add rel[a].plt to output if it has entries. // Even for static linking it can contain R_[*]_IRELATIVE relocations. InX::RelaPlt = make>( Config->IsRela ? ".rela.plt" : ".rel.plt", false /*Sort*/); Add(InX::RelaPlt); // The RelaIplt immediately follows .rel.plt (.rel.dyn for ARM) to ensure // that the IRelative relocations are processed last by the dynamic loader. // We cannot place the iplt section in .rel.dyn when Android relocation // packing is enabled because that would cause a section type mismatch. // However, because the Android dynamic loader reads .rel.plt after .rel.dyn, // we can get the desired behaviour by placing the iplt section in .rel.plt. InX::RelaIplt = make>( (Config->EMachine == EM_ARM && !Config->AndroidPackDynRelocs) ? ".rel.dyn" : InX::RelaPlt->Name, false /*Sort*/); Add(InX::RelaIplt); InX::Plt = make(Target->PltHeaderSize); Add(InX::Plt); InX::Iplt = make(0); Add(InX::Iplt); if (!Config->Relocatable) { if (Config->EhFrameHdr) { InX::EhFrameHdr = make(); Add(InX::EhFrameHdr); } InX::EhFrame = make(); Add(InX::EhFrame); } if (InX::SymTab) Add(InX::SymTab); Add(InX::ShStrTab); if (InX::StrTab) Add(InX::StrTab); if (Config->EMachine == EM_ARM && !Config->Relocatable) // Add a sentinel to terminate .ARM.exidx. It helps an unwinder // to find the exact address range of the last entry. Add(make()); } // The main function of the writer. template void Writer::run() { // Create linker-synthesized sections such as .got or .plt. // Such sections are of type input section. createSyntheticSections(); if (!Config->Relocatable) combineEhFrameSections(); // We want to process linker script commands. When SECTIONS command // is given we let it create sections. Script->processSectionCommands(); // Linker scripts controls how input sections are assigned to output sections. // Input sections that were not handled by scripts are called "orphans", and // they are assigned to output sections by the default rule. Process that. Script->addOrphanSections(); if (Config->Discard != DiscardPolicy::All) copyLocalSymbols(); if (Config->CopyRelocs) addSectionSymbols(); // Now that we have a complete set of output sections. This function // completes section contents. For example, we need to add strings // to the string table, and add entries to .got and .plt. // finalizeSections does that. finalizeSections(); if (errorCount()) return; + Script->assignAddresses(); + // If -compressed-debug-sections is specified, we need to compress // .debug_* sections. Do it right now because it changes the size of // output sections. - parallelForEach(OutputSections, - [](OutputSection *Sec) { Sec->maybeCompress(); }); + for (OutputSection *Sec : OutputSections) + Sec->maybeCompress(); - Script->assignAddresses(); Script->allocateHeaders(Phdrs); // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a // 0 sized region. This has to be done late since only after assignAddresses // we know the size of the sections. removeEmptyPTLoad(); if (!Config->OFormatBinary) assignFileOffsets(); else assignFileOffsetsBinary(); setPhdrs(); if (Config->Relocatable) { for (OutputSection *Sec : OutputSections) Sec->Addr = 0; } // It does not make sense try to open the file if we have error already. if (errorCount()) return; // Write the result down to a file. openFile(); if (errorCount()) return; if (!Config->OFormatBinary) { writeTrapInstr(); writeHeader(); writeSections(); } else { writeSectionsBinary(); } // Backfill .note.gnu.build-id section content. This is done at last // because the content is usually a hash value of the entire output file. writeBuildId(); if (errorCount()) return; // Handle -Map option. writeMapFile(); if (errorCount()) return; if (auto E = Buffer->commit()) error("failed to write to the output file: " + toString(std::move(E))); } static bool shouldKeepInSymtab(SectionBase *Sec, StringRef SymName, const Symbol &B) { if (B.isFile() || B.isSection()) return false; // If sym references a section in a discarded group, don't keep it. if (Sec == &InputSection::Discarded) return false; if (Config->Discard == DiscardPolicy::None) return true; // In ELF assembly .L symbols are normally discarded by the assembler. // If the assembler fails to do so, the linker discards them if // * --discard-locals is used. // * The symbol is in a SHF_MERGE section, which is normally the reason for // the assembler keeping the .L symbol. if (!SymName.startswith(".L") && !SymName.empty()) return true; if (Config->Discard == DiscardPolicy::Locals) return false; return !Sec || !(Sec->Flags & SHF_MERGE); } static bool includeInSymtab(const Symbol &B) { if (!B.isLocal() && !B.IsUsedInRegularObj) return false; if (auto *D = dyn_cast(&B)) { // Always include absolute symbols. SectionBase *Sec = D->Section; if (!Sec) return true; Sec = Sec->Repl; // Exclude symbols pointing to garbage-collected sections. if (isa(Sec) && !Sec->Live) return false; if (auto *S = dyn_cast(Sec)) if (!S->getSectionPiece(D->Value)->Live) return false; return true; } return B.Used; } // Local symbols are not in the linker's symbol table. This function scans // each object file's symbol table to copy local symbols to the output. template void Writer::copyLocalSymbols() { if (!InX::SymTab) return; for (InputFile *File : ObjectFiles) { ObjFile *F = cast>(File); for (Symbol *B : F->getLocalSymbols()) { if (!B->isLocal()) fatal(toString(F) + ": broken object: getLocalSymbols returns a non-local symbol"); auto *DR = dyn_cast(B); // No reason to keep local undefined symbol in symtab. if (!DR) continue; if (!includeInSymtab(*B)) continue; SectionBase *Sec = DR->Section; if (!shouldKeepInSymtab(Sec, B->getName(), *B)) continue; InX::SymTab->addSymbol(B); } } } template void Writer::addSectionSymbols() { // Create a section symbol for each output section so that we can represent // relocations that point to the section. If we know that no relocation is // referring to a section (that happens if the section is a synthetic one), we // don't create a section symbol for that section. for (BaseCommand *Base : Script->SectionCommands) { auto *Sec = dyn_cast(Base); if (!Sec) continue; auto I = llvm::find_if(Sec->SectionCommands, [](BaseCommand *Base) { if (auto *ISD = dyn_cast(Base)) return !ISD->Sections.empty(); return false; }); if (I == Sec->SectionCommands.end()) continue; InputSection *IS = cast(*I)->Sections[0]; // Relocations are not using REL[A] section symbols. if (IS->Type == SHT_REL || IS->Type == SHT_RELA) continue; // Unlike other synthetic sections, mergeable output sections contain data // copied from input sections, and there may be a relocation pointing to its // contents if -r or -emit-reloc are given. if (isa(IS) && !(IS->Flags & SHF_MERGE)) continue; auto *Sym = make(IS->File, "", STB_LOCAL, /*StOther=*/0, STT_SECTION, /*Value=*/0, /*Size=*/0, IS); InX::SymTab->addSymbol(Sym); } } // Today's loaders have a feature to make segments read-only after // processing dynamic relocations to enhance security. PT_GNU_RELRO // is defined for that. // // This function returns true if a section needs to be put into a // PT_GNU_RELRO segment. static bool isRelroSection(const OutputSection *Sec) { if (!Config->ZRelro) return false; uint64_t Flags = Sec->Flags; // Non-allocatable or non-writable sections don't need RELRO because // they are not writable or not even mapped to memory in the first place. // RELRO is for sections that are essentially read-only but need to // be writable only at process startup to allow dynamic linker to // apply relocations. if (!(Flags & SHF_ALLOC) || !(Flags & SHF_WRITE)) return false; // Once initialized, TLS data segments are used as data templates // for a thread-local storage. For each new thread, runtime // allocates memory for a TLS and copy templates there. No thread // are supposed to use templates directly. Thus, it can be in RELRO. if (Flags & SHF_TLS) return true; // .init_array, .preinit_array and .fini_array contain pointers to // functions that are executed on process startup or exit. These // pointers are set by the static linker, and they are not expected // to change at runtime. But if you are an attacker, you could do // interesting things by manipulating pointers in .fini_array, for // example. So they are put into RELRO. uint32_t Type = Sec->Type; if (Type == SHT_INIT_ARRAY || Type == SHT_FINI_ARRAY || Type == SHT_PREINIT_ARRAY) return true; // .got contains pointers to external symbols. They are resolved by // the dynamic linker when a module is loaded into memory, and after // that they are not expected to change. So, it can be in RELRO. if (InX::Got && Sec == InX::Got->getParent()) return true; // .got.plt contains pointers to external function symbols. They are // by default resolved lazily, so we usually cannot put it into RELRO. // However, if "-z now" is given, the lazy symbol resolution is // disabled, which enables us to put it into RELRO. if (Sec == InX::GotPlt->getParent()) return Config->ZNow; // .dynamic section contains data for the dynamic linker, and // there's no need to write to it at runtime, so it's better to put // it into RELRO. if (Sec == InX::Dynamic->getParent()) return true; // Sections with some special names are put into RELRO. This is a // bit unfortunate because section names shouldn't be significant in // ELF in spirit. But in reality many linker features depend on // magic section names. StringRef S = Sec->Name; return S == ".data.rel.ro" || S == ".bss.rel.ro" || S == ".ctors" || S == ".dtors" || S == ".jcr" || S == ".eh_frame" || S == ".openbsd.randomdata"; } // We compute a rank for each section. The rank indicates where the // section should be placed in the file. Instead of using simple // numbers (0,1,2...), we use a series of flags. One for each decision // point when placing the section. // Using flags has two key properties: // * It is easy to check if a give branch was taken. // * It is easy two see how similar two ranks are (see getRankProximity). enum RankFlags { RF_NOT_ADDR_SET = 1 << 16, RF_NOT_INTERP = 1 << 15, RF_NOT_ALLOC = 1 << 14, RF_WRITE = 1 << 13, RF_EXEC_WRITE = 1 << 12, RF_EXEC = 1 << 11, RF_NON_TLS_BSS = 1 << 10, RF_NON_TLS_BSS_RO = 1 << 9, RF_NOT_TLS = 1 << 8, RF_BSS = 1 << 7, RF_PPC_NOT_TOCBSS = 1 << 6, RF_PPC_OPD = 1 << 5, RF_PPC_TOCL = 1 << 4, RF_PPC_TOC = 1 << 3, RF_PPC_BRANCH_LT = 1 << 2, RF_MIPS_GPREL = 1 << 1, RF_MIPS_NOT_GOT = 1 << 0 }; static unsigned getSectionRank(const OutputSection *Sec) { unsigned Rank = 0; // We want to put section specified by -T option first, so we // can start assigning VA starting from them later. if (Config->SectionStartMap.count(Sec->Name)) return Rank; Rank |= RF_NOT_ADDR_SET; // Put .interp first because some loaders want to see that section // on the first page of the executable file when loaded into memory. if (Sec->Name == ".interp") return Rank; Rank |= RF_NOT_INTERP; // Allocatable sections go first to reduce the total PT_LOAD size and // so debug info doesn't change addresses in actual code. if (!(Sec->Flags & SHF_ALLOC)) return Rank | RF_NOT_ALLOC; // Sort sections based on their access permission in the following // order: R, RX, RWX, RW. This order is based on the following // considerations: // * Read-only sections come first such that they go in the // PT_LOAD covering the program headers at the start of the file. // * Read-only, executable sections come next, unless the // -no-rosegment option is used. // * Writable, executable sections follow such that .plt on // architectures where it needs to be writable will be placed // between .text and .data. // * Writable sections come last, such that .bss lands at the very // end of the last PT_LOAD. bool IsExec = Sec->Flags & SHF_EXECINSTR; bool IsWrite = Sec->Flags & SHF_WRITE; if (IsExec) { if (IsWrite) Rank |= RF_EXEC_WRITE; else if (!Config->SingleRoRx) Rank |= RF_EXEC; } else { if (IsWrite) Rank |= RF_WRITE; } // If we got here we know that both A and B are in the same PT_LOAD. bool IsTls = Sec->Flags & SHF_TLS; bool IsNoBits = Sec->Type == SHT_NOBITS; // The first requirement we have is to put (non-TLS) nobits sections last. The // reason is that the only thing the dynamic linker will see about them is a // p_memsz that is larger than p_filesz. Seeing that it zeros the end of the // PT_LOAD, so that has to correspond to the nobits sections. bool IsNonTlsNoBits = IsNoBits && !IsTls; if (IsNonTlsNoBits) Rank |= RF_NON_TLS_BSS; // We place nobits RelRo sections before plain r/w ones, and non-nobits RelRo // sections after r/w ones, so that the RelRo sections are contiguous. bool IsRelRo = isRelroSection(Sec); if (IsNonTlsNoBits && !IsRelRo) Rank |= RF_NON_TLS_BSS_RO; if (!IsNonTlsNoBits && IsRelRo) Rank |= RF_NON_TLS_BSS_RO; // The TLS initialization block needs to be a single contiguous block in a R/W // PT_LOAD, so stick TLS sections directly before the other RelRo R/W // sections. The TLS NOBITS sections are placed here as they don't take up // virtual address space in the PT_LOAD. if (!IsTls) Rank |= RF_NOT_TLS; // Within the TLS initialization block, the non-nobits sections need to appear // first. if (IsNoBits) Rank |= RF_BSS; // Some architectures have additional ordering restrictions for sections // within the same PT_LOAD. if (Config->EMachine == EM_PPC64) { // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections // that we would like to make sure appear is a specific order to maximize // their coverage by a single signed 16-bit offset from the TOC base // pointer. Conversely, the special .tocbss section should be first among // all SHT_NOBITS sections. This will put it next to the loaded special // PPC64 sections (and, thus, within reach of the TOC base pointer). StringRef Name = Sec->Name; if (Name != ".tocbss") Rank |= RF_PPC_NOT_TOCBSS; if (Name == ".opd") Rank |= RF_PPC_OPD; if (Name == ".toc1") Rank |= RF_PPC_TOCL; if (Name == ".toc") Rank |= RF_PPC_TOC; if (Name == ".branch_lt") Rank |= RF_PPC_BRANCH_LT; } if (Config->EMachine == EM_MIPS) { // All sections with SHF_MIPS_GPREL flag should be grouped together // because data in these sections is addressable with a gp relative address. if (Sec->Flags & SHF_MIPS_GPREL) Rank |= RF_MIPS_GPREL; if (Sec->Name != ".got") Rank |= RF_MIPS_NOT_GOT; } return Rank; } static bool compareSections(const BaseCommand *ACmd, const BaseCommand *BCmd) { const OutputSection *A = cast(ACmd); const OutputSection *B = cast(BCmd); if (A->SortRank != B->SortRank) return A->SortRank < B->SortRank; if (!(A->SortRank & RF_NOT_ADDR_SET)) return Config->SectionStartMap.lookup(A->Name) < Config->SectionStartMap.lookup(B->Name); return false; } void PhdrEntry::add(OutputSection *Sec) { LastSec = Sec; if (!FirstSec) FirstSec = Sec; p_align = std::max(p_align, Sec->Alignment); if (p_type == PT_LOAD) Sec->PtLoad = this; } // The beginning and the ending of .rel[a].plt section are marked // with __rel[a]_iplt_{start,end} symbols if it is a statically linked // executable. The runtime needs these symbols in order to resolve // all IRELATIVE relocs on startup. For dynamic executables, we don't // need these symbols, since IRELATIVE relocs are resolved through GOT // and PLT. For details, see http://www.airs.com/blog/archives/403. template void Writer::addRelIpltSymbols() { if (!Config->Static) return; StringRef S = Config->IsRela ? "__rela_iplt_start" : "__rel_iplt_start"; addOptionalRegular(S, InX::RelaIplt, 0, STV_HIDDEN, STB_WEAK); S = Config->IsRela ? "__rela_iplt_end" : "__rel_iplt_end"; addOptionalRegular(S, InX::RelaIplt, -1, STV_HIDDEN, STB_WEAK); } template void Writer::forEachRelSec(std::function Fn) { // Scan all relocations. Each relocation goes through a series // of tests to determine if it needs special treatment, such as // creating GOT, PLT, copy relocations, etc. // Note that relocations for non-alloc sections are directly // processed by InputSection::relocateNonAlloc. for (InputSectionBase *IS : InputSections) if (IS->Live && isa(IS) && (IS->Flags & SHF_ALLOC)) Fn(*IS); for (EhInputSection *ES : InX::EhFrame->Sections) Fn(*ES); } // This function generates assignments for predefined symbols (e.g. _end or // _etext) and inserts them into the commands sequence to be processed at the // appropriate time. This ensures that the value is going to be correct by the // time any references to these symbols are processed and is equivalent to // defining these symbols explicitly in the linker script. template void Writer::setReservedSymbolSections() { if (ElfSym::GlobalOffsetTable) { // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention to // be at some offset from the base of the .got section, usually 0 or the end // of the .got InputSection *GotSection = InX::MipsGot ? cast(InX::MipsGot) : cast(InX::Got); ElfSym::GlobalOffsetTable->Section = GotSection; } PhdrEntry *Last = nullptr; PhdrEntry *LastRO = nullptr; for (PhdrEntry *P : Phdrs) { if (P->p_type != PT_LOAD) continue; Last = P; if (!(P->p_flags & PF_W)) LastRO = P; } if (LastRO) { // _etext is the first location after the last read-only loadable segment. if (ElfSym::Etext1) ElfSym::Etext1->Section = LastRO->LastSec; if (ElfSym::Etext2) ElfSym::Etext2->Section = LastRO->LastSec; } if (Last) { // _edata points to the end of the last mapped initialized section. OutputSection *Edata = nullptr; for (OutputSection *OS : OutputSections) { if (OS->Type != SHT_NOBITS) Edata = OS; if (OS == Last->LastSec) break; } if (ElfSym::Edata1) ElfSym::Edata1->Section = Edata; if (ElfSym::Edata2) ElfSym::Edata2->Section = Edata; // _end is the first location after the uninitialized data region. if (ElfSym::End1) ElfSym::End1->Section = Last->LastSec; if (ElfSym::End2) ElfSym::End2->Section = Last->LastSec; } if (ElfSym::Bss) ElfSym::Bss->Section = findSection(".bss"); // Setup MIPS _gp_disp/__gnu_local_gp symbols which should // be equal to the _gp symbol's value. if (ElfSym::MipsGp) { // Find GP-relative section with the lowest address // and use this address to calculate default _gp value. for (OutputSection *OS : OutputSections) { if (OS->Flags & SHF_MIPS_GPREL) { ElfSym::MipsGp->Section = OS; ElfSym::MipsGp->Value = 0x7ff0; break; } } } } // We want to find how similar two ranks are. // The more branches in getSectionRank that match, the more similar they are. // Since each branch corresponds to a bit flag, we can just use // countLeadingZeros. static int getRankProximityAux(OutputSection *A, OutputSection *B) { return countLeadingZeros(A->SortRank ^ B->SortRank); } static int getRankProximity(OutputSection *A, BaseCommand *B) { if (auto *Sec = dyn_cast(B)) if (Sec->Live) return getRankProximityAux(A, Sec); return -1; } // When placing orphan sections, we want to place them after symbol assignments // so that an orphan after // begin_foo = .; // foo : { *(foo) } // end_foo = .; // doesn't break the intended meaning of the begin/end symbols. // We don't want to go over sections since findOrphanPos is the // one in charge of deciding the order of the sections. // We don't want to go over changes to '.', since doing so in // rx_sec : { *(rx_sec) } // . = ALIGN(0x1000); // /* The RW PT_LOAD starts here*/ // rw_sec : { *(rw_sec) } // would mean that the RW PT_LOAD would become unaligned. static bool shouldSkip(BaseCommand *Cmd) { if (isa(Cmd)) return false; if (auto *Assign = dyn_cast(Cmd)) return Assign->Name != "."; return true; } // We want to place orphan sections so that they share as much // characteristics with their neighbors as possible. For example, if // both are rw, or both are tls. template static std::vector::iterator findOrphanPos(std::vector::iterator B, std::vector::iterator E) { OutputSection *Sec = cast(*E); // Find the first element that has as close a rank as possible. auto I = std::max_element(B, E, [=](BaseCommand *A, BaseCommand *B) { return getRankProximity(Sec, A) < getRankProximity(Sec, B); }); if (I == E) return E; // Consider all existing sections with the same proximity. int Proximity = getRankProximity(Sec, *I); for (; I != E; ++I) { auto *CurSec = dyn_cast(*I); if (!CurSec || !CurSec->Live) continue; if (getRankProximity(Sec, CurSec) != Proximity || Sec->SortRank < CurSec->SortRank) break; } auto IsLiveSection = [](BaseCommand *Cmd) { auto *OS = dyn_cast(Cmd); return OS && OS->Live; }; auto J = std::find_if(llvm::make_reverse_iterator(I), llvm::make_reverse_iterator(B), IsLiveSection); I = J.base(); // As a special case, if the orphan section is the last section, put // it at the very end, past any other commands. // This matches bfd's behavior and is convenient when the linker script fully // specifies the start of the file, but doesn't care about the end (the non // alloc sections for example). auto NextSec = std::find_if(I, E, IsLiveSection); if (NextSec == E) return E; while (I != E && shouldSkip(*I)) ++I; return I; } // If no layout was provided by linker script, we want to apply default // sorting for special input sections and handle --symbol-ordering-file. template void Writer::sortInputSections() { assert(!Script->HasSectionsCommand); // Sort input sections by priority using the list provided // by --symbol-ordering-file. DenseMap Order = buildSectionOrder(); if (!Order.empty()) for (BaseCommand *Base : Script->SectionCommands) if (auto *Sec = dyn_cast(Base)) if (Sec->Live) Sec->sort([&](InputSectionBase *S) { return Order.lookup(S); }); // Sort input sections by section name suffixes for // __attribute__((init_priority(N))). if (OutputSection *Sec = findSection(".init_array")) Sec->sortInitFini(); if (OutputSection *Sec = findSection(".fini_array")) Sec->sortInitFini(); // Sort input sections by the special rule for .ctors and .dtors. if (OutputSection *Sec = findSection(".ctors")) Sec->sortCtorsDtors(); if (OutputSection *Sec = findSection(".dtors")) Sec->sortCtorsDtors(); } template void Writer::sortSections() { Script->adjustSectionsBeforeSorting(); // Don't sort if using -r. It is not necessary and we want to preserve the // relative order for SHF_LINK_ORDER sections. if (Config->Relocatable) return; for (BaseCommand *Base : Script->SectionCommands) if (auto *Sec = dyn_cast(Base)) Sec->SortRank = getSectionRank(Sec); if (!Script->HasSectionsCommand) { sortInputSections(); // We know that all the OutputSections are contiguous in this case. auto E = Script->SectionCommands.end(); auto I = Script->SectionCommands.begin(); auto IsSection = [](BaseCommand *Base) { return isa(Base); }; I = std::find_if(I, E, IsSection); E = std::find_if(llvm::make_reverse_iterator(E), llvm::make_reverse_iterator(I), IsSection) .base(); std::stable_sort(I, E, compareSections); return; } // Orphan sections are sections present in the input files which are // not explicitly placed into the output file by the linker script. // // The sections in the linker script are already in the correct // order. We have to figuere out where to insert the orphan // sections. // // The order of the sections in the script is arbitrary and may not agree with // compareSections. This means that we cannot easily define a strict weak // ordering. To see why, consider a comparison of a section in the script and // one not in the script. We have a two simple options: // * Make them equivalent (a is not less than b, and b is not less than a). // The problem is then that equivalence has to be transitive and we can // have sections a, b and c with only b in a script and a less than c // which breaks this property. // * Use compareSectionsNonScript. Given that the script order doesn't have // to match, we can end up with sections a, b, c, d where b and c are in the // script and c is compareSectionsNonScript less than b. In which case d // can be equivalent to c, a to b and d < a. As a concrete example: // .a (rx) # not in script // .b (rx) # in script // .c (ro) # in script // .d (ro) # not in script // // The way we define an order then is: // * Sort only the orphan sections. They are in the end right now. // * Move each orphan section to its preferred position. We try // to put each section in the last position where it it can share // a PT_LOAD. // // There is some ambiguity as to where exactly a new entry should be // inserted, because Commands contains not only output section // commands but also other types of commands such as symbol assignment // expressions. There's no correct answer here due to the lack of the // formal specification of the linker script. We use heuristics to // determine whether a new output command should be added before or // after another commands. For the details, look at shouldSkip // function. auto I = Script->SectionCommands.begin(); auto E = Script->SectionCommands.end(); auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) { if (auto *Sec = dyn_cast(Base)) return Sec->Live && Sec->SectionIndex == INT_MAX; return false; }); // Sort the orphan sections. std::stable_sort(NonScriptI, E, compareSections); // As a horrible special case, skip the first . assignment if it is before any // section. We do this because it is common to set a load address by starting // the script with ". = 0xabcd" and the expectation is that every section is // after that. auto FirstSectionOrDotAssignment = std::find_if(I, E, [](BaseCommand *Cmd) { return !shouldSkip(Cmd); }); if (FirstSectionOrDotAssignment != E && isa(**FirstSectionOrDotAssignment)) ++FirstSectionOrDotAssignment; I = FirstSectionOrDotAssignment; while (NonScriptI != E) { auto Pos = findOrphanPos(I, NonScriptI); OutputSection *Orphan = cast(*NonScriptI); // As an optimization, find all sections with the same sort rank // and insert them with one rotate. unsigned Rank = Orphan->SortRank; auto End = std::find_if(NonScriptI + 1, E, [=](BaseCommand *Cmd) { return cast(Cmd)->SortRank != Rank; }); std::rotate(Pos, NonScriptI, End); NonScriptI = End; } Script->adjustSectionsAfterSorting(); } static bool compareByFilePosition(InputSection *A, InputSection *B) { // Synthetic, i. e. a sentinel section, should go last. if (A->kind() == InputSectionBase::Synthetic || B->kind() == InputSectionBase::Synthetic) return A->kind() != InputSectionBase::Synthetic; InputSection *LA = A->getLinkOrderDep(); InputSection *LB = B->getLinkOrderDep(); OutputSection *AOut = LA->getParent(); OutputSection *BOut = LB->getParent(); if (AOut != BOut) return AOut->SectionIndex < BOut->SectionIndex; return LA->OutSecOff < LB->OutSecOff; } // This function is used by the --merge-exidx-entries to detect duplicate // .ARM.exidx sections. It is Arm only. // // The .ARM.exidx section is of the form: // | PREL31 offset to function | Unwind instructions for function | // where the unwind instructions are either a small number of unwind // instructions inlined into the table entry, the special CANT_UNWIND value of // 0x1 or a PREL31 offset into a .ARM.extab Section that contains unwind // instructions. // // We return true if all the unwind instructions in the .ARM.exidx entries of // Cur can be merged into the last entry of Prev. static bool isDuplicateArmExidxSec(InputSection *Prev, InputSection *Cur) { // References to .ARM.Extab Sections have bit 31 clear and are not the // special EXIDX_CANTUNWIND bit-pattern. auto IsExtabRef = [](uint32_t Unwind) { return (Unwind & 0x80000000) == 0 && Unwind != 0x1; }; struct ExidxEntry { ulittle32_t Fn; ulittle32_t Unwind; }; // Get the last table Entry from the previous .ARM.exidx section. const ExidxEntry &PrevEntry = *reinterpret_cast( Prev->Data.data() + Prev->getSize() - sizeof(ExidxEntry)); if (IsExtabRef(PrevEntry.Unwind)) return false; // We consider the unwind instructions of an .ARM.exidx table entry // a duplicate if the previous unwind instructions if: // - Both are the special EXIDX_CANTUNWIND. // - Both are the same inline unwind instructions. // We do not attempt to follow and check links into .ARM.extab tables as // consecutive identical entries are rare and the effort to check that they // are identical is high. if (isa(Cur)) // Exidx sentinel section has implicit EXIDX_CANTUNWIND; return PrevEntry.Unwind == 0x1; ArrayRef Entries( reinterpret_cast(Cur->Data.data()), Cur->getSize() / sizeof(ExidxEntry)); for (const ExidxEntry &Entry : Entries) if (IsExtabRef(Entry.Unwind) || Entry.Unwind != PrevEntry.Unwind) return false; // All table entries in this .ARM.exidx Section can be merged into the // previous Section. return true; } template void Writer::resolveShfLinkOrder() { for (OutputSection *Sec : OutputSections) { if (!(Sec->Flags & SHF_LINK_ORDER)) continue; // Link order may be distributed across several InputSectionDescriptions // but sort must consider them all at once. std::vector ScriptSections; std::vector Sections; for (BaseCommand *Base : Sec->SectionCommands) { if (auto *ISD = dyn_cast(Base)) { for (InputSection *&IS : ISD->Sections) { ScriptSections.push_back(&IS); Sections.push_back(IS); } } } std::stable_sort(Sections.begin(), Sections.end(), compareByFilePosition); if (!Config->Relocatable && Config->EMachine == EM_ARM && Sec->Type == SHT_ARM_EXIDX) { if (!Sections.empty() && isa(Sections.back())) { assert(Sections.size() >= 2 && "We should create a sentinel section only if there are " "alive regular exidx sections."); // The last executable section is required to fill the sentinel. // Remember it here so that we don't have to find it again. auto *Sentinel = cast(Sections.back()); Sentinel->Highest = Sections[Sections.size() - 2]->getLinkOrderDep(); } if (Config->MergeArmExidx) { // The EHABI for the Arm Architecture permits consecutive identical // table entries to be merged. We use a simple implementation that // removes a .ARM.exidx Input Section if it can be merged into the // previous one. This does not require any rewriting of InputSection // contents but misses opportunities for fine grained deduplication // where only a subset of the InputSection contents can be merged. int Cur = 1; int Prev = 0; // The last one is a sentinel entry which should not be removed. int N = Sections.size() - 1; while (Cur < N) { if (isDuplicateArmExidxSec(Sections[Prev], Sections[Cur])) Sections[Cur] = nullptr; else Prev = Cur; ++Cur; } } } for (int I = 0, N = Sections.size(); I < N; ++I) *ScriptSections[I] = Sections[I]; // Remove the Sections we marked as duplicate earlier. for (BaseCommand *Base : Sec->SectionCommands) if (auto *ISD = dyn_cast(Base)) ISD->Sections.erase( std::remove(ISD->Sections.begin(), ISD->Sections.end(), nullptr), ISD->Sections.end()); } } static void applySynthetic(const std::vector &Sections, std::function Fn) { for (SyntheticSection *SS : Sections) if (SS && SS->getParent() && !SS->empty()) Fn(SS); } // In order to allow users to manipulate linker-synthesized sections, // we had to add synthetic sections to the input section list early, // even before we make decisions whether they are needed. This allows // users to write scripts like this: ".mygot : { .got }". // // Doing it has an unintended side effects. If it turns out that we // don't need a .got (for example) at all because there's no // relocation that needs a .got, we don't want to emit .got. // // To deal with the above problem, this function is called after // scanRelocations is called to remove synthetic sections that turn // out to be empty. static void removeUnusedSyntheticSections() { // All input synthetic sections that can be empty are placed after // all regular ones. We iterate over them all and exit at first // non-synthetic. for (InputSectionBase *S : llvm::reverse(InputSections)) { SyntheticSection *SS = dyn_cast(S); if (!SS) return; OutputSection *OS = SS->getParent(); if (!SS->empty() || !OS) continue; std::vector::iterator Empty = OS->SectionCommands.end(); for (auto I = OS->SectionCommands.begin(), E = OS->SectionCommands.end(); I != E; ++I) { BaseCommand *B = *I; if (auto *ISD = dyn_cast(B)) { llvm::erase_if(ISD->Sections, [=](InputSection *IS) { return IS == SS; }); if (ISD->Sections.empty()) Empty = I; } } if (Empty != OS->SectionCommands.end()) OS->SectionCommands.erase(Empty); // If there are no other sections in the output section, remove it from the // output. if (OS->SectionCommands.empty()) OS->Live = false; } } // Returns true if a symbol can be replaced at load-time by a symbol // with the same name defined in other ELF executable or DSO. static bool computeIsPreemptible(const Symbol &B) { assert(!B.isLocal()); // Only symbols that appear in dynsym can be preempted. if (!B.includeInDynsym()) return false; // Only default visibility symbols can be preempted. if (B.Visibility != STV_DEFAULT) return false; // At this point copy relocations have not been created yet, so any // symbol that is not defined locally is preemptible. if (!B.isDefined()) return true; // If we have a dynamic list it specifies which local symbols are preemptible. if (Config->HasDynamicList) return false; if (!Config->Shared) return false; // -Bsymbolic means that definitions are not preempted. if (Config->Bsymbolic || (Config->BsymbolicFunctions && B.isFunc())) return false; return true; } // Create output section objects and add them to OutputSections. template void Writer::finalizeSections() { Out::DebugInfo = findSection(".debug_info"); Out::PreinitArray = findSection(".preinit_array"); Out::InitArray = findSection(".init_array"); Out::FiniArray = findSection(".fini_array"); // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop // symbols for sections, so that the runtime can get the start and end // addresses of each section by section name. Add such symbols. if (!Config->Relocatable) { addStartEndSymbols(); for (BaseCommand *Base : Script->SectionCommands) if (auto *Sec = dyn_cast(Base)) addStartStopSymbols(Sec); } // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type. // It should be okay as no one seems to care about the type. // Even the author of gold doesn't remember why gold behaves that way. // https://sourceware.org/ml/binutils/2002-03/msg00360.html if (InX::DynSymTab) Symtab->addRegular("_DYNAMIC", STV_HIDDEN, STT_NOTYPE, 0 /*Value*/, /*Size=*/0, STB_WEAK, InX::Dynamic, /*File=*/nullptr); // Define __rel[a]_iplt_{start,end} symbols if needed. addRelIpltSymbols(); // This responsible for splitting up .eh_frame section into // pieces. The relocation scan uses those pieces, so this has to be // earlier. applySynthetic({InX::EhFrame}, [](SyntheticSection *SS) { SS->finalizeContents(); }); for (Symbol *S : Symtab->getSymbols()) S->IsPreemptible |= computeIsPreemptible(*S); // Scan relocations. This must be done after every symbol is declared so that // we can correctly decide if a dynamic relocation is needed. if (!Config->Relocatable) forEachRelSec(scanRelocations); if (InX::Plt && !InX::Plt->empty()) InX::Plt->addSymbols(); if (InX::Iplt && !InX::Iplt->empty()) InX::Iplt->addSymbols(); // Now that we have defined all possible global symbols including linker- // synthesized ones. Visit all symbols to give the finishing touches. for (Symbol *Sym : Symtab->getSymbols()) { if (!includeInSymtab(*Sym)) continue; if (InX::SymTab) InX::SymTab->addSymbol(Sym); if (InX::DynSymTab && Sym->includeInDynsym()) { InX::DynSymTab->addSymbol(Sym); if (auto *SS = dyn_cast(Sym)) if (cast>(Sym->File)->IsNeeded) In::VerNeed->addSymbol(SS); } } // Do not proceed if there was an undefined symbol. if (errorCount()) return; removeUnusedSyntheticSections(); sortSections(); Script->removeEmptyCommands(); // Now that we have the final list, create a list of all the // OutputSections for convenience. for (BaseCommand *Base : Script->SectionCommands) if (auto *Sec = dyn_cast(Base)) OutputSections.push_back(Sec); // Prefer command line supplied address over other constraints. for (OutputSection *Sec : OutputSections) { auto I = Config->SectionStartMap.find(Sec->Name); if (I != Config->SectionStartMap.end()) Sec->AddrExpr = [=] { return I->second; }; } // This is a bit of a hack. A value of 0 means undef, so we set it // to 1 t make __ehdr_start defined. The section number is not // particularly relevant. Out::ElfHeader->SectionIndex = 1; unsigned I = 1; for (OutputSection *Sec : OutputSections) { Sec->SectionIndex = I++; Sec->ShName = InX::ShStrTab->addString(Sec->Name); } // Binary and relocatable output does not have PHDRS. // The headers have to be created before finalize as that can influence the // image base and the dynamic section on mips includes the image base. if (!Config->Relocatable && !Config->OFormatBinary) { Phdrs = Script->hasPhdrsCommands() ? Script->createPhdrs() : createPhdrs(); addPtArmExid(Phdrs); Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size(); } // Some symbols are defined in term of program headers. Now that we // have the headers, we can find out which sections they point to. setReservedSymbolSections(); // Dynamic section must be the last one in this list and dynamic // symbol table section (DynSymTab) must be the first one. applySynthetic( {InX::DynSymTab, InX::Bss, InX::BssRelRo, InX::GnuHashTab, InX::HashTab, InX::SymTab, InX::ShStrTab, InX::StrTab, In::VerDef, InX::DynStrTab, InX::Got, InX::MipsGot, InX::IgotPlt, InX::GotPlt, InX::RelaDyn, InX::RelaIplt, InX::RelaPlt, InX::Plt, InX::Iplt, InX::EhFrameHdr, In::VerSym, In::VerNeed, InX::Dynamic}, [](SyntheticSection *SS) { SS->finalizeContents(); }); if (!Script->HasSectionsCommand && !Config->Relocatable) fixSectionAlignments(); // After link order processing .ARM.exidx sections can be deduplicated, which // needs to be resolved before any other address dependent operation. resolveShfLinkOrder(); // Some architectures need to generate content that depends on the address // of InputSections. For example some architectures use small displacements // for jump instructions that is is the linker's responsibility for creating // range extension thunks for. As the generation of the content may also // alter InputSection addresses we must converge to a fixed point. if (Target->NeedsThunks || Config->AndroidPackDynRelocs) { ThunkCreator TC; AArch64Err843419Patcher A64P; bool Changed; do { Script->assignAddresses(); Changed = false; if (Target->NeedsThunks) Changed |= TC.createThunks(OutputSections); if (Config->FixCortexA53Errata843419) { if (Changed) Script->assignAddresses(); Changed |= A64P.createFixes(); } if (InX::MipsGot) InX::MipsGot->updateAllocSize(); Changed |= InX::RelaDyn->updateAllocSize(); } while (Changed); } // Fill other section headers. The dynamic table is finalized // at the end because some tags like RELSZ depend on result // of finalizing other sections. for (OutputSection *Sec : OutputSections) Sec->finalize(); // createThunks may have added local symbols to the static symbol table applySynthetic({InX::SymTab}, [](SyntheticSection *SS) { SS->postThunkContents(); }); } // The linker is expected to define SECNAME_start and SECNAME_end // symbols for a few sections. This function defines them. template void Writer::addStartEndSymbols() { auto Define = [&](StringRef Start, StringRef End, OutputSection *OS) { // These symbols resolve to the image base if the section does not exist. // A special value -1 indicates end of the section. if (OS) { addOptionalRegular(Start, OS, 0); addOptionalRegular(End, OS, -1); } else { if (Config->Pic) OS = Out::ElfHeader; addOptionalRegular(Start, OS, 0); addOptionalRegular(End, OS, 0); } }; Define("__preinit_array_start", "__preinit_array_end", Out::PreinitArray); Define("__init_array_start", "__init_array_end", Out::InitArray); Define("__fini_array_start", "__fini_array_end", Out::FiniArray); if (OutputSection *Sec = findSection(".ARM.exidx")) Define("__exidx_start", "__exidx_end", Sec); } // If a section name is valid as a C identifier (which is rare because of // the leading '.'), linkers are expected to define __start_ and // __stop_ symbols. They are at beginning and end of the section, // respectively. This is not requested by the ELF standard, but GNU ld and // gold provide the feature, and used by many programs. template void Writer::addStartStopSymbols(OutputSection *Sec) { StringRef S = Sec->Name; if (!isValidCIdentifier(S)) return; addOptionalRegular(Saver.save("__start_" + S), Sec, 0, STV_DEFAULT); addOptionalRegular(Saver.save("__stop_" + S), Sec, -1, STV_DEFAULT); } static bool needsPtLoad(OutputSection *Sec) { if (!(Sec->Flags & SHF_ALLOC)) return false; // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is // responsible for allocating space for them, not the PT_LOAD that // contains the TLS initialization image. if (Sec->Flags & SHF_TLS && Sec->Type == SHT_NOBITS) return false; return true; } // Linker scripts are responsible for aligning addresses. Unfortunately, most // linker scripts are designed for creating two PT_LOADs only, one RX and one // RW. This means that there is no alignment in the RO to RX transition and we // cannot create a PT_LOAD there. static uint64_t computeFlags(uint64_t Flags) { if (Config->Omagic) return PF_R | PF_W | PF_X; if (Config->SingleRoRx && !(Flags & PF_W)) return Flags | PF_X; return Flags; } // Decide which program headers to create and which sections to include in each // one. template std::vector Writer::createPhdrs() { std::vector Ret; auto AddHdr = [&](unsigned Type, unsigned Flags) -> PhdrEntry * { Ret.push_back(make(Type, Flags)); return Ret.back(); }; // The first phdr entry is PT_PHDR which describes the program header itself. AddHdr(PT_PHDR, PF_R)->add(Out::ProgramHeaders); // PT_INTERP must be the second entry if exists. if (OutputSection *Cmd = findSection(".interp")) AddHdr(PT_INTERP, Cmd->getPhdrFlags())->add(Cmd); // Add the first PT_LOAD segment for regular output sections. uint64_t Flags = computeFlags(PF_R); PhdrEntry *Load = AddHdr(PT_LOAD, Flags); // Add the headers. We will remove them if they don't fit. Load->add(Out::ElfHeader); Load->add(Out::ProgramHeaders); for (OutputSection *Sec : OutputSections) { if (!(Sec->Flags & SHF_ALLOC)) break; if (!needsPtLoad(Sec)) continue; // Segments are contiguous memory regions that has the same attributes // (e.g. executable or writable). There is one phdr for each segment. // Therefore, we need to create a new phdr when the next section has // different flags or is loaded at a discontiguous address using AT linker // script command. uint64_t NewFlags = computeFlags(Sec->getPhdrFlags()); if (Sec->LMAExpr || Flags != NewFlags) { Load = AddHdr(PT_LOAD, NewFlags); Flags = NewFlags; } Load->add(Sec); } // Add a TLS segment if any. PhdrEntry *TlsHdr = make(PT_TLS, PF_R); for (OutputSection *Sec : OutputSections) if (Sec->Flags & SHF_TLS) TlsHdr->add(Sec); if (TlsHdr->FirstSec) Ret.push_back(TlsHdr); // Add an entry for .dynamic. if (InX::DynSymTab) AddHdr(PT_DYNAMIC, InX::Dynamic->getParent()->getPhdrFlags()) ->add(InX::Dynamic->getParent()); // PT_GNU_RELRO includes all sections that should be marked as // read-only by dynamic linker after proccessing relocations. // Current dynamic loaders only support one PT_GNU_RELRO PHDR, give // an error message if more than one PT_GNU_RELRO PHDR is required. PhdrEntry *RelRo = make(PT_GNU_RELRO, PF_R); bool InRelroPhdr = false; bool IsRelroFinished = false; for (OutputSection *Sec : OutputSections) { if (!needsPtLoad(Sec)) continue; if (isRelroSection(Sec)) { InRelroPhdr = true; if (!IsRelroFinished) RelRo->add(Sec); else error("section: " + Sec->Name + " is not contiguous with other relro" + " sections"); } else if (InRelroPhdr) { InRelroPhdr = false; IsRelroFinished = true; } } if (RelRo->FirstSec) Ret.push_back(RelRo); // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr. if (!InX::EhFrame->empty() && InX::EhFrameHdr && InX::EhFrame->getParent() && InX::EhFrameHdr->getParent()) AddHdr(PT_GNU_EH_FRAME, InX::EhFrameHdr->getParent()->getPhdrFlags()) ->add(InX::EhFrameHdr->getParent()); // PT_OPENBSD_RANDOMIZE is an OpenBSD-specific feature. That makes // the dynamic linker fill the segment with random data. if (OutputSection *Cmd = findSection(".openbsd.randomdata")) AddHdr(PT_OPENBSD_RANDOMIZE, Cmd->getPhdrFlags())->add(Cmd); // PT_GNU_STACK is a special section to tell the loader to make the // pages for the stack non-executable. If you really want an executable // stack, you can pass -z execstack, but that's not recommended for // security reasons. unsigned Perm; if (Config->ZExecstack) Perm = PF_R | PF_W | PF_X; else Perm = PF_R | PF_W; AddHdr(PT_GNU_STACK, Perm)->p_memsz = Config->ZStackSize; // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable // is expected to perform W^X violations, such as calling mprotect(2) or // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on // OpenBSD. if (Config->ZWxneeded) AddHdr(PT_OPENBSD_WXNEEDED, PF_X); // Create one PT_NOTE per a group of contiguous .note sections. PhdrEntry *Note = nullptr; for (OutputSection *Sec : OutputSections) { if (Sec->Type == SHT_NOTE) { if (!Note || Sec->LMAExpr) Note = AddHdr(PT_NOTE, PF_R); Note->add(Sec); } else { Note = nullptr; } } return Ret; } template void Writer::addPtArmExid(std::vector &Phdrs) { if (Config->EMachine != EM_ARM) return; auto I = llvm::find_if(OutputSections, [](OutputSection *Cmd) { return Cmd->Type == SHT_ARM_EXIDX; }); if (I == OutputSections.end()) return; // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME PhdrEntry *ARMExidx = make(PT_ARM_EXIDX, PF_R); ARMExidx->add(*I); Phdrs.push_back(ARMExidx); } // The first section of each PT_LOAD, the first section in PT_GNU_RELRO and the // first section after PT_GNU_RELRO have to be page aligned so that the dynamic // linker can set the permissions. template void Writer::fixSectionAlignments() { auto PageAlign = [](OutputSection *Cmd) { if (Cmd && !Cmd->AddrExpr) Cmd->AddrExpr = [=] { return alignTo(Script->getDot(), Config->MaxPageSize); }; }; for (const PhdrEntry *P : Phdrs) if (P->p_type == PT_LOAD && P->FirstSec) PageAlign(P->FirstSec); for (const PhdrEntry *P : Phdrs) { if (P->p_type != PT_GNU_RELRO) continue; if (P->FirstSec) PageAlign(P->FirstSec); // Find the first section after PT_GNU_RELRO. If it is in a PT_LOAD we // have to align it to a page. auto End = OutputSections.end(); auto I = std::find(OutputSections.begin(), End, P->LastSec); if (I == End || (I + 1) == End) continue; OutputSection *Cmd = (*(I + 1)); if (needsPtLoad(Cmd)) PageAlign(Cmd); } } // Adjusts the file alignment for a given output section and returns // its new file offset. The file offset must be the same with its // virtual address (modulo the page size) so that the loader can load // executables without any address adjustment. static uint64_t getFileAlignment(uint64_t Off, OutputSection *Cmd) { OutputSection *First = Cmd->PtLoad ? Cmd->PtLoad->FirstSec : nullptr; // The first section in a PT_LOAD has to have congruent offset and address // module the page size. if (Cmd == First) return alignTo(Off, std::max(Cmd->Alignment, Config->MaxPageSize), Cmd->Addr); // For SHT_NOBITS we don't want the alignment of the section to impact the // offset of the sections that follow. Since nothing seems to care about the // sh_offset of the SHT_NOBITS section itself, just ignore it. if (Cmd->Type == SHT_NOBITS) return Off; // If the section is not in a PT_LOAD, we just have to align it. if (!Cmd->PtLoad) return alignTo(Off, Cmd->Alignment); // If two sections share the same PT_LOAD the file offset is calculated // using this formula: Off2 = Off1 + (VA2 - VA1). return First->Offset + Cmd->Addr - First->Addr; } static uint64_t setOffset(OutputSection *Cmd, uint64_t Off) { Off = getFileAlignment(Off, Cmd); Cmd->Offset = Off; // For SHT_NOBITS we should not count the size. if (Cmd->Type == SHT_NOBITS) return Off; return Off + Cmd->Size; } template void Writer::assignFileOffsetsBinary() { uint64_t Off = 0; for (OutputSection *Sec : OutputSections) if (Sec->Flags & SHF_ALLOC) Off = setOffset(Sec, Off); FileSize = alignTo(Off, Config->Wordsize); } // Assign file offsets to output sections. template void Writer::assignFileOffsets() { uint64_t Off = 0; Off = setOffset(Out::ElfHeader, Off); Off = setOffset(Out::ProgramHeaders, Off); PhdrEntry *LastRX = nullptr; for (PhdrEntry *P : Phdrs) if (P->p_type == PT_LOAD && (P->p_flags & PF_X)) LastRX = P; for (OutputSection *Sec : OutputSections) { Off = setOffset(Sec, Off); if (Script->HasSectionsCommand) continue; // If this is a last section of the last executable segment and that // segment is the last loadable segment, align the offset of the // following section to avoid loading non-segments parts of the file. if (LastRX && LastRX->LastSec == Sec) Off = alignTo(Off, Target->PageSize); } SectionHeaderOff = alignTo(Off, Config->Wordsize); FileSize = SectionHeaderOff + (OutputSections.size() + 1) * sizeof(Elf_Shdr); } // Finalize the program headers. We call this function after we assign // file offsets and VAs to all sections. template void Writer::setPhdrs() { for (PhdrEntry *P : Phdrs) { OutputSection *First = P->FirstSec; OutputSection *Last = P->LastSec; if (First) { P->p_filesz = Last->Offset - First->Offset; if (Last->Type != SHT_NOBITS) P->p_filesz += Last->Size; P->p_memsz = Last->Addr + Last->Size - First->Addr; P->p_offset = First->Offset; P->p_vaddr = First->Addr; if (!P->HasLMA) P->p_paddr = First->getLMA(); } if (P->p_type == PT_LOAD) P->p_align = std::max(P->p_align, Config->MaxPageSize); else if (P->p_type == PT_GNU_RELRO) { P->p_align = 1; // The glibc dynamic loader rounds the size down, so we need to round up // to protect the last page. This is a no-op on FreeBSD which always // rounds up. P->p_memsz = alignTo(P->p_memsz, Target->PageSize); } // The TLS pointer goes after PT_TLS. At least glibc will align it, // so round up the size to make sure the offsets are correct. if (P->p_type == PT_TLS) { Out::TlsPhdr = P; if (P->p_memsz) P->p_memsz = alignTo(P->p_memsz, P->p_align); } } } // The entry point address is chosen in the following ways. // // 1. the '-e' entry command-line option; // 2. the ENTRY(symbol) command in a linker control script; // 3. the value of the symbol _start, if present; // 4. the number represented by the entry symbol, if it is a number; // 5. the address of the first byte of the .text section, if present; // 6. the address 0. template uint64_t Writer::getEntryAddr() { // Case 1, 2 or 3 if (Symbol *B = Symtab->find(Config->Entry)) return B->getVA(); // Case 4 uint64_t Addr; if (to_integer(Config->Entry, Addr)) return Addr; // Case 5 if (OutputSection *Sec = findSection(".text")) { if (Config->WarnMissingEntry) warn("cannot find entry symbol " + Config->Entry + "; defaulting to 0x" + utohexstr(Sec->Addr)); return Sec->Addr; } // Case 6 if (Config->WarnMissingEntry) warn("cannot find entry symbol " + Config->Entry + "; not setting start address"); return 0; } static uint16_t getELFType() { if (Config->Pic) return ET_DYN; if (Config->Relocatable) return ET_REL; return ET_EXEC; } template void Writer::writeHeader() { uint8_t *Buf = Buffer->getBufferStart(); memcpy(Buf, "\177ELF", 4); // Write the ELF header. auto *EHdr = reinterpret_cast(Buf); EHdr->e_ident[EI_CLASS] = Config->Is64 ? ELFCLASS64 : ELFCLASS32; EHdr->e_ident[EI_DATA] = Config->IsLE ? ELFDATA2LSB : ELFDATA2MSB; EHdr->e_ident[EI_VERSION] = EV_CURRENT; EHdr->e_ident[EI_OSABI] = Config->OSABI; EHdr->e_type = getELFType(); EHdr->e_machine = Config->EMachine; EHdr->e_version = EV_CURRENT; EHdr->e_entry = getEntryAddr(); EHdr->e_shoff = SectionHeaderOff; EHdr->e_flags = Config->EFlags; EHdr->e_ehsize = sizeof(Elf_Ehdr); EHdr->e_phnum = Phdrs.size(); EHdr->e_shentsize = sizeof(Elf_Shdr); EHdr->e_shnum = OutputSections.size() + 1; EHdr->e_shstrndx = InX::ShStrTab->getParent()->SectionIndex; if (!Config->Relocatable) { EHdr->e_phoff = sizeof(Elf_Ehdr); EHdr->e_phentsize = sizeof(Elf_Phdr); } // Write the program header table. auto *HBuf = reinterpret_cast(Buf + EHdr->e_phoff); for (PhdrEntry *P : Phdrs) { HBuf->p_type = P->p_type; HBuf->p_flags = P->p_flags; HBuf->p_offset = P->p_offset; HBuf->p_vaddr = P->p_vaddr; HBuf->p_paddr = P->p_paddr; HBuf->p_filesz = P->p_filesz; HBuf->p_memsz = P->p_memsz; HBuf->p_align = P->p_align; ++HBuf; } // Write the section header table. Note that the first table entry is null. auto *SHdrs = reinterpret_cast(Buf + EHdr->e_shoff); for (OutputSection *Sec : OutputSections) Sec->writeHeaderTo(++SHdrs); } // Open a result file. template void Writer::openFile() { if (!Config->Is64 && FileSize > UINT32_MAX) { error("output file too large: " + Twine(FileSize) + " bytes"); return; } unlinkAsync(Config->OutputFile); unsigned Flags = 0; if (!Config->Relocatable) Flags = FileOutputBuffer::F_executable; Expected> BufferOrErr = FileOutputBuffer::create(Config->OutputFile, FileSize, Flags); if (!BufferOrErr) error("failed to open " + Config->OutputFile + ": " + llvm::toString(BufferOrErr.takeError())); else Buffer = std::move(*BufferOrErr); } template void Writer::writeSectionsBinary() { uint8_t *Buf = Buffer->getBufferStart(); for (OutputSection *Sec : OutputSections) if (Sec->Flags & SHF_ALLOC) Sec->writeTo(Buf + Sec->Offset); } static void fillTrap(uint8_t *I, uint8_t *End) { for (; I + 4 <= End; I += 4) memcpy(I, &Target->TrapInstr, 4); } // Fill the last page of executable segments with trap instructions // instead of leaving them as zero. Even though it is not required by any // standard, it is in general a good thing to do for security reasons. // // We'll leave other pages in segments as-is because the rest will be // overwritten by output sections. template void Writer::writeTrapInstr() { if (Script->HasSectionsCommand) return; // Fill the last page. uint8_t *Buf = Buffer->getBufferStart(); for (PhdrEntry *P : Phdrs) if (P->p_type == PT_LOAD && (P->p_flags & PF_X)) fillTrap(Buf + alignDown(P->p_offset + P->p_filesz, Target->PageSize), Buf + alignTo(P->p_offset + P->p_filesz, Target->PageSize)); // Round up the file size of the last segment to the page boundary iff it is // an executable segment to ensure that other tools don't accidentally // trim the instruction padding (e.g. when stripping the file). PhdrEntry *Last = nullptr; for (PhdrEntry *P : Phdrs) if (P->p_type == PT_LOAD) Last = P; if (Last && (Last->p_flags & PF_X)) Last->p_memsz = Last->p_filesz = alignTo(Last->p_filesz, Target->PageSize); } // Write section contents to a mmap'ed file. template void Writer::writeSections() { uint8_t *Buf = Buffer->getBufferStart(); // PPC64 needs to process relocations in the .opd section // before processing relocations in code-containing sections. if (auto *OpdCmd = findSection(".opd")) { Out::Opd = OpdCmd; Out::OpdBuf = Buf + Out::Opd->Offset; OpdCmd->template writeTo(Buf + Out::Opd->Offset); } OutputSection *EhFrameHdr = nullptr; if (InX::EhFrameHdr && !InX::EhFrameHdr->empty()) EhFrameHdr = InX::EhFrameHdr->getParent(); // In -r or -emit-relocs mode, write the relocation sections first as in // ELf_Rel targets we might find out that we need to modify the relocated // section while doing it. for (OutputSection *Sec : OutputSections) if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA) Sec->writeTo(Buf + Sec->Offset); for (OutputSection *Sec : OutputSections) if (Sec != Out::Opd && Sec != EhFrameHdr && Sec->Type != SHT_REL && Sec->Type != SHT_RELA) Sec->writeTo(Buf + Sec->Offset); // The .eh_frame_hdr depends on .eh_frame section contents, therefore // it should be written after .eh_frame is written. if (EhFrameHdr) EhFrameHdr->writeTo(Buf + EhFrameHdr->Offset); } template void Writer::writeBuildId() { if (!InX::BuildId || !InX::BuildId->getParent()) return; // Compute a hash of all sections of the output file. uint8_t *Start = Buffer->getBufferStart(); uint8_t *End = Start + FileSize; InX::BuildId->writeBuildId({Start, End}); } template void elf::writeResult(); template void elf::writeResult(); template void elf::writeResult(); template void elf::writeResult(); Index: vendor/lld/dist-release_60/test/ELF/Inputs/as-needed-lazy.s =================================================================== --- vendor/lld/dist-release_60/test/ELF/Inputs/as-needed-lazy.s (nonexistent) +++ vendor/lld/dist-release_60/test/ELF/Inputs/as-needed-lazy.s (revision 328370) @@ -0,0 +1,3 @@ +.global foo +foo: + nop Property changes on: vendor/lld/dist-release_60/test/ELF/Inputs/as-needed-lazy.s ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: vendor/lld/dist-release_60/test/ELF/Inputs/compress-debug.s =================================================================== --- vendor/lld/dist-release_60/test/ELF/Inputs/compress-debug.s (nonexistent) +++ vendor/lld/dist-release_60/test/ELF/Inputs/compress-debug.s (revision 328370) @@ -0,0 +1,5 @@ +.text +.fill 0x44 + +.section .debug_info,"",@progbits +.fill 0x43 Property changes on: vendor/lld/dist-release_60/test/ELF/Inputs/compress-debug.s ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: vendor/lld/dist-release_60/test/ELF/as-needed-lazy.s =================================================================== --- vendor/lld/dist-release_60/test/ELF/as-needed-lazy.s (nonexistent) +++ vendor/lld/dist-release_60/test/ELF/as-needed-lazy.s (revision 328370) @@ -0,0 +1,14 @@ +# REQUIRES: x86 +# RUN: llvm-mc -filetype=obj -triple=x86_64-pc-linux %s -o %t1.o +# RUN: llvm-mc -filetype=obj -triple=x86_64-pc-linux %p/Inputs/as-needed-lazy.s -o %t2.o +# RUN: ld.lld %t2.o -o %t2.so -shared +# RUN: rm -f %t2.a +# RUN: llvm-ar rc %t2.a %t2.o +# RUN: ld.lld %t1.o %t2.a --as-needed %t2.so -o %t +# RUN: llvm-readobj -d %t | FileCheck %s + +# CHECK-NOT: NEEDED + +.global _start +_start: + nop Property changes on: vendor/lld/dist-release_60/test/ELF/as-needed-lazy.s ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: vendor/lld/dist-release_60/test/ELF/compress-debug-sections-reloc.s =================================================================== --- vendor/lld/dist-release_60/test/ELF/compress-debug-sections-reloc.s (nonexistent) +++ vendor/lld/dist-release_60/test/ELF/compress-debug-sections-reloc.s (revision 328370) @@ -0,0 +1,26 @@ +# REQUIRES: x86, zlib + +# RUN: llvm-mc -filetype=obj -triple=x86_64-unknown-linux %s -o %t.o +# RUN: llvm-mc -filetype=obj -triple=x86_64-unknown-linux %S/Inputs/compress-debug.s -o %t2.o +# RUN: ld.lld %t2.o %t.o -o %t1 --compress-debug-sections=zlib -Ttext=0 +# RUN: llvm-dwarfdump %t1 -debug-str | FileCheck %s +# These two checks correspond to the patched values of a_sym and a_debug_sym. +# D = 0x44 - address of .text input section for this file (the start address of +# .text is 0 as requested on the command line, and the size of the +# preceding .text in the other input file is 0x44). +# C = 0x43 - offset of .debug_info section for this file (the size of +# the preceding .debug_info from the other input file is 0x43). +# CHECK: 0x00000000: "D" +# CHECK: 0x00000004: "C" + +.text +a_sym: +nop + +.section .debug_str,"",@progbits +.long a_sym +.long a_debug_sym + +.section .debug_info,"",@progbits +a_debug_sym: +.long 0x88776655 Property changes on: vendor/lld/dist-release_60/test/ELF/compress-debug-sections-reloc.s ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: vendor/lld/dist-release_60/test/ELF/linkerscript/at-self-reference.s =================================================================== --- vendor/lld/dist-release_60/test/ELF/linkerscript/at-self-reference.s (nonexistent) +++ vendor/lld/dist-release_60/test/ELF/linkerscript/at-self-reference.s (revision 328370) @@ -0,0 +1,63 @@ +# REQUIRES: x86 +# RUN: llvm-mc -filetype=obj -triple=x86_64-unknown-linux %s -o %t +# RUN: echo "SECTIONS { \ +# RUN: . = 0x1000; \ +# RUN: .aaa : AT(ADDR(.aaa)) { *(.aaa) } \ +# RUN: .bbb : AT(ADDR(.bbb)) { *(.bbb) } \ +# RUN: }" > %t.script +# RUN: ld.lld %t --script %t.script -o %t2 +# RUN: llvm-readobj -program-headers %t2 | FileCheck %s + +# CHECK: ProgramHeaders [ +# CHECK-NEXT: ProgramHeader { +# CHECK-NEXT: Type: PT_LOAD (0x1) +# CHECK-NEXT: Offset: 0x1000 +# CHECK-NEXT: VirtualAddress: 0x1000 +# CHECK-NEXT: PhysicalAddress: 0x1000 +# CHECK-NEXT: FileSize: 3 +# CHECK-NEXT: MemSize: 3 +# CHECK-NEXT: Flags [ (0x5) +# CHECK-NEXT: PF_R (0x4) +# CHECK-NEXT: PF_X (0x1) +# CHECK-NEXT: ] +# CHECK-NEXT: Alignment: 4096 +# CHECK-NEXT: } +# CHECK-NEXT: ProgramHeader { +# CHECK-NEXT: Type: PT_LOAD (0x1) +# CHECK-NEXT: Offset: 0x1008 +# CHECK-NEXT: VirtualAddress: 0x1008 +# CHECK-NEXT: PhysicalAddress: 0x1008 +# CHECK-NEXT: FileSize: 9 +# CHECK-NEXT: MemSize: 9 +# CHECK-NEXT: Flags [ (0x5) +# CHECK-NEXT: PF_R (0x4) +# CHECK-NEXT: PF_X (0x1) +# CHECK-NEXT: ] +# CHECK-NEXT: Alignment: 4096 +# CHECK-NEXT: } +# CHECK-NEXT: ProgramHeader { +# CHECK-NEXT: Type: PT_GNU_STACK (0x6474E551) +# CHECK-NEXT: Offset: 0x0 +# CHECK-NEXT: VirtualAddress: 0x0 +# CHECK-NEXT: PhysicalAddress: 0x0 +# CHECK-NEXT: FileSize: 0 +# CHECK-NEXT: MemSize: 0 +# CHECK-NEXT: Flags [ (0x6) +# CHECK-NEXT: PF_R (0x4) +# CHECK-NEXT: PF_W (0x2) +# CHECK-NEXT: ] +# CHECK-NEXT: Alignment: 0 +# CHECK-NEXT: } +# CHECK-NEXT:] + +.global _start +_start: + nop + + +.section .aaa, "a" +.asciz "aa" + +.section .bbb, "a" +.align 8 +.quad 0 Property changes on: vendor/lld/dist-release_60/test/ELF/linkerscript/at-self-reference.s ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: vendor/lld/dist-release_60/test/ELF/linkerscript/at2.s =================================================================== --- vendor/lld/dist-release_60/test/ELF/linkerscript/at2.s (nonexistent) +++ vendor/lld/dist-release_60/test/ELF/linkerscript/at2.s (revision 328370) @@ -0,0 +1,81 @@ +# REQUIRES: x86 +# RUN: llvm-mc -filetype=obj -triple=x86_64-unknown-linux %s -o %t +# RUN: echo "MEMORY { \ +# RUN: AX (ax) : ORIGIN = 0x2000, LENGTH = 0x100 \ +# RUN: AW (aw) : ORIGIN = 0x3000, LENGTH = 0x100 \ +# RUN: FLASH (ax) : ORIGIN = 0x6000, LENGTH = 0x100 \ +# RUN: RAM (aw) : ORIGIN = 0x7000, LENGTH = 0x100 } \ +# RUN: SECTIONS { \ +# RUN: .foo1 : { *(.foo1) } > AX AT>FLASH \ +# RUN: .foo2 : { *(.foo2) } > AX \ +# RUN: .bar1 : { *(.bar1) } > AW AT> RAM \ +# RUN: .bar2 : { *(.bar2) } > AW AT > RAM \ +# RUN: .bar3 : { *(.bar3) } > AW AT >RAM \ +# RUN: }" > %t.script +# RUN: ld.lld %t --script %t.script -o %t2 +# RUN: llvm-readobj -program-headers %t2 | FileCheck %s +# RUN: llvm-objdump -section-headers %t2 | FileCheck %s --check-prefix=SECTIONS + +# CHECK: ProgramHeaders [ +# CHECK-NEXT: ProgramHeader { +# CHECK-NEXT: Type: PT_LOAD +# CHECK-NEXT: Offset: 0x1000 +# CHECK-NEXT: VirtualAddress: 0x2000 +# CHECK-NEXT: PhysicalAddress: 0x6000 +# CHECK-NEXT: FileSize: 16 +# CHECK-NEXT: MemSize: 16 +# CHECK-NEXT: Flags [ +# CHECK-NEXT: PF_R +# CHECK-NEXT: PF_X +# CHECK-NEXT: ] +# CHECK-NEXT: Alignment: +# CHECK-NEXT: } +# CHECK-NEXT: ProgramHeader { +# CHECK-NEXT: Type: PT_LOAD +# CHECK-NEXT: Offset: 0x2000 +# CHECK-NEXT: VirtualAddress: 0x3000 +# CHECK-NEXT: PhysicalAddress: 0x7000 +# CHECK-NEXT: FileSize: 24 +# CHECK-NEXT: MemSize: 24 +# CHECK-NEXT: Flags [ +# CHECK-NEXT: PF_R +# CHECK-NEXT: PF_W +# CHECK-NEXT: ] +# CHECK-NEXT: Alignment: 4096 +# CHECK-NEXT: } + +# SECTIONS: Sections: +# SECTIONS-NEXT: Idx Name Size Address +# SECTIONS-NEXT: 0 00000000 0000000000000000 +# SECTIONS-NEXT: 1 .foo1 00000008 0000000000002000 +# SECTIONS-NEXT: 2 .foo2 00000008 0000000000002008 +# SECTIONS-NEXT: 3 .text 00000000 0000000000002010 +# SECTIONS-NEXT: 4 .bar1 00000008 0000000000003000 +# SECTIONS-NEXT: 5 .bar2 00000008 0000000000003008 +# SECTIONS-NEXT: 6 .bar3 00000008 0000000000003010 + +# RUN: llvm-mc -filetype=obj -triple=x86_64-unknown-linux %s -o %t +# RUN: echo "MEMORY { \ +# RUN: FLASH (ax) : ORIGIN = 0x2000, LENGTH = 0x100 \ +# RUN: RAM (aw) : ORIGIN = 0x5000, LENGTH = 0x100 } \ +# RUN: SECTIONS { \ +# RUN: .foo1 : AT(0x500) { *(.foo1) } > FLASH AT>FLASH \ +# RUN: }" > %t2.script +# RUN: not ld.lld %t --script %t2.script -o %t2 2>&1 | \ +# RUN: FileCheck %s --check-prefix=ERR +# ERR: error: section can't have both LMA and a load region + +.section .foo1, "ax" +.quad 0 + +.section .foo2, "ax" +.quad 0 + +.section .bar1, "aw" +.quad 0 + +.section .bar2, "aw" +.quad 0 + +.section .bar3, "aw" +.quad 0 Property changes on: vendor/lld/dist-release_60/test/ELF/linkerscript/at2.s ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: vendor/lld/dist-release_60/test/ELF/linkerscript/compress-debug-sections-custom.s =================================================================== --- vendor/lld/dist-release_60/test/ELF/linkerscript/compress-debug-sections-custom.s (nonexistent) +++ vendor/lld/dist-release_60/test/ELF/linkerscript/compress-debug-sections-custom.s (revision 328370) @@ -0,0 +1,35 @@ +# REQUIRES: x86, zlib + +# RUN: echo "SECTIONS { \ +# RUN: .text : { . += 0x10; *(.text) } \ +# RUN: .debug_str : { . += 0x10; *(.debug_str) } \ +# RUN: .debug_info : { . += 0x10; *(.debug_info) } \ +# RUN: }" > %t.script + +# RUN: llvm-mc -filetype=obj -triple=x86_64-unknown-linux %s -o %t.o +# RUN: llvm-mc -filetype=obj -triple=x86_64-unknown-linux %S/../Inputs/compress-debug.s -o %t2.o +# RUN: ld.lld %t2.o %t.o -o %t1 --compress-debug-sections=zlib -T %t.script +# RUN: llvm-dwarfdump %t1 -debug-str | FileCheck %s +# These two checks correspond to the patched values of a_sym and a_debug_sym. +# T = 0x54 - address of .text input section for this file (the start address of +# .text is 0 by default, the size of the preceding .text in the other input +# file is 0x44, and the linker script adds an additional 0x10). +# S = 0x53 - offset of .debug_info section for this file (the size of +# the preceding .debug_info from the other input file is 0x43, and the +# linker script adds an additional 0x10). +# Also note that the .debug_str offsets are also offset by 0x10, as directed by +# the linker script. +# CHECK: 0x00000010: "T" +# CHECK: 0x00000014: "S" + +.text +a_sym: +nop + +.section .debug_str,"",@progbits +.long a_sym +.long a_debug_sym + +.section .debug_info,"",@progbits +a_debug_sym: +.long 0x88776655 Property changes on: vendor/lld/dist-release_60/test/ELF/linkerscript/compress-debug-sections-custom.s ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: vendor/lld/dist-release_60/test/ELF/linkerscript/parse-section-in-addr.s =================================================================== --- vendor/lld/dist-release_60/test/ELF/linkerscript/parse-section-in-addr.s (nonexistent) +++ vendor/lld/dist-release_60/test/ELF/linkerscript/parse-section-in-addr.s (revision 328370) @@ -0,0 +1,10 @@ +# REQUIRES: x86 +# RUN: llvm-mc -filetype=obj -triple=x86_64-pc-linux %s -o %t.o + +# RUN: echo "SECTIONS { \ +# RUN: .foo-bar : AT(ADDR(.foo-bar)) { *(.text) } \ +# RUN: }" > %t.script +# RUN: ld.lld -o %t.so --script %t.script %t.o -shared +# RUN: llvm-readelf -S %t.so | FileCheck %s + +# CHECK: .foo-bar Property changes on: vendor/lld/dist-release_60/test/ELF/linkerscript/parse-section-in-addr.s ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: vendor/lld/dist-release_60/test/ELF/sysv-hash-no-rosegment.s =================================================================== --- vendor/lld/dist-release_60/test/ELF/sysv-hash-no-rosegment.s (nonexistent) +++ vendor/lld/dist-release_60/test/ELF/sysv-hash-no-rosegment.s (revision 328370) @@ -0,0 +1,13 @@ +# REQUIRES: x86 +# RUN: llvm-mc -filetype=obj -triple=x86_64-pc-linux %s -o %t.o +# RUN: ld.lld -shared --no-rosegment -o %t %t.o +# RUN: llvm-readobj -hash-table %t | FileCheck %s + +# CHECK: HashTable { +# CHECK-NEXT: Num Buckets: 2 +# CHECK-NEXT: Num Chains: 2 +# CHECK-NEXT: Buckets: [1, 0] +# CHECK-NEXT: Chains: [0, 0] +# CHECK-NEXT: } + +callq undef@PLT Property changes on: vendor/lld/dist-release_60/test/ELF/sysv-hash-no-rosegment.s ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property