| | | 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.Collections; |
| | | 5 | | using System.Diagnostics; |
| | | 6 | | using System.IO.Pipelines; |
| | | 7 | | using System.Runtime.ExceptionServices; |
| | | 8 | | using System.Runtime.InteropServices; |
| | | 9 | | using System.Text.Json.Serialization; |
| | | 10 | | using System.Text.Json.Serialization.Metadata; |
| | | 11 | | using System.Threading; |
| | | 12 | | using System.Threading.Tasks; |
| | | 13 | | |
| | | 14 | | namespace System.Text.Json |
| | | 15 | | { |
| | | 16 | | [StructLayout(LayoutKind.Auto)] |
| | | 17 | | [DebuggerDisplay("{DebuggerDisplay,nq}")] |
| | | 18 | | internal struct WriteStack |
| | | 19 | | { |
| | 0 | 20 | | public readonly int CurrentDepth => _count; |
| | | 21 | | |
| | | 22 | | /// <summary> |
| | | 23 | | /// Exposes the stack frame that is currently active. |
| | | 24 | | /// </summary> |
| | | 25 | | public WriteStackFrame Current; |
| | | 26 | | |
| | | 27 | | /// <summary> |
| | | 28 | | /// Gets the parent stack frame, if it exists. |
| | | 29 | | /// </summary> |
| | | 30 | | public readonly ref WriteStackFrame Parent |
| | | 31 | | { |
| | | 32 | | get |
| | | 33 | | { |
| | | 34 | | Debug.Assert(_count - _indexOffset > 0); |
| | | 35 | | Debug.Assert(_stack is not null); |
| | | 36 | | return ref _stack[_count - _indexOffset - 1]; |
| | | 37 | | } |
| | | 38 | | } |
| | | 39 | | |
| | | 40 | | /// <summary> |
| | | 41 | | /// Buffer containing all frames in the stack. For performance it is only populated for serialization depths > 1 |
| | | 42 | | /// </summary> |
| | | 43 | | private WriteStackFrame[] _stack; |
| | | 44 | | |
| | | 45 | | /// <summary> |
| | | 46 | | /// Tracks the current depth of the stack. |
| | | 47 | | /// </summary> |
| | | 48 | | private int _count; |
| | | 49 | | |
| | | 50 | | /// <summary> |
| | | 51 | | /// If not zero, indicates that the stack is part of a re-entrant continuation of given depth. |
| | | 52 | | /// </summary> |
| | | 53 | | private int _continuationCount; |
| | | 54 | | |
| | | 55 | | /// <summary> |
| | | 56 | | /// Offset used to derive the index of the current frame in the stack buffer from the current value of <see cref |
| | | 57 | | /// following the formula currentIndex := _count - _indexOffset. |
| | | 58 | | /// Value can vary between 0 or 1 depending on whether we need to allocate a new frame on the first Push() opera |
| | | 59 | | /// which can happen if the root converter is polymorphic. |
| | | 60 | | /// </summary> |
| | | 61 | | private byte _indexOffset; |
| | | 62 | | |
| | | 63 | | /// <summary> |
| | | 64 | | /// Cancellation token used by converters performing async serialization (e.g. IAsyncEnumerable) |
| | | 65 | | /// </summary> |
| | | 66 | | public CancellationToken CancellationToken; |
| | | 67 | | |
| | | 68 | | /// <summary> |
| | | 69 | | /// In the case of async serialization, used by resumable converters to signal that |
| | | 70 | | /// the current buffer contents should not be flushed to the underlying stream. |
| | | 71 | | /// </summary> |
| | | 72 | | public bool SuppressFlush; |
| | | 73 | | |
| | | 74 | | /// <summary> |
| | | 75 | | /// Stores a pending task that a resumable converter depends on to continue work. |
| | | 76 | | /// It must be awaited by the root context before serialization is resumed. |
| | | 77 | | /// </summary> |
| | | 78 | | public Task? PendingTask; |
| | | 79 | | |
| | | 80 | | /// <summary> |
| | | 81 | | /// The amount of bytes to write before the underlying Stream should be flushed and the |
| | | 82 | | /// current buffer adjusted to remove the processed bytes. |
| | | 83 | | /// </summary> |
| | | 84 | | public int FlushThreshold; |
| | | 85 | | |
| | | 86 | | public PipeWriter? PipeWriter; |
| | | 87 | | |
| | | 88 | | /// <summary> |
| | | 89 | | /// Indicates that the state still contains suspended frames waiting re-entry. |
| | | 90 | | /// </summary> |
| | 0 | 91 | | public readonly bool IsContinuation => _continuationCount != 0; |
| | | 92 | | |
| | | 93 | | // The bag of preservable references. |
| | | 94 | | public ReferenceResolver ReferenceResolver; |
| | | 95 | | |
| | | 96 | | /// <summary> |
| | | 97 | | /// Internal flag to let us know that we need to read ahead in the inner read loop. |
| | | 98 | | /// </summary> |
| | | 99 | | public bool SupportContinuation; |
| | | 100 | | |
| | | 101 | | /// <summary> |
| | | 102 | | /// Internal flag indicating that async serialization is supported. Implies `SupportContinuation`. |
| | | 103 | | /// </summary> |
| | | 104 | | public bool SupportAsync; |
| | | 105 | | |
| | | 106 | | /// <summary> |
| | | 107 | | /// Stores a reference id that has been calculated for a newly serialized object. |
| | | 108 | | /// </summary> |
| | | 109 | | public string? NewReferenceId; |
| | | 110 | | |
| | | 111 | | /// <summary> |
| | | 112 | | /// Indicates that the next converter is polymorphic and must serialize a type discriminator. |
| | | 113 | | /// </summary> |
| | | 114 | | public object? PolymorphicTypeDiscriminator; |
| | | 115 | | |
| | | 116 | | /// <summary> |
| | | 117 | | /// The polymorphic type resolver used by the next converter. |
| | | 118 | | /// </summary> |
| | | 119 | | public PolymorphicTypeResolver? PolymorphicTypeResolver; |
| | | 120 | | |
| | | 121 | | /// <summary> |
| | | 122 | | /// Whether the current frame needs to write out any metadata. |
| | | 123 | | /// </summary> |
| | 0 | 124 | | public readonly bool CurrentContainsMetadata => NewReferenceId is not null || PolymorphicTypeDiscriminator is no |
| | | 125 | | |
| | | 126 | | private void EnsurePushCapacity() |
| | 0 | 127 | | { |
| | 0 | 128 | | if (_stack is null) |
| | 0 | 129 | | { |
| | 0 | 130 | | _stack = new WriteStackFrame[4]; |
| | 0 | 131 | | } |
| | 0 | 132 | | else if (_count - _indexOffset == _stack.Length) |
| | 0 | 133 | | { |
| | 0 | 134 | | Array.Resize(ref _stack, 2 * _stack.Length); |
| | 0 | 135 | | } |
| | 0 | 136 | | } |
| | | 137 | | |
| | | 138 | | internal void Initialize( |
| | | 139 | | JsonTypeInfo jsonTypeInfo, |
| | | 140 | | object? rootValueBoxed = null, |
| | | 141 | | bool supportContinuation = false, |
| | | 142 | | bool supportAsync = false) |
| | 0 | 143 | | { |
| | 0 | 144 | | Debug.Assert(!supportAsync || supportContinuation, "supportAsync must imply supportContinuation"); |
| | 0 | 145 | | Debug.Assert(!IsContinuation); |
| | 0 | 146 | | Debug.Assert(CurrentDepth == 0); |
| | | 147 | | |
| | 0 | 148 | | Current.JsonTypeInfo = jsonTypeInfo; |
| | 0 | 149 | | Current.JsonPropertyInfo = jsonTypeInfo.PropertyInfoForTypeInfo; |
| | 0 | 150 | | Current.NumberHandling = Current.JsonPropertyInfo.EffectiveNumberHandling; |
| | 0 | 151 | | SupportContinuation = supportContinuation; |
| | 0 | 152 | | SupportAsync = supportAsync; |
| | | 153 | | |
| | 0 | 154 | | JsonSerializerOptions options = jsonTypeInfo.Options; |
| | 0 | 155 | | if (options.ReferenceHandlingStrategy != JsonKnownReferenceHandler.Unspecified) |
| | 0 | 156 | | { |
| | 0 | 157 | | Debug.Assert(options.ReferenceHandler is not null); |
| | 0 | 158 | | ReferenceResolver = options.ReferenceHandler.CreateResolver(writing: true); |
| | | 159 | | |
| | 0 | 160 | | if (options.ReferenceHandlingStrategy == JsonKnownReferenceHandler.IgnoreCycles && |
| | 0 | 161 | | rootValueBoxed is not null && jsonTypeInfo.Type.IsValueType) |
| | 0 | 162 | | { |
| | | 163 | | // Root object is a boxed value type, we need to push it to the reference stack before starting the |
| | 0 | 164 | | ReferenceResolver.PushReferenceForCycleDetection(rootValueBoxed); |
| | 0 | 165 | | } |
| | 0 | 166 | | } |
| | 0 | 167 | | } |
| | | 168 | | |
| | | 169 | | /// <summary> |
| | | 170 | | /// Gets the nested JsonTypeInfo before resolving any polymorphic converters |
| | | 171 | | /// </summary> |
| | | 172 | | public readonly JsonTypeInfo PeekNestedJsonTypeInfo() |
| | 0 | 173 | | { |
| | 0 | 174 | | Debug.Assert(Current.PolymorphicSerializationState != PolymorphicSerializationState.PolymorphicReEntryStarte |
| | 0 | 175 | | return _count == 0 ? Current.JsonTypeInfo : Current.JsonPropertyInfo!.JsonTypeInfo; |
| | 0 | 176 | | } |
| | | 177 | | |
| | | 178 | | public void Push() |
| | 0 | 179 | | { |
| | 0 | 180 | | Debug.Assert(_continuationCount == 0 || _count < _continuationCount); |
| | | 181 | | |
| | 0 | 182 | | if (_continuationCount == 0) |
| | 0 | 183 | | { |
| | 0 | 184 | | Debug.Assert(Current.PolymorphicSerializationState != PolymorphicSerializationState.PolymorphicReEntrySu |
| | | 185 | | |
| | 0 | 186 | | if (_count == 0 && Current.PolymorphicSerializationState == PolymorphicSerializationState.None) |
| | 0 | 187 | | { |
| | | 188 | | // Perf enhancement: do not create a new stackframe on the first push operation |
| | | 189 | | // unless the converter has primed the current frame for polymorphic dispatch. |
| | 0 | 190 | | _count = 1; |
| | 0 | 191 | | _indexOffset = 1; // currentIndex := _count - 1; |
| | 0 | 192 | | } |
| | | 193 | | else |
| | 0 | 194 | | { |
| | 0 | 195 | | JsonTypeInfo jsonTypeInfo = Current.GetNestedJsonTypeInfo(); |
| | 0 | 196 | | JsonNumberHandling? numberHandling = Current.NumberHandling; |
| | | 197 | | |
| | 0 | 198 | | EnsurePushCapacity(); |
| | 0 | 199 | | _stack[_count - _indexOffset] = Current; |
| | 0 | 200 | | Current = default; |
| | 0 | 201 | | _count++; |
| | | 202 | | |
| | 0 | 203 | | Current.JsonTypeInfo = jsonTypeInfo; |
| | 0 | 204 | | Current.JsonPropertyInfo = jsonTypeInfo.PropertyInfoForTypeInfo; |
| | | 205 | | // Allow number handling on property to win over handling on type. |
| | 0 | 206 | | Current.NumberHandling = numberHandling ?? Current.JsonPropertyInfo.EffectiveNumberHandling; |
| | 0 | 207 | | } |
| | 0 | 208 | | } |
| | | 209 | | else |
| | 0 | 210 | | { |
| | | 211 | | // We are re-entering a continuation, adjust indices accordingly |
| | 0 | 212 | | if (_count++ > 0 || _indexOffset == 0) |
| | 0 | 213 | | { |
| | 0 | 214 | | Current = _stack[_count - _indexOffset]; |
| | 0 | 215 | | } |
| | | 216 | | |
| | | 217 | | // check if we are done |
| | 0 | 218 | | if (_continuationCount == _count) |
| | 0 | 219 | | { |
| | 0 | 220 | | _continuationCount = 0; |
| | 0 | 221 | | } |
| | 0 | 222 | | } |
| | | 223 | | |
| | | 224 | | #if DEBUG |
| | | 225 | | // Ensure the method is always exercised in debug builds. |
| | 0 | 226 | | _ = PropertyPath(); |
| | | 227 | | #endif |
| | 0 | 228 | | } |
| | | 229 | | |
| | | 230 | | public void Pop(bool success) |
| | 0 | 231 | | { |
| | 0 | 232 | | Debug.Assert(_count > 0); |
| | 0 | 233 | | Debug.Assert(_continuationCount == 0 || _count < _continuationCount); |
| | | 234 | | |
| | 0 | 235 | | if (!success) |
| | 0 | 236 | | { |
| | | 237 | | // Check if we need to initialize the continuation. |
| | 0 | 238 | | if (_continuationCount == 0) |
| | 0 | 239 | | { |
| | 0 | 240 | | if (_count == 1 && _indexOffset > 0) |
| | 0 | 241 | | { |
| | | 242 | | // No need to copy any frames here. |
| | 0 | 243 | | _continuationCount = 1; |
| | 0 | 244 | | _count = 0; |
| | 0 | 245 | | return; |
| | | 246 | | } |
| | | 247 | | |
| | | 248 | | // Need to push the Current frame to the stack, |
| | | 249 | | // ensure that we have sufficient capacity. |
| | 0 | 250 | | EnsurePushCapacity(); |
| | 0 | 251 | | _continuationCount = _count--; |
| | 0 | 252 | | } |
| | 0 | 253 | | else if (--_count == 0 && _indexOffset > 0) |
| | 0 | 254 | | { |
| | | 255 | | // reached the root, no need to copy frames. |
| | 0 | 256 | | return; |
| | | 257 | | } |
| | | 258 | | |
| | 0 | 259 | | int currentIndex = _count - _indexOffset; |
| | 0 | 260 | | _stack[currentIndex + 1] = Current; |
| | 0 | 261 | | Current = _stack[currentIndex]; |
| | 0 | 262 | | } |
| | | 263 | | else |
| | 0 | 264 | | { |
| | 0 | 265 | | Debug.Assert(_continuationCount == 0); |
| | | 266 | | |
| | 0 | 267 | | if (--_count > 0 || _indexOffset == 0) |
| | 0 | 268 | | { |
| | 0 | 269 | | Current = _stack[_count - _indexOffset]; |
| | 0 | 270 | | } |
| | 0 | 271 | | } |
| | 0 | 272 | | } |
| | | 273 | | |
| | | 274 | | /// <summary> |
| | | 275 | | /// Walks the stack cleaning up any leftover IDisposables |
| | | 276 | | /// in the event of an exception on serialization |
| | | 277 | | /// </summary> |
| | | 278 | | public readonly void DisposePendingDisposablesOnException() |
| | 0 | 279 | | { |
| | 0 | 280 | | Exception? exception = null; |
| | | 281 | | |
| | 0 | 282 | | Debug.Assert(Current.AsyncEnumerator is null); |
| | 0 | 283 | | DisposeFrame(Current.CollectionEnumerator, ref exception); |
| | | 284 | | |
| | 0 | 285 | | if (_stack is not null) |
| | 0 | 286 | | { |
| | 0 | 287 | | int currentIndex = _count - _indexOffset; |
| | 0 | 288 | | int stackSize = Math.Max(currentIndex, _continuationCount); |
| | 0 | 289 | | for (int i = 0; i < stackSize; i++) |
| | 0 | 290 | | { |
| | 0 | 291 | | Debug.Assert(_stack[i].AsyncEnumerator is null); |
| | | 292 | | |
| | 0 | 293 | | if (i == currentIndex) |
| | 0 | 294 | | { |
| | | 295 | | // Matches the entry in Current, skip to avoid double disposal. |
| | 0 | 296 | | Debug.Assert(_stack[i].CollectionEnumerator is null || ReferenceEquals(Current.CollectionEnumera |
| | 0 | 297 | | continue; |
| | | 298 | | } |
| | | 299 | | |
| | 0 | 300 | | DisposeFrame(_stack[i].CollectionEnumerator, ref exception); |
| | 0 | 301 | | } |
| | 0 | 302 | | } |
| | | 303 | | |
| | 0 | 304 | | if (exception is not null) |
| | 0 | 305 | | { |
| | 0 | 306 | | ExceptionDispatchInfo.Capture(exception).Throw(); |
| | | 307 | | } |
| | | 308 | | |
| | | 309 | | static void DisposeFrame(IEnumerator? collectionEnumerator, ref Exception? exception) |
| | 0 | 310 | | { |
| | | 311 | | try |
| | 0 | 312 | | { |
| | 0 | 313 | | if (collectionEnumerator is IDisposable disposable) |
| | 0 | 314 | | { |
| | 0 | 315 | | disposable.Dispose(); |
| | 0 | 316 | | } |
| | 0 | 317 | | } |
| | 0 | 318 | | catch (Exception e) |
| | 0 | 319 | | { |
| | 0 | 320 | | exception = e; |
| | 0 | 321 | | } |
| | 0 | 322 | | } |
| | 0 | 323 | | } |
| | | 324 | | |
| | | 325 | | /// <summary> |
| | | 326 | | /// Walks the stack cleaning up any leftover I(Async)Disposables |
| | | 327 | | /// in the event of an exception on async serialization |
| | | 328 | | /// </summary> |
| | | 329 | | public readonly async ValueTask DisposePendingDisposablesOnExceptionAsync() |
| | 0 | 330 | | { |
| | 0 | 331 | | Exception? exception = null; |
| | | 332 | | |
| | 0 | 333 | | exception = await DisposeFrame(Current.CollectionEnumerator, Current.AsyncEnumerator, exception).ConfigureAw |
| | | 334 | | |
| | 0 | 335 | | if (_stack is not null) |
| | 0 | 336 | | { |
| | 0 | 337 | | Debug.Assert(_continuationCount == 0 || _count < _continuationCount); |
| | 0 | 338 | | int currentIndex = _count - _indexOffset; |
| | 0 | 339 | | int stackSize = Math.Max(currentIndex, _continuationCount); |
| | 0 | 340 | | for (int i = 0; i < stackSize; i++) |
| | 0 | 341 | | { |
| | 0 | 342 | | if (i == currentIndex) |
| | 0 | 343 | | { |
| | | 344 | | // Matches the entry in Current, skip to avoid double disposal. |
| | 0 | 345 | | Debug.Assert(_stack[i].CollectionEnumerator is null || ReferenceEquals(Current.CollectionEnumera |
| | 0 | 346 | | Debug.Assert(_stack[i].AsyncEnumerator is null || ReferenceEquals(Current.AsyncEnumerator, _stac |
| | 0 | 347 | | continue; |
| | | 348 | | } |
| | | 349 | | |
| | 0 | 350 | | exception = await DisposeFrame(_stack[i].CollectionEnumerator, _stack[i].AsyncEnumerator, exception) |
| | 0 | 351 | | } |
| | 0 | 352 | | } |
| | | 353 | | |
| | 0 | 354 | | if (exception is not null) |
| | 0 | 355 | | { |
| | 0 | 356 | | ExceptionDispatchInfo.Capture(exception).Throw(); |
| | | 357 | | } |
| | | 358 | | |
| | | 359 | | static async ValueTask<Exception?> DisposeFrame(IEnumerator? collectionEnumerator, object? asyncEnumerator, |
| | 0 | 360 | | { |
| | 0 | 361 | | Debug.Assert(!(collectionEnumerator is not null && asyncEnumerator is not null)); |
| | | 362 | | |
| | | 363 | | try |
| | 0 | 364 | | { |
| | 0 | 365 | | if (collectionEnumerator is IDisposable disposable) |
| | 0 | 366 | | { |
| | 0 | 367 | | disposable.Dispose(); |
| | 0 | 368 | | } |
| | 0 | 369 | | else if (asyncEnumerator is IAsyncDisposable asyncDisposable) |
| | 0 | 370 | | { |
| | 0 | 371 | | await asyncDisposable.DisposeAsync().ConfigureAwait(false); |
| | 0 | 372 | | } |
| | 0 | 373 | | } |
| | 0 | 374 | | catch (Exception e) |
| | 0 | 375 | | { |
| | 0 | 376 | | exception = e; |
| | 0 | 377 | | } |
| | | 378 | | |
| | 0 | 379 | | return exception; |
| | 0 | 380 | | } |
| | 0 | 381 | | } |
| | | 382 | | |
| | | 383 | | // Return a property path as a simple JSONPath using dot-notation when possible. When special characters are pre |
| | | 384 | | // $.x.y.z |
| | | 385 | | // $['PropertyName.With.Special.Chars'] |
| | | 386 | | public string PropertyPath() |
| | 0 | 387 | | { |
| | 0 | 388 | | StringBuilder sb = new StringBuilder("$"); |
| | | 389 | | |
| | 0 | 390 | | (int frameCount, bool includeCurrentFrame) = _continuationCount switch |
| | 0 | 391 | | { |
| | 0 | 392 | | 0 => (_count - 1, true), // Not a continuation, report previous frames and Current. |
| | 0 | 393 | | 1 => (0, true), // Continuation of depth 1, just report Current frame. |
| | 0 | 394 | | int c => (c, false) // Continuation of depth > 1, report the entire stack. |
| | 0 | 395 | | }; |
| | | 396 | | |
| | 0 | 397 | | for (int i = 1; i <= frameCount; i++) |
| | 0 | 398 | | { |
| | 0 | 399 | | AppendStackFrame(sb, ref _stack[i - _indexOffset]); |
| | 0 | 400 | | } |
| | | 401 | | |
| | 0 | 402 | | if (includeCurrentFrame) |
| | 0 | 403 | | { |
| | 0 | 404 | | AppendStackFrame(sb, ref Current); |
| | 0 | 405 | | } |
| | | 406 | | |
| | 0 | 407 | | return sb.ToString(); |
| | | 408 | | |
| | | 409 | | static void AppendStackFrame(StringBuilder sb, ref WriteStackFrame frame) |
| | 0 | 410 | | { |
| | | 411 | | // Append the property name. Or attempt to get the JSON property name from the property name specified i |
| | 0 | 412 | | string? propertyName = |
| | 0 | 413 | | frame.JsonPropertyInfo?.MemberName ?? |
| | 0 | 414 | | frame.JsonPropertyNameAsString; |
| | | 415 | | |
| | 0 | 416 | | AppendPropertyName(sb, propertyName); |
| | 0 | 417 | | } |
| | | 418 | | |
| | | 419 | | static void AppendPropertyName(StringBuilder sb, string? propertyName) |
| | 0 | 420 | | { |
| | 0 | 421 | | if (propertyName is not null) |
| | 0 | 422 | | { |
| | 0 | 423 | | if (propertyName.AsSpan().ContainsSpecialCharacters()) |
| | 0 | 424 | | { |
| | 0 | 425 | | sb.Append(@"['"); |
| | 0 | 426 | | sb.AppendEscapedPropertyName(propertyName); |
| | 0 | 427 | | sb.Append(@"']"); |
| | 0 | 428 | | } |
| | | 429 | | else |
| | 0 | 430 | | { |
| | 0 | 431 | | sb.Append('.'); |
| | 0 | 432 | | sb.Append(propertyName); |
| | 0 | 433 | | } |
| | 0 | 434 | | } |
| | 0 | 435 | | } |
| | 0 | 436 | | } |
| | | 437 | | |
| | | 438 | | [DebuggerBrowsable(DebuggerBrowsableState.Never)] |
| | 0 | 439 | | private string DebuggerDisplay => $"Path = {PropertyPath()} Current = ConverterStrategy.{Current.JsonPropertyInf |
| | | 440 | | } |
| | | 441 | | } |
| | | 442 | | |