Make -r work, fixing PR 91
[oota-llvm.git] / tools / gccld / gccld.cpp
1 //===- gccld.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 "gccld.h"
24 #include "llvm/Module.h"
25 #include "llvm/PassManager.h"
26 #include "llvm/Bytecode/Reader.h"
27 #include "llvm/Bytecode/WriteBytecodePass.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Transforms/IPO.h"
30 #include "llvm/Transforms/Scalar.h"
31 #include "llvm/Transforms/Utils/Linker.h"
32 #include "Support/CommandLine.h"
33 #include "Support/FileUtilities.h"
34 #include "Support/Signals.h"
35 #include "Support/SystemUtils.h"
36 #include <fstream>
37 #include <memory>
38
39 namespace {
40   cl::list<std::string> 
41   InputFilenames(cl::Positional, cl::desc("<input bytecode files>"),
42                  cl::OneOrMore);
43
44   cl::opt<std::string> 
45   OutputFilename("o", cl::desc("Override output filename"), cl::init("a.out"),
46                  cl::value_desc("filename"));
47
48   cl::opt<bool>    
49   Verbose("v", cl::desc("Print information about actions taken"));
50   
51   cl::list<std::string> 
52   LibPaths("L", cl::desc("Specify a library search path"), cl::Prefix,
53            cl::value_desc("directory"));
54
55   cl::list<std::string> 
56   Libraries("l", cl::desc("Specify libraries to link to"), cl::Prefix,
57             cl::value_desc("library prefix"));
58
59   cl::opt<bool>
60   Strip("s", cl::desc("Strip symbol info from executable"));
61
62   cl::opt<bool>
63   NoInternalize("disable-internalize",
64                 cl::desc("Do not mark all symbols as internal"));
65   cl::alias
66   ExportDynamic("export-dynamic", cl::desc("Alias for -disable-internalize"),
67                 cl::aliasopt(NoInternalize));
68
69   cl::opt<bool>
70   LinkAsLibrary("link-as-library", cl::desc("Link the .bc files together as a"
71                                             " library, not an executable"));
72   cl::alias
73   Relink("r", cl::desc("Alias for -link-as-library"),
74          cl::aliasopt(LinkAsLibrary));
75
76   cl::opt<bool>    
77   Native("native",
78          cl::desc("Generate a native binary instead of a shell script"));
79   
80   // Compatibility options that are ignored but supported by LD
81   cl::opt<std::string>
82   CO3("soname", cl::Hidden, cl::desc("Compatibility option: ignored"));
83   cl::opt<std::string>
84   CO4("version-script", cl::Hidden, cl::desc("Compatibility option: ignored"));
85   cl::opt<bool>
86   CO5("eh-frame-hdr", cl::Hidden, cl::desc("Compatibility option: ignored"));
87 }
88
89 //
90 // Function: PrintAndReturn ()
91 //
92 // Description:
93 //  Prints a message (usually error message) to standard error (stderr) and
94 //  returns a value usable for an exit status.
95 //
96 // Inputs:
97 //  progname - The name of the program (i.e. argv[0]).
98 //  Message  - The message to print to standard error.
99 //  Extra    - Extra information to print between the program name and thei
100 //             message.  It is optional.
101 //
102 // Outputs:
103 //  None.
104 //
105 // Return value:
106 //  Returns a value that can be used as the exit status (i.e. for exit()).
107 //
108 int
109 PrintAndReturn (const char *progname,
110                 const std::string &Message,
111                 const std::string &Extra)
112 {
113   std::cerr << progname << Extra << ": " << Message << "\n";
114   return 1;
115 }
116
117 //
118 //
119 // Function: CopyEnv()
120 //
121 // Description:
122 //      This function takes an array of environment variables and makes a
123 //      copy of it.  This copy can then be manipulated any way the caller likes
124 //  without affecting the process's real environment.
125 //
126 // Inputs:
127 //  envp - An array of C strings containing an environment.
128 //
129 // Outputs:
130 //  None.
131 //
132 // Return value:
133 //  NULL - An error occurred.
134 //
135 //  Otherwise, a pointer to a new array of C strings is returned.  Every string
136 //  in the array is a duplicate of the one in the original array (i.e. we do
137 //  not copy the char *'s from one array to another).
138 //
139 char ** CopyEnv(char ** const envp) {
140   // Count the number of entries in the old list;
141   unsigned entries;   // The number of entries in the old environment list
142   for (entries = 0; envp[entries] != NULL; entries++)
143   {
144     ;
145   }
146
147   // Add one more entry for the NULL pointer that ends the list.
148   ++entries;
149
150   // If there are no entries at all, just return NULL.
151   if (entries == 0)
152     return NULL;
153
154   // Allocate a new environment list.
155   char **newenv;
156   if ((newenv = new (char *) [entries]) == NULL)
157     return NULL;
158
159   // Make a copy of the list.  Don't forget the NULL that ends the list.
160   entries = 0;
161   while (envp[entries] != NULL) {
162     newenv[entries] = new char[strlen (envp[entries]) + 1];
163     strcpy (newenv[entries], envp[entries]);
164     ++entries;
165   }
166   newenv[entries] = NULL;
167
168   return newenv;
169 }
170
171
172 //
173 // Function: RemoveEnv()
174 //
175 // Description:
176 //      Remove the specified environment variable from the environment array.
177 //
178 // Inputs:
179 //      name - The name of the variable to remove.  It cannot be NULL.
180 //      envp - The array of environment variables.  It cannot be NULL.
181 //
182 // Outputs:
183 //      envp - The pointer to the specified variable name is removed.
184 //
185 // Return value:
186 //      None.
187 //
188 // Notes:
189 //  This is mainly done because functions to remove items from the environment
190 //  are not available across all platforms.  In particular, Solaris does not
191 //  seem to have an unsetenv() function or a setenv() function (or they are
192 //  undocumented if they do exist).
193 //
194 void RemoveEnv(const char * name, char ** const envp) {
195   for (unsigned index=0; envp[index] != NULL; index++) {
196     // Find the first equals sign in the array and make it an EOS character.
197     char *p = strchr (envp[index], '=');
198     if (p == NULL)
199       continue;
200     else
201       *p = '\0';
202
203     // Compare the two strings.  If they are equal, zap this string.
204     // Otherwise, restore it.
205     if (!strcmp(name, envp[index]))
206       *envp[index] = '\0';
207     else
208       *p = '=';
209   }
210
211   return;
212 }
213
214
215 int main(int argc, char **argv, char **envp) {
216   cl::ParseCommandLineOptions(argc, argv, " llvm linker for GCC\n");
217
218   std::string ErrorMessage;
219   std::auto_ptr<Module> Composite(LoadObject(InputFilenames[0], ErrorMessage));
220   if (Composite.get() == 0)
221     return PrintAndReturn(argv[0], ErrorMessage);
222
223   // We always look first in the current directory when searching for libraries.
224   LibPaths.insert(LibPaths.begin(), ".");
225
226   // If the user specified an extra search path in their environment, respect
227   // it.
228   if (char *SearchPath = getenv("LLVM_LIB_SEARCH_PATH"))
229     LibPaths.push_back(SearchPath);
230
231   // Remove any consecutive duplicates of the same library...
232   Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
233                   Libraries.end());
234
235   // Link in all of the files
236   if (LinkFiles(argv[0], Composite.get(), InputFilenames, Verbose))
237     return 1; // Error already printed
238
239   if (!LinkAsLibrary)
240     LinkLibraries(argv[0], Composite.get(), Libraries, LibPaths,
241                   Verbose, Native);
242
243   // Link in all of the libraries next...
244
245   // Create the output file.
246   std::string RealBytecodeOutput = OutputFilename;
247   if (!LinkAsLibrary) RealBytecodeOutput += ".bc";
248   std::ofstream Out(RealBytecodeOutput.c_str());
249   if (!Out.good())
250     return PrintAndReturn(argv[0], "error opening '" + RealBytecodeOutput +
251                                    "' for writing!");
252
253   // Ensure that the bytecode file gets removed from the disk if we get a
254   // SIGINT signal.
255   RemoveFileOnSignal(RealBytecodeOutput);
256
257   // Generate the bytecode file.
258   if (GenerateBytecode(Composite.get(), Strip, !NoInternalize, &Out)) {
259     Out.close();
260     return PrintAndReturn(argv[0], "error generating bytcode");
261   }
262
263   // Close the bytecode file.
264   Out.close();
265
266   // If we are not linking a library, generate either a native executable
267   // or a JIT shell script, depending upon what the user wants.
268   if (!LinkAsLibrary) {
269     // If the user wants to generate a native executable, compile it from the
270     // bytecode file.
271     //
272     // Otherwise, create a script that will run the bytecode through the JIT.
273     if (Native) {
274       // Name of the Assembly Language output file
275       std::string AssemblyFile = OutputFilename + ".s";
276
277       // Mark the output files for removal if we get an interrupt.
278       RemoveFileOnSignal(AssemblyFile);
279       RemoveFileOnSignal(OutputFilename);
280
281       // Determine the locations of the llc and gcc programs.
282       std::string llc = FindExecutable("llc", argv[0]);
283       std::string gcc = FindExecutable("gcc", argv[0]);
284       if (llc.empty())
285         return PrintAndReturn(argv[0], "Failed to find llc");
286
287       if (gcc.empty())
288         return PrintAndReturn(argv[0], "Failed to find gcc");
289
290       // Generate an assembly language file for the bytecode.
291       if (Verbose) std::cout << "Generating Assembly Code\n";
292       GenerateAssembly(AssemblyFile, RealBytecodeOutput, llc, envp);
293       if (Verbose) std::cout << "Generating Native Code\n";
294       GenerateNative(OutputFilename, AssemblyFile, Libraries, LibPaths,
295                      gcc, envp);
296
297       // Remove the assembly language file.
298       removeFile (AssemblyFile);
299     } else {
300       // Output the script to start the program...
301       std::ofstream Out2(OutputFilename.c_str());
302       if (!Out2.good())
303         return PrintAndReturn(argv[0], "error opening '" + OutputFilename +
304                                        "' for writing!");
305       Out2 << "#!/bin/sh\nlli $0.bc $*\n";
306       Out2.close();
307     }
308   
309     // Make the script executable...
310     MakeFileExecutable(OutputFilename);
311
312     // Make the bytecode file readable and directly executable in LLEE as well
313     MakeFileExecutable(RealBytecodeOutput);
314     MakeFileReadable(RealBytecodeOutput);
315   }
316
317   return 0;
318 }