Coverage Report

Created: 2026-12-01 06:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Objects/frameobject.c
Line
Count
Source
1
/* Frame object implementation */
2
3
#include "Python.h"
4
#include "pycore_cell.h"          // PyCell_GetRef()
5
#include "pycore_ceval.h"         // _PyEval_SetOpcodeTrace()
6
#include "pycore_code.h"          // CO_FAST_LOCAL
7
#include "pycore_dict.h"          // _PyDict_LoadBuiltinsFromGlobals()
8
#include "pycore_frame.h"         // PyFrameObject
9
#include "pycore_function.h"      // _PyFunction_FromConstructor()
10
#include "pycore_genobject.h"     // _PyGen_GetGeneratorFromFrame()
11
#include "pycore_interpframe.h"   // _PyFrame_GetLocalsArray()
12
#include "pycore_list.h"          // _PyList_AppendTakeRef()
13
#include "pycore_modsupport.h"    // _PyArg_CheckPositional()
14
#include "pycore_object.h"        // _PyObject_GC_UNTRACK()
15
#include "pycore_opcode_metadata.h" // _PyOpcode_Caches
16
#include "pycore_optimizer.h"     // _Py_Executors_InvalidateDependency()
17
#include "pycore_pystate.h"       // _PyEval_StopTheWorld()
18
#include "pycore_tstate.h"        // _PyThreadStateImpl
19
#include "pycore_tuple.h"         // _PyTuple_FromPair
20
#include "pycore_unicodeobject.h" // _PyUnicode_Equal()
21
#include "pycore_weakref.h"       // FT_CLEAR_WEAKREFS()
22
23
#include "frameobject.h"          // PyFrameLocalsProxyObject
24
#include "opcode.h"               // EXTENDED_ARG
25
26
#include "clinic/frameobject.c.h"
27
28
29
#define PyFrameObject_CAST(op)  \
30
56.4M
    (assert(PyObject_TypeCheck((op), &PyFrame_Type)), (PyFrameObject *)(op))
31
32
#define PyFrameLocalsProxyObject_CAST(op)                           \
33
145
    (                                                               \
34
145
        assert(PyObject_TypeCheck((op), &PyFrameLocalsProxy_Type)), \
35
145
        (PyFrameLocalsProxyObject *)(op)                            \
36
145
    )
37
38
#define OFF(x) offsetof(PyFrameObject, x)
39
40
/*[clinic input]
41
class frame "PyFrameObject *" "&PyFrame_Type"
42
[clinic start generated code]*/
43
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=2d1dbf2e06cf351f]*/
44
45
/*[clinic input]
46
class FrameLocalsProxy "PyFrameLocalsProxyObject *" "&PyFrameLocalsProxy_Type"
47
[clinic start generated code]*/
48
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=b877b1c7551e6925]*/
49
50
51
#ifdef Py_GIL_DISABLED
52
// Returns 1 if the frame may be executing or resumed on another thread.
53
static int
54
_frame_is_on_other_thread(PyFrameObject *frame)
55
{
56
    _PyInterpreterFrame *iframe = frame->f_frame;
57
    if (iframe->owner == FRAME_OWNED_BY_THREAD) {
58
        PyThreadState *tstate = _PyThreadState_GET();
59
        int32_t our_tlbc = ((_PyThreadStateImpl *)tstate)->tlbc_index;
60
        return iframe->tlbc_index != our_tlbc;
61
    }
62
    if (iframe->owner == FRAME_OWNED_BY_GENERATOR) {
63
        // Another thread may be running or resume the generator.
64
        return 1;
65
    }
66
    // FRAME_OWNED_BY_FRAME_OBJECT: the frame can no longer run.
67
    return 0;
68
}
69
#endif
70
71
// Evaluate CALL under the frame's critical section, or with the world
72
// stopped if the frame may be running on another thread.
73
#ifdef Py_GIL_DISABLED
74
#define FRAMELOCALSPROXY_LOCKED(FRAME, CALL, RESULT)               \
75
    do {                                                                 \
76
        int _stw;                                                        \
77
        Py_BEGIN_CRITICAL_SECTION(FRAME);                                \
78
        _stw = _frame_is_on_other_thread(FRAME);                         \
79
        if (!_stw) {                                                     \
80
            RESULT = CALL;                                               \
81
        }                                                                \
82
        Py_END_CRITICAL_SECTION();                                       \
83
        if (_stw) {                                                      \
84
            PyInterpreterState *interp = _PyInterpreterState_GET();      \
85
            _PyEval_StopTheWorld(interp);                                \
86
            RESULT = CALL;                                               \
87
            _PyEval_StartTheWorld(interp);                               \
88
        }                                                                \
89
    } while (0)
90
#else
91
#define FRAMELOCALSPROXY_LOCKED(FRAME, CALL, RESULT)               \
92
100
    do {                                                                 \
93
100
        RESULT = CALL;                                                   \
94
100
    } while (0)
95
#endif
96
97
98
// Returns a borrowed reference, the frame object keeps its code alive.
99
static PyCodeObject *
100
framelocalsproxy_getcode(PyFrameObject *frame)
101
92
{
102
92
    PyCodeObject *co;
103
92
    Py_BEGIN_CRITICAL_SECTION(frame);
104
92
    co = _PyFrame_GetCode(frame->f_frame);
105
92
    Py_END_CRITICAL_SECTION();
106
92
    return co;
107
92
}
108
109
// Returns a new reference to the extra locals dict or NULL. The running
110
// frame never touches it, so no stop the world is needed.
111
static PyObject *
112
framelocalsproxy_get_extra(PyFrameObject *frame, bool create)
113
0
{
114
0
    PyObject *extra;
115
0
    Py_BEGIN_CRITICAL_SECTION(frame);
116
0
    extra = frame->f_extra_locals;
117
0
    if (extra == NULL && create) {
118
0
        extra = frame->f_extra_locals = PyDict_New();
119
0
    }
120
0
    Py_XINCREF(extra);
121
0
    Py_END_CRITICAL_SECTION();
122
0
    return extra;
123
0
}
124
125
// Returns new reference or NULL
126
static PyObject *
127
framelocalsproxy_getval(_PyInterpreterFrame *frame, PyCodeObject *co, int i)
128
307
{
129
307
    _PyStackRef *fast = _PyFrame_GetLocalsArray(frame);
130
307
    _PyLocals_Kind kind = _PyLocals_GetKind(co->co_localspluskinds, i);
131
132
307
    PyObject *value = PyStackRef_AsPyObjectBorrow(fast[i]);
133
307
    PyObject *cell = NULL;
134
135
307
    if (value == NULL) {
136
123
        return NULL;
137
123
    }
138
139
184
    if (kind == CO_FAST_FREE || kind & CO_FAST_CELL) {
140
        // The cell was set when the frame was created from
141
        // the function's closure.
142
        // GH-128396: With PEP 709, it's possible to have a fast variable in
143
        // an inlined comprehension that has the same name as the cell variable
144
        // in the frame, where the `kind` obtained from frame can not guarantee
145
        // that the variable is a cell.
146
        // If the variable is not a cell, we are okay with it and we can simply
147
        // return the value.
148
0
        if (PyCell_Check(value)) {
149
0
            cell = value;
150
0
        }
151
0
    }
152
153
184
    if (cell != NULL) {
154
0
        value = PyCell_GetRef((PyCellObject *)cell);
155
0
    }
156
184
    else {
157
184
        Py_XINCREF(value);
158
184
    }
159
160
184
    if (value == NULL) {
161
0
        return NULL;
162
0
    }
163
164
184
    return value;
165
184
}
166
167
static bool
168
framelocalsproxy_hasval(_PyInterpreterFrame *frame, PyCodeObject *co, int i)
169
215
{
170
215
    PyObject *value = framelocalsproxy_getval(frame, co, i);
171
215
    if (value == NULL) {
172
123
        return false;
173
123
    }
174
92
    Py_DECREF(value);
175
92
    return true;
176
215
}
177
178
static int
179
framelocalsproxy_is_first_occurrence(PyObject *seen, PyObject *name)
180
92
{
181
92
    int found = PySet_Contains(seen, name);
182
92
    if (found < 0) {
183
0
        return -1;
184
0
    }
185
92
    if (found) {
186
0
        return 0;
187
0
    }
188
92
    if (PySet_Add(seen, name) < 0) {
189
0
        return -1;
190
0
    }
191
92
    return 1;
192
92
}
193
194
static int
195
framelocalsproxy_getkeyindex(PyFrameObject *frame, PyObject *key, bool read, PyObject **value_ptr)
196
92
{
197
    /*
198
     * Returns -2 (!) if an error occurred; exception will be set.
199
     * Returns the fast locals index of the key on success:
200
     *   - if read == true, returns the index if the value is not NULL
201
     *   - if read == false, returns the index if the value is not hidden
202
     * Otherwise returns -1.
203
     *
204
     * If read == true and value_ptr is not NULL, *value_ptr is set to
205
     * the value of the key if it is found (with a new reference).
206
     */
207
208
    // value_ptr should only be given if we are reading the value
209
92
    assert(read || value_ptr == NULL);
210
211
92
    PyCodeObject *co = framelocalsproxy_getcode(frame);
212
213
    // Ensure that the key is hashable.
214
92
    Py_hash_t key_hash = PyObject_Hash(key);
215
92
    if (key_hash == -1) {
216
0
        return -2;
217
0
    }
218
219
92
    bool found = false;
220
221
    // We do 2 loops here because it's highly possible the key is interned
222
    // and we can do a pointer comparison.
223
576
    for (int i = 0; i < co->co_nlocalsplus; i++) {
224
576
        PyObject *name = PyTuple_GET_ITEM(co->co_localsplusnames, i);
225
576
        if (name == key) {
226
92
            if (read) {
227
92
                PyObject *value;
228
92
                FRAMELOCALSPROXY_LOCKED(frame,
229
92
                    framelocalsproxy_getval(frame->f_frame, co, i), value);
230
92
                if (value != NULL) {
231
92
                    if (value_ptr != NULL) {
232
92
                        *value_ptr = value;
233
92
                    }
234
0
                    else {
235
0
                        Py_DECREF(value);
236
0
                    }
237
92
                    return i;
238
92
                }
239
92
            } else {
240
0
                if (!(_PyLocals_GetKind(co->co_localspluskinds, i) & CO_FAST_HIDDEN)) {
241
0
                    return i;
242
0
                }
243
0
            }
244
0
            found = true;
245
0
        }
246
576
    }
247
0
    if (found) {
248
        // This is an attempt to read an unset local variable or
249
        // write to a variable that is hidden from regular write operations
250
0
        return -1;
251
0
    }
252
    // This is unlikely, but we need to make sure. This means the key
253
    // is not interned.
254
0
    for (int i = 0; i < co->co_nlocalsplus; i++) {
255
0
        PyObject *name = PyTuple_GET_ITEM(co->co_localsplusnames, i);
256
0
        Py_hash_t name_hash = PyObject_Hash(name);
257
0
        assert(name_hash != -1);  // keys are exact unicode
258
0
        if (name_hash != key_hash) {
259
0
            continue;
260
0
        }
261
0
        int same = PyObject_RichCompareBool(name, key, Py_EQ);
262
0
        if (same < 0) {
263
0
            return -2;
264
0
        }
265
0
        if (same) {
266
0
            if (read) {
267
0
                PyObject *value;
268
0
                FRAMELOCALSPROXY_LOCKED(frame,
269
0
                    framelocalsproxy_getval(frame->f_frame, co, i), value);
270
0
                if (value != NULL) {
271
0
                    if (value_ptr != NULL) {
272
0
                        *value_ptr = value;
273
0
                    }
274
0
                    else {
275
0
                        Py_DECREF(value);
276
0
                    }
277
0
                    return i;
278
0
                }
279
0
            } else {
280
0
                if (!(_PyLocals_GetKind(co->co_localspluskinds, i) & CO_FAST_HIDDEN)) {
281
0
                    return i;
282
0
                }
283
0
            }
284
0
        }
285
0
    }
286
287
0
    return -1;
288
0
}
289
290
static PyObject *
291
framelocalsproxy_getitem(PyObject *self, PyObject *key)
292
92
{
293
92
    PyFrameObject *frame = PyFrameLocalsProxyObject_CAST(self)->frame;
294
92
    PyObject *value = NULL;
295
296
92
    int i = framelocalsproxy_getkeyindex(frame, key, true, &value);
297
92
    if (i == -2) {
298
0
        return NULL;
299
0
    }
300
92
    if (i >= 0) {
301
92
        assert(value != NULL);
302
92
        return value;
303
92
    }
304
92
    assert(value == NULL);
305
306
    // Okay not in the fast locals, try extra locals
307
308
0
    PyObject *extra = framelocalsproxy_get_extra(frame, false);
309
0
    if (extra != NULL) {
310
0
        int found = PyDict_GetItemRef(extra, key, &value);
311
0
        Py_DECREF(extra);
312
0
        if (found != 0) {
313
0
            return value;
314
0
        }
315
0
    }
316
317
0
    PyErr_Format(PyExc_KeyError, "local variable '%R' is not defined", key);
318
0
    return NULL;
319
0
}
320
321
static int
322
add_overwritten_fast_local(PyFrameObject *frame, PyObject *obj)
323
0
{
324
0
    Py_ssize_t new_size;
325
0
    if (frame->f_overwritten_fast_locals == NULL) {
326
0
        new_size = 1;
327
0
    }
328
0
    else {
329
0
        Py_ssize_t size = PyTuple_Size(frame->f_overwritten_fast_locals);
330
0
        if (size == -1) {
331
0
            return -1;
332
0
        }
333
0
        new_size = size + 1;
334
0
    }
335
0
    PyObject *new_tuple = PyTuple_New(new_size);
336
0
    if (new_tuple == NULL) {
337
0
        return -1;
338
0
    }
339
0
    for (Py_ssize_t i = 0; i < new_size - 1; i++) {
340
0
        PyObject *o = PyTuple_GET_ITEM(frame->f_overwritten_fast_locals, i);
341
0
        PyTuple_SET_ITEM(new_tuple, i, Py_NewRef(o));
342
0
    }
343
0
    PyTuple_SET_ITEM(new_tuple, new_size - 1, Py_NewRef(obj));
344
0
    Py_XSETREF(frame->f_overwritten_fast_locals, new_tuple);
345
0
    return 0;
346
0
}
347
348
// The replaced value is returned in `*old_value` so that it is decref'd
349
// outside stop the world.
350
static int
351
framelocalsproxy_setfast_lock_held(PyFrameObject *frame, int i,
352
                                   PyObject *value, PyObject **old_value)
