Coverage Report

Created: 2026-01-09 06:26

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Python/perf_jit_trampoline.c
Line
Count
Source
1
/*
2
 * Python Perf Trampoline Support - JIT Dump Implementation
3
 *
4
 * This file implements the perf jitdump API for Python's performance profiling
5
 * integration. It allows perf (Linux performance analysis tool) to understand
6
 * and profile dynamically generated Python bytecode by creating JIT dump files
7
 * that perf can inject into its analysis.
8
 *
9
 *
10
 * IMPORTANT: This file exports specific callback functions that are part of
11
 * Python's internal API. Do not modify the function signatures or behavior
12
 * of exported functions without coordinating with the Python core team.
13
 *
14
 * Usually the binary and libraries are mapped in separate region like below:
15
 *
16
 *   address ->
17
 *    --+---------------------+--//--+---------------------+--
18
 *      | .text | .data | ... |      | .text | .data | ... |
19
 *    --+---------------------+--//--+---------------------+--
20
 *          myprog                      libc.so
21
 *
22
 * So it'd be easy and straight-forward to find a mapped binary or library from an
23
 * address.
24
 *
25
 * But for JIT code, the code arena only cares about the code section. But the
26
 * resulting DSOs (which is generated by perf inject -j) contain ELF headers and
27
 * unwind info too. Then it'd generate following address space with synthesized
28
 * MMAP events. Let's say it has a sample between address B and C.
29
 *
30
 *                                                sample
31
 *                                                  |
32
 *   address ->                         A       B   v   C
33
 *   ---------------------------------------------------------------------------------------------------
34
 *   /tmp/jitted-PID-0.so   | (headers) | .text | unwind info |
35
 *   /tmp/jitted-PID-1.so           | (headers) | .text | unwind info |
36
 *   /tmp/jitted-PID-2.so                   | (headers) | .text | unwind info |
37
 *     ...
38
 *   ---------------------------------------------------------------------------------------------------
39
 *
40
 * If it only maps the .text section, it'd find the jitted-PID-1.so but cannot see
41
 * the unwind info. If it maps both .text section and unwind sections, the sample
42
 * could be mapped to either jitted-PID-0.so or jitted-PID-1.so and it's confusing
43
 * which one is right. So to make perf happy we have non-overlapping ranges for each
44
 * DSO:
45
 *
46
 *   address ->
47
 *   -------------------------------------------------------------------------------------------------------
48
 *   /tmp/jitted-PID-0.so   | (headers) | .text | unwind info |
49
 *   /tmp/jitted-PID-1.so                         | (headers) | .text | unwind info |
50
 *   /tmp/jitted-PID-2.so                                               | (headers) | .text | unwind info |
51
 *     ...
52
 *   -------------------------------------------------------------------------------------------------------
53
 *
54
 * As the trampolines are constant, we add a constant padding but in general the padding needs to have the
55
 * size of the unwind info rounded to 16 bytes. In general, for our trampolines this is 0x50
56
 */
57
58
59
60
#include "Python.h"
61
#include "pycore_ceval.h"         // _PyPerf_Callbacks
62
#include "pycore_frame.h"
63
#include "pycore_interp.h"
64
#include "pycore_mmap.h"          // _PyAnnotateMemoryMap()
65
#include "pycore_runtime.h"       // _PyRuntime
66
67
#ifdef PY_HAVE_PERF_TRAMPOLINE
68
69
/* Standard library includes for perf jitdump implementation */
70
#if defined(__linux__)
71
#  include <elf.h>                // ELF architecture constants
72
#endif
73
#include <fcntl.h>                // File control operations
74
#include <stdio.h>                // Standard I/O operations
75
#include <stdlib.h>               // Standard library functions
76
#include <sys/mman.h>             // Memory mapping functions (mmap)
77
#include <sys/types.h>            // System data types
78
#include <unistd.h>               // System calls (sysconf, getpid)
79
#include <sys/time.h>             // Time functions (gettimeofday)
80
#if defined(__linux__)
81
#  include <sys/syscall.h>        // System call interface
82
#endif
83
84
// =============================================================================
85
//                           CONSTANTS AND CONFIGURATION
86
// =============================================================================
87
88
/*
89
 * Memory layout considerations for perf jitdump:
90
 *
91
 * Perf expects non-overlapping memory regions for each JIT-compiled function.
92
 * When perf processes the jitdump file, it creates synthetic DSO (Dynamic
93
 * Shared Object) files that contain:
94
 * - ELF headers
95
 * - .text section (actual machine code)
96
 * - Unwind information (for stack traces)
97
 *
98
 * To ensure proper address space layout, we add padding between code regions.
99
 * This prevents address conflicts when perf maps the synthesized DSOs.
100
 *
101
 * Memory layout example:
102
 * /tmp/jitted-PID-0.so: [headers][.text][unwind_info][padding]
103
 * /tmp/jitted-PID-1.so:                                       [headers][.text][unwind_info][padding]
104
 *
105
 * The padding size is now calculated automatically during initialization
106
 * based on the actual unwind information requirements.
107
 */
108
109
110
/* These constants are defined inside <elf.h>, which we can't use outside of linux. */
111
#if !defined(__linux__)
112
#  if defined(__i386__) || defined(_M_IX86)
113
#    define EM_386      3
114
#  elif defined(__arm__) || defined(_M_ARM)
115
#    define EM_ARM      40
116
#  elif defined(__x86_64__) || defined(_M_X64)
117
#    define EM_X86_64   62
118
#  elif defined(__aarch64__)
119
#    define EM_AARCH64  183
120
#  elif defined(__riscv)
121
#    define EM_RISCV    243
122
#  endif
123
#endif
124
125
/* Convenient access to the global trampoline API state */
126
0
#define trampoline_api _PyRuntime.ceval.perf.trampoline_api
127
128
/* Type aliases for clarity and portability */
129
typedef uint64_t uword;                    // Word-sized unsigned integer
130
typedef const char* CodeComments;          // Code comment strings
131
132
/* Memory size constants */
133
0
#define MB (1024 * 1024)                   // 1 Megabyte for buffer sizing
134
135
// =============================================================================
136
//                        ARCHITECTURE-SPECIFIC DEFINITIONS
137
// =============================================================================
138
139
/*
140
 * Returns the ELF machine architecture constant for the current platform.
141
 * This is required for the jitdump header to correctly identify the target
142
 * architecture for perf processing.
143
 *
144
 */
145
0
static uint64_t GetElfMachineArchitecture(void) {
146
0
#if defined(__x86_64__) || defined(_M_X64)
147
0
    return EM_X86_64;
148
#elif defined(__i386__) || defined(_M_IX86)
149
    return EM_386;
150
#elif defined(__aarch64__)
151
    return EM_AARCH64;
152
#elif defined(__arm__) || defined(_M_ARM)
153
    return EM_ARM;
154
#elif defined(__riscv)
155
    return EM_RISCV;
156
#else
157
    Py_UNREACHABLE();  // Unsupported architecture - should never reach here
158
    return 0;
159
#endif
160
0
}
161
162
// =============================================================================
163
//                           PERF JITDUMP DATA STRUCTURES
164
// =============================================================================
165
166
/*
167
 * Perf jitdump file format structures
168
 *
169
 * These structures define the binary format that perf expects for JIT dump files.
170
 * The format is documented in the Linux perf tools source code and must match
171
 * exactly for proper perf integration.
172
 */
173
174
/*
175
 * Jitdump file header - written once at the beginning of each jitdump file
176
 * Contains metadata about the process and jitdump format version
177
 */
178
typedef struct {
179
    uint32_t magic;              // Magic number (0x4A695444 = "JiTD")
180
    uint32_t version;            // Jitdump format version (currently 1)
181
    uint32_t size;               // Size of this header structure
182
    uint32_t elf_mach_target;    // Target architecture (from GetElfMachineArchitecture)
183
    uint32_t reserved;           // Reserved field (must be 0)
184
    uint32_t process_id;         // Process ID of the JIT compiler
185
    uint64_t time_stamp;         // Timestamp when jitdump was created
186
    uint64_t flags;              // Feature flags (currently unused)
187
} Header;
188
189
/*
190
 * Perf event types supported by the jitdump format
191
 * Each event type has a corresponding structure format
192
 */
193
enum PerfEvent {
194
    PerfLoad = 0,           // Code load event (new JIT function)
195
    PerfMove = 1,           // Code move event (function relocated)
196
    PerfDebugInfo = 2,      // Debug information event
197
    PerfClose = 3,          // JIT session close event
198
    PerfUnwindingInfo = 4   // Stack unwinding information event
199
};
200
201
/*
202
 * Base event structure - common header for all perf events
203
 * Every event in the jitdump file starts with this structure
204
 */
205
struct BaseEvent {
206
    uint32_t event;         // Event type (from PerfEvent enum)
207
    uint32_t size;          // Total size of this event including payload
208
    uint64_t time_stamp;    // Timestamp when event occurred
209
};
210
211
/*
212
 * Code load event - indicates a new JIT-compiled function is available
213
 * This is the most important event type for Python profiling
214
 */
215
typedef struct {
216
    struct BaseEvent base;   // Common event header
217
    uint32_t process_id;     // Process ID where code was generated
218
#if defined(__APPLE__)
219
    uint64_t thread_id;      // Thread ID where code was generated
220
#else
221
    uint32_t thread_id;      // Thread ID where code was generated
222
#endif
223
    uint64_t vma;            // Virtual memory address where code is loaded
224
    uint64_t code_address;   // Address of the actual machine code
225
    uint64_t code_size;      // Size of the machine code in bytes
226
    uint64_t code_id;        // Unique identifier for this code region
227
    /* Followed by:
228
     * - null-terminated function name string
229
     * - raw machine code bytes
230
     */
231
} CodeLoadEvent;
232
233
/*
234
 * Code unwinding information event - provides DWARF data for stack traces
235
 * Essential for proper stack unwinding during profiling
236
 */
237
typedef struct {
238
    struct BaseEvent base;      // Common event header
239
    uint64_t unwind_data_size;  // Size of the unwinding data
240
    uint64_t eh_frame_hdr_size; // Size of the EH frame header
241
    uint64_t mapped_size;       // Total mapped size (with padding)
242
    /* Followed by:
243
     * - EH frame header
244
     * - DWARF unwinding information
245
     * - Padding to alignment boundary
246
     */
247
} CodeUnwindingInfoEvent;
248
249
// =============================================================================
250
//                              GLOBAL STATE MANAGEMENT
251
// =============================================================================
252
253
/*
254
 * Global state for the perf jitdump implementation
255
 *
256
 * This structure maintains all the state needed for generating jitdump files.
257
 * It's designed as a singleton since there's typically only one jitdump file
258
 * per Python process.
259
 */
260
typedef struct {
261
    FILE* perf_map;          // File handle for the jitdump file
262
    PyThread_type_lock map_lock;  // Thread synchronization lock
263
    void* mapped_buffer;     // Memory-mapped region (signals perf we're active)
264
    size_t mapped_size;      // Size of the mapped region
265
    int code_id;             // Counter for unique code region identifiers
266
} PerfMapJitState;
267
268
/* Global singleton instance */
269
static PerfMapJitState perf_jit_map_state;
270
271
// =============================================================================
272
//                              TIME UTILITIES
273
// =============================================================================
274
275
/* Time conversion constant */
276
static const intptr_t nanoseconds_per_second = 1000000000;
277
278
/*
279
 * Get current monotonic time in nanoseconds
280
 *
281
 * Monotonic time is preferred for event timestamps because it's not affected
282
 * by system clock adjustments. This ensures consistent timing relationships
283
 * between events even if the system clock is changed.
284
 *
285
 * Returns: Current monotonic time in nanoseconds since an arbitrary epoch
286
 */
287
0
static int64_t get_current_monotonic_ticks(void) {
288
0
    struct timespec ts;
289
0
    if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {
290
0
        Py_UNREACHABLE();  // Should never fail on supported systems
291
0
        return 0;
292
0
    }
293
294
    /* Convert to nanoseconds for maximum precision */
295
0
    int64_t result = ts.tv_sec;
296
0
    result *= nanoseconds_per_second;
297
0
    result += ts.tv_nsec;
298
0
    return result;
299
0
}
300
301
/*
302
 * Get current wall clock time in microseconds
303
 *
304
 * Used for the jitdump file header timestamp. Unlike monotonic time,
305
 * this represents actual wall clock time that can be correlated with
306
 * other system events.
307
 *
308
 * Returns: Current time in microseconds since Unix epoch
309
 */
310
0
static int64_t get_current_time_microseconds(void) {
311
0
    struct timeval tv;
312
0
    if (gettimeofday(&tv, NULL) < 0) {
313
0
        Py_UNREACHABLE();  // Should never fail on supported systems
314
0
        return 0;
315
0
    }
316
0
    return ((int64_t)(tv.tv_sec) * 1000000) + tv.tv_usec;
317
0
}
318
319
// =============================================================================
320
//                              UTILITY FUNCTIONS
321
// =============================================================================
322
323
/*
324
 * Round up a value to the next multiple of a given number
325
 *
326
 * This is essential for maintaining proper alignment requirements in the
327
 * jitdump format. Many structures need to be aligned to specific boundaries
328
 * (typically 8 or 16 bytes) for efficient processing by perf.
329
 *
330
 * Args:
331
 *   value: The value to round up
332
 *   multiple: The multiple to round up to
333
 *
334
 * Returns: The smallest value >= input that is a multiple of 'multiple'
335
 */
336
0
static size_t round_up(int64_t value, int64_t multiple) {
337
0
    if (multiple == 0) {
338
0
        return value;  // Avoid division by zero
339
0
    }
340
341
0
    int64_t remainder = value % multiple;
342
0
    if (remainder == 0) {
343
0
        return value;  // Already aligned
344
0
    }
345
346
    /* Calculate how much to add to reach the next multiple */
347
0
    int64_t difference = multiple - remainder;
348
0
    int64_t rounded_up_value = value + difference;
349
350
0
    return rounded_up_value;
351
0
}
352
353
// =============================================================================
354
//                              FILE I/O UTILITIES
355
// =============================================================================
356
357
/*
358
 * Write data to the jitdump file with error handling
359
 *
360
 * This function ensures that all data is written to the file, handling
361
 * partial writes that can occur with large buffers or when the system
362
 * is under load.
363
 *
364
 * Args:
365
 *   buffer: Pointer to data to write
366
 *   size: Number of bytes to write
367
 */
368
0
static void perf_map_jit_write_fully(const void* buffer, size_t size) {
369
0
    FILE* out_file = perf_jit_map_state.perf_map;
370
0
    const char* ptr = (const char*)(buffer);
371
372
0
    while (size > 0) {
373
0
        const size_t written = fwrite(ptr, 1, size, out_file);
374
0
        if (written == 0) {
375
0
            Py_UNREACHABLE();  // Write failure - should be very rare
376
0
            break;
377
0
        }
378
0
        size -= written;
379
0
        ptr += written;
380
0
    }
381
0
}
382
383
/*
384
 * Write the jitdump file header
385
 *
386
 * The header must be written exactly once at the beginning of each jitdump
387
 * file. It provides metadata that perf uses to parse the rest of the file.
388
 *
389
 * Args:
390
 *   pid: Process ID to include in the header
391
 *   out_file: File handle to write to (currently unused, uses global state)
392
 */
393
0
static void perf_map_jit_write_header(int pid, FILE* out_file) {
394
0
    Header header;
395
396
    /* Initialize header with required values */
397
0
    header.magic = 0x4A695444;                    // "JiTD" magic number
398
0
    header.version = 1;                           // Current jitdump version
399
0
    header.size = sizeof(Header);                 // Header size for validation
400
0
    header.elf_mach_target = GetElfMachineArchitecture();  // Target architecture
401
0
    header.process_id = pid;                      // Process identifier
402
0
    header.time_stamp = get_current_time_microseconds();   // Creation time
403
0
    header.flags = 0;                             // No special flags currently used
404
405
0
    perf_map_jit_write_fully(&header, sizeof(header));
406
0
}
407
408
// =============================================================================
409
//                              DWARF CONSTANTS AND UTILITIES
410
// =============================================================================
411
412
/*
413
 * DWARF (Debug With Arbitrary Record Formats) constants
414
 *
415
 * DWARF is a debugging data format used to provide stack unwinding information.
416
 * These constants define the various encoding types and opcodes used in
417
 * DWARF Call Frame Information (CFI) records.
418
 */
