Coverage Report

Created: 2025-08-26 06:26

/src/cpython/Python/instrumentation.c
Line
Count
Source (jump to first uncovered line)
1
#include "Python.h"
2
#include "pycore_bitutils.h"      // _Py_popcount32()
3
#include "pycore_call.h"          // _PyObject_VectorcallTstate()
4
#include "pycore_ceval.h"         // _PY_EVAL_EVENTS_BITS
5
#include "pycore_code.h"          // _PyCode_Clear_Executors()
6
#include "pycore_critical_section.h" // _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED()
7
#include "pycore_frame.h"         // PyFrameObject
8
#include "pycore_interpframe.h"   // _PyFrame_GetBytecode()
9
#include "pycore_long.h"          // _PyLong_GetZero()
10
#include "pycore_modsupport.h"    // _PyModule_CreateInitialized()
11
#include "pycore_namespace.h"     // _PyNamespace_New()
12
#include "pycore_opcode_metadata.h" // IS_VALID_OPCODE()
13
#include "pycore_opcode_utils.h"  // IS_CONDITIONAL_JUMP_OPCODE()
14
#include "pycore_optimizer.h"     // _PyExecutorObject
15
#include "pycore_pyatomic_ft_wrappers.h" // FT_ATOMIC_STORE_UINTPTR_RELEASE()
16
#include "pycore_pystate.h"       // _PyInterpreterState_GET()
17
#include "pycore_runtime_structs.h" // _PyCoMonitoringData
18
#include "pycore_tuple.h"         // _PyTuple_FromArraySteal()
19
20
#include "opcode_ids.h"
21
22
23
/* Uncomment this to dump debugging output when assertions fail */
24
// #define INSTRUMENT_DEBUG 1
25
26
#if defined(Py_DEBUG) && defined(Py_GIL_DISABLED)
27
28
#define ASSERT_WORLD_STOPPED_OR_LOCKED(obj)                         \
29
    if (!_PyInterpreterState_GET()->stoptheworld.world_stopped) {   \
30
        _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(obj);             \
31
    }
32
#define ASSERT_WORLD_STOPPED() assert(_PyInterpreterState_GET()->stoptheworld.world_stopped);
33
34
#else
35
36
#define ASSERT_WORLD_STOPPED_OR_LOCKED(obj)
37
#define ASSERT_WORLD_STOPPED()
38
39
#endif
40
41
#ifdef Py_GIL_DISABLED
42
43
#define LOCK_CODE(code)                                             \
44
    assert(!_PyInterpreterState_GET()->stoptheworld.world_stopped); \
45
    Py_BEGIN_CRITICAL_SECTION(code)
46
47
#define UNLOCK_CODE()   Py_END_CRITICAL_SECTION()
48
49
#define MODIFY_BYTECODE(code, func, ...)                       \
50
    do {                                                       \
51
        PyCodeObject *co = (code);                             \
52
        for (Py_ssize_t i = 0; i < code->co_tlbc->size; i++) { \
53
            char *bc = co->co_tlbc->entries[i];                \
54
            if (bc == NULL) {                                  \
55
                continue;                                      \
56
            }                                                  \
57
            (func)(code, (_Py_CODEUNIT *)bc, __VA_ARGS__);           \
58
        }                                                      \
59
    } while (0)
60
61
#else
62
63
#define LOCK_CODE(code)
64
#define UNLOCK_CODE()
65
#define MODIFY_BYTECODE(code, func, ...) \
66
0
    (func)(code, _PyCode_CODE(code), __VA_ARGS__)
67
68
#endif
69
70
PyObject _PyInstrumentation_DISABLE = _PyObject_HEAD_INIT(&PyBaseObject_Type);
71
72
PyObject _PyInstrumentation_MISSING = _PyObject_HEAD_INIT(&PyBaseObject_Type);
73
74
static const int8_t EVENT_FOR_OPCODE[256] = {
75
    [RETURN_VALUE] = PY_MONITORING_EVENT_PY_RETURN,
76
    [INSTRUMENTED_RETURN_VALUE] = PY_MONITORING_EVENT_PY_RETURN,
77
    [CALL] = PY_MONITORING_EVENT_CALL,
78
    [INSTRUMENTED_CALL] = PY_MONITORING_EVENT_CALL,
79
    [CALL_KW] = PY_MONITORING_EVENT_CALL,
80
    [INSTRUMENTED_CALL_KW] = PY_MONITORING_EVENT_CALL,
81
    [CALL_FUNCTION_EX] = PY_MONITORING_EVENT_CALL,
82
    [INSTRUMENTED_CALL_FUNCTION_EX] = PY_MONITORING_EVENT_CALL,
83
    [LOAD_SUPER_ATTR] = PY_MONITORING_EVENT_CALL,
84
    [INSTRUMENTED_LOAD_SUPER_ATTR] = PY_MONITORING_EVENT_CALL,
85
    [RESUME] = -1,
86
    [YIELD_VALUE] = PY_MONITORING_EVENT_PY_YIELD,
87
    [INSTRUMENTED_YIELD_VALUE] = PY_MONITORING_EVENT_PY_YIELD,
88
    [JUMP_FORWARD] = PY_MONITORING_EVENT_JUMP,
89
    [JUMP_BACKWARD] = PY_MONITORING_EVENT_JUMP,
90
    [POP_JUMP_IF_FALSE] = PY_MONITORING_EVENT_BRANCH_RIGHT,
91
    [POP_JUMP_IF_TRUE] = PY_MONITORING_EVENT_BRANCH_RIGHT,
92
    [POP_JUMP_IF_NONE] = PY_MONITORING_EVENT_BRANCH_RIGHT,
93
    [POP_JUMP_IF_NOT_NONE] = PY_MONITORING_EVENT_BRANCH_RIGHT,
94
    [INSTRUMENTED_JUMP_FORWARD] = PY_MONITORING_EVENT_JUMP,
95
    [INSTRUMENTED_JUMP_BACKWARD] = PY_MONITORING_EVENT_JUMP,
96
    [INSTRUMENTED_POP_JUMP_IF_FALSE] = PY_MONITORING_EVENT_BRANCH_RIGHT,
97
    [INSTRUMENTED_POP_JUMP_IF_TRUE] = PY_MONITORING_EVENT_BRANCH_RIGHT,
98
    [INSTRUMENTED_POP_JUMP_IF_NONE] = PY_MONITORING_EVENT_BRANCH_RIGHT,
99
    [INSTRUMENTED_POP_JUMP_IF_NOT_NONE] = PY_MONITORING_EVENT_BRANCH_RIGHT,
100
    [FOR_ITER] = PY_MONITORING_EVENT_BRANCH_LEFT,
101
    [INSTRUMENTED_FOR_ITER] = PY_MONITORING_EVENT_BRANCH_LEFT,
102
    [POP_ITER] = PY_MONITORING_EVENT_BRANCH_RIGHT,
103
    [INSTRUMENTED_POP_ITER] = PY_MONITORING_EVENT_BRANCH_RIGHT,
104
    [END_FOR] = PY_MONITORING_EVENT_STOP_ITERATION,
105
    [INSTRUMENTED_END_FOR] = PY_MONITORING_EVENT_STOP_ITERATION,
106
    [END_SEND] = PY_MONITORING_EVENT_STOP_ITERATION,
107
    [INSTRUMENTED_END_SEND] = PY_MONITORING_EVENT_STOP_ITERATION,
108
    [NOT_TAKEN] = PY_MONITORING_EVENT_BRANCH_LEFT,
109
    [INSTRUMENTED_NOT_TAKEN] = PY_MONITORING_EVENT_BRANCH_LEFT,
110
    [END_ASYNC_FOR] = PY_MONITORING_EVENT_BRANCH_RIGHT,
111
};
112
113
static const uint8_t DE_INSTRUMENT[256] = {
114
    [INSTRUMENTED_RESUME] = RESUME,
115
    [INSTRUMENTED_RETURN_VALUE] = RETURN_VALUE,
116
    [INSTRUMENTED_CALL] = CALL,
117
    [INSTRUMENTED_CALL_KW] = CALL_KW,
118
    [INSTRUMENTED_CALL_FUNCTION_EX] = CALL_FUNCTION_EX,
119
    [INSTRUMENTED_YIELD_VALUE] = YIELD_VALUE,
120
    [INSTRUMENTED_JUMP_FORWARD] = JUMP_FORWARD,
121
    [INSTRUMENTED_JUMP_BACKWARD] = JUMP_BACKWARD,
122
    [INSTRUMENTED_POP_JUMP_IF_FALSE] = POP_JUMP_IF_FALSE,
123
    [INSTRUMENTED_POP_JUMP_IF_TRUE] = POP_JUMP_IF_TRUE,
124
    [INSTRUMENTED_POP_JUMP_IF_NONE] = POP_JUMP_IF_NONE,
125
    [INSTRUMENTED_POP_JUMP_IF_NOT_NONE] = POP_JUMP_IF_NOT_NONE,
126
    [INSTRUMENTED_FOR_ITER] = FOR_ITER,
127
    [INSTRUMENTED_POP_ITER] = POP_ITER,
128
    [INSTRUMENTED_END_FOR] = END_FOR,
129
    [INSTRUMENTED_END_SEND] = END_SEND,
130
    [INSTRUMENTED_LOAD_SUPER_ATTR] = LOAD_SUPER_ATTR,
131
    [INSTRUMENTED_NOT_TAKEN] = NOT_TAKEN,
132
    [INSTRUMENTED_END_ASYNC_FOR] = END_ASYNC_FOR,
133
};
134
135
static const uint8_t INSTRUMENTED_OPCODES[256] = {
136
    [RETURN_VALUE] = INSTRUMENTED_RETURN_VALUE,
137
    [INSTRUMENTED_RETURN_VALUE] = INSTRUMENTED_RETURN_VALUE,
138
    [CALL] = INSTRUMENTED_CALL,
139
    [INSTRUMENTED_CALL] = INSTRUMENTED_CALL,
140
    [CALL_KW] = INSTRUMENTED_CALL_KW,
141
    [INSTRUMENTED_CALL_KW] = INSTRUMENTED_CALL_KW,
142
    [CALL_FUNCTION_EX] = INSTRUMENTED_CALL_FUNCTION_EX,
143
    [INSTRUMENTED_CALL_FUNCTION_EX] = INSTRUMENTED_CALL_FUNCTION_EX,
144
    [YIELD_VALUE] = INSTRUMENTED_YIELD_VALUE,
145
    [INSTRUMENTED_YIELD_VALUE] = INSTRUMENTED_YIELD_VALUE,
146
    [RESUME] = INSTRUMENTED_RESUME,
147
    [INSTRUMENTED_RESUME] = INSTRUMENTED_RESUME,
148
    [JUMP_FORWARD] = INSTRUMENTED_JUMP_FORWARD,
149
    [INSTRUMENTED_JUMP_FORWARD] = INSTRUMENTED_JUMP_FORWARD,
150
    [JUMP_BACKWARD] = INSTRUMENTED_JUMP_BACKWARD,
151
    [INSTRUMENTED_JUMP_BACKWARD] = INSTRUMENTED_JUMP_BACKWARD,
152
    [POP_JUMP_IF_FALSE] = INSTRUMENTED_POP_JUMP_IF_FALSE,
153
    [INSTRUMENTED_POP_JUMP_IF_FALSE] = INSTRUMENTED_POP_JUMP_IF_FALSE,
154
    [POP_JUMP_IF_TRUE] = INSTRUMENTED_POP_JUMP_IF_TRUE,
155
    [INSTRUMENTED_POP_JUMP_IF_TRUE] = INSTRUMENTED_POP_JUMP_IF_TRUE,
156
    [POP_JUMP_IF_NONE] = INSTRUMENTED_POP_JUMP_IF_NONE,
157
    [INSTRUMENTED_POP_JUMP_IF_NONE] = INSTRUMENTED_POP_JUMP_IF_NONE,
158
    [POP_JUMP_IF_NOT_NONE] = INSTRUMENTED_POP_JUMP_IF_NOT_NONE,
159
    [INSTRUMENTED_POP_JUMP_IF_NOT_NONE] = INSTRUMENTED_POP_JUMP_IF_NOT_NONE,
160
    [END_FOR] = INSTRUMENTED_END_FOR,
161
    [INSTRUMENTED_END_FOR] = INSTRUMENTED_END_FOR,
162
    [END_SEND] = INSTRUMENTED_END_SEND,
163
    [INSTRUMENTED_END_SEND] = INSTRUMENTED_END_SEND,
164
    [FOR_ITER] = INSTRUMENTED_FOR_ITER,
165
    [INSTRUMENTED_FOR_ITER] = INSTRUMENTED_FOR_ITER,
166
    [POP_ITER] = INSTRUMENTED_POP_ITER,
167
    [INSTRUMENTED_POP_ITER] = INSTRUMENTED_POP_ITER,
168
    [LOAD_SUPER_ATTR] = INSTRUMENTED_LOAD_SUPER_ATTR,
169
    [INSTRUMENTED_LOAD_SUPER_ATTR] = INSTRUMENTED_LOAD_SUPER_ATTR,
170
    [NOT_TAKEN] = INSTRUMENTED_NOT_TAKEN,
171
    [INSTRUMENTED_NOT_TAKEN] = INSTRUMENTED_NOT_TAKEN,
172
    [END_ASYNC_FOR] = INSTRUMENTED_END_ASYNC_FOR,
173
    [INSTRUMENTED_END_ASYNC_FOR] = INSTRUMENTED_END_ASYNC_FOR,
174
175
    [INSTRUMENTED_LINE] = INSTRUMENTED_LINE,
176
    [INSTRUMENTED_INSTRUCTION] = INSTRUMENTED_INSTRUCTION,
177
};
178
179
static inline bool
180
opcode_has_event(int opcode)
181
0
{
182
0
    return (
183
0
        opcode != INSTRUMENTED_LINE &&
184
0
        INSTRUMENTED_OPCODES[opcode] > 0
185
0
    );
186
0
}
187
188
static inline bool
189
is_instrumented(int opcode)
190
0
{
191
0
    assert(opcode != 0);
192
0
    assert(opcode != RESERVED);
193
0
    return opcode != ENTER_EXECUTOR && opcode >= MIN_INSTRUMENTED_OPCODE;
194
0
}
195
196
#ifndef NDEBUG
197
static inline bool
198
monitors_equals(_Py_LocalMonitors a, _Py_LocalMonitors b)
199
{
200
    for (int i = 0; i < _PY_MONITORING_LOCAL_EVENTS; i++) {
201
        if (a.tools[i] != b.tools[i]) {
202
            return false;
203
        }
204
    }
205
    return true;
206
}
207
#endif
208
209
static inline _Py_LocalMonitors
210
monitors_sub(_Py_LocalMonitors a, _Py_LocalMonitors b)
211
0
{
212
0
    _Py_LocalMonitors res;
213
0
    for (int i = 0; i < _PY_MONITORING_LOCAL_EVENTS; i++) {
214
0
        res.tools[i] = a.tools[i] & ~b.tools[i];
215
0
    }
216
0
    return res;
217
0
}
218
219
#ifndef NDEBUG
220
static inline _Py_LocalMonitors
221
monitors_and(_Py_LocalMonitors a, _Py_LocalMonitors b)
222
{
223
    _Py_LocalMonitors res;
224
    for (int i = 0; i < _PY_MONITORING_LOCAL_EVENTS; i++) {
225
        res.tools[i] = a.tools[i] & b.tools[i];
226
    }
227
    return res;
228
}
229
#endif
230
231
/* The union of the *local* events in a and b.
232
 * Global events like RAISE are ignored.
233
 * Used for instrumentation, as only local
234
 * events get instrumented.
235
 */
236
static inline _Py_LocalMonitors
237
local_union(_Py_GlobalMonitors a, _Py_LocalMonitors b)
238
0
{
239
0
    _Py_LocalMonitors res;
240
0
    for (int i = 0; i < _PY_MONITORING_LOCAL_EVENTS; i++) {
241
0
        res.tools[i] = a.tools[i] | b.tools[i];
242
0
    }
243
0
    return res;
244
0
}
245
246
static inline bool
247
monitors_are_empty(_Py_LocalMonitors m)
248
0
{
249
0
    for (int i = 0; i < _PY_MONITORING_LOCAL_EVENTS; i++) {
250
0
        if (m.tools[i]) {
251
0
            return false;
252
0
        }
253
0
    }
254
0
    return true;
255
0
}
256
257
static inline bool
258
multiple_tools(_Py_LocalMonitors *m)
259
0
{
260
0
    for (int i = 0; i < _PY_MONITORING_LOCAL_EVENTS; i++) {
261
0
        if (_Py_popcount32(m->tools[i]) > 1) {
262
0
            return true;
263
0
        }
264
0
    }
265
0
    return false;
266
0
}
267
268
static inline _PyMonitoringEventSet
269
get_local_events(_Py_LocalMonitors *m, int tool_id)
270
0
{
271
0
    _PyMonitoringEventSet result = 0;
272
0
    for (int e = 0; e < _PY_MONITORING_LOCAL_EVENTS; e++) {
273
0
        if ((m->tools[e] >> tool_id) & 1) {
274
0
            result |= (1 << e);
275
0
        }
276
0
    }
277
0
    return result;
278
0
}
279
280
static inline _PyMonitoringEventSet
281
get_events(_Py_GlobalMonitors *m, int tool_id)
282
0
{
283
0
    _PyMonitoringEventSet result = 0;
284
0
    for (int e = 0; e < _PY_MONITORING_UNGROUPED_EVENTS; e++) {
285
0
        if ((m->tools[e] >> tool_id) & 1) {
286
0
            result |= (1 << e);
287
0
        }
288
0
    }
289
0
    return result;
290
0
}
291
292
/* Module code can have line 0, even though modules start at line 1,
293
 * so -1 is a legal delta. */
294
0
#define NO_LINE (-2)
295
296
/* Returns the line delta. Defined as:
297
 * if line is None:
298
 *     line_delta = NO_LINE
299
 * else:
300
 *     line_delta = line - first_line
301
 */
