Coverage Report

Created: 2025-11-24 06:11

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