Index: COFF/DLL.h =================================================================== --- COFF/DLL.h +++ COFF/DLL.h @@ -19,19 +19,12 @@ // Windows-specific. // IdataContents creates all chunks for the DLL import table. // You are supposed to call add() to add symbols and then -// call getChunks() to get a list of chunks. +// call create() to populate the chunk vectors. class IdataContents { public: void add(DefinedImportData *Sym) { Imports.push_back(Sym); } bool empty() { return Imports.empty(); } - std::vector getChunks(); - uint64_t getDirRVA() { return Dirs[0]->getRVA(); } - uint64_t getDirSize(); - uint64_t getIATRVA() { return Addresses[0]->getRVA(); } - uint64_t getIATSize(); - -private: void create(); std::vector Imports; Index: COFF/DLL.cpp =================================================================== --- COFF/DLL.cpp +++ COFF/DLL.cpp @@ -470,30 +470,6 @@ } // anonymous namespace -uint64_t IdataContents::getDirSize() { - return Dirs.size() * sizeof(ImportDirectoryTableEntry); -} - -uint64_t IdataContents::getIATSize() { - return Addresses.size() * ptrSize(); -} - -// Returns a list of .idata contents. -// See Microsoft PE/COFF spec 5.4 for details. -std::vector IdataContents::getChunks() { - create(); - - // The loader assumes a specific order of data. - // Add each type in the correct order. - std::vector V; - V.insert(V.end(), Dirs.begin(), Dirs.end()); - V.insert(V.end(), Lookups.begin(), Lookups.end()); - V.insert(V.end(), Addresses.begin(), Addresses.end()); - V.insert(V.end(), Hints.begin(), Hints.end()); - V.insert(V.end(), DLLNames.begin(), DLLNames.end()); - return V; -} - void IdataContents::create() { std::vector> V = binImports(Imports); Index: COFF/Writer.cpp =================================================================== --- COFF/Writer.cpp +++ COFF/Writer.cpp @@ -167,6 +167,7 @@ void createSections(); void createMiscChunks(); void createImportTables(); + void appendImportThunks(); void createExportTable(); void mergeSections(); void readRelocTargets(); @@ -205,6 +206,10 @@ std::vector Strtab; std::vector OutputSymtab; IdataContents Idata; + Chunk *ImportTableStart = nullptr; + uint64_t ImportTableSize = 0; + Chunk *IATStart = nullptr; + uint64_t IATSize = 0; DelayLoadContents DelayIdata; EdataContents Edata; bool SetNoSEHCharacteristic = false; @@ -492,9 +497,10 @@ void Writer::run() { ScopedTimer T1(CodeLayoutTimer); + createImportTables(); createSections(); createMiscChunks(); - createImportTables(); + appendImportThunks(); createExportTable(); mergeSections(); readRelocTargets(); @@ -554,6 +560,50 @@ }); } +// Sort concrete section chunks from GNU import libraries. +static bool fixGnuImportChunks( + std::map, std::vector> &Map) { + const uint32_t RDATA = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ; + + // Make sure all .idata$* section chunks are mapped as RDATA in order to + // be sorted into the same sections as our own synthesized .idata chunks. + for (auto &Pair : Map) { + if (!Pair.first.first.startswith(".idata")) + continue; + if (Pair.first.second == RDATA) + continue; + std::vector &SrcVect = Pair.second; + std::vector &DestVect = Map[{Pair.first.first, RDATA}]; + DestVect.insert(DestVect.end(), SrcVect.begin(), SrcVect.end()); + SrcVect.clear(); + } + + bool HasIdata = false; + // Sort all .idata$* chunks, grouping chunks from the same library, + // with alphabetical ordering of the object fils within a library. + for (auto &Pair : Map) { + if (!Pair.first.first.startswith(".idata")) + continue; + + std::vector &Chunks = Pair.second; + if (!Chunks.empty()) + HasIdata = true; + std::stable_sort(Chunks.begin(), Chunks.end(), [&](Chunk *S, Chunk *T) { + SectionChunk *SC1 = dyn_cast_or_null(S); + SectionChunk *SC2 = dyn_cast_or_null(T); + if (!SC1 || !SC2) { + // if SC1, order them ascending. If SC2 or both null, + // S is not less than T. + return SC1 != nullptr; + } + // Sort according to the "libraryname(objecfile)" + // formatting of the ObjFile. + return toString(SC1->File) < toString(SC2->File); + }); + } + return HasIdata; +} + // Create output section objects and add them to OutputSections. void Writer::createSections() { // First, create the builtin sections. @@ -602,11 +652,48 @@ Map[{C->getSectionName(), C->getOutputCharacteristics()}].push_back(C); } + // Even in non MinGW cases, we might need to link against GNU import + // libraries. + bool HasIdata = fixGnuImportChunks(Map); + + if (!Idata.empty() || HasIdata) { + // Even if Idata contains no imports, we need to create and add it since + // it provides the terminator for the descriptors in .idata$2. + Idata.create(); + // Add the .idata content in the right section groups, to allow + // chunks from other linked in object files to be grouped together. + // See Microsoft PE/COFF spec 5.4 for details. + auto AddChunks = [&](StringRef N, std::vector &V) { + std::vector &DestVect = Map[{N, DATA | R}]; + DestVect.insert(DestVect.end(), V.begin(), V.end()); + }; + // The loader assumes a specific order of data. + // Add each type in the correct order. + AddChunks(".idata$2", Idata.Dirs); + AddChunks(".idata$4", Idata.Lookups); + AddChunks(".idata$5", Idata.Addresses); + AddChunks(".idata$6", Idata.Hints); + AddChunks(".idata$7", Idata.DLLNames); + } + // Process an /order option. if (!Config->Order.empty()) for (auto &Pair : Map) sortBySectionOrder(Pair.second); + if (!Idata.empty() || HasIdata) { + std::vector &ImportTables = Map[{".idata$2", DATA | R}]; + ImportTableStart = ImportTables.front(); + for (Chunk *C : ImportTables) + ImportTableSize += C->getSize(); + + std::vector &IAT = Map[{".idata$5", DATA | R}]; + if (!IAT.empty()) + IATStart = IAT.front(); + for (Chunk *C : IAT) + IATSize += C->getSize(); + } + // Then create an OutputSection for each section. // '$' and all following characters in input section names are // discarded when determining output section. So, .text$foo @@ -697,9 +784,6 @@ // IdataContents class abstracted away the details for us, // so we just let it create chunks and add them to the section. void Writer::createImportTables() { - if (ImportFile::Instances.empty()) - return; - // Initialize DLLOrder so that import entries are ordered in // the same order as in the command line. (That affects DLL // initialization order, and this ordering is MSVC-compatible.) @@ -711,14 +795,6 @@ if (Config->DLLOrder.count(DLL) == 0) Config->DLLOrder[DLL] = Config->DLLOrder.size(); - if (File->ThunkSym) { - if (!isa(File->ThunkSym)) - fatal(toString(*File->ThunkSym) + " was replaced"); - DefinedImportThunk *Thunk = cast(File->ThunkSym); - if (File->ThunkLive) - TextSec->addChunk(Thunk->getChunk()); - } - if (File->ImpSym && !isa(File->ImpSym)) fatal(toString(*File->ImpSym) + " was replaced"); DefinedImportData *ImpSym = cast_or_null(File->ImpSym); @@ -731,10 +807,24 @@ Idata.add(ImpSym); } } +} + +void Writer::appendImportThunks() { + if (ImportFile::Instances.empty()) + return; + + for (ImportFile *File : ImportFile::Instances) { + if (!File->Live) + continue; - if (!Idata.empty()) - for (Chunk *C : Idata.getChunks()) - IdataSec->addChunk(C); + if (File->ThunkSym) { + if (!isa(File->ThunkSym)) + fatal(toString(*File->ThunkSym) + " was replaced"); + DefinedImportThunk *Thunk = cast(File->ThunkSym); + if (File->ThunkLive) + TextSec->addChunk(Thunk->getChunk()); + } + } if (!DelayIdata.empty()) { Defined *Helper = cast(Config->DelayLoadHelper); @@ -1053,11 +1143,13 @@ Dir[EXPORT_TABLE].RelativeVirtualAddress = Edata.getRVA(); Dir[EXPORT_TABLE].Size = Edata.getSize(); } - if (!Idata.empty()) { - Dir[IMPORT_TABLE].RelativeVirtualAddress = Idata.getDirRVA(); - Dir[IMPORT_TABLE].Size = Idata.getDirSize(); - Dir[IAT].RelativeVirtualAddress = Idata.getIATRVA(); - Dir[IAT].Size = Idata.getIATSize(); + if (ImportTableStart) { + Dir[IMPORT_TABLE].RelativeVirtualAddress = ImportTableStart->getRVA(); + Dir[IMPORT_TABLE].Size = ImportTableSize; + } + if (IATStart) { + Dir[IAT].RelativeVirtualAddress = IATStart->getRVA(); + Dir[IAT].Size = IATSize; } if (RsrcSec->getVirtualSize()) { Dir[RESOURCE_TABLE].RelativeVirtualAddress = RsrcSec->getRVA(); Index: test/COFF/Inputs/gnu-implib-func.s =================================================================== --- /dev/null +++ test/COFF/Inputs/gnu-implib-func.s @@ -0,0 +1,27 @@ + .text + .global func + .global __imp_func +func: + jmp *__imp_func + + # The data that is emitted into .idata$7 here is isn't needed for + # the import data structures, but we need to emit something which + # produces a relocation against _head_test_lib, to pull in the + # header and trailer objects. + + .section .idata$7 + .rva _head_test_lib + + .section .idata$5 +__imp_func: + .rva .Lhint_name + .long 0 + + .section .idata$4 + .rva .Lhint_name + .long 0 + + .section .idata$6 +.Lhint_name: + .short 0 + .asciz "func" Index: test/COFF/Inputs/gnu-implib-head.s =================================================================== --- /dev/null +++ test/COFF/Inputs/gnu-implib-head.s @@ -0,0 +1,13 @@ + .section .idata$2 + .global _head_test_lib +_head_test_lib: + .rva hname + .long 0 + .long 0 + .rva __test_lib_iname + .rva fthunk + + .section .idata$5 +fthunk: + .section .idata$4 +hname: Index: test/COFF/Inputs/gnu-implib-tail.s =================================================================== --- /dev/null +++ test/COFF/Inputs/gnu-implib-tail.s @@ -0,0 +1,11 @@ + .section .idata$4 + .long 0 + .long 0 + .section .idata$5 + .long 0 + .long 0 + + .section .idata$7 + .global __test_lib_iname +__test_lib_iname: + .asciz "foo.dll" Index: test/COFF/imports-gnu-only.s =================================================================== --- /dev/null +++ test/COFF/imports-gnu-only.s @@ -0,0 +1,28 @@ +# REQUIRES: x86 +# +# RUN: llvm-mc -triple=x86_64-windows-gnu %p/Inputs/gnu-implib-head.s -filetype=obj -o %t-dabcdh.o +# RUN: llvm-mc -triple=x86_64-windows-gnu %p/Inputs/gnu-implib-func.s -filetype=obj -o %t-dabcds00000.o +# RUN: llvm-mc -triple=x86_64-windows-gnu %p/Inputs/gnu-implib-tail.s -filetype=obj -o %t-dabcdt.o +# RUN: rm -f %t-implib.a +# RUN: llvm-ar rcs %t-implib.a %t-dabcdh.o %t-dabcds00000.o %t-dabcdt.o +# RUN: llvm-mc -triple=x86_64-windows-gnu %s -filetype=obj -o %t.obj +# RUN: lld-link -out:%t.exe -entry:main -subsystem:console \ +# RUN: %t.obj %t-implib.a +# RUN: llvm-objdump -s %t.exe | FileCheck -check-prefix=DATA %s + + .text + .global main +main: + call func + ret + +# Check that the linker inserted the null terminating import descriptor, +# even if there were no normal import libraries, only gnu ones. + +# DATA: Contents of section .rdata: +# First import descriptor +# DATA: 140002000 28200000 00000000 00000000 53200000 +# Last word from first import descriptor, null terminator descriptor +# DATA: 140002010 38200000 00000000 00000000 00000000 +# Null terminator descriptor and import lookup table. +# DATA: 140002020 00000000 00000000 48200000 00000000 Index: test/COFF/imports-gnu.test =================================================================== --- /dev/null +++ test/COFF/imports-gnu.test @@ -0,0 +1,29 @@ +# REQUIRES: x86 +# Verify that the lld can link to GNU import libs. +# +# RUN: llvm-mc -triple=x86_64-windows-gnu %p/Inputs/gnu-implib-head.s -filetype=obj -o %t-dabcdh.o +# RUN: llvm-mc -triple=x86_64-windows-gnu %p/Inputs/gnu-implib-func.s -filetype=obj -o %t-dabcds00000.o +# RUN: llvm-mc -triple=x86_64-windows-gnu %p/Inputs/gnu-implib-tail.s -filetype=obj -o %t-dabcdt.o +# RUN: rm -f %t-implib.a +# RUN: llvm-ar rcs %t-implib.a %t-dabcdh.o %t-dabcds00000.o %t-dabcdt.o +# Not linking with -lldmingw; one can link to GNU import libs even if not targeting MinGW. +# RUN: lld-link -out:%t.exe -entry:main -subsystem:console \ +# RUN: %p/Inputs/hello64.obj %p/Inputs/std64.lib %t-implib.a -include:func +# RUN: llvm-readobj -coff-imports %t.exe | FileCheck -check-prefix=IMPORT %s + +# Check that import entries from both libraries show up. + +IMPORT: Import { +IMPORT-NEXT: Name: foo.dll +IMPORT-NEXT: ImportLookupTableRVA: +IMPORT-NEXT: ImportAddressTableRVA: +IMPORT-NEXT: Symbol: func (0) +IMPORT-NEXT: } +IMPORT-NEXT: Import { +IMPORT-NEXT: Name: std64.dll +IMPORT-NEXT: ImportLookupTableRVA: +IMPORT-NEXT: ImportAddressTableRVA: +IMPORT-NEXT: Symbol: ExitProcess (0) +IMPORT-NEXT: Symbol: (50) +IMPORT-NEXT: Symbol: MessageBoxA (1) +IMPORT-NEXT: } Index: test/COFF/no-idata.s =================================================================== --- /dev/null +++ test/COFF/no-idata.s @@ -0,0 +1,20 @@ +# REQUIRES: x86 +# +# RUN: llvm-mc -triple=x86_64-windows-gnu %s -filetype=obj -o %t.obj +# RUN: lld-link -out:%t.exe -entry:main -subsystem:console %t.obj +# RUN: llvm-objdump -s %t.exe | FileCheck -check-prefix=DUMP %s +# RUN: llvm-readobj -file-headers %t.exe | FileCheck -check-prefix=DIRECTORY %s + + .text + .global main +main: + ret + +# Check that no .idata (.rdata) entries were added, no null terminator +# for the import descriptor table. +# DUMP: Contents of section .text: +# DUMP-NEXT: 140001000 c3 +# DUMP-NEXT-EMPTY: + +# DIRECTORY: ImportTableRVA: 0x0 +# DIRECTORY: ImportTableSize: 0x0