419
420
/* DWARF Call Frame Information version */
421
#define DWRF_CIE_VERSION 1
422
423
/* DWARF CFA (Call Frame Address) opcodes */
424
enum {
425
    DWRF_CFA_nop = 0x0,                    // No operation
426
    DWRF_CFA_offset_extended = 0x5,        // Extended offset instruction
427
    DWRF_CFA_def_cfa = 0xc,               // Define CFA rule
428
    DWRF_CFA_def_cfa_register = 0xd,      // Define CFA register
429
    DWRF_CFA_def_cfa_offset = 0xe,        // Define CFA offset
430
    DWRF_CFA_offset_extended_sf = 0x11,   // Extended signed offset
431
    DWRF_CFA_advance_loc = 0x40,          // Advance location counter
432
    DWRF_CFA_offset = 0x80,               // Simple offset instruction
433
    DWRF_CFA_restore = 0xc0               // Restore register
434
};
435
436
/* DWARF Exception Handling pointer encodings */
437
enum {
438
    DWRF_EH_PE_absptr = 0x00,             // Absolute pointer
439
    DWRF_EH_PE_omit = 0xff,               // Omitted value
440
441
    /* Data type encodings */
442
    DWRF_EH_PE_uleb128 = 0x01,            // Unsigned LEB128
443
    DWRF_EH_PE_udata2 = 0x02,             // Unsigned 2-byte
444
    DWRF_EH_PE_udata4 = 0x03,             // Unsigned 4-byte
445
    DWRF_EH_PE_udata8 = 0x04,             // Unsigned 8-byte
446
    DWRF_EH_PE_sleb128 = 0x09,            // Signed LEB128
447
    DWRF_EH_PE_sdata2 = 0x0a,             // Signed 2-byte
448
    DWRF_EH_PE_sdata4 = 0x0b,             // Signed 4-byte
449
    DWRF_EH_PE_sdata8 = 0x0c,             // Signed 8-byte
450
    DWRF_EH_PE_signed = 0x08,             // Signed flag
451
452
    /* Reference type encodings */
453
    DWRF_EH_PE_pcrel = 0x10,              // PC-relative
454
    DWRF_EH_PE_textrel = 0x20,            // Text-relative
455
    DWRF_EH_PE_datarel = 0x30,            // Data-relative
456
    DWRF_EH_PE_funcrel = 0x40,            // Function-relative
457
    DWRF_EH_PE_aligned = 0x50,            // Aligned
458
    DWRF_EH_PE_indirect = 0x80            // Indirect
459
};
460
461
/* Additional DWARF constants for debug information */
462
enum { DWRF_TAG_compile_unit = 0x11 };
463
enum { DWRF_children_no = 0, DWRF_children_yes = 1 };
464
enum {
465
    DWRF_AT_name = 0x03,         // Name attribute
466
    DWRF_AT_stmt_list = 0x10,    // Statement list
467
    DWRF_AT_low_pc = 0x11,       // Low PC address
468
    DWRF_AT_high_pc = 0x12       // High PC address
469
};
470
enum {
471
    DWRF_FORM_addr = 0x01,       // Address form
472
    DWRF_FORM_data4 = 0x06,      // 4-byte data
473
    DWRF_FORM_string = 0x08      // String form
474
};
475
476
/* Line number program opcodes */
477
enum {
478
    DWRF_LNS_extended_op = 0,    // Extended opcode
479
    DWRF_LNS_copy = 1,           // Copy operation
480
    DWRF_LNS_advance_pc = 2,     // Advance program counter
481
    DWRF_LNS_advance_line = 3    // Advance line number
482
};
483
484
/* Line number extended opcodes */
485
enum {
486
    DWRF_LNE_end_sequence = 1,   // End of sequence
487
    DWRF_LNE_set_address = 2     // Set address
488
};
489
490
/*
491
 * Architecture-specific DWARF register numbers
492
 *
493
 * These constants define the register numbering scheme used by DWARF
494
 * for each supported architecture. The numbers must match the ABI
495
 * specification for proper stack unwinding.
496
 */
497
enum {
498
#ifdef __x86_64__
499
    /* x86_64 register numbering (note: order is defined by x86_64 ABI) */
500
    DWRF_REG_AX,    // RAX
501
    DWRF_REG_DX,    // RDX
502
    DWRF_REG_CX,    // RCX
503
    DWRF_REG_BX,    // RBX
504
    DWRF_REG_SI,    // RSI
505
    DWRF_REG_DI,    // RDI
506
    DWRF_REG_BP,    // RBP
507
    DWRF_REG_SP,    // RSP
508
    DWRF_REG_8,     // R8
509
    DWRF_REG_9,     // R9
510
    DWRF_REG_10,    // R10
511
    DWRF_REG_11,    // R11
512
    DWRF_REG_12,    // R12
513
    DWRF_REG_13,    // R13
514
    DWRF_REG_14,    // R14
515
    DWRF_REG_15,    // R15
516
    DWRF_REG_RA,    // Return address (RIP)
517
#elif defined(__aarch64__) && defined(__AARCH64EL__) && !defined(__ILP32__)
518
    /* AArch64 register numbering */
519
    DWRF_REG_FP = 29,  // Frame Pointer
520
    DWRF_REG_RA = 30,  // Link register (return address)
521
    DWRF_REG_SP = 31,  // Stack pointer
522
#else
523
#    error "Unsupported target architecture"
524
#endif
525
};
526
527
/* DWARF encoding constants used in EH frame headers */
528
static const uint8_t DwarfUData4 = 0x03;     // Unsigned 4-byte data
529
static const uint8_t DwarfSData4 = 0x0b;     // Signed 4-byte data
530
static const uint8_t DwarfPcRel = 0x10;      // PC-relative encoding
531
static const uint8_t DwarfDataRel = 0x30;    // Data-relative encoding
532
533
// =============================================================================
534
//                              ELF OBJECT CONTEXT
535
// =============================================================================
536
537
/*
538
 * Context for building ELF/DWARF structures
539
 *
540
 * This structure maintains state while constructing DWARF unwind information.
541
 * It acts as a simple buffer manager with pointers to track current position
542
 * and important landmarks within the buffer.
543
 */
544
typedef struct ELFObjectContext {
545
    uint8_t* p;            // Current write position in buffer
546
    uint8_t* startp;       // Start of buffer (for offset calculations)
547
    uint8_t* eh_frame_p;   // Start of EH frame data (for relative offsets)
548
    uint8_t* fde_p;        // Start of FDE data (for PC-relative calculations)
549
    uint32_t code_size;    // Size of the code being described
550
} ELFObjectContext;
551
552
/*
553
 * EH Frame Header structure for DWARF unwinding
554
 *
555
 * This structure provides metadata about the DWARF unwinding information
556
 * that follows. It's required by the perf jitdump format to enable proper
557
 * stack unwinding during profiling.
558
 */
559
typedef struct {
560
    unsigned char version;           // EH frame version (always 1)
561
    unsigned char eh_frame_ptr_enc;  // Encoding of EH frame pointer
562
    unsigned char fde_count_enc;     // Encoding of FDE count
563
    unsigned char table_enc;         // Encoding of table entries
564
    int32_t eh_frame_ptr;           // Pointer to EH frame data
565
    int32_t eh_fde_count;           // Number of FDEs (Frame Description Entries)
566
    int32_t from;                   // Start address of code range
567
    int32_t to;                     // End address of code range
568
} EhFrameHeader;
569
570
// =============================================================================
571
//                              DWARF GENERATION UTILITIES
572
// =============================================================================
573
574
/*
575
 * Append a null-terminated string to the ELF context buffer
576
 *
577
 * Args:
578
 *   ctx: ELF object context
579
 *   str: String to append (must be null-terminated)
580
 *
581
 * Returns: Offset from start of buffer where string was written
582
 */
583
0
static uint32_t elfctx_append_string(ELFObjectContext* ctx, const char* str) {
584
0
    uint8_t* p = ctx->p;
585
0
    uint32_t ofs = (uint32_t)(p - ctx->startp);
586
587
    /* Copy string including null terminator */
588
0
    do {
589
0
        *p++ = (uint8_t)*str;
590
0
    } while (*str++);
591
592
0
    ctx->p = p;
593
0
    return ofs;
594
0
}
595
596
/*
597
 * Append a SLEB128 (Signed Little Endian Base 128) value
598
 *
599
 * SLEB128 is a variable-length encoding used extensively in DWARF.
600
 * It efficiently encodes small numbers in fewer bytes.
601
 *
602
 * Args:
603
 *   ctx: ELF object context
604
 *   v: Signed value to encode
605
 */
606
0
static void elfctx_append_sleb128(ELFObjectContext* ctx, int32_t v) {
607
0
    uint8_t* p = ctx->p;
608
609
    /* Encode 7 bits at a time, with continuation bit in MSB */
610
0
    for (; (uint32_t)(v + 0x40) >= 0x80; v >>= 7) {
611
0
        *p++ = (uint8_t)((v & 0x7f) | 0x80);  // Set continuation bit
612
0
    }
613
0
    *p++ = (uint8_t)(v & 0x7f);  // Final byte without continuation bit
614
615
0
    ctx->p = p;
616
0
}
617
618
/*
619
 * Append a ULEB128 (Unsigned Little Endian Base 128) value
620
 *
621
 * Similar to SLEB128 but for unsigned values.
622
 *
623
 * Args:
624
 *   ctx: ELF object context
625
 *   v: Unsigned value to encode
626
 */
627
0
static void elfctx_append_uleb128(ELFObjectContext* ctx, uint32_t v) {
628
0
    uint8_t* p = ctx->p;
629
630
    /* Encode 7 bits at a time, with continuation bit in MSB */
631
0
    for (; v >= 0x80; v >>= 7) {
632
0
        *p++ = (char)((v & 0x7f) | 0x80);  // Set continuation bit
633
0
    }
634
0
    *p++ = (char)v;  // Final byte without continuation bit
635
636
0
    ctx->p = p;
637
0
}
638
639
/*
640
 * Macros for generating DWARF structures
641
 *
642
 * These macros provide a convenient way to write various data types
643
 * to the DWARF buffer while automatically advancing the pointer.
644
 */
645
#define DWRF_U8(x) (*p++ = (x))                                    // Write unsigned 8-bit
646
#define DWRF_I8(x) (*(int8_t*)p = (x), p++)                       // Write signed 8-bit
647
#define DWRF_U16(x) (*(uint16_t*)p = (x), p += 2)                 // Write unsigned 16-bit
648
#define DWRF_U32(x) (*(uint32_t*)p = (x), p += 4)                 // Write unsigned 32-bit
649
#define DWRF_ADDR(x) (*(uintptr_t*)p = (x), p += sizeof(uintptr_t)) // Write address
650
#define DWRF_UV(x) (ctx->p = p, elfctx_append_uleb128(ctx, (x)), p = ctx->p) // Write ULEB128
651
#define DWRF_SV(x) (ctx->p = p, elfctx_append_sleb128(ctx, (x)), p = ctx->p) // Write SLEB128
652
#define DWRF_STR(str) (ctx->p = p, elfctx_append_string(ctx, (str)), p = ctx->p) // Write string
653
654
/* Align to specified boundary with NOP instructions */
655
#define DWRF_ALIGNNOP(s)                                          \
656
    while ((uintptr_t)p & ((s)-1)) {                              \
657
        *p++ = DWRF_CFA_nop;                                       \
658
    }
659
660
/* Write a DWARF section with automatic size calculation */
661
#define DWRF_SECTION(name, stmt)                                  \
662
0
    {                                                             \
663
0
        uint32_t* szp_##name = (uint32_t*)p;                      \
664
0
        p += 4;                                                   \
665
0
        stmt;                                                     \
666
0
        *szp_##name = (uint32_t)((p - (uint8_t*)szp_##name) - 4); \
667
0
    }
668
669
// =============================================================================
670
//                              DWARF EH FRAME GENERATION
671
// =============================================================================
672
673
static void elf_init_ehframe(ELFObjectContext* ctx);
674
675
/*
676
 * Initialize DWARF .eh_frame section for a code region
677
 *
678
 * The .eh_frame section contains Call Frame Information (CFI) that describes
679
 * how to unwind the stack at any point in the code. This is essential for
680
 * proper profiling as it allows perf to generate accurate call graphs.
681
 *
682
 * The function generates two main components:
683
 * 1. CIE (Common Information Entry) - describes calling conventions
684
 * 2. FDE (Frame Description Entry) - describes specific function unwinding
685
 *
686
 * Args:
687
 *   ctx: ELF object context containing code size and buffer pointers
688
 */
