This reverts commit r223330 because it broke Darwin and ELF
linkers in a way that we couldn't have caught with the existing
test cases.
llvm-svn: 223373
To find an AtomLayout object for the given symbol I replace the
`Layout::findAtomAddrByName` method by `Layout::findAtomLayoutByName` method.
llvm-svn: 223359
Looks like the rule of /export is more complicated than
I was thinking. If /export:foo, for example, is given, and
if the actual symbol name in an object file is _foo@<number>,
we need to export that symbol as foo, not as the mangled name.
If only /export:_foo@<number> is given, the symbol is exported
as _foo@<number>.
If both /export:foo and /export:_foo@<number> are given,
they are considered as duplicates, and the linker needs to
choose the unmangled name.
The basic idea seems that the linker needs to export a symbol
with the same name as given as /export.
We exported mangled symbols. This patch fixes that issue.
llvm-svn: 223341
The aim of this patch is to reduce the excessive abstraction from
the InputGraph. We found that even a simple thing, such as sorting
input files (Mach-O) or adding a new file to the input file list
(PE/COFF), is nearly impossible with the InputGraph abstraction,
because it hides too much information behind it. As a result,
we invented complex interactions between components (e.g.
notifyProgress() mechanism) and tricky code to work around that
limitation. There were many occasions that we needed to write
awkward code.
This patch is a first step to make it cleaner. As a first step,
this removes Group class from the InputGraph. The grouping feature
is now directly handled by the Resolver. notifyProgress is removed
since we no longer need that. I could have cleaned it up even more,
but in order to keep the patch minimum, I focused on Group.
SimpleFileNode class, a container of File objects, is now limited
to have only one File. We shold have done this earlier.
We used to allow putting multiple File objects to FileNode.
Although SimpleFileNode usually has only one file, the Driver class
actually used that capability. I modified the Driver class a bit,
so that one FileNode is created for each input File.
We should now probably remove SimpleFileNode and directly store
File objects to the InputGraph in some way, because a container
that can contain only one object is useless. This is a TODO.
Mach-O input files are now sorted before they are passe to the
Resolver. DarwinInputGraph class is no longer needed, so removed.
PECOFF still has hacky code to add a new file to the input file list.
This will be cleaned up in another patch.
llvm-svn: 223330
/export option can be given multiple times to specify multiple
symbols to be exported. /export accepts both decorated and
undecorated name.
If you give both undecorated and decorated name of the same symbol
to /export, they are resolved to the same symbol. In this case,
we need to de-duplicate the exported names, so that we don't have
duplicated items in the export symbol table in a DLL.
We remove duplicate items from a vector. The bug was there.
Because we had pointers pointing to elements of the vector,
after an item is removed, they would point wrong elements.
This patch is to remove these pointers. Added a test for that case.
llvm-svn: 223200
In PR21682 Jean-Daliel Dupas found a leak in the trie builder and suggested
a fix was to use a list instead of SmallVector so that the list elements
could be allocated in the BumpPtrAllocator.
llvm-svn: 223104
RoundTripPasses should always be called in DEBUG mode if the environment
variable "LLD_RUN_ROUNDTRIP_TEST" is set.
Flavors should not be able to override this behavior.
llvm-svn: 223073
This would allow other flavor specific contexts to override the default value,
if they want to optionally run the round trip passes.
There is some information lost like the original file owner of the atom with
RoundTripPasses. The Gnu flavor needs this information inorder to implement
LinkerScript matching and for other diagnostic outputs such as Map files.
The flag also can be used to record information in the Atom if the information
to the Writer needs to be conveyed through References too.
llvm-svn: 222983
The AtomSections were improperly merging sections from various input files. This
patch fixes the problem, with an updated test that was provided by Simon.
Thanks to Simon Atanasyan for catching this issue.
llvm-svn: 222982
Opening a file using openFileForWrite and closing it using close
was asymmetric. It also had a subtle portability problem (details are
described in the commit message for r219189).
llvm-svn: 222802
This was basically benign resource leak on Unix, but on Windows
it could cause builds to fail because opened file descriptor
prevents other processes from moving or removing the file.
llvm-svn: 222799
.ilk file is a file for incremental linking. We don't create nor use
that file.
/MAXILKFILE is an undocumented option to specify the maximum size
of the .ilk file, IIUC. We should just ignore the option.
llvm-svn: 222777
There are many build files in the wild that depend on the fact that
link.exe produces a PDB file if /DEBUG option is given. They fail
if the file is not created.
This patch is to make LLD create an empty (dummy) file to satisfy
such build targets. This doesn't do anything other than "touching"
the file.
If a target depends on the content of the PDB file, this workaround
is no help, of course. Otherwise this patch should help build some
stuff.
llvm-svn: 222773
/debug makes MSVC link.exe to not remove unused sections from
the resulting executable. We did the same thing before. However,
I realized that the removal of associative section depends on
the dead-stripping pass in LLD, so we cannot disable that. Or
LLD may produce slightly broken executables that have too much
data in it (which could result in nasty subtle bugs).
This patch is a temporary measure to create correct executable.
Currently /debug does not have any real effect for LLD anyway.
I'll improve associative section handling in another patch, so that
they are removed from output without depending on the dead-stripping
pass.
llvm-svn: 222483
Export table entries need to be sorted in ASCII-betical order,
so that the loader can find an entry for a function by binary search.
We sorted the entries by its mangled names. That can be different
from their exported names. As a result, LLD produces incorrect export
table, from which the loader complains that a function that actually
exists in a DLL cannot be found.
This patch fixes that issue.
llvm-svn: 222452
This reverts commit r222310.
Not sure which commit is the cause of the failure on the darwin bot. Will need
to revert my changes and commit one change at a time.
llvm-svn: 222330
Mach-o does not use a simple SO_NEEDED to track dependent dylibs. Instead,
the linker copies four things from each dylib to each client: the runtime path
(aka "install name"), the build time, current version (dylib build number), and
compatibility version The build time is no longer used (it cause every rebuild
of a dylib to be different). The compatibility version is usually just 1.0
and never changes, or the dylib becomes incompatible.
This patch copies that information into the NormalizedMachO format and
propagates it to clients.
llvm-svn: 222300
This patch fixes the following MSVC warning.
warning C4334: '<<' : result of 32-bit shift implicitly
converted to 64 bits (was 64-bit shift intended?)
llvm-svn: 222293
When fixing up BL instructions, the linker has to compare the thumbness of the
target to decide if the instruction needs to be converted to BLX. But with B
instruction there is no BX, so the linker asserts if the target is not the
same thumbness. This assert was firing in -r mode when the target was undefined
which it interpreted as being non-thumb.
Test case change is to add a B (in both thumb and arm code) to an undefined
symbol and round trip through -r mode.
llvm-svn: 222266
The arm64 assembler almost always uses r_extern=1 relocations in which the
r_symbolnum field is the index of the symbol the relocation references. But
sometimes it will set r_extern=0 in which case the linker needs to read the
content of the reloction to determine the target.
Add test case that the r_extern=0 relocation round trips.
llvm-svn: 222200
The arm64 assembler almost always uses r_extern=1 relocations in which the
r_symbolnum field is the index of the symbol the relocation references. But
sometimes it will set r_extern=0 in which case the linker needs to read the
content of the reloction to determine the target.
Add test case that the r_extern=0 relocation round trips.
llvm-svn: 222198
If you have something like
__declspec(align(8192)) int foo = 1;
in your code, the compiler makes the data to be aligned to 8192-byte
boundary, and the linker align the section containing the data to 8192.
LLD always aligned the section to 4192. So, as long as alignment
requirement is smaller than 4192, it was correct, but for larger
requirements, it's wrong.
This patch fixes the issue.
llvm-svn: 222043
AddressOfEntryPoint is overridden after we layout all atoms (until then,
we don't know the entry point address for obvious reason.)
I believe this code is leftover from very early version of the
PE/COFF port that we only had an entry function in a test object file.
llvm-svn: 222026
With --no-align-segments, there is a bug that the fileoffset may not be
congruent to virtual address modulo page alignment.
This patch fixes the problem.
llvm-svn: 221890
MIPS ELF symbols might contain some additional MIPS-specific flags
in the st_other field besides visibility ones. These flags indicate
code properties like microMIPS / MIPS16 encoding, position independent
code etc. We need to transfer the flags from input objects to the
output linked file to write them into the symbol table, adjust symbols
addresses etc.
I add new attribute CodeModel to the DefinedAtom class to hold target
specific flag and to get over YAML/Native format conversion barrier.
Other architectures/targets can extend CodeModel enumeration by their
own flags.
MIPS specific part of this patch adds support for STO_MIPS_MICROMIPS
flag. This flag marks microMIPS symbols. Such symbol should:
a) Has STO_MIPS_MICROMIPS in the corresponding .symtab record.
b) Has adjusted (odd) address in the corresponding .symtab
and .dynsym records.
llvm-svn: 221864
The segment alignment for PT_LOAD segments is set to page size by default, but
if any of the sections require an alignment more than the page size, the segment
alignment property is set to the maximum alignment of the sections that are part
of the segment.
llvm-svn: 221862
The user can use the max-page-size option and set the maximum page size. Dont
check for maximum allowed values for page size, as its what the kernel is
configured with.
Fix the test as well.
llvm-svn: 221858
Each entry in the delay-import address table had a wrong alignment
requirement if 32 bit. As a result it got wrong delay-import table.
Because llvm-readobj doesn't print out that field, we don't have a
test for that. I'll submit a test that would catch this bug after
improving llvm-readobj.
llvm-svn: 221853
The GOT slots were being laid out in a random order by the GOTPass which
caused randomness in the output file.
Note: With this change lld now bootstraps on darwin. That is:
1) link lld using system linker to make lld.1
2) link lld using lld.1 to make lld.2
3) link lld using lld.2 to make lld.3
Now lld.2 and lld.3 are identical.
llvm-svn: 221831
On darwin in final linked images, the __TEXT segment covers that start of the
file. That means in memory a process can see the mach_header (and load commands)
for every loaded image in a process. There are APIs that take and return the
mach_header addresses as a way to specify a particular loaded image.
For completeness, any code can get the address of the mach_header of the image
it is in by using &__dso_handle. In addition there are mach-o type specific
symbols like __mh_execute_header.
The linker needs to supply a definition for any of these symbols if used. But
the address the symbol it resolves to is not in any section. Instead it is the
address of the start of the __TEXT segment.
I needed to make a small change to SimpleFileNode to not override
resetNextIndex() because the Driver creates a SimpleFileNode to hold the
internal/implicit files that the context/writer can create. For some reason
SimpleFileNode overrode resetNextIndex() to do nothing instead of reseting
the index (which mach-o needs if the internal file is an archive).
llvm-svn: 221822
The way lazy binding works in mach-o is that the linker generates a helper
function and has the stub (PLT) initially jump to it. The helper function
pushes an extra parameter then jumps into dyld. The extra parameter is an
offset into the lazy binding info where dyld will find the information about
which symbol to bind and way lazy binding pointer to update.
llvm-svn: 221654
The dynamic table was creating the entry DT_FINI_ARRAY{SZ} even when there was
no .fini_array section. The entries should be creating in the dynamic section
only if there are sections .init_array/.fini_array in the output.
Fixes the tests that checked for errroneous outputs.
llvm-svn: 221588
The value of _DYNAMIC should be pointing at the start of the .dynamic segment.
This was pointing to the end of the dynamic segment. Similarly the value of
_GLOBAL_OFFSET_TABLE_ was not proper too.
llvm-svn: 221587
The parsing routines in the linker script to parse strings encoded in various
formats(hexadecimal, octal, decimal, etc), is needed by the GNU driver too. This
library provides helper functions for all flavors and flavors to add helper
functions which other flavors may make use of.
llvm-svn: 221583
lld generates an ELF by adhering to the ELF spec by aligning vma/fileoffset to a
page boundary, but this becomes an issue when dealing with large pages. This
adds support so that lld generated executables adheres to the ELF spec with the
rule vma % p_align = offset % p_align.
This is supported by the flag --no-align-segments.
This could be the default in few targets like X86_64 to save space on disk.
llvm-svn: 221571
My previous fix to have FileArchive own the member MemoryBuffers was not a
complete solution for darwin because nothing owned the FileArchive object.
Fixed MachOFileNode to be like ELFFileNode and have the graph node own the
archive object.
llvm-svn: 221552
The darwin linker lets you rearrange functions and data for better locality
(less paging). You do this with the -order_file option which supplies a text
file containing one symbol per line.
Implementing this required a small change to LayoutPass to add a custom sorter
hook.
llvm-svn: 221545
When FileArchive loads a member, it instantiates a temporary MemoryBuffer
which points to the member range of the archive file. The problem is that the
object file parsers call getBufferIndentifer() on that temporary MemoryBuffer
and store that StringRef as the _path data member for that lld::File. When
FileArchive::instantiateMember() goes out of scope the MemoryBuffer is deleted
and the File::._path becomes a dangling reference.
The fix adds a vector<> to FileArchive to own the instantiated MemoryBuffers.
In addition it fixes member's path to be the standard format
(e.g. "/path/libfoo.a(foo.o)") instead of just the leaf name.
llvm-svn: 221544
Request `getPairRelocation()` function to get paired relocation type.
That allows us to look up another pairs like R_MICROMIPS_HI16/LO16
in the future.
llvm-svn: 221539
ELFLinkingContext had these two functions, which is really not needed since
the Writer uses a llvm::object template composed of Endianness, Alignment,
Is32bit/64bit. We could just use that and not duplicate functionality.
No Change In Functionality.
llvm-svn: 221523
If /subsystem option is not given, the linker needs to infer the
subsystem based on the entry point symbol. If it fails to infer
that, the linker should error out on it.
LLD was almost correct, but it would fail to infer the subsystem
if the entry point is specified with /entry. This is because the
subsystem inference was coupled with the entry point function
searching (if no entry point name is specified, the linker needs
to find the right entry name).
This patch makes the subsystem inference an independent pass to
fix the issue. Now, as long as an entry point function is defined,
LLD can infer the subsystem no matter how it resolved the entry
point.
I don't think scanning all the defined symbols is fast, although
it shouldn't be that slow. The file class there does not provide
any easy way to find an atom by name, so this is what we can do
at this moment. I'd like to revisit this later to make it more
efficient.
llvm-svn: 221499
The darwin linker has two ways to force all members of an archive to be loaded.
The -all_load option applies to all static libraries. The -force_load takes
a path to a library and just that library's members are force loaded.
llvm-svn: 221477
1. The path checks ELF header flags to prevent linking of incompatible files.
For example we do not allow to link files with different ABI, -mnan
flags, some combination of target CPU etc.
2. The patch merge ELF header flags from input object files to put their
combination to the generated file. For example, if some input files
have EF_MIPS_NOREORDER flag we need to put this flag to the output
file header.
I use the `parseFile()` (not `canParse()`) method because in case of
recognition of incorrect input flags combination we should show detailed
error message and stop the linking process and should not try to use
another `Reader`.
llvm-svn: 221439
The darwin linker does not process dwarf debug info. Instead it produces a
"debug map" in the output file which points back to the original .o files for
anything that wants debug info (e.g. debugger).
The -S option means "don't add a debug map". lld for mach-o currently does
not generate the debug map, so there is nothing to do when this option is used.
But we need to process the option to get existing projects building.
llvm-svn: 221432
Darwin uses two-level-namespace lookup for symbols which means the static
linker records where each symbol must be found at runtime. Thus defining a
symbol in a dylib loaded earlier will not effect where symbols needed by
later dylibs will be found. Instead overriding is done through a section
of type S_INTERPOSING which contains tuples of <interposer, interposee>.
llvm-svn: 221421
SECREL relocation's value is the offset to the beginning of the section.
Because of the off-by-one error, if a SECREL relocation target is at the
beginning of a section, it got wrong value.
Added a test that would have caught this.
llvm-svn: 221420
The local variable `cfi` became dead in r220730 when it's use was
obviated; it was replaced with a call to read32.
No functionality change intended.
llvm-svn: 221412
Many programs, for reasons unknown, really like to look at the
AddressOfRelocationTable to determine whether or not they are looking at
a bona fide PE file. Without this, programs like the UNIX `file'
utility will insist that they are looking at a MS DOS executable.
llvm-svn: 221335
LLD skipped COMDAT section symbols when reading them because
I thought we don't want to have symbols with the same name.
But they are actually needed because relocations may refer to
the section symbols. So we shoulnd't skip them.
llvm-svn: 221329
The job of the CompactUnwind pass is to turn __compact_unwind data (and
__eh_frame) into the compressed final form in __unwind_info. After it's done,
the original atoms are no longer relevant and should be deleted (they cause
problems during actual execution, quite apart from the fact that they're not
needed).
llvm-svn: 221301
The ELF writer creates a invalid binary for few cases with large filesize and
memory size for segments. This patch addresses the functionality and updates the
test. This patch also cleans up parts of the ELF writer for future enhancements
to support Linker scripts.
llvm-svn: 221233
Normally, PE files have section names of eight characters or less.
However, this is problematic for DWARF because DWARF section names are
things like .debug_aranges.
Instead of truncating the section name, redirect the section name into
the string table.
Differential Revision: http://reviews.llvm.org/D6104
llvm-svn: 221212
This patch does *not* implement any semantic actions, but it is a first step to
teach LLD how to read complete linker scripts. The additional linker scripts
statements whose parsing is now supported are:
* SEARCH_DIR directive
* SECTIONS directive
* Symbol definitions inside SECTIONS including PROVIDE and PROVIDE_HIDDEN
* C-like expressions used in many places in linker scripts
* Input to output sections mapping
The goal of this commit was guided towards completely parsing a default GNU ld
linker script and the linker script used to link the FreeBSD kernel. Thus, it
also adds a test case based on the default linker script used in GNU ld for
x86_64 ELF targets. I tested SPEC userland programs linked by GNU ld, using the
linker script dump'ed by this parser, and everything went fine. I then tested
linking the FreeBSD kernel with a dump'ed linker script, installed the new
kernel and booted it, everything went fine.
Directives that still need to be implemented:
* MEMORY
* PHDRS
Reviewers: silvas, shankarke and ruiu
http://reviews.llvm.org/D5852
llvm-svn: 221126
lld was regenerating LC_DATA_IN_CODE in .o output files, but not into
final linked images.
Update test case to verify data-in-code info makes it into final linked images.
llvm-svn: 220827
Objective-C switched to a new ABI which uses a different mangling for class
names. But to keep projects building that use export lists that use the old
class name mangling, the linker recognizes the old names and transforms them
to the new mangling.
llvm-svn: 220598
In final linked shared images, the __TEXT segment contains both code and
the mach-o header/load-commands. In the case of a data-only dylib, there is
no code, so we need to force the addition of the __TEXT segment.
llvm-svn: 220597
This is a follow-up patch for r220333. r220333 renames exported symbols.
That raised another issue; if we have both decorated and undecorated names
for the same symbol, we'll end up have two duplicate exported symbol
entries.
This is a fix for that issue by removing duplciate entries.
llvm-svn: 220350
All compiler generated mach-o object files are marked with MH_SUBSECTIONS_VIA_SYMBOLS.
But hand written assembly files need to opt-in if they are written correctly.
The flag means the linker can break up a sections at symbol addresses and
dead strip or re-order functions.
This change recognizes object files without the flag and marks its atoms as
not dead strippable and adds a layout-after chain of references so that the
atoms cannot be re-ordered.
llvm-svn: 220348
There are two ways to specify a symbol to be exported in the module
definition file.
1) EXPORT <external name> = <symbol>
2) EXPORT <symbol>
In (1), you give both external name and internal name. In that case,
the linker tries to find a symbol using the internal name, and write
that address to the export table with the external name. Thus, from
the outer world, the symbol seems to be exported as the external name.
In (2), internal name is basically the same as the external name
with an exception: if you give an undecorated symbol to the EXPORT
directive, and if the linker finds a decorated symbol, the external
name for the symbol will become the decorated symbol.
LLD didn't implement that exception correctly. This patch fixes that.
llvm-svn: 220333
The darwin linker operates differently than the gnu linker with respect to
libraries. The darwin linker first links in all object files from the command
line, then to resolve any remaining undefines, it repeatedly iterates over
libraries on the command line until either all undefines are resolved or no
undefines were resolved in the last pass.
When Shankar made the InputGraph model, the plan for darwin was for the darwin
driver to place all libraries in a group at the end of the InputGraph. Thus
making the darwin model a subset of the gnu model. But it turns out that does
not work because the driver cannot tell if a file is an object or library until
it has been loaded, which happens later.
This solution is to subclass InputGraph for darwin and just iterate the graph
the way darwin linker needs.
llvm-svn: 220330
HAVE_CXXABI_H is not defined on FreeBSD but the system actually
has the header. CMake test fails because the header depends on size_t.
llvm-svn: 220315
The canParse function for all the ELF subtargets check if the input files match
the subtarget.
There were few mismatches in the input files that didnt match the subtarget for
which the link was being invoked, which also acts as a test for this change.
llvm-svn: 220182
For PC relative accesses, negative addends were to be ignored. The linker was
not ignoring it and would fail with an assert. This fixes the issue and is able
to get Helloworld working.
llvm-svn: 220179
The old code was used as a workaround to fix how relocations are calculated for
sections with SHF_MERGE|SHF_STRINGS attribute. This patch removes the erroneous
code.
llvm-svn: 220159
This fixes the way archive members are displayed when the linker is used with a
flag to show all the files that it processes.
When an archive file member is read, we need to show the archive filename and
the member.
llvm-svn: 220144
This would permit the ELF reader to check the architecture that is being
selected by the linking process.
This patch also sorts the include files according to LLVM conventions.
llvm-svn: 220129
The code was making non-portable assumptions about the exact string returned by
the glob (possibly by the shell?); this is more robust and matches what is done
everywhere else.
llvm-svn: 220117
Previously we supported x86 only. This patch is to support x64.
The array of pointers to delay-loaded functions points the
DLL delay loading function at start-up. When a function is called
for the first time, the delay loading function gets called and
then rewrite the function pointer array.
llvm-svn: 220096
-all_load tells the darwin linker to immediately load all members of all
archives. The code do that used reinterpret_cast<> instead of dyn_cast<>.
If the file was a dylib, the reinterpret_cast<> turned a pointer to a dylib
into a pointer to an archive...boom.
Added test case to reproduce the crash, simplified the code and used dyn_cast<>.
llvm-svn: 219990
First, add a comment to support more variation in FDE formats. Second, refactor
fde -> function handling into a separate function living in the ArchHandler.
llvm-svn: 219959
To deal with cycles in shared library dependencies, the darwin linker supports
marking specific link dependencies as "upward". An upward link is when a
lower level library links against a higher level library.
llvm-svn: 219949
This patch creates the import address table and sets its
address to the delay-load import table. This also creates
wrapper functions for __delayLoadHelper2.
x86 only for now.
llvm-svn: 219948
Not all situations are representable in the compressed __unwind_info format,
and when this happens the entry needs to point to the more general __eh_frame
description.
Just x86_64 implementation for now.
rdar://problem/18208653
llvm-svn: 219836
We'll also need references back to the CIE eventually, but for now making sure
we can work out what an FDE is referring to is enough.
The actual kind of reference needs to be different between architectures,
probably because of MachO's chronic shortage of relocation types but I don't
really want to know in case I find out something that distresses me even more.
rdar://problem/18208653
llvm-svn: 219824
Because we use cast<> at the beginning of this function, it will
abort there if a given atom is not a DefinedAtom.
In the switch statement, we checked if a given atom is a DefinedAtom
again by evaluating definition() == Atom::definitionRegular.
This was always true. So we can remove the outer switch statement.
llvm-svn: 219724
Arm code has two instruction encodings "thumb" and "arm". When branching from
one code encoding to another, you need to use an instruction that switches
the instruction mode. Usually the transition only happens at call sites, and
the linker can transform a BL instruction in BLX (or vice versa). But if the
compiler did a tail call optimization and a function ends with a branch (not
branch and link), there is no pc-rel BX instruction.
The ShimPass looks for pc-rel B instructions that will need to switch mode.
For those cases it synthesizes a shim which does the transition, then modifies
the original atom with the B instruction to target to the shim atom.
llvm-svn: 219655
When committed in r219353, this patch originally caused problems because it was
not tested in debug build. In such scenarios, Driver.cpp adds two additional
passes. These passes serialize all atoms via YAML and reads it back. Since the
patch changed ObjectAtom to hold a new reference, the serialization was removing
the extra data.
This commit implements r219853 in another way, similar to the original MIPS way,
by using a StringSet that holds the names of all copied atoms instead of
directly holding a reference to the copied atom. In this way, this commit is
simpler and eliminate the necessity of changing the DefinedAtom hierarchy to
hold a new data.
Reviewers: shankarke
http://reviews.llvm.org/D5713
llvm-svn: 219449
We are going to have another type of jump table for the delay-load
import table. In order to prepare for that, we want to factor out
the function handling the jump table. No functionality change.
llvm-svn: 219446
Previously the field was not set. The field should be pointing to
a placeholder where the DLL delay-loader writes the base address
of a DLL.
llvm-svn: 219415
This is a partial patch to emit the delay-import table. With this,
LLD is now able to emit the table that llvm-readobj can read and
dump.
The table lacks a few fields, such as the address of HMODULE, the
import address table, etc. They'll be added in subsequent patches.
llvm-svn: 219384
Enhances the creation of an ELF dynamic executable by avoiding recording
unnecessary shared libraries as NEEDED to load a program.
To do this, we must keep track of not only symbols that were referenced but
also of COPY relocations, which steal the symbol from a shared library but does
not store from which lib this symbol came from. To fix this, this commit changes
ObjectSymbol to store the original library from which this symbol came. With
this information, we are able to build a list of the exact shared libraries that
must be marked as DT_NEEDED, instead of blindly marking all shared libraries as
needed.
This logic originally came from the MIPS backend with some adaptation.
Reviewers: atanasyan, shankar.easwaran
http://reviews.llvm.org/D5574
llvm-svn: 219353
Updates the remaining tasks in the X86_64 ELF lld backend after the commit that
handles general dynamic TLS relocations.
Reviewer: shankarke
http://reviews.llvm.org/D5673
llvm-svn: 219350
This commit implements in the X86_64 ELF lld backend yet another feature that
was only available in the MIPS backend. However, this patch changes generic ELF
classes to make it trivial for other ELF backends to use this logic too. When
creating a dynamic executable that has dynamic relocations against weak
undefined symbols, these symbols must be exported to the dynamic symbol table
to seek a possible resolution at run time.
A common use case is the __gmon_start__ weak glibc undefined symbol.
Reviewer: shankarke
http://reviews.llvm.org/D5571
llvm-svn: 219349
When creating a dynamic executable and receiving the -E flag, the linker should
export all globally visible symbols in its dynamic symbol table.
This commit also moves the logic that exports symbols in the dynamic symbol
table from OutputELFWriter to the ExecutableWriter class. It is not correct to
leave this at OutputELFWriter because DynamicLibraryWriter, another subclass of
OutputELFWriter, already exports all symbols, meaning we can potentially end up
with duplicated symbols in the dynamic symbol table when creating shared libs.
Reviewers: shankarke
http://reviews.llvm.org/D5585
llvm-svn: 219334
Summary: Add support in the universal driver to print the lld version and the
repository version.
Test Plan: A driver test is added
Reviewers: kledzik, ruiu
Reviewed By: ruiu
Subscribers: llvm-commits
Projects: #lld
Differential Revision: http://reviews.llvm.org/D5641
llvm-svn: 219277
mach-o supports "fat" files which are a header/table-of-contents followed by a
concatenation of mach-o files (or archives of mach-o files) built for
different architectures. Previously, the support for fat files was in the
MachOReader, but that only supported fat .o files and dylibs (not archives).
The fix is to put the fat handing into MachOFileNode. That way any input file
kind (including archives) can be fat. MachOFileNode selects the sub-range
of the fat file that matches the arch being linked and creates a MemoryBuffer
for just that subrange.
llvm-svn: 219268
Teach the reader about ARM NT relocation types. Although the writer cannot yet
perform the actual application of these relocations, the reader can at least now
identify the relocation types.
llvm-svn: 219178
Previously, we would not check the target machine type and the module (object)
machine type. Add a check to ensure that we do not attempt to use an object
file with a different target architecture.
This change identified a couple of tests which were incorrectly mixing up
architecture types, using x86 input for a x64 target. Adjust the tests
appropriately. The renaming of the input and the architectures covers the
changes to the existing tests.
One significant change to the existing tests is that the newly added test input
for x64 uses the correct user label prefix for X64.
llvm-svn: 219093
Rather than a series of cascading ifs, use a switch statement to convert the
error code to a string. This has the benefit of allowing the compiler to inform
us if we ever add a new error code but fail to update the string representation.
Add in stringified versions for a couple of missing InputGraphErrors.
llvm-svn: 219089
In order to support more than x86/x86_64, we need to change the behaviour to use
the actual machine type rather than checking the bitness and assuming that we
are on X86. This replaces the use of is64bit in applyAllRelocations with a
check on the machine type. This will enable adding support for handling ARM
relocations.
Rename the existing applyRelocation methods to be similarly named and to make it
clear the types of relocations they will process.
llvm-svn: 219088
This option is added by Xcode when it runs the linker. It produces a binary
file which contains the file the linker used. Xcode uses the info to
dynamically update it dependency tracking.
To check the content of the binary file, the test case uses a python script
to dump the binary file as text which FileCheck can check.
llvm-svn: 219039
When creating the graph edges of the atoms of an ELF file, special care must be
taken with atoms that represent weak symbols. They cannot be the target of any
Reference::kindLayoutAfter edge because they can be merged and point to other
code, screwing up the final layout of the atoms. ELFFile::createAtoms()
correctly handles this corner case. The problem is that createAtoms() assumed
that there can be no zero-sized weak symbols, which is not true. Consider:
my_weak_func1:
my_weak_func2:
my_weak_func3:
code
In this case, we have two zero-sized weak symbols, my_weak_func1 and
my_weak_func2, and one non-zero weak symbol my_weak_func3. createAtoms() would
correctly handle my_weak_func3, but not the first two symbols. This problem
happens in the musl C library when a zero-sized weak symbol is merged and
screws up the file layout. Since this musl code lives at the finalization hooks,
any C program linked with LLD and musl was correctly executing, but segfaulting
at the end.
Reviewers: shankarke
http://reviews.llvm.org/D5606
llvm-svn: 219034
DLL delay importing is a feature to load a DLL lazily, instead of
at program start-up time.
If the feature is turned on with the /delayload flag, the linker
resolves the delay-load helper function. All function pointer table
entries for the DLL are initially pointing to the helper function.
When called, the function loads and resolves the DLL symbols using
dlopen-ish Windows system calls and then write the reuslts to the
function pointer table. The helper function is in "delayimp.lib".
Note that this feature is not completely implemented yet. LLD
also needs to emit the table that's consumed by the delay-load
helper function. That'll be done in another patch.
llvm-svn: 218943
The mergeByContent attribute on DefinedAtoms triggers the symbol table to
coalesce atoms with the exact same content. The problem is that atoms can also
have a required custom section. The coalescing should never change the custom
section of an atom.
The fix is to only consider to atoms to have the same content if their
sectionChoice() and customSectionName() attributes match.
llvm-svn: 218893
This patch adds logic to avoid putting the dynamic linker library (ld.so) as a
DT_NEEDED entry in the dynamic table. It should only appear in PT_INTERP.
This patch fixes SPEC programs 433, 445, 450, 453, 456, 462 when running on
Ubuntu Linux x86_64 and when linking SPEC programs with LLD and glibc 2.19.
http://reviews.llvm.org/D5573
llvm-svn: 218847
Summary: With r218633, the logic that monitors which shared library symbols were used was copied from the MIPS lld backend to ELF classes, making it available to all ELF backends. However, this made the isDynSymEntryRequired() functions in MipsDynamicLibraryWriter.h/MipsELFWriters.h/MipsExecutableWriter.h to be duplicated logic, since this is already implemented in OutputELFWriter<>/DefaultLayout. This patch removes this duplicated code from MIPS.
Reviewers: Bigcheese, shankarke
Reviewed By: shankarke
Subscribers: llvm-commits
Differential Revision: http://reviews.llvm.org/D5564
llvm-svn: 218846
No functionality change. This removes a down-cast from LinkingContext to
MachOLinkingContext.
Also, remove const from LinkingContext::createImplicitFiles() to remove
the need for another const cast. Seems reasonable for createImplicitFiles()
to need to modify the context (MachOLinkingContext does).
llvm-svn: 218796
The darwin linker has the -demangle option which directs it to demangle C++
(and soon Swift) mangled symbol names. Long term we need some Diagnostics object
for formatting errors and warnings. But for now we have the Core linker just
writing messages to llvm::errs(). So, to enable demangling, I changed the
Resolver to call a LinkingContext method on the symbol name.
To make this more interesting, the demangling code is done via __cxa_demangle()
which is part of the C++ ABI, which is only supported on some platforms, so I
had to conditionalize the code with the config generated HAVE_CXXABI_H.
llvm-svn: 218718
This is yet another edge case of ambiguous name resolution.
When a symbol is specified with /entry:SYM, SYM may be resolved
to the C++ mangled function name (?SYM@@YAXXZ).
llvm-svn: 218706
This is a minimally useful pass to construct the __unwind_info section in a
final object from the various __compact_unwind inputs. Currently it doesn't
produce any compressed pages, only works for x86_64 and will fail if any
function ends up without __compact_unwind.
rdar://problem/18208653
llvm-svn: 218703
MSDN doesn't say about /export:foo=bar style option, but
it turned out MSVC link.exe actually accepts that. So we need that
too.
It also means that the export directive in the module definition
file and /export command line option are functionally equivalent.
llvm-svn: 218695
Summary:
This patch adds support for the general dynamic TLS access model for X86_64 (see www.akkadia.org/drepper/tls.pdf).
To properly support TLS, the patch also changes the __tls_get_addr atom to be a shared library atom instead of a regularly defined atom (the previous lld approach). This closely models the reality of a function that will be resolved at runtime by the dynamic linker and loader itself (ld.so). I was tempted to force LLD to link against ld.so itself to resolve these symbols, but since GNU ld does not need the ld.so library to resolve this symbol, I decided to mimic its behavior and keep hardwired a definition of __tls_get_addr in the lld code.
This patch also moves some important logic that previously was only available to the MIPS lld backend to be used to all ELF backends. This logic, which now lives in the DefaultLayout class, will monitor which external (shared lib) symbols are really imported by the current module and will only populate the dynamic symbol table with used symbols, as opposed to the previous approach of dumping all shared lib symbols in the dynamic symbol table. This is important to this patch to avoid __tls_get_addr from getting injected into all dynamic symbol tables.
By solving the previous problem of always adding __tls_get_addr, now the produced symbol tables are slightly smaller. But this impacted several tests that relied on hardwired/predefined sizes of the symbol table, requiring this patch to update such tests.
Test Plan: Added a LIT test case that exercises a simple use case of TLS variable in a shared library.
Reviewers: ruiu, rafael, Bigcheese, shankarke
Reviewed By: Bigcheese, shankarke
Subscribers: emaste, shankarke, joerg, kledzik, mcrosier, llvm-commits
Projects: #lld
Differential Revision: http://reviews.llvm.org/D5505
llvm-svn: 218633
Previously we emit two or more identical definitions for an
exported symbol if the same /export option is given more than
once. This patch fixes that bug.
llvm-svn: 218433
This patch is difficult to test in isolation, so a subsequent patch will test
further.
Patch by Daniel Stewart <stewartd@codeaurora.org>!
Phabricator Revision: http://reviews.llvm.org/D5377
llvm-svn: 218418
lib.exe prints a warning if a symbol in a module definition file has
both the PRIVATE attribute and an ordinal like this.
EXPORTS
foo @1 PRIVATE
This patch suppresses that.
llvm-svn: 218395
Currently you can omit the leading underscore from exported
symbol name. LLD will look for mangled name for you. But it won't
look for C++ mangled name.
This patch is to support that.
If "sym" is specified to be exported, the linker looks for not
only "sym", but also "_sym" and "?sym@@<whatever>", so that you
can export a C++ function without decorating it.
llvm-svn: 218355
Exported symbol name resolution is two-pass. In the first pass,
we try to resolve that as a regular undefined symbol. If it fails,
we look for mangled name for the symbol and rename the undefined
symbol and try again.
After all name resolution is done, we look for an atom for each
exported symbol again, to construct the export table. In this
process we try the regular names first, and then try mangled names.
But at this moment we should have knew which name is correct.
This patch is to keep the information we get in the first process
to use it later.
llvm-svn: 218354
The export table descriptor is a data structure to keep information
about the export table. It contains a symbol name, and the name may
or may not be mangled.
We need unmangled names for the export table, so we demangle them
before writing them to the export table.
Obviously this is not a correct round-trip conversion. That could
drop a leading underscore from a symbol because that's
indistinguishable from a mangled name.
What we need to do is to keep unmangled names. This patch does that.
llvm-svn: 218345
/machine:ebc was previously recognized but rejected. Unknown architecture
names were handled differently but eventually rejected too. We don't need
to distinguish them.
llvm-svn: 218344
This patch changes the type of export table set from std::set to
std::vector. The new code is slightly inefficient, but because
export table elements are actually mutable, std::vector is better
here. No functionality change.
llvm-svn: 218343
If two or more /export options are given for the same symbol, we should
always print a warning message and use the first one regardless of other
parameters.
Previously there was a case that the first parameter is not used.
llvm-svn: 218342
A symbol in a module definition file may be annotated with the
PRIVATE keyword like this.
EXPORTS
func PRIVATE
The PRIVATE keyword does not affect the resulting .dll file.
But it prevents the symbol to be listed in the .lib (import
library) file.
llvm-svn: 218273
Patch from Rafael Auler!
When a shared lib has an undefined symbol that is defined in a regular object
(the program), the final executable must export this symbol in the dynamic
symbol table. However, in the current logic, lld only puts the symbol in the
dynamic symbol table if the symbol is weak. This patch fixes lld to put the
symbol in the dynamic symbol table regardless if it is weak or not.
This caused a problem in FreeBSD10, whose programs link against a crt1.o
that defines the symbol __progname, which is, in turn, undefined in libc.so.7
and will only be resolved in runtime.
http://reviews.llvm.org/D5424
llvm-svn: 218259
llvm\tools\lld\lib\readerwriter\macho\macholinkingcontext.cpp(647):
warning C4715: 'lld::MachOLinkingContext::exportSymbolNamed' :
not all control paths return a value
llvm\tools\lld\lib\readerwriter\macho\machonormalizedfilefromatoms.cpp(723):
warning C4715: '`anonymous namespace'::Util::getSymbolTableRegion' :
not all control paths return a value
While all enum values do appear in the switch, an uninitialized or corrupted
enum variable would not be caught without the default: case in the switch.
llvm-svn: 218197
Atoms are ordered in the output file by ordinal. File has file ordinal,
and atom has atom ordinal which is unique within the file.
No two atoms should have the same combination of ordinals.
However that contract was not satisifed for alias atoms. Alias atom
is defined by /alternatename:sym1=sym2. In this case sym1 is defined
as an alias for sym2. sym1 always got ordinal 0.
As a result LLD failed with an assertion failure.
This patch assigns ordinal to alias atoms.
llvm-svn: 218158
Cache the machine type value of the linking context. We need this in order to
calculate the virtual address of the atom when resolving function symbols.
Windows on ARM must check if the atom is a function and if so, set the Thumb bit
for the returned virtual address. Failure to do so will result in an abnormal
exit due to a trap caused by invalid instruction decoding. The same information
can be used to determine the relocation type that was previously being done via
is64 to select between x86 and x86_64.
llvm-svn: 218106
Accept /machine:arm as an argument. This is changed to support ARM NT.
Although there is no way to differentiate between ARM (Windows CE) and ARM NT
(Windows on ARM), since LLVM currently only supports Windows on ARM, simply take
/machine:arm to mean Windows on ARM.
llvm-svn: 218105
Rather than saving whether we are targeting 64-bit x86 (x86_64), simply convert
the single use of that information to the actual relocation type. This will
permit the selection of non-x86 relocation types (e.g. for WoA support).
Inline the access of the machine type field as it is relatively cheap (a couple
of pointer dereferences) rather than storing the relocation type as a member
variable.
llvm-svn: 218104
When we encounter an unknown machine type, we print out the machine type magic.
However, we would print out the magic in decimal rather than hex. Perform this
conversion to make it easier to identify what machine is unsupported.
llvm-svn: 218103
This patch fixes a forbidden use of Twine. It should only be used
as an intermediary value, but never stored.
This caused a bug in lld when running on Linux and compiled with
optimizations - it couldn't properly search libs.
Patch from Rafael Auler!
llvm-svn: 218083
I made LLD to report an error if /safeseh:no option is given on x64,
but it turned out MSVC link.exe doesn't report error on it.
Removing the check.
llvm-svn: 218077
The contents from section .CRT$XLA to .CRT$XLZ is an array of function
pointers. They are called by the runtime when a new thread is created
or (gracefully) terminated.
You can make your own initialization function to be called by that
mechanism. All you have to do is:
- Define a pointer to a function in a .CRT$XL* section using pragma
- Make an external reference to "__tls_used" symbol
That technique is used in many projects. This patch is to support that.
What this patch does is to set the relative virtual address of
"__tls_used" to the PECOFF directory table. __tls_used is actually a
struct containing pointers to a symbol in .CRT$XLA and another symbol
in .CRT$XLZ. The runtime looks at the directory table, gets the address
of the struct, and call the function pointers between XLA and XLZ.
llvm-svn: 218007
On darwin, the linker tools records which dylib (DSO) each undefined was found
in, and then at runtime, the loader (dyld) only looks in that one specific
dylib for each undefined symbol. Now that llvm-objdump can display that info
I can write test cases.
llvm-svn: 217898