1 //===- ExecutionDriver.cpp - Allow execution of LLVM program --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains code used to execute the program utilizing one of the
11 // various ways of running LLVM bitcode.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "BugDriver.h"
16 #include "ToolRunner.h"
17 #include "llvm/Support/CommandLine.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Support/FileUtilities.h"
20 #include "llvm/Support/Program.h"
21 #include "llvm/Support/SystemUtils.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include <fstream>
24 
25 using namespace llvm;
26 
27 namespace {
28 // OutputType - Allow the user to specify the way code should be run, to test
29 // for miscompilation.
30 //
31 enum OutputType {
32   AutoPick,
33   RunLLI,
34   RunJIT,
35   RunLLC,
36   RunLLCIA,
37   LLC_Safe,
38   CompileCustom,
39   Custom
40 };
41 
42 cl::opt<double> AbsTolerance("abs-tolerance",
43                              cl::desc("Absolute error tolerated"),
44                              cl::init(0.0));
45 cl::opt<double> RelTolerance("rel-tolerance",
46                              cl::desc("Relative error tolerated"),
47                              cl::init(0.0));
48 
49 cl::opt<OutputType> InterpreterSel(
50     cl::desc("Specify the \"test\" i.e. suspect back-end:"),
51     cl::values(clEnumValN(AutoPick, "auto", "Use best guess"),
52                clEnumValN(RunLLI, "run-int", "Execute with the interpreter"),
53                clEnumValN(RunJIT, "run-jit", "Execute with JIT"),
54                clEnumValN(RunLLC, "run-llc", "Compile with LLC"),
55                clEnumValN(RunLLCIA, "run-llc-ia",
56                           "Compile with LLC with integrated assembler"),
57                clEnumValN(LLC_Safe, "llc-safe", "Use LLC for all"),
58                clEnumValN(CompileCustom, "compile-custom",
59                           "Use -compile-command to define a command to "
60                           "compile the bitcode. Useful to avoid linking."),
61                clEnumValN(Custom, "run-custom",
62                           "Use -exec-command to define a command to execute "
63                           "the bitcode. Useful for cross-compilation."),
64                clEnumValEnd),
65     cl::init(AutoPick));
66 
67 cl::opt<OutputType> SafeInterpreterSel(
68     cl::desc("Specify \"safe\" i.e. known-good backend:"),
69     cl::values(clEnumValN(AutoPick, "safe-auto", "Use best guess"),
70                clEnumValN(RunLLC, "safe-run-llc", "Compile with LLC"),
71                clEnumValN(Custom, "safe-run-custom",
72                           "Use -exec-command to define a command to execute "
73                           "the bitcode. Useful for cross-compilation."),
74                clEnumValEnd),
75     cl::init(AutoPick));
76 
77 cl::opt<std::string> SafeInterpreterPath(
78     "safe-path", cl::desc("Specify the path to the \"safe\" backend program"),
79     cl::init(""));
80 
81 cl::opt<bool> AppendProgramExitCode(
82     "append-exit-code",
83     cl::desc("Append the exit code to the output so it gets diff'd too"),
84     cl::init(false));
85 
86 cl::opt<std::string>
87     InputFile("input", cl::init("/dev/null"),
88               cl::desc("Filename to pipe in as stdin (default: /dev/null)"));
89 
90 cl::list<std::string>
91     AdditionalSOs("additional-so", cl::desc("Additional shared objects to load "
92                                             "into executing programs"));
93 
94 cl::list<std::string> AdditionalLinkerArgs(
95     "Xlinker", cl::desc("Additional arguments to pass to the linker"));
96 
97 cl::opt<std::string> CustomCompileCommand(
98     "compile-command", cl::init("llc"),
99     cl::desc("Command to compile the bitcode (use with -compile-custom) "
100              "(default: llc)"));
101 
102 cl::opt<std::string> CustomExecCommand(
103     "exec-command", cl::init("simulate"),
104     cl::desc("Command to execute the bitcode (use with -run-custom) "
105              "(default: simulate)"));
106 }
107 
108 namespace llvm {
109 // Anything specified after the --args option are taken as arguments to the
110 // program being debugged.
111 cl::list<std::string> InputArgv("args", cl::Positional,
112                                 cl::desc("<program arguments>..."),
113                                 cl::ZeroOrMore, cl::PositionalEatsArgs);
114 
115 cl::opt<std::string>
116     OutputPrefix("output-prefix", cl::init("bugpoint"),
117                  cl::desc("Prefix to use for outputs (default: 'bugpoint')"));
118 }
119 
120 namespace {
121 cl::list<std::string> ToolArgv("tool-args", cl::Positional,
122                                cl::desc("<tool arguments>..."), cl::ZeroOrMore,
123                                cl::PositionalEatsArgs);
124 
125 cl::list<std::string> SafeToolArgv("safe-tool-args", cl::Positional,
126                                    cl::desc("<safe-tool arguments>..."),
127                                    cl::ZeroOrMore, cl::PositionalEatsArgs);
128 
129 cl::opt<std::string> CCBinary("gcc", cl::init(""),
130                               cl::desc("The gcc binary to use."));
131 
132 cl::list<std::string> CCToolArgv("gcc-tool-args", cl::Positional,
133                                  cl::desc("<gcc-tool arguments>..."),
134                                  cl::ZeroOrMore, cl::PositionalEatsArgs);
135 }
136 
137 //===----------------------------------------------------------------------===//
138 // BugDriver method implementation
139 //
140 
141 /// initializeExecutionEnvironment - This method is used to set up the
142 /// environment for executing LLVM programs.
143 ///
144 Error BugDriver::initializeExecutionEnvironment() {
145   outs() << "Initializing execution environment: ";
146 
147   // Create an instance of the AbstractInterpreter interface as specified on
148   // the command line
149   SafeInterpreter = nullptr;
150   std::string Message;
151 
152   if (CCBinary.empty()) {
153     if (sys::findProgramByName("clang"))
154       CCBinary = "clang";
155     else
156       CCBinary = "gcc";
157   }
158 
159   switch (InterpreterSel) {
160   case AutoPick:
161     if (!Interpreter) {
162       InterpreterSel = RunJIT;
163       Interpreter =
164           AbstractInterpreter::createJIT(getToolName(), Message, &ToolArgv);
165     }
166     if (!Interpreter) {
167       InterpreterSel = RunLLC;
168       Interpreter = AbstractInterpreter::createLLC(
169           getToolName(), Message, CCBinary, &ToolArgv, &CCToolArgv);
170     }
171     if (!Interpreter) {
172       InterpreterSel = RunLLI;
173       Interpreter =
174           AbstractInterpreter::createLLI(getToolName(), Message, &ToolArgv);
175     }
176     if (!Interpreter) {
177       InterpreterSel = AutoPick;
178       Message = "Sorry, I can't automatically select an interpreter!\n";
179     }
180     break;
181   case RunLLI:
182     Interpreter =
183         AbstractInterpreter::createLLI(getToolName(), Message, &ToolArgv);
184     break;
185   case RunLLC:
186   case RunLLCIA:
187   case LLC_Safe:
188     Interpreter = AbstractInterpreter::createLLC(
189         getToolName(), Message, CCBinary, &ToolArgv, &CCToolArgv,
190         InterpreterSel == RunLLCIA);
191     break;
192   case RunJIT:
193     Interpreter =
194         AbstractInterpreter::createJIT(getToolName(), Message, &ToolArgv);
195     break;
196   case CompileCustom:
197     Interpreter = AbstractInterpreter::createCustomCompiler(
198         Message, CustomCompileCommand);
199     break;
200   case Custom:
201     Interpreter =
202         AbstractInterpreter::createCustomExecutor(Message, CustomExecCommand);
203     break;
204   }
205   if (!Interpreter)
206     errs() << Message;
207   else // Display informational messages on stdout instead of stderr
208     outs() << Message;
209 
210   std::string Path = SafeInterpreterPath;
211   if (Path.empty())
212     Path = getToolName();
213   std::vector<std::string> SafeToolArgs = SafeToolArgv;
214   switch (SafeInterpreterSel) {
215   case AutoPick:
216     // In "llc-safe" mode, default to using LLC as the "safe" backend.
217     if (!SafeInterpreter && InterpreterSel == LLC_Safe) {
218       SafeInterpreterSel = RunLLC;
219       SafeToolArgs.push_back("--relocation-model=pic");
220       SafeInterpreter = AbstractInterpreter::createLLC(
221           Path.c_str(), Message, CCBinary, &SafeToolArgs, &CCToolArgv);
222     }
223 
224     if (!SafeInterpreter && InterpreterSel != RunLLC &&
225         InterpreterSel != RunJIT) {
226       SafeInterpreterSel = RunLLC;
227       SafeToolArgs.push_back("--relocation-model=pic");
228       SafeInterpreter = AbstractInterpreter::createLLC(
229           Path.c_str(), Message, CCBinary, &SafeToolArgs, &CCToolArgv);
230     }
231     if (!SafeInterpreter) {
232       SafeInterpreterSel = AutoPick;
233       Message = "Sorry, I can't automatically select a safe interpreter!\n";
234     }
235     break;
236   case RunLLC:
237   case RunLLCIA:
238     SafeToolArgs.push_back("--relocation-model=pic");
239     SafeInterpreter = AbstractInterpreter::createLLC(
240         Path.c_str(), Message, CCBinary, &SafeToolArgs, &CCToolArgv,
241         SafeInterpreterSel == RunLLCIA);
242     break;
243   case Custom:
244     SafeInterpreter =
245         AbstractInterpreter::createCustomExecutor(Message, CustomExecCommand);
246     break;
247   default:
248     Message = "Sorry, this back-end is not supported by bugpoint as the "
249               "\"safe\" backend right now!\n";
250     break;
251   }
252   if (!SafeInterpreter) {
253     outs() << Message << "\nExiting.\n";
254     exit(1);
255   }
256 
257   cc = CC::create(Message, CCBinary, &CCToolArgv);
258   if (!cc) {
259     outs() << Message << "\nExiting.\n";
260     exit(1);
261   }
262 
263   // If there was an error creating the selected interpreter, quit with error.
264   if (Interpreter == nullptr)
265     return make_error<StringError>("Failed to init execution environment",
266                                    inconvertibleErrorCode());
267   return Error::success();
268 }
269 
270 /// compileProgram - Try to compile the specified module, returning false and
271 /// setting Error if an error occurs.  This is used for code generation
272 /// crash testing.
273 ///
274 Error BugDriver::compileProgram(Module *M) const {
275   // Emit the program to a bitcode file...
276   SmallString<128> BitcodeFile;
277   int BitcodeFD;
278   std::error_code EC = sys::fs::createUniqueFile(
279       OutputPrefix + "-test-program-%%%%%%%.bc", BitcodeFD, BitcodeFile);
280   if (EC) {
281     errs() << ToolName << ": Error making unique filename: " << EC.message()
282            << "\n";
283     exit(1);
284   }
285   if (writeProgramToFile(BitcodeFile.str(), BitcodeFD, M)) {
286     errs() << ToolName << ": Error emitting bitcode to file '" << BitcodeFile
287            << "'!\n";
288     exit(1);
289   }
290 
291   // Remove the temporary bitcode file when we are done.
292   FileRemover BitcodeFileRemover(BitcodeFile.str(), !SaveTemps);
293 
294   // Actually compile the program!
295   return Interpreter->compileProgram(BitcodeFile.str(), Timeout, MemoryLimit);
296 }
297 
298 /// executeProgram - This method runs "Program", capturing the output of the
299 /// program to a file, returning the filename of the file.  A recommended
300 /// filename may be optionally specified.
301 ///
302 Expected<std::string> BugDriver::executeProgram(const Module *Program,
303                                                 std::string OutputFile,
304                                                 std::string BitcodeFile,
305                                                 const std::string &SharedObj,
306                                                 AbstractInterpreter *AI) const {
307   if (!AI)
308     AI = Interpreter;
309   assert(AI && "Interpreter should have been created already!");
310   bool CreatedBitcode = false;
311   if (BitcodeFile.empty()) {
312     // Emit the program to a bitcode file...
313     SmallString<128> UniqueFilename;
314     int UniqueFD;
315     std::error_code EC = sys::fs::createUniqueFile(
316         OutputPrefix + "-test-program-%%%%%%%.bc", UniqueFD, UniqueFilename);
317     if (EC) {
318       errs() << ToolName << ": Error making unique filename: " << EC.message()
319              << "!\n";
320       exit(1);
321     }
322     BitcodeFile = UniqueFilename.str();
323 
324     if (writeProgramToFile(BitcodeFile, UniqueFD, Program)) {
325       errs() << ToolName << ": Error emitting bitcode to file '" << BitcodeFile
326              << "'!\n";
327       exit(1);
328     }
329     CreatedBitcode = true;
330   }
331 
332   // Remove the temporary bitcode file when we are done.
333   std::string BitcodePath(BitcodeFile);
334   FileRemover BitcodeFileRemover(BitcodePath, CreatedBitcode && !SaveTemps);
335 
336   if (OutputFile.empty())
337     OutputFile = OutputPrefix + "-execution-output-%%%%%%%";
338 
339   // Check to see if this is a valid output filename...
340   SmallString<128> UniqueFile;
341   std::error_code EC = sys::fs::createUniqueFile(OutputFile, UniqueFile);
342   if (EC) {
343     errs() << ToolName << ": Error making unique filename: " << EC.message()
344            << "\n";
345     exit(1);
346   }
347   OutputFile = UniqueFile.str();
348 
349   // Figure out which shared objects to run, if any.
350   std::vector<std::string> SharedObjs(AdditionalSOs);
351   if (!SharedObj.empty())
352     SharedObjs.push_back(SharedObj);
353 
354   Expected<int> RetVal = AI->ExecuteProgram(BitcodeFile, InputArgv, InputFile,
355                                             OutputFile, AdditionalLinkerArgs,
356                                             SharedObjs, Timeout, MemoryLimit);
357   if (Error E = RetVal.takeError())
358     return std::move(E);
359 
360   if (*RetVal == -1) {
361     errs() << "<timeout>";
362     static bool FirstTimeout = true;
363     if (FirstTimeout) {
364       outs()
365           << "\n"
366              "*** Program execution timed out!  This mechanism is designed to "
367              "handle\n"
368              "    programs stuck in infinite loops gracefully.  The -timeout "
369              "option\n"
370              "    can be used to change the timeout threshold or disable it "
371              "completely\n"
372              "    (with -timeout=0).  This message is only displayed once.\n";
373       FirstTimeout = false;
374     }
375   }
376 
377   if (AppendProgramExitCode) {
378     std::ofstream outFile(OutputFile.c_str(), std::ios_base::app);
379     outFile << "exit " << *RetVal << '\n';
380     outFile.close();
381   }
382 
383   // Return the filename we captured the output to.
384   return OutputFile;
385 }
386 
387 /// executeProgramSafely - Used to create reference output with the "safe"
388 /// backend, if reference output is not provided.
389 ///
390 Expected<std::string>
391 BugDriver::executeProgramSafely(const Module *Program,
392                                 const std::string &OutputFile) const {
393   return executeProgram(Program, OutputFile, "", "", SafeInterpreter);
394 }
395 
396 Expected<std::string>
397 BugDriver::compileSharedObject(const std::string &BitcodeFile) {
398   assert(Interpreter && "Interpreter should have been created already!");
399   std::string OutputFile;
400 
401   // Using the known-good backend.
402   Expected<CC::FileType> FT =
403       SafeInterpreter->OutputCode(BitcodeFile, OutputFile);
404   if (Error E = FT.takeError())
405     return std::move(E);
406 
407   std::string SharedObjectFile;
408   if (Error E = cc->MakeSharedObject(OutputFile, *FT, SharedObjectFile,
409                                      AdditionalLinkerArgs))
410     return std::move(E);
411 
412   // Remove the intermediate C file
413   sys::fs::remove(OutputFile);
414 
415   return SharedObjectFile;
416 }
417 
418 /// createReferenceFile - calls compileProgram and then records the output
419 /// into ReferenceOutputFile. Returns true if reference file created, false
420 /// otherwise. Note: initializeExecutionEnvironment should be called BEFORE
421 /// this function.
422 ///
423 Error BugDriver::createReferenceFile(Module *M, const std::string &Filename) {
424   if (Error E = compileProgram(Program))
425     return E;
426 
427   Expected<std::string> Result = executeProgramSafely(Program, Filename);
428   if (Error E = Result.takeError()) {
429     if (Interpreter != SafeInterpreter) {
430       E = joinErrors(
431               std::move(E),
432               make_error<StringError>(
433                   "*** There is a bug running the \"safe\" backend.  Either"
434                   " debug it (for example with the -run-jit bugpoint option,"
435                   " if JIT is being used as the \"safe\" backend), or fix the"
436                   " error some other way.\n",
437                   inconvertibleErrorCode()));
438     }
439     return E;
440   }
441   ReferenceOutputFile = *Result;
442   outs() << "\nReference output is: " << ReferenceOutputFile << "\n\n";
443   return Error::success();
444 }
445 
446 /// diffProgram - This method executes the specified module and diffs the
447 /// output against the file specified by ReferenceOutputFile.  If the output
448 /// is different, 1 is returned.  If there is a problem with the code
449 /// generator (e.g., llc crashes), this will set ErrMsg.
450 ///
451 Expected<bool> BugDriver::diffProgram(const Module *Program,
452                                       const std::string &BitcodeFile,
453                                       const std::string &SharedObject,
454                                       bool RemoveBitcode) const {
455   // Execute the program, generating an output file...
456   Expected<std::string> Output =
457       executeProgram(Program, "", BitcodeFile, SharedObject, nullptr);
458   if (Error E = Output.takeError())
459     return std::move(E);
460 
461   std::string Error;
462   bool FilesDifferent = false;
463   if (int Diff = DiffFilesWithTolerance(ReferenceOutputFile, *Output,
464                                         AbsTolerance, RelTolerance, &Error)) {
465     if (Diff == 2) {
466       errs() << "While diffing output: " << Error << '\n';
467       exit(1);
468     }
469     FilesDifferent = true;
470   } else {
471     // Remove the generated output if there are no differences.
472     sys::fs::remove(*Output);
473   }
474 
475   // Remove the bitcode file if we are supposed to.
476   if (RemoveBitcode)
477     sys::fs::remove(BitcodeFile);
478   return FilesDifferent;
479 }
480 
481 bool BugDriver::isExecutingJIT() { return InterpreterSel == RunJIT; }
482