302
static int
303
compute_line_delta(PyCodeObject *code, int line)
304
0
{
305
0
    if (line < 0) {
306
0
        assert(line == -1);
307
0
        return NO_LINE;
308
0
    }
309
0
    int delta = line - code->co_firstlineno;
310
0
    assert(delta > NO_LINE);
311
0
    return delta;
312
0
}
313
314
static int
315
compute_line(PyCodeObject *code, int line_delta)
316
0
{
317
0
    if (line_delta == NO_LINE) {
318
0
        return -1;
319
0
    }
320
0
    assert(line_delta > NO_LINE);
321
0
    return code->co_firstlineno + line_delta;
322
0
}
323
324
int
325
_PyInstruction_GetLength(PyCodeObject *code, int offset)
326
0
{
327
0
    ASSERT_WORLD_STOPPED_OR_LOCKED(code);
328
329
0
    _Py_CODEUNIT inst = _Py_GetBaseCodeUnit(code, offset);
330
0
    return 1 + _PyOpcode_Caches[inst.op.code];
331
0
}
332
333
static inline uint8_t
334
get_original_opcode(_PyCoLineInstrumentationData *line_data, int index)
335
0
{
336
0
    return line_data->data[index*line_data->bytes_per_entry];
337
0
}
338
339
static inline uint8_t *
340
get_original_opcode_ptr(_PyCoLineInstrumentationData *line_data, int index)
341
0
{
342
0
    return &line_data->data[index*line_data->bytes_per_entry];
343
0
}
344
345
static inline void
346
set_original_opcode(_PyCoLineInstrumentationData *line_data, int index, uint8_t opcode)
347
0
{
348
0
    line_data->data[index*line_data->bytes_per_entry] = opcode;
349
0
}
350
351
static inline int
352
get_line_delta(_PyCoLineInstrumentationData *line_data, int index)
353
0
{
354
0
    uint8_t *ptr = &line_data->data[index*line_data->bytes_per_entry+1];
355
0
    assert(line_data->bytes_per_entry >= 2);
356
0
    uint32_t value = *ptr;
357
0
    for (int idx = 2; idx < line_data->bytes_per_entry; idx++) {
358
0
        ptr++;
359
0
        int shift = (idx-1)*8;
360
0
        value |= ((uint32_t)(*ptr)) << shift;
361
0
    }
362
0
    assert(value < INT_MAX);
363
    /* NO_LINE is stored as zero. */
364
0
    return ((int)value) + NO_LINE;
365
0
}
366
367
static inline void
368
set_line_delta(_PyCoLineInstrumentationData *line_data, int index, int line_delta)
369
0
{
370
    /* Store line_delta + 2 as we need -2 to represent no line number */
371
0
    assert(line_delta >= NO_LINE);
372
0
    uint32_t adjusted = line_delta - NO_LINE;
373
0
    uint8_t *ptr = &line_data->data[index*line_data->bytes_per_entry+1];
374
0
    assert(adjusted < (1ULL << ((line_data->bytes_per_entry-1)*8)));
375
0
    assert(line_data->bytes_per_entry >= 2);
376
0
    *ptr = adjusted & 0xff;
377
0
    for (int idx = 2; idx < line_data->bytes_per_entry; idx++) {
378
0
        ptr++;
379
0
        adjusted >>= 8;
380
0
        *ptr = adjusted & 0xff;
381
0
    }
382
0
}
383
384
#ifdef INSTRUMENT_DEBUG
385
386
static void
387
dump_instrumentation_data_tools(PyCodeObject *code, uint8_t *tools, int i, FILE*out)
388
{
389
    if (tools == NULL) {
390
        fprintf(out, "tools = NULL");
391
    }
392
    else {
393
        fprintf(out, "tools = %d", tools[i]);
394
    }
395
}
396
397
static void
398
dump_instrumentation_data_lines(PyCodeObject *code, _PyCoLineInstrumentationData *lines, int i, FILE*out)
399
{
400
    if (lines == NULL) {
401
        fprintf(out, ", lines = NULL");
402
    }
403
    else {
404
        int opcode = get_original_opcode(lines, i);
405
        int line_delta = get_line_delta(lines, i);
406
        if (opcode == 0) {
407
            fprintf(out, ", lines = {original_opcode = No LINE (0), line_delta = %d)", line_delta);
408
        }
409
        else {
410
            fprintf(out, ", lines = {original_opcode = %s, line_delta = %d)", _PyOpcode_OpName[opcode], line_delta);
411
        }
412
    }
413
}
414
415
static void
416
dump_instrumentation_data_line_tools(PyCodeObject *code, uint8_t *line_tools, int i, FILE*out)
417
{
418
    if (line_tools == NULL) {
419
        fprintf(out, ", line_tools = NULL");
420
    }
421
    else {
422
        fprintf(out, ", line_tools = %d", line_tools[i]);
423
    }
424
}
425
426
static void
427
dump_instrumentation_data_per_instruction(PyCodeObject *code, _PyCoMonitoringData *data, int i, FILE*out)
428
{
429
    if (data->per_instruction_opcodes == NULL) {
430
        fprintf(out, ", per-inst opcode = NULL");
431
    }
432
    else {
433
        fprintf(out, ", per-inst opcode = %s", _PyOpcode_OpName[data->per_instruction_opcodes[i]]);
434
    }
435
    if (data->per_instruction_tools == NULL) {
436
        fprintf(out, ", per-inst tools = NULL");
437
    }
438
    else {
439
        fprintf(out, ", per-inst tools = %d", data->per_instruction_tools[i]);
440
    }
441
}
442
443
static void
444
dump_global_monitors(const char *prefix, _Py_GlobalMonitors monitors, FILE*out)
445
{
446
    fprintf(out, "%s monitors:\n", prefix);
447
    for (int event = 0; event < _PY_MONITORING_UNGROUPED_EVENTS; event++) {
448
        fprintf(out, "    Event %d: Tools %x\n", event, monitors.tools[event]);
449
    }
450
}
451
452
static void
453
dump_local_monitors(const char *prefix, _Py_LocalMonitors monitors, FILE*out)
454
{
455
    fprintf(out, "%s monitors:\n", prefix);
456
    for (int event = 0; event < _PY_MONITORING_LOCAL_EVENTS; event++) {
457
        fprintf(out, "    Event %d: Tools %x\n", event, monitors.tools[event]);
458
    }
459
}
460
461
/** NOTE:
462
 * Do not use PyCode_Addr2Line to determine the line number in instrumentation,
463
 * as `PyCode_Addr2Line` uses the monitoring data if it is available.
464
 */
465
466
467
/* No error checking -- Don't use this for anything but experimental debugging */
468
static void
469
dump_instrumentation_data(PyCodeObject *code, int star, FILE*out)
470
{
471
    _PyCoMonitoringData *data = code->_co_monitoring;
472
    fprintf(out, "\n");
473
    PyObject_Print(code->co_name, out, Py_PRINT_RAW);
474
    fprintf(out, "\n");
475
    if (data == NULL) {
476
        fprintf(out, "NULL\n");
477
        return;
478
    }
479
    dump_global_monitors("Global", _PyInterpreterState_GET()->monitors, out);
480
    dump_local_monitors("Code", data->local_monitors, out);
481
    dump_local_monitors("Active", data->active_monitors, out);
482
    int code_len = (int)Py_SIZE(code);
483
    bool starred = false;
484
    PyCodeAddressRange range;
485
    _PyCode_InitAddressRange(code, &range);
486
    for (int i = 0; i < code_len; i += _PyInstruction_GetLength(code, i)) {
487
        _Py_CODEUNIT *instr = &_PyCode_CODE(code)[i];
488
        int opcode = instr->op.code;
489
        if (i == star) {
490
            fprintf(out, "**  ");
491
            starred = true;
492
        }
493
        fprintf(out, "Offset: %d, line: %d %s: ", i, _PyCode_CheckLineNumber(i*2, &range), _PyOpcode_OpName[opcode]);
494
        dump_instrumentation_data_tools(code, data->tools, i, out);
495
        dump_instrumentation_data_lines(code, data->lines, i, out);
496
        dump_instrumentation_data_line_tools(code, data->line_tools, i, out);
497
        dump_instrumentation_data_per_instruction(code, data, i, out);
498
        fprintf(out, "\n");
499
        ;
500
    }
501
    if (!starred && star >= 0) {
502
        fprintf(out, "Error offset not at valid instruction offset: %d\n", star);
503
        fprintf(out, "    ");
504
        dump_instrumentation_data_tools(code, data->tools, star, out);
505
        dump_instrumentation_data_lines(code, data->lines, star, out);
506
        dump_instrumentation_data_line_tools(code, data->line_tools, star, out);
507
        dump_instrumentation_data_per_instruction(code, data, star, out);
508
        fprintf(out, "\n");
509
    }
510
}
511
512
#define CHECK(test) do { \
513
    if (!(test)) { \
514
        dump_instrumentation_data(code, i, stderr); \
515
    } \
516
    assert(test); \
517
} while (0)
518
519
static bool
520
valid_opcode(int opcode)
521
{
522
    if (opcode == INSTRUMENTED_LINE) {
523
        return true;
524
    }
525
    if (IS_VALID_OPCODE(opcode) &&
526
        opcode != CACHE &&
527
        opcode != RESERVED &&
528
        opcode < 255)
529
    {
530
       return true;
531
    }
532
    return false;
533
}
534
535
static void
536
sanity_check_instrumentation(PyCodeObject *code)
537
{
538
    ASSERT_WORLD_STOPPED_OR_LOCKED(code);
539
540
    _PyCoMonitoringData *data = code->_co_monitoring;
541
    if (data == NULL) {
542
        return;
543
    }
544
    _Py_GlobalMonitors global_monitors = _PyInterpreterState_GET()->monitors;
545
    _Py_LocalMonitors active_monitors;
546
    if (code->_co_monitoring) {
547
        _Py_LocalMonitors local_monitors = code->_co_monitoring->local_monitors;
548
        active_monitors = local_union(global_monitors, local_monitors);
549
    }
550
    else {
551
        _Py_LocalMonitors empty = (_Py_LocalMonitors) { 0 };
552
        active_monitors = local_union(global_monitors, empty);
553
    }
554
    assert(monitors_equals(
555
        code->_co_monitoring->active_monitors,
556
        active_monitors));
557
    int code_len = (int)Py_SIZE(code);
558
    PyCodeAddressRange range;
559
    _PyCode_InitAddressRange(co, &range);
560
    for (int i = 0; i < code_len;) {
561
        _Py_CODEUNIT *instr = &_PyCode_CODE(code)[i];
562
        int opcode = instr->op.code;
563
        int base_opcode = _Py_GetBaseCodeUnit(code, i).op.code;
564
        CHECK(valid_opcode(opcode));
565
        CHECK(valid_opcode(base_opcode));
566
        if (opcode == INSTRUMENTED_INSTRUCTION) {
567
            opcode = data->per_instruction_opcodes[i];
568
            if (!is_instrumented(opcode)) {
569
                CHECK(_PyOpcode_Deopt[opcode] == opcode);
570
            }
571
        }
572
        if (opcode == INSTRUMENTED_LINE) {
573
            CHECK(data->lines);
574
            opcode = get_original_opcode(data->lines, i);
575
            CHECK(valid_opcode(opcode));
576
            CHECK(opcode != END_FOR);
577
            CHECK(opcode != RESUME);
578
            CHECK(opcode != RESUME_CHECK);
579
            CHECK(opcode != INSTRUMENTED_RESUME);
580
            if (!is_instrumented(opcode)) {
581
                CHECK(_PyOpcode_Deopt[opcode] == opcode);
582
            }
583
            CHECK(opcode != INSTRUMENTED_LINE);
584
        }
585
        else if (data->lines) {
586
            /* If original_opcode is INSTRUMENTED_INSTRUCTION
587
             * *and* we are executing a INSTRUMENTED_LINE instruction
588
             * that has de-instrumented itself, then we will execute
589
             * an invalid INSTRUMENTED_INSTRUCTION */
590
            CHECK(get_original_opcode(data->lines, i) != INSTRUMENTED_INSTRUCTION);
591
        }
592
        if (opcode == INSTRUMENTED_INSTRUCTION) {
593
            CHECK(data->per_instruction_opcodes[i] != 0);
594
            opcode = data->per_instruction_opcodes[i];
595
        }
596
        if (is_instrumented(opcode)) {
597
            CHECK(DE_INSTRUMENT[opcode] == base_opcode);
598
            int event = EVENT_FOR_OPCODE[DE_INSTRUMENT[opcode]];
599
            if (event < 0) {
600
                /* RESUME fixup */
601
                event = instr->op.arg ? 1: 0;
602
            }
603
            CHECK(active_monitors.tools[event] != 0);
604
        }
605
        if (data->lines && get_original_opcode(data->lines, i)) {
606
            int line1 = compute_line(code, get_line_delta(data->lines, i));
607
            int line2 = _PyCode_CheckLineNumber(i*sizeof(_Py_CODEUNIT), &range);
608
            CHECK(line1 == line2);
609
        }
610
        CHECK(valid_opcode(opcode));
611
        if (data->tools) {
612
            uint8_t local_tools = data->tools[i];
613
            if (opcode_has_event(base_opcode)) {
614
                int event = EVENT_FOR_OPCODE[base_opcode];
615
                if (event == -1) {
616
                    /* RESUME fixup */
617
                    event = _PyCode_CODE(code)[i].op.arg;
618
                }
619
                CHECK((active_monitors.tools[event] & local_tools) == local_tools);
620
            }
621
            else {
622
                CHECK(local_tools == 0xff);
623
            }
624
        }
625
        i += _PyInstruction_GetLength(code, i);
626
        assert(i <= code_len);
627
    }
628
}
629
#else
630
631
0
#define CHECK(test) assert(test)
632
633
#endif
634
635
/* Get the underlying code unit, stripping instrumentation and ENTER_EXECUTOR */
636
_Py_CODEUNIT
637
_Py_GetBaseCodeUnit(PyCodeObject *code, int i)
638
1.65M
{
639
1.65M
    _Py_CODEUNIT *src_instr = _PyCode_CODE(code) + i;
640
1.65M
    _Py_CODEUNIT inst = {
641
1.65M
        .cache = FT_ATOMIC_LOAD_UINT16_RELAXED(*(uint16_t *)src_instr)};
642
1.65M
    int opcode = inst.op.code;
643
1.65M
    if (opcode < MIN_INSTRUMENTED_OPCODE) {
644
1.65M
        inst.op.code = _PyOpcode_Deopt[opcode];
645
1.65M
        assert(inst.op.code < MIN_SPECIALIZED_OPCODE);
646
1.65M
        return inst;
647
1.65M
    }
648
0
    if (opcode == ENTER_EXECUTOR) {
649
0
        _PyExecutorObject *exec = code->co_executors->executors[inst.op.arg];
650
0
        opcode = _PyOpcode_Deopt[exec->vm_data.opcode];
651
0
        inst.op.code = opcode;
652
0
        inst.op.arg = exec->vm_data.oparg;
653
0
        assert(inst.op.code < MIN_SPECIALIZED_OPCODE);
654
0
        return inst;
655
0
    }
656
0
    if (opcode == INSTRUMENTED_LINE) {
657
0
        opcode = get_original_opcode(code->_co_monitoring->lines, i);
658
0
    }
659
0
    if (opcode == INSTRUMENTED_INSTRUCTION) {
660
0
        opcode = code->_co_monitoring->per_instruction_opcodes[i];
661
0
    }
662
0
    CHECK(opcode != INSTRUMENTED_INSTRUCTION);
663
0
    CHECK(opcode != INSTRUMENTED_LINE);
664
0
    int deinstrumented = DE_INSTRUMENT[opcode];
665
0
    if (deinstrumented) {
666
0
        inst.op.code = deinstrumented;
667
0
    }
668
0
    else {
669
0
        inst.op.code = _PyOpcode_Deopt[opcode];
670
0
    }
671
0
    assert(inst.op.code < MIN_SPECIALIZED_OPCODE);
672
0
    return inst;
673
0
}
674
675
static void
676
de_instrument(PyCodeObject *code, _Py_CODEUNIT *bytecode, _PyCoMonitoringData *monitoring, int i,
677
              int event)
678
0
{
679
0
    assert(event != PY_MONITORING_EVENT_INSTRUCTION);
680
0
    assert(event != PY_MONITORING_EVENT_LINE);
681
682
0
    _Py_CODEUNIT *instr = &bytecode[i];
683
0
    uint8_t *opcode_ptr = &instr->op.code;
684
0
    int opcode = *opcode_ptr;
685
0
    assert(opcode != ENTER_EXECUTOR);
686
0
    if (opcode == INSTRUMENTED_LINE) {
687
0
        opcode_ptr = get_original_opcode_ptr(monitoring->lines, i);
688
0
        opcode = *opcode_ptr;
689
0
    }
690
0
    if (opcode == INSTRUMENTED_INSTRUCTION) {
691
0
        opcode_ptr = &monitoring->per_instruction_opcodes[i];
692
0
        opcode = *opcode_ptr;
693
0
    }
694
0
    int deinstrumented = DE_INSTRUMENT[opcode];
695
0
    if (deinstrumented == 0) {
696
0
        return;
697
0
    }
698
0
    CHECK(_PyOpcode_Deopt[deinstrumented] == deinstrumented);
699
0
    FT_ATOMIC_STORE_UINT8_RELAXED(*opcode_ptr, deinstrumented);
700
0
    if (_PyOpcode_Caches[deinstrumented]) {
701
0
        FT_ATOMIC_STORE_UINT16_RELAXED(instr[1].counter.value_and_backoff,
702
0
                                       adaptive_counter_warmup().value_and_backoff);
703
0
    }
704
0
}
705
706
static void
707
de_instrument_line(PyCodeObject *code, _Py_CODEUNIT *bytecode, _PyCoMonitoringData *monitoring,
708
                   int i)
709
0
{
710
0
    _Py_CODEUNIT *instr = &bytecode[i];
711
0
    int opcode = instr->op.code;
712
0
    if (opcode != INSTRUMENTED_LINE) {
713
0
        return;
714
0
    }
715
0
    _PyCoLineInstrumentationData *lines = monitoring->lines;
716
0
    int original_opcode = get_original_opcode(lines, i);
717
0
    if (original_opcode == INSTRUMENTED_INSTRUCTION) {
718
0
        set_original_opcode(lines, i, monitoring->per_instruction_opcodes[i]);
719
0
    }
720
0
    CHECK(original_opcode != 0);
721
0
    CHECK(original_opcode == _PyOpcode_Deopt[original_opcode]);
722
0
    FT_ATOMIC_STORE_UINT8(instr->op.code, original_opcode);
723
0
    if (_PyOpcode_Caches[original_opcode]) {
724
0
        FT_ATOMIC_STORE_UINT16_RELAXED(instr[1].counter.value_and_backoff,
725
0
                                       adaptive_counter_warmup().value_and_backoff);
726
0
    }
727
0
    assert(instr->op.code != INSTRUMENTED_LINE);
728
0
}
729
730
static void
731
de_instrument_per_instruction(PyCodeObject *code, _Py_CODEUNIT *bytecode,
732
                              _PyCoMonitoringData *monitoring, int i)
733
0
{
734
0
    _Py_CODEUNIT *instr = &bytecode[i];
735
0
    uint8_t *opcode_ptr = &instr->op.code;
736
0
    int opcode = *opcode_ptr;
737
0
    if (opcode == INSTRUMENTED_LINE) {
738
0
        opcode_ptr = get_original_opcode_ptr(monitoring->lines, i);
739
0
        opcode = *opcode_ptr;
740
0
    }
741
0
    if (opcode != INSTRUMENTED_INSTRUCTION) {
742
0
        return;
743
0
    }
744
0
    int original_opcode = monitoring->per_instruction_opcodes[i];
745
0
    CHECK(original_opcode != 0);
746
0
    CHECK(original_opcode == _PyOpcode_Deopt[original_opcode]);
747
0
    FT_ATOMIC_STORE_UINT8_RELAXED(*opcode_ptr, original_opcode);
748
0
    if (_PyOpcode_Caches[original_opcode]) {
749
0
        FT_ATOMIC_STORE_UINT16_RELAXED(instr[1].counter.value_and_backoff,
750
0
                                       adaptive_counter_warmup().value_and_backoff);
751
0
    }
752
0
    assert(*opcode_ptr != INSTRUMENTED_INSTRUCTION);
753
0
    assert(instr->op.code != INSTRUMENTED_INSTRUCTION);
754
0
}
755
756
static void
757
instrument(PyCodeObject *code, _Py_CODEUNIT *bytecode, _PyCoMonitoringData *monitoring, int i)
758
0
{
759
0
    _Py_CODEUNIT *instr = &bytecode[i];
760
0
    uint8_t *opcode_ptr = &instr->op.code;
761
0
    int opcode =*opcode_ptr;
762
0
    if (opcode == INSTRUMENTED_LINE) {
763
0
        opcode_ptr = get_original_opcode_ptr(monitoring->lines, i);
764
0
        opcode = *opcode_ptr;
765
0
    }
766
0
    if (opcode == INSTRUMENTED_INSTRUCTION) {
767
0
        opcode_ptr = &monitoring->per_instruction_opcodes[i];
768
0
        opcode = *opcode_ptr;
769
0
        CHECK(opcode != INSTRUMENTED_INSTRUCTION && opcode != INSTRUMENTED_LINE);
770
0
        CHECK(opcode == _PyOpcode_Deopt[opcode]);
771
0
    }
772
0
    CHECK(opcode != 0);
773
0
    if (!is_instrumented(opcode)) {
774
0
        int deopt = _PyOpcode_Deopt[opcode];
775
0
        int instrumented = INSTRUMENTED_OPCODES[deopt];
776
0
        assert(instrumented);
777
0
        FT_ATOMIC_STORE_UINT8_RELAXED(*opcode_ptr, instrumented);
778
0
        if (_PyOpcode_Caches[deopt]) {
779
0
            FT_ATOMIC_STORE_UINT16_RELAXED(instr[1].counter.value_and_backoff,
780
0
                                           adaptive_counter_warmup().value_and_backoff);
781
0
        }
782
0
    }
783
0
}
784
785
static void
786
instrument_line(PyCodeObject *code, _Py_CODEUNIT *bytecode, _PyCoMonitoringData *monitoring, int i)
787
0
{
788
0
    uint8_t *opcode_ptr = &bytecode[i].op.code;
789
0
    int opcode = *opcode_ptr;
790
0
    if (opcode == INSTRUMENTED_LINE) {
791
0
        return;
792
0
    }
793
0
    set_original_opcode(monitoring->lines, i, _PyOpcode_Deopt[opcode]);
794
0
    CHECK(get_line_delta(monitoring->lines, i) > NO_LINE);
795
0
    FT_ATOMIC_STORE_UINT8_RELAXED(*opcode_ptr, INSTRUMENTED_LINE);
796
0
}
797
798
static void
799
instrument_per_instruction(PyCodeObject *code, _Py_CODEUNIT *bytecode,
800
                           _PyCoMonitoringData *monitoring, int i)
801
0
{
802
0
    _Py_CODEUNIT *instr = &bytecode[i];
803
0
    uint8_t *opcode_ptr = &instr->op.code;
804
0
    int opcode = *opcode_ptr;
805
0
    if (opcode == INSTRUMENTED_LINE) {
806
0
        opcode_ptr = get_original_opcode_ptr(monitoring->lines, i);
807
0
        opcode = *opcode_ptr;
808
0
    }
809
0
    if (opcode == INSTRUMENTED_INSTRUCTION) {
810
0
        assert(monitoring->per_instruction_opcodes[i] > 0);
811
0
        return;
812
0
    }
813
0
    CHECK(opcode != 0);
814
0
    if (is_instrumented(opcode)) {
815
0
        monitoring->per_instruction_opcodes[i] = opcode;
816
0
    }
817
0
    else {
818
0
        assert(opcode != 0);
819
0
        assert(_PyOpcode_Deopt[opcode] != 0);
820
0
        assert(_PyOpcode_Deopt[opcode] != RESUME);
821
0
        monitoring->per_instruction_opcodes[i] = _PyOpcode_Deopt[opcode];
822
0
    }
823
0
    assert(monitoring->per_instruction_opcodes[i] > 0);
824
0
    FT_ATOMIC_STORE_UINT8_RELAXED(*opcode_ptr, INSTRUMENTED_INSTRUCTION);
825
0
}
826
827
static void
828
remove_tools(PyCodeObject * code, int offset, int event, int tools)
829
0
{
830
0
    ASSERT_WORLD_STOPPED_OR_LOCKED(code);
831
0
    assert(event != PY_MONITORING_EVENT_LINE);
832
0
    assert(event != PY_MONITORING_EVENT_INSTRUCTION);
833
0
    assert(PY_MONITORING_IS_INSTRUMENTED_EVENT(event));
834
0
    assert(opcode_has_event(_Py_GetBaseCodeUnit(code, offset).op.code));
835
0
    _PyCoMonitoringData *monitoring = code->_co_monitoring;
836
0
    assert(monitoring);
837
0
    bool should_de_instrument;
838
0
    if (monitoring->tools) {
839
0
        monitoring->tools[offset] &= ~tools;
840
0
        should_de_instrument = (monitoring->tools[offset] == 0);
841
0
    }
842
0
    else {
843
        /* Single tool */
844
0
        uint8_t single_tool = monitoring->active_monitors.tools[event];
845
0
        assert(_Py_popcount32(single_tool) <= 1);
846
0
        should_de_instrument = ((single_tool & tools) == single_tool);
847
0
    }
848
0
    if (should_de_instrument) {
849
0
        MODIFY_BYTECODE(code, de_instrument, monitoring, offset, event);
850
0
    }
851
0
}
852
853
#ifndef NDEBUG
854
static bool
855
tools_is_subset_for_event(PyCodeObject * code, int event, int tools)
856
{
857
    int global_tools = _PyInterpreterState_GET()->monitors.tools[event];
858
    int local_tools = code->_co_monitoring->local_monitors.tools[event];
859
    return tools == ((global_tools | local_tools) & tools);
860
}
861
#endif
862
863
static void
864
remove_line_tools(PyCodeObject * code, int offset, int tools)
865
0
{
866
0
    ASSERT_WORLD_STOPPED_OR_LOCKED(code);
867
868
0
    _PyCoMonitoringData *monitoring = code->_co_monitoring;
869
0
    assert(monitoring);
870
0
    bool should_de_instrument;
871
0
    if (monitoring->line_tools)
872
0
    {
873
0
        uint8_t *toolsptr = &monitoring->line_tools[offset];
874
0
        *toolsptr &= ~tools;
875
0
        should_de_instrument = (*toolsptr == 0);
876
0
    }
877
0
    else {
878
        /* Single tool */
879
0
        uint8_t single_tool = monitoring->active_monitors.tools[PY_MONITORING_EVENT_LINE];
880
0
        assert(_Py_popcount32(single_tool) <= 1);
881
0
        should_de_instrument = ((single_tool & tools) == single_tool);
882
0
    }
883
0
    if (should_de_instrument) {
884
0
        MODIFY_BYTECODE(code, de_instrument_line, monitoring, offset);
885
0
    }
886
0
}
887
888
static void
889
add_tools(PyCodeObject * code, int offset, int event, int tools)
890
0
{
891
0
    ASSERT_WORLD_STOPPED_OR_LOCKED(code);
892
0
    assert(event != PY_MONITORING_EVENT_LINE);
893
0
    assert(event != PY_MONITORING_EVENT_INSTRUCTION);
894
0
    assert(PY_MONITORING_IS_INSTRUMENTED_EVENT(event));
895
0
    assert(code->_co_monitoring);
896
0
    if (code->_co_monitoring &&
897
0
        code->_co_monitoring->tools
898
0
    ) {
899
0
        code->_co_monitoring->tools[offset] |= tools;
900
0
    }
901
0
    else {
902
        /* Single tool */
903
0
        assert(_Py_popcount32(tools) == 1);
904
0
        assert(tools_is_subset_for_event(code, event, tools));
905
0
    }
906
0
    MODIFY_BYTECODE(code, instrument, code->_co_monitoring, offset);
907
0
}
908
909
static void
910
add_line_tools(PyCodeObject * code, int offset, int tools)
911
0
{
912
0
    ASSERT_WORLD_STOPPED_OR_LOCKED(code);
913
914
0
    assert(tools_is_subset_for_event(code, PY_MONITORING_EVENT_LINE, tools));
915
0
    assert(code->_co_monitoring);
916
0
    if (code->_co_monitoring->line_tools) {
917
0
        code->_co_monitoring->line_tools[offset] |= tools;
918
0
    }
919
0
    else {
920
        /* Single tool */
921
0
        assert(_Py_popcount32(tools) == 1);
922
0
    }
923
0
    MODIFY_BYTECODE(code, instrument_line, code->_co_monitoring, offset);
924
0
}
925
926
927
static void
928
add_per_instruction_tools(PyCodeObject * code, int offset, int tools)
929
0
{
930
0
    ASSERT_WORLD_STOPPED_OR_LOCKED(code);
931
932
0
    assert(tools_is_subset_for_event(code, PY_MONITORING_EVENT_INSTRUCTION, tools));
933
0
    assert(code->_co_monitoring);
934
0
    if (code->_co_monitoring->per_instruction_tools) {
935
0
        code->_co_monitoring->per_instruction_tools[offset] |= tools;
936
0
    }
937
0
    else {
938
        /* Single tool */
939
0
        assert(_Py_popcount32(tools) == 1);
940
0
    }
941
0
    MODIFY_BYTECODE(code, instrument_per_instruction, code->_co_monitoring, offset);
942
0
}
943
944
945
static void
946
remove_per_instruction_tools(PyCodeObject * code, int offset, int tools)
947
0
{
948
0
    ASSERT_WORLD_STOPPED_OR_LOCKED(code);
949
950
0
    _PyCoMonitoringData *monitoring = code->_co_monitoring;
951
0
    assert(code->_co_monitoring);
952
0
    bool should_de_instrument;
953
0
    if (code->_co_monitoring->per_instruction_tools) {
954
0
        uint8_t *toolsptr = &code->_co_monitoring->per_instruction_tools[offset];
955
0
        *toolsptr &= ~tools;
956
0
        should_de_instrument = (*toolsptr == 0);
957
0
    }
958
0
    else {
959
        /* Single tool */
960
0
        uint8_t single_tool = code->_co_monitoring->active_monitors.tools[PY_MONITORING_EVENT_INSTRUCTION];
961
0
        assert(_Py_popcount32(single_tool) <= 1);
962
0
        should_de_instrument = ((single_tool & tools) == single_tool);
963
0
    }
964
0
    if (should_de_instrument) {
965
0
        MODIFY_BYTECODE(code, de_instrument_per_instruction, monitoring, offset);
966
0
    }
967
0
}
968
969
970
/* Return 1 if DISABLE returned, -1 if error, 0 otherwise */
971
static int
972
call_one_instrument(
973
    PyInterpreterState *interp, PyThreadState *tstate, PyObject **args,
974
    size_t nargsf, int8_t tool, int event)
975
0
{
976
0
    assert(0 <= tool && tool < 8);
977
0
    assert(tstate->tracing == 0);
978
0
    PyObject *instrument = interp->monitoring_callables[tool][event];
979
0
    if (instrument == NULL) {
980
0
        return 0;
981
0
    }
982
0
    int old_what = tstate->what_event;
983
0
    tstate->what_event = event;
984
0
    tstate->tracing++;
985
0
    PyObject *res = _PyObject_VectorcallTstate(tstate, instrument, args, nargsf, NULL);
986
0
    tstate->tracing--;
987
0
    tstate->what_event = old_what;
988
0
    if (res == NULL) {
989
0
        return -1;
990
0
    }
991
0
    Py_DECREF(res);
992
0
    return (res == &_PyInstrumentation_DISABLE);
993
0
}
994
995
static const int8_t MOST_SIGNIFICANT_BITS[16] = {
996
    -1, 0, 1, 1,
997
    2, 2, 2, 2,
998
    3, 3, 3, 3,
999
    3, 3, 3, 3,
1000
};
1001
1002
/* We could use _Py_bit_length here, but that is designed for larger (32/64)
1003
 * bit ints, and can perform relatively poorly on platforms without the
1004
 * necessary intrinsics. */
1005
0
static inline int most_significant_bit(uint8_t bits) {
1006
0
    assert(bits != 0);
1007
0
    if (bits > 15) {
1008
0
        return MOST_SIGNIFICANT_BITS[bits>>4]+4;
1009
0
    }
1010
0
    return MOST_SIGNIFICANT_BITS[bits];
1011
0
}
1012
1013
static uint32_t
1014
global_version(PyInterpreterState *interp)
1015
2.01k
{
1016
2.01k
    uint32_t version = (uint32_t)_Py_atomic_load_uintptr_relaxed(
1017
2.01k
        &interp->ceval.instrumentation_version);
1018
#ifdef Py_DEBUG
1019
    PyThreadState *tstate = _PyThreadState_GET();
1020
    uint32_t thread_version =
1021
        (uint32_t)(_Py_atomic_load_uintptr_relaxed(&tstate->eval_breaker) &
1022
                   ~_PY_EVAL_EVENTS_MASK);
1023
    assert(thread_version == version);
1024
#endif
1025
2.01k
    return version;
1026
2.01k
}
1027
1028
/* Atomically set the given version in the given location, without touching
1029
   anything in _PY_EVAL_EVENTS_MASK. */
1030
static void
1031
set_version_raw(uintptr_t *ptr, uint32_t version)
1032
0
{
1033
0
    uintptr_t old = _Py_atomic_load_uintptr_relaxed(ptr);
1034
0
    uintptr_t new;
1035
0
    do {
1036
0
        new = (old & _PY_EVAL_EVENTS_MASK) | version;
1037
0
    } while (!_Py_atomic_compare_exchange_uintptr(ptr, &old, new));
1038
0
}
1039
1040
static void
1041
set_global_version(PyThreadState *tstate, uint32_t version)
1042
0
{
1043
0
    ASSERT_WORLD_STOPPED();
1044
1045
0
    assert((version & _PY_EVAL_EVENTS_MASK) == 0);
1046
0
    PyInterpreterState *interp = tstate->interp;
1047
0
    set_version_raw(&interp->ceval.instrumentation_version, version);
1048
1049
#ifdef Py_GIL_DISABLED
1050
    // Set the version on all threads in free-threaded builds.
1051
    _Py_FOR_EACH_TSTATE_BEGIN(interp, tstate) {
1052
        set_version_raw(&tstate->eval_breaker, version);
1053
    };
1054
    _Py_FOR_EACH_TSTATE_END(interp);
1055
#else
1056
    // Normal builds take the current version from instrumentation_version when
1057
    // attaching a thread, so we only have to set the current thread's version.
1058
0
    set_version_raw(&tstate->eval_breaker, version);
1059
0
#endif
1060
0
}
1061
1062
static bool
1063
is_version_up_to_date(PyCodeObject *code, PyInterpreterState *interp)
1064
2.01k
{
1065
2.01k
    ASSERT_WORLD_STOPPED_OR_LOCKED(code);
1066
2.01k
    return global_version(interp) == code->_co_instrumentation_version;
1067
2.01k
}
1068
1069
#ifndef NDEBUG
1070
static bool
1071
instrumentation_cross_checks(PyInterpreterState *interp, PyCodeObject *code)
1072
{
1073
    ASSERT_WORLD_STOPPED_OR_LOCKED(code);
1074
    _Py_LocalMonitors expected = local_union(
1075
        interp->monitors,
1076
        code->_co_monitoring->local_monitors);
1077
    return monitors_equals(code->_co_monitoring->active_monitors, expected);
1078
}
1079
1080
static int
1081
debug_check_sanity(PyInterpreterState *interp, PyCodeObject *code)
1082
{
1083
    int res;
1084
    LOCK_CODE(code);
1085
    res = is_version_up_to_date(code, interp) &&
1086
          instrumentation_cross_checks(interp, code);
1087
    UNLOCK_CODE();
1088
    return res;
1089
}
1090
1091
#endif
1092
1093
static inline uint8_t
1094
get_tools_for_instruction(PyCodeObject *code, PyInterpreterState *interp, int i, int event)
1095
0
{
1096
0
    uint8_t tools;
1097
0
    assert(event != PY_MONITORING_EVENT_LINE);
1098
0
    assert(event != PY_MONITORING_EVENT_INSTRUCTION);
1099
0
    if (event >= _PY_MONITORING_UNGROUPED_EVENTS) {
1100
0
        assert(event == PY_MONITORING_EVENT_C_RAISE ||
1101
0
                event == PY_MONITORING_EVENT_C_RETURN);
1102
0
        event = PY_MONITORING_EVENT_CALL;
1103
0
    }
1104
0
    if (PY_MONITORING_IS_INSTRUMENTED_EVENT(event)) {
1105
0
        CHECK(debug_check_sanity(interp, code));
1106
0
        if (code->_co_monitoring->tools) {
1107
0
            tools = code->_co_monitoring->tools[i];
1108
0
        }
1109
0
        else {
1110
0
            tools = code->_co_monitoring->active_monitors.tools[event];
1111
0
        }
1112
0
    }
1113
0
    else {
1114
0
        tools = interp->monitors.tools[event];
1115
0
    }
1116
0
    return tools;
1117
0
}
1118
1119
static const char *const event_names [] = {
1120
    [PY_MONITORING_EVENT_PY_START] = "PY_START",
1121
    [PY_MONITORING_EVENT_PY_RESUME] = "PY_RESUME",
1122
    [PY_MONITORING_EVENT_PY_RETURN] = "PY_RETURN",
1123
    [PY_MONITORING_EVENT_PY_YIELD] = "PY_YIELD",
1124
    [PY_MONITORING_EVENT_CALL] = "CALL",
1125
    [PY_MONITORING_EVENT_LINE] = "LINE",
1126
    [PY_MONITORING_EVENT_INSTRUCTION] = "INSTRUCTION",
1127
    [PY_MONITORING_EVENT_JUMP] = "JUMP",
1128
    [PY_MONITORING_EVENT_BRANCH] = "BRANCH",
1129
    [PY_MONITORING_EVENT_BRANCH_LEFT] = "BRANCH_LEFT",
1130
    [PY_MONITORING_EVENT_BRANCH_RIGHT] = "BRANCH_RIGHT",
1131
    [PY_MONITORING_EVENT_C_RETURN] = "C_RETURN",
1132
    [PY_MONITORING_EVENT_PY_THROW] = "PY_THROW",
1133
    [PY_MONITORING_EVENT_RAISE] = "RAISE",
1134
    [PY_MONITORING_EVENT_RERAISE] = "RERAISE",
1135
    [PY_MONITORING_EVENT_EXCEPTION_HANDLED] = "EXCEPTION_HANDLED",
1136
    [PY_MONITORING_EVENT_C_RAISE] = "C_RAISE",
1137
    [PY_MONITORING_EVENT_PY_UNWIND] = "PY_UNWIND",
1138
    [PY_MONITORING_EVENT_STOP_ITERATION] = "STOP_ITERATION",
1139
};
1140
1141
static int
1142
call_instrumentation_vector(
1143
    _Py_CODEUNIT *instr, PyThreadState *tstate, int event,
1144
    _PyInterpreterFrame *frame, _Py_CODEUNIT *arg2, Py_ssize_t nargs, PyObject *args[])
