2c225503d619f97cead1708136563b43692c5017
[oota-llvm.git] / lib / Linker / LinkItems.cpp
1 //===- lib/Linker/LinkItems.cpp - Link LLVM objects and libraries ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains routines to handle linking together LLVM bitcode files,
11 // and to handle annoying things like static libraries.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Linker.h"
16 #include "llvm/Module.h"
17 #include "llvm/Bitcode/ReaderWriter.h"
18 #include "llvm/System/Path.h"
19 #include "llvm/Support/ErrorHandling.h"
20 #include "llvm/Support/MemoryBuffer.h"
21 using namespace llvm;
22
23 // LinkItems - This function is the main entry point into linking. It takes a
24 // list of LinkItem which indicates the order the files should be linked and
25 // how each file should be treated (plain file or with library search). The
26 // function only links bitcode and produces a result list of items that are
27 // native objects. 
28 bool
29 Linker::LinkInItems(const ItemList& Items, ItemList& NativeItems) {
30   // Clear the NativeItems just in case
31   NativeItems.clear();
32
33   // For each linkage item ...
34   for (ItemList::const_iterator I = Items.begin(), E = Items.end();
35        I != E; ++I) {
36     if (I->second) {
37       // Link in the library suggested.
38       bool is_native = false;
39       if (LinkInLibrary(I->first, is_native))
40         return true;
41       if (is_native)
42         NativeItems.push_back(*I);
43     } else {
44       // Link in the file suggested
45       bool is_native = false;
46       if (LinkInFile(sys::Path(I->first), is_native))
47         return true;
48       if (is_native)
49         NativeItems.push_back(*I);
50     }
51   }
52
53   // At this point we have processed all the link items provided to us. Since
54   // we have an aggregated module at this point, the dependent libraries in
55   // that module should also be aggregated with duplicates eliminated. This is
56   // now the time to process the dependent libraries to resolve any remaining
57   // symbols.
58   bool is_native;
59   for (Module::lib_iterator I = Composite->lib_begin(),
60          E = Composite->lib_end(); I != E; ++I) {
61     if(LinkInLibrary(*I, is_native))
62       return true;
63     if (is_native)
64       NativeItems.push_back(std::make_pair(*I, true));
65   }
66
67   return false;
68 }
69
70
71 /// LinkInLibrary - links one library into the HeadModule.
72 ///
73 bool Linker::LinkInLibrary(StringRef Lib, bool& is_native) {
74   is_native = false;
75   // Determine where this library lives.
76   sys::Path Pathname = FindLib(Lib);
77   if (Pathname.isEmpty())
78     return error("Cannot find library '" + Lib.str() + "'");
79
80   // If its an archive, try to link it in
81   std::string Magic;
82   Pathname.getMagicNumber(Magic, 64);
83   switch (sys::IdentifyFileType(Magic.c_str(), 64)) {
84     default: llvm_unreachable("Bad file type identification");
85     case sys::Unknown_FileType:
86       return warning("Supposed library '" + Lib.str() + "' isn't a library.");
87
88     case sys::Bitcode_FileType:
89       // LLVM ".so" file.
90       if (LinkInFile(Pathname, is_native))
91         return true;
92       break;
93
94     case sys::Archive_FileType:
95       if (LinkInArchive(Pathname, is_native))
96         return error("Cannot link archive '" + Pathname.str() + "'");
97       break;
98
99     case sys::ELF_Relocatable_FileType:
100     case sys::ELF_SharedObject_FileType:
101     case sys::Mach_O_Object_FileType:
102     case sys::Mach_O_FixedVirtualMemorySharedLib_FileType:
103     case sys::Mach_O_DynamicallyLinkedSharedLib_FileType:
104     case sys::Mach_O_DynamicallyLinkedSharedLibStub_FileType:
105     case sys::COFF_FileType:
106       is_native = true;
107       break;
108   }
109   return false;
110 }
111
112 /// LinkLibraries - takes the specified library files and links them into the
113 /// main bitcode object file.
114 ///
115 /// Inputs:
116 ///  Libraries  - The list of libraries to link into the module.
117 ///
118 /// Return value:
119 ///  FALSE - No error.
120 ///  TRUE  - Error.
121 ///
122 bool Linker::LinkInLibraries(const std::vector<std::string> &Libraries) {
123
124   // Process the set of libraries we've been provided.
125   bool is_native = false;
126   for (unsigned i = 0; i < Libraries.size(); ++i)
127     if (LinkInLibrary(Libraries[i], is_native))
128       return true;
129
130   // At this point we have processed all the libraries provided to us. Since
131   // we have an aggregated module at this point, the dependent libraries in
132   // that module should also be aggregated with duplicates eliminated. This is
133   // now the time to process the dependent libraries to resolve any remaining
134   // symbols.
135   const Module::LibraryListType& DepLibs = Composite->getLibraries();
136   for (Module::LibraryListType::const_iterator I = DepLibs.begin(),
137          E = DepLibs.end(); I != E; ++I)
138     if (LinkInLibrary(*I, is_native))
139       return true;
140
141   return false;
142 }
143
144 /// LinkInFile - opens a bitcode file and links in all objects which
145 /// provide symbols that are currently undefined.
146 ///
147 /// Inputs:
148 ///  File - The pathname of the bitcode file.
149 ///
150 /// Outputs:
151 ///  ErrorMessage - A C++ string detailing what error occurred, if any.
152 ///
153 /// Return Value:
154 ///  TRUE  - An error occurred.
155 ///  FALSE - No errors.
156 ///
157 bool Linker::LinkInFile(const sys::Path &File, bool &is_native) {
158   is_native = false;
159   
160   // Check for a file of name "-", which means "read standard input"
161   if (File.str() == "-") {
162     std::auto_ptr<Module> M;
163     MemoryBuffer *Buffer = MemoryBuffer::getSTDIN();
164     if (!Buffer->getBufferSize()) {
165       delete Buffer;
166       Error = "standard input is empty";
167     } else {
168       M.reset(ParseBitcodeFile(Buffer, Context, &Error));
169       delete Buffer;
170       if (M.get())
171         if (!LinkInModule(M.get(), &Error))
172           return false;
173     }
174     return error("Cannot link stdin: " + Error);
175   }
176
177   // Make sure we can at least read the file
178   if (!File.canRead())
179     return error("Cannot find linker input '" + File.str() + "'");
180
181   // If its an archive, try to link it in
182   std::string Magic;
183   File.getMagicNumber(Magic, 64);
184   switch (sys::IdentifyFileType(Magic.c_str(), 64)) {
185     default: llvm_unreachable("Bad file type identification");
186     case sys::Unknown_FileType:
187       return warning("Ignoring file '" + File.str() + 
188                    "' because does not contain bitcode.");
189
190     case sys::Archive_FileType:
191       // A user may specify an ar archive without -l, perhaps because it
192       // is not installed as a library. Detect that and link the archive.
193       if (LinkInArchive(File, is_native))
194         return true;
195       break;
196
197     case sys::Bitcode_FileType: {
198       verbose("Linking bitcode file '" + File.str() + "'");
199       std::auto_ptr<Module> M(LoadObject(File));
200       if (M.get() == 0)
201         return error("Cannot load file '" + File.str() + "': " + Error);
202       if (LinkInModule(M.get(), &Error))
203         return error("Cannot link file '" + File.str() + "': " + Error);
204
205       verbose("Linked in file '" + File.str() + "'");
206       break;
207     }
208
209     case sys::ELF_Relocatable_FileType:
210     case sys::ELF_SharedObject_FileType:
211     case sys::Mach_O_Object_FileType:
212     case sys::Mach_O_FixedVirtualMemorySharedLib_FileType:
213     case sys::Mach_O_DynamicallyLinkedSharedLib_FileType:
214     case sys::Mach_O_DynamicallyLinkedSharedLibStub_FileType:
215     case sys::COFF_FileType:
216       is_native = true;
217       break;
218   }
219   return false;
220 }
221
222 /// LinkFiles - takes a module and a list of files and links them all together.
223 /// It locates the file either in the current directory, as its absolute
224 /// or relative pathname, or as a file somewhere in LLVM_LIB_SEARCH_PATH.
225 ///
226 /// Inputs:
227 ///  Files      - A vector of sys::Path indicating the LLVM bitcode filenames
228 ///               to be linked.  The names can refer to a mixture of pure LLVM
229 ///               bitcode files and archive (ar) formatted files.
230 ///
231 /// Return value:
232 ///  FALSE - No errors.
233 ///  TRUE  - Some error occurred.
234 ///
235 bool Linker::LinkInFiles(const std::vector<sys::Path> &Files) {
236   bool is_native;
237   for (unsigned i = 0; i < Files.size(); ++i)
238     if (LinkInFile(Files[i], is_native))
239       return true;
240   return false;
241 }