| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System.Buffers; |
| | | 5 | | using System.Collections.Generic; |
| | | 6 | | using System.Diagnostics; |
| | | 7 | | using System.Diagnostics.CodeAnalysis; |
| | | 8 | | using System.Text; |
| | | 9 | | |
| | | 10 | | namespace System.Reflection.Metadata |
| | | 11 | | { |
| | | 12 | | internal static class TypeNameParserHelpers |
| | | 13 | | { |
| | | 14 | | internal const int SZArray = -1; |
| | | 15 | | internal const int Pointer = -2; |
| | | 16 | | internal const int ByRef = -3; |
| | | 17 | | private const char EscapeCharacter = '\\'; |
| | | 18 | | |
| | 1 | 19 | | private static readonly SearchValues<char> s_endOfFullTypeNameDelimiterChars = SearchValues.Create("[]&*,+\\"); |
| | | 20 | | |
| | | 21 | | /// <returns>Positive length or negative value for invalid name</returns> |
| | | 22 | | internal static int GetFullTypeNameLength(ReadOnlySpan<char> input, out bool isNestedType) |
| | 56172 | 23 | | { |
| | 56172 | 24 | | isNestedType = false; |
| | | 25 | | |
| | | 26 | | // NET 6+ guarantees that MemoryExtensions.IndexOfAny has worst-case complexity |
| | | 27 | | // O(m * i) if a match is found, or O(m * n) if a match is not found, where: |
| | | 28 | | // i := index of match position |
| | | 29 | | // m := number of needles |
| | | 30 | | // n := length of search space (haystack) |
| | | 31 | | // |
| | | 32 | | // Downlevel versions of .NET do not make this guarantee, instead having a |
| | | 33 | | // worst-case complexity of O(m * n) even if a match occurs at the beginning of |
| | | 34 | | // the search space. Since we're running this in a loop over untrusted user |
| | | 35 | | // input, that makes the total loop complexity potentially O(m * n^2), where |
| | | 36 | | // 'n' is adversary-controlled. To avoid DoS issues here, we'll loop manually. |
| | 56172 | 37 | | int offset = input.IndexOfAny(s_endOfFullTypeNameDelimiterChars); |
| | 56172 | 38 | | if (offset < 0) |
| | 1292 | 39 | | { |
| | 1292 | 40 | | return input.Length; // no type name end chars were found, the whole input is the type name |
| | | 41 | | } |
| | | 42 | | |
| | 54880 | 43 | | if (input[offset] == EscapeCharacter) // this is very rare (IL Emit or pure IL) |
| | 4084 | 44 | | { |
| | 4084 | 45 | | offset = GetUnescapedOffset(input, startOffset: offset); // this is slower, but very rare so acceptable |
| | 4084 | 46 | | } |
| | | 47 | | |
| | 54880 | 48 | | isNestedType = offset > 0 && offset < input.Length && input[offset] == '+'; |
| | 54880 | 49 | | return offset; |
| | | 50 | | |
| | | 51 | | static int GetUnescapedOffset(ReadOnlySpan<char> input, int startOffset) |
| | 4084 | 52 | | { |
| | 4084 | 53 | | int offset = startOffset; |
| | 39476 | 54 | | for (; offset < input.Length; offset++) |
| | 21372 | 55 | | { |
| | 21372 | 56 | | char c = input[offset]; |
| | 21372 | 57 | | if (c == EscapeCharacter) |
| | 8160 | 58 | | { |
| | 8160 | 59 | | offset++; // skip the escaped char |
| | | 60 | | |
| | 8160 | 61 | | if (offset == input.Length || // invalid name that ends with escape character |
| | 8160 | 62 | | !s_endOfFullTypeNameDelimiterChars.Contains(input[offset])) // invalid name, escapes a char |
| | 76 | 63 | | { |
| | 76 | 64 | | return -1; |
| | | 65 | | } |
| | 8084 | 66 | | } |
| | 13212 | 67 | | else if (s_endOfFullTypeNameDelimiterChars.Contains(c)) |
| | 3600 | 68 | | { |
| | 3600 | 69 | | break; |
| | | 70 | | } |
| | 17696 | 71 | | } |
| | 4008 | 72 | | return offset; |
| | 4084 | 73 | | } |
| | 56172 | 74 | | } |
| | | 75 | | |
| | | 76 | | internal static int IndexOfNamespaceDelimiter(ReadOnlySpan<char> fullName) |
| | 7180 | 77 | | { |
| | | 78 | | // Matches algorithm from ns::FindSep in src\coreclr\utilcode\namespaceutil.cpp |
| | | 79 | | // This could result in the type name beginning with a '.' character. |
| | 7180 | 80 | | int index = fullName.LastIndexOf('.'); |
| | | 81 | | |
| | 7180 | 82 | | if (index > 0 && fullName[index - 1] == '.') |
| | 4 | 83 | | { |
| | 4 | 84 | | index--; |
| | 4 | 85 | | } |
| | | 86 | | |
| | 7180 | 87 | | return index; |
| | 7180 | 88 | | } |
| | | 89 | | |
| | | 90 | | internal static string Unescape(string input) |
| | 0 | 91 | | { |
| | 0 | 92 | | int indexOfEscapeCharacter = input.IndexOf(EscapeCharacter); |
| | 0 | 93 | | if (indexOfEscapeCharacter < 0) |
| | 0 | 94 | | { |
| | | 95 | | // Nothing to escape, just return the original value. |
| | 0 | 96 | | return input; |
| | | 97 | | } |
| | | 98 | | |
| | 0 | 99 | | return UnescapeToBuilder(input, indexOfEscapeCharacter); |
| | | 100 | | |
| | | 101 | | static string UnescapeToBuilder(string name, int indexOfEscapeCharacter) |
| | 0 | 102 | | { |
| | | 103 | | // This code path is executed very rarely (IL Emit or pure IL with chars not allowed in C# or F#). |
| | 0 | 104 | | var sb = new ValueStringBuilder(stackalloc char[64]); |
| | 0 | 105 | | sb.EnsureCapacity(name.Length); |
| | 0 | 106 | | sb.Append(name.AsSpan(0, indexOfEscapeCharacter)); |
| | | 107 | | |
| | 0 | 108 | | for (int i = indexOfEscapeCharacter; i < name.Length;) |
| | 0 | 109 | | { |
| | 0 | 110 | | char c = name[i++]; |
| | | 111 | | |
| | 0 | 112 | | if (c != EscapeCharacter || i == name.Length) |
| | 0 | 113 | | { |
| | 0 | 114 | | sb.Append(c); |
| | 0 | 115 | | } |
| | 0 | 116 | | else if (name[i] == EscapeCharacter) // escaped escape character ;) |
| | 0 | 117 | | { |
| | 0 | 118 | | sb.Append(c); |
| | | 119 | | // Consume the escaped escape character, it's important for edge cases |
| | | 120 | | // like escaped escape character followed by another escaped char (example: "\\\\\\+") |
| | 0 | 121 | | i++; |
| | 0 | 122 | | } |
| | 0 | 123 | | } |
| | | 124 | | |
| | 0 | 125 | | return sb.ToString(); |
| | 0 | 126 | | } |
| | 0 | 127 | | } |
| | | 128 | | |
| | | 129 | | // this method handles escaping of the ] just to let the AssemblyNameParser fail for the right input |
| | | 130 | | internal static ReadOnlySpan<char> GetAssemblyNameCandidate(ReadOnlySpan<char> input) |
| | 11164 | 131 | | { |
| | | 132 | | // The only delimiter which can terminate an assembly name is ']'. |
| | | 133 | | // Otherwise EOL serves as the terminator. |
| | 11164 | 134 | | int offset = input.IndexOf(']'); |
| | | 135 | | |
| | 11164 | 136 | | if (offset > 0 && input[offset - 1] == EscapeCharacter) // this should be very rare (IL Emit & pure IL) |
| | 672 | 137 | | { |
| | 672 | 138 | | offset = GetUnescapedOffset(input, startIndex: offset); |
| | 672 | 139 | | } |
| | | 140 | | |
| | 11164 | 141 | | return offset < 0 ? input : input.Slice(0, offset); |
| | | 142 | | |
| | | 143 | | static int GetUnescapedOffset(ReadOnlySpan<char> input, int startIndex) |
| | 672 | 144 | | { |
| | 672 | 145 | | int offset = startIndex; |
| | 71144 | 146 | | for (; offset < input.Length; offset++) |
| | 35348 | 147 | | { |
| | 35348 | 148 | | if (input[offset] is ']') |
| | 5480 | 149 | | { |
| | 5480 | 150 | | if (input[offset - 1] != EscapeCharacter) |
| | 112 | 151 | | { |
| | 112 | 152 | | break; |
| | | 153 | | } |
| | 5368 | 154 | | } |
| | 35236 | 155 | | } |
| | 672 | 156 | | return offset; |
| | 672 | 157 | | } |
| | 11164 | 158 | | } |
| | | 159 | | |
| | | 160 | | internal static void AppendRankOrModifierStringRepresentation(int rankOrModifier, ref ValueStringBuilder builder |
| | 9024 | 161 | | { |
| | 9024 | 162 | | if (rankOrModifier == ByRef) |
| | 1112 | 163 | | { |
| | 1112 | 164 | | builder.Append('&'); |
| | 1112 | 165 | | } |
| | 7912 | 166 | | else if (rankOrModifier == Pointer) |
| | 3092 | 167 | | { |
| | 3092 | 168 | | builder.Append('*'); |
| | 3092 | 169 | | } |
| | 4820 | 170 | | else if (rankOrModifier == SZArray) |
| | 3912 | 171 | | { |
| | 3912 | 172 | | builder.Append("[]"); |
| | 3912 | 173 | | } |
| | 908 | 174 | | else if (rankOrModifier == 1) |
| | 332 | 175 | | { |
| | 332 | 176 | | builder.Append("[*]"); |
| | 332 | 177 | | } |
| | | 178 | | else |
| | 576 | 179 | | { |
| | 576 | 180 | | Debug.Assert(rankOrModifier >= 2); |
| | | 181 | | |
| | | 182 | | // O(rank) work, so we have to assume the rank is trusted. We don't put a hard cap on this, |
| | | 183 | | // but within the TypeName parser, we do require the input string to contain the correct number |
| | | 184 | | // of commas. This forces the input string to have at least O(rank) length, so there's no |
| | | 185 | | // alg. complexity attack possible here. Callers can of course pass any arbitrary value to |
| | | 186 | | // TypeName.MakeArrayTypeName, but per first sentence in this comment, we have to assume any |
| | | 187 | | // such arbitrary value which is programmatically fed in originates from a trustworthy source. |
| | | 188 | | |
| | 576 | 189 | | builder.Append('['); |
| | 576 | 190 | | builder.Append(',', rankOrModifier - 1); |
| | 576 | 191 | | builder.Append(']'); |
| | 576 | 192 | | } |
| | 9024 | 193 | | } |
| | | 194 | | |
| | | 195 | | /// <summary> |
| | | 196 | | /// Are there any captured generic args? We'll look for "[[" and "[" that is not followed by "]", "*" and ",". |
| | | 197 | | /// </summary> |
| | | 198 | | internal static bool IsBeginningOfGenericArgs(ref ReadOnlySpan<char> span, out bool doubleBrackets) |
| | 49704 | 199 | | { |
| | 49704 | 200 | | doubleBrackets = false; |
| | | 201 | | |
| | 49704 | 202 | | if (!span.IsEmpty && span[0] == '[') |
| | 21420 | 203 | | { |
| | | 204 | | // There are no spaces allowed before the first '[', but spaces are allowed after that. |
| | 21420 | 205 | | ReadOnlySpan<char> trimmed = span.Slice(1).TrimStart(); |
| | 21420 | 206 | | if (!trimmed.IsEmpty) |
| | 21364 | 207 | | { |
| | 21364 | 208 | | if (trimmed[0] == '[') |
| | 3992 | 209 | | { |
| | 3992 | 210 | | doubleBrackets = true; |
| | 3992 | 211 | | span = trimmed.Slice(1).TrimStart(); |
| | 3992 | 212 | | return true; |
| | | 213 | | } |
| | 17372 | 214 | | if (!(trimmed[0] is ',' or '*' or ']')) // [] or [*] or [,] or [,,,, ...] |
| | 12716 | 215 | | { |
| | 12716 | 216 | | span = trimmed; |
| | 12716 | 217 | | return true; |
| | | 218 | | } |
| | 4656 | 219 | | } |
| | 4712 | 220 | | } |
| | | 221 | | |
| | 32996 | 222 | | return false; |
| | 49704 | 223 | | } |
| | | 224 | | |
| | | 225 | | internal static bool TryGetTypeNameInfo(TypeNameParseOptions options, ref ReadOnlySpan<char> input, |
| | | 226 | | ref List<int>? nestedNameLengths, ref int recursiveDepth, out int totalLength) |
| | 50364 | 227 | | { |
| | | 228 | | bool isNestedType; |
| | 50364 | 229 | | totalLength = 0; |
| | | 230 | | do |
| | 56172 | 231 | | { |
| | 56172 | 232 | | int length = GetFullTypeNameLength(input.Slice(totalLength), out isNestedType); |
| | 56172 | 233 | | if (length <= 0) |
| | 564 | 234 | | { |
| | | 235 | | // invalid type names: |
| | | 236 | | // -1: invalid escaping |
| | | 237 | | // 0: pair of unescaped "++" characters |
| | 564 | 238 | | return false; |
| | | 239 | | } |
| | | 240 | | |
| | | 241 | | #if SYSTEM_PRIVATE_CORELIB |
| | | 242 | | // Compat: Ignore leading '.' for type names without namespace. .NET Framework historically ignored lead |
| | | 243 | | // that code out there depends on this behavior. For example, type names formed by concatenating namespa |
| | | 244 | | // empty namespace (bug), are going to have superfluous leading '.'. |
| | | 245 | | // This behavior means that types that start with '.' are not round-trippable via type name. |
| | | 246 | | if (length > 1 && input[0] == '.' && input.Slice(0, length).LastIndexOf('.') == 0) |
| | | 247 | | { |
| | | 248 | | input = input.Slice(1); |
| | | 249 | | length--; |
| | | 250 | | } |
| | | 251 | | #endif |
| | 55608 | 252 | | if (isNestedType) |
| | 5904 | 253 | | { |
| | 5904 | 254 | | if (!TryDive(options, ref recursiveDepth)) |
| | 96 | 255 | | { |
| | 96 | 256 | | return false; |
| | | 257 | | } |
| | | 258 | | |
| | 5808 | 259 | | (nestedNameLengths ??= new()).Add(length); |
| | 5808 | 260 | | totalLength += 1; // skip the '+' sign in next search |
| | 5808 | 261 | | } |
| | 55512 | 262 | | totalLength += length; |
| | 111024 | 263 | | } while (isNestedType); |
| | | 264 | | |
| | 49704 | 265 | | return true; |
| | 50364 | 266 | | } |
| | | 267 | | |
| | | 268 | | internal static bool TryParseNextDecorator(ref ReadOnlySpan<char> input, out int rankOrModifier) |
| | 79580 | 269 | | { |
| | | 270 | | // Then try pulling a single decorator. |
| | | 271 | | // Whitespace cannot precede the decorator, but it can follow the decorator. |
| | | 272 | | |
| | 79580 | 273 | | ReadOnlySpan<char> originalInput = input; // so we can restore on 'false' return |
| | | 274 | | |
| | 79580 | 275 | | if (TryStripFirstCharAndTrailingSpaces(ref input, '*')) |
| | 8664 | 276 | | { |
| | 8664 | 277 | | rankOrModifier = Pointer; |
| | 8664 | 278 | | return true; |
| | | 279 | | } |
| | | 280 | | |
| | 70916 | 281 | | if (TryStripFirstCharAndTrailingSpaces(ref input, '&')) |
| | 7760 | 282 | | { |
| | 7760 | 283 | | rankOrModifier = ByRef; |
| | 7760 | 284 | | return true; |
| | | 285 | | } |
| | | 286 | | |
| | 63156 | 287 | | if (TryStripFirstCharAndTrailingSpaces(ref input, '[')) |
| | 14932 | 288 | | { |
| | | 289 | | // SZArray := [] |
| | | 290 | | // MDArray := [*] or [,] or [,,,, ...] |
| | | 291 | | |
| | 14932 | 292 | | int rank = 1; |
| | 14932 | 293 | | bool hasSeenAsterisk = false; |
| | | 294 | | |
| | 31456 | 295 | | ReadNextArrayToken: |
| | | 296 | | |
| | 31456 | 297 | | if (TryStripFirstCharAndTrailingSpaces(ref input, ']')) |
| | 13964 | 298 | | { |
| | | 299 | | // End of array marker |
| | 13964 | 300 | | rankOrModifier = rank == 1 && !hasSeenAsterisk ? SZArray : rank; |
| | 13964 | 301 | | return true; |
| | | 302 | | } |
| | | 303 | | |
| | 17492 | 304 | | if (!hasSeenAsterisk) |
| | 17216 | 305 | | { |
| | 17216 | 306 | | if (rank == 1 && TryStripFirstCharAndTrailingSpaces(ref input, '*')) |
| | 2800 | 307 | | { |
| | | 308 | | // [*] |
| | 2800 | 309 | | hasSeenAsterisk = true; |
| | 2800 | 310 | | goto ReadNextArrayToken; |
| | | 311 | | } |
| | 14416 | 312 | | else if (TryStripFirstCharAndTrailingSpaces(ref input, ',')) |
| | 13724 | 313 | | { |
| | | 314 | | // [,,, ...] |
| | | 315 | | // The runtime restricts arrays to rank 32, but we don't enforce that here. |
| | | 316 | | // Instead, the max rank is controlled by the total number of commas present |
| | | 317 | | // in the array decorator. |
| | 41172 | 318 | | checked { rank++; } |
| | 13724 | 319 | | goto ReadNextArrayToken; |
| | | 320 | | } |
| | 692 | 321 | | } |
| | | 322 | | |
| | | 323 | | // Don't know what this token is. |
| | | 324 | | // Fall through to 'return false' statement. |
| | 968 | 325 | | } |
| | | 326 | | |
| | 49192 | 327 | | input = originalInput; // ensure 'ref input' not mutated |
| | 49192 | 328 | | rankOrModifier = 0; |
| | 49192 | 329 | | return false; |
| | 79580 | 330 | | } |
| | | 331 | | |
| | | 332 | | internal static bool TryStripFirstCharAndTrailingSpaces(ref ReadOnlySpan<char> span, char value) |
| | 347888 | 333 | | { |
| | 347888 | 334 | | if (!span.IsEmpty && span[0] == value) |
| | 106428 | 335 | | { |
| | 106428 | 336 | | span = span.Slice(1).TrimStart(); |
| | 106428 | 337 | | return true; |
| | | 338 | | } |
| | 241460 | 339 | | return false; |
| | 347888 | 340 | | } |
| | | 341 | | |
| | | 342 | | [DoesNotReturn] |
| | | 343 | | internal static void ThrowArgumentNullException(string paramName) |
| | 0 | 344 | | { |
| | 0 | 345 | | throw new ArgumentNullException(paramName); |
| | | 346 | | } |
| | | 347 | | |
| | | 348 | | [DoesNotReturn] |
| | | 349 | | internal static void ThrowArgumentException_InvalidTypeName(int errorIndex) |
| | 3796 | 350 | | { |
| | 3796 | 351 | | throw new ArgumentException(SR.Argument_InvalidTypeName, $"typeName@{errorIndex}"); |
| | | 352 | | } |
| | | 353 | | |
| | | 354 | | [DoesNotReturn] |
| | | 355 | | internal static void ThrowInvalidOperation_MaxNodesExceeded(int limit) |
| | 254 | 356 | | { |
| | | 357 | | #if SYSTEM_REFLECTION_METADATA |
| | 254 | 358 | | throw new InvalidOperationException(SR.Format(SR.InvalidOperation_MaxNodesExceeded, limit)); |
| | | 359 | | #else |
| | | 360 | | Debug.Fail("Expected to be unreachable"); |
| | | 361 | | throw new InvalidOperationException(); |
| | | 362 | | #endif |
| | | 363 | | } |
| | | 364 | | |
| | | 365 | | [DoesNotReturn] |
| | | 366 | | internal static void ThrowInvalidOperation_NotGenericType() |
| | 0 | 367 | | { |
| | | 368 | | #if SYSTEM_REFLECTION_METADATA |
| | 0 | 369 | | throw new InvalidOperationException(SR.InvalidOperation_NotGenericType); |
| | | 370 | | #else |
| | | 371 | | Debug.Fail("Expected to be unreachable"); |
| | | 372 | | throw new InvalidOperationException(); |
| | | 373 | | #endif |
| | | 374 | | } |
| | | 375 | | |
| | | 376 | | [DoesNotReturn] |
| | | 377 | | internal static void ThrowInvalidOperation_NotNestedType() |
| | 0 | 378 | | { |
| | | 379 | | #if SYSTEM_REFLECTION_METADATA |
| | 0 | 380 | | throw new InvalidOperationException(SR.InvalidOperation_NotNestedType); |
| | | 381 | | #else |
| | | 382 | | Debug.Fail("Expected to be unreachable"); |
| | | 383 | | throw new InvalidOperationException(); |
| | | 384 | | #endif |
| | | 385 | | } |
| | | 386 | | |
| | | 387 | | [DoesNotReturn] |
| | | 388 | | internal static void ThrowInvalidOperation_NoElement() |
| | 0 | 389 | | { |
| | | 390 | | #if SYSTEM_REFLECTION_METADATA |
| | 0 | 391 | | throw new InvalidOperationException(SR.InvalidOperation_NoElement); |
| | | 392 | | #else |
| | | 393 | | Debug.Fail("Expected to be unreachable"); |
| | | 394 | | throw new InvalidOperationException(); |
| | | 395 | | #endif |
| | | 396 | | } |
| | | 397 | | |
| | | 398 | | [DoesNotReturn] |
| | | 399 | | internal static void ThrowInvalidOperation_HasToBeArrayClass() |
| | 0 | 400 | | { |
| | | 401 | | #if SYSTEM_REFLECTION_METADATA |
| | 0 | 402 | | throw new InvalidOperationException(SR.Argument_HasToBeArrayClass); |
| | | 403 | | #else |
| | | 404 | | Debug.Fail("Expected to be unreachable"); |
| | | 405 | | throw new InvalidOperationException(); |
| | | 406 | | #endif |
| | | 407 | | } |
| | | 408 | | |
| | | 409 | | [DoesNotReturn] |
| | | 410 | | internal static void ThrowInvalidOperation_NestedTypeNamespace() |
| | 0 | 411 | | { |
| | | 412 | | #if SYSTEM_REFLECTION_METADATA |
| | 0 | 413 | | throw new InvalidOperationException(SR.InvalidOperation_NestedTypeNamespace); |
| | | 414 | | #else |
| | | 415 | | Debug.Fail("Expected to be unreachable"); |
| | | 416 | | throw new InvalidOperationException(); |
| | | 417 | | #endif |
| | | 418 | | } |
| | | 419 | | |
| | | 420 | | internal static bool IsMaxDepthExceeded(TypeNameParseOptions options, int depth) |
| | | 421 | | #if SYSTEM_PRIVATE_CORELIB |
| | | 422 | | => false; // CoreLib does not enforce any limits |
| | | 423 | | #else |
| | 85956 | 424 | | => depth > options.MaxNodes; |
| | | 425 | | #endif |
| | | 426 | | |
| | | 427 | | internal static bool TryDive(TypeNameParseOptions options, ref int depth) |
| | 81908 | 428 | | { |
| | 81908 | 429 | | depth++; |
| | 81908 | 430 | | return !IsMaxDepthExceeded(options, depth); |
| | 81908 | 431 | | } |
| | | 432 | | |
| | | 433 | | #if SYSTEM_REFLECTION_METADATA |
| | | 434 | | [DoesNotReturn] |
| | | 435 | | internal static void ThrowInvalidOperation_NotSimpleName(string fullName) |
| | 0 | 436 | | { |
| | 0 | 437 | | throw new InvalidOperationException(SR.Format(SR.Arg_NotSimpleTypeName, fullName)); |
| | | 438 | | } |
| | | 439 | | #endif |
| | | 440 | | } |
| | | 441 | | } |
| | | 442 | | |