authorgravatar for alex@alexrp.comAlex Rønne Petersen <alex@alexrp.com> 2026-03-25 18:27:03+01:00
committergravatar for alex@alexrp.comAlex Rønne Petersen <alex@alexrp.com> 2026-03-25 18:27:03+01:00
log8a517285cebb007f14d499c611f3a052f45f0683
treeb335e6d238fa34dbfd2d9c67b77c3902ebdb5198
parent94355f1920d880837823812481140270d0dc631e
parent5363a81a57b669e43fc790b3318e1a02f967eb15

Merge pull request 'std.heap.ArenaAllocator/std.heap.FixedBufferAllocator: fix `end_index` memory ordering' (#31647) from justusk/zig:arena-mem-ord into master

Reviewed-on: https://codeberg.org/ziglang/zig/pulls/31647 Reviewed-by: jacobly <jacobly@noreply.codeberg.org>

2 files changed, 99 insertions(+), 72 deletions(-)

lib/std/heap/ArenaAllocator.zig+61-51
......@@ -207,17 +207,20 @@ pub fn reset(arena: *ArenaAllocator, mode: ResetMode) bool {
207207
208208/// Concurrent accesses to node pointers generally have to have acquire/release
209209/// semantics to guarantee that newly allocated notes are in a valid state when
210/// being inserted into a list. Exceptions are possible, e.g. a CAS loop that
210/// being inserted into a list. Exceptions are possible, e.g. a cmpxchg loop that
211211/// never accesses the node returned on failure can use monotonic semantics on
212212/// failure, but must still use release semantics on success to protect the node
213213/// it's trying to push.
214214const Node = struct {
215215 /// Only meant to be accessed indirectly via the methods supplied by this type,
216216 /// except if the node is owned by the thread accessing it.
217 /// Must always be an even number to accomodate `resize` bit.
217 /// Must always be an even number to accommodate `resize` bit.
218218 size: Size,
219 /// Concurrent accesses to `end_index` can be monotonic as long as its value
220 /// is compared to a version of `size` before using it to access memory.
219 /// Any increase of `end_index` has to use acquire semantics;
220 /// any decrease of `end_index` that invalidates (formerly) active allocations
221 /// has to use release semantics.
222 /// This guarantees that all accesses to memory that's about to be freed
223 /// happen-before the free is published.
221224 /// Since `size` can only grow and never shrink, memory access depending on
222225 /// any `end_index` <= any `size` can never be OOB.
223226 end_index: usize,
......@@ -319,11 +322,6 @@ fn pushFreeList(arena: *ArenaAllocator, first: *Node, last: *Node) void {
319322 }
320323}
321324
322fn sliceContainsSlice(container: []u8, slice: []u8) bool {
323 return @intFromPtr(slice.ptr) >= @intFromPtr(container.ptr) and
324 @intFromPtr(slice.ptr + slice.len) <= @intFromPtr(container.ptr + container.len);
325}
326
327325fn alignedIndex(buf_ptr: [*]u8, end_index: usize, alignment: Alignment) usize {
328326 // Wrapping arithmetic to avoid overflows since `end_index` isn't bounded by
329327 // `size`. This is always ok since the max alignment in byte units is also
......@@ -357,10 +355,17 @@ fn alloc(ctx: *anyopaque, n: usize, alignment: Alignment, ret_addr: usize) ?[*]u
357355 // with a single cmpxchg afterwards, which may fail.
358356
359357 const alignable = n + alignment.toByteUnits() - 1;
360 const end_index = @atomicRmw(usize, &node.end_index, .Add, alignable, .monotonic);
358 const end_index = @atomicRmw(usize, &node.end_index, .Add, alignable, .acquire); // acquire any memory that may have been freed
361359 const aligned_index = alignedIndex(buf.ptr, end_index, alignment);
362360 assert(end_index + alignable >= aligned_index + n);
363 _ = @cmpxchgStrong(usize, &node.end_index, end_index + alignable, aligned_index + n, .monotonic, .monotonic);
361 _ = @cmpxchgStrong(
362 usize,
363 &node.end_index,
364 end_index + alignable,
365 aligned_index + n,
366 .monotonic, // no need to release alignment padding; there's no one accessing it!
367 .monotonic,
368 );
364369
365370 if (aligned_index + n > buf.len) break :first_node .{ node, buf.len };
366371 return buf[aligned_index..][0..n].ptr;
......@@ -382,7 +387,7 @@ fn alloc(ctx: *anyopaque, n: usize, alignment: Alignment, ret_addr: usize) ?[*]u
382387 const new_size = mem.alignForward(usize, @sizeOf(Node) + aligned_index + n, 2);
383388
384389 if (new_size <= allocated_slice.len) {
385 // a `resize` or `free` call managed to sneak in and we need to
390 // A `resize` or `free` call managed to sneak in and we need to
386391 // guarantee that `size` is only ever increased; retry!
387392 continue :retry;
388393 }
......@@ -390,14 +395,16 @@ fn alloc(ctx: *anyopaque, n: usize, alignment: Alignment, ret_addr: usize) ?[*]u
390395 if (arena.child_allocator.rawResize(allocated_slice, .of(Node), new_size, @returnAddress())) {
391396 size = new_size;
392397
393 if (@cmpxchgStrong( // strong because a spurious failure could result in suboptimal usage of this node
398 // strong because a spurious failure could result in suboptimal
399 // usage of this node
400 if (null == @cmpxchgStrong(
394401 usize,
395402 &node.end_index,
396403 end_index,
397404 aligned_index + n,
405 .acquire, // acquire any memory that may have been freed
398406 .monotonic,
399 .monotonic,
400 ) == null) {
407 )) {
401408 const new_buf = allocated_slice.ptr[0..new_size][@sizeOf(Node)..];
402409 return new_buf[aligned_index..][0..n].ptr;
403410 }
......@@ -548,40 +555,48 @@ fn resize(ctx: *anyopaque, memory: []u8, alignment: Alignment, new_len: usize, r
548555 assert(new_len > 0);
549556
550557 const node = arena.loadFirstNode().?;
551 const buf = node.loadBuf();
552
553 if (!sliceContainsSlice(buf, memory)) {
554 // Not within current node.
555 return new_len <= memory.len;
556 }
558 const buf_ptr = @as([*]u8, @ptrCast(node)) + @sizeOf(Node);
557559
558560 const cur_end_index = @atomicLoad(usize, &node.end_index, .monotonic);
559561
560 if (buf.ptr + cur_end_index != memory.ptr + memory.len) {
561 // It's not the most recent allocation, so it cannot be expanded.
562 if (buf_ptr + cur_end_index != memory.ptr + memory.len) {
563 // It's not the most recent allocation, so it cannot be expanded,
564 // but it's fine if they want to make it smaller.
562565 return new_len <= memory.len;
563566 }
564567
565 const new_end_index: usize = new_end_index: {
566 if (memory.len >= new_len) {
567 break :new_end_index cur_end_index - (memory.len - new_len);
568 }
569 if (buf.len - cur_end_index >= new_len - memory.len) {
570 break :new_end_index cur_end_index + (new_len - memory.len);
571 }
572 return false;
573 };
574 assert(buf.ptr + new_end_index == memory.ptr + new_len);
568 if (new_len <= memory.len) {
569 const new_end_index = cur_end_index - (memory.len - new_len);
570 assert(buf_ptr + new_end_index == memory.ptr + new_len);
571
572 _ = @cmpxchgStrong(
573 usize,
574 &node.end_index,
575 cur_end_index,
576 new_end_index,
577 .release, // release freed memory
578 .monotonic,
579 );
580 return true; // Shrinking allocations should always succeed.
581 }
575582
576 return null == @cmpxchgStrong(
577 usize,
578 &node.end_index,
579 cur_end_index,
580 new_end_index,
581 .monotonic,
582 .monotonic,
583 ) or
584 new_len <= memory.len; // Shrinking allocations should always succeed.
583 // Saturating arithmetic because `end_index` is not guaranteed to be `<= size`.
584 // The allocation we're trying to resize *could* belong to a different node!
585 if (node.loadBuf().len -| cur_end_index >= new_len - memory.len) {
586 const new_end_index = cur_end_index + (new_len - memory.len);
587 assert(buf_ptr + new_end_index == memory.ptr + new_len);
588
589 return null == @cmpxchgStrong(
590 usize,
591 &node.end_index,
592 cur_end_index,
593 new_end_index,
594 .acquire, // acquire any memory that may have been freed
595 .monotonic,
596 );
597 }
598
599 return false;
585600}
586601
587602fn remap(ctx: *anyopaque, memory: []u8, alignment: Alignment, new_len: usize, ret_addr: usize) ?[*]u8 {
......@@ -596,29 +611,24 @@ fn free(ctx: *anyopaque, memory: []u8, alignment: Alignment, ret_addr: usize) vo
596611 assert(memory.len > 0);
597612
598613 const node = arena.loadFirstNode().?;
599 const buf = node.loadBuf();
600
601 if (!sliceContainsSlice(buf, memory)) {
602 // Not within current node; we cannot free it.
603 return;
604 }
614 const buf_ptr = @as([*]u8, @ptrCast(node)) + @sizeOf(Node);
605615
606616 const cur_end_index = @atomicLoad(usize, &node.end_index, .monotonic);
607617
608 if (buf.ptr + cur_end_index != memory.ptr + memory.len) {
618 if (buf_ptr + cur_end_index != memory.ptr + memory.len) {
609619 // Not the most recent allocation; we cannot free it.
610620 return;
611621 }
612622
613623 const new_end_index = cur_end_index - memory.len;
614 assert(buf.ptr + new_end_index == memory.ptr);
624 assert(buf_ptr + new_end_index == memory.ptr);
615625
616626 _ = @cmpxchgStrong(
617627 usize,
618628 &node.end_index,
619629 cur_end_index,
620630 new_end_index,
621 .monotonic,
631 .release, // release freed memory
622632 .monotonic,
623633 );
624634}
lib/std/heap/FixedBufferAllocator.zig+38-21
......@@ -137,7 +137,14 @@ fn threadSafeAlloc(ctx: *anyopaque, n: usize, alignment: mem.Alignment, ret_addr
137137 const adjusted_index = cur_end_index + adjust_off;
138138 const new_end_index = adjusted_index + n;
139139 if (new_end_index > self.buffer.len) return null;
140 cur_end_index = @cmpxchgWeak(usize, &self.end_index, cur_end_index, new_end_index, .monotonic, .monotonic) orelse
140 cur_end_index = @cmpxchgWeak(
141 usize,
142 &self.end_index,
143 cur_end_index,
144 new_end_index,
145 .acquire, // acquire any memory that may have been freed
146 .monotonic,
147 ) orelse
141148 return self.buffer[adjusted_index..new_end_index].ptr;
142149 }
143150}
......@@ -154,26 +161,36 @@ fn threadSafeResize(ctx: *anyopaque, memory: []u8, alignment: mem.Alignment, new
154161 return new_len <= memory.len;
155162 }
156163
157 const new_end_index: usize = new_end_index: {
158 if (memory.len >= new_len) {
159 break :new_end_index cur_end_index - (memory.len - new_len);
160 }
161 if (fba.buffer.len - cur_end_index >= new_len - memory.len) {
162 break :new_end_index cur_end_index + (new_len - memory.len);
163 }
164 return false;
165 };
166 assert(fba.buffer.ptr + new_end_index == memory.ptr + new_len);
164 if (new_len <= memory.len) {
165 const new_end_index = cur_end_index - (memory.len - new_len);
166 assert(fba.buffer.ptr + new_end_index == memory.ptr + new_len);
167
168 _ = @cmpxchgStrong(
169 usize,
170 &fba.end_index,
171 cur_end_index,
172 new_end_index,
173 .release, // release freed memory
174 .monotonic,
175 );
176 return true; // Shrinking allocations should always succeed.
177 }
167178
168 return null == @cmpxchgStrong(
169 usize,
170 &fba.end_index,
171 cur_end_index,
172 new_end_index,
173 .monotonic,
174 .monotonic,
175 ) or
176 new_len <= memory.len; // Shrinking allocations should always succeed.
179 if (fba.buffer.len - cur_end_index >= new_len - memory.len) {
180 const new_end_index = cur_end_index + (new_len - memory.len);
181 assert(fba.buffer.ptr + new_end_index == memory.ptr + new_len);
182
183 return null == @cmpxchgStrong(
184 usize,
185 &fba.end_index,
186 cur_end_index,
187 new_end_index,
188 .acquire, // acquire any memory that may have been freed
189 .monotonic,
190 );
191 }
192
193 return false;
177194}
178195
179196fn threadSafeRemap(ctx: *anyopaque, memory: []u8, alignment: mem.Alignment, new_len: usize, ret_addr: usize) ?[*]u8 {
......@@ -201,7 +218,7 @@ fn threadSafeFree(ctx: *anyopaque, memory: []u8, alignment: mem.Alignment, ret_a
201218 &fba.end_index,
202219 cur_end_index,
203220 new_end_index,
204 .monotonic,
221 .release, // release freed memory
205222 .monotonic,
206223 );
207224}