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 #include "ToolRunner.h"
15 #include "llvm/Config/config.h" // for HAVE_LINK_R
16 #include "llvm/Support/CommandLine.h"
17 #include "llvm/Support/Debug.h"
18 #include "llvm/Support/FileSystem.h"
19 #include "llvm/Support/FileUtilities.h"
20 #include "llvm/Support/Program.h"
21 #include "llvm/Support/raw_ostream.h"
26 #define DEBUG_TYPE "toolrunner"
30 SaveTemps("save-temps", cl::init(false), cl::desc("Save temporary files"));
35 RemoteClient("remote-client",
36 cl::desc("Remote execution client (rsh/ssh)"));
39 RemoteHost("remote-host",
40 cl::desc("Remote execution (rsh/ssh) host"));
43 RemotePort("remote-port",
44 cl::desc("Remote execution (rsh/ssh) port"));
47 RemoteUser("remote-user",
48 cl::desc("Remote execution (rsh/ssh) user id"));
51 RemoteExtra("remote-extra-options",
52 cl::desc("Remote execution (rsh/ssh) extra options"));
55 /// RunProgramWithTimeout - This function provides an alternate interface
56 /// to the sys::Program::ExecuteAndWait interface.
57 /// @see sys::Program::ExecuteAndWait
58 static int RunProgramWithTimeout(StringRef ProgramPath,
63 unsigned NumSeconds = 0,
64 unsigned MemoryLimit = 0,
65 std::string *ErrMsg = nullptr) {
66 const StringRef *Redirects[3] = { &StdInFile, &StdOutFile, &StdErrFile };
67 return sys::ExecuteAndWait(ProgramPath, Args, nullptr, Redirects,
68 NumSeconds, MemoryLimit, ErrMsg);
71 /// RunProgramRemotelyWithTimeout - This function runs the given program
72 /// remotely using the given remote client and the sys::Program::ExecuteAndWait.
73 /// Returns the remote program exit code or reports a remote client error if it
74 /// fails. Remote client is required to return 255 if it failed or program exit
76 /// @see sys::Program::ExecuteAndWait
77 static int RunProgramRemotelyWithTimeout(StringRef RemoteClientPath,
82 unsigned NumSeconds = 0,
83 unsigned MemoryLimit = 0) {
84 const StringRef *Redirects[3] = { &StdInFile, &StdOutFile, &StdErrFile };
86 // Run the program remotely with the remote client
87 int ReturnCode = sys::ExecuteAndWait(RemoteClientPath, Args, nullptr,
88 Redirects, NumSeconds, MemoryLimit);
90 // Has the remote client fail?
91 if (255 == ReturnCode) {
92 std::ostringstream OS;
93 OS << "\nError running remote client:\n ";
94 for (const char **Arg = Args; *Arg; ++Arg)
98 // The error message is in the output file, let's print it out from there.
99 std::string StdOutFileName = StdOutFile.str();
100 std::ifstream ErrorFile(StdOutFileName.c_str());
102 std::copy(std::istreambuf_iterator<char>(ErrorFile),
103 std::istreambuf_iterator<char>(),
104 std::ostreambuf_iterator<char>(OS));
114 static std::string ProcessFailure(StringRef ProgPath, const char** Args,
115 unsigned Timeout = 0,
116 unsigned MemoryLimit = 0) {
117 std::ostringstream OS;
118 OS << "\nError running tool:\n ";
119 for (const char **Arg = Args; *Arg; ++Arg)
123 // Rerun the compiler, capturing any error messages to print them.
124 SmallString<128> ErrorFilename;
125 std::error_code EC = sys::fs::createTemporaryFile(
126 "bugpoint.program_error_messages", "", ErrorFilename);
128 errs() << "Error making unique filename: " << EC.message() << "\n";
132 RunProgramWithTimeout(ProgPath, Args, "", ErrorFilename.str(),
133 ErrorFilename.str(), Timeout, MemoryLimit);
134 // FIXME: check return code ?
136 // Print out the error messages generated by CC if possible...
137 std::ifstream ErrorFile(ErrorFilename.c_str());
139 std::copy(std::istreambuf_iterator<char>(ErrorFile),
140 std::istreambuf_iterator<char>(),
141 std::ostreambuf_iterator<char>(OS));
145 sys::fs::remove(ErrorFilename.c_str());
149 //===---------------------------------------------------------------------===//
150 // LLI Implementation of AbstractIntepreter interface
153 class LLI : public AbstractInterpreter {
154 std::string LLIPath; // The path to the LLI executable
155 std::vector<std::string> ToolArgs; // Args to pass to LLI
157 LLI(const std::string &Path, const std::vector<std::string> *Args)
160 if (Args) { ToolArgs = *Args; }
163 int ExecuteProgram(const std::string &Bitcode,
164 const std::vector<std::string> &Args,
165 const std::string &InputFile,
166 const std::string &OutputFile,
168 const std::vector<std::string> &CCArgs,
169 const std::vector<std::string> &SharedLibs =
170 std::vector<std::string>(),
171 unsigned Timeout = 0,
172 unsigned MemoryLimit = 0) override;
176 int LLI::ExecuteProgram(const std::string &Bitcode,
177 const std::vector<std::string> &Args,
178 const std::string &InputFile,
179 const std::string &OutputFile,
181 const std::vector<std::string> &CCArgs,
182 const std::vector<std::string> &SharedLibs,
184 unsigned MemoryLimit) {
185 std::vector<const char*> LLIArgs;
186 LLIArgs.push_back(LLIPath.c_str());
187 LLIArgs.push_back("-force-interpreter=true");
189 for (std::vector<std::string>::const_iterator i = SharedLibs.begin(),
190 e = SharedLibs.end(); i != e; ++i) {
191 LLIArgs.push_back("-load");
192 LLIArgs.push_back((*i).c_str());
195 // Add any extra LLI args.
196 for (unsigned i = 0, e = ToolArgs.size(); i != e; ++i)
197 LLIArgs.push_back(ToolArgs[i].c_str());
199 LLIArgs.push_back(Bitcode.c_str());
200 // Add optional parameters to the running program from Argv
201 for (unsigned i=0, e = Args.size(); i != e; ++i)
202 LLIArgs.push_back(Args[i].c_str());
203 LLIArgs.push_back(nullptr);
205 outs() << "<lli>"; outs().flush();
206 DEBUG(errs() << "\nAbout to run:\t";
207 for (unsigned i=0, e = LLIArgs.size()-1; i != e; ++i)
208 errs() << " " << LLIArgs[i];
211 return RunProgramWithTimeout(LLIPath, &LLIArgs[0],
212 InputFile, OutputFile, OutputFile,
213 Timeout, MemoryLimit, Error);
216 void AbstractInterpreter::anchor() { }
218 #if defined(LLVM_ON_UNIX)
219 const char EXESuffix[] = "";
220 #elif defined (LLVM_ON_WIN32)
221 const char EXESuffix[] = "exe";
224 /// Prepend the path to the program being executed
225 /// to \p ExeName, given the value of argv[0] and the address of main()
226 /// itself. This allows us to find another LLVM tool if it is built in the same
227 /// directory. An empty string is returned on error; note that this function
228 /// just mainpulates the path and doesn't check for executability.
229 /// @brief Find a named executable.
230 static std::string PrependMainExecutablePath(const std::string &ExeName,
233 // Check the directory that the calling program is in. We can do
234 // this if ProgramPath contains at least one / character, indicating that it
235 // is a relative path to the executable itself.
236 std::string Main = sys::fs::getMainExecutable(Argv0, MainAddr);
237 StringRef Result = sys::path::parent_path(Main);
239 if (!Result.empty()) {
240 SmallString<128> Storage = Result;
241 sys::path::append(Storage, ExeName);
242 sys::path::replace_extension(Storage, EXESuffix);
243 return Storage.str();
249 // LLI create method - Try to find the LLI executable
250 AbstractInterpreter *AbstractInterpreter::createLLI(const char *Argv0,
251 std::string &Message,
252 const std::vector<std::string> *ToolArgs) {
253 std::string LLIPath =
254 PrependMainExecutablePath("lli", Argv0, (void *)(intptr_t) & createLLI);
255 if (!LLIPath.empty()) {
256 Message = "Found lli: " + LLIPath + "\n";
257 return new LLI(LLIPath, ToolArgs);
260 Message = "Cannot find `lli' in executable directory!\n";
264 //===---------------------------------------------------------------------===//
265 // Custom compiler command implementation of AbstractIntepreter interface
267 // Allows using a custom command for compiling the bitcode, thus allows, for
268 // example, to compile a bitcode fragment without linking or executing, then
269 // using a custom wrapper script to check for compiler errors.
271 class CustomCompiler : public AbstractInterpreter {
272 std::string CompilerCommand;
273 std::vector<std::string> CompilerArgs;
276 const std::string &CompilerCmd, std::vector<std::string> CompArgs) :
277 CompilerCommand(CompilerCmd), CompilerArgs(CompArgs) {}
279 void compileProgram(const std::string &Bitcode,
281 unsigned Timeout = 0,
282 unsigned MemoryLimit = 0) override;
284 int ExecuteProgram(const std::string &Bitcode,
285 const std::vector<std::string> &Args,
286 const std::string &InputFile,
287 const std::string &OutputFile,
289 const std::vector<std::string> &CCArgs =
290 std::vector<std::string>(),
291 const std::vector<std::string> &SharedLibs =
292 std::vector<std::string>(),
293 unsigned Timeout = 0,
294 unsigned MemoryLimit = 0) override {
295 *Error = "Execution not supported with -compile-custom";
301 void CustomCompiler::compileProgram(const std::string &Bitcode,
304 unsigned MemoryLimit) {
306 std::vector<const char*> ProgramArgs;
307 ProgramArgs.push_back(CompilerCommand.c_str());
309 for (std::size_t i = 0; i < CompilerArgs.size(); ++i)
310 ProgramArgs.push_back(CompilerArgs.at(i).c_str());
311 ProgramArgs.push_back(Bitcode.c_str());
312 ProgramArgs.push_back(nullptr);
314 // Add optional parameters to the running program from Argv
315 for (unsigned i = 0, e = CompilerArgs.size(); i != e; ++i)
316 ProgramArgs.push_back(CompilerArgs[i].c_str());
318 if (RunProgramWithTimeout(CompilerCommand, &ProgramArgs[0],
320 Timeout, MemoryLimit, Error))
321 *Error = ProcessFailure(CompilerCommand, &ProgramArgs[0],
322 Timeout, MemoryLimit);
325 //===---------------------------------------------------------------------===//
326 // Custom execution command implementation of AbstractIntepreter interface
328 // Allows using a custom command for executing the bitcode, thus allows,
329 // for example, to invoke a cross compiler for code generation followed by
330 // a simulator that executes the generated binary.
332 class CustomExecutor : public AbstractInterpreter {
333 std::string ExecutionCommand;
334 std::vector<std::string> ExecutorArgs;
337 const std::string &ExecutionCmd, std::vector<std::string> ExecArgs) :
338 ExecutionCommand(ExecutionCmd), ExecutorArgs(ExecArgs) {}
340 int ExecuteProgram(const std::string &Bitcode,
341 const std::vector<std::string> &Args,
342 const std::string &InputFile,
343 const std::string &OutputFile,
345 const std::vector<std::string> &CCArgs,
346 const std::vector<std::string> &SharedLibs =
347 std::vector<std::string>(),
348 unsigned Timeout = 0,
349 unsigned MemoryLimit = 0) override;
353 int CustomExecutor::ExecuteProgram(const std::string &Bitcode,
354 const std::vector<std::string> &Args,
355 const std::string &InputFile,
356 const std::string &OutputFile,
358 const std::vector<std::string> &CCArgs,
359 const std::vector<std::string> &SharedLibs,
361 unsigned MemoryLimit) {
363 std::vector<const char*> ProgramArgs;
364 ProgramArgs.push_back(ExecutionCommand.c_str());
366 for (std::size_t i = 0; i < ExecutorArgs.size(); ++i)
367 ProgramArgs.push_back(ExecutorArgs.at(i).c_str());
368 ProgramArgs.push_back(Bitcode.c_str());
369 ProgramArgs.push_back(nullptr);
371 // Add optional parameters to the running program from Argv
372 for (unsigned i = 0, e = Args.size(); i != e; ++i)
373 ProgramArgs.push_back(Args[i].c_str());
375 return RunProgramWithTimeout(
377 &ProgramArgs[0], InputFile, OutputFile,
378 OutputFile, Timeout, MemoryLimit, Error);
381 // Tokenize the CommandLine to the command and the args to allow
382 // defining a full command line as the command instead of just the
383 // executed program. We cannot just pass the whole string after the command
384 // as a single argument because then program sees only a single
385 // command line argument (with spaces in it: "foo bar" instead
386 // of "foo" and "bar").
388 // code borrowed from:
389 // http://oopweb.com/CPP/Documents/CPPHOWTO/Volume/C++Programming-HOWTO-7.html
390 static void lexCommand(std::string &Message, const std::string &CommandLine,
391 std::string &CmdPath, std::vector<std::string> &Args) {
393 std::string Command = "";
394 std::string delimiters = " ";
396 std::string::size_type lastPos = CommandLine.find_first_not_of(delimiters, 0);
397 std::string::size_type pos = CommandLine.find_first_of(delimiters, lastPos);
399 while (std::string::npos != pos || std::string::npos != lastPos) {
400 std::string token = CommandLine.substr(lastPos, pos - lastPos);
404 Args.push_back(token);
405 // Skip delimiters. Note the "not_of"
406 lastPos = CommandLine.find_first_not_of(delimiters, pos);
407 // Find next "non-delimiter"
408 pos = CommandLine.find_first_of(delimiters, lastPos);
411 auto Path = sys::findProgramByName(Command);
414 std::string("Cannot find '") + Command +
415 "' in PATH: " + Path.getError().message() + "\n";
420 Message = "Found command in: " + CmdPath + "\n";
423 // Custom execution environment create method, takes the execution command
425 AbstractInterpreter *AbstractInterpreter::createCustomCompiler(
426 std::string &Message,
427 const std::string &CompileCommandLine) {
430 std::vector<std::string> Args;
431 lexCommand(Message, CompileCommandLine, CmdPath, Args);
435 return new CustomCompiler(CmdPath, Args);
438 // Custom execution environment create method, takes the execution command
440 AbstractInterpreter *AbstractInterpreter::createCustomExecutor(
441 std::string &Message,
442 const std::string &ExecCommandLine) {
446 std::vector<std::string> Args;
447 lexCommand(Message, ExecCommandLine, CmdPath, Args);
451 return new CustomExecutor(CmdPath, Args);
454 //===----------------------------------------------------------------------===//
455 // LLC Implementation of AbstractIntepreter interface
457 CC::FileType LLC::OutputCode(const std::string &Bitcode,
458 std::string &OutputAsmFile, std::string &Error,
459 unsigned Timeout, unsigned MemoryLimit) {
460 const char *Suffix = (UseIntegratedAssembler ? ".llc.o" : ".llc.s");
462 SmallString<128> UniqueFile;
464 sys::fs::createUniqueFile(Bitcode + "-%%%%%%%" + Suffix, UniqueFile);
466 errs() << "Error making unique filename: " << EC.message() << "\n";
469 OutputAsmFile = UniqueFile.str();
470 std::vector<const char *> LLCArgs;
471 LLCArgs.push_back(LLCPath.c_str());
473 // Add any extra LLC args.
474 for (unsigned i = 0, e = ToolArgs.size(); i != e; ++i)
475 LLCArgs.push_back(ToolArgs[i].c_str());
477 LLCArgs.push_back("-o");
478 LLCArgs.push_back(OutputAsmFile.c_str()); // Output to the Asm file
479 LLCArgs.push_back(Bitcode.c_str()); // This is the input bitcode
481 if (UseIntegratedAssembler)
482 LLCArgs.push_back("-filetype=obj");
484 LLCArgs.push_back (nullptr);
486 outs() << (UseIntegratedAssembler ? "<llc-ia>" : "<llc>");
488 DEBUG(errs() << "\nAbout to run:\t";
489 for (unsigned i = 0, e = LLCArgs.size()-1; i != e; ++i)
490 errs() << " " << LLCArgs[i];
493 if (RunProgramWithTimeout(LLCPath, &LLCArgs[0],
495 Timeout, MemoryLimit))
496 Error = ProcessFailure(LLCPath, &LLCArgs[0],
497 Timeout, MemoryLimit);
498 return UseIntegratedAssembler ? CC::ObjectFile : CC::AsmFile;
501 void LLC::compileProgram(const std::string &Bitcode, std::string *Error,
502 unsigned Timeout, unsigned MemoryLimit) {
503 std::string OutputAsmFile;
504 OutputCode(Bitcode, OutputAsmFile, *Error, Timeout, MemoryLimit);
505 sys::fs::remove(OutputAsmFile);
508 int LLC::ExecuteProgram(const std::string &Bitcode,
509 const std::vector<std::string> &Args,
510 const std::string &InputFile,
511 const std::string &OutputFile,
513 const std::vector<std::string> &ArgsForCC,
514 const std::vector<std::string> &SharedLibs,
516 unsigned MemoryLimit) {
518 std::string OutputAsmFile;
519 CC::FileType FileKind = OutputCode(Bitcode, OutputAsmFile, *Error, Timeout,
521 FileRemover OutFileRemover(OutputAsmFile, !SaveTemps);
523 std::vector<std::string> CCArgs(ArgsForCC);
524 CCArgs.insert(CCArgs.end(), SharedLibs.begin(), SharedLibs.end());
526 // Assuming LLC worked, compile the result with CC and run it.
527 return cc->ExecuteProgram(OutputAsmFile, Args, FileKind,
528 InputFile, OutputFile, Error, CCArgs,
529 Timeout, MemoryLimit);
532 /// createLLC - Try to find the LLC executable
534 LLC *AbstractInterpreter::createLLC(const char *Argv0,
535 std::string &Message,
536 const std::string &CCBinary,
537 const std::vector<std::string> *Args,
538 const std::vector<std::string> *CCArgs,
539 bool UseIntegratedAssembler) {
540 std::string LLCPath =
541 PrependMainExecutablePath("llc", Argv0, (void *)(intptr_t) & createLLC);
542 if (LLCPath.empty()) {
543 Message = "Cannot find `llc' in executable directory!\n";
547 CC *cc = CC::create(Message, CCBinary, CCArgs);
549 errs() << Message << "\n";
552 Message = "Found llc: " + LLCPath + "\n";
553 return new LLC(LLCPath, cc, Args, UseIntegratedAssembler);
556 //===---------------------------------------------------------------------===//
557 // JIT Implementation of AbstractIntepreter interface
560 class JIT : public AbstractInterpreter {
561 std::string LLIPath; // The path to the LLI executable
562 std::vector<std::string> ToolArgs; // Args to pass to LLI
564 JIT(const std::string &Path, const std::vector<std::string> *Args)
567 if (Args) { ToolArgs = *Args; }
570 int ExecuteProgram(const std::string &Bitcode,
571 const std::vector<std::string> &Args,
572 const std::string &InputFile,
573 const std::string &OutputFile,
575 const std::vector<std::string> &CCArgs =
576 std::vector<std::string>(),
577 const std::vector<std::string> &SharedLibs =
578 std::vector<std::string>(),
579 unsigned Timeout = 0,
580 unsigned MemoryLimit = 0) override;
584 int JIT::ExecuteProgram(const std::string &Bitcode,
585 const std::vector<std::string> &Args,
586 const std::string &InputFile,
587 const std::string &OutputFile,
589 const std::vector<std::string> &CCArgs,
590 const std::vector<std::string> &SharedLibs,
592 unsigned MemoryLimit) {
593 // Construct a vector of parameters, incorporating those from the command-line
594 std::vector<const char*> JITArgs;
595 JITArgs.push_back(LLIPath.c_str());
596 JITArgs.push_back("-force-interpreter=false");
598 // Add any extra LLI args.
599 for (unsigned i = 0, e = ToolArgs.size(); i != e; ++i)
600 JITArgs.push_back(ToolArgs[i].c_str());
602 for (unsigned i = 0, e = SharedLibs.size(); i != e; ++i) {
603 JITArgs.push_back("-load");
604 JITArgs.push_back(SharedLibs[i].c_str());
606 JITArgs.push_back(Bitcode.c_str());
607 // Add optional parameters to the running program from Argv
608 for (unsigned i=0, e = Args.size(); i != e; ++i)
609 JITArgs.push_back(Args[i].c_str());
610 JITArgs.push_back(nullptr);
612 outs() << "<jit>"; outs().flush();
613 DEBUG(errs() << "\nAbout to run:\t";
614 for (unsigned i=0, e = JITArgs.size()-1; i != e; ++i)
615 errs() << " " << JITArgs[i];
618 DEBUG(errs() << "\nSending output to " << OutputFile << "\n");
619 return RunProgramWithTimeout(LLIPath, &JITArgs[0],
620 InputFile, OutputFile, OutputFile,
621 Timeout, MemoryLimit, Error);
624 /// createJIT - Try to find the LLI executable
626 AbstractInterpreter *AbstractInterpreter::createJIT(const char *Argv0,
627 std::string &Message, const std::vector<std::string> *Args) {
628 std::string LLIPath =
629 PrependMainExecutablePath("lli", Argv0, (void *)(intptr_t) & createJIT);
630 if (!LLIPath.empty()) {
631 Message = "Found lli: " + LLIPath + "\n";
632 return new JIT(LLIPath, Args);
635 Message = "Cannot find `lli' in executable directory!\n";
639 //===---------------------------------------------------------------------===//
643 static bool IsARMArchitecture(std::vector<const char*> Args) {
644 for (std::vector<const char*>::const_iterator
645 I = Args.begin(), E = Args.end(); I != E; ++I) {
646 if (StringRef(*I).equals_lower("-arch")) {
648 if (I != E && StringRef(*I).startswith_lower("arm"))
656 int CC::ExecuteProgram(const std::string &ProgramFile,
657 const std::vector<std::string> &Args,
659 const std::string &InputFile,
660 const std::string &OutputFile,
662 const std::vector<std::string> &ArgsForCC,
664 unsigned MemoryLimit) {
665 std::vector<const char*> CCArgs;
667 CCArgs.push_back(CCPath.c_str());
669 if (TargetTriple.getArch() == Triple::x86)
670 CCArgs.push_back("-m32");
672 for (std::vector<std::string>::const_iterator
673 I = ccArgs.begin(), E = ccArgs.end(); I != E; ++I)
674 CCArgs.push_back(I->c_str());
676 // Specify -x explicitly in case the extension is wonky
677 if (fileType != ObjectFile) {
678 CCArgs.push_back("-x");
679 if (fileType == CFile) {
680 CCArgs.push_back("c");
681 CCArgs.push_back("-fno-strict-aliasing");
683 CCArgs.push_back("assembler");
685 // For ARM architectures we don't want this flag. bugpoint isn't
686 // explicitly told what architecture it is working on, so we get
688 if (TargetTriple.isOSDarwin() && !IsARMArchitecture(CCArgs))
689 CCArgs.push_back("-force_cpusubtype_ALL");
693 CCArgs.push_back(ProgramFile.c_str()); // Specify the input filename.
695 CCArgs.push_back("-x");
696 CCArgs.push_back("none");
697 CCArgs.push_back("-o");
699 SmallString<128> OutputBinary;
701 sys::fs::createUniqueFile(ProgramFile + "-%%%%%%%.cc.exe", OutputBinary);
703 errs() << "Error making unique filename: " << EC.message() << "\n";
706 CCArgs.push_back(OutputBinary.c_str()); // Output to the right file...
708 // Add any arguments intended for CC. We locate them here because this is
709 // most likely -L and -l options that need to come before other libraries but
710 // after the source. Other options won't be sensitive to placement on the
711 // command line, so this should be safe.
712 for (unsigned i = 0, e = ArgsForCC.size(); i != e; ++i)
713 CCArgs.push_back(ArgsForCC[i].c_str());
715 CCArgs.push_back("-lm"); // Hard-code the math library...
716 CCArgs.push_back("-O2"); // Optimize the program a bit...
717 #if defined (HAVE_LINK_R)
718 CCArgs.push_back("-Wl,-R."); // Search this dir for .so files
720 if (TargetTriple.getArch() == Triple::sparc)
721 CCArgs.push_back("-mcpu=v9");
722 CCArgs.push_back(nullptr); // NULL terminator
724 outs() << "<CC>"; outs().flush();
725 DEBUG(errs() << "\nAbout to run:\t";
726 for (unsigned i = 0, e = CCArgs.size()-1; i != e; ++i)
727 errs() << " " << CCArgs[i];
730 if (RunProgramWithTimeout(CCPath, &CCArgs[0], "", "", "")) {
731 *Error = ProcessFailure(CCPath, &CCArgs[0]);
735 std::vector<const char*> ProgramArgs;
737 // Declared here so that the destructor only runs after
738 // ProgramArgs is used.
741 if (RemoteClientPath.empty())
742 ProgramArgs.push_back(OutputBinary.c_str());
744 ProgramArgs.push_back(RemoteClientPath.c_str());
745 ProgramArgs.push_back(RemoteHost.c_str());
746 if (!RemoteUser.empty()) {
747 ProgramArgs.push_back("-l");
748 ProgramArgs.push_back(RemoteUser.c_str());
750 if (!RemotePort.empty()) {
751 ProgramArgs.push_back("-p");
752 ProgramArgs.push_back(RemotePort.c_str());
754 if (!RemoteExtra.empty()) {
755 ProgramArgs.push_back(RemoteExtra.c_str());
758 // Full path to the binary. We need to cd to the exec directory because
759 // there is a dylib there that the exec expects to find in the CWD
760 char* env_pwd = getenv("PWD");
764 Exec += OutputBinary.c_str();
765 ProgramArgs.push_back(Exec.c_str());
768 // Add optional parameters to the running program from Argv
769 for (unsigned i = 0, e = Args.size(); i != e; ++i)
770 ProgramArgs.push_back(Args[i].c_str());
771 ProgramArgs.push_back(nullptr); // NULL terminator
773 // Now that we have a binary, run it!
774 outs() << "<program>"; outs().flush();
775 DEBUG(errs() << "\nAbout to run:\t";
776 for (unsigned i = 0, e = ProgramArgs.size()-1; i != e; ++i)
777 errs() << " " << ProgramArgs[i];
781 FileRemover OutputBinaryRemover(OutputBinary.str(), !SaveTemps);
783 if (RemoteClientPath.empty()) {
784 DEBUG(errs() << "<run locally>");
785 int ExitCode = RunProgramWithTimeout(OutputBinary.str(), &ProgramArgs[0],
786 InputFile, OutputFile, OutputFile,
787 Timeout, MemoryLimit, Error);
788 // Treat a signal (usually SIGSEGV) or timeout as part of the program output
789 // so that crash-causing miscompilation is handled seamlessly.
791 std::ofstream outFile(OutputFile.c_str(), std::ios_base::app);
792 outFile << *Error << '\n';
798 outs() << "<run remotely>"; outs().flush();
799 return RunProgramRemotelyWithTimeout(RemoteClientPath,
800 &ProgramArgs[0], InputFile, OutputFile,
801 OutputFile, Timeout, MemoryLimit);
805 int CC::MakeSharedObject(const std::string &InputFile, FileType fileType,
806 std::string &OutputFile,
807 const std::vector<std::string> &ArgsForCC,
808 std::string &Error) {
809 SmallString<128> UniqueFilename;
810 std::error_code EC = sys::fs::createUniqueFile(
811 InputFile + "-%%%%%%%" + LTDL_SHLIB_EXT, UniqueFilename);
813 errs() << "Error making unique filename: " << EC.message() << "\n";
816 OutputFile = UniqueFilename.str();
818 std::vector<const char*> CCArgs;
820 CCArgs.push_back(CCPath.c_str());
822 if (TargetTriple.getArch() == Triple::x86)
823 CCArgs.push_back("-m32");
825 for (std::vector<std::string>::const_iterator
826 I = ccArgs.begin(), E = ccArgs.end(); I != E; ++I)
827 CCArgs.push_back(I->c_str());
829 // Compile the C/asm file into a shared object
830 if (fileType != ObjectFile) {
831 CCArgs.push_back("-x");
832 CCArgs.push_back(fileType == AsmFile ? "assembler" : "c");
834 CCArgs.push_back("-fno-strict-aliasing");
835 CCArgs.push_back(InputFile.c_str()); // Specify the input filename.
836 CCArgs.push_back("-x");
837 CCArgs.push_back("none");
838 if (TargetTriple.getArch() == Triple::sparc)
839 CCArgs.push_back("-G"); // Compile a shared library, `-G' for Sparc
840 else if (TargetTriple.isOSDarwin()) {
841 // link all source files into a single module in data segment, rather than
842 // generating blocks. dynamic_lookup requires that you set
843 // MACOSX_DEPLOYMENT_TARGET=10.3 in your env. FIXME: it would be better for
844 // bugpoint to just pass that in the environment of CC.
845 CCArgs.push_back("-single_module");
846 CCArgs.push_back("-dynamiclib"); // `-dynamiclib' for MacOS X/PowerPC
847 CCArgs.push_back("-undefined");
848 CCArgs.push_back("dynamic_lookup");
850 CCArgs.push_back("-shared"); // `-shared' for Linux/X86, maybe others
852 if (TargetTriple.getArch() == Triple::x86_64)
853 CCArgs.push_back("-fPIC"); // Requires shared objs to contain PIC
855 if (TargetTriple.getArch() == Triple::sparc)
856 CCArgs.push_back("-mcpu=v9");
858 CCArgs.push_back("-o");
859 CCArgs.push_back(OutputFile.c_str()); // Output to the right filename.
860 CCArgs.push_back("-O2"); // Optimize the program a bit.
864 // Add any arguments intended for CC. We locate them here because this is
865 // most likely -L and -l options that need to come before other libraries but
866 // after the source. Other options won't be sensitive to placement on the
867 // command line, so this should be safe.
868 for (unsigned i = 0, e = ArgsForCC.size(); i != e; ++i)
869 CCArgs.push_back(ArgsForCC[i].c_str());
870 CCArgs.push_back(nullptr); // NULL terminator
874 outs() << "<CC>"; outs().flush();
875 DEBUG(errs() << "\nAbout to run:\t";
876 for (unsigned i = 0, e = CCArgs.size()-1; i != e; ++i)
877 errs() << " " << CCArgs[i];
880 if (RunProgramWithTimeout(CCPath, &CCArgs[0], "", "", "")) {
881 Error = ProcessFailure(CCPath, &CCArgs[0]);
887 /// create - Try to find the CC executable
889 CC *CC::create(std::string &Message,
890 const std::string &CCBinary,
891 const std::vector<std::string> *Args) {
892 auto CCPath = sys::findProgramByName(CCBinary);
894 Message = "Cannot find `" + CCBinary + "' in PATH: " +
895 CCPath.getError().message() + "\n";
899 std::string RemoteClientPath;
900 if (!RemoteClient.empty()) {
901 auto Path = sys::findProgramByName(RemoteClient);
903 Message = "Cannot find `" + RemoteClient + "' in PATH: " +
904 Path.getError().message() + "\n";
907 RemoteClientPath = *Path;
910 Message = "Found CC: " + *CCPath + "\n";
911 return new CC(*CCPath, RemoteClientPath, Args);