Coverage Report

Created: 2025-11-24 06:11

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