Coverage Report

Created: 2026-10-17 06:15

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