Skip to content

NativeAOT osx-arm64: double local reads a wrong value after a loop containing throwing calls (10.0.11, 10.0.12) #135616

In progress

Description

@mathewritter

Description

On osx-arm64, a NativeAOT-published program reads a wrong value from a double local after a loop: the local mac is computed before a foreach whose body runs a floating-point while loop and calls a helper that can throw. After the loop, mac reads back as 1 instead of about 4,300, so the final check fails. The same program gives the correct result under the JIT (Release) and under linux-x64 NativeAOT. Marking the lambda [MethodImpl(MethodImplOptions.NoOptimization)] avoids it.

The repro was minimized by statement-level delta debugging from a numerical test in a larger suite. That suite has 25 tests that fail only under osx-arm64 NativeAOT, with the same pattern: values read back changed after loops with throwing calls.

Reproduction Steps

Save the two files below in an empty folder, then:

dotnet publish -c Release -r osx-arm64 --self-contained true -p:PublishAot=true -o out
./out/Repro        # prints: REPRO FAIL: Mac state not impossible   (exit 1)
dotnet run -c Release   # JIT: prints REPRO PASS

Repro.csproj:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework><Nullable>enable</Nullable><InvariantGlobalization>true</InvariantGlobalization></PropertyGroup>
</Project>

Program.cs:

using System;
internal static class EarthPilotReadout
{
    public enum RecoveryVerdict
    {
        /// <summary>No propellant can be burned.</summary>
        NoFuel,
        /// <summary>The upper bound on available impulse is below the lower bound on need: no burns from here or higher can restore the floor.</summary>
        Impossible,
        /// <summary>The ideal burn time for the bound impulse exceeds the coast estimate of the time to the air: entry should
        /// come first. A heuristic, not a proof: a burn changes the descent, so the cue says "likely".</summary>
        TooLate,
        /// <summary>Available impulse covers the bound by less than 15 %, in time: losses may eat the margin.</summary>
        Marginal,
        /// <summary>Available impulse covers the bound with at least 15 % spare, in time; still an estimate, not a promise.</summary>
        Feasible
    }

    public static double RecoveryDeltaVLowerBound(double radiusMeters, double speedMetersPerSecond, double floorRadiusMeters,
        double airRadiusMeters, double gravitationalParameter)
    {
        if (!double.IsFinite(radiusMeters) || radiusMeters <= 0) throw new ArgumentOutOfRangeException(nameof(radiusMeters));
        if (!double.IsFinite(speedMetersPerSecond) || speedMetersPerSecond < 0) throw new ArgumentOutOfRangeException(nameof(speedMetersPerSecond));
        if (!double.IsFinite(floorRadiusMeters) || floorRadiusMeters <= 0) throw new ArgumentOutOfRangeException(nameof(floorRadiusMeters));
        if (!double.IsFinite(airRadiusMeters) || airRadiusMeters <= 0) throw new ArgumentOutOfRangeException(nameof(airRadiusMeters));
        if (!double.IsFinite(gravitationalParameter) || gravitationalParameter <= 0) throw new ArgumentOutOfRangeException(nameof(gravitationalParameter));
        double reference = Math.Min(radiusMeters, airRadiusMeters);
        double energy = speedMetersPerSecond * speedMetersPerSecond / 2 - gravitationalParameter / radiusMeters;
        double fastest = Math.Sqrt(Math.Max(0, 2 * (energy + gravitationalParameter / reference)));
        double least = -gravitationalParameter / (floorRadiusMeters + Math.Max(reference, floorRadiusMeters));
        if (energy >= least) return 0;
        return Math.Max(0, Math.Sqrt(2 * (least + gravitationalParameter / reference)) - fastest);
    }

    public static double AvailableDeltaV(double massKilograms, double propellantKilograms, double specificImpulseSeconds)
    {
        if (!double.IsFinite(massKilograms) || massKilograms <= 0) throw new ArgumentOutOfRangeException(nameof(massKilograms));
        if (!double.IsFinite(propellantKilograms) || propellantKilograms < 0 || propellantKilograms >= massKilograms) throw new ArgumentOutOfRangeException(nameof(propellantKilograms));
        if (!double.IsFinite(specificImpulseSeconds) || specificImpulseSeconds <= 0) throw new ArgumentOutOfRangeException(nameof(specificImpulseSeconds));
        return specificImpulseSeconds * 9.80665 * Math.Log(massKilograms / (massKilograms - propellantKilograms));
    }

    public static double BurnSeconds(double deltaV, double thrustNewtons, double massFlowKilogramsPerSecond, double massKilograms)
    {
        if (!double.IsFinite(deltaV) || deltaV < 0) throw new ArgumentOutOfRangeException(nameof(deltaV));
        if (!double.IsFinite(thrustNewtons) || thrustNewtons <= 0) throw new ArgumentOutOfRangeException(nameof(thrustNewtons));
        if (!double.IsFinite(massFlowKilogramsPerSecond) || massFlowKilogramsPerSecond < 0)
            throw new ArgumentOutOfRangeException(nameof(massFlowKilogramsPerSecond));
        if (!double.IsFinite(massKilograms) || massKilograms <= 0) throw new ArgumentOutOfRangeException(nameof(massKilograms));
        if (massFlowKilogramsPerSecond == 0) return deltaV * massKilograms / thrustNewtons;
        double fraction = 1 - Math.Exp(-deltaV * massFlowKilogramsPerSecond / thrustNewtons);
        return massKilograms / massFlowKilogramsPerSecond * fraction;
    }

    public static RecoveryVerdict Recovery(double availableDeltaV, double neededDeltaV, double burnSeconds, double secondsToAir)
    {
        if (!double.IsFinite(availableDeltaV) || availableDeltaV < 0) throw new ArgumentOutOfRangeException(nameof(availableDeltaV));
        if (!double.IsFinite(neededDeltaV) || neededDeltaV < 0) throw new ArgumentOutOfRangeException(nameof(neededDeltaV));
        if (!double.IsFinite(burnSeconds) || burnSeconds < 0) throw new ArgumentOutOfRangeException(nameof(burnSeconds));
        if (!double.IsFinite(secondsToAir) || secondsToAir < 0) throw new ArgumentOutOfRangeException(nameof(secondsToAir));
        return availableDeltaV <= 0 ? RecoveryVerdict.NoFuel
            : availableDeltaV < neededDeltaV ? RecoveryVerdict.Impossible
            : burnSeconds > secondsToAir ? RecoveryVerdict.TooLate
            : availableDeltaV < 1.15 * neededDeltaV ? RecoveryVerdict.Marginal : RecoveryVerdict.Feasible;
    }
}
internal static class Program
{
    private static void Require(bool condition, string message)
    { if (!condition) throw new Exception(message); }
    private static void Reject<T>(Action action, string message) where T : Exception
    {
        try { action(); } catch (T) { return; }
        throw new Exception(message);
    }
    private static int Main()
    {
        Action fixture = () =>
        {
            const double mu = 3.986004418e14, air = 6_378_137 + 100_000, floor = 6_378_137 + 150_000;
            // 41 % fuel gives at most about 1.9 km/s, so the fall-back stays impossible under the rigorous bound.
            double mac = EarthPilotReadout.RecoveryDeltaVLowerBound(6_378_137 + 144_570, 3500, floor, air, mu);
            double available = EarthPilotReadout.AvailableDeltaV(400_000, 160_000, 380);
            // Burn time is the ideal finite-mass time, checked independently of the production formula: Codex's
            // counterexample (ALL SIX thrust and flow, 400 t, 1000 m/s) is 21.966176 s, below the former Δv·m/F of 25.27 s.
            const double allSixThrust = 15_827_933.1, allSixFlow = 4546.411483;
            // Brute-force integration of dv/dt = F / (m0 - ṁ t) until the impulse is reached, 1 ms steps (midpoint mass).
            foreach (double impulse in new[] { 250.0, 1000.0, 4000.0 })
            {
                double v = 0, t = 0; const double step = .001;
                while (v < impulse) { v += allSixThrust / (400_000 - allSixFlow * (t + step / 2)) * step; t += step; }
                double ideal = EarthPilotReadout.BurnSeconds(impulse, allSixThrust, allSixFlow, 400_000);
                Require(Math.Abs(ideal - t) < 2 * step, $"integrated {t:F3} s vs ideal {ideal:F3} s for {impulse} m/s");
                Require(ideal < impulse * 400_000 / allSixThrust && ideal > impulse * (400_000 - allSixFlow * ideal) / allSixThrust,
                    $"ideal time outside the constant-mass bounds for {impulse} m/s");
            }
            Require(EarthPilotReadout.BurnSeconds(0, allSixThrust, allSixFlow, 400_000) == 0, "zero impulse takes time");
            Reject<ArgumentOutOfRangeException>(() => EarthPilotReadout.BurnSeconds(1, 0, 1, 1), "zero thrust");
            Require(EarthPilotReadout.Recovery(available, mac, 1, 100) == EarthPilotReadout.RecoveryVerdict.Impossible, "Mac state not impossible");
        };
        try { fixture(); Console.WriteLine("REPRO PASS"); return 0; }
        catch (Exception e) { Console.WriteLine("REPRO FAIL: " + e.Message); return 1; }
    }
}

Expected behavior

REPRO PASS: mac keeps the value computed before the loop, so Recovery(available, mac, 1, 100) returns Impossible.

Actual behavior

