Coverage Report

Created: 2026-11-30 07:19

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