Repository navigation
Expand file tree
/
Copy pathbinary_io_reader.c
More file actions
1994 lines (1831 loc) · 68.4 KB
/
Copy pathbinary_io_reader.c
File metadata and controls
1994 lines (1831 loc) · 68.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******************************************************************************
* Python Remote Debugging Module - Binary Reader Implementation
*
* High-performance binary file reader for profiling data with optional zstd
* decompression.
******************************************************************************/
#ifndef Py_BUILD_CORE_MODULE
# define Py_BUILD_CORE_MODULE
#endif
#include "binary_io.h"
#include "_remote_debugging.h"
#include "pycore_bitutils.h" /* _Py_bswap32, _Py_bswap64 for cross-endian reading */
#include <math.h>
#include <string.h>
#ifdef HAVE_ZSTD
#include <zstd.h>
#endif
#ifdef _Py_MEMORY_SANITIZER
# include <sanitizer/msan_interface.h>
#endif
/* ============================================================================
* CONSTANTS FOR BINARY FORMAT SIZES
* ============================================================================ */
/* Progress callback frequency */
#define PROGRESS_CALLBACK_INTERVAL 1000
/* Cap per-batch RLE samples to bound the timestamp list (gh-151378) */
#define MAX_RLE_BATCH_SAMPLES 8192
#define FRAME_INFO_CACHE_SIZE 1024
#if !USE_MMAP
/* The block parser limits stored columns to MAX_BLOCK_SIZE */
#define MAX_STORED_BLOCK_SIZE (MAX_BLOCK_SIZE + 1024)
/* Replay reads samples through a window that fits any block */
#define SAMPLE_WINDOW_SIZE (2 * MAX_BLOCK_SIZE)
#endif
/* ============================================================================
* BINARY READER IMPLEMENTATION
* ============================================================================ */
static inline int
reader_parse_header(BinaryReader *reader, const uint8_t *data, size_t file_size)
{
if (file_size < FILE_HEADER_PLACEHOLDER_SIZE) {
PyErr_SetString(PyExc_ValueError, "File too small for header");
return -1;
}
/* Use memcpy to avoid strict aliasing violations and unaligned access */
uint32_t magic;
uint32_t version;
memcpy(&magic, &data[HDR_OFF_MAGIC], HDR_SIZE_MAGIC);
memcpy(&version, &data[HDR_OFF_VERSION], HDR_SIZE_VERSION);
/* Detect endianness from magic number */
if (magic == BINARY_FORMAT_MAGIC) {
reader->needs_swap = 0;
} else if (magic == BINARY_FORMAT_MAGIC_SWAPPED) {
reader->needs_swap = 1;
version = _Py_bswap32(version);
} else {
PyErr_Format(PyExc_ValueError, "Invalid magic number: 0x%08x", magic);
return -1;
}
if (version != BINARY_FORMAT_VERSION) {
if (version > BINARY_FORMAT_VERSION && file_size >= HDR_OFF_PY_MICRO + 1) {
/* Newer format - try to read Python version for better error */
uint8_t py_major = data[HDR_OFF_PY_MAJOR];
uint8_t py_minor = data[HDR_OFF_PY_MINOR];
uint8_t py_micro = data[HDR_OFF_PY_MICRO];
PyErr_Format(PyExc_ValueError,
"Binary file was created with Python %u.%u.%u (format version %u), "
"but this is Python %d.%d.%d (format version %d)",
py_major, py_minor, py_micro, version,
PY_MAJOR_VERSION, PY_MINOR_VERSION, PY_MICRO_VERSION,
BINARY_FORMAT_VERSION);
} else {
PyErr_Format(PyExc_ValueError,
"Unsupported format version %u (this reader supports version %d)",
version, BINARY_FORMAT_VERSION);
}
return -1;
}
reader->py_major = data[HDR_OFF_PY_MAJOR];
reader->py_minor = data[HDR_OFF_PY_MINOR];
reader->py_micro = data[HDR_OFF_PY_MICRO];
/* Read header fields with byte-swapping if needed */
uint64_t start_time_us, sample_interval_us, string_table_offset, frame_table_offset;
uint64_t sample_count;
uint32_t thread_count, compression_type, profiling_config;
memcpy(&start_time_us, &data[HDR_OFF_START_TIME], HDR_SIZE_START_TIME);
memcpy(&sample_interval_us, &data[HDR_OFF_INTERVAL], HDR_SIZE_INTERVAL);
memcpy(&sample_count, &data[HDR_OFF_SAMPLES], HDR_SIZE_SAMPLES);
memcpy(&thread_count, &data[HDR_OFF_THREADS], HDR_SIZE_THREADS);
memcpy(&string_table_offset, &data[HDR_OFF_STR_TABLE], HDR_SIZE_STR_TABLE);
memcpy(&frame_table_offset, &data[HDR_OFF_FRAME_TABLE], HDR_SIZE_FRAME_TABLE);
memcpy(&compression_type, &data[HDR_OFF_COMPRESSION], HDR_SIZE_COMPRESSION);
memcpy(&profiling_config, &data[HDR_OFF_CONFIG], HDR_SIZE_CONFIG);
reader->start_time_us = SWAP64_IF(reader->needs_swap, start_time_us);
reader->sample_interval_us = SWAP64_IF(reader->needs_swap, sample_interval_us);
reader->sample_count = SWAP64_IF(reader->needs_swap, sample_count);
reader->thread_count = SWAP32_IF(reader->needs_swap, thread_count);
reader->string_table_offset = SWAP64_IF(reader->needs_swap, string_table_offset);
reader->frame_table_offset = SWAP64_IF(reader->needs_swap, frame_table_offset);
reader->compression_type = (int)SWAP32_IF(reader->needs_swap, compression_type);
profiling_config = SWAP32_IF(reader->needs_swap, profiling_config);
uint32_t profiling_mode =
profiling_config & PROFILING_CONFIG_MODE_MASK;
if (profiling_mode > PROFILING_MODE_EXCEPTION + 1) {
PyErr_Format(PyExc_ValueError,
"Invalid profiling mode in header: %u", profiling_mode);
return -1;
}
reader->profiling_mode = (int)profiling_mode - 1;
reader->capture_features =
profiling_config & PROFILING_CONFIG_FEATURES_KNOWN
? (int)((profiling_config >> PROFILING_CONFIG_FEATURES_SHIFT) &
PROFILING_FEATURE_MASK)
: -1;
return 0;
}
static inline int
reader_parse_footer(BinaryReader *reader, const uint8_t *data, size_t file_size)
{
if (file_size < FILE_FOOTER_SIZE) {
PyErr_SetString(PyExc_ValueError, "File too small for footer");
return -1;
}
const uint8_t *footer = data + file_size - FILE_FOOTER_SIZE;
/* Use memcpy to avoid strict aliasing violations */
uint32_t strings_count, frames_count;
memcpy(&strings_count, &footer[FTR_OFF_STRINGS], FTR_SIZE_STRINGS);
memcpy(&frames_count, &footer[FTR_OFF_FRAMES], FTR_SIZE_FRAMES);
reader->strings_count = SWAP32_IF(reader->needs_swap, strings_count);
reader->frames_count = SWAP32_IF(reader->needs_swap, frames_count);
return 0;
}
static inline int
reader_parse_profile_stats(BinaryReader *reader, const uint8_t *data,
size_t file_size)
{
size_t minimum_size = FILE_FOOTER_SIZE + PROFILE_STATS_V1_SIZE;
if (file_size < minimum_size) {
return 0;
}
const uint8_t *stats_end = data + file_size - FILE_FOOTER_SIZE;
const uint8_t *stats_tail = stats_end - PROFILE_STATS_MAGIC_SIZE -
PST_SIZE_VERSION - PST_SIZE_SIZE;
if (memcmp(stats_tail,
PROFILE_STATS_MAGIC, PROFILE_STATS_MAGIC_SIZE) != 0) {
return 0;
}
uint32_t version, size;
memcpy(&version, stats_tail + PROFILE_STATS_MAGIC_SIZE,
PST_SIZE_VERSION);
memcpy(&size, stats_tail + PROFILE_STATS_MAGIC_SIZE + PST_SIZE_VERSION,
PST_SIZE_SIZE);
version = SWAP32_IF(reader->needs_swap, version);
size = SWAP32_IF(reader->needs_swap, size);
if (size < PROFILE_STATS_V1_SIZE ||
size > file_size - FILE_FOOTER_SIZE) {
PyErr_SetString(PyExc_ValueError,
"Invalid profiling statistics size");
return -1;
}
if (version != PROFILE_STATS_VERSION) {
return 0;
}
const uint8_t *trailer = stats_end - size;
uint64_t duration_bits, sample_rate_bits;
memcpy(&duration_bits, trailer + PST_OFF_DURATION, PST_SIZE_DURATION);
memcpy(&sample_rate_bits, trailer + PST_OFF_SAMPLE_RATE,
PST_SIZE_SAMPLE_RATE);
duration_bits = SWAP64_IF(reader->needs_swap, duration_bits);
sample_rate_bits = SWAP64_IF(reader->needs_swap, sample_rate_bits);
memcpy(&reader->duration_sec, &duration_bits, sizeof(duration_bits));
memcpy(&reader->sample_rate, &sample_rate_bits, sizeof(sample_rate_bits));
if (!isfinite(reader->duration_sec) || reader->duration_sec < 0.0 ||
!isfinite(reader->sample_rate) || reader->sample_rate < 0.0) {
PyErr_SetString(PyExc_ValueError,
"Invalid profiling statistics values");
return -1;
}
reader->has_profile_stats = 1;
if (size >= PROFILE_STATS_SIZE) {
uint64_t error_rate_bits, missed_samples_bits;
uint32_t present;
memcpy(&error_rate_bits, trailer + PST_OFF_ERROR_RATE,
PST_SIZE_ERROR_RATE);
memcpy(&missed_samples_bits, trailer + PST_OFF_MISSED_SAMPLES,
PST_SIZE_MISSED_SAMPLES);
memcpy(&present, trailer + PST_OFF_PRESENT, PST_SIZE_PRESENT);
error_rate_bits = SWAP64_IF(reader->needs_swap, error_rate_bits);
missed_samples_bits = SWAP64_IF(reader->needs_swap,
missed_samples_bits);
present = SWAP32_IF(reader->needs_swap, present);
memcpy(&reader->error_rate, &error_rate_bits,
sizeof(error_rate_bits));
memcpy(&reader->missed_samples, &missed_samples_bits,
sizeof(missed_samples_bits));
if (((present & PROFILE_STATS_ERROR_RATE) &&
(!isfinite(reader->error_rate) || reader->error_rate < 0.0)) ||
((present & PROFILE_STATS_MISSED) &&
!isfinite(reader->missed_samples))) {
PyErr_SetString(PyExc_ValueError,
"Invalid profiling statistics values");
return -1;
}
reader->profile_stats_present = present;
}
return 0;
}
static int
reader_decompress(BinaryReader *reader, const uint8_t *compressed_data,
size_t compressed_size, ByteBuffer *output,
size_t decoded_size)
{
#ifdef HAVE_ZSTD
/* The data must be exactly one zstd frame */
size_t frame_size = ZSTD_findFrameCompressedSize(compressed_data,
compressed_size);
if (ZSTD_isError(frame_size) || frame_size != compressed_size) {
PyErr_SetString(PyExc_ValueError, "Corrupted zstd frame header");
return -1;
}
/* Check the decompressed size recorded in the frame header before
* allocating for it */
unsigned long long frame_content_size = ZSTD_getFrameContentSize(compressed_data, compressed_size);
if (frame_content_size == ZSTD_CONTENTSIZE_ERROR) {
/* Corrupted frame header - fail early */
PyErr_SetString(PyExc_ValueError, "Corrupted zstd frame header");
return -1;
}
if (frame_content_size != decoded_size) {
PyErr_SetString(PyExc_ValueError,
"zstd frame size does not match the decoded size");
return -1;
}
/* Append the decoded data to the output buffer */
if (buffer_reserve(output, output->size + decoded_size) < 0) {
return -1;
}
uint8_t *decoded = output->data + output->size;
size_t result = ZSTD_decompressDCtx(reader->dctx, decoded, decoded_size,
compressed_data, compressed_size);
if (ZSTD_isError(result)) {
PyErr_Format(PyExc_ValueError, "zstd decompression error: %s",
ZSTD_getErrorName(result));
return -1;
}
/* Verify decompression is complete */
if (result != decoded_size) {
PyErr_SetString(PyExc_ValueError, "Incomplete zstd frame: data may be truncated");
return -1;
}
_Py_MSAN_UNPOISON(decoded, decoded_size);
output->size += decoded_size;
return 0;
#else
PyErr_SetString(PyExc_RuntimeError,
"File uses zstd compression but zstd support not compiled in");
return -1;
#endif
}
/* Reject a table/run count whose entries cannot fit in the bytes still
* available; a malicious file could otherwise drive a huge allocation.
* Each entry occupies at least min_entry_size bytes. */
static int
reader_validate_count(const char *what, uint32_t count,
size_t available_bytes, size_t min_entry_size)
{
size_t max_possible = available_bytes / min_entry_size;
if (count > max_possible) {
PyErr_Format(PyExc_ValueError,
"Invalid %s count %u exceeds maximum possible %zu",
what, count, max_possible);
return -1;
}
return 0;
}
static inline int
reader_parse_string_table(BinaryReader *reader, const uint8_t *data,
size_t size, size_t offset)
{
if (reader_validate_count("string", reader->strings_count, size - offset,
MIN_STRING_ENTRY_SIZE) < 0) {
return -1;
}
reader->strings = PyMem_Calloc(reader->strings_count, sizeof(PyObject *));
if (!reader->strings && reader->strings_count > 0) {
PyErr_NoMemory();
return -1;
}
for (uint32_t i = 0; i < reader->strings_count; i++) {
size_t prev_offset = offset;
uint32_t str_len = decode_varint_u32(data, &offset, size);
if (offset == prev_offset) {
PyErr_SetString(PyExc_ValueError, "Malformed varint in string table");
return -1;
}
if (offset > size || str_len > size - offset) {
PyErr_SetString(PyExc_ValueError, "String table overflow");
return -1;
}
reader->strings[i] = PyUnicode_DecodeUTF8((char *)&data[offset], str_len, "replace");
if (!reader->strings[i]) {
return -1;
}
offset += str_len;
}
return 0;
}
static inline int
reader_parse_frame_table(BinaryReader *reader, const uint8_t *data,
size_t size, size_t offset)
{
/* Check for integer overflow in allocation size calculation. */
#if SIZEOF_SIZE_T < 8
if (reader->frames_count > SIZE_MAX / sizeof(FrameEntry)) {
PyErr_SetString(PyExc_OverflowError, "Frame count too large for allocation");
return -1;
}
#endif
if (reader_validate_count("frame", reader->frames_count, size - offset,
MIN_FRAME_ENTRY_SIZE) < 0) {
return -1;
}
size_t alloc_size = (size_t)reader->frames_count * sizeof(FrameEntry);
reader->frames = PyMem_Malloc(alloc_size);
if (!reader->frames && reader->frames_count > 0) {
PyErr_NoMemory();
return -1;
}
for (uint32_t i = 0; i < reader->frames_count; i++) {
FrameEntry *frame = &reader->frames[i];
size_t prev_offset;
prev_offset = offset;
frame->filename_idx = decode_varint_u32(data, &offset, size);
if (offset == prev_offset) {
PyErr_SetString(PyExc_ValueError, "Malformed varint in frame table (filename)");
return -1;
}
prev_offset = offset;
frame->funcname_idx = decode_varint_u32(data, &offset, size);
if (offset == prev_offset) {
PyErr_SetString(PyExc_ValueError, "Malformed varint in frame table (funcname)");
return -1;
}
prev_offset = offset;
frame->lineno = decode_varint_i32(data, &offset, size);
if (offset == prev_offset) {
PyErr_SetString(PyExc_ValueError, "Malformed varint in frame table (lineno)");
return -1;
}
prev_offset = offset;
int32_t end_lineno_delta = decode_varint_i32(data, &offset, size);
if (offset == prev_offset) {
PyErr_SetString(PyExc_ValueError, "Malformed varint in frame table (end_lineno_delta)");
return -1;
}
/* Reconstruct end_lineno from delta. If lineno is -1, result is -1. */
if (frame->lineno == LOCATION_NOT_AVAILABLE) {
frame->end_lineno = LOCATION_NOT_AVAILABLE;
} else {
frame->end_lineno = frame->lineno + end_lineno_delta;
}
prev_offset = offset;
frame->column = decode_varint_i32(data, &offset, size);
if (offset == prev_offset) {
PyErr_SetString(PyExc_ValueError, "Malformed varint in frame table (column)");
return -1;
}
prev_offset = offset;
int32_t end_column_delta = decode_varint_i32(data, &offset, size);
if (offset == prev_offset) {
PyErr_SetString(PyExc_ValueError, "Malformed varint in frame table (end_column_delta)");
return -1;
}
/* Reconstruct end_column from delta. If column is -1, result is -1. */
if (frame->column == LOCATION_NOT_AVAILABLE) {
frame->end_column = LOCATION_NOT_AVAILABLE;
} else {
frame->end_column = frame->column + end_column_delta;
}
/* Read opcode byte */
if (offset >= size) {
PyErr_SetString(PyExc_ValueError, "Unexpected end of frame table (opcode)");
return -1;
}
frame->opcode = data[offset++];
}
return 0;
}
#if USE_MMAP && defined(__linux__) && defined(MADV_DONTNEED)
static size_t
reader_discard_mapped_pages(BinaryReader *reader, size_t start, size_t end)
{
start = _Py_SIZE_ROUND_UP(start, reader->page_size);
end = _Py_SIZE_ROUND_DOWN(end, reader->page_size);
if (start >= end) {
return start;
}
(void)madvise(reader->mapped_data + start, end - start, MADV_DONTNEED);
return end;
}
#else
static inline size_t
reader_discard_mapped_pages(BinaryReader *reader, size_t start, size_t end)
{
return end;
}
#endif
#if !USE_MMAP
/* Checked fread with GIL release - returns 0 on success, -1 on error */
static int
fread_checked_allow_threads(void *data, size_t size, FILE *fp)
{
size_t nread;
Py_BEGIN_ALLOW_THREADS
nread = fread(data, 1, size, fp);
Py_END_ALLOW_THREADS
if (nread != size) {
int err = errno;
if (ferror(fp) && err != 0) {
errno = err;
PyErr_SetFromErrno(PyExc_IOError);
}
else {
PyErr_Format(PyExc_ValueError,
"Unexpected end of file: read %zu of %zu bytes",
nread, size);
}
return -1;
}
return 0;
}
static int
reader_read_at(BinaryReader *reader, size_t offset, uint8_t *buffer,
size_t size)
{
if (FSEEK64(reader->fp, (file_offset_t)offset, SEEK_SET) != 0) {
PyErr_SetFromErrno(PyExc_IOError);
return -1;
}
return fread_checked_allow_threads(buffer, size, reader->fp);
}
#endif
BinaryReader *
binary_reader_open(PyObject *path)
{
BinaryReader *reader = PyMem_Calloc(1, sizeof(BinaryReader));
if (!reader) {
PyErr_NoMemory();
return NULL;
}
#if USE_MMAP
/* Open with mmap on Unix */
FILE *fp = Py_fopen(path, "rb");
if (!fp) {
goto error;
}
int fd = fileno(fp);
struct stat st;
if (fstat(fd, &st) < 0) {
PyErr_SetFromErrno(PyExc_IOError);
Py_fclose(fp);
goto error;
}
if (st.st_size < 0) {
PyErr_SetString(PyExc_IOError, "Invalid negative file size");
Py_fclose(fp);
goto error;
}
if ((uintmax_t)st.st_size > SIZE_MAX) {
PyErr_SetString(PyExc_OverflowError, "File is too large to map");
Py_fclose(fp);
goto error;
}
reader->mapped_size = st.st_size;
if (reader->mapped_size == 0) {
PyErr_SetString(PyExc_ValueError, "File too small for header");
Py_fclose(fp);
goto error;
}
reader->mapped_data = mmap(NULL, reader->mapped_size, PROT_READ,
MAP_PRIVATE, fd, 0);
if (reader->mapped_data == MAP_FAILED) {
reader->mapped_data = NULL;
PyErr_SetFromErrno(PyExc_IOError);
Py_fclose(fp);
goto error;
}
reader->page_size = (size_t)sysconf(_SC_PAGESIZE);
/* Hint sequential access pattern - failures are non-fatal */
(void)madvise(reader->mapped_data, reader->mapped_size, MADV_SEQUENTIAL);
/* Use transparent huge pages for large files to reduce TLB misses.
* Only beneficial for files >= 32MB where TLB pressure matters. */
#ifdef MADV_HUGEPAGE
if (reader->mapped_size >= (32 * 1024 * 1024)) {
(void)madvise(reader->mapped_data, reader->mapped_size, MADV_HUGEPAGE);
}
#endif
/* Add file descriptor-level hints for better kernel I/O scheduling */
#if defined(__linux__) && defined(POSIX_FADV_SEQUENTIAL)
(void)posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL);
#endif
if (Py_fclose(fp) != 0) {
PyErr_SetFromErrno(PyExc_IOError);
goto error;
}
uint8_t *data = reader->mapped_data;
size_t file_size = reader->mapped_size;
#else
/* Use stdio on Windows. Read the header and tables now, samples during
* replay. */
reader->fp = Py_fopen(path, "rb");
if (!reader->fp) {
goto error;
}
if (FSEEK64(reader->fp, 0, SEEK_END) != 0) {
PyErr_SetFromErrno(PyExc_IOError);
goto error;
}
file_offset_t file_size_off = FTELL64(reader->fp);
if (file_size_off < 0) {
PyErr_SetFromErrno(PyExc_IOError);
goto error;
}
if ((uint64_t)file_size_off > SIZE_MAX) {
PyErr_SetString(PyExc_OverflowError, "File is too large to read");
goto error;
}
reader->file_size = (size_t)file_size_off;
if (reader->file_size == 0) {
PyErr_SetString(PyExc_ValueError, "File too small for header");
goto error;
}
uint8_t data[FILE_HEADER_PLACEHOLDER_SIZE];
size_t file_size = reader->file_size;
if (reader_read_at(reader, 0, data,
Py_MIN(file_size, sizeof(data))) < 0) {
goto error;
}
#endif
if (reader_parse_header(reader, data, file_size) < 0) {
goto error;
}
/* Validate table offsets are within file bounds */
if (reader->string_table_offset > file_size) {
PyErr_Format(PyExc_ValueError,
"Invalid string table offset: %llu exceeds file size %zu",
(unsigned long long)reader->string_table_offset, file_size);
goto error;
}
if (reader->frame_table_offset > file_size) {
PyErr_Format(PyExc_ValueError,
"Invalid frame table offset: %llu exceeds file size %zu",
(unsigned long long)reader->frame_table_offset, file_size);
goto error;
}
if (reader->string_table_offset < FILE_HEADER_PLACEHOLDER_SIZE) {
PyErr_Format(PyExc_ValueError,
"Invalid string table offset: %llu is before data section",
(unsigned long long)reader->string_table_offset);
goto error;
}
if (reader->frame_table_offset < FILE_HEADER_PLACEHOLDER_SIZE) {
PyErr_Format(PyExc_ValueError,
"Invalid frame table offset: %llu is before data section",
(unsigned long long)reader->frame_table_offset);
goto error;
}
if (reader->string_table_offset > reader->frame_table_offset) {
PyErr_Format(PyExc_ValueError,
"Invalid table offsets: string table (%llu) is after frame table (%llu)",
(unsigned long long)reader->string_table_offset,
(unsigned long long)reader->frame_table_offset);
goto error;
}
if (reader->compression_type == COMPRESSION_ZSTD) {
#ifdef HAVE_ZSTD
reader->dctx = ZSTD_createDCtx();
if (!reader->dctx) {
PyErr_SetString(PyExc_MemoryError, "Failed to create zstd decompression context");
goto error;
}
#else
PyErr_SetString(PyExc_RuntimeError,
"File uses zstd compression but zstd support not compiled in");
goto error;
#endif
}
reader->sample_data_size =
(size_t)reader->string_table_offset - FILE_HEADER_PLACEHOLDER_SIZE;
/* Tables, statistics and footer follow the samples. The footer is
* always the last bytes of the file. */
size_t tail_offset = Py_MIN((size_t)reader->string_table_offset,
file_size - FILE_FOOTER_SIZE);
size_t tail_size = file_size - tail_offset;
#if USE_MMAP
reader->sample_data = data + FILE_HEADER_PLACEHOLDER_SIZE;
const uint8_t *tail = data + tail_offset;
#else
reader->table_data = PyMem_Malloc(tail_size);
if (!reader->table_data) {
PyErr_NoMemory();
goto error;
}
if (reader_read_at(reader, tail_offset, reader->table_data,
tail_size) < 0) {
goto error;
}
const uint8_t *tail = reader->table_data;
#endif
if (reader_parse_footer(reader, tail, tail_size) < 0 ||
reader_parse_profile_stats(reader, tail, tail_size) < 0 ||
reader_parse_string_table(
reader, tail, tail_size,
(size_t)reader->string_table_offset - tail_offset) < 0 ||
reader_parse_frame_table(
reader, tail, tail_size,
(size_t)reader->frame_table_offset - tail_offset) < 0) {
goto error;
}
#if USE_MMAP
(void)reader_discard_mapped_pages(reader, tail_offset, file_size);
#else
PyMem_Free(reader->table_data);
reader->table_data = NULL;
#endif
return reader;
error:
binary_reader_close(reader);
return NULL;
}
/* Get or create reader thread state for stack reconstruction */
static ThreadEntry *
reader_get_or_create_thread_state(BinaryReader *reader, uint64_t thread_id,
uint32_t interpreter_id)
{
/* Search existing threads (key is thread_id + interpreter_id) */
for (size_t i = 0; i < reader->thread_state_count; i++) {
if (reader->thread_states[i].thread_id == thread_id &&
reader->thread_states[i].interpreter_id == interpreter_id) {
return &reader->thread_states[i];
}
}
if (reader->thread_state_count >= reader->thread_count) {
PyErr_Format(PyExc_ValueError,
"Invalid thread count: sample data contains more unique threads than declared in header "
"(declared %u, found at least %zu)",
reader->thread_count, reader->thread_state_count + 1);
return NULL;
}
if (!reader->thread_states) {
reader->thread_state_capacity = 16;
reader->thread_states = PyMem_Calloc(reader->thread_state_capacity, sizeof(ThreadEntry));
if (!reader->thread_states) {
PyErr_NoMemory();
return NULL;
}
}
else if (GROW_ARRAY(reader->thread_states, reader->thread_state_count,
reader->thread_state_capacity, ThreadEntry) < 0) {
return NULL;
}
ThreadEntry *ts = &reader->thread_states[reader->thread_state_count];
memset(ts, 0, sizeof(ThreadEntry));
ts->thread_id = thread_id;
ts->interpreter_id = interpreter_id;
reader->thread_state_count++;
return ts;
}
static PyObject *
reader_get_frame_info(RemoteDebuggingState *state, BinaryReader *reader,
uint32_t frame_index)
{
if (frame_index >= reader->frames_count) {
PyErr_Format(PyExc_ValueError, "Invalid frame index: %u", frame_index);
return NULL;
}
if (reader->frame_info_cache == NULL) {
size_t cache_size = Py_MIN(reader->frames_count,
(uint32_t)FRAME_INFO_CACHE_SIZE);
reader->frame_info_cache = PyMem_Calloc(
cache_size, sizeof(*reader->frame_info_cache));
if (reader->frame_info_cache == NULL) {
PyErr_NoMemory();
return NULL;
}
reader->frame_info_cache_size = cache_size;
}
ReaderFrameCacheEntry *entry = &reader->frame_info_cache[
frame_index % reader->frame_info_cache_size];
if (entry->frame_info != NULL && entry->frame_index == frame_index) {
return Py_NewRef(entry->frame_info);
}
FrameEntry *frame = &reader->frames[frame_index];
if (frame->filename_idx >= reader->strings_count ||
frame->funcname_idx >= reader->strings_count) {
PyErr_SetString(PyExc_ValueError, "Invalid string index in frame");
return NULL;
}
PyObject *frame_info = PyStructSequence_New(state->FrameInfo_Type);
if (!frame_info) {
return NULL;
}
/* Build location tuple with full position info */
PyObject *location;
if (frame->lineno != LOCATION_NOT_AVAILABLE) {
location = Py_BuildValue("(iiii)",
frame->lineno,
frame->end_lineno,
frame->column,
frame->end_column);
if (!location) {
Py_DECREF(frame_info);
return NULL;
}
}
else {
location = Py_NewRef(Py_None);
}
/* Build opcode object */
PyObject *opcode_obj;
if (frame->opcode != OPCODE_NONE) {
opcode_obj = PyLong_FromLong(frame->opcode);
if (!opcode_obj) {
Py_DECREF(location);
Py_DECREF(frame_info);
return NULL;
}
}
else {
opcode_obj = Py_NewRef(Py_None);
}
PyStructSequence_SetItem(frame_info, 0, Py_NewRef(reader->strings[frame->filename_idx]));
PyStructSequence_SetItem(frame_info, 1, location);
PyStructSequence_SetItem(frame_info, 2, Py_NewRef(reader->strings[frame->funcname_idx]));
PyStructSequence_SetItem(frame_info, 3, opcode_obj);
Py_XSETREF(entry->frame_info, Py_NewRef(frame_info));
entry->frame_index = frame_index;
return frame_info;
}
/* Build a Python list of FrameInfo objects from frame indices. Stacks are
* kept outermost first, but collectors expect innermost first. */
static PyObject *
build_frame_list(RemoteDebuggingState *state, BinaryReader *reader,
const uint32_t *frame_indices, size_t stack_depth)
{
PyObject *frame_list = PyList_New(stack_depth);
if (!frame_list) {
return NULL;
}
for (size_t k = 0; k < stack_depth; k++) {
PyObject *frame_info = reader_get_frame_info(
state, reader, frame_indices[stack_depth - 1 - k]);
if (frame_info == NULL) {
goto error;
}
PyList_SET_ITEM(frame_list, k, frame_info);
}
return frame_list;
error:
Py_DECREF(frame_list);
return NULL;
}
/* Helper to build sample_list from frame indices (shared by emit functions) */
static PyObject *
build_sample_list(RemoteDebuggingState *state, BinaryReader *reader,
uint64_t thread_id, uint32_t interpreter_id, uint8_t status,
const uint32_t *frame_indices, size_t stack_depth)
{
PyObject *frame_list = NULL, *thread_info = NULL, *thread_list = NULL;
PyObject *interp_info = NULL, *sample_list = NULL;
frame_list = build_frame_list(state, reader, frame_indices, stack_depth);
if (!frame_list) {
goto error;
}
thread_info = PyStructSequence_New(state->ThreadInfo_Type);
if (!thread_info) {
goto error;
}
PyObject *tid = PyLong_FromUnsignedLongLong(thread_id);
if (!tid) {
goto error;
}
PyObject *st = PyLong_FromLong(status);
if (!st) {
Py_DECREF(tid);
goto error;
}
PyStructSequence_SetItem(thread_info, 0, tid);
PyStructSequence_SetItem(thread_info, 1, st);
PyStructSequence_SetItem(thread_info, 2, frame_list);
frame_list = NULL; /* ownership transferred */
thread_list = PyList_New(1);
if (!thread_list) {
goto error;
}
PyList_SET_ITEM(thread_list, 0, thread_info);
thread_info = NULL;
interp_info = PyStructSequence_New(state->InterpreterInfo_Type);
if (!interp_info) {
goto error;
}
PyObject *iid = PyLong_FromUnsignedLong(interpreter_id);
if (!iid) {
goto error;
}
PyStructSequence_SetItem(interp_info, 0, iid);
PyStructSequence_SetItem(interp_info, 1, thread_list);
thread_list = NULL;
sample_list = PyList_New(1);
if (!sample_list) {
goto error;
}
PyList_SET_ITEM(sample_list, 0, interp_info);
return sample_list;
error:
Py_XDECREF(sample_list);
Py_XDECREF(interp_info);
Py_XDECREF(thread_list);
Py_XDECREF(thread_info);
Py_XDECREF(frame_list);
return NULL;
}
/* Helper to emit a sample to the collector. timestamps_list is borrowed. */
static int
emit_sample(RemoteDebuggingState *state, PyObject *collector,
uint64_t thread_id, uint32_t interpreter_id, uint8_t status,
const uint32_t *frame_indices, size_t stack_depth,
BinaryReader *reader, PyObject *timestamps_list)
{
PyObject *sample_list = build_sample_list(state, reader, thread_id,
interpreter_id, status,
frame_indices, stack_depth);
if (!sample_list) {
return -1;
}
PyObject *result = PyObject_CallMethod(collector, "collect", "OO", sample_list, timestamps_list);
Py_DECREF(sample_list);
if (!result) {
return -1;
}
Py_DECREF(result);
return 0;
}
/* Helper to invoke progress callback, returns -1 on error */
static inline int
invoke_progress_callback(PyObject *callback, Py_ssize_t current, uint64_t total)
{
if (callback && callback != Py_None) {
PyObject *result = PyObject_CallFunction(callback, "nK", current, (unsigned long long)total);
if (result) {
Py_DECREF(result);
} else {
return -1;
}
}
return 0;
}
/* ============================================================================
* SAMPLE BLOCKS
* ============================================================================ */
static int
block_error(const char *message)
{
PyErr_Format(PyExc_ValueError, "Invalid sample block: %s", message);
return -1;
}
static inline int
block_read_varint(const ByteBuffer *column, size_t *offset, uint64_t *value)
{
size_t prev_offset = *offset;
*value = decode_varint_u64(column->data, offset, column->size);
return *offset == prev_offset ? -1 : 0;
}
static int
block_read_varint_u32(const ByteBuffer *column, size_t *offset,
uint32_t *value)
{
size_t prev_offset = *offset;
*value = decode_varint_u32(column->data, offset, column->size);
return *offset == prev_offset ? -1 : 0;
}
static int
reader_parse_block_header(BinaryReader *reader, const ByteBuffer *section,
size_t *offset, BlockHeader *header)
{
/* Block magic "TBLK" */
if (section->size - *offset < BLOCK_MAGIC_SIZE) {
return block_error("truncated header");
}
if (memcmp(section->data + *offset, BLOCK_MAGIC, BLOCK_MAGIC_SIZE) != 0) {
return block_error("wrong magic");
}
*offset += BLOCK_MAGIC_SIZE;
/* Sample count and base timestamp (varints) */
if (block_read_varint_u32(section, offset, &header->sample_count) < 0 ||
block_read_varint(section, offset, &header->base_timestamp) < 0) {
return -1;