REPRO FAIL: Mac state not impossible. Instrumenting the original test showed mac == 1 at the final check, while the same local had passed 4000 < mac < 4600 twelve lines earlier.

Regression?

Unknown. Observed with .NET 10.0.11 and 10.0.12.

Known Workarounds

[MethodImpl(MethodImplOptions.NoOptimization)] on the affected lambda or method. OptimizationPreference=Size does not help.

Configuration

Configuration Result
osx-arm64 NativeAOT, SDK 10.0.400 / ILCompiler 10.0.11 FAIL
osx-arm64 NativeAOT, Microsoft.DotNet.ILCompiler 10.0.12 + runtime 10.0.12 FAIL
osx-arm64 NativeAOT, -p:OptimizationPreference=Size FAIL
osx-arm64 NativeAOT, NoOptimization on the lambda PASS
osx-arm64 JIT (Release), default and with TieredCompilation=0 PASS
linux-x64 NativeAOT (the original 1,630-test suite) PASS

Hardware and OS: Apple M3 Pro, macOS 27.0.1. .NET 11 previews were not tested (no .NET 11 SDK installed).

Other information

The JIT on osx-arm64 passes even with full optimization forced (DOTNET_TieredCompilation=0 DOTNET_ReadyToRun=0, and separately DOTNET_TieredPGO=0 DOTNET_TC_QuickJitForLoops=0), so this seems specific to NativeAOT (ILC) code generation for ARM64. It may be register allocation or spilling of a long-lived double across a loop that contains a call that can throw, but that is a guess.

