Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -1923,6 +1923,7 @@
/none/tests/linux/clonev
/none/tests/linux/Makefile
/none/tests/linux/Makefile.in
/none/tests/linux/main_stack_attr
/none/tests/linux/membarrier
/none/tests/linux/mremap
/none/tests/linux/mremap2
Expand Down
14 changes: 14 additions & 0 deletions CODSPEED-CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,20 @@ This file documents changes made to Valgrind for CodSpeed integration, beyond th

## Fixes

### Linux: glibc reports the main thread stack size correctly again

`pthread_getattr_np` reports the main thread's stack size as `RLIMIT_STACK`
minus the space between the initial SP and the top of the stack mapping.
Valgrind placed the initial SP at the bottom of a fixed 8 MiB startup region
that holds the argument and environment strings and the argc/argv/envp/auxv
tables. With the default 8 MiB limit, glibc therefore reported a stack of
only 4 KiB, and CPython 3.14 failed at startup with `BufferError`.

The strings now live in a separate mapping. Only the tables stay above SP,
in a 64 KiB region, so glibc reports `RLIMIT_STACK - 64 KiB` (natively about
`RLIMIT_STACK - 100 KiB`). The initial SP stays at the same address for any
argument and environment size.

### Cache simulation: suppress the host L3 warning for explicit LL settings

Callgrind and Cachegrind no longer print the warning about using the host's
Expand Down
118 changes: 77 additions & 41 deletions coregrind/m_initimg/initimg-linux.c
Original file line number Diff line number Diff line change
Expand Up @@ -316,20 +316,26 @@ static HChar *copy_str(HChar **tab, const HChar *str)
This sets up the client's initial stack, containing the args,
environment and aux vector.

The startup image occupies a fixed-size region directly below
clstack_end, so the initial SP does not depend on the number or size
of arguments, environment variables or auxiliary strings. Tables
grow upward from that fixed SP; strings are placed downward from
clstack_end. The runtime stack starts in the page below SP and grows
into the reservation further down.
The startup image is a fixed-size region below clstack_end, so the
initial SP does not depend on the argument and environment sizes.
Strings get their own mapping, separated from the stack mapping by an
unmapped page: glibc's pthread_getattr_np() subtracts everything
between SP and the end of SP's mapping from RLIMIT_STACK, so only the
small table region sits there.

The format of the startup image is:

higher address +-----------------+ <- clstack_end
| |
: string table :
: (unused) :
| |
+-----------------+
| string table | (grows upward)
+-----------------+ <- strings_start (fixed)
| unmapped page |
+-----------------+ <- tables_end (fixed)
| (unused) |
+-----------------+
| AT_NULL |
- -
| auxv |
Expand All @@ -347,10 +353,9 @@ static HChar *copy_str(HChar **tab, const HChar *str)
lower address | runtime stack |
: :

The startup image has a fixed capacity so that later mappings and the
runtime stack remain at stable addresses. Linux limits the aggregate
argument/environment size to well below this capacity; inputs that do
not fit are rejected instead of silently moving SP.
Tables larger than TABLES_REGION_SZB take whole granules from the
string mapping; SP stays put. Inputs exceeding STARTUP_REGION_SZB are
rejected.

Allocate and create the initial client stack. It is allocated down
from clstack_end, which was previously determined by the address
Expand All @@ -365,10 +370,15 @@ static HChar *copy_str(HChar **tab, const HChar *str)

---------------------------------------------------------------- */

/* Since Linux 4.13, execve() limits argv/envp strings plus their pointer
arrays to 6 MiB (3/4 of _STK_LIM). */
/* Fixed distance from the initial SP to clstack_end. Since Linux 4.13,
execve() limits argv/envp strings plus their pointer arrays to 6 MiB
(3/4 of _STK_LIM). */
#define STARTUP_REGION_SZB (8 * 1024 * 1024)

/* Table mapping above SP (argc, argv, envp, auxv). glibc subtracts it
from the reported main stack size, so keep it small. */
#define TABLES_REGION_SZB (64 * 1024)

