Skip to content

Commit dbf88f8

Browse files
authored
Merge pull request #259 from CoreTrace/fix/summary-reachability
fix(summaries): keep nothing of the blocks constant propagation proves unreachable
2 parents 1f13cfc + 1fe578d commit dbf88f8

10 files changed

Lines changed: 335 additions & 30 deletions

File tree

‎docs/usage.md‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,11 @@ variable is not treated that way yet.
132132
| `plaintext-credential-storage` | A parameter named like a password stored in a database without hashing. Medium confidence, since a name is a hint. |
133133
| `exploitable-vulnerability` | An API affected by an advisory of a vulnerable requirement, see Dependencies. |
134134

135-
Each flow is judged before it is reported. A dominating guard that proves the value
135+
Each flow is judged before it is reported. Code constant propagation proves can never
136+
run (under `if False:`, `while False:`) reports nothing, in the function and through the
137+
project functions that contain it: their summaries keep nothing of such code, neither a
138+
sink nor a returned, merged or stored value. Code that may run is kept, whatever decides
139+
it at run time, a parameter or a module-level name. A dominating guard that proves the value
136140
safe (`isdigit()`, membership in a constant allowlist, equality with a constant, a
137141
numeric value proven by `int()`, `len()` or bounded arithmetic, a validator such as
138142
`re.fullmatch`) refutes it and nothing is reported. A sink that selects code by name,
@@ -913,7 +917,10 @@ such as `metaclass=`, `with` targets of any assignable form and `match` with eve
913917
pattern kind. `finally` is modelled on the normal path only. A
914918
`nonlocal` write made by a nested function flows back to the enclosing variable when the
915919
enclosing function calls that nested function directly by name; a nested function passed
916-
around and called elsewhere keeps its writes to itself. Methods of module-level classes are
920+
around and called elsewhere keeps its writes to itself. Where the nested function may
921+
return without writing the name (no write on some path, a write constant propagation
922+
proves cannot run, or an exception before it), the variable keeps the value it had
923+
before the call, joined with what may be written; only a write on every path replaces it. Methods of module-level classes are
917924
analysed like functions.
918925

919926
## Looking at the intermediate representation

‎src/coretrace_python/cache.py‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@
4242
from coretrace_python.semantic.symbols import SymbolId
4343
from coretrace_python.source import FileLocation, Location, SourceId, SourceSpan
4444

45-
CACHE_FORMAT = 15
45+
CACHE_FORMAT = 16
4646

4747

4848
@dataclass(frozen=True)
@@ -300,7 +300,12 @@ def _encode_summary(summary: FunctionSummary) -> dict[str, Any]:
300300
],
301301
"side_effects": sorted(summary.side_effects),
302302
"nonlocal_writes": [
303-
{"name": w.name, "dependencies": sorted(w.dependencies), "externals": sorted(str(s) for s in w.externals)}
303+
{
304+
"name": w.name,
305+
"dependencies": sorted(w.dependencies),
306+
"externals": sorted(str(s) for s in w.externals),
307+
"kept": w.kept,
308+
}
304309
for w in summary.nonlocal_writes
305310
],
306311
"static": summary.static,
@@ -328,7 +333,10 @@ def _decode_summary(data: Mapping[str, Any]) -> FunctionSummary:
328333
frozenset(_string(name) for name in data["side_effects"]),
329334
tuple(
330335
NonlocalWrite(
331-
_string(w["name"]), _indices(w["dependencies"]), frozenset(SymbolId(_string(s)) for s in w["externals"])
336+
_string(w["name"]),
337+
_indices(w["dependencies"]),
338+
frozenset(SymbolId(_string(s)) for s in w["externals"]),
339+
bool(w["kept"]),
332340
)
333341
for w in data["nonlocal_writes"]
334342
),

‎src/coretrace_python/interprocedural/summaries.py‎