689
0
static size_t calculate_eh_frame_size(void) {
690
    /* Calculate the EH frame size for the trampoline function */
691
0
    extern void *_Py_trampoline_func_start;
692
0
    extern void *_Py_trampoline_func_end;
693
694
0
    size_t code_size = (char*)&_Py_trampoline_func_end - (char*)&_Py_trampoline_func_start;
695
696
0
    ELFObjectContext ctx;
697
0
    char buffer[1024];  // Buffer for DWARF data (1KB should be sufficient)
698
0
    ctx.code_size = code_size;
699
0
    ctx.startp = ctx.p = (uint8_t*)buffer;
700
0
    ctx.fde_p = NULL;
701
702
0
    elf_init_ehframe(&ctx);
703
0
    return ctx.p - ctx.startp;
704
0
}
705
706
0
static void elf_init_ehframe(ELFObjectContext* ctx) {
707
0
    uint8_t* p = ctx->p;
708
0
    uint8_t* framep = p;  // Remember start of frame data
709
710
    /*
711
    * DWARF Unwind Table for Trampoline Function
712
    *
713
    * This section defines DWARF Call Frame Information (CFI) using encoded macros
714
    * like `DWRF_U8`, `DWRF_UV`, and `DWRF_SECTION` to describe how the trampoline function
715
    * preserves and restores registers. This is used by profiling tools (e.g., `perf`)
716
    * and debuggers for stack unwinding in JIT-compiled code.
717
    *
718
    * -------------------------------------------------
719
    * TO REGENERATE THIS TABLE FROM GCC OBJECTS:
720
    * -------------------------------------------------
721
    *
722
    * 1. Create a trampoline source file (e.g., `trampoline.c`):
723
    *
724
    *      #include <Python.h>
725
    *      typedef PyObject* (*py_evaluator)(void*, void*, int);
726
    *      PyObject* trampoline(void *ts, void *f, int throwflag, py_evaluator evaluator) {
727
    *          return evaluator(ts, f, throwflag);
728
    *      }
729
    *
730
    * 2. Compile to an object file with frame pointer preservation:
731
    *
732
    *      gcc trampoline.c -I. -I./Include -O2 -fno-omit-frame-pointer -mno-omit-leaf-frame-pointer -c
733
    *
734
    * 3. Extract DWARF unwind info from the object file:
735
    *
736
    *      readelf -w trampoline.o
737
    *
738
    *    Example output from `.eh_frame`:
739
    *
740
    *      00000000 CIE
741
    *        Version:               1
742
    *        Augmentation:          "zR"
743
    *        Code alignment factor: 4
744
    *        Data alignment factor: -8
745
    *        Return address column: 30
746
    *        DW_CFA_def_cfa: r31 (sp) ofs 0
747
    *
748
    *      00000014 FDE cie=00000000 pc=0..14
749
    *        DW_CFA_advance_loc: 4
750
    *        DW_CFA_def_cfa_offset: 16
751
    *        DW_CFA_offset: r29 at cfa-16
752
    *        DW_CFA_offset: r30 at cfa-8
753
    *        DW_CFA_advance_loc: 12
754
    *        DW_CFA_restore: r30
755
    *        DW_CFA_restore: r29
756
    *        DW_CFA_def_cfa_offset: 0
757
    *
758
    * -- These values can be verified by comparing with `readelf -w` or `llvm-dwarfdump --eh-frame`.
759
    *
760
    * ----------------------------------
761
    * HOW TO TRANSLATE TO DWRF_* MACROS:
762
    * ----------------------------------
763
    *
764
    * After compiling your trampoline with:
765
    *
766
    *     gcc trampoline.c -I. -I./Include -O2 -fno-omit-frame-pointer -mno-omit-leaf-frame-pointer -c
767
    *
768
    * run:
769
    *
770
    *     readelf -w trampoline.o
771
    *
772
    * to inspect the generated `.eh_frame` data. You will see two main components:
773
    *
774
    *     1. A CIE (Common Information Entry): shared configuration used by all FDEs.
775
    *     2. An FDE (Frame Description Entry): function-specific unwind instructions.
776
    *
777
    * ---------------------
778
    * Translating the CIE:
779
    * ---------------------
780
    * From `readelf -w`, you might see:
781
    *
782
    *   00000000 0000000000000010 00000000 CIE
783
    *     Version:               1
784
    *     Augmentation:          "zR"
785
    *     Code alignment factor: 4
786
    *     Data alignment factor: -8
787
    *     Return address column: 30
788
    *     Augmentation data:     1b
789
    *     DW_CFA_def_cfa: r31 (sp) ofs 0
790
    *
791
    * Map this to:
792
    *
793
    *     DWRF_SECTION(CIE,
794
    *         DWRF_U32(0);                             // CIE ID (always 0 for CIEs)
795
    *         DWRF_U8(DWRF_CIE_VERSION);              // Version: 1
796
    *         DWRF_STR("zR");                         // Augmentation string "zR"
797
    *         DWRF_UV(4);                             // Code alignment factor = 4
798
    *         DWRF_SV(-8);                            // Data alignment factor = -8
799
    *         DWRF_U8(DWRF_REG_RA);                   // Return address register (e.g., x30 = 30)
800
    *         DWRF_UV(1);                             // Augmentation data length = 1
801
    *         DWRF_U8(DWRF_EH_PE_pcrel | DWRF_EH_PE_sdata4); // Encoding for FDE pointers
802
    *
803
    *         DWRF_U8(DWRF_CFA_def_cfa);              // DW_CFA_def_cfa
804
    *         DWRF_UV(DWRF_REG_SP);                   // Register: SP (r31)
805
    *         DWRF_UV(0);                             // Offset = 0
806
    *
807
    *         DWRF_ALIGNNOP(sizeof(uintptr_t));       // Align to pointer size boundary
808
    *     )
809
    *
810
    * Notes:
811
    *   - Use `DWRF_UV` for unsigned LEB128, `DWRF_SV` for signed LEB128.
812
    *   - `DWRF_REG_RA` and `DWRF_REG_SP` are architecture-defined constants.
813
    *
814
    * ---------------------
815
    * Translating the FDE:
816
    * ---------------------
817
    * From `readelf -w`:
818
    *
819
    *   00000014 0000000000000020 00000018 FDE cie=00000000 pc=0000000000000000..0000000000000014
820
    *     DW_CFA_advance_loc: 4
821
    *     DW_CFA_def_cfa_offset: 16
822
    *     DW_CFA_offset: r29 at cfa-16
823
    *     DW_CFA_offset: r30 at cfa-8
824
    *     DW_CFA_advance_loc: 12
825
    *     DW_CFA_restore: r30
826
    *     DW_CFA_restore: r29
827
    *     DW_CFA_def_cfa_offset: 0
828
    *
829
    * Map the FDE header and instructions to:
830
    *
831
    *     DWRF_SECTION(FDE,
832
    *         DWRF_U32((uint32_t)(p - framep));       // Offset to CIE (relative from here)
833
    *         DWRF_U32(pc_relative_offset);           // PC-relative location of the code (calculated dynamically)
834
    *         DWRF_U32(ctx->code_size);               // Code range covered by this FDE
835
    *         DWRF_U8(0);                             // Augmentation data length (none)
836
    *
837
    *         DWRF_U8(DWRF_CFA_advance_loc | 1);      // Advance location by 1 unit (1 * 4 = 4 bytes)
838
    *         DWRF_U8(DWRF_CFA_def_cfa_offset);       // CFA = SP + 16
839
    *         DWRF_UV(16);
840
    *
841
    *         DWRF_U8(DWRF_CFA_offset | DWRF_REG_FP); // Save x29 (frame pointer)
842
    *         DWRF_UV(2);                             // At offset 2 * 8 = 16 bytes
843
    *
844
    *         DWRF_U8(DWRF_CFA_offset | DWRF_REG_RA); // Save x30 (return address)
845
    *         DWRF_UV(1);                             // At offset 1 * 8 = 8 bytes
846
    *
847
    *         DWRF_U8(DWRF_CFA_advance_loc | 3);      // Advance location by 3 units (3 * 4 = 12 bytes)
848
    *
849
    *         DWRF_U8(DWRF_CFA_offset | DWRF_REG_RA); // Restore x30
850
    *         DWRF_U8(DWRF_CFA_offset | DWRF_REG_FP); // Restore x29
851
    *
852
    *         DWRF_U8(DWRF_CFA_def_cfa_offset);       // CFA = SP
853
    *         DWRF_UV(0);
854
    *     )
855
    *
856
    * To regenerate:
857
    *   1. Get the `code alignment factor`, `data alignment factor`, and `RA column` from the CIE.
858
    *   2. Note the range of the function from the FDE's `pc=...` line and map it to the JIT code as
859
    *      the code is in a different address space every time.
860
    *   3. For each `DW_CFA_*` entry, use the corresponding `DWRF_*` macro:
861
    *        - `DW_CFA_def_cfa_offset`     → DWRF_U8(DWRF_CFA_def_cfa_offset), DWRF_UV(value)
862
    *        - `DW_CFA_offset: rX`         → DWRF_U8(DWRF_CFA_offset | reg), DWRF_UV(offset)
863
    *        - `DW_CFA_restore: rX`        → DWRF_U8(DWRF_CFA_offset | reg) // restore is same as reusing offset
864
    *        - `DW_CFA_advance_loc: N`     → DWRF_U8(DWRF_CFA_advance_loc | (N / code_alignment_factor))
865
    *   4. Use `DWRF_REG_FP`, `DWRF_REG_RA`, etc., for register numbers.
866
    *   5. Use `sizeof(uintptr_t)` (typically 8) for pointer size calculations and alignment.
867
    */
868
869
    /*
870
     * Emit DWARF EH CIE (Common Information Entry)
871
     *
872
     * The CIE describes the calling conventions and basic unwinding rules
873
     * that apply to all functions in this compilation unit.
874
     */
875
0
    DWRF_SECTION(CIE,
876
0
        DWRF_U32(0);                           // CIE ID (0 indicates this is a CIE)
877
0
        DWRF_U8(DWRF_CIE_VERSION);            // CIE version (1)
878
0
        DWRF_STR("zR");                       // Augmentation string ("zR" = has LSDA)
879
0
#ifdef __x86_64__
880
0
        DWRF_UV(1);                           // Code alignment factor (x86_64: 1 byte)
881
#elif defined(__aarch64__) && defined(__AARCH64EL__) && !defined(__ILP32__)
882
        DWRF_UV(4);                           // Code alignment factor (AArch64: 4 bytes per instruction)
883
#endif
884
0
        DWRF_SV(-(int64_t)sizeof(uintptr_t)); // Data alignment factor (negative)
885
0
        DWRF_U8(DWRF_REG_RA);                 // Return address register number
886
0
        DWRF_UV(1);                           // Augmentation data length
887
0
        DWRF_U8(DWRF_EH_PE_pcrel | DWRF_EH_PE_sdata4); // FDE pointer encoding
888
889
        /* Initial CFI instructions - describe default calling convention */
890
0
#ifdef __x86_64__
891
        /* x86_64 initial CFI state */
892
0
        DWRF_U8(DWRF_CFA_def_cfa);            // Define CFA (Call Frame Address)
893
0
        DWRF_UV(DWRF_REG_SP);                 // CFA = SP register
894
0
        DWRF_UV(sizeof(uintptr_t));           // CFA = SP + pointer_size
895
0
        DWRF_U8(DWRF_CFA_offset|DWRF_REG_RA); // Return address is saved
896
0
        DWRF_UV(1);                           // At offset 1 from CFA
897
#elif defined(__aarch64__) && defined(__AARCH64EL__) && !defined(__ILP32__)
898
        /* AArch64 initial CFI state */
899
        DWRF_U8(DWRF_CFA_def_cfa);            // Define CFA (Call Frame Address)
900
        DWRF_UV(DWRF_REG_SP);                 // CFA = SP register
901
        DWRF_UV(0);                           // CFA = SP + 0 (AArch64 starts with offset 0)
902
        // No initial register saves in AArch64 CIE
903
#endif
904
0
        DWRF_ALIGNNOP(sizeof(uintptr_t));     // Align to pointer boundary
905
0
    )
906
907
0
    ctx->eh_frame_p = p;  // Remember start of FDE data
908
909
    /*
910
     * Emit DWARF EH FDE (Frame Description Entry)
911
     *
912
     * The FDE describes unwinding information specific to this function.
913
     * It references the CIE and provides function-specific CFI instructions.
914
     *
915
     * The PC-relative offset is calculated after the entire EH frame is built
916
     * to ensure accurate positioning relative to the synthesized DSO layout.
917
     */
918
0
    DWRF_SECTION(FDE,
919
0
        DWRF_U32((uint32_t)(p - framep));     // Offset to CIE (backwards reference)
920
0
        ctx->fde_p = p;                        // Remember where PC offset field is located for later calculation
921
0
        DWRF_U32(0);                           // Placeholder for PC-relative offset (calculated at end of elf_init_ehframe)
922
0
        DWRF_U32(ctx->code_size);             // Address range covered by this FDE (code length)
923
0
        DWRF_U8(0);                           // Augmentation data length (none)
924
925
        /*
926
         * Architecture-specific CFI instructions
927
         *
928
         * These instructions describe how registers are saved and restored
929
         * during function calls. Each architecture has different calling
930
         * conventions and register usage patterns.
931
         */
932
0
#ifdef __x86_64__
933
        /* x86_64 calling convention unwinding rules with frame pointer */
934
#  if defined(__CET__) && (__CET__ & 1)
935
        DWRF_U8(DWRF_CFA_advance_loc | 4);    // Advance past endbr64 (4 bytes)
936
#  endif
937
0
        DWRF_U8(DWRF_CFA_advance_loc | 1);    // Advance past push %rbp (1 byte)
938
0
        DWRF_U8(DWRF_CFA_def_cfa_offset);     // def_cfa_offset 16
939
0
        DWRF_UV(16);                          // New offset: SP + 16
940
0
        DWRF_U8(DWRF_CFA_offset | DWRF_REG_BP); // offset r6 at cfa-16
941
0
        DWRF_UV(2);                           // Offset factor: 2 * 8 = 16 bytes
942
0
        DWRF_U8(DWRF_CFA_advance_loc | 3);    // Advance past mov %rsp,%rbp (3 bytes)
943
0
        DWRF_U8(DWRF_CFA_def_cfa_register);   // def_cfa_register r6
944
0
        DWRF_UV(DWRF_REG_BP);                 // Use base pointer register
945
0
        DWRF_U8(DWRF_CFA_advance_loc | 3);    // Advance past call *%rcx (2 bytes) + pop %rbp (1 byte) = 3
946
0
        DWRF_U8(DWRF_CFA_def_cfa);            // def_cfa r7 ofs 8
947
0
        DWRF_UV(DWRF_REG_SP);                 // Use stack pointer register
948
0
        DWRF_UV(8);                           // New offset: SP + 8
949
#elif defined(__aarch64__) && defined(__AARCH64EL__) && !defined(__ILP32__)
950
        /* AArch64 calling convention unwinding rules */
951
        DWRF_U8(DWRF_CFA_advance_loc | 1);        // Advance by 1 instruction (4 bytes)
952
        DWRF_U8(DWRF_CFA_def_cfa_offset);         // CFA = SP + 16
953
        DWRF_UV(16);                              // Stack pointer moved by 16 bytes
954
        DWRF_U8(DWRF_CFA_offset | DWRF_REG_FP);   // x29 (frame pointer) saved
955
        DWRF_UV(2);                               // At CFA-16 (2 * 8 = 16 bytes from CFA)
956
        DWRF_U8(DWRF_CFA_offset | DWRF_REG_RA);   // x30 (link register) saved
957
        DWRF_UV(1);                               // At CFA-8 (1 * 8 = 8 bytes from CFA)
958
        DWRF_U8(DWRF_CFA_advance_loc | 3);        // Advance by 3 instructions (12 bytes)
959
        DWRF_U8(DWRF_CFA_restore | DWRF_REG_RA);  // Restore x30 - NO DWRF_UV() after this!
960
        DWRF_U8(DWRF_CFA_restore | DWRF_REG_FP);  // Restore x29 - NO DWRF_UV() after this!
961
        DWRF_U8(DWRF_CFA_def_cfa_offset);         // CFA = SP + 0 (stack restored)
962
        DWRF_UV(0);                               // Back to original stack position
963
#else
964
#    error "Unsupported target architecture"
965
#endif
966
967
0
        DWRF_ALIGNNOP(sizeof(uintptr_t));     // Align to pointer boundary
968
0
    )
969
970
0
    ctx->p = p;  // Update context pointer to end of generated data
971
972
    /* Calculate and update the PC-relative offset in the FDE
973
     *
974
     * When perf processes the jitdump, it creates a synthesized DSO with this layout:
975
     *
976
     *     Synthesized DSO Memory Layout:
977
     *     ┌─────────────────────────────────────────────────────────────┐ < code_start
978
     *     │                        Code Section                         │
979
     *     │                    (round_up(code_size, 8) bytes)           │
980
     *     ├─────────────────────────────────────────────────────────────┤ < start of EH frame data
981
     *     │                      EH Frame Data                          │
982
     *     │  ┌─────────────────────────────────────────────────────┐    │
983
     *     │  │                 CIE data                            │    │
984
     *     │  └─────────────────────────────────────────────────────┘    │
985
     *     │  ┌─────────────────────────────────────────────────────┐    │
986
     *     │  │ FDE Header:                                         │    │
987
     *     │  │   - CIE offset (4 bytes)                            │    │
988
     *     │  │   - PC offset (4 bytes) <─ fde_offset_in_frame ─────┼────┼─> points to code_start
989
     *     │  │   - address range (4 bytes)                         │    │   (this specific field)
990
     *     │  │ CFI Instructions...                                 │    │
991
     *     │  └─────────────────────────────────────────────────────┘    │
992
     *     ├─────────────────────────────────────────────────────────────┤ < reference_point
993
     *     │                    EhFrameHeader                            │
994
     *     │                 (navigation metadata)                       │
995
     *     └─────────────────────────────────────────────────────────────┘
996
     *
997
     * The PC offset field in the FDE must contain the distance from itself to code_start:
998
     *
999
     *   distance = code_start - fde_pc_field
1000
     *
1001
     * Where:
1002
     *   fde_pc_field_location = reference_point - eh_frame_size + fde_offset_in_frame
1003
     *   code_start_location = reference_point - eh_frame_size - round_up(code_size, 8)
1004
     *
1005
     * Therefore:
1006
     *   distance = code_start_location - fde_pc_field_location
1007
     *            = (ref - eh_frame_size - rounded_code_size) - (ref - eh_frame_size + fde_offset_in_frame)
1008
     *            = -rounded_code_size - fde_offset_in_frame
1009
     *            = -(round_up(code_size, 8) + fde_offset_in_frame)
1010
     *
1011
     * Note: fde_offset_in_frame is the offset from EH frame start to the PC offset field,
1012
     *
1013
     */
1014
0
    if (ctx->fde_p != NULL) {
1015
0
        int32_t fde_offset_in_frame = (ctx->fde_p - ctx->startp);
1016
0
        int32_t rounded_code_size = round_up(ctx->code_size, 8);
1017
0
        int32_t pc_relative_offset = -(rounded_code_size + fde_offset_in_frame);
1018
1019
1020
        // Update the PC-relative offset in the FDE
1021
0
        *(int32_t*)ctx->fde_p = pc_relative_offset;
1022
0
    }
1023
0
}
1024
1025
// =============================================================================
1026
//                              JITDUMP INITIALIZATION
1027
// =============================================================================
1028
1029
/*
1030
 * Initialize the perf jitdump interface
1031
 *
1032
 * This function sets up everything needed to generate jitdump files:
1033
 * 1. Creates the jitdump file with a unique name
1034
 * 2. Maps the first page to signal perf that we're using the interface
1035
 * 3. Writes the jitdump header
1036
 * 4. Initializes synchronization primitives
1037
 *
1038
 * The memory mapping is crucial - perf detects jitdump files by scanning
1039
 * for processes that have mapped files matching the pattern /tmp/jit-*.dump
1040
 *
1041
 * Returns: Pointer to initialized state, or NULL on failure
1042
 */