1145
0
{
1146
0
    if (tstate->tracing) {
1147
0
        return 0;
1148
0
    }
1149
0
    assert(!_PyErr_Occurred(tstate));
1150
0
    assert(args[0] == NULL);
1151
0
    PyCodeObject *code = _PyFrame_GetCode(frame);
1152
0
    assert(args[1] == NULL);
1153
0
    args[1] = (PyObject *)code;
1154
0
    int offset = (int)(instr - _PyFrame_GetBytecode(frame));
1155
    /* Offset visible to user should be the offset in bytes, as that is the
1156
     * convention for APIs involving code offsets. */
1157
0
    int bytes_arg2 = (int)(arg2 - _PyFrame_GetBytecode(frame)) * (int)sizeof(_Py_CODEUNIT);
1158
0
    PyObject *arg2_obj = PyLong_FromLong(bytes_arg2);
1159
0
    if (arg2_obj == NULL) {
1160
0
        return -1;
1161
0
    }
1162
0
    assert(args[2] == NULL);
1163
0
    args[2] = arg2_obj;
1164
0
    PyInterpreterState *interp = tstate->interp;
1165
0
    uint8_t tools = get_tools_for_instruction(code, interp, offset, event);
1166
0
    size_t nargsf = (size_t) nargs | PY_VECTORCALL_ARGUMENTS_OFFSET;
1167
0
    PyObject **callargs = &args[1];
1168
0
    int err = 0;
1169
0
    while (tools) {
1170
0
        int tool = most_significant_bit(tools);
1171
0
        assert(tool >= 0 && tool < 8);
1172
0
        assert(tools & (1 << tool));
1173
0
        tools ^= (1 << tool);
1174
0
        int res = call_one_instrument(interp, tstate, callargs, nargsf, tool, event);
1175
0
        if (res == 0) {
1176
            /* Nothing to do */
1177
0
        }
1178
0
        else if (res < 0) {
1179
            /* error */
1180
0
            err = -1;
1181
0
            break;
1182
0
        }
1183
0
        else {
1184
            /* DISABLE */
1185
0
            if (!PY_MONITORING_IS_INSTRUMENTED_EVENT(event)) {
1186
0
                PyErr_Format(PyExc_ValueError,
1187
0
                              "Cannot disable %s events. Callback removed.",
1188
0
                             event_names[event]);
1189
                /* Clear tool to prevent infinite loop */
1190
0
                Py_CLEAR(interp->monitoring_callables[tool][event]);
1191
0
                err = -1;
1192
0
                break;
1193
0
            }
1194
0
            else {
1195
0
                PyInterpreterState *interp = tstate->interp;
1196
0
                _PyEval_StopTheWorld(interp);
1197
0
                remove_tools(code, offset, event, 1 << tool);
1198
0
                _PyEval_StartTheWorld(interp);
1199
0
            }
1200
0
        }
1201
0
    }
1202
0
    Py_DECREF(arg2_obj);
1203
0
    return err;
1204
0
}
1205
1206
Py_NO_INLINE int
1207
_Py_call_instrumentation(
1208
    PyThreadState *tstate, int event,
1209
    _PyInterpreterFrame *frame, _Py_CODEUNIT *instr)
1210
0
{
1211
0
    PyObject *args[3] = { NULL, NULL, NULL };
1212
0
    return call_instrumentation_vector(instr, tstate, event, frame, instr, 2, args);
1213
0
}
1214
1215
Py_NO_INLINE int
1216
_Py_call_instrumentation_arg(
1217
    PyThreadState *tstate, int event,
1218
    _PyInterpreterFrame *frame, _Py_CODEUNIT *instr, PyObject *arg)
1219
0
{
1220
0
    PyObject *args[4] = { NULL, NULL, NULL, arg };
1221
0
    return call_instrumentation_vector(instr, tstate, event, frame, instr, 3, args);
1222
0
}
1223
1224
Py_NO_INLINE int
1225
_Py_call_instrumentation_2args(
1226
    PyThreadState *tstate, int event,
1227
    _PyInterpreterFrame *frame, _Py_CODEUNIT *instr, PyObject *arg0, PyObject *arg1)
1228
0
{
1229
0
    PyObject *args[5] = { NULL, NULL, NULL, arg0, arg1 };
1230
0
    return call_instrumentation_vector(instr, tstate, event, frame, instr, 4, args);
1231
0
}
1232
1233
Py_NO_INLINE _Py_CODEUNIT *
1234
_Py_call_instrumentation_jump(
1235
    _Py_CODEUNIT *instr, PyThreadState *tstate, int event,
1236
    _PyInterpreterFrame *frame, _Py_CODEUNIT *src, _Py_CODEUNIT *dest)
1237
0
{
1238
0
    assert(event == PY_MONITORING_EVENT_JUMP ||
1239
0
           event == PY_MONITORING_EVENT_BRANCH_RIGHT ||
1240
0
           event == PY_MONITORING_EVENT_BRANCH_LEFT);
1241
0
    int to = (int)(dest - _PyFrame_GetBytecode(frame));
1242
0
    PyObject *to_obj = PyLong_FromLong(to * (int)sizeof(_Py_CODEUNIT));
1243
0
    if (to_obj == NULL) {
1244
0
        return NULL;
1245
0
    }
1246
0
    PyObject *args[4] = { NULL, NULL, NULL, to_obj };
1247
0
    _Py_CODEUNIT *instr_ptr = frame->instr_ptr;
1248
0
    int err = call_instrumentation_vector(instr, tstate, event, frame, src, 3, args);
1249
0
    Py_DECREF(to_obj);
1250
0
    if (err) {
1251
0
        return NULL;
1252
0
    }
1253
0
    if (frame->instr_ptr != instr_ptr) {
1254
        /* The callback has caused a jump (by setting the line number) */
1255
0
        return frame->instr_ptr;
1256
0
    }
1257
0
    return dest;
1258
0
}
1259
1260
static void
1261
call_instrumentation_vector_protected(
1262
    PyThreadState *tstate, int event,
1263
    _PyInterpreterFrame *frame, _Py_CODEUNIT *instr, Py_ssize_t nargs, PyObject *args[])
1264
0
{
1265
0
    assert(_PyErr_Occurred(tstate));
1266
0
    PyObject *exc = _PyErr_GetRaisedException(tstate);
1267
0
    int err = call_instrumentation_vector(instr, tstate, event, frame, instr, nargs, args);
1268
0
    if (err) {
1269
0
        Py_XDECREF(exc);
1270
0
    }
1271
0
    else {
1272
0
        _PyErr_SetRaisedException(tstate, exc);
1273
0
    }
1274
0
    assert(_PyErr_Occurred(tstate));
1275
0
}
1276
1277
Py_NO_INLINE void
1278
_Py_call_instrumentation_exc2(
1279
    PyThreadState *tstate, int event,
1280
    _PyInterpreterFrame *frame, _Py_CODEUNIT *instr, PyObject *arg0, PyObject *arg1)