Activity

  1. added
    untriaged
    on Oct 12, 2026
  2. dotnet-policy-service commented on Oct 12, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/area-system-numerics
    See info in area-owners.md if you want to be subscribed.

  3. added
    area-CodeGen-coreclr
    on Oct 12, 2026
  4. dotnet-policy-service commented on Oct 12, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @JulieLeeMSFT, @jakobbotsch
    See info in area-owners.md if you want to be subscribed.

  5. EgorBo commented on Oct 12, 2026

    @EgorBo
    Member

    The root cause appears to be incorrect NativeAOT ARM64 Mach-O compact-unwind metadata, rather than loop optimization or register allocation.

    In GetArm64CompactUnwindCode, the floating-point register-pair flags are shifted using the absolute array index. i starts at REG_IDX_D8 == 12, so the flags end up six bits too high. The calculation should be:

    unwindCode |= UNWIND_ARM64_FRAME_D8_D9_PAIR << ((i - REG_IDX_D8) >> 1);

    This explains the exact mac == 1 observation:

    • The fixture keeps mac in the callee-saved register d8 and passes it correctly to the final Recovery call.
    • The final BurnSeconds(1, 0, 1, 1) saves d8/d9, overwrites them with its flow/mass arguments (1), and then throws because the thrust is zero.
    • The .NET 10.0.12 object contains compact-unwind encoding 0x44004001 for BurnSeconds, instead of 0x44000101. The unwinder therefore misses the saved FP registers, and the catch resumes with d8 == 1 instead of the original mac.

    The loop is incidental. NoOptimization avoids the symptom by keeping the value on the stack, while the JIT and non-Apple targets use different unwind paths.

    The issue is also present on current main: invoking the actual encoder produces incorrect flags for all four FP register pairs. An isolated run of the actual ARM64 compact unwinder on Windows leaves d8 == 1 with the emitted encoding and restores the saved value with the corrected encoding. The complete NativeAOT executable has not been run on macOS as part of this investigation. This calculation was introduced in #111451.

    AI disclosure: This investigation and comment were generated by GitHub Copilot.

  6. added and removed
    area-CodeGen-coreclr
    on Oct 12, 2026
  7. mathewritter commented on Oct 13, 2026

    @mathewritter
    Author

    Confirmed on Apple Silicon: M3 Pro, macOS 27.0.1 (26A434), .NET SDK 10.0.400, Apple clang 21.0.0. ILCompiler 10.0.11 and 10.0.12 give identical results.

    • Repro: the repro from this issue, published osx-arm64 NativeAOT with -p:StripSymbols=false, prints REPRO FAIL on both ILCompiler versions.
    • Encoding: llvm-objdump --unwind-info on the ILC object shows BurnSeconds as 0x44004001. Its prologue is stp d9, d8, [sp,#-0x30]!; stp x20, x19, [sp,#0x10]; stp x29, x30, [sp,#0x20], so the expected encoding is 0x44000101. The D8/D9 flag is at 0x4000 instead of 0x100, exactly as described in the comment above.
    • One-byte patch: I changed that single byte in a copy of the object (0x40 → 0x01, giving 0x44000101) and relinked with the build's exact clang command. The patched binary prints REPRO PASS. A control relink of the unmodified object still fails.
    • All four D pairs: in the same repro object, the Main lambda saves d8–d15 and x19–x22, and is encoded 0x4403c003 instead of 0x44000f03. D10/D11, D12/D13 and D14/D15 land at 0x8000, 0x10000 and 0x20000, as predicted. The proposed << ((i - REG_IDX_D8) >> 1) should cover all four. A regression test that checks the emitted compact-unwind encoding for a function saving FP register pairs would catch this class of bug.
    • Scale: in our full test suite's NativeAOT object, 1,872 of the 21,418 frame-mode compact-unwind entries have D-pair flags in 0x0003C000: 1,872 with D8/D9, 885 with D10/D11, 548 with D12/D13 and 371 with D14/D15. No frame-mode entry uses the valid D-pair bits (0xF00), so every frame-mode function that saves d8–d15 appears to be misencoded. Our 25 osx-arm64-NativeAOT-only fixture failures (of 1,634) are nearly all exception or refusal-path tests, which is consistent with this. I haven't traced each one individually.
    • iOS (untested): ios-arm64 NativeAOT presumably shares the same Mach-O writer and would be affected the same way. I haven't tested it.

    Thanks for the quick diagnosis.

  8. sirforce commented on Dec 3, 2026

    @sirforce

    Still reproduces on 10.0.14 and 10.0.15 (osx-arm64 NativeAOT), so it isn't fixed in the current servicing releases. A smaller repro, in case it's useful as a regression test: the exception is caught in a callee, with no loop needed.

    Platform ILCompiler / runtime JIT NativeAOT
    osx-arm64 (SDK 10.0.403) 10.0.14 pass fail (lo=-1 hi=1, exit 1)
    osx-arm64 (ILCompiler and runtime pack pinned to 10.0.15) 10.0.15 pass fail (lo=-1 hi=1, exit 1)
    win-x64 (SDK 10.0.404) 10.0.15 pass pass

    The win-x64 pass is consistent with the compact-unwind diagnosis above (Mach-O only).

    Program.cs (repro)
    using System.Runtime.CompilerServices;
    
    static class Program
    {
        private sealed class Boom : Exception;
    
        // The thrower keeps doubles live in callee-saved floating-point registers before throwing.
        [MethodImpl(MethodImplOptions.NoInlining)]
        private static double Thrower(double x)
        {
            double a = 1.0, b = 2.0, c = 3.0, d = 4.0, e = 5.0, f = 6.0, g = 7.0, h = 8.0;
            for (var i = 0; i < 3; i++)
            {
                a += Helper(x); b += Helper(a); c += Helper(b); d += Helper(c);
                e += Helper(d); f += Helper(e); g += Helper(f); h += Helper(g);
            }
            if (x < 0)
            {
                throw new Boom();
            }
            return a + b + c + d + e + f + g + h;
        }
    
        [MethodImpl(MethodImplOptions.NoInlining)]
        private static double Helper(double v) => v * 0.0;
    
        [MethodImpl(MethodImplOptions.NoInlining)]
        private static double Safe(double x)
        {
            try
            {
                return Thrower(x);
            }
            catch (Boom)
            {
                return double.NaN;
            }
        }
    
        [MethodImpl(MethodImplOptions.NoInlining)]
        private static int Caller(double lo, double hi)
        {
            double keepLo = lo * 1.0, keepHi = hi * 1.0, sum = 0;
            for (var i = 0; i < 2; i++)
            {
                sum += Safe(-1) is var y && double.IsNaN(y) ? 0 : y;
                sum += Helper(keepLo) + Helper(keepHi);
            }
            // Compare through memory, so the check itself isn't fooled by the same corrupted registers.
            var seen = new[] { keepLo, keepHi };
            Console.WriteLine($"lo={seen[0]:R} hi={seen[1]:R} (expected -0.5 0.25)");
            return BitConverter.DoubleToInt64Bits(seen[0]) == BitConverter.DoubleToInt64Bits(-0.5)
                && BitConverter.DoubleToInt64Bits(seen[1]) == BitConverter.DoubleToInt64Bits(0.25) ? 0 : 1;
        }
    
        private static int Main() => Caller(-0.5, 0.25);
    }
    aot-fp-repro.csproj
    <Project Sdk="Microsoft.NET.Sdk">
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net10.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
        <PublishAot>true</PublishAot>
        <InvariantGlobalization>true</InvariantGlobalization>
      </PropertyGroup>
    </Project>
    dotnet run -c Release                                           # lo=-0.5 hi=0.25, exit 0
    dotnet publish -c Release -r osx-arm64 -o out && ./out/aot-fp-repro   # lo=-1 hi=1, exit 1
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area-NativeAOT-coreclruntriaged

Type

No type

Projects

  • Status
    No status

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions