Skip to content

SharedArrayPool<char>.Rent sometimes erroneously returns the same array when called recursively #118292

Closed

Description

@fitdev

Description

I discovered this issue when tracing corrupted output of DefaultInterpolatedStringHandler, as I was using string interpolations extensively. I tracked it down to the fact that in the recursive call to DefaultInterpolatedStringHandler constructor (when the "parent" interpolation accepts as one of its arguments the "child" which also goes through string interpolation process), the "child" DefaultInterpolatedStringHandler is given the same char array that is already being used by the "parent" DefaultInterpolatedStringHandler. This of course leads to all sort of corruptions.

I tracked it down to:

This is where the "child"'s char array comes from, and it turns out to be the same instance as the "parent"'s one, currently being used by the "parent" DefaultInterpolatedStringHandler up the stack on the same thread.

Reproduction Steps

This is an illustration of the problem, however, in a standalone app, I could not reproduce this behavior. But the code is exactly the same as the one that manifests the issue in a real app:

using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;

namespace StringInterpolationRepro;

internal static class Program {

  static void Main(string[] args) {
    var PrependNameToPreheader = true;
    var Name = "John Doe";
    var Preheader = "Your order has been processed!";
    var spacer = HTML_SPACER(5);
    var constructed = $@"{spacer}
			{((PrependNameToPreheader ? Name.AppendIfNotEmpty(", ") : "").As(out var namePrefix) + namePrefix.IfEmpty(Preheader, Preheader.ToLowerFirst())).HTML_ROW("center", "middle", "classname", "font-weight:bold;")}
			{spacer}";

    Console.WriteLine(constructed);
    Console.ReadLine();
  }

  public static string HTML_SPACER(int px = 25, int colspan = 1) => px > 0 ? $@"<tr>{"&nbsp;".HTML_TD(colspan, null, px.ToString(), style: $@"font-size:{px}px;line-height:{px}px;")}</tr>" : "";

