1 //===- gccld.cpp - LLVM 'ld' compatible linker ----------------------------===//
3 // This utility is intended to be compatible with GCC, and follows standard
4 // system 'ld' conventions. As such, the default output file is ./a.out.
5 // Additionally, this program outputs a shell script that is used to invoke LLI
6 // to execute the program. In this manner, the generated executable (a.out for
7 // example), is directly executable, whereas the bytecode file actually lives in
8 // the a.out.bc file generated by this program. Also, Force is on by default.
10 // Note that if someone (or a script) deletes the executable program generated,
11 // the .bc file will be left around. Considering that this is a temporary hack,
12 // I'm not too worried about this.
14 //===----------------------------------------------------------------------===//
17 #include "llvm/Transforms/Utils/Linker.h"
18 #include "llvm/Module.h"
19 #include "llvm/PassManager.h"
20 #include "llvm/Bytecode/Reader.h"
21 #include "llvm/Bytecode/WriteBytecodePass.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Transforms/IPO.h"
24 #include "llvm/Transforms/Scalar.h"
25 #include "Support/FileUtilities.h"
26 #include "Support/SystemUtils.h"
27 #include "Support/CommandLine.h"
28 #include "Support/Signals.h"
35 InputFilenames(cl::Positional, cl::desc("<input bytecode files>"),
39 OutputFilename("o", cl::desc("Override output filename"), cl::init("a.out"),
40 cl::value_desc("filename"));
43 Verbose("v", cl::desc("Print information about actions taken"));
46 LibPaths("L", cl::desc("Specify a library search path"), cl::Prefix,
47 cl::value_desc("directory"));
50 Libraries("l", cl::desc("Specify libraries to link to"), cl::Prefix,
51 cl::value_desc("library prefix"));
54 Strip("s", cl::desc("Strip symbol info from executable"));
57 NoInternalize("disable-internalize",
58 cl::desc("Do not mark all symbols as internal"));
60 ExportDynamic("export-dynamic", cl::desc("Alias for -disable-internalize"),
61 cl::aliasopt(NoInternalize));
64 LinkAsLibrary("link-as-library", cl::desc("Link the .bc files together as a"
65 " library, not an executable"));
69 cl::desc("Generate a native binary instead of a shell script"));
71 // Compatibility options that are ignored but supported by LD
73 CO3("soname", cl::Hidden, cl::desc("Compatibility option: ignored"));
75 CO4("version-script", cl::Hidden, cl::desc("Compatibility option: ignored"));
77 CO5("eh-frame-hdr", cl::Hidden, cl::desc("Compatibility option: ignored"));
79 CO6("r", cl::Hidden, cl::desc("Compatibility option: ignored"));
83 // Function: PrintAndReturn ()
86 // Prints a message (usually error message) to standard error (stderr) and
87 // returns a value usable for an exit status.
90 // progname - The name of the program (i.e. argv[0]).
91 // Message - The message to print to standard error.
92 // Extra - Extra information to print between the program name and thei
93 // message. It is optional.
99 // Returns a value that can be used as the exit status (i.e. for exit()).
102 PrintAndReturn (const char *progname,
103 const std::string &Message,
104 const std::string &Extra)
106 std::cerr << progname << Extra << ": " << Message << "\n";
113 // Function: CopyEnv()
116 // This function takes an array of environment variables and makes a
117 // copy of it. This copy can then be manipulated any way the caller likes
118 // without affecting the process's real environment.
121 // envp - An array of C strings containing an environment.
127 // NULL - An error occurred.
129 // Otherwise, a pointer to a new array of C strings is returned. Every string
130 // in the array is a duplicate of the one in the original array (i.e. we do
131 // not copy the char *'s from one array to another).
134 CopyEnv (char ** const envp)
137 // Count the number of entries in the old list;
139 unsigned entries; // The number of entries in the old environment list
140 for (entries = 0; envp[entries] != NULL; entries++)
146 // Add one more entry for the NULL pointer that ends the list.
151 // If there are no entries at all, just return NULL.
159 // Allocate a new environment list.
162 if ((newenv = new (char *) [entries]) == NULL)
168 // Make a copy of the list. Don't forget the NULL that ends the list.
171 while (envp[entries] != NULL)
173 newenv[entries] = new char[strlen (envp[entries]) + 1];
174 strcpy (newenv[entries], envp[entries]);
177 newenv[entries] = NULL;
184 // Function: RemoveEnv()
187 // Remove the specified environment variable from the environment array.
190 // name - The name of the variable to remove. It cannot be NULL.
191 // envp - The array of environment variables. It cannot be NULL.
194 // envp - The pointer to the specified variable name is removed.
200 // This is mainly done because functions to remove items from the environment
201 // are not available across all platforms. In particular, Solaris does not
202 // seem to have an unsetenv() function or a setenv() function (or they are
203 // undocumented if they do exist).
206 RemoveEnv (const char * name, char ** const envp)
208 for (unsigned index=0; envp[index] != NULL; index++) {
209 // Find the first equals sign in the array and make it an EOS character.
210 char *p = strchr (envp[index], '=');
220 // Compare the two strings. If they are equal, zap this string.
221 // Otherwise, restore it.
223 if (!strcmp (name, envp[index]))
238 main(int argc, char **argv, char ** envp)
240 cl::ParseCommandLineOptions(argc, argv, " llvm linker for GCC\n");
242 std::string ErrorMessage;
243 std::auto_ptr<Module> Composite(LoadObject(InputFilenames[0], ErrorMessage));
244 if (Composite.get() == 0)
245 return PrintAndReturn(argv[0], ErrorMessage);
247 // We always look first in the current directory when searching for libraries.
248 LibPaths.insert(LibPaths.begin(), ".");
250 // If the user specied an extra search path in their environment, respect it.
251 if (char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH"))
252 LibPaths.push_back(SearchPath);
254 // Remove any consecutive duplicates of the same library...
255 Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
258 // Link in all of the files
259 LinkFiles(argv[0], Composite.get(), InputFilenames, Verbose);
260 LinkLibraries(argv[0], Composite.get(), Libraries, LibPaths, Verbose, Native);
262 // Link in all of the libraries next...
265 // Create the output file.
267 std::string RealBytecodeOutput = OutputFilename;
268 if (!LinkAsLibrary) RealBytecodeOutput += ".bc";
269 std::ofstream Out(RealBytecodeOutput.c_str());
271 return PrintAndReturn(argv[0], "error opening '" + RealBytecodeOutput +
275 // Ensure that the bytecode file gets removed from the disk if we get a
278 RemoveFileOnSignal(RealBytecodeOutput);
281 // Generate the bytecode file.
283 if (GenerateBytecode (Composite.get(), Strip, !NoInternalize, &Out)) {
285 return PrintAndReturn(argv[0], "error generating bytcode");
289 // Close the bytecode file.
294 // If we are not linking a library, generate either a native executable
295 // or a JIT shell script, depending upon what the user wants.
297 if (!LinkAsLibrary) {
299 // If the user wants to generate a native executable, compile it from the
302 // Otherwise, create a script that will run the bytecode through the JIT.
305 // Name of the Assembly Language output file
306 std::string AssemblyFile = OutputFilename + ".s";
309 // Mark the output files for removal if we get an interrupt.
311 RemoveFileOnSignal (AssemblyFile);
312 RemoveFileOnSignal (OutputFilename);
315 // Determine the locations of the llc and gcc programs.
317 std::string llc=FindExecutable ("llc", argv[0]);
318 std::string gcc=FindExecutable ("gcc", argv[0]);
320 return PrintAndReturn (argv[0], "Failed to find llc");
323 return PrintAndReturn (argv[0], "Failed to find gcc");
326 // Generate an assembly language file for the bytecode.
328 if (Verbose) std::cout << "Generating Assembly Code\n";
329 GenerateAssembly(AssemblyFile, RealBytecodeOutput, llc, envp);
330 if (Verbose) std::cout << "Generating Native Code\n";
331 GenerateNative(OutputFilename, AssemblyFile, Libraries, LibPaths,
335 // Remove the assembly language file.
337 removeFile (AssemblyFile);
339 // Output the script to start the program...
340 std::ofstream Out2(OutputFilename.c_str());
342 return PrintAndReturn(argv[0], "error opening '" + OutputFilename +
344 Out2 << "#!/bin/sh\nlli -q $0.bc $*\n";
348 // Make the script executable...
349 MakeFileExecutable (OutputFilename);
351 // Make the bytecode file readable and directly executable in LLEE as well
352 MakeFileExecutable (RealBytecodeOutput);
353 MakeFileReadable (RealBytecodeOutput);