1281
0
{
1282
0
    assert(_PyErr_Occurred(tstate));
1283
0
    PyObject *args[5] = { NULL, NULL, NULL, arg0, arg1 };
1284
0
    call_instrumentation_vector_protected(tstate, event, frame, instr, 4, args);
1285
0
}
1286
1287
int
1288
_Py_Instrumentation_GetLine(PyCodeObject *code, int index)
1289
0
{
1290
0
    _PyCoMonitoringData *monitoring = code->_co_monitoring;
1291
0
    assert(monitoring != NULL);
1292
0
    assert(monitoring->lines != NULL);
1293
0
    assert(index < Py_SIZE(code));
1294
0
    _PyCoLineInstrumentationData *line_data = monitoring->lines;
1295
0
    int line_delta = get_line_delta(line_data, index);
1296
0
    int line = compute_line(code, line_delta);
1297
0
    return line;
1298
0
}
1299
1300
Py_NO_INLINE int
1301
_Py_call_instrumentation_line(PyThreadState *tstate, _PyInterpreterFrame* frame, _Py_CODEUNIT *instr, _Py_CODEUNIT *prev)
1302
0
{
1303
0
    PyCodeObject *code = _PyFrame_GetCode(frame);
1304
0
    assert(tstate->tracing == 0);
1305
0
    assert(debug_check_sanity(tstate->interp, code));
1306
0
    _Py_CODEUNIT *bytecode = _PyFrame_GetBytecode(frame);
1307
0
    int i = (int)(instr - bytecode);
1308
1309
0
    _PyCoMonitoringData *monitoring = code->_co_monitoring;
1310
0
    _PyCoLineInstrumentationData *line_data = monitoring->lines;
1311
0
    PyInterpreterState *interp = tstate->interp;
1312
0
    int line = _Py_Instrumentation_GetLine(code, i);
1313
0
    assert(line >= 0);
1314
0
    assert(prev != NULL);
1315
0
    int prev_index = (int)(prev - bytecode);
1316
0
    int prev_line = _Py_Instrumentation_GetLine(code, prev_index);
1317
0
    if (prev_line == line) {
1318
0
        int prev_opcode = bytecode[prev_index].op.code;
1319
        /* RESUME and INSTRUMENTED_RESUME are needed for the operation of
1320
            * instrumentation, so must never be hidden by an INSTRUMENTED_LINE.
1321
            */
1322
0
        if (prev_opcode != RESUME && prev_opcode != INSTRUMENTED_RESUME) {
1323
0
            goto done;
1324
0
        }
1325
0
    }
1326
1327
0
    uint8_t tools = code->_co_monitoring->line_tools != NULL ?
1328
0
        code->_co_monitoring->line_tools[i] :
1329
0
        (interp->monitors.tools[PY_MONITORING_EVENT_LINE] |
1330
0
         code->_co_monitoring->local_monitors.tools[PY_MONITORING_EVENT_LINE]
1331
0
        );
1332
    /* Special case sys.settrace to avoid boxing the line number,
1333
     * only to immediately unbox it. */
1334
0
    if (tools & (1 << PY_MONITORING_SYS_TRACE_ID)) {
1335
0
        if (tstate->c_tracefunc != NULL) {
1336
0
            PyFrameObject *frame_obj = _PyFrame_GetFrameObject(frame);
1337
0
            if (frame_obj == NULL) {
1338
0
                return -1;
1339
0
            }
1340
0
            if (frame_obj->f_trace_lines) {
1341
                /* Need to set tracing and what_event as if using
1342
                 * the instrumentation call. */
1343
0
                int old_what = tstate->what_event;
1344
0
                tstate->what_event = PY_MONITORING_EVENT_LINE;
1345
0
                tstate->tracing++;
1346
                /* Call c_tracefunc directly, having set the line number. */
1347
0
                Py_INCREF(frame_obj);
1348
0
                frame_obj->f_lineno = line;
1349
0
                int err = tstate->c_tracefunc(tstate->c_traceobj, frame_obj, PyTrace_LINE, Py_None);
1350
0
                frame_obj->f_lineno = 0;
1351
0
                tstate->tracing--;
1352
0
                tstate->what_event = old_what;
1353
0
                Py_DECREF(frame_obj);
1354
0
                if (err) {
1355
0
                    return -1;
1356
0
                }
1357
0
            }
1358
0
        }
1359
0
        tools &= (255 - (1 << PY_MONITORING_SYS_TRACE_ID));
1360
0
    }
1361
0
    if (tools == 0) {
1362
0
        goto done;
1363
0
    }
1364
0
    PyObject *line_obj = PyLong_FromLong(line);
1365
0
    if (line_obj == NULL) {
1366
0
        return -1;
1367
0
    }
1368
0
    PyObject *args[3] = { NULL, (PyObject *)code, line_obj };
1369
0
    do {
1370
0
        int tool = most_significant_bit(tools);
1371
0
        assert(tool >= 0 && tool < PY_MONITORING_SYS_PROFILE_ID);
1372
0
        assert(tools & (1 << tool));
1373
0
        tools &= ~(1 << tool);
1374
0
        int res = call_one_instrument(interp, tstate, &args[1],
1375
0
                                      2 | PY_VECTORCALL_ARGUMENTS_OFFSET,
1376
0
                                      tool, PY_MONITORING_EVENT_LINE);
1377
0
        if (res == 0) {
1378
            /* Nothing to do */
1379
0
        }
1380
0
        else if (res < 0) {
1381
            /* error */
1382
0
            Py_DECREF(line_obj);
1383
0
            return -1;
1384
0
        }
1385
0
        else {
1386
            /* DISABLE  */
1387
0
            PyInterpreterState *interp = tstate->interp;
1388
0
            _PyEval_StopTheWorld(interp);
1389
0
            remove_line_tools(code, i, 1 << tool);
1390
0
            _PyEval_StartTheWorld(interp);
1391
0
        }
1392
0
    } while (tools);
1393
0
    Py_DECREF(line_obj);
1394
0
    uint8_t original_opcode;
1395
0
done:
1396
0
    original_opcode = get_original_opcode(line_data, i);
1397
0
    assert(original_opcode != 0);
1398
0
    assert(original_opcode != INSTRUMENTED_LINE);
1399
0
    assert(_PyOpcode_Deopt[original_opcode] == original_opcode);
1400
0
    return original_opcode;
1401
0
}
1402
1403
Py_NO_INLINE int
1404
_Py_call_instrumentation_instruction(PyThreadState *tstate, _PyInterpreterFrame* frame, _Py_CODEUNIT *instr)
1405
0
{
1406
0
    PyCodeObject *code = _PyFrame_GetCode(frame);
1407
0
    int offset = (int)(instr - _PyFrame_GetBytecode(frame));
1408
0
    _PyCoMonitoringData *instrumentation_data = code->_co_monitoring;
1409
0
    assert(instrumentation_data->per_instruction_opcodes);
1410
0
    int next_opcode = instrumentation_data->per_instruction_opcodes[offset];
1411
0
    if (tstate->tracing) {
1412
0
        return next_opcode;
1413
0
    }
1414
0
    assert(debug_check_sanity(tstate->interp, code));
1415
0
    PyInterpreterState *interp = tstate->interp;
1416
0
    uint8_t tools = instrumentation_data->per_instruction_tools != NULL ?
1417
0
        instrumentation_data->per_instruction_tools[offset] :
1418
0
        (interp->monitors.tools[PY_MONITORING_EVENT_INSTRUCTION] |
1419
0
         code->_co_monitoring->local_monitors.tools[PY_MONITORING_EVENT_INSTRUCTION]
1420
0
        );
1421
0
    int bytes_offset = offset * (int)sizeof(_Py_CODEUNIT);
1422
0
    PyObject *offset_obj = PyLong_FromLong(bytes_offset);
1423
0
    if (offset_obj == NULL) {
1424
0
        return -1;
1425
0
    }
1426
0
    PyObject *args[3] = { NULL, (PyObject *)code, offset_obj };
1427
0
    while (tools) {
1428
0
        int tool = most_significant_bit(tools);
1429
0
        assert(tool >= 0 && tool < 8);
1430
0
        assert(tools & (1 << tool));
1431
0
        tools &= ~(1 << tool);
1432
0
        int res = call_one_instrument(interp, tstate, &args[1],
1433
0
                                      2 | PY_VECTORCALL_ARGUMENTS_OFFSET,
1434
0
                                      tool, PY_MONITORING_EVENT_INSTRUCTION);
1435
0
        if (res == 0) {
1436
            /* Nothing to do */
1437
0
        }
1438
0
        else if (res < 0) {
1439
            /* error */
1440
0
            Py_DECREF(offset_obj);
1441
0
            return -1;
1442
0
        }
1443
0
        else {
1444
            /* DISABLE  */
1445
0
            PyInterpreterState *interp = tstate->interp;
1446
0
            _PyEval_StopTheWorld(interp);
1447
0
            remove_per_instruction_tools(code, offset, 1 << tool);
1448
0
            _PyEval_StartTheWorld(interp);
1449
0
        }
1450
0
    }
1451
0
    Py_DECREF(offset_obj);
1452
0
    assert(next_opcode != 0);
1453
0
    return next_opcode;
1454
0
}
1455
1456
static void
1457
initialize_tools(PyCodeObject *code)
1458
0
{
1459
0
    ASSERT_WORLD_STOPPED_OR_LOCKED(code);
1460
0
    uint8_t* tools = code->_co_monitoring->tools;
1461
1462
0
    assert(tools != NULL);
1463
0
    int code_len = (int)Py_SIZE(code);
1464
0
    for (int i = 0; i < code_len; i++) {
1465
0
        _Py_CODEUNIT *instr = &_PyCode_CODE(code)[i];
1466
0
        int opcode = instr->op.code;
1467
0
        assert(opcode != ENTER_EXECUTOR);
1468
0
        if (opcode == INSTRUMENTED_LINE) {
1469
0
            opcode = get_original_opcode(code->_co_monitoring->lines, i);
1470
0
        }
1471
0
        if (opcode == INSTRUMENTED_INSTRUCTION) {
1472
0
            opcode = code->_co_monitoring->per_instruction_opcodes[i];
1473
0
        }
1474
0
        bool instrumented = is_instrumented(opcode);
1475
0
        if (instrumented) {
1476
0
            opcode = DE_INSTRUMENT[opcode];
1477
0
            assert(opcode != 0);
1478
0
        }
1479
0
        opcode = _PyOpcode_Deopt[opcode];
1480
0
        if (opcode_has_event(opcode)) {
1481
0
            if (instrumented) {
1482
0
                int8_t event;
1483
0
                if (opcode == RESUME) {
1484
0
                    event = instr->op.arg != 0;
1485
0
                }
1486
0
                else {
1487
0
                    event = EVENT_FOR_OPCODE[opcode];
1488
0
                    assert(event > 0);
1489
0
                }
1490
0
                assert(event >= 0);
1491
0
                assert(PY_MONITORING_IS_INSTRUMENTED_EVENT(event));
1492
0
                tools[i] = code->_co_monitoring->active_monitors.tools[event];
1493
0
                CHECK(tools[i] != 0);
1494
0
            }
1495
0
            else {
1496
0
                tools[i] = 0;
1497
0
            }
1498
0
        }
1499
#ifdef Py_DEBUG
1500
        /* Initialize tools for invalid locations to all ones to try to catch errors */
1501
        else {
1502
            tools[i] = 0xff;
1503
        }
1504
        for (int j = 1; j <= _PyOpcode_Caches[opcode]; j++) {
1505
            tools[i+j] = 0xff;
1506
        }
1507
#endif
1508
0
        i += _PyOpcode_Caches[opcode];
1509
0
    }
1510
0
}
1511
1512
static void
1513
initialize_lines(PyCodeObject *code, int bytes_per_entry)
1514
0
{
1515
0
    ASSERT_WORLD_STOPPED_OR_LOCKED(code);
1516
0
    _PyCoLineInstrumentationData *line_data = code->_co_monitoring->lines;
1517
1518
0
    assert(line_data != NULL);
1519
0
    line_data->bytes_per_entry = bytes_per_entry;
1520
0
    int code_len = (int)Py_SIZE(code);
1521
0
    PyCodeAddressRange range;
1522
0
    _PyCode_InitAddressRange(code, &range);
1523
0
    int current_line = -1;
1524
0
    for (int i = 0; i < code_len; ) {
1525
0
        int opcode = _Py_GetBaseCodeUnit(code, i).op.code;
1526
0
        int line = _PyCode_CheckLineNumber(i*(int)sizeof(_Py_CODEUNIT), &range);
1527
0
        set_line_delta(line_data, i, compute_line_delta(code, line));
1528
0
        int length = _PyInstruction_GetLength(code, i);
1529
0
        if (i < code->_co_firsttraceable) {
1530
0
            set_original_opcode(line_data, i, 0);
1531
0
        }
1532
0
        else {
1533
0
            switch (opcode) {
1534
0
                case END_ASYNC_FOR:
1535
0
                case END_FOR:
1536
0
                case END_SEND:
1537
0
                case RESUME:
1538
0
                case POP_ITER:
1539
                    /* END_FOR cannot start a line, as it is skipped by FOR_ITER
1540
                    * END_SEND cannot start a line, as it is skipped by SEND
1541
                    * RESUME and POP_ITER must not be instrumented with INSTRUMENTED_LINE */
1542
0
                    set_original_opcode(line_data, i, 0);
1543
0
                    break;
1544
0
                default:
1545
                    /* Set original_opcode to the opcode iff the instruction
1546
                    * starts a line, and thus should be instrumented.
1547
                    * This saves having to perform this check every time the
1548
                    * we turn instrumentation on or off, and serves as a sanity
1549
                    * check when debugging.
1550
                    */
1551
0
                    if (line != current_line && line >= 0) {
1552
0
                        set_original_opcode(line_data, i, opcode);
1553
0
                        CHECK(get_line_delta(line_data, i) != NO_LINE);
1554
0
                    }
1555
0
                    else {
1556
0
                        set_original_opcode(line_data, i, 0);
1557
0
                    }
1558
0
                    current_line = line;
1559
0
            }
1560
0
        }
1561
0
        for (int j = 1; j < length; j++) {
1562
0
            set_original_opcode(line_data, i+j, 0);
1563
0
            set_line_delta(line_data, i+j, NO_LINE);
1564
0
        }
1565
0
        i += length;
1566
0
    }
1567
0
    for (int i = code->_co_firsttraceable; i < code_len; ) {
1568
0
        _Py_CODEUNIT inst =_Py_GetBaseCodeUnit(code, i);
1569
0
        int opcode = inst.op.code;
1570
0
        int oparg = 0;
1571
0
        while (opcode == EXTENDED_ARG) {
1572
0
            oparg = (oparg << 8) | inst.op.arg;
1573
0
            i++;
1574
0
            inst =_Py_GetBaseCodeUnit(code, i);
1575
0
            opcode = inst.op.code;
1576
0
        }
1577
0
        oparg = (oparg << 8) | inst.op.arg;
1578
0
        i += _PyInstruction_GetLength(code, i);
1579
0
        int target = -1;
1580
0
        switch (opcode) {
1581
0
            case POP_JUMP_IF_FALSE:
1582
0
            case POP_JUMP_IF_TRUE:
1583
0
            case POP_JUMP_IF_NONE:
1584
0
            case POP_JUMP_IF_NOT_NONE:
1585
0
            case JUMP_FORWARD:
1586
0
            {
1587
0
                target = i + oparg;
1588
0
                break;
1589
0
            }
1590
0
            case FOR_ITER:
1591
0
            case SEND:
1592
0
            {
1593
                /* Skip over END_FOR/END_SEND */
1594
0
                target = i + oparg + 1;
1595
0
                break;
1596
0
            }
1597
0
            case JUMP_BACKWARD:
1598
0
            case JUMP_BACKWARD_NO_INTERRUPT:
1599
0
            {
1600
0
                target = i - oparg;
1601
0
                break;
1602
0
            }
1603
0
            default:
1604
0
                continue;
1605
0
        }
1606
0
        assert(target >= 0);
1607
0
        if (get_line_delta(line_data, target) != NO_LINE) {
1608
0
            int opcode = _Py_GetBaseCodeUnit(code, target).op.code;
1609
0
            if (opcode != POP_ITER) {
1610
0
                set_original_opcode(line_data, target, opcode);
1611
0
            }
1612
0
        }
1613
0
    }
1614
    /* Scan exception table */
1615
0
    unsigned char *start = (unsigned char *)PyBytes_AS_STRING(code->co_exceptiontable);
1616
0
    unsigned char *end = start + PyBytes_GET_SIZE(code->co_exceptiontable);
1617
0
    unsigned char *scan = start;
1618
0
    while (scan < end) {
1619
0
        int start_offset, size, handler;
1620
0
        scan = parse_varint(scan, &start_offset);
1621
0
        assert(start_offset >= 0 && start_offset < code_len);
1622
0
        scan = parse_varint(scan, &size);
1623
0
        assert(size >= 0 && start_offset+size <= code_len);
1624
0
        scan = parse_varint(scan, &handler);
1625
0
        assert(handler >= 0 && handler < code_len);
1626
0
        int depth_and_lasti;
1627
0
        scan = parse_varint(scan, &depth_and_lasti);
1628
0
        int original_opcode = _Py_GetBaseCodeUnit(code, handler).op.code;
1629
        /* Skip if not the start of a line.
1630
         * END_ASYNC_FOR is a bit special as it marks the end of
1631
         * an `async for` loop, which should not generate its own
1632
         * line event. */
1633
0
        if (get_line_delta(line_data, handler) != NO_LINE && original_opcode != END_ASYNC_FOR) {
1634
0
            set_original_opcode(line_data, handler, original_opcode);
1635
0
        }
1636
0
    }
1637
0
}
1638
1639
static void
1640
initialize_line_tools(PyCodeObject *code, _Py_LocalMonitors *all_events)
1641
0
{
1642
0
    ASSERT_WORLD_STOPPED_OR_LOCKED(code);
1643
0
    uint8_t *line_tools = code->_co_monitoring->line_tools;
1644
1645
0
    assert(line_tools != NULL);
1646
0
    int code_len = (int)Py_SIZE(code);
1647
0
    for (int i = 0; i < code_len; i++) {
1648
0
        line_tools[i] = all_events->tools[PY_MONITORING_EVENT_LINE];
1649
0
    }
1650
0
}
1651
1652
static int
1653
allocate_instrumentation_data(PyCodeObject *code)
1654
0
{
1655
0
    ASSERT_WORLD_STOPPED_OR_LOCKED(code);
1656
1657
0
    if (code->_co_monitoring == NULL) {
1658
0
        code->_co_monitoring = PyMem_Malloc(sizeof(_PyCoMonitoringData));
1659
0
        if (code->_co_monitoring == NULL) {
1660
0
            PyErr_NoMemory();
1661
0
            return -1;
1662
0
        }
1663
0
        code->_co_monitoring->local_monitors = (_Py_LocalMonitors){ 0 };
1664
0
        code->_co_monitoring->active_monitors = (_Py_LocalMonitors){ 0 };
1665
0
        code->_co_monitoring->tools = NULL;
1666
0
        code->_co_monitoring->lines = NULL;
1667
0
        code->_co_monitoring->line_tools = NULL;
1668
0
        code->_co_monitoring->per_instruction_opcodes = NULL;
1669
0
        code->_co_monitoring->per_instruction_tools = NULL;
1670
0
    }
1671
0
    return 0;
1672
0
}
1673
1674
static int
1675
update_instrumentation_data(PyCodeObject *code, PyInterpreterState *interp)
1676
0
{
1677
0
    ASSERT_WORLD_STOPPED_OR_LOCKED(code);
1678
1679
0
    int code_len = (int)Py_SIZE(code);
1680
0
    if (allocate_instrumentation_data(code)) {
1681
0
        return -1;
1682
0
    }
1683
    // If the local monitors are out of date, clear them up
1684
0
    _Py_LocalMonitors *local_monitors = &code->_co_monitoring->local_monitors;
1685
0
    for (int i = 0; i < PY_MONITORING_TOOL_IDS; i++) {
1686
0
        if (code->_co_monitoring->tool_versions[i] != interp->monitoring_tool_versions[i]) {
1687
0
            for (int j = 0; j < _PY_MONITORING_LOCAL_EVENTS; j++) {
1688
0
                local_monitors->tools[j] &= ~(1 << i);
1689
0
            }
1690
0
        }
1691
0
    }
1692
1693
0
    _Py_LocalMonitors all_events = local_union(
1694
0
        interp->monitors,
1695
0
        code->_co_monitoring->local_monitors);
1696
0
    bool multitools = multiple_tools(&all_events);
1697
0
    if (code->_co_monitoring->tools == NULL && multitools) {
1698
0
        code->_co_monitoring->tools = PyMem_Malloc(code_len);
1699
0
        if (code->_co_monitoring->tools == NULL) {
1700
0
            PyErr_NoMemory();
1701
0
            return -1;
1702
0
        }
1703
0
        initialize_tools(code);
1704
0
    }
1705
0
    if (all_events.tools[PY_MONITORING_EVENT_LINE]) {
1706
0
        if (code->_co_monitoring->lines == NULL) {
1707
0
            PyCodeAddressRange range;
1708
0
            _PyCode_InitAddressRange(code, &range);
1709
0
            int max_line = code->co_firstlineno + 1;
1710
0
            _PyCode_InitAddressRange(code, &range);
1711
0
            for (int i = code->_co_firsttraceable; i < code_len; ) {
1712
0
                int line = _PyCode_CheckLineNumber(i*(int)sizeof(_Py_CODEUNIT), &range);
1713
0
                if (line > max_line) {
1714
0
                    max_line = line;
1715
0
                }
1716
0
                int length = _PyInstruction_GetLength(code, i);
1717
0
                i += length;
1718
0
            }
1719
0
            int bytes_per_entry;
1720
0
            int max_delta = max_line - code->co_firstlineno;
1721
            /* We store delta+2 in the table, so 253 is max for one byte */
1722
0
            if (max_delta < 256+NO_LINE) {
1723
0
                bytes_per_entry = 2;
1724
0
            }
1725
0
            else if (max_delta < (1 << 16)+NO_LINE) {
1726
0
                bytes_per_entry = 3;
1727
0
            }
1728
0
            else if (max_delta < (1 << 24)+NO_LINE) {
1729
0
                bytes_per_entry = 4;
1730
0
            }
1731
0
            else {
1732
0
                bytes_per_entry = 5;
1733
0
            }
1734
0
            code->_co_monitoring->lines = PyMem_Malloc(1 + code_len * bytes_per_entry);
1735
0
            if (code->_co_monitoring->lines == NULL) {
1736
0
                PyErr_NoMemory();
1737
0
                return -1;
1738
0
            }
1739
0
            initialize_lines(code, bytes_per_entry);
1740
0
        }
1741
0
        if (multitools && code->_co_monitoring->line_tools == NULL) {
1742
0
            code->_co_monitoring->line_tools = PyMem_Malloc(code_len);
1743
0
            if (code->_co_monitoring->line_tools == NULL) {
1744
0
                PyErr_NoMemory();
1745
0
                return -1;
1746
0
            }
1747
0
            initialize_line_tools(code, &all_events);
1748
0
        }
1749
0
    }
1750
0
    if (all_events.tools[PY_MONITORING_EVENT_INSTRUCTION]) {
1751
0
        if (code->_co_monitoring->per_instruction_opcodes == NULL) {
1752
0
            code->_co_monitoring->per_instruction_opcodes = PyMem_Malloc(code_len * sizeof(_PyCoLineInstrumentationData));
1753
0
            if (code->_co_monitoring->per_instruction_opcodes == NULL) {
1754
0
                PyErr_NoMemory();
1755
0
                return -1;
1756
0
            }
1757
            // Initialize all of the instructions so if local events change while another thread is executing
1758
            // we know what the original opcode was.
1759
0
            for (int i = 0; i < code_len; i++) {
1760
0
                int opcode = _PyCode_CODE(code)[i].op.code;
1761
0
                code->_co_monitoring->per_instruction_opcodes[i] = _PyOpcode_Deopt[opcode];
1762
0
            }
1763
0
        }
1764
0
        if (multitools && code->_co_monitoring->per_instruction_tools == NULL) {
1765
0
            code->_co_monitoring->per_instruction_tools = PyMem_Malloc(code_len);
1766
0
            if (code->_co_monitoring->per_instruction_tools == NULL) {
1767
0
                PyErr_NoMemory();
1768
0
                return -1;
1769
0
            }
1770
0
            for (int i = 0; i < code_len; i++) {
1771
0
                code->_co_monitoring->per_instruction_tools[i] = 0;
1772
0
            }
1773
0
        }
1774
0
    }
1775
0
    return 0;
1776
0
}
1777
1778
static int
1779
force_instrument_lock_held(PyCodeObject *code, PyInterpreterState *interp)
1780
0
{
1781
0
    ASSERT_WORLD_STOPPED_OR_LOCKED(code);
1782
1783
#ifdef _Py_TIER2
1784
    if (code->co_executors != NULL) {
1785
        _PyCode_Clear_Executors(code);
1786
    }
1787
    _Py_Executors_InvalidateDependency(interp, code, 1);
1788
#endif
1789
0
    int code_len = (int)Py_SIZE(code);
1790
    /* Exit early to avoid creating instrumentation
1791
     * data for potential statically allocated code
1792
     * objects.
1793
     * See https://github.com/python/cpython/issues/108390 */
1794
0
    if (code->co_flags & CO_NO_MONITORING_EVENTS) {
1795
0
        return 0;
1796
0
    }
1797
0
    if (update_instrumentation_data(code, interp)) {
1798
0
        return -1;
1799
0
    }
1800
0
    _Py_LocalMonitors active_events = local_union(
1801
0
        interp->monitors,
1802
0
        code->_co_monitoring->local_monitors);
1803
0
    _Py_LocalMonitors new_events;
1804
0
    _Py_LocalMonitors removed_events;
1805
1806
0
    bool restarted = interp->last_restart_version > code->_co_instrumentation_version;
1807
0
    if (restarted) {
1808
0
        removed_events = code->_co_monitoring->active_monitors;
1809
0
        new_events = active_events;
1810
0
    }
1811
0
    else {
1812
0
        removed_events = monitors_sub(code->_co_monitoring->active_monitors, active_events);
1813
0
        new_events = monitors_sub(active_events, code->_co_monitoring->active_monitors);
1814
0
        assert(monitors_are_empty(monitors_and(new_events, removed_events)));
1815
0
    }
1816
0
    code->_co_monitoring->active_monitors = active_events;
1817
0
    if (monitors_are_empty(new_events) && monitors_are_empty(removed_events)) {
1818
0
        goto done;
1819
0
    }
1820
    /* Insert instrumentation */
1821
0
    for (int i = code->_co_firsttraceable; i < code_len; i+= _PyInstruction_GetLength(code, i)) {
1822
0
        assert(_PyCode_CODE(code)[i].op.code != ENTER_EXECUTOR);
1823
0
        _Py_CODEUNIT instr = _Py_GetBaseCodeUnit(code, i);
1824
0
        CHECK(instr.op.code != 0);
1825
0
        int base_opcode = instr.op.code;
1826
0
        if (opcode_has_event(base_opcode)) {
1827
0
            int8_t event;
1828
0
            if (base_opcode == RESUME) {
1829
0
                event = instr.op.arg > 0;
1830
0
            }
1831
0
            else {
1832
0
                event = EVENT_FOR_OPCODE[base_opcode];
1833
0
                assert(event > 0);
1834
0
            }
1835
0
            uint8_t removed_tools = removed_events.tools[event];
1836
0
            if (removed_tools) {
1837
0
                remove_tools(code, i, event, removed_tools);
1838
0
            }
1839
0
            uint8_t new_tools = new_events.tools[event];
1840
0
            if (new_tools) {
1841
0
                add_tools(code, i, event, new_tools);
1842
0
            }
1843
0
        }
1844
0
    }
1845
1846
    // GH-103845: We need to remove both the line and instruction instrumentation before
1847
    // adding new ones, otherwise we may remove the newly added instrumentation.
1848
0
    uint8_t removed_line_tools = removed_events.tools[PY_MONITORING_EVENT_LINE];
1849
0
    uint8_t removed_per_instruction_tools = removed_events.tools[PY_MONITORING_EVENT_INSTRUCTION];
1850
1851
0
    if (removed_line_tools) {
1852
0
        _PyCoLineInstrumentationData *line_data = code->_co_monitoring->lines;
1853
0
        for (int i = code->_co_firsttraceable; i < code_len;) {
1854
0
            if (get_original_opcode(line_data, i)) {
1855
0
                remove_line_tools(code, i, removed_line_tools);
1856
0
            }
1857
0
            i += _PyInstruction_GetLength(code, i);
1858
0
        }
1859
0
    }
1860
0
    if (removed_per_instruction_tools) {
1861
0
        for (int i = code->_co_firsttraceable; i < code_len;) {
1862
0
            int opcode = _Py_GetBaseCodeUnit(code, i).op.code;
1863
0
            if (opcode == RESUME || opcode == END_FOR) {
1864
0
                i += _PyInstruction_GetLength(code, i);
1865
0
                continue;
1866
0
            }
1867
0
            remove_per_instruction_tools(code, i, removed_per_instruction_tools);
1868
0
            i += _PyInstruction_GetLength(code, i);
1869
0
        }
1870
0
    }
1871
#ifdef INSTRUMENT_DEBUG
1872
    sanity_check_instrumentation(code);
1873
#endif
1874
1875
0
    uint8_t new_line_tools = new_events.tools[PY_MONITORING_EVENT_LINE];
1876
0
    uint8_t new_per_instruction_tools = new_events.tools[PY_MONITORING_EVENT_INSTRUCTION];
1877
1878
0
    if (new_line_tools) {
1879
0
        _PyCoLineInstrumentationData *line_data = code->_co_monitoring->lines;
1880
0
        for (int i = code->_co_firsttraceable; i < code_len;) {
1881
0
            if (get_original_opcode(line_data, i)) {
1882
0
                add_line_tools(code, i, new_line_tools);
1883
0
            }
1884
0
            i += _PyInstruction_GetLength(code, i);
1885
0
        }
1886
0
    }
1887
0
    if (new_per_instruction_tools) {
1888
0
        for (int i = code->_co_firsttraceable; i < code_len;) {
1889
0
            int opcode = _Py_GetBaseCodeUnit(code, i).op.code;
1890
0
            if (opcode == RESUME || opcode == END_FOR) {
1891
0
                i += _PyInstruction_GetLength(code, i);
1892
0
                continue;
1893
0
            }
1894
0
            add_per_instruction_tools(code, i, new_per_instruction_tools);
1895
0
            i += _PyInstruction_GetLength(code, i);
1896
0
        }
1897
0
    }
1898
1899
0
done:
1900
0
    FT_ATOMIC_STORE_UINTPTR_RELEASE(code->_co_instrumentation_version,
1901
0
                                    global_version(interp));
1902
1903
#ifdef INSTRUMENT_DEBUG
1904
    sanity_check_instrumentation(code);
1905
#endif
1906
0
    return 0;
1907
0
}
1908
1909
static int
1910
instrument_lock_held(PyCodeObject *code, PyInterpreterState *interp)
1911
2.01k
{
1912
2.01k
    ASSERT_WORLD_STOPPED_OR_LOCKED(code);
1913
1914
2.01k
    if (is_version_up_to_date(code, interp)) {
1915
2.01k
        assert(
1916
2.01k
            interp->ceval.instrumentation_version == 0 ||
1917
2.01k
            instrumentation_cross_checks(interp, code)
1918
2.01k
        );
1919
2.01k
        return 0;
1920
2.01k
    }
1921
1922
0
    return force_instrument_lock_held(code, interp);
1923
2.01k
}
1924
1925
int
1926
_Py_Instrument(PyCodeObject *code, PyInterpreterState *interp)
1927
2.01k
{
1928
2.01k
    int res;
1929
2.01k
    LOCK_CODE(code);
1930
2.01k
    res = instrument_lock_held(code, interp);
1931
2.01k
    UNLOCK_CODE();
1932
2.01k
    return res;
1933
2.01k
}
1934
1935
#define C_RETURN_EVENTS \
1936
0
    ((1 << PY_MONITORING_EVENT_C_RETURN) | \
1937
0
     (1 << PY_MONITORING_EVENT_C_RAISE))
