From 11551434aaf998e9044722f4fbdbec83bcd39ebb Mon Sep 17 00:00:00 2001 From: Hugo Date: Mon, 5 Oct 2026 11:47:35 +0200 Subject: [PATCH 01/10] test(input): files from compile directories of their own, with a relative model When jobs are automatic, the default, files compile in parallel and each one changes the working directory of the whole process to its compile command's directory (#184). The changes interleave: a file can compile from another file's directory, and the analyzer can end in one of them, where a relative resource model or cache directory no longer resolves. check_resource_model_across_compile_directories generates 8 files, each in a directory of its own with the one header it includes through a relative -I, and a resource model, given by a relative path, that alone defines the leak every file has. It requires: - with automatic jobs, --jobs=1 and --jobs=4, three runs each with empty caches: the model loads, the 8 leaks and no other are reported, and the compile IR and resource caches are under the start directory; - the relative model and cache paths anchored to the start directory (--print-effective-config); - no compile with a changed working directory, under automatic jobs, for compile commands that need none (--timing). On main, automatic jobs fail every run ('unit6.h' file not found, no output), --jobs=4 writes caches under the compile directories, the paths stay relative, and automatic jobs change the directory for every file. Refs #184 --- run_test.py | 161 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 161 insertions(+) diff --git a/run_test.py b/run_test.py index 02c0eee..f1c0f10 100755 --- a/run_test.py +++ b/run_test.py @@ -2073,6 +2073,166 @@ def check_unknown_alloca_virtual_callback_escape() -> bool: return True +def check_resource_model_across_compile_directories() -> bool: + """ + A resource model given by a relative path is loaded, and used, whatever the job count, while + the files compile from compile-command directories of their own. Each directory holds the one + header its file includes through a relative -I, so a file compiles only from its own + directory; the analyzer must come back to the directory it started from, where the model and + the relative cache directories are. Every run starts with empty caches, and a leak that only + the model defines must be reported in every file. The relative paths must be anchored to the + start directory, and parallel jobs must not change the working directory for files whose + compile commands need no directory of their own. + """ + print("=== Testing the resource model across compile-command directories ===") + unit_count = 8 + ok = True + with tempfile.TemporaryDirectory(prefix="ct_resource_model_cwd_") as tmp: + root = Path(tmp) + project = root / "project" + entries = [] + for i in range(unit_count): + unit_dir = project / f"unit{i}" + (unit_dir / "include").mkdir(parents=True) + (unit_dir / "include" / f"unit{i}.h").write_text( + "void* ct_open_widget(void);\nvoid ct_close_widget(void* w);\n" + ) + source = unit_dir / f"unit{i}.c" + source.write_text( + f'#include "unit{i}.h"\n\n' + f"int leak_widget_{i}(void)\n{{\n void* w = ct_open_widget();\n" + " return w != 0;\n}\n\n" + f"int keep_widget_{i}(void)\n{{\n void* w = ct_open_widget();\n" + " ct_close_widget(w);\n return 0;\n}\n" + ) + entries.append( + { + "directory": str(unit_dir), + "file": str(source), + "arguments": ["cc", "-Iinclude", "-c", str(source), "-o", f"unit{i}.o"], + } + ) + compdb = project / "compile_commands.json" + compdb.write_text(json.dumps(entries, indent=2)) + run_dir = root / "run" + run_dir.mkdir() + (run_dir / "widget-model.txt").write_text( + "acquire_ret ct_open_widget Widget\nrelease_arg ct_close_widget 0 Widget\n" + ) + sources = [entry["file"] for entry in entries] + expected = {f"leak_widget_{i}" for i in range(unit_count)} + + analyzer = str(Path(RUN_CONFIG.analyzer).resolve()) + + def run_from_start_dir(args): + try: + return subprocess.run( + [analyzer, *args], + cwd=run_dir, + capture_output=True, + text=True, + timeout=RUN_CONFIG.analyzer_timeout, + ) + except subprocess.TimeoutExpired: + return None + + start_dir = run_dir.resolve() + result = run_from_start_dir( + [ + "--print-effective-config", + f"--compile-commands={compdb}", + "--resource-model=widget-model.txt", + "--compile-ir-cache-dir=caches-config/compile-ir", + sources[0], + ] + ) + printed = (result.stdout + result.stderr) if result else "" + for line in ( + f"resource-model: {start_dir / 'widget-model.txt'}", + f"compile-ir-cache-dir: {start_dir / 'caches-config' / 'compile-ir'}", + ): + if line in printed: + print(f" ✅ effective configuration: {line.split(':')[0]} anchored to start") + else: + print(f" ❌ effective configuration lacks '{line}'") + ok = False + + absolute_compdb = project / "compile_commands_absolute.json" + absolute_compdb.write_text( + json.dumps( + [ + {**entry, "arguments": ["cc", f"-I{Path(entry['directory']) / 'include'}", + *entry["arguments"][2:]]} + for entry in entries + ], + indent=2, + ) + ) + # Automatic jobs, the default, run in parallel too. + result = run_from_start_dir( + ["--timing", f"--compile-commands={absolute_compdb}", + "--compile-ir-cache-dir=caches-timing/compile-ir", *sources] + ) + timing = (result.stdout + result.stderr) if result else "" + if result is None or result.returncode != 0: + print(" ❌ automatic jobs with absolute include paths: run failed") + ok = False + elif "input.compiler.invoke.cwd" in timing: + print(" ❌ automatic jobs changed the working directory for absolute commands") + ok = False + else: + print(" ✅ automatic jobs kept the working directory for absolute commands") + + for mode in ([], ["--jobs=1"], ["--jobs=4"]): + label = mode[0] if mode else "default jobs" + for attempt in range(1, 4): + caches = f"caches-{label.replace('=', '').replace(' ', '-')}-{attempt}" + cmd = [ + analyzer, + "--format=json", + f"--compile-commands={compdb}", + "--resource-model=widget-model.txt", + f"--compile-ir-cache-dir={caches}/compile-ir", + f"--resource-summary-cache-dir={caches}/resource", + *mode, + *sources, + ] + result = run_from_start_dir(cmd[1:]) + if result is None: + print(f" ❌ {label}, run {attempt}: timed out") + ok = False + continue + problems = [] + if "cannot open model file" in result.stderr: + problems.append("the model failed to load") + try: + diagnostics = json.loads(result.stdout or "").get("diagnostics", []) + except json.JSONDecodeError: + diagnostics = None + problems.append(f"no JSON output (exit {result.returncode})") + if diagnostics is not None: + found = { + d.get("location", {}).get("function") + for d in diagnostics + if d.get("ruleId") == "ResourceLifetime.MissingRelease" + } + if found != expected: + problems.append(f"leaks reported in {sorted(found)}") + for cache in ("compile-ir", "resource"): + if not (run_dir / caches / cache).is_dir(): + problems.append(f"no {cache} cache under the start directory") + strays = sorted(str(p.relative_to(root)) for p in project.rglob(caches)) + if strays: + problems.append(f"caches under the compile directories: {strays}") + if problems: + print(f" ❌ {label}, run {attempt}: {'; '.join(problems)}") + ok = False + else: + print(f" ✅ {label}, run {attempt}: model used in {unit_count} files") + print() + return ok + + def check_resource_lifetime_cross_tu() -> bool: """ Regression: cross-TU resource summaries must propagate acquire/release effects @@ -5055,6 +5215,7 @@ def record_ok(ok: bool): check_exclude_dir_filter, check_multi_tu_folder_analysis, check_resource_lifetime_cross_tu, + check_resource_model_across_compile_directories, check_ownership_cross_tu, check_ownership_wrapper_metadata, check_uninitialized_cross_tu, From 372b3f303a426e76f778031b8cc0977132beea47 Mon Sep 17 00:00:00 2001 From: Hugo Date: Mon, 5 Oct 2026 11:53:12 +0200 Subject: [PATCH 02/10] fix(input): one lock for every compile and the whole working-directory change A compile that needs its compile command's directory changes the working directory of the whole process (#184). Three things let that leak into the rest of the run: - InputPipeline chose its path with config.jobs > 1, but jobs is 0 when automatic, the default: parallel loads then changed the directory for every file. It now uses resolveConfiguredJobs, moved out of AnalyzerApp into StackUsageAnalyzer for both, so parallel runs try a compile from the current directory first, as with an explicit job count. - The change was made before taking the compile lock, and the separate lock of the fallback covered fallbacks only. Two threads could save and restore the directory in an interleaved order, compile in a directory not their own, and leave the process in one. The compile lock is now taken before the change and held until it is undone; the fallback lock goes. - The resource, escape and buffer models, the compile IR and resource summary caches, the --dump-ir output and the compile database were opened through paths relative to whatever the directory was at that time. They are now anchored to the directory the analyzer starts from, once the arguments are parsed. A compile from its command's directory still changes the directory of the whole process while it runs; removing that needs compilerlib to compile against a working directory of its own. Refs #184 --- include/StackUsageAnalyzer.hpp | 4 ++++ src/StackUsageAnalyzer.cpp | 10 ++++++++++ src/analysis/InputPipeline.cpp | 14 +++++++------- src/app/AnalyzerApp.cpp | 9 --------- src/cli/ArgParser.cpp | 16 ++++++++++++++++ 5 files changed, 37 insertions(+), 16 deletions(-) diff --git a/include/StackUsageAnalyzer.hpp b/include/StackUsageAnalyzer.hpp index 7c9ccbb..845fc66 100644 --- a/include/StackUsageAnalyzer.hpp +++ b/include/StackUsageAnalyzer.hpp @@ -127,6 +127,10 @@ namespace ctrace::stack std::uint32_t reservedFlags : 17 = 0; }; + // The number of jobs the analysis runs: the configured count, or the hardware concurrency when + // jobs are automatic (jobs is then 0). + unsigned resolveConfiguredJobs(const AnalysisConfig& config); + // Per-function result struct FunctionResult { diff --git a/src/StackUsageAnalyzer.cpp b/src/StackUsageAnalyzer.cpp index 07a956b..f0ffa90 100644 --- a/src/StackUsageAnalyzer.cpp +++ b/src/StackUsageAnalyzer.cpp @@ -5,13 +5,23 @@ #include "analyzer/HotspotProfiler.hpp" #include "analysis/InputPipeline.hpp" +#include #include #include +#include #include namespace ctrace::stack { + unsigned resolveConfiguredJobs(const AnalysisConfig& config) + { + if (!config.jobsAuto) + return std::max(1u, config.jobs); + + const unsigned hw = std::thread::hardware_concurrency(); + return hw == 0 ? 1u : hw; + } AnalysisResult analyzeModule(llvm::Module& mod, const AnalysisConfig& config) { diff --git a/src/analysis/InputPipeline.cpp b/src/analysis/InputPipeline.cpp index e08272e..47d99de 100644 --- a/src/analysis/InputPipeline.cpp +++ b/src/analysis/InputPipeline.cpp @@ -38,12 +38,14 @@ namespace ctrace::stack::analysis { namespace { - std::mutex gCompileWorkingDirMutex; // compilerlib drives an in-process clang CompilerInstance. clang/LLVM keep global // mutable state (target registry, cl options, timers); two worker threads compiling // at once hung intermittently on the first compile of a run. Compilation is // serialised here; module analysis stays parallel, and the IR cache makes the - // compile step cheap on repeated runs. + // compile step cheap on repeated runs. A compile that needs its compile command's + // directory changes the working directory of the whole process: it holds the same + // lock from before that change until it is undone, so no other compile runs in a + // directory that is not its own, and two changes never interleave. std::mutex gCompileInvokeMutex; std::string makeAbsolutePath(const std::string& path) @@ -883,6 +885,7 @@ namespace ctrace::stack::analysis return compilerlib::compile(compileArgs, outputMode); } + std::lock_guard compileLock(gCompileInvokeMutex); std::string cwdError; ScopedCurrentPath cwdGuard(workingDir, cwdError); if (!cwdError.empty()) @@ -891,7 +894,6 @@ namespace ctrace::stack::analysis return std::nullopt; } const ScopedHotspot hotspot(config.timing, "input.compiler.invoke.cwd"); - std::lock_guard compileLock(gCompileInvokeMutex); return compilerlib::compile(compileArgs, outputMode); }; @@ -902,16 +904,14 @@ namespace ctrace::stack::analysis retriedWithWorkingDir = false; std::optional res; const bool hasWorkingDir = !workingDir.empty(); - if (config.jobs > 1 && hasWorkingDir) + if (resolveConfiguredJobs(config) > 1 && hasWorkingDir) { // Optimistic fast path for multi-job runs: most compdb commands use absolute // paths. res = compileWithOptionalWorkingDir(compileArgs, outputMode, false); if (!res || !res->success) { - // Fallback keeps correctness for relative include paths and avoids process - // cwd races. - std::lock_guard lock(gCompileWorkingDirMutex); + // Fallback keeps correctness for relative include paths. res = compileWithOptionalWorkingDir(compileArgs, outputMode, true); retriedWithWorkingDir = true; } diff --git a/src/app/AnalyzerApp.cpp b/src/app/AnalyzerApp.cpp index 7a037ed..58f5410 100644 --- a/src/app/AnalyzerApp.cpp +++ b/src/app/AnalyzerApp.cpp @@ -97,15 +97,6 @@ struct NormalizedPathFilters std::vector excludeDirs; }; -static unsigned resolveConfiguredJobs(const AnalysisConfig& cfg) -{ - if (!cfg.jobsAuto) - return std::max(1u, cfg.jobs); - - const unsigned hw = std::thread::hardware_concurrency(); - return hw == 0 ? 1u : hw; -} - #if defined(CTRACE_STACK_ANALYZER_HAS_PTHREAD) static std::size_t resolveParallelWorkerStackBytes() { diff --git a/src/cli/ArgParser.cpp b/src/cli/ArgParser.cpp index d267786..027c2d3 100644 --- a/src/cli/ArgParser.cpp +++ b/src/cli/ArgParser.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -1658,6 +1659,21 @@ namespace ctrace::stack::cli parsed.inputFilenames.emplace_back(std::move(argStr)); } + // The analysis opens these while other threads may be compiling from the directory of + // their compile command: they are anchored to the directory the analyzer starts from. + std::error_code startDirError; + const std::filesystem::path startDir = std::filesystem::current_path(startDirError); + if (!startDirError) + { + for (std::string* path : + {&cfg.escapeModelPath, &cfg.bufferModelPath, &cfg.resourceModelPath, + &cfg.resourceSummaryCacheDir, &cfg.compileIRCacheDir, &cfg.dumpIRPath, + &parsed.compileCommandsPath}) + { + *path = resolveConfigRelativePath(*path, startDir); + } + } + return result; } From 5ee76e8f7a941f8fcf468f25c50c7362f31d34ef Mon Sep 17 00:00:00 2001 From: Hugo Date: Wed, 7 Oct 2026 23:44:22 +0200 Subject: [PATCH 03/10] test(input): a header of the start directory must not replace the command's Review of #184: a compile command's relative -I resolves against its directory, but the analyzer first compiled from the current directory and only used the command's directory when that compile failed. When both directories hold the header, the start directory's one was used, with no error: on main with --jobs>1, and with automatic jobs since the fix for the working-directory race. check_resource_model_across_compile_directories now puts, in the start directory, a header of the same name for every file, one that drops the leak. Each mode must still report the 8 leaks. On 3b2260e, automatic jobs and --jobs=4 report none; --jobs=1 reports all 8. The check no longer requires automatic jobs to compile commands with absolute paths without changing the working directory: that was the behavior that picks the wrong header. Refs #184 --- run_test.py | 36 +++++++----------------------------- 1 file changed, 7 insertions(+), 29 deletions(-) diff --git a/run_test.py b/run_test.py index f1c0f10..82f3786 100755 --- a/run_test.py +++ b/run_test.py @@ -2081,8 +2081,8 @@ def check_resource_model_across_compile_directories() -> bool: directory; the analyzer must come back to the directory it started from, where the model and the relative cache directories are. Every run starts with empty caches, and a leak that only the model defines must be reported in every file. The relative paths must be anchored to the - start directory, and parallel jobs must not change the working directory for files whose - compile commands need no directory of their own. + start directory. The start directory also holds a header of the same name for every file, + one that drops the leak: a file compiled from there instead of its own directory loses it. """ print("=== Testing the resource model across compile-command directories ===") unit_count = 8 @@ -2115,7 +2115,11 @@ def check_resource_model_across_compile_directories() -> bool: compdb = project / "compile_commands.json" compdb.write_text(json.dumps(entries, indent=2)) run_dir = root / "run" - run_dir.mkdir() + (run_dir / "include").mkdir(parents=True) + for i in range(unit_count): + (run_dir / "include" / f"unit{i}.h").write_text( + "#define ct_open_widget() ((void*)0)\nvoid ct_close_widget(void* w);\n" + ) (run_dir / "widget-model.txt").write_text( "acquire_ret ct_open_widget Widget\nrelease_arg ct_close_widget 0 Widget\n" ) @@ -2157,32 +2161,6 @@ def run_from_start_dir(args): print(f" ❌ effective configuration lacks '{line}'") ok = False - absolute_compdb = project / "compile_commands_absolute.json" - absolute_compdb.write_text( - json.dumps( - [ - {**entry, "arguments": ["cc", f"-I{Path(entry['directory']) / 'include'}", - *entry["arguments"][2:]]} - for entry in entries - ], - indent=2, - ) - ) - # Automatic jobs, the default, run in parallel too. - result = run_from_start_dir( - ["--timing", f"--compile-commands={absolute_compdb}", - "--compile-ir-cache-dir=caches-timing/compile-ir", *sources] - ) - timing = (result.stdout + result.stderr) if result else "" - if result is None or result.returncode != 0: - print(" ❌ automatic jobs with absolute include paths: run failed") - ok = False - elif "input.compiler.invoke.cwd" in timing: - print(" ❌ automatic jobs changed the working directory for absolute commands") - ok = False - else: - print(" ✅ automatic jobs kept the working directory for absolute commands") - for mode in ([], ["--jobs=1"], ["--jobs=4"]): label = mode[0] if mode else "default jobs" for attempt in range(1, 4): From adb3d4e9f17f5fbce7b864d90704fb50893562eb Mon Sep 17 00:00:00 2001 From: Hugo Date: Wed, 7 Oct 2026 23:45:04 +0200 Subject: [PATCH 04/10] fix(input): compile every command in its own directory A compile command whose directory differs from the current one was first compiled from the current directory, and from its own only when that failed. Relative paths then resolved against the wrong directory without any error when both held the file: another header, another IR. This "optimistic fast path" (2289afb) predates the lock that serializes every compile (967be74), so it no longer ran anything in parallel. A command with a directory is now always compiled there, under the compile lock, whatever the job count. The retry and its log suffix go, and resolveConfiguredJobs returns to AnalyzerApp, its only user again. Refs #184 --- include/StackUsageAnalyzer.hpp | 4 -- src/StackUsageAnalyzer.cpp | 10 ----- src/analysis/InputPipeline.cpp | 79 +++++++++------------------------- src/app/AnalyzerApp.cpp | 9 ++++ 4 files changed, 29 insertions(+), 73 deletions(-) diff --git a/include/StackUsageAnalyzer.hpp b/include/StackUsageAnalyzer.hpp index 845fc66..7c9ccbb 100644 --- a/include/StackUsageAnalyzer.hpp +++ b/include/StackUsageAnalyzer.hpp @@ -127,10 +127,6 @@ namespace ctrace::stack std::uint32_t reservedFlags : 17 = 0; }; - // The number of jobs the analysis runs: the configured count, or the hardware concurrency when - // jobs are automatic (jobs is then 0). - unsigned resolveConfiguredJobs(const AnalysisConfig& config); - // Per-function result struct FunctionResult { diff --git a/src/StackUsageAnalyzer.cpp b/src/StackUsageAnalyzer.cpp index f0ffa90..07a956b 100644 --- a/src/StackUsageAnalyzer.cpp +++ b/src/StackUsageAnalyzer.cpp @@ -5,23 +5,13 @@ #include "analyzer/HotspotProfiler.hpp" #include "analysis/InputPipeline.hpp" -#include #include #include -#include #include namespace ctrace::stack { - unsigned resolveConfiguredJobs(const AnalysisConfig& config) - { - if (!config.jobsAuto) - return std::max(1u, config.jobs); - - const unsigned hw = std::thread::hardware_concurrency(); - return hw == 0 ? 1u : hw; - } AnalysisResult analyzeModule(llvm::Module& mod, const AnalysisConfig& config) { diff --git a/src/analysis/InputPipeline.cpp b/src/analysis/InputPipeline.cpp index 47d99de..e67e02f 100644 --- a/src/analysis/InputPipeline.cpp +++ b/src/analysis/InputPipeline.cpp @@ -874,18 +874,19 @@ namespace ctrace::stack::analysis const std::vector bitcodeArgs = buildBitcodeCompileArgs(args, tempBitcodePath); - auto compileWithOptionalWorkingDir = - [&](const std::vector& compileArgs, compilerlib::OutputMode outputMode, - bool useWorkingDir) -> std::optional + // A compile command's relative paths are relative to its directory: compile there, + // even when the current directory also resolves them, to another header. + auto compileInWorkingDir = + [&](const std::vector& compileArgs, + compilerlib::OutputMode outputMode) -> std::optional { - if (!useWorkingDir) + std::lock_guard compileLock(gCompileInvokeMutex); + if (workingDir.empty()) { const ScopedHotspot hotspot(config.timing, "input.compiler.invoke"); - std::lock_guard compileLock(gCompileInvokeMutex); return compilerlib::compile(compileArgs, outputMode); } - std::lock_guard compileLock(gCompileInvokeMutex); std::string cwdError; ScopedCurrentPath cwdGuard(workingDir, cwdError); if (!cwdError.empty()) @@ -897,32 +898,6 @@ namespace ctrace::stack::analysis return compilerlib::compile(compileArgs, outputMode); }; - auto compileWithConfiguredWorkingDir = - [&](const std::vector& compileArgs, compilerlib::OutputMode outputMode, - bool& retriedWithWorkingDir) -> std::optional - { - retriedWithWorkingDir = false; - std::optional res; - const bool hasWorkingDir = !workingDir.empty(); - if (resolveConfiguredJobs(config) > 1 && hasWorkingDir) - { - // Optimistic fast path for multi-job runs: most compdb commands use absolute - // paths. - res = compileWithOptionalWorkingDir(compileArgs, outputMode, false); - if (!res || !res->success) - { - // Fallback keeps correctness for relative include paths. - res = compileWithOptionalWorkingDir(compileArgs, outputMode, true); - retriedWithWorkingDir = true; - } - } - else - { - res = compileWithOptionalWorkingDir(compileArgs, outputMode, hasWorkingDir); - } - return res; - }; - if (cachePaths.enabled) { auto cached = [&]() -> std::optional @@ -1044,7 +1019,6 @@ namespace ctrace::stack::analysis } } - bool retriedWithWorkingDir = false; bool compiledViaBitcode = false; std::optional res; std::optional sourceSnapshot; @@ -1057,20 +1031,14 @@ namespace ctrace::stack::analysis preferBitcodeCompile ? bitcodeArgs : args; appendDependencyCaptureArgs(cacheCompileArgs, cachePaths.depFile); - bool retriedForDependencyCompile = false; - res = compileWithConfiguredWorkingDir(cacheCompileArgs, - preferBitcodeCompile - ? compilerlib::OutputMode::ToFile - : compilerlib::OutputMode::ToMemory, - retriedForDependencyCompile); - retriedWithWorkingDir = retriedForDependencyCompile; + res = compileInWorkingDir(cacheCompileArgs, + preferBitcodeCompile ? compilerlib::OutputMode::ToFile + : compilerlib::OutputMode::ToMemory); if (preferBitcodeCompile && (!res || !res->success)) { - bool retriedForFallbackCompile = false; - auto fallbackResult = compileWithConfiguredWorkingDir( - args, compilerlib::OutputMode::ToMemory, retriedForFallbackCompile); - retriedWithWorkingDir = retriedWithWorkingDir || retriedForFallbackCompile; + auto fallbackResult = + compileInWorkingDir(args, compilerlib::OutputMode::ToMemory); if (fallbackResult) res = std::move(fallbackResult); } @@ -1100,21 +1068,17 @@ namespace ctrace::stack::analysis } else { - res = compileWithConfiguredWorkingDir(preferBitcodeCompile ? bitcodeArgs : args, - preferBitcodeCompile - ? compilerlib::OutputMode::ToFile - : compilerlib::OutputMode::ToMemory, - retriedWithWorkingDir); + res = compileInWorkingDir(preferBitcodeCompile ? bitcodeArgs : args, + preferBitcodeCompile ? compilerlib::OutputMode::ToFile + : compilerlib::OutputMode::ToMemory); if (res && res->success) { compiledViaBitcode = preferBitcodeCompile; } else if (preferBitcodeCompile) { - bool retriedForFallbackCompile = false; - auto fallbackResult = compileWithConfiguredWorkingDir( - args, compilerlib::OutputMode::ToMemory, retriedForFallbackCompile); - retriedWithWorkingDir = retriedWithWorkingDir || retriedForFallbackCompile; + auto fallbackResult = + compileInWorkingDir(args, compilerlib::OutputMode::ToMemory); if (fallbackResult) res = std::move(fallbackResult); } @@ -1140,8 +1104,7 @@ namespace ctrace::stack::analysis auto ms = std::chrono::duration_cast(compileEnd - compileStart) .count(); - coretrace::log(coretrace::Level::Info, "Compilation done in {} ms{}\n", ms, - retriedWithWorkingDir ? " (retry with working directory)" : ""); + coretrace::log(coretrace::Level::Info, "Compilation done in {} ms\n", ms); } std::string llvmIRForCache; @@ -1195,10 +1158,8 @@ namespace ctrace::stack::analysis { if (compiledViaBitcode) { - bool retriedForTextFallback = false; - auto textFallback = compileWithConfiguredWorkingDir( - args, compilerlib::OutputMode::ToMemory, retriedForTextFallback); - retriedWithWorkingDir = retriedWithWorkingDir || retriedForTextFallback; + auto textFallback = + compileInWorkingDir(args, compilerlib::OutputMode::ToMemory); if (!textFallback) return result; res = std::move(textFallback); diff --git a/src/app/AnalyzerApp.cpp b/src/app/AnalyzerApp.cpp index 58f5410..7a037ed 100644 --- a/src/app/AnalyzerApp.cpp +++ b/src/app/AnalyzerApp.cpp @@ -97,6 +97,15 @@ struct NormalizedPathFilters std::vector excludeDirs; }; +static unsigned resolveConfiguredJobs(const AnalysisConfig& cfg) +{ + if (!cfg.jobsAuto) + return std::max(1u, cfg.jobs); + + const unsigned hw = std::thread::hardware_concurrency(); + return hw == 0 ? 1u : hw; +} + #if defined(CTRACE_STACK_ANALYZER_HAS_PTHREAD) static std::size_t resolveParallelWorkerStackBytes() { From 6016573a9b775b119e938aca16a7bbb504fea0e3 Mon Sep 17 00:00:00 2001 From: Hugo Date: Wed, 7 Oct 2026 23:45:23 +0200 Subject: [PATCH 05/10] test(cli): a requested model that cannot be read must fail the run Review of #184: each analysis loads its model itself, logs a failure to stderr and goes on without it. A resource, escape or buffer model given on the command line but missing ends with code 0 and no finding, and run_code_analysis.py reports "CI gate passed". check_unreadable_model_fails gives each of the three options a missing file and a directory: the analyzer must exit with a nonzero code naming the path. run_code_analysis.py given a missing resource model must fail. On 274c1c1 all six runs exit with 0 and the CI script passes. A model that can be read but is malformed keeps its current handling (check_escape_model_rejects_unsupported_brackets); it is a separate question. Refs #184 --- run_test.py | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/run_test.py b/run_test.py index 82f3786..f59aece 100755 --- a/run_test.py +++ b/run_test.py @@ -3501,6 +3501,43 @@ def check_escape_model_rejects_unsupported_brackets() -> bool: return True +def check_unreadable_model_fails() -> bool: + """ + A model the command line asks for, but that cannot be read, is a configuration error: the + analyzer must stop with a nonzero code naming the file, and run_code_analysis.py must fail, + instead of analyzing without the model and reporting success. + """ + print("=== Testing that a requested model that cannot be read fails the run ===") + ok = True + with tempfile.TemporaryDirectory(prefix="ct_unreadable_model_") as tmp: + tmpdir = Path(tmp) + source = tmpdir / "leak.c" + source.write_text("void* acquire_handle(void);\nvoid leak(void) { (void)acquire_handle(); }\n") + missing = tmpdir / "missing-model.txt" + for option in ("--resource-model", "--escape-model", "--buffer-model"): + for path, what in ((missing, "missing file"), (tmpdir, "directory")): + result = run_analyzer_uncached([f"{option}={path}", str(source)]) + output = (result.stdout or "") + (result.stderr or "") + if result.returncode != 0 and str(path) in output: + print(f" ✅ {option}, {what}: code {result.returncode}, file named") + else: + print(f" ❌ {option}, {what}: code {result.returncode}, file named: {str(path) in output}") + ok = False + script = _run_ci_script( + ["--analyzer", str(RUN_CONFIG.analyzer), "--fail-on", "warning", + f"--analyzer-arg=--resource-model={missing}", str(source)], + jobs=1, + ) + if script.returncode != 0: + print(f" ✅ run_code_analysis.py with a missing model: code {script.returncode}") + else: + print(" ❌ run_code_analysis.py passed with a missing model") + print((script.stdout or "") + (script.stderr or "")) + ok = False + print() + return ok + + def check_docker_entrypoint_guardrails() -> bool: """ Regression: docker wrapper should only create compatibility symlinks under @@ -5207,6 +5244,7 @@ def record_ok(ok: bool): check_noreturn_cross_tu, check_use_after_free_advanced_inter_tu, check_escape_model_rejects_unsupported_brackets, + check_unreadable_model_fails, check_human_vs_json_parity, check_diagnostic_rule_coverage_regression, check_diagnostic_cwe_coverage, From e2e9f875e98b4dc4719f90e7cdc5829e99deeb66 Mon Sep 17 00:00:00 2001 From: Hugo Date: Wed, 7 Oct 2026 23:45:58 +0200 Subject: [PATCH 06/10] fix(app): stop when a requested model file cannot be read The resource, escape and buffer models are read by the analyses that use them, which log a failure and run without the model. A missing model then passed for a run that found nothing, and run_code_analysis.py for a passing CI gate. Before any input is loaded, every model given on the command line or in the config file must now be a readable file; otherwise the run stops with "Cannot read model file: " and exit code 1, which the CI script already turns into a failure. This check covers missing and unreadable files only. A model that can be read but holds malformed rules is still reported on stderr and skipped by the analysis: a separate question, noted in the README. Refs #184 --- README.md | 1 + src/app/AnalyzerApp.cpp | 24 ++++++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/README.md b/README.md index 5476cb8..caf8c04 100644 --- a/README.md +++ b/README.md @@ -249,6 +249,7 @@ Ready-to-adapt workflow examples: --escape-model= loads external noescape rules for stack pointer escape analysis (`noescape_arg`) --buffer-model= loads external buffer write rules for copy/string overflow checks (`bounded_write`/`unbounded_write`) --resource-model= loads external acquire/release rules for generic resource lifetime checks +A model path given to one of these three options that is not a readable file stops the run with an error (exit code 1). A model that can be read but holds malformed rules is reported on stderr, and the analysis runs without it. --resource-cross-tu enables cross-TU resource summaries for resource lifetime analysis (default: on) --no-resource-cross-tu disables cross-TU resource summaries --resource-summary-cache-dir= sets cache directory for cross-TU resource summaries (default: .cache/resource-lifetime) diff --git a/src/app/AnalyzerApp.cpp b/src/app/AnalyzerApp.cpp index 7a037ed..ed68226 100644 --- a/src/app/AnalyzerApp.cpp +++ b/src/app/AnalyzerApp.cpp @@ -835,6 +835,26 @@ static AppStatus configureDumpIRPath(const std::vector& inputFilena return AppStatus::success(); } +// A model the command line asks for is read by the analyses that use it, which only log a +// failure and run without it: an unreadable model would pass for a run that found nothing. +static AppStatus checkRequestedModelsReadable(const AnalysisConfig& cfg) +{ + const std::pair models[] = { + {"resource", &cfg.resourceModelPath}, + {"stack escape", &cfg.escapeModelPath}, + {"buffer", &cfg.bufferModelPath}, + }; + for (const auto& [kind, path] : models) + { + if (path->empty()) + continue; + std::error_code fsErr; + if (!std::filesystem::is_regular_file(*path, fsErr) || !std::ifstream(*path)) + return AppStatus::failure(std::string("Cannot read ") + kind + " model file: " + *path); + } + return AppStatus::success(); +} + static void printInterprocStatus(const AnalysisConfig& cfg, std::size_t inputCount, bool needsCrossTUResourceSummaries, bool needsCrossTUUninitializedSummaries, @@ -2616,6 +2636,10 @@ class RunPlanBuilder plan.sarifBaseDir = std::move(parsedArgs_.sarifBaseDir); plan.sarifOutPath = std::move(parsedArgs_.sarifOutPath); + AppStatus modelStatus = checkRequestedModelsReadable(plan.cfg); + if (!modelStatus.isOk()) + return AppResult::failure(std::move(modelStatus.error)); + if (parsedArgs_.compileCommandsExplicit) { AppStatus loadStatus = From d3824fdd8cd1c934b7a47e1832be7b9e26f6d92b Mon Sep 17 00:00:00 2001 From: Hugo Date: Thu, 8 Oct 2026 18:16:37 +0200 Subject: [PATCH 07/10] test(input): relative input paths with parallel compiles from other directories Review of #187: a compile command with a directory of its own is now always compiled there, and the change of directory holds for the whole process. Meanwhile, another thread resolves its own relative input path against that directory, to find its compile command and to compile it: with 24 files given by relative paths, --jobs=4 fails with "No compile command found for: src/unit03.c", where --jobs=1 and main succeed. check_resource_model_across_compile_directories now runs every mode with the files given by absolute paths, then by paths relative to the start directory, each run with empty caches of its own. Each must report the 8 leaks and name each file as it was given (#124). On e2e9f87, 5 of the 6 parallel runs with relative paths fail; --jobs=1 and absolute paths pass. Refs #184 --- run_test.py | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/run_test.py b/run_test.py index f59aece..893f6ba 100755 --- a/run_test.py +++ b/run_test.py @@ -2083,6 +2083,9 @@ def check_resource_model_across_compile_directories() -> bool: the model defines must be reported in every file. The relative paths must be anchored to the start directory. The start directory also holds a header of the same name for every file, one that drops the leak: a file compiled from there instead of its own directory loses it. + The files are given by absolute paths, then by paths relative to the start directory, which + must resolve there whatever directory another file is compiling from at the time; the + results name each file as it was given. """ print("=== Testing the resource model across compile-command directories ===") unit_count = 8 @@ -2161,10 +2164,16 @@ def run_from_start_dir(args): print(f" ❌ effective configuration lacks '{line}'") ok = False - for mode in ([], ["--jobs=1"], ["--jobs=4"]): - label = mode[0] if mode else "default jobs" + relative_sources = [os.path.relpath(source, run_dir) for source in sources] + runs = [ + (paths, given, mode) + for paths, given in (("absolute paths", sources), ("relative paths", relative_sources)) + for mode in ([], ["--jobs=1"], ["--jobs=4"]) + ] + for paths, given, mode in runs: + label = f"{paths}, {mode[0] if mode else 'default jobs'}" for attempt in range(1, 4): - caches = f"caches-{label.replace('=', '').replace(' ', '-')}-{attempt}" + caches = f"caches-{label.replace('=', '').replace(', ', '-').replace(' ', '-')}-{attempt}" cmd = [ analyzer, "--format=json", @@ -2173,7 +2182,7 @@ def run_from_start_dir(args): f"--compile-ir-cache-dir={caches}/compile-ir", f"--resource-summary-cache-dir={caches}/resource", *mode, - *sources, + *given, ] result = run_from_start_dir(cmd[1:]) if result is None: @@ -2196,6 +2205,13 @@ def run_from_start_dir(args): } if found != expected: problems.append(f"leaks reported in {sorted(found)}") + files = { + d.get("location", {}).get("file") + for d in diagnostics + if d.get("ruleId") == "ResourceLifetime.MissingRelease" + } + if found == expected and files != set(given): + problems.append(f"leaks not named as given: {sorted(files)}") for cache in ("compile-ir", "resource"): if not (run_dir / caches / cache).is_dir(): problems.append(f"no {cache} cache under the start directory") From c5911fb00cad4f218bf876b31ad4031168a4cc9d Mon Sep 17 00:00:00 2001 From: Hugo Date: Thu, 8 Oct 2026 18:18:36 +0200 Subject: [PATCH 08/10] fix(input): resolve relative input paths from the directory the run started in A compile command with a directory of its own is compiled from there, and the change of directory holds for the whole process while it lasts. loadModuleForAnalysis resolved a relative input against the current directory: to find its compile command, to compile it, for its compile IR cache key and to read it. Another thread could then resolve it from a compile command's directory, and with --jobs=4 an input given as src/unit03.c had no compile command. The directory the analyzer starts from is now recorded with the other anchored paths, as AnalysisConfig::inputBaseDir, before any input is loaded. Every access to an input goes through its path resolved from there. The path given is kept for messages and results (#124), and a file without a compile command is still compiled under the name given: no other thread changes the directory while a compile holds the lock. Refs #184 --- include/StackUsageAnalyzer.hpp | 2 ++ src/analysis/InputPipeline.cpp | 46 ++++++++++++++++------------------ src/cli/ArgParser.cpp | 1 + 3 files changed, 25 insertions(+), 24 deletions(-) diff --git a/include/StackUsageAnalyzer.hpp b/include/StackUsageAnalyzer.hpp index 7c9ccbb..27d9988 100644 --- a/include/StackUsageAnalyzer.hpp +++ b/include/StackUsageAnalyzer.hpp @@ -93,6 +93,8 @@ namespace ctrace::stack std::string smtSecondaryBackend; std::string smtBackend = "interval"; std::string dumpIRPath; + // The directory relative input paths resolve from; empty: the current one at load. + std::string inputBaseDir; std::string escapeModelPath; std::string bufferModelPath; std::string resourceModelPath; diff --git a/src/analysis/InputPipeline.cpp b/src/analysis/InputPipeline.cpp index e67e02f..a7bddfa 100644 --- a/src/analysis/InputPipeline.cpp +++ b/src/analysis/InputPipeline.cpp @@ -48,15 +48,6 @@ namespace ctrace::stack::analysis // directory that is not its own, and two changes never interleave. std::mutex gCompileInvokeMutex; - std::string makeAbsolutePath(const std::string& path) - { - std::error_code ec; - std::filesystem::path absPath = std::filesystem::absolute(path, ec); - if (ec) - return path; - return absPath.lexically_normal().generic_string(); - } - void appendIfMissing(std::vector& args, const std::string& flag) { if (std::find(args.begin(), args.end(), flag) == args.end()) @@ -661,14 +652,15 @@ namespace ctrace::stack::analysis return true; } - bool buildCompileArgs(const std::string& filename, LanguageType language, - const AnalysisConfig& config, std::vector& args, - std::string& workingDir, std::string& error) + bool buildCompileArgs(const std::string& filename, const std::string& inputPath, + LanguageType language, const AnalysisConfig& config, + std::vector& args, std::string& workingDir, + std::string& error) { const CompileCommand* command = nullptr; if (config.compilationDatabase) { - command = config.compilationDatabase->findCommandForFile(filename); + command = config.compilationDatabase->findCommandForFile(inputPath); } if (command) @@ -713,7 +705,7 @@ namespace ctrace::stack::analysis args.push_back("-g"); appendIfMissing(args, "-fno-discard-value-names"); const bool useAbsolutePath = (command != nullptr); - args.push_back(useAbsolutePath ? makeAbsolutePath(filename) : filename); + args.push_back(useAbsolutePath ? inputPath : filename); return true; } @@ -822,13 +814,19 @@ namespace ctrace::stack::analysis using ctrace::stack::analyzer::ScopedHotspot; ModuleLoadResult result; const ScopedHotspot totalHotspot(config.timing, "input.load_module.total"); + // A relative input resolves from the directory the analysis started in, not from the + // current one: another thread may be compiling from its compile command's directory, + // which the whole process shares meanwhile. std::error_code cwdErr; - std::filesystem::path baseDir = std::filesystem::current_path(cwdErr); + const std::filesystem::path baseDir = config.inputBaseDir.empty() + ? std::filesystem::current_path(cwdErr) + : std::filesystem::path(config.inputBaseDir); + const std::string inputPath = makeAbsolutePathFrom(filename, baseDir.string()); using Clock = std::chrono::steady_clock; auto compileStart = Clock::now(); { const ScopedHotspot hotspot(config.timing, "input.detect_language"); - result.language = detectLanguageFromFile(filename, ctx); + result.language = detectLanguageFromFile(inputPath, ctx); } if (result.language == LanguageType::Unknown) @@ -846,8 +844,8 @@ namespace ctrace::stack::analysis bool compileArgsReady = false; { const ScopedHotspot hotspot(config.timing, "input.build_compile_args"); - compileArgsReady = buildCompileArgs(filename, result.language, config, args, - workingDir, compileError); + compileArgsReady = buildCompileArgs(filename, inputPath, result.language, config, + args, workingDir, compileError); } if (!compileArgsReady) { @@ -859,7 +857,7 @@ namespace ctrace::stack::analysis coretrace::log(coretrace::Level::Info, "Compiling {}...\n", filename); const bool preferBitcodeCompile = (config.compileIRFormat == CompileIRFormat::BC); const CompileIRCachePaths cachePaths = - buildCompileIRCachePaths(config, filename, result.language, args, workingDir); + buildCompileIRCachePaths(config, inputPath, result.language, args, workingDir); std::error_code tempDirErr; std::filesystem::path tempDir = std::filesystem::temp_directory_path(tempDirErr); @@ -1051,7 +1049,7 @@ namespace ctrace::stack::analysis "input.cache.parse_dependencies"); return parseDepfileDependencies(cachePaths.depFile, workingDir); }(); - const std::string sourcePath = makeAbsolutePathFrom(filename, workingDir); + const std::string& sourcePath = inputPath; sourceSnapshot = [&]() -> std::optional { const ScopedHotspot hotspot(config.timing, @@ -1257,7 +1255,7 @@ namespace ctrace::stack::analysis cwdErr ? std::string() : baseDir.lexically_normal().generic_string(); const CompileIRCachePaths cachePaths = isTextIRInput - ? buildCompileIRCachePaths(config, filename, result.language, {}, cacheWorkingDir) + ? buildCompileIRCachePaths(config, inputPath, result.language, {}, cacheWorkingDir) : CompileIRCachePaths{}; if (isTextIRInput && cachePaths.enabled) @@ -1359,7 +1357,7 @@ namespace ctrace::stack::analysis const auto parseStart = Clock::now(); { const ScopedHotspot hotspot(config.timing, "input.parse_ir_file"); - result.module = llvm::parseIRFile(filename, err, ctx); + result.module = llvm::parseIRFile(inputPath, err, ctx); } if (config.timing) { @@ -1373,10 +1371,10 @@ namespace ctrace::stack::analysis { if (isTextIRInput && cachePaths.enabled) { - if (const auto sourceSnapshot = captureFileSnapshot(filename)) + if (const auto sourceSnapshot = captureFileSnapshot(inputPath)) { std::string sourceIR; - (void)readTextFile(filename, sourceIR); + (void)readTextFile(inputPath, sourceIR); std::string llvmBitcode; llvm::raw_string_ostream bitcodeStream(llvmBitcode); diff --git a/src/cli/ArgParser.cpp b/src/cli/ArgParser.cpp index 027c2d3..9348d6a 100644 --- a/src/cli/ArgParser.cpp +++ b/src/cli/ArgParser.cpp @@ -1672,6 +1672,7 @@ namespace ctrace::stack::cli { *path = resolveConfigRelativePath(*path, startDir); } + cfg.inputBaseDir = startDir.string(); } return result; From 934ba5c5913a6174c2fb655d5705a3fadf4b652a Mon Sep 17 00:00:00 2001 From: Hugo Date: Thu, 8 Oct 2026 18:19:37 +0200 Subject: [PATCH 09/10] test(input): a compile IR cache entry of the previous schema must be compiled again Review of #187: the compile IR cache keeps the IR that the previous pipeline built from the current directory, with a header of the same name as the compile command's own, under schema compile-ir-cache-v2. A run that now compiles from the command's directory reused it: 7 where a run with an empty cache gives 42. check_compile_ir_cache_rebuilds_previous_schema rewrites the entry of the current key as the previous pipeline left it: the previous schema, and the IR built with the start directory's header, with the sources and dependencies left valid. The next run must compile again, give 42 and rewrite the entry, and the run after it must reuse that entry. An entry stored under a previous key is never looked up again; the schema in the key covers it, not this check. On c5911fb the stale entry is reused: 7. Refs #184 --- run_test.py | 78 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) diff --git a/run_test.py b/run_test.py index 893f6ba..538241e 100755 --- a/run_test.py +++ b/run_test.py @@ -3517,6 +3517,83 @@ def check_escape_model_rejects_unsupported_brackets() -> bool: return True +def check_compile_ir_cache_rebuilds_previous_schema() -> bool: + """ + A file used to be compiled from the current directory, and from its compile command's only + when that failed: with a header of the same name in both, the compile IR cache kept the IR + built with the wrong one. Compiling from the command's directory changes the IR of an + unchanged command, so the cache schema changed. + + The schema is in two places: the cache key, and the metadata of each entry. An entry stored + under a previous key is never looked up again; this check covers the other one. It rewrites + the entry of the current key as the previous pipeline left it: the previous schema, and the + IR built with the start directory's header (7, where the command's header gives 42), with + the sources and dependencies left valid. The next run must compile again and give 42, and + rewrite the entry; the run after it must reuse that entry and give 42 again. + """ + print("=== Testing that compile IR cached under a previous schema is rebuilt ===") + ok = True + with tempfile.TemporaryDirectory(prefix="ct_compile_ir_schema_") as tmp: + root = Path(tmp) + (root / "start" / "include").mkdir(parents=True) + (root / "start" / "include" / "config.h").write_text("#define VALUE 7\n") + (root / "project" / "build" / "include").mkdir(parents=True) + (root / "project" / "build" / "include" / "config.h").write_text("#define VALUE 42\n") + source = root / "project" / "value.c" + source.write_text("#include \nint value(void) { return VALUE; }\n") + compdb = root / "project" / "compile_commands.json" + compdb.write_text(json.dumps([{ + "directory": str(root / "project" / "build"), + "file": str(source), + "arguments": ["cc", "-Iinclude", "-c", str(source)], + }])) + cache = root / "compile-ir" + analyzer = str(Path(RUN_CONFIG.analyzer).resolve()) + + def run(name): + dump = root / f"ir-{name}" + try: + result = subprocess.run( + [analyzer, "--timing", f"--compile-commands={compdb}", + "--compile-ir-format=ll", f"--compile-ir-cache-dir={cache}", + f"--dump-ir={dump}/", str(source)], + cwd=root / "start", capture_output=True, text=True, + timeout=RUN_CONFIG.analyzer_timeout, + ) + except subprocess.TimeoutExpired: + return None, False + returned = re.findall(r"ret i32 (\d+)", "".join(p.read_text() for p in dump.glob("*.ll"))) + return (returned[0] if returned else None), "Compilation cache hit" in result.stderr + + value, _ = run("empty") + entries = sorted(cache.glob("*.json")) + if value != "42" or len(entries) != 1: + print(f" ❌ with an empty cache: returns {value}, {len(entries)} cache entries") + return False + metadata = json.loads(entries[0].read_text()) + current = metadata["schema"] + ir_file = entries[0].with_suffix(".ll") + metadata["schema"] = "compile-ir-cache-v2" + entries[0].write_text(json.dumps(metadata)) + ir_file.write_text(ir_file.read_text().replace("ret i32 42", "ret i32 7")) + + value, hit = run("previous") + rewritten = json.loads(entries[0].read_text())["schema"] + if value == "42" and not hit and rewritten == current: + print(" ✅ an entry of the previous schema is compiled again and rewritten") + else: + ok = False + print(f" ❌ with the previous schema: returns {value}, cache hit {hit}, entry schema {rewritten}") + value, hit = run("rebuilt") + if value == "42" and hit: + print(" ✅ the rewritten entry is reused") + else: + ok = False + print(f" ❌ after the rebuild: returns {value}, cache hit {hit}") + print() + return ok + + def check_unreadable_model_fails() -> bool: """ A model the command line asks for, but that cannot be read, is a configuration error: the @@ -5260,6 +5337,7 @@ def record_ok(ok: bool): check_noreturn_cross_tu, check_use_after_free_advanced_inter_tu, check_escape_model_rejects_unsupported_brackets, + check_compile_ir_cache_rebuilds_previous_schema, check_unreadable_model_fails, check_human_vs_json_parity, check_diagnostic_rule_coverage_regression, From 7962221284abefcee4fdcbbd29d681f07eae34cf Mon Sep 17 00:00:00 2001 From: Hugo Date: Thu, 8 Oct 2026 18:19:47 +0200 Subject: [PATCH 10/10] fix(input): move the compile IR cache to schema v3 A compile command with a directory of its own is now always compiled from there, so an unchanged command can give other IR than before: the IR of a file whose header of the same name also sits in the start directory. The compile IR cache kept the previous IR under the same key and accepted it, and the fix had no effect on a cache filled before it. The schema becomes compile-ir-cache-v3, in the cache key and in the metadata of each entry: previous entries are no longer looked up, and an entry whose metadata names the previous schema is compiled again. Refs #184 --- src/analysis/InputPipeline.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/analysis/InputPipeline.cpp b/src/analysis/InputPipeline.cpp index a7bddfa..b19df82 100644 --- a/src/analysis/InputPipeline.cpp +++ b/src/analysis/InputPipeline.cpp @@ -192,7 +192,7 @@ namespace ctrace::stack::analysis } } - constexpr llvm::StringLiteral kCompileIRCacheSchema = "compile-ir-cache-v2"; + constexpr llvm::StringLiteral kCompileIRCacheSchema = "compile-ir-cache-v3"; struct FileSnapshot {