Debian Codegraph @

src/source/pywhere.cpp

raw symbols SCIP
1 #include "pywhere.hpp"
2
3 #include <Python.h>
4 #include <dlfcn.h>
5 #include <frameobject.h>
6 #include <unistd.h>
7
8 #include <mutex>
9 #include <unordered_map>
10 #include <vector>
11
12 #include "traceconfig.hpp"
13
14 // NOTE: uncomment for debugging, but this causes issues
15 // for production builds on Alpine
16 //
17 // #include "printf.h"
18 const int NEWLINE_TRIGGER_LENGTH = 98820;
19
20 static bool last_profiled_invalidated = false;
21 // An RAII class to simplify acquiring and releasing the GIL.
22 class GIL {
23 public:
24 GIL() { _gstate = PyGILState_Ensure(); }
25 ~GIL() { PyGILState_Release(_gstate); }
26
27 private:
28 PyGILState_STATE _gstate;
29 };
30
31 #include "pyptr.h"
32
33 #if PY_VERSION_HEX < 0x03090000 // new in 3.9
34 inline PyFrameObject* PyThreadState_GetFrame(PyThreadState* threadState) {
35 if (threadState != nullptr && threadState->frame != nullptr &&
36 // threadState->frame is a "borrowed" reference. With Python 3.8.10,
37 // this sometimes refers to a zero-refcount frame that, if we were to
38 // attempt freeing again (when we decrement back to 0), glibc would
39 // abort due to a double free.
40 threadState->frame->ob_base.ob_base.ob_refcnt > 0) {
41 Py_XINCREF(threadState->frame);
42 return threadState->frame;
43 }
44 return nullptr;
45 }
46 inline PyCodeObject* PyFrame_GetCode(PyFrameObject* frame) {
47 Py_XINCREF(frame->f_code);
48 return frame->f_code;
49 }
50 inline PyFrameObject* PyFrame_GetBack(PyFrameObject* frame) {
51 Py_XINCREF(frame->f_back);
52 return frame->f_back;
53 }
54 #endif
55 #if PY_VERSION_HEX < 0x030B0000 // new in 3.11
56 inline int PyFrame_GetLasti(PyFrameObject* frame) { return frame->f_lasti; }
57 #endif
58
59 #if PY_VERSION_HEX >= 0x030B0000
60 typedef struct _frame {
61 PyObject_HEAD PyFrameObject* f_back; /* previous frame, or NULL */
62 void* f_frame; /* points to the frame data */
63 PyObject* f_trace; /* Trace function */
64 int f_lineno; /* Current line number. Only valid if non-zero */
65 char f_trace_lines; /* Emit per-line trace events? */
66 char f_trace_opcodes; /* Emit per-opcode trace events? */
67 char f_fast_as_locals; /* Have the fast locals of this frame been converted to
68 a dict? */
69 /* The frame data, if this frame object owns the frame */
70 PyObject* _f_frame_data[1];
71 } PyFrameType;
72 #else
73 typedef PyFrameObject PyFrameType;
74 #endif
75
76 static PyPtr<PyFrameObject> findMainPythonThread_frame() {
77 PyThreadState* main = nullptr;
78
79 PyThreadState* t = PyInterpreterState_ThreadHead(PyInterpreterState_Main());
80 for (; t != nullptr; t = PyThreadState_Next(t)) {
81 // Recognize the main thread as the one with the smallest ID.
82 // In Juan's experiments, it's the last thread on the list and has id 1.
83 //
84 // FIXME this could be brittle... another way would be to use
85 // _PyRuntime.main_thread (a native thread ID) and compare it to
86 // PyThreadState.thread_id, with the caveats that main_thread, etc.
87 // might go away or change, and thread_id is initialized with the
88 // native thread ID of whichever thread creates that PyThreadState.
89 if (main == nullptr || main->id > t->id) {
90 main = t;
91 }
92 }
93
94 return PyPtr<PyFrameObject>(main ? PyThreadState_GetFrame(main) : nullptr);
95 }
96 // I'm not sure whether last_profiled_invalidated is quite needed, so I'm
97 // leaving this infrastructure here
98 //
99 PyObject* get_last_profiled_invalidated(PyObject* self, PyObject* args) {
100 if (last_profiled_invalidated) {
101 Py_RETURN_TRUE;
102 }
103 Py_RETURN_FALSE;
104 }
105
106 PyObject* set_last_profiled_invalidated_true(PyObject* self, PyObject* args) {
107 last_profiled_invalidated = true;
108 Py_RETURN_NONE;
109 }
110
111 PyObject* set_last_profiled_invalidated_false(PyObject* self, PyObject* args) {
112 last_profiled_invalidated = false;
113 Py_RETURN_NONE;
114 }
115
116 PyObject* set_scalene_done_true(PyObject* self, PyObject* args) {
117 auto scalene_done = (std::atomic_bool*)dlsym(RTLD_DEFAULT, "p_scalene_done");
118 if (scalene_done == nullptr) {
119 PyErr_SetString(PyExc_Exception, "Unable to find p_scalene_done");
120 return NULL;
121 }
122 *scalene_done = true;
123 Py_RETURN_NONE;
124 }
125 PyObject* set_scalene_done_false(PyObject* self, PyObject* args) {
126 auto scalene_done = (std::atomic_bool*)dlsym(RTLD_DEFAULT, "p_scalene_done");
127 if (scalene_done == nullptr) {
128 PyErr_SetString(PyExc_Exception, "Unable to find p_whereInPython");
129 return NULL;
130 }
131 *scalene_done = false;
132 Py_RETURN_NONE;
133 }
134
135 int whereInPython(std::string& filename, int& lineno, int& bytei) {
136 if (!Py_IsInitialized()) { // No python, no python stack.
137 return 0;
138 }
139 // This function walks the Python stack until it finds a frame
140 // corresponding to a file we are actually profiling. On success,
141 // it updates filename, lineno, and byte code index appropriately,
142 // and returns 1. If the stack walk encounters no such file, it
143 // sets the filename to the pseudo-filename "<BOGUS>" for special
144 // treatment within Scalene, and returns 0.
145 filename = "<BOGUS>";
146 lineno = 1;
147 bytei = 0;
148 GIL gil;
149
150 PyThreadState* threadState = PyGILState_GetThisThreadState();
151 PyPtr<PyFrameObject> frame =
152 threadState ? PyThreadState_GetFrame(threadState) : nullptr;
153
154 if (static_cast<PyFrameObject*>(frame) == nullptr) {
155 // Various packages may create native threads; attribute what they do
156 // to what the main thread is doing, as it's likely to have requested it.
157 frame = findMainPythonThread_frame(); // note this may be nullptr
158 }
159
160 auto traceConfig = TraceConfig::getInstance();
161 if (!traceConfig) {
162 return 0;
163 }
164
165 while (static_cast<PyFrameObject*>(frame) != nullptr) {
166 PyPtr<PyCodeObject> code =
167 PyFrame_GetCode(static_cast<PyFrameObject*>(frame));
168 PyPtr<> co_filename =
169 PyUnicode_AsASCIIString(static_cast<PyCodeObject*>(code)->co_filename);
170
171 if (!(static_cast<PyObject*>(co_filename))) {
172 return 0;
173 }
174
175 auto filenameStr = PyBytes_AsString(static_cast<PyObject*>(co_filename));
176 if (filenameStr == NULL || strlen(filenameStr) == 0) {
177 continue;
178 }
179
180 if (traceConfig->should_trace(filenameStr)) {
181 #if defined(PyPy_FatalError)
182 // If this macro is defined, we are compiling PyPy, which
183 // AFAICT does not have any way to access bytecode index, so
184 // we punt and set it to 0.
185 bytei = 0;
186 #else
187 bytei = PyFrame_GetLasti(static_cast<PyFrameObject*>(frame));
188 #endif
189 lineno = PyFrame_GetLineNumber(static_cast<PyFrameObject*>(frame));
190
191 filename = filenameStr;
192 return 1;
193 }
194
195 frame = PyFrame_GetBack(static_cast<PyFrameObject*>(frame));
196 }
197 return 0;
198 }
199
200 static PyObject* register_files_to_profile(PyObject* self, PyObject* args) {
201 PyObject* a_list;
202 PyObject* base_path;
203 int profile_all;
204 if (!PyArg_ParseTuple(args, "OOp", &a_list, &base_path, &profile_all))
205 return NULL;
206 auto is_list = PyList_Check(a_list);
207 if (!is_list) {
208 PyErr_SetString(PyExc_Exception, "Requires list or list-like object");
209 return NULL;
210 }
211 TraceConfig::setInstance(new TraceConfig(a_list, base_path, profile_all));
212
213 auto p_where =
214 (decltype(p_whereInPython)*)dlsym(RTLD_DEFAULT, "p_whereInPython");
215 if (p_where == nullptr) {
216 PyErr_SetString(PyExc_Exception, "Unable to find p_whereInPython");
217 return NULL;
218 }
219 *p_where = whereInPython;
220
221 Py_RETURN_NONE;
222 }
223
224 static PyObject* print_files_to_profile(PyObject* self, PyObject* args) {
225 if (TraceConfig* pl = TraceConfig::getInstance()) {
226 pl->print();
227 }
228 Py_RETURN_NONE;
229 }
230 typedef struct {
231 PyObject* scalene_module;
232 PyObject* scalene_dict;
233 PyObject* scalene_profiler_module;
234 PyObject* scalene_class;
235 PyObject* scalene_class_dict;
236 PyObject* scalene_last_profiled;
237 PyObject* invalidate_queue;
238 PyObject* nada;
239 PyObject* zero;
240 } unchanging_modules;
241
242 static unchanging_modules module_pointers;
243
244 static bool on_stack(char* outer_filename, int lineno, PyFrameObject* frame) {
245 while (frame != NULL) {
246 int iter_lineno = PyFrame_GetLineNumber(frame);
247
248 PyPtr<PyCodeObject> code =
249 PyFrame_GetCode(static_cast<PyFrameObject*>(frame));
250
251 PyPtr<> co_filename(
252 PyUnicode_AsASCIIString(static_cast<PyCodeObject*>(code)->co_filename));
253 auto fname = PyBytes_AsString(static_cast<PyObject*>(co_filename));
254 if (iter_lineno == lineno && strstr(fname, outer_filename)) {
255 Py_XDECREF(frame);
256 return true;
257 }
258 Py_XDECREF(frame);
259 frame = PyFrame_GetBack(frame);
260 }
261 return false;
262 }
263
264 static void allocate_newline() {
265 PyPtr<> abc(PyLong_FromLong(NEWLINE_TRIGGER_LENGTH));
266 PyPtr<> tmp(PyByteArray_FromObject(static_cast<PyObject*>(abc)));
267 }
268
269 static int trace_func(PyObject* obj, PyFrameObject* frame, int what,
270 PyObject* arg) {
271 if (what == PyTrace_CALL || what == PyTrace_C_CALL) {
272 // Prior to this check, trace_func was called
273 // in every child frame. When we figured out the frame
274 // was a child of the current line, only then did we disable tracing in that frame.
275 // This was causing a major slowdown when importing pytorch-- from what we can tell,
276 // the import itself called many functions and the call overhead of the entire tracing harness
277 // was incurred for each call at least once.
278 //
279 //
280 // What we're trying to do here, though, is see if we have moved on to another line of the client program.
281 // Therefore, we can disable tracing for the moment, since one of three things has happened:
282 //
283 // 1. We have called a library function. We therefore know that there will be absolutely no important events coming from this
284 // frame, since the program can't progress to the next line before until the call has ended
285 //
286 // 2. We have called a client function. We know that the line we were on hasn't ended yet, since we would get a PyTrace_Line
287 // event if that did happen. This leaves us with one of two cases:
288 //
289 // 2.1: The function makes no allocations. Therefore, not tracing Line events in its frame is valid and the next Line
290 // we get is in the parent frame, the one that we care about
291 // 2.2: the function does make an allocation. In that case, we separately enable settrace at that allocation,
292 // so we still track it
293 //
294 //
295 // FIXME: if, in a single line, we see a pattern in a single line like allocation -> client call w/ allocation, we won't actually increment
296 // the n_mallocs counter for the line we started with
297 frame->f_trace_lines = 0;
298 frame->f_trace = NULL;
299 #if PY_VERSION_HEX >= 0x030a0000 && PY_VERSION_HEX < 0x030c0000
300 // This pre-3.12 optimization only exists post 3.9
301 PyThreadState* tstate = PyThreadState_Get();
302 tstate->cframe->use_tracing = 0;
303 #endif
304
305 }
306 if (what != PyTrace_LINE) {
307 return 0;
308 }
309 auto cast_frame = static_cast<PyFrameType*>(frame);
310 int lineno = PyFrame_GetLineNumber(frame);
311
312 PyPtr<PyCodeObject> code(PyFrame_GetCode(static_cast<PyFrameObject*>(frame)));
313 // Take ownership of these right now
314 PyObject* last_fname(PyList_GetItem(
315 static_cast<PyObject*>(module_pointers.scalene_last_profiled), 0));
316 Py_IncRef(last_fname);
317 PyObject* last_lineno(PyList_GetItem(
318 static_cast<PyObject*>(module_pointers.scalene_last_profiled), 1));
319 Py_IncRef(last_lineno);
320 auto lineno_l = PyLong_AsLong(static_cast<PyObject*>(last_lineno));
321 if (lineno == lineno_l &&
322 PyUnicode_Compare(static_cast<PyObject*>(last_fname),
323 static_cast<PyCodeObject*>(code)->co_filename) == 0) {
324 return 0;
325 }
326 PyPtr<> last_fname_unicode(PyUnicode_AsASCIIString(last_fname));
327 auto last_fname_s =
328 PyBytes_AsString(static_cast<PyObject*>(last_fname_unicode));
329 PyPtr<> co_filename(
330 PyUnicode_AsASCIIString(static_cast<PyCodeObject*>(code)->co_filename));
331
332 // Needed because decref will be called in on_stack
333 Py_INCREF(frame);
334 if (on_stack(last_fname_s, lineno_l, static_cast<PyFrameObject*>(frame))) {
335 return 0;
336 }
337
338 PyEval_SetTrace(NULL, NULL);
339 Py_IncRef(module_pointers.nada);
340 auto res = PyList_SetItem(module_pointers.scalene_last_profiled, 0,
341 module_pointers.nada);
342 Py_IncRef(module_pointers.zero);
343 res = PyList_SetItem(module_pointers.scalene_last_profiled, 1,
344 module_pointers.zero);
345
346 PyObject* last_profiled_ret(PyTuple_Pack(2, last_fname, last_lineno));
347 Py_IncRef(module_pointers.zero);
348 res = PyList_SetItem(module_pointers.scalene_last_profiled, 2,
349 module_pointers.zero);
350
351 allocate_newline();
352 last_profiled_invalidated = true;
353 Py_IncRef(last_profiled_ret);
354
355 res = PyList_Append(module_pointers.invalidate_queue, last_profiled_ret);
356
357 return 0;
358 }
359
360 static PyObject* populate_struct(PyObject* self, PyObject* args) {
361 PyObject* scalene_module(
362 PyImport_GetModule(PyUnicode_FromString("scalene"))); // New reference
363 PyObject* scalene_dict(
364 PyModule_GetDict(static_cast<PyObject*>(scalene_module)));
365 Py_IncRef(scalene_dict);
366 PyObject* scalene_profiler_module(
367 PyDict_GetItemString(scalene_dict, "scalene_profiler"));
368 Py_IncRef(scalene_profiler_module);
369 PyObject* scalene_class(PyDict_GetItemString(
370 PyModule_GetDict(scalene_profiler_module), "Scalene"));
371 Py_IncRef(scalene_class);
372 PyObject* scalene_class_dict(PyObject_GenericGetDict(scalene_class, NULL));
373 PyObject* last_profiled(
374 PyObject_GetAttrString(scalene_class, "_Scalene__last_profiled"));
375 PyObject* invalidate_queue(
376 PyObject_GetAttrString(scalene_class, "_Scalene__invalidate_queue"));
377 PyObject* zero(PyLong_FromSize_t(0));
378 PyObject* nada(PyUnicode_FromString("NADA"));
379 module_pointers = {scalene_module,
380 scalene_dict,
381 scalene_profiler_module,
382 scalene_class,
383 scalene_class_dict,
384 last_profiled,
385 invalidate_queue,
386 nada,
387 zero};
388 Py_RETURN_NONE;
389 }
390
391 static PyObject* depopulate_struct(PyObject* self, PyObject* args) {
392 auto m = module_pointers;
393 Py_DECREF(m.scalene_module);
394 Py_DECREF(m.scalene_dict);
395 Py_DECREF(m.scalene_profiler_module);
396 Py_DECREF(m.scalene_class);
397 Py_DECREF(m.scalene_class_dict);
398 Py_DECREF(m.scalene_last_profiled);
399 Py_DECREF(m.invalidate_queue);
400 Py_DECREF(m.nada);
401 Py_DECREF(m.zero);
402 module_pointers = {};
403 Py_RETURN_NONE;
404 }
405
406 static PyObject* enable_settrace(PyObject* self, PyObject* args) {
407 PyObject* frame;
408 if (!PyArg_ParseTuple(args, "O", &frame)) {
409 return NULL;
410 }
411 PyFrameObject* frame_obj = (PyFrameObject*) frame;
412 PyEval_SetTrace(trace_func, NULL);
413 frame_obj->f_trace_lines = 1;
414 Py_RETURN_NONE;
415 }
416
417 static PyObject* disable_settrace(PyObject* self, PyObject* args) {
418 PyEval_SetTrace(NULL, NULL);
419 Py_RETURN_NONE;
420 }
421
422 // static PyObject* return_buffer(PyObject* self, PyObject* args) {
423 // return PyByteArray_FromObject(PyLong_FromLong(50));
424 // }
425
426 static PyMethodDef EmbMethods[] = {
427 {"register_files_to_profile", register_files_to_profile, METH_VARARGS,
428 "Provides list of things into allocator"},
429 {"print_files_to_profile", print_files_to_profile, METH_NOARGS,
430 "printing for debug"},
431 // {"return_buffer", return_buffer, METH_NOARGS, ""},
432 {"enable_settrace", enable_settrace, METH_VARARGS, ""},
433 {"disable_settrace", disable_settrace, METH_NOARGS, ""},
434 {"populate_struct", populate_struct, METH_NOARGS, ""},
435 {"depopulate_struct", depopulate_struct, METH_NOARGS, ""},
436 {"get_last_profiled_invalidated", get_last_profiled_invalidated,
437 METH_NOARGS, ""},
438 {"set_last_profiled_invalidated_true", set_last_profiled_invalidated_true,
439 METH_NOARGS, ""},
440 {"set_last_profiled_invalidated_false", set_last_profiled_invalidated_false,
441 METH_NOARGS, ""},
442 {"set_scalene_done_true", set_scalene_done_true, METH_NOARGS, ""},
443 {"set_scalene_done_false", set_scalene_done_false, METH_NOARGS, ""},
444
445 {NULL, NULL, 0, NULL}};
446
447 static PyModuleDef EmbedModule = {PyModuleDef_HEAD_INIT,
448 "pywhere",
449 NULL,
450 -1,
451 EmbMethods,
452 NULL,
453 NULL,
454 NULL,
455 NULL};
456
457 PyMODINIT_FUNC PyInit_pywhere() { return PyModule_Create(&EmbedModule); }