Repository navigation
Description
JIT: loop cloning generates unsafe fast clone for decreasing loops when limit and indexed arrays differ
Note
This issue was investigated and drafted with GitHub Copilot CLI.
Description
optDeriveLoopCloningConditions derives a limit <relop> arr.Length condition for the per-access bounds-check elision, where limit is the loop test's RHS. For increasing loops this is sound because the visited indices are [init, limit) and init is independently constrained >= 0. For decreasing loops the visited indices are [limit+1, init], so the value that must fit in the indexed array is init, not limit. The current code only constrains init against the array length when the limit is a constant or an invariant local — when HasArrayLengthLimit is true, ident is set to the limit (loopcloning.cpp ~line 1419) and no bound on init is emitted, so the fast clone (with bounds checks removed) is taken even when init is far outside the indexed array.
This is benign in the very common shape for (i = a.Length - 1; i > 0; i--) a[i]… because there init and the indexed array agree and the array-deref/length condition implicitly bounds init. It becomes unsafe as soon as the loop test's limit array differs from the array being indexed inside the body.
Reproduction
Repository: dotnet/runtime
Tested on: main at 9593745 (also reproduces on .NET 10 RTM)
Configuration: windows.x64.Checked, FullOpts, tiering disabled.
using System;
using System.Runtime.CompilerServices;
public class P
{
[MethodImpl(MethodImplOptions.NoInlining)]
public static int LatentBugGT(byte[] limitArr, byte[] accessArr, int startIdx)
{
int sum = 0;
for (int i = startIdx; i > limitArr.Length; i--)
sum += accessArr[i];
return sum;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static int LatentBugGE(byte[] limitArr, byte[] accessArr, int startIdx)
{
int sum = 0;
for (int i = startIdx; i >= limitArr.Length; i--)
sum += accessArr[i];
return sum;
}
public static int Main()
{
Console.WriteLine("=== GT ===");
try { int x = LatentBugGT(new byte[1], new byte[5], 1000); Console.WriteLine($"BUG: returned {x}"); }
catch (IndexOutOfRangeException) { Console.WriteLine("OK: threw IndexOutOfRangeException"); }
Console.WriteLine("=== GE ===");
try { int x = LatentBugGE(new byte[1], new byte[5], 1000); Console.WriteLine($"BUG: returned {x}"); }
catch (IndexOutOfRangeException) { Console.WriteLine("OK: threw IndexOutOfRangeException"); }
return 100;
}
}Expected
Both calls index accessArr[1000] (length 5) and must throw IndexOutOfRangeException.
Actual
=== GT ===
BUG: returned 0
=== GE ===
BUG: returned 0
Both loops silently iterate i = 1000, 999, …, 2 (or …, 1 for GE) and dereference accessArr[i] for ~999 out-of-bounds indices with no exception. Whatever the GC heap happens to contain at those offsets is summed and returned. (In the small repro above the sum happens to be 0; with arbitrary heap state this would silently corrupt analysis results, or — for write loops — silently corrupt heap memory.)
Cloning conditions emitted
JIT dump from the unmodified clrjit.dll:
Conditions: (V04 GE 0) && (V00.Length LT V01.Length)
Considering condition 0: (V04 GE 0), could not be evaluated
Considering condition 1: (V00.Length LT V01.Length), could not be evaluated
Loops cloned: 1
Loops statically optimized: 0
V04 = startIdx, V00 = limitArr, V01 = accessArr. With the bad inputs startIdx=1000, limitArr.Length=1, accessArr.Length=5:
| condition | actual |
|---|---|
startIdx >= 0 |
1000 >= 0 ✓ |
limitArr.Length < accessArr.Length |
1 < 5 ✓ |
Both pass → fast clone runs without bounds checks → OOB reads of accessArr.
Root cause
In src/coreclr/jit/loopcloning.cpp optDeriveLoopCloningConditions:
- For
HasConstInitdecreasing loops,ident = init(line ~1348). - For variable-init decreasing loops,
ident = initVar(line ~1370). - For
HasArrayLengthLimit,identis unconditionally set to the limit array's length (~line 1419), regardless of direction. The decreasing path then emitscond(opLimitCondition, ident, accessArr.Length)which evaluates tolimitArr.Length < accessArr.Length— a constraint onlimit, notinit.
The cloning condition needed for soundness in the decreasing direction is init < accessArr.Length (for GT) or init <= accessArr.Length (for GE), independent of what the limit array is.
Suggested fix
For decreasing loops with HasArrayLengthLimit, do not let the limit array length be used as ident. Instead, always materialize an independent init-based identifier (from iterInfo->IterVar at the preheader, or iterInfo->ConstInitValue) and emit the per-access init <relop> accessArr.Length condition against it. The increasing-loop path can be left as is.
Why this isn't fixed in PR for #84697
This was found while reviewing the changes for #84697 (bounds-check elimination for i != arr.Length loops). To keep that PR's blast radius bounded I restricted GT_NE support to increasing loops only, with an explicit comment noting that decreasing GT_NE would have inherited (and widened) this bug into the very common for (i = end; i != start; i--) idiom. The regression test in that PR (Runtime_84697.SumDecreasingNETwoArrays) pins the safe behavior for GT_NE. The pre-existing GT_GT/GT_GE versions documented here remain.
Suggested area / labels
area-CodeGen-coreclrtenet-correctnessbug
category
correctness
theme
loop-cloning · bounds-checks
skill-level
expert
cost
medium
impact
medium (correctness — silent OOB read in an uncommon but legitimate code shape)
Activity
AndyAyersMS commentedon Jun 9, 2026
Note
AI-assisted analysis (GitHub Copilot CLI).
Bug provenance
The bug was introduced in #67930 (commit
1bc09e76f04, Apr 26 2022) which added theisIncreasingLoop/isDecreasingLoopdistinction tooptDeriveLoopCloningConditions. That PR correctly gated theLPFLG_CONST_LIMITandLPFLG_VAR_LIMITbranches onisIncreasingLoop(so they only assignident = limitfor increasing loops), but the parallelLPFLG_ARRLEN_LIMITbranch was missed — it kept the unconditionalident = LC_Ident(LC_Array(...))that was correct only under the original "increasing only" assumption.The misconception is visible in the comment block that was added in the same PR:
For decreasing loops the upper end of the IV's range is
init(i.e. the LHS of the test), notend/limit; the conditions should beinit <= arrLen/init < arrLen. The current per-access conditionident <relop> accessArr.Lengthis therefore correct only whenidentrepresentsinitfor decreasing loops — which the other two limit branches achieve by leavingidentalone, but theARRLEN_LIMITbranch silently overwrote.Release impact
1bc09e76f04is inv7.0.0-preview.5.22301.12, so the bug shipped in:In other words, ~4 years and 4 major releases. The reason it appears to have gone unreported is that the unsafe shape requires:
>= accessArr.LengthThe much more common decreasing-loop idiom
for (i = a.Length - 1; i >= 0; i--) a[i]usesLPFLG_CONST_LIMIT(limit0), notLPFLG_ARRLEN_LIMIT, so it is unaffected.JIT: fix loop cloning condition for decreasing loops with array-lengt…
JIT: eliminate bounds checks for "i != arr.Length" loops
JIT: clone "i != arr.Length" loops to eliminate bounds checks (#129268)
JIT: fix loop cloning condition for decreasing loops with array-lengt…
JIT: fix loop cloning condition for decreasing loops with array-lengt…