Coverage Report

Created: 2025-08-29 06:15

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