1 //===--- Job.cpp - Command to Execute -------------------------------------===// 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 #include "clang/Driver/Job.h" 11 #include "InputInfo.h" 12 #include "clang/Driver/Driver.h" 13 #include "clang/Driver/DriverDiagnostic.h" 14 #include "clang/Driver/Tool.h" 15 #include "clang/Driver/ToolChain.h" 16 #include "llvm/ADT/ArrayRef.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/ADT/SmallString.h" 19 #include "llvm/ADT/StringRef.h" 20 #include "llvm/ADT/StringSet.h" 21 #include "llvm/ADT/StringSwitch.h" 22 #include "llvm/Support/FileSystem.h" 23 #include "llvm/Support/Path.h" 24 #include "llvm/Support/Program.h" 25 #include "llvm/Support/raw_ostream.h" 26 #include <cassert> 27 using namespace clang::driver; 28 using llvm::raw_ostream; 29 using llvm::StringRef; 30 using llvm::ArrayRef; 31 32 Command::Command(const Action &Source, const Tool &Creator, 33 const char *Executable, const ArgStringList &Arguments, 34 ArrayRef<InputInfo> Inputs) 35 : Source(Source), Creator(Creator), Executable(Executable), 36 Arguments(Arguments), ResponseFile(nullptr) { 37 for (const auto &II : Inputs) 38 if (II.isFilename()) 39 InputFilenames.push_back(II.getFilename()); 40 } 41 42 /// @brief Check if the compiler flag in question should be skipped when 43 /// emitting a reproducer. Also track how many arguments it has and if the 44 /// option is some kind of include path. 45 static bool skipArgs(const char *Flag, bool HaveCrashVFS, int &SkipNum, 46 bool &IsInclude) { 47 SkipNum = 2; 48 // These flags are all of the form -Flag <Arg> and are treated as two 49 // arguments. Therefore, we need to skip the flag and the next argument. 50 bool ShouldSkip = llvm::StringSwitch<bool>(Flag) 51 .Cases("-MF", "-MT", "-MQ", "-serialize-diagnostic-file", true) 52 .Cases("-o", "-coverage-file", "-dependency-file", true) 53 .Cases("-fdebug-compilation-dir", "-include-pch", true) 54 .Cases("-dwarf-debug-flags", "-ivfsoverlay", true) 55 .Case("-diagnostic-log-file", true) 56 .Default(false); 57 if (ShouldSkip) 58 return true; 59 60 // Some include flags shouldn't be skipped if we have a crash VFS 61 IsInclude = llvm::StringSwitch<bool>(Flag) 62 .Cases("-include", "-header-include-file", true) 63 .Cases("-idirafter", "-internal-isystem", "-iwithprefix", true) 64 .Cases("-internal-externc-isystem", "-iprefix", true) 65 .Cases("-iwithprefixbefore", "-isystem", "-iquote", true) 66 .Cases("-isysroot", "-I", "-F", "-resource-dir", true) 67 .Case("-iframework", true) 68 .Default(false); 69 if (IsInclude) 70 return HaveCrashVFS ? false : true; 71 72 // The remaining flags are treated as a single argument. 73 74 // These flags are all of the form -Flag and have no second argument. 75 ShouldSkip = llvm::StringSwitch<bool>(Flag) 76 .Cases("-M", "-MM", "-MG", "-MP", "-MD", true) 77 .Case("-MMD", true) 78 .Default(false); 79 80 // Match found. 81 SkipNum = 1; 82 if (ShouldSkip) 83 return true; 84 85 // These flags are treated as a single argument (e.g., -F<Dir>). 86 StringRef FlagRef(Flag); 87 IsInclude = FlagRef.startswith("-F") || FlagRef.startswith("-I"); 88 if (IsInclude) 89 return HaveCrashVFS ? false : true; 90 if (FlagRef.startswith("-fmodules-cache-path=")) 91 return true; 92 93 SkipNum = 0; 94 return false; 95 } 96 97 void Command::printArg(raw_ostream &OS, StringRef Arg, bool Quote) { 98 const bool Escape = Arg.find_first_of("\"\\$") != StringRef::npos; 99 100 if (!Quote && !Escape) { 101 OS << Arg; 102 return; 103 } 104 105 // Quote and escape. This isn't really complete, but good enough. 106 OS << '"'; 107 for (const char c : Arg) { 108 if (c == '"' || c == '\\' || c == '$') 109 OS << '\\'; 110 OS << c; 111 } 112 OS << '"'; 113 } 114 115 void Command::writeResponseFile(raw_ostream &OS) const { 116 // In a file list, we only write the set of inputs to the response file 117 if (Creator.getResponseFilesSupport() == Tool::RF_FileList) { 118 for (const char *Arg : InputFileList) { 119 OS << Arg << '\n'; 120 } 121 return; 122 } 123 124 // In regular response files, we send all arguments to the response file. 125 // Wrapping all arguments in double quotes ensures that both Unix tools and 126 // Windows tools understand the response file. 127 for (const char *Arg : Arguments) { 128 OS << '"'; 129 130 for (; *Arg != '\0'; Arg++) { 131 if (*Arg == '\"' || *Arg == '\\') { 132 OS << '\\'; 133 } 134 OS << *Arg; 135 } 136 137 OS << "\" "; 138 } 139 } 140 141 void Command::buildArgvForResponseFile( 142 llvm::SmallVectorImpl<const char *> &Out) const { 143 // When not a file list, all arguments are sent to the response file. 144 // This leaves us to set the argv to a single parameter, requesting the tool 145 // to read the response file. 146 if (Creator.getResponseFilesSupport() != Tool::RF_FileList) { 147 Out.push_back(Executable); 148 Out.push_back(ResponseFileFlag.c_str()); 149 return; 150 } 151 152 llvm::StringSet<> Inputs; 153 for (const char *InputName : InputFileList) 154 Inputs.insert(InputName); 155 Out.push_back(Executable); 156 // In a file list, build args vector ignoring parameters that will go in the 157 // response file (elements of the InputFileList vector) 158 bool FirstInput = true; 159 for (const char *Arg : Arguments) { 160 if (Inputs.count(Arg) == 0) { 161 Out.push_back(Arg); 162 } else if (FirstInput) { 163 FirstInput = false; 164 Out.push_back(Creator.getResponseFileFlag()); 165 Out.push_back(ResponseFile); 166 } 167 } 168 } 169 170 /// @brief Rewrite relative include-like flag paths to absolute ones. 171 static void 172 rewriteIncludes(const llvm::ArrayRef<const char *> &Args, size_t Idx, 173 size_t NumArgs, 174 llvm::SmallVectorImpl<llvm::SmallString<128>> &IncFlags) { 175 using namespace llvm; 176 using namespace sys; 177 auto getAbsPath = [](StringRef InInc, SmallVectorImpl<char> &OutInc) -> bool { 178 if (path::is_absolute(InInc)) // Nothing to do here... 179 return false; 180 std::error_code EC = fs::current_path(OutInc); 181 if (EC) 182 return false; 183 path::append(OutInc, InInc); 184 return true; 185 }; 186 187 SmallString<128> NewInc; 188 if (NumArgs == 1) { 189 StringRef FlagRef(Args[Idx + NumArgs - 1]); 190 assert((FlagRef.startswith("-F") || FlagRef.startswith("-I")) && 191 "Expecting -I or -F"); 192 StringRef Inc = FlagRef.slice(2, StringRef::npos); 193 if (getAbsPath(Inc, NewInc)) { 194 SmallString<128> NewArg(FlagRef.slice(0, 2)); 195 NewArg += NewInc; 196 IncFlags.push_back(std::move(NewArg)); 197 } 198 return; 199 } 200 201 assert(NumArgs == 2 && "Not expecting more than two arguments"); 202 StringRef Inc(Args[Idx + NumArgs - 1]); 203 if (!getAbsPath(Inc, NewInc)) 204 return; 205 IncFlags.push_back(SmallString<128>(Args[Idx])); 206 IncFlags.push_back(std::move(NewInc)); 207 } 208 209 void Command::Print(raw_ostream &OS, const char *Terminator, bool Quote, 210 CrashReportInfo *CrashInfo) const { 211 // Always quote the exe. 212 OS << ' '; 213 printArg(OS, Executable, /*Quote=*/true); 214 215 llvm::ArrayRef<const char *> Args = Arguments; 216 llvm::SmallVector<const char *, 128> ArgsRespFile; 217 if (ResponseFile != nullptr) { 218 buildArgvForResponseFile(ArgsRespFile); 219 Args = ArrayRef<const char *>(ArgsRespFile).slice(1); // no executable name 220 } 221 222 bool HaveCrashVFS = CrashInfo && !CrashInfo->VFSPath.empty(); 223 for (size_t i = 0, e = Args.size(); i < e; ++i) { 224 const char *const Arg = Args[i]; 225 226 if (CrashInfo) { 227 int NumArgs = 0; 228 bool IsInclude = false; 229 if (skipArgs(Arg, HaveCrashVFS, NumArgs, IsInclude)) { 230 i += NumArgs - 1; 231 continue; 232 } 233 234 // Relative includes need to be expanded to absolute paths. 235 if (HaveCrashVFS && IsInclude) { 236 SmallVector<SmallString<128>, 2> NewIncFlags; 237 rewriteIncludes(Args, i, NumArgs, NewIncFlags); 238 if (!NewIncFlags.empty()) { 239 for (auto &F : NewIncFlags) { 240 OS << ' '; 241 printArg(OS, F.c_str(), Quote); 242 } 243 i += NumArgs - 1; 244 continue; 245 } 246 } 247 248 auto Found = std::find_if(InputFilenames.begin(), InputFilenames.end(), 249 [&Arg](StringRef IF) { return IF == Arg; }); 250 if (Found != InputFilenames.end() && 251 (i == 0 || StringRef(Args[i - 1]) != "-main-file-name")) { 252 // Replace the input file name with the crashinfo's file name. 253 OS << ' '; 254 StringRef ShortName = llvm::sys::path::filename(CrashInfo->Filename); 255 printArg(OS, ShortName.str(), Quote); 256 continue; 257 } 258 } 259 260 OS << ' '; 261 printArg(OS, Arg, Quote); 262 } 263 264 if (CrashInfo && HaveCrashVFS) { 265 OS << ' '; 266 printArg(OS, "-ivfsoverlay", Quote); 267 OS << ' '; 268 printArg(OS, CrashInfo->VFSPath.str(), Quote); 269 270 // The leftover modules from the crash are stored in 271 // <name>.cache/vfs/modules 272 // Leave it untouched for pcm inspection and provide a clean/empty dir 273 // path to contain the future generated module cache: 274 // <name>.cache/vfs/repro-modules 275 SmallString<128> RelModCacheDir = llvm::sys::path::parent_path( 276 llvm::sys::path::parent_path(CrashInfo->VFSPath)); 277 llvm::sys::path::append(RelModCacheDir, "repro-modules"); 278 279 std::string ModCachePath = "-fmodules-cache-path="; 280 ModCachePath.append(RelModCacheDir.c_str()); 281 282 OS << ' '; 283 printArg(OS, ModCachePath, Quote); 284 } 285 286 if (ResponseFile != nullptr) { 287 OS << "\n Arguments passed via response file:\n"; 288 writeResponseFile(OS); 289 // Avoiding duplicated newline terminator, since FileLists are 290 // newline-separated. 291 if (Creator.getResponseFilesSupport() != Tool::RF_FileList) 292 OS << "\n"; 293 OS << " (end of response file)"; 294 } 295 296 OS << Terminator; 297 } 298 299 void Command::setResponseFile(const char *FileName) { 300 ResponseFile = FileName; 301 ResponseFileFlag = Creator.getResponseFileFlag(); 302 ResponseFileFlag += FileName; 303 } 304 305 int Command::Execute(const StringRef **Redirects, std::string *ErrMsg, 306 bool *ExecutionFailed) const { 307 SmallVector<const char*, 128> Argv; 308 309 if (ResponseFile == nullptr) { 310 Argv.push_back(Executable); 311 Argv.append(Arguments.begin(), Arguments.end()); 312 Argv.push_back(nullptr); 313 314 return llvm::sys::ExecuteAndWait(Executable, Argv.data(), /*env*/ nullptr, 315 Redirects, /*secondsToWait*/ 0, 316 /*memoryLimit*/ 0, ErrMsg, 317 ExecutionFailed); 318 } 319 320 // We need to put arguments in a response file (command is too large) 321 // Open stream to store the response file contents 322 std::string RespContents; 323 llvm::raw_string_ostream SS(RespContents); 324 325 // Write file contents and build the Argv vector 326 writeResponseFile(SS); 327 buildArgvForResponseFile(Argv); 328 Argv.push_back(nullptr); 329 SS.flush(); 330 331 // Save the response file in the appropriate encoding 332 if (std::error_code EC = writeFileWithEncoding( 333 ResponseFile, RespContents, Creator.getResponseFileEncoding())) { 334 if (ErrMsg) 335 *ErrMsg = EC.message(); 336 if (ExecutionFailed) 337 *ExecutionFailed = true; 338 return -1; 339 } 340 341 return llvm::sys::ExecuteAndWait(Executable, Argv.data(), /*env*/ nullptr, 342 Redirects, /*secondsToWait*/ 0, 343 /*memoryLimit*/ 0, ErrMsg, ExecutionFailed); 344 } 345 346 FallbackCommand::FallbackCommand(const Action &Source_, const Tool &Creator_, 347 const char *Executable_, 348 const ArgStringList &Arguments_, 349 ArrayRef<InputInfo> Inputs, 350 std::unique_ptr<Command> Fallback_) 351 : Command(Source_, Creator_, Executable_, Arguments_, Inputs), 352 Fallback(std::move(Fallback_)) {} 353 354 void FallbackCommand::Print(raw_ostream &OS, const char *Terminator, 355 bool Quote, CrashReportInfo *CrashInfo) const { 356 Command::Print(OS, "", Quote, CrashInfo); 357 OS << " ||"; 358 Fallback->Print(OS, Terminator, Quote, CrashInfo); 359 } 360 361 static bool ShouldFallback(int ExitCode) { 362 // FIXME: We really just want to fall back for internal errors, such 363 // as when some symbol cannot be mangled, when we should be able to 364 // parse something but can't, etc. 365 return ExitCode != 0; 366 } 367 368 int FallbackCommand::Execute(const StringRef **Redirects, std::string *ErrMsg, 369 bool *ExecutionFailed) const { 370 int PrimaryStatus = Command::Execute(Redirects, ErrMsg, ExecutionFailed); 371 if (!ShouldFallback(PrimaryStatus)) 372 return PrimaryStatus; 373 374 // Clear ExecutionFailed and ErrMsg before falling back. 375 if (ErrMsg) 376 ErrMsg->clear(); 377 if (ExecutionFailed) 378 *ExecutionFailed = false; 379 380 const Driver &D = getCreator().getToolChain().getDriver(); 381 D.Diag(diag::warn_drv_invoking_fallback) << Fallback->getExecutable(); 382 383 int SecondaryStatus = Fallback->Execute(Redirects, ErrMsg, ExecutionFailed); 384 return SecondaryStatus; 385 } 386 387 ForceSuccessCommand::ForceSuccessCommand(const Action &Source_, 388 const Tool &Creator_, 389 const char *Executable_, 390 const ArgStringList &Arguments_, 391 ArrayRef<InputInfo> Inputs) 392 : Command(Source_, Creator_, Executable_, Arguments_, Inputs) {} 393 394 void ForceSuccessCommand::Print(raw_ostream &OS, const char *Terminator, 395 bool Quote, CrashReportInfo *CrashInfo) const { 396 Command::Print(OS, "", Quote, CrashInfo); 397 OS << " || (exit 0)" << Terminator; 398 } 399 400 int ForceSuccessCommand::Execute(const StringRef **Redirects, 401 std::string *ErrMsg, 402 bool *ExecutionFailed) const { 403 int Status = Command::Execute(Redirects, ErrMsg, ExecutionFailed); 404 (void)Status; 405 if (ExecutionFailed) 406 *ExecutionFailed = false; 407 return 0; 408 } 409 410 void JobList::Print(raw_ostream &OS, const char *Terminator, bool Quote, 411 CrashReportInfo *CrashInfo) const { 412 for (const auto &Job : *this) 413 Job.Print(OS, Terminator, Quote, CrashInfo); 414 } 415 416 void JobList::clear() { Jobs.clear(); } 417