Coverage Report

Created: 2026-07-16 07:04

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython3/Objects/codeobject.c
Line
Count
Source
1
#include "Python.h"
2
#include "opcode.h"
3
4
#include "pycore_code.h"          // _PyCodeConstructor
5
#include "pycore_function.h"      // _PyFunction_ClearCodeByVersion()
6
#include "pycore_hashtable.h"     // _Py_hashtable_t
7
#include "pycore_index_pool.h"    // _PyIndexPool_Fini()
8
#include "pycore_initconfig.h"    // _PyStatus_OK()
9
#include "pycore_interp.h"        // PyInterpreterState.co_extra_freefuncs
10
#include "pycore_interpframe.h"   // FRAME_SPECIALS_SIZE
11
#include "pycore_opcode_metadata.h" // _PyOpcode_Caches
12
#include "pycore_opcode_utils.h"  // RESUME_AT_FUNC_START
13
#include "pycore_optimizer.h"     // _Py_ExecutorDetach
14
#include "pycore_pymem.h"         // _PyMem_FreeDelayed()
15
#include "pycore_pystate.h"       // _PyInterpreterState_GET()
16
#include "pycore_setobject.h"     // _PySet_NextEntry()
17
#include "pycore_tuple.h"         // _PyTuple_ITEMS()
18
#include "pycore_unicodeobject.h" // _PyUnicode_InternImmortal()
19
#include "pycore_uniqueid.h"      // _PyObject_AssignUniqueId()
20
#include "pycore_weakref.h"       // FT_CLEAR_WEAKREFS()
21
22
#include "clinic/codeobject.c.h"
23
#include <stdbool.h>
24
25
26
#define INITIAL_SPECIALIZED_CODE_SIZE 16
27
28
static const char *
29
0
code_event_name(PyCodeEvent event) {
30
0
    switch (event) {
31
0
        #define CASE(op)                \
32
0
        case PY_CODE_EVENT_##op:         \
33
0
            return "PY_CODE_EVENT_" #op;
34
0
        PY_FOREACH_CODE_EVENT(CASE)
35
0
        #undef CASE
36
0
    }
37
0
    Py_UNREACHABLE();
38
0
}
39
40
static void
41
notify_code_watchers(PyCodeEvent event, PyCodeObject *co)
42
24.0k
{
43
24.0k
    assert(Py_REFCNT(co) > 0);
44
24.0k
    PyInterpreterState *interp = _PyInterpreterState_GET();
45
24.0k
    assert(interp->_initialized);
46
24.0k
    uint8_t bits = interp->active_code_watchers;
47
24.0k
    int i = 0;
48
24.0k
    while (bits) {
49
0
        assert(i < CODE_MAX_WATCHERS);
50
0
        if (bits & 1) {
51
0
            PyCode_WatchCallback cb = interp->code_watchers[i];
52
            // callback must be non-null if the watcher bit is set
53
0
            assert(cb != NULL);
54
0
            if (cb(event, co) < 0) {
55
0
                PyErr_FormatUnraisable(
56
0
                    "Exception ignored in %s watcher callback for %R",
57
0
                    code_event_name(event), co);
58
0
            }
59
0
        }
60
0
        i++;
61
0
        bits >>= 1;
62
0
    }
63
24.0k
}
64
65
int
66
PyCode_AddWatcher(PyCode_WatchCallback callback)
67
0
{
68
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
69
0
    assert(interp->_initialized);
70
71
0
    for (int i = 0; i < CODE_MAX_WATCHERS; i++) {
72
0
        if (!interp->code_watchers[i]) {
73
0
            interp->code_watchers[i] = callback;
74
0
            interp->active_code_watchers |= (1 << i);
75
0
            return i;
76
0
        }
77
0
    }
78
79
0
    PyErr_SetString(PyExc_RuntimeError, "no more code watcher IDs available");
80
0
    return -1;
81
0
}
82
83
static inline int
84
validate_watcher_id(PyInterpreterState *interp, int watcher_id)
85
0
{
86
0
    if (watcher_id < 0 || watcher_id >= CODE_MAX_WATCHERS) {
87
0
        PyErr_Format(PyExc_ValueError, "Invalid code watcher ID %d", watcher_id);
88
0
        return -1;
89
0
    }
90
0
    if (!interp->code_watchers[watcher_id]) {
91
0
        PyErr_Format(PyExc_ValueError, "No code watcher set for ID %d", watcher_id);
92
0
        return -1;
93
0
    }
94
0
    return 0;
95
0
}
96
97
int
98
PyCode_ClearWatcher(int watcher_id)
99
0
{
100
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
101
0
    assert(interp->_initialized);
102
0
    if (validate_watcher_id(interp, watcher_id) < 0) {
103
0
        return -1;
104
0
    }
105
0
    interp->code_watchers[watcher_id] = NULL;
106
0
    interp->active_code_watchers &= ~(1 << watcher_id);
107
0
    return 0;
108
0
}
109
110
/******************
111
 * generic helpers
112
 ******************/
113
114
3.79k
#define _PyCodeObject_CAST(op)  (assert(PyCode_Check(op)), (PyCodeObject *)(op))
115
116
static int
117
should_intern_string(PyObject *o)
118
66.4k
{
119
#ifdef Py_GIL_DISABLED
120
    // The free-threaded build interns (and immortalizes) all string constants
121
    return 1;
122
#else
123
    // compute if s matches [a-zA-Z0-9_]
124
66.4k
    const unsigned char *s, *e;
125
126
66.4k
    if (!PyUnicode_IS_ASCII(o))
127
27
        return 0;
128
129
66.4k
    s = PyUnicode_1BYTE_DATA(o);
130
66.4k
    e = s + PyUnicode_GET_LENGTH(o);
131
520k
    for (; s != e; s++) {
132
479k
        if (!Py_ISALNUM(*s) && *s != '_')
133
25.2k
            return 0;
134
479k
    }
135
41.2k
    return 1;
136
66.4k
#endif
137
66.4k
}
138
139
#ifdef Py_GIL_DISABLED
140
static PyObject *intern_one_constant(PyObject *op);
141
142
// gh-130851: In the free threading build, we intern and immortalize most
143
// constants, except code objects. However, users can generate code objects
144
// with arbitrary co_consts. We don't want to immortalize or intern unexpected
145
// constants or tuples/sets containing unexpected constants.
146
static int
147
should_immortalize_constant(PyObject *v)
148
{
149
    // Only immortalize containers if we've already immortalized all their
150
    // elements.
151
    if (PyTuple_CheckExact(v)) {
152
        for (Py_ssize_t i = PyTuple_GET_SIZE(v); --i >= 0; ) {
153
            if (!_Py_IsImmortal(PyTuple_GET_ITEM(v, i))) {
154
                return 0;
155
            }
156
        }
157
        return 1;
158
    }
159
    else if (PyFrozenSet_CheckExact(v)) {
160
        PyObject *item;
161
        Py_hash_t hash;
162
        Py_ssize_t pos = 0;
163
        while (_PySet_NextEntry(v, &pos, &item, &hash)) {
164
            if (!_Py_IsImmortal(item)) {
165
                return 0;
166
            }
167
        }
168
        return 1;
169
    }
170
    else if (PySlice_Check(v)) {
171
        PySliceObject *slice = (PySliceObject *)v;
172
        return (_Py_IsImmortal(slice->start) &&
173
                _Py_IsImmortal(slice->stop) &&
174
                _Py_IsImmortal(slice->step));
175
    }
176
    return (PyLong_CheckExact(v) || PyFloat_CheckExact(v) ||
177
            PyComplex_Check(v) || PyBytes_CheckExact(v));
178
}
179
#endif
180
181
static int
182
intern_strings(PyObject *tuple)
183
40.6k
{
184
40.6k
    PyInterpreterState *interp = _PyInterpreterState_GET();
185
40.6k
    Py_ssize_t i;
186
187
234k
    for (i = PyTuple_GET_SIZE(tuple); --i >= 0; ) {
188
193k
        PyObject *v = PyTuple_GET_ITEM(tuple, i);
189
193k
        if (v == NULL || !PyUnicode_CheckExact(v)) {
190
0
            PyErr_SetString(PyExc_SystemError,
191
0
                            "non-string found in code slot");
192
0
            return -1;
193
0
        }
194
193k
        _PyUnicode_InternImmortal(interp, &_PyTuple_ITEMS(tuple)[i]);
195
193k
    }
196
40.6k
    return 0;
197
40.6k
}
198
199
/* Intern constants. In the default build, this interns selected string
200
   constants. In the free-threaded build, this also interns non-string
201
   constants. */
202
static int
203
intern_constants(PyObject *tuple, int *modified)
204
27.9k
{
205
27.9k
    PyInterpreterState *interp = _PyInterpreterState_GET();
206
137k
    for (Py_ssize_t i = PyTuple_GET_SIZE(tuple); --i >= 0; ) {
207
109k
        PyObject *v = PyTuple_GET_ITEM(tuple, i);
208
109k
        if (PyUnicode_CheckExact(v)) {
209
66.4k
            if (should_intern_string(v)) {
210
41.2k
                PyObject *w = v;
211
41.2k
                _PyUnicode_InternMortal(interp, &v);
212
41.2k
                if (w != v) {
213
0
                    PyTuple_SET_ITEM(tuple, i, v);
214
0
                    if (modified) {
215
0
                        *modified = 1;
216
0
                    }
217
0
                }
218
41.2k
            }
219
66.4k
        }
220
43.4k
        else if (PyTuple_CheckExact(v)) {
221
7.51k
            if (intern_constants(v, NULL) < 0) {
222
0
                return -1;
223
0
            }
224
7.51k
        }
225
35.9k
        else if (PyFrozenSet_CheckExact(v)) {
226
93
            PyObject *w = v;
227
93
            PyObject *tmp = PySequence_Tuple(v);
228
93
            if (tmp == NULL) {
229
0
                return -1;
230
0
            }
231
93
            int tmp_modified = 0;
232
93
            if (intern_constants(tmp, &tmp_modified) < 0) {
233
0
                Py_DECREF(tmp);
234
0
                return -1;
235
0
            }
236
93
            if (tmp_modified) {
237
0
                v = PyFrozenSet_New(tmp);
238
0
                if (v == NULL) {
239
0
                    Py_DECREF(tmp);
240
0
                    return -1;
241
0
                }
242
243
0
                PyTuple_SET_ITEM(tuple, i, v);
244
0
                Py_DECREF(w);
245
0
                if (modified) {
246
0
                    *modified = 1;
247
0
                }
248
0
            }
249
93
            Py_DECREF(tmp);
250
93
        }
251
#ifdef Py_GIL_DISABLED
252
        else if (PySlice_Check(v)) {
253
            PySliceObject *slice = (PySliceObject *)v;
254
            PyObject *tmp = PyTuple_New(3);
255
            if (tmp == NULL) {
256
                return -1;
257
            }
258
            PyTuple_SET_ITEM(tmp, 0, Py_NewRef(slice->start));
259
            PyTuple_SET_ITEM(tmp, 1, Py_NewRef(slice->stop));
260
            PyTuple_SET_ITEM(tmp, 2, Py_NewRef(slice->step));
261
            int tmp_modified = 0;
262
            if (intern_constants(tmp, &tmp_modified) < 0) {
263
                Py_DECREF(tmp);
264
                return -1;
265
            }
266
            if (tmp_modified) {
267
                v = PySlice_New(PyTuple_GET_ITEM(tmp, 0),
268
                                PyTuple_GET_ITEM(tmp, 1),
269
                                PyTuple_GET_ITEM(tmp, 2));
270
                if (v == NULL) {
271
                    Py_DECREF(tmp);
272
                    return -1;
273
                }
274
                PyTuple_SET_ITEM(tuple, i, v);
275
                Py_DECREF(slice);
276
                if (modified) {
277
                    *modified = 1;
278
                }
279
            }
280
            Py_DECREF(tmp);
281
        }
282
283
        // Intern non-string constants in the free-threaded build
284
        _PyThreadStateImpl *tstate = (_PyThreadStateImpl *)_PyThreadState_GET();
285
        if (!_Py_IsImmortal(v) && !PyUnicode_CheckExact(v) &&
286
            should_immortalize_constant(v) &&
287
            !tstate->suppress_co_const_immortalization)
288
        {
289
            PyObject *interned = intern_one_constant(v);
290
            if (interned == NULL) {
291
                return -1;
292
            }
293
            else if (interned != v) {
294
                PyTuple_SET_ITEM(tuple, i, interned);
295
                Py_SETREF(v, interned);
296
                if (modified) {
297
                    *modified = 1;
298
                }
299
            }
300
        }
301
#endif
302
109k
    }
303
27.9k
    return 0;
304
27.9k
}
305
306
/* Return a shallow copy of a tuple that is
307
   guaranteed to contain exact strings, by converting string subclasses
308
   to exact strings and complaining if a non-string is found. */
309
static PyObject*
310
validate_and_copy_tuple(PyObject *tup)
311
0
{
312
0
    PyObject *newtuple;
313
0
    PyObject *item;
314
0
    Py_ssize_t i, len;
315
316
0
    len = PyTuple_GET_SIZE(tup);
317
0
    newtuple = PyTuple_New(len);
318
0
    if (newtuple == NULL)
319
0
        return NULL;
320
321
0
    for (i = 0; i < len; i++) {
322
0
        item = PyTuple_GET_ITEM(tup, i);
323
0
        if (PyUnicode_CheckExact(item)) {
324
0
            Py_INCREF(item);
325
0
        }
326
0
        else if (!PyUnicode_Check(item)) {
327
0
            PyErr_Format(
328
0
                PyExc_TypeError,
329
0
                "name tuples must contain only "
330
0
                "strings, not '%.500s'",
331
0
                Py_TYPE(item)->tp_name);
332
0
            Py_DECREF(newtuple);
333
0
            return NULL;
334
0
        }
335
0
        else {
336
0
            item = _PyUnicode_Copy(item);
337
0
            if (item == NULL) {
338
0
                Py_DECREF(newtuple);
339
0
                return NULL;
340
0
            }
341
0
        }
342
0
        PyTuple_SET_ITEM(newtuple, i, item);
343
0
    }
344
345
0
    return newtuple;
346
0
}
347
348
static int
349
init_co_cached(PyCodeObject *self)
350
0
{
351
0
    _PyCoCached *cached = FT_ATOMIC_LOAD_PTR(self->_co_cached);
352
0
    if (cached != NULL) {
353
0
        return 0;
354
0
    }
355
356
0
    Py_BEGIN_CRITICAL_SECTION(self);
357
0
    cached = self->_co_cached;
358
0
    if (cached == NULL) {
359
0
        cached = PyMem_New(_PyCoCached, 1);
360
0
        if (cached == NULL) {
361
0
            PyErr_NoMemory();
362
0
        }
363
0
        else {
364
0
            cached->_co_code = NULL;
365
0
            cached->_co_cellvars = NULL;
366
0
            cached->_co_freevars = NULL;
367
0
            cached->_co_varnames = NULL;
368
0
            FT_ATOMIC_STORE_PTR(self->_co_cached, cached);
369
0
        }
370
0
    }
371
0
    Py_END_CRITICAL_SECTION();
372
0
    return cached != NULL ? 0 : -1;
373
0
}
374
375
/******************
376
 * _PyCode_New()
377
 ******************/
378
379
// This is also used in compile.c.
380
void
381
_Py_set_localsplus_info(int offset, PyObject *name, _PyLocals_Kind kind,
382
                        PyObject *names, PyObject *kinds)
383
49
{
384
49
    PyTuple_SET_ITEM(names, offset, Py_NewRef(name));
385
49
    _PyLocals_SetKind(kinds, offset, kind);
386
49
}
387
388
static void
389
get_localsplus_counts(PyObject *names, PyObject *kinds,
390
                      int *pnlocals, int *pncellvars,
391
                      int *pnfreevars)
