locks.py¶
clew/locks.py
R1 lock layer, L1: where locks are declared and where they are acquired.
detect_undeclared_lock_primitives
list[tuple[str, str]] clew.locks.detect_undeclared_lock_primitives(sqlite3.Connection conn, list[LockPattern] patterns)
Called acquire/release pairs that no active lock pattern covers.
Source · 56 lines
def detect_undeclared_lock_primitives(
conn: sqlite3.Connection, patterns: list[LockPattern]
) -> list[tuple[str, str]]:
"""THE MEASURED GAP (gh#385). On mbedtls the lock layer held ONE identity — `mutex->mutex`,
scope unknown, confidence low — for a repository with five named global mutexes and 38 lock
sites, and a graded agent copied that number into its answer as "one first-party mutex
identity resolved with 1 acquisition". Every acquisition goes through the function POINTER
`mbedtls_mutex_lock`, which is not a built-in primitive, so the detector only ever saw
`pthread_mutex_lock(&mutex->mutex)` inside the single wrapper.
DECLARING IT IS THE FIX, and it works: `locks: [{name: mbedtls_mutex_lock, form: call,
kind: mutex, role: acquire, operand_index: 0}]` takes the layer from 1 identity / 1
acquisition to 10 / 46, with real names (`mbedtls_threading_gmtime_mutex`, `debug_mutex`,
`ctx->mutex`, `heap.mutex`). That is the same answer the `STORE_SET_*` accessors got: the
layer was empty because the detector had no way to look, not because the repo has no locks.
SO THE DEFECT IS THAT NOTHING TOLD THE OWNER TO DECLARE IT. `detect_undeclared_accessor_families`
exists for exactly this reason one layer over, and the lock layer had no counterpart — it
reported a confident `1` instead of a hint. Purely advisory: this never fabricates an
acquisition.
PAIRED, NOT NAME-SNIFFED. A single name containing "lock" proves nothing — `spinlock_t`,
`unlock_reason`, `lock_free_queue` all contain it. What identifies a primitive is that
BOTH halves of an acquire/release pair are CALLED in the same index, which is a property of
the code rather than of a naming fashion. `_take`/`_give` catches FreeRTOS, `_enter`/`_exit`
catches Zephyr-style and CMSIS-style, and a repo whose pair this misses still declares
explicitly — a missed hint costs nothing, while a false hint costs an operator real time,
which is the asymmetry `AccessorFamily` records.
@brief Suggest acquire/release pairs a build should declare as lock primitives.
@return (acquire name, release name) pairs, sorted.
@version 1
"""
## READ FROM `memberdef`, NOT FROM CALL SITES, and the reason is the defect itself: the
## primitive is a function POINTER, so the fnptr layer resolves each call to the BOUND
## implementation (`threading_mutex_lock_pthread`) and the pointer's own name never appears
## as a callee. No table carries unresolved callee names — `critical_section_calls` has one
## but only inside an already-detected critical section, which is exactly what is missing
## here. So the pair is looked for among indexed NAMES, whatever kind they are: mbedtls's
## halves are `variable` rows, and a repo whose primitive is a real function has them as
## `function` rows.
covered = {p.name.lower() for p in patterns}
called = {row[0] for row in conn.execute("SELECT DISTINCT name FROM memberdef WHERE name<>''")}
found: list[tuple[str, str]] = []
for name in sorted(called):
lowered = name.lower()
if lowered in covered:
continue
for acquire_suffix, release_suffix in _LOCK_SUFFIXES:
if not lowered.endswith(acquire_suffix):
continue
partner = name[: -len(acquire_suffix)] + release_suffix
if partner in called:
found.append((name, partner))
break
return found1 more lines, not shown
Activity · 15 steps
Requirements
extract_locks
None clew.locks.extract_locks(Path db_path, Path repo_root, Path|dict|None lock_patterns=None, IndexCache|None cache=None, Harvester|None harvester=None)
Harvest lock declarations, acquisitions and critical-section members.
Called by _build_stages, run_real_stages
Calls _build_function_indexes, _ensure_lock_tables, _insert_sites, _log_lock_summary, lock_harvester, run_harvest
Source · 44 lines
def extract_locks(
db_path: Path,
repo_root: Path,
lock_patterns: Path | dict | None = None,
cache: IndexCache | None = None,
harvester: Harvester | None = None,
) -> None:
"""Runs after the call-edge layers so function extents exist for holder
resolution. The tables are created unconditionally, so a repo with no locks
yields empty tables rather than absent ones, and R2/R4 never branch on existence.
The function-name index that Layer 3 builds for call edges is reused here to
resolve L2's callee names, so an `critical_section_calls.callee_rowid` and a
`call_edges.callee_rowid` for the same site agree by construction rather
than by two independent lookups that could drift.
`harvester` is the one gh#358's shared parse pass already built and warmed the
cache with. Passing the OBJECT rather than rebuilding from `lock_patterns` is
what makes the two cache keys equal by construction; rebuilding here would also
re-run the declaration merge and its warnings a second time. Omitted (every
caller outside the pipeline), it is built here exactly as before.
@brief Populate locks + lock_acquisitions + critical_section_calls.
@version 5
"""
from .call_edges import _build_function_indexes
conn = sqlite3.connect(str(db_path))
_ensure_lock_tables(conn)
name_to_rowids, file_funcs = _build_function_indexes(conn)
harvester = harvester or lock_harvester(lock_patterns)
inserted = 0
members = 0
for path_rowid, payload in run_harvest(conn, repo_root, harvester, cache):
added, member_rows = _insert_sites(
conn, path_rowid, payload, file_funcs.get(path_rowid, []), name_to_rowids
)
inserted += added
members += member_rows
conn.commit()
_log_lock_summary(conn, inserted, members)
conn.close()
Activity · 14 steps
Requirements
harvest
Any clew.locks._LockHarvester.harvest(self, Any tree, bytes src_bytes)
Harvest one file's lock sites.
Source · 4 lines
def harvest(self, tree: Any, src_bytes: bytes) -> Any:
return _walk_lock_sites(tree, src_bytes, self.patterns_by_name)
Activity · 1 steps
Requirements
load_lock_patterns
list[LockPattern] clew.locks.load_lock_patterns(Path|dict|None source)
Merge a repo's declared lock wrappers over the built-in primitives.
Called by collect, lock_harvester
Tested by 12 tests
test_a_declared_call_primitive_with_no_known_release_fails_closed, test_a_declared_call_wrapper_can_name_its_release_and_so_gets_an_extent, test_a_lock_declaration_with_releases_is_accepted_on_both_routes, test_an_undeclared_acquire_release_pair_is_suggested, test_critical_section_excludes_call_after_early_return, test_declared_wrapper_merges_over_the_builtin_primitives, test_invalid_declared_form_and_mode_fail_closed_instead_of_coercing, test_invalid_declared_kind_fails_closed_rather_than_normalizing, test_invalid_declared_role_fails_closed, test_lock_site_detects_mutex_lock_binding, test_lock_site_detects_mutex_lock_with_poison_recovery, test_lock_site_detects_rwlock_read_and_write
Calls _declared_lock_pattern, _pattern_document, declaration_origin, list
Source · 39 lines
def load_lock_patterns(source: Path | dict | None) -> list[LockPattern]:
"""Expected shape, mirroring the thread/accessor manifests::
locks:
- name: "ScopedLock" # a project's own RAII wrapper
form: "raii"
kind: "mutex"
- name: "bsp_lock_take" # a project's own call-form primitive
form: "call"
operand_index: 0
An invalid `form`/`kind`/`role`/`mode` RAISES `DeclarationError` naming the
file, the token and the allowed set. Two of these were unguarded before:
`role` rode straight into the INSERT and surfaced as a bare `IntegrityError`
mid-build, while `form`/`mode` silently coerced anything that was not the
exact non-default spelling into the default — so `form: "cal"` became an
RAII guard and `mode: "shard"` became an exclusive hold. Both are specific,
real synchronization claims invented from a typo.
`kind` in particular CANNOT fall back: it is part of lock identity
(`UNIQUE(name, scope, kind)`), so two differently-typo'd kinds normalizing
to one token merge unrelated acquisitions into a single lock row — the
fabricated-shared-lock error this module's identity rule exists to prevent.
@brief Merge declared lock conventions over the defaults.
@return Merged LockPattern list.
@version 2
"""
merged: dict[str, LockPattern] = {p.name: p for p in DEFAULT_LOCK_PATTERNS}
data = _pattern_document(source)
origin = declaration_origin(source, SECTION_LOCKS)
for entry in data.get("locks", []) or []:
name = entry.get("name")
if not name:
continue
merged[name] = _declared_lock_pattern(entry, name, f"{origin}: lock pattern {name!r}")
return list(merged.values())
Activity · 9 steps
Requirements
lock_harvester
Harvester clew.locks.lock_harvester(Path|dict|None lock_patterns=None)
The lock stage's harvester for one declared lock vocabulary.
Source · 13 lines
def lock_harvester(lock_patterns: Path | dict | None = None) -> Harvester:
"""The ONE construction site, called once per build by gh#358's shared parse
pass and handed to `extract_locks` — so the key the pass writes and the key the
stage reads cannot drift, and the declaration merge (with its shadowing
warnings) runs once.
@brief Build this stage's harvester.
@version 1
"""
patterns = load_lock_patterns(lock_patterns)
return _LockHarvester({p.name: p for p in patterns}, manifest_key(lock_patterns))