353
0
{
354
    /* Merge locals into fast locals */
355
0
    _PyStackRef *fast = _PyFrame_GetLocalsArray(frame->f_frame);
356
0
    PyCodeObject *co = _PyFrame_GetCode(frame->f_frame);
357
358
#if _Py_TIER2
359
    _Py_Executors_InvalidateDependency(_PyInterpreterState_GET(), co, 1);
360
#endif
361
362
0
    _PyLocals_Kind kind = _PyLocals_GetKind(co->co_localspluskinds, i);
363
0
    _PyStackRef oldvalue = fast[i];
364
0
    PyObject *cell = NULL;
365
0
    if (kind == CO_FAST_FREE) {
366
        // The cell was set when the frame was created from
367
        // the function's closure, unless the frame has been cleared.
368
0
        assert(PyStackRef_IsNull(oldvalue) || PyCell_Check(PyStackRef_AsPyObjectBorrow(oldvalue)));
369
0
        cell = PyStackRef_AsPyObjectBorrow(oldvalue);
370
0
    } else if (kind & CO_FAST_CELL && !PyStackRef_IsNull(oldvalue)) {
371
0
        PyObject *as_obj = PyStackRef_AsPyObjectBorrow(oldvalue);
372
0
        if (PyCell_Check(as_obj)) {
373
0
            cell = as_obj;
374
0
        }
375
0
    }
376
0
    if (cell != NULL) {
377
0
        Py_XINCREF(value);
378
0
        *old_value = PyCell_SwapTakeRef((PyCellObject *)cell, value);
379
0
    } else if (value != PyStackRef_AsPyObjectBorrow(oldvalue)) {
380
0
        PyObject *old_obj = PyStackRef_AsPyObjectBorrow(fast[i]);
381
0
        if (old_obj != NULL && !_Py_IsImmortal(old_obj)) {
382
0
            if (add_overwritten_fast_local(frame, old_obj) < 0) {
383
0
                return -1;
384
0
            }
385
0
            PyStackRef_CLOSE(fast[i]);
386
0
        }
387
0
        fast[i] = PyStackRef_FromPyObjectNew(value);
388
0
    }
389
0
    return 0;
390
0
}
391
392
static int
393
framelocalsproxy_setitem(PyObject *self, PyObject *key, PyObject *value)
394
0
{
395
0
    PyFrameObject *frame = PyFrameLocalsProxyObject_CAST(self)->frame;
396
397
0
    int i = framelocalsproxy_getkeyindex(frame, key, false, NULL);
398
0
    if (i == -2) {
399
0
        return -1;
400
0
    }
401
0
    if (i >= 0) {
402
0
        if (value == NULL) {
403
0
            PyErr_SetString(PyExc_ValueError, "cannot remove local variables from FrameLocalsProxy");
404
0
            return -1;
405
0
        }
406
0
        PyObject *old_value = NULL;
407
0
        int result;
408
0
        FRAMELOCALSPROXY_LOCKED(frame,
409
0
            framelocalsproxy_setfast_lock_held(frame, i, value, &old_value),
410
0
            result);
411
0
        Py_XDECREF(old_value);
412
0
        return result;
413
0
    }
414
415
    // Okay not in the fast locals, try extra locals
416
417
0
    PyObject *extra = framelocalsproxy_get_extra(frame, value != NULL);
418
0
    if (extra == NULL) {
419
0
        if (value == NULL) {
420
0
            _PyErr_SetKeyError(key);
421
0
        }
422
0
        return -1;
423
0
    }
424
425
0
    int result;
426
0
    if (value == NULL) {
427
0
        result = PyDict_DelItem(extra, key);
428
0
    } else {
429
0
        result = PyDict_SetItem(extra, key, value);
430
0
    }
431
0
    Py_DECREF(extra);
432
0
    return result;
433
0
}
434
435
static int
436
framelocalsproxy_merge(PyObject* self, PyObject* other)
437
0
{
438
0
    if (!PyDict_Check(other) && !PyFrameLocalsProxy_Check(other)) {
439
0
        return -1;
440
0
    }
441
442
0
    PyObject *keys = PyMapping_Keys(other);
443
0
    if (keys == NULL) {
444
0
        return -1;
445
0
    }
446
447
0
    PyObject *iter = PyObject_GetIter(keys);
448
0
    Py_DECREF(keys);
449
0
    if (iter == NULL) {
450
0
        return -1;
451
0
    }
452
453
0
    PyObject *key = NULL;
454
0
    PyObject *value = NULL;
455
456
0
    while ((key = PyIter_Next(iter)) != NULL) {
457
0
        value = PyObject_GetItem(other, key);
458
0
        if (value == NULL) {
459
0
            Py_DECREF(key);
460
0
            Py_DECREF(iter);
461
0
            return -1;
462
0
        }
463
464
0
        if (framelocalsproxy_setitem(self, key, value) < 0) {
465
0
            Py_DECREF(key);
466
0
            Py_DECREF(value);
467
0
            Py_DECREF(iter);
468
0
            return -1;
469
0
        }
470
471
0
        Py_DECREF(key);
472
0
        Py_DECREF(value);
473
0
    }
474
475
0
    Py_DECREF(iter);
476
477
0
    if (PyErr_Occurred()) {
478
0
        return -1;
479
0
    }
480
481
0
    return 0;
482
0
}
483
484
static PyObject *
485
framelocalsproxy_keys_lock_held(PyFrameObject *frame)
486
8
{
487
8
    PyCodeObject *co = _PyFrame_GetCode(frame->f_frame);
488
8
    PyObject *names = PyList_New(0);
489
8
    if (names == NULL) {
490
0
        return NULL;
491
0
    }
492
    // An inlined comprehension cell can share a name with a free var.
493
8
    PyObject *seen = PySet_New(NULL);
494
8
    if (seen == NULL) {
495
0
        Py_DECREF(names);
496
0
        return NULL;
497
0
    }
498
499
152
    for (int i = 0; i < co->co_nlocalsplus; i++) {
500
144
        if (framelocalsproxy_hasval(frame->f_frame, co, i)) {
501
92
            PyObject *name = PyTuple_GET_ITEM(co->co_localsplusnames, i);
502
92
            int first = framelocalsproxy_is_first_occurrence(seen, name);
503
92
            if (first < 0) {
504
0
                goto error;
505
0
            }
506
92
            if (first) {
507
92
                if (PyList_Append(names, name) < 0) {
508
0
                    goto error;
509
0
                }
510
92
            }
511
92
        }
512
144
    }
513
8
    Py_DECREF(seen);
514
515
    // Iterate through the extra locals
516
8
    if (frame->f_extra_locals) {
517
0
        assert(PyDict_Check(frame->f_extra_locals));
518
519
0
        Py_ssize_t i = 0;
520
0
        PyObject *key = NULL;
521
0
        PyObject *value = NULL;
522
0
        int err = 0;
523
524
0
        Py_BEGIN_CRITICAL_SECTION(frame->f_extra_locals);
525
0
        while (PyDict_Next(frame->f_extra_locals, &i, &key, &value)) {
526
0
            if (PyList_Append(names, key) < 0) {
527
0
                err = -1;
528
0
                break;
529
0
            }
530
0
        }
531
0
        Py_END_CRITICAL_SECTION();
532
0
        if (err < 0) {
533
0
            Py_DECREF(names);
534
0
            return NULL;
535
0
        }
536
0
    }
537
538
8
    return names;
539
540
0
error:
541
0
    Py_DECREF(seen);
542
0
    Py_DECREF(names);
543
0
    return NULL;
544
8
}
545
546
static PyObject *
547
framelocalsproxy_keys(PyObject *self, PyObject *Py_UNUSED(ignored))
548
8
{
549
8
    PyFrameObject *frame = PyFrameLocalsProxyObject_CAST(self)->frame;
550
8
    PyObject *result;
551
8
    FRAMELOCALSPROXY_LOCKED(frame,
552
8
        framelocalsproxy_keys_lock_held(frame), result);
553
8
    return result;
554
8
}
555
556
static void
557
framelocalsproxy_dealloc(PyObject *self)
558
45
{
559
45
    PyFrameLocalsProxyObject *proxy = PyFrameLocalsProxyObject_CAST(self);
560
45
    PyObject_GC_UnTrack(self);
561
45
    Py_CLEAR(proxy->frame);
562
45
    Py_TYPE(self)->tp_free(self);
563
45
}
564
565
/*[clinic input]
566
@vectorcall
567
@classmethod
568
FrameLocalsProxy.__new__ as framelocalsproxy_new
569
    frame: object
570
    /
571
572
Create a write-through view of the locals dictionary for a frame.
573
574
  frame
575
    the frame object to wrap.
576
[clinic start generated code]*/
577
578
static PyObject *
579
framelocalsproxy_new_impl(PyTypeObject *type, PyObject *frame)
580
/*[clinic end generated code: output=803b377132a928b9 input=5ab4ffd26ec8e290]*/
581
45
{
582
45
    if (!PyFrame_Check(frame)) {
583
0
        PyErr_Format(PyExc_TypeError, "expect frame, not %T", frame);
584
0
        return NULL;
585
0
    }
586
45
    PyFrameLocalsProxyObject *self = (PyFrameLocalsProxyObject *)type->tp_alloc(type, 0);
587
45
    if (self == NULL) {
588
0
        return NULL;
589
0
    }
590
45
    self->frame = (PyFrameObject *)Py_NewRef(frame);
591
45
    return (PyObject *)self;
592
45
}
593
594
static int
595
framelocalsproxy_tp_clear(PyObject *self)
596
0
{
597
0
    PyFrameLocalsProxyObject *proxy = PyFrameLocalsProxyObject_CAST(self);
598
0
    Py_CLEAR(proxy->frame);
599
0
    return 0;
600
0
}
601
602
static int
603
framelocalsproxy_visit(PyObject *self, visitproc visit, void *arg)
604
0
{
605
0
    PyFrameLocalsProxyObject *proxy = PyFrameLocalsProxyObject_CAST(self);
606
0
    Py_VISIT(proxy->frame);
607
0
    return 0;
608
0
}
609
610
static PyObject *
611
framelocalsproxy_iter(PyObject *self)
612
0
{
613
0
    PyObject* keys = framelocalsproxy_keys(self, NULL);
614
0
    if (keys == NULL) {
615
0
        return NULL;
616
0
    }
617
618
0
    PyObject* iter = PyObject_GetIter(keys);
619
0
    Py_XDECREF(keys);
620
621
0
    return iter;
622
0
}
623
624
static PyObject *
625
framelocalsproxy_richcompare(PyObject *lhs, PyObject *rhs, int op)
626
0
{
627
0
    PyFrameLocalsProxyObject *self = PyFrameLocalsProxyObject_CAST(lhs);
628
0
    if (PyFrameLocalsProxy_Check(rhs)) {
629
0
        PyFrameLocalsProxyObject *other = (PyFrameLocalsProxyObject *)rhs;
630
0
        bool result = self->frame == other->frame;
631
0
        if (op == Py_EQ) {
632
0
            return PyBool_FromLong(result);
633
0
        } else if (op == Py_NE) {
634
0
            return PyBool_FromLong(!result);
635
0
        }
636
0
    } else if (PyDict_Check(rhs)) {
637
0
        PyObject *dct = PyDict_New();
638
0
        if (dct == NULL) {
639
0
            return NULL;
640
0
        }
641
642
0
        if (PyDict_Update(dct, lhs) < 0) {
643
0
            Py_DECREF(dct);
644
0
            return NULL;
645
0
        }
646
647
0
        PyObject *result = PyObject_RichCompare(dct, rhs, op);
648
0
        Py_DECREF(dct);
649
0
        return result;
650
0
    }
651
652
0
    Py_RETURN_NOTIMPLEMENTED;
653
0
}
654
655
static PyObject *
656
framelocalsproxy_repr(PyObject *self)
657
0
{
658
0
    int i = Py_ReprEnter(self);
659
0
    if (i != 0) {
660
0
        return i > 0 ? PyUnicode_FromString("{...}") : NULL;
661
0
    }
662
663
0
    PyObject *dct = PyDict_New();
664
0
    if (dct == NULL) {
665
0
        Py_ReprLeave(self);
666
0
        return NULL;
667
0
    }
668
669
0
    if (PyDict_Update(dct, self) < 0) {
670
0
        Py_DECREF(dct);
671
0
        Py_ReprLeave(self);
672
0
        return NULL;
673
0
    }
674
675
0
    PyObject *repr = PyObject_Repr(dct);
676
0
    Py_DECREF(dct);
677
678
0
    Py_ReprLeave(self);
679
680
0
    return repr;
681
0
}
682
683
static PyObject*
684
framelocalsproxy_or(PyObject *self, PyObject *other)
685
0
{
686
0
    if (!PyDict_Check(other) && !PyFrameLocalsProxy_Check(other)) {
687
0
        Py_RETURN_NOTIMPLEMENTED;
688
0
    }
689
690
0
    PyObject *result = PyDict_New();
691
0
    if (result == NULL) {
692
0
        return NULL;
693
0
    }
694
695
0
    if (PyDict_Update(result, self) < 0) {
696
0
        Py_DECREF(result);
697
0
        return NULL;
698
0
    }
699
700
0
    if (PyDict_Update(result, other) < 0) {
701
0
        Py_DECREF(result);
702
0
        return NULL;
703
0
    }
704
705
0
    return result;
706
0
}
707
708
static PyObject*
709
framelocalsproxy_inplace_or(PyObject *self, PyObject *other)
710
0
{
711
0
    if (!PyDict_Check(other) && !PyFrameLocalsProxy_Check(other)) {
712
0
        Py_RETURN_NOTIMPLEMENTED;
713
0
    }
714
715
0
    if (framelocalsproxy_merge(self, other) < 0) {
716
0
        Py_RETURN_NOTIMPLEMENTED;
717
0
    }
718
719
0
    return Py_NewRef(self);
720
0
}
721
722
static PyObject *
723
framelocalsproxy_values_lock_held(PyFrameObject *frame)
724
0
{
725
0
    PyCodeObject *co = _PyFrame_GetCode(frame->f_frame);
726
0
    PyObject *values = PyList_New(0);
727
0
    if (values == NULL) {
728
0
        return NULL;
729
0
    }
730
0
    PyObject *seen = PySet_New(NULL);
731
0
    if (seen == NULL) {
732
0
        Py_DECREF(values);
733
0
        return NULL;
734
0
    }
735
736
0
    for (int i = 0; i < co->co_nlocalsplus; i++) {
737
0
        PyObject *value = framelocalsproxy_getval(frame->f_frame, co, i);
738
0
        if (value) {
739
0
            PyObject *name = PyTuple_GET_ITEM(co->co_localsplusnames, i);
740
0
            int first = framelocalsproxy_is_first_occurrence(seen, name);
741
0
            if (first == 1) {
742
0
                if (PyList_Append(values, value) < 0) {
743
0
                    Py_DECREF(value);
744
0
                    goto error;
745
0
                }
746
0
            }
747
0
            Py_DECREF(value);
748
0
            if (first < 0) {
749
0
                goto error;
750
0
            }
751
0
        }
752
0
    }
753
0
    Py_DECREF(seen);
754
755
    // Iterate through the extra locals
756
0
    if (frame->f_extra_locals) {
757
0
        Py_ssize_t j = 0;
758
0
        PyObject *key = NULL;
759
0
        PyObject *value = NULL;
760
0
        int err = 0;
761
0
        Py_BEGIN_CRITICAL_SECTION(frame->f_extra_locals);
762
0
        while (PyDict_Next(frame->f_extra_locals, &j, &key, &value)) {
763
0
            if (PyList_Append(values, value) < 0) {
764
0
                err = -1;
765
0
                break;
766
0
            }
767
0
        }
768
0
        Py_END_CRITICAL_SECTION();
769
0
        if (err < 0) {
770
0
            Py_DECREF(values);
771
0
            return NULL;
772
0
        }
773
0
    }
774
775
0
    return values;
776
777
0
error:
778
0
    Py_DECREF(seen);
779
0
    Py_DECREF(values);
780
0
    return NULL;
781
0
}
782
783
static PyObject *
784
framelocalsproxy_values(PyObject *self, PyObject *Py_UNUSED(ignored))
785
0
{
786
0
    PyFrameObject *frame = PyFrameLocalsProxyObject_CAST(self)->frame;
787
0
    PyObject *result;
788
0
    FRAMELOCALSPROXY_LOCKED(frame,
789
0
        framelocalsproxy_values_lock_held(frame), result);
790
0
    return result;
791
0
}
792
793
static PyObject *
794
framelocalsproxy_items_lock_held(PyFrameObject *frame)
795
0
{
796
0
    PyCodeObject *co = _PyFrame_GetCode(frame->f_frame);
797
0
    PyObject *items = PyList_New(0);
798
0
    if (items == NULL) {
799
0
        return NULL;
800
0
    }
801
0
    PyObject *seen = PySet_New(NULL);
802
0
    if (seen == NULL) {
803
0
        Py_DECREF(items);
804
0
        return NULL;
805
0
    }
806
807
0
    for (int i = 0; i < co->co_nlocalsplus; i++) {
808
0
        PyObject *name = PyTuple_GET_ITEM(co->co_localsplusnames, i);
809
0
        PyObject *value = framelocalsproxy_getval(frame->f_frame, co, i);
810
811
0
        if (value) {
812
0
            int first = framelocalsproxy_is_first_occurrence(seen, name);
813
0
            if (first == 1) {
814
0
                PyObject *pair = _PyTuple_FromPairSteal(Py_NewRef(name), value);
815
0
                if (pair == NULL) {
816
0
                    goto error;
817
0
                }
818
0
                if (_PyList_AppendTakeRef((PyListObject *)items, pair) < 0) {
819
0
                    goto error;
820
0
                }
821
0
            }
822
0
            else {
823
0
                Py_DECREF(value);
824
0
                if (first < 0) {
825
0
                    goto error;
826
0
                }
827
0
            }
828
0
        }
829
0
    }
830
0
    Py_DECREF(seen);
831
0
    seen = NULL;
832
833
    // Iterate through the extra locals
834
0
    if (frame->f_extra_locals) {
835
0
        Py_ssize_t j = 0;
836
0
        PyObject *key = NULL;
837
0
        PyObject *value = NULL;
838
0
        int err = 0;
839
0
        Py_BEGIN_CRITICAL_SECTION(frame->f_extra_locals);
840
0
        while (PyDict_Next(frame->f_extra_locals, &j, &key, &value)) {
841
0
            PyObject *pair = _PyTuple_FromPair(key, value);
842
0
            if (pair == NULL
843
0
                || _PyList_AppendTakeRef((PyListObject *)items, pair) < 0)
844
0
            {
845
0
                err = -1;
846
0
                break;
847
0
            }
848
0
        }
849
0
        Py_END_CRITICAL_SECTION();
850
0
        if (err < 0) {
851
0
            goto error;
852
0
        }
853
0
    }
854
855
0
    return items;
856
857
0
error:
858
0
    Py_XDECREF(seen);
859
0
    Py_DECREF(items);
860
0
    return NULL;
861
0
}
862
863
static PyObject *
864
framelocalsproxy_items(PyObject *self, PyObject *Py_UNUSED(ignored))
865
0
{
866
0
    PyFrameObject *frame = PyFrameLocalsProxyObject_CAST(self)->frame;
867
0
    PyObject *result;
868
0
    FRAMELOCALSPROXY_LOCKED(frame,
869
0
        framelocalsproxy_items_lock_held(frame), result);
870
0
    return result;
871
0
}
872
873
static Py_ssize_t
874
framelocalsproxy_length_lock_held(PyFrameObject *frame)
875
0
{
876
0
    PyCodeObject *co = _PyFrame_GetCode(frame->f_frame);
877
0
    Py_ssize_t size = 0;
878
879
0
    if (frame->f_extra_locals != NULL) {
880
0
        assert(PyDict_Check(frame->f_extra_locals));
881
0
        size += PyDict_Size(frame->f_extra_locals);
882
0
    }
883
884
0
    PyObject *seen = PySet_New(NULL);
885
0
    if (seen == NULL) {
886
0
        return -1;
887
0
    }
888
0
    for (int i = 0; i < co->co_nlocalsplus; i++) {
889
0
        if (framelocalsproxy_hasval(frame->f_frame, co, i)) {
890
0
            PyObject *name = PyTuple_GET_ITEM(co->co_localsplusnames, i);
891
0
            int first = framelocalsproxy_is_first_occurrence(seen, name);
892
0
            if (first < 0) {
893
0
                Py_DECREF(seen);
894
0
                return -1;
895
0
            }
896
0
            else if (first) {
897
0
                size++;
898
0
            }
899
0
        }
900
0
    }
901
0
    Py_DECREF(seen);
902
0
    return size;
903
0
}
904
905
static Py_ssize_t
906
framelocalsproxy_length(PyObject *self)
907
0
{
908
0
    PyFrameObject *frame = PyFrameLocalsProxyObject_CAST(self)->frame;
909
0
    Py_ssize_t result;
910
0
    FRAMELOCALSPROXY_LOCKED(frame,
911
0
        framelocalsproxy_length_lock_held(frame), result);
912
0
    return result;
913
0
}
914
915
static int
916
framelocalsproxy_contains(PyObject *self, PyObject *key)
917
0
{
918
0
    PyFrameObject *frame = PyFrameLocalsProxyObject_CAST(self)->frame;
919
920
0
    int i = framelocalsproxy_getkeyindex(frame, key, true, NULL);
921
0
    if (i == -2) {
922
0
        return -1;
923
0
    }
924
0
    if (i >= 0) {
925
0
        return 1;
926
0
    }
927
928
0
    PyObject *extra = framelocalsproxy_get_extra(frame, false);
929
0
    if (extra != NULL) {
930
0
        int result = PyDict_Contains(extra, key);
931
0
        Py_DECREF(extra);
932
0
        return result;
933
0
    }
934
935
0
    return 0;
936
0
}
937
938
static PyObject* framelocalsproxy___contains__(PyObject *self, PyObject *key)
939
0
{
940
0
    int result = framelocalsproxy_contains(self, key);
941
0
    if (result < 0) {
942
0
        return NULL;
943
0
    }
944
0
    return PyBool_FromLong(result);
945
0
}
946
947
static PyObject*
948
framelocalsproxy_update(PyObject *self, PyObject *other)
949
0
{
950
0
    if (framelocalsproxy_merge(self, other) < 0) {
951
0
        PyErr_SetString(PyExc_TypeError, "update() argument must be dict or another FrameLocalsProxy");
952
0
        return NULL;
953
0
    }
954
955
0
    Py_RETURN_NONE;
956
0
}
957
958
static PyObject*
959
framelocalsproxy_get(PyObject* self, PyObject *const *args, Py_ssize_t nargs)
960
0
{
961
0
    if (nargs < 1 || nargs > 2) {
962
0
        PyErr_SetString(PyExc_TypeError, "get expected 1 or 2 arguments");
963
0
        return NULL;
964
0
    }
965
966
0
    PyObject *key = args[0];
967
0
    PyObject *default_value = Py_None;
968
969
0
    if (nargs == 2) {
970
0
        default_value = args[1];
971
0
    }
972
973
0
    PyObject *result = framelocalsproxy_getitem(self, key);
974
975
0
    if (result == NULL) {
976
0
        if (PyErr_ExceptionMatches(PyExc_KeyError)) {
977
0
            PyErr_Clear();
978
0
            return Py_XNewRef(default_value);
979
0
        }
980
0
        return NULL;
981
0
    }
982
983
0
    return result;
984
0
}
985
986
static PyObject*
987
framelocalsproxy_setdefault(PyObject* self, PyObject *const *args, Py_ssize_t nargs)
988
0
{
989
0
    if (nargs < 1 || nargs > 2) {
990
0
        PyErr_SetString(PyExc_TypeError, "setdefault expected 1 or 2 arguments");
991
0
        return NULL;
992
0
    }
993
994
0
    PyObject *key = args[0];
995
0
    PyObject *default_value = Py_None;
996
997
0
    if (nargs == 2) {
998
0
        default_value = args[1];
999
0
    }
1000
1001
0
    PyObject *result = framelocalsproxy_getitem(self, key);
1002
1003
0
    if (result == NULL) {
1004
0
        if (PyErr_ExceptionMatches(PyExc_KeyError)) {
1005
0
            PyErr_Clear();
1006
0
            if (framelocalsproxy_setitem(self, key, default_value) < 0) {
1007
0
                return NULL;
1008
0
            }
1009
0
            return Py_XNewRef(default_value);
1010
0
        }
1011
0
        return NULL;
1012
0
    }
1013
1014
0
    return result;
1015
0
}
1016
1017
static PyObject*
1018
framelocalsproxy_pop(PyObject* self, PyObject *const *args, Py_ssize_t nargs)
1019
0
{
1020
0
    if (!_PyArg_CheckPositional("pop", nargs, 1, 2)) {
1021
0
        return NULL;
1022
0
    }
1023
1024
0
    PyObject *key = args[0];
1025
0
    PyObject *default_value = NULL;
1026
1027
0
    if (nargs == 2) {
1028
0
        default_value = args[1];
1029
0
    }
1030
1031
0
    PyFrameObject *frame = PyFrameLocalsProxyObject_CAST(self)->frame;
1032
1033
0
    int i = framelocalsproxy_getkeyindex(frame, key, false, NULL);
1034
0
    if (i == -2) {
1035
0
        return NULL;
1036
0
    }
1037
1038
0
    if (i >= 0) {
1039
0
        PyErr_SetString(PyExc_ValueError, "cannot remove local variables from FrameLocalsProxy");
1040
0
        return NULL;
1041
0
    }
1042
1043
0
    PyObject *result = NULL;
1044
1045
0
    PyObject *extra = framelocalsproxy_get_extra(frame, false);
1046
0
    if (extra == NULL) {
1047
0
        if (default_value != NULL) {
1048
0
            return Py_XNewRef(default_value);
1049
0
        } else {
1050
0
            _PyErr_SetKeyError(key);
1051
0
            return NULL;
1052
0
        }
1053
0
    }
1054
1055
0
    int found = PyDict_Pop(extra, key, &result);
1056
0
    Py_DECREF(extra);
1057
0
    if (found < 0) {
1058
0
        return NULL;
1059
0
    }
1060
1061
0
    if (result == NULL) {
1062
0
        if (default_value != NULL) {
1063
0
            return Py_XNewRef(default_value);
1064
0
        } else {
1065
0
            _PyErr_SetKeyError(key);
1066
0
            return NULL;
1067
0
        }
1068
0
    }
1069
1070
0
    return result;
1071
0
}
1072
1073
static PyObject*
1074
framelocalsproxy_copy(PyObject *self, PyObject *Py_UNUSED(ignored))
1075
0
{
1076
0
    PyObject* result = PyDict_New();
1077
1078
0
    if (result == NULL) {
1079
0
        return NULL;
1080
0
    }
1081
1082
0
    if (PyDict_Update(result, self) < 0) {
1083
0
        Py_DECREF(result);
1084
0
        return NULL;
1085
0
    }
1086
1087
0
    return result;
1088
0
}
1089
1090
static PyObject*
1091
framelocalsproxy_reversed(PyObject *self, PyObject *Py_UNUSED(ignored))
1092
0
{
1093
0
    PyObject *result = framelocalsproxy_keys(self, NULL);
1094
1095
0
    if (result == NULL) {
1096
0
        return NULL;
1097
0
    }
1098
1099
0
    if (PyList_Reverse(result) < 0) {
1100
0
        Py_DECREF(result);
1101
0
        return NULL;
1102
0
    }
1103
0
    return result;
1104
0
}
1105
1106
static PyNumberMethods framelocalsproxy_as_number = {
1107
    .nb_or = framelocalsproxy_or,
1108
    .nb_inplace_or = framelocalsproxy_inplace_or,
1109
};
1110
1111
static PySequenceMethods framelocalsproxy_as_sequence = {
1112
    .sq_contains = framelocalsproxy_contains,
1113
};
1114
1115
static PyMappingMethods framelocalsproxy_as_mapping = {
1116
    .mp_length = framelocalsproxy_length,
1117
    .mp_subscript = framelocalsproxy_getitem,
1118
    .mp_ass_subscript = framelocalsproxy_setitem,
1119
};
1120
1121
static PyMethodDef framelocalsproxy_methods[] = {
1122
    {"__contains__", framelocalsproxy___contains__, METH_O | METH_COEXIST, NULL},
1123
    {"__getitem__", framelocalsproxy_getitem, METH_O | METH_COEXIST, NULL},
1124
    {"update", framelocalsproxy_update, METH_O, NULL},
1125
    {"__reversed__", framelocalsproxy_reversed, METH_NOARGS, NULL},
1126
    {"copy", framelocalsproxy_copy, METH_NOARGS, NULL},
1127
    {"keys", framelocalsproxy_keys, METH_NOARGS, NULL},
1128
    {"values", framelocalsproxy_values, METH_NOARGS, NULL},
1129
    {"items", _PyCFunction_CAST(framelocalsproxy_items), METH_NOARGS, NULL},
1130
    {"get", _PyCFunction_CAST(framelocalsproxy_get), METH_FASTCALL, NULL},
1131
    {"pop", _PyCFunction_CAST(framelocalsproxy_pop), METH_FASTCALL, NULL},
1132
    {
1133
        "setdefault",
1134
        _PyCFunction_CAST(framelocalsproxy_setdefault),
1135
        METH_FASTCALL,
1136
        NULL
1137
    },
1138
    {NULL, NULL}   /* sentinel */
1139
};
1140
1141
PyTypeObject PyFrameLocalsProxy_Type = {
1142
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1143
    .tp_name = "FrameLocalsProxy",
1144
    .tp_basicsize = sizeof(PyFrameLocalsProxyObject),
1145
    .tp_dealloc = framelocalsproxy_dealloc,
1146
    .tp_repr = &framelocalsproxy_repr,
1147
    .tp_as_number = &framelocalsproxy_as_number,
1148
    .tp_as_sequence = &framelocalsproxy_as_sequence,
1149
    .tp_as_mapping = &framelocalsproxy_as_mapping,
1150
    .tp_getattro = PyObject_GenericGetAttr,
1151
    .tp_setattro = PyObject_GenericSetAttr,
1152
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_MAPPING,
1153
    .tp_traverse = framelocalsproxy_visit,
1154
    .tp_clear = framelocalsproxy_tp_clear,
1155
    .tp_richcompare = framelocalsproxy_richcompare,
1156
    .tp_iter = framelocalsproxy_iter,
1157
    .tp_methods = framelocalsproxy_methods,
1158
    .tp_alloc = PyType_GenericAlloc,
1159
    .tp_new = framelocalsproxy_new,
1160
    .tp_free = PyObject_GC_Del,
1161
    .tp_doc = framelocalsproxy_new__doc__,
1162
    .tp_vectorcall = framelocalsproxy_vectorcall,
1163
};
1164
1165
PyObject *
1166
_PyFrameLocalsProxy_New(PyFrameObject *frame)
1167
45
{
1168
45
    return framelocalsproxy_new_impl(&PyFrameLocalsProxy_Type, (PyObject *)frame);
1169
45
}
1170
1171
static PyMemberDef frame_memberlist[] = {
1172
    {"f_trace_lines",   Py_T_BOOL,         OFF(f_trace_lines), 0},
1173
    {NULL}      /* Sentinel */
1174
};
1175
1176
/*[clinic input]
1177
@critical_section
1178
@getter
1179
frame.f_locals as frame_locals
1180
1181
Return the mapping used by the frame to look up local variables.
1182
[clinic start generated code]*/
1183
1184
static PyObject *
1185
frame_locals_get_impl(PyFrameObject *self)
1186
/*[clinic end generated code: output=b4ace8bb4cae71f4 input=7bd444d0dc8ddf44]*/
1187
37
{
1188
37
    assert(!_PyFrame_IsIncomplete(self->f_frame));
1189
1190
37
    PyCodeObject *co = _PyFrame_GetCode(self->f_frame);
1191
1192
37
    if (!(co->co_flags & CO_OPTIMIZED) && !_PyFrame_HasHiddenLocals(self->f_frame)) {
1193
0
        if (self->f_frame->f_locals == NULL) {
1194
            // We found cases when f_locals is NULL for non-optimized code.
1195
            // We fill the f_locals with an empty dict to avoid crash until
1196
            // we find the root cause.
1197
0
            self->f_frame->f_locals = PyDict_New();
1198
0
            if (self->f_frame->f_locals == NULL) {
1199
0
                return NULL;
1200
0
            }
1201
0
        }
1202
0
        return Py_NewRef(self->f_frame->f_locals);
1203
0
    }
1204
1205
37
    return _PyFrameLocalsProxy_New(self);
1206
37
}
1207
1208
int
1209
PyFrame_GetLineNumber(PyFrameObject *f)
1210
875k
{
1211
875k
    assert(f != NULL);
1212
875k
    if (f->f_lineno == -1) {
1213
        // We should calculate it once. If we can't get the line number,
1214
        // set f->f_lineno to 0.
1215
0
        f->f_lineno = PyUnstable_InterpreterFrame_GetLine(f->f_frame);
1216
0
        if (f->f_lineno < 0) {
1217
0
            f->f_lineno = 0;
1218
0
            return -1;
1219
0
        }
1220
0
    }
1221
1222
875k
    if (f->f_lineno > 0) {
1223
0
        return f->f_lineno;
1224
0
    }
1225
875k
    return PyUnstable_InterpreterFrame_GetLine(f->f_frame);
1226
875k
}
1227
1228
/*[clinic input]
1229
@critical_section
1230
@getter
1231
frame.f_lineno as frame_lineno
1232
1233
Return the current line number in the frame.
1234
[clinic start generated code]*/
1235
1236
static PyObject *
1237
frame_lineno_get_impl(PyFrameObject *self)
1238
/*[clinic end generated code: output=70f35de5ac7ad630 input=87b9ec648b742936]*/
1239
21.2k
{
1240
21.2k
    int lineno = PyFrame_GetLineNumber(self);
1241
21.2k
    if (lineno < 0) {
1242
0
        Py_RETURN_NONE;
1243
0
    }
1244
21.2k
    return PyLong_FromLong(lineno);
1245
21.2k
}
1246
1247
/*[clinic input]
1248
@critical_section
1249
@getter
1250
frame.f_lasti as frame_lasti
1251
1252
Return the index of the last attempted instruction in the frame.
1253
[clinic start generated code]*/
1254
1255
static PyObject *
1256
frame_lasti_get_impl(PyFrameObject *self)
1257
/*[clinic end generated code: output=03275b4f0327d1a2 input=0225ed49cb1fbeeb]*/
1258
0
{
1259
0
    int lasti = PyUnstable_InterpreterFrame_GetLasti(self->f_frame);
1260
0
    if (lasti < 0) {
1261
0
        return PyLong_FromLong(-1);
1262
0
    }
1263
0
    return PyLong_FromLong(lasti);
1264
0
}
1265
1266
/*[clinic input]
1267
@critical_section
1268
@getter
1269
frame.f_globals as frame_globals
1270
1271
Return the global variables in the frame.
1272
[clinic start generated code]*/
1273
1274
static PyObject *
1275
frame_globals_get_impl(PyFrameObject *self)
1276
/*[clinic end generated code: output=7758788c32885528 input=7fff7241357d314d]*/
1277
0
{
1278
0
    PyObject *globals = self->f_frame->f_globals;
1279
0
    if (globals == NULL) {
1280
0
        globals = Py_None;
1281
0
    }
1282
0
    return Py_NewRef(globals);
1283
0
}
1284
1285
/*[clinic input]
1286
@critical_section
1287
@getter
1288
frame.f_builtins as frame_builtins
1289
1290
Return the built-in variables in the frame.
1291
[clinic start generated code]*/
1292
1293
static PyObject *
1294
frame_builtins_get_impl(PyFrameObject *self)
1295
/*[clinic end generated code: output=45362faa6d42c702 input=27c696d6ffcad2c7]*/
1296
0
{
1297
0
    PyObject *builtins = self->f_frame->f_builtins;
1298
0
    if (builtins == NULL) {
1299
0
        builtins = Py_None;
1300
0
    }
1301
0
    return Py_NewRef(builtins);
1302
0
}
1303
1304
/*[clinic input]
1305
@getter
1306
frame.f_code as frame_code
1307
1308
Return the code object being executed in this frame.
1309
[clinic start generated code]*/
1310
1311
static PyObject *
1312
frame_code_get_impl(PyFrameObject *self)
1313
/*[clinic end generated code: output=a5ed6207395a8cef input=e127e7098c124816]*/
1314
63.7k
{
1315
63.7k
    if (PySys_Audit("object.__getattr__", "Os", self, "f_code") < 0) {
1316
0
        return NULL;
1317
0
    }
1318
63.7k
    return (PyObject *)PyFrame_GetCode(self);
1319
63.7k
}
1320
1321
/*[clinic input]
1322
@critical_section
1323
@getter
1324
frame.f_back as frame_back
1325
[clinic start generated code]*/
1326
1327
static PyObject *
1328
frame_back_get_impl(PyFrameObject *self)
1329
/*[clinic end generated code: output=3a84c22a55a63c79 input=9e528570d0e1f44a]*/
1330
22.5k
{
1331
22.5k
    PyObject *res = (PyObject *)PyFrame_GetBack(self);
1332
22.5k
    if (res == NULL && !PyErr_Occurred()) {
1333
116
        Py_RETURN_NONE;
1334
116
    }
1335
22.4k
    return res;
1336
22.5k
}
1337
1338
/*[clinic input]
1339
@critical_section
1340
@getter
1341
frame.f_trace_opcodes as frame_trace_opcodes
1342
1343
Return True if opcode tracing is enabled, False otherwise.
1344
[clinic start generated code]*/
1345
1346
static PyObject *
1347
frame_trace_opcodes_get_impl(PyFrameObject *self)
1348
/*[clinic end generated code: output=53ff41d09cc32e87 input=4eb91dc88e04677a]*/
1349
0
{
1350
0
    return self->f_trace_opcodes ? Py_True : Py_False;
1351
0
}
1352
1353
/*[clinic input]
1354
@critical_section
1355
@setter
1356
frame.f_trace_opcodes as frame_trace_opcodes
1357
[clinic start generated code]*/
1358
1359
static int
1360
frame_trace_opcodes_set_impl(PyFrameObject *self, PyObject *value)
1361
/*[clinic end generated code: output=92619da2bfccd449 input=7e286eea3c0333ff]*/
1362
0
{
1363
0
    if (!PyBool_Check(value)) {
1364
0
        PyErr_SetString(PyExc_TypeError,
1365
0
                        "attribute value type must be bool");
1366
0
        return -1;
1367
0
    }
1368
0
    if (value == Py_True) {
1369
0
        self->f_trace_opcodes = 1;
1370
0
        if (self->f_trace) {
1371
0
            return _PyEval_SetOpcodeTrace(self, true);
1372
0
        }
1373
0
    }
1374
0
    else {
1375
0
        self->f_trace_opcodes = 0;
1376
0
        return _PyEval_SetOpcodeTrace(self, false);
1377
0
    }
1378
0
    return 0;
1379
0
}
1380
1381
/* Model the evaluation stack, to determine which jumps
1382
 * are safe and how many values needs to be popped.
1383
 * The stack is modelled by a 64 integer, treating any
1384
 * stack that can't fit into 64 bits as "overflowed".
1385
 */
1386
1387
typedef enum kind {
1388
    Iterator = 1,
1389
    Except = 2,
1390
    Object = 3,
1391
    Null = 4,
1392
    Lasti = 5,
1393
} Kind;
1394
1395
static int
1396
0
compatible_kind(Kind from, Kind to) {
1397
0
    if (to == 0) {
1398
0
        return 0;
1399
0
    }
1400
0
    if (to == Object) {
1401
0
        return from != Null;
1402
0
    }
1403
0
    if (to == Null) {
1404
0
        return 1;
1405
0
    }
1406
0
    return from == to;
1407
0
}
1408
1409
0
#define BITS_PER_BLOCK 3
1410
1411
0
#define UNINITIALIZED -2
1412
0
#define OVERFLOWED -1
1413
1414
0
#define MAX_STACK_ENTRIES (63/BITS_PER_BLOCK)
1415
0
#define WILL_OVERFLOW (1ULL<<((MAX_STACK_ENTRIES-1)*BITS_PER_BLOCK))
1416
1417
0
#define EMPTY_STACK 0
1418
1419
static inline int64_t
1420
push_value(int64_t stack, Kind kind)
1421
0
{
1422
0
    if (((uint64_t)stack) >= WILL_OVERFLOW) {
1423
0
        return OVERFLOWED;
1424
0
    }
1425
0
    else {
1426
0
        return (stack << BITS_PER_BLOCK) | kind;
1427
0
    }
1428
0
}
1429
1430
static inline int64_t
1431
pop_value(int64_t stack)
1432
0
{
1433
0
    return Py_ARITHMETIC_RIGHT_SHIFT(int64_t, stack, BITS_PER_BLOCK);
1434
0
}
1435
1436
0
#define MASK ((1<<BITS_PER_BLOCK)-1)
1437
1438
static inline Kind
1439
top_of_stack(int64_t stack)
1440
0
{
1441
0
    return stack & MASK;
1442
0
}
1443
1444
static inline Kind
1445
peek(int64_t stack, int n)
1446
0
{
1447
0
    assert(n >= 1);
1448
0
    return (stack>>(BITS_PER_BLOCK*(n-1))) & MASK;
1449
0
}
1450
1451
static Kind
1452
stack_swap(int64_t stack, int n)
1453
0
{
1454
0
    assert(n >= 1);
1455
0
    Kind to_swap = peek(stack, n);
1456
0
    Kind top = top_of_stack(stack);
1457
0
    int shift = BITS_PER_BLOCK*(n-1);
1458
0
    int64_t replaced_low = (stack & ~(MASK << shift)) | (top << shift);
1459
0
    int64_t replaced_top = (replaced_low & ~MASK) | to_swap;
1460
0
    return replaced_top;
1461
0
}
1462
1463
static int64_t
1464
0
pop_to_level(int64_t stack, int level) {
1465
0
    if (level == 0) {
1466
0
        return EMPTY_STACK;
1467
0
    }
1468
0
    int64_t max_item = (1<<BITS_PER_BLOCK) - 1;
1469
0
    int64_t level_max_stack = max_item << ((level-1) * BITS_PER_BLOCK);
1470
0
    while (stack > level_max_stack) {
1471
0
        stack = pop_value(stack);
1472
0
    }
1473
0
    return stack;
1474
0
}
1475
1476
#if 0
1477
/* These functions are useful for debugging the stack marking code */
1478
1479
static char
1480
tos_char(int64_t stack) {
1481
    switch(top_of_stack(stack)) {
1482
        case Iterator:
1483
            return 'I';
1484
        case Except:
1485
            return 'E';
1486
        case Object:
1487
            return 'O';
1488
        case Lasti:
1489
            return 'L';
1490
        case Null:
1491
            return 'N';
1492
    }
1493
    return '?';
1494
}
1495
1496
static void
1497
print_stack(int64_t stack) {
1498
    if (stack < 0) {
1499
        if (stack == UNINITIALIZED) {
1500
            printf("---");
1501
        }
1502
        else if (stack == OVERFLOWED) {
1503
            printf("OVERFLOWED");
1504
        }
1505
        else {
1506
            printf("??");
1507
        }
1508
        return;
1509
    }
1510
    while (stack) {
1511
        printf("%c", tos_char(stack));
1512
        stack = pop_value(stack);
1513
    }
1514
}
1515
1516
static void
1517
print_stacks(int64_t *stacks, int n) {
1518
    for (int i = 0; i < n; i++) {
1519
        printf("%d: ", i);
1520
        print_stack(stacks[i]);
1521
        printf("\n");
1522
    }
1523
}
1524
1525
#endif
1526
1527
static int64_t *
1528
mark_stacks(PyCodeObject *code_obj, int len)
1529
0
{
1530
0
    PyObject *co_code = _PyCode_GetCode(code_obj);
1531
0
    if (co_code == NULL) {
1532
0
        return NULL;
1533
0
    }
1534
0
    int64_t *stacks = PyMem_New(int64_t, len+1);
1535
1536
0
    if (stacks == NULL) {
1537
0
        PyErr_NoMemory();
1538
0
        Py_DECREF(co_code);
1539
0
        return NULL;
1540
0
    }
1541
0
    for (int i = 1; i <= len; i++) {
1542
0
        stacks[i] = UNINITIALIZED;
1543
0
    }
1544
0
    stacks[0] = EMPTY_STACK;
1545
0
    int todo = 1;
1546
0
    while (todo) {
1547
0
        todo = 0;
1548
        /* Scan instructions */
1549
0
        for (int i = 0; i < len;) {
1550
0
            int j;
1551
0
            int64_t next_stack = stacks[i];
1552
0
            _Py_CODEUNIT inst = _Py_GetBaseCodeUnit(code_obj, i);
1553
0
            int opcode = inst.op.code;
1554
0
            int oparg = 0;
1555
0
            while (opcode == EXTENDED_ARG) {
1556
0
                oparg = (oparg << 8) | inst.op.arg;
1557
0
                i++;
1558
0
                inst = _Py_GetBaseCodeUnit(code_obj, i);
1559
0
                opcode = inst.op.code;
1560
0
                stacks[i] = next_stack;
1561
0
            }
1562
0
            oparg = (oparg << 8) | inst.op.arg;
1563
0
            int next_i = i + _PyOpcode_Caches[opcode] + 1;
1564
0
            if (next_stack == UNINITIALIZED) {
1565
0
                i = next_i;
1566
0
                continue;
1567
0
            }
1568
0
            switch (opcode) {
1569
0
                case POP_JUMP_IF_FALSE:
1570
0
                case POP_JUMP_IF_TRUE:
1571
0
                case POP_JUMP_IF_NONE:
1572
0
                case POP_JUMP_IF_NOT_NONE:
1573
0
                {
1574
0
                    int64_t target_stack;
1575
0
                    j = next_i + oparg;
1576
0
                    assert(j < len);
1577
0
                    next_stack = pop_value(next_stack);
1578
0
                    target_stack = next_stack;
1579
0
                    assert(stacks[j] == UNINITIALIZED || stacks[j] == target_stack);
1580
0
                    stacks[j] = target_stack;
1581
0
                    stacks[next_i] = next_stack;
1582
0
                    break;
1583
0
                }
1584
0
                case SEND:
1585
0
                    j = oparg + i + INLINE_CACHE_ENTRIES_SEND + 1;
1586
0
                    assert(j < len);
1587
0
                    assert(stacks[j] == UNINITIALIZED || stacks[j] == next_stack);
1588
0
                    stacks[j] = next_stack;
1589
0
                    stacks[next_i] = next_stack;
1590
0
                    break;
1591
0
                case JUMP_FORWARD:
1592
0
                    j = oparg + i + 1;
1593
0
                    assert(j < len);
1594
0
                    assert(stacks[j] == UNINITIALIZED || stacks[j] == next_stack);
1595
0
                    stacks[j] = next_stack;
1596
0
                    break;
1597
0
                case JUMP_BACKWARD:
1598
0
                case JUMP_BACKWARD_NO_INTERRUPT:
1599
0
                    j = next_i - oparg;
1600
0
                    assert(j >= 0);
1601
0
                    assert(j < len);
1602
0
                    if (stacks[j] == UNINITIALIZED && j < i) {
1603
0
                        todo = 1;
1604
0
                    }
1605
0
                    assert(stacks[j] == UNINITIALIZED || stacks[j] == next_stack);
1606
0
                    stacks[j] = next_stack;
1607
0
                    break;
1608
0
                case GET_ITER:
1609
0
                    next_stack = push_value(pop_value(next_stack), Iterator);
1610
0
                    next_stack = push_value(next_stack, Iterator);
1611
0
                    stacks[next_i] = next_stack;
1612
0
                    break;
1613
0
                case GET_AITER:
1614
0
                    next_stack = push_value(pop_value(next_stack), Iterator);
1615
0
                    stacks[next_i] = next_stack;
1616
0
                    break;
1617
0
                case FOR_ITER:
1618
0
                {
1619
0
                    int64_t target_stack = push_value(next_stack, Object);
1620
0
                    stacks[next_i] = target_stack;
1621
0
                    j = oparg + 1 + INLINE_CACHE_ENTRIES_FOR_ITER + i;
1622
0
                    assert(j < len);
1623
0
                    assert(stacks[j] == UNINITIALIZED || stacks[j] == target_stack);
1624
0
                    stacks[j] = target_stack;
1625
0
                    break;
1626
0
                }
1627
0
                case END_ASYNC_FOR:
1628
0
                    next_stack = pop_value(pop_value(next_stack));
1629
0
                    stacks[next_i] = next_stack;
1630
0
                    break;
1631
0
                case PUSH_EXC_INFO:
1632
0
                    next_stack = push_value(next_stack, Except);
1633
0
                    stacks[next_i] = next_stack;
1634
0
                    break;
1635
0
                case POP_EXCEPT:
1636
0
                    assert(top_of_stack(next_stack) == Except);
1637
0
                    next_stack = pop_value(next_stack);
1638
0
                    stacks[next_i] = next_stack;
1639
0
                    break;
1640
0
                case RETURN_VALUE:
1641
0
                    assert(pop_value(next_stack) == EMPTY_STACK);
1642
0
                    assert(top_of_stack(next_stack) == Object);
1643
0
                    break;
1644
0
                case RAISE_VARARGS:
1645
0
                    break;
1646
0
                case RERAISE:
1647
0
                    assert(top_of_stack(next_stack) == Except);
1648
                    /* End of block */
1649
0
                    break;
1650
0
                case PUSH_NULL:
1651
0
                    next_stack = push_value(next_stack, Null);
1652
0
                    stacks[next_i] = next_stack;
1653
0
                    break;
1654
0
                case LOAD_GLOBAL:
1655
0
                {
1656
0
                    int j = oparg;
1657
0
                    next_stack = push_value(next_stack, Object);
1658
0
                    if (j & 1) {
1659
0
                        next_stack = push_value(next_stack, Null);
1660
0
                    }
1661
0
                    stacks[next_i] = next_stack;
1662
0
                    break;
1663
0
                }
1664
0
                case LOAD_ATTR:
1665
0
                {
1666
0
                    assert(top_of_stack(next_stack) == Object);
1667
0
                    int j = oparg;
1668
0
                    if (j & 1) {
1669
0
                        next_stack = pop_value(next_stack);
1670
0
                        next_stack = push_value(next_stack, Object);
1671
0
                        next_stack = push_value(next_stack, Null);
1672
0
                    }
1673
0
                    stacks[next_i] = next_stack;
1674
0
                    break;
1675
0
                }
1676
0
                case SWAP:
1677
0
                {
1678
0
                    int n = oparg;
1679
0
                    next_stack = stack_swap(next_stack, n);
1680
0
                    stacks[next_i] = next_stack;
1681
0
                    break;
1682
0
                }
1683
0
                case COPY:
1684
0
                {
1685
0
                    int n = oparg;
1686
0
                    next_stack = push_value(next_stack, peek(next_stack, n));
1687
0
                    stacks[next_i] = next_stack;
1688
0
                    break;
1689
0
                }
1690
0
                case CACHE:
1691
0
                case RESERVED:
1692
0
                {
1693
0
                    assert(0);
1694
0
                }
1695
0
                default:
1696
0
                {
1697
0
                    int delta = PyCompile_OpcodeStackEffect(opcode, oparg);
1698
0
                    assert(delta != PY_INVALID_STACK_EFFECT);
1699
0
                    while (delta < 0) {
1700
0
                        next_stack = pop_value(next_stack);
1701
0
                        delta++;
1702
0
                    }
1703
0
                    while (delta > 0) {
1704
0
                        next_stack = push_value(next_stack, Object);
1705
0
                        delta--;
1706
0
                    }
1707
0
                    stacks[next_i] = next_stack;
1708
0
                }
1709
0
            }
1710
0
            i = next_i;
1711
0
        }
1712
        /* Scan exception table */
1713
0
        unsigned char *start = (unsigned char *)PyBytes_AS_STRING(code_obj->co_exceptiontable);
1714
0
        unsigned char *end = start + PyBytes_GET_SIZE(code_obj->co_exceptiontable);
1715
0
        unsigned char *scan = start;
1716
0
        while (scan < end) {
1717
0
            int start_offset, size, handler;
1718
0
            scan = parse_varint(scan, &start_offset);
1719
0
            assert(start_offset >= 0 && start_offset < len);
1720
0
            scan = parse_varint(scan, &size);
1721
0
            assert(size >= 0 && start_offset+size <= len);
1722
0
            scan = parse_varint(scan, &handler);
1723
0
            assert(handler >= 0 && handler < len);
1724
0
            int depth_and_lasti;
1725
0
            scan = parse_varint(scan, &depth_and_lasti);
1726
0
            int level = depth_and_lasti >> 1;
1727
0
            int lasti = depth_and_lasti & 1;
1728
0
            if (stacks[start_offset] != UNINITIALIZED) {
1729
0
                if (stacks[handler] == UNINITIALIZED) {
1730
0
                    todo = 1;
1731
0
                    uint64_t target_stack = pop_to_level(stacks[start_offset], level);
1732
0
                    if (lasti) {
1733
0
                        target_stack = push_value(target_stack, Lasti);
1734
0
                    }
1735
0
                    target_stack = push_value(target_stack, Except);
1736
0
                    stacks[handler] = target_stack;
1737
0
                }
1738
0
            }
1739
0
        }
1740
0
    }
1741
0
    Py_DECREF(co_code);
1742
0
    return stacks;
1743
0
}
1744
1745
static int
1746
compatible_stack(int64_t from_stack, int64_t to_stack)
1747
0
{
1748
0
    if (from_stack < 0 || to_stack < 0) {
1749
0
        return 0;
1750
0
    }
1751
0
    while(from_stack > to_stack) {
1752
0
        from_stack = pop_value(from_stack);
1753
0
    }
1754
0
    while(from_stack) {
1755
0
        Kind from_top = top_of_stack(from_stack);
1756
0
        Kind to_top = top_of_stack(to_stack);
1757
0
        if (!compatible_kind(from_top, to_top)) {
1758
0
            return 0;
1759
0
        }
1760
0
        from_stack = pop_value(from_stack);
1761
0
        to_stack = pop_value(to_stack);
1762
0
    }
1763
0
    return to_stack == 0;
1764
0
}
1765
1766
static const char *
1767
explain_incompatible_stack(int64_t to_stack)
1768
0
{
1769
0
    assert(to_stack != 0);
1770
0
    if (to_stack == OVERFLOWED) {
1771
0
        return "stack is too deep to analyze";
1772
0
    }
1773
0
    if (to_stack == UNINITIALIZED) {
1774
0
        return "can't jump into an exception handler, or code may be unreachable";
1775
0
    }
1776
0
    Kind target_kind = top_of_stack(to_stack);
1777
0
    switch(target_kind) {
1778
0
        case Except:
1779
0
            return "can't jump into an 'except' block as there's no exception";
1780
0
        case Lasti:
1781
0
            return "can't jump into a re-raising block as there's no location";
1782
0
        case Object:
1783
0
        case Null:
1784
0
            return "incompatible stacks";
1785
0
        case Iterator:
1786
0
            return "can't jump into the body of a for loop";
1787
0
        default:
1788
0
            Py_UNREACHABLE();
1789
0
    }
1790
0
}
1791
1792
static int *
1793
marklines(PyCodeObject *code, int len)
1794
0
{
1795
0
    PyCodeAddressRange bounds;
1796
0
    _PyCode_InitAddressRange(code, &bounds);
1797
0
    assert (bounds.ar_end == 0);
1798
0
    int last_line = -1;
1799
1800
0
    int *linestarts = PyMem_New(int, len);
1801
0
    if (linestarts == NULL) {
1802
0
        return NULL;
1803
0
    }
1804
0
    for (int i = 0; i < len; i++) {
1805
0
        linestarts[i] = -1;
1806
0
    }
1807
1808
0
    while (_PyLineTable_NextAddressRange(&bounds)) {
1809
0
        assert(bounds.ar_start / (int)sizeof(_Py_CODEUNIT) < len);
1810
0
        if (bounds.ar_line != last_line && bounds.ar_line != -1) {
1811
0
            linestarts[bounds.ar_start / sizeof(_Py_CODEUNIT)] = bounds.ar_line;
1812
0
            last_line = bounds.ar_line;
1813
0
        }
1814
0
    }
1815
0
    return linestarts;
1816
0
}
1817
1818
static int
1819
first_line_not_before(int *lines, int len, int line)
1820
0
{
1821
0
    int result = INT_MAX;
1822
0
    for (int i = 0; i < len; i++) {
1823
0
        if (lines[i] < result && lines[i] >= line) {
1824
0
            result = lines[i];
1825
0
        }
1826
0
    }
1827
0
    if (result == INT_MAX) {
1828
0
        return -1;
1829
0
    }
1830
0
    return result;
1831
0
}
1832
1833
static bool frame_is_suspended(PyFrameObject *frame)
1834
0
{
1835
0
    assert(!_PyFrame_IsIncomplete(frame->f_frame));
1836
0
    if (frame->f_frame->owner == FRAME_OWNED_BY_GENERATOR) {
1837
0
        PyGenObject *gen = _PyGen_GetGeneratorFromFrame(frame->f_frame);
1838
0
        return FRAME_STATE_SUSPENDED(gen->gi_frame_state);
1839
0
    }
1840
0
    return false;
1841
0
}
1842
1843
/* Setter for f_lineno - you can set f_lineno from within a trace function in
1844
 * order to jump to a given line of code, subject to some restrictions.  Most
1845
 * lines are OK to jump to because they don't make any assumptions about the
1846
 * state of the stack (obvious because you could remove the line and the code
1847
 * would still work without any stack errors), but there are some constructs
1848
 * that limit jumping:
1849
 *
1850
 *  o Any exception handlers.
1851
 *  o 'for' and 'async for' loops can't be jumped into because the
1852
 *    iterator needs to be on the stack.
1853
 *  o Jumps cannot be made from within a trace function invoked with a
1854
 *    'return' or 'exception' event since the eval loop has been exited at
1855
 *    that time.
1856
 */
1857
/*[clinic input]
1858
@critical_section
1859
@setter
1860
frame.f_lineno as frame_lineno
1861
[clinic start generated code]*/
1862
1863
static int
1864
frame_lineno_set_impl(PyFrameObject *self, PyObject *value)
1865
/*[clinic end generated code: output=e64c86ff6be64292 input=36ed3c896b27fb91]*/
1866
0
{
1867
0
    PyCodeObject *code = _PyFrame_GetCode(self->f_frame);
1868
    /* f_lineno must be an integer. */
1869
0
    if (!PyLong_CheckExact(value)) {
1870
0
        PyErr_SetString(PyExc_ValueError,
1871
0
                        "lineno must be an integer");
1872
0
        return -1;
1873
0
    }
1874
1875
0
    bool is_suspended = frame_is_suspended(self);
1876
    /*
1877
     * This code preserves the historical restrictions on
1878
     * setting the line number of a frame.
1879
     * Jumps are forbidden on a 'return' trace event (except after a yield).
1880
     * Jumps from 'call' trace events are also forbidden.
1881
     * In addition, jumps are forbidden when not tracing,
1882
     * as this is a debugging feature.
1883
     */
1884
0
    int what_event = PyThreadState_GET()->what_event;
1885
0
    if (what_event < 0) {
1886
0
        PyErr_Format(PyExc_ValueError,
1887
0
                    "f_lineno can only be set in a trace function");
1888
0
        return -1;
1889
0
    }
1890
0
    switch (what_event) {
1891
0
        case PY_MONITORING_EVENT_PY_RESUME:
1892
0
        case PY_MONITORING_EVENT_JUMP:
1893
0
        case PY_MONITORING_EVENT_BRANCH:
1894
0
        case PY_MONITORING_EVENT_BRANCH_LEFT:
1895
0
        case PY_MONITORING_EVENT_BRANCH_RIGHT:
1896
0
        case PY_MONITORING_EVENT_LINE:
1897
0
        case PY_MONITORING_EVENT_PY_YIELD:
1898
            /* Setting f_lineno is allowed for the above events */
1899
0
            break;
1900
0
        case PY_MONITORING_EVENT_PY_START:
1901
0
            PyErr_Format(PyExc_ValueError,
1902
0
                     "can't jump from the 'call' trace event of a new frame");
1903
0
            return -1;
1904
0
        case PY_MONITORING_EVENT_CALL:
1905
0
        case PY_MONITORING_EVENT_C_RETURN:
1906
0
            PyErr_SetString(PyExc_ValueError,
1907
0
                "can't jump during a call");
1908
0
            return -1;
1909
0
        case PY_MONITORING_EVENT_PY_RETURN:
1910
0
        case PY_MONITORING_EVENT_PY_UNWIND:
1911
0
        case PY_MONITORING_EVENT_PY_THROW:
1912
0
        case PY_MONITORING_EVENT_RAISE:
1913
0
        case PY_MONITORING_EVENT_C_RAISE:
1914
0
        case PY_MONITORING_EVENT_INSTRUCTION:
1915
0
        case PY_MONITORING_EVENT_EXCEPTION_HANDLED:
1916
0
            PyErr_Format(PyExc_ValueError,
1917
0
                "can only jump from a 'line' trace event");
1918
0
            return -1;
1919
0
        default:
1920
0
            PyErr_SetString(PyExc_SystemError,
1921
0
                "unexpected event type");
1922
0
            return -1;
1923
0
    }
1924
1925
0
    int new_lineno;
1926
1927
    /* Fail if the line falls outside the code block and
1928
        select first line with actual code. */
1929
0
    int overflow;
1930
0
    long l_new_lineno = PyLong_AsLongAndOverflow(value, &overflow);
1931
0
    if (overflow
1932
0
#if SIZEOF_LONG > SIZEOF_INT
1933
0
        || l_new_lineno > INT_MAX
1934
0
        || l_new_lineno < INT_MIN
1935
0
#endif
1936
0
    ) {
1937
0
        PyErr_SetString(PyExc_ValueError,
1938
0
                        "lineno out of range");
1939
0
        return -1;
1940
0
    }
1941
0
    new_lineno = (int)l_new_lineno;
1942
1943
0
    if (new_lineno < code->co_firstlineno) {
1944
0
        PyErr_Format(PyExc_ValueError,
1945
0
                    "line %d comes before the current code block",
1946
0
                    new_lineno);
1947
0
        return -1;
1948
0
    }
1949
1950
    /* PyCode_NewWithPosOnlyArgs limits co_code to be under INT_MAX so this
1951
     * should never overflow. */
1952
0
    int len = (int)Py_SIZE(code);
1953
0
    int *lines = marklines(code, len);
1954
0
    if (lines == NULL) {
1955
0
        return -1;
1956
0
    }
1957
1958
0
    new_lineno = first_line_not_before(lines, len, new_lineno);
1959
0
    if (new_lineno < 0) {
1960
0
        PyErr_Format(PyExc_ValueError,
1961
0
                    "line %d comes after the current code block",
1962
0
                    (int)l_new_lineno);
1963
0
        PyMem_Free(lines);
1964
0
        return -1;
1965
0
    }
1966
1967
0
    int64_t *stacks = mark_stacks(code, len);
1968
0
    if (stacks == NULL) {
1969
0
        PyMem_Free(lines);
1970
0
        return -1;
1971
0
    }
1972
1973
0
    int64_t best_stack = OVERFLOWED;
1974
0
    int best_addr = -1;
1975
0
    int64_t start_stack = stacks[_PyInterpreterFrame_LASTI(self->f_frame)];
1976
0
    int err = -1;
1977
0
    const char *msg = "cannot find bytecode for specified line";
1978
0
    for (int i = 0; i < len; i++) {
1979
0
        if (lines[i] == new_lineno) {
1980
0
            int64_t target_stack = stacks[i];
1981
0
            if (compatible_stack(start_stack, target_stack)) {
1982
0
                err = 0;
1983
0
                if (target_stack > best_stack) {
1984
0
                    best_stack = target_stack;
1985
0
                    best_addr = i;
1986
0
                }
1987
0
            }
1988
0
            else if (err < 0) {
1989
0
                if (start_stack == OVERFLOWED) {
1990
0
                    msg = "stack to deep to analyze";
1991
0
                }
1992
0
                else if (start_stack == UNINITIALIZED) {
1993
0
                    msg = "can't jump from unreachable code";
1994
0
                }
1995
0
                else {
1996
0
                    msg = explain_incompatible_stack(target_stack);
1997
0
                    err = 1;
1998
0
                }
1999
0
            }
2000
0
        }
2001
0
    }
2002
0
    PyMem_Free(stacks);
2003
0
    PyMem_Free(lines);
2004
0
    if (err) {
2005
0
        PyErr_SetString(PyExc_ValueError, msg);
2006
0
        return -1;
2007
0
    }
2008
    // Populate any NULL locals that the compiler might have "proven" to exist
2009
    // in the new location. Rather than crashing or changing co_code, just bind
2010
    // None instead:
2011
0
    int unbound = 0;
2012
0
    for (int i = 0; i < code->co_nlocalsplus; i++) {
2013
        // Counting every unbound local is overly-cautious, but a full flow
2014
        // analysis (like we do in the compiler) is probably too expensive:
2015
0
        unbound += PyStackRef_IsNull(self->f_frame->localsplus[i]);
2016
0
    }
2017
0
    if (unbound) {
2018
0
        const char *e = "assigning None to %d unbound local%s";
2019
0
        const char *s = (unbound == 1) ? "" : "s";
2020
0
        if (PyErr_WarnFormat(PyExc_RuntimeWarning, 0, e, unbound, s)) {
2021
0
            return -1;
2022
0
        }
2023
        // Do this in a second pass to avoid writing a bunch of Nones when
2024
        // warnings are being treated as errors and the previous bit raises:
2025
0
        for (int i = 0; i < code->co_nlocalsplus; i++) {
2026
0
            if (PyStackRef_IsNull(self->f_frame->localsplus[i])) {
2027
0
                self->f_frame->localsplus[i] = PyStackRef_None;
2028
0
                unbound--;
2029
0
            }
2030
0
        }
2031
0
        assert(unbound == 0);
2032
0
    }
2033
0
    if (is_suspended) {
2034
        /* Account for value popped by yield */
2035
0
        start_stack = pop_value(start_stack);
2036
0
    }
2037
0
    while (start_stack > best_stack) {
2038
0
        _PyStackRef popped = _PyFrame_StackPop(self->f_frame);
2039
0
        if (top_of_stack(start_stack) == Except) {
2040
            /* Pop exception stack as well as the evaluation stack */
2041
0
            PyObject *exc = PyStackRef_AsPyObjectBorrow(popped);
2042
0
            assert(PyExceptionInstance_Check(exc) || exc == Py_None);
2043
0
            PyThreadState *tstate = _PyThreadState_GET();
2044
0
            Py_XSETREF(tstate->exc_info->exc_value, exc == Py_None ? NULL : exc);
2045
0
        }
2046
0
        else {
2047
0
            PyStackRef_XCLOSE(popped);
2048
0
        }
2049
0
        start_stack = pop_value(start_stack);
2050
0
    }
2051
    /* Finally set the new lasti and return OK. */
2052
0
    self->f_lineno = 0;
2053
0
    self->f_frame->instr_ptr = _PyFrame_GetBytecode(self->f_frame) + best_addr;
2054
0
    return 0;
2055
0
}
2056
2057
/*[clinic input]
2058
@permit_long_summary
2059
@critical_section
2060
@getter
2061
frame.f_trace as frame_trace
2062
2063
Return the trace function for this frame, or None if no trace function is set.
2064
[clinic start generated code]*/
2065
2066
static PyObject *
2067
frame_trace_get_impl(PyFrameObject *self)
2068
/*[clinic end generated code: output=5475cbfce07826cd input=e4eacf2c68cac577]*/
2069
0
{
2070
0
    PyObject* trace = self->f_trace;
2071
0
    if (trace == NULL) {
2072
0
        trace = Py_None;
2073
0
    }
2074
0
    return Py_NewRef(trace);
2075
0
}
2076
2077
/*[clinic input]
2078
@permit_long_summary
2079
@critical_section
2080
@setter
2081
@deleter
2082
frame.f_trace as frame_trace
2083
[clinic start generated code]*/
2084
2085
static int
2086
frame_trace_set_impl(PyFrameObject *self, PyObject *value)
2087
/*[clinic end generated code: output=d6fe08335cf76ae4 input=9fb7a5805196eae2]*/
2088
0
{
2089
0
    if (value == Py_None) {
2090
0
        value = NULL;
2091
0
    }
2092
0
    if (value != self->f_trace) {
2093
0
        Py_XSETREF(self->f_trace, Py_XNewRef(value));
2094
0
        if (value != NULL && self->f_trace_opcodes) {
2095
0
            return _PyEval_SetOpcodeTrace(self, true);
2096
0
        }
2097
0
    }
2098
0
    return 0;
2099
0
}
2100
2101
/*[clinic input]
2102
@permit_long_summary
2103
@critical_section
2104
@getter
2105
frame.f_generator as frame_generator
2106
2107
Return the generator or coroutine associated with this frame, or None.
2108
[clinic start generated code]*/
2109
2110
static PyObject *
2111
frame_generator_get_impl(PyFrameObject *self)
2112
/*[clinic end generated code: output=97aeb2392562e55b input=3ffba57ba10f84be]*/
2113
0
{
2114
0
    if (self->f_frame->owner == FRAME_OWNED_BY_GENERATOR) {
2115
0
        PyObject *gen = (PyObject *)_PyGen_GetGeneratorFromFrame(self->f_frame);
2116
0
        return Py_NewRef(gen);
2117
0
    }
2118
0
    Py_RETURN_NONE;
2119
0
}
2120
2121
2122
static PyGetSetDef frame_getsetlist[] = {
2123
    FRAME_F_BACK_GETSETDEF
2124
    FRAME_F_LOCALS_GETSETDEF
2125
    FRAME_F_LINENO_GETSETDEF
2126
    FRAME_F_TRACE_GETSETDEF
2127
    FRAME_F_LASTI_GETSETDEF
2128
    FRAME_F_GLOBALS_GETSETDEF
2129
    FRAME_F_BUILTINS_GETSETDEF
2130
    FRAME_F_CODE_GETSETDEF
2131
    FRAME_F_TRACE_OPCODES_GETSETDEF
2132
    FRAME_F_GENERATOR_GETSETDEF
2133
    {0}
2134
};
2135
2136
static void
2137
frame_dealloc(PyObject *op)
2138
56.1M
{
2139
    /* It is the responsibility of the owning generator/coroutine
2140
     * to have cleared the generator pointer */
2141
56.1M
    PyFrameObject *f = PyFrameObject_CAST(op);
2142
56.1M
    if (_PyObject_GC_IS_TRACKED(f)) {
2143
40.2M
        _PyObject_GC_UNTRACK(f);
2144
40.2M
    }
2145
2146
56.1M
    FT_CLEAR_WEAKREFS(op, f->f_weakreflist);
2147
2148
    /* GH-106092: If f->f_frame was on the stack and we reached the maximum
2149
     * nesting depth for deallocations, the trashcan may have delayed this
2150
     * deallocation until after f->f_frame is freed. Avoid dereferencing
2151
     * f->f_frame unless we know it still points to valid memory. */
2152
56.1M
    _PyInterpreterFrame *frame = (_PyInterpreterFrame *)f->_f_frame_data;
2153
2154
    /* Kill all local variables including specials, if we own them */
2155
56.1M
    if (f->f_frame == frame && frame->owner == FRAME_OWNED_BY_FRAME_OBJECT) {
2156
40.2M
        PyStackRef_CLEAR(frame->f_executable);
2157
40.2M
        PyStackRef_CLEAR(frame->f_funcobj);
2158
40.2M
        Py_CLEAR(frame->f_locals);
2159
40.2M
        _PyStackRef *locals = _PyFrame_GetLocalsArray(frame);
2160
40.2M
        _PyStackRef *sp = frame->stackpointer;
2161
219M
        while (sp > locals) {
2162
179M
            sp--;
2163
179M
            PyStackRef_CLEAR(*sp);
2164
179M
        }
2165
40.2M
    }
2166
56.1M
    Py_CLEAR(f->f_back);
2167
56.1M
    Py_CLEAR(f->f_trace);
2168
56.1M
    Py_CLEAR(f->f_extra_locals);
2169
56.1M
    Py_CLEAR(f->f_locals_cache);
2170
56.1M
    Py_CLEAR(f->f_overwritten_fast_locals);
2171
56.1M
    PyObject_GC_Del(f);
2172
56.1M
}
2173
2174
static int
2175
frame_traverse(PyObject *op, visitproc visit, void *arg)
2176
291k
{
2177
291k
    PyFrameObject *f = PyFrameObject_CAST(op);
2178
291k
    Py_VISIT(f->f_back);
2179
291k
    Py_VISIT(f->f_trace);
2180
291k
    Py_VISIT(f->f_extra_locals);
2181
291k
    Py_VISIT(f->f_locals_cache);
2182
291k
    Py_VISIT(f->f_overwritten_fast_locals);
2183
291k
    if (f->f_frame->owner != FRAME_OWNED_BY_FRAME_OBJECT) {
2184
0
        return 0;
2185
0
    }
2186
291k
    assert(f->f_frame->frame_obj == NULL);
2187
291k
    return _PyFrame_Traverse(f->f_frame, visit, arg);
2188
291k
}
2189
2190
static int
2191
frame_tp_clear(PyObject *op)
2192
0
{
2193
0
    PyFrameObject *f = PyFrameObject_CAST(op);
2194
0
    Py_CLEAR(f->f_trace);
2195
0
    Py_CLEAR(f->f_extra_locals);
2196
0
    Py_CLEAR(f->f_locals_cache);
2197
0
    Py_CLEAR(f->f_overwritten_fast_locals);
2198
2199
    /* locals and stack */
2200
0
    _PyStackRef *locals = _PyFrame_GetLocalsArray(f->f_frame);
2201
0
    _PyStackRef *sp = f->f_frame->stackpointer;
2202
0
    assert(sp >= locals);
2203
0
    while (sp > locals) {
2204
0
        sp--;
2205
0
        PyStackRef_CLEAR(*sp);
2206
0
    }
2207
0
    f->f_frame->stackpointer = locals;
2208
0
    Py_CLEAR(f->f_frame->f_locals);
2209
0
    return 0;
2210
0
}
2211
2212
/*[clinic input]
2213
@critical_section
2214
frame.clear
2215
2216
Clear all references held by the frame.
2217
[clinic start generated code]*/
2218
2219
static PyObject *
2220
frame_clear_impl(PyFrameObject *self)
2221
/*[clinic end generated code: output=864c662f16e9bfcc input=c358f9cff5f9b681]*/
2222
0
{
2223
0
    if (self->f_frame->owner == FRAME_OWNED_BY_GENERATOR) {
2224
0
        PyGenObject *gen = _PyGen_GetGeneratorFromFrame(self->f_frame);
2225
0
        if (_PyGen_ClearFrame(gen) < 0) {
2226
0
            return NULL;
2227
0
        }
2228
0
    }
2229
0
    else if (self->f_frame->owner == FRAME_OWNED_BY_THREAD) {
2230
0
        PyErr_SetString(PyExc_RuntimeError,
2231
0
                        "cannot clear an executing frame");
2232
0
        return NULL;
2233
0
    }
2234
0
    else {
2235
0
        assert(self->f_frame->owner == FRAME_OWNED_BY_FRAME_OBJECT);
2236
0
        (void)frame_tp_clear((PyObject *)self);
2237
0
    }
2238
0
    Py_RETURN_NONE;
2239
0
}
2240
2241
/*[clinic input]
2242
@critical_section
2243
frame.__sizeof__
2244
2245
Return the size of the frame in memory, in bytes.
2246
[clinic start generated code]*/
2247
2248
static PyObject *
2249
frame___sizeof___impl(PyFrameObject *self)
2250
/*[clinic end generated code: output=82948688e81078e2 input=908f90a83e73131d]*/
2251
0
{
2252
0
    Py_ssize_t res;
2253
0
    res = offsetof(PyFrameObject, _f_frame_data) + offsetof(_PyInterpreterFrame, localsplus);
2254
0
    PyCodeObject *code = _PyFrame_GetCode(self->f_frame);
2255
0
    res += _PyFrame_NumSlotsForCodeObject(code) * sizeof(PyObject *);
2256
0
    return PyLong_FromSsize_t(res);
2257
0
}
2258
2259
/*[clinic input]
2260
@critical_section
2261
frame.__repr__
2262
[clinic start generated code]*/
2263
2264
static PyObject *
2265
frame_repr_impl(PyFrameObject *self)
2266
/*[clinic end generated code: output=6dc361d24ba61076 input=cea0fd14e4749a55]*/
2267
0
{
2268
0
    int lineno = PyFrame_GetLineNumber(self);
2269
0
    PyCodeObject *code = _PyFrame_GetCode(self->f_frame);
2270
0
    return PyUnicode_FromFormat(
2271
0
        "<frame at %p, file %R, line %d, code %S>",
2272
0
        self, code->co_filename, lineno, code->co_name);
2273
0
}
2274
2275
static PyMethodDef frame_methods[] = {
2276
    FRAME_CLEAR_METHODDEF
2277
    FRAME___SIZEOF___METHODDEF
2278
    {NULL, NULL}  /* sentinel */
2279
};
2280
2281
PyTypeObject PyFrame_Type = {
2282
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
2283
    "frame",
2284
    offsetof(PyFrameObject, _f_frame_data) +
2285
    offsetof(_PyInterpreterFrame, localsplus),
2286
    sizeof(PyObject *),
2287
    frame_dealloc,                              /* tp_dealloc */
2288
    0,                                          /* tp_vectorcall_offset */
2289
    0,                                          /* tp_getattr */
2290
    0,                                          /* tp_setattr */
2291
    0,                                          /* tp_as_async */
2292
    frame_repr,                                 /* tp_repr */
2293
    0,                                          /* tp_as_number */
2294
    0,                                          /* tp_as_sequence */
2295
    0,                                          /* tp_as_mapping */
2296
    0,                                          /* tp_hash */
2297
    0,                                          /* tp_call */
2298
    0,                                          /* tp_str */
2299
    PyObject_GenericGetAttr,                    /* tp_getattro */
2300
    PyObject_GenericSetAttr,                    /* tp_setattro */
2301
    0,                                          /* tp_as_buffer */
2302
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2303
    0,                                          /* tp_doc */
2304
    frame_traverse,                             /* tp_traverse */
2305
    frame_tp_clear,                             /* tp_clear */
2306
    0,                                          /* tp_richcompare */
2307
    OFF(f_weakreflist),                         /* tp_weaklistoffset */
2308
    0,                                          /* tp_iter */
2309
    0,                                          /* tp_iternext */
2310
    frame_methods,                              /* tp_methods */
2311
    frame_memberlist,                           /* tp_members */
2312
    frame_getsetlist,                           /* tp_getset */
2313
    0,                                          /* tp_base */
2314
    0,                                          /* tp_dict */
2315
};
2316
2317
static void
2318
init_frame(PyThreadState *tstate, _PyInterpreterFrame *frame,
2319
           PyFunctionObject *func, PyObject *locals)
2320
1.13k
{
2321
1.13k
    PyCodeObject *code = (PyCodeObject *)func->func_code;
2322
1.13k
    _PyFrame_Initialize(tstate, frame, PyStackRef_FromPyObjectNew(func),
2323
1.13k
                        Py_XNewRef(locals), code, 0, NULL);
2324
1.13k
}
2325
2326
PyFrameObject*
2327
_PyFrame_New_NoTrack(PyCodeObject *code)
2328
56.1M
{
2329
56.1M
    CALL_STAT_INC(frame_objects_created);
2330
56.1M
    int slots = code->co_nlocalsplus + code->co_stacksize;
2331
56.1M
    PyFrameObject *f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type, slots);
2332
56.1M
    if (f == NULL) {
2333
0
        return NULL;
2334
0
    }
2335
56.1M
    f->f_back = NULL;
2336
56.1M
    f->f_trace = NULL;
2337
56.1M
    f->f_trace_lines = 1;
2338
56.1M
    f->f_trace_opcodes = 0;
2339
56.1M
    f->f_lineno = 0;
2340
56.1M
    f->f_extra_locals = NULL;
2341
56.1M
    f->f_locals_cache = NULL;
2342
56.1M
    f->f_overwritten_fast_locals = NULL;
2343
56.1M
    f->f_weakreflist = NULL;
