Coverage Report

Created: 2025-11-24 06:11

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