Skip to content

Commit e797c71

Browse files
Reland "[libc] make integration test malloc work properly when threaded" (#152236)
Reverts #152096
1 parent 6ba6efe commit e797c71

File tree

2 files changed

+14
-8
lines changed

2 files changed

+14
-8
lines changed

libc/test/IntegrationTest/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,5 +13,6 @@ add_object_library(
1313
DEPENDS
1414
libc.hdr.stdint_proxy
1515
libc.src.__support.OSUtil.osutil
16+
libc.src.__support.CPP.atomic
1617
${arch_specific_deps}
1718
)

libc/test/IntegrationTest/test.cpp

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@
55
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
66
//
77
//===----------------------------------------------------------------------===//
8-
98
#include "hdr/stdint_proxy.h"
9+
#include "src/__support/CPP/atomic.h"
1010
#include "src/__support/common.h"
1111
#include "src/__support/macros/config.h"
1212
#include <stddef.h>
@@ -63,16 +63,21 @@ int atexit(void (*func)(void)) { return LIBC_NAMESPACE::atexit(func); }
6363
// which just hands out continuous blocks from a statically allocated chunk of
6464
// memory.
6565

66-
static constexpr uint64_t MEMORY_SIZE = 16384;
67-
static uint8_t memory[MEMORY_SIZE];
68-
static uint8_t *ptr = memory;
66+
static constexpr uint64_t ALIGNMENT = alignof(long double);
67+
static constexpr uint64_t MEMORY_SIZE = 65336;
68+
alignas(ALIGNMENT) static uint8_t memory[MEMORY_SIZE];
69+
static size_t ptr = 0;
6970

7071
extern "C" {
7172

72-
void *malloc(size_t s) {
73-
void *mem = ptr;
74-
ptr += s;
75-
return static_cast<uint64_t>(ptr - memory) >= MEMORY_SIZE ? nullptr : mem;
73+
void *malloc(size_t size) {
74+
LIBC_NAMESPACE::cpp::AtomicRef<size_t> ref(ptr);
75+
size = (size + ALIGNMENT - 1) & ~(ALIGNMENT - 1);
76+
size_t old_ptr =
77+
ref.fetch_add(size, LIBC_NAMESPACE::cpp::MemoryOrder::RELAXED);
78+
if (static_cast<size_t>(old_ptr + size) > MEMORY_SIZE)
79+
return nullptr;
80+
return &memory[old_ptr];
7681
}
7782

7883
void free(void *) {}

0 commit comments

Comments
 (0)