1043
0
static void* perf_map_jit_init(void) {
1044
0
    char filename[100];
1045
0
    int pid = getpid();
1046
1047
    /* Create unique filename based on process ID */
1048
0
    snprintf(filename, sizeof(filename) - 1, "/tmp/jit-%d.dump", pid);
1049
1050
    /* Create/open the jitdump file with appropriate permissions */
1051
0
    const int fd = open(filename, O_CREAT | O_TRUNC | O_RDWR, 0666);
1052
0
    if (fd == -1) {
1053
0
        return NULL;  // Failed to create file
1054
0
    }
1055
1056
    /* Get system page size for memory mapping */
1057
0
    const long page_size = sysconf(_SC_PAGESIZE);
1058
0
    if (page_size == -1) {
1059
0
        close(fd);
1060
0
        return NULL;  // Failed to get page size
1061
0
    }
1062
1063
#if defined(__APPLE__)
1064
    // On macOS, samply uses a preload to find jitdumps and this mmap can be slow.
1065
    perf_jit_map_state.mapped_buffer = NULL;
1066
#else
1067
    /*
1068
     * Map the first page of the jitdump file
1069
     *
1070
     * This memory mapping serves as a signal to perf that this process
1071
     * is generating JIT code. Perf scans /proc/.../maps looking for mapped
1072
     * files that match the jitdump naming pattern.
1073
     *
1074
     * The mapping must be PROT_READ | PROT_EXEC to be detected by perf.
1075
     */
1076
0
    perf_jit_map_state.mapped_buffer = mmap(
1077
0
        NULL,                    // Let kernel choose address
1078
0
        page_size,               // Map one page
1079
0
        PROT_READ | PROT_EXEC,   // Read and execute permissions (required by perf)
1080
0
        MAP_PRIVATE,             // Private mapping
1081
0
        fd,                      // File descriptor
1082
0
        0                        // Offset 0 (first page)
1083
0
    );
1084
1085
0
    if (perf_jit_map_state.mapped_buffer == NULL) {
1086
0
        close(fd);
1087
0
        return NULL;  // Memory mapping failed
1088
0
    }
1089
0
    (void)_PyAnnotateMemoryMap(perf_jit_map_state.mapped_buffer, page_size,
1090
0
                               "cpython:perf_jit_trampoline");
1091
0
#endif
1092
1093
0
    perf_jit_map_state.mapped_size = page_size;
1094
1095
    /* Convert file descriptor to FILE* for easier I/O operations */
1096
0
    perf_jit_map_state.perf_map = fdopen(fd, "w+");
1097
0
    if (perf_jit_map_state.perf_map == NULL) {
1098
0
        close(fd);
1099
0
        return NULL;  // Failed to create FILE*
1100
0
    }
1101
1102
    /*
1103
     * Set up file buffering for better performance
1104
     *
1105
     * We use a large buffer (2MB) because jitdump files can be written
1106
     * frequently during program execution. Buffering reduces system call
1107
     * overhead and improves overall performance.
1108
     */
1109
0
    setvbuf(perf_jit_map_state.perf_map, NULL, _IOFBF, 2 * MB);
1110
1111
    /* Write the jitdump file header */
1112
0
    perf_map_jit_write_header(pid, perf_jit_map_state.perf_map);
1113
1114
    /*
1115
     * Initialize thread synchronization lock
1116
     *
1117
     * Multiple threads may attempt to write to the jitdump file
1118
     * simultaneously. This lock ensures thread-safe access to the
1119
     * global jitdump state.
1120
     */
1121
0
    perf_jit_map_state.map_lock = PyThread_allocate_lock();
1122
0
    if (perf_jit_map_state.map_lock == NULL) {
1123
0
        fclose(perf_jit_map_state.perf_map);
1124
0
        return NULL;  // Failed to create lock
1125
0
    }
1126
1127
    /* Initialize code ID counter */
1128
0
    perf_jit_map_state.code_id = 0;
1129
1130
    /* Calculate padding size based on actual unwind info requirements */
1131
0
    size_t eh_frame_size = calculate_eh_frame_size();
1132
0
    size_t unwind_data_size = sizeof(EhFrameHeader) + eh_frame_size;
1133
0
    trampoline_api.code_padding = round_up(unwind_data_size, 16);
1134
0
    trampoline_api.code_alignment = 32;
1135
1136
0
    return &perf_jit_map_state;
1137
0
}
1138
1139
// =============================================================================
1140
//                              MAIN JITDUMP ENTRY WRITING
1141
// =============================================================================
1142
1143
/*
1144
 * Write a complete jitdump entry for a Python function
1145
 *
1146
 * This is the main function called by Python's trampoline system whenever
1147
 * a new piece of JIT-compiled code needs to be recorded. It writes both
1148
 * the unwinding information and the code load event to the jitdump file.
1149
 *
1150
 * The function performs these steps:
1151
 * 1. Initialize jitdump system if not already done
1152
 * 2. Extract function name and filename from Python code object
1153
 * 3. Generate DWARF unwinding information
1154
 * 4. Write unwinding info event to jitdump file
1155
 * 5. Write code load event to jitdump file
1156
 *
1157
 * Args:
1158
 *   state: Jitdump state (currently unused, uses global state)
1159
 *   code_addr: Address where the compiled code resides
1160
 *   code_size: Size of the compiled code in bytes
1161
 *   co: Python code object containing metadata
1162
 *
1163
 * IMPORTANT: This function signature is part of Python's internal API
1164
 * and must not be changed without coordinating with core Python development.
1165
 */
1166
static void perf_map_jit_write_entry(void *state, const void *code_addr,
1167
                                    unsigned int code_size, PyCodeObject *co)
1168
0
{
1169
    /* Initialize jitdump system on first use */
1170
0
    if (perf_jit_map_state.perf_map == NULL) {
1171
0
        void* ret = perf_map_jit_init();
1172
0
        if(ret == NULL){
1173
0
            return;  // Initialization failed, silently abort
1174
0
        }
1175
0
    }
1176
1177
    /*
1178
     * Extract function information from Python code object
1179
     *
1180
     * We create a human-readable function name by combining the qualified
1181
     * name (includes class/module context) with the filename. This helps
1182
     * developers identify functions in perf reports.
1183
     */
1184
0
    const char *entry = "";
1185
0
    if (co->co_qualname != NULL) {
1186
0
        entry = PyUnicode_AsUTF8(co->co_qualname);
1187
0
    }
1188
1189
0
    const char *filename = "";
1190
0
    if (co->co_filename != NULL) {
1191
0
        filename = PyUnicode_AsUTF8(co->co_filename);
1192
0
    }
1193
1194
    /*
1195
     * Create formatted function name for perf display
1196
     *
1197
     * Format: "py::<function_name>:<filename>"
1198
     * The "py::" prefix helps identify Python functions in mixed-language
1199
     * profiles (e.g., when profiling C extensions alongside Python code).
1200
     */
1201
0
    size_t perf_map_entry_size = snprintf(NULL, 0, "py::%s:%s", entry, filename) + 1;
1202
0
    char* perf_map_entry = (char*) PyMem_RawMalloc(perf_map_entry_size);
1203
0
    if (perf_map_entry == NULL) {
1204
0
        return;  // Memory allocation failed
1205
0
    }
1206
0
    snprintf(perf_map_entry, perf_map_entry_size, "py::%s:%s", entry, filename);
1207
1208
0
    const size_t name_length = strlen(perf_map_entry);
1209
0
    uword base = (uword)code_addr;
1210
0
    uword size = code_size;
1211
1212
    /*
1213
     * Generate DWARF unwinding information
1214
     *
1215
     * DWARF data is essential for proper stack unwinding during profiling.
1216
     * Without it, perf cannot generate accurate call graphs, especially
1217
     * in optimized code where frame pointers may be omitted.
1218
     */
1219
0
    ELFObjectContext ctx;
1220
0
    char buffer[1024];  // Buffer for DWARF data (1KB should be sufficient)
1221
0
    ctx.code_size = code_size;
1222
0
    ctx.startp = ctx.p = (uint8_t*)buffer;
1223
0
    ctx.fde_p = NULL;  // Initialize to NULL, will be set when FDE is written
1224
1225
    /* Generate EH frame (Exception Handling frame) data */
1226
0
    elf_init_ehframe(&ctx);
1227
0
    int eh_frame_size = ctx.p - ctx.startp;
1228
1229
    /*
1230
     * Write Code Unwinding Information Event
1231
     *
1232
     * This event must be written before the code load event to ensure
1233
     * perf has the unwinding information available when it processes
1234
     * the code region.
1235
     */
1236
0
    CodeUnwindingInfoEvent ev2;
1237
0
    ev2.base.event = PerfUnwindingInfo;
1238
0
    ev2.base.time_stamp = get_current_monotonic_ticks();
1239
0
    ev2.unwind_data_size = sizeof(EhFrameHeader) + eh_frame_size;
1240
1241
    /* Verify we don't exceed our padding budget */
1242
0
    assert(ev2.unwind_data_size <= (uint64_t)trampoline_api.code_padding);
1243
1244
0
    ev2.eh_frame_hdr_size = sizeof(EhFrameHeader);
1245
0
    ev2.mapped_size = round_up(ev2.unwind_data_size, 16);  // 16-byte alignment
1246
1247
    /* Calculate total event size with padding */
1248
0
    int content_size = sizeof(ev2) + sizeof(EhFrameHeader) + eh_frame_size;
1249
0
    int padding_size = round_up(content_size, 8) - content_size;  // 8-byte align
1250
0
    ev2.base.size = content_size + padding_size;
1251
1252
    /* Write the unwinding info event header */
1253
0
    perf_map_jit_write_fully(&ev2, sizeof(ev2));
1254
1255
    /*
1256
     * Write EH Frame Header
1257
     *
1258
     * The EH frame header provides metadata about the DWARF unwinding
1259
     * information that follows. It includes pointers and counts that
1260
     * help perf navigate the unwinding data efficiently.
1261
     */
1262
0
    EhFrameHeader f;
1263
0
    f.version = 1;
1264
0
    f.eh_frame_ptr_enc = DwarfSData4 | DwarfPcRel;  // PC-relative signed 4-byte
1265
0
    f.fde_count_enc = DwarfUData4;                  // Unsigned 4-byte count
1266
0
    f.table_enc = DwarfSData4 | DwarfDataRel;       // Data-relative signed 4-byte
1267
1268
    /* Calculate relative offsets for EH frame navigation */
1269
0
    f.eh_frame_ptr = -(eh_frame_size + 4 * sizeof(unsigned char));
1270
0
    f.eh_fde_count = 1;  // We generate exactly one FDE per function
1271
0
    f.from = -(round_up(code_size, 8) + eh_frame_size);
1272
1273
0
    int cie_size = ctx.eh_frame_p - ctx.startp;
1274
0
    f.to = -(eh_frame_size - cie_size);
1275
1276
    /* Write EH frame data and header */
1277
0
    perf_map_jit_write_fully(ctx.startp, eh_frame_size);
1278
0
    perf_map_jit_write_fully(&f, sizeof(f));
1279
1280
    /* Write padding to maintain alignment */
1281
0
    char padding_bytes[] = "\0\0\0\0\0\0\0\0";
1282
0
    perf_map_jit_write_fully(&padding_bytes, padding_size);
1283
1284
    /*
1285
     * Write Code Load Event
1286
     *
1287
     * This event tells perf about the new code region. It includes:
1288
     * - Memory addresses and sizes
1289
     * - Process and thread identification
1290
     * - Function name for symbol resolution
1291
     * - The actual machine code bytes
1292
     */
1293
0
    CodeLoadEvent ev;
1294
0
    ev.base.event = PerfLoad;
1295
0
    ev.base.size = sizeof(ev) + (name_length+1) + size;
1296
0
    ev.base.time_stamp = get_current_monotonic_ticks();
1297
0
    ev.process_id = getpid();
1298
#if defined(__APPLE__)
1299
    pthread_threadid_np(NULL, &ev.thread_id);
1300
#else
1301
0
    ev.thread_id = syscall(SYS_gettid);  // Get thread ID via system call
1302
0
#endif
1303
0
    ev.vma = base;                       // Virtual memory address
1304
0
    ev.code_address = base;              // Same as VMA for our use case
1305
0
    ev.code_size = size;
1306
1307
    /* Assign unique code ID and increment counter */
1308
0
    perf_jit_map_state.code_id += 1;
1309
0
    ev.code_id = perf_jit_map_state.code_id;
1310
1311
    /* Write code load event and associated data */
1312
0
    perf_map_jit_write_fully(&ev, sizeof(ev));
1313
0
    perf_map_jit_write_fully(perf_map_entry, name_length+1);  // Include null terminator
1314
0
    perf_map_jit_write_fully((void*)(base), size);           // Copy actual machine code
1315
1316
    /* Clean up allocated memory */
1317
0
    PyMem_RawFree(perf_map_entry);
1318
0
}
1319
1320
// =============================================================================
1321
//                              CLEANUP AND FINALIZATION
1322
// =============================================================================
1323
1324
/*
1325
 * Finalize and cleanup the perf jitdump system
1326
 *
1327
 * This function is called when Python is shutting down or when the
1328
 * perf trampoline system is being disabled. It ensures all resources
1329
 * are properly released and all buffered data is flushed to disk.
1330
 *
1331
 * Args:
1332
 *   state: Jitdump state (currently unused, uses global state)
1333
 *
1334
 * Returns: 0 on success
1335
 *
1336
 * IMPORTANT: This function signature is part of Python's internal API
1337
 * and must not be changed without coordinating with core Python development.
1338
 */