  public static string HTML_TD(this string content, int colspan = 0, string? width = null, string? height = null, string align = "left", string valign = "top", string cssClass = "text", string style = "") => $@"<td {(width.IsNotEmpty() ? $@" width=""{width}""" : "")} {(height.IsNotEmpty() ? $@" height=""{height}""" : "")} {(colspan > 1 ? $@" colspan=""{colspan}""" : "")} align=""{align}"" valign=""{valign}"" {(cssClass.IsNotEmpty() ? $@" class=""{cssClass}""" : "")} {style.IfNotEmpty($@" style=""{style}""")}>{content}</td>";

  public static string HTML_ROW(this string content, string align = "left", string valign = "top", string cssClass = "text", string style = "") => $@"<tr>{content.HTML_TD(0, null, null, align, valign, cssClass, style)}</tr>";

  extension([NotNullWhen(true)] string? s) {

    [DebuggerStepThrough, MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
    public bool IsNotEmpty() => !string.IsNullOrEmpty(s);

  }

  [DebuggerStepThrough, MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
  public static string IfEmpty(this string? it, string ifEmpty, string ifNotEmpty) => string.IsNullOrEmpty(it) ? ifEmpty : ifNotEmpty;

[DebuggerStepThrough, MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
  public static string IfNotEmpty(this string it, string replace) => string.IsNullOrEmpty(it) ? "" : replace;

  [return:NotNullIfNotNull(nameof(fallback))]
  public static string? AppendIfNotEmpty(this string? it, string suffix, string? fallback = "") => !string.IsNullOrEmpty(it) ? it + suffix : fallback;

  [DebuggerStepThrough, MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
  public static T As<T>(this T value, out T target) {
    target = value;
    return target;
  }

  [DebuggerStepThrough, MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
  public static string ToLowerFirst(this string? it) {
    if (string.IsNullOrEmpty(it)) return "";
    if (it.Length < 2) return it.ToLowerInvariant();
    return string.Concat([char.ToLowerInvariant(it[0])], it.AsSpan(1));
  }

}

The issue occurs when HTML_TD gets executed, which instantiates a "child" DefaultInterpolatedStringHandler which in turn is given the already being used char array. However in this simple sterile repro it does not happen for some reason (presumably because slightly different path is being followed within SharedArrayPool<>.Rent due to different initial conditions).

Expected behavior

A new char array should be return for the child/nested callers.

Actual behavior

The already used char array ends up being returned.

I verified that they are indeed the same arrays - not merely arrays with identical contents.

Regression?

Possibly, but not sure. Perhaps sometime in DotNet 8-9 timeframe.

Known Workarounds

Not using nested string interpolations (in my case), though it's hardly a realistic option!

Configuration

.NET SDK:
 Version:           10.0.100-preview.3.25201.16
 Commit:            9dee3cf508
 Workload version:  10.0.100-manifests.ef4f854f
 MSBuild version:   17.14.0-preview-25177-05+903614e16

Runtime Environment:
 OS Name:     Windows
 OS Version:  10.0.22621
 OS Platform: Windows
 RID:         win-x64

Actual runtime environment though is DotNet 9.0.7 (System.Buffers v. 9.0.7)

Other information

No response

Activity

  1. added
    untriaged
    on Aug 1, 2025
  2. stephentoub commented on Aug 1, 2025

    @stephentoub
    Member

    This is an illustration of the problem, however, in a standalone app, I could not reproduce this behavior.

    Thank you for trying. We would really need a repro though to pursue this.

  3. EgorBo commented on Aug 1, 2025

    @EgorBo
    Member

    Possibly, some other part of your app somewhere does ArrayPool.Return over the same array twice. In that case ArrayPool indeed can rent the same array instance more than once.

  4. EgorBo commented on Aug 1, 2025

    @EgorBo
    Member
    // Some distant part of your app:
    var x = ArrayPool<int>.Shared.Rent(1024);
    ArrayPool<int>.Shared.Return(x);
    ArrayPool<int>.Shared.Return(x); // buggy double-free
    
    // This code:
    
    var a1 = ArrayPool<int>.Shared.Rent(1024);
    var a2 = ArrayPool<int>.Shared.Rent(1024);
    Console.WriteLine(object.ReferenceEquals(a1, a2)); // prints 'true'
  5. added
    needs-author-action
    on Aug 1, 2025
  6. fitdev commented on Aug 1, 2025

    @fitdev
    Author

    @EgorBo

    Possibly, some other part of your app somewhere does ArrayPool.Return over the same array twice. In that case ArrayPool indeed can rent the same array instance more than once.

    Thank you for suggestion!

    But I did monitor ArrayPool's Rent and Return calls while debugging this and the only callers were the "parent" and "child" DefaultInterpolatedStringHandlers calling Rent.

    Are you saying that even non-concurrent double frees (those not happening between calls to Rent) can lead to this behavior?

    In any case I think this is a bit problematic design, leading one to a pit of failure so to speak. Because if there is a 3rd party dependency that uses a ArrayPool which does this double free, it will the screw app the whole app, unbeknownst to the app's author, and it would be impossible to figure out who the offender is so to speak unless it is in the source code under authors control. This may be my case, I don't know. I will inspect all the Return calls in my code, but there are 3rd party libs that I use which may cause this.

    Wouldn't it be better for ArrayPool being such a foundational piece to protect against double frees, by simply checking if the array has already been freed?

  7. removed
    needs-author-action
    on Aug 1, 2025
  8. fitdev commented on Aug 1, 2025

    @fitdev
    Author

    And if it is any relevance, this happens within a Threadpool Worker thread, whereas it does not happen when run within the main thread.

  9. MihaZupan commented on Aug 1, 2025

    @MihaZupan
    Member

    Perhaps having #109695 in the product could be useful for tracking down issues like these

  10. EgorBo commented on Aug 1, 2025

    @EgorBo
    Member

    Yes, it's an error-prone API and there is an ongoing discussion about possibly marking it as "requires 'unsafe' context" for developers to be aware of it. It's a low-level tool to "fix" GC-related performance issues (normally driven by a memory profiler), and it does require careful use. It's close to impossible to implement it in a 100% safe manner in current C# while keeping the performance benefits and flexibility it provides. Hopefully, something like #109695 can indeed at least help with it in Debug/Opt-in mode.

    if there is a 3rd party dependency that uses a ArrayPool which does this double free, it will the screw app the whole app

    ArrayPool is not the only thing where double-free (or use-after-free) can screw the whole app

  11. jkotas commented on Aug 2, 2025

    @jkotas
    Member

    ArrayPool is instrumented with very detailed tracing that you can use to diagnose double-free issues like this one.

    For example, use https://github.com/microsoft/perfview and collect a trace with *System.Buffers.ArrayPoolEventSource:*:*:@StacksEnabled=true additional provider and then look for ArrayPool events.

    Here is a program that I have tried it on:

    using System.Buffers;
    
    var a = ArrayPool<byte>.Shared.Rent(100);
    ArrayPool<byte>.Shared.Return(a);
    
    a = ArrayPool<byte>.Shared.Rent(100);
    ArrayPool<byte>.Shared.Return(a);
    ArrayPool<byte>.Shared.Return(a);
    

    Perfview events window with a filter set to ArrayPool events:
    Image

    Once you figure out the event that's causing the problem, you can find the stacktrace by zooming at it in stack view:

    Image
  12. fitdev commented on Aug 2, 2025

    @fitdev
    Author

    Thank you all for help and suggestions!

    It was indeed the case of double free ArrayPool<char>.Shared.Return, albeit a very subtle one and very difficult to notice.

    Sorry for all the trouble.

    Though I wish ArrayPool were resilient to such "double frees" (but I realize it would come at a perf penalty and thus defeat the purpose of the API).

  13. removed
    untriaged
    on Aug 2, 2025
  14. locked and limited conversation to collaborators on Sep 2, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions