Debian Codegraph @

rpython/rlib/rvmprof/src/shared/vmprof_unix.c

raw symbols SCIP
1 #include "vmprof_unix.h"
2
3 #ifndef RPYTHON_VMPROF
4 #if PY_VERSION_HEX >= 0x030b00f0 /* >= 3.11 */
5 #include "populate_frames.h"
6 #endif
7 #endif
8
9 #ifdef VMPROF_UNIX
10
11 #if VMPROF_LINUX
12 #include <syscall.h>
13 #endif
14
15
16 #include <dlfcn.h>
17 #include <pthread.h>
18 #include <unistd.h>
19 #include <assert.h>
20 #include <errno.h>
21 #include <stdio.h>
22 #include <fcntl.h>
23 #include <time.h>
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <sys/time.h>
27
28 #include "vmp_stack.h"
29 #include "vmprof_mt.h"
30 #include "vmprof_getpc.h"
31 #include "vmprof_common.h"
32 #include "vmprof_memory.h"
33 #include "compat.h"
34
35
36
37 /* value: LSB bit is 1 if signals must be ignored; all other bits
38 are a counter for how many threads are currently in a signal handler */
39 static long volatile signal_handler_ignore = 1;
40 static long volatile signal_handler_entries = 0;
41 static char atfork_hook_installed = 0;
42 static volatile int spinlock;
43 static jmp_buf restore_point;
44 static struct profbuf_s *volatile current_codes;
45
46
47 void vmprof_ignore_signals(int ignored)
48 {
49 if (ignored) {
50 __sync_add_and_fetch(&signal_handler_ignore, 1L);
51 while (signal_handler_entries != 0L) {
52 usleep(1);
53 }
54 } else {
55 __sync_sub_and_fetch(&signal_handler_ignore, 1L);
56 }
57 }
58
59 long vmprof_enter_signal(void)
60 {
61 __sync_fetch_and_add(&signal_handler_entries, 1L);
62 return signal_handler_ignore;
63 }
64
65 long vmprof_exit_signal(void)
66 {
67 return __sync_sub_and_fetch(&signal_handler_entries, 1L);
68 }
69
70 int install_pthread_atfork_hooks(void) {
71 /* this is needed to prevent the problems described there:
72 - http://code.google.com/p/gperftools/issues/detail?id=278
73 - http://lists.debian.org/debian-glibc/2010/03/msg00161.html
74
75 TL;DR: if the RSS of the process is large enough, the clone() syscall
76 will be interrupted by the SIGPROF before it can complete, then
77 retried, interrupted again and so on, in an endless loop. The
78 solution is to disable the timer around the fork, and re-enable it
79 only inside the parent.
80 */
81 if (atfork_hook_installed)
82 return 0;
83 int ret = pthread_atfork(atfork_disable_timer, atfork_enable_timer, atfork_close_profile_file);
84 if (ret != 0)
85 return -1;
86 atfork_hook_installed = 1;
87 return 0;
88 }
89
90 void segfault_handler(int arg)
91 {
92 longjmp(restore_point, SIGSEGV);
93 }
94
95 int _vmprof_sample_stack(struct profbuf_s *p, PY_THREAD_STATE_T * tstate, ucontext_t * uc)
96 {
97 int depth;
98 struct prof_stacktrace_s *st = (struct prof_stacktrace_s *)p->data;
99 st->marker = MARKER_STACKTRACE;
100 st->count = 1;
101 #ifdef RPYTHON_VMPROF
102 depth = get_stack_trace(get_vmprof_stack(), st->stack, MAX_STACK_DEPTH-1, (intptr_t)GetPC(uc));
103 #else
104 depth = get_stack_trace(tstate, st->stack, MAX_STACK_DEPTH-1, (intptr_t)NULL);
105 #endif
106 // useful for tests (see test_stop_sampling)
107 #ifndef RPYTHON_LL2CTYPES
108 if (depth == 0) {
109 return 0;
110 }
111 #endif
112 st->depth = depth;
113 st->stack[depth++] = tstate;
114 long rss = get_current_proc_rss();
115 if (rss >= 0)
116 st->stack[depth++] = (void*)rss;
117 p->data_offset = offsetof(struct prof_stacktrace_s, marker);
118 p->data_size = (depth * sizeof(void *) +
119 sizeof(struct prof_stacktrace_s) -
120 offsetof(struct prof_stacktrace_s, marker));
121 return 1;
122 }
123
124 #ifndef RPYTHON_VMPROF
125 PY_THREAD_STATE_T * _get_pystate_for_this_thread(void) {
126 // see issue 116 on github.com/vmprof/vmprof-python.
127 // PyGILState_GetThisThreadState(); can hang forever
128 //
129 PyInterpreterState * istate;
130 PyThreadState * state;
131 long mythread_id;
132
133 mythread_id = PyThread_get_thread_ident();
134 istate = PyInterpreterState_Head();
135 if (istate == NULL) {
136 #if DEBUG
137 fprintf(stderr, "WARNING: interp state head is null (for thread id %ld)\n", mythread_id);
138 #endif
139 return NULL;
140 }
141 // fish fish fish, it will NOT lock the keymutex in pythread
142 do {
143 state = PyInterpreterState_ThreadHead(istate);
144 do {
145 if (state->thread_id == mythread_id) {
146 return state;
147 }
148 } while ((state = PyThreadState_Next(state)) != NULL);
149 } while ((istate = PyInterpreterState_Next(istate)) != NULL);
150
151 // uh? not found?
152 #if DEBUG
153 fprintf(stderr, "WARNING: cannot find thread state (for thread id %ld), sample will be thrown away\n", mythread_id);
154 #endif
155 return NULL;
156 }
157 #endif
158
159 void flush_codes(void)
160 {
161 struct profbuf_s *p = current_codes;
162 if (p != NULL) {
163 current_codes = NULL;
164 commit_buffer(vmp_profile_fileno(), p);
165 }
166 }
167
168 void set_current_codes(void * to) {
169 current_codes = to;
170 }
171
172 #endif
173
174 void vmprof_aquire_lock(void) {
175 while (__sync_lock_test_and_set(&spinlock, 1)) {
176 }
177 }
178
179 void vmprof_release_lock(void) {
180 __sync_lock_release(&spinlock);
181 }
182
183 void sigprof_handler(int sig_nr, siginfo_t* info, void *ucontext)
184 {
185 int commit;
186 PY_THREAD_STATE_T * tstate = NULL;
187 void (*prevhandler)(int);
188
189 #ifndef RPYTHON_VMPROF
190
191 // Even though the docs say that this function call is for 'esoteric use'
192 // it seems to be correctly set when the interpreter is teared down!
193 if (!Py_IsInitialized()) {
194 return;
195 }
196
197 // TERRIBLE HACK AHEAD
198 // on OS X, the thread local storage is sometimes uninitialized
199 // when the signal handler runs - it means it's impossible to read errno
200 // or call any syscall or read PyThread_Current or pthread_self. Additionally,
201 // it seems impossible to read the register gs.
202 // here we register segfault handler (all guarded by a spinlock) and call
203 // longjmp in case segfault happens while reading a thread local
204 //
205 // We do the same error detection for linux to ensure that
206 // get_current_thread_state returns a sane result
207 while (__sync_lock_test_and_set(&spinlock, 1)) {
208 }
209
210 #ifdef VMPROF_UNIX
211 // SIGNAL ABUSE AHEAD
212 // On linux, the prof timer will deliver the signal to the thread which triggered the timer,
213 // because these timers are based on process and system time, and as such, are thread-aware.
214 // For the real timer, the signal gets delivered to the main thread, seemingly always.
215 // Consequently if we want to sample multiple threads, we need to forward this signal.
216 if (vmprof_get_signal_type() == SIGALRM) {
217 if (is_main_thread() && broadcast_signal_for_threads()) {
218 __sync_lock_release(&spinlock);
219 return;
220 }
221 }
222 #endif
223
224 prevhandler = signal(SIGSEGV, &segfault_handler);
225 int fault_code = setjmp(restore_point);
226 if (fault_code == 0) {
227 pthread_self();
228 tstate = _get_pystate_for_this_thread();
229 } else {
230 signal(SIGSEGV, prevhandler);
231 __sync_lock_release(&spinlock);
232 return;
233 }
234 signal(SIGSEGV, prevhandler);
235 __sync_lock_release(&spinlock);
236 #endif
237
238 long val = vmprof_enter_signal();
239
240 if (val == 0) {
241 int saved_errno = errno;
242 int fd = vmp_profile_fileno();
243 assert(fd >= 0);
244
245 struct profbuf_s *p = reserve_buffer(fd);
246 if (p == NULL) {
247 /* ignore this signal: there are no free buffers right now */
248 } else {
249 #ifdef RPYTHON_VMPROF
250 commit = _vmprof_sample_stack(p, NULL, (ucontext_t*)ucontext);
251 #else
252 commit = _vmprof_sample_stack(p, tstate, (ucontext_t*)ucontext);
253 #endif
254 if (commit) {
255 commit_buffer(fd, p);
256 } else {
257 #if DEBUG
258 fprintf(stderr, "WARNING: canceled buffer, no stack trace was written\n");
259 #endif
260 cancel_buffer(p);
261 }
262 }
263
264 errno = saved_errno;
265 }
266
267 vmprof_exit_signal();
268 }
269
270 int install_sigprof_handler(void)
271 {
272 struct sigaction sa;
273 memset(&sa, 0, sizeof(sa));
274 sa.sa_sigaction = sigprof_handler;
275 sa.sa_flags = SA_RESTART | SA_SIGINFO;
276 if (sigemptyset(&sa.sa_mask) == -1 ||
277 sigaction(vmprof_get_signal_type(), &sa, NULL) == -1)
278 return -1;
279 return 0;
280 }
281
282 int remove_sigprof_handler(void)
283 {
284 struct sigaction ign_sigint, prev;
285 ign_sigint.sa_handler = SIG_IGN;
286 ign_sigint.sa_flags = 0;
287 sigemptyset(&ign_sigint.sa_mask);
288
289 if (sigaction(vmprof_get_signal_type(), &ign_sigint, NULL) < 0) {
290 fprintf(stderr, "Could not remove the signal handler (for profiling)\n");
291 return -1;
292 }
293 return 0;
294 }
295
296 int install_sigprof_timer(void)
297 {
298 static struct itimerval timer;
299 timer.it_interval.tv_sec = 0;
300 timer.it_interval.tv_usec = (int)vmprof_get_profile_interval_usec();
301 timer.it_value = timer.it_interval;
302 if (setitimer(vmprof_get_itimer_type(), &timer, NULL) != 0)
303 return -1;
304 return 0;
305 }
306
307 int remove_sigprof_timer(void)
308 {
309 static struct itimerval timer;
310 timerclear(&(timer.it_interval));
311 timerclear(&(timer.it_value));
312 if (setitimer(vmprof_get_itimer_type(), &timer, NULL) != 0) {
313 fprintf(stderr, "Could not disable the signal handler (for profiling)\n");
314 return -1;
315 }
316 return 0;
317 }
318
319 void atfork_disable_timer(void)
320 {
321 if (vmprof_get_profile_interval_usec() > 0) {
322 remove_sigprof_timer();
323 vmprof_set_enabled(0);
324 }
325 }
326
327 void atfork_close_profile_file(void)
328 {
329 int fd = vmp_profile_fileno();
330 if (fd != -1)
331 close(fd);
332 vmp_set_profile_fileno(-1);
333 }
334 void atfork_enable_timer(void)
335 {
336 if (vmprof_get_profile_interval_usec() > 0) {
337 install_sigprof_timer();
338 vmprof_set_enabled(1);
339 }
340 }
341
342 #ifdef VMP_SUPPORTS_NATIVE_PROFILING
343 void init_cpyprof(int native)
344 {
345 // skip this if native should not be enabled
346 if (!native) {
347 vmp_native_disable();
348 return;
349 }
350 vmp_native_enable();
351 }
352
353 static void disable_cpyprof(void)
354 {
355 vmp_native_disable();
356 }
357 #endif
358
359 int vmprof_enable(int memory, int native, int real_time)
360 {
361 #ifdef VMP_SUPPORTS_NATIVE_PROFILING
362 init_cpyprof(native);
363 #endif
364 assert(vmp_profile_fileno() >= 0);
365 assert(vmprof_get_prepare_interval_usec() > 0);
366 vmprof_set_profile_interval_usec(vmprof_get_prepare_interval_usec());
367 if (memory && setup_rss() == -1)
368 goto error;
369 #if VMPROF_UNIX
370 if (real_time && insert_thread(pthread_self(), -1) == -1)
371 goto error;
372 #endif
373 if (install_pthread_atfork_hooks() == -1)
374 goto error;
375 if (install_sigprof_handler() == -1)
376 goto error;
377 if (install_sigprof_timer() == -1)
378 goto error;
379 signal_handler_ignore = 0;
380 return 0;
381
382 error:
383 vmp_set_profile_fileno(-1);
384 vmprof_set_profile_interval_usec(0);
385 return -1;
386 }
387
388
389 int close_profile(void)
390 {
391 int fileno = vmp_profile_fileno();
392 fsync(fileno);
393 (void)vmp_write_time_now(MARKER_TRAILER);
394 teardown_rss();
395
396 /* don't close() the file descriptor from here */
397 vmp_set_profile_fileno(-1);
398 return 0;
399 }
400
401 int vmprof_disable(void)
402 {
403 signal_handler_ignore = 1;
404 vmprof_set_profile_interval_usec(0);
405 #ifdef VMP_SUPPORTS_NATIVE_PROFILING
406 disable_cpyprof();
407 #endif
408
409 if (remove_sigprof_timer() == -1) {
410 return -1;
411 }
412 if (remove_sigprof_handler() == -1) {
413 return -1;
414 }
415 #ifdef VMPROF_UNIX
416 if ((vmprof_get_signal_type() == SIGALRM) && remove_threads() == -1) {
417 return -1;
418 }
419 #endif
420 flush_codes();
421 if (shutdown_concurrent_bufs(vmp_profile_fileno()) < 0)
422 return -1;
423 return close_profile();
424 }
425
426 int vmprof_register_virtual_function(char *code_name, intptr_t code_uid,
427 int auto_retry)
428 {
429 long namelen = strnlen(code_name, 1023);
430 long blocklen = 1 + sizeof(intptr_t) + sizeof(long) + namelen;
431 struct profbuf_s *p;
432 char *t;
433
434 retry:
435 p = current_codes;
436 if (p != NULL) {
437 if (__sync_bool_compare_and_swap(&current_codes, p, NULL)) {
438 /* grabbed 'current_codes': we will append the current block
439 to it if it contains enough room */
440 size_t freesize = SINGLE_BUF_SIZE - p->data_size;
441 if (freesize < (size_t)blocklen) {
442 /* full: flush it */
443 commit_buffer(vmp_profile_fileno(), p);
444 p = NULL;
445 }
446 }
447 else {
448 /* compare-and-swap failed, don't try again */
449 p = NULL;
450 }
451 }
452
453 if (p == NULL) {
454 p = reserve_buffer(vmp_profile_fileno());
455 if (p == NULL) {
456 /* can't get a free block; should almost never be the
457 case. Spin loop if allowed, or return a failure code
458 if not (e.g. we're in a signal handler) */
459 if (auto_retry > 0) {
460 auto_retry--;
461 usleep(1);
462 goto retry;
463 }
464 return -1;
465 }
466 }
467
468 t = p->data + p->data_size;
469 p->data_size += blocklen;
470 assert(p->data_size <= SINGLE_BUF_SIZE);
471 *t++ = MARKER_VIRTUAL_IP;
472 memcpy(t, &code_uid, sizeof(intptr_t)); t += sizeof(intptr_t);
473 memcpy(t, &namelen, sizeof(long)); t += sizeof(long);
474 memcpy(t, code_name, namelen);
475
476 /* try to reattach 'p' to 'current_codes' */
477 if (!__sync_bool_compare_and_swap(&current_codes, NULL, p)) {
478 /* failed, flush it */
479 commit_buffer(vmp_profile_fileno(), p);
480 }
481 return 0;
482 }
483
484 #if PY_VERSION_HEX < 0x030900B1 && ! defined(RPYTHON_VMPROF) /* < 3.9 */
485 static inline PyFrameObject* PyThreadState_GetFrame(PyThreadState *tstate)
486 {
487 Py_XINCREF(tstate->frame);
488 return tstate->frame;
489 }
490 #endif
491
492 int get_stack_trace(PY_THREAD_STATE_T * current, void** result, int max_depth, intptr_t pc)
493 {
494 #if PY_VERSION_HEX >= 0x030B0000 /* < 3.11, no pypy 3.11 at the moment*/
495 _PyInterpreterFrame * frame;
496 #else
497 PY_STACK_FRAME_T * frame;
498 #endif
499
500 #ifdef RPYTHON_VMPROF
501 // do nothing here,
502 frame = (PY_STACK_FRAME_T*)current;
503 #else
504 if (current == NULL) {
505 #if DEBUG
506 fprintf(stderr, "WARNING: get_stack_trace, current is NULL\n");
507 #endif
508 return 0;
509 }
510 #if PY_VERSION_HEX >= 0x030B0000 /* < 3.11 */
511 frame = unsafe_PyThreadState_GetInterpreterFrame(current);
512 #else
513 frame = PyThreadState_GetFrame(current);
514 #endif
515
516 #endif /* RPYTHON_VMPROF */
517
518 if (frame == NULL) {
519 #if DEBUG
520 fprintf(stderr, "WARNING: get_stack_trace, frame is NULL\n");
521 #endif
522 return 0;
523 }
524
525 int res = vmp_walk_and_record_stack(frame, result, max_depth, 1, pc);
526
527 #if PY_VERSION_HEX < 0x030B0000 && ! defined(RPYTHON_VMPROF) /* < 3.11 */
528 Py_XDECREF(frame);
529 #endif
530
531 return res;
532 }