2344
56.1M
    return f;
2345
56.1M
}
2346
2347
/* Legacy API */
2348
PyFrameObject*
2349
PyFrame_New(PyThreadState *tstate, PyCodeObject *code,
2350
            PyObject *globals, PyObject *locals)
2351
1.13k
{
2352
1.13k
    PyObject *builtins = _PyDict_LoadBuiltinsFromGlobals(globals);
2353
1.13k
    if (builtins == NULL) {
2354
0
        return NULL;
2355
0
    }
2356
1.13k
    PyFrameConstructor desc = {
2357
1.13k
        .fc_globals = globals,
2358
1.13k
        .fc_builtins = builtins,
2359
1.13k
        .fc_name = code->co_name,
2360
1.13k
        .fc_qualname = code->co_name,
2361
1.13k
        .fc_code = (PyObject *)code,
2362
1.13k
        .fc_defaults = NULL,
2363
1.13k
        .fc_kwdefaults = NULL,
2364
1.13k
        .fc_closure = NULL
2365
1.13k
    };
2366
1.13k
    PyFunctionObject *func = _PyFunction_FromConstructor(&desc);
2367
1.13k
    _Py_DECREF_BUILTINS(builtins);
2368
1.13k
    if (func == NULL) {
2369
0
        return NULL;
2370
0
    }
2371
1.13k
    PyFrameObject *f = _PyFrame_New_NoTrack(code);
2372
1.13k
    if (f == NULL) {
2373
0
        Py_DECREF(func);
2374
0
        return NULL;
2375
0
    }
2376
1.13k
    init_frame(tstate, (_PyInterpreterFrame *)f->_f_frame_data, func, locals);
2377
1.13k
    f->f_frame = (_PyInterpreterFrame *)f->_f_frame_data;
2378
1.13k
    f->f_frame->owner = FRAME_OWNED_BY_FRAME_OBJECT;
2379
    // This frame needs to be "complete", so pretend that the first RESUME ran:
2380
1.13k
    f->f_frame->instr_ptr = _PyCode_CODE(code) + code->_co_firsttraceable + 1;
2381
1.13k
    assert(!_PyFrame_IsIncomplete(f->f_frame));
2382
1.13k
    Py_DECREF(func);
2383
1.13k
    _PyObject_GC_TRACK(f);
2384
1.13k
    return f;
2385
1.13k
}
2386
2387
// Initialize frame free variables if needed
2388
static void
2389
frame_init_get_vars(_PyInterpreterFrame *frame)
2390
0
{
2391
    // COPY_FREE_VARS has no quickened forms, so no need to use _PyOpcode_Deopt
2392
    // here:
2393
0
    PyCodeObject *co = _PyFrame_GetCode(frame);
2394
0
    int lasti = _PyInterpreterFrame_LASTI(frame);
2395
0
    if (!(lasti < 0
2396
0
          && _PyFrame_GetBytecode(frame)->op.code == COPY_FREE_VARS
2397
0
          && PyStackRef_FunctionCheck(frame->f_funcobj)))
2398
0
    {
2399
        /* Free vars are initialized */
2400
0
        return;
2401
0
    }
2402
2403
    /* Free vars have not been initialized -- Do that */
2404
0
    PyFunctionObject *func = _PyFrame_GetFunction(frame);
2405
0
    PyObject *closure = func->func_closure;
2406
0
    int offset = PyUnstable_Code_GetFirstFree(co);
2407
0
    for (int i = 0; i < co->co_nfreevars; ++i) {
2408
0
        PyObject *o = PyTuple_GET_ITEM(closure, i);
2409
0
        frame->localsplus[offset + i] = PyStackRef_FromPyObjectNew(o);
2410
0
    }
2411
    // COPY_FREE_VARS doesn't have inline CACHEs, either:
2412
0
    frame->instr_ptr = _PyFrame_GetBytecode(frame);
2413
0
}
2414
2415
2416
static int
2417
frame_get_var(_PyInterpreterFrame *frame, PyCodeObject *co, int i,
2418
              PyObject **pvalue)
2419
0
{
2420
0
    _PyLocals_Kind kind = _PyLocals_GetKind(co->co_localspluskinds, i);
2421
2422
    /* If the namespace is unoptimized, then one of the
2423
       following cases applies:
2424
       1. It does not contain free variables, because it
2425
          uses import * or is a top-level namespace.
2426
       2. It is a class namespace.
2427
       We don't want to accidentally copy free variables
2428
       into the locals dict used by the class.
2429
    */
2430
0
    if (kind & CO_FAST_FREE && !(co->co_flags & CO_OPTIMIZED)) {
2431
0
        return 0;
2432
0
    }
2433
2434
0
    PyObject *value = NULL;
2435
0
    if (frame->stackpointer == NULL || frame->stackpointer > frame->localsplus + i) {
2436
0
        value = PyStackRef_AsPyObjectBorrow(frame->localsplus[i]);
2437
0
        if (kind & CO_FAST_FREE) {
2438
            // The cell was set by COPY_FREE_VARS.
2439
0
            assert(value != NULL && PyCell_Check(value));
2440
0
            value = PyCell_GetRef((PyCellObject *)value);
2441
0
        }
2442
0
        else if (kind & CO_FAST_CELL) {
2443
0
            if (value != NULL) {
2444
0
                if (PyCell_Check(value)) {
2445
0
                    assert(!_PyFrame_IsIncomplete(frame));
2446
0
                    value = PyCell_GetRef((PyCellObject *)value);
2447
0
                }
2448
0
                else {
2449
                    // (likely) Otherwise it is an arg (kind & CO_FAST_LOCAL),
2450
                    // with the initial value set when the frame was created...
2451
                    // (unlikely) ...or it was set via the f_locals proxy.
2452
0
                    Py_INCREF(value);
2453
0
                }
2454
0
            }
2455
0
        }
2456
0
        else {
2457
0
            Py_XINCREF(value);
2458
0
        }
2459
0
    }
2460
0
    *pvalue = value;
2461
0
    return 1;
2462
0
}
2463
2464
2465
int
2466
PyUnstable_InterpreterFrame_GetLocal(_PyInterpreterFrame *frame,
2467
                                     Py_ssize_t index, PyObject **result)