Lines changed: 56 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -332,11 +332,15 @@ class Mutation:
332332
@dataclass(frozen=True)
333333
class NonlocalWrite:
334334
"""What the function stores into its ``nonlocal`` ``name``: data of its parameters
335-
and results of external symbols, written back to the caller's variable."""
335+
and results of external symbols, written back to the caller's variable. ``kept``
336+
says it may also return without writing it, on a path with no reachable write, so
337+
the caller's variable may keep the value it had. A function with no record for a
338+
``nonlocal`` never writes it (#258)."""
336339

337340
name: str
338341
dependencies: Dependencies
339342
externals: frozenset[SymbolId]
343+
kept: bool = False
340344

341345

342346
@dataclass(frozen=True)
@@ -509,6 +513,11 @@ def evaluate(self, block: BasicBlock, incoming: Mapping[BlockId, State]) -> Stat
509513
return MappingProxyType(state)
510514

511515
def flow(self, cfg: CFG, block_id: BlockId, incoming: Mapping[BlockId, State]) -> Mapping[BlockId, State]:
516+
# A block constant propagation proves unreachable has no effect: no store, call,
517+
# return or write, and nothing it would pass on reaches its successors or their
518+
# phis (#258). A block that may run is kept, whatever decides it.
519+
if not self.reachable(block_id):
520+
return {}
512521
block = self.blocks[block_id]
513522
state = self.evaluate(block, incoming)
514523
exits = {target: state for target in block.exception_targets}
@@ -576,9 +585,9 @@ def call(self, call: Call, state: dict[Key, Dep]) -> Dep:
576585
given = self.graph.arguments_at(self.name, call.location)
577586
self.record(target.symbol, arguments, named, call.location, None, given)
578587
# Where its result is called: facts the summary keeps whatever the models;
579-
# the consumer decides which kinds of a sink apply there (#240). An invocation
580-
# is kept only when it and the call can run, by constant propagation.
581-
if call.result is not None and self.runs(call):
588+
# the consumer decides which kinds of a sink apply there (#240). The call runs,
589+
# as its block is evaluated; an invocation is kept only when it can run too.
590+
if call.result is not None:
582591
for invocation in invocations(self.function, self.uses, call.result):
583592
if self.runs(invocation):
584593
self.record(target.symbol, arguments, named, call.location, None, given, invocation.location)
@@ -597,14 +606,17 @@ def call(self, call: Call, state: dict[Key, Dep]) -> Dep:
597606
return everything | state.get(call.callee, EMPTY)
598607

599608
def nonlocal_result(self, instruction: NonlocalResult, state: dict[Key, Dep]) -> Dep:
600-
"""What the nested callee left in its nonlocal ``name``, in the caller's terms."""
609+
"""What the nested callee left in its nonlocal ``name``, in the caller's terms:
610+
what it may write, and the value before the call wherever it may leave the name
611+
unwritten, or when what it does is not known."""
601612

613+
previous = self.deep(instruction.previous, state)
602614
call = self.defs.get(instruction.call)
603615
if not isinstance(call, Call):
604-
return EMPTY
616+
return previous
605617
target = self.graph.target_at(self.name, call.location)
606618
if not isinstance(target, KnownFunction) or target.name not in self.table:
607-
return EMPTY
619+
return previous
608620
callee = self.table[target.name]
609621
arguments = tuple(self.deep(a, state) for a in call.arguments)
610622
made = self.defs.get(call.callee)
@@ -615,10 +627,9 @@ def nonlocal_result(self, instruction: NonlocalResult, state: dict[Key, Dep]) ->
615627
keywords = EMPTY
616628
for value in (*call.starred, *(v for _, v in call.keywords)):
617629
keywords |= self.deep(value, state)
618-
deps = EMPTY
619-
for write in callee.nonlocal_writes:
620-
if write.name != instruction.name:
621-
continue
630+
written = [write for write in callee.nonlocal_writes if write.name == instruction.name]
631+
deps = previous if not written or any(write.kept for write in written) else EMPTY
632+
for write in written:
622633
for index in write.dependencies:
623634
deps |= arguments[index] if index < len(arguments) else keywords
624635
deps |= Dep(externals=write.externals)
@@ -681,6 +692,38 @@ def mapped(indices: Dependencies, cleared: Cleared = ()) -> Dep:
681692
def uses(self) -> DefUse:
682693
return def_use(self.function)
683694

695+
def may_return_unwritten(self, name: str) -> bool:
696+
"""Whether a path from the entry to a return writes no ``nonlocal`` ``name``,
697+
through the blocks that can run. An exception edge leaves a block before its
698+
write, so its handler is reached unwritten."""
699+
700+
writes = {
701+
block.id
702+
for block in self.function.blocks
703+
if any(isinstance(i, SetNonlocal) and i.name == name for i in block.instructions)
704+
}
705+
pending = [self.function.entry]
706+
seen: set[BlockId] = set()
707+
while pending:
708+
block_id = pending.pop()
709+
if block_id in seen or not self.reachable(block_id):
710+
continue
711+
seen.add(block_id)
712+
block = self.blocks[block_id]
713+
pending.extend(block.exception_targets)
714+
if block_id in writes:
715+
continue
716+
terminator = block.terminator
717+
if isinstance(terminator, Return):
718+
return True
719+
if isinstance(terminator, Branch):
720+
pending.extend((terminator.then_block, terminator.else_block))
721+
elif isinstance(terminator, Jump):
722+
pending.append(terminator.target)
723+
elif isinstance(terminator, ForNext):
724+
pending.extend((terminator.body, terminator.exit))
725+
return False
726+
684727
def runs(self, call: Call) -> bool:
685728
"""Whether ``call`` can run: its block is reachable by constant propagation."""
686729

@@ -769,7 +812,7 @@ def summarize(
769812
problem.mutated_globals = set()
770813
problem.nonlocal_stores = {}
771814
for block in function.blocks:
772-
if solution.reached(block.id):
815+
if solution.reached(block.id) and problem.reachable(block.id):
773816
problem.evaluate(block, solution.incoming(block.id))
774817
mutations: list[Mutation] = []
775818
for index, parameter in enumerate(function.parameters):
@@ -788,9 +831,8 @@ def summarize(
788831
mutations=tuple(mutations),
789832
side_effects=frozenset(problem.mutated_globals),
790833
nonlocal_writes=tuple(
791-
NonlocalWrite(name, deps.parameters, deps.externals)
834+
NonlocalWrite(name, deps.parameters, deps.externals, problem.may_return_unwritten(name))
792835
for name, deps in sorted(problem.nonlocal_stores.items())
793-
if deps.parameters or deps.externals
794836
),
795837
static=static,
796838
return_cleared=problem.returns.cleared,

‎src/coretrace_python/ir/lowering.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -251,7 +251,8 @@ def write_back_nonlocals(self, node: nodes.Call, call: Value) -> None:
251251
return
252252
bindings = self.scopes.scope_for(nested).bindings
253253
for name in sorted(n for n, b in bindings.items() if b.kind is BindingKind.NONLOCAL):
254-
written = self.emit(NonlocalResult(self.new_value(), node.span, call, name))
254+
previous = self.expression(nodes.Name(name, node.span))
255+
written = self.emit(NonlocalResult(self.new_value(), node.span, call, name, previous))
255256
self.store(nodes.Name(name, node.span), written)
256257

257258
# ------------------------------------------------------------------ statements

‎src/coretrace_python/ir/model.py‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from coretrace_python.source import SourceSpan
1010

1111
# Bumped whenever the instruction set or its meaning changes; part of the cache key.
12-
PYIR_SCHEMA_VERSION = 1
12+
PYIR_SCHEMA_VERSION = 2
1313

1414

1515
@dataclass(frozen=True)
@@ -245,12 +245,15 @@ class Yield(Operands):
245245
@dataclass(frozen=True)
246246
class NonlocalResult(Operands):
247247
"""The value a nested function left in its ``nonlocal`` ``name`` when ``call``
248-
returned; the caller stores it back into its own variable."""
248+
returned; the caller stores it back into its own variable. ``previous`` is the value
249+
that variable held before the call, which it keeps wherever the function may leave
250+
the name unwritten (``NonlocalWrite.kept``)."""
249251

250252
result: Value
251253
location: SourceSpan
252254
call: Value
253255
name: str
256+
previous: Value
254257

255258

256259
@dataclass(frozen=True)

‎src/coretrace_python/ir/printer.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,10 @@ def _instruction(instruction: Instruction) -> str:
129129
suffix = "" if instruction.value is None else f" {_value(instruction.value)}"
130130
return f"{_value(instruction.result)} = yield{suffix}"
131131
if isinstance(instruction, NonlocalResult):
132-
return f"{_value(instruction.result)} = nonlocal_result {_value(instruction.call)}, {instruction.name!r}"
132+
return (
133+
f"{_value(instruction.result)} = nonlocal_result {_value(instruction.call)}, {instruction.name!r}"
134+
f" else {_value(instruction.previous)}"
135+
)
133136
if isinstance(instruction, SetAttr):
134137
return f"set_attr {_value(instruction.object)}, {instruction.attribute!r}, {_value(instruction.value)}"
135138
if isinstance(instruction, SetItem):

‎src/coretrace_python/taint/engine.py‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -464,14 +464,17 @@ def constructed_keys(self, call: Call, state: Mapping[Key, Taint]) -> Taint:
464464
return taint
465465

466466
def nonlocal_result(self, instruction: NonlocalResult, state: dict[Key, Taint]) -> Taint:
467-
"""The taint a nested callee left in its nonlocal ``name``, in the caller's terms."""
467+
"""The taint a nested callee left in its nonlocal ``name``, in the caller's terms:
468+
what it may write, and the value before the call wherever it may leave the name
469+
unwritten (``NonlocalWrite.kept``), or when what it does is not known."""
468470

471+
previous = self.deep(instruction.previous, state)
469472
call = self.defs.get(instruction.call)
470473
if not isinstance(call, Call):
471-
return Taint.none()
474+
return previous
472475
target = self.graph.target_at(self.name, call.location)
473476
if not isinstance(target, KnownFunction):
474-
return Taint.none()
477+
return previous
475478
summary = self.summaries.summary(target.name)
476479
arguments = (
477480
*(self.deep(r, state) for r in (() if summary.static else self.receiver(call, target.name))),
@@ -481,10 +484,9 @@ def nonlocal_result(self, instruction: NonlocalResult, state: dict[Key, Taint])
481484
keywords = Taint.none()
482485
for value in (*call.starred, *(v for _, v in call.keywords)):
483486
keywords = keywords.join(self.deep(value, state))
484-
result = Taint.none()
485-
for write in summary.nonlocal_writes:
486-
if write.name != instruction.name:
487-
continue
487+
written = [write for write in summary.nonlocal_writes if write.name == instruction.name]
488+
result = previous if not written or any(write.kept for write in written) else Taint.none()
489+
for write in written:
488490
for index in sorted(write.dependencies):
489491
result = result.join(arguments[index] if index < len(arguments) else keywords)
490492
for symbol in sorted(write.externals, key=str):

‎tests/test_cache_engine_version.py‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
"""What makes a fix reach a cached project (#258, review of PR #259).
2+
3+
A change to the analysis that keeps the cache format and the plugins, as the summaries
4+
dropping unreachable blocks does, keeps every key between commits of one version: a
5+
cache built before it would still serve the old results. What delivers it is the
6+
version of the engine, part of every key: once it changes, nothing cached is reused and
7+
every module is analysed again with the engine that reads it.
8+
"""
9+
10+
from __future__ import annotations
11+
12+
from pathlib import Path
13+
14+
import pytest
15+
16+
from coretrace_python import engine
17+
from coretrace_python.cache import ProjectCache
18+
19+
APP = "import os\n\n\ndef helper(cmd):\n if False:\n os.system(cmd)\n\n\ndef caller():\n helper(input())\n"
20+
21+
22+
def project(tmp_path: Path) -> Path:
23+
root = tmp_path / "project"
24+
(root / "app").mkdir(parents=True)
25+
(root / "app" / "__init__.py").write_text("", encoding="utf-8")
26+
(root / "app" / "main.py").write_text(APP, encoding="utf-8")
27+
return root
28+
29+
30+
def test_a_new_engine_version_reuses_nothing_cached(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
31+
root = project(tmp_path)
32+
cache = ProjectCache(tmp_path / "cache")
33+
built = engine.analyze_project(root, [engine.BUNDLED_PLUGINS], cache=cache)
34+
same_version = engine.analyze_project(root, [engine.BUNDLED_PLUGINS], cache=cache)
35+
36+
monkeypatch.setattr(engine, "__version__", "0.0.0+next")
37+
next_version = engine.analyze_project(root, [engine.BUNDLED_PLUGINS], cache=cache)
38+
39+
assert set(same_version.reused) == set(built.keys) == {"app", "app.main"}
40+
assert next_version.reused == ()
41+
assert set(next_version.keys.values()).isdisjoint(built.keys.values())
42+
assert [f for f in next_version.findings if f.rule_id == "command-injection"] == []

0 commit comments

Comments
 (0)