Coverage Report

Created: 2025-10-10 06:33

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