1339
0
static int perf_map_jit_fini(void* state) {
1340
    /*
1341
     * Close jitdump file with proper synchronization
1342
     *
1343
     * We need to acquire the lock to ensure no other threads are
1344
     * writing to the file when we close it. This prevents corruption
1345
     * and ensures all data is properly flushed.
1346
     */
1347
0
    if (perf_jit_map_state.perf_map != NULL) {
1348
0
        PyThread_acquire_lock(perf_jit_map_state.map_lock, 1);
1349
0
        fclose(perf_jit_map_state.perf_map);  // This also flushes buffers
1350
0
        PyThread_release_lock(perf_jit_map_state.map_lock);
1351
1352
        /* Clean up synchronization primitive */
1353
0
        PyThread_free_lock(perf_jit_map_state.map_lock);
1354
0
        perf_jit_map_state.perf_map = NULL;
1355
0
    }
1356
1357
    /*
1358
     * Unmap the memory region
1359
     *
1360
     * This removes the signal to perf that we were generating JIT code.
1361
     * After this point, perf will no longer detect this process as
1362
     * having JIT capabilities.
1363
     */
1364
0
    if (perf_jit_map_state.mapped_buffer != NULL) {
1365
0
        munmap(perf_jit_map_state.mapped_buffer, perf_jit_map_state.mapped_size);
1366
0
        perf_jit_map_state.mapped_buffer = NULL;
1367
0
    }
1368
1369
    /* Clear global state reference */
1370
0
    trampoline_api.state = NULL;
1371
1372
0
    return 0;  // Success
1373
0
}
1374
1375
// =============================================================================
1376
//                              PUBLIC API EXPORT
1377
// =============================================================================
1378
1379
/*
1380
 * Python Perf Callbacks Structure
1381
 *
1382
 * This structure defines the callback interface that Python's trampoline
1383
 * system uses to integrate with perf profiling. It contains function
1384
 * pointers for initialization, event writing, and cleanup.
1385
 *
1386
 * CRITICAL: This structure and its contents are part of Python's internal
1387
 * API. The function signatures and behavior must remain stable to maintain
1388
 * compatibility with the Python interpreter's perf integration system.
1389
 *
1390
 * Used by: Python's _PyPerf_Callbacks system in pycore_ceval.h
1391
 */
1392
_PyPerf_Callbacks _Py_perfmap_jit_callbacks = {
1393
    &perf_map_jit_init,        // Initialization function
1394
    &perf_map_jit_write_entry, // Event writing function
1395
    &perf_map_jit_fini,        // Cleanup function
1396
};
1397
1398
#endif /* PY_HAVE_PERF_TRAMPOLINE */