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