FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
cpython/Modules/_remote_debugging/module.c at main · python/cpython · GitHub
Uh oh!
There was an error while loading.
Please reload this page
.
python
/
cpython
Public
Uh oh!
There was an error while loading.
Please reload this page
.
Notifications
You must be signed in to change notification settings
Fork
35.3k
Star
74.9k
Code
Issues
5k+
Pull requests
2.6k
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
cpython
/
Modules
/
_remote_debugging
/
module.c
Copy path
More file actions
More file actions
Latest commit
History
History
History
2413 lines (2084 loc) · 77.8 KB
Breadcrumbs
cpython
/
Modules
/
_remote_debugging
/
module.c
Copy path
File metadata and controls
2413 lines (2084 loc) · 77.8 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
/******************************************************************************
* Remote Debugging Module - Main Module Implementation
*
* This file contains the main module initialization, the RemoteUnwinder
* class implementation, and utility functions.
******************************************************************************/
#include
"_remote_debugging.h"
#include
"binary_io.h"
#include
"debug_offsets_validation.h"
#include
"gc_stats.h"
/* Forward declarations for clinic-generated code */
typedef
struct
{
PyObject_HEAD
BinaryWriter
*
writer
;
uint64_t
cached_total_samples
;
/* Preserved after finalize */
}
BinaryWriterObject
;
typedef
struct
{
PyObject_HEAD
BinaryReader
*
reader
;
}
BinaryReaderObject
;
#include
"clinic/module.c.h"
/* ============================================================================
* STRUCTSEQ TYPE DEFINITIONS
* ============================================================================ */
// TaskInfo structseq type
static
PyStructSequence_Field
TaskInfo_fields
[]
=
{
{
"task_id"
,
"Task ID (memory address)"
},
{
"task_name"
,
"Task name"
},
{
"coroutine_stack"
,
"Coroutine call stack"
},
{
"awaited_by"
,
"Tasks awaiting this task"
},
{
NULL
}
};
PyStructSequence_Desc
TaskInfo_desc
=
{
"_remote_debugging.TaskInfo"
,
"Information about an asyncio task"
,
TaskInfo_fields
,
4
};
// LocationInfo structseq type
static
PyStructSequence_Field
LocationInfo_fields
[]
=
{
{
"lineno"
,
"Line number"
},
{
"end_lineno"
,
"End line number"
},
{
"col_offset"
,
"Column offset"
},
{
"end_col_offset"
,
"End column offset"
},
{
NULL
}
};
PyStructSequence_Desc
LocationInfo_desc
=
{
"_remote_debugging.LocationInfo"
,
"Source location information: (lineno, end_lineno, col_offset, end_col_offset)"
,
LocationInfo_fields
,
4
};
// FrameInfo structseq type
static
PyStructSequence_Field
FrameInfo_fields
[]
=
{
{
"filename"
,
"Source code filename"
},
{
"location"
,
"LocationInfo structseq or None for synthetic frames"
},
{
"funcname"
,
"Function name"
},
{
"opcode"
,
"Opcode being executed (None if not gathered)"
},
{
NULL
}
};
PyStructSequence_Desc
FrameInfo_desc
=
{
"_remote_debugging.FrameInfo"
,
"Information about a frame"
,
FrameInfo_fields
,
4
};
// CoroInfo structseq type
static
PyStructSequence_Field
CoroInfo_fields
[]
=
{
{
"call_stack"
,
"Coroutine call stack"
},
{
"task_name"
,
"Task name"
},
{
NULL
}
};
PyStructSequence_Desc
CoroInfo_desc
=
{
"_remote_debugging.CoroInfo"
,
"Information about a coroutine"
,
CoroInfo_fields
,
2
};
// ThreadInfo structseq type
static
PyStructSequence_Field
ThreadInfo_fields
[]
=
{
{
"thread_id"
,
"Thread ID"
},
{
"status"
,
"Thread status (flags: HAS_GIL, ON_CPU, UNKNOWN or legacy enum)"
},
{
"frame_info"
,
"Frame information"
},
{
NULL
}
};
PyStructSequence_Desc
ThreadInfo_desc
=
{
"_remote_debugging.ThreadInfo"
,
"Information about a thread"
,
ThreadInfo_fields
,
3
};
// InterpreterInfo structseq type
static
PyStructSequence_Field
InterpreterInfo_fields
[]
=
{
{
"interpreter_id"
,
"Interpreter ID"
},
{
"threads"
,
"List of threads in this interpreter"
},
{
NULL
}
};
PyStructSequence_Desc
InterpreterInfo_desc
=
{
"_remote_debugging.InterpreterInfo"
,
"Information about an interpreter"
,
InterpreterInfo_fields
,
2
};
// AwaitedInfo structseq type
static
PyStructSequence_Field
AwaitedInfo_fields
[]
=
{
{
"thread_id"
,
"Thread ID"
},
{
"awaited_by"
,
"List of tasks awaited by this thread"
},
{
NULL
}
};
PyStructSequence_Desc
AwaitedInfo_desc
=
{
"_remote_debugging.AwaitedInfo"
,
"Information about what a thread is awaiting"
,
AwaitedInfo_fields
,
2
};
// GCStatsInfo structseq type
static
PyStructSequence_Field
GCStatsInfo_fields
[]
=
{
{
"gen"
,
"GC generation number"
},
{
"iid"
,
"Interpreter ID"
},
{
"ts_start"
,
"Raw timestamp at collection start"
},
{
"ts_stop"
,
"Raw timestamp at collection stop"
},
{
"collections"
,
"Total number of collections"
},
{
"collected"
,
"Total number of collected objects"
},
{
"uncollectable"
,
"Total number of uncollectable objects"
},
{
"candidates"
,
"Total objects considered and traversed"
},
{
"heap_size"
,
"Number of live objects"
},
{
"duration"
,
"Total collection time, in seconds"
},
{
NULL
}
};
PyStructSequence_Desc
GCStatsInfo_desc
=
{
"_remote_debugging.GCStatsInfo"
,
"Information about a garbage collector stats sample"
,
GCStatsInfo_fields
,
10
};
/* ============================================================================
* UTILITY FUNCTIONS
* ============================================================================ */
void
cached_code_metadata_destroy
(
void
*
ptr
)
{
CachedCodeMetadata
*
meta
=
(
CachedCodeMetadata
*
)
ptr
;
Py_DECREF
(
meta
->
func_name
);
Py_DECREF
(
meta
->
file_name
);
Py_DECREF
(
meta
->
linetable
);
Py_XDECREF
(
meta
->
last_frame_info
);
PyMem_RawFree
(
meta
);
}
RemoteDebuggingState
*
RemoteDebugging_GetState
(
PyObject
*
module
)
{
void
*
state
=
_PyModule_GetState
(
module
);
assert
(
state
!=
NULL
);
return
(
RemoteDebuggingState
*
)
state
;
}
RemoteDebuggingState
*
RemoteDebugging_GetStateFromType
(
PyTypeObject
*
type
)
{
PyObject
*
module
=
PyType_GetModule
(
type
);
assert
(
module
!=
NULL
);
return
RemoteDebugging_GetState
(
module
);
}
RemoteDebuggingState
*
RemoteDebugging_GetStateFromObject
(
PyObject
*
obj
)
{
RemoteUnwinderObject
*
unwinder
=
(
RemoteUnwinderObject
*
)
obj
;
if
(
unwinder
->
cached_state
==
NULL
) {
unwinder
->
cached_state
=
RemoteDebugging_GetStateFromType
(
Py_TYPE
(
obj
));
}
return
unwinder
->
cached_state
;
}
int
RemoteDebugging_InitState
(
RemoteDebuggingState
*
st
)
{
return
0
;
}
int
is_prerelease_version
(
uint64_t
version
)
{
return
(
version
&
0xF0
)
!=
0xF0
;
}
int
validate_debug_offsets
(
struct
_Py_DebugOffsets
*
debug_offsets
)
{
if
(
memcmp
(
debug_offsets
->
cookie
,
_Py_Debug_Cookie
,
sizeof
(
debug_offsets
->
cookie
))
!=
0
) {
// The remote is probably running a Python version predating debug offsets.
PyErr_SetString
(
PyExc_RuntimeError
,
"Can't determine the Python version of the remote process"
);
return
-1
;
}
// Assume debug offsets could change from one pre-release version to another,
// or one minor version to another, but are stable across patch versions.
if
(
is_prerelease_version
(
Py_Version
)
&&
Py_Version
!=
debug_offsets
->
version
) {
PyErr_SetString
(
PyExc_RuntimeError
,
"Can't attach from a pre-release Python interpreter"
" to a process running a different Python version"
);
return
-1
;
}
if
(
is_prerelease_version
(
debug_offsets
->
version
)
&&
Py_Version
!=
debug_offsets
->
version
) {
PyErr_SetString
(
PyExc_RuntimeError
,
"Can't attach to a pre-release Python interpreter"
" from a process running a different Python version"
);
return
-1
;
}
unsigned
int
remote_major
=
(
debug_offsets
->
version
>>
24
)
&
0xFF
;
unsigned
int
remote_minor
=
(
debug_offsets
->
version
>>
16
)
&
0xFF
;
if
(
PY_MAJOR_VERSION
!=
remote_major
||
PY_MINOR_VERSION
!=
remote_minor
) {
PyErr_Format
(
PyExc_RuntimeError
,
"Can't attach from a Python %d.%d process to a Python %d.%d process"
,
PY_MAJOR_VERSION
,
PY_MINOR_VERSION
,
remote_major
,
remote_minor
);
return
-1
;
}
// The debug offsets differ between free threaded and non-free threaded builds.
if
(
_Py_Debug_Free_Threaded
&&
!
debug_offsets
->
free_threaded
) {
PyErr_SetString
(
PyExc_RuntimeError
,
"Cannot attach from a free-threaded Python process"
" to a process running a non-free-threaded version"
);
return
-1
;
}
if
(!
_Py_Debug_Free_Threaded
&&
debug_offsets
->
free_threaded
) {
PyErr_SetString
(
PyExc_RuntimeError
,
"Cannot attach to a free-threaded Python process"
" from a process running a non-free-threaded version"
);
return
-1
;
}
return
_PyRemoteDebug_ValidateDebugOffsetsLayout
(
debug_offsets
);
}
/* ============================================================================
* REMOTEUNWINDER CLASS IMPLEMENTATION
* ============================================================================ */
/*[clinic input]
module _remote_debugging
class _remote_debugging.RemoteUnwinder "RemoteUnwinderObject *" "&RemoteUnwinder_Type"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=12b4dce200381115]*/
/*[clinic input]
@permit_long_summary
_remote_debugging.RemoteUnwinder.__init__
pid: pid_t
*
all_threads: bool = False
only_active_thread: bool = False
mode: int = 0
debug: bool = False
skip_non_matching_threads: bool = True
native: bool = False
gc: bool = False
opcodes: bool = False
cache_frames: bool = False
stats: bool = False
Initialize a new RemoteUnwinder object for debugging a remote Python process.
Args:
pid: Process ID of the target Python process to debug
all_threads: If True, initialize state for all threads in the
process. If False, only initialize for the main thread.
only_active_thread: If True, only sample the thread holding the GIL.
mode: Profiling mode: 0=WALL (wall-time), 1=CPU (cpu-time), 2=GIL
(gil-time). Cannot be used together with all_threads=True.
debug: If True, chain exceptions to explain the sequence of events
that lead to the exception.
skip_non_matching_threads: If True, skip threads that don't match
the selected mode. If False, include all threads regardless of
mode.
native: If True, include artificial "<native>" frames to denote
calls to non-Python code.
gc: If True, include artificial "<GC>" frames to denote active
garbage collection.
opcodes: If True, gather bytecode opcode information for
instruction-level profiling.
cache_frames: If True, enable frame caching optimization to avoid
re-reading unchanged parent frames between samples.
stats: If True, collect statistics about cache hits, memory reads,
etc. Use get_stats() to retrieve the collected statistics.
The RemoteUnwinder provides functionality to inspect and debug a running
Python process, including examining thread states, stack frames and
other runtime data.
Raises:
PermissionError: If access to the target process is denied
OSError: If unable to attach to the target process or access its
memory
RuntimeError: If unable to read debug information from the target
process
ValueError: If both all_threads and only_active_thread are True
[clinic start generated code]*/
static
int
_remote_debugging_RemoteUnwinder___init___impl
(
RemoteUnwinderObject
*
self
,
pid_t
pid
,
int
all_threads
,
int
only_active_thread
,
int
mode
,
int
debug
,
int
skip_non_matching_threads
,
int
native
,
int
gc
,
int
opcodes
,
int
cache_frames
,
int
stats
)
/*[clinic end generated code: output=acfe554c8a92cf6b input=3b5a5ad153709125]*/
{
// Validate that all_threads and only_active_thread are not both True
if
(
all_threads
&&
only_active_thread
) {
PyErr_SetString
(
PyExc_ValueError
,
"all_threads and only_active_thread cannot both be True"
);
return
-1
;
}
#ifdef
Py_GIL_DISABLED
if
(
only_active_thread
) {
PyErr_SetString
(
PyExc_ValueError
,
"only_active_thread is not supported in free-threaded builds"
);
return
-1
;
}
#endif
self
->
native
=
native
;
self
->
gc
=
gc
;
self
->
opcodes
=
opcodes
;
self
->
cache_frames
=
cache_frames
;
self
->
collect_stats
=
stats
;
self
->
stale_invalidation_counter
=
0
;
self
->
cached_tstate_interpreter_addr
=
0
;
self
->
cached_tstate_addr
=
0
;
memset
(
self
->
cached_tstates
,
0
,
sizeof
(
self
->
cached_tstates
));
memset
(
self
->
cached_generations
,
0
,
sizeof
(
self
->
cached_generations
));
self
->
debug
=
debug
;
self
->
only_active_thread
=
only_active_thread
;
self
->
mode
=
mode
;
self
->
skip_non_matching_threads
=
skip_non_matching_threads
;
self
->
cached_state
=
NULL
;
self
->
frame_cache
=
NULL
;
#ifdef
Py_REMOTE_DEBUG_SUPPORTS_BLOCKING
self
->
threads_stopped
=
0
;
#endif
// Initialize stats to zero
memset
(
&
self
->
stats
,
0
,
sizeof
(
self
->
stats
));
if
(
_Py_RemoteDebug_InitProcHandle
(
&
self
->
handle
,
pid
)
<
0
) {
set_exception_cause
(
self
,
PyExc_RuntimeError
,
"Failed to initialize process handle"
);
return
-1
;
}
self
->
runtime_start_address
=
_Py_RemoteDebug_GetPyRuntimeAddress
(
&
self
->
handle
);
if
(
self
->
runtime_start_address
==
0
) {
set_exception_cause
(
self
,
PyExc_RuntimeError
,
"Failed to get Python runtime address"
);
return
-1
;
}
if
(
_Py_RemoteDebug_ReadDebugOffsets
(
&
self
->
handle
,
&
self
->
runtime_start_address
,
&
self
->
debug_offsets
)
<
0
)
{
set_exception_cause
(
self
,
PyExc_RuntimeError
,
"Failed to read debug offsets"
);
return
-1
;
}
// Validate that the debug offsets are valid
if
(
validate_debug_offsets
(
&
self
->
debug_offsets
)
==
-1
) {
set_exception_cause
(
self
,
PyExc_RuntimeError
,
"Invalid debug offsets found"
);
return
-1
;
}
// Try to read async debug offsets, but don't fail if they're not available
self
->
async_debug_offsets_available
=
1
;
int
async_debug_result
=
read_async_debug
(
self
);
if
(
async_debug_result
==
PY_REMOTE_DEBUG_INVALID_ASYNC_DEBUG_OFFSETS
) {
return
-1
;
}
if
(
async_debug_result
<
0
) {
if
(
_Py_RemoteDebug_HasPermissionError
()) {
return
-1
;
}
PyErr_Clear
();
memset
(
&
self
->
async_debug_offsets
,
0
,
sizeof
(
self
->
async_debug_offsets
));
self
->
async_debug_offsets_available
=
0
;
}
if
(
populate_initial_state_data
(
all_threads
,
self
,
self
->
runtime_start_address
,
&
self
->
interpreter_addr
,
&
self
->
tstate_addr
)
<
0
)
{
set_exception_cause
(
self
,
PyExc_RuntimeError
,
"Failed to populate initial state data"
);
return
-1
;
}
self
->
code_object_cache
=
_Py_hashtable_new_full
(
_Py_hashtable_hash_ptr
,
_Py_hashtable_compare_direct
,
NULL
,
// keys are stable pointers, don't destroy
cached_code_metadata_destroy
,
NULL
);
if
(
self
->
code_object_cache
==
NULL
) {
PyErr_NoMemory
();
set_exception_cause
(
self
,
PyExc_MemoryError
,
"Failed to create code object cache"
);
return
-1
;
}
#ifdef
Py_GIL_DISABLED
// Initialize TLBC cache
self
->
tlbc_generation
=
0
;
self
->
tlbc_cache
=
_Py_hashtable_new_full
(
_Py_hashtable_hash_ptr
,
_Py_hashtable_compare_direct
,
NULL
,
// keys are stable pointers, don't destroy
tlbc_cache_entry_destroy
,
NULL
);
if
(
self
->
tlbc_cache
==
NULL
) {
_Py_hashtable_destroy
(
self
->
code_object_cache
);
PyErr_NoMemory
();
set_exception_cause
(
self
,
PyExc_MemoryError
,
"Failed to create TLBC cache"
);
return
-1
;
}
#endif
#if
defined(
__APPLE__
)
self
->
thread_id_offset
=
0
;
self
->
thread_id_offset_initialized
=
0
;
#endif
#ifdef
MS_WINDOWS
self
->
win_process_buffer
=
NULL
;
self
->
win_process_buffer_size
=
0
;
#endif
#ifdef
__linux__
self
->
thread_tids
=
NULL
;
self
->
thread_tids_capacity
=
0
;
#endif
if
(
cache_frames
&&
frame_cache_init
(
self
)
<
0
) {
return
-1
;
}
// Clear stale profiler anchors from previous profilers. This prevents us
// from stopping frame walking early due to stale frame pointers.
if
(
cache_frames
) {
clear_last_profiled_frames
(
self
);
}
return
0
;
}
static
inline
size_t
interpreter_thread_cache_index
(
uintptr_t
interpreter_addr
)
{
// Direct-mapped table indexed by the remote interpreter address. Each entry
// stores the full address and verifies it on lookup, so hash collisions
// degrade to misses and cannot return a value from the wrong interpreter.
return
(
size_t
)
_Py_HashPointerRaw
((
const
void
*
)
interpreter_addr
)
&
(
INTERPRETER_THREAD_CACHE_SIZE
-
1
);
}
static
inline
uintptr_t
get_cached_tstate_for_interpreter
(
RemoteUnwinderObject
*
self
,
uintptr_t
interpreter_addr
)
{
if
(
interpreter_addr
==
0
) {
return
0
;
}
if
(
self
->
cached_tstate_interpreter_addr
==
interpreter_addr
) {
return
self
->
cached_tstate_addr
;
}
InterpreterTstateCacheEntry
*
entry
=
&
self
->
cached_tstates
[
interpreter_thread_cache_index
(
interpreter_addr
)];
if
(
entry
->
interpreter_addr
==
interpreter_addr
) {
self
->
cached_tstate_interpreter_addr
=
interpreter_addr
;
self
->
cached_tstate_addr
=
entry
->
thread_state_addr
;
return
entry
->
thread_state_addr
;
}
return
0
;
}
static
inline
void
set_cached_tstate_for_interpreter
(
RemoteUnwinderObject
*
self
,
uintptr_t
interpreter_addr
,
uintptr_t
thread_state_addr
)
{
if
(
interpreter_addr
==
0
||
thread_state_addr
==
0
) {
return
;
}
self
->
cached_tstate_interpreter_addr
=
interpreter_addr
;
self
->
cached_tstate_addr
=
thread_state_addr
;
InterpreterTstateCacheEntry
*
entry
=
&
self
->
cached_tstates
[
interpreter_thread_cache_index
(
interpreter_addr
)];
entry
->
interpreter_addr
=
interpreter_addr
;
entry
->
thread_state_addr
=
thread_state_addr
;
}
static
void
refresh_generation_caches_from_interp_state
(
RemoteUnwinderObject
*
self
,
uintptr_t
interpreter_addr
,
const
char
*
interp_state_buffer
)
{
uint64_t
code_object_generation
=
GET_MEMBER
(
uint64_t
,
interp_state_buffer
,
self
->
debug_offsets
.
interpreter_state
.
code_object_generation
);
if
(
self
->
cached_generation_interpreter_addr
==
interpreter_addr
) {
if
(
code_object_generation
!=
self
->
cached_code_object_generation
) {
self
->
cached_code_object_generation
=
code_object_generation
;
_Py_hashtable_clear
(
self
->
code_object_cache
);
}
}
else
{
InterpreterGenerationCacheEntry
*
entry
=
&
self
->
cached_generations
[
interpreter_thread_cache_index
(
interpreter_addr
)];
// A slot rebound from another interpreter must be treated as changed:
// the code_object_cache is global, so even if the new generation
// numerically matches what the previous occupant had, stale entries
// from that occupant could still be served.
int
changed
=
entry
->
interpreter_addr
!=
interpreter_addr
||
entry
->
code_object_generation
!=
code_object_generation
;
entry
->
interpreter_addr
=
interpreter_addr
;
entry
->
code_object_generation
=
code_object_generation
;
if
(
changed
) {
_Py_hashtable_clear
(
self
->
code_object_cache
);
}
self
->
cached_generation_interpreter_addr
=
interpreter_addr
;
self
->
cached_code_object_generation
=
code_object_generation
;
}
#ifdef
Py_GIL_DISABLED
uint32_t
current_tlbc_generation
=
GET_MEMBER
(
uint32_t
,
interp_state_buffer
,
self
->
debug_offsets
.
interpreter_state
.
tlbc_generation
);
if
(
current_tlbc_generation
!=
self
->
tlbc_generation
) {
self
->
tlbc_generation
=
current_tlbc_generation
;
_Py_hashtable_clear
(
self
->
tlbc_cache
);
}
#endif
}
static
int
refresh_generation_caches_for_interpreter
(
RemoteUnwinderObject
*
self
,
uintptr_t
interpreter_addr
)
{
char
interp_state_buffer
[
INTERP_STATE_BUFFER_SIZE
];
if
(
_Py_RemoteDebug_ReadRemoteMemory
(
&
self
->
handle
,
interpreter_addr
,
INTERP_STATE_BUFFER_SIZE
,
interp_state_buffer
)
<
0
) {
set_exception_cause
(
self
,
PyExc_RuntimeError
,
"Failed to read interpreter state buffer"
);
return
-1
;
}
refresh_generation_caches_from_interp_state
(
self
,
interpreter_addr
,
interp_state_buffer
);
return
0
;
}
static
int
read_interp_state_and_maybe_thread_frame
(
RemoteUnwinderObject
*
unwinder
,
uintptr_t
interpreter_addr
,
char
*
interp_state_buffer
,
char
*
tstate_buffer
,
char
*
frame_buffer
,
RemoteReadPrefetch
*
prefetch
)
{
prefetch
->
tstate
=
NULL
;
prefetch
->
frame
=
NULL
;
if
(
prefetch
->
tstate_addr
!=
0
) {
size_t
tstate_size
=
(
size_t
)
unwinder
->
debug_offsets
.
thread_state
.
size
;
_Py_RemoteReadSegment
segments
[
3
]
=
{
{
interpreter_addr
,
interp_state_buffer
,
INTERP_STATE_BUFFER_SIZE
},
{
prefetch
->
tstate_addr
,
tstate_buffer
,
tstate_size
},
{
prefetch
->
frame_addr
,
frame_buffer
,
SIZEOF_INTERP_FRAME
},
};
int
nsegs
=
prefetch
->
frame_addr
!=
0
?
3
:
2
;
Py_ssize_t
nread
=
_Py_RemoteDebug_BatchedReadRemoteMemory
(
&
unwinder
->
handle
,
segments
,
nsegs
);
int
completed
=
0
;
if
(
nread
>= (
Py_ssize_t
)
INTERP_STATE_BUFFER_SIZE
) {
completed
=
1
;
Py_ssize_t
with_tstate
=
(
Py_ssize_t
)
INTERP_STATE_BUFFER_SIZE
+
(
Py_ssize_t
)
tstate_size
;
if
(
nread
>=
with_tstate
) {
completed
=
2
;
}
if
(
nsegs
==
3
&&
nread
==
with_tstate
+
(
Py_ssize_t
)
SIZEOF_INTERP_FRAME
) {
completed
=
3
;
}
}
STATS_BATCHED_READ
(
unwinder
,
nsegs
,
completed
);
if
(
completed
>=
1
) {
if
(
completed
>=
2
) {
prefetch
->
tstate
=
tstate_buffer
;
}
if
(
completed
>=
3
) {
prefetch
->
frame
=
frame_buffer
;
}
return
0
;
}
}
return
_Py_RemoteDebug_ReadRemoteMemory
(
&
unwinder
->
handle
,
interpreter_addr
,
INTERP_STATE_BUFFER_SIZE
,
interp_state_buffer
);
}
/*[clinic input]
@critical_section
_remote_debugging.RemoteUnwinder.get_stack_trace
Returns stack traces for all interpreters and threads in process.
Each element in the returned list is a tuple of (interpreter_id,
thread_list), where:
- interpreter_id is the interpreter identifier
- thread_list is a list of tuples (thread_id, frame_list) for
threads in that interpreter
- thread_id is the OS thread identifier
- frame_list is a list of tuples (function_name, filename,
line_number) representing the Python stack frames for that
thread, ordered from most recent to oldest
The threads returned depend on the initialization parameters:
- If only_active_thread was True: returns only the thread holding
the GIL across all interpreters
- If all_threads was True: returns all threads across all
interpreters
- Otherwise: returns only the main thread of each interpreter
Example:
[
(0, [ # Main interpreter
(1234, [
('process_data', 'worker.py', 127),
('run_worker', 'worker.py', 45),
('main', 'app.py', 23)
]),
(1235, [
('handle_request', 'server.py', 89),
('serve_forever', 'server.py', 52)
])
]),
(1, [ # Sub-interpreter
(1236, [
('sub_worker', 'sub.py', 15)
])
])
]
Raises:
RuntimeError: If there is an error copying memory from the
target process
OSError: If there is an error accessing the target process
PermissionError: If access to the target process is denied
UnicodeDecodeError: If there is an error decoding strings from
the target process
[clinic start generated code]*/
static
PyObject
*
_remote_debugging_RemoteUnwinder_get_stack_trace_impl
(
RemoteUnwinderObject
*
self
)
/*[clinic end generated code: output=666192b90c69d567 input=86a992b853f48aa9]*/
{
STATS_INC
(
self
,
total_samples
);
PyObject
*
result
=
PyList_New
(
0
);
if
(!
result
) {
set_exception_cause
(
self
,
PyExc_MemoryError
,
"Failed to create stack trace result list"
);
return
NULL
;
}
// Iterate over all interpreters
uintptr_t
current_interpreter
=
self
->
interpreter_addr
;
while
(
current_interpreter
!=
0
) {
// Read interpreter state to get the interpreter ID
char
interp_state_buffer
[
INTERP_STATE_BUFFER_SIZE
];
char
prefetched_tstate
[
SIZEOF_THREAD_STATE
];
char
prefetched_frame
[
SIZEOF_INTERP_FRAME
];
RemoteReadPrefetch
prefetch
=
{
0
};
if
(
self
->
cache_frames
) {
prefetch
.
tstate_addr
=
get_cached_tstate_for_interpreter
(
self
,
current_interpreter
);
}
if
(
prefetch
.
tstate_addr
!=
0
) {
FrameCacheEntry
*
entry
=
frame_cache_find_by_tstate
(
self
,
prefetch
.
tstate_addr
);
if
(
entry
&&
entry
->
num_addrs
>
0
) {
prefetch
.
frame_addr
=
entry
->
addrs
[
0
];
}
}
if
(
read_interp_state_and_maybe_thread_frame
(
self
,
current_interpreter
,
interp_state_buffer
,
prefetched_tstate
,
prefetched_frame
,
&
prefetch
)
<
0
) {
set_exception_cause
(
self
,
PyExc_RuntimeError
,
"Failed to read interpreter state buffer"
);
Py_CLEAR
(
result
);
goto
exit
;
}
refresh_generation_caches_from_interp_state
(
self
,
current_interpreter
,
interp_state_buffer
);
uintptr_t
gc_frame
=
0
;
if
(
self
->
gc
) {
gc_frame
=
GET_MEMBER
(
uintptr_t
,
interp_state_buffer
,
self
->
debug_offsets
.
interpreter_state
.
gc
+
self
->
debug_offsets
.
gc
.
frame
);
}
int64_t
interpreter_id
=
GET_MEMBER
(
int64_t
,
interp_state_buffer
,
self
->
debug_offsets
.
interpreter_state
.
id
);
// Create a list to hold threads for this interpreter
PyObject
*
interpreter_threads
=
PyList_New
(
0
);
if
(!
interpreter_threads
) {
set_exception_cause
(
self
,
PyExc_MemoryError
,
"Failed to create interpreter threads list"
);
Py_CLEAR
(
result
);
goto
exit
;
}
// Get the GIL holder for this interpreter (needed for GIL_WAIT logic)
uintptr_t
gil_holder_tstate
=
0
;
int
gil_locked
=
GET_MEMBER
(
int
,
interp_state_buffer
,
self
->
debug_offsets
.
interpreter_state
.
gil_runtime_state_locked
);
if
(
gil_locked
) {
gil_holder_tstate
=
(
uintptr_t
)
GET_MEMBER
(
PyThreadState
*
,
interp_state_buffer
,
self
->
debug_offsets
.
interpreter_state
.
gil_runtime_state_holder
);
}
uintptr_t
current_tstate
;
if
(
self
->
only_active_thread
) {
// Find the GIL holder for THIS interpreter
if
(!
gil_locked
) {
// This interpreter's GIL is not locked, skip it
Py_DECREF
(
interpreter_threads
);
goto
next_interpreter
;
}
current_tstate
=
gil_holder_tstate
;
}
else
if
(
self
->
tstate_addr
==
0
) {
// Get all threads for this interpreter
current_tstate
=
GET_MEMBER
(
uintptr_t
,
interp_state_buffer
,
self
->
debug_offsets
.
interpreter_state
.
threads_head
);
}
else
{
// Target specific thread (only process first interpreter)
current_tstate
=
self
->
tstate_addr
;
}
if
(
current_tstate
!=
0
&&
self
->
cache_frames
) {
set_cached_tstate_for_interpreter
(
self
,
current_interpreter
,
current_tstate
);
}
// Acquire main thread state information
uintptr_t
main_thread_tstate
=
GET_MEMBER
(
uintptr_t
,
interp_state_buffer
,
self
->
debug_offsets
.
interpreter_state
.
threads_main
);
while
(
current_tstate
!=
0
) {
uintptr_t
prev_tstate
=
current_tstate
;
PyObject
*
frame_info
=
unwind_stack_for_thread
(
self
,
&
current_tstate
,
gil_holder_tstate
,
gc_frame
,
main_thread_tstate
,
&
prefetch
);
if
(!
frame_info
) {
// Check if this was an intentional skip due to mode-based filtering
if
((
self
->
mode
==
PROFILING_MODE_CPU
||
self
->
mode
==
PROFILING_MODE_GIL
||
self
->
mode
==
PROFILING_MODE_EXCEPTION
)
&&
!
PyErr_Occurred
()) {
// Detect cycle: if current_tstate didn't advance, we have corrupted data
if
(
current_tstate
==
prev_tstate
) {
Py_DECREF
(
interpreter_threads
);
PyErr_Format
(
PyExc_RuntimeError
,
"Thread list cycle detected at address 0x%lx (corrupted remote memory)"
,
current_tstate
);
set_exception_cause
(
self
,
PyExc_RuntimeError
,
"Thread list cycle detected (corrupted remote memory)"
);
Py_CLEAR
(
result
);
goto
exit
;
}
// Thread was skipped due to mode filtering, continue to next thread
continue
;
}
// This was an actual error
Py_DECREF
(
interpreter_threads
);
set_exception_cause
(
self
,
PyExc_RuntimeError
,
"Failed to unwind stack for thread"
);
Py_CLEAR
(
result
);
goto
exit
;
}
if
(
PyList_Append
(
interpreter_threads
,
frame_info
)
==
-1
) {
Py_DECREF
(
frame_info
);
Py_DECREF
(
interpreter_threads
);
set_exception_cause
(
self
,
PyExc_RuntimeError
,
"Failed to append thread frame info"
);
Py_CLEAR
(
result
);
goto
exit
;
}
Py_DECREF
(
frame_info
);
// If targeting specific thread or only active thread, process just one
if
(
self
->
tstate_addr
||
self
->
only_active_thread
) {
break
;
}
}
// Create the InterpreterInfo StructSequence
RemoteDebuggingState
*
state
=
RemoteDebugging_GetStateFromObject
((
PyObject
*
)
self
);
PyObject
*
interpreter_info
=
PyStructSequence_New
(
state
->
InterpreterInfo_Type
);
if
(!
interpreter_info
) {
Py_DECREF
(
interpreter_threads
);
set_exception_cause
(
self
,
PyExc_MemoryError
,
"Failed to create InterpreterInfo"
);
Py_CLEAR
(
result
);
goto
exit
;
}
PyObject
*
interp_id
=
PyLong_FromLongLong
(
interpreter_id
);
if
(!
interp_id
) {
Py_DECREF
(
interpreter_threads
);
Py_DECREF
(
interpreter_info
);
set_exception_cause
(
self
,
PyExc_MemoryError
,
"Failed to create interpreter ID"
);
Py_CLEAR
(
result
);
goto
exit
;
}
PyStructSequence_SetItem
(
interpreter_info
,
0
,
interp_id
);
// steals reference
PyStructSequence_SetItem
(
interpreter_info
,
1
,
interpreter_threads
);
// steals reference
// Add this interpreter to the result list
if
(
PyList_Append
(
result
,
interpreter_info
)
==
-1
) {
Py_DECREF
(
interpreter_info
);
set_exception_cause
(
self
,
PyExc_RuntimeError
,
"Failed to append interpreter info"
);
Py_CLEAR
(
result
);
goto
exit
;
}
Py_DECREF
(
interpreter_info
);
next_interpreter
:
// Get the next interpreter address
current_interpreter
=
GET_MEMBER
(
uintptr_t
,
interp_state_buffer
,
self
->
debug_offsets
.
interpreter_state
.
next
);
// If we're targeting a specific thread, stop after first interpreter
if
(
self
->
tstate_addr
!=
0
) {
break
;
}
}
exit
:
// Invalidate cache entries for threads not seen in this sample.
// Only do this every 1024 iterations to avoid performance overhead.
if
(
self
->
cache_frames
&&
result
) {
if
(
++
self
->
stale_invalidation_counter
>=
1024
) {
self
->
stale_invalidation_counter
=
0
;
frame_cache_invalidate_stale
(
self
,
result
);
}
}
_Py_RemoteDebug_ClearCache
(
&
self
->
handle
);
return
result
;
}
/*[clinic input]
@permit_long_summary
@critical_section
_remote_debugging.RemoteUnwinder.get_all_awaited_by
Get all tasks and their awaited_by relationships from the remote process.
This provides a tree structure showing which tasks are waiting for
other tasks.
For each task, returns:
1. The call stack frames leading to where the task is currently
executing
2. The name of the task
3. A list of tasks that this task is waiting for, with their own
frames/names/etc
Returns a list of [frames, task_name, subtasks] where:
- frames: List of (func_name, filename, lineno) showing the call
stack
- task_name: String identifier for the task
- subtasks: List of tasks being awaited by this task, in same format
Raises:
RuntimeError: If AsyncioDebug section is not available in the
remote process
MemoryError: If memory allocation fails
OSError: If reading from the remote process fails
Example output:
[
# Task c2_root waiting for two subtasks
[
# Call stack of c2_root
[("c5", "script.py", 10), ("c4", "script.py", 14)],
"c2_root",
[
# First subtask (sub_main_2) and what it's waiting for
[
[("c1", "script.py", 23)],
"sub_main_2",
[...]
],
# Second subtask and its waiters
[...]
]
]
]
[clinic start generated code]*/
static
PyObject
*
_remote_debugging_RemoteUnwinder_get_all_awaited_by_impl
(
RemoteUnwinderObject
*
self
)
/*[clinic end generated code: output=6a49cd345e8aec53 input=c22bfee0612e0b69]*/
{
if
(
ensure_async_debug_offsets
(
self
)
<
0
) {
return
NULL
;
}
if
(
refresh_generation_caches_for_interpreter
(
self
,
self
->
interpreter_addr
)
<
0
) {
return
NULL
;
}
PyObject
*
result
=
PyList_New
(
0
);
if
(
result
==
NULL
) {
set_exception_cause
(
self
,
PyExc_MemoryError
,
"Failed to create awaited_by result list"
);
goto
result_err
;
}
// Process all threads
if
(
iterate_threads
(
self
,
process_thread_for_awaited_by
,
result
)
<
0
) {
goto
result_err
;
}
uintptr_t
head_addr
=
self
->
interpreter_addr
+
(
uintptr_t
)
self
->
async_debug_offsets
.
asyncio_interpreter_state
.
asyncio_tasks_head
;
// On top of a per-thread task lists used by default by asyncio to avoid
// contention, there is also a fallback per-interpreter list of tasks;
// any tasks still pending when a thread is destroyed will be moved to the
// per-interpreter task list. It's unlikely we'll find anything here, but
// interesting for debugging.
if
(
append_awaited_by
(
self
,
0
,
head_addr
,
result
))
{
set_exception_cause
(
self
,
PyExc_RuntimeError
,
"Failed to append interpreter awaited_by in get_all_awaited_by"
);
goto
result_err
;
}
_Py_RemoteDebug_ClearCache
(
&
self
->
handle
);
return
result
;
result_err
:
_Py_RemoteDebug_ClearCache
(
&
self
->
handle
);
Py_XDECREF
(
result
);
return
NULL
;
}
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL