Fix off-by-one error in processing of libraries named on command line.
[oota-llvm.git] / tools / gccld / Linker.cpp
1 //===- Linker.cpp - Link together LLVM objects and libraries --------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains routines to handle linking together LLVM bytecode files,
11 // and to handle annoying things like static libraries.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "gccld.h"
16 #include "llvm/Module.h"
17 #include "llvm/PassManager.h"
18 #include "llvm/Bytecode/Reader.h"
19 #include "llvm/Bytecode/WriteBytecodePass.h"
20 #include "llvm/Target/TargetData.h"
21 #include "llvm/Transforms/IPO.h"
22 #include "llvm/Transforms/Scalar.h"
23 #include "llvm/Transforms/Utils/Linker.h"
24 #include "Support/CommandLine.h"
25 #include "Support/FileUtilities.h"
26 #include "Support/Signals.h"
27 #include "Support/SystemUtils.h"
28 #include <algorithm>
29 #include <fstream>
30 #include <memory>
31 #include <set>
32
33 /// FileExists - determines if the specified filename exists and is readable.
34 ///
35 /// Inputs:
36 ///  FN - The name of the file.
37 ///
38 /// Outputs:
39 ///  None.
40 ///
41 /// Return Value:
42 ///  TRUE - The file exists and is readable.
43 ///  FALSE - The file does not exist or is unreadable.
44 ///
45 static inline bool FileExists(const std::string &FN) {
46   return access(FN.c_str(), R_OK | F_OK) != -1;
47 }
48
49 /// IsArchive - determines if the specified file is an ar archive
50 /// by checking the magic string at the beginning of the file.
51 ///
52 /// Inputs:
53 ///  filename - A C++ string containing the name of the file.
54 ///
55 /// Outputs:
56 ///  None.
57 ///
58 /// Return value:
59 ///  TRUE  - The file is an archive.
60 ///  FALSE - The file is not an archive.
61 ///
62 static inline bool IsArchive(const std::string &filename) {
63   std::string ArchiveMagic("!<arch>\012");
64   char buf[1 + ArchiveMagic.size()];
65   std::ifstream f(filename.c_str());
66   f.read(buf, ArchiveMagic.size());
67   buf[ArchiveMagic.size()] = '\0';
68   return ArchiveMagic == buf;
69 }
70
71 /// FindLib - locates a particular library.  It will prepend and append
72 /// various directories, prefixes, and suffixes until it can find the library.
73 ///
74 /// Inputs:
75 ///  Filename  - Name of the file to find.
76 ///  Paths     - List of directories to search.
77 ///
78 /// Outputs:
79 ///  None.
80 ///
81 /// Return value:
82 ///  The name of the file is returned.
83 ///  If the file is not found, an empty string is returned.
84 ///
85 static std::string
86 FindLib(const std::string &Filename, const std::vector<std::string> &Paths) {
87   // Determine if the pathname can be found as it stands.
88   if (FileExists(Filename))
89     return Filename;
90
91   // If that doesn't work, convert the name into a library name.
92   std::string LibName = "lib" + Filename;
93
94   // Iterate over the directories in Paths to see if we can find the library
95   // there.
96   for (unsigned Index = 0; Index != Paths.size(); ++Index) {
97     std::string Directory = Paths[Index] + "/";
98
99     if (FileExists(Directory + LibName + ".bc"))
100       return Directory + LibName + ".bc";
101
102     if (FileExists(Directory + LibName + ".so"))
103       return Directory + LibName + ".so";
104
105     if (FileExists(Directory + LibName + ".a"))
106       return Directory + LibName + ".a";
107   }
108
109   // One last hope: Check LLVM_LIB_SEARCH_PATH.
110   char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH");
111   if (SearchPath == NULL)
112     return std::string();
113
114   LibName = std::string(SearchPath) + "/" + LibName;
115   if (FileExists(LibName))
116     return LibName;
117
118   return std::string();
119 }
120
121 /// GetAllDefinedSymbols - finds all of the defined symbols in the specified 
122 /// module.
123 ///
124 /// Inputs:
125 ///  M - The module in which to find defined symbols.
126 ///
127 /// Outputs:
128 ///  DefinedSymbols - A set of C++ strings that will contain the name of all
129 ///                   defined symbols.
130 ///
131 /// Return value:
132 ///  None.
133 ///
134 void GetAllDefinedSymbols(Module *M, std::set<std::string> &DefinedSymbols) {
135   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
136     if (I->hasName() && !I->isExternal() && !I->hasInternalLinkage())
137       DefinedSymbols.insert(I->getName());
138   for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
139     if (I->hasName() && !I->isExternal() && !I->hasInternalLinkage())
140       DefinedSymbols.insert(I->getName());
141 }
142
143 /// GetAllUndefinedSymbols - calculates the set of undefined symbols that still
144 /// exist in an LLVM module. This is a bit tricky because there may be two
145 /// symbols with the same name but different LLVM types that will be resolved to
146 /// each other but aren't currently (thus we need to treat it as resolved).
147 ///
148 /// Inputs:
149 ///  M - The module in which to find undefined symbols.
150 ///
151 /// Outputs:
152 ///  UndefinedSymbols - A set of C++ strings containing the name of all
153 ///                     undefined symbols.
154 ///
155 /// Return value:
156 ///  None.
157 ///
158 void
159 GetAllUndefinedSymbols(Module *M, std::set<std::string> &UndefinedSymbols) {
160   std::set<std::string> DefinedSymbols;
161   UndefinedSymbols.clear();   // Start out empty
162   
163   for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
164     if (I->hasName()) {
165       if (I->isExternal())
166         UndefinedSymbols.insert(I->getName());
167       else if (!I->hasInternalLinkage())
168         DefinedSymbols.insert(I->getName());
169     }
170   for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
171     if (I->hasName()) {
172       if (I->isExternal())
173         UndefinedSymbols.insert(I->getName());
174       else if (!I->hasInternalLinkage())
175         DefinedSymbols.insert(I->getName());
176     }
177   
178   // Prune out any defined symbols from the undefined symbols set...
179   for (std::set<std::string>::iterator I = UndefinedSymbols.begin();
180        I != UndefinedSymbols.end(); )
181     if (DefinedSymbols.count(*I))
182       UndefinedSymbols.erase(I++);  // This symbol really is defined!
183     else
184       ++I; // Keep this symbol in the undefined symbols list
185 }
186
187
188 /// LoadObject - reads the specified bytecode object file.
189 ///
190 /// Inputs:
191 ///  FN - The name of the file to load.
192 ///
193 /// Outputs:
194 ///  OutErrorMessage - The error message to give back to the caller.
195 ///
196 /// Return Value:
197 ///  A pointer to a module represening the bytecode file is returned.
198 ///  If an error occurs, the pointer is 0.
199 ///
200 std::auto_ptr<Module>
201 LoadObject(const std::string & FN, std::string &OutErrorMessage) {
202   std::string ErrorMessage;
203   Module *Result = ParseBytecodeFile(FN, &ErrorMessage);
204   if (Result) return std::auto_ptr<Module>(Result);
205   OutErrorMessage = "Bytecode file '" + FN + "' corrupt!";
206   if (ErrorMessage.size()) OutErrorMessage += ": " + ErrorMessage;
207   return std::auto_ptr<Module>();
208 }
209
210 /// LinkInArchive - opens an archive library and link in all objects which
211 /// provide symbols that are currently undefined.
212 ///
213 /// Inputs:
214 ///  M        - The module in which to link the archives.
215 ///  Filename - The pathname of the archive.
216 ///  Verbose  - Flags whether verbose messages should be printed.
217 ///
218 /// Outputs:
219 ///  ErrorMessage - A C++ string detailing what error occurred, if any.
220 ///
221 /// Return Value:
222 ///  TRUE  - An error occurred.
223 ///  FALSE - No errors.
224 ///
225 static bool LinkInArchive(Module *M,
226                           const std::string &Filename,
227                           std::string &ErrorMessage,
228                           bool Verbose)
229 {
230   // Find all of the symbols currently undefined in the bytecode program.
231   // If all the symbols are defined, the program is complete, and there is
232   // no reason to link in any archive files.
233   std::set<std::string> UndefinedSymbols;
234   GetAllUndefinedSymbols(M, UndefinedSymbols);
235   if (UndefinedSymbols.empty()) {
236     if (Verbose) std::cerr << "  No symbols undefined, don't link library!\n";
237     return false;  // No need to link anything in!
238   }
239
240   // Load in the archive objects.
241   if (Verbose) std::cerr << "  Loading '" << Filename << "'\n";
242   std::vector<Module*> Objects;
243   if (ReadArchiveFile(Filename, Objects, &ErrorMessage))
244     return true;
245
246   // Figure out which symbols are defined by all of the modules in the archive.
247   std::vector<std::set<std::string> > DefinedSymbols;
248   DefinedSymbols.resize(Objects.size());
249   for (unsigned i = 0; i != Objects.size(); ++i) {
250     GetAllDefinedSymbols(Objects[i], DefinedSymbols[i]);
251   }
252
253   // While we are linking in object files, loop.
254   bool Linked = true;
255   while (Linked) {     
256     Linked = false;
257
258     for (unsigned i = 0; i != Objects.size(); ++i) {
259       // Consider whether we need to link in this module...  we only need to
260       // link it in if it defines some symbol which is so far undefined.
261       //
262       const std::set<std::string> &DefSymbols = DefinedSymbols[i];
263
264       bool ObjectRequired = false;
265       for (std::set<std::string>::iterator I = UndefinedSymbols.begin(),
266              E = UndefinedSymbols.end(); I != E; ++I)
267         if (DefSymbols.count(*I)) {
268           if (Verbose)
269             std::cerr << "  Found object providing symbol '" << *I << "'...\n";
270           ObjectRequired = true;
271           break;
272         }
273       
274       // We DO need to link this object into the program...
275       if (ObjectRequired) {
276         if (LinkModules(M, Objects[i], &ErrorMessage))
277           return true;   // Couldn't link in the right object file...        
278         
279         // Since we have linked in this object, delete it from the list of
280         // objects to consider in this archive file.
281         std::swap(Objects[i], Objects.back());
282         std::swap(DefinedSymbols[i], DefinedSymbols.back());
283         Objects.pop_back();
284         DefinedSymbols.pop_back();
285         --i;   // Do not skip an entry
286         
287         // The undefined symbols set should have shrunk.
288         GetAllUndefinedSymbols(M, UndefinedSymbols);
289         Linked = true;  // We have linked something in!
290       }
291     }
292   }
293   
294   return false;
295 }
296
297 /// LinkInFile - opens an archive library and link in all objects which
298 /// provide symbols that are currently undefined.
299 ///
300 /// Inputs:
301 ///  HeadModule - The module in which to link the archives.
302 ///  Filename   - The pathname of the archive.
303 ///  Verbose    - Flags whether verbose messages should be printed.
304 ///
305 /// Outputs:
306 ///  ErrorMessage - A C++ string detailing what error occurred, if any.
307 ///
308 /// Return Value:
309 ///  TRUE  - An error occurred.
310 ///  FALSE - No errors.
311 ///
312 static bool LinkInFile(Module *HeadModule,
313                        const std::string &Filename,
314                        std::string &ErrorMessage,
315                        bool Verbose)
316 {
317   std::auto_ptr<Module> M(LoadObject(Filename, ErrorMessage));
318   if (M.get() == 0) return true;
319   if (Verbose) std::cerr << "Linking in '" << Filename << "'\n";
320   return LinkModules(HeadModule, M.get(), &ErrorMessage);
321 }
322
323 /// LinkFiles - takes a module and a list of files and links them all together.
324 /// It locates the file either in the current directory, as its absolute
325 /// or relative pathname, or as a file somewhere in LLVM_LIB_SEARCH_PATH.
326 ///
327 /// Inputs:
328 ///  progname   - The name of the program (infamous argv[0]).
329 ///  HeadModule - The module under which all files will be linked.
330 ///  Files      - A vector of C++ strings indicating the LLVM bytecode filenames
331 ///               to be linked.  The names can refer to a mixture of pure LLVM
332 ///               bytecode files and archive (ar) formatted files.
333 ///  Verbose    - Flags whether verbose output should be printed while linking.
334 ///
335 /// Outputs:
336 ///  HeadModule - The module will have the specified LLVM bytecode files linked
337 ///               in.
338 ///
339 /// Return value:
340 ///  FALSE - No errors.
341 ///  TRUE  - Some error occurred.
342 ///
343 bool LinkFiles(const char *progname,
344                Module *HeadModule,
345                const std::vector<std::string> &Files,
346                bool Verbose)
347 {
348   // String in which to receive error messages.
349   std::string ErrorMessage;
350
351   // Full pathname of the file
352   std::string Pathname;
353
354   // Get the library search path from the environment
355   char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH");
356
357   for (unsigned i = 1; i < Files.size(); ++i) {
358     // Determine where this file lives.
359     if (FileExists(Files[i])) {
360       Pathname = Files[i];
361     } else {
362       if (SearchPath == NULL) {
363         std::cerr << progname << ": Cannot find linker input file '"
364                   << Files[i] << "'\n";
365         return true;
366       }
367
368       Pathname = std::string(SearchPath)+"/"+Files[i];
369       if (!FileExists(Pathname)) {
370         std::cerr << progname << ": Cannot find linker input file '"
371                   << Files[i] << "'\n";
372         return true;
373       }
374     }
375
376     // A user may specify an ar archive without -l, perhaps because it
377     // is not installed as a library. Detect that and link the library.
378     if (IsArchive(Pathname)) {
379       if (Verbose)
380         std::cerr << "Linking archive '" << Files[i] << "'\n";
381
382       if (LinkInArchive(HeadModule, Pathname, ErrorMessage, Verbose)) {
383         PrintAndReturn(progname, ErrorMessage,
384                        ": Error linking in '" + Files[i] + "'");
385         return true;
386       }
387     } else {
388       if (Verbose)
389         std::cerr << "Linking file '" << Files[i] << "'\n";
390
391       if (LinkInFile(HeadModule, Pathname, ErrorMessage, Verbose)) {
392         PrintAndReturn(progname, ErrorMessage,
393                        ": Error linking in '" + Files[i] + "'");
394         return true;
395       }
396     }
397   }
398
399   return false;
400 }
401
402 /// LinkLibraries - takes the specified library files and links them into the
403 /// main bytecode object file.
404 ///
405 /// Inputs:
406 ///  progname   - The name of the program (infamous argv[0]).
407 ///  HeadModule - The module into which all necessary libraries will be linked.
408 ///  Libraries  - The list of libraries to link into the module.
409 ///  LibPaths   - The list of library paths in which to find libraries.
410 ///  Verbose    - Flags whether verbose messages should be printed.
411 ///  Native     - Flags whether native code is being generated.
412 ///
413 /// Outputs:
414 ///  HeadModule - The module will have all necessary libraries linked in.
415 ///
416 /// Return value:
417 ///  FALSE - No error.
418 ///  TRUE  - Error.
419 ///
420 bool LinkLibraries(const char *progname,
421                    Module *HeadModule,
422                    const std::vector<std::string> &Libraries,
423                    const std::vector<std::string> &LibPaths,
424                    bool Verbose,
425                    bool Native)
426 {
427   // String in which to receive error messages.
428   std::string ErrorMessage;
429
430   for (unsigned i = 0; i < Libraries.size(); ++i) {
431     // Determine where this library lives.
432     std::string Pathname = FindLib(Libraries[i], LibPaths);
433     if (Pathname.empty()) {
434       // If the pathname does not exist, then continue to the next one if
435       // we're doing a native link and give an error if we're doing a bytecode
436       // link.
437       if (!Native) {
438         PrintAndReturn(progname, "Cannot find " + Libraries[i] + "\n");
439         return true;
440       }
441     }
442
443     // A user may specify an ar archive without -l, perhaps because it
444     // is not installed as a library. Detect that and link the library.
445     if (IsArchive(Pathname)) {
446       if (Verbose)
447         std::cerr << "Linking archive '" << Libraries[i] << "'\n";
448
449       if (LinkInArchive(HeadModule, Pathname, ErrorMessage, Verbose)) {
450         PrintAndReturn(progname, ErrorMessage,
451                        ": Error linking in '" + Libraries[i] + "'");
452         return true;
453       }
454     } else {
455       if (Verbose)
456         std::cerr << "Linking file '" << Libraries[i] << "'\n";
457
458       if (LinkInFile(HeadModule, Pathname, ErrorMessage, Verbose)) {
459         PrintAndReturn(progname, ErrorMessage,
460                        ": error linking in '" + Libraries[i] + "'");
461         return true;
462       }
463     }
464   }
465
466   return false;
467 }