* nscd/nscd_helper.c (get_mapping): Use MSG_CMSG_CLOEXEC for
[glibc.git] / elf / tst-execstack.c
blob4b06615451ebb208f9119df046e80ddeeb6fc345
1 /* Test program for making nonexecutable stacks executable
2 on load of a DSO that requires executable stacks. */
4 #include <dlfcn.h>
5 #include <stdio.h>
6 #include <string.h>
7 #include <unistd.h>
8 #include <error.h>
10 static void
11 print_maps (void)
13 #if 0
14 char *cmd = NULL;
15 asprintf (&cmd, "cat /proc/%d/maps", getpid ());
16 system (cmd);
17 free (cmd);
18 #endif
21 static void deeper (void (*f) (void));
23 #if USE_PTHREADS
24 # include <pthread.h>
26 static void *
27 tryme_thread (void *f)
29 (*((void (*) (void)) f)) ();
31 return 0;
34 static pthread_barrier_t startup_barrier, go_barrier;
35 static void *
36 waiter_thread (void *arg)
38 void **f = arg;
39 pthread_barrier_wait (&startup_barrier);
40 pthread_barrier_wait (&go_barrier);
42 (*((void (*) (void)) *f)) ();
44 return 0;
46 #endif
48 static int
49 do_test (void)
51 static void *f; /* Address of this is used in other threads. */
53 #if USE_PTHREADS
54 /* Create some threads while stacks are nonexecutable. */
55 #define N 5
56 pthread_t thr[N];
58 pthread_barrier_init (&startup_barrier, NULL, N + 1);
59 pthread_barrier_init (&go_barrier, NULL, N + 1);
61 for (int i = 0; i < N; ++i)
63 int rc = pthread_create (&thr[i], NULL, &waiter_thread, &f);
64 if (rc)
65 error (1, rc, "pthread_create");
68 /* Make sure they are all there using their stacks. */
69 pthread_barrier_wait (&startup_barrier);
70 puts ("threads waiting");
71 #endif
73 print_maps ();
75 /* Loading this module should force stacks to become executable. */
76 void *h = dlopen ("tst-execstack-mod.so", RTLD_LAZY);
77 if (h == NULL)
79 printf ("cannot load: %s\n", dlerror ());
80 return 1;
83 f = dlsym (h, "tryme");
84 if (f == NULL)
86 printf ("symbol not found: %s\n", dlerror ());
87 return 1;
90 /* Test if that really made our stack executable.
91 The `tryme' function should crash if not. */
93 (*((void (*) (void)) f)) ();
95 print_maps ();
97 /* Test that growing the stack region gets new executable pages too. */
98 deeper ((void (*) (void)) f);
100 print_maps ();
102 #if USE_PTHREADS
103 /* Test that a fresh thread now gets an executable stack. */
105 pthread_t th;
106 int rc = pthread_create (&th, NULL, &tryme_thread, f);
107 if (rc)
108 error (1, rc, "pthread_create");
111 puts ("threads go");
112 /* The existing threads' stacks should have been changed.
113 Let them run to test it. */
114 pthread_barrier_wait (&go_barrier);
116 pthread_exit (0);
117 #endif
119 return 0;
122 static void
123 deeper (void (*f) (void))
125 char stack[1100 * 1024];
126 memfrob (stack, sizeof stack);
127 (*f) ();
128 memfrob (stack, sizeof stack);
132 #define TEST_FUNCTION do_test ()
133 #include "../test-skeleton.c"