Skip to content

task { } miscompiles access to a ResumableStateMachine<_> of another instantiation #20958

Closed

Description

@majocha

Inside a statically compiled resumable state machine such as task { }, every value of type ResumableStateMachine<X> is compiled as if it were the state machine's own struct, even when X is not the machine's data type. The result is either InvalidProgramException or a read from the wrong memory.

#nowarn "57"
open System.Threading.Tasks
open Microsoft.FSharp.Core.CompilerServices

type Data<'T>() =
    [<DefaultValue(false)>]
    val mutable items: ResizeArray<'T>

type Runner<'T>() =
    [<DefaultValue(false)>]
    val mutable _machine: ResumableStateMachine<Data<'T>>

    member this.Init(xs: 'T list) =
        let d = Data<'T>()
        d.items <- ResizeArray xs
        this._machine.Data <- d

    member this.CountAsync() = task {
        do! Task.Yield()
        return this._machine.Data.items.Count
    }

let r = Runner<int>()
r.Init [ 1; 2; 3 ]
printfn "%d" (r.CountAsync().Result)

Expected: 3
Actual: NullReferenceException. A ResumableStateMachine<string> field read the same way fails with InvalidProgramException instead.

It reproduces with SDK 10.0.114 and current main in Debug and Release, and with SDK 10.0.403 in Release.

The cause is the template replacement in IlxGen.fs (GenNamedTyAppAux, GenRecdFieldRef). It matches on the type constructor only and ignores the type arguments, so this._machine.Data is emitted as a field of the task's generated struct.

This breaks TaskSeqDynamic<'T>.DisposeAsync in FSharp.Control.TaskSeq, which reads its ResumableStateMachine<TaskSeqStateMachineData<'T>> field inside a task.

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions