1 //===-- ToolRunner.cpp ----------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the interfaces described in the ToolRunner.h file.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "toolrunner"
15 #include "ToolRunner.h"
16 #include "llvm/Config/config.h" // for HAVE_LINK_R
17 #include "llvm/Support/CommandLine.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Support/FileUtilities.h"
20 #include "llvm/Support/PathV1.h"
21 #include "llvm/Support/Program.h"
22 #include "llvm/Support/raw_ostream.h"
29 SaveTemps("save-temps", cl::init(false), cl::desc("Save temporary files"));
34 RemoteClient("remote-client",
35 cl::desc("Remote execution client (rsh/ssh)"));
38 RemoteHost("remote-host",
39 cl::desc("Remote execution (rsh/ssh) host"));
42 RemotePort("remote-port",
43 cl::desc("Remote execution (rsh/ssh) port"));
46 RemoteUser("remote-user",
47 cl::desc("Remote execution (rsh/ssh) user id"));
50 RemoteExtra("remote-extra-options",
51 cl::desc("Remote execution (rsh/ssh) extra options"));
54 /// RunProgramWithTimeout - This function provides an alternate interface
55 /// to the sys::Program::ExecuteAndWait interface.
56 /// @see sys::Program::ExecuteAndWait
57 static int RunProgramWithTimeout(StringRef ProgramPath,
62 unsigned NumSeconds = 0,
63 unsigned MemoryLimit = 0,
64 std::string *ErrMsg = 0) {
65 const StringRef *Redirects[3] = { &StdInFile, &StdOutFile, &StdErrFile };
67 #if 0 // For debug purposes
70 for (unsigned i = 0; Args[i]; ++i)
71 errs() << " " << Args[i];
76 return sys::ExecuteAndWait(ProgramPath, Args, 0, Redirects,
77 NumSeconds, MemoryLimit, ErrMsg);
80 /// RunProgramRemotelyWithTimeout - This function runs the given program
81 /// remotely using the given remote client and the sys::Program::ExecuteAndWait.
82 /// Returns the remote program exit code or reports a remote client error if it
83 /// fails. Remote client is required to return 255 if it failed or program exit
85 /// @see sys::Program::ExecuteAndWait
86 static int RunProgramRemotelyWithTimeout(StringRef RemoteClientPath,
91 unsigned NumSeconds = 0,
92 unsigned MemoryLimit = 0) {
93 const StringRef *Redirects[3] = { &StdInFile, &StdOutFile, &StdErrFile };
95 #if 0 // For debug purposes
98 for (unsigned i = 0; Args[i]; ++i)
99 errs() << " " << Args[i];
104 // Run the program remotely with the remote client
105 int ReturnCode = sys::ExecuteAndWait(RemoteClientPath, Args, 0,
106 Redirects, NumSeconds, MemoryLimit);
108 // Has the remote client fail?
109 if (255 == ReturnCode) {
110 std::ostringstream OS;
111 OS << "\nError running remote client:\n ";
112 for (const char **Arg = Args; *Arg; ++Arg)
116 // The error message is in the output file, let's print it out from there.
117 std::string StdOutFileName = StdOutFile.str();
118 std::ifstream ErrorFile(StdOutFileName.c_str());
120 std::copy(std::istreambuf_iterator<char>(ErrorFile),
121 std::istreambuf_iterator<char>(),
122 std::ostreambuf_iterator<char>(OS));
132 static std::string ProcessFailure(StringRef ProgPath, const char** Args,
133 unsigned Timeout = 0,
134 unsigned MemoryLimit = 0) {
135 std::ostringstream OS;
136 OS << "\nError running tool:\n ";
137 for (const char **Arg = Args; *Arg; ++Arg)
141 // Rerun the compiler, capturing any error messages to print them.
142 sys::Path ErrorFilename("bugpoint.program_error_messages");
144 if (ErrorFilename.makeUnique(true, &ErrMsg)) {
145 errs() << "Error making unique filename: " << ErrMsg << "\n";
148 RunProgramWithTimeout(ProgPath, Args, "", ErrorFilename.str(),
149 ErrorFilename.str(), Timeout, MemoryLimit);
150 // FIXME: check return code ?
152 // Print out the error messages generated by GCC if possible...
153 std::ifstream ErrorFile(ErrorFilename.c_str());
155 std::copy(std::istreambuf_iterator<char>(ErrorFile),
156 std::istreambuf_iterator<char>(),
157 std::ostreambuf_iterator<char>(OS));
161 ErrorFilename.eraseFromDisk();
165 //===---------------------------------------------------------------------===//
166 // LLI Implementation of AbstractIntepreter interface
169 class LLI : public AbstractInterpreter {
170 std::string LLIPath; // The path to the LLI executable
171 std::vector<std::string> ToolArgs; // Args to pass to LLI
173 LLI(const std::string &Path, const std::vector<std::string> *Args)
176 if (Args) { ToolArgs = *Args; }
179 virtual int ExecuteProgram(const std::string &Bitcode,
180 const std::vector<std::string> &Args,
181 const std::string &InputFile,
182 const std::string &OutputFile,
184 const std::vector<std::string> &GCCArgs,
185 const std::vector<std::string> &SharedLibs =
186 std::vector<std::string>(),
187 unsigned Timeout = 0,
188 unsigned MemoryLimit = 0);
192 int LLI::ExecuteProgram(const std::string &Bitcode,
193 const std::vector<std::string> &Args,
194 const std::string &InputFile,
195 const std::string &OutputFile,
197 const std::vector<std::string> &GCCArgs,
198 const std::vector<std::string> &SharedLibs,
200 unsigned MemoryLimit) {
201 std::vector<const char*> LLIArgs;
202 LLIArgs.push_back(LLIPath.c_str());
203 LLIArgs.push_back("-force-interpreter=true");
205 for (std::vector<std::string>::const_iterator i = SharedLibs.begin(),
206 e = SharedLibs.end(); i != e; ++i) {
207 LLIArgs.push_back("-load");
208 LLIArgs.push_back((*i).c_str());
211 // Add any extra LLI args.
212 for (unsigned i = 0, e = ToolArgs.size(); i != e; ++i)
213 LLIArgs.push_back(ToolArgs[i].c_str());
215 LLIArgs.push_back(Bitcode.c_str());
216 // Add optional parameters to the running program from Argv
217 for (unsigned i=0, e = Args.size(); i != e; ++i)
218 LLIArgs.push_back(Args[i].c_str());
219 LLIArgs.push_back(0);
221 outs() << "<lli>"; outs().flush();
222 DEBUG(errs() << "\nAbout to run:\t";
223 for (unsigned i=0, e = LLIArgs.size()-1; i != e; ++i)
224 errs() << " " << LLIArgs[i];
227 return RunProgramWithTimeout(LLIPath, &LLIArgs[0],
228 InputFile, OutputFile, OutputFile,
229 Timeout, MemoryLimit, Error);
232 void AbstractInterpreter::anchor() { }
234 /// Prepend the path to the program being executed
235 /// to \p ExeName, given the value of argv[0] and the address of main()
236 /// itself. This allows us to find another LLVM tool if it is built in the same
237 /// directory. An empty string is returned on error; note that this function
238 /// just mainpulates the path and doesn't check for executability.
239 /// @brief Find a named executable.
240 static sys::Path PrependMainExecutablePath(const std::string &ExeName,
241 const char *Argv0, void *MainAddr) {
242 // Check the directory that the calling program is in. We can do
243 // this if ProgramPath contains at least one / character, indicating that it
244 // is a relative path to the executable itself.
245 sys::Path Result = sys::Path::GetMainExecutable(Argv0, MainAddr);
246 Result.eraseComponent();
248 if (!Result.isEmpty()) {
249 Result.appendComponent(ExeName);
250 Result.appendSuffix(sys::Path::GetEXESuffix());
256 // LLI create method - Try to find the LLI executable
257 AbstractInterpreter *AbstractInterpreter::createLLI(const char *Argv0,
258 std::string &Message,
259 const std::vector<std::string> *ToolArgs) {
260 std::string LLIPath =
261 PrependMainExecutablePath("lli", Argv0, (void *)(intptr_t)&createLLI).str();
262 if (!LLIPath.empty()) {
263 Message = "Found lli: " + LLIPath + "\n";
264 return new LLI(LLIPath, ToolArgs);
267 Message = "Cannot find `lli' in executable directory!\n";
271 //===---------------------------------------------------------------------===//
272 // Custom compiler command implementation of AbstractIntepreter interface
274 // Allows using a custom command for compiling the bitcode, thus allows, for
275 // example, to compile a bitcode fragment without linking or executing, then
276 // using a custom wrapper script to check for compiler errors.
278 class CustomCompiler : public AbstractInterpreter {
279 std::string CompilerCommand;
280 std::vector<std::string> CompilerArgs;
283 const std::string &CompilerCmd, std::vector<std::string> CompArgs) :
284 CompilerCommand(CompilerCmd), CompilerArgs(CompArgs) {}
286 virtual void compileProgram(const std::string &Bitcode,
288 unsigned Timeout = 0,
289 unsigned MemoryLimit = 0);
291 virtual int ExecuteProgram(const std::string &Bitcode,
292 const std::vector<std::string> &Args,
293 const std::string &InputFile,
294 const std::string &OutputFile,
296 const std::vector<std::string> &GCCArgs =
297 std::vector<std::string>(),
298 const std::vector<std::string> &SharedLibs =
299 std::vector<std::string>(),
300 unsigned Timeout = 0,
301 unsigned MemoryLimit = 0) {
302 *Error = "Execution not supported with -compile-custom";
308 void CustomCompiler::compileProgram(const std::string &Bitcode,
311 unsigned MemoryLimit) {
313 std::vector<const char*> ProgramArgs;
314 ProgramArgs.push_back(CompilerCommand.c_str());
316 for (std::size_t i = 0; i < CompilerArgs.size(); ++i)
317 ProgramArgs.push_back(CompilerArgs.at(i).c_str());
318 ProgramArgs.push_back(Bitcode.c_str());
319 ProgramArgs.push_back(0);
321 // Add optional parameters to the running program from Argv
322 for (unsigned i = 0, e = CompilerArgs.size(); i != e; ++i)
323 ProgramArgs.push_back(CompilerArgs[i].c_str());
325 if (RunProgramWithTimeout(CompilerCommand, &ProgramArgs[0],
327 Timeout, MemoryLimit, Error))
328 *Error = ProcessFailure(CompilerCommand, &ProgramArgs[0],
329 Timeout, MemoryLimit);
332 //===---------------------------------------------------------------------===//
333 // Custom execution command implementation of AbstractIntepreter interface
335 // Allows using a custom command for executing the bitcode, thus allows,
336 // for example, to invoke a cross compiler for code generation followed by
337 // a simulator that executes the generated binary.
339 class CustomExecutor : public AbstractInterpreter {
340 std::string ExecutionCommand;
341 std::vector<std::string> ExecutorArgs;
344 const std::string &ExecutionCmd, std::vector<std::string> ExecArgs) :
345 ExecutionCommand(ExecutionCmd), ExecutorArgs(ExecArgs) {}
347 virtual int ExecuteProgram(const std::string &Bitcode,
348 const std::vector<std::string> &Args,
349 const std::string &InputFile,
350 const std::string &OutputFile,
352 const std::vector<std::string> &GCCArgs,
353 const std::vector<std::string> &SharedLibs =
354 std::vector<std::string>(),
355 unsigned Timeout = 0,
356 unsigned MemoryLimit = 0);
360 int CustomExecutor::ExecuteProgram(const std::string &Bitcode,
361 const std::vector<std::string> &Args,
362 const std::string &InputFile,
363 const std::string &OutputFile,
365 const std::vector<std::string> &GCCArgs,
366 const std::vector<std::string> &SharedLibs,
368 unsigned MemoryLimit) {
370 std::vector<const char*> ProgramArgs;
371 ProgramArgs.push_back(ExecutionCommand.c_str());
373 for (std::size_t i = 0; i < ExecutorArgs.size(); ++i)
374 ProgramArgs.push_back(ExecutorArgs.at(i).c_str());
375 ProgramArgs.push_back(Bitcode.c_str());
376 ProgramArgs.push_back(0);
378 // Add optional parameters to the running program from Argv
379 for (unsigned i = 0, e = Args.size(); i != e; ++i)
380 ProgramArgs.push_back(Args[i].c_str());
382 return RunProgramWithTimeout(
384 &ProgramArgs[0], InputFile, OutputFile,
385 OutputFile, Timeout, MemoryLimit, Error);
388 // Tokenize the CommandLine to the command and the args to allow
389 // defining a full command line as the command instead of just the
390 // executed program. We cannot just pass the whole string after the command
391 // as a single argument because then program sees only a single
392 // command line argument (with spaces in it: "foo bar" instead
393 // of "foo" and "bar").
395 // code borrowed from:
396 // http://oopweb.com/CPP/Documents/CPPHOWTO/Volume/C++Programming-HOWTO-7.html
397 static void lexCommand(std::string &Message, const std::string &CommandLine,
398 std::string &CmdPath, std::vector<std::string> Args) {
400 std::string Command = "";
401 std::string delimiters = " ";
403 std::string::size_type lastPos = CommandLine.find_first_not_of(delimiters, 0);
404 std::string::size_type pos = CommandLine.find_first_of(delimiters, lastPos);
406 while (std::string::npos != pos || std::string::npos != lastPos) {
407 std::string token = CommandLine.substr(lastPos, pos - lastPos);
411 Args.push_back(token);
412 // Skip delimiters. Note the "not_of"
413 lastPos = CommandLine.find_first_not_of(delimiters, pos);
414 // Find next "non-delimiter"
415 pos = CommandLine.find_first_of(delimiters, lastPos);
418 CmdPath = sys::FindProgramByName(Command);
419 if (CmdPath.empty()) {
421 std::string("Cannot find '") + Command +
426 Message = "Found command in: " + CmdPath + "\n";
429 // Custom execution environment create method, takes the execution command
431 AbstractInterpreter *AbstractInterpreter::createCustomCompiler(
432 std::string &Message,
433 const std::string &CompileCommandLine) {
436 std::vector<std::string> Args;
437 lexCommand(Message, CompileCommandLine, CmdPath, Args);
441 return new CustomCompiler(CmdPath, Args);
444 // Custom execution environment create method, takes the execution command
446 AbstractInterpreter *AbstractInterpreter::createCustomExecutor(
447 std::string &Message,
448 const std::string &ExecCommandLine) {
452 std::vector<std::string> Args;
453 lexCommand(Message, ExecCommandLine, CmdPath, Args);
457 return new CustomExecutor(CmdPath, Args);
460 //===----------------------------------------------------------------------===//
461 // LLC Implementation of AbstractIntepreter interface
463 GCC::FileType LLC::OutputCode(const std::string &Bitcode,
464 std::string &OutputAsmFile, std::string &Error,
465 unsigned Timeout, unsigned MemoryLimit) {
466 const char *Suffix = (UseIntegratedAssembler ? ".llc.o" : ".llc.s");
467 sys::Path uniqueFile(Bitcode + Suffix);
469 if (uniqueFile.makeUnique(true, &ErrMsg)) {
470 errs() << "Error making unique filename: " << ErrMsg << "\n";
473 OutputAsmFile = uniqueFile.str();
474 std::vector<const char *> LLCArgs;
475 LLCArgs.push_back(LLCPath.c_str());
477 // Add any extra LLC args.
478 for (unsigned i = 0, e = ToolArgs.size(); i != e; ++i)
479 LLCArgs.push_back(ToolArgs[i].c_str());
481 LLCArgs.push_back("-o");
482 LLCArgs.push_back(OutputAsmFile.c_str()); // Output to the Asm file
483 LLCArgs.push_back(Bitcode.c_str()); // This is the input bitcode
485 if (UseIntegratedAssembler)
486 LLCArgs.push_back("-filetype=obj");
488 LLCArgs.push_back (0);
490 outs() << (UseIntegratedAssembler ? "<llc-ia>" : "<llc>");
492 DEBUG(errs() << "\nAbout to run:\t";
493 for (unsigned i = 0, e = LLCArgs.size()-1; i != e; ++i)
494 errs() << " " << LLCArgs[i];
497 if (RunProgramWithTimeout(LLCPath, &LLCArgs[0],
499 Timeout, MemoryLimit))
500 Error = ProcessFailure(LLCPath, &LLCArgs[0],
501 Timeout, MemoryLimit);
502 return UseIntegratedAssembler ? GCC::ObjectFile : GCC::AsmFile;
505 void LLC::compileProgram(const std::string &Bitcode, std::string *Error,
506 unsigned Timeout, unsigned MemoryLimit) {
507 std::string OutputAsmFile;
508 OutputCode(Bitcode, OutputAsmFile, *Error, Timeout, MemoryLimit);
509 sys::fs::remove(OutputAsmFile);
512 int LLC::ExecuteProgram(const std::string &Bitcode,
513 const std::vector<std::string> &Args,
514 const std::string &InputFile,
515 const std::string &OutputFile,
517 const std::vector<std::string> &ArgsForGCC,
518 const std::vector<std::string> &SharedLibs,
520 unsigned MemoryLimit) {
522 std::string OutputAsmFile;
523 GCC::FileType FileKind = OutputCode(Bitcode, OutputAsmFile, *Error, Timeout,
525 FileRemover OutFileRemover(OutputAsmFile, !SaveTemps);
527 std::vector<std::string> GCCArgs(ArgsForGCC);
528 GCCArgs.insert(GCCArgs.end(), SharedLibs.begin(), SharedLibs.end());
530 // Assuming LLC worked, compile the result with GCC and run it.
531 return gcc->ExecuteProgram(OutputAsmFile, Args, FileKind,
532 InputFile, OutputFile, Error, GCCArgs,
533 Timeout, MemoryLimit);
536 /// createLLC - Try to find the LLC executable
538 LLC *AbstractInterpreter::createLLC(const char *Argv0,
539 std::string &Message,
540 const std::string &GCCBinary,
541 const std::vector<std::string> *Args,
542 const std::vector<std::string> *GCCArgs,
543 bool UseIntegratedAssembler) {
544 std::string LLCPath =
545 PrependMainExecutablePath("llc", Argv0, (void *)(intptr_t)&createLLC).str();
546 if (LLCPath.empty()) {
547 Message = "Cannot find `llc' in executable directory!\n";
551 GCC *gcc = GCC::create(Message, GCCBinary, GCCArgs);
553 errs() << Message << "\n";
556 Message = "Found llc: " + LLCPath + "\n";
557 return new LLC(LLCPath, gcc, Args, UseIntegratedAssembler);
560 //===---------------------------------------------------------------------===//
561 // JIT Implementation of AbstractIntepreter interface
564 class JIT : public AbstractInterpreter {
565 std::string LLIPath; // The path to the LLI executable
566 std::vector<std::string> ToolArgs; // Args to pass to LLI
568 JIT(const std::string &Path, const std::vector<std::string> *Args)
571 if (Args) { ToolArgs = *Args; }
574 virtual int ExecuteProgram(const std::string &Bitcode,
575 const std::vector<std::string> &Args,
576 const std::string &InputFile,
577 const std::string &OutputFile,
579 const std::vector<std::string> &GCCArgs =
580 std::vector<std::string>(),
581 const std::vector<std::string> &SharedLibs =
582 std::vector<std::string>(),
583 unsigned Timeout = 0,
584 unsigned MemoryLimit = 0);
588 int JIT::ExecuteProgram(const std::string &Bitcode,
589 const std::vector<std::string> &Args,
590 const std::string &InputFile,
591 const std::string &OutputFile,
593 const std::vector<std::string> &GCCArgs,
594 const std::vector<std::string> &SharedLibs,
596 unsigned MemoryLimit) {
597 // Construct a vector of parameters, incorporating those from the command-line
598 std::vector<const char*> JITArgs;
599 JITArgs.push_back(LLIPath.c_str());
600 JITArgs.push_back("-force-interpreter=false");
602 // Add any extra LLI args.
603 for (unsigned i = 0, e = ToolArgs.size(); i != e; ++i)
604 JITArgs.push_back(ToolArgs[i].c_str());
606 for (unsigned i = 0, e = SharedLibs.size(); i != e; ++i) {
607 JITArgs.push_back("-load");
608 JITArgs.push_back(SharedLibs[i].c_str());
610 JITArgs.push_back(Bitcode.c_str());
611 // Add optional parameters to the running program from Argv
612 for (unsigned i=0, e = Args.size(); i != e; ++i)
613 JITArgs.push_back(Args[i].c_str());
614 JITArgs.push_back(0);
616 outs() << "<jit>"; outs().flush();
617 DEBUG(errs() << "\nAbout to run:\t";
618 for (unsigned i=0, e = JITArgs.size()-1; i != e; ++i)
619 errs() << " " << JITArgs[i];
622 DEBUG(errs() << "\nSending output to " << OutputFile << "\n");
623 return RunProgramWithTimeout(LLIPath, &JITArgs[0],
624 InputFile, OutputFile, OutputFile,
625 Timeout, MemoryLimit, Error);
628 /// createJIT - Try to find the LLI executable
630 AbstractInterpreter *AbstractInterpreter::createJIT(const char *Argv0,
631 std::string &Message, const std::vector<std::string> *Args) {
632 std::string LLIPath =
633 PrependMainExecutablePath("lli", Argv0, (void *)(intptr_t)&createJIT).str();
634 if (!LLIPath.empty()) {
635 Message = "Found lli: " + LLIPath + "\n";
636 return new JIT(LLIPath, Args);
639 Message = "Cannot find `lli' in executable directory!\n";
643 //===---------------------------------------------------------------------===//
647 static bool IsARMArchitecture(std::vector<const char*> Args) {
648 for (std::vector<const char*>::const_iterator
649 I = Args.begin(), E = Args.end(); I != E; ++I) {
650 if (StringRef(*I).equals_lower("-arch")) {
652 if (I != E && StringRef(*I).substr(0, strlen("arm")).equals_lower("arm"))
660 int GCC::ExecuteProgram(const std::string &ProgramFile,
661 const std::vector<std::string> &Args,
663 const std::string &InputFile,
664 const std::string &OutputFile,
666 const std::vector<std::string> &ArgsForGCC,
668 unsigned MemoryLimit) {
669 std::vector<const char*> GCCArgs;
671 GCCArgs.push_back(GCCPath.c_str());
673 if (TargetTriple.getArch() == Triple::x86)
674 GCCArgs.push_back("-m32");
676 for (std::vector<std::string>::const_iterator
677 I = gccArgs.begin(), E = gccArgs.end(); I != E; ++I)
678 GCCArgs.push_back(I->c_str());
680 // Specify -x explicitly in case the extension is wonky
681 if (fileType != ObjectFile) {
682 GCCArgs.push_back("-x");
683 if (fileType == CFile) {
684 GCCArgs.push_back("c");
685 GCCArgs.push_back("-fno-strict-aliasing");
687 GCCArgs.push_back("assembler");
689 // For ARM architectures we don't want this flag. bugpoint isn't
690 // explicitly told what architecture it is working on, so we get
692 if (TargetTriple.isOSDarwin() && !IsARMArchitecture(GCCArgs))
693 GCCArgs.push_back("-force_cpusubtype_ALL");
697 GCCArgs.push_back(ProgramFile.c_str()); // Specify the input filename.
699 GCCArgs.push_back("-x");
700 GCCArgs.push_back("none");
701 GCCArgs.push_back("-o");
702 sys::Path OutputBinary (ProgramFile+".gcc.exe");
704 if (OutputBinary.makeUnique(true, &ErrMsg)) {
705 errs() << "Error making unique filename: " << ErrMsg << "\n";
708 GCCArgs.push_back(OutputBinary.c_str()); // Output to the right file...
710 // Add any arguments intended for GCC. We locate them here because this is
711 // most likely -L and -l options that need to come before other libraries but
712 // after the source. Other options won't be sensitive to placement on the
713 // command line, so this should be safe.
714 for (unsigned i = 0, e = ArgsForGCC.size(); i != e; ++i)
715 GCCArgs.push_back(ArgsForGCC[i].c_str());
717 GCCArgs.push_back("-lm"); // Hard-code the math library...
718 GCCArgs.push_back("-O2"); // Optimize the program a bit...
719 #if defined (HAVE_LINK_R)
720 GCCArgs.push_back("-Wl,-R."); // Search this dir for .so files
722 if (TargetTriple.getArch() == Triple::sparc)
723 GCCArgs.push_back("-mcpu=v9");
724 GCCArgs.push_back(0); // NULL terminator
726 outs() << "<gcc>"; outs().flush();
727 DEBUG(errs() << "\nAbout to run:\t";
728 for (unsigned i = 0, e = GCCArgs.size()-1; i != e; ++i)
729 errs() << " " << GCCArgs[i];
732 if (RunProgramWithTimeout(GCCPath, &GCCArgs[0], "", "", "")) {
733 *Error = ProcessFailure(GCCPath, &GCCArgs[0]);
737 std::vector<const char*> ProgramArgs;
739 // Declared here so that the destructor only runs after
740 // ProgramArgs is used.
743 if (RemoteClientPath.empty())
744 ProgramArgs.push_back(OutputBinary.c_str());
746 ProgramArgs.push_back(RemoteClientPath.c_str());
747 ProgramArgs.push_back(RemoteHost.c_str());
748 if (!RemoteUser.empty()) {
749 ProgramArgs.push_back("-l");
750 ProgramArgs.push_back(RemoteUser.c_str());
752 if (!RemotePort.empty()) {
753 ProgramArgs.push_back("-p");
754 ProgramArgs.push_back(RemotePort.c_str());
756 if (!RemoteExtra.empty()) {
757 ProgramArgs.push_back(RemoteExtra.c_str());
760 // Full path to the binary. We need to cd to the exec directory because
761 // there is a dylib there that the exec expects to find in the CWD
762 char* env_pwd = getenv("PWD");
766 Exec += OutputBinary.c_str();
767 ProgramArgs.push_back(Exec.c_str());
770 // Add optional parameters to the running program from Argv
771 for (unsigned i = 0, e = Args.size(); i != e; ++i)
772 ProgramArgs.push_back(Args[i].c_str());
773 ProgramArgs.push_back(0); // NULL terminator
775 // Now that we have a binary, run it!
776 outs() << "<program>"; outs().flush();
777 DEBUG(errs() << "\nAbout to run:\t";
778 for (unsigned i = 0, e = ProgramArgs.size()-1; i != e; ++i)
779 errs() << " " << ProgramArgs[i];
783 FileRemover OutputBinaryRemover(OutputBinary.str(), !SaveTemps);
785 if (RemoteClientPath.empty()) {
786 DEBUG(errs() << "<run locally>");
787 int ExitCode = RunProgramWithTimeout(OutputBinary.str(), &ProgramArgs[0],
788 InputFile, OutputFile, OutputFile,
789 Timeout, MemoryLimit, Error);
790 // Treat a signal (usually SIGSEGV) or timeout as part of the program output
791 // so that crash-causing miscompilation is handled seamlessly.
793 std::ofstream outFile(OutputFile.c_str(), std::ios_base::app);
794 outFile << *Error << '\n';
800 outs() << "<run remotely>"; outs().flush();
801 return RunProgramRemotelyWithTimeout(RemoteClientPath,
802 &ProgramArgs[0], InputFile, OutputFile,
803 OutputFile, Timeout, MemoryLimit);
807 int GCC::MakeSharedObject(const std::string &InputFile, FileType fileType,
808 std::string &OutputFile,
809 const std::vector<std::string> &ArgsForGCC,
810 std::string &Error) {
811 sys::Path uniqueFilename(InputFile+LTDL_SHLIB_EXT);
813 if (uniqueFilename.makeUnique(true, &ErrMsg)) {
814 errs() << "Error making unique filename: " << ErrMsg << "\n";
817 OutputFile = uniqueFilename.str();
819 std::vector<const char*> GCCArgs;
821 GCCArgs.push_back(GCCPath.c_str());
823 if (TargetTriple.getArch() == Triple::x86)
824 GCCArgs.push_back("-m32");
826 for (std::vector<std::string>::const_iterator
827 I = gccArgs.begin(), E = gccArgs.end(); I != E; ++I)
828 GCCArgs.push_back(I->c_str());
830 // Compile the C/asm file into a shared object
831 if (fileType != ObjectFile) {
832 GCCArgs.push_back("-x");
833 GCCArgs.push_back(fileType == AsmFile ? "assembler" : "c");
835 GCCArgs.push_back("-fno-strict-aliasing");
836 GCCArgs.push_back(InputFile.c_str()); // Specify the input filename.
837 GCCArgs.push_back("-x");
838 GCCArgs.push_back("none");
839 if (TargetTriple.getArch() == Triple::sparc)
840 GCCArgs.push_back("-G"); // Compile a shared library, `-G' for Sparc
841 else if (TargetTriple.isOSDarwin()) {
842 // link all source files into a single module in data segment, rather than
843 // generating blocks. dynamic_lookup requires that you set
844 // MACOSX_DEPLOYMENT_TARGET=10.3 in your env. FIXME: it would be better for
845 // bugpoint to just pass that in the environment of GCC.
846 GCCArgs.push_back("-single_module");
847 GCCArgs.push_back("-dynamiclib"); // `-dynamiclib' for MacOS X/PowerPC
848 GCCArgs.push_back("-undefined");
849 GCCArgs.push_back("dynamic_lookup");
851 GCCArgs.push_back("-shared"); // `-shared' for Linux/X86, maybe others
853 if (TargetTriple.getArch() == Triple::x86_64)
854 GCCArgs.push_back("-fPIC"); // Requires shared objs to contain PIC
856 if (TargetTriple.getArch() == Triple::sparc)
857 GCCArgs.push_back("-mcpu=v9");
859 GCCArgs.push_back("-o");
860 GCCArgs.push_back(OutputFile.c_str()); // Output to the right filename.
861 GCCArgs.push_back("-O2"); // Optimize the program a bit.
865 // Add any arguments intended for GCC. We locate them here because this is
866 // most likely -L and -l options that need to come before other libraries but
867 // after the source. Other options won't be sensitive to placement on the
868 // command line, so this should be safe.
869 for (unsigned i = 0, e = ArgsForGCC.size(); i != e; ++i)
870 GCCArgs.push_back(ArgsForGCC[i].c_str());
871 GCCArgs.push_back(0); // NULL terminator
875 outs() << "<gcc>"; outs().flush();
876 DEBUG(errs() << "\nAbout to run:\t";
877 for (unsigned i = 0, e = GCCArgs.size()-1; i != e; ++i)
878 errs() << " " << GCCArgs[i];
881 if (RunProgramWithTimeout(GCCPath, &GCCArgs[0], "", "", "")) {
882 Error = ProcessFailure(GCCPath, &GCCArgs[0]);
888 /// create - Try to find the `gcc' executable
890 GCC *GCC::create(std::string &Message,
891 const std::string &GCCBinary,
892 const std::vector<std::string> *Args) {
893 std::string GCCPath = sys::FindProgramByName(GCCBinary);
894 if (GCCPath.empty()) {
895 Message = "Cannot find `"+ GCCBinary +"' in PATH!\n";
899 std::string RemoteClientPath;
900 if (!RemoteClient.empty())
901 RemoteClientPath = sys::FindProgramByName(RemoteClient);
903 Message = "Found gcc: " + GCCPath + "\n";
904 return new GCC(GCCPath, RemoteClientPath, Args);