1938
1939
#define C_CALL_EVENTS \
1940
0
    (C_RETURN_EVENTS | (1 << PY_MONITORING_EVENT_CALL))
1941
1942
1943
static int
1944
instrument_all_executing_code_objects(PyInterpreterState *interp)
1945
0
{
1946
0
    ASSERT_WORLD_STOPPED();
1947
1948
0
    int err = 0;
1949
0
    _Py_FOR_EACH_TSTATE_BEGIN(interp, ts) {
1950
0
        _PyInterpreterFrame *frame = ts->current_frame;
1951
0
        while (frame) {
1952
0
            if (frame->owner < FRAME_OWNED_BY_INTERPRETER) {
1953
0
                err = instrument_lock_held(_PyFrame_GetCode(frame), interp);
1954
0
                if (err) {
1955
0
                    goto done;
1956
0
                }
1957
0
            }
1958
0
            frame = frame->previous;
1959
0
        }
1960
0
    }
1961
0
done:
1962
0
    _Py_FOR_EACH_TSTATE_END(interp);
1963
0
    return err;
1964
0
}
1965
1966
static void
1967
set_events(_Py_GlobalMonitors *m, int tool_id, _PyMonitoringEventSet events)
1968
0
{
1969
0
    assert(0 <= tool_id && tool_id < PY_MONITORING_TOOL_IDS);
1970
0
    for (int e = 0; e < _PY_MONITORING_UNGROUPED_EVENTS; e++) {
1971
0
        uint8_t *tools = &m->tools[e];
1972
0
        int active = (events >> e) & 1;
1973
0
        *tools &= ~(1 << tool_id);
1974
0
        *tools |= (active << tool_id);
1975
0
    }
1976
0
}
1977
1978
static void
1979
set_local_events(_Py_LocalMonitors *m, int tool_id, _PyMonitoringEventSet events)
1980
0
{
1981
0
    assert(0 <= tool_id && tool_id < PY_MONITORING_TOOL_IDS);
1982
0
    for (int e = 0; e < _PY_MONITORING_LOCAL_EVENTS; e++) {
1983
0
        uint8_t *tools = &m->tools[e];
1984
0
        int val = (events >> e) & 1;
1985
0
        *tools &= ~(1 << tool_id);
1986
0
        *tools |= (val << tool_id);
1987
0
    }
1988
0
}
1989
1990
static int
1991
check_tool(PyInterpreterState *interp, int tool_id)
1992
0
{
1993
0
    if (tool_id < PY_MONITORING_SYS_PROFILE_ID &&
1994
0
        interp->monitoring_tool_names[tool_id] == NULL)
1995
0
    {
1996
0
        PyErr_Format(PyExc_ValueError, "tool %d is not in use", tool_id);
1997
0
        return -1;
1998
0
    }
1999
0
    return 0;
2000
0
}
2001
2002
/* We share the eval-breaker with flags, so the monitoring
2003
 * version goes in the top 24 bits */
2004
0
#define MONITORING_VERSION_INCREMENT (1 << _PY_EVAL_EVENTS_BITS)
2005
2006
int
2007
_PyMonitoring_SetEvents(int tool_id, _PyMonitoringEventSet events)
2008
0
{
2009
0
    ASSERT_WORLD_STOPPED();
2010
0
    assert(0 <= tool_id && tool_id < PY_MONITORING_TOOL_IDS);
2011
0
    PyThreadState *tstate = _PyThreadState_GET();
2012
0
    PyInterpreterState *interp = tstate->interp;
2013
0
    assert(events < (1 << _PY_MONITORING_UNGROUPED_EVENTS));
2014
0
    if (check_tool(interp, tool_id)) {
2015
0
        return -1;
2016
0
    }
2017
2018
0
    uint32_t existing_events = get_events(&interp->monitors, tool_id);
2019
0
    if (existing_events == events) {
2020
0
        return 0;
2021
0
    }
2022
0
    set_events(&interp->monitors, tool_id, events);
2023
0
    uint32_t new_version = global_version(interp) + MONITORING_VERSION_INCREMENT;
2024
0
    if (new_version == 0) {
2025
0
        PyErr_Format(PyExc_OverflowError, "events set too many times");
2026
0
        return -1;
2027
0
    }
2028
0
    set_global_version(tstate, new_version);
2029
#ifdef _Py_TIER2
2030
    _Py_Executors_InvalidateAll(interp, 1);
2031
#endif
2032
0
    return instrument_all_executing_code_objects(interp);
2033
0
}
2034
2035
int
2036
_PyMonitoring_SetLocalEvents(PyCodeObject *code, int tool_id, _PyMonitoringEventSet events)
2037
0
{
2038
0
    ASSERT_WORLD_STOPPED();
2039
2040
0
    assert(0 <= tool_id && tool_id < PY_MONITORING_TOOL_IDS);
2041
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
2042
0
    assert(events < (1 << _PY_MONITORING_LOCAL_EVENTS));
2043
0
    if (code->_co_firsttraceable >= Py_SIZE(code)) {
2044
0
        PyErr_Format(PyExc_SystemError, "cannot instrument shim code object '%U'", code->co_name);
2045
0
        return -1;
2046
0
    }
2047
0
    if (check_tool(interp, tool_id)) {
2048
0
        return -1;
2049
0
    }
2050
2051
0
    if (allocate_instrumentation_data(code)) {
2052
0
        return -1;
2053
0
    }
2054
2055
0
    code->_co_monitoring->tool_versions[tool_id] = interp->monitoring_tool_versions[tool_id];
2056
2057
0
    _Py_LocalMonitors *local = &code->_co_monitoring->local_monitors;
2058
0
    uint32_t existing_events = get_local_events(local, tool_id);
2059
0
    if (existing_events == events) {
2060
0
        return 0;
2061
0
    }
2062
0
    set_local_events(local, tool_id, events);
2063
2064
0
    return force_instrument_lock_held(code, interp);
2065
0
}
2066
2067
int
2068
_PyMonitoring_GetLocalEvents(PyCodeObject *code, int tool_id, _PyMonitoringEventSet *events)
2069
0
{
2070
0
    assert(0 <= tool_id && tool_id < PY_MONITORING_TOOL_IDS);
2071
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
2072
0
    if (check_tool(interp, tool_id)) {
2073
0
        return -1;
2074
0
    }
2075
0
    if (code->_co_monitoring == NULL) {
2076
0
        *events = 0;
2077
0
        return 0;
2078
0
    }
2079
0
    _Py_LocalMonitors *local = &code->_co_monitoring->local_monitors;
2080
0
    *events = get_local_events(local, tool_id);
2081
0
    return 0;
2082
0
}
2083
2084
int _PyMonitoring_ClearToolId(int tool_id)
2085
0
{
2086
0
    assert(0 <= tool_id && tool_id < PY_MONITORING_TOOL_IDS);
2087
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
2088
2089
0
    for (int i = 0; i < _PY_MONITORING_EVENTS; i++) {
2090
0
        PyObject *func = _PyMonitoring_RegisterCallback(tool_id, i, NULL);
2091
0
        if (func != NULL) {
2092
0
            Py_DECREF(func);
2093
0
        }
2094
0
    }
2095
2096
0
    _PyEval_StopTheWorld(interp);
2097
0
    if (_PyMonitoring_SetEvents(tool_id, 0) < 0) {
2098
0
        _PyEval_StartTheWorld(interp);
2099
0
        return -1;
2100
0
    }
2101
2102
0
    uint32_t version = global_version(interp) + MONITORING_VERSION_INCREMENT;
2103
0
    if (version == 0) {
2104
0
        PyErr_Format(PyExc_OverflowError, "events set too many times");
2105
0
        _PyEval_StartTheWorld(interp);
2106
0
        return -1;
2107
0
    }
2108
2109
    // monitoring_tool_versions[tool_id] is set to latest global version here to
2110
    //   1. invalidate local events on all existing code objects
2111
    //   2. be ready for the next call to set local events
2112
0
    interp->monitoring_tool_versions[tool_id] = version;
2113
2114
    // Set the new global version so all the code objects can refresh the
2115
    // instrumentation.
2116
0
    set_global_version(_PyThreadState_GET(), version);
2117
0
    int res = instrument_all_executing_code_objects(interp);
2118
0
    _PyEval_StartTheWorld(interp);
2119
0
    return res;
2120
0
}
2121
2122
/*[clinic input]
2123
module monitoring
2124
[clinic start generated code]*/
2125
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=37257f5987a360cf]*/
2126
/*[clinic end generated code]*/
2127
2128
#include "clinic/instrumentation.c.h"
2129
2130
static int
2131
check_valid_tool(int tool_id)
2132
0
{
2133
0
    if (tool_id < 0 || tool_id >= PY_MONITORING_SYS_PROFILE_ID) {
2134
0
        PyErr_Format(PyExc_ValueError, "invalid tool %d (must be between 0 and 5)", tool_id);
2135
0
        return -1;
2136
0
    }
2137
0
    return 0;
2138
0
}
2139
2140
/*[clinic input]
2141
monitoring.use_tool_id
2142
2143
    tool_id: int
2144
    name: object
2145
    /
2146
2147
[clinic start generated code]*/
2148
2149
static PyObject *
2150
monitoring_use_tool_id_impl(PyObject *module, int tool_id, PyObject *name)
2151
/*[clinic end generated code: output=30d76dc92b7cd653 input=ebc453761c621be1]*/
2152
0
{
2153
0
    if (check_valid_tool(tool_id))  {
2154
0
        return NULL;
2155
0
    }
2156
0
    if (!PyUnicode_Check(name)) {
2157
0
        PyErr_SetString(PyExc_ValueError, "tool name must be a str");
2158
0
        return NULL;
2159
0
    }
2160
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
2161
0
    if (interp->monitoring_tool_names[tool_id] != NULL) {
2162
0
        PyErr_Format(PyExc_ValueError, "tool %d is already in use", tool_id);
2163
0
        return NULL;
2164
0
    }
2165
0
    interp->monitoring_tool_names[tool_id] = Py_NewRef(name);
2166
0
    Py_RETURN_NONE;
2167
0
}
2168
2169
/*[clinic input]
2170
monitoring.clear_tool_id
2171
2172
    tool_id: int
2173
    /
2174
2175
[clinic start generated code]*/
2176
2177
static PyObject *
2178
monitoring_clear_tool_id_impl(PyObject *module, int tool_id)
2179
/*[clinic end generated code: output=04defc23470b1be7 input=af643d6648a66163]*/
2180
0
{
2181
0
    if (check_valid_tool(tool_id))  {
2182
0
        return NULL;
2183
0
    }
2184
2185
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
2186
2187
0
    if (interp->monitoring_tool_names[tool_id] != NULL) {
2188
0
        if (_PyMonitoring_ClearToolId(tool_id) < 0) {
2189
0
            return NULL;
2190
0
        }
2191
0
    }
2192
2193
0
    Py_RETURN_NONE;
2194
0
}
2195
2196
/*[clinic input]
2197
monitoring.free_tool_id
2198
2199
    tool_id: int
2200
    /
2201
2202
[clinic start generated code]*/
2203
2204
static PyObject *
2205
monitoring_free_tool_id_impl(PyObject *module, int tool_id)
2206
/*[clinic end generated code: output=86c2d2a1219a8591 input=a23fb6be3a8618e9]*/
2207
0
{
2208
0
    if (check_valid_tool(tool_id))  {
2209
0
        return NULL;
2210
0
    }
2211
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
2212
2213
0
    if (interp->monitoring_tool_names[tool_id] != NULL) {
2214
0
        if (_PyMonitoring_ClearToolId(tool_id) < 0) {
2215
0
            return NULL;
2216
0
        }
2217
0
    }
2218
2219
0
    Py_CLEAR(interp->monitoring_tool_names[tool_id]);
2220
0
    Py_RETURN_NONE;
2221
0
}
2222
2223
/*[clinic input]
2224
monitoring.get_tool
2225
2226
    tool_id: int
2227
    /
2228
2229
[clinic start generated code]*/
2230
2231
static PyObject *
2232
monitoring_get_tool_impl(PyObject *module, int tool_id)
2233
/*[clinic end generated code: output=1c05a98b404a9a16 input=eeee9bebd0bcae9d]*/
2234
2235
/*[clinic end generated code]*/
2236
0
{
2237
0
    if (check_valid_tool(tool_id))  {
2238
0
        return NULL;
2239
0
    }
2240
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
2241
0
    PyObject *name = interp->monitoring_tool_names[tool_id];
2242
0
    if (name == NULL) {
2243
0
        Py_RETURN_NONE;
2244
0
    }
2245
0
    return Py_NewRef(name);
2246
0
}
2247
2248
/*[clinic input]
2249
monitoring.register_callback
2250
2251
2252
    tool_id: int
2253
    event: int
2254
    func: object
2255
    /
2256
2257
[clinic start generated code]*/
2258
2259
static PyObject *
2260
monitoring_register_callback_impl(PyObject *module, int tool_id, int event,
2261
                                  PyObject *func)
2262
/*[clinic end generated code: output=e64daa363004030c input=df6d70ea4cf81007]*/
2263
0
{
2264
0
    if (check_valid_tool(tool_id))  {
2265
0
        return NULL;
2266
0
    }
2267
0
    if (_Py_popcount32(event) != 1) {
2268
0
        PyErr_SetString(PyExc_ValueError, "The callback can only be set for one event at a time");
2269
0
        return NULL;
2270
0
    }
2271
0
    int event_id = _Py_bit_length(event)-1;
2272
0
    if (event_id < 0 || event_id >= _PY_MONITORING_EVENTS) {
2273
0
        PyErr_Format(PyExc_ValueError, "invalid event %d", event);
2274
0
        return NULL;
2275
0
    }
2276
0
    if (PySys_Audit("sys.monitoring.register_callback", "O", func) < 0) {
2277
0
        return NULL;
2278
0
    }
2279
0
    if (func == Py_None) {
2280
0
        func = NULL;
2281
0
    }
2282
0
    func = _PyMonitoring_RegisterCallback(tool_id, event_id, func);
2283
0
    if (func == NULL) {
2284
0
        Py_RETURN_NONE;
2285
0
    }
2286
0
    return func;
2287
0
}
2288
2289
/*[clinic input]
2290
monitoring.get_events -> int
2291
2292
    tool_id: int
2293
    /
2294
2295
[clinic start generated code]*/
2296
2297
static int
2298
monitoring_get_events_impl(PyObject *module, int tool_id)
2299
/*[clinic end generated code: output=4450cc13f826c8c0 input=a64b238f76c4b2f7]*/
2300
0
{
2301
0
    if (check_valid_tool(tool_id))  {
2302
0
        return -1;
2303
0
    }
2304
0
    _Py_GlobalMonitors *m = &_PyInterpreterState_GET()->monitors;
2305
0
    _PyMonitoringEventSet event_set = get_events(m, tool_id);
2306
0
    return event_set;
2307
0
}
2308
2309
/*[clinic input]
2310
monitoring.set_events
2311
2312
    tool_id: int
2313
    event_set: int
2314
    /
2315
2316
[clinic start generated code]*/
2317
2318
static PyObject *
2319
monitoring_set_events_impl(PyObject *module, int tool_id, int event_set)
2320
/*[clinic end generated code: output=1916c1e49cfb5bdb input=a77ba729a242142b]*/
2321
0
{
2322
0
    if (check_valid_tool(tool_id))  {
2323
0
        return NULL;
2324
0
    }
2325
0
    if (event_set < 0 || event_set >= (1 << _PY_MONITORING_EVENTS)) {
2326
0
        PyErr_Format(PyExc_ValueError, "invalid event set 0x%x", event_set);
2327
0
        return NULL;
2328
0
    }
2329
0
    if ((event_set & C_RETURN_EVENTS) && (event_set & C_CALL_EVENTS) != C_CALL_EVENTS) {
2330
0
        PyErr_Format(PyExc_ValueError, "cannot set C_RETURN or C_RAISE events independently");
2331
0
        return NULL;
2332
0
    }
2333
0
    event_set &= ~C_RETURN_EVENTS;
2334
0
    if (event_set & (1 << PY_MONITORING_EVENT_BRANCH)) {
2335
0
        event_set &= ~(1 << PY_MONITORING_EVENT_BRANCH);
2336
0
        event_set |= (1 << PY_MONITORING_EVENT_BRANCH_RIGHT) | (1 << PY_MONITORING_EVENT_BRANCH_LEFT);
2337
0
    }
2338
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
2339
0
    _PyEval_StopTheWorld(interp);
2340
0
    int err = _PyMonitoring_SetEvents(tool_id, event_set);
2341
0
    _PyEval_StartTheWorld(interp);
2342
0
    if (err) {
2343
0
        return NULL;
2344
0
    }
2345
0
    Py_RETURN_NONE;
2346
0
}
2347
2348
/*[clinic input]
2349
monitoring.get_local_events -> int
2350
2351
    tool_id: int
2352
    code: object
2353
    /
2354
2355
[clinic start generated code]*/
2356
2357
static int
2358
monitoring_get_local_events_impl(PyObject *module, int tool_id,
2359
                                 PyObject *code)