struct auxv
{
Word a_type;
Expand Down Expand Up @@ -427,9 +437,11 @@ Addr setup_client_stack( void* init_sp,
unsigned auxsize; /* total size of auxv in bytes */
Int argc; /* total argc */
Int envc; /* total number of env vars */
unsigned stacksize; /* total client stack size */
unsigned tablesize; /* argc, argv, envp and auxv in bytes */
Addr client_SP; /* client stack base (initial SP) */
Addr clstack_start;
Addr tables_end; /* one past the table mapping */
Addr strings_start; /* start of the string mapping */
Int i;

vg_assert(VG_IS_PAGE_ALIGNED(clstack_end+1));
Expand Down Expand Up @@ -491,38 +503,46 @@ Addr setup_client_stack( void* init_sp,
# endif

/* OK, now we know how big the client stack is */
stacksize =
tablesize =
sizeof(Word) + /* argc */
sizeof(HChar **) + /* argc[0] == exename */
sizeof(HChar **)*argc + /* argv */
sizeof(HChar **) + /* terminal NULL */
sizeof(HChar **)*envc + /* envp */
sizeof(HChar **) + /* terminal NULL */
auxsize + /* auxv */
VG_ROUNDUP(stringsize, sizeof(Word)); /* strings (aligned) */

if (0) VG_(printf)("stacksize = %u\n", stacksize);
auxsize; /* auxv */

/* client_SP is fixed so that unused startup data cannot change the
addresses used by the client. The tables grow upward from it and
the strings are placed downward from clstack_end. */
client_SP = clstack_end + 1 - STARTUP_REGION_SZB;
vg_assert(VG_IS_PAGE_ALIGNED(client_SP));
if (0) VG_(printf)("tablesize = %u stringsize = %u\n",
tablesize, stringsize);

if (stacksize > STARTUP_REGION_SZB) {
VG_(printf)("valgrind: "
"The client arguments and environment need %u bytes, "
"exceeding the fixed %u-byte startup region.\n",
stacksize, (unsigned)STARTUP_REGION_SZB);
VG_(printf)("valgrind: "
"Please report this at "
"https://github.com/CodSpeedHQ/valgrind-codspeed/issues.\n\n");
VG_(exit)(1);
/* Tables grow upward from the fixed SP, strings upward from
strings_start. Oversized tables take granules from the string
mapping, so SP never moves. */
{ SizeT tables_szB = VG_ROUNDUP(tablesize, TABLES_REGION_SZB);
if (tables_szB + VKI_PAGE_SIZE + stringsize > STARTUP_REGION_SZB) {
VG_(printf)("valgrind: "
"The client arguments and environment need %u + %u "
"bytes, exceeding the fixed %u-byte startup region.\n",
tablesize, stringsize, (unsigned)STARTUP_REGION_SZB);
VG_(printf)("valgrind: "
"Please report this at "
"https://github.com/CodSpeedHQ/valgrind-codspeed/issues.\n\n");
VG_(exit)(1);
}
if (tables_szB > TABLES_REGION_SZB)
VG_(debugLog)(1, "initimg",
"Startup tables need %u bytes, more than one "
"%u-byte granule; the string mapping shrinks\n",
tablesize, (unsigned)TABLES_REGION_SZB);
client_SP = clstack_end + 1 - STARTUP_REGION_SZB;
tables_end = client_SP + tables_szB;
}
strings_start = tables_end + VKI_PAGE_SIZE;
vg_assert(VG_IS_PAGE_ALIGNED(client_SP));
vg_assert(VG_IS_PAGE_ALIGNED(strings_start));

/* base of the string table (aligned) */
stringbase = strtab = (HChar *)(clstack_end + 1)
- VG_ROUNDUP(stringsize, sizeof(Word));
stringbase = strtab = (HChar *)strings_start;

/* Keep the page below the fixed SP mapped so that the first stack
writes do not fault before stack growth is set up. */
Expand All @@ -532,16 +552,18 @@ Addr setup_client_stack( void* init_sp,
clstack_max_size = VG_PGROUNDUP(clstack_max_size);

if (0)
VG_(printf)("stringsize=%u auxsize=%u stacksize=%u maxsize=0x%lx\n"
VG_(printf)("stringsize=%u auxsize=%u tablesize=%u maxsize=0x%lx\n"
"clstack_start %p\n"
"clstack_end %p\n",
stringsize, auxsize, stacksize, clstack_max_size,
stringsize, auxsize, tablesize, clstack_max_size,
(void*)clstack_start, (void*)clstack_end);

/* ==================== allocate space ==================== */

{ SizeT anon_size = clstack_end - clstack_start + 1;
SizeT resvn_size = clstack_max_size - anon_size;
{ SizeT anon_size = tables_end - clstack_start;
SizeT strings_size = clstack_end + 1 - strings_start;
SizeT resvn_size = clstack_max_size - STARTUP_REGION_SZB
- VKI_PAGE_SIZE;
Addr anon_start = clstack_start;
Addr resvn_start = anon_start - resvn_size;
SizeT inner_HACK = 0;
Expand Down Expand Up @@ -580,7 +602,9 @@ Addr setup_client_stack( void* init_sp,
resvn_start, resvn_size, anon_start, anon_size);

/* Create a shrinkable reservation followed by an anonymous
segment. Together these constitute a growdown stack. */
segment. Together these constitute a growdown stack. The page
above is reserved so no client mapping lands there; the strings
get their own anonymous segment. */
res = VG_(mk_SysRes_Error)(0);
ok = VG_(am_create_reservation)(
resvn_start,
Expand All @@ -596,6 +620,12 @@ Addr setup_client_stack( void* init_sp,
info->stack_prot
);
}
if (ok && !sr_isError(res))
ok = VG_(am_create_reservation)(tables_end, VKI_PAGE_SIZE,
SmFixed, 0);
if (ok && !sr_isError(res))
res = VG_(am_mmap_anon_fixed_client)(strings_start, strings_size,
info->stack_prot);
if ((!ok) || sr_isError(res)) {
/* Allocation of the stack failed. We have to stop. */
VG_(printf)("valgrind: "
Expand Down Expand Up @@ -1011,7 +1041,7 @@ Addr setup_client_stack( void* init_sp,

/* client_SP is pointing at client's argc/argv */

vg_assert((Addr)(auxv + 1) <= (Addr)stringbase);
vg_assert((Addr)(auxv + 1) <= tables_end);
vg_assert((Addr)strtab <= clstack_end + 1);

if (0) VG_(printf)("startup SP = %#lx\n", client_SP);
Expand Down Expand Up @@ -1192,6 +1222,12 @@ IIFinaliseImageInfo VG_(ii_create_image)( IICreateImageInfo iicii,
iicii.clstack_end, iifii.clstack_max_size,
vex_archinfo );

/* The main thread's stack ends at the stack segment, below the
separate string mapping; size it from the reservation bottom
to there. */
vg_assert(VG_(clstk_end) <= iicii.clstack_end);
iifii.clstack_max_size -= iicii.clstack_end - VG_(clstk_end);

VG_(free)(env);

VG_(debugLog)(2, "initimg",
Expand Down
4 changes: 4 additions & 0 deletions none/tests/linux/Makefile.am
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ EXTRA_DIST = \
bug506910.stderr.exp bug506910.vgtest \
clonev.stdout.exp clonev.stderr.exp clonev.vgtest \
getdents_filter.stderr.exp getdents_filter.stdout.exp getdents_filter.vgtest \
main_stack_attr.stderr.exp main_stack_attr.stdout.exp \
main_stack_attr.vgtest \
membarrier.stderr.exp membarrier.vgtest \
mremap.stderr.exp mremap.stderr.exp-glibc27 mremap.stdout.exp \
mremap.vgtest \
Expand All @@ -31,6 +33,7 @@ check_PROGRAMS = \
bug498317 \
clonev \
getdents_filter \
main_stack_attr \
mremap \
mremap2 \
mremap3 \
Expand Down Expand Up @@ -59,6 +62,7 @@ bug506910_SOURCES = bug506910.cpp
open_client_SOURCES = open_client.cpp
endif
clonev_LDADD = -lpthread
main_stack_attr_LDADD = -lpthread
pthread_stack_LDADD = -lpthread

stack_overflow_CFLAGS = $(AM_CFLAGS) @FLAG_W_NO_UNINITIALIZED@ \
Expand Down
92 changes: 92 additions & 0 deletions none/tests/linux/main_stack_attr.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/* glibc's pthread_getattr_np reports the main thread stack as
RLIMIT_STACK minus the startup data above __libc_stack_end. Runtimes
such as CPython size their stack guard from it, so the range must
cover SP and be close to the limit, as natively.

"main_stack_attr N" checks itself, then re-executes with N extra
arguments to grow the startup pointer tables. */

#define _GNU_SOURCE
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/resource.h>
#include <unistd.h>

enum {
MIB = 1024 * 1024,
STACK_LIMIT = 8 * MIB,
/* The startup image above the initial SP is a few KiB natively. */
MAX_STARTUP_OVERHEAD = 1 * MIB,
};

/* Argument of the re-executed child; a numeric argument marks the
parent, so the child does not re-execute. */
static char CHILD_ARG[] = "x";

static int reexec_with_args(const char *self, long count)
{
char **argv = calloc(count + 2, sizeof(*argv));
long i;

if (argv == NULL)
return 1;
argv[0] = (char *)self;
for (i = 0; i < count; i++)
argv[i + 1] = CHILD_ARG;
execv(self, argv);
perror("execv");
return 1;
}

int main(int argc, char **argv)
{
struct rlimit rl;
pthread_attr_t attr;
void *stack_addr;
size_t stack_size;
rlim_t limit = STACK_LIMIT;
uintptr_t sp = (uintptr_t)&rl;

if (getrlimit(RLIMIT_STACK, &rl) != 0) {
perror("getrlimit");
return 1;
}
if (rl.rlim_max != RLIM_INFINITY && rl.rlim_max < limit)
limit = rl.rlim_max;
rl.rlim_cur = limit;
if (setrlimit(RLIMIT_STACK, &rl) != 0) {
perror("setrlimit");
return 1;
}

if (pthread_getattr_np(pthread_self(), &attr) != 0
|| pthread_attr_getstack(&attr, &stack_addr, &stack_size) != 0) {
fprintf(stderr, "pthread_getattr_np failed\n");
return 1;
}
pthread_attr_destroy(&attr);

if (sp < (uintptr_t)stack_addr
|| sp >= (uintptr_t)stack_addr + stack_size) {
printf("SP %#lx outside reported stack [%#lx, %#lx)\n",
(unsigned long)sp, (unsigned long)stack_addr,
(unsigned long)((uintptr_t)stack_addr + stack_size));
return 1;
}
if (stack_size + MAX_STARTUP_OVERHEAD < limit) {
printf("reported stack size %zu KiB, limit %lu KiB\n",
stack_size / 1024, (unsigned long)(limit / 1024));
return 1;
}

printf("Main thread stack attributes cover SP and match RLIMIT_STACK.\n");

if (argc == 2 && strcmp(argv[1], CHILD_ARG) != 0) {
fflush(stdout);
return reexec_with_args(argv[0], strtol(argv[1], NULL, 10));
}
return 0;
}
Empty file.
2 changes: 2 additions & 0 deletions none/tests/linux/main_stack_attr.stdout.exp
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Main thread stack attributes cover SP and match RLIMIT_STACK.
Main thread stack attributes cover SP and match RLIMIT_STACK.
3 changes: 3 additions & 0 deletions none/tests/linux/main_stack_attr.vgtest
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
prog: main_stack_attr
vgopts: -q --trace-children=yes
args: 20000
Loading