|
5 | 5 | #include <vector> |
6 | 6 | #include <string> |
7 | 7 | #include <iostream> |
| 8 | +#include <regex> |
| 9 | +#include <unistd.h> |
8 | 10 |
|
9 | 11 | #include <swift/Basic/LLVMInitialize.h> |
10 | 12 | #include <swift/FrontendTool/FrontendTool.h> |
@@ -51,7 +53,52 @@ static void lockOutputSwiftModuleTraps(const codeql::SwiftExtractorConfiguration |
51 | 53 | } |
52 | 54 | } |
53 | 55 |
|
| 56 | +static bool checkRunUnderFilter(int argc, char* const* argv) { |
| 57 | + auto runUnderFilter = getenv("CODEQL_EXTRACTOR_SWIFT_RUN_UNDER_FILTER"); |
| 58 | + if (runUnderFilter == nullptr) { |
| 59 | + return true; |
| 60 | + } |
| 61 | + std::string call = argv[0]; |
| 62 | + for (auto i = 1; i < argc; ++i) { |
| 63 | + call += ' '; |
| 64 | + call += argv[i]; |
| 65 | + } |
| 66 | + std::regex filter{runUnderFilter, std::regex_constants::basic | std::regex_constants::nosubs}; |
| 67 | + return std::regex_search(call, filter); |
| 68 | +} |
| 69 | + |
| 70 | +// if `CODEQL_EXTRACTOR_SWIFT_RUN_UNDER` env variable is set, and either |
| 71 | +// * `CODEQL_EXTRACTOR_SWIFT_RUN_UNDER_FILTER` is not set, or |
| 72 | +// * it is set to a regexp matching any substring of the extractor call |
| 73 | +// then the running process is substituted with the command (and possibly |
| 74 | +// options) stated in `CODEQL_EXTRACTOR_SWIFT_RUN_UNDER`, followed by `argv`. |
| 75 | +// Before calling `exec`, `CODEQL_EXTRACTOR_SWIFT_RUN_UNDER` is unset to avoid |
| 76 | +// unpleasant loops. |
| 77 | +// An example usage is to run the extractor under `gdbserver :1234` when the |
| 78 | +// arguments match a given source file. |
| 79 | +static void checkWhetherToRunUnderTool(int argc, char* const* argv) { |
| 80 | + assert(argc > 0); |
| 81 | + |
| 82 | + auto runUnder = getenv("CODEQL_EXTRACTOR_SWIFT_RUN_UNDER"); |
| 83 | + if (runUnder == nullptr || !checkRunUnderFilter(argc, argv)) { |
| 84 | + return; |
| 85 | + } |
| 86 | + std::vector<char*> args; |
| 87 | + // split RUN_UNDER value by spaces to get args vector |
| 88 | + for (auto word = std::strtok(runUnder, " "); word != nullptr; word = std::strtok(nullptr, " ")) { |
| 89 | + args.push_back(word); |
| 90 | + } |
| 91 | + // append process args, including extractor executable path |
| 92 | + args.insert(args.end(), argv, argv + argc); |
| 93 | + args.push_back(nullptr); |
| 94 | + // avoid looping on this function |
| 95 | + unsetenv("CODEQL_EXTRACTOR_SWIFT_RUN_UNDER"); |
| 96 | + execvp(args[0], args.data()); |
| 97 | +} |
| 98 | + |
54 | 99 | int main(int argc, char** argv) { |
| 100 | + checkWhetherToRunUnderTool(argc, argv); |
| 101 | + |
55 | 102 | if (argc == 1) { |
56 | 103 | // TODO: print usage |
57 | 104 | return 1; |
|
0 commit comments