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 //===----------------------------------------------------------------------===//
16 #include "llvm/Transforms/Utils/Linker.h"
17 #include "llvm/Module.h"
18 #include "llvm/PassManager.h"
19 #include "llvm/Bytecode/Reader.h"
20 #include "llvm/Bytecode/WriteBytecodePass.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/Transforms/IPO.h"
23 #include "llvm/Transforms/Scalar.h"
24 #include "Support/FileUtilities.h"
25 #include "Support/SystemUtils.h"
26 #include "Support/CommandLine.h"
27 #include "Support/Signals.h"
28 #include "Config/unistd.h"
38 InputFilenames(cl::Positional, cl::desc("<input bytecode files>"),
42 OutputFilename("o", cl::desc("Override output filename"), cl::init("a.out"),
43 cl::value_desc("filename"));
46 Verbose("v", cl::desc("Print information about actions taken"));
49 LibPaths("L", cl::desc("Specify a library search path"), cl::Prefix,
50 cl::value_desc("directory"));
53 Libraries("l", cl::desc("Specify libraries to link to"), cl::Prefix,
54 cl::value_desc("library prefix"));
57 Strip("s", cl::desc("Strip symbol info from executable"));
60 NoInternalize("disable-internalize",
61 cl::desc("Do not mark all symbols as internal"));
63 ExportDynamic("export-dynamic", cl::desc("Alias for -disable-internalize"),
64 cl::aliasopt(NoInternalize));
67 LinkAsLibrary("link-as-library", cl::desc("Link the .bc files together as a"
68 " library, not an executable"));
71 Native("native", cl::desc("Generate a native binary instead of a shell script"));
73 // Compatibility options that are ignored but supported by LD
75 CO3("soname", cl::Hidden, cl::desc("Compatibility option: ignored"));
77 CO4("version-script", cl::Hidden, cl::desc("Compatibility option: ignored"));
79 CO5("eh-frame-hdr", cl::Hidden, cl::desc("Compatibility option: ignored"));
81 CO6("r", cl::Hidden, cl::desc("Compatibility option: ignored"));
85 // Function: PrintAndReturn ()
88 // Prints a message (usually error message) to standard error (stderr) and
89 // returns a value usable for an exit status.
92 // progname - The name of the program (i.e. argv[0]).
93 // Message - The message to print to standard error.
94 // Extra - Extra information to print between the program name and thei
95 // message. It is optional.
101 // Returns a value that can be used as the exit status (i.e. for exit()).
104 PrintAndReturn (const char *progname,
105 const std::string &Message,
106 const std::string &Extra)
108 std::cerr << progname << Extra << ": " << Message << "\n";
115 // Function: CopyEnv()
118 // This function takes an array of environment variables and makes a
119 // copy of it. This copy can then be manipulated any way the caller likes
120 // without affecting the process's real environment.
123 // envp - An array of C strings containing an environment.
129 // NULL - An error occurred.
131 // Otherwise, a pointer to a new array of C strings is returned. Every string
132 // in the array is a duplicate of the one in the original array (i.e. we do
133 // not copy the char *'s from one array to another).
136 CopyEnv (char ** const envp)
138 // The new environment list
141 // The number of entries in the old environment list
145 // Count the number of entries in the old list;
147 for (entries = 0; envp[entries] != NULL; entries++)
153 // Add one more entry for the NULL pointer that ends the list.
158 // If there are no entries at all, just return NULL.
166 // Allocate a new environment list.
168 if ((newenv = new (char *) [entries]) == NULL)
174 // Make a copy of the list. Don't forget the NULL that ends the list.
177 while (envp[entries] != NULL)
179 newenv[entries] = new char[strlen (envp[entries]) + 1];
180 strcpy (newenv[entries], envp[entries]);
183 newenv[entries] = NULL;
190 // Function: RemoveEnv()
193 // Remove the specified environment variable from the environment array.
196 // name - The name of the variable to remove. It cannot be NULL.
197 // envp - The array of environment variables. It cannot be NULL.
200 // envp - The pointer to the specified variable name is removed.
206 // This is mainly done because functions to remove items from the environment
207 // are not available across all platforms. In particular, Solaris does not
208 // seem to have an unsetenv() function or a setenv() function (or they are
209 // undocumented if they do exist).
212 RemoveEnv (const char * name, char ** const envp)
214 // Pointer for scanning arrays
217 // Index for selecting elements of the environment array
220 for (index=0; envp[index] != NULL; index++)
223 // Find the first equals sign in the array and make it an EOS character.
225 p = strchr (envp[index], '=');
236 // Compare the two strings. If they are equal, zap this string.
237 // Otherwise, restore it.
239 if (!strcmp (name, envp[index]))
254 main(int argc, char **argv, char ** envp)
256 cl::ParseCommandLineOptions(argc, argv, " llvm linker for GCC\n");
258 std::string ErrorMessage;
259 std::auto_ptr<Module> Composite(LoadObject(InputFilenames[0], ErrorMessage));
260 if (Composite.get() == 0)
261 return PrintAndReturn(argv[0], ErrorMessage);
263 // We always look first in the current directory when searching for libraries.
264 LibPaths.insert(LibPaths.begin(), ".");
266 // If the user specied an extra search path in their environment, respect it.
267 if (char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH"))
268 LibPaths.push_back(SearchPath);
270 // Remove any consecutive duplicates of the same library...
271 Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
274 // Link in all of the files
275 LinkFiles (argv[0], Composite.get(), InputFilenames, Verbose);
276 LinkLibraries (argv[0], Composite.get(), Libraries, LibPaths, Verbose, Native);
278 // Link in all of the libraries next...
281 // Create the output file.
283 std::string RealBytecodeOutput = OutputFilename;
284 if (!LinkAsLibrary) RealBytecodeOutput += ".bc";
285 std::ofstream Out(RealBytecodeOutput.c_str());
287 return PrintAndReturn(argv[0], "error opening '" + RealBytecodeOutput +
291 // Ensure that the bytecode file gets removed from the disk if we get a
294 RemoveFileOnSignal(RealBytecodeOutput);
297 // Generate the bytecode file.
299 if (GenerateBytecode (Composite.get(), Strip, !NoInternalize, &Out))
302 return PrintAndReturn(argv[0], "error generating bytcode");
306 // Close the bytecode file.
311 // If we are not linking a library, generate either a native executable
312 // or a JIT shell script, depending upon what the user wants.
314 if (!LinkAsLibrary) {
316 // If the user wants to generate a native executable, compile it from the
319 // Otherwise, create a script that will run the bytecode through the JIT.
323 // Name of the Assembly Language output file
324 std::string AssemblyFile = OutputFilename + ".s";
327 // Mark the output files for removal if we get an interrupt.
329 RemoveFileOnSignal (AssemblyFile);
330 RemoveFileOnSignal (OutputFilename);
333 // Determine the locations of the llc and gcc programs.
335 std::string llc=FindExecutable ("llc", argv[0]);
336 std::string gcc=FindExecutable ("gcc", argv[0]);
339 return PrintAndReturn (argv[0], "Failed to find llc");
344 return PrintAndReturn (argv[0], "Failed to find gcc");
348 // Generate an assembly language file for the bytecode.
350 if (Verbose) std::cout << "Generating Assembly Code\n";
351 GenerateAssembly (AssemblyFile, RealBytecodeOutput, llc, envp);
352 if (Verbose) std::cout << "Generating Native Code\n";
353 GenerateNative (OutputFilename, AssemblyFile, Libraries, LibPaths, gcc, envp);
356 // Remove the assembly language file.
358 removeFile (AssemblyFile);
362 // Output the script to start the program...
363 std::ofstream Out2(OutputFilename.c_str());
365 return PrintAndReturn(argv[0], "error opening '" + OutputFilename +
367 Out2 << "#!/bin/sh\nlli -q $0.bc $*\n";
371 // Make the script executable...
372 MakeFileExecutable (OutputFilename);
374 // Make the bytecode file readable and directly executable in LLEE as well
375 MakeFileExecutable (RealBytecodeOutput);
376 MakeFileReadable (RealBytecodeOutput);