Skip to content

feat(solidity-import): opt-in inlining of direct linked library calls (#2728) - #2957

Merged
fricoben merged 6 commits into
mainfrom
importer/zodiac-2728-libcall
Nov 25, 2026
Merged

fricoben merged 6 commits into
mainfrom
importer/zodiac-2728-libcall

Conversation

@fricoben

Copy link
Copy Markdown
Member

Refs #2728 (partial: remaining linked-library shapes — memory/calldata/function-typed arguments and results, attached using L for T calls, constructor-time immutable inline initializers, and bodies reaching msg.data, msg.sig, gasleft() or inline assembly — stay located rejections; Zodiac Roles' 3 packed roots advance past external library calls and next hit ConditionStorer.store's bytes memory parameter).

Summary

  • Opt-in profile flag Profile.linkedLibrariesMatchSource (default false; behaviour, diagnostics and sourceDigest are unchanged when off).
  • Bounded DELEGATECALL inlining slice: when linkedLibrariesMatchSource := true, a direct runtime L.f(...) call to an implemented public or external library function (void, single-return, or multi-return) is modelled by f's body in the caller's frame only when:
    • every parameter is an elementary value type, enum, user-defined value type (resolved by AST declaration ID from typeIdentifier) or storage reference, and every return is a value type (with scalar arguments and single/multi returns ABI-cleaned across the DELEGATECALL boundary);
    • nothing reachable from f (transitively across internal helpers, function pointers, user-defined operators, modifiers, and nested linked library calls) uses msg.data, msg.sig (including parenthesized (msg).sig/.data), gasleft() or inline assembly;
    • the calling root reads no Yul returndatasize() or bubbled returndatacopy/revert pair in either order, and constructor-time immutable inline initializers keep linkedLibrariesMatchSource := false.
  • Trust surface & reporting: documented in docs/TRUST_ASSUMPTIONS.md and docs/SOLIDITY_IMPORT.md; each relying root lists its linked calls in FunctionStatus.linkedLibraryCalls (linked library L.f decl N at file:line:column), carries the .assumed local obligation solidity_linked_library_matches_source, and hashes "linkedLibrariesMatchSource": true into sourceDigest.

Gates on 9ffb879a0 (9ffb879a0f17c97ab847f955186a66b61ee5abdc)

  • make check -> pass (All checks passed., 675 anchors, 0 problems, 1,043 Python unit tests OK)
  • lean-job zodiac2728-r3 -- lake build Compiler.SolidityImport.Import Contracts.SolidityImportSmoke.LinkedLibraryCallSequenceModel Contracts.SolidityImportSmoke.LinkedLibraryCallChecks -> pass (Build completed successfully (119 jobs).)
  • python3 scripts/check_lean_warning_regression.py --log .lake/build_r3.log -> pass (Lean warning baseline check passed)
  • PYTHONPATH=scripts .lake/slice-testing-venv/bin/python3 -m solidity_differential.check_linked_library_call_rejections --output .lake/rej2728_final -> pass (26 linked library call acceptance/rejection controls pass)
  • PYTHONPATH=scripts .lake/slice-testing-venv/bin/python3 -m solidity_differential.check_library_call_rejections --output .lake/lib2728_final -> pass (9 library call acceptance/rejection controls pass, flag off)
  • PYTHONPATH=scripts .lake/slice-testing-venv/bin/python3 -m solidity_differential.check_reference_argument_rejections --output .lake/ref2728_final -> pass (9 reference acceptance/rejection controls pass, flag off)
  • PYTHONPATH=scripts .lake/slice-testing-venv/bin/python3 -m solidity_differential.check_linked_library_call --transactions 240 --seed 2728 --output .lake/abc2728_final -> pass (linked library call A/B/C agree: 200 ok / 40 revert across source EVM with deployed & linked libraries, Denote, and compiled model)
  • PYTHONPATH=scripts .lake/slice-testing-venv/bin/python3 -m solidity_differential.check_linked_library_call --transactions 240 --seed 2728 --negative-control --output .lake/abc2728neg_final -> pass (linked library negative control diverges as expected)
  • PYTHONPATH=scripts .lake/slice-testing-venv/bin/python3 -m solidity_differential.check_linked_library_call_rejections --output .lake/mut2728_final --mutant frame-check -> pass (linked library frame-check mutant detected; all 6 frame controls — msg-data, paren-msg-sig, msg-sig-in-internal-helper, msg-data-in-modifier, msg-sig-in-udvt-operator, inline-assembly — admitted by mutant and rejected by real code)
  • Coverage not measured locally (CI-only mode; CI runs the full differential/mutation/build suites on the PR head).

…#2728)

A `public` or `external` library function called from outside its library compiles
to a DELEGATECALL into the account linked at deployment, which the source does not
determine, so the importer rejects it. The new profile flag
`linkedLibrariesMatchSource` (off by default) states the trust assumption that every
such library is linked to code that behaves as solc's compilation of the same source.
With it, a direct `L.f(...)` call is modelled by `f`'s body in the caller's frame when
every argument is a value type or a storage reference, every result is a value type,
and nothing the body reaches (helpers, nested linked calls, modifiers) uses msg.data,
msg.sig, gasleft() or inline assembly. Everything else rejects with its location.

Each root lists the linked calls it relies on in the import report, its model carries
the `.assumed` local obligation `solidity_linked_library_matches_source`, and the flag
is part of the digest when set. Without the flag the diagnostics are unchanged.

Evidence: LinkedLibraryCallSequence A/B/C with both libraries deployed and linked
(storage, events, forwarded custom error / Error(string) / panic data, nested
library-to-library call), a negative control that links different library code and
must diverge, located rejection controls and a frame-check mutant.

Refs #2728
…ked library call

The DELEGATECALL sets the return-data buffer (32 bytes for one value-type result,
0 for a void call), the inlined body issues no call. A root that makes a linked
library call and reads Yul returndatasize (in either order) now rejects at the
later of the two. Also: precise linked-code comparison recipe (nested links,
legacy PUSH20 vs via-IR immutableReferences), updated comments, neutral fixture
names, two new located controls.

Refs #2728
… beside linked calls

The returndatacopy/revert bubble pair is lowered without lowerYul, so it skipped
the linked-call returndata guard. It now goes through noteReturndataRead. Adds
controls for both orders, a returndata-check mutant next to the frame-check one,
and states that the linked-call differential evidence is via-IR only.

Refs #2728
…w gaps

Admit external void and multi-return linked library calls in inlineVoidFn and
inlineMultiFn, ABI-clean value-type arguments and results across the DELEGATECALL
boundary, follow overloaded-operator function edges in linkedLibraryFrameHazardWalk,
keep immutable inline initializers outside linkedLibrariesMatchSource, and route
check_linked_library_call_rejections in check_importer_move_equivalence.py.

Refs #2728
…nked-call obligations

Unwrap parenthesized TupleExpression bases in linkedLibraryFrameHazard so (msg).sig
and (msg).data cannot bypass the linked-call frame check, and add compile-time #guard
checks for per-root linkedLibraryCalls report entries, the .assumed
solidity_linked_library_matches_source obligation, sourceDigest flag sensitivity, and
independent entry vs. single/multi-return narrow-value cleaning.

Refs #2728
…nked-call cleaning

Resolve user-defined value types via userValueTypeById from typeDescriptions.typeIdentifier
in mType and avoid overwriting file-level userValueTypes entries with scoped homonyms so
narrow UDVT arguments and results are ABI-cleaned across linked library calls even when
wider homonymous UDVTs exist in other scopes or imported files.

Refs #2728
@fricoben
fricoben requested a review from Th0rgal as a code owner November 25, 2026 18:54
@fricoben

Copy link
Copy Markdown
Member Author

Looks good to merge on 9ffb879.

Summary of Review (origin/main...9ffb879a0)

  1. DELEGATECALL frame equivalence & solc codegen (0.8.34 via-IR and legacy)

    • Verified against solc 0.8.34 Yul IR and legacy EVM assembly in /tmp that direct L.f(...) calls to public/external library functions compile to DELEGATECALL (for nonpayable, view, and pure functions alike), omit callvalue() guards in the library dispatcher (preserving payable caller semantics), check address() != deployAddr on state-changing selectors (satisfied whenever L is linked to a distinct library account per the trust assumption), check extcodesize > 0 on void calls (satisfied by non-empty library runtime code), and bubble revert payloads (Error(string), custom errors, Panic(uint256)) verbatim.
    • ABI round-trip & cleaning: isLinkedLibraryValueTypeIdentifier and linkedLibraryParamKind in Compiler/SolidityImport/LibraryCallGuard.lean admit only elementary value types (uintN, intN, address/address payable, bool, bytes1..bytes32), enums, UDVTs, and storage reference parameters (struct, mapping, bytes/string, T[], all slot-aligned at byte offset 0), and only value-type returns. Narrow arguments are ABI-cleaned in bindHelperParams and narrow single/multi returns in inlineFn and inlineMultiFn; trySignFlipSelfCall? is unreachable on DELEGATECALLs because solc rejects external library self-calls (Libraries cannot call their own functions externally). mType in Compiler/SolidityImport/ExprHelpers.lean resolves UDVTs by AST declaration ID from typeIdentifier (handling $$$-escaped $ in identifiers and homonymous file/scoped UDVTs).
    • Evaluation order, interface calls & returndata: statefulCallIn and interfaceCallIn? track linked library callees across sibling operands and non-revert-free assignment targets. noteReturndataRead and admitLinkedLibraryCall fail closed in either order if a root combines an inlined linked library call with Yul returndatasize() or a bubbled returndatacopy/revert pair. Constructor-time immutable inline initializers disable linkedLibrariesMatchSource.
  2. Transitive frame-hazard rejection

    • linkedLibraryFrameHazard and linkedLibraryFrameHazardWalk reject InlineAssembly, msg.data, msg.sig (including parenthesized (msg).sig/.data, failing closed on deep tuple nesting), and gasleft(), walking referencedDeclaration and overloaded-operator function edges transitively across env.funs and env.modifiers (internal helpers, internal function pointers, modifiers, UDVT operators, and nested linked library calls).
  3. Default-off invariance (linkedLibrariesMatchSource := false)

    • Default false in Compiler/SolidityImport/Profile.lean preserves exact prior rejection locations and externalLibraryCallDiagnostic ("external library calls are outside this slice"), skips interfaceCallIn? traversal into DELEGATECALL bodies, omits linkedLibrariesMatchSource from digestInput (preserving sourceDigest), and emits no extra report lines or obligations.
  4. Documentation, obligations, report & digest

    • docs/SOLIDITY_IMPORT.md and docs/TRUST_ASSUMPTIONS.md accurately document the linking assumption, bytecode verification procedure, admitted fragment, unmodelled gas/call-depth/free-pointer differences, and via-IR differential scope.
    • Every root reaching an admitted linked call (directly or transitively) records FunctionStatus.linkedLibraryCalls, carries the .assumed solidity_linked_library_matches_source local obligation, rolls back cleanly under collectUnsupported, and hashes "linkedLibrariesMatchSource": true into sourceDigest.
  5. Tests, mutations & name-selection hygiene

    • Verified Contracts/SolidityImportSmoke/LinkedLibraryCallChecks.lean (built via default SolidityImportSmoke target), scripts/solidity_differential/check_linked_library_call.py (stateful 3-way EVM/Denote/compiled campaign + vacuity checks + mutated-library --negative-control), and scripts/solidity_differential/check_linked_library_call_rejections.py (acceptance/located-rejection cases + frame-check and returndata-check mutants wired into scripts/solidity_import_mutations.py).
    • check_importer_name_selection.py passed across all 48 importer files with no contract/function/test names keyed in importer logic. Refs #2728 accurately reflects the partial opt-in slice.

Findings

None.

@vercel

vercel Bot commented Nov 25, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated
veritylang.com Ignored Ignored Nov 25, 2026 6:54pm UTC

Request Review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OpenCodeReview first-pass review

🟡 Scout triage + 0/4 paquet(s) reviewés sémantiquement. 8 finding(s) (1 high / 5 medium / 2 low); les hunks hors paquets restent à couvrir par un humain ou Codex.

Paquets non couverts par la review sémantique

  • scripts/solidity_differential/check_linked_library_call_rejections.py — error (Command failed: ocr review --from 69e9186 --to 9ffb879 --format json --audience agent --rule /home/ubuntu/actions-runner-verity-ocr/_work/_temp/ocr-tools/rules.json --concurr)
  • Contracts/SolidityImportSmoke/LinkedLibraryCallSequenceModel.lean — error (Command failed: ocr review --from 69e9186 --to 9ffb879 --format json --audience agent --rule /home/ubuntu/actions-runner-verity-ocr/_work/_temp/ocr-tools/rules.json --concurr)
  • scripts/solidity_differential/check_linked_library_call.py — error (Command failed: ocr review --from 69e9186 --to 9ffb879 --format json --audience agent --rule /home/ubuntu/actions-runner-verity-ocr/_work/_temp/ocr-tools/rules.json --concurr)
  • Compiler/SolidityImport/LibraryCallGuard.lean — error (Command failed: ocr review --from 69e9186 --to 9ffb879 --format json --audience agent --rule /home/ubuntu/actions-runner-verity-ocr/_work/_temp/ocr-tools/rules.json --concurr)

📝 4 groupe(s) de paquets au-delà du budget n'ont eu que le triage scout.

Large Lean diff routed to bounded packet review: 9 Lean file(s), 1548 changed supported line(s). Scout triage fallback_deterministic; strong packet review required. Full-file OCR was not attempted.

✅ Posted 8 inline comment(s).

OCR pilot metrics & packet coverage

OCR pilot metrics

  • Routing: large-lean-hotspots (router-v11)
  • Changed files: 21 supported / 21 total; Lean 9, trust docs 1, workflow/scripts 9, contracts 1, docs 1
  • Changed lines: 1548 supported; thresholds large Lean >=3 files or >800 lines
  • OCR: status scout_triage; comments 8; files 8; tokens 0; tool calls 0; warnings 1; duration 232s
  • Largest changed files: scripts/solidity_differential/check_linked_library_call.py (+310/-0), scripts/solidity_differential/check_linked_library_call_rejections.py (+274/-0), Contracts/SolidityImportSmoke/LinkedLibraryCallSequence.sol (+263/-0), Compiler/SolidityImport/Import.lean (+142/-19), Compiler/SolidityImport/LibraryCallGuard.lean (+145/-1)

Packet coverage

  • Packet review: enabled; selected 8/8 packet(s)
  • Scout: configured; status fallback_deterministic; model reviewer_scout
  • Scout lenses: provenance, verification-independence, environment-determinism, proof-soundness; rubric items checked 3
  • Scout provider HTTP status: 502
  • Scout provider error: <!DOCTYPE html> <!--[if lt IE 7]> <html class="no-js ie6 oldie" lang="en-US"> <![endif]--> <!--[if IE 7]> <html class="no-js ie7 oldie" lang="en-US"> <![endif]--> <!--[if IE 8]> <html class="no-js ie8 oldie" lang="en-US"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en-US"> <!--<![endif]--> <head> <title>thomas.md | 502: Bad gateway</title> <meta charset="UTF-8" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="X-UA-Compatible" content="I
  • Strong review: required; status blocked_packet_input
  • Residual risk: Triaged top 8 deterministically ranked packet(s); remaining changed hunks/files require Codex or human proof review, and selected packets still need strong reviewer analysis.
  • Strong packet-review blocker: Selected packets require semantic review; see packet review outcomes for actual coverage.
  • Covered packets:
    • scripts/solidity_differential/check_linked_library_call_rejections.py:1 score 154 — introduced sorry/admit, public declaration/signature changed, changed imports
    • Contracts/SolidityImportSmoke/LinkedLibraryCallSequenceModel.lean:1 score 78 — public declaration/signature changed, changed imports
    • scripts/solidity_differential/check_linked_library_call.py:1 score 74 — public declaration/signature changed, changed imports
    • Compiler/SolidityImport/LibraryCallGuard.lean:121 score 66 — public declaration/signature changed
    • docs/TRUST_ASSUMPTIONS.md:2168 score 64 — trust-boundary docs drift
    • Compiler/SolidityImport/Report.lean:94 score 60 — public declaration/signature changed
    • Contracts/SolidityImportSmoke/LinkedLibraryCallChecks.lean:1 score 49 — changed imports
    • scripts/solidity_import_mutations.py:787 score 34 — public declaration/signature changed

Pilot mode: advisory only. Codex Review remains the merge gate.

Comment thread docs/TRUST_ASSUMPTIONS.md Resolved
Comment thread Compiler/SolidityImport/Report.lean Resolved
Comment thread scripts/solidity_import_mutations.py Resolved
@fricoben
fricoben merged commit 2f421e6 into main Nov 25, 2026
26 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant