Skip to content

let-else failure path: owned payload of the non-matching variant leaks (str Err) or faults on drop (Result[Vec[str], str]) #1365

Closed

Description

@ehartford

The failure path of let PATTERN = subject else: ... mishandles an owned payload of the variant that did not match: a str Err payload leaks, and with a Vec[str] Ok type the else path faults in the str drop.

Spec: §9.7 (let ... else), §2.4 (every owned value is dropped exactly once).

Repro 1 (leak), a stage1 built from origin/main 5fd93bc:

fn items(k: i32) -> Result[i32, str]:
    if k == 0: return Err("none".clone())
    1
fn refutable(k: i32) -> i32:
    let Ok(v) = items(k) else: return -1
    v
fn main:
    print(f"{refutable(0)}")

with run --debug-alloc: prints -1, then debug-alloc: LEAK addr=... size=16 origin=unknown, leak count=1. Expected: leak count=0 (the Err payload drops when the else branch leaves).

Repro 2 (crash):

fn items(k: i32) -> Result[Vec[str], str]:
    if k == 0: return Err("none".clone())
    var v: Vec[str] = Vec.new()
    v
fn refutable(k: i32) -> i32:
    let Ok(v) = items(k) else: return -1
    0
fn main:
    print(f"{refutable(0)}")

rc=138 (EXC_BAD_ACCESS code=2 at a static-data address):

frame #0 with_str_free_drop_origin at rt_core.w:2827:5
frame #1 refutable at l7.w:6:32 [inlined]
frame #3 main at l7.w:9:24

Likely site (not yet proven at the instruction): MirLower.lower_let_else (src/MirLower.w ~5990) cancels the materialized subject's scheduled value drop with cancel_scheduled_value_drop_for_local on the success path, which is not path-sensitive, so the fail path, which still owns the subject, leaves with no drop (repro 1). Repro 2 needs the debug allocator plus the address trap to name the bad free.

Workaround: match in place of let ... else when the non-matching variant owns a payload.

Found while building the #1354 matrix (var destructuring). That change leaves this path alone: a drop-scheduling fix has to be in a batch by itself.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions