Coverage Report

Created: 2026-06-21 06:15

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Python/assemble.c
Line
Count
Source
1
#include "Python.h"
2
#include "pycore_code.h"            // write_location_entry_start()
3
#include "pycore_compile.h"
4
#include "pycore_instruction_sequence.h"
5
#include "pycore_opcode_utils.h"    // IS_BACKWARDS_JUMP_OPCODE
6
#include "pycore_opcode_metadata.h" // is_pseudo_target, _PyOpcode_Caches
7
#include "pycore_symtable.h"        // _Py_SourceLocation
8
9
#include <stdbool.h>
10
11
4.22k
#define DEFAULT_CODE_SIZE 128
12
4.22k
#define DEFAULT_LNOTAB_SIZE 16
13
4.22k
#define DEFAULT_CNOTAB_SIZE 32
14
15
#undef SUCCESS
16
#undef ERROR
17
303k
#define SUCCESS 0
18
4.22k
#define ERROR -1
19
20
#define RETURN_IF_ERROR(X)  \
21
337k
    if ((X) < 0) {          \
22
0
        return ERROR;       \
23
0
    }
24
25
typedef _Py_SourceLocation location;
26
typedef _PyInstruction instruction;
27
typedef _PyInstructionSequence instr_sequence;
28
29
static inline bool
30
same_location(location a, location b)
31
301k
{
32
301k
    return a.lineno == b.lineno &&
33
108k
           a.end_lineno == b.end_lineno &&
34
105k
           a.col_offset == b.col_offset &&
35
62.7k
           a.end_col_offset == b.end_col_offset;
36
301k
}
37
38
static int
39
instr_size(instruction *instr)
40
796k
{
41
796k
    int opcode = instr->i_opcode;
42
796k
    int oparg = instr->i_oparg;
43
796k
    assert(!IS_PSEUDO_INSTR(opcode));
44
796k
    assert(OPCODE_HAS_ARG(opcode) || oparg == 0);
45
796k
    int extended_args = (0xFFFFFF < oparg) + (0xFFFF < oparg) + (0xFF < oparg);
46
796k
    int caches = _PyOpcode_Caches[opcode];
47
796k
    return extended_args + 1 + caches;
48
796k
}
49
50
struct assembler {
51
    PyObject *a_bytecode;  /* bytes containing bytecode */
52
    int a_offset;              /* offset into bytecode */
53
    PyObject *a_except_table;  /* bytes containing exception table */
54
    int a_except_table_off;    /* offset into exception table */
55
    /* Location Info */
56
    int a_lineno;          /* lineno of last emitted instruction */
57
    PyObject* a_linetable; /* bytes containing location info */
58
    int a_location_off;    /* offset of last written location info frame */
59
};
60
61
static int
62
assemble_init(struct assembler *a, int firstlineno)
63
4.22k
{
64
4.22k
    memset(a, 0, sizeof(struct assembler));
65
4.22k
    a->a_lineno = firstlineno;
66
4.22k
    a->a_linetable = NULL;
67
4.22k
    a->a_location_off = 0;
68
4.22k
    a->a_except_table = NULL;
69
4.22k
    a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
70
4.22k
    if (a->a_bytecode == NULL) {
71
0
        goto error;
72
0
    }
73
4.22k
    a->a_linetable = PyBytes_FromStringAndSize(NULL, DEFAULT_CNOTAB_SIZE);
74
4.22k
    if (a->a_linetable == NULL) {
75
0
        goto error;
76
0
    }
77
4.22k
    a->a_except_table = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
78
4.22k
    if (a->a_except_table == NULL) {
79
0
        goto error;
80
0
    }
81
4.22k
    return SUCCESS;
82
0
error:
83
0
    Py_CLEAR(a->a_bytecode);
84
0
    Py_CLEAR(a->a_linetable);
85
0
    Py_CLEAR(a->a_except_table);
86
0
    return ERROR;
87
4.22k
}
88
89
static void
90
assemble_free(struct assembler *a)
91
4.22k
{
92
4.22k
    Py_XDECREF(a->a_bytecode);
93
4.22k
    Py_XDECREF(a->a_linetable);
94
4.22k
    Py_XDECREF(a->a_except_table);
95
4.22k
}
96
97
static inline void
98
10.3k
write_except_byte(struct assembler *a, int byte) {
99
10.3k
    unsigned char *p = (unsigned char *) PyBytes_AS_STRING(a->a_except_table);
100
10.3k
    p[a->a_except_table_off++] = byte;
101
10.3k
}
102
103
3.02k
#define CONTINUATION_BIT 64
104
105
static void
106
assemble_emit_exception_table_item(struct assembler *a, int value, int msb)
107
7.28k
{
108
7.28k
    assert ((msb | 128) == 128);
109
7.28k
    assert(value >= 0 && value < (1 << 30));
110
7.28k
    if (value >= 1 << 24) {
111
0
        write_except_byte(a, (value >> 24) | CONTINUATION_BIT | msb);
112
0
        msb = 0;
113
0
    }
114
7.28k
    if (value >= 1 << 18) {
115
0
        write_except_byte(a, ((value >> 18)&0x3f) | CONTINUATION_BIT | msb);
116
0
        msb = 0;
117
0
    }
118
7.28k
    if (value >= 1 << 12) {
119
0
        write_except_byte(a, ((value >> 12)&0x3f) | CONTINUATION_BIT | msb);
120
0
        msb = 0;
121
0
    }
122
7.28k
    if (value >= 1 << 6) {
123
3.02k
        write_except_byte(a, ((value >> 6)&0x3f) | CONTINUATION_BIT | msb);
124
3.02k
        msb = 0;
125
3.02k
    }
126
7.28k
    write_except_byte(a, (value&0x3f) | msb);
127
7.28k
}
128
129
/* See InternalDocs/exception_handling.md for details of layout */
130
1.82k
#define MAX_SIZE_OF_ENTRY 20
131
132
static int
133
assemble_emit_exception_table_entry(struct assembler *a, int start, int end,
134
                                    int handler_offset,
135
                                    _PyExceptHandlerInfo *handler)
136
1.82k
{
137
1.82k
    Py_ssize_t len = PyBytes_GET_SIZE(a->a_except_table);
138
1.82k
    if (a->a_except_table_off + MAX_SIZE_OF_ENTRY >= len) {
139
577
        RETURN_IF_ERROR(_PyBytes_Resize(&a->a_except_table, len * 2));
140
577
    }
141
1.82k
    int size = end-start;
142
1.82k
    assert(end > start);
143
1.82k
    int target = handler_offset;
144
1.82k
    int depth = handler->h_startdepth - 1;
145
1.82k
    if (handler->h_preserve_lasti > 0) {
146
1.35k
        depth -= 1;
147
1.35k
    }
148
1.82k
    assert(depth >= 0);
149
1.82k
    int depth_lasti = (depth<<1) | handler->h_preserve_lasti;
150
1.82k
    assemble_emit_exception_table_item(a, start, (1<<7));
151
1.82k
    assemble_emit_exception_table_item(a, size, 0);
152
1.82k
    assemble_emit_exception_table_item(a, target, 0);
153
1.82k
    assemble_emit_exception_table_item(a, depth_lasti, 0);
154
1.82k
    return SUCCESS;
155
1.82k
}
156
157
static int
158
assemble_exception_table(struct assembler *a, instr_sequence *instrs)
159
4.22k
{
160
4.22k
    int ioffset = 0;
161
4.22k
    _PyExceptHandlerInfo handler;
162
4.22k
    handler.h_label = -1;
163
4.22k
    handler.h_startdepth = -1;
164
4.22k
    handler.h_preserve_lasti = -1;
165
4.22k
    int start = -1;
166
155k
    for (int i = 0; i < instrs->s_used; i++) {
167
150k
        instruction *instr = &instrs->s_instrs[i];
168
150k
        if (instr->i_except_handler_info.h_label != handler.h_label) {
169
3.27k
            if (handler.h_label >= 0) {
170
1.82k
                int handler_offset = instrs->s_instrs[handler.h_label].i_offset;
171
1.82k
                RETURN_IF_ERROR(
172
1.82k
                    assemble_emit_exception_table_entry(a, start, ioffset,
173
1.82k
                                                        handler_offset,
174
1.82k
                                                        &handler));
175
1.82k
            }
176
3.27k
            start = ioffset;
177
3.27k
            handler = instr->i_except_handler_info;
178
3.27k
        }
179
150k
        ioffset += instr_size(instr);
180
150k
    }
181
4.22k
    if (handler.h_label >= 0) {
182
0
        int handler_offset = instrs->s_instrs[handler.h_label].i_offset;
183
0
        RETURN_IF_ERROR(assemble_emit_exception_table_entry(a, start, ioffset,
184
0
                                                            handler_offset,
185
0
                                                            &handler));
186
0
    }
187
4.22k
    return SUCCESS;
188
4.22k
}
189
190
191
/* Code location emitting code. See locations.md for a description of the format. */
192
193
#define MSB 0x80
194
195
static void
196
write_location_byte(struct assembler* a, int val)
197
114k
{
198
114k
    PyBytes_AS_STRING(a->a_linetable)[a->a_location_off] = val&255;
199
114k
    a->a_location_off++;
200
114k
}
201
202
203
static uint8_t *
204
location_pointer(struct assembler* a)
205
248k
{
206
248k
    return (uint8_t *)PyBytes_AS_STRING(a->a_linetable) +
207
248k
        a->a_location_off;
208
248k
}
209
210
static void
211
write_location_first_byte(struct assembler* a, int code, int length)
212
114k
{
213
114k
    a->a_location_off += write_location_entry_start(
214
114k
        location_pointer(a), code, length);
215
114k
}
216
217
static void
218
write_location_varint(struct assembler* a, unsigned int val)
219
100k
{
220
100k
    uint8_t *ptr = location_pointer(a);
221
100k
    a->a_location_off += write_varint(ptr, val);
222
100k
}
223
224
225
static void
226
write_location_signed_varint(struct assembler* a, int val)
227
33.6k
{
228
33.6k
    uint8_t *ptr = location_pointer(a);
229
33.6k
    a->a_location_off += write_signed_varint(ptr, val);
230
33.6k
}
231
232
static void
233
write_location_info_short_form(struct assembler* a, int length, int column, int end_column)
234
42.8k
{
235
42.8k
    assert(length > 0 &&  length <= 8);
236
42.8k
    int column_low_bits = column & 7;
237
42.8k
    int column_group = column >> 3;
238
42.8k
    assert(column < 80);
239
42.8k
    assert(end_column >= column);
240
42.8k
    assert(end_column - column < 16);
241
42.8k
    write_location_first_byte(a, PY_CODE_LOCATION_INFO_SHORT0 + column_group, length);
242
42.8k
    write_location_byte(a, (column_low_bits << 4) | (end_column - column));
243
42.8k
}
244
245
static void
246
write_location_info_oneline_form(struct assembler* a, int length, int line_delta, int column, int end_column)
247
35.9k
{
248
35.9k
    assert(length > 0 &&  length <= 8);
249
35.9k
    assert(line_delta >= 0 && line_delta < 3);
250
35.9k
    assert(column < 128);
251
35.9k
    assert(end_column < 128);
252
35.9k
    write_location_first_byte(a, PY_CODE_LOCATION_INFO_ONE_LINE0 + line_delta, length);
253
35.9k
    write_location_byte(a, column);
254
35.9k
    write_location_byte(a, end_column);
255
35.9k
}
256
257
static void
258
write_location_info_long_form(struct assembler* a, location loc, int length)
259
33.5k
{
260
33.5k
    assert(length > 0 &&  length <= 8);
261
33.5k
    write_location_first_byte(a, PY_CODE_LOCATION_INFO_LONG, length);
262
33.5k
    write_location_signed_varint(a, loc.lineno - a->a_lineno);
263
33.5k
    assert(loc.end_lineno >= loc.lineno);
264
33.5k
    write_location_varint(a, loc.end_lineno - loc.lineno);
265
33.5k
    write_location_varint(a, loc.col_offset + 1);
266
33.5k
    write_location_varint(a, loc.end_col_offset + 1);
267
33.5k
}
268
269
static void
270
write_location_info_none(struct assembler* a, int length)
271
1.84k
{
272
1.84k
    write_location_first_byte(a, PY_CODE_LOCATION_INFO_NONE, length);
273
1.84k
}
274
275
static void
276
write_location_info_no_column(struct assembler* a, int length, int line_delta)
277
92
{
278
92
    write_location_first_byte(a, PY_CODE_LOCATION_INFO_NO_COLUMNS, length);
279
92
    write_location_signed_varint(a, line_delta);
280
92
}
281
282
114k
#define THEORETICAL_MAX_ENTRY_SIZE 25 /* 1 + 6 + 6 + 6 + 6 */
283
284
285
static int
286
write_location_info_entry(struct assembler* a, location loc, int isize)
287
114k
{
288
114k
    Py_ssize_t len = PyBytes_GET_SIZE(a->a_linetable);
289
114k
    if (a->a_location_off + THEORETICAL_MAX_ENTRY_SIZE >= len) {
290
6.30k
        assert(len > THEORETICAL_MAX_ENTRY_SIZE);
291
6.30k
        RETURN_IF_ERROR(_PyBytes_Resize(&a->a_linetable, len*2));
292
6.30k
    }
293
114k
    if (loc.lineno == NO_LOCATION.lineno) {
294
1.84k
        write_location_info_none(a, isize);
295
1.84k
        return SUCCESS;
296
1.84k
    }
297
112k
    int line_delta = loc.lineno - a->a_lineno;
298
112k
    int column = loc.col_offset;
299
112k
    int end_column = loc.end_col_offset;
300
112k
    if (column < 0 || end_column < 0) {
301
92
        if (loc.end_lineno == loc.lineno || loc.end_lineno < 0) {
302
92
            write_location_info_no_column(a, isize, line_delta);
303
92
            a->a_lineno = loc.lineno;
304
92
            return SUCCESS;
305
92
        }
306
92
    }
307
112k
    else if (loc.end_lineno == loc.lineno) {
308
95.8k
        if (line_delta == 0 && column < 80 && end_column - column < 16 && end_column >= column) {
309
42.8k
            write_location_info_short_form(a, isize, column, end_column);
310
42.8k
            return SUCCESS;
311
42.8k
        }
312
53.0k
        if (line_delta >= 0 && line_delta < 3 && column < 128 && end_column < 128) {
313
35.9k
            write_location_info_oneline_form(a, isize, line_delta, column, end_column);
314
35.9k
            a->a_lineno = loc.lineno;
315
35.9k
            return SUCCESS;
316
35.9k
        }
317
53.0k
    }
318
33.5k
    write_location_info_long_form(a, loc, isize);
319
33.5k
    a->a_lineno = loc.lineno;
320
33.5k
    return SUCCESS;
321
112k
}
322
323
static int
324
assemble_emit_location(struct assembler* a, location loc, int isize)
325
104k
{
326
104k
    if (isize == 0) {
327
3.02k
        return SUCCESS;
328
3.02k
    }
329
114k
    while (isize > 8) {
330
12.6k
        RETURN_IF_ERROR(write_location_info_entry(a, loc, 8));
331
12.6k
        isize -= 8;
332
12.6k
    }
333
101k
    return write_location_info_entry(a, loc, isize);
334
101k
}
335
336
static int
337
assemble_location_info(struct assembler *a, instr_sequence *instrs,
338
                       int firstlineno)
