c# - stringbuilder转string - stringbuilder初始化



----在StringBuilder.ToString()的上下文中是什么意思? (3)

不要认为是这种情况 - 如果字符串构建器实例在另一个线程上发生变异,则有问题的代码会复制到局部变量以防止发生错误。

我认为----可能与四个字母发誓有关......

https://ffff65535.com

stringbuilder.csReference Source页面ToString方法中有这个注释:

if (chunk.m_ChunkLength > 0)
{
    // Copy these into local variables so that they 
    // are stable even in the presence of ----s (hackers might do this)
    char[] sourceArray = chunk.m_ChunkChars;
    int chunkOffset = chunk.m_ChunkOffset;
    int chunkLength = chunk.m_ChunkLength;

这是什么意思? 是----s恶意用户可能会插入到要格式化的字符串中?


在CoreCLR存储库中,您有一个更全面的报价:

将这些复制到局部变量中,即使在竞争条件下也能保持稳定

Github

基本上:这是一个线程考虑因素。


除了@Jeroen的优秀答案之外,这不仅仅是一个线程考虑因素。 这是为了防止有人故意创建竞争条件并以这种方式导致缓冲区溢出。 稍后在代码中,检查该局部变量的长度。 如果代码是检查可访问变量的长度,则可能在检查时间长度和wstrcpy之间的不同线程上进行了更改:

        // Check that we will not overrun our boundaries. 
        if ((uint)(chunkLength + chunkOffset) <= ret.Length && (uint)chunkLength <= (uint)sourceArray.Length)
        {
            ///
            /// imagine that another thread has changed the chunk.m_ChunkChars array here!
           /// we're now in big trouble, our attempt to prevent a buffer overflow has been thawrted! 
           /// oh wait, we're ok, because we're using a local variable that the other thread can't access anyway.
            fixed (char* sourcePtr = sourceArray)
                string.wstrcpy(destinationPtr + chunkOffset, sourcePtr, chunkLength);
        }
        else
        {
            throw new ArgumentOutOfRangeException("chunkLength", Environment.GetResourceString("ArgumentOutOfRange_Index"));
        }
    }
    chunk = chunk.m_ChunkPrevious;
} while (chunk != null);

真的很有趣的问题。





reference-source