392
40.6k
{
393
40.6k
    int nlocals = 0;
394
40.6k
    int ncellvars = 0;
395
40.6k
    int nfreevars = 0;
396
40.6k
    Py_ssize_t nlocalsplus = PyTuple_GET_SIZE(names);
397
166k
    for (int i = 0; i < nlocalsplus; i++) {
398
125k
        _PyLocals_Kind kind = _PyLocals_GetKind(kinds, i);
399
125k
        if (kind & CO_FAST_LOCAL) {
400
115k
            nlocals += 1;
401
115k
            if (kind & CO_FAST_CELL) {
402
1.05k
                ncellvars += 1;
403
1.05k
            }
404
115k
        }
405
9.92k
        else if (kind & CO_FAST_CELL) {
406
5.49k
            ncellvars += 1;
407
5.49k
        }
408
4.42k
        else if (kind & CO_FAST_FREE) {
409
4.42k
            nfreevars += 1;
410
4.42k
        }
411
125k
    }
412
40.6k
    if (pnlocals != NULL) {
413
40.6k
        *pnlocals = nlocals;
414
40.6k
    }
415
40.6k
    if (pncellvars != NULL) {
416
20.3k
        *pncellvars = ncellvars;
417
20.3k
    }
418
40.6k
    if (pnfreevars != NULL) {
419
20.3k
        *pnfreevars = nfreevars;
420
20.3k
    }
421
40.6k
}
422
423
static PyObject *
424
get_localsplus_names(PyCodeObject *co, _PyLocals_Kind kind, int num)
425
0
{
426
0
    PyObject *names = PyTuple_New(num);
427
0
    if (names == NULL) {
428
0
        return NULL;
429
0
    }
430
0
    int index = 0;
431
0
    for (int offset = 0; offset < co->co_nlocalsplus; offset++) {
432
0
        _PyLocals_Kind k = _PyLocals_GetKind(co->co_localspluskinds, offset);
433
0
        if ((k & kind) == 0) {
434
0
            continue;
435
0
        }
436
0
        assert(index < num);
437
0
        PyObject *name = PyTuple_GET_ITEM(co->co_localsplusnames, offset);
438
0
        PyTuple_SET_ITEM(names, index, Py_NewRef(name));
439
0
        index += 1;
440
0
    }
441
0
    assert(index == num);
442
0
    return names;
443
0
}
444
445
int
446
_PyCode_Validate(struct _PyCodeConstructor *con)
447
20.3k
{
448
    /* Check argument types */
449
20.3k
    if (con->argcount < con->posonlyargcount || con->posonlyargcount < 0 ||
450
20.3k
        con->kwonlyargcount < 0 ||
451
20.3k
        con->stacksize < 0 || con->flags < 0 ||
452
20.3k
        con->code == NULL || !PyBytes_Check(con->code) ||
453
20.3k
        con->consts == NULL || !PyTuple_Check(con->consts) ||
454
20.3k
        con->names == NULL || !PyTuple_Check(con->names) ||
455
20.3k
        con->localsplusnames == NULL || !PyTuple_Check(con->localsplusnames) ||
456
20.3k
        con->localspluskinds == NULL || !PyBytes_Check(con->localspluskinds) ||
457
20.3k
        PyTuple_GET_SIZE(con->localsplusnames)
458
20.3k
            != PyBytes_GET_SIZE(con->localspluskinds) ||
459
20.3k
        con->name == NULL || !PyUnicode_Check(con->name) ||
460
20.3k
        con->qualname == NULL || !PyUnicode_Check(con->qualname) ||
461
20.3k
        con->filename == NULL || !PyUnicode_Check(con->filename) ||
462
20.3k
        con->linetable == NULL || !PyBytes_Check(con->linetable) ||
463
20.3k
        con->exceptiontable == NULL || !PyBytes_Check(con->exceptiontable)
464
20.3k
        ) {
465
0
        PyErr_BadInternalCall();
466
0
        return -1;
467
0
    }
468
469
    /* Make sure that code is indexable with an int, this is
470
       a long running assumption in ceval.c and many parts of
471
       the interpreter. */
472
20.3k
    if (PyBytes_GET_SIZE(con->code) > INT_MAX) {
473
0
        PyErr_SetString(PyExc_OverflowError,
474
0
                        "code: co_code larger than INT_MAX");
475
0
        return -1;
476
0
    }
477
20.3k
    if (PyBytes_GET_SIZE(con->code) % sizeof(_Py_CODEUNIT) != 0 ||
478
20.3k
        !_Py_IS_ALIGNED(PyBytes_AS_STRING(con->code), sizeof(_Py_CODEUNIT))
479
20.3k
        ) {
480
0
        PyErr_SetString(PyExc_ValueError, "code: co_code is malformed");
481
0
        return -1;
482
0
    }
483
484
    /* Ensure that the co_varnames has enough names to cover the arg counts.
485
     * Note that totalargs = nlocals - nplainlocals.  We check nplainlocals
486
     * here to avoid the possibility of overflow (however remote). */
487
20.3k
    int nlocals;
488
20.3k
    get_localsplus_counts(con->localsplusnames, con->localspluskinds,
489
20.3k
                          &nlocals, NULL, NULL);
490
20.3k
    int nplainlocals = nlocals -
491
20.3k
                       con->argcount -
492
20.3k
                       con->kwonlyargcount -
493
20.3k
                       ((con->flags & CO_VARARGS) != 0) -
494
20.3k
                       ((con->flags & CO_VARKEYWORDS) != 0);
495
20.3k
    if (nplainlocals < 0) {
496
0
        PyErr_SetString(PyExc_ValueError, "code: co_varnames is too small");
497
0
        return -1;
498
0
    }
499
500
20.3k
    return 0;
501
20.3k
}
502
503
extern void
504
_PyCode_Quicken(_Py_CODEUNIT *instructions, Py_ssize_t size, int enable_counters, int flags);
505
506
#ifdef Py_GIL_DISABLED
507
static _PyCodeArray * _PyCodeArray_New(Py_ssize_t size);
508
#endif
509
510
static int
511
init_code(PyCodeObject *co, struct _PyCodeConstructor *con)
512
20.3k
{
513
20.3k
    int nlocalsplus = (int)PyTuple_GET_SIZE(con->localsplusnames);
514
20.3k
    int nlocals, ncellvars, nfreevars;
515
20.3k
    get_localsplus_counts(con->localsplusnames, con->localspluskinds,
516
20.3k
                          &nlocals, &ncellvars, &nfreevars);
517
20.3k
    if (con->stacksize == 0) {
518
0
        con->stacksize = 1;
519
0
    }
520
521
20.3k
    PyInterpreterState *interp = _PyInterpreterState_GET();
522
20.3k
    co->co_filename = Py_NewRef(con->filename);
523
20.3k
    co->co_name = Py_NewRef(con->name);
524
20.3k
    co->co_qualname = Py_NewRef(con->qualname);
525
20.3k
    _PyUnicode_InternMortal(interp, &co->co_filename);
526
20.3k
    _PyUnicode_InternMortal(interp, &co->co_name);
527
20.3k
    _PyUnicode_InternMortal(interp, &co->co_qualname);
528
20.3k
    co->co_flags = con->flags;
529
530
20.3k
    co->co_firstlineno = con->firstlineno;
531
20.3k
    co->co_linetable = Py_NewRef(con->linetable);
532
533
20.3k
    co->co_consts = Py_NewRef(con->consts);
534
20.3k
    co->co_names = Py_NewRef(con->names);
535
536
20.3k
    co->co_localsplusnames = Py_NewRef(con->localsplusnames);
537
20.3k
    co->co_localspluskinds = Py_NewRef(con->localspluskinds);
538
539
20.3k
    co->co_argcount = con->argcount;
540
20.3k
    co->co_posonlyargcount = con->posonlyargcount;
541
20.3k
    co->co_kwonlyargcount = con->kwonlyargcount;
542
543
20.3k
    co->co_stacksize = con->stacksize;
544
545
20.3k
    co->co_exceptiontable = Py_NewRef(con->exceptiontable);
546
547
    /* derived values */
548
20.3k
    co->co_nlocalsplus = nlocalsplus;
549
20.3k
    co->co_nlocals = nlocals;
550
20.3k
    co->co_framesize = nlocalsplus + con->stacksize + FRAME_SPECIALS_SIZE;
551
20.3k
    co->co_ncellvars = ncellvars;
552
20.3k
    co->co_nfreevars = nfreevars;
553
20.3k
    FT_MUTEX_LOCK(&interp->func_state.mutex);
554
20.3k
    co->co_version = interp->func_state.next_version;
555
20.3k
    if (interp->func_state.next_version != 0) {
556
20.3k
        interp->func_state.next_version++;
557
20.3k
    }
558
20.3k
    FT_MUTEX_UNLOCK(&interp->func_state.mutex);
559
20.3k
    co->_co_monitoring = NULL;
560
20.3k
    co->_co_instrumentation_version = 0;
561
    /* not set */
562
20.3k
    co->co_weakreflist = NULL;
563
20.3k
    co->co_extra = NULL;
564
20.3k
    co->_co_cached = NULL;
565
20.3k
    co->co_executors = NULL;
566
567
20.3k
    memcpy(_PyCode_CODE(co), PyBytes_AS_STRING(con->code),
568
20.3k
           PyBytes_GET_SIZE(con->code));
569
#ifdef Py_GIL_DISABLED
570
    co->co_tlbc = _PyCodeArray_New(INITIAL_SPECIALIZED_CODE_SIZE);
571
    if (co->co_tlbc == NULL) {
572
        return -1;
573
    }
574
    co->co_tlbc->entries[0] = co->co_code_adaptive;
575
#endif
576
20.3k
    int entry_point = 0;
577
29.7k
    while (entry_point < Py_SIZE(co)) {
578
29.7k
        if (_PyCode_CODE(co)[entry_point].op.code == RESUME &&
579
20.8k
           (_PyCode_CODE(co)[entry_point].op.arg & RESUME_OPARG_LOCATION_MASK) != RESUME_AT_GEN_EXPR_START
580
29.7k
        ) {
581
20.3k
            break;
582
20.3k
        }
583
9.42k
        entry_point++;
584
9.42k
    }
585
20.3k
    co->_co_firsttraceable = entry_point;
586
587
#ifdef Py_GIL_DISABLED
588
    int enable_counters = interp->config.tlbc_enabled && interp->opt_config.specialization_enabled;
589
    _PyCode_Quicken(_PyCode_CODE(co), Py_SIZE(co), enable_counters, co->co_flags);
590
#else
591
20.3k
    _PyCode_Quicken(_PyCode_CODE(co), Py_SIZE(co), interp->opt_config.specialization_enabled, co->co_flags);
592
20.3k
#endif
593
20.3k
    notify_code_watchers(PY_CODE_EVENT_CREATE, co);
594
20.3k
    return 0;
595
20.3k
}
596
597
static int
598
scan_varint(const uint8_t *ptr)
599
5.92M
{
600
5.92M
    unsigned int read = *ptr++;
601
5.92M
    unsigned int val = read & 63;
602
5.92M
    unsigned int shift = 0;
603
5.92M
    while (read & 64) {
604
0
        read = *ptr++;
605
0
        shift += 6;
606
0
        val |= (read & 63) << shift;
607
0
    }
608
5.92M
    return val;
609
5.92M
}
610
611
static int
612
scan_signed_varint(const uint8_t *ptr)
613
5.92M
{
614
5.92M
    unsigned int uval = scan_varint(ptr);
615
5.92M
    if (uval & 1) {
616
2.08M
        return -(int)(uval >> 1);
617
2.08M
    }
618
3.83M
    else {
619
3.83M
        return uval >> 1;
620
3.83M
    }
621
5.92M
}
622
623
static int
624
get_line_delta(const uint8_t *ptr)
625
118M
{
626
118M
    int code = ((*ptr) >> 3) & 15;
627
118M
    switch (code) {
628
356k
        case PY_CODE_LOCATION_INFO_NONE:
629
356k
            return 0;
630
0
        case PY_CODE_LOCATION_INFO_NO_COLUMNS:
631
5.92M
        case PY_CODE_LOCATION_INFO_LONG:
632
5.92M
            return scan_signed_varint(ptr+1);
633
24.9M
        case PY_CODE_LOCATION_INFO_ONE_LINE0:
634
24.9M
            return 0;
635
19.7M
        case PY_CODE_LOCATION_INFO_ONE_LINE1:
636
19.7M
            return 1;
637
6.26M
        case PY_CODE_LOCATION_INFO_ONE_LINE2:
638
6.26M
            return 2;
639
61.0M
        default:
640
            /* Same line */
641
61.0M
            return 0;
642
118M
    }
643
118M
}
644
645
static PyObject *
646
remove_column_info(PyObject *locations)
647
0
{
648
0
    Py_ssize_t offset = 0;
649
0
    const uint8_t *data = (const uint8_t *)PyBytes_AS_STRING(locations);
650
0
    PyObject *res = PyBytes_FromStringAndSize(NULL, 32);
651
0
    if (res == NULL) {
652
0
        PyErr_NoMemory();
653
0
        return NULL;
654
0
    }
655
0
    uint8_t *output = (uint8_t *)PyBytes_AS_STRING(res);
656
0
    while (offset < PyBytes_GET_SIZE(locations)) {
657
0
        Py_ssize_t write_offset = output - (uint8_t *)PyBytes_AS_STRING(res);
658
0
        if (write_offset + 16 >= PyBytes_GET_SIZE(res)) {
659
0
            if (_PyBytes_Resize(&res, PyBytes_GET_SIZE(res) * 2) < 0) {
660
0
                return NULL;
661
0
            }
662
0
            output = (uint8_t *)PyBytes_AS_STRING(res) + write_offset;
663
0
        }
664
0
        int code = (data[offset] >> 3) & 15;
665
0
        if (code == PY_CODE_LOCATION_INFO_NONE) {
666
0
            *output++ = data[offset];
667
0
        }
668
0
        else {
669
0
            int blength = (data[offset] & 7)+1;
670
0
            output += write_location_entry_start(
671
0
                output, PY_CODE_LOCATION_INFO_NO_COLUMNS, blength);
672
0
            int ldelta = get_line_delta(&data[offset]);
673
0
            output += write_signed_varint(output, ldelta);
674
0
        }
675
0
        offset++;
676
0
        while (offset < PyBytes_GET_SIZE(locations) &&
677
0
            (data[offset] & 128) == 0) {
678
0
            offset++;
679
0
        }
680
0
    }
681
0
    Py_ssize_t write_offset = output - (uint8_t *)PyBytes_AS_STRING(res);
682
0
    if (_PyBytes_Resize(&res, write_offset)) {
683
0
        return NULL;
684
0
    }
685
0
    return res;
686
0
}
687
688
static int
689
intern_code_constants(struct _PyCodeConstructor *con)
690
20.3k
{
691
#ifdef Py_GIL_DISABLED
692
    PyInterpreterState *interp = _PyInterpreterState_GET();
693
    struct _py_code_state *state = &interp->code_state;
694
    FT_MUTEX_LOCK(&state->mutex);
695
#endif
696
20.3k
    if (intern_strings(con->names) < 0) {
697
0
        goto error;
698
0
    }
699
20.3k
    if (intern_constants(con->consts, NULL) < 0) {
700
0
        goto error;
701
0
    }
702
20.3k
    if (intern_strings(con->localsplusnames) < 0) {
703
0
        goto error;
704
0
    }
705
20.3k
    FT_MUTEX_UNLOCK(&state->mutex);
706
20.3k
    return 0;
707
708
0
error:
709
0
    FT_MUTEX_UNLOCK(&state->mutex);
710
0
    return -1;
711
20.3k
}
712
713
/* The caller is responsible for ensuring that the given data is valid. */
714
715
PyCodeObject *
716
_PyCode_New(struct _PyCodeConstructor *con)
717
20.3k
{
718
20.3k
    if (intern_code_constants(con) < 0) {
719
0
        return NULL;
720
0
    }
721
722
20.3k
    PyObject *replacement_locations = NULL;
723
    // Compact the linetable if we are opted out of debug
724
    // ranges.
725
20.3k
    if (!_Py_GetConfig()->code_debug_ranges) {
726
0
        replacement_locations = remove_column_info(con->linetable);
727
0
        if (replacement_locations == NULL) {
728
0
            return NULL;
729
0
        }
730
0
        con->linetable = replacement_locations;
731
0
    }
732
733
20.3k
    Py_ssize_t size = PyBytes_GET_SIZE(con->code) / sizeof(_Py_CODEUNIT);
734
20.3k
    PyCodeObject *co;
735
#ifdef Py_GIL_DISABLED
736
    co = PyObject_GC_NewVar(PyCodeObject, &PyCode_Type, size);
737
#else
738
20.3k
    co = PyObject_NewVar(PyCodeObject, &PyCode_Type, size);
739
20.3k
#endif
740
20.3k
    if (co == NULL) {
741
0
        Py_XDECREF(replacement_locations);
742
0
        PyErr_NoMemory();
743
0
        return NULL;
744
0
    }
745
746
#ifdef Py_GIL_DISABLED
747
    co->_co_unique_id = _Py_INVALID_UNIQUE_ID;
748
#endif
749
750
20.3k
    if (init_code(co, con) < 0) {
751
0
        Py_DECREF(co);
752
0
        return NULL;
753
0
    }
754
755
#ifdef Py_GIL_DISABLED
756
    co->_co_unique_id = _PyObject_AssignUniqueId((PyObject *)co);
757
    _PyObject_GC_TRACK(co);
758
#endif
759
20.3k
    Py_XDECREF(replacement_locations);
760
20.3k
    return co;
761
20.3k
}
762
763
764
/******************
765
 * the legacy "constructors"
766
 ******************/
767
768
PyCodeObject *
769
PyUnstable_Code_NewWithPosOnlyArgs(
770
                          int argcount, int posonlyargcount, int kwonlyargcount,
771
                          int nlocals, int stacksize, int flags,
772
                          PyObject *code, PyObject *consts, PyObject *names,
773
                          PyObject *varnames, PyObject *freevars, PyObject *cellvars,
774
                          PyObject *filename, PyObject *name,
775
                          PyObject *qualname, int firstlineno,
776
                          PyObject *linetable,
777
                          PyObject *exceptiontable)
778
0
{
779
0
    PyCodeObject *co = NULL;
780
0
    PyObject *localsplusnames = NULL;
781
0
    PyObject *localspluskinds = NULL;
782
783
0
    if (varnames == NULL || !PyTuple_Check(varnames) ||
784
0
        cellvars == NULL || !PyTuple_Check(cellvars) ||
785
0
        freevars == NULL || !PyTuple_Check(freevars)
786
0
        ) {
787
0
        PyErr_BadInternalCall();
788
0
        return NULL;
789
0
    }
790
791
    // Set the "fast locals plus" info.
792
0
    int nvarnames = (int)PyTuple_GET_SIZE(varnames);
793
0
    int ncellvars = (int)PyTuple_GET_SIZE(cellvars);
794
0
    int nfreevars = (int)PyTuple_GET_SIZE(freevars);
795
0
    int nlocalsplus = nvarnames + ncellvars + nfreevars;
796
0
    localsplusnames = PyTuple_New(nlocalsplus);
797
0
    if (localsplusnames == NULL) {
798
0
        goto error;
799
0
    }
800
0
    localspluskinds = PyBytes_FromStringAndSize(NULL, nlocalsplus);
801
0
    if (localspluskinds == NULL) {
802
0
        goto error;
803
0
    }
804
0
    int  offset = 0;
805
0
    for (int i = 0; i < nvarnames; i++, offset++) {
806
0
        PyObject *name = PyTuple_GET_ITEM(varnames, i);
807
0
        _Py_set_localsplus_info(offset, name, CO_FAST_LOCAL,
808
0
                               localsplusnames, localspluskinds);
809
0
    }
810
0
    for (int i = 0; i < ncellvars; i++, offset++) {
811
0
        PyObject *name = PyTuple_GET_ITEM(cellvars, i);
812
0
        int argoffset = -1;
813
0
        for (int j = 0; j < nvarnames; j++) {
814
0
            int cmp = PyUnicode_Compare(PyTuple_GET_ITEM(varnames, j),
815
0
                                        name);
816
0
            assert(!PyErr_Occurred());
817
0
            if (cmp == 0) {
818
0
                argoffset = j;
819
0
                break;
820
0
            }
821
0
        }
822
0
        if (argoffset >= 0) {
823
            // Merge the localsplus indices.
824
0
            nlocalsplus -= 1;
825
0
            offset -= 1;
826
0
            _PyLocals_Kind kind = _PyLocals_GetKind(localspluskinds, argoffset);
827
0
            _PyLocals_SetKind(localspluskinds, argoffset, kind | CO_FAST_CELL);
828
0
            continue;
829
0
        }
830
0
        _Py_set_localsplus_info(offset, name, CO_FAST_CELL,
831
0
                               localsplusnames, localspluskinds);
832
0
    }
833
0
    for (int i = 0; i < nfreevars; i++, offset++) {
834
0
        PyObject *name = PyTuple_GET_ITEM(freevars, i);
835
0
        _Py_set_localsplus_info(offset, name, CO_FAST_FREE,
836
0
                               localsplusnames, localspluskinds);
837
0
    }
838
839
    // gh-110543: Make sure the CO_FAST_HIDDEN flag is set correctly.
840
0
    if (!(flags & CO_OPTIMIZED)) {
841
0
        Py_ssize_t code_len = PyBytes_GET_SIZE(code);
842
0
        _Py_CODEUNIT *code_data = (_Py_CODEUNIT *)PyBytes_AS_STRING(code);
843
0
        Py_ssize_t num_code_units = code_len / sizeof(_Py_CODEUNIT);
844
0
        int extended_arg = 0;
845
0
        for (int i = 0; i < num_code_units; i += 1 + _PyOpcode_Caches[code_data[i].op.code]) {
846
0
            _Py_CODEUNIT *instr = &code_data[i];
847
0
            uint8_t opcode = instr->op.code;
848
0
            if (opcode == EXTENDED_ARG) {
849
0
                extended_arg = extended_arg << 8 | instr->op.arg;
850
0
                continue;
851
0
            }
852
0
            if (opcode == LOAD_FAST_AND_CLEAR) {
853
0
                int oparg = extended_arg << 8 | instr->op.arg;
854
0
                if (oparg >= nlocalsplus) {
855
0
                    PyErr_Format(PyExc_ValueError,
856
0
                                "code: LOAD_FAST_AND_CLEAR oparg %d out of range",
857
0
                                oparg);
858
0
                    goto error;
859
0
                }
860
0
                _PyLocals_Kind kind = _PyLocals_GetKind(localspluskinds, oparg);
861
0
                _PyLocals_SetKind(localspluskinds, oparg, kind | CO_FAST_HIDDEN);
862
0
            }
863
0
            extended_arg = 0;
864
0
        }
865
0
    }
866
867
    // If any cells were args then nlocalsplus will have shrunk.
868
0
    if (nlocalsplus != PyTuple_GET_SIZE(localsplusnames)) {
869
0
        if (_PyTuple_Resize(&localsplusnames, nlocalsplus) < 0
870
0
                || _PyBytes_Resize(&localspluskinds, nlocalsplus) < 0) {
871
0
            goto error;
872
0
        }
873
0
    }
874
875
0
    struct _PyCodeConstructor con = {
876
0
        .filename = filename,
877
0
        .name = name,
878
0
        .qualname = qualname,
879
0
        .flags = flags,
880
881
0
        .code = code,
882
0
        .firstlineno = firstlineno,
883
0
        .linetable = linetable,
884
885
0
        .consts = consts,
886
0
        .names = names,
887
888
0
        .localsplusnames = localsplusnames,
889
0
        .localspluskinds = localspluskinds,
890
891
0
        .argcount = argcount,
892
0
        .posonlyargcount = posonlyargcount,
893
0
        .kwonlyargcount = kwonlyargcount,
894
895
0
        .stacksize = stacksize,
896
897
0
        .exceptiontable = exceptiontable,
898
0
    };
899
900
0
    if (_PyCode_Validate(&con) < 0) {
901
0
        goto error;
902
0
    }
903
0
    assert(PyBytes_GET_SIZE(code) % sizeof(_Py_CODEUNIT) == 0);
904
0
    assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(code), sizeof(_Py_CODEUNIT)));
905
0
    if (nlocals != PyTuple_GET_SIZE(varnames)) {
906
0
        PyErr_SetString(PyExc_ValueError,
907
0
                        "code: co_nlocals != len(co_varnames)");
908
0
        goto error;
909
0
    }
910
911
0
    co = _PyCode_New(&con);
912
0
    if (co == NULL) {
913
0
        goto error;
914
0
    }
915
916
0
error:
917
0
    Py_XDECREF(localsplusnames);
918
0
    Py_XDECREF(localspluskinds);
919
0
    return co;
920
0
}
921
922
PyCodeObject *
923
PyUnstable_Code_New(int argcount, int kwonlyargcount,
924
           int nlocals, int stacksize, int flags,
925
           PyObject *code, PyObject *consts, PyObject *names,
926
           PyObject *varnames, PyObject *freevars, PyObject *cellvars,
927
           PyObject *filename, PyObject *name, PyObject *qualname,
928
           int firstlineno,
929
           PyObject *linetable,
930
           PyObject *exceptiontable)
931
0
{
932
0
    return PyCode_NewWithPosOnlyArgs(argcount, 0, kwonlyargcount, nlocals,
933
0
                                     stacksize, flags, code, consts, names,
934
0
                                     varnames, freevars, cellvars, filename,
935
0
                                     name, qualname, firstlineno,
936
0
                                     linetable,
937
0
                                     exceptiontable);
938
0
}
939
940
// NOTE: When modifying the construction of PyCode_NewEmpty, please also change
941
// test.test_code.CodeLocationTest.test_code_new_empty to keep it in sync!
942
943
static const uint8_t assert0[8] = {
944
    RESUME, RESUME_AT_FUNC_START,
945
    CACHE, 0,
946
    LOAD_COMMON_CONSTANT, CONSTANT_ASSERTIONERROR,
947
    RAISE_VARARGS, 1
948
};
949
950
static const uint8_t linetable[2] = {
951
    (1 << 7)  // New entry.
952
    | (PY_CODE_LOCATION_INFO_NO_COLUMNS << 3)
953
    | (4 - 1),  // Four code units.
954
    0,  // Offset from co_firstlineno.
955
};
956
957
PyCodeObject *
958
PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno)
959
0
{
960
0
    PyObject *nulltuple = NULL;
961
0
    PyObject *filename_ob = NULL;
962
0
    PyObject *funcname_ob = NULL;
963
0
    PyObject *code_ob = NULL;
964
0
    PyObject *linetable_ob = NULL;
965
0
    PyCodeObject *result = NULL;
966
967
0
    nulltuple = PyTuple_New(0);
968
0
    if (nulltuple == NULL) {
969
0
        goto failed;
970
0
    }
971
0
    funcname_ob = PyUnicode_FromString(funcname);
972
0
    if (funcname_ob == NULL) {
973
0
        goto failed;
974
0
    }
975
0
    filename_ob = PyUnicode_DecodeFSDefault(filename);
976
0
    if (filename_ob == NULL) {
977
0
        goto failed;
978
0
    }
979
0
    code_ob = PyBytes_FromStringAndSize((const char *)assert0, 8);
980
0
    if (code_ob == NULL) {
981
0
        goto failed;
982
0
    }
983
0
    linetable_ob = PyBytes_FromStringAndSize((const char *)linetable, 2);
984
0
    if (linetable_ob == NULL) {
985
0
        goto failed;
986
0
    }
987
988
0
#define emptystring (PyObject *)&_Py_SINGLETON(bytes_empty)
989
0
    struct _PyCodeConstructor con = {
990
0
        .filename = filename_ob,
991
0
        .name = funcname_ob,
992
0
        .qualname = funcname_ob,
993
0
        .code = code_ob,
994
0
        .firstlineno = firstlineno,
995
0
        .linetable = linetable_ob,
996
0
        .consts = nulltuple,
997
0
        .names = nulltuple,
998
0
        .localsplusnames = nulltuple,
999
0
        .localspluskinds = emptystring,
1000
0
        .exceptiontable = emptystring,
1001
0
        .stacksize = 1,
1002
0
    };
1003
0
    result = _PyCode_New(&con);
1004
1005
0
failed:
1006
0
    Py_XDECREF(nulltuple);
1007
0
    Py_XDECREF(funcname_ob);
1008
0
    Py_XDECREF(filename_ob);
1009
0
    Py_XDECREF(code_ob);
1010
0
    Py_XDECREF(linetable_ob);
1011
0
    return result;
1012
0
}
1013
1014
1015
/******************
1016
 * source location tracking (co_lines/co_positions)
1017
 ******************/
1018
1019
int
1020
PyCode_Addr2Line(PyCodeObject *co, int addrq)
1021
549k
{
1022
549k
    if (addrq < 0) {
1023
0
        return co->co_firstlineno;
1024
0
    }
1025
549k
    _PyCoMonitoringData *data = _Py_atomic_load_ptr_acquire(&co->_co_monitoring);
1026
549k
    if (data) {
1027
0
        _PyCoLineInstrumentationData *lines = _Py_atomic_load_ptr_acquire(&data->lines);
1028
0
        if (lines) {
1029
0
            return _Py_Instrumentation_GetLine(co, lines, addrq/sizeof(_Py_CODEUNIT));
1030
0
        }
1031
0
    }
1032
549k
    assert(addrq >= 0 && addrq < _PyCode_NBYTES(co));
1033
549k
    PyCodeAddressRange bounds;
1034
549k
    _PyCode_InitAddressRange(co, &bounds);
1035
549k
    return _PyCode_CheckLineNumber(addrq, &bounds);
1036
549k
}
1037
1038
int
1039
_PyCode_SafeAddr2Line(PyCodeObject *co, int addrq)
1040
0
{
1041
0
    if (addrq < 0) {
1042
0
        return co->co_firstlineno;
1043
0
    }
1044
0
    if (co->_co_monitoring && co->_co_monitoring->lines) {
1045
0
        return _Py_Instrumentation_GetLine(co, co->_co_monitoring->lines, addrq/sizeof(_Py_CODEUNIT));
1046
0
    }
1047
0
    if (!(addrq >= 0 && addrq < _PyCode_NBYTES(co))) {
1048
0
        return -1;
1049
0
    }
1050
0
    PyCodeAddressRange bounds;
1051
0
    _PyCode_InitAddressRange(co, &bounds);
1052
0
    return _PyCode_CheckLineNumber(addrq, &bounds);
1053
0
}
1054
1055
void
1056
_PyLineTable_InitAddressRange(const char *linetable, Py_ssize_t length, int firstlineno, PyCodeAddressRange *range)
1057
549k
{
1058
549k
    range->opaque.lo_next = (const uint8_t *)linetable;
1059
549k
    range->opaque.limit = range->opaque.lo_next + length;
1060
549k
    range->ar_start = -1;
1061
549k
    range->ar_end = 0;
1062
549k
    range->opaque.computed_line = firstlineno;
1063
549k
    range->ar_line = -1;
1064
549k
}
1065
1066
int
1067
_PyCode_InitAddressRange(PyCodeObject* co, PyCodeAddressRange *bounds)
1068
549k
{
1069
549k
    assert(co->co_linetable != NULL);
1070
549k
    const char *linetable = PyBytes_AS_STRING(co->co_linetable);
1071
549k
    Py_ssize_t length = PyBytes_GET_SIZE(co->co_linetable);
1072
549k
    _PyLineTable_InitAddressRange(linetable, length, co->co_firstlineno, bounds);
1073
549k
    return bounds->ar_line;
1074
549k
}
1075
1076
/* Update *bounds to describe the first and one-past-the-last instructions in
1077
   the same line as lasti.  Return the number of that line, or -1 if lasti is out of bounds. */
1078
int
1079
_PyCode_CheckLineNumber(int lasti, PyCodeAddressRange *bounds)
1080
549k
{
1081
118M
    while (bounds->ar_end <= lasti) {
1082
118M
        if (!_PyLineTable_NextAddressRange(bounds)) {
1083
0
            return -1;
1084
0
        }
1085
118M
    }
1086
549k
    while (bounds->ar_start > lasti) {
1087
0
        if (!_PyLineTable_PreviousAddressRange(bounds)) {
1088
0
            return -1;
1089
0
        }
1090
0
    }
1091
549k
    return bounds->ar_line;
1092
549k
}
1093
1094
static int
1095
is_no_line_marker(uint8_t b)
1096
118M
{
1097
118M
    return (b >> 3) == 0x1f;
1098
118M
}
1099
1100
1101
#define ASSERT_VALID_BOUNDS(bounds) \
1102
236M
    assert(bounds->opaque.lo_next <=  bounds->opaque.limit && \
1103
236M
        (bounds->ar_line == -1 || bounds->ar_line == bounds->opaque.computed_line) && \
1104
236M
        (bounds->opaque.lo_next == bounds->opaque.limit || \
1105
236M
        (*bounds->opaque.lo_next) & 128))
1106
1107
static int
1108
next_code_delta(PyCodeAddressRange *bounds)
1109
118M
{
1110
118M
    assert((*bounds->opaque.lo_next) & 128);
1111
118M
    return (((*bounds->opaque.lo_next) & 7) + 1) * sizeof(_Py_CODEUNIT);
1112
118M
}
1113
1114
static int
1115
previous_code_delta(PyCodeAddressRange *bounds)
1116
0
{
1117
0
    if (bounds->ar_start == 0) {
1118
        // If we looking at the first entry, the
1119
        // "previous" entry has an implicit length of 1.
1120
0
        return 1;
1121
0
    }
1122
0
    const uint8_t *ptr = bounds->opaque.lo_next-1;
1123
0
    while (((*ptr) & 128) == 0) {
1124
0
        ptr--;
1125
0
    }
1126
0
    return (((*ptr) & 7) + 1) * sizeof(_Py_CODEUNIT);
1127
0
}
1128
1129
static int
1130
read_byte(PyCodeAddressRange *bounds)
1131
0
{
1132
0
    return *bounds->opaque.lo_next++;
1133
0
}
1134
1135
static int
1136
read_varint(PyCodeAddressRange *bounds)
1137
0
{
1138
0
    unsigned int read = read_byte(bounds);
1139
0
    unsigned int val = read & 63;
1140
0
    unsigned int shift = 0;
1141
0
    while (read & 64) {
1142
0
        read = read_byte(bounds);
1143
0
        shift += 6;
1144
0
        val |= (read & 63) << shift;
1145
0
    }
1146
0
    return val;
1147
0
}
1148
1149
static int
1150
read_signed_varint(PyCodeAddressRange *bounds)
1151
0
{
1152
0
    unsigned int uval = read_varint(bounds);
1153
0
    if (uval & 1) {
1154
0
        return -(int)(uval >> 1);
1155
0
    }
1156
0
    else {
1157
0
        return uval >> 1;
1158
0
    }
1159
0
}
1160
1161
static void
1162
retreat(PyCodeAddressRange *bounds)
1163
0
{
1164
0
    ASSERT_VALID_BOUNDS(bounds);
1165
0
    assert(bounds->ar_start >= 0);
1166
0
    do {
1167
0
        bounds->opaque.lo_next--;
1168
0
    } while (((*bounds->opaque.lo_next) & 128) == 0);
1169
0
    bounds->opaque.computed_line -= get_line_delta(bounds->opaque.lo_next);
1170
0
    bounds->ar_end = bounds->ar_start;
1171
0
    bounds->ar_start -= previous_code_delta(bounds);
1172
0
    if (is_no_line_marker(bounds->opaque.lo_next[-1])) {
1173
0
        bounds->ar_line = -1;
1174
0
    }
1175
0
    else {
1176
0
        bounds->ar_line = bounds->opaque.computed_line;
1177
0
    }
1178
0
    ASSERT_VALID_BOUNDS(bounds);
1179
0
}
1180
1181
static void
1182
advance(PyCodeAddressRange *bounds)
1183
118M
{
1184
118M
    ASSERT_VALID_BOUNDS(bounds);
1185
118M
    bounds->opaque.computed_line += get_line_delta(bounds->opaque.lo_next);
1186
118M
    if (is_no_line_marker(*bounds->opaque.lo_next)) {
1187
356k
        bounds->ar_line = -1;
1188
356k
    }
1189
118M
    else {
1190
118M
        bounds->ar_line = bounds->opaque.computed_line;
1191
118M
    }
1192
118M
    bounds->ar_start = bounds->ar_end;
1193
118M
    bounds->ar_end += next_code_delta(bounds);
1194
307M
    do {
1195
307M
        bounds->opaque.lo_next++;
1196
307M
    } while (bounds->opaque.lo_next < bounds->opaque.limit &&
1197
307M
        ((*bounds->opaque.lo_next) & 128) == 0);
1198
118M
    ASSERT_VALID_BOUNDS(bounds);
1199
118M
}
1200
1201
static void
1202
advance_with_locations(PyCodeAddressRange *bounds, int *endline, int *column, int *endcolumn)
1203
0
{
1204
0
    ASSERT_VALID_BOUNDS(bounds);
1205
0
    int first_byte = read_byte(bounds);
1206
0
    int code = (first_byte >> 3) & 15;
1207
0
    bounds->ar_start = bounds->ar_end;
1208
0
    bounds->ar_end = bounds->ar_start + ((first_byte & 7) + 1) * sizeof(_Py_CODEUNIT);
1209
0
    switch(code) {
1210
0
        case PY_CODE_LOCATION_INFO_NONE:
1211
0
            bounds->ar_line = *endline = -1;
1212
0
            *column =  *endcolumn = -1;
1213
0
            break;
1214
0
        case PY_CODE_LOCATION_INFO_LONG:
1215
0
        {
1216
0
            bounds->opaque.computed_line += read_signed_varint(bounds);
1217
0
            bounds->ar_line = bounds->opaque.computed_line;
1218
0
            *endline = bounds->ar_line + read_varint(bounds);
1219
0
            *column = read_varint(bounds)-1;
1220
0
            *endcolumn = read_varint(bounds)-1;
1221
0
            break;
1222
0
        }
1223
0
        case PY_CODE_LOCATION_INFO_NO_COLUMNS:
1224
0
        {
1225
            /* No column */
1226
0
            bounds->opaque.computed_line += read_signed_varint(bounds);
1227
0
            *endline = bounds->ar_line = bounds->opaque.computed_line;
1228
0
            *column = *endcolumn = -1;
1229
0
            break;
1230
0
        }
1231
0
        case PY_CODE_LOCATION_INFO_ONE_LINE0:
1232
0
        case PY_CODE_LOCATION_INFO_ONE_LINE1:
1233
0
        case PY_CODE_LOCATION_INFO_ONE_LINE2:
1234
0
        {
1235
            /* one line form */
1236
0
            int line_delta = code - 10;
1237
0
            bounds->opaque.computed_line += line_delta;
1238
0
            *endline = bounds->ar_line = bounds->opaque.computed_line;
1239
0
            *column = read_byte(bounds);
1240
0
            *endcolumn = read_byte(bounds);
1241
0
            break;
1242
0
        }
1243
0
        default:
1244
0
        {
1245
            /* Short forms */
1246
0
            int second_byte = read_byte(bounds);
1247
0
            assert((second_byte & 128) == 0);
1248
0
            *endline = bounds->ar_line = bounds->opaque.computed_line;
1249
0
            *column = code << 3 | (second_byte >> 4);
1250
0
            *endcolumn = *column + (second_byte & 15);
1251
0
        }
1252
0
    }
1253
0
    ASSERT_VALID_BOUNDS(bounds);
1254
0
}
1255
int
1256
PyCode_Addr2Location(PyCodeObject *co, int addrq,
1257
                     int *start_line, int *start_column,
1258
                     int *end_line, int *end_column)
1259
0
{
1260
0
    if (addrq < 0) {
1261
0
        *start_line = *end_line = co->co_firstlineno;
1262
0
        *start_column = *end_column = 0;
1263
0
        return 1;
1264
0
    }
1265
0
    assert(addrq >= 0 && addrq < _PyCode_NBYTES(co));
1266
0
    PyCodeAddressRange bounds;
1267
0
    _PyCode_InitAddressRange(co, &bounds);
1268
0
    _PyCode_CheckLineNumber(addrq, &bounds);
1269
0
    retreat(&bounds);
1270
0
    advance_with_locations(&bounds, end_line, start_column, end_column);
1271
0
    *start_line = bounds.ar_line;
1272
0
    return 1;
1273
0
}
1274
1275
1276
static inline int
1277
118M
at_end(PyCodeAddressRange *bounds) {
1278
118M
    return bounds->opaque.lo_next >= bounds->opaque.limit;
1279
118M
}
1280
1281
int
1282
_PyLineTable_PreviousAddressRange(PyCodeAddressRange *range)
1283
0
{
1284
0
    if (range->ar_start <= 0) {
1285
0
        return 0;
1286
0
    }
1287
0
    retreat(range);
1288
0
    assert(range->ar_end > range->ar_start);
1289
0
    return 1;
1290
0
}
1291
1292
int
1293
_PyLineTable_NextAddressRange(PyCodeAddressRange *range)
1294
118M
{
1295
118M
    if (at_end(range)) {
1296
0
        return 0;
1297
0
    }
1298
118M
    advance(range);
1299
118M
    assert(range->ar_end > range->ar_start);
1300
118M
    return 1;
1301
118M
}
1302
1303
1304
typedef struct {
1305
    PyObject_HEAD
1306
    PyCodeObject *li_code;
1307
    PyCodeAddressRange li_line;
1308
} lineiterator;
1309
1310
1311
static void
1312
lineiter_dealloc(PyObject *self)
1313
0
{
1314
0
    lineiterator *li = (lineiterator*)self;
1315
0
    Py_DECREF(li->li_code);
1316
0
    Py_TYPE(li)->tp_free(li);
1317
0
}
1318
1319
static PyObject *
1320
0
_source_offset_converter(void *arg) {
1321
0
    int *value = (int*)arg;
1322
0
    if (*value == -1) {
1323
0
        Py_RETURN_NONE;
1324
0
    }
1325
0
    return PyLong_FromLong(*value);
1326
0
}
1327
1328
static PyObject *
1329
lineiter_next(PyObject *self)
1330
0
{
1331
0
    lineiterator *li = (lineiterator*)self;
1332
0
    PyCodeAddressRange *bounds = &li->li_line;
1333
0
    if (!_PyLineTable_NextAddressRange(bounds)) {
1334
0
        return NULL;
1335
0
    }
1336
0
    int start = bounds->ar_start;
1337
0
    int line = bounds->ar_line;
1338
    // Merge overlapping entries:
1339
0
    while (_PyLineTable_NextAddressRange(bounds)) {
1340
0
        if (bounds->ar_line != line) {
1341
0
            _PyLineTable_PreviousAddressRange(bounds);
1342
0
            break;
1343
0
        }
1344
0
    }
1345
0
    return Py_BuildValue("iiO&", start, bounds->ar_end,
1346
0
                         _source_offset_converter, &line);
1347
0
}
1348
1349
PyTypeObject _PyLineIterator = {
1350
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1351
    "line_iterator",                    /* tp_name */
1352
    sizeof(lineiterator),               /* tp_basicsize */
1353
    0,                                  /* tp_itemsize */
1354
    /* methods */
1355
    lineiter_dealloc,                   /* tp_dealloc */
1356
    0,                                  /* tp_vectorcall_offset */
1357
    0,                                  /* tp_getattr */
1358
    0,                                  /* tp_setattr */
1359
    0,                                  /* tp_as_async */
1360
    0,                                  /* tp_repr */
1361
    0,                                  /* tp_as_number */
1362
    0,                                  /* tp_as_sequence */
1363
    0,                                  /* tp_as_mapping */
1364
    0,                                  /* tp_hash */
1365
    0,                                  /* tp_call */
1366
    0,                                  /* tp_str */
1367
    0,                                  /* tp_getattro */
1368
    0,                                  /* tp_setattro */
1369
    0,                                  /* tp_as_buffer */
1370
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,       /* tp_flags */
1371
    0,                                  /* tp_doc */
1372
    0,                                  /* tp_traverse */
1373
    0,                                  /* tp_clear */
1374
    0,                                  /* tp_richcompare */
1375
    0,                                  /* tp_weaklistoffset */
1376
    PyObject_SelfIter,                  /* tp_iter */
1377
    lineiter_next,                      /* tp_iternext */
1378
    0,                                  /* tp_methods */
1379
    0,                                  /* tp_members */
1380
    0,                                  /* tp_getset */
1381
    0,                                  /* tp_base */
1382
    0,                                  /* tp_dict */
1383
    0,                                  /* tp_descr_get */
1384
    0,                                  /* tp_descr_set */
1385
    0,                                  /* tp_dictoffset */
1386
    0,                                  /* tp_init */
1387
    0,                                  /* tp_alloc */
1388
    0,                                  /* tp_new */
1389
    PyObject_Free,                      /* tp_free */
1390
};
1391
1392
static lineiterator *
1393
new_linesiterator(PyCodeObject *code)
1394
0
{
1395
0
    lineiterator *li = (lineiterator *)PyType_GenericAlloc(&_PyLineIterator, 0);
1396
0
    if (li == NULL) {
1397
0
        return NULL;
1398
0
    }
1399
0
    li->li_code = (PyCodeObject*)Py_NewRef(code);
1400
0
    _PyCode_InitAddressRange(code, &li->li_line);
1401
0
    return li;
1402
0
}
1403
1404
/* co_positions iterator object. */
1405
typedef struct {
1406
    PyObject_HEAD
1407
    PyCodeObject* pi_code;
1408
    PyCodeAddressRange pi_range;
1409
    int pi_offset;
1410
    int pi_endline;
1411
    int pi_column;
1412
    int pi_endcolumn;
1413
} positionsiterator;
1414
1415
static void
1416
positionsiter_dealloc(PyObject *self)
1417
0
{
1418
0
    positionsiterator *pi = (positionsiterator*)self;
1419
0
    Py_DECREF(pi->pi_code);
1420
0
    Py_TYPE(pi)->tp_free(pi);
1421
0
}
1422
1423
static PyObject*
1424
positionsiter_next(PyObject *self)
1425
0
{
1426
0
    positionsiterator *pi = (positionsiterator*)self;
1427
0
    if (pi->pi_offset >= pi->pi_range.ar_end) {
1428
0
        assert(pi->pi_offset == pi->pi_range.ar_end);
1429
0
        if (at_end(&pi->pi_range)) {
1430
0
            return NULL;
1431
0
        }
1432
0
        advance_with_locations(&pi->pi_range, &pi->pi_endline, &pi->pi_column, &pi->pi_endcolumn);
1433
0
    }
1434
0
    pi->pi_offset += 2;
1435
0
    return Py_BuildValue("(O&O&O&O&)",
1436
0
        _source_offset_converter, &pi->pi_range.ar_line,
1437
0
        _source_offset_converter, &pi->pi_endline,
1438
0
        _source_offset_converter, &pi->pi_column,
1439
0
        _source_offset_converter, &pi->pi_endcolumn);
1440
0
}
1441
1442
PyTypeObject _PyPositionsIterator = {
1443
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1444
    "positions_iterator",               /* tp_name */
1445
    sizeof(positionsiterator),          /* tp_basicsize */
1446
    0,                                  /* tp_itemsize */
1447
    /* methods */
1448
    positionsiter_dealloc,              /* tp_dealloc */
1449
    0,                                  /* tp_vectorcall_offset */
1450
    0,                                  /* tp_getattr */
1451
    0,                                  /* tp_setattr */
1452
    0,                                  /* tp_as_async */
1453
    0,                                  /* tp_repr */
1454
    0,                                  /* tp_as_number */
1455
    0,                                  /* tp_as_sequence */
1456
    0,                                  /* tp_as_mapping */
1457
    0,                                  /* tp_hash */
1458
    0,                                  /* tp_call */
1459
    0,                                  /* tp_str */
1460
    0,                                  /* tp_getattro */
1461
    0,                                  /* tp_setattro */
1462
    0,                                  /* tp_as_buffer */
1463
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,       /* tp_flags */
1464
    0,                                  /* tp_doc */
1465
    0,                                  /* tp_traverse */
1466
    0,                                  /* tp_clear */
1467
    0,                                  /* tp_richcompare */
1468
    0,                                  /* tp_weaklistoffset */
1469
    PyObject_SelfIter,                  /* tp_iter */
1470
    positionsiter_next,                 /* tp_iternext */
1471
    0,                                  /* tp_methods */
1472
    0,                                  /* tp_members */
1473
    0,                                  /* tp_getset */
1474
    0,                                  /* tp_base */
1475
    0,                                  /* tp_dict */
1476
    0,                                  /* tp_descr_get */
1477
    0,                                  /* tp_descr_set */
1478
    0,                                  /* tp_dictoffset */
1479
    0,                                  /* tp_init */
1480
    0,                                  /* tp_alloc */
1481
    0,                                  /* tp_new */
1482
    PyObject_Free,                      /* tp_free */
1483
};
1484
1485
static PyObject*
1486
code_positionsiterator(PyObject *self, PyObject* Py_UNUSED(args))
1487
0
{
1488
0
    PyCodeObject *code = (PyCodeObject*)self;
1489
0
    positionsiterator* pi = (positionsiterator*)PyType_GenericAlloc(&_PyPositionsIterator, 0);
1490
0
    if (pi == NULL) {
1491
0
        return NULL;
1492
0
    }
1493
0
    pi->pi_code = (PyCodeObject*)Py_NewRef(code);
1494
0
    _PyCode_InitAddressRange(code, &pi->pi_range);
1495
0
    pi->pi_offset = pi->pi_range.ar_end;
1496
0
    return (PyObject*)pi;
1497
0
}
1498
1499
1500
/******************
1501
 * "extra" frame eval info (see PEP 523)
1502
 ******************/
1503
1504
/* Holder for co_extra information */
1505
typedef struct {
1506
    Py_ssize_t ce_size;
1507
    void *ce_extras[1];
1508
} _PyCodeObjectExtra;
1509
1510
1511
static inline size_t
1512
code_extra_size(Py_ssize_t n)
1513
0
{
1514
0
    return sizeof(_PyCodeObjectExtra) + (n - 1) * sizeof(void *);
1515
0
}
1516
1517
#ifdef Py_GIL_DISABLED
1518
static int
1519
code_extra_grow_ft(PyCodeObject *co, _PyCodeObjectExtra *old_co_extra,
1520
                   Py_ssize_t old_ce_size, Py_ssize_t new_ce_size,
1521
                   Py_ssize_t index, void *extra)
1522
{
1523
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(co);
1524
    _PyCodeObjectExtra *new_co_extra = PyMem_Malloc(
1525
        code_extra_size(new_ce_size));
1526
    if (new_co_extra == NULL) {
1527
        PyErr_NoMemory();
1528
        return -1;
1529
    }
1530
1531
    if (old_ce_size > 0) {
1532
        memcpy(new_co_extra->ce_extras, old_co_extra->ce_extras,
1533
               old_ce_size * sizeof(void *));
1534
    }
1535
    for (Py_ssize_t i = old_ce_size; i < new_ce_size; i++) {
1536
        new_co_extra->ce_extras[i] = NULL;
1537
    }
1538
    new_co_extra->ce_size = new_ce_size;
1539
    new_co_extra->ce_extras[index] = extra;
1540
1541
    // Publish new buffer and its contents to lock-free readers.
1542
    FT_ATOMIC_STORE_PTR_RELEASE(co->co_extra, new_co_extra);
1543
    if (old_co_extra != NULL) {
1544
        // QSBR: defer old-buffer free until lock-free readers quiesce.
1545
        _PyMem_FreeDelayed(old_co_extra, code_extra_size(old_ce_size));
1546
    }
1547
    return 0;
1548
}
1549
#else
1550
static int
1551
code_extra_grow_gil(PyCodeObject *co, _PyCodeObjectExtra *old_co_extra,
1552
                    Py_ssize_t old_ce_size, Py_ssize_t new_ce_size,
1553
                    Py_ssize_t index, void *extra)
1554
0
{
1555
0
    _PyCodeObjectExtra *new_co_extra = PyMem_Realloc(
1556
0
        old_co_extra, code_extra_size(new_ce_size));
1557
0
    if (new_co_extra == NULL) {
1558
0
        PyErr_NoMemory();
1559
0
        return -1;
1560
0
    }
1561
1562
0
    for (Py_ssize_t i = old_ce_size; i < new_ce_size; i++) {
1563
0
        new_co_extra->ce_extras[i] = NULL;
1564
0
    }
1565
0
    new_co_extra->ce_size = new_ce_size;
1566
0
    new_co_extra->ce_extras[index] = extra;
1567
0
    co->co_extra = new_co_extra;
1568
0
    return 0;
1569
0
}
1570
#endif
1571
1572
int
1573
PyUnstable_Code_GetExtra(PyObject *code, Py_ssize_t index, void **extra)
1574
0
{
1575
0
    if (!PyCode_Check(code)) {
1576
0
        PyErr_BadInternalCall();
1577
0
        return -1;
1578
0
    }
1579
1580
0
    PyCodeObject *co = (PyCodeObject *)code;
1581
0
    *extra = NULL;
1582
1583
0
    if (index < 0) {
1584
0
        return 0;
1585
0
    }
1586
1587
    // Lock-free read; pairs with release stores in SetExtra.
1588
0
    _PyCodeObjectExtra *co_extra = FT_ATOMIC_LOAD_PTR_ACQUIRE(co->co_extra);
1589
0
    if (co_extra != NULL && index < co_extra->ce_size) {
1590
0
        *extra = FT_ATOMIC_LOAD_PTR_ACQUIRE(co_extra->ce_extras[index]);
1591
0
    }
1592
1593
0
    return 0;
1594
0
}
1595
1596
1597
int
1598
PyUnstable_Code_SetExtra(PyObject *code, Py_ssize_t index, void *extra)
1599
0
{
1600
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
1601
1602
    // co_extra_user_count is monotonically increasing and published with
1603
    // release store in RequestCodeExtraIndex, so once an index is valid
1604
    // it stays valid.
1605
0
    Py_ssize_t user_count = FT_ATOMIC_LOAD_SSIZE_ACQUIRE(
1606
0
        interp->co_extra_user_count);
1607
1608
0
    if (!PyCode_Check(code) || index < 0 || index >= user_count) {
1609
0
        PyErr_BadInternalCall();
1610
0
        return -1;
1611
0
    }
1612
1613
0
    PyCodeObject *co = (PyCodeObject *)code;
1614
0
    int result = 0;
1615
0
    void *old_slot_value = NULL;
1616
1617
0
    Py_BEGIN_CRITICAL_SECTION(co);
1618
1619
0
    _PyCodeObjectExtra *old_co_extra = (_PyCodeObjectExtra *)co->co_extra;
1620
0
    Py_ssize_t old_ce_size = (old_co_extra == NULL)
1621
0
        ? 0 : old_co_extra->ce_size;
1622
1623
    // Fast path: slot already exists, update in place.
1624
0
    if (index < old_ce_size) {
1625
0
        old_slot_value = old_co_extra->ce_extras[index];
1626
0
        FT_ATOMIC_STORE_PTR_RELEASE(old_co_extra->ce_extras[index], extra);
1627
0
        goto done;
1628
0
    }
1629
1630
    // Slow path: buffer needs to grow.
1631
0
    Py_ssize_t new_ce_size = user_count;
1632
#ifdef Py_GIL_DISABLED
1633
    // FT build: allocate new buffer and swap; QSBR reclaims the old one.
1634
    result = code_extra_grow_ft(
1635
        co, old_co_extra, old_ce_size, new_ce_size, index, extra);
1636
#else
1637
    // GIL build: grow with realloc.
1638
0
    result = code_extra_grow_gil(
1639
0
        co, old_co_extra, old_ce_size, new_ce_size, index, extra);
1640
0
#endif
1641
1642
0
done:;
1643
0
    Py_END_CRITICAL_SECTION();
1644
0
    if (old_slot_value != NULL) {
1645
        // Free the old slot value if a free function was registered.
1646
        // The caller must ensure no other thread can still access the old
1647
        // value after this overwrite.
1648
0
        freefunc free_extra = interp->co_extra_freefuncs[index];
1649
0
        if (free_extra != NULL) {
1650
0
            free_extra(old_slot_value);
1651
0
        }
1652
0
    }
1653
1654
0
    return result;
1655
0
}
1656
1657
1658
/******************
1659
 * other PyCodeObject accessor functions
1660
 ******************/
1661
1662
static PyObject *
1663
get_cached_locals(PyCodeObject *co, PyObject **cached_field,
1664
    _PyLocals_Kind kind, int num)
1665
0
{
1666
0
    assert(cached_field != NULL);
1667
0
    assert(co->_co_cached != NULL);
1668
0
    PyObject *varnames = FT_ATOMIC_LOAD_PTR(*cached_field);
1669
0
    if (varnames != NULL) {
1670
0
        return Py_NewRef(varnames);
1671
0
    }
1672
1673
0
    Py_BEGIN_CRITICAL_SECTION(co);
1674
0
    varnames = *cached_field;
1675
0
    if (varnames == NULL) {
1676
0
        varnames = get_localsplus_names(co, kind, num);
1677
0
        if (varnames != NULL) {
1678
0
            FT_ATOMIC_STORE_PTR(*cached_field, varnames);
1679
0
        }
1680
0
    }
1681
0
    Py_END_CRITICAL_SECTION();
1682
0
    return Py_XNewRef(varnames);
1683
0
}
1684
1685
PyObject *
1686
_PyCode_GetVarnames(PyCodeObject *co)
1687
0
{
1688
0
    if (init_co_cached(co)) {
1689
0
        return NULL;
1690
0
    }
1691
0
    return get_cached_locals(co, &co->_co_cached->_co_varnames, CO_FAST_LOCAL, co->co_nlocals);
1692
0
}
1693
1694
PyObject *
1695
PyCode_GetVarnames(PyCodeObject *code)
1696
0
{
1697
0
    return _PyCode_GetVarnames(code);
1698
0
}
1699
1700
PyObject *
1701
_PyCode_GetCellvars(PyCodeObject *co)
1702
0
{
1703
0
    if (init_co_cached(co)) {
1704
0
        return NULL;
1705
0
    }
1706
0
    return get_cached_locals(co, &co->_co_cached->_co_cellvars, CO_FAST_CELL, co->co_ncellvars);
1707
0
}
1708
1709
PyObject *
1710
PyCode_GetCellvars(PyCodeObject *code)
1711
0
{
1712
0
    return _PyCode_GetCellvars(code);
1713
0
}
1714
1715
PyObject *
1716
_PyCode_GetFreevars(PyCodeObject *co)
1717
0
{
1718
0
    if (init_co_cached(co)) {
1719
0
        return NULL;
1720
0
    }
1721
0
    return get_cached_locals(co, &co->_co_cached->_co_freevars, CO_FAST_FREE, co->co_nfreevars);
1722
0
}
1723
1724
PyObject *
1725
PyCode_GetFreevars(PyCodeObject *code)
1726
0
{
1727
0
    return _PyCode_GetFreevars(code);
1728
0
}
1729
1730
1731
0
#define GET_OPARG(co, i, initial) (initial)
1732
// We may want to move these macros to pycore_opcode_utils.h
1733
// and use them in Python/bytecodes.c.
1734
#define LOAD_GLOBAL_NAME_INDEX(oparg) ((oparg)>>1)
1735
0
#define LOAD_ATTR_NAME_INDEX(oparg) ((oparg)>>1)
1736
1737
#ifndef Py_DEBUG
1738
0
#define GETITEM(v, i) PyTuple_GET_ITEM((v), (i))
1739
#else
1740
static inline PyObject *
1741
GETITEM(PyObject *v, Py_ssize_t i)
1742
{
1743
    assert(PyTuple_Check(v));
1744
    assert(i >= 0);
1745
    assert(i < PyTuple_GET_SIZE(v));
1746
    assert(PyTuple_GET_ITEM(v, i) != NULL);
1747
    return PyTuple_GET_ITEM(v, i);
1748
}
1749
#endif
1750
1751
static int
1752
identify_unbound_names(PyThreadState *tstate, PyCodeObject *co,
1753
                       PyObject *globalnames, PyObject *attrnames,
1754
                       PyObject *globalsns, PyObject *builtinsns,
1755
                       struct co_unbound_counts *counts, int *p_numdupes)
