1 //===--- Tooling.cpp - Running clang standalone tools ---------------------===// 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 implements functions to run clang tools standalone instead 11 // of running them as a plugin. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/Tooling/ArgumentsAdjusters.h" 16 #include "clang/Tooling/Tooling.h" 17 #include "clang/Tooling/CompilationDatabase.h" 18 #include "clang/Driver/Compilation.h" 19 #include "clang/Driver/Driver.h" 20 #include "clang/Driver/Tool.h" 21 #include "clang/Frontend/CompilerInstance.h" 22 #include "clang/Frontend/FrontendDiagnostic.h" 23 #include "clang/Frontend/TextDiagnosticPrinter.h" 24 #include "llvm/ADT/STLExtras.h" 25 #include "llvm/Support/FileSystem.h" 26 #include "llvm/Support/Host.h" 27 #include "llvm/Support/raw_ostream.h" 28 29 // For chdir, see the comment in ClangTool::run for more information. 30 #ifdef _WIN32 31 # include <direct.h> 32 #else 33 # include <unistd.h> 34 #endif 35 36 namespace clang { 37 namespace tooling { 38 39 FrontendActionFactory::~FrontendActionFactory() {} 40 41 // FIXME: This file contains structural duplication with other parts of the 42 // code that sets up a compiler to run tools on it, and we should refactor 43 // it to be based on the same framework. 44 45 /// \brief Builds a clang driver initialized for running clang tools. 46 static clang::driver::Driver *newDriver(clang::DiagnosticsEngine *Diagnostics, 47 const char *BinaryName) { 48 const std::string DefaultOutputName = "a.out"; 49 clang::driver::Driver *CompilerDriver = new clang::driver::Driver( 50 BinaryName, llvm::sys::getDefaultTargetTriple(), 51 DefaultOutputName, false, *Diagnostics); 52 CompilerDriver->setTitle("clang_based_tool"); 53 return CompilerDriver; 54 } 55 56 /// \brief Retrieves the clang CC1 specific flags out of the compilation's jobs. 57 /// 58 /// Returns NULL on error. 59 static const clang::driver::ArgStringList *getCC1Arguments( 60 clang::DiagnosticsEngine *Diagnostics, 61 clang::driver::Compilation *Compilation) { 62 // We expect to get back exactly one Command job, if we didn't something 63 // failed. Extract that job from the Compilation. 64 const clang::driver::JobList &Jobs = Compilation->getJobs(); 65 if (Jobs.size() != 1 || !isa<clang::driver::Command>(*Jobs.begin())) { 66 llvm::SmallString<256> error_msg; 67 llvm::raw_svector_ostream error_stream(error_msg); 68 Compilation->PrintJob(error_stream, Compilation->getJobs(), "; ", true); 69 Diagnostics->Report(clang::diag::err_fe_expected_compiler_job) 70 << error_stream.str(); 71 return NULL; 72 } 73 74 // The one job we find should be to invoke clang again. 75 const clang::driver::Command *Cmd = 76 cast<clang::driver::Command>(*Jobs.begin()); 77 if (StringRef(Cmd->getCreator().getName()) != "clang") { 78 Diagnostics->Report(clang::diag::err_fe_expected_clang_command); 79 return NULL; 80 } 81 82 return &Cmd->getArguments(); 83 } 84 85 /// \brief Returns a clang build invocation initialized from the CC1 flags. 86 static clang::CompilerInvocation *newInvocation( 87 clang::DiagnosticsEngine *Diagnostics, 88 const clang::driver::ArgStringList &CC1Args) { 89 assert(!CC1Args.empty() && "Must at least contain the program name!"); 90 clang::CompilerInvocation *Invocation = new clang::CompilerInvocation; 91 clang::CompilerInvocation::CreateFromArgs( 92 *Invocation, CC1Args.data() + 1, CC1Args.data() + CC1Args.size(), 93 *Diagnostics); 94 Invocation->getFrontendOpts().DisableFree = false; 95 return Invocation; 96 } 97 98 bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code, 99 const Twine &FileName) { 100 SmallString<16> FileNameStorage; 101 StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage); 102 const char *const CommandLine[] = { 103 "clang-tool", "-fsyntax-only", FileNameRef.data() 104 }; 105 FileManager Files((FileSystemOptions())); 106 ToolInvocation Invocation( 107 std::vector<std::string>( 108 CommandLine, 109 CommandLine + llvm::array_lengthof(CommandLine)), 110 ToolAction, &Files); 111 112 SmallString<1024> CodeStorage; 113 Invocation.mapVirtualFile(FileNameRef, 114 Code.toNullTerminatedStringRef(CodeStorage)); 115 return Invocation.run(); 116 } 117 118 std::string getAbsolutePath(StringRef File) { 119 llvm::SmallString<1024> BaseDirectory; 120 if (const char *PWD = ::getenv("PWD")) 121 BaseDirectory = PWD; 122 else 123 llvm::sys::fs::current_path(BaseDirectory); 124 SmallString<1024> PathStorage; 125 if (llvm::sys::path::is_absolute(File)) { 126 llvm::sys::path::native(File, PathStorage); 127 return PathStorage.str(); 128 } 129 StringRef RelativePath(File); 130 // FIXME: Should '.\\' be accepted on Win32? 131 if (RelativePath.startswith("./")) { 132 RelativePath = RelativePath.substr(strlen("./")); 133 } 134 llvm::SmallString<1024> AbsolutePath(BaseDirectory); 135 llvm::sys::path::append(AbsolutePath, RelativePath); 136 llvm::sys::path::native(Twine(AbsolutePath), PathStorage); 137 return PathStorage.str(); 138 } 139 140 ToolInvocation::ToolInvocation( 141 ArrayRef<std::string> CommandLine, FrontendAction *ToolAction, 142 FileManager *Files) 143 : CommandLine(CommandLine.vec()), ToolAction(ToolAction), Files(Files) { 144 } 145 146 void ToolInvocation::mapVirtualFile(StringRef FilePath, StringRef Content) { 147 SmallString<1024> PathStorage; 148 llvm::sys::path::native(FilePath, PathStorage); 149 MappedFileContents[PathStorage] = Content; 150 } 151 152 bool ToolInvocation::run() { 153 std::vector<const char*> Argv; 154 for (int I = 0, E = CommandLine.size(); I != E; ++I) 155 Argv.push_back(CommandLine[I].c_str()); 156 const char *const BinaryName = Argv[0]; 157 DiagnosticOptions DefaultDiagnosticOptions; 158 TextDiagnosticPrinter DiagnosticPrinter( 159 llvm::errs(), DefaultDiagnosticOptions); 160 DiagnosticsEngine Diagnostics(llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs>( 161 new DiagnosticIDs()), &DiagnosticPrinter, false); 162 163 const llvm::OwningPtr<clang::driver::Driver> Driver( 164 newDriver(&Diagnostics, BinaryName)); 165 // Since the input might only be virtual, don't check whether it exists. 166 Driver->setCheckInputsExist(false); 167 const llvm::OwningPtr<clang::driver::Compilation> Compilation( 168 Driver->BuildCompilation(llvm::makeArrayRef(Argv))); 169 const clang::driver::ArgStringList *const CC1Args = getCC1Arguments( 170 &Diagnostics, Compilation.get()); 171 if (CC1Args == NULL) { 172 return false; 173 } 174 llvm::OwningPtr<clang::CompilerInvocation> Invocation( 175 newInvocation(&Diagnostics, *CC1Args)); 176 return runInvocation(BinaryName, Compilation.get(), Invocation.take(), 177 *CC1Args); 178 } 179 180 bool ToolInvocation::runInvocation( 181 const char *BinaryName, 182 clang::driver::Compilation *Compilation, 183 clang::CompilerInvocation *Invocation, 184 const clang::driver::ArgStringList &CC1Args) { 185 // Show the invocation, with -v. 186 if (Invocation->getHeaderSearchOpts().Verbose) { 187 llvm::errs() << "clang Invocation:\n"; 188 Compilation->PrintJob(llvm::errs(), Compilation->getJobs(), "\n", true); 189 llvm::errs() << "\n"; 190 } 191 192 // Create a compiler instance to handle the actual work. 193 clang::CompilerInstance Compiler; 194 Compiler.setInvocation(Invocation); 195 Compiler.setFileManager(Files); 196 // FIXME: What about LangOpts? 197 198 // ToolAction can have lifetime requirements for Compiler or its members, and 199 // we need to ensure it's deleted earlier than Compiler. So we pass it to an 200 // OwningPtr declared after the Compiler variable. 201 llvm::OwningPtr<FrontendAction> ScopedToolAction(ToolAction.take()); 202 203 // Create the compilers actual diagnostics engine. 204 Compiler.createDiagnostics(CC1Args.size(), 205 const_cast<char**>(CC1Args.data())); 206 if (!Compiler.hasDiagnostics()) 207 return false; 208 209 Compiler.createSourceManager(*Files); 210 addFileMappingsTo(Compiler.getSourceManager()); 211 212 const bool Success = Compiler.ExecuteAction(*ScopedToolAction); 213 214 Compiler.resetAndLeakFileManager(); 215 return Success; 216 } 217 218 void ToolInvocation::addFileMappingsTo(SourceManager &Sources) { 219 for (llvm::StringMap<StringRef>::const_iterator 220 It = MappedFileContents.begin(), End = MappedFileContents.end(); 221 It != End; ++It) { 222 // Inject the code as the given file name into the preprocessor options. 223 const llvm::MemoryBuffer *Input = 224 llvm::MemoryBuffer::getMemBuffer(It->getValue()); 225 // FIXME: figure out what '0' stands for. 226 const FileEntry *FromFile = Files->getVirtualFile( 227 It->getKey(), Input->getBufferSize(), 0); 228 Sources.overrideFileContents(FromFile, Input); 229 } 230 } 231 232 ClangTool::ClangTool(const CompilationDatabase &Compilations, 233 ArrayRef<std::string> SourcePaths) 234 : Files((FileSystemOptions())), 235 ArgsAdjuster(new ClangSyntaxOnlyAdjuster()) { 236 for (unsigned I = 0, E = SourcePaths.size(); I != E; ++I) { 237 llvm::SmallString<1024> File(getAbsolutePath(SourcePaths[I])); 238 239 std::vector<CompileCommand> CompileCommandsForFile = 240 Compilations.getCompileCommands(File.str()); 241 if (!CompileCommandsForFile.empty()) { 242 for (int I = 0, E = CompileCommandsForFile.size(); I != E; ++I) { 243 CompileCommands.push_back(std::make_pair(File.str(), 244 CompileCommandsForFile[I])); 245 } 246 } else { 247 // FIXME: There are two use cases here: doing a fuzzy 248 // "find . -name '*.cc' |xargs tool" match, where as a user I don't care 249 // about the .cc files that were not found, and the use case where I 250 // specify all files I want to run over explicitly, where this should 251 // be an error. We'll want to add an option for this. 252 llvm::outs() << "Skipping " << File << ". Command line not found.\n"; 253 } 254 } 255 } 256 257 void ClangTool::mapVirtualFile(StringRef FilePath, StringRef Content) { 258 MappedFileContents.push_back(std::make_pair(FilePath, Content)); 259 } 260 261 void ClangTool::setArgumentsAdjuster(ArgumentsAdjuster *Adjuster) { 262 ArgsAdjuster.reset(Adjuster); 263 } 264 265 int ClangTool::run(FrontendActionFactory *ActionFactory) { 266 // Exists solely for the purpose of lookup of the resource path. 267 // This just needs to be some symbol in the binary. 268 static int StaticSymbol; 269 // The driver detects the builtin header path based on the path of the 270 // executable. 271 // FIXME: On linux, GetMainExecutable is independent of the value of the 272 // first argument, thus allowing ClangTool and runToolOnCode to just 273 // pass in made-up names here. Make sure this works on other platforms. 274 std::string MainExecutable = 275 llvm::sys::Path::GetMainExecutable("clang_tool", &StaticSymbol).str(); 276 277 bool ProcessingFailed = false; 278 for (unsigned I = 0; I < CompileCommands.size(); ++I) { 279 std::string File = CompileCommands[I].first; 280 // FIXME: chdir is thread hostile; on the other hand, creating the same 281 // behavior as chdir is complex: chdir resolves the path once, thus 282 // guaranteeing that all subsequent relative path operations work 283 // on the same path the original chdir resulted in. This makes a difference 284 // for example on network filesystems, where symlinks might be switched 285 // during runtime of the tool. Fixing this depends on having a file system 286 // abstraction that allows openat() style interactions. 287 if (chdir(CompileCommands[I].second.Directory.c_str())) 288 llvm::report_fatal_error("Cannot chdir into \"" + 289 CompileCommands[I].second.Directory + "\n!"); 290 std::vector<std::string> CommandLine = 291 ArgsAdjuster->Adjust(CompileCommands[I].second.CommandLine); 292 assert(!CommandLine.empty()); 293 CommandLine[0] = MainExecutable; 294 llvm::outs() << "Processing: " << File << ".\n"; 295 ToolInvocation Invocation(CommandLine, ActionFactory->create(), &Files); 296 for (int I = 0, E = MappedFileContents.size(); I != E; ++I) { 297 Invocation.mapVirtualFile(MappedFileContents[I].first, 298 MappedFileContents[I].second); 299 } 300 if (!Invocation.run()) { 301 llvm::outs() << "Error while processing " << File << ".\n"; 302 ProcessingFailed = true; 303 } 304 } 305 return ProcessingFailed ? 1 : 0; 306 } 307 308 } // end namespace tooling 309 } // end namespace clang 310