2468
0
{
2469
0
    PyCodeObject *co = _PyFrame_GetCode(frame);
2470
0
    *result = NULL;
2471
0
    if (index < 0 || index >= co->co_nlocalsplus) {
2472
0
        PyErr_Format(
2473
0
            PyExc_IndexError,
2474
0
            "PyUnstable_InterpreterFrame_GetLocal: index %zd out of range [0, %d)",
2475
0
            index, co->co_nlocalsplus);
2476
0
        return -1;
2477
0
    }
2478
2479
0
    int offset = PyUnstable_Code_GetFirstFree(co);  // co_nlocalsplus - co_nfreevars
2480
0
    if (index < offset) {
2481
        // Local or cell variable. frame_get_var unboxes cells and copes with
2482
        // not-yet-started frames and arguments not yet promoted by MAKE_CELL.
2483
0
        if (_PyLocals_GetKind(co->co_localspluskinds, (int)index) & CO_FAST_HIDDEN) {
2484
0
            return 0;
2485
0
        }
2486
0
        PyObject *value = NULL;
2487
0
        frame_get_var(frame, co, (int)index, &value);
2488
0
        if (value == NULL) {
2489
0
            return 0;
2490
0
        }
2491
0
        *result = value;  // strong reference
2492
0
        return 1;
2493
0
    }
2494
2495
    // Free variable: read from the function closure rather than localsplus.
2496
0
    if ((co->co_flags & CO_OPTIMIZED)
2497
0
         && PyStackRef_FunctionCheck(frame->f_funcobj))
2498
0
    {
2499
0
        PyFunctionObject *func = _PyFrame_GetFunction(frame);
2500
0
        PyObject *cell = PyTuple_GET_ITEM(func->func_closure, index - offset);
2501
0
        PyObject *value = PyCell_GetRef((PyCellObject *)cell);
2502
0
        if (value == NULL) {
2503
0
            return 0;
2504
0
        }
2505
0
        *result = value;
2506
0
        return 1;
2507
0
    }
2508
0
    return 0;
2509
0
}
2510
2511
2512
bool
2513
_PyFrame_HasHiddenLocals(_PyInterpreterFrame *frame)
2514
411
{
2515
    /*
2516
     * This function returns if there are hidden locals introduced by PEP 709,
2517
     * which are the isolated fast locals for inline comprehensions
2518
     */
2519
411
    PyCodeObject* co = _PyFrame_GetCode(frame);
2520
2521
482
    for (int i = 0; i < co->co_nlocalsplus; i++) {
2522
71
        _PyLocals_Kind kind = _PyLocals_GetKind(co->co_localspluskinds, i);
2523
2524
71
        if (kind & CO_FAST_HIDDEN) {
2525
71
            if (framelocalsproxy_hasval(frame, co, i)) {
2526
0
                return true;
2527
0
            }
2528
71
        }
2529
71
    }
2530
2531
411
    return false;
2532
411
}
2533
2534
2535
PyObject *
2536
_PyFrame_GetLocals(_PyInterpreterFrame *frame)
2537
419
{
2538
    // We should try to avoid creating the FrameObject if possible.
2539
    // So we check if the frame is a module or class level scope
2540
419
    PyCodeObject *co = _PyFrame_GetCode(frame);
2541
2542
419
    if (!(co->co_flags & CO_OPTIMIZED) && !_PyFrame_HasHiddenLocals(frame)) {
2543
411
        if (frame->f_locals == NULL) {
2544
            // We found cases when f_locals is NULL for non-optimized code.
2545
            // We fill the f_locals with an empty dict to avoid crash until
2546
            // we find the root cause.
2547
0
            frame->f_locals = PyDict_New();
2548
0
            if (frame->f_locals == NULL) {
2549
0
                return NULL;
2550
0
            }
2551
0
        }
2552
411
        return Py_NewRef(frame->f_locals);
2553
411
    }
2554
2555
8
    PyFrameObject* f = _PyFrame_GetFrameObject(frame);
2556
8
    if (f == NULL) {
2557
0
        return NULL;
2558
0
    }
2559
2560
8
    return _PyFrameLocalsProxy_New(f);
2561
8
}
2562
2563
2564
// Returns 1 if `name` is a bound fast local, storing its value in `*pvalue`.
2565
static int
2566
frame_getvar_lock_held(PyFrameObject *frame_obj, PyObject *name,
2567
                       PyObject **pvalue)
2568
0
{
2569
0
    _PyInterpreterFrame *frame = frame_obj->f_frame;
2570
0
    frame_init_get_vars(frame);
2571
2572
0
    PyCodeObject *co = _PyFrame_GetCode(frame);
2573
0
    for (int i = 0; i < co->co_nlocalsplus; i++) {
2574
0
        PyObject *var_name = PyTuple_GET_ITEM(co->co_localsplusnames, i);
2575
0
        if (!_PyUnicode_Equal(var_name, name)) {
2576
0
            continue;
2577
0
        }
2578
0
        if (!frame_get_var(frame, co, i, pvalue)) {
2579
0
            return 0;
2580
0
        }
2581
0
        return *pvalue != NULL;
2582
0
    }
2583
0
    return 0;
2584
0
}
2585
2586
PyObject *
2587
PyFrame_GetVar(PyFrameObject *frame_obj, PyObject *name)
2588
0
{
2589
0
    if (!PyUnicode_Check(name)) {
2590
0
        PyErr_Format(PyExc_TypeError, "name must be str, not %s",
2591
0
                     Py_TYPE(name)->tp_name);
2592
0
        return NULL;
2593
0
    }
2594
2595
0
    PyObject *value = NULL;
2596
0
    int found;
2597
0
    FRAMELOCALSPROXY_LOCKED(frame_obj,
2598
0
        frame_getvar_lock_held(frame_obj, name, &value), found);
2599
0
    if (found) {
2600
0
        return value;
2601
0
    }
2602
0
    PyErr_Format(PyExc_NameError, "variable %R does not exist", name);
2603
0
    return NULL;
2604
0
}
2605
2606
2607
PyObject *
2608
PyFrame_GetVarString(PyFrameObject *frame, const char *name)
2609
0
{
2610
0
    PyObject *name_obj = PyUnicode_FromString(name);
2611
0
    if (name_obj == NULL) {
2612
0
        return NULL;
2613
0
    }
2614
0
    PyObject *value = PyFrame_GetVar(frame, name_obj);
2615
0
    Py_DECREF(name_obj);
2616
0
    return value;
2617
0
}
2618
2619
2620
int
2621
PyFrame_FastToLocalsWithError(PyFrameObject *f)
2622
0
{
2623
    // Nothing to do here, as f_locals is now a write-through proxy in
2624
    // optimized frames. Soft-deprecated, since there's no maintenance hassle.
2625
0
    return 0;
2626
0
}
2627
2628
void
2629
PyFrame_FastToLocals(PyFrameObject *f)
2630
0
{
2631
    // Nothing to do here, as f_locals is now a write-through proxy in
2632
    // optimized frames. Soft-deprecated, since there's no maintenance hassle.
2633
0
    return;
2634
0
}
2635
2636
void
2637
PyFrame_LocalsToFast(PyFrameObject *f, int clear)
2638
0
{
2639
    // Nothing to do here, as f_locals is now a write-through proxy in
2640
    // optimized frames. Soft-deprecated, since there's no maintenance hassle.
2641
0
    return;
2642
0
}
2643
2644
int
2645
_PyFrame_IsEntryFrame(PyFrameObject *frame)
2646
0
{
2647
0
    assert(frame != NULL);
2648
0
    _PyInterpreterFrame *f = frame->f_frame;
2649
0
    assert(!_PyFrame_IsIncomplete(f));
2650
0
    return f->previous && f->previous->owner == FRAME_OWNED_BY_INTERPRETER;
2651
0
}
2652
2653
PyCodeObject *
2654
PyFrame_GetCode(PyFrameObject *frame)
2655
23.7M
{
2656
23.7M
    assert(frame != NULL);
2657
23.7M
    PyObject *code;
2658
23.7M
    Py_BEGIN_CRITICAL_SECTION(frame);
2659
23.7M
    assert(!_PyFrame_IsIncomplete(frame->f_frame));
2660
23.7M
    code = Py_NewRef(_PyFrame_GetCode(frame->f_frame));
2661
23.7M
    Py_END_CRITICAL_SECTION();
2662
23.7M
    return (PyCodeObject *)code;
2663
23.7M
}
2664
2665
2666
PyFrameObject*
2667
PyFrame_GetBack(PyFrameObject *frame)
2668
22.8M
{
2669
22.8M
    assert(frame != NULL);
2670
22.8M
    assert(!_PyFrame_IsIncomplete(frame->f_frame));
2671
22.8M
    PyFrameObject *back = frame->f_back;
2672
22.8M
    if (back == NULL) {
2673
22.8M
        _PyInterpreterFrame *prev = frame->f_frame->previous;
2674
22.8M
        prev = _PyFrame_GetFirstComplete(prev);
2675
22.8M
        if (prev) {
2676
22.8M
            back = _PyFrame_GetFrameObject(prev);
2677
22.8M
            if (back == NULL) {
2678
0
                return NULL;
2679
0
            }
2680
22.8M
        }
2681
22.8M
    }
2682
22.8M
    return (PyFrameObject*)Py_XNewRef(back);
2683
22.8M
}
2684
2685
PyObject*
2686
PyFrame_GetLocals(PyFrameObject *frame)
2687
0
{
2688
0
    assert(!_PyFrame_IsIncomplete(frame->f_frame));
2689
0
    return frame_locals_get((PyObject *)frame, NULL);
2690
0
}
2691
2692
PyObject*
2693
PyFrame_GetGlobals(PyFrameObject *frame)
2694
0
{
2695
0
    assert(!_PyFrame_IsIncomplete(frame->f_frame));
2696
0
    return frame_globals_get((PyObject *)frame, NULL);
2697
0
}
2698
2699
PyObject*
2700
PyFrame_GetBuiltins(PyFrameObject *frame)
2701
0
{
2702
0
    assert(!_PyFrame_IsIncomplete(frame->f_frame));
2703
0
    return frame_builtins_get((PyObject *)frame, NULL);
2704
0
}
2705
2706
int
2707
PyFrame_GetLasti(PyFrameObject *frame)
2708
0
{
2709
0
    int ret;
2710
0
    Py_BEGIN_CRITICAL_SECTION(frame);
2711
0
    assert(!_PyFrame_IsIncomplete(frame->f_frame));
2712
0
    int lasti = _PyInterpreterFrame_LASTI(frame->f_frame);
2713
0
    ret = lasti < 0 ? -1 : lasti * (int)sizeof(_Py_CODEUNIT);
2714
0
    Py_END_CRITICAL_SECTION();
2715
0
    return ret;
2716
0
}
2717
2718
PyObject *
2719
PyFrame_GetGenerator(PyFrameObject *frame)
2720
0
{
2721
0
    assert(!_PyFrame_IsIncomplete(frame->f_frame));
2722
    return frame_generator_get((PyObject *)frame, NULL);
2723
0
}