Skip to content

Add check for vtable metadata of a different trait - #5001

Open
miguelcorderopamphile wants to merge 2 commits into
model-checking:mainfrom
miguelcorderopamphile:fix/invalid-vtable-check
Open

miguelcorderopamphile wants to merge 2 commits into
model-checking:mainfrom
miguelcorderopamphile:fix/invalid-vtable-check

Conversation

@miguelcorderopamphile

Copy link
Copy Markdown

Refs #3738 (this does not close the issue: cross-crate metadata is not covered yet).

What this changes

Kani now fails verification when the vtable pointer used by a virtual call is equal to a vtable that it generated for a different principal trait. This detects invalid wide pointer metadata like the reproducer in #3738:

let meta_b = ptr::metadata(&s as &dyn B);
let meta_a: DynMetadata<dyn A> = unsafe { std::mem::transmute(meta_b) };
let fat: *const dyn A = ptr::from_raw_parts(data, meta_a);
let _ = (*fat).f(); // UB; previously verified successfully

Context

ptr::from_raw_parts goes through normal MIR, and nothing validated the metadata. Vtables are already generated as Kani::CommonVTable globals with a size sanity check (check_vtable_size), so this check reuses that machinery: VtableCtx records each generated vtable with its principal trait, and codegen_virtual_funcall adds one SafetyCheck assertion per call site (a single conjunction over the mismatching vtables).

The principal comparison matches what codegen already uses to reuse vtables for dyn-to-dyn casts, so auto trait differences (e.g. dyn T + Send to dyn T) do not trigger the check.

Known limitations

  • Only vtables generated in the same crate are checked. Wrong-trait metadata that points to a vtable from another crate is not caught yet; that requires the per-call-site data that --restrict-vtable aggregates after linking (left as the design question in Check vtable validity when explicitly creating wide pointer #3738).
  • The set of vtables seen grows during codegen, so checks use the vtables recorded up to that point.

Testing

  • New regression test tests/expected/dyn-vtable-wrong-trait/wrong_trait_vtable.rs, plus the reproducer above.
  • tests/kani: 618 passed (3 pre-existing, unrelated failures in Quantifiers on this machine because z3 is unavailable), tests/ui: 153 passed, tests/expected: 499 passed (remaining failures are pre-existing on this CBMC build), DynTrait suite: 30/30, covering upcasting, dyn Fn and cross-crate trait objects.

AI assistance was used to develop this change.

@miguelcorderopamphile
miguelcorderopamphile requested review from a team as code owners October 14, 2026 01:47
@github-actions github-actions Bot added Z-EndToEndBenchCI Tag a PR to run benchmark CI Z-CompilerBenchCI Tag a PR to run benchmark CI labels Oct 14, 2026
@feliperodri
feliperodri requested a balanced review from Copilot November 6, 2026 18:53

Copilot AI 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.

Warning

Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.

Copilot review overview

3 open issues
What changed in this PR

Adds a safety check to detect invalid trait-object vtable metadata where a wide pointer’s vtable pointer matches a vtable generated for a different principal trait, and introduces a regression test for the scenario in #3738.

Changes:

  • Record generated vtable globals alongside their principal trait in VtableCtx.
  • Emit a per-virtual-call-site SafetyCheck asserting the vtable pointer does not equal any mismatching in-crate generated vtable.
  • Add an expected test case covering ptr::from_raw_parts-constructed wrong-trait metadata.
File Description
tests/​expected/​dyn-vtable-wrong-trait/​wrong_trait_vtable.rs New regression harness reproducing wrong-trait vtable metadata via transmute + from_raw_parts.
tests/​expected/​dyn-vtable-wrong-trait/​expected Expected failure output for the new regression harness.
kani-compiler/​src/​codegen_cprover_gotoc/​context/​vtable_ctx.rs Track generated vtables (principal trait + symbol + type) for later validation at call sites.
kani-compiler/​src/​codegen_cprover_gotoc/​codegen/​statement.rs Add call-site assertion to reject mismatching generated vtables as metadata targets.
kani-compiler/​src/​codegen_cprover_gotoc/​codegen/​rvalue.rs Record each generated vtable in VtableCtx during vtable construction.

Review effort: Lite

Record each generated vtable global together with its principal trait and
fail verification when a virtual call uses a vtable generated for a
different principal trait. This detects invalid wide pointer metadata,
e.g. built via `ptr::from_raw_parts`, which was previously accepted.
- Store generated vtables in a named struct instead of a 3-tuple.
- Deduplicate vtable symbols with an FxHashSet instead of a linear scan.
- Iterate over the vtable slice without cloning it at every call site.
- Combine the mismatching-vtable checks into a balanced tree so large
  vtables sets cannot produce a deeply nested expression.

@feliperodri feliperodri left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for taking on #3738. The reproducer test is good. One blocker, then two design points.

  1. Upcasting to a supertrait whose vtable is a prefix. For trait Sub: Super, supertrait_vtable_slot returns None and codegen reuses Sub's vtable for &dyn Super (rvalue.rs:1815). That vtable is recorded with principal Sub, so a call through dyn Super asserts vtable != &Sub_vtable and fails on valid code: let s: &dyn Sub = &x; (s as &dyn Super).m();. DynTrait/upcast.rs only upcasts to the second supertrait, which has its own slot. Please add a test for the first supertrait and for a single-supertrait trait. The check needs to accept vtables whose principal is a subtrait of the call's principal.
  2. Codegen order. A call is checked only against vtables generated before it, so detection depends on codegen order. Could the check be filled in after codegen, once all vtables are known?
  3. Size. Each virtual call compares against every other trait's vtable. The stack overflow in std_codegen shows the size. Have you considered storing a per-trait id in each vtable and checking it at the call? That is one comparison, doesn't depend on order, and might extend to vtables from other crates.

I added the labels from #3738 and the Soundness milestone.

// the goto program with one assertion per generated vtable.
let mut mismatches = Vec::new();
for vtable in self.vtable_ctx.vtables() {
if vtable.principal.as_ref() != Some(&call_principal) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This also flags the vtable reused for an upcast to a prefix supertrait (see point 1 in the review): a vtable whose principal is a subtrait of call_principal is valid here.

@feliperodri feliperodri added [C] Feature / Enhancement A new feature request or enhancement to an existing feature. [E] Unsupported UB Undefined behavior that Kani does not detect labels Nov 8, 2026
@feliperodri feliperodri added this to the Soundness milestone Nov 8, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

[C] Feature / Enhancement A new feature request or enhancement to an existing feature. [E] Unsupported UB Undefined behavior that Kani does not detect Z-CompilerBenchCI Tag a PR to run benchmark CI Z-EndToEndBenchCI Tag a PR to run benchmark CI

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants