Skip to content

Commit 298c247

Browse files
InlineArrayTransform: Add more bounds checking
1 parent 47dd905 commit 298c247

File tree

1 file changed

+23
-12
lines changed

1 file changed

+23
-12
lines changed

ICSharpCode.Decompiler/IL/Transforms/InlineArrayTransform.cs

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,10 @@ static bool MatchSpanIndexerWithInlineArrayAsSpan(Call inst, [NotNullWhen(true)]
9393
if (!MatchInlineArrayHelper(targetInst.Method, "InlineArrayAsReadOnlySpan", out var inlineArrayType))
9494
return false;
9595

96-
if (targetInst.Arguments is not [var addrInst, LdcI4])
96+
if (targetInst.Arguments is not [var addrInst, LdcI4 { Value: var length }])
97+
return false;
98+
99+
if (length < 0 || length > inlineArrayType.GetInlineArrayLength())
97100
return false;
98101

99102
type = inlineArrayType;
@@ -110,7 +113,10 @@ static bool MatchSpanIndexerWithInlineArrayAsSpan(Call inst, [NotNullWhen(true)]
110113
if (!MatchInlineArrayHelper(targetInst.Method, "InlineArrayAsSpan", out var inlineArrayType))
111114
return false;
112115

113-
if (targetInst.Arguments is not [var addrInst, LdcI4])
116+
if (targetInst.Arguments is not [var addrInst, LdcI4 { Value: var length }])
117+
return false;
118+
119+
if (length < 0 || length > inlineArrayType.GetInlineArrayLength())
114120
return false;
115121

116122
type = inlineArrayType;
@@ -135,28 +141,33 @@ static bool MatchInlineArrayElementRef(Call inst, [NotNullWhen(true)] out IType?
135141
index = null;
136142
isReadOnly = false;
137143

138-
if (inst.Arguments is not [var addrInst, var indexInst])
144+
if (inst.Arguments is not [var addrInst, LdcI4 { Value: var indexValue } indexInst])
139145
return false;
140146

147+
addr = addrInst;
148+
index = indexInst;
149+
141150
if (MatchInlineArrayHelper(inst.Method, "InlineArrayElementRef", out var inlineArrayType))
142151
{
143152
isReadOnly = false;
144153
type = inlineArrayType;
145-
addr = addrInst;
146-
index = indexInst;
147-
return true;
148154
}
149-
150-
if (MatchInlineArrayHelper(inst.Method, "InlineArrayElementRefReadOnly", out inlineArrayType))
155+
else if (MatchInlineArrayHelper(inst.Method, "InlineArrayElementRefReadOnly", out inlineArrayType))
151156
{
152157
isReadOnly = true;
153158
type = inlineArrayType;
154-
addr = addrInst;
155-
index = indexInst;
156-
return true;
159+
}
160+
else
161+
{
162+
return false;
157163
}
158164

159-
return false;
165+
if (indexValue < 0 || indexValue >= inlineArrayType.GetInlineArrayLength())
166+
{
167+
return false;
168+
}
169+
170+
return true;
160171
}
161172

162173
private static bool MatchInlineArrayFirstElementRef(Call inst, [NotNullWhen(true)] out IType? type, [NotNullWhen(true)] out ILInstruction? addr, out bool isReadOnly)

0 commit comments

Comments
 (0)