Skip to content

JIT: Head merging can reorder a null dereference ahead of a division and throw the wrong exception #137253

Closed

Description

@NinoFloris

Description

Head merging can move a field read shared by both branches ahead of the condition that established its non-nullness. The interference check misses this when the condition contains an invariant load that can throw but has no GTF_GLOB_REF.

If the condition evaluates a division first, a null receiver and zero divisor incorrectly produce NullReferenceException instead of DivideByZeroException.

Reproduction Steps

Similar codegen is already present in ILCompiler.IBC.IBCProfileParser.GetSigTypeFromIBCZapSig. Discovered through the verifier added in #137045

using System;
using System.Runtime.CompilerServices;

class Program
{
    class Receiver { public int Value = 42; }
    static int s_marker;

    [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.AggressiveOptimization)]
    static int Read(Receiver receiver, int divisor)
    {
        int value;
        // Both branches read receiver.Value after GetType has checked receiver.
        // Moving that read before the condition invalidates its non-null proof.
        if ((10 / divisor > 0) == (receiver.GetType() == typeof(Receiver)))
        {
            value = receiver.Value;
            s_marker = 1;
        }
        else
        {
            value = receiver.Value;
            s_marker = 2;
        }
        return value;
    }

    static void Main()
    {
        try { Read(null, 0); }
        catch (Exception ex)
        {
            Console.WriteLine(ex.GetType().Name);
            Console.WriteLine(s_marker);
        }
    }
}

Expected behavior

DivideByZeroException

Actual behavior

NullReferenceException

Regression?

No response

Known Workarounds

No response

Configuration

No response

Other information

The hole is that the interference check misses faulting invariant loads without GTF_GLOB_REF, which inlining or devirtualization can leave behind. GetType() is just an easy way to get one.

Activity

  1. added
    untriaged
    on Nov 10, 2026
  2. added
    area-CodeGen-coreclr
    on Nov 10, 2026
  3. dotnet-policy-service commented on Nov 10, 2026

    @dotnet-policy-service
    Contributor

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

  4. removed
    untriaged
    on Nov 12, 2026
  5. added a commit that references this issue on Nov 12, 2026
    c4cecc4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-CodeGen-coreclr

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions