ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
tool.cpp
Go to the documentation of this file.
1#include "clang/AST/ASTConsumer.h"
2#include "clang/AST/ASTContext.h"
3#include "clang/AST/ASTTypeTraits.h"
4#include "clang/AST/Attr.h"
5#include "clang/AST/ParentMapContext.h"
6#include "clang/AST/RecursiveASTVisitor.h"
7#include "clang/Frontend/CompilerInstance.h"
8#include "clang/Lex/Lexer.h"
9#include "clang/Rewrite/Core/Rewriter.h"
10#include "clang/Tooling/ArgumentsAdjusters.h"
11#include "clang/Tooling/CommonOptionsParser.h"
12#include "clang/Tooling/Tooling.h"
13#include "llvm/ADT/RewriteBuffer.h"
14#include "llvm/ADT/StringRef.h"
15#include "llvm/Support/CommandLine.h"
16#include "llvm/Support/Error.h"
17#include "llvm/Support/FileSystem.h"
18#include "llvm/Support/InitLLVM.h"
19#include "llvm/Support/raw_ostream.h"
20
21#include <algorithm>
22#include <cctype>
23#include <filesystem>
24#include <fstream>
25#include <mutex>
26#include <optional>
27#include <string>
28#include <unordered_set>
29#include <utility>
30#include <vector>
31
32using namespace llvm;
33using namespace clang;
34
35std::mutex &outputRegistryMutex() {
36 static std::mutex mutex;
37 return mutex;
38}
39
40std::unordered_set<std::string> &outputRegistry() {
41 static std::unordered_set<std::string> registry;
42 return registry;
43}
44
45bool registerOutputPath(const std::string &path) {
46 std::lock_guard<std::mutex> guard(outputRegistryMutex());
47 auto &registry = outputRegistry();
48 auto [_, inserted] = registry.insert(path);
49 return inserted;
50}
51
52void unregisterOutputPath(const std::string &path) {
53 std::lock_guard<std::mutex> guard(outputRegistryMutex());
54 outputRegistry().erase(path);
55}
56
57// LLVM command line options MUST be declared at file scope (not in anonymous namespace)
58// to ensure proper static initialization
59namespace fs = std::filesystem;
60
61static cl::OptionCategory ToolCategory("ascii-chat instrumentation options");
62
63static cl::extrahelp CommonHelp(tooling::CommonOptionsParser::HelpMessage);
64static cl::extrahelp MoreHelp("\nInstrumentation tool for ascii-chat debugging\n");
65
66static cl::opt<std::string> OutputDirectoryOption("output-dir", cl::desc("Directory where instrumented sources will be written"), cl::value_desc("path"), cl::Required, cl::cat(ToolCategory));
67
68static cl::opt<std::string> InputRootOption("input-root", cl::desc("Root directory of original sources (used to compute relative paths)"), cl::value_desc("path"), cl::init(""), cl::cat(ToolCategory));
69
70static cl::opt<std::string> BuildPath("p", cl::desc("Build path (directory containing compile_commands.json)"), cl::Optional, cl::cat(ToolCategory));
71static cl::opt<std::string> CompileSourceOption("compile-source", cl::desc("Compilation database source corresponding to the input"), cl::init(""), cl::cat(ToolCategory));
72static cl::opt<std::string> ResourceDirOption("resource-dir", cl::desc("Clang builtin headers directory"), cl::init(""), cl::cat(ToolCategory));
73static cl::opt<bool> LogMacroExpansionsOption("log-macro-expansions", cl::desc("Instrument statements originating from macro expansions"), cl::init(false), cl::cat(ToolCategory));
74
75static cl::opt<bool> LogMacroInvocationsOption("log-macro-invocations", cl::desc("Emit a synthetic record for the macro invocation site when expansions are instrumented"), cl::init(false),
76 cl::cat(ToolCategory));
77
78static cl::opt<bool> LegacyIncludeMacroExpansionsOption("include-macro-expansions", cl::desc("Deprecated alias for --log-macro-expansions (kept for backward compatibility)"), cl::init(false),
79 cl::cat(ToolCategory), cl::Hidden);
80
81static cl::list<std::string> FileIncludeFilters("filter-file", cl::desc("Only instrument files whose path contains the given substring"), cl::value_desc("substring"), cl::cat(ToolCategory));
82
83static cl::list<std::string> FunctionIncludeFilters("filter-function", cl::desc("Only instrument functions whose name matches the given substring"), cl::value_desc("substring"),
84 cl::cat(ToolCategory));
85
86static cl::opt<std::string> FileListOption("file-list", cl::desc("Path to file containing newline-delimited translation units to instrument"), cl::value_desc("path"), cl::init(""),
87 cl::cat(ToolCategory));
88
89static cl::list<std::string> SourcePaths(cl::Positional, cl::desc("<source0> [... <sourceN>]"), cl::cat(ToolCategory));
90
91static cl::opt<std::string> SignalHandlerAnnotation("signal-handler-annotation", cl::desc("Annotation string used to mark functions that should be skipped"), cl::value_desc("annotation"),
92 cl::init("ASCII_INSTR_SOURCE_PRINT_SIGNAL_HANDLER"), cl::cat(ToolCategory));
93
94constexpr unsigned kMacroFlagNone = 0U;
95constexpr unsigned kMacroFlagExpansion = 1U;
96constexpr unsigned kMacroFlagInvocation = 2U;
97
98namespace {
99
100// The compiled file can be a generated source; parse the original using that
101// target's exact compile command, while retaining the original file's context.
102class MappedCompilationDatabase final : public tooling::CompilationDatabase {
103public:
104 MappedCompilationDatabase(const tooling::CompilationDatabase &base, std::string compiled) : base_(base), compiled_(std::move(compiled)) {}
105
106 std::vector<tooling::CompileCommand> getCompileCommands(StringRef input) const override {
107 auto commands = base_.getCompileCommands(compiled_);
108 for (auto &command : commands) {
109 for (auto &arg : command.CommandLine) {
110 if ((fs::path(command.Directory) / fs::path(arg)).lexically_normal() == fs::path(compiled_).lexically_normal())
111 arg = input.str();
112 }
113 command.Filename = input.str();
114 }
115 return commands;
116 }
117
118private:
119 const tooling::CompilationDatabase &base_;
120 std::string compiled_;
121};
122
123class InstrumentationVisitor : public clang::RecursiveASTVisitor<InstrumentationVisitor> {
124public:
125 InstrumentationVisitor(clang::ASTContext &context, clang::Rewriter &rewriter, const fs::path &outputDir, const fs::path &inputRoot, bool enableFileFilters, bool enableFunctionFilters,
126 bool logMacroInvocations, bool logMacroExpansions)
127 : context_(context), rewriter_(rewriter), outputDir_(outputDir), inputRoot_(inputRoot), enableFileFilters_(enableFileFilters), enableFunctionFilters_(enableFunctionFilters),
128 logMacroInvocations_(logMacroInvocations), logMacroExpansions_(logMacroExpansions) {}
129
130 bool TraverseFunctionDecl(clang::FunctionDecl *funcDecl) {
131 const bool previousSkipState = skipCurrentFunction_;
132 currentFunction_ = funcDecl;
133 skipCurrentFunction_ = shouldSkipFunction(funcDecl);
134
135 const bool result = clang::RecursiveASTVisitor<InstrumentationVisitor>::TraverseFunctionDecl(funcDecl);
136
137 skipCurrentFunction_ = previousSkipState;
138 currentFunction_ = nullptr;
139 return result;
140 }
141
142 bool VisitStmt(clang::Stmt *statement) {
143 if (!statement || !currentFunction_) {
144 return true;
145 }
146
147 if (!isDirectChildOfCompound(*statement)) {
148 return true;
149 }
150
151 if (llvm::isa<clang::CompoundStmt>(statement) || llvm::isa<clang::NullStmt>(statement)) {
152 return true;
153 }
154
155 if (skipCurrentFunction_) {
156 return true;
157 }
158
159 if (!shouldInstrumentStatement(*statement)) {
160 return true;
161 }
162
163 clang::SourceManager &sourceManager = context_.getSourceManager();
164 const clang::LangOptions &langOptions = context_.getLangOpts();
165
166 clang::SourceLocation beginLocation = statement->getBeginLoc();
167 if (beginLocation.isInvalid()) {
168 return true;
169 }
170
171 clang::SourceLocation expansionLocation = sourceManager.getExpansionLoc(beginLocation);
172 if (!expansionLocation.isValid()) {
173 return true;
174 }
175
176 if (!sourceManager.isWrittenInMainFile(expansionLocation)) {
177 return true;
178 }
179
180 const clang::FileID fileId = sourceManager.getFileID(expansionLocation);
181 const clang::FileEntry *fileEntry = sourceManager.getFileEntryForID(fileId);
182 if (fileEntry == nullptr) {
183 return true;
184 }
185
186 const llvm::StringRef absoluteFilePath = fileEntry->tryGetRealPathName();
187 if (absoluteFilePath.empty()) {
188 return true;
189 }
190
191 const fs::path filePath = fs::path(absoluteFilePath.str());
192 if (enableFileFilters_ && !matchesFileFilters(filePath)) {
193 return true;
194 }
195
196 const std::string relativePath = makeRelativePath(filePath);
197 const std::string uniqueKey = buildUniqueKey(filePath, expansionLocation, sourceManager);
198 if (!instrumentedLocations_.insert(uniqueKey).second) {
199 return true;
200 }
201
202 const bool isMacroExpansion = sourceManager.isMacroBodyExpansion(beginLocation) || sourceManager.isMacroArgExpansion(beginLocation);
203
204 std::string instrumentationBlock;
205
206 if (isMacroExpansion) {
207 if (logMacroInvocations_) {
208 const std::optional<MacroInvocationMetadata> invocationMetadata = buildMacroInvocationMetadata(*statement, sourceManager, langOptions);
209 if (invocationMetadata.has_value()) {
210 if (macroInvocationLocations_.insert(invocationMetadata->uniqueKey).second) {
211 instrumentationBlock.append(buildInstrumentationLine(invocationMetadata->relativePath, invocationMetadata->lineNumber, invocationMetadata->snippet, kMacroFlagInvocation));
212 }
213 }
214 }
215
216 if (logMacroExpansions_) {
217 const unsigned lineNumber = sourceManager.getSpellingLineNumber(expansionLocation);
218 const std::optional<std::string> snippetOpt = extractSnippet(*statement, sourceManager, langOptions);
219 const llvm::StringRef snippetRef = snippetOpt ? llvm::StringRef(*snippetOpt) : llvm::StringRef("<unavailable>");
220 instrumentationBlock.append(buildInstrumentationLine(relativePath, lineNumber, snippetRef, kMacroFlagExpansion));
221 }
222
223 if (instrumentationBlock.empty()) {
224 return true;
225 }
226 } else {
227 const unsigned lineNumber = sourceManager.getSpellingLineNumber(expansionLocation);
228 const std::optional<std::string> snippetOpt = extractSnippet(*statement, sourceManager, langOptions);
229 const llvm::StringRef snippetRef = snippetOpt ? llvm::StringRef(*snippetOpt) : llvm::StringRef("<unavailable>");
230 instrumentationBlock.append(buildInstrumentationLine(relativePath, lineNumber, snippetRef, kMacroFlagNone));
231 }
232
233 if (instrumentationBlock.empty()) {
234 return true;
235 }
236
237 rewriter_.InsertText(expansionLocation, instrumentationBlock, true, true);
238 includeNeeded_ = true;
239 return true;
240 }
241
242 bool includeNeeded() const {
243 return includeNeeded_;
244 }
245
246 std::string buildUniqueKey(const fs::path &filePath, clang::SourceLocation location, const clang::SourceManager &sourceManager) const {
247 const unsigned offset = sourceManager.getFileOffset(location);
248 return (filePath.string() + ":" + std::to_string(offset));
249 }
250
251 std::string buildInstrumentationLine(const std::string &relativePath, unsigned lineNumber, llvm::StringRef snippet, unsigned macroFlag) const {
252 std::string escapedSnippet = escapeSnippet(snippet);
253 std::string instrumentationLine;
254 instrumentationLine.reserve(escapedSnippet.size() + 256);
255 instrumentationLine.append("asciichat_instr_log_line(\"");
256 instrumentationLine.append(relativePath);
257 instrumentationLine.append("\", ");
258 instrumentationLine.append(std::to_string(lineNumber));
259 instrumentationLine.append(", __func__, \"");
260 instrumentationLine.append(escapedSnippet);
261 instrumentationLine.append("\", ");
262 instrumentationLine.append(std::to_string(macroFlag));
263 instrumentationLine.append(");\n");
264 return instrumentationLine;
265 }
266
267 struct MacroInvocationMetadata {
268 std::string relativePath;
269 unsigned lineNumber = 0;
270 std::string snippet;
271 std::string uniqueKey;
272 };
273
274 std::optional<MacroInvocationMetadata> buildMacroInvocationMetadata(const clang::Stmt &statement, clang::SourceManager &sourceManager, const clang::LangOptions &langOptions) const {
275 clang::SourceLocation beginLocation = statement.getBeginLoc();
276 if (!(sourceManager.isMacroBodyExpansion(beginLocation) || sourceManager.isMacroArgExpansion(beginLocation))) {
277 return std::nullopt;
278 }
279
280 clang::SourceLocation callerLocation = sourceManager.getImmediateMacroCallerLoc(beginLocation);
281 if (!callerLocation.isValid()) {
282 return std::nullopt;
283 }
284
285 callerLocation = sourceManager.getExpansionLoc(callerLocation);
286 if (!callerLocation.isValid() || !sourceManager.isWrittenInMainFile(callerLocation)) {
287 return std::nullopt;
288 }
289
290 const clang::FileID callerFileId = sourceManager.getFileID(callerLocation);
291 const clang::FileEntry *callerFileEntry = sourceManager.getFileEntryForID(callerFileId);
292 if (callerFileEntry == nullptr) {
293 return std::nullopt;
294 }
295
296 const llvm::StringRef callerPathRef = callerFileEntry->tryGetRealPathName();
297 if (callerPathRef.empty()) {
298 return std::nullopt;
299 }
300
301 MacroInvocationMetadata metadata;
302 const fs::path callerPath = fs::path(callerPathRef.str());
303 metadata.relativePath = makeRelativePath(callerPath);
304 metadata.lineNumber = sourceManager.getSpellingLineNumber(callerLocation);
305 metadata.uniqueKey = buildUniqueKey(callerPath, callerLocation, sourceManager);
306
307 clang::CharSourceRange expansionRange = sourceManager.getImmediateExpansionRange(beginLocation);
308 if (expansionRange.isValid()) {
309 bool invalid = false;
310 llvm::StringRef invocationSource = clang::Lexer::getSourceText(expansionRange, sourceManager, langOptions, &invalid);
311 if (!invalid && !invocationSource.empty()) {
312 metadata.snippet = invocationSource.str();
313 }
314 }
315
316 if (metadata.snippet.empty()) {
317 bool invalid = false;
318 clang::CharSourceRange tokenRange = clang::CharSourceRange::getTokenRange(callerLocation, callerLocation);
319 llvm::StringRef fallback = clang::Lexer::getSourceText(tokenRange, sourceManager, langOptions, &invalid);
320 if (!invalid && !fallback.empty()) {
321 metadata.snippet = fallback.str();
322 } else {
323 metadata.snippet = "<macro invocation>";
324 }
325 }
326
327 return metadata;
328 }
329
330 bool matchesFileFilters(const fs::path &filePath) const {
331 if (FileIncludeFilters.empty()) {
332 return true;
333 }
334 const std::string filePathString = filePath.generic_string();
335 for (const std::string &token : FileIncludeFilters) {
336 if (filePathString.find(token) != std::string::npos) {
337 return true;
338 }
339 }
340 return false;
341 }
342
343 bool matchesFunctionFilters(const clang::FunctionDecl *functionDecl) const {
344 if (FunctionIncludeFilters.empty()) {
345 return true;
346 }
347 if (functionDecl == nullptr) {
348 return false;
349 }
350 const std::string functionName = functionDecl->getNameInfo().getAsString();
351 for (const std::string &token : FunctionIncludeFilters) {
352 if (functionName.find(token) != std::string::npos) {
353 return true;
354 }
355 }
356 return false;
357 }
358
359 bool shouldInstrumentStatement(const clang::Stmt &statement) const {
360 if (llvm::isa<clang::NullStmt>(&statement)) {
361 return false;
362 }
363 if (llvm::isa<clang::ImplicitCastExpr>(&statement)) {
364 return false;
365 }
366 if (llvm::isa<clang::ParenExpr>(&statement)) {
367 return false;
368 }
369
370 if (enableFunctionFilters_ && !matchesFunctionFilters(currentFunction_)) {
371 return false;
372 }
373
374 return true;
375 }
376
377 bool shouldSkipFunction(const clang::FunctionDecl *functionDecl) const {
378 if (functionDecl == nullptr) {
379 return true;
380 }
381
382 if (functionDecl->isImplicit()) {
383 return true;
384 }
385
386 clang::SourceManager &sourceManager = context_.getSourceManager();
387 clang::SourceLocation location = functionDecl->getLocation();
388 location = sourceManager.getExpansionLoc(location);
389 if (!location.isValid() || !sourceManager.isWrittenInMainFile(location)) {
390 return true;
391 }
392
393 for (const clang::AnnotateAttr *annotation : functionDecl->specific_attrs<clang::AnnotateAttr>()) {
394 if (!annotation) {
395 continue;
396 }
397 if (annotation->getAnnotation() == SignalHandlerAnnotation.getValue()) {
398 return true;
399 }
400 }
401
402 return false;
403 }
404
405 std::string makeRelativePath(const fs::path &absolutePath) const {
406 if (inputRoot_.empty()) {
407 return absolutePath.generic_string();
408 }
409
410 std::error_code errorCode;
411 fs::path relative = fs::relative(absolutePath, inputRoot_, errorCode);
412 if (errorCode) {
413 return absolutePath.generic_string();
414 }
415 return relative.generic_string();
416 }
417
418 static std::string escapeSnippet(llvm::StringRef snippet) {
419 std::string result;
420 result.reserve(snippet.size());
421 constexpr std::size_t kMaxSnippetLength = 1024;
422 std::size_t processed = 0;
423 for (char ch : snippet) {
424 if (processed >= kMaxSnippetLength) {
425 result.append("<truncated>");
426 break;
427 }
428 processed++;
429 const unsigned char uch = static_cast<unsigned char>(ch);
430 switch (ch) {
431 case '\\':
432 result.append("\\\\");
433 break;
434 case '"':
435 result.append("\\\"");
436 break;
437 case '\n':
438 result.append("\\n");
439 break;
440 case '\r':
441 result.append("\\r");
442 break;
443 case '\t':
444 result.append("\\t");
445 break;
446 default:
447 if (std::isprint(uch) != 0 || uch >= 0x80) {
448 result.push_back(static_cast<char>(uch));
449 } else {
450 result.append("\\\\x");
451 constexpr char hexDigits[] = "0123456789ABCDEF";
452 result.push_back(hexDigits[(uch >> 4) & 0xF]);
453 result.push_back(hexDigits[uch & 0xF]);
454 }
455 break;
456 }
457 }
458 return result;
459 }
460
461 static std::optional<std::string> extractSnippet(const clang::Stmt &statement, const clang::SourceManager &sourceManager, const clang::LangOptions &langOptions) {
462 clang::SourceLocation begin = statement.getBeginLoc();
463 clang::SourceLocation end = statement.getEndLoc();
464
465 if (begin.isInvalid() || end.isInvalid()) {
466 return std::nullopt;
467 }
468
469 clang::SourceLocation expansionBegin = sourceManager.getExpansionLoc(begin);
470 clang::SourceLocation expansionEnd = sourceManager.getExpansionLoc(end);
471 if (!expansionBegin.isValid() || !expansionEnd.isValid()) {
472 return std::nullopt;
473 }
474
475 clang::CharSourceRange range = clang::CharSourceRange::getTokenRange(expansionBegin, expansionEnd);
476 bool invalid = false;
477 llvm::StringRef text = clang::Lexer::getSourceText(range, sourceManager, langOptions, &invalid);
478 if (invalid || text.empty()) {
479 return std::nullopt;
480 }
481 return text.str();
482 }
483
484private:
485 clang::ASTContext &context_;
486 clang::Rewriter &rewriter_;
487 fs::path outputDir_;
488 fs::path inputRoot_;
489 bool enableFileFilters_;
490 bool enableFunctionFilters_;
491 bool logMacroInvocations_;
492 bool logMacroExpansions_;
493 const clang::FunctionDecl *currentFunction_ = nullptr;
494 bool skipCurrentFunction_ = false;
495 bool includeNeeded_ = false;
496 std::unordered_set<std::string> instrumentedLocations_;
497 std::unordered_set<std::string> macroInvocationLocations_;
498
499 bool isDirectChildOfCompound(const clang::Stmt &statement) const {
500 clang::DynTypedNodeList parents = context_.getParents(statement);
501 for (const auto &parent : parents) {
502 if (parent.get<clang::CompoundStmt>()) {
503 return true;
504 }
505 }
506 return false;
507 }
508};
509
510class InstrumentationASTConsumer : public clang::ASTConsumer {
511public:
512 explicit InstrumentationASTConsumer(InstrumentationVisitor &visitor) : visitor_(visitor) {}
513
514 void HandleTranslationUnit(clang::ASTContext &context) override {
515 visitor_.TraverseDecl(context.getTranslationUnitDecl());
516 }
517
518private:
519 InstrumentationVisitor &visitor_;
520};
521
522class InstrumentationFrontendAction : public clang::ASTFrontendAction {
523public:
524 explicit InstrumentationFrontendAction(const fs::path &outputDir, const fs::path &inputRoot, bool enableFileFilters, bool enableFunctionFilters, bool logMacroInvocations, bool logMacroExpansions)
525 : outputDir_(outputDir), inputRoot_(inputRoot), enableFileFilters_(enableFileFilters), enableFunctionFilters_(enableFunctionFilters), logMacroInvocations_(logMacroInvocations),
526 logMacroExpansions_(logMacroExpansions) {}
527
528 void EndSourceFileAction() override {
529 clang::SourceManager &sourceManager = rewriter_.getSourceMgr();
530 const clang::FileEntry *fileEntry = sourceManager.getFileEntryForID(sourceManager.getMainFileID());
531 if (!fileEntry) {
532 return;
533 }
534
535 if (!visitor_) {
536 llvm::errs() << "Instrumentation visitor not initialized; skipping file output"
537 << "\n";
538 hadWriteError_ = true;
539 return;
540 }
541
542 const llvm::StringRef filePathRef = fileEntry->tryGetRealPathName();
543 if (filePathRef.empty()) {
544 llvm::errs() << "Unable to resolve file path for instrumented output\n";
545 return;
546 }
547
548 const fs::path originalPath = fs::path(filePathRef.str());
549 const std::string relativePath = visitor_->makeRelativePath(originalPath);
550 const fs::path destinationPath = outputDir_ / relativePath;
551 const std::string destinationString = destinationPath.string();
552
553 if (!registerOutputPath(destinationString)) {
554 return;
555 }
556
557 std::error_code sameFileError;
558 const bool sameFile = fs::equivalent(originalPath, destinationPath, sameFileError);
559 if (fs::exists(destinationPath) && (CompileSourceOption.empty() || (!sameFileError && sameFile))) {
560 llvm::errs() << "Refusing to overwrite existing file: " << destinationPath.c_str() << "\n";
561 unregisterOutputPath(destinationString);
562 hadWriteError_ = true;
563 return;
564 }
565
566 const fs::path parent = destinationPath.parent_path();
567 std::error_code directoryError;
568 fs::create_directories(parent, directoryError);
569 if (directoryError) {
570 llvm::errs() << "Failed to create output directory: " << parent.c_str() << " - " << directoryError.message() << "\n";
571 unregisterOutputPath(destinationString);
572 hadWriteError_ = true;
573 return;
574 }
575
576 ensureIncludeInserted(originalPath);
577
578 std::string rewrittenContents;
579 if (const llvm::RewriteBuffer *buffer = rewriter_.getRewriteBufferFor(sourceManager.getMainFileID())) {
580 rewrittenContents.assign(buffer->begin(), buffer->end());
581 } else {
582 rewrittenContents = sourceManager.getBufferData(sourceManager.getMainFileID()).str();
583 }
584
585 std::error_code fileError;
586 llvm::raw_fd_ostream outputStream(destinationPath.string(), fileError, llvm::sys::fs::OF_Text);
587 if (fileError) {
588 llvm::errs() << "Failed to open output file: " << destinationPath.c_str() << " - " << fileError.message() << "\n";
589 unregisterOutputPath(destinationString);
590 hadWriteError_ = true;
591 return;
592 }
593 outputStream << rewrittenContents;
594 outputStream.close();
595 if (outputStream.has_error()) {
596 llvm::errs() << "Error while writing instrumented file: " << destinationPath.c_str() << "\n";
597 unregisterOutputPath(destinationString);
598 hadWriteError_ = true;
599 }
600 }
601
602 bool hadWriteError() const {
603 return hadWriteError_;
604 }
605
606protected:
607 std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(clang::CompilerInstance &compiler, llvm::StringRef) override {
608 rewriter_.setSourceMgr(compiler.getSourceManager(), compiler.getLangOpts());
609 visitor_ =
610 std::make_unique<InstrumentationVisitor>(compiler.getASTContext(), rewriter_, outputDir_, inputRoot_, enableFileFilters_, enableFunctionFilters_, logMacroInvocations_, logMacroExpansions_);
611 return std::make_unique<InstrumentationASTConsumer>(*visitor_);
612 }
613
614private:
615 void ensureIncludeInserted(const fs::path &originalPath) {
616 (void)originalPath; // Unused parameter - kept for future use
617 if (!visitor_ || !visitor_->includeNeeded()) {
618 return;
619 }
620
621 clang::SourceManager &sourceManager = rewriter_.getSourceMgr();
622 const clang::FileID fileId = sourceManager.getMainFileID();
623 const llvm::StringRef bufferData = sourceManager.getBufferData(fileId);
624 if (bufferData.contains("#include <ascii-chat/tooling/panic/instrument_log.h>")) {
625 return;
626 }
627
628 clang::SourceLocation insertionLocation = sourceManager.getLocForStartOfFile(fileId);
629 rewriter_.InsertText(insertionLocation, "#include <ascii-chat/tooling/panic/instrument_log.h>\n", false, true);
630 }
631
632 clang::Rewriter rewriter_;
633 fs::path outputDir_;
634 fs::path inputRoot_;
635 bool enableFileFilters_;
636 bool enableFunctionFilters_;
637 bool logMacroInvocations_;
638 bool logMacroExpansions_;
639 std::unique_ptr<InstrumentationVisitor> visitor_;
640 bool hadWriteError_ = false;
641};
642
643class InstrumentationActionFactory : public clang::tooling::FrontendActionFactory {
644public:
645 InstrumentationActionFactory(const fs::path &outputDir, const fs::path &inputRoot, bool enableFileFilters, bool enableFunctionFilters, bool logMacroInvocations, bool logMacroExpansions)
646 : outputDir_(outputDir), inputRoot_(inputRoot), enableFileFilters_(enableFileFilters), enableFunctionFilters_(enableFunctionFilters), logMacroInvocations_(logMacroInvocations),
647 logMacroExpansions_(logMacroExpansions) {}
648
649 std::unique_ptr<clang::FrontendAction> create() {
650 return std::make_unique<InstrumentationFrontendAction>(outputDir_, inputRoot_, enableFileFilters_, enableFunctionFilters_, logMacroInvocations_, logMacroExpansions_);
651 }
652
653private:
654 fs::path outputDir_;
655 fs::path inputRoot_;
656 bool enableFileFilters_;
657 bool enableFunctionFilters_;
658 bool logMacroInvocations_;
659 bool logMacroExpansions_;
660};
661
662} // namespace
663
664int main(int argc, const char **argv) {
665 // Initialize LLVM infrastructure (this triggers command-line option registration!)
666 llvm::InitLLVM InitLLVM(argc, argv);
667
668 // Parse command-line options
669 cl::ParseCommandLineOptions(argc, argv, "ascii-chat instrumentation tool\n");
670
671 const fs::path outputDir = fs::path(OutputDirectoryOption.getValue());
672 fs::path inputRoot;
673 if (!InputRootOption.getValue().empty()) {
674 inputRoot = fs::path(InputRootOption.getValue());
675 } else {
676 inputRoot = fs::current_path();
677 }
678
679 std::vector<std::string> rawSourceArgs;
680 rawSourceArgs.reserve(SourcePaths.size());
681 for (const auto &path : SourcePaths) {
682 rawSourceArgs.push_back(path);
683 }
684 std::vector<std::string> sourcePaths;
685 std::vector<std::string> extraCompilerArgs;
686 for (std::size_t i = 0; i < rawSourceArgs.size(); ++i) {
687 const std::string &entry = rawSourceArgs[i];
688 if (entry.empty()) {
689 continue;
690 }
691 if (entry == "--") {
692 continue;
693 }
694 if (entry[0] == '-') {
695 extraCompilerArgs.push_back(entry);
696 const bool consumesNext = (entry == "-I" || entry == "-isystem" || entry == "-include" || entry == "-include-pch" || entry == "-imacros" || entry == "-idirafter" || entry == "-iprefix" ||
697 entry == "-iwithprefix" || entry == "-iwithprefixbefore" || entry == "-resource-dir" || entry == "-Xclang" || entry == "-Xpreprocessor");
698 if (consumesNext && (i + 1) < rawSourceArgs.size()) {
699 extraCompilerArgs.push_back(rawSourceArgs[i + 1]);
700 ++i;
701 }
702 continue;
703 }
704 sourcePaths.push_back(entry);
705 }
706 if (!FileListOption.getValue().empty()) {
707 std::ifstream listStream(FileListOption.getValue());
708 if (!listStream.is_open()) {
709 llvm::errs() << "Failed to open file list: " << FileListOption.getValue() << "\n";
710 return 1;
711 }
712
713 std::string line;
714 while (std::getline(listStream, line)) {
715 llvm::StringRef trimmed(line);
716 trimmed = trimmed.trim();
717 if (trimmed.empty()) {
718 continue;
719 }
720 sourcePaths.emplace_back(trimmed.str());
721 }
722 }
723
724 if (sourcePaths.empty()) {
725 llvm::errs() << "No translation units specified for instrumentation. Provide positional source paths or --file-list."
726 << "\n";
727 return 1;
728 }
729
730 if (fs::exists(outputDir)) {
731 if (!fs::is_directory(outputDir)) {
732 llvm::errs() << "Output path exists and is not a directory: " << outputDir.c_str() << "\n";
733 return 1;
734 }
735 } else {
736 std::error_code errorCode;
737 fs::create_directories(outputDir, errorCode);
738 if (errorCode) {
739 llvm::errs() << "Failed to create output directory: " << outputDir.c_str() << " - " << errorCode.message() << "\n";
740 return 1;
741 }
742 }
743
744 const bool logMacroExpansions = LogMacroExpansionsOption.getValue() || LegacyIncludeMacroExpansionsOption.getValue();
745 const bool logMacroInvocations = LogMacroInvocationsOption.getValue();
746
747 if (!LogMacroExpansionsOption.getValue() && LegacyIncludeMacroExpansionsOption.getValue()) {
748 llvm::errs() << "warning: --include-macro-expansions is deprecated; use --log-macro-expansions instead\n";
749 }
750
751 // Load compilation database
752 std::string buildPath = BuildPath.getValue();
753 if (buildPath.empty()) {
754 buildPath = ".";
755 }
756 std::string errorMessage;
757 std::unique_ptr<tooling::CompilationDatabase> compilations = tooling::CompilationDatabase::loadFromDirectory(buildPath, errorMessage);
758 if (!compilations) {
759 llvm::errs() << "Error loading compilation database from '" << buildPath << "': " << errorMessage << "\n";
760 return 1;
761 }
762
763 std::unique_ptr<MappedCompilationDatabase> mapped;
764 if (!CompileSourceOption.empty()) {
765 if (sourcePaths.size() != 1) {
766 llvm::errs() << "--compile-source requires exactly one input\n";
767 return 1;
768 }
769 mapped = std::make_unique<MappedCompilationDatabase>(*compilations, CompileSourceOption.getValue());
770 }
771 clang::tooling::ClangTool tool(mapped ? static_cast<const tooling::CompilationDatabase &>(*mapped) : *compilations, sourcePaths);
772
773 if (!ResourceDirOption.empty()) {
774 const std::string resourceDir = ResourceDirOption.getValue();
775 tool.appendArgumentsAdjuster([resourceDir](const tooling::CommandLineArguments &args, StringRef) {
776 auto adjusted = args;
777 adjusted.push_back("-resource-dir");
778 adjusted.push_back(resourceDir);
779 return adjusted;
780 });
781 }
782 if (mapped) {
783 tool.appendArgumentsAdjuster([](const tooling::CommandLineArguments &args, StringRef input) {
784 auto adjusted = args;
785 adjusted.push_back("-DDEFER_PARSING=1");
786 adjusted.push_back("-iquote");
787 adjusted.push_back(fs::path(input.str()).parent_path().string());
788 return adjusted;
789 });
790 }
791
792 if (!extraCompilerArgs.empty()) {
793 const std::vector<std::string> extraArgsCopy(extraCompilerArgs.begin(), extraCompilerArgs.end());
794 tool.appendArgumentsAdjuster([extraArgsCopy](const clang::tooling::CommandLineArguments &args, llvm::StringRef) {
795 clang::tooling::CommandLineArguments adjusted = args;
796 adjusted.insert(adjusted.end(), extraArgsCopy.begin(), extraArgsCopy.end());
797 return adjusted;
798 });
799 }
800
801 auto stripPchAdjuster = [](const clang::tooling::CommandLineArguments &args, llvm::StringRef) {
802 clang::tooling::CommandLineArguments result;
803 const auto containsCMakePch = [](llvm::StringRef value) { return value.contains("cmake_pch"); };
804
805 for (std::size_t i = 0; i < args.size(); ++i) {
806 const std::string &arg = args[i];
807 llvm::StringRef argRef(arg);
808
809 if ((argRef == "-include" || argRef == "--include" || argRef == "-include-pch" || argRef == "--include-pch") && (i + 1) < args.size()) {
810 if (containsCMakePch(args[i + 1])) {
811 ++i;
812 continue;
813 }
814 }
815
816 if ((argRef.starts_with("-include=") || argRef.starts_with("--include=") || argRef.starts_with("-include-pch=") || argRef.starts_with("--include-pch=")) && containsCMakePch(argRef)) {
817 continue;
818 }
819
820 result.push_back(arg);
821 }
822
823 return result;
824 };
825 tool.appendArgumentsAdjuster(stripPchAdjuster);
826
827 auto ensureSourceIncludeAdjuster = [&inputRoot](const clang::tooling::CommandLineArguments &args, llvm::StringRef) {
828 clang::tooling::CommandLineArguments result = args;
829
830 const auto hasInclude = [&result](const std::string &dir) {
831 const std::string combined = "-I" + dir;
832 if (std::find(result.begin(), result.end(), combined) != result.end()) {
833 return true;
834 }
835 for (std::size_t i = 0; i + 1 < result.size(); ++i) {
836 if (result[i] == "-I" && result[i + 1] == dir) {
837 return true;
838 }
839 }
840 return false;
841 };
842
843 const auto appendInclude = [&result](const std::string &dir) {
844 result.push_back("-I");
845 result.push_back(dir);
846 };
847
848 const std::string libDir = (inputRoot / "lib").generic_string();
849 const std::string srcDir = (inputRoot / "src").generic_string();
850
851 if (!hasInclude(libDir)) {
852 appendInclude(libDir);
853 }
854 if (!hasInclude(srcDir)) {
855 appendInclude(srcDir);
856 }
857
858 return result;
859 };
860 tool.appendArgumentsAdjuster(ensureSourceIncludeAdjuster);
861
862 // Instrumented headers are now hard-linked into the output tree, so we can
863 // rely on the original include paths without further adjustment.
864
865 // NOTE: -skip-function-bodies optimization removed - it was causing errors with LibTooling
866 // LibTooling handles arguments differently than the clang driver, so -Xclang flags don't work
867 // The optimization wasn't providing significant benefit anyway
868
869 // Optimization: strip unnecessary compilation flags
870 auto stripUnnecessaryFlags = [](const clang::tooling::CommandLineArguments &args, llvm::StringRef) {
871 clang::tooling::CommandLineArguments result;
872
873 for (size_t i = 0; i < args.size(); ++i) {
874 const std::string &arg = args[i];
875
876 // Skip sanitizer flags (not needed for instrumentation, slow down parsing)
877 if (arg.find("-fsanitize") != std::string::npos)
878 continue;
879 if (arg.find("-fno-sanitize") != std::string::npos)
880 continue;
881 if (arg.find("sanitize") != std::string::npos)
882 continue;
883
884 // Skip debug info generation flags (not needed, slow down codegen)
885 if (arg == "-g" || arg == "-g2" || arg == "-g3")
886 continue;
887 if (arg == "-gcolumn-info")
888 continue;
889 if (arg == "-fstandalone-debug")
890 continue;
891 if (arg.find("-gcodeview") != std::string::npos)
892 continue;
893 if (arg.find("-gdwarf") != std::string::npos)
894 continue;
895
896 // Skip stack protector (not needed for instrumentation)
897 if (arg.find("-fstack-protector") != std::string::npos)
898 continue;
899
900 // Skip frame pointer flags
901 if (arg.find("-fno-omit-frame-pointer") != std::string::npos)
902 continue;
903 if (arg.find("-fomit-frame-pointer") != std::string::npos)
904 continue;
905
906 // Skip optimization-related debug flags
907 if (arg == "-fno-inline")
908 continue;
909 if (arg == "-fno-eliminate-unused-debug-types")
910 continue;
911
912 result.push_back(arg);
913 }
914
915 // NOTE: -w flag removed - it was causing "no such file or directory" errors with LibTooling
916 // Warnings are already suppressed by the stripped flags above
917
918 return result;
919 };
920 tool.appendArgumentsAdjuster(stripUnnecessaryFlags);
921
922 InstrumentationActionFactory actionFactory(outputDir, inputRoot, !FileIncludeFilters.empty(), !FunctionIncludeFilters.empty(), logMacroInvocations, logMacroExpansions);
923 const int executionResult = tool.run(&actionFactory);
924 if (executionResult != 0) {
925 llvm::errs() << "Instrumenter failed with code " << executionResult << "\n";
926 }
927 return executionResult;
928}
action_args_t args
constexpr unsigned kMacroFlagExpansion
Definition tool.cpp:95
void unregisterOutputPath(const std::string &path)
Definition tool.cpp:52
std::mutex & outputRegistryMutex()
Definition tool.cpp:35
constexpr unsigned kMacroFlagInvocation
Definition tool.cpp:96
int main(int argc, const char **argv)
Definition tool.cpp:664
std::unordered_set< std::string > & outputRegistry()
Definition tool.cpp:40
constexpr unsigned kMacroFlagNone
Definition tool.cpp:94
bool registerOutputPath(const std::string &path)
Definition tool.cpp:45