339
4.22k
{
340
4.22k
    a->a_lineno = firstlineno;
341
4.22k
    location loc = NO_LOCATION;
342
155k
    for (int i = instrs->s_used-1; i >= 0; i--) {
343
150k
        instruction *instr = &instrs->s_instrs[i];
344
150k
        if (same_location(instr->i_loc, NEXT_LOCATION)) {
345
0
            if (IS_TERMINATOR_OPCODE(instr->i_opcode)) {
346
0
                instr->i_loc = NO_LOCATION;
347
0
            }
348
0
            else {
349
0
                assert(i < instrs->s_used-1);
350
0
                instr->i_loc = instr[1].i_loc;
351
0
            }
352
0
        }
353
150k
    }
354
4.22k
    int size = 0;
355
155k
    for (int i = 0; i < instrs->s_used; i++) {
356
150k
        instruction *instr = &instrs->s_instrs[i];
357
150k
        if (!same_location(loc, instr->i_loc)) {
358
100k
                RETURN_IF_ERROR(assemble_emit_location(a, loc, size));
359
100k
                loc = instr->i_loc;
360
100k
                size = 0;
361
100k
        }
362
150k
        size += instr_size(instr);
363
150k
    }
364
4.22k
    RETURN_IF_ERROR(assemble_emit_location(a, loc, size));
365
4.22k
    return SUCCESS;
366
4.22k
}
367
368
static void
369
write_instr(_Py_CODEUNIT *codestr, instruction *instr, int ilen)
370
150k
{
371
150k
    int opcode = instr->i_opcode;
372
150k
    assert(!IS_PSEUDO_INSTR(opcode));
373
150k
    int oparg = instr->i_oparg;
374
150k
    assert(OPCODE_HAS_ARG(opcode) || oparg == 0);
375
150k
    int caches = _PyOpcode_Caches[opcode];
376
150k
    switch (ilen - caches) {
377
0
        case 4:
378
0
            codestr->op.code = EXTENDED_ARG;
379
0
            codestr->op.arg = (oparg >> 24) & 0xFF;
380
0
            codestr++;
381
0
            _Py_FALLTHROUGH;
382
0
        case 3:
383
0
            codestr->op.code = EXTENDED_ARG;
384
0
            codestr->op.arg = (oparg >> 16) & 0xFF;
385
0
            codestr++;
386
0
            _Py_FALLTHROUGH;
387
262
        case 2:
388
262
            codestr->op.code = EXTENDED_ARG;
389
262
            codestr->op.arg = (oparg >> 8) & 0xFF;
390
262
            codestr++;
391
262
            _Py_FALLTHROUGH;
392
150k
        case 1:
393
150k
            codestr->op.code = opcode;
394
150k
            codestr->op.arg = oparg & 0xFF;
395
150k
            codestr++;
396
150k
            break;
397
0
        default:
398
0
            Py_UNREACHABLE();
399
150k
    }
400
314k
    while (caches--) {
401
163k
        codestr->op.code = CACHE;
402
163k
        codestr->op.arg = 0;
403
163k
        codestr++;
404
163k
    }
405
150k
}
406
407
/* assemble_emit_instr()
408
   Extend the bytecode with a new instruction.
409
   Update lnotab if necessary.
410
*/
411
412
static int
413
assemble_emit_instr(struct assembler *a, instruction *instr)
414
150k
{
415
150k
    Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
416
150k
    _Py_CODEUNIT *code;
417
418
150k
    int size = instr_size(instr);
419
150k
    if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
420
2.13k
        if (len > PY_SSIZE_T_MAX / 2) {
421
0
            PyErr_NoMemory();
422
0
            return ERROR;
423
0
        }
424
2.13k
        RETURN_IF_ERROR(_PyBytes_Resize(&a->a_bytecode, len * 2));
425
2.13k
    }