1756
0
{
1757
    // This function is inspired by inspect.getclosurevars().
1758
    // It would be nicer if we had something similar to co_localspluskinds,
1759
    // but for co_names.
1760
0
    assert(globalnames != NULL);
1761
0
    assert(PySet_Check(globalnames));
1762
0
    assert(PySet_GET_SIZE(globalnames) == 0 || counts != NULL);
1763
0
    assert(attrnames != NULL);
1764
0
    assert(PySet_Check(attrnames));
1765
0
    assert(PySet_GET_SIZE(attrnames) == 0 || counts != NULL);
1766
0
    assert(globalsns == NULL || PyAnyDict_Check(globalsns));
1767
0
    assert(builtinsns == NULL || PyDict_Check(builtinsns));
1768
0
    assert(counts == NULL || counts->total == 0);
1769
0
    struct co_unbound_counts unbound = {0};
1770
0
    int numdupes = 0;
1771
0
    Py_ssize_t len = Py_SIZE(co);
1772
0
    for (int i = 0; i < len; i += _PyInstruction_GetLength(co, i)) {
1773
0
        _Py_CODEUNIT inst = _Py_GetBaseCodeUnit(co, i);
1774
0
        if (inst.op.code == LOAD_ATTR) {
1775
0
            int oparg = GET_OPARG(co, i, inst.op.arg);
1776
0
            int index = LOAD_ATTR_NAME_INDEX(oparg);
1777
0
            PyObject *name = GETITEM(co->co_names, index);
1778
0
            if (PySet_Contains(attrnames, name)) {
1779
0
                if (_PyErr_Occurred(tstate)) {
1780
0
                    return -1;
1781
0
                }
1782
0
                continue;
1783
0
            }
1784
0
            unbound.total += 1;
1785
0
            unbound.numattrs += 1;
1786
0
            if (PySet_Add(attrnames, name) < 0) {
1787
0
                return -1;
1788
0
            }
1789
0
            if (PySet_Contains(globalnames, name)) {
1790
0
                if (_PyErr_Occurred(tstate)) {
1791
0
                    return -1;
1792
0
                }
1793
0
                numdupes += 1;
1794
0
            }
1795
0
        }
1796
0
        else if (inst.op.code == LOAD_GLOBAL) {
1797
0
            int oparg = GET_OPARG(co, i, inst.op.arg);
1798
0
            int index = LOAD_ATTR_NAME_INDEX(oparg);
1799
0
            PyObject *name = GETITEM(co->co_names, index);
1800
0
            if (PySet_Contains(globalnames, name)) {
1801
0
                if (_PyErr_Occurred(tstate)) {
1802
0
                    return -1;
1803
0
                }
1804
0
                continue;
1805
0
            }
1806
0
            unbound.total += 1;
1807
0
            unbound.globals.total += 1;
1808
0
            if (globalsns != NULL && PyDict_Contains(globalsns, name)) {
1809
0
                if (_PyErr_Occurred(tstate)) {
1810
0
                    return -1;
1811
0
                }
1812
0
                unbound.globals.numglobal += 1;
1813
0
            }
1814
0
            else if (builtinsns != NULL && PyDict_Contains(builtinsns, name)) {
1815
0
                if (_PyErr_Occurred(tstate)) {
1816
0
                    return -1;
1817
0
                }
1818
0
                unbound.globals.numbuiltin += 1;
1819
0
            }
1820
0
            else {
1821
0
                unbound.globals.numunknown += 1;
1822
0
            }
1823
0
            if (PySet_Add(globalnames, name) < 0) {
1824
0
                return -1;
1825
0
            }
1826
0
            if (PySet_Contains(attrnames, name)) {
1827
0
                if (_PyErr_Occurred(tstate)) {
1828
0
                    return -1;
1829
0
                }
1830
0
                numdupes += 1;
1831
0
            }
1832
0
        }
1833
0
    }
1834
0
    if (counts != NULL) {
1835
0
        *counts = unbound;
1836
0
    }
1837
0
    if (p_numdupes != NULL) {
1838
0
        *p_numdupes = numdupes;
1839
0
    }
1840
0
    return 0;
1841
0
}
1842
1843
1844
void
1845
_PyCode_GetVarCounts(PyCodeObject *co, _PyCode_var_counts_t *counts)
1846
0
{
1847
0
    assert(counts != NULL);
1848
1849
    // Count the locals, cells, and free vars.
1850
0
    struct co_locals_counts locals = {0};
1851
0
    int numfree = 0;
1852
0
    PyObject *kinds = co->co_localspluskinds;
1853
0
    Py_ssize_t numlocalplusfree = PyBytes_GET_SIZE(kinds);
1854
0
    for (int i = 0; i < numlocalplusfree; i++) {
1855
0
        _PyLocals_Kind kind = _PyLocals_GetKind(co->co_localspluskinds, i);
1856
0
        if (kind & CO_FAST_FREE) {
1857
0
            assert(!(kind & CO_FAST_LOCAL));
1858
0
            assert(!(kind & CO_FAST_HIDDEN));
1859
0
            assert(!(kind & CO_FAST_ARG));
1860
0
            numfree += 1;
1861
0
        }
1862
0
        else {
1863
            // Apparently not all non-free vars a CO_FAST_LOCAL.
1864
0
            assert(kind);
1865
0
            locals.total += 1;
1866
0
            if (kind & CO_FAST_ARG) {
1867
0
                locals.args.total += 1;
1868
0
                if (kind & CO_FAST_ARG_VAR) {
1869
0
                    if (kind & CO_FAST_ARG_POS) {
1870
0
                        assert(!(kind & CO_FAST_ARG_KW));
1871
0
                        assert(!locals.args.varargs);
1872
0
                        locals.args.varargs = 1;
1873
0
                    }
1874
0
                    else {
1875
0
                        assert(kind & CO_FAST_ARG_KW);
1876
0
                        assert(!locals.args.varkwargs);
1877
0
                        locals.args.varkwargs = 1;
1878
0
                    }
1879
0
                }
1880
0
                else if (kind & CO_FAST_ARG_POS) {
1881
0
                    if (kind & CO_FAST_ARG_KW) {
1882
0
                        locals.args.numposorkw += 1;
1883
0
                    }
1884
0
                    else {
1885
0
                        locals.args.numposonly += 1;
1886
0
                    }
1887
0
                }
1888
0
                else {
1889
0
                    assert(kind & CO_FAST_ARG_KW);
1890
0
                    locals.args.numkwonly += 1;
1891
0
                }
1892
0
                if (kind & CO_FAST_CELL) {
1893
0
                    locals.cells.total += 1;
1894
0
                    locals.cells.numargs += 1;
1895
0
                }
1896
                // Args are never hidden currently.
1897
0
                assert(!(kind & CO_FAST_HIDDEN));
1898
0
            }
1899
0
            else {
1900
0
                if (kind & CO_FAST_CELL) {
1901
0
                    locals.cells.total += 1;
1902
0
                    locals.cells.numothers += 1;
1903
0
                    if (kind & CO_FAST_HIDDEN) {
1904
0
                        locals.hidden.total += 1;
1905
0
                        locals.hidden.numcells += 1;
1906
0
                    }
1907
0
                }
1908
0
                else {
1909
0
                    locals.numpure += 1;
1910
0
                    if (kind & CO_FAST_HIDDEN) {
1911
0
                        locals.hidden.total += 1;
1912
0
                        locals.hidden.numpure += 1;
1913
0
                    }
1914
0
                }
1915
0
            }
1916
0
        }
1917
0
    }
1918
0
    assert(locals.args.total == (
1919
0
            co->co_argcount + co->co_kwonlyargcount
1920
0
            + !!(co->co_flags & CO_VARARGS)
1921
0
            + !!(co->co_flags & CO_VARKEYWORDS)));
1922
0
    assert(locals.args.numposonly == co->co_posonlyargcount);
1923
0
    assert(locals.args.numposonly + locals.args.numposorkw == co->co_argcount);
1924
0
    assert(locals.args.numkwonly == co->co_kwonlyargcount);
1925
0
    assert(locals.cells.total == co->co_ncellvars);
1926
0
    assert(locals.args.total + locals.numpure == co->co_nlocals);
1927
0
    assert(locals.total + locals.cells.numargs == co->co_nlocals + co->co_ncellvars);
1928
0
    assert(locals.total + numfree == co->co_nlocalsplus);
1929
0
    assert(numfree == co->co_nfreevars);
1930
1931
    // Get the unbound counts.
1932
0
    assert(PyTuple_GET_SIZE(co->co_names) >= 0);
1933
0
    assert(PyTuple_GET_SIZE(co->co_names) < INT_MAX);
1934
0
    int numunbound = (int)PyTuple_GET_SIZE(co->co_names);
1935
0
    struct co_unbound_counts unbound = {
1936
0
        .total = numunbound,
1937
        // numglobal and numattrs can be set later
1938
        // with _PyCode_SetUnboundVarCounts().
1939
0
        .numunknown = numunbound,
1940
0
    };
1941
1942
    // "Return" the result.
1943
0
    *counts = (_PyCode_var_counts_t){
1944
0
        .total = locals.total + numfree + unbound.total,
1945
0
        .locals = locals,
1946
0
        .numfree = numfree,
1947
0
        .unbound = unbound,
1948
0
    };
1949
0
}
1950
1951
int
1952
_PyCode_SetUnboundVarCounts(PyThreadState *tstate,
1953
                            PyCodeObject *co, _PyCode_var_counts_t *counts,
1954
                            PyObject *globalnames, PyObject *attrnames,
1955
                            PyObject *globalsns, PyObject *builtinsns)
1956
0
{
1957
0
    int res = -1;
1958
0
    PyObject *globalnames_owned = NULL;
1959
0
    PyObject *attrnames_owned = NULL;
1960
1961
    // Prep the name sets.
1962
0
    if (globalnames == NULL) {
1963
0
        globalnames_owned = PySet_New(NULL);
1964
0
        if (globalnames_owned == NULL) {
1965
0
            goto finally;
1966
0
        }
1967
0
        globalnames = globalnames_owned;
1968
0
    }
1969
0
    else if (!PySet_Check(globalnames)) {
1970
0
        _PyErr_Format(tstate, PyExc_TypeError,
1971
0
                     "expected a set for \"globalnames\", got %R", globalnames);
1972
0
        goto finally;
1973
0
    }
1974
0
    if (attrnames == NULL) {
1975
0
        attrnames_owned = PySet_New(NULL);
1976
0
        if (attrnames_owned == NULL) {
1977
0
            goto finally;
1978
0
        }
1979
0
        attrnames = attrnames_owned;
1980
0
    }
1981
0
    else if (!PySet_Check(attrnames)) {
1982
0
        _PyErr_Format(tstate, PyExc_TypeError,
1983
0
                     "expected a set for \"attrnames\", got %R", attrnames);
1984
0
        goto finally;
1985
0
    }
1986
1987
    // Fill in unbound.globals and unbound.numattrs.
1988
0
    struct co_unbound_counts unbound = {0};
1989
0
    int numdupes = 0;
1990
0
    Py_BEGIN_CRITICAL_SECTION(co);
1991
0
    res = identify_unbound_names(
1992
0
            tstate, co, globalnames, attrnames, globalsns, builtinsns,
1993
0
            &unbound, &numdupes);
1994
0
    Py_END_CRITICAL_SECTION();
1995
0
    if (res < 0) {
1996
0
        goto finally;
1997
0
    }
1998
0
    assert(unbound.numunknown == 0);
1999
0
    assert(unbound.total - numdupes <= counts->unbound.total);
2000
0
    assert(counts->unbound.numunknown == counts->unbound.total);
2001
    // There may be a name that is both a global and an attr.
2002
0
    int totalunbound = counts->unbound.total + numdupes;
2003
0
    unbound.numunknown = totalunbound - unbound.total;
2004
0
    unbound.total = totalunbound;
2005
0
    counts->unbound = unbound;
2006
0
    counts->total += numdupes;
2007
0
    res = 0;
2008
2009
0
finally:
2010
0
    Py_XDECREF(globalnames_owned);
2011
0
    Py_XDECREF(attrnames_owned);
2012
0
    return res;
2013
0
}
2014
2015
2016
int
2017
_PyCode_CheckNoInternalState(PyCodeObject *co, const char **p_errmsg)
2018
0
{
2019
0
    const char *errmsg = NULL;
2020
    // We don't worry about co_executors, co_instrumentation,
2021
    // or co_monitoring.  They are essentially ephemeral.
2022
0
    if (co->co_extra != NULL) {
2023
0
        errmsg = "only basic code objects are supported";
2024
0
    }
2025
2026
0
    if (errmsg != NULL) {
2027
0
        if (p_errmsg != NULL) {
2028
0
            *p_errmsg = errmsg;
2029
0
        }
2030
0
        return 0;
2031
0
    }
2032
0
    return 1;
2033
0
}
2034
2035
int
2036
_PyCode_CheckNoExternalState(PyCodeObject *co, _PyCode_var_counts_t *counts,
2037
                             const char **p_errmsg)
2038
0
{
2039
0
    const char *errmsg = NULL;
2040
0
    if (counts->numfree > 0) {  // It's a closure.
2041
0
        errmsg = "closures not supported";
2042
0
    }
2043
0
    else if (counts->unbound.globals.numglobal > 0) {
2044
0
        errmsg = "globals not supported";
2045
0
    }
2046
0
    else if (counts->unbound.globals.numbuiltin > 0
2047
0
             && counts->unbound.globals.numunknown > 0)
2048
0
    {
2049
0
        errmsg = "globals not supported";
2050
0
    }
2051
    // Otherwise we don't check counts.unbound.globals.numunknown since we can't
2052
    // distinguish beween globals and builtins here.
2053
2054
0
    if (errmsg != NULL) {
2055
0
        if (p_errmsg != NULL) {
2056
0
            *p_errmsg = errmsg;
2057
0
        }
2058
0
        return 0;
2059
0
    }
2060
0
    return 1;
2061
0
}
2062
2063
int
2064
_PyCode_VerifyStateless(PyThreadState *tstate,
2065
                        PyCodeObject *co, PyObject *globalnames,
2066
                        PyObject *globalsns, PyObject *builtinsns)
2067
0
{
2068
0
    const char *errmsg;
2069
0
   _PyCode_var_counts_t counts = {0};
2070
0
    _PyCode_GetVarCounts(co, &counts);
2071
0
    if (_PyCode_SetUnboundVarCounts(
2072
0
                            tstate, co, &counts, globalnames, NULL,
2073
0
                            globalsns, builtinsns) < 0)
2074
0
    {
2075
0
        return -1;
2076
0
    }
2077
    // We may consider relaxing the internal state constraints
2078
    // if it becomes a problem.
2079
0
    if (!_PyCode_CheckNoInternalState(co, &errmsg)) {
2080
0
        _PyErr_SetString(tstate, PyExc_ValueError, errmsg);
2081
0
        return -1;
2082
0
    }
2083
0
    if (builtinsns != NULL) {
2084
        // Make sure the next check will fail for globals,
2085
        // even if there aren't any builtins.
2086
0
        counts.unbound.globals.numbuiltin += 1;
2087
0
    }
2088
0
    if (!_PyCode_CheckNoExternalState(co, &counts, &errmsg)) {
2089
0
        _PyErr_SetString(tstate, PyExc_ValueError, errmsg);
2090
0
        return -1;
2091
0
    }
2092
    // Note that we don't check co->co_flags & CO_NESTED for anything here.
2093
0
    return 0;
2094
0
}
2095
2096
2097
int
2098
_PyCode_CheckPureFunction(PyCodeObject *co, const char **p_errmsg)
2099
0
{
2100
0
    const char *errmsg = NULL;
2101
0
    if (co->co_flags & CO_GENERATOR) {
2102
0
        errmsg = "generators not supported";
2103
0
    }
2104
0
    else if (co->co_flags & CO_COROUTINE) {
2105
0
        errmsg = "coroutines not supported";
2106
0
    }
2107
0
    else if (co->co_flags & CO_ITERABLE_COROUTINE) {
2108
0
        errmsg = "coroutines not supported";
2109
0
    }
2110
0
    else if (co->co_flags & CO_ASYNC_GENERATOR) {
2111
0
        errmsg = "generators not supported";
2112
0
    }
2113
2114
0
    if (errmsg != NULL) {
2115
0
        if (p_errmsg != NULL) {
2116
0
            *p_errmsg = errmsg;
2117
0
        }
2118
0
        return 0;
2119
0
    }
2120
0
    return 1;
2121
0
}
2122
2123
/* Here "value" means a non-None value, since a bare return is identical
2124
 * to returning None explicitly.  Likewise a missing return statement
2125
 * at the end of the function is turned into "return None". */
2126
static int
2127
code_returns_only_none(PyCodeObject *co)
2128
0
{
2129
0
    if (!_PyCode_CheckPureFunction(co, NULL)) {
2130
0
        return 0;
2131
0
    }
2132
0
    int len = (int)Py_SIZE(co);
2133
0
    assert(len > 0);
2134
2135
    // Look up None in co_consts.
2136
0
    Py_ssize_t nconsts = PyTuple_Size(co->co_consts);
2137
0
    int none_index = 0;
2138
0
    for (; none_index < nconsts; none_index++) {
2139
0
        if (PyTuple_GET_ITEM(co->co_consts, none_index) == Py_None) {
2140
0
            break;
2141
0
        }
2142
0
    }
2143
    /* We don't worry about EXTENDED_ARG for now. */
2144
0
    for (int i = 0; i < len; i += _PyInstruction_GetLength(co, i)) {
2145
0
        _Py_CODEUNIT inst = _Py_GetBaseCodeUnit(co, i);
2146
0
        if (!IS_RETURN_OPCODE(inst.op.code)) {
2147
0
            continue;
2148
0
        }
2149
0
        assert(i != 0);
2150
0
        _Py_CODEUNIT prev = _Py_GetBaseCodeUnit(co, i-1);
2151
0
        if (prev.op.code == LOAD_COMMON_CONSTANT &&
2152
0
            prev.op.arg == CONSTANT_NONE)
2153
0
        {
2154
0
            continue;
2155
0
        }
2156
0
        if (none_index < nconsts && prev.op.code == LOAD_CONST
2157
0
            && prev.op.arg == none_index)
2158
0
        {
2159
0
            continue;
2160
0
        }
2161
0
        return 0;
2162
0
    }
2163
0
    return 1;
2164
0
}
2165
2166
int
2167
_PyCode_ReturnsOnlyNone(PyCodeObject *co)
2168
0
{
2169
0
    int res;
2170
0
    Py_BEGIN_CRITICAL_SECTION(co);
2171
0
    res = code_returns_only_none(co);
2172
0
    Py_END_CRITICAL_SECTION();
2173
0
    return res;
2174
0
}
2175
2176
2177
#ifdef _Py_TIER2
2178
2179
static void
2180
clear_executors(PyCodeObject *co)
2181
{
2182
    assert(co->co_executors);
2183
    for (int i = 0; i < co->co_executors->size; i++) {
2184
        if (co->co_executors->executors[i]) {
2185
            _Py_ExecutorDetach(co->co_executors->executors[i]);
2186
            assert(co->co_executors->executors[i] == NULL);
2187
        }
2188
    }
2189
    PyMem_Free(co->co_executors);
2190
    co->co_executors = NULL;
2191
}
2192
2193
void
2194
_PyCode_Clear_Executors(PyCodeObject *code)
2195
{
2196
    clear_executors(code);
2197
}
2198
2199
#endif
2200
2201
static void
2202
deopt_code(PyCodeObject *code, _Py_CODEUNIT *instructions)
2203
0
{
2204
0
    Py_ssize_t len = Py_SIZE(code);
2205
0
    for (int i = 0; i < len; i++) {
2206
0
        _Py_CODEUNIT inst = _Py_GetBaseCodeUnit(code, i);
2207
0
        assert(inst.op.code < MIN_SPECIALIZED_OPCODE);
2208
0
        int caches = _PyOpcode_Caches[inst.op.code];
2209
0
        instructions[i] = inst;
2210
0
        for (int j = 1; j <= caches; j++) {
2211
0
            instructions[i+j].cache = 0;
2212
0
        }
2213
0
        i += caches;
2214
0
    }
2215
0
}
2216
2217
PyObject *
2218
_PyCode_GetCode(PyCodeObject *co)
2219
0
{
2220
0
    if (init_co_cached(co)) {
2221
0
        return NULL;
2222
0
    }
2223
2224
0
    _PyCoCached *cached = co->_co_cached;
2225
0
    PyObject *code = FT_ATOMIC_LOAD_PTR(cached->_co_code);
2226
0
    if (code != NULL) {
2227
0
        return Py_NewRef(code);
2228
0
    }
2229
2230
0
    Py_BEGIN_CRITICAL_SECTION(co);
2231
0
    code = cached->_co_code;
2232
0
    if (code == NULL) {
2233
0
        code = PyBytes_FromStringAndSize((const char *)_PyCode_CODE(co),
2234
0
                                         _PyCode_NBYTES(co));
2235
0
        if (code != NULL) {
2236
0
            deopt_code(co, (_Py_CODEUNIT *)PyBytes_AS_STRING(code));
2237
0
            assert(cached->_co_code == NULL);
2238
0
            FT_ATOMIC_STORE_PTR(cached->_co_code, code);
2239
0
        }
2240
0
    }
2241
0
    Py_END_CRITICAL_SECTION();
2242
0
    return Py_XNewRef(code);
2243
0
}
2244
2245
PyObject *
2246
PyCode_GetCode(PyCodeObject *co)
2247
0
{
2248
0
    return _PyCode_GetCode(co);
2249
0
}
2250
2251
/******************
2252
 * PyCode_Type
2253
 ******************/
