Skip to content
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@ Notable changes are grouped by release. See [all releases](https://github.com/Co

## Unreleased

- `scripts/ci/run_code_analysis.py` gives `--jobs=1` to each analyzer when it runs one on every
processor. Each of them used to choose its own number of threads, as if it had every processor
to itself. A `--jobs` or a `--config` passed through `--analyzer-arg` keeps the caller's
choice. Fewer analyzers than processors still choose for themselves: the script runs at most
one per processor, and fewer when the inputs split into fewer groups. On this repository's
self-analysis, with 4 analyzers on 4 processors, `--jobs=1` changed the time of the run by
less than 2 % and lowered its memory peak by 4 to 7 %.
- `ResourceLifetime.DoubleRelease` is decided release by release by the ownership engine where
it can. A release of a pointer that holds only NULL or a resource still owned no longer gets a
report: a release on each branch of an `if`/`else` or `switch`, in a `catch` that returns,
Expand Down
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,12 @@ python3 scripts/ci/run_code_analysis.py \
--sarif-out artifacts/stack-usage.sarif
```

The adapter splits the inputs between at most one analyzer per processor (`ANALYZER_JOBS=<n>`
sets another limit) and runs them at once. When that puts an analyzer on every processor, each
one runs with `--jobs=1`; fewer analyzers than processors each choose their own number of
threads. To choose otherwise, pass `--analyzer-arg=--jobs=<N>`, or a configuration file with
`--analyzer-arg=--config=<path>`.

GitHub Actions consumer example is available at:
- `docs/ci/github-actions-consumer.yml`
- `docs/ci/github-actions-module-consumer.yml` (consume this repo directly via `uses:`)
Expand Down
89 changes: 89 additions & 0 deletions run_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -5438,6 +5438,94 @@ def run_script(*names: str) -> subprocess.CompletedProcess:
return ok


def check_ci_script_analyzer_jobs() -> bool:
"""
run_code_analysis.py runs its analyzers at once, by default at most one per processor. Left
to itself, each of them counts on every processor for its own threads. When every processor
already has its analyzer, the script must give each analyzer --jobs=1, unless the caller
chooses through --jobs or through a configuration file, which may set jobs. Fewer analyzers
than processors keep their own choice, and so does a single analyzer. A stand-in analyzer
then writes down the --jobs arguments that a run of the script gives it.
"""
print("=== Testing CI script analyzer jobs ===")
spec = importlib.util.spec_from_file_location("run_code_analysis", CI_SCRIPT)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
analyzer_jobs_args = getattr(module, "analyzer_jobs_args", None)
if analyzer_jobs_args is None:
print(f" ❌ {CI_SCRIPT.name} has no analyzer_jobs_args")
print()
return False

ok = True
model = "--resource-model=generic.txt"
# (arguments from the caller, analyzers at once, processors), then what each analyzer gets.
rule_cases = [
(([model], 4, 4), [model, "--jobs=1"]),
(([model], 4, 2), [model, "--jobs=1"]),
(([model], 2, 4), [model]),
(([model], 1, 4), [model]),
(([model], 1, 1), [model]),
((["--jobs=3"], 4, 4), ["--jobs=3"]),
((["--jobs", "3"], 4, 4), ["--jobs", "3"]),
((["--config=analyzer.cfg"], 4, 4), ["--config=analyzer.cfg"]),
((["--config", "analyzer.cfg"], 4, 4), ["--config", "analyzer.cfg"]),
]
for arguments, expected in rule_cases:
given = analyzer_jobs_args(*arguments)
if given != expected:
print(f" ❌ analyzer_jobs_args{arguments} gives {given}, expected {expected}")
ok = False

stand_in = textwrap.dedent(
"""\
#!/usr/bin/env python3
import json, os, sys
from pathlib import Path

jobs = [a for a in sys.argv[1:] if a == "--jobs" or a.startswith("--jobs=")]
Path(__file__).with_name(f"jobs-{os.getpid()}.json").write_text(json.dumps(jobs))
print(json.dumps({"diagnostics": []}))
"""
)
# One analyzer per input, and at least as many as this machine has processors.
analyzers = max(2, os.cpu_count() or 1)
with tempfile.TemporaryDirectory() as tmp:
analyzer = Path(tmp) / "stand-in-analyzer"
analyzer.write_text(stand_in)
analyzer.chmod(0o755)
inputs = []
for i in range(analyzers):
path = Path(tmp) / f"unit_{i}.c"
path.write_text("int f(void) { return 0; }\n")
inputs.append(str(path))

def jobs_given(*analyzer_args: str) -> Optional[list]:
"""The --jobs arguments of each analyzer the script ran, or None when it failed."""
for seen in Path(tmp).glob("jobs-*.json"):
seen.unlink()
args = ["--analyzer", str(analyzer), "--fail-on", "none",
*[f"--analyzer-arg={arg}" for arg in analyzer_args], *inputs]
result = _run_ci_script(args, jobs=analyzers)
if result.returncode != 0:
print((result.stdout or "") + (result.stderr or ""))
return None
return sorted(json.loads(seen.read_text()) for seen in Path(tmp).glob("jobs-*.json"))

run_cases = [
("an analyzer on every processor", jobs_given(), [["--jobs=1"]] * analyzers),
("the same, --jobs=3 from the caller", jobs_given("--jobs=3"), [["--jobs=3"]] * analyzers),
]
for what, given, expected in run_cases:
if given != expected:
print(f" ❌ {what}: the analyzers got {given}, expected {expected}")
ok = False
if ok:
print(" ✅ CI script analyzer jobs OK")
print()
return ok


COMMIT_CHECKER = Path(__file__).resolve().parent / "scripts" / "ci" / "commit_checker.py"
COMMIT_CHECK_WORKFLOW = Path(__file__).resolve().parent / ".github" / "workflows" / "commit-check.yml"

Expand Down Expand Up @@ -6029,6 +6117,7 @@ def record_ok(ok: bool):
check_ci_script_sarif_merge,
check_ci_script_sarif_rule_join,
check_ci_script_sarif_chunks,
check_ci_script_analyzer_jobs,
check_ci_commit_checker_range,
]
# Env-mutating check — must run outside the parallel pool.
Expand Down
28 changes: 25 additions & 3 deletions scripts/ci/run_code_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,15 @@ def parse_args() -> argparse.Namespace:
parser.add_argument("--json-out", help="Write analyzer JSON output to this file.")
parser.add_argument("--sarif-out", help="Write analyzer SARIF output to this file.")
parser.add_argument("--fail-on", choices=("none", "error", "warning"), default="error")
parser.add_argument("--analyzer-arg", action="append", default=[], help="Repeatable.")
parser.add_argument(
"--analyzer-arg",
action="append",
default=[],
help=(
"Repeatable. With an analyzer on every processor, each one gets --jobs=1 unless "
"--jobs or --config is given here."
),
)
parser.add_argument("--base-dir", help="Passed through to analyzer.")

parser.add_argument("--inputs-from-git", action="store_true")
Expand Down Expand Up @@ -317,6 +325,19 @@ def analyzer_cmd(
return cmd


def analyzer_jobs_args(analyzer_args: list[str], analyzers: int, processors: int) -> list[str]:
"""
The arguments of each of @analyzers analyzers that run at once on @processors processors.
When every processor already has its analyzer, each one gets --jobs=1: left to itself, an
analyzer counts on every processor for its own threads. What the caller chooses is kept,
through --jobs or through a configuration file, which may set jobs.
"""
caller_chooses = any(arg.split("=", 1)[0] in ("--jobs", "--config") for arg in analyzer_args)
if analyzers > 1 and analyzers >= processors and not caller_chooses:
return [*analyzer_args, "--jobs=1"]
return analyzer_args


def join_rule_properties(rule: dict, other: dict) -> None:
"""Give @rule the tags of @other it lacks, and the higher security-severity of the two."""
if not other:
Expand Down Expand Up @@ -427,7 +448,8 @@ def main() -> int:
jobs = int(os.environ.get("ANALYZER_JOBS", os.cpu_count() or 1))
chunk_size = max(1, math.ceil(len(selected_inputs) / jobs))
chunks = [selected_inputs[i:i + chunk_size] for i in range(0, len(selected_inputs), chunk_size)]

analyzer_args = analyzer_jobs_args(args.analyzer_arg, len(chunks), os.cpu_count() or 1)

print(f"Running analyzer on {len(selected_inputs)} file(s) across {len(chunks)} job(s).")

def run_chunk(i, chunk):
Expand All @@ -439,7 +461,7 @@ def run_chunk(i, chunk):
fmt="json",
compdb_path=compdb_path,
base_dir=args.base_dir,
extra_args=args.analyzer_arg,
extra_args=analyzer_args,
sarif_out=chunk_sarif,
)
run = subprocess.run(cmd, check=False, capture_output=True, text=True)
Expand Down
Loading