426
150k
    code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
427
150k
    a->a_offset += size;
428
150k
    write_instr(code, instr, size);
429
150k
    return SUCCESS;
430
150k
}
431
432
static int
433
assemble_emit(struct assembler *a, instr_sequence *instrs,
434
              int first_lineno, PyObject *const_cache)
435
4.22k
{
436
4.22k
    RETURN_IF_ERROR(assemble_init(a, first_lineno));
437
438
155k
    for (int i = 0; i < instrs->s_used; i++) {
439
150k
        instruction *instr = &instrs->s_instrs[i];
440
150k
        RETURN_IF_ERROR(assemble_emit_instr(a, instr));
441
150k
    }
442
443
4.22k
    RETURN_IF_ERROR(assemble_location_info(a, instrs, a->a_lineno));
444
445
4.22k
    RETURN_IF_ERROR(assemble_exception_table(a, instrs));
446
447
4.22k
    RETURN_IF_ERROR(_PyBytes_Resize(&a->a_except_table, a->a_except_table_off));
448
4.22k
    RETURN_IF_ERROR(_PyCompile_ConstCacheMergeOne(const_cache, &a->a_except_table));
449
450
4.22k
    RETURN_IF_ERROR(_PyBytes_Resize(&a->a_linetable, a->a_location_off));
451
4.22k
    RETURN_IF_ERROR(_PyCompile_ConstCacheMergeOne(const_cache, &a->a_linetable));
452
453
4.22k
    RETURN_IF_ERROR(_PyBytes_Resize(&a->a_bytecode, a->a_offset * sizeof(_Py_CODEUNIT)));
454
4.22k
    RETURN_IF_ERROR(_PyCompile_ConstCacheMergeOne(const_cache, &a->a_bytecode));
455
4.22k
    return SUCCESS;
456
4.22k
}
457
458
static PyObject *
459
dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
460
4.22k
{
461
4.22k
    PyObject *tuple, *k, *v;
462
4.22k
    Py_ssize_t pos = 0, size = PyDict_GET_SIZE(dict);
463
464
4.22k
    tuple = PyTuple_New(size);
465
4.22k
    if (tuple == NULL)
466
0
        return NULL;
467
24.7k
    while (PyDict_Next(dict, &pos, &k, &v)) {
468
20.4k
        Py_ssize_t i = PyLong_AsSsize_t(v);
469
20.4k
        if (i == -1 && PyErr_Occurred()) {
470
0
            Py_DECREF(tuple);
471
0
            return NULL;
472
0
        }
473
20.4k
        assert((i - offset) < size);
474
20.4k
        assert((i - offset) >= 0);
475
20.4k
        PyTuple_SET_ITEM(tuple, i - offset, Py_NewRef(k));
476
20.4k
    }
477
4.22k
    return tuple;
478
4.22k
}
479
480
// This is in codeobject.c.
481
extern void _Py_set_localsplus_info(int, PyObject *, unsigned char,
482
                                   PyObject *, PyObject *);
483
484
static int
485
compute_localsplus_info(_PyCompile_CodeUnitMetadata *umd, int nlocalsplus,
486
                        int flags, PyObject *names, PyObject *kinds)
487
4.22k
{
488
4.22k
    PyObject *k, *v;
489
4.22k
    Py_ssize_t pos = 0;
490
491
    // Set the locals kinds.  Arg vars fill the first portion of the list.
492
4.22k
    struct {
493
4.22k
        int count;
494
4.22k
        _PyLocals_Kind kind;
495
4.22k
    }  argvarkinds[6] = {
496
4.22k
        {(int)umd->u_posonlyargcount, CO_FAST_ARG_POS},
497
4.22k
        {(int)umd->u_argcount, CO_FAST_ARG_POS | CO_FAST_ARG_KW},
498
4.22k
        {(int)umd->u_kwonlyargcount, CO_FAST_ARG_KW},
499
4.22k
        {!!(flags & CO_VARARGS), CO_FAST_ARG_VAR | CO_FAST_ARG_POS},
500
4.22k
        {!!(flags & CO_VARKEYWORDS), CO_FAST_ARG_VAR | CO_FAST_ARG_KW},
501
4.22k
        {-1, 0},  // the remaining local vars
502
4.22k
    };
503
4.22k
    int max = 0;
504
29.5k
    for (int i = 0; i < 6; i++) {
505
25.3k
        max = argvarkinds[i].count < 0
506
25.3k
            ? INT_MAX
507
25.3k
            : max + argvarkinds[i].count;
508
35.1k
        while (pos < max && PyDict_Next(umd->u_varnames, &pos, &k, &v)) {
509
9.82k
            int offset = PyLong_AsInt(v);
510
9.82k
            if (offset == -1 && PyErr_Occurred()) {
511
0
                return ERROR;
512
0
            }
513
9.82k
            assert(offset >= 0);
514
9.82k
            assert(offset < nlocalsplus);
515
516
9.82k
            _PyLocals_Kind kind = CO_FAST_LOCAL | argvarkinds[i].kind;
517
518
9.82k
            int has_key = PyDict_Contains(umd->u_fasthidden, k);
519
9.82k
            RETURN_IF_ERROR(has_key);
520
9.82k
            if (has_key) {
521
3
                kind |= CO_FAST_HIDDEN;
522
3
            }
523
524
9.82k
            has_key = PyDict_Contains(umd->u_cellvars, k);
525
9.82k
            RETURN_IF_ERROR(has_key);
526
9.82k
            if (has_key) {
527
462
                kind |= CO_FAST_CELL;
528
462
            }
529
530
9.82k
            _Py_set_localsplus_info(offset, k, kind, names, kinds);
531
9.82k
        }
532
25.3k
    }
533
4.22k
    int nlocals = (int)PyDict_GET_SIZE(umd->u_varnames);
534
535
    // This counter mirrors the fix done in fix_cell_offsets().
536
4.22k
    int numdropped = 0, cellvar_offset = -1;
537
4.22k
    pos = 0;
538
5.10k
    while (PyDict_Next(umd->u_cellvars, &pos, &k, &v)) {
539
876
        int has_name = PyDict_Contains(umd->u_varnames, k);
540
876
        RETURN_IF_ERROR(has_name);
541
876
        if (has_name) {
542
            // Skip cells that are already covered by locals.
543
462
            numdropped += 1;
544
462
            continue;
545
462
        }
546
547
414
        cellvar_offset = PyLong_AsInt(v);
548
414
        if (cellvar_offset == -1 && PyErr_Occurred()) {
549
0
            return ERROR;
550
0
        }
551
414
        assert(cellvar_offset >= 0);
552
414
        cellvar_offset += nlocals - numdropped;
553
414
        assert(cellvar_offset < nlocalsplus);
554
414
        _Py_set_localsplus_info(cellvar_offset, k, CO_FAST_CELL, names, kinds);
555
414
    }
556
557
4.22k
    pos = 0;
558
4.96k
    while (PyDict_Next(umd->u_freevars, &pos, &k, &v)) {
559
734
        int offset = PyLong_AsInt(v);
560
734
        if (offset == -1 && PyErr_Occurred()) {
561
0
            return ERROR;
562
0
        }
563
734
        assert(offset >= 0);
564
734
        offset += nlocals - numdropped;
565
734
        assert(offset < nlocalsplus);
566
        /* XXX If the assertion below fails it is most likely because a freevar
567
           was added to u_freevars with the wrong index due to not taking into
568
           account cellvars already present, see gh-128632. */
569
734
        assert(offset > cellvar_offset);
570
734
        _Py_set_localsplus_info(offset, k, CO_FAST_FREE, names, kinds);
571
734
    }
572
4.22k
    return SUCCESS;
573
4.22k
}
574
575
static PyCodeObject *
576
makecode(_PyCompile_CodeUnitMetadata *umd, struct assembler *a, PyObject *const_cache,
577
         PyObject *constslist, int maxdepth, int nlocalsplus, int code_flags,
578
         PyObject *filename)
579
4.22k
{
580
4.22k
    PyCodeObject *co = NULL;
581
4.22k
    PyObject *names = NULL;
582
4.22k
    PyObject *consts = NULL;
583
4.22k
    PyObject *localsplusnames = NULL;
584
4.22k
    PyObject *localspluskinds = NULL;
585
4.22k
    names = dict_keys_inorder(umd->u_names, 0);
586
4.22k
    if (!names) {
587
0
        goto error;
588
0
    }
589
4.22k
    if (_PyCompile_ConstCacheMergeOne(const_cache, &names) < 0) {
590
0
        goto error;
591
0
    }
592
593
4.22k
    consts = PyList_AsTuple(constslist); /* PyCode_New requires a tuple */
594
4.22k
    if (consts == NULL) {
595
0
        goto error;
596
0
    }
597
4.22k
    if (_PyCompile_ConstCacheMergeOne(const_cache, &consts) < 0) {
598
0
        goto error;
599
0
    }
600
601
4.22k
    assert(umd->u_posonlyargcount < INT_MAX);
602
4.22k
    assert(umd->u_argcount < INT_MAX);
603
4.22k
    assert(umd->u_kwonlyargcount < INT_MAX);
604
4.22k
    int posonlyargcount = (int)umd->u_posonlyargcount;
605
4.22k
    int posorkwargcount = (int)umd->u_argcount;
606
4.22k
    assert(INT_MAX - posonlyargcount - posorkwargcount > 0);
607
4.22k
    int kwonlyargcount = (int)umd->u_kwonlyargcount;
608
609
4.22k
    localsplusnames = PyTuple_New(nlocalsplus);
610
4.22k
    if (localsplusnames == NULL) {
611
0
        goto error;
612
0
    }
613
4.22k
    localspluskinds = PyBytes_FromStringAndSize(NULL, nlocalsplus);
614
4.22k
    if (localspluskinds == NULL) {
615
0
        goto error;
616
0
    }
617
4.22k
    if (compute_localsplus_info(
618
4.22k
            umd, nlocalsplus, code_flags,
619
4.22k
            localsplusnames, localspluskinds) == ERROR)
620
0
    {
621
0
        goto error;
622
0
    }
623
624
4.22k
    struct _PyCodeConstructor con = {
625
4.22k
        .filename = filename,
626
4.22k
        .name = umd->u_name,
627
4.22k
        .qualname = umd->u_qualname ? umd->u_qualname : umd->u_name,
628
4.22k
        .flags = code_flags,
629
630
4.22k
        .code = a->a_bytecode,
631
4.22k
        .firstlineno = umd->u_firstlineno,
632
4.22k
        .linetable = a->a_linetable,
633
634
4.22k
        .consts = consts,
635
4.22k
        .names = names,
636
637
4.22k
        .localsplusnames = localsplusnames,
638
4.22k
        .localspluskinds = localspluskinds,
639
640
4.22k
        .argcount = posonlyargcount + posorkwargcount,
641
4.22k
        .posonlyargcount = posonlyargcount,
642
4.22k
        .kwonlyargcount = kwonlyargcount,
643
644
4.22k
        .stacksize = maxdepth,
645
646
4.22k
        .exceptiontable = a->a_except_table,
647
4.22k
    };
648
649
4.22k
   if (_PyCode_Validate(&con) < 0) {
650
0
        goto error;
651
0
    }
652
653
4.22k
    if (_PyCompile_ConstCacheMergeOne(const_cache, &localsplusnames) < 0) {
654
0
        goto error;
655
0
    }
656
4.22k
    con.localsplusnames = localsplusnames;
657
658
4.22k
    co = _PyCode_New(&con);
659
4.22k
    if (co == NULL) {
660
0
        goto error;
661
0
    }
662
663
4.22k
error:
664
4.22k
    Py_XDECREF(names);
665
4.22k
    Py_XDECREF(consts);
666
4.22k
    Py_XDECREF(localsplusnames);
667
4.22k
    Py_XDECREF(localspluskinds);
668
4.22k
    return co;
669
4.22k
}
670
671
672
// The offset (in code units) of the END_SEND from the SEND in the `yield from` sequence.
673
0
#define END_SEND_OFFSET 6
674
675
static int
676
resolve_jump_offsets(instr_sequence *instrs)
677
4.22k
{
678
    /* Compute the size of each instruction and fixup jump args.
679
     * Replace instruction index with position in bytecode.
680
     */
681
682
155k
    for (int i = 0; i < instrs->s_used; i++) {
683
150k
        instruction *instr = &instrs->s_instrs[i];
684
150k
        if (OPCODE_HAS_JUMP(instr->i_opcode)) {
685
4.86k
            instr->i_target = instr->i_oparg;
686
4.86k
        }
687
150k
    }
688
689
4.22k
    int extended_arg_recompile;
690
691
4.29k
    do {
692
4.29k
        int totsize = 0;
693
173k
        for (int i = 0; i < instrs->s_used; i++) {
694
168k
            instruction *instr = &instrs->s_instrs[i];
695
168k
            instr->i_offset = totsize;
696
168k
            int isize = instr_size(instr);
697
168k
            totsize += isize;
698
168k
        }
699
4.29k
        extended_arg_recompile = 0;
700
701
4.29k
        int offset = 0;
702
173k
        for (int i = 0; i < instrs->s_used; i++) {
703
168k
            instruction *instr = &instrs->s_instrs[i];
704
168k
            int isize = instr_size(instr);
705
            /* jump offsets are computed relative to
706
             * the instruction pointer after fetching
707
             * the jump instruction.
708
             */
709
168k
            offset += isize;
710
168k
            if (OPCODE_HAS_JUMP(instr->i_opcode)) {
711
6.33k
                instruction *target = &instrs->s_instrs[instr->i_target];
712
6.33k
                instr->i_oparg = target->i_offset;
713
6.33k
                if (instr->i_opcode == END_ASYNC_FOR) {
714
                    // sys.monitoring needs to be able to find the matching END_SEND
715
                    // but the target is the SEND, so we adjust it here.
716
0
                    instr->i_oparg = offset - instr->i_oparg - END_SEND_OFFSET;
717
0
                }
718
6.33k
                else if (instr->i_oparg < offset) {
719
951
                    assert(IS_BACKWARDS_JUMP_OPCODE(instr->i_opcode));
720
951
                    instr->i_oparg = offset - instr->i_oparg;
721
951
                }
722
5.38k
                else {
723
5.38k
                    assert(!IS_BACKWARDS_JUMP_OPCODE(instr->i_opcode));
724
5.38k
                    instr->i_oparg = instr->i_oparg - offset;
725
5.38k
                }
726
6.33k
                if (instr_size(instr) != isize) {
727
420
                    extended_arg_recompile = 1;
728
420
                }
729
6.33k
            }
730
168k
        }
731
    /* XXX: This is an awful hack that could hurt performance, but
732
        on the bright side it should work until we come up
733
        with a better solution.
734
735
        The issue is that in the first loop instr_size() is
736
        called, and it requires i_oparg be set appropriately.
737
        There is a bootstrap problem because i_oparg is
738
        calculated in the second loop above.
739
740
        So we loop until we stop seeing new EXTENDED_ARGs.
741
        The only EXTENDED_ARGs that could be popping up are
742
        ones in jump instructions.  So this should converge
743
        fairly quickly.
744
    */
745
4.29k
    } while (extended_arg_recompile);
746
4.22k
    return SUCCESS;
747
4.22k
}
748
749
static int
750
resolve_unconditional_jumps(instr_sequence *instrs)
751
4.22k
{
752
    /* Resolve directions of unconditional jumps */
753
754
155k
    for (int i = 0; i < instrs->s_used; i++) {
755
150k
        instruction *instr = &instrs->s_instrs[i];
756
150k
        bool is_forward = (instr->i_oparg > i);
757
150k
        switch(instr->i_opcode) {
758
628
            case JUMP:
759
628
                assert(is_pseudo_target(JUMP, JUMP_FORWARD));
760
628
                assert(is_pseudo_target(JUMP, JUMP_BACKWARD));
761
628
                instr->i_opcode = is_forward ? JUMP_FORWARD : JUMP_BACKWARD;
762
628
                break;
763
470
            case JUMP_NO_INTERRUPT:
764
470
                assert(is_pseudo_target(JUMP_NO_INTERRUPT, JUMP_FORWARD));
765
470
                assert(is_pseudo_target(JUMP_NO_INTERRUPT, JUMP_BACKWARD_NO_INTERRUPT));
766
470
                instr->i_opcode = is_forward ?
767
338
                    JUMP_FORWARD : JUMP_BACKWARD_NO_INTERRUPT;
768
470
                break;
769
149k
            default:
770
149k
                if (OPCODE_HAS_JUMP(instr->i_opcode) &&
771
3.76k
                    IS_PSEUDO_INSTR(instr->i_opcode)) {
772
0
                    Py_UNREACHABLE();
773
0
                }
774
150k
        }
775
150k
    }
776
4.22k
    return SUCCESS;
777
4.22k
}
778
779
PyCodeObject *
780
_PyAssemble_MakeCodeObject(_PyCompile_CodeUnitMetadata *umd, PyObject *const_cache,
781
                           PyObject *consts, int maxdepth, instr_sequence *instrs,
782
                           int nlocalsplus, int code_flags, PyObject *filename)
783
4.22k
{
784
4.22k
    if (_PyInstructionSequence_ApplyLabelMap(instrs) < 0) {
785
0
        return NULL;
786
0
    }
787
4.22k
    if (resolve_unconditional_jumps(instrs) < 0) {
788
0
        return NULL;
789
0
    }
790
4.22k
    if (resolve_jump_offsets(instrs) < 0) {
791
0
        return NULL;
792
0
    }
793
4.22k
    PyCodeObject *co = NULL;
794
795
4.22k
    struct assembler a;
796
4.22k
    int res = assemble_emit(&a, instrs, umd->u_firstlineno, const_cache);
797
4.22k
    if (res == SUCCESS) {
798
4.22k
        co = makecode(umd, &a, const_cache, consts, maxdepth, nlocalsplus,
799
4.22k
                      code_flags, filename);
800
4.22k
    }
801
4.22k
    assemble_free(&a);
802
4.22k
    return co;
803
4.22k
}