2254
2255
/*[clinic input]
2256
class code "PyCodeObject *" "&PyCode_Type"
2257
[clinic start generated code]*/
2258
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=78aa5d576683bb4b]*/
2259
2260
/*[clinic input]
2261
@classmethod
2262
code.__new__ as code_new
2263
2264
    argcount: int
2265
    posonlyargcount: int
2266
    kwonlyargcount: int
2267
    nlocals: int
2268
    stacksize: int
2269
    flags: int
2270
    codestring as code: object(subclass_of="&PyBytes_Type")
2271
    constants as consts: object(subclass_of="&PyTuple_Type")
2272
    names: object(subclass_of="&PyTuple_Type")
2273
    varnames: object(subclass_of="&PyTuple_Type")
2274
    filename: unicode
2275
    name: unicode
2276
    qualname: unicode
2277
    firstlineno: int
2278
    linetable: object(subclass_of="&PyBytes_Type")
2279
    exceptiontable: object(subclass_of="&PyBytes_Type")
2280
    freevars: object(subclass_of="&PyTuple_Type", c_default="NULL") = ()
2281
    cellvars: object(subclass_of="&PyTuple_Type", c_default="NULL") = ()
2282
    /
2283
2284
Create a code object.  Not for the faint of heart.
2285
[clinic start generated code]*/
2286
2287
static PyObject *
2288
code_new_impl(PyTypeObject *type, int argcount, int posonlyargcount,
2289
              int kwonlyargcount, int nlocals, int stacksize, int flags,
2290
              PyObject *code, PyObject *consts, PyObject *names,
2291
              PyObject *varnames, PyObject *filename, PyObject *name,
2292
              PyObject *qualname, int firstlineno, PyObject *linetable,
2293
              PyObject *exceptiontable, PyObject *freevars,
2294
              PyObject *cellvars)
2295
/*[clinic end generated code: output=069fa20d299f9dda input=e31da3c41ad8064a]*/
2296
0
{
2297
0
    PyObject *co = NULL;
2298
0
    PyObject *ournames = NULL;
2299
0
    PyObject *ourvarnames = NULL;
2300
0
    PyObject *ourfreevars = NULL;
2301
0
    PyObject *ourcellvars = NULL;
2302
2303
0
    if (PySys_Audit("code.__new__", "OOOiiiiii",
2304
0
                    code, filename, name, argcount, posonlyargcount,
2305
0
                    kwonlyargcount, nlocals, stacksize, flags) < 0) {
2306
0
        goto cleanup;
2307
0
    }
2308
2309
0
    if (argcount < 0) {
2310
0
        PyErr_SetString(
2311
0
            PyExc_ValueError,
2312
0
            "code: argcount must not be negative");
2313
0
        goto cleanup;
2314
0
    }
2315
2316
0
    if (posonlyargcount < 0) {
2317
0
        PyErr_SetString(
2318
0
            PyExc_ValueError,
2319
0
            "code: posonlyargcount must not be negative");
2320
0
        goto cleanup;
2321
0
    }
2322
2323
0
    if (kwonlyargcount < 0) {
2324
0
        PyErr_SetString(
2325
0
            PyExc_ValueError,
2326
0
            "code: kwonlyargcount must not be negative");
2327
0
        goto cleanup;
2328
0
    }
2329
0
    if (nlocals < 0) {
2330
0
        PyErr_SetString(
2331
0
            PyExc_ValueError,
2332
0
            "code: nlocals must not be negative");
2333
0
        goto cleanup;
2334
0
    }
2335
2336
0
    ournames = validate_and_copy_tuple(names);
2337
0
    if (ournames == NULL)
2338
0
        goto cleanup;
2339
0
    ourvarnames = validate_and_copy_tuple(varnames);
2340
0
    if (ourvarnames == NULL)
2341
0
        goto cleanup;
2342
0
    if (freevars)
2343
0
        ourfreevars = validate_and_copy_tuple(freevars);
2344
0
    else
2345
0
        ourfreevars = PyTuple_New(0);
2346
0
    if (ourfreevars == NULL)
2347
0
        goto cleanup;
2348
0
    if (cellvars)
2349
0
        ourcellvars = validate_and_copy_tuple(cellvars);
2350
0
    else
2351
0
        ourcellvars = PyTuple_New(0);
2352
0
    if (ourcellvars == NULL)
2353
0
        goto cleanup;
2354
2355
0
    co = (PyObject *)PyCode_NewWithPosOnlyArgs(argcount, posonlyargcount,
2356
0
                                               kwonlyargcount,
2357
0
                                               nlocals, stacksize, flags,
2358
0
                                               code, consts, ournames,
2359
0
                                               ourvarnames, ourfreevars,
2360
0
                                               ourcellvars, filename,
2361
0
                                               name, qualname, firstlineno,
2362
0
                                               linetable,
2363
0
                                               exceptiontable
2364
0
                                              );
2365
0
  cleanup:
2366
0
    Py_XDECREF(ournames);
2367
0
    Py_XDECREF(ourvarnames);
2368
0
    Py_XDECREF(ourfreevars);
2369
0
    Py_XDECREF(ourcellvars);
2370
0
    return co;
2371
0
}
2372
2373
static void
2374
free_monitoring_data(_PyCoMonitoringData *data)
2375
3.74k
{
2376
3.74k
    if (data == NULL) {
2377
3.74k
        return;
2378
3.74k
    }
2379
0
    if (data->tools) {
2380
0
        PyMem_Free(data->tools);
2381
0
    }
2382
0
    if (data->lines) {
2383
0
        PyMem_Free(data->lines);
2384
0
    }
2385
0
    if (data->line_tools) {
2386
0
        PyMem_Free(data->line_tools);
2387
0
    }
2388
0
    if (data->per_instruction_opcodes) {
2389
0
        PyMem_Free(data->per_instruction_opcodes);
2390
0
    }
2391
0
    if (data->per_instruction_tools) {
2392
0
        PyMem_Free(data->per_instruction_tools);
2393
0
    }
2394
0
    PyMem_Free(data);
2395
0
}
2396
2397
static void
2398
code_dealloc(PyObject *self)
2399
3.74k
{
2400
3.74k
    PyThreadState *tstate = PyThreadState_GET();
2401
3.74k
    _Py_atomic_add_uint64(&tstate->interp->_code_object_generation, 1);
2402
3.74k
    PyCodeObject *co = _PyCodeObject_CAST(self);
2403
0
    _PyObject_ResurrectStart(self);
2404
3.74k
    notify_code_watchers(PY_CODE_EVENT_DESTROY, co);
2405
3.74k
    if (_PyObject_ResurrectEnd(self)) {
2406
0
        return;
2407
0
    }
2408
2409
#ifdef Py_GIL_DISABLED
2410
    PyObject_GC_UnTrack(co);
2411
#endif
2412
2413
3.74k
    _PyFunction_ClearCodeByVersion(co->co_version);
2414
3.74k
    if (co->co_extra != NULL) {
2415
0
        PyInterpreterState *interp = _PyInterpreterState_GET();
2416
0
        _PyCodeObjectExtra *co_extra = co->co_extra;
2417
2418
0
        for (Py_ssize_t i = 0; i < co_extra->ce_size; i++) {
2419
0
            freefunc free_extra = interp->co_extra_freefuncs[i];
2420
2421
0
            if (free_extra != NULL) {
2422
0
                free_extra(co_extra->ce_extras[i]);
2423
0
            }
2424
0
        }
2425
2426
0
        PyMem_Free(co_extra);
2427
0
    }
2428
#ifdef _Py_TIER2
2429
    if (co->co_executors != NULL) {
2430
        clear_executors(co);
2431
    }
2432
#endif
2433
2434
3.74k
    Py_XDECREF(co->co_consts);
2435
3.74k
    Py_XDECREF(co->co_names);
2436
3.74k
    Py_XDECREF(co->co_localsplusnames);
2437
3.74k
    Py_XDECREF(co->co_localspluskinds);
2438
3.74k
    Py_XDECREF(co->co_filename);
2439
3.74k
    Py_XDECREF(co->co_name);
2440
3.74k
    Py_XDECREF(co->co_qualname);
2441
3.74k
    Py_XDECREF(co->co_linetable);
2442
3.74k
    Py_XDECREF(co->co_exceptiontable);
2443
#ifdef Py_GIL_DISABLED
2444
    assert(co->_co_unique_id == _Py_INVALID_UNIQUE_ID);
2445
#endif
2446
3.74k
    if (co->_co_cached != NULL) {
2447
0
        Py_XDECREF(co->_co_cached->_co_code);
2448
0
        Py_XDECREF(co->_co_cached->_co_cellvars);
2449
0
        Py_XDECREF(co->_co_cached->_co_freevars);
2450
0
        Py_XDECREF(co->_co_cached->_co_varnames);
2451
0
        PyMem_Free(co->_co_cached);
2452
0
    }
2453
3.74k
    FT_CLEAR_WEAKREFS(self, co->co_weakreflist);
2454
3.74k
    free_monitoring_data(co->_co_monitoring);
2455
#ifdef Py_GIL_DISABLED
2456
    if (co->co_tlbc != NULL) {
2457
        // The first element always points to the mutable bytecode at the end of
2458
        // the code object, which will be freed when the code object is freed.
2459
        for (Py_ssize_t i = 1; i < co->co_tlbc->size; i++) {
2460
            char *entry = co->co_tlbc->entries[i];
2461
            if (entry != NULL) {
2462
                PyMem_Free(entry);
2463
            }
2464
        }
2465
        PyMem_Free(co->co_tlbc);
2466
    }
2467
#endif
2468
3.74k
    PyObject_Free(co);
2469
3.74k
}
2470
2471
#ifdef Py_GIL_DISABLED
2472
static int
2473
code_traverse(PyObject *self, visitproc visit, void *arg)
2474
{
2475
    PyCodeObject *co = _PyCodeObject_CAST(self);
2476
    Py_VISIT(co->co_consts);
2477
    return 0;
2478
}
2479
#endif
2480
2481
static PyObject *
2482
code_repr(PyObject *self)
2483
0
{
2484
0
    PyCodeObject *co = _PyCodeObject_CAST(self);
2485
0
    int lineno;
2486
0
    if (co->co_firstlineno != 0)
2487
0
        lineno = co->co_firstlineno;
2488
0
    else
2489
0
        lineno = -1;
2490
0
    if (co->co_filename && PyUnicode_Check(co->co_filename)) {
2491
0
        return PyUnicode_FromFormat(
2492
0
            "<code object %U at %p, file \"%U\", line %d>",
2493
0
            co->co_name, co, co->co_filename, lineno);
2494
0
    } else {
2495
0
        return PyUnicode_FromFormat(
2496
0
            "<code object %U at %p, file ???, line %d>",
2497
0
            co->co_name, co, lineno);
2498
0
    }
2499
0
}
2500
2501
static PyObject *
2502
code_richcompare(PyObject *self, PyObject *other, int op)
2503
0
{
2504
0
    PyCodeObject *co, *cp;
2505
0
    int eq;
2506
0
    PyObject *consts1, *consts2;
2507
0
    PyObject *res;
2508
2509
0
    if ((op != Py_EQ && op != Py_NE) ||
2510
0
        !PyCode_Check(self) ||
2511
0
        !PyCode_Check(other)) {
2512
0
        Py_RETURN_NOTIMPLEMENTED;
2513
0
    }
2514
2515
0
    co = (PyCodeObject *)self;
2516
0
    cp = (PyCodeObject *)other;
2517
2518
0
    eq = PyObject_RichCompareBool(co->co_name, cp->co_name, Py_EQ);
2519
0
    if (eq <= 0) goto unequal;
2520
0
    eq = co->co_argcount == cp->co_argcount;
2521
0
    if (!eq) goto unequal;
2522
0
    eq = co->co_posonlyargcount == cp->co_posonlyargcount;
2523
0
    if (!eq) goto unequal;
2524
0
    eq = co->co_kwonlyargcount == cp->co_kwonlyargcount;
2525
0
    if (!eq) goto unequal;
2526
0
    eq = co->co_flags == cp->co_flags;
2527
0
    if (!eq) goto unequal;
2528
0
    eq = co->co_firstlineno == cp->co_firstlineno;
2529
0
    if (!eq) goto unequal;
2530
0
    eq = Py_SIZE(co) == Py_SIZE(cp);
2531
0
    if (!eq) {
2532
0
        goto unequal;
2533
0
    }
2534
0
    for (int i = 0; i < Py_SIZE(co); i++) {
2535
0
        _Py_CODEUNIT co_instr = _Py_GetBaseCodeUnit(co, i);
2536
0
        _Py_CODEUNIT cp_instr = _Py_GetBaseCodeUnit(cp, i);
2537
0
        if (co_instr.cache != cp_instr.cache) {
2538
0
            goto unequal;
2539
0
        }
2540
0
        i += _PyOpcode_Caches[co_instr.op.code];
2541
0
    }
2542
2543
    /* compare constants */
2544
0
    consts1 = _PyCode_ConstantKey(co->co_consts);
2545
0
    if (!consts1)
2546
0
        return NULL;
2547
0
    consts2 = _PyCode_ConstantKey(cp->co_consts);
2548
0
    if (!consts2) {
2549
0
        Py_DECREF(consts1);
2550
0
        return NULL;
2551
0
    }
2552
0
    eq = PyObject_RichCompareBool(consts1, consts2, Py_EQ);
2553
0
    Py_DECREF(consts1);
2554
0
    Py_DECREF(consts2);
2555
0
    if (eq <= 0) goto unequal;
2556
2557
0
    eq = PyObject_RichCompareBool(co->co_names, cp->co_names, Py_EQ);
2558
0
    if (eq <= 0) goto unequal;
2559
0
    eq = PyObject_RichCompareBool(co->co_localsplusnames,
2560
0
                                  cp->co_localsplusnames, Py_EQ);
2561
0
    if (eq <= 0) goto unequal;
2562
0
    eq = PyObject_RichCompareBool(co->co_linetable, cp->co_linetable, Py_EQ);
2563
0
    if (eq <= 0) {
2564
0
        goto unequal;
2565
0
    }
2566
0
    eq = PyObject_RichCompareBool(co->co_exceptiontable,
2567
0
                                  cp->co_exceptiontable, Py_EQ);
2568
0
    if (eq <= 0) {
2569
0
        goto unequal;
2570
0
    }
2571
2572
0
    if (op == Py_EQ)
2573
0
        res = Py_True;
2574
0
    else
2575
0
        res = Py_False;
2576
0
    goto done;
2577
2578
0
  unequal:
2579
0
    if (eq < 0)
2580
0
        return NULL;
2581
0
    if (op == Py_NE)
2582
0
        res = Py_True;
2583
0
    else
2584
0
        res = Py_False;
2585
2586
0
  done:
2587
0
    return Py_NewRef(res);
2588
0
}
2589
2590
static Py_hash_t
2591
code_hash(PyObject *self)
2592
50
{
2593
50
    PyCodeObject *co = _PyCodeObject_CAST(self);
2594
0
    Py_uhash_t uhash = 20221211;
2595
1.37k
    #define SCRAMBLE_IN(H) do {       \
2596
1.37k
        uhash ^= (Py_uhash_t)(H);     \
2597
1.37k
        uhash *= PyHASH_MULTIPLIER;  \
2598
1.37k
    } while (0)
2599
300
    #define SCRAMBLE_IN_HASH(EXPR) do {     \
2600
300
        Py_hash_t h = PyObject_Hash(EXPR);  \
2601
300
        if (h == -1) {                      \
2602
0
            return -1;                      \
2603
0
        }                                   \
2604
300
        SCRAMBLE_IN(h);                     \
2605
300
    } while (0)
2606
2607
50
    SCRAMBLE_IN_HASH(co->co_name);
2608
50
    SCRAMBLE_IN_HASH(co->co_consts);
2609
50
    SCRAMBLE_IN_HASH(co->co_names);
2610
50
    SCRAMBLE_IN_HASH(co->co_localsplusnames);
2611
50
    SCRAMBLE_IN_HASH(co->co_linetable);
2612
50
    SCRAMBLE_IN_HASH(co->co_exceptiontable);
2613
50
    SCRAMBLE_IN(co->co_argcount);
2614
50
    SCRAMBLE_IN(co->co_posonlyargcount);
2615
50
    SCRAMBLE_IN(co->co_kwonlyargcount);
2616
50
    SCRAMBLE_IN(co->co_flags);
2617
50
    SCRAMBLE_IN(co->co_firstlineno);
2618
50
    SCRAMBLE_IN(Py_SIZE(co));
2619
435
    for (int i = 0; i < Py_SIZE(co); i++) {
2620
385
        _Py_CODEUNIT co_instr = _Py_GetBaseCodeUnit(co, i);
2621
385
        SCRAMBLE_IN(co_instr.op.code);
2622
385
        SCRAMBLE_IN(co_instr.op.arg);
2623
385
        i += _PyOpcode_Caches[co_instr.op.code];
2624
385
    }
2625
50
    if ((Py_hash_t)uhash == -1) {
2626
0
        return -2;
2627
0
    }
2628
50
    return (Py_hash_t)uhash;
2629
50
}
2630
2631
2632
#define OFF(x) offsetof(PyCodeObject, x)
2633
2634
static PyMemberDef code_memberlist[] = {
2635
    {"co_argcount",        Py_T_INT,     OFF(co_argcount),        Py_READONLY},
2636
    {"co_posonlyargcount", Py_T_INT,     OFF(co_posonlyargcount), Py_READONLY},
2637
    {"co_kwonlyargcount",  Py_T_INT,     OFF(co_kwonlyargcount),  Py_READONLY},
2638
    {"co_stacksize",       Py_T_INT,     OFF(co_stacksize),       Py_READONLY},
2639
    {"co_flags",           Py_T_INT,     OFF(co_flags),           Py_READONLY},
2640
    {"co_nlocals",         Py_T_INT,     OFF(co_nlocals),         Py_READONLY},
2641
    {"co_consts",          _Py_T_OBJECT, OFF(co_consts),          Py_READONLY},
2642
    {"co_names",           _Py_T_OBJECT, OFF(co_names),           Py_READONLY},
2643
    {"co_filename",        _Py_T_OBJECT, OFF(co_filename),        Py_READONLY},
2644
    {"co_name",            _Py_T_OBJECT, OFF(co_name),            Py_READONLY},
2645
    {"co_qualname",        _Py_T_OBJECT, OFF(co_qualname),        Py_READONLY},
2646
    {"co_firstlineno",     Py_T_INT,     OFF(co_firstlineno),     Py_READONLY},
2647
    {"co_linetable",       _Py_T_OBJECT, OFF(co_linetable),       Py_READONLY},
2648
    {"co_exceptiontable",  _Py_T_OBJECT, OFF(co_exceptiontable),  Py_READONLY},
2649
    {NULL}      /* Sentinel */
2650
};
2651
2652
2653
static PyObject *
2654
code_getvarnames(PyObject *self, void *closure)
2655
0
{
2656
0
    PyCodeObject *code = _PyCodeObject_CAST(self);
2657
0
    return _PyCode_GetVarnames(code);
2658
0
}
2659
2660
static PyObject *
2661
code_getcellvars(PyObject *self, void *closure)
2662
0
{
2663
0
    PyCodeObject *code = _PyCodeObject_CAST(self);
2664
0
    return _PyCode_GetCellvars(code);
2665
0
}
2666
2667
static PyObject *
2668
code_getfreevars(PyObject *self, void *closure)
2669
0
{
2670
0
    PyCodeObject *code = _PyCodeObject_CAST(self);
2671
0
    return _PyCode_GetFreevars(code);
2672
0
}
2673
2674
static PyObject *
2675
code_getcodeadaptive(PyObject *self, void *closure)
2676
0
{
2677
0
    PyCodeObject *code = _PyCodeObject_CAST(self);
2678
0
    return PyBytes_FromStringAndSize(code->co_code_adaptive,
2679
0
                                     _PyCode_NBYTES(code));
2680
0
}
2681
2682
static PyObject *
2683
code_getcode(PyObject *self, void *closure)
2684
0
{
2685
0
    PyCodeObject *code = _PyCodeObject_CAST(self);
2686
0
    return _PyCode_GetCode(code);
2687
0
}
2688
2689
static PyGetSetDef code_getsetlist[] = {
2690
    {"_co_code_adaptive", code_getcodeadaptive, NULL, NULL},
2691
    // The following old names are kept for backward compatibility.
2692
    {"co_varnames",       code_getvarnames,     NULL, NULL},
2693
    {"co_cellvars",       code_getcellvars,     NULL, NULL},
2694
    {"co_freevars",       code_getfreevars,     NULL, NULL},
2695
    {"co_code",           code_getcode,         NULL, NULL},
2696
    {0}
2697
};
2698
2699
2700
static PyObject *
2701
code_sizeof(PyObject *self, PyObject *Py_UNUSED(args))
2702
0
{
2703
0
    PyCodeObject *co = _PyCodeObject_CAST(self);
2704
0
    size_t res = _PyObject_VAR_SIZE(Py_TYPE(co), Py_SIZE(co));
2705
0
    _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra*) co->co_extra;
2706
0
    if (co_extra != NULL) {
2707
0
        res += sizeof(_PyCodeObjectExtra);
2708
0
        res += ((size_t)co_extra->ce_size - 1) * sizeof(co_extra->ce_extras[0]);
2709
0
    }
2710
0
    return PyLong_FromSize_t(res);
2711
0
}
2712
2713
static PyObject *
2714
code_linesiterator(PyObject *self, PyObject *Py_UNUSED(args))
2715
0
{
2716
0
    PyCodeObject *code = _PyCodeObject_CAST(self);
2717
0
    return (PyObject *)new_linesiterator(code);
2718
0
}
2719
2720
static PyObject *
2721
code_branchesiterator(PyObject *self, PyObject *Py_UNUSED(args))
2722
0
{
2723
0
    PyCodeObject *code = _PyCodeObject_CAST(self);
2724
0
    return _PyInstrumentation_BranchesIterator(code);
2725
0
}
2726
2727
/*[clinic input]
2728
@permit_long_summary
2729
@text_signature "($self, /, **changes)"
2730
code.replace
2731
2732
    *
2733
    co_argcount: int(c_default="((PyCodeObject *)self)->co_argcount") = unchanged
2734
    co_posonlyargcount: int(c_default="((PyCodeObject *)self)->co_posonlyargcount") = unchanged
2735
    co_kwonlyargcount: int(c_default="((PyCodeObject *)self)->co_kwonlyargcount") = unchanged
2736
    co_nlocals: int(c_default="((PyCodeObject *)self)->co_nlocals") = unchanged
2737
    co_stacksize: int(c_default="((PyCodeObject *)self)->co_stacksize") = unchanged
2738
    co_flags: int(c_default="((PyCodeObject *)self)->co_flags") = unchanged
2739
    co_firstlineno: int(c_default="((PyCodeObject *)self)->co_firstlineno") = unchanged
2740
    co_code: object(subclass_of="&PyBytes_Type", c_default="NULL") = unchanged
2741
    co_consts: object(subclass_of="&PyTuple_Type", c_default="((PyCodeObject *)self)->co_consts") = unchanged
2742
    co_names: object(subclass_of="&PyTuple_Type", c_default="((PyCodeObject *)self)->co_names") = unchanged
2743
    co_varnames: object(subclass_of="&PyTuple_Type", c_default="NULL") = unchanged
2744
    co_freevars: object(subclass_of="&PyTuple_Type", c_default="NULL") = unchanged
2745
    co_cellvars: object(subclass_of="&PyTuple_Type", c_default="NULL") = unchanged
2746
    co_filename: unicode(c_default="((PyCodeObject *)self)->co_filename") = unchanged
2747
    co_name: unicode(c_default="((PyCodeObject *)self)->co_name") = unchanged
2748
    co_qualname: unicode(c_default="((PyCodeObject *)self)->co_qualname") = unchanged
2749
    co_linetable: object(subclass_of="&PyBytes_Type", c_default="((PyCodeObject *)self)->co_linetable") = unchanged
2750
    co_exceptiontable: object(subclass_of="&PyBytes_Type", c_default="((PyCodeObject *)self)->co_exceptiontable") = unchanged
2751
2752
Return a copy of the code object with new values for the specified fields.
2753
[clinic start generated code]*/
2754
2755
static PyObject *
2756
code_replace_impl(PyCodeObject *self, int co_argcount,
2757
                  int co_posonlyargcount, int co_kwonlyargcount,
2758
                  int co_nlocals, int co_stacksize, int co_flags,
2759
                  int co_firstlineno, PyObject *co_code, PyObject *co_consts,
2760
                  PyObject *co_names, PyObject *co_varnames,
2761
                  PyObject *co_freevars, PyObject *co_cellvars,
2762
                  PyObject *co_filename, PyObject *co_name,
2763
                  PyObject *co_qualname, PyObject *co_linetable,
2764
                  PyObject *co_exceptiontable)
2765
/*[clinic end generated code: output=e75c48a15def18b9 input=e944fdac8b456114]*/
2766
0
{
2767
0
#define CHECK_INT_ARG(ARG) \
2768
0
        if (ARG < 0) { \
2769
0
            PyErr_SetString(PyExc_ValueError, \
2770
0
                            #ARG " must be a positive integer"); \
2771
0
            return NULL; \
2772
0
        }
2773
2774
0
    CHECK_INT_ARG(co_argcount);
2775
0
    CHECK_INT_ARG(co_posonlyargcount);
2776
0
    CHECK_INT_ARG(co_kwonlyargcount);
2777
0
    CHECK_INT_ARG(co_nlocals);
2778
0
    CHECK_INT_ARG(co_stacksize);
2779
0
    CHECK_INT_ARG(co_flags);
2780
0
    CHECK_INT_ARG(co_firstlineno);
2781
2782
0
#undef CHECK_INT_ARG
2783
2784
0
    PyObject *code = NULL;
2785
0
    if (co_code == NULL) {
2786
0
        code = _PyCode_GetCode(self);
2787
0
        if (code == NULL) {
2788
0
            return NULL;
2789
0
        }
2790
0
        co_code = code;
2791
0
    }
2792
2793
0
    if (PySys_Audit("code.__new__", "OOOiiiiii",
2794
0
                    co_code, co_filename, co_name, co_argcount,
2795
0
                    co_posonlyargcount, co_kwonlyargcount, co_nlocals,
2796
0
                    co_stacksize, co_flags) < 0) {
2797
0
        Py_XDECREF(code);
2798
0
        return NULL;
2799
0
    }
2800
2801
0
    PyCodeObject *co = NULL;
2802
0
    PyObject *varnames = NULL;
2803
0
    PyObject *cellvars = NULL;
2804
0
    PyObject *freevars = NULL;
2805
0
    if (co_varnames == NULL) {
2806
0
        varnames = get_localsplus_names(self, CO_FAST_LOCAL, self->co_nlocals);
2807
0
        if (varnames == NULL) {
2808
0
            goto error;
2809
0
        }
2810
0
        co_varnames = varnames;
2811
0
    }
2812
0
    if (co_cellvars == NULL) {
2813
0
        cellvars = get_localsplus_names(self, CO_FAST_CELL, self->co_ncellvars);
2814
0
        if (cellvars == NULL) {
2815
0
            goto error;
2816
0
        }
2817
0
        co_cellvars = cellvars;
2818
0
    }
2819
0
    if (co_freevars == NULL) {
2820
0
        freevars = get_localsplus_names(self, CO_FAST_FREE, self->co_nfreevars);
2821
0
        if (freevars == NULL) {
2822
0
            goto error;
2823
0
        }
2824
0
        co_freevars = freevars;
2825
0
    }
2826
2827
0
    co = PyCode_NewWithPosOnlyArgs(
2828
0
        co_argcount, co_posonlyargcount, co_kwonlyargcount, co_nlocals,
2829
0
        co_stacksize, co_flags, co_code, co_consts, co_names,
2830
0
        co_varnames, co_freevars, co_cellvars, co_filename, co_name,
2831
0
        co_qualname, co_firstlineno,
2832
0
        co_linetable, co_exceptiontable);
2833
2834
0
error:
2835
0
    Py_XDECREF(code);
2836
0
    Py_XDECREF(varnames);
2837
0
    Py_XDECREF(cellvars);
2838
0
    Py_XDECREF(freevars);
2839
0
    return (PyObject *)co;
2840
0
}
2841
2842
/*[clinic input]
2843
code._varname_from_oparg
2844
2845
    oparg: int
2846
2847
(internal-only) Return the local variable name for the given oparg.
2848
2849
WARNING: this method is for internal use only and may change or go
2850
away.
2851
[clinic start generated code]*/
2852
2853
static PyObject *
2854
code__varname_from_oparg_impl(PyCodeObject *self, int oparg)
2855
/*[clinic end generated code: output=1fd1130413184206 input=6ba7d6df0d566463]*/
2856
0
{
2857
0
    PyObject *name = PyTuple_GetItem(self->co_localsplusnames, oparg);
2858
0
    if (name == NULL) {
2859
0
        return NULL;
2860
0
    }
2861
0
    return Py_NewRef(name);
2862
0
}
2863
2864
/* XXX code objects need to participate in GC? */
2865
2866
static struct PyMethodDef code_methods[] = {
2867
    {"__sizeof__", code_sizeof, METH_NOARGS},
2868
    {"co_lines", code_linesiterator, METH_NOARGS},
2869
    {"co_branches", code_branchesiterator, METH_NOARGS},
2870
    {"co_positions", code_positionsiterator, METH_NOARGS},
2871
    CODE_REPLACE_METHODDEF
2872
    CODE__VARNAME_FROM_OPARG_METHODDEF
2873
    {"__replace__", _PyCFunction_CAST(code_replace), METH_FASTCALL|METH_KEYWORDS,
2874
     PyDoc_STR("__replace__($self, /, **changes)\n--\n\nThe same as replace().")},
2875
    {NULL, NULL}                /* sentinel */
2876
};
2877
2878
2879
PyTypeObject PyCode_Type = {
2880
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
2881
    "code",
2882
    offsetof(PyCodeObject, co_code_adaptive),
2883
    sizeof(_Py_CODEUNIT),
2884
    code_dealloc,                       /* tp_dealloc */
2885
    0,                                  /* tp_vectorcall_offset */
2886
    0,                                  /* tp_getattr */
2887
    0,                                  /* tp_setattr */
2888
    0,                                  /* tp_as_async */
2889
    code_repr,                          /* tp_repr */
2890
    0,                                  /* tp_as_number */
2891
    0,                                  /* tp_as_sequence */
2892
    0,                                  /* tp_as_mapping */
2893
    code_hash,                          /* tp_hash */
2894
    0,                                  /* tp_call */
2895
    0,                                  /* tp_str */
2896
    PyObject_GenericGetAttr,            /* tp_getattro */
2897
    0,                                  /* tp_setattro */
2898
    0,                                  /* tp_as_buffer */
2899
#ifdef Py_GIL_DISABLED
2900
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
2901
#else
2902
    Py_TPFLAGS_DEFAULT,                 /* tp_flags */
2903
#endif
2904
    code_new__doc__,                    /* tp_doc */
2905
#ifdef Py_GIL_DISABLED
2906
    code_traverse,                      /* tp_traverse */
2907
#else
2908
    0,                                  /* tp_traverse */
2909
#endif
2910
    0,                                  /* tp_clear */
2911
    code_richcompare,                   /* tp_richcompare */
2912
    offsetof(PyCodeObject, co_weakreflist),     /* tp_weaklistoffset */
2913
    0,                                  /* tp_iter */
2914
    0,                                  /* tp_iternext */
2915
    code_methods,                       /* tp_methods */
2916
    code_memberlist,                    /* tp_members */
2917
    code_getsetlist,                    /* tp_getset */
2918
    0,                                  /* tp_base */
2919
    0,                                  /* tp_dict */
2920
    0,                                  /* tp_descr_get */
2921
    0,                                  /* tp_descr_set */
2922
    0,                                  /* tp_dictoffset */
2923
    0,                                  /* tp_init */
2924
    0,                                  /* tp_alloc */
2925
    code_new,                           /* tp_new */
2926
};
2927
2928
2929
/******************
2930
 * other API
2931
 ******************/
2932
2933
PyObject*
2934
_PyCode_ConstantKey(PyObject *op)
2935
209
{
2936
209
    PyObject *key;
2937
2938
    /* Py_None and Py_Ellipsis are singletons. */
2939
209
    if (op == Py_None || op == Py_Ellipsis
2940
209
       || PyLong_CheckExact(op)
2941
209
       || PyUnicode_CheckExact(op)
2942
          /* code_richcompare() uses _PyCode_ConstantKey() internally */
2943
140
       || PyCode_Check(op))
2944
89
    {
2945
        /* Objects of these types are always different from object of other
2946
         * type and from tuples. */
2947
89
        key = Py_NewRef(op);
2948
89
    }
2949
120
    else if (PyBool_Check(op) || PyBytes_CheckExact(op)) {
2950
        /* Make booleans different from integers 0 and 1.
2951
         * Avoid BytesWarning from comparing bytes with strings. */
2952
60
        key = _PyTuple_FromPair((PyObject *)Py_TYPE(op), op);
2953
60
    }
2954
60
    else if (PyFloat_CheckExact(op)) {
2955
0
        double d = PyFloat_AS_DOUBLE(op);
2956
        /* all we need is to make the tuple different in either the 0.0
2957
         * or -0.0 case from all others, just to avoid the "coercion".
2958
         */
2959
0
        if (d == 0.0 && copysign(1.0, d) < 0.0)
2960
0
            key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
2961
0
        else
2962
0
            key = _PyTuple_FromPair((PyObject *)Py_TYPE(op), op);
2963
0
    }
2964
60
    else if (PyComplex_CheckExact(op)) {
2965
0
        Py_complex z;
2966
0
        int real_negzero, imag_negzero;
2967
        /* For the complex case we must make complex(x, 0.)
2968
           different from complex(x, -0.) and complex(0., y)
2969
           different from complex(-0., y), for any x and y.
2970
           All four complex zeros must be distinguished.*/
2971
0
        z = PyComplex_AsCComplex(op);
2972
0
        real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
2973
0
        imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
2974
        /* use True, False and None singleton as tags for the real and imag
2975
         * sign, to make tuples different */
2976
0
        if (real_negzero && imag_negzero) {
2977
0
            key = PyTuple_Pack(3, Py_TYPE(op), op, Py_True);
2978
0
        }
2979
0
        else if (imag_negzero) {
2980
0
            key = PyTuple_Pack(3, Py_TYPE(op), op, Py_False);
2981
0
        }
2982
0
        else if (real_negzero) {
2983
0
            key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None);
2984
0
        }
2985
0
        else {
2986
0
            key = _PyTuple_FromPair((PyObject *)Py_TYPE(op), op);
2987
0
        }
2988
0
    }
2989
60
    else if (PyTuple_CheckExact(op)) {
2990
60
        Py_ssize_t i, len;
2991
60
        PyObject *tuple;
2992
2993
60
        len = PyTuple_GET_SIZE(op);
2994
60
        tuple = PyTuple_New(len);
2995
60
        if (tuple == NULL)
2996
0
            return NULL;
2997
2998
139
        for (i=0; i < len; i++) {
2999
79
            PyObject *item, *item_key;
3000
3001
79
            item = PyTuple_GET_ITEM(op, i);
3002
0
            item_key = _PyCode_ConstantKey(item);
3003
79
            if (item_key == NULL) {
3004
0
                Py_DECREF(tuple);
3005
0
                return NULL;
3006
0
            }
3007
3008
79
            PyTuple_SET_ITEM(tuple, i, item_key);
3009
79
        }
3010
3011
60
        key = _PyTuple_FromPair(tuple, op);
3012
60
        Py_DECREF(tuple);
3013
60
    }
3014
0
    else if (PyFrozenSet_CheckExact(op)) {
3015
0
        Py_ssize_t pos = 0;
3016
0
        PyObject *item;
3017
0
        Py_hash_t hash;
3018
0
        Py_ssize_t i, len;
3019
0
        PyObject *tuple, *set;
3020
3021
0
        len = PySet_GET_SIZE(op);
3022
0
        tuple = PyTuple_New(len);
3023
0
        if (tuple == NULL)
3024
0
            return NULL;
3025
3026
0
        i = 0;
3027
0
        while (_PySet_NextEntry(op, &pos, &item, &hash)) {
3028
0
            PyObject *item_key;
3029
3030
0
            item_key = _PyCode_ConstantKey(item);
3031
0
            if (item_key == NULL) {
3032
0
                Py_DECREF(tuple);
3033
0
                return NULL;
3034
0
            }
3035
3036
0
            assert(i < len);
3037
0
            PyTuple_SET_ITEM(tuple, i, item_key);
3038
0
            i++;
3039
0
        }
3040
0
        set = PyFrozenSet_New(tuple);
3041
0
        Py_DECREF(tuple);
3042
0
        if (set == NULL)
3043
0
            return NULL;
3044
3045
0
        key = _PyTuple_FromPair(set, op);
3046
0
        Py_DECREF(set);
3047
0
        return key;
3048
0
    }
3049
0
    else if (PySlice_Check(op)) {
3050
0
        PySliceObject *slice = (PySliceObject *)op;
3051
0
        PyObject *start_key = NULL;
3052
0
        PyObject *stop_key = NULL;
3053
0
        PyObject *step_key = NULL;
3054
0
        key = NULL;
3055
3056
0
        start_key = _PyCode_ConstantKey(slice->start);
3057
0
        if (start_key == NULL) {
3058
0
            goto slice_exit;
3059
0
        }
3060
3061
0
        stop_key = _PyCode_ConstantKey(slice->stop);
3062
0
        if (stop_key == NULL) {
3063
0
            goto slice_exit;
3064
0
        }
3065
3066
0
        step_key = _PyCode_ConstantKey(slice->step);
3067
0
        if (step_key == NULL) {
3068
0
            goto slice_exit;
3069
0
        }
3070
3071
0
        PyObject *slice_key = PySlice_New(start_key, stop_key, step_key);
3072
0
        if (slice_key == NULL) {
3073
0
            goto slice_exit;
3074
0
        }
3075
3076
0
        key = _PyTuple_FromPair(slice_key, op);
3077
0
        Py_DECREF(slice_key);
3078
0
    slice_exit:
3079
0
        Py_XDECREF(start_key);
3080
0
        Py_XDECREF(stop_key);
3081
0
        Py_XDECREF(step_key);
3082
0
    }
3083
0
    else {
3084
        /* for other types, use the object identifier as a unique identifier
3085
         * to ensure that they are seen as unequal. */
3086
0
        PyObject *obj_id = PyLong_FromVoidPtr(op);
3087
0
        if (obj_id == NULL)
3088
0
            return NULL;
3089
3090
0
        key = _PyTuple_FromPair(obj_id, op);
3091
0
        Py_DECREF(obj_id);
3092
0
    }
3093
209
    return key;
3094
209
}
3095
3096
#ifdef Py_GIL_DISABLED
3097
static PyObject *
3098
intern_one_constant(PyObject *op)
3099
{
3100
    PyInterpreterState *interp = _PyInterpreterState_GET();
3101
    _Py_hashtable_t *consts = interp->code_state.constants;
3102
3103
    assert(!PyUnicode_CheckExact(op));  // strings are interned separately
3104
3105
    _Py_hashtable_entry_t *entry = _Py_hashtable_get_entry(consts, op);
3106
    if (entry == NULL) {
3107
        if (_Py_hashtable_set(consts, op, op) != 0) {
3108
            PyErr_NoMemory();
3109
            return NULL;
3110
        }
3111
3112
#ifdef Py_REF_DEBUG
3113
        Py_ssize_t refcnt = Py_REFCNT(op);
3114
        if (refcnt != 1) {
3115
            // Adjust the reftotal to account for the fact that we only
3116
            // restore a single reference in _PyCode_Fini.
3117
            _Py_AddRefTotal(_PyThreadState_GET(), -(refcnt - 1));
3118
        }
3119
#endif
3120
3121
        _Py_SetImmortal(op);
3122
        return op;
3123
    }
3124
3125
    assert(_Py_IsImmortal(entry->value));
3126
    return (PyObject *)entry->value;
3127
}
3128
3129
static int
3130
compare_constants(const void *key1, const void *key2)
3131
{
3132
    PyObject *op1 = (PyObject *)key1;
3133
    PyObject *op2 = (PyObject *)key2;
3134
    if (op1 == op2) {
3135
        return 1;
3136
    }
3137
    if (Py_TYPE(op1) != Py_TYPE(op2)) {
3138
        return 0;
3139
    }
3140
    // We compare container contents by identity because we have already
3141
    // internalized the items.
3142
    if (PyTuple_CheckExact(op1)) {
3143
        Py_ssize_t size = PyTuple_GET_SIZE(op1);
3144
        if (size != PyTuple_GET_SIZE(op2)) {
3145
            return 0;
3146
        }
3147
        for (Py_ssize_t i = 0; i < size; i++) {
3148
            if (PyTuple_GET_ITEM(op1, i) != PyTuple_GET_ITEM(op2, i)) {
3149
                return 0;
3150
            }
3151
        }
3152
        return 1;
3153
    }
3154
    else if (PyFrozenSet_CheckExact(op1)) {
3155
        if (PySet_GET_SIZE(op1) != PySet_GET_SIZE(op2)) {
3156
            return 0;
3157
        }
3158
        Py_ssize_t pos1 = 0, pos2 = 0;
3159
        PyObject *obj1, *obj2;
3160
        Py_hash_t hash1, hash2;
3161
        while ((_PySet_NextEntry(op1, &pos1, &obj1, &hash1)) &&
3162
               (_PySet_NextEntry(op2, &pos2, &obj2, &hash2)))
3163
        {
3164
            if (obj1 != obj2) {
3165
                return 0;
3166
            }
3167
        }
3168
        return 1;
3169
    }
3170
    else if (PySlice_Check(op1)) {
3171
        PySliceObject *s1 = (PySliceObject *)op1;
3172
        PySliceObject *s2 = (PySliceObject *)op2;
3173
        return (s1->start == s2->start &&
3174
                s1->stop  == s2->stop  &&
3175
                s1->step  == s2->step);
3176
    }
3177
    else if (PyBytes_CheckExact(op1) || PyLong_CheckExact(op1)) {
3178
        return PyObject_RichCompareBool(op1, op2, Py_EQ);
3179
    }
3180
    else if (PyFloat_CheckExact(op1)) {
3181
        // Ensure that, for example, +0.0 and -0.0 are distinct
3182
        double f1 = PyFloat_AS_DOUBLE(op1);
3183
        double f2 = PyFloat_AS_DOUBLE(op2);
3184
        return memcmp(&f1, &f2, sizeof(double)) == 0;
3185
    }
3186
    else if (PyComplex_CheckExact(op1)) {
3187
        Py_complex c1 = ((PyComplexObject *)op1)->cval;
3188
        Py_complex c2 = ((PyComplexObject *)op2)->cval;
3189
        return memcmp(&c1, &c2, sizeof(Py_complex)) == 0;
3190
    }
3191
    // gh-130851: Treat instances of unexpected types as distinct if they are
3192
    // not the same object.
3193
    return 0;
3194
}
3195
3196
static Py_uhash_t
3197
hash_const(const void *key)
3198
{
3199
    PyObject *op = (PyObject *)key;
3200
    if (PySlice_Check(op)) {
3201
        PySliceObject *s = (PySliceObject *)op;
3202
        PyObject *data[3] = { s->start, s->stop, s->step };
3203
        return Py_HashBuffer(&data, sizeof(data));
3204
    }
3205
    else if (PyTuple_CheckExact(op)) {
3206
        Py_ssize_t size = PyTuple_GET_SIZE(op);
3207
        PyObject **data = _PyTuple_ITEMS(op);
3208
        return Py_HashBuffer(data, sizeof(PyObject *) * size);
3209
    }
3210
    Py_hash_t h = PyObject_Hash(op);
3211
    if (h == -1) {
3212
        // gh-130851: Other than slice objects, every constant that the
3213
        // bytecode compiler generates is hashable. However, users can
3214
        // provide their own constants, when constructing code objects via
3215
        // types.CodeType(). If the user-provided constant is unhashable, we
3216
        // use the memory address of the object as a fallback hash value.
3217
        PyErr_Clear();
3218
        return (Py_uhash_t)(uintptr_t)key;
3219
    }
3220
    return (Py_uhash_t)h;
3221
}
3222
3223
static int
3224
clear_containers(_Py_hashtable_t *ht, const void *key, const void *value,
3225
                 void *user_data)
3226
{
3227
    // First clear containers to avoid recursive deallocation later on in
3228
    // destroy_key.
3229
    PyObject *op = (PyObject *)key;
3230
    if (PyTuple_CheckExact(op)) {
3231
        for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(op); i++) {
3232
            Py_CLEAR(_PyTuple_ITEMS(op)[i]);
3233
        }
3234
    }
3235
    else if (PySlice_Check(op)) {
3236
        PySliceObject *slice = (PySliceObject *)op;
3237
        Py_SETREF(slice->start, Py_None);
3238
        Py_SETREF(slice->stop, Py_None);
3239
        Py_SETREF(slice->step, Py_None);
3240
    }
3241
    else if (PyFrozenSet_CheckExact(op)) {
3242
        _PySet_ClearInternal((PySetObject *)op);
3243
    }
3244
    return 0;
3245
}
3246
3247
static void
3248
destroy_key(void *key)
3249
{
3250
    _Py_ClearImmortal(key);
3251
}
3252
#endif
3253
3254
PyStatus
3255
_PyCode_Init(PyInterpreterState *interp)
3256
20
{
3257
#ifdef Py_GIL_DISABLED
3258
    struct _py_code_state *state = &interp->code_state;
3259
    state->constants = _Py_hashtable_new_full(&hash_const, &compare_constants,
3260
                                              &destroy_key, NULL, NULL);
3261
    if (state->constants == NULL) {
3262
        return _PyStatus_NO_MEMORY();
3263
    }
3264
#endif
3265
20
    return _PyStatus_OK();
3266
20
}
3267
3268
void
3269
_PyCode_Fini(PyInterpreterState *interp)
3270
0
{
3271
#ifdef Py_GIL_DISABLED
3272
    // Free interned constants
3273
    struct _py_code_state *state = &interp->code_state;
3274
    if (state->constants) {
3275
        _Py_hashtable_foreach(state->constants, &clear_containers, NULL);
3276
        _Py_hashtable_destroy(state->constants);
3277
        state->constants = NULL;
3278
    }
3279
    _PyIndexPool_Fini(&interp->tlbc_indices);
3280
#endif
3281
0
}
3282
3283
#ifdef Py_GIL_DISABLED
3284
3285
// Thread-local bytecode (TLBC)
3286
//
3287
// Each thread specializes a thread-local copy of the bytecode, created on the
3288
// first RESUME, in free-threaded builds. All copies of the bytecode for a code
3289
// object are stored in the `co_tlbc` array. Threads reserve a globally unique
3290
// index identifying its copy of the bytecode in all `co_tlbc` arrays at thread
3291
// creation and release the index at thread destruction. The first entry in
3292
// every `co_tlbc` array always points to the "main" copy of the bytecode that
3293
// is stored at the end of the code object. This ensures that no bytecode is
3294
// copied for programs that do not use threads.
3295
//
3296
// Thread-local bytecode can be disabled at runtime by providing either `-X
3297
// tlbc=0` or `PYTHON_TLBC=0`. Disabling thread-local bytecode also disables
3298
// specialization. All threads share the main copy of the bytecode when
3299
// thread-local bytecode is disabled.
3300
//
3301
// Concurrent modifications to the bytecode made by the specializing
3302
// interpreter and instrumentation use atomics, with specialization taking care
3303
// not to overwrite an instruction that was instrumented concurrently.
3304
3305
int32_t
3306
_Py_ReserveTLBCIndex(PyInterpreterState *interp)
3307
{
3308
    if (interp->config.tlbc_enabled) {
3309
        return _PyIndexPool_AllocIndex(&interp->tlbc_indices);
3310
    }
3311
    // All threads share the main copy of the bytecode when TLBC is disabled
3312
    return 0;
3313
}
3314
3315
void
3316
_Py_ClearTLBCIndex(_PyThreadStateImpl *tstate)
3317
{
3318
    PyInterpreterState *interp = ((PyThreadState *)tstate)->interp;
3319
    if (interp->config.tlbc_enabled) {
3320
        _PyIndexPool_FreeIndex(&interp->tlbc_indices, tstate->tlbc_index);
3321
    }
3322
}
3323
3324
static _PyCodeArray *
3325
_PyCodeArray_New(Py_ssize_t size)
3326
{
3327
    _PyCodeArray *arr = PyMem_Calloc(
3328
        1, offsetof(_PyCodeArray, entries) + sizeof(void *) * size);
3329
    if (arr == NULL) {
3330
        PyErr_NoMemory();
3331
        return NULL;
3332
    }
3333
    arr->size = size;
3334
    return arr;
3335
}
3336
3337
// Get the underlying code unit, leaving instrumentation
3338
static _Py_CODEUNIT
3339
deopt_code_unit(PyCodeObject *code, int i)
3340
{
3341
    _Py_CODEUNIT *src_instr = _PyCode_CODE(code) + i;
3342
    _Py_CODEUNIT inst = {
3343
        .cache = FT_ATOMIC_LOAD_UINT16_RELAXED(*(uint16_t *)src_instr)};
3344
    int opcode = inst.op.code;
3345
    if (opcode < MIN_INSTRUMENTED_OPCODE) {
3346
        inst.op.code = _PyOpcode_Deopt[opcode];
3347
        assert(inst.op.code < MIN_SPECIALIZED_OPCODE);
3348
    }
3349
    // JIT should not be enabled with free-threading
3350
    assert(inst.op.code != ENTER_EXECUTOR);
3351
    return inst;
3352
}
3353
3354
static void
3355
copy_code(PyInterpreterState *interp, _Py_CODEUNIT *dst, PyCodeObject *co)
3356
{
3357
    int code_len = (int) Py_SIZE(co);
3358
    for (int i = 0; i < code_len; i += _PyInstruction_GetLength(co, i)) {
3359
        dst[i] = deopt_code_unit(co, i);
3360
    }
3361
    _PyCode_Quicken(dst, code_len, interp->opt_config.specialization_enabled, co->co_flags);
3362
}
3363
3364
static Py_ssize_t
3365
get_pow2_greater(Py_ssize_t initial, Py_ssize_t limit)
3366
{
3367
    // initial must be a power of two
3368
    assert(!(initial & (initial - 1)));
3369
    Py_ssize_t res = initial;
3370
    while (res && res < limit) {
3371
        res <<= 1;
3372
    }
3373
    return res;
3374
}
3375
3376
static _Py_CODEUNIT *
3377
create_tlbc_lock_held(PyInterpreterState *interp, PyCodeObject *co, Py_ssize_t idx)
3378
{
3379
    _PyCodeArray *tlbc = co->co_tlbc;
3380
    if (idx >= tlbc->size) {
3381
        Py_ssize_t new_size = get_pow2_greater(tlbc->size, idx + 1);
3382
        if (!new_size) {
3383
            PyErr_NoMemory();
3384
            return NULL;
3385
        }
3386
        _PyCodeArray *new_tlbc = _PyCodeArray_New(new_size);
3387
        if (new_tlbc == NULL) {
3388
            return NULL;
3389
        }
3390
        memcpy(new_tlbc->entries, tlbc->entries, tlbc->size * sizeof(void *));
3391
        _Py_atomic_store_ptr_release(&co->co_tlbc, new_tlbc);
3392
        _PyMem_FreeDelayed(tlbc, tlbc->size * sizeof(void *));
3393
        tlbc = new_tlbc;
3394
    }
3395
    char *bc = PyMem_Calloc(1, _PyCode_NBYTES(co));
3396
    if (bc == NULL) {
3397
        PyErr_NoMemory();
3398
        return NULL;
3399
    }
3400
    copy_code(interp, (_Py_CODEUNIT *) bc, co);
3401
    assert(tlbc->entries[idx] == NULL);
3402
    tlbc->entries[idx] = bc;
3403
    return (_Py_CODEUNIT *) bc;
3404
}
3405
3406
static _Py_CODEUNIT *
3407
get_tlbc_lock_held(PyCodeObject *co)
3408
{
3409
    _PyCodeArray *tlbc = co->co_tlbc;
3410
    _PyThreadStateImpl *tstate = (_PyThreadStateImpl *)PyThreadState_GET();
3411
    int32_t idx = tstate->tlbc_index;
3412
    if (idx < tlbc->size && tlbc->entries[idx] != NULL) {
3413
        return (_Py_CODEUNIT *)tlbc->entries[idx];
3414
    }
3415
    PyInterpreterState *interp = tstate->base.interp;
3416
    return create_tlbc_lock_held(interp, co, idx);
3417
}
3418
3419
_Py_CODEUNIT *
3420
_PyCode_GetTLBC(PyCodeObject *co)
3421
{
3422
    _Py_CODEUNIT *result;
3423
    Py_BEGIN_CRITICAL_SECTION(co);
3424
    result = get_tlbc_lock_held(co);
3425
    Py_END_CRITICAL_SECTION();
3426
    return result;
3427
}
3428
3429
// My kingdom for a bitset
3430
struct flag_set {
3431
    uint8_t *flags;
3432
    Py_ssize_t size;
3433
};
3434
3435
static inline int
3436
flag_is_set(struct flag_set *flags, Py_ssize_t idx)
3437
{
3438
    assert(idx >= 0);
3439
    return (idx < flags->size) && flags->flags[idx];
3440
}
3441
3442
// Set the flag for each tlbc index in use
3443
static int
3444
get_indices_in_use(PyInterpreterState *interp, struct flag_set *in_use)
3445
{
3446
    assert(interp->stoptheworld.world_stopped);
3447
    assert(in_use->flags == NULL);
3448
    int32_t max_index = 0;
3449
    _Py_FOR_EACH_TSTATE_BEGIN(interp, p) {
3450
        int32_t idx = ((_PyThreadStateImpl *) p)->tlbc_index;
3451
        if (idx > max_index) {
3452
            max_index = idx;
3453
        }
3454
    }
3455
    _Py_FOR_EACH_TSTATE_END(interp);
3456
    in_use->size = (size_t) max_index + 1;
3457
    in_use->flags = PyMem_Calloc(in_use->size, sizeof(*in_use->flags));
3458
    if (in_use->flags == NULL) {
3459
        return -1;
3460
    }
3461
    _Py_FOR_EACH_TSTATE_BEGIN(interp, p) {
3462
        in_use->flags[((_PyThreadStateImpl *) p)->tlbc_index] = 1;
3463
    }
3464
    _Py_FOR_EACH_TSTATE_END(interp);
3465
    return 0;
3466
}
3467
3468
struct get_code_args {
3469
    _PyObjectStack code_objs;
3470
    struct flag_set indices_in_use;
3471
    int err;
3472
};
3473
3474
static void
3475
clear_get_code_args(struct get_code_args *args)
3476
{
3477
    if (args->indices_in_use.flags != NULL) {
3478
        PyMem_Free(args->indices_in_use.flags);
3479
        args->indices_in_use.flags = NULL;
3480
    }
3481
    _PyObjectStack_Clear(&args->code_objs);
3482
}
3483
3484
static inline int
3485
is_bytecode_unused(_PyCodeArray *tlbc, Py_ssize_t idx,
3486
                   struct flag_set *indices_in_use)
3487
{
3488
    assert(idx > 0 && idx < tlbc->size);
3489
    return tlbc->entries[idx] != NULL && !flag_is_set(indices_in_use, idx);
3490
}
3491
3492
static int
3493
get_code_with_unused_tlbc(PyObject *obj, void *data)
3494
{
3495
    struct get_code_args *args = (struct get_code_args *) data;
3496
    if (!PyCode_Check(obj)) {
3497
        return 1;
3498
    }
3499
    PyCodeObject *co = (PyCodeObject *) obj;
3500
    _PyCodeArray *tlbc = co->co_tlbc;
3501
    // The first index always points at the main copy of the bytecode embedded
3502
    // in the code object.
3503
    for (Py_ssize_t i = 1; i < tlbc->size; i++) {
3504
        if (is_bytecode_unused(tlbc, i, &args->indices_in_use)) {
3505
            if (_PyObjectStack_Push(&args->code_objs, obj) < 0) {
3506
                args->err = -1;
3507
                return 0;
3508
            }
3509
            return 1;
3510
        }
3511
    }
3512
    return 1;
3513
}
3514
3515
static void
3516
free_unused_bytecode(PyCodeObject *co, struct flag_set *indices_in_use)
3517
{
3518
    _PyCodeArray *tlbc = co->co_tlbc;
3519
    // The first index always points at the main copy of the bytecode embedded
3520
    // in the code object.
3521
    for (Py_ssize_t i = 1; i < tlbc->size; i++) {
3522
        if (is_bytecode_unused(tlbc, i, indices_in_use)) {
3523
            PyMem_Free(tlbc->entries[i]);
3524
            tlbc->entries[i] = NULL;
3525
        }
3526
    }
3527
}
3528
3529
int
3530
_Py_ClearUnusedTLBC(PyInterpreterState *interp)
3531
{
3532
    struct get_code_args args = {
3533
        .code_objs = {NULL},
3534
        .indices_in_use = {NULL, 0},
3535
        .err = 0,
3536
    };
3537
    _PyEval_StopTheWorld(interp);
3538
    // Collect in-use tlbc indices
3539
    if (get_indices_in_use(interp, &args.indices_in_use) < 0) {
3540
        goto err;
3541
    }
3542
    // Collect code objects that have bytecode not in use by any thread
3543
    _PyGC_VisitObjectsWorldStopped(
3544
        interp, get_code_with_unused_tlbc, &args);
3545
    if (args.err < 0) {
3546
        goto err;
3547
    }
3548
    // Free unused bytecode. This must happen outside of gc_visit_heaps; it is
3549
    // unsafe to allocate or free any mimalloc managed memory when it's
3550
    // running.
3551
    PyObject *obj;
3552
    while ((obj = _PyObjectStack_Pop(&args.code_objs)) != NULL) {
3553
        free_unused_bytecode((PyCodeObject*) obj, &args.indices_in_use);
3554
    }
3555
    _PyEval_StartTheWorld(interp);
3556
    clear_get_code_args(&args);
3557
    return 0;
3558
3559
err:
3560
    _PyEval_StartTheWorld(interp);
3561
    clear_get_code_args(&args);
3562
    PyErr_NoMemory();
3563
    return -1;
3564
}
3565
3566
#endif