Debian Codegraph @

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

raw symbols SCIP
1 /**
2 * This file is the CPython module _vmprof. It does not share code
3 * with PyPy. PyPy's _vmprof module is included in the main repo.
4 */
5 #define _GNU_SOURCE 1
6
7 #include <Python.h>
8 #include <frameobject.h>
9 #include <signal.h>
10
11 #include "_vmprof.h"
12 #include "vmprof_common.h"
13
14
15 #ifndef RPYTHON_VMPROF
16 #if PY_VERSION_HEX >= 0x030b00f0 /* >= 3.11 */
17 #include "internal/pycore_frame.h"
18 #include "populate_frames.h"
19 #endif
20 #endif
21
22 static destructor Original_code_dealloc = 0;
23 static PyObject* (*_default_eval_loop)(PyFrameObject *, int) = 0;
24
25 #if VMPROF_UNIX
26 #include "trampoline.h"
27 #include "machine.h"
28 #include "symboltable.h"
29 #include "vmprof_unix.h"
30 #else
31 #include "vmprof_win.h"
32 #endif
33 #include "vmp_stack.h"
34
35 #ifdef VMPROF_UNIX
36 #ifdef __clang__
37 __attribute__((optnone))
38 #elif defined(__GNUC__)
39 __attribute__((optimize("O1")))
40 #endif
41 PY_EVAL_RETURN_T * vmprof_eval(PY_STACK_FRAME_T *f, int throwflag)
42 {
43 #ifdef X86_64
44 register PY_STACK_FRAME_T * callee_saved asm("rbx");
45 #elif defined(X86_32)
46 register PY_STACK_FRAME_T * callee_saved asm("edi");
47 #elif defined(__arm__)
48 register PY_STACK_FRAME_T * callee_saved asm("r4");
49 #elif defined(__aarch64__)
50 register PY_STACK_FRAME_T * callee_saved asm("x19");
51 #elif defined(__powerpc64__)
52 register PY_STACK_FRAME_T * callee_saved asm("r3");
53 #else
54 # error "platform not supported"
55 #endif
56
57 asm volatile(
58 #ifdef X86_64
59 "movq %1, %0\t\n"
60 #elif defined(X86_32)
61 "mov %1, %0\t\n"
62 #elif defined(__arm__) || defined(__aarch64__)
63 "mov %1, %0\t\n"
64 #elif defined(__powerpc64__)
65 "addi %1, %0, 0\t\n"
66 #else
67 # error "platform not supported"
68 #endif
69 : "=r" (callee_saved)
70 : "r" (f) );
71 return _default_eval_loop(f, throwflag);
72 }
73 #endif
74
75 static int emit_code_object(PyCodeObject *co)
76 {
77 char buf[MAX_FUNC_NAME + 1];
78 const char *co_name, *co_filename;
79 int co_firstlineno;
80 int sz;
81 #if PY_MAJOR_VERSION >= 3
82 co_name = PyUnicode_AsUTF8(co->co_name);
83 if (co_name == NULL)
84 return -1;
85 co_filename = PyUnicode_AsUTF8(co->co_filename);
86 if (co_filename == NULL)
87 return -1;
88 #else
89 co_name = PyString_AS_STRING(co->co_name);
90 co_filename = PyString_AS_STRING(co->co_filename);
91 #endif
92 co_firstlineno = co->co_firstlineno;
93
94 sz = snprintf(buf, MAX_FUNC_NAME / 2, "py:%s", co_name);
95 if (sz < 0) sz = 0;
96 if (sz > MAX_FUNC_NAME / 2) sz = MAX_FUNC_NAME / 2;
97 snprintf(buf + sz, MAX_FUNC_NAME / 2, ":%d:%s", co_firstlineno,
98 co_filename);
99 return vmprof_register_virtual_function(buf, CODE_ADDR_TO_UID(co), 500000);
100 }
101
102 static int _look_for_code_object(PyObject *o, void * param)
103 {
104 Py_ssize_t i;
105 PyObject * all_codes, * seen_codes;
106
107 all_codes = (PyObject*)((void**)param)[0];
108 seen_codes = (PyObject*)((void**)param)[1];
109 if (PyCode_Check(o) && !PySet_Contains(all_codes, o)) {
110 PyCodeObject *co = (PyCodeObject *)o;
111 PyObject * id = PyLong_FromVoidPtr((void*)CODE_ADDR_TO_UID(co));
112 if (PySet_Contains(seen_codes, id)) {
113 // only emit if the code id has been seen!
114 if (emit_code_object(co) < 0)
115 return -1;
116 if (PySet_Add(all_codes, o) < 0)
117 return -1;
118 }
119
120 /* as a special case, recursively look for and add code
121 objects found in the co_consts. The problem is that code
122 objects are not created as GC-aware in CPython, so we need
123 to hack like this to hope to find most of them.
124 */
125 i = PyTuple_Size(co->co_consts);
126 while (i > 0) {
127 --i;
128 if (_look_for_code_object(PyTuple_GET_ITEM(co->co_consts, i),
129 param) < 0)
130 return -1;
131 }
132 }
133 return 0;
134 }
135
136 static
137 void emit_all_code_objects(PyObject * seen_code_ids)
138 {
139 PyObject *gc_module = NULL, *lst = NULL, *all_codes = NULL;
140 Py_ssize_t i, size;
141 void * param[2];
142
143 gc_module = PyImport_ImportModuleNoBlock("gc");
144 if (gc_module == NULL)
145 goto error;
146
147 // lst contains all objects that are known by the gc
148 lst = PyObject_CallMethod(gc_module, "get_objects", "");
149 if (lst == NULL || !PyList_Check(lst))
150 goto error;
151
152 // the set only includes the code objects found in the profile
153 all_codes = PySet_New(NULL);
154 if (all_codes == NULL)
155 goto error;
156
157 param[0] = all_codes;
158 param[1] = seen_code_ids;
159
160 size = PyList_GET_SIZE(lst);
161 for (i = 0; i < size; i++) {
162 PyObject *o = PyList_GET_ITEM(lst, i);
163 if (o->ob_type->tp_traverse &&
164 o->ob_type->tp_traverse(o, _look_for_code_object, (void*)param)
165 < 0)
166 goto error;
167 }
168
169 error:
170 Py_XDECREF(all_codes);
171 Py_XDECREF(lst);
172 Py_XDECREF(gc_module);
173 }
174
175 static void cpyprof_code_dealloc(PyObject *co)
176 {
177 if (vmprof_is_enabled()) {
178 emit_code_object((PyCodeObject *)co);
179 /* xxx error return values are ignored */
180 }
181 Original_code_dealloc(co);
182 }
183
184 static PyObject *enable_vmprof(PyObject* self, PyObject *args)
185 {
186 int fd;
187 int memory = 0;
188 int lines = 0;
189 int native = 0;
190 int real_time = 0;
191 double interval;
192 char *p_error;
193
194 if (!PyArg_ParseTuple(args, "id|iiii", &fd, &interval, &memory, &lines, &native, &real_time)) {
195 return NULL;
196 }
197
198 if (write(fd, NULL, 0) != 0) {
199 PyErr_SetString(PyExc_ValueError, "file descriptor must be writeable");
200 return NULL;
201 }
202
203 if ((read(fd, NULL, 0) != 0) && (native != 0)) {
204 PyErr_SetString(PyExc_ValueError, "file descriptor must be readable");
205 return NULL;
206 }
207
208 if (vmprof_is_enabled()) {
209 PyErr_SetString(PyExc_ValueError, "vmprof is already enabled");
210 return NULL;
211 }
212
213 #ifndef VMPROF_UNIX
214 if (real_time) {
215 PyErr_SetString(PyExc_ValueError, "real time profiling is only supported on Linux and MacOS");
216 return NULL;
217 }
218 #endif
219
220 vmp_profile_lines(lines);
221
222 if (!Original_code_dealloc) {
223 Original_code_dealloc = PyCode_Type.tp_dealloc;
224 PyCode_Type.tp_dealloc = &cpyprof_code_dealloc;
225 }
226
227 p_error = vmprof_init(fd, interval, memory, lines, "cpython", native, real_time);
228 if (p_error) {
229 PyErr_SetString(PyExc_ValueError, p_error);
230 return NULL;
231 }
232
233 if (vmprof_enable(memory, native, real_time) < 0) {
234 PyErr_SetFromErrno(PyExc_OSError);
235 return NULL;
236 }
237
238 vmprof_set_enabled(1);
239
240 Py_RETURN_NONE;
241 }
242
243 static PyObject * vmp_is_enabled(PyObject *module, PyObject *noargs) {
244 if (vmprof_is_enabled()) {
245 Py_RETURN_TRUE;
246 }
247 Py_RETURN_FALSE;
248 }
249
250 static PyObject *
251 disable_vmprof(PyObject *module, PyObject *noargs)
252 {
253 if (vmprof_disable() < 0) {
254 PyErr_SetFromErrno(PyExc_OSError);
255 return NULL;
256 }
257
258 vmprof_set_enabled(0);
259
260 if (PyErr_Occurred())
261 return NULL;
262
263 Py_RETURN_NONE;
264 }
265
266 static PyObject *
267 write_all_code_objects(PyObject *module, PyObject * seen_code_ids)
268 {
269 // assumptions: signals must be disabled (see stop_sampling)
270 emit_all_code_objects(seen_code_ids);
271
272 if (PyErr_Occurred())
273 return NULL;
274 Py_RETURN_NONE;
275 }
276
277
278 #if PY_VERSION_HEX < 0x030900B1 /* < 3.9 */
279 static inline PyFrameObject* PyThreadState_GetFrame(PyThreadState *tstate)
280 {
281 Py_XINCREF(tstate->frame);
282 return tstate->frame;
283 }
284 #endif
285
286
287
288 static PyObject *
289 sample_stack_now(PyObject *module, PyObject * args)
290 {
291 PyThreadState * tstate = NULL;
292 PyObject * list = NULL;
293 int i;
294 int entry_count;
295 void ** m;
296 void * routine_ip;
297 long skip = 0;
298
299 // stop any signal to occur
300 vmprof_ignore_signals(1);
301
302 list = PyList_New(0);
303 if (list == NULL) {
304 goto error;
305 }
306
307 if (!PyArg_ParseTuple(args, "l", &skip)) {
308 goto error;
309 }
310
311 tstate = PyGILState_GetThisThreadState();
312 m = (void**)malloc(SINGLE_BUF_SIZE);
313 if (m == NULL) {
314 PyErr_SetString(PyExc_MemoryError, "could not allocate buffer for stack trace");
315 vmprof_ignore_signals(0);
316 return NULL;
317 }
318
319 #if PY_VERSION_HEX >= 0x030B0000 /* < 3.11, no pypy 3.11 at the moment*/
320 _PyInterpreterFrame * frame = unsafe_PyThreadState_GetInterpreterFrame(tstate);
321 #else
322 PyFrameObject* frame = PyThreadState_GetFrame(tstate);
323 #endif
324
325 entry_count = vmp_walk_and_record_stack(frame, m, SINGLE_BUF_SIZE/sizeof(void*)-1, (int)skip, 0);
326
327 Py_XDECREF(frame);
328
329
330 for (i = 0; i < entry_count; i++) {
331 routine_ip = m[i];
332 PyList_Append(list, PyLong_NEW((Py_ssize_t)routine_ip));
333 }
334
335 free(m);
336
337 vmprof_ignore_signals(0);
338 Py_INCREF(list);
339 return list;
340
341 error:
342 vmprof_ignore_signals(0);
343 Py_DECREF(list);
344 Py_RETURN_NONE;
345 }
346
347 #ifdef VMP_SUPPORTS_NATIVE_PROFILING
348 static PyObject *
349 resolve_addr(PyObject *module, PyObject *args) {
350 long long addr;
351 PyObject * o_name = NULL;
352 PyObject * o_lineno = NULL;
353 PyObject * o_srcfile = NULL;
354 char name[128];
355 int lineno = 0;
356 char srcfile[256];
357
358 if (!PyArg_ParseTuple(args, "L", &addr)) {
359 return NULL;
360 }
361 name[0] = '\x00';
362 srcfile[0] = '-';
363 srcfile[1] = '\x00';
364 if (vmp_resolve_addr((void*)addr, name, 128, &lineno, srcfile, 256) != 0) {
365 goto error;
366 }
367
368 o_name = PyStr_NEW(name);
369 if (o_name == NULL) goto error;
370 o_lineno = PyLong_NEW(lineno);
371 if (o_lineno == NULL) goto error;
372 o_srcfile = PyStr_NEW(srcfile);
373 if (o_srcfile == NULL) goto error;
374 //
375 return PyTuple_Pack(3, o_name, o_lineno, o_srcfile);
376 error:
377 Py_XDECREF(o_name);
378 Py_XDECREF(o_lineno);
379 Py_XDECREF(o_srcfile);
380
381 Py_RETURN_NONE;
382 }
383 #endif
384
385 static PyObject *
386 stop_sampling(PyObject *module, PyObject *noargs)
387 {
388 vmprof_ignore_signals(1);
389 return PyLong_NEW(vmp_profile_fileno());
390 }
391
392 static PyObject *
393 start_sampling(PyObject *module, PyObject *noargs)
394 {
395 vmprof_ignore_signals(0);
396 Py_RETURN_NONE;
397 }
398
399 #ifdef VMPROF_UNIX
400 static PyObject * vmp_get_profile_path(PyObject *module, PyObject *noargs) {
401 PyObject * o;
402 if (vmprof_is_enabled()) {
403 char buffer[4096];
404 buffer[0] = 0;
405 ssize_t buffer_len = vmp_fd_to_path(vmp_profile_fileno(), buffer, 4096);
406 if (buffer_len == -1) {
407 PyErr_Format(PyExc_NotImplementedError, "not implemented platform %s", vmp_machine_os_name());
408 return NULL;
409 }
410 return PyStr_n_NEW(buffer, buffer_len);
411 }
412 Py_RETURN_NONE;
413 }
414 #endif
415
416
417 #ifdef VMPROF_UNIX
418 static PyObject *
419 insert_real_time_thread(PyObject *module, PyObject * args) {
420 ssize_t thread_count;
421 unsigned long thread_id = 0;
422 pthread_t th = pthread_self();
423
424 if (!PyArg_ParseTuple(args, "|k", &thread_id)) {
425 return NULL;
426 }
427
428 if (thread_id) {
429 #if SIZEOF_LONG <= SIZEOF_PTHREAD_T
430 th = (pthread_t) thread_id;
431 #else
432 th = (pthread_t) *(unsigned long *) &thread_id;
433 #endif
434 }
435
436 if (!vmprof_is_enabled()) {
437 PyErr_SetString(PyExc_ValueError, "vmprof is not enabled");
438 return NULL;
439 }
440
441 if (vmprof_get_signal_type() != SIGALRM) {
442 PyErr_SetString(PyExc_ValueError, "vmprof is not in real time mode");
443 return NULL;
444 }
445
446 vmprof_aquire_lock();
447 thread_count = insert_thread(th, -1);
448 vmprof_release_lock();
449
450 return PyLong_FromSsize_t(thread_count);
451 }
452
453 static PyObject *
454 remove_real_time_thread(PyObject *module, PyObject * args) {
455 ssize_t thread_count;
456 unsigned long thread_id = 0;
457 pthread_t th = pthread_self();
458
459 if (!PyArg_ParseTuple(args, "|k", &thread_id)) {
460 return NULL;
461 }
462
463 if (thread_id) {
464 #if SIZEOF_LONG <= SIZEOF_PTHREAD_T
465 th = (pthread_t) thread_id;
466 #else
467 th = (pthread_t) *(unsigned long *) &thread_id;
468 #endif
469 }
470
471 if (!vmprof_is_enabled()) {
472 PyErr_SetString(PyExc_ValueError, "vmprof is not enabled");
473 return NULL;
474 }
475
476 if (vmprof_get_signal_type() != SIGALRM) {
477 PyErr_SetString(PyExc_ValueError, "vmprof is not in real time mode");
478 return NULL;
479 }
480
481 vmprof_aquire_lock();
482 thread_count = remove_thread(th, -1);
483 vmprof_release_lock();
484
485 return PyLong_FromSsize_t(thread_count);
486 }
487 #endif
488
489 static PyMethodDef VMProfMethods[] = {
490 {"enable", enable_vmprof, METH_VARARGS, "Enable profiling."},
491 {"disable", disable_vmprof, METH_NOARGS, "Disable profiling."},
492 {"write_all_code_objects", write_all_code_objects, METH_O,
493 "Write eagerly all the IDs of code objects"},
494 {"sample_stack_now", sample_stack_now, METH_VARARGS,
495 "Sample the stack now"},
496 {"is_enabled", vmp_is_enabled, METH_NOARGS,
497 "Indicates if vmprof is currently sampling."},
498 {"stop_sampling", stop_sampling, METH_NOARGS,
499 "Blocks signals to occur and returns the file descriptor"},
500 {"start_sampling", start_sampling, METH_NOARGS,
501 "Unblocks vmprof signals. After compeltion vmprof will sample again"},
502 #ifdef VMP_SUPPORTS_NATIVE_PROFILING
503 {"resolve_addr", resolve_addr, METH_VARARGS,
504 "Returns the name of the given address"},
505 #endif
506 #ifdef VMPROF_UNIX
507 {"get_profile_path", vmp_get_profile_path, METH_NOARGS,
508 "Profile path the profiler logs to."},
509 {"insert_real_time_thread", insert_real_time_thread, METH_VARARGS,
510 "Insert a thread into the real time profiling list."},
511 {"remove_real_time_thread", remove_real_time_thread, METH_VARARGS,
512 "Remove a thread from the real time profiling list."},
513 #endif
514 {NULL, NULL, 0, NULL} /* Sentinel */
515 };
516
517
518 #if PY_MAJOR_VERSION >= 3
519 static struct PyModuleDef VmprofModule = {
520 PyModuleDef_HEAD_INIT,
521 "_vmprof",
522 "", // doc
523 -1, // size
524 VMProfMethods
525 };
526
527 PyMODINIT_FUNC PyInit__vmprof(void)
528 {
529 return PyModule_Create(&VmprofModule);
530 }
531 #else
532 PyMODINIT_FUNC init_vmprof(void)
533 {
534 Py_InitModule("_vmprof", VMProfMethods);
535 }
536 #endif