Repository navigation
Avoid unnecessary allocations when splitting binary XML text - #136765
Conversation
Co-authored-by: Copilot App <[email protected]>
|
Azure Pipelines: Successfully started running 3 pipeline(s). 12 pipeline(s) were filtered out due to trigger conditions. There may be pipelines that require an authorized user to comment /azp run to run. |
| private void InsertNode(XmlBinaryNodeType nodeType, int length) | ||
| { | ||
| byte[] buffer = new byte[5]; | ||
| Span<byte> buffer = stackalloc byte[1 + sizeof(int)]; |
There was a problem hiding this comment.
nit: = [0, 0, 0, 0, 0] will avoid an unsafe{} here.
I know it doesn't look pretty, but we have no other good option to avoid unsafe (unless you disable SkipLocalsInit for System.Private.DataContractSerialization)
There was a problem hiding this comment.
Funny enough, = [0, 0, 0, 0, 0] emits a better codegen than stackalloc byte[1 + sizeof(int)]; 😐 (no gs cookie) https://godbolt.org/z/9KdPT66r9
There was a problem hiding this comment.
will avoid an unsafe{} here
What unsafe?
no gs cookie
We've been talking about that for years. That's either a hole the JIT should fix, or it should also avoid it for this const stackalloc case. I'm not aware of any fundamental reason those should differ.
We're not really advocating going through the libraries and replacing such stackalloc's with [0, ..., 0], are we?
There was a problem hiding this comment.
will avoid an unsafe{} here
What unsafe?
the compiler can't prove you overwrite/don't consume undefined values.
We've already started the migration, see #136664
That's either a hole the JIT should fix, or it should also avoid it for this const stackalloc case. I'm not aware of any fundamental reason those should differ.
My point was more about perf concern of that replacement if you had any.
We're not really advocating going through the libraries and replacing such stackalloc's with [0, ..., 0], are we?
I don't see anything wrong with small buffers like up to 4-5 elements, the readability isn't bad + no unsafe {} (or InlineArray5?). After the automatic migration (November) your code will be converted into:
scoped Span<byte> buffer;
// SAFETY: To be audited
unsafe
{
buffer= stackalloc byte [1 + sizeof(int)];
}so technically this change replaces safe code with unsafe (just not at the very moment).
There was a problem hiding this comment.
the compiler can't prove you overwrite/don't consume undefined values.
Your concern is the lack of zero init?
First, the compiler should actually be able to prove that in this case; this isn't a case of it not being able to if we wanted it to, this is a case of wanting rules that apply in other cases to consistently apply to a case like this as well.
Also, this is a const-sized stackalloc. From the compiler's perspective, it is equivalent to a fixed length initializer. If your recommendation for any such stackalloc is going to be zero-initializing it with syntax like [0, ..., 0] in order to avoid unsafe, you should instead just drop the SkipLocalsInit from the library.
Personally, I think we're in the wrong by saying this case must be unsafe. There is nothing inherently unsafe about random bytes here.
I don't see anything wrong with small buffers like up to 4-5 elements, the readability isn't bad + no unsafe {}
It's about developers needing to a remember a bazillion rules about one thing being subtly better than another, but only in certain cases, certain lengths, use this one here, use that one there... we're making this unnecessarily complicated, encouraging churn for reasons that shouldn't exist.
There was a problem hiding this comment.
reading stack garbage from structs' paddings as bytes is fully safe too (e.g. ROS MemoryMarshal.AsBytes should be made back caller-safe)
The purist perspective inspired by Rust was valuable in getting the memory safety project off the ground and establish the principles. As we are learning by applying our current design to large amounts of real-world code, we should shift our focus toward a more pragmatic question when creating case-laws for the gray areas: what actually helps developers and agents write correct, secure C# code? I think MemoryMarshal.AsBytes should stay as unsafe with that in mind. Yes, there will be inconsistencies and I think that's fine.
There was a problem hiding this comment.
Well the question is - is it worth introducing this inconsistency in the first place? or those who relies on SkipLocalsInit (it already requires AllowUnsafeBlocks) will just slap a comment // SAFETY: the buffer is fully initialized by the following code. or just avoid unitialized buffers & potentially avoid problems those might cause.
There was a problem hiding this comment.
We are always going to have inconsistency since we cannot afford to disallow global state that acts as unsafe escape hatch.
If we keep going with purist perspective exclusively, disallow all ways to get uninitialized scratch byte buffers from safe code and keep telling everyone to avoid unsafe code at the same time, I worry we are going to see emergence of per-library static byte buffer pools since you can make those using 100% safe code. It won't help with safety (the byte buffers from a pool have unpredictable state just like stack allocated byte buffers) and hurt performance of the system as a whole (trivial local pools do great on microbenchmarks).
There was a problem hiding this comment.
Do we want to enable just byte? or any primitive except for bool (and float/double)?
e.g. stackalloc char is only 3x less popular than stackalloc byte (same for int). Do we want to explain why bool is unsafe?
And we still haven't touched exposing stack data. utf8/utf16 (byte/char) could be problematic when initialized out of garbage as well? (cc @GrabYourPitchforks).
Also, a scratch buffer initialized with garbage might be problematic when the reciever expects zero-termination (but that involves unsafe anyway).
There was a problem hiding this comment.
I'm on vacation, so I'd appreciate it if someone could move this forward as a C# proposal or change if we agree on it.
The insertion check was using the five-byte source buffer's length instead of the backing buffer's capacity, so every split allocated a replacement. Check the backing buffer instead and put the continuation header on the stack.