2360
/*[clinic end generated code: output=d3e92c1c9c1de8f9 input=bb0f927530386a94]*/
2361
0
{
2362
0
    if (!PyCode_Check(code)) {
2363
0
        PyErr_Format(
2364
0
            PyExc_TypeError,
2365
0
            "code must be a code object"
2366
0
        );
2367
0
        return -1;
2368
0
    }
2369
0
    if (check_valid_tool(tool_id))  {
2370
0
        return -1;
2371
0
    }
2372
0
    _PyMonitoringEventSet event_set = 0;
2373
0
    _PyCoMonitoringData *data = ((PyCodeObject *)code)->_co_monitoring;
2374
0
    if (data != NULL) {
2375
0
        for (int e = 0; e < _PY_MONITORING_LOCAL_EVENTS; e++) {
2376
0
            if ((data->local_monitors.tools[e] >> tool_id) & 1) {
2377
0
                event_set |= (1 << e);
2378
0
            }
2379
0
        }
2380
0
    }
2381
0
    return event_set;
2382
0
}
2383
2384
/*[clinic input]
2385
monitoring.set_local_events
2386
2387
    tool_id: int
2388
    code: object
2389
    event_set: int
2390
    /
2391
2392
[clinic start generated code]*/
2393
2394
static PyObject *
2395
monitoring_set_local_events_impl(PyObject *module, int tool_id,
2396
                                 PyObject *code, int event_set)
2397
/*[clinic end generated code: output=68cc755a65dfea99 input=5655ecd78d937a29]*/
2398
0
{
2399
0
    if (!PyCode_Check(code)) {
2400
0
        PyErr_Format(
2401
0
            PyExc_TypeError,
2402
0
            "code must be a code object"
2403
0
        );
2404
0
        return NULL;
2405
0
    }
2406
0
    if (check_valid_tool(tool_id))  {
2407
0
        return NULL;
2408
0
    }
2409
0
    if ((event_set & C_RETURN_EVENTS) && (event_set & C_CALL_EVENTS) != C_CALL_EVENTS) {
2410
0
        PyErr_Format(PyExc_ValueError, "cannot set C_RETURN or C_RAISE events independently");
2411
0
        return NULL;
2412
0
    }
2413
0
    event_set &= ~C_RETURN_EVENTS;
2414
0
    if (event_set & (1 << PY_MONITORING_EVENT_BRANCH)) {
2415
0
        event_set &= ~(1 << PY_MONITORING_EVENT_BRANCH);
2416
0
        event_set |= (1 << PY_MONITORING_EVENT_BRANCH_RIGHT) | (1 << PY_MONITORING_EVENT_BRANCH_LEFT);
2417
0
    }
2418
0
    if (event_set < 0 || event_set >= (1 << _PY_MONITORING_LOCAL_EVENTS)) {
2419
0
        PyErr_Format(PyExc_ValueError, "invalid local event set 0x%x", event_set);
2420
0
        return NULL;
2421
0
    }
2422
2423
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
2424
0
    _PyEval_StopTheWorld(interp);
2425
0
    int err = _PyMonitoring_SetLocalEvents((PyCodeObject*)code, tool_id, event_set);
2426
0
    _PyEval_StartTheWorld(interp);
2427
0
    if (err) {
2428
0
        return NULL;
2429
0
    }
2430
0
    Py_RETURN_NONE;
2431
0
}
2432
2433
/*[clinic input]
2434
monitoring.restart_events
2435
2436
[clinic start generated code]*/
2437
2438
static PyObject *
2439
monitoring_restart_events_impl(PyObject *module)
2440
/*[clinic end generated code: output=e025dd5ba33314c4 input=add8a855063c8008]*/
2441
0
{
2442
    /* We want to ensure that:
2443
     * last restart version > instrumented version for all code objects
2444
     * last restart version < current version
2445
     */
2446
0
    PyThreadState *tstate = _PyThreadState_GET();
2447
0
    PyInterpreterState *interp = tstate->interp;
2448
2449
0
    _PyEval_StopTheWorld(interp);
2450
0
    uint32_t restart_version = global_version(interp) + MONITORING_VERSION_INCREMENT;
2451
0
    uint32_t new_version = restart_version + MONITORING_VERSION_INCREMENT;
2452
0
    if (new_version <= MONITORING_VERSION_INCREMENT) {
2453
0
        _PyEval_StartTheWorld(interp);
2454
0
        PyErr_Format(PyExc_OverflowError, "events set too many times");
2455
0
        return NULL;
2456
0
    }
2457
0
    interp->last_restart_version = restart_version;
2458
0
    set_global_version(tstate, new_version);
2459
0
    int res = instrument_all_executing_code_objects(interp);
2460
0
    _PyEval_StartTheWorld(interp);
2461
2462
0
    if (res) {
2463
0
        return NULL;
2464
0
    }
2465
0
    Py_RETURN_NONE;
2466
0
}
2467
2468
static int
2469
add_power2_constant(PyObject *obj, const char *name, int i)
2470
304
{
2471
304
    PyObject *val = PyLong_FromLong(1<<i);
2472
304
    if (val == NULL) {
2473
0
        return -1;
2474
0
    }
2475
304
    int err = PyObject_SetAttrString(obj, name, val);
2476
304
    Py_DECREF(val);
2477
304
    return err;
2478
304
}
2479
2480
/*[clinic input]
2481
monitoring._all_events
2482
[clinic start generated code]*/
2483
2484
static PyObject *
2485
monitoring__all_events_impl(PyObject *module)
2486
/*[clinic end generated code: output=6b7581e2dbb690f6 input=62ee9672c17b7f0e]*/
2487
0
{
2488
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
2489
0
    PyObject *res = PyDict_New();
2490
0
    if (res == NULL) {
2491
0
        return NULL;
2492
0
    }
2493
0
    for (int e = 0; e < _PY_MONITORING_UNGROUPED_EVENTS; e++) {
2494
0
        uint8_t tools = interp->monitors.tools[e];
2495
0
        if (tools == 0) {
2496
0
            continue;
2497
0
        }
2498
0
        PyObject *tools_obj = PyLong_FromLong(tools);
2499
0
        assert(tools_obj != NULL);
2500
0
        int err = PyDict_SetItemString(res, event_names[e], tools_obj);
2501
0
        Py_DECREF(tools_obj);
2502
0
        if (err < 0) {
2503
0
            Py_DECREF(res);
2504
0
            return NULL;
2505
0
        }
2506
0
    }
2507
0
    return res;
2508
0
}
2509
2510
static PyMethodDef methods[] = {
2511
    MONITORING_USE_TOOL_ID_METHODDEF
2512
    MONITORING_CLEAR_TOOL_ID_METHODDEF
2513
    MONITORING_FREE_TOOL_ID_METHODDEF
2514
    MONITORING_GET_TOOL_METHODDEF
2515
    MONITORING_REGISTER_CALLBACK_METHODDEF
2516
    MONITORING_GET_EVENTS_METHODDEF
2517
    MONITORING_SET_EVENTS_METHODDEF
2518
    MONITORING_GET_LOCAL_EVENTS_METHODDEF
2519
    MONITORING_SET_LOCAL_EVENTS_METHODDEF
2520
    MONITORING_RESTART_EVENTS_METHODDEF
2521
    MONITORING__ALL_EVENTS_METHODDEF
2522
    {NULL, NULL}  // sentinel
2523
};
2524
2525
static struct PyModuleDef monitoring_module = {
2526
    PyModuleDef_HEAD_INIT,
2527
    .m_name = "sys.monitoring",
2528
    .m_size = -1, /* multiple "initialization" just copies the module dict. */
2529
    .m_methods = methods,
2530
};
2531
2532
PyObject *_Py_CreateMonitoringObject(void)
2533
16
{
2534
16
    PyObject *mod = _PyModule_CreateInitialized(&monitoring_module, PYTHON_API_VERSION);
2535
16
    if (mod == NULL) {
2536
0
        return NULL;
2537
0
    }
2538
16
    if (PyObject_SetAttrString(mod, "DISABLE", &_PyInstrumentation_DISABLE)) {
2539
0
        goto error;
2540
0
    }
2541
16
    if (PyObject_SetAttrString(mod, "MISSING", &_PyInstrumentation_MISSING)) {
2542
0
        goto error;
2543
0
    }
2544
16
    PyObject *events = _PyNamespace_New(NULL);
2545
16
    if (events == NULL) {
2546
0
        goto error;
2547
0
    }
2548
16
    int err = PyObject_SetAttrString(mod, "events", events);
2549
16
    Py_DECREF(events);
2550
16
    if (err) {
2551
0
        goto error;
2552
0
    }
2553
320
    for (int i = 0; i < _PY_MONITORING_EVENTS; i++) {
2554
304
        if (add_power2_constant(events, event_names[i], i)) {
2555
0
            goto error;
2556
0
        }
2557
304
    }
2558
16
    err = PyObject_SetAttrString(events, "NO_EVENTS", _PyLong_GetZero());
2559
16
    if (err) goto error;
2560
16
    PyObject *val = PyLong_FromLong(PY_MONITORING_DEBUGGER_ID);
2561
16
    assert(val != NULL); /* Can't return NULL because the int is small. */
2562
16
    err = PyObject_SetAttrString(mod, "DEBUGGER_ID", val);
2563
16
    Py_DECREF(val);
2564
16
    if (err) goto error;
2565
16
    val = PyLong_FromLong(PY_MONITORING_COVERAGE_ID);
2566
16
    assert(val != NULL);
2567
16
    err = PyObject_SetAttrString(mod, "COVERAGE_ID", val);
2568
16
    Py_DECREF(val);
2569
16
    if (err) goto error;
2570
16
    val = PyLong_FromLong(PY_MONITORING_PROFILER_ID);
2571
16
    assert(val != NULL);
2572
16
    err = PyObject_SetAttrString(mod, "PROFILER_ID", val);
2573
16
    Py_DECREF(val);
2574
16
    if (err) goto error;
2575
16
    val = PyLong_FromLong(PY_MONITORING_OPTIMIZER_ID);
2576
16
    assert(val != NULL);
2577
16
    err = PyObject_SetAttrString(mod, "OPTIMIZER_ID", val);
2578
16
    Py_DECREF(val);
2579
16
    if (err) goto error;
2580
16
    return mod;
2581
0
error:
2582
0
    Py_DECREF(mod);
2583
0
    return NULL;
2584
16
}
2585
2586
2587
static int
2588
capi_call_instrumentation(PyMonitoringState *state, PyObject *codelike, int32_t offset,
2589
                          PyObject **args, Py_ssize_t nargs, int event)
2590
0
{
2591
0
    PyThreadState *tstate = _PyThreadState_GET();
2592
0
    PyInterpreterState *interp = tstate->interp;
2593
2594
0
    uint8_t tools = state->active;
2595
0
    assert(args[1] == NULL);
2596
0
    args[1] = codelike;
2597
0
    if (offset < 0) {
2598
0
        PyErr_SetString(PyExc_ValueError, "offset must be non-negative");
2599
0
        return -1;
2600
0
    }
2601
0
    if (event != PY_MONITORING_EVENT_LINE) {
2602
0
        PyObject *offset_obj = PyLong_FromLong(offset);
2603
0
        if (offset_obj == NULL) {
2604
0
            return -1;
2605
0
        }
2606
0
        assert(args[2] == NULL);
2607
0
        args[2] = offset_obj;
2608
0
    }
2609
0
    size_t nargsf = (size_t) nargs | PY_VECTORCALL_ARGUMENTS_OFFSET;
2610
0
    PyObject **callargs = &args[1];
2611
0
    int err = 0;
2612
2613
0
    while (tools) {
2614
0
        int tool = most_significant_bit(tools);
2615
0
        assert(tool >= 0 && tool < 8);
2616
0
        assert(tools & (1 << tool));
2617
0
        tools ^= (1 << tool);
2618
0
        int res = call_one_instrument(interp, tstate, callargs, nargsf, tool, event);
2619
0
        if (res == 0) {
2620
            /* Nothing to do */
2621
0
        }
2622
0
        else if (res < 0) {
2623
            /* error */
2624
0
            err = -1;
2625
0
            break;
2626
0
        }
2627
0
        else {
2628
            /* DISABLE */
2629
0
            if (!PY_MONITORING_IS_INSTRUMENTED_EVENT(event)) {
2630
0
                PyErr_Format(PyExc_ValueError,
2631
0
                             "Cannot disable %s events. Callback removed.",
2632
0
                             event_names[event]);
2633
                /* Clear tool to prevent infinite loop */
2634
0
                Py_CLEAR(interp->monitoring_callables[tool][event]);
2635
0
                err = -1;
2636
0
                break;
2637
0
            }
2638
0
            else {
2639
0
                state->active &= ~(1 << tool);
2640
0
            }
2641
0
        }
2642
0
    }
2643
0
    return err;
2644
0
}
2645
2646
int
2647
PyMonitoring_EnterScope(PyMonitoringState *state_array, uint64_t *version,
2648
                         const uint8_t *event_types, Py_ssize_t length)
2649
0
{
2650
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
2651
0
    if (global_version(interp) == *version) {
2652
0
        return 0;
2653
0
    }
2654
2655
0
    _Py_GlobalMonitors *m = &interp->monitors;
2656
0
    for (Py_ssize_t i = 0; i < length; i++) {
2657
0
        int event = event_types[i];
2658
0
        state_array[i].active = m->tools[event];
2659
0
    }
2660
0
    *version = global_version(interp);
2661
0
    return 0;
2662
0
}
2663
2664
int
2665
PyMonitoring_ExitScope(void)
2666
0
{
2667
0
    return 0;
2668
0
}
2669
2670
int
2671
_PyMonitoring_FirePyStartEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset)
2672
0
{
2673
0
    assert(state->active);
2674
0
    PyObject *args[3] = { NULL, NULL, NULL };
2675
0
    return capi_call_instrumentation(state, codelike, offset, args, 2,
2676
0
                                     PY_MONITORING_EVENT_PY_START);
2677
0
}
2678
2679
int
2680
_PyMonitoring_FirePyResumeEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset)
2681
0
{
2682
0
    assert(state->active);
2683
0
    PyObject *args[3] = { NULL, NULL, NULL };
2684
0
    return capi_call_instrumentation(state, codelike, offset, args, 2,
2685
0
                                     PY_MONITORING_EVENT_PY_RESUME);
2686
0
}
2687
2688
2689
2690
int
2691
_PyMonitoring_FirePyReturnEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset,
2692
                                PyObject* retval)
2693
0
{
2694
0
    assert(state->active);
2695
0
    PyObject *args[4] = { NULL, NULL, NULL, retval };
2696
0
    return capi_call_instrumentation(state, codelike, offset, args, 3,
2697
0
                                     PY_MONITORING_EVENT_PY_RETURN);
2698
0
}
2699
2700
int
2701
_PyMonitoring_FirePyYieldEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset,
2702
                               PyObject* retval)
2703
0
{
2704
0
    assert(state->active);
2705
0
    PyObject *args[4] = { NULL, NULL, NULL, retval };
2706
0
    return capi_call_instrumentation(state, codelike, offset, args, 3,
2707
0
                                     PY_MONITORING_EVENT_PY_YIELD);
2708
0
}
2709
2710
int
2711
_PyMonitoring_FireCallEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset,
2712
                            PyObject* callable, PyObject *arg0)
2713
0
{
2714
0
    assert(state->active);
2715
0
    PyObject *args[5] = { NULL, NULL, NULL, callable, arg0 };
2716
0
    return capi_call_instrumentation(state, codelike, offset, args, 4,
2717
0
                                     PY_MONITORING_EVENT_CALL);
2718
0
}
2719
2720
int
2721
_PyMonitoring_FireLineEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset,
2722
                            int lineno)
2723
0
{
2724
0
    assert(state->active);
2725
0
    PyObject *lno = PyLong_FromLong(lineno);
2726
0
    if (lno == NULL) {
2727
0
        return -1;
2728
0
    }
2729
0
    PyObject *args[3] = { NULL, NULL, lno };
2730
0
    int res= capi_call_instrumentation(state, codelike, offset, args, 2,
2731
0
                                       PY_MONITORING_EVENT_LINE);
2732
0
    Py_DECREF(lno);
2733
0
    return res;
2734
0
}
2735
2736
int
2737
_PyMonitoring_FireJumpEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset,
2738
                            PyObject *target_offset)
2739
0
{
2740
0
    assert(state->active);
2741
0
    PyObject *args[4] = { NULL, NULL, NULL, target_offset };
2742
0
    return capi_call_instrumentation(state, codelike, offset, args, 3,
2743
0
                                     PY_MONITORING_EVENT_JUMP);
2744
0
}
2745
2746
int
2747
_PyMonitoring_FireBranchEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset,
2748
                              PyObject *target_offset)
2749
0
{
2750
0
    assert(state->active);
2751
0
    PyObject *args[4] = { NULL, NULL, NULL, target_offset };
2752
0
    return capi_call_instrumentation(state, codelike, offset, args, 3,
2753
0
                                     PY_MONITORING_EVENT_BRANCH_RIGHT);
2754
0
}
2755
2756
int
2757
_PyMonitoring_FireBranchRightEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset,
2758
                              PyObject *target_offset)
2759
0
{
2760
0
    assert(state->active);
2761
0
    PyObject *args[4] = { NULL, NULL, NULL, target_offset };
2762
0
    return capi_call_instrumentation(state, codelike, offset, args, 3,
2763
0
                                     PY_MONITORING_EVENT_BRANCH_RIGHT);
2764
0
}
2765
2766
int
2767
_PyMonitoring_FireBranchLeftEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset,
2768
                              PyObject *target_offset)
