lh | 9ed821d | 2023-04-07 01:36:19 -0700 | [diff] [blame] | 1 | #include <errno.h> |
| 2 | #include <pthread.h> |
| 3 | #include <stdio.h> |
| 4 | #include <stdlib.h> |
| 5 | #include <string.h> |
| 6 | #include <unistd.h> |
| 7 | #include <sys/mman.h> |
| 8 | #include <sys/resource.h> |
| 9 | |
| 10 | static void use_stack (size_t needed); |
| 11 | |
| 12 | void (*use_stack_ptr) (size_t) = use_stack; |
| 13 | |
| 14 | static void |
| 15 | use_stack (size_t needed) |
| 16 | { |
| 17 | size_t sz = sysconf (_SC_PAGESIZE); |
| 18 | char *buf = alloca (sz); |
| 19 | memset (buf, '\0', sz); |
| 20 | |
| 21 | if (needed > sz) |
| 22 | use_stack_ptr (needed - sz); |
| 23 | } |
| 24 | |
| 25 | static void |
| 26 | use_up_memory (void) |
| 27 | { |
| 28 | struct rlimit rl; |
| 29 | getrlimit (RLIMIT_AS, &rl); |
| 30 | rl.rlim_cur = 10 * 1024 * 1024; |
| 31 | setrlimit (RLIMIT_AS, &rl); |
| 32 | |
| 33 | char *c; |
| 34 | int PAGESIZE = getpagesize (); |
| 35 | while (1) |
| 36 | { |
| 37 | c = mmap (NULL, PAGESIZE, PROT_NONE, MAP_ANON | MAP_PRIVATE, -1, 0); |
| 38 | if (c == MAP_FAILED) |
| 39 | break; |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | static void * |
| 44 | child (void *arg) |
| 45 | { |
| 46 | sleep (1); |
| 47 | return arg; |
| 48 | } |
| 49 | |
| 50 | static int |
| 51 | do_test (void) |
| 52 | { |
| 53 | int err; |
| 54 | pthread_t tid; |
| 55 | |
| 56 | /* Allocate the memory needed for the stack. */ |
| 57 | use_stack_ptr (PTHREAD_STACK_MIN); |
| 58 | |
| 59 | use_up_memory (); |
| 60 | |
| 61 | err = pthread_create (&tid, NULL, child, NULL); |
| 62 | if (err != 0) |
| 63 | { |
| 64 | printf ("pthread_create returns %d: %s\n", err, |
| 65 | err == EAGAIN ? "OK" : "FAIL"); |
| 66 | return err != EAGAIN; |
| 67 | } |
| 68 | |
| 69 | /* We did not fail to allocate memory despite the preparation. Oh well. */ |
| 70 | return 0; |
| 71 | } |
| 72 | |
| 73 | #define TEST_FUNCTION do_test () |
| 74 | #include "../test-skeleton.c" |