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 File Reference

Go to the source code of this file.

Functions

std::mutex & outputRegistryMutex ()
std::unordered_set< std::string > & outputRegistry ()
bool registerOutputPath (const std::string &path)
void unregisterOutputPath (const std::string &path)
int main (int argc, const char **argv)

Variables

constexpr unsigned kMacroFlagNone = 0U
constexpr unsigned kMacroFlagExpansion = 1U
constexpr unsigned kMacroFlagInvocation = 2U

Function Documentation

◆ main()

int main ( int argc,
const char ** argv )

Definition at line 664 of file tool.cpp.

664 {
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

References args.

◆ outputRegistry()

std::unordered_set< std::string > & outputRegistry ( )

Definition at line 40 of file tool.cpp.

40 {
41 static std::unordered_set<std::string> registry;
42 return registry;
43}

Referenced by registerOutputPath(), and unregisterOutputPath().

◆ outputRegistryMutex()

std::mutex & outputRegistryMutex ( )

Definition at line 35 of file tool.cpp.

35 {
36 static std::mutex mutex;
37 return mutex;
38}

Referenced by registerOutputPath(), and unregisterOutputPath().

◆ registerOutputPath()

bool registerOutputPath ( const std::string & path)

Definition at line 45 of file tool.cpp.

45 {
46 std::lock_guard<std::mutex> guard(outputRegistryMutex());
47 auto &registry = outputRegistry();
48 auto [_, inserted] = registry.insert(path);
49 return inserted;
50}
std::mutex & outputRegistryMutex()
Definition tool.cpp:35
std::unordered_set< std::string > & outputRegistry()
Definition tool.cpp:40

References outputRegistry(), and outputRegistryMutex().

◆ unregisterOutputPath()

void unregisterOutputPath ( const std::string & path)

Definition at line 52 of file tool.cpp.

52 {
53 std::lock_guard<std::mutex> guard(outputRegistryMutex());
54 outputRegistry().erase(path);
55}

References outputRegistry(), and outputRegistryMutex().

Variable Documentation

◆ kMacroFlagExpansion

unsigned kMacroFlagExpansion = 1U
constexpr

Definition at line 95 of file tool.cpp.

◆ kMacroFlagInvocation

unsigned kMacroFlagInvocation = 2U
constexpr

Definition at line 96 of file tool.cpp.

◆ kMacroFlagNone

unsigned kMacroFlagNone = 0U
constexpr

Definition at line 94 of file tool.cpp.