2769
0
{
2770
0
    assert(state->active);
2771
0
    PyObject *args[4] = { NULL, NULL, NULL, target_offset };
2772
0
    return capi_call_instrumentation(state, codelike, offset, args, 3,
2773
0
                                     PY_MONITORING_EVENT_BRANCH_LEFT);
2774
0
}
2775
2776
int
2777
_PyMonitoring_FireCReturnEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset,
2778
                               PyObject *retval)
2779
0
{
2780
0
    assert(state->active);
2781
0
    PyObject *args[4] = { NULL, NULL, NULL, retval };
2782
0
    return capi_call_instrumentation(state, codelike, offset, args, 3,
2783
0
                                     PY_MONITORING_EVENT_C_RETURN);
2784
0
}
2785
2786
static inline int
2787
0
exception_event_setup(PyObject **exc, int event) {
2788
0
    *exc = PyErr_GetRaisedException();
2789
0
    if (*exc == NULL) {
2790
0
        PyErr_Format(PyExc_ValueError,
2791
0
                     "Firing event %d with no exception set",
2792
0
                     event);
2793
0
        return -1;
2794
0
    }
2795
0
    return 0;
2796
0
}
2797
2798
2799
static inline int
2800
0
exception_event_teardown(int err, PyObject *exc) {
2801
0
    if (err == 0) {
2802
0
        PyErr_SetRaisedException(exc);
2803
0
    }
2804
0
    else {
2805
0
        assert(PyErr_Occurred());
2806
0
        Py_XDECREF(exc);
2807
0
    }
2808
0
    return err;
2809
0
}
2810
2811
int
2812
_PyMonitoring_FirePyThrowEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset)
2813
0
{
2814
0
    int event = PY_MONITORING_EVENT_PY_THROW;
2815
0
    assert(state->active);
2816
0
    PyObject *exc;
2817
0
    if (exception_event_setup(&exc, event) < 0) {
2818
0
        return -1;
2819
0
    }
2820
0
    PyObject *args[4] = { NULL, NULL, NULL, exc };
2821
0
    int err = capi_call_instrumentation(state, codelike, offset, args, 3, event);
2822
0
    return exception_event_teardown(err, exc);
2823
0
}
2824
2825
int
2826
_PyMonitoring_FireRaiseEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset)
2827
0
{
2828
0
    int event = PY_MONITORING_EVENT_RAISE;
2829
0
    assert(state->active);
2830
0
    PyObject *exc;
2831
0
    if (exception_event_setup(&exc, event) < 0) {
2832
0
        return -1;
2833
0
    }
2834
0
    PyObject *args[4] = { NULL, NULL, NULL, exc };
2835
0
    int err = capi_call_instrumentation(state, codelike, offset, args, 3, event);
2836
0
    return exception_event_teardown(err, exc);
2837
0
}
2838
2839
int
2840
_PyMonitoring_FireCRaiseEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset)
2841
0
{
2842
0
    int event = PY_MONITORING_EVENT_C_RAISE;
2843
0
    assert(state->active);
2844
0
    PyObject *exc;
2845
0
    if (exception_event_setup(&exc, event) < 0) {
2846
0
        return -1;
2847
0
    }
2848
0
    PyObject *args[4] = { NULL, NULL, NULL, exc };
2849
0
    int err = capi_call_instrumentation(state, codelike, offset, args, 3, event);
2850
0
    return exception_event_teardown(err, exc);
2851
0
}
2852
2853
int
2854
_PyMonitoring_FireReraiseEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset)
2855
0
{
2856
0
    int event = PY_MONITORING_EVENT_RERAISE;
2857
0
    assert(state->active);
2858
0
    PyObject *exc;
2859
0
    if (exception_event_setup(&exc, event) < 0) {
2860
0
        return -1;
2861
0
    }
2862
0
    PyObject *args[4] = { NULL, NULL, NULL, exc };
2863
0
    int err = capi_call_instrumentation(state, codelike, offset, args, 3, event);
2864
0
    return exception_event_teardown(err, exc);
2865
0
}
2866
2867
int
2868
_PyMonitoring_FireExceptionHandledEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset)
2869
0
{
2870
0
    int event = PY_MONITORING_EVENT_EXCEPTION_HANDLED;
2871
0
    assert(state->active);
2872
0
    PyObject *exc;
2873
0
    if (exception_event_setup(&exc, event) < 0) {
2874
0
        return -1;
2875
0
    }
2876
0
    PyObject *args[4] = { NULL, NULL, NULL, exc };
2877
0
    int err = capi_call_instrumentation(state, codelike, offset, args, 3, event);
2878
0
    return exception_event_teardown(err, exc);
2879
0
}
2880
2881
int
2882
_PyMonitoring_FirePyUnwindEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset)
2883
0
{
2884
0
    int event = PY_MONITORING_EVENT_PY_UNWIND;
2885
0
    assert(state->active);
2886
0
    PyObject *exc;
2887
0
    if (exception_event_setup(&exc, event) < 0) {
2888
0
        return -1;
2889
0
    }
2890
0
    PyObject *args[4] = { NULL, NULL, NULL, exc };
2891
0
    int err = capi_call_instrumentation(state, codelike, offset, args, 3, event);
2892
0
    return exception_event_teardown(err, exc);
2893
0
}
2894
2895
int
2896
_PyMonitoring_FireStopIterationEvent(PyMonitoringState *state, PyObject *codelike, int32_t offset, PyObject *value)
2897
0
{
2898
0
    int event = PY_MONITORING_EVENT_STOP_ITERATION;
2899
0
    assert(state->active);
2900
0
    assert(!PyErr_Occurred());
2901
0
    PyErr_SetObject(PyExc_StopIteration, value);
2902
0
    PyObject *exc;
2903
0
    if (exception_event_setup(&exc, event) < 0) {
2904
0
        return -1;
2905
0
    }
2906
0
    PyObject *args[4] = { NULL, NULL, NULL, exc };
2907
0
    int err = capi_call_instrumentation(state, codelike, offset, args, 3, event);
2908
0
    Py_DECREF(exc);
2909
0
    return exception_event_teardown(err, NULL);
2910
0
}
2911
2912
2913
2914
/* Handle legacy BRANCH event */
2915
2916
typedef struct _PyLegacyBranchEventHandler {
2917
    PyObject_HEAD
2918
    vectorcallfunc vectorcall;
2919
    PyObject *handler;
2920
    bool right;
2921
    int tool_id;
2922
} _PyLegacyBranchEventHandler;
2923
2924
0
#define _PyLegacyBranchEventHandler_CAST(op)    ((_PyLegacyBranchEventHandler *)(op))
2925
2926
static void
2927
dealloc_branch_handler(PyObject *op)
2928
0
{
2929
0
    _PyLegacyBranchEventHandler *self = _PyLegacyBranchEventHandler_CAST(op);
2930
0
    Py_CLEAR(self->handler);
2931
0
    PyObject_Free(self);
2932
0
}
2933
2934
static PyTypeObject _PyLegacyBranchEventHandler_Type = {
2935
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
2936
    "sys.monitoring.branch_event_handler",
2937
    sizeof(_PyLegacyBranchEventHandler),
2938
    .tp_dealloc = dealloc_branch_handler,
2939
    .tp_vectorcall_offset = offsetof(_PyLegacyBranchEventHandler, vectorcall),
2940
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
2941
        Py_TPFLAGS_HAVE_VECTORCALL | Py_TPFLAGS_DISALLOW_INSTANTIATION,
2942
    .tp_call = PyVectorcall_Call,
2943
};
2944
2945
2946
static PyObject *
2947
branch_handler_vectorcall(
2948
    PyObject *op, PyObject *const *args,
2949
    size_t nargsf, PyObject *kwnames
2950
0
) {
2951
0
    _PyLegacyBranchEventHandler *self = _PyLegacyBranchEventHandler_CAST(op);
2952
    // Find the other instrumented instruction and remove tool
2953
    // The spec (PEP 669) allows spurious events after a DISABLE,
2954
    // so a best effort is good enough.
2955
0
    assert(PyVectorcall_NARGS(nargsf) >= 3);
2956
0
    PyCodeObject *code = (PyCodeObject *)args[0];
2957
0
    int src_offset = PyLong_AsLong(args[1]);
2958
0
    if (PyErr_Occurred()) {
2959
0
        return NULL;
2960
0
    }
2961
0
    _Py_CODEUNIT instr = _PyCode_CODE(code)[src_offset/2];
2962
0
    if (!is_instrumented(instr.op.code)) {
2963
        /* Already disabled */
2964
0
        return &_PyInstrumentation_DISABLE;
2965
0
    }
2966
0
    PyObject *res = PyObject_Vectorcall(self->handler, args, nargsf, kwnames);
2967
0
    if (res == &_PyInstrumentation_DISABLE) {
2968
        /* We need FOR_ITER and POP_JUMP_ to be the same size */
2969
0
        assert(INLINE_CACHE_ENTRIES_FOR_ITER == 1);
2970
0
        int offset;
2971
0
        int other_event;
2972
0
        if (instr.op.code == FOR_ITER) {
2973
0
            if (self->right) {
2974
0
                offset = src_offset/2;
2975
0
                other_event = PY_MONITORING_EVENT_BRANCH_LEFT;
2976
0
            }
2977
0
            else {
2978
                // We don't know where the POP_ITER is, so
2979
                // we cannot de-instrument it.
2980
0
                return res;
2981
0
            }
2982
0
        }
2983
0
        else if (IS_CONDITIONAL_JUMP_OPCODE(instr.op.code)) {
2984
0
            if (self->right) {
2985
0
                offset = src_offset/2 + 2;
2986
0
                other_event = PY_MONITORING_EVENT_BRANCH_LEFT;
2987
0
                assert(_Py_GetBaseCodeUnit(code, offset).op.code == NOT_TAKEN);
2988
0
            }
2989
0
            else {
2990
0
                offset = src_offset/2;
2991
0
                other_event = PY_MONITORING_EVENT_BRANCH_RIGHT;
2992
0
            }
2993
0
        }
2994
0
        else {
2995
            // Orphaned NOT_TAKEN -- Jump removed by the compiler
2996
0
            return res;
2997
0
        }
2998
0
        PyInterpreterState *interp = _PyInterpreterState_GET();
2999
0
        _PyEval_StopTheWorld(interp);
3000
0
        remove_tools(code, offset, other_event, 1 << self->tool_id);
3001
0
        _PyEval_StartTheWorld(interp);
3002
0
    }
3003
0
    return res;
3004
0
}
3005
3006
static PyObject *make_branch_handler(int tool_id, PyObject *handler, bool right)
3007
0
{
3008
0
    _PyLegacyBranchEventHandler *callback =
3009
0
        PyObject_NEW(_PyLegacyBranchEventHandler, &_PyLegacyBranchEventHandler_Type);
3010
0
    if (callback == NULL) {
3011
0
        return NULL;
3012
0
    }
3013
0
    callback->vectorcall = branch_handler_vectorcall;
3014
0
    callback->handler = Py_NewRef(handler);
3015
0
    callback->right = right;
3016
0
    callback->tool_id = tool_id;
3017
0
    return (PyObject *)callback;
3018
0
}
3019
3020
PyObject *
3021
_PyMonitoring_RegisterCallback(int tool_id, int event_id, PyObject *obj)
3022
0
{
3023
0
    assert(0 <= tool_id && tool_id < PY_MONITORING_TOOL_IDS);
3024
0
    assert(0 <= event_id && event_id < _PY_MONITORING_EVENTS);
3025
0
    PyObject *res;
3026
0
    if (event_id == PY_MONITORING_EVENT_BRANCH) {
3027
0
        PyObject *left, *right;
3028
0
        if (obj == NULL) {
3029
0
            left = NULL;
3030
0
            right = NULL;
3031
0
        }
3032
0
        else {
3033
0
            right = make_branch_handler(tool_id, obj, true);
3034
0
            if (right == NULL) {
3035
0
                return NULL;
3036
0
            }
3037
0
            left = make_branch_handler(tool_id, obj, false);
3038
0
            if (left == NULL) {
3039
0
                Py_DECREF(right);
3040
0
                return NULL;
3041
0
            }
3042
0
        }
3043
0
        PyInterpreterState *interp = _PyInterpreterState_GET();
3044
0
        _PyEval_StopTheWorld(interp);
3045
0
        PyObject *old_right = interp->monitoring_callables[tool_id][PY_MONITORING_EVENT_BRANCH_RIGHT];
3046
0
        interp->monitoring_callables[tool_id][PY_MONITORING_EVENT_BRANCH_RIGHT] = right;
3047
0
        res = interp->monitoring_callables[tool_id][PY_MONITORING_EVENT_BRANCH_LEFT];
3048
0
        interp->monitoring_callables[tool_id][PY_MONITORING_EVENT_BRANCH_LEFT] = left;
3049
0
        _PyEval_StartTheWorld(interp);
3050
0
        Py_XDECREF(old_right);
3051
0
    }
3052
0
    else {
3053
0
        PyInterpreterState *interp = _PyInterpreterState_GET();
3054
0
        _PyEval_StopTheWorld(interp);
3055
0
        res = interp->monitoring_callables[tool_id][event_id];
3056
0
        interp->monitoring_callables[tool_id][event_id] = Py_XNewRef(obj);
3057
0
        _PyEval_StartTheWorld(interp);
3058
0
    }
3059
0
    if (res != NULL && Py_TYPE(res) == &_PyLegacyBranchEventHandler_Type) {
3060
0
        _PyLegacyBranchEventHandler *wrapper = (_PyLegacyBranchEventHandler *)res;
3061
0
        res = Py_NewRef(wrapper->handler);
3062
0
        Py_DECREF(wrapper);
3063
0
    }
3064
0
    return res;
3065
0
}
3066
3067
/* Branch Iterator */
3068
3069
typedef struct {
3070
    PyObject_HEAD
3071
    PyCodeObject *bi_code;
3072
    int bi_offset;
3073
} branchesiterator;
3074
3075
0
#define branchesiterator_CAST(op)   ((branchesiterator *)(op))
3076
3077
static PyObject *
3078
0
int_triple(int a, int b, int c) {
3079
0
    PyObject *obja = PyLong_FromLong(a);
3080
0
    PyObject *objb = NULL;
3081
0
    PyObject *objc = NULL;
3082
0
    if (obja == NULL) {
3083
0
        goto error;
3084
0
    }
3085
0
    objb = PyLong_FromLong(b);
3086
0
    if (objb == NULL) {
3087
0
        goto error;
3088
0
    }
3089
0
    objc = PyLong_FromLong(c);
3090
0
    if (objc == NULL) {
3091
0
        goto error;
3092
0
    }
3093
0
    PyObject *array[3] = { obja, objb, objc };
3094
0
    return _PyTuple_FromArraySteal(array, 3);
3095
0
error:
3096
0
    Py_XDECREF(obja);
3097
0
    Py_XDECREF(objb);
3098
0
    Py_XDECREF(objc);
3099
0
    return NULL;
3100
0
}
3101
3102
static PyObject *
3103
branchesiter_next(PyObject *op)
3104
0
{
3105
0
    branchesiterator *bi = branchesiterator_CAST(op);
3106
0
    int offset = bi->bi_offset;
3107
0
    int oparg = 0;
3108
0
    while (offset < Py_SIZE(bi->bi_code)) {
3109
0
        _Py_CODEUNIT inst = _Py_GetBaseCodeUnit(bi->bi_code, offset);
3110
0
        int next_offset = offset + 1 + _PyOpcode_Caches[inst.op.code];
3111
0
        switch(inst.op.code) {
3112
0
            case EXTENDED_ARG:
3113
0
                oparg = (oparg << 8) | inst.op.arg;
3114
0
                break;
3115
0
            case FOR_ITER:
3116
0
                oparg = (oparg << 8) | inst.op.arg;
3117
0
                bi->bi_offset = next_offset;
3118
0
                int target = next_offset + oparg+2; // Skips END_FOR and POP_ITER
3119
0
                return int_triple(offset*2, next_offset*2, target*2);
3120
0
            case POP_JUMP_IF_FALSE:
3121
0
            case POP_JUMP_IF_TRUE:
3122
0
            case POP_JUMP_IF_NONE:
3123
0
            case POP_JUMP_IF_NOT_NONE:
3124
0
                oparg = (oparg << 8) | inst.op.arg;
3125
                /* Skip NOT_TAKEN */
3126
0
                int not_taken = next_offset + 1;
3127
0
                bi->bi_offset = not_taken;
3128
0
                return int_triple(offset*2, not_taken*2, (next_offset + oparg)*2);
3129
0
            case END_ASYNC_FOR:
3130
0
                oparg = (oparg << 8) | inst.op.arg;
3131
0
                int src_offset = next_offset - oparg;
3132
0
                bi->bi_offset = next_offset;
3133
0
                assert(_Py_GetBaseCodeUnit(bi->bi_code, src_offset).op.code == END_SEND);
3134
0
                assert(_Py_GetBaseCodeUnit(bi->bi_code, src_offset+1).op.code == NOT_TAKEN);
3135
0
                not_taken = src_offset + 2;
3136
0
                return int_triple(src_offset *2, not_taken*2, next_offset*2);
3137
0
            default:
3138
0
                oparg = 0;
3139
0
        }
3140
0
        offset = next_offset;
3141
0
    }
3142
0
    return NULL;
3143
0
}
3144
3145
static void
3146
branchesiter_dealloc(PyObject *op)
3147
0
{
3148
0
    branchesiterator *bi = branchesiterator_CAST(op);
3149
0
    Py_DECREF(bi->bi_code);
3150
0
    PyObject_Free(bi);
3151
0
}
3152
3153
static PyTypeObject _PyBranchesIterator = {
3154
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
3155
    "line_iterator",                    /* tp_name */
3156
    sizeof(branchesiterator),           /* tp_basicsize */
3157
    0,                                  /* tp_itemsize */
3158
    /* methods */
3159
    .tp_dealloc = branchesiter_dealloc,
3160
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
3161
    .tp_iter = PyObject_SelfIter,
3162
    .tp_iternext = branchesiter_next,
3163
    .tp_free = PyObject_Del,
3164
};
3165
3166
PyObject *
3167
_PyInstrumentation_BranchesIterator(PyCodeObject *code)
3168
0
{
3169
3170
0
    branchesiterator *bi = (branchesiterator *)PyType_GenericAlloc(&_PyBranchesIterator, 0);
3171
0
    if (bi == NULL) {
3172
0
        return NULL;
3173
0
    }
3174
0
    bi->bi_code = (PyCodeObject*)Py_NewRef(code);
3175
0
    bi->bi_offset = 0;
3176
0
    return (PyObject *)bi;
3177
0
}