Delete memory allocated by CopyEnv
[oota-llvm.git] / tools / llvm-ld / llvm-ld.cpp
1 //===- llvm-ld.cpp - LLVM 'ld' compatible linker --------------------------===//
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 utility is intended to be compatible with GCC, and follows standard
11 // system 'ld' conventions.  As such, the default output file is ./a.out.
12 // Additionally, this program outputs a shell script that is used to invoke LLI
13 // to execute the program.  In this manner, the generated executable (a.out for
14 // example), is directly executable, whereas the bytecode file actually lives in
15 // the a.out.bc file generated by this program.  Also, Force is on by default.
16 //
17 // Note that if someone (or a script) deletes the executable program generated,
18 // the .bc file will be left around.  Considering that this is a temporary hack,
19 // I'm not too worried about this.
20 //
21 //===----------------------------------------------------------------------===//
22
23 #include "llvm/Linker.h"
24 #include "llvm/System/Program.h"
25 #include "llvm/Module.h"
26 #include "llvm/PassManager.h"
27 #include "llvm/Bytecode/Reader.h"
28 #include "llvm/Bytecode/Writer.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetMachineRegistry.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/FileUtilities.h"
34 #include "llvm/Support/SystemUtils.h"
35 #include "llvm/System/Signals.h"
36 #include <fstream>
37 #include <iostream>
38 #include <memory>
39
40 using namespace llvm;
41
42 // Input/Output Options
43 static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
44   cl::desc("<input bytecode files>"));
45
46 static cl::opt<std::string> OutputFilename("o", cl::init("a.out"),
47   cl::desc("Override output filename"),
48   cl::value_desc("filename"));
49
50 static cl::opt<bool> Verbose("v",
51   cl::desc("Print information about actions taken"));
52
53 static cl::list<std::string> LibPaths("L", cl::Prefix,
54   cl::desc("Specify a library search path"),
55   cl::value_desc("directory"));
56
57 static cl::list<std::string> Libraries("l", cl::Prefix,
58   cl::desc("Specify libraries to link to"),
59   cl::value_desc("library prefix"));
60
61 static cl::opt<bool> LinkAsLibrary("link-as-library",
62   cl::desc("Link the .bc files together as a library, not an executable"));
63
64 static cl::alias Relink("r", cl::aliasopt(LinkAsLibrary),
65   cl::desc("Alias for -link-as-library"));
66
67 static cl::opt<const TargetMachineRegistry::Entry*, false, TargetNameParser>
68   MachineArch("march", cl::desc("Architecture to generate assembly for:"));
69
70 static cl::opt<bool> Native("native",
71   cl::desc("Generate a native binary instead of a shell script"));
72
73 static cl::opt<bool>NativeCBE("native-cbe",
74   cl::desc("Generate a native binary with the C backend and GCC"));
75
76 static cl::opt<bool>DisableCompression("disable-compression",cl::init(false),
77   cl::desc("Disable writing of compressed bytecode files"));
78
79 static cl::list<std::string> PostLinkOpts("post-link-opts",
80   cl::value_desc("path to post-link optimization programs"),
81   cl::desc("Run one or more optimization programs after linking"));
82
83 // Compatibility options that are ignored but supported by LD
84 static cl::opt<std::string> CO3("soname", cl::Hidden,
85   cl::desc("Compatibility option: ignored"));
86
87 static cl::opt<std::string> CO4("version-script", cl::Hidden,
88   cl::desc("Compatibility option: ignored"));
89
90 static cl::opt<bool> CO5("eh-frame-hdr", cl::Hidden,
91   cl::desc("Compatibility option: ignored"));
92
93 static  cl::opt<std::string> CO6("h", cl::Hidden,
94   cl::desc("Compatibility option: ignored"));
95
96 /// This is just for convenience so it doesn't have to be passed around
97 /// everywhere.
98 static std::string progname;
99
100 /// PrintAndReturn - Prints a message to standard error and returns true.
101 ///
102 /// Inputs:
103 ///  progname - The name of the program (i.e. argv[0]).
104 ///  Message  - The message to print to standard error.
105 ///
106 static int PrintAndReturn(const std::string &Message) {
107   std::cerr << progname << ": " << Message << "\n";
108   return 1;
109 }
110
111 /// CopyEnv - This function takes an array of environment variables and makes a
112 /// copy of it.  This copy can then be manipulated any way the caller likes
113 /// without affecting the process's real environment.
114 ///
115 /// Inputs:
116 ///  envp - An array of C strings containing an environment.
117 ///
118 /// Return value:
119 ///  NULL - An error occurred.
120 ///
121 ///  Otherwise, a pointer to a new array of C strings is returned.  Every string
122 ///  in the array is a duplicate of the one in the original array (i.e. we do
123 ///  not copy the char *'s from one array to another).
124 ///
125 static char ** CopyEnv(char ** const envp) {
126   // Count the number of entries in the old list;
127   unsigned entries;   // The number of entries in the old environment list
128   for (entries = 0; envp[entries] != NULL; entries++)
129     /*empty*/;
130
131   // Add one more entry for the NULL pointer that ends the list.
132   ++entries;
133
134   // If there are no entries at all, just return NULL.
135   if (entries == 0)
136     return NULL;
137
138   // Allocate a new environment list.
139   char **newenv = new char* [entries];
140   if ((newenv = new char* [entries]) == NULL)
141     return NULL;
142
143   // Make a copy of the list.  Don't forget the NULL that ends the list.
144   entries = 0;
145   while (envp[entries] != NULL) {
146     newenv[entries] = new char[strlen (envp[entries]) + 1];
147     strcpy (newenv[entries], envp[entries]);
148     ++entries;
149   }
150   newenv[entries] = NULL;
151
152   return newenv;
153 }
154
155
156 /// RemoveEnv - Remove the specified environment variable from the environment
157 /// array.
158 ///
159 /// Inputs:
160 ///  name - The name of the variable to remove.  It cannot be NULL.
161 ///  envp - The array of environment variables.  It cannot be NULL.
162 ///
163 /// Notes:
164 ///  This is mainly done because functions to remove items from the environment
165 ///  are not available across all platforms.  In particular, Solaris does not
166 ///  seem to have an unsetenv() function or a setenv() function (or they are
167 ///  undocumented if they do exist).
168 ///
169 static void RemoveEnv(const char * name, char ** const envp) {
170   for (unsigned index=0; envp[index] != NULL; index++) {
171     // Find the first equals sign in the array and make it an EOS character.
172     char *p = strchr (envp[index], '=');
173     if (p == NULL)
174       continue;
175     else
176       *p = '\0';
177
178     // Compare the two strings.  If they are equal, zap this string.
179     // Otherwise, restore it.
180     if (!strcmp(name, envp[index]))
181       *envp[index] = '\0';
182     else
183       *p = '=';
184   }
185
186   return;
187 }
188
189 /// GenerateBytecode - generates a bytecode file from the module provided
190 void GenerateBytecode(Module* M, const std::string& FileName) {
191
192   // Create the output file.
193   std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
194                                std::ios::binary;
195   std::ofstream Out(FileName.c_str(), io_mode);
196   if (!Out.good()) {
197     PrintAndReturn("error opening '" + FileName + "' for writing!");
198     return;
199   }
200
201   // Ensure that the bytecode file gets removed from the disk if we get a
202   // terminating signal.
203   sys::RemoveFileOnSignal(sys::Path(FileName));
204
205   // Write it out
206   WriteBytecodeToFile(M, Out, !DisableCompression);
207
208   // Close the bytecode file.
209   Out.close();
210 }
211
212 /// GenerateAssembly - generates a native assembly language source file from the
213 /// specified bytecode file.
214 ///
215 /// Inputs:
216 ///  InputFilename  - The name of the output bytecode file.
217 ///  OutputFilename - The name of the file to generate.
218 ///  llc            - The pathname to use for LLC.
219 ///  envp           - The environment to use when running LLC.
220 ///
221 /// Return non-zero value on error.
222 ///
223 static int GenerateAssembly(const std::string &OutputFilename,
224                             const std::string &InputFilename,
225                             const sys::Path &llc) {
226   // Run LLC to convert the bytecode file into assembly code.
227   std::vector<const char*> args;
228   args.push_back(llc.c_str());
229   args.push_back("-f");
230   args.push_back("-o");
231   args.push_back(OutputFilename.c_str());
232   args.push_back(InputFilename.c_str());
233   args.push_back(0);
234
235   return sys::Program::ExecuteAndWait(llc,&args[0]);
236 }
237
238 /// GenerateAssembly - generates a native assembly language source file from the
239 /// specified bytecode file.
240 static int GenerateCFile(const std::string &OutputFile,
241                          const std::string &InputFile,
242                          const sys::Path &llc) {
243   // Run LLC to convert the bytecode file into C.
244   std::vector<const char*> args;
245   args.push_back(llc.c_str());
246   args.push_back("-march=c");
247   args.push_back("-f");
248   args.push_back("-o");
249   args.push_back(OutputFile.c_str());
250   args.push_back(InputFile.c_str());
251   args.push_back(0);
252   return sys::Program::ExecuteAndWait(llc, &args[0]);
253 }
254
255 /// GenerateNative - generates a native assembly language source file from the
256 /// specified assembly source file.
257 ///
258 /// Inputs:
259 ///  InputFilename  - The name of the output bytecode file.
260 ///  OutputFilename - The name of the file to generate.
261 ///  Libraries      - The list of libraries with which to link.
262 ///  LibPaths       - The list of directories in which to find libraries.
263 ///  gcc            - The pathname to use for GGC.
264 ///  envp           - A copy of the process's current environment.
265 ///
266 /// Outputs:
267 ///  None.
268 ///
269 /// Returns non-zero value on error.
270 ///
271 static int GenerateNative(const std::string &OutputFilename,
272                           const std::string &InputFilename,
273                           const std::vector<std::string> &Libraries,
274                           const sys::Path &gcc, char ** const envp) {
275   // Remove these environment variables from the environment of the
276   // programs that we will execute.  It appears that GCC sets these
277   // environment variables so that the programs it uses can configure
278   // themselves identically.
279   //
280   // However, when we invoke GCC below, we want it to use its normal
281   // configuration.  Hence, we must sanitize its environment.
282   char ** clean_env = CopyEnv(envp);
283   if (clean_env == NULL)
284     return 1;
285   RemoveEnv("LIBRARY_PATH", clean_env);
286   RemoveEnv("COLLECT_GCC_OPTIONS", clean_env);
287   RemoveEnv("GCC_EXEC_PREFIX", clean_env);
288   RemoveEnv("COMPILER_PATH", clean_env);
289   RemoveEnv("COLLECT_GCC", clean_env);
290
291
292   // Run GCC to assemble and link the program into native code.
293   //
294   // Note:
295   //  We can't just assemble and link the file with the system assembler
296   //  and linker because we don't know where to put the _start symbol.
297   //  GCC mysteriously knows how to do it.
298   std::vector<const char*> args;
299   args.push_back(gcc.c_str());
300   args.push_back("-fno-strict-aliasing");
301   args.push_back("-O3");
302   args.push_back("-o");
303   args.push_back(OutputFilename.c_str());
304   args.push_back(InputFilename.c_str());
305
306   // Add in the libraries to link.
307   for (unsigned index = 0; index < Libraries.size(); index++)
308     if (Libraries[index] != "crtend") {
309       args.push_back("-l");
310       args.push_back(Libraries[index].c_str());
311     }
312   args.push_back(0);
313
314   // Run the compiler to assembly and link together the program.
315   int R = sys::Program::ExecuteAndWait(gcc, &args[0], (const char**)clean_env);
316   delete [] clean_env;
317   return R;
318 }
319
320 /// EmitShellScript - Output the wrapper file that invokes the JIT on the LLVM
321 /// bytecode file for the program.
322 static void EmitShellScript(char **argv) {
323 #if defined(_WIN32) || defined(__CYGWIN__)
324   // Windows doesn't support #!/bin/sh style shell scripts in .exe files.  To
325   // support windows systems, we copy the llvm-stub.exe executable from the
326   // build tree to the destination file.
327   sys::Path llvmstub = FindExecutable("llvm-stub.exe", argv[0]);
328   if (llvmstub.isEmpty()) {
329     std::cerr << "Could not find llvm-stub.exe executable!\n";
330     exit(1);
331   }
332   sys::CopyFile(sys::Path(OutputFilename), llvmstub);
333   return;
334 #endif
335
336   // Output the script to start the program...
337   std::ofstream Out2(OutputFilename.c_str());
338   if (!Out2.good())
339     exit(PrintAndReturn("error opening '" + OutputFilename + "' for writing!"));
340
341   Out2 << "#!/bin/sh\n";
342   // Allow user to setenv LLVMINTERP if lli is not in their PATH.
343   Out2 << "lli=${LLVMINTERP-lli}\n";
344   Out2 << "exec $lli \\\n";
345   // gcc accepts -l<lib> and implicitly searches /lib and /usr/lib.
346   LibPaths.push_back("/lib");
347   LibPaths.push_back("/usr/lib");
348   LibPaths.push_back("/usr/X11R6/lib");
349   // We don't need to link in libc! In fact, /usr/lib/libc.so may not be a
350   // shared object at all! See RH 8: plain text.
351   std::vector<std::string>::iterator libc =
352     std::find(Libraries.begin(), Libraries.end(), "c");
353   if (libc != Libraries.end()) Libraries.erase(libc);
354   // List all the shared object (native) libraries this executable will need
355   // on the command line, so that we don't have to do this manually!
356   for (std::vector<std::string>::iterator i = Libraries.begin(),
357          e = Libraries.end(); i != e; ++i) {
358     sys::Path FullLibraryPath = sys::Path::FindLibrary(*i);
359     if (!FullLibraryPath.isEmpty() && FullLibraryPath.isDynamicLibrary())
360       Out2 << "    -load=" << FullLibraryPath.toString() << " \\\n";
361   }
362   Out2 << "    $0.bc ${1+\"$@\"}\n";
363   Out2.close();
364 }
365
366 // BuildLinkItems -- This function generates a LinkItemList for the LinkItems
367 // linker function by combining the Files and Libraries in the order they were
368 // declared on the command line.
369 static void BuildLinkItems(
370   Linker::ItemList& Items,
371   const cl::list<std::string>& Files,
372   const cl::list<std::string>& Libraries) {
373
374   // Build the list of linkage items for LinkItems.
375
376   cl::list<std::string>::const_iterator fileIt = Files.begin();
377   cl::list<std::string>::const_iterator libIt  = Libraries.begin();
378
379   int libPos = -1, filePos = -1;
380   while ( libIt != Libraries.end() || fileIt != Files.end() ) {
381     if (libIt != Libraries.end())
382       libPos = Libraries.getPosition(libIt - Libraries.begin());
383     else
384       libPos = -1;
385     if (fileIt != Files.end())
386       filePos = Files.getPosition(fileIt - Files.begin());
387     else
388       filePos = -1;
389
390     if (filePos != -1 && (libPos == -1 || filePos < libPos)) {
391       // Add a source file
392       Items.push_back(std::make_pair(*fileIt++, false));
393     } else if (libPos != -1 && (filePos == -1 || libPos < filePos)) {
394       // Add a library
395       Items.push_back(std::make_pair(*libIt++, true));
396     }
397   }
398 }
399
400 // Rightly this should go in a header file but it just seems such a waste.
401 namespace llvm {
402 extern void Optimize(Module*);
403 }
404
405 int main(int argc, char **argv, char **envp) {
406   try {
407     // Initial global variable above for convenience printing of program name.
408     progname = sys::Path(argv[0]).getBasename();
409     Linker TheLinker(progname, OutputFilename, Verbose);
410
411     // Parse the command line options
412     cl::ParseCommandLineOptions(argc, argv, " llvm linker\n");
413     sys::PrintStackTraceOnErrorSignal();
414
415     // Set up the library paths for the Linker
416     TheLinker.addPaths(LibPaths);
417     TheLinker.addSystemPaths();
418
419     // Remove any consecutive duplicates of the same library...
420     Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
421                     Libraries.end());
422
423     if (LinkAsLibrary) {
424       std::vector<sys::Path> Files;
425       for (unsigned i = 0; i < InputFilenames.size(); ++i )
426         Files.push_back(sys::Path(InputFilenames[i]));
427       if (TheLinker.LinkInFiles(Files))
428         return 1; // Error already printed
429
430       // The libraries aren't linked in but are noted as "dependent" in the
431       // module.
432       for (cl::list<std::string>::const_iterator I = Libraries.begin(),
433            E = Libraries.end(); I != E ; ++I) {
434         TheLinker.getModule()->addLibrary(*I);
435       }
436     } else {
437       // Build a list of the items from our command line
438       Linker::ItemList Items;
439       Linker::ItemList NativeItems;
440       BuildLinkItems(Items, InputFilenames, Libraries);
441
442       // Link all the items together
443       if (TheLinker.LinkInItems(Items,NativeItems) )
444         return 1;
445     }
446
447     std::auto_ptr<Module> Composite(TheLinker.releaseModule());
448
449     // Optimize the module
450     Optimize(Composite.get());
451
452     // Generate the bytecode for the optimized module.
453     std::string RealBytecodeOutput = OutputFilename;
454     if (!LinkAsLibrary) RealBytecodeOutput += ".bc";
455     GenerateBytecode(Composite.get(), RealBytecodeOutput);
456
457     // If we are not linking a library, generate either a native executable
458     // or a JIT shell script, depending upon what the user wants.
459     if (!LinkAsLibrary) {
460       // If the user wants to run a post-link optimization, run it now.
461       if (!PostLinkOpts.empty()) {
462         std::vector<std::string> opts = PostLinkOpts;
463         for (std::vector<std::string>::iterator I = opts.begin(),
464              E = opts.end(); I != E; ++I) {
465           sys::Path prog(*I);
466           if (!prog.canExecute()) {
467             prog = sys::Program::FindProgramByName(*I);
468             if (prog.isEmpty())
469               return PrintAndReturn(std::string("Optimization program '") + *I +
470                 "' is not found or not executable.");
471           }
472           // Get the program arguments
473           sys::Path tmp_output("opt_result");
474           if (!tmp_output.createTemporaryFileOnDisk()) {
475             return PrintAndReturn(
476               "Can't create temporary file for post-link optimization");
477           }
478           const char* args[4];
479           args[0] = I->c_str();
480           args[1] = RealBytecodeOutput.c_str();
481           args[2] = tmp_output.c_str();
482           args[3] = 0;
483           if (0 == sys::Program::ExecuteAndWait(prog, args)) {
484             if (tmp_output.isBytecodeFile()) {
485               sys::Path target(RealBytecodeOutput);
486               target.eraseFromDisk();
487               tmp_output.renamePathOnDisk(target);
488             } else
489               return PrintAndReturn(
490                 "Post-link optimization output is not bytecode");
491           }
492         }
493       }
494
495       // If the user wants to generate a native executable, compile it from the
496       // bytecode file.
497       //
498       // Otherwise, create a script that will run the bytecode through the JIT.
499       if (Native) {
500         // Name of the Assembly Language output file
501         sys::Path AssemblyFile ( OutputFilename);
502         AssemblyFile.appendSuffix("s");
503
504         // Mark the output files for removal if we get an interrupt.
505         sys::RemoveFileOnSignal(AssemblyFile);
506         sys::RemoveFileOnSignal(sys::Path(OutputFilename));
507
508         // Determine the locations of the llc and gcc programs.
509         sys::Path llc = FindExecutable("llc", argv[0]);
510         if (llc.isEmpty())
511           return PrintAndReturn("Failed to find llc");
512
513         sys::Path gcc = FindExecutable("gcc", argv[0]);
514         if (gcc.isEmpty())
515           return PrintAndReturn("Failed to find gcc");
516
517         // Generate an assembly language file for the bytecode.
518         if (Verbose) std::cout << "Generating Assembly Code\n";
519         GenerateAssembly(AssemblyFile.toString(), RealBytecodeOutput, llc);
520         if (Verbose) std::cout << "Generating Native Code\n";
521         GenerateNative(OutputFilename, AssemblyFile.toString(), Libraries,
522                        gcc, envp);
523
524         // Remove the assembly language file.
525         AssemblyFile.eraseFromDisk();
526       } else if (NativeCBE) {
527         sys::Path CFile (OutputFilename);
528         CFile.appendSuffix("cbe.c");
529
530         // Mark the output files for removal if we get an interrupt.
531         sys::RemoveFileOnSignal(CFile);
532         sys::RemoveFileOnSignal(sys::Path(OutputFilename));
533
534         // Determine the locations of the llc and gcc programs.
535         sys::Path llc = FindExecutable("llc", argv[0]);
536         if (llc.isEmpty())
537           return PrintAndReturn("Failed to find llc");
538
539         sys::Path gcc = FindExecutable("gcc", argv[0]);
540         if (gcc.isEmpty())
541           return PrintAndReturn("Failed to find gcc");
542
543         // Generate an assembly language file for the bytecode.
544         if (Verbose) std::cout << "Generating Assembly Code\n";
545         GenerateCFile(CFile.toString(), RealBytecodeOutput, llc);
546         if (Verbose) std::cout << "Generating Native Code\n";
547         GenerateNative(OutputFilename, CFile.toString(), Libraries, gcc, envp);
548
549         // Remove the assembly language file.
550         CFile.eraseFromDisk();
551
552       } else {
553         EmitShellScript(argv);
554       }
555
556       // Make the script executable...
557       sys::Path(OutputFilename).makeExecutableOnDisk();
558
559       // Make the bytecode file readable and directly executable in LLEE as well
560       sys::Path(RealBytecodeOutput).makeExecutableOnDisk();
561       sys::Path(RealBytecodeOutput).makeReadableOnDisk();
562     }
563
564     return 0;
565   } catch (const std::string& msg) {
566     std::cerr << argv[0] << ": " << msg << "\n";
567   } catch (...) {
568     std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
569   }
570   return 1;
571 }