-
-
Notifications
You must be signed in to change notification settings - Fork 135
Expand file tree
/
Copy path_pydevd_sys_monitoring.py
More file actions
2003 lines (1690 loc) · 73 KB
/
_pydevd_sys_monitoring.py
File metadata and controls
2003 lines (1690 loc) · 73 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
# Copyright: Brainwy Software
#
# License: EPL
from collections import namedtuple
import dis
import os
import re
import sys
from _pydev_bundle._pydev_saved_modules import threading
from types import CodeType, FrameType
from typing import Dict, Optional, Tuple, Any
from os.path import basename, splitext
from _pydev_bundle import pydev_log
from _pydevd_bundle import pydevd_dont_trace
from _pydevd_bundle.pydevd_constants import (
IS_PY313_OR_GREATER,
GlobalDebuggerHolder,
ForkSafeLock,
PYDEVD_IPYTHON_CONTEXT,
EXCEPTION_TYPE_USER_UNHANDLED,
RETURN_VALUES_DICT,
PYTHON_SUSPEND,
)
from pydevd_file_utils import (
NORM_PATHS_AND_BASE_CONTAINER,
get_abs_path_real_path_and_base_from_file,
get_abs_path_real_path_and_base_from_frame,
)
from _pydevd_bundle.pydevd_trace_dispatch import should_stop_on_exception, handle_exception
from _pydevd_bundle.pydevd_constants import EXCEPTION_TYPE_HANDLED
from _pydevd_bundle.pydevd_trace_dispatch import is_unhandled_exception
from _pydevd_bundle.pydevd_breakpoints import stop_on_unhandled_exception
from _pydevd_bundle.pydevd_utils import get_clsname_for_code
# fmt: off
# IFDEF CYTHON
# import cython
# from _pydevd_bundle.pydevd_cython cimport set_additional_thread_info, any_thread_stepping, PyDBAdditionalThreadInfo
# ELSE
from _pydevd_bundle.pydevd_additional_thread_info import set_additional_thread_info, any_thread_stepping, PyDBAdditionalThreadInfo
# ENDIF
# fmt: on
try:
from _pydevd_bundle.pydevd_bytecode_utils import get_smart_step_into_variant_from_frame_offset
except ImportError:
def get_smart_step_into_variant_from_frame_offset(*args, **kwargs):
return None
if hasattr(sys, "monitoring"):
DEBUGGER_ID = sys.monitoring.DEBUGGER_ID
monitor = sys.monitoring
_thread_local_info = threading.local()
_get_ident = threading.get_ident
_thread_active = threading._active # noqa
# IFDEF CYTHON
# cython_inline_constant: CMD_THREAD_SUSPEND = 105
# cython_inline_constant: CMD_STEP_INTO = 107
# cython_inline_constant: CMD_STEP_OVER = 108
# cython_inline_constant: CMD_STEP_INTO_MY_CODE = 144
# cython_inline_constant: CMD_STEP_INTO_COROUTINE = 206
# cython_inline_constant: CMD_SMART_STEP_INTO = 128
# cython_inline_constant: can_skip: bool = True
# cython_inline_constant: CMD_STEP_RETURN = 109
# cython_inline_constant: CMD_STEP_OVER_MY_CODE = 159
# cython_inline_constant: CMD_STEP_RETURN_MY_CODE = 160
# cython_inline_constant: CMD_SET_BREAK = 111
# cython_inline_constant: CMD_SET_FUNCTION_BREAK = 208
# cython_inline_constant: STATE_RUN = 1
# cython_inline_constant: STATE_SUSPEND = 2
# ELSE
# Note: those are now inlined on cython.
CMD_THREAD_SUSPEND: int = 105
CMD_STEP_INTO: int = 107
CMD_STEP_OVER: int = 108
CMD_STEP_INTO_MY_CODE: int = 144
CMD_STEP_INTO_COROUTINE: int = 206
CMD_SMART_STEP_INTO: int = 128
can_skip: bool = True
CMD_STEP_RETURN: int = 109
CMD_STEP_OVER_MY_CODE: int = 159
CMD_STEP_RETURN_MY_CODE: int = 160
CMD_SET_BREAK: int = 111
CMD_SET_FUNCTION_BREAK: int = 208
STATE_RUN: int = 1
STATE_SUSPEND: int = 2
# ENDIF
IGNORE_EXCEPTION_TAG = re.compile("[^#]*#.*@IgnoreException")
DEBUG_START = ("pydevd.py", "run")
DEBUG_START_PY3K = ("_pydev_execfile.py", "execfile")
TRACE_PROPERTY = "pydevd_traceproperty.py"
_global_notify_skipped_step_in = False
_global_notify_skipped_step_in_lock = ForkSafeLock()
# fmt: off
# IFDEF CYTHON
# cdef _notify_skipped_step_in_because_of_filters(py_db, frame):
# ELSE
def _notify_skipped_step_in_because_of_filters(py_db, frame):
# ENDIF
# fmt: on
global _global_notify_skipped_step_in
with _global_notify_skipped_step_in_lock:
if _global_notify_skipped_step_in:
# Check with lock in place (callers should actually have checked
# before without the lock in place due to performance).
return
_global_notify_skipped_step_in = True
py_db.notify_skipped_step_in_because_of_filters(frame)
# Easy for cython: always get the one at level 0 as that's the caller frame
# (on Python we have to control the depth to get the first user frame).
# fmt: off
# IFDEF CYTHON
# @cython.cfunc
# def _getframe(depth=0):
# return sys._getframe()
# ELSE
_getframe = sys._getframe
# ENDIF
# fmt: on
# fmt: off
# IFDEF CYTHON
# cdef _get_bootstrap_frame(depth):
# ELSE
def _get_bootstrap_frame(depth: int) -> Tuple[Optional[FrameType], bool]:
# ENDIF
# fmt: on
try:
return _thread_local_info.f_bootstrap, _thread_local_info.is_bootstrap_frame_internal
except:
frame = _getframe(depth)
f_bootstrap = frame
# print('called at', f_bootstrap.f_code.co_name, f_bootstrap.f_code.co_filename, f_bootstrap.f_code.co_firstlineno)
is_bootstrap_frame_internal = False
while f_bootstrap is not None:
filename = f_bootstrap.f_code.co_filename
name = splitext(basename(filename))[0]
if name == "threading":
if f_bootstrap.f_code.co_name in ("__bootstrap", "_bootstrap"):
# We need __bootstrap_inner, not __bootstrap.
return None, False
elif f_bootstrap.f_code.co_name in ("__bootstrap_inner", "_bootstrap_inner", "is_alive"):
# Note: be careful not to use threading.current_thread to avoid creating a dummy thread.
is_bootstrap_frame_internal = True
break
elif name == "pydev_monkey":
if f_bootstrap.f_code.co_name == "__call__":
is_bootstrap_frame_internal = True
break
elif name == "pydevd":
if f_bootstrap.f_code.co_name in ("run", "main"):
# We need to get to _exec
return None, False
if f_bootstrap.f_code.co_name == "_exec":
is_bootstrap_frame_internal = True
break
elif f_bootstrap.f_back is None:
break
f_bootstrap = f_bootstrap.f_back
if f_bootstrap is not None:
_thread_local_info.is_bootstrap_frame_internal = is_bootstrap_frame_internal
_thread_local_info.f_bootstrap = f_bootstrap
return _thread_local_info.f_bootstrap, _thread_local_info.is_bootstrap_frame_internal
return f_bootstrap, is_bootstrap_frame_internal
# fmt: off
# IFDEF CYTHON
# cdef _get_unhandled_exception_frame(exc, int depth):
# ELSE
def _get_unhandled_exception_frame(exc, depth: int) -> Optional[FrameType]:
# ENDIF
# fmt: on
try:
# Unhandled frame has to be from the same exception.
if _thread_local_info.f_unhandled_exc is exc:
return _thread_local_info.f_unhandled_frame
else:
del _thread_local_info.f_unhandled_frame
del _thread_local_info.f_unhandled_exc
raise AttributeError('Not the same exception')
except:
f_unhandled = _getframe(depth)
while f_unhandled is not None and f_unhandled.f_back is not None:
f_back = f_unhandled.f_back
filename = f_back.f_code.co_filename
name = splitext(basename(filename))[0]
# When the back frame is the bootstrap (or if we have no back
# frame) then use this frame as the one to track.
if name == "threading":
if f_back.f_code.co_name in ("__bootstrap", "_bootstrap", "__bootstrap_inner", "_bootstrap_inner", "run"):
break
elif name == "pydev_monkey":
if f_back.f_code.co_name == "__call__":
break
elif name == "pydevd":
if f_back.f_code.co_name in ("_exec", "run", "main"):
break
elif name == "pydevd_runpy":
if f_back.f_code.co_name.startswith(("run", "_run")):
break
elif name == "<frozen runpy>":
if f_back.f_code.co_name.startswith(("run", "_run")):
break
elif name == "runpy":
if f_back.f_code.co_name.startswith(("run", "_run")):
break
f_unhandled = f_back
if f_unhandled is not None:
_thread_local_info.f_unhandled_frame = f_unhandled
_thread_local_info.f_unhandled_exc = exc
return _thread_local_info.f_unhandled_frame
return f_unhandled
# fmt: off
# IFDEF CYTHON
# cdef class ThreadInfo:
# cdef unsigned long thread_ident
# cdef PyDBAdditionalThreadInfo additional_info
# thread: threading.Thread
# trace: bool
# ELSE
class ThreadInfo:
additional_info: PyDBAdditionalThreadInfo
thread_ident: int
thread: threading.Thread
trace: bool
# ENDIF
# fmt: on
# fmt: off
# IFDEF CYTHON
# def __init__(self, thread, unsigned long thread_ident, bint trace, PyDBAdditionalThreadInfo additional_info):
# ELSE
def __init__(self, thread: threading.Thread, thread_ident: int, trace: bool, additional_info: PyDBAdditionalThreadInfo):
# ENDIF
# fmt: on
self.thread = thread
self.thread_ident = thread_ident
self.additional_info = additional_info
self.trace = trace
self._use_handle = hasattr(thread, "_handle")
self._use_started = hasattr(thread, "_started")
self._use_os_thread_handle = hasattr(thread, "_os_thread_handle")
# fmt: off
# IFDEF CYTHON
# cdef bint is_thread_alive(self):
# ELSE
def is_thread_alive(self):
# ENDIF
# fmt: on
# Python 3.14
if self._use_os_thread_handle and self._use_started:
return not self.thread._os_thread_handle.is_done()
# Python 3.13
elif self._use_handle and self._use_started:
return not self.thread._handle.is_done()
# Python 3.12
else:
return not self.thread._is_stopped
class _DeleteDummyThreadOnDel:
"""
Helper class to remove a dummy thread from threading._active on __del__.
"""
def __init__(self, dummy_thread):
self._dummy_thread = dummy_thread
self._tident = dummy_thread.ident
# Put the thread on a thread local variable so that when
# the related thread finishes this instance is collected.
#
# Note: no other references to this instance may be created.
# If any client code creates a reference to this instance,
# the related _DummyThread will be kept forever!
_thread_local_info._track_dummy_thread_ref = self
def __del__(self):
with threading._active_limbo_lock:
if _thread_active.get(self._tident) is self._dummy_thread:
_thread_active.pop(self._tident, None)
# fmt: off
# IFDEF CYTHON
# cdef _create_thread_info(depth):
# cdef unsigned long thread_ident
# ELSE
def _create_thread_info(depth):
# ENDIF
# fmt: on
# Don't call threading.currentThread because if we're too early in the process
# we may create a dummy thread.
thread_ident = _get_ident()
f_bootstrap_frame, is_bootstrap_frame_internal = _get_bootstrap_frame(depth + 1)
if f_bootstrap_frame is None:
return None # Case for threading when it's still in bootstrap or early in pydevd.
if is_bootstrap_frame_internal:
t = None
if f_bootstrap_frame.f_code.co_name in ("__bootstrap_inner", "_bootstrap_inner", "is_alive"):
# Note: be careful not to use threading.current_thread to avoid creating a dummy thread.
t = f_bootstrap_frame.f_locals.get("self")
if not isinstance(t, threading.Thread):
t = None
elif f_bootstrap_frame.f_code.co_name in ("_exec", "__call__"):
# Note: be careful not to use threading.current_thread to avoid creating a dummy thread.
t = f_bootstrap_frame.f_locals.get("t")
if not isinstance(t, threading.Thread):
t = None
else:
# This means that the first frame is not in threading nor in pydevd.
# In practice this means it's some unmanaged thread, so, creating
# a dummy thread is ok in this use-case.
t = threading.current_thread()
if t is None:
t = _thread_active.get(thread_ident)
if isinstance(t, threading._DummyThread) and not IS_PY313_OR_GREATER:
_thread_local_info._ref = _DeleteDummyThreadOnDel(t)
if t is None:
return None
if getattr(t, "is_pydev_daemon_thread", False):
return ThreadInfo(t, thread_ident, False, None)
else:
try:
additional_info = t.additional_info
if additional_info is None:
raise AttributeError()
except:
additional_info = set_additional_thread_info(t)
return ThreadInfo(t, thread_ident, True, additional_info)
# fmt: off
# IFDEF CYTHON
# cdef class FuncCodeInfo:
# cdef str co_filename
# cdef str canonical_normalized_filename
# cdef str abs_path_filename
# cdef bint always_skip_code
# cdef bint breakpoint_found
# cdef bint function_breakpoint_found
# cdef bint plugin_line_breakpoint_found
# cdef bint plugin_call_breakpoint_found
# cdef bint plugin_line_stepping
# cdef bint plugin_call_stepping
# cdef bint plugin_return_stepping
# cdef int pydb_mtime
# cdef dict bp_line_to_breakpoint
# cdef object function_breakpoint
# cdef bint always_filtered_out
# cdef bint filtered_out_force_checked
# cdef object try_except_container_obj
# cdef object code_obj
# cdef str co_name
# ELSE
class FuncCodeInfo:
# ENDIF
# fmt: on
def __init__(self):
self.co_filename: str = ""
self.canonical_normalized_filename: str = ""
self.abs_path_filename: str = ""
# These is never seen and we never stop, even if it's a callback coming
# from user code (these are completely invisible to the debugging tracing).
self.always_skip_code: bool = False
self.breakpoint_found: bool = False
self.function_breakpoint_found: bool = False
# A plugin can choose whether to stop on function calls or line events.
self.plugin_line_breakpoint_found: bool = False
self.plugin_call_breakpoint_found: bool = False
self.plugin_line_stepping: bool = False
self.plugin_call_stepping: bool = False
self.plugin_return_stepping: bool = False
# When pydb_mtime != PyDb.mtime the validity of breakpoints have
# to be re-evaluated (if invalid a new FuncCodeInfo must be created and
# tracing can't be disabled for the related frames).
self.pydb_mtime: int = -1
self.bp_line_to_breakpoint: Dict[int, Any] = {}
self.function_breakpoint = None
# This means some file is globally filtered out during debugging. Note
# that we may still need to pause in it (in a step return to user code,
# we may need to track this one).
self.always_filtered_out: bool = False
# This should be used to filter code in a CMD_STEP_INTO_MY_CODE
# (and other XXX_MY_CODE variants).
self.filtered_out_force_checked: bool = False
self.try_except_container_obj: Optional[_TryExceptContainerObj] = None
self.code_obj: CodeType = None
self.co_name: str = ""
def get_line_of_offset(self, offset):
for start, end, line in self.code_obj.co_lines():
if start is not None and end is not None and line is not None:
if offset >= start and offset <= end:
return line
return -1
# fmt: off
# IFDEF CYTHON
# cdef _get_thread_info(bint create, int depth):
# ELSE
def _get_thread_info(create: bool, depth: int) -> Optional[ThreadInfo]:
# ENDIF
# fmt: on
"""
Provides thread-related info.
May return None if the thread is still not active.
"""
try:
# Note: changing to a `dict[thread.ident] = thread_info` had almost no
# effect in the performance.
return _thread_local_info.thread_info
except:
if not create:
return None
thread_info = _create_thread_info(depth + 1)
if thread_info is None:
return None
_thread_local_info.thread_info = thread_info
return _thread_local_info.thread_info
# fmt: off
# IFDEF CYTHON
# cdef class _CodeLineInfo:
# cdef dict line_to_offset
# cdef int first_line
# cdef int last_line
# ELSE
class _CodeLineInfo:
line_to_offset: Dict[int, Any]
first_line: int
last_line: int
# ENDIF
# fmt: on
# fmt: off
# IFDEF CYTHON
# def __init__(self, dict line_to_offset, int first_line, int last_line):
# self.line_to_offset = line_to_offset
# self.first_line = first_line
# self.last_line = last_line
# ELSE
def __init__(self, line_to_offset, first_line, last_line):
self.line_to_offset = line_to_offset
self.first_line = first_line
self.last_line = last_line
# ENDIF
# fmt: on
# Note: this method has a version in cython too
# fmt: off
# IFDEF CYTHON
# cdef _CodeLineInfo _get_code_line_info(code_obj, _cache={}):
# ELSE
def _get_code_line_info(code_obj, _cache={}) -> _CodeLineInfo:
# ENDIF
# fmt: on
try:
return _cache[code_obj]
except:
line_to_offset = {}
first_line = None
last_line = None
for offset, line in dis.findlinestarts(code_obj):
if line is not None:
line_to_offset[line] = offset
if len(line_to_offset):
first_line = min(line_to_offset)
last_line = max(line_to_offset)
ret = _CodeLineInfo(line_to_offset, first_line, last_line)
_cache[code_obj] = ret
return ret
_code_to_func_code_info_cache: Dict[CodeType, "FuncCodeInfo"] = {}
# fmt: off
# IFDEF CYTHON
# cpdef FuncCodeInfo _get_func_code_info(code_obj, frame_or_depth):
# cdef FuncCodeInfo func_code_info
# ELSE
def _get_func_code_info(code_obj, frame_or_depth) -> FuncCodeInfo:
# ENDIF
# fmt: on
"""
Provides code-object related info.
Note that it contains informations on the breakpoints for a given function.
If breakpoints change a new FuncCodeInfo instance will be created.
Note that this can be called by any thread.
"""
py_db = GlobalDebuggerHolder.global_dbg
if py_db is None:
return None
func_code_info = _code_to_func_code_info_cache.get(code_obj)
if func_code_info is not None:
if func_code_info.pydb_mtime == py_db.mtime:
# if DEBUG:
# print('_get_func_code_info: matched mtime', key, code_obj)
return func_code_info
# fmt: off
# IFDEF CYTHON
# cdef dict cache_file_type
# cdef tuple cache_file_type_key
# cdef PyCodeObject * code
# cdef str co_filename
# cdef str co_name
# code = <PyCodeObject *> code_obj
# co_filename = <str> code.co_filename
# co_name = <str> code.co_name
# ELSE
cache_file_type: dict
cache_file_type_key: tuple
code = code_obj
co_filename: str = code.co_filename
co_name: str = code.co_name
# ENDIF
# fmt: on
# print('_get_func_code_info: new (mtime did not match)', key, code_obj)
func_code_info = FuncCodeInfo()
func_code_info.code_obj = code_obj
code_line_info = _get_code_line_info(code_obj)
line_to_offset = code_line_info.line_to_offset
func_code_info.pydb_mtime = py_db.mtime
func_code_info.co_filename = co_filename
func_code_info.co_name = co_name
# Compute whether to always skip this.
try:
abs_path_real_path_and_base = NORM_PATHS_AND_BASE_CONTAINER[co_filename]
except:
abs_path_real_path_and_base = get_abs_path_real_path_and_base_from_file(co_filename)
func_code_info.abs_path_filename = abs_path_real_path_and_base[0]
func_code_info.canonical_normalized_filename = abs_path_real_path_and_base[1]
frame = None
cache_file_type = py_db.get_cache_file_type()
# Note: this cache key must be the same from PyDB.get_file_type() -- see it for comments
# on the cache.
cache_file_type_key = (code.co_firstlineno, abs_path_real_path_and_base[0], code_obj)
try:
file_type = cache_file_type[cache_file_type_key] # Make it faster
except:
if frame is None:
if frame_or_depth.__class__ == int:
frame = _getframe(frame_or_depth + 1)
else:
frame = frame_or_depth
assert frame.f_code is code_obj, "%s != %s" % (frame.f_code, code_obj)
file_type = py_db.get_file_type(frame, abs_path_real_path_and_base) # we don't want to debug anything related to pydevd
if file_type is not None:
func_code_info.always_skip_code = True
func_code_info.always_filtered_out = True
_code_to_func_code_info_cache[code_obj] = func_code_info
return func_code_info
# still not set, check for dont trace comments.
if pydevd_dont_trace.should_trace_hook is not None:
# I.e.: cache the result skip (no need to evaluate the same frame multiple times).
# Note that on a code reload, we won't re-evaluate this because in practice, the frame.f_code
# Which will be handled by this frame is read-only, so, we can cache it safely.
if not pydevd_dont_trace.should_trace_hook(code_obj, func_code_info.abs_path_filename):
if frame is None:
if frame_or_depth.__class__ == int:
frame = _getframe(frame_or_depth + 1)
else:
frame = frame_or_depth
assert frame.f_code is code_obj
func_code_info.always_filtered_out = True
_code_to_func_code_info_cache[code_obj] = func_code_info
return func_code_info
if frame is None:
if frame_or_depth.__class__ == int:
frame = _getframe(frame_or_depth + 1)
else:
frame = frame_or_depth
assert frame.f_code is code_obj
func_code_info.filtered_out_force_checked = py_db.apply_files_filter(frame, func_code_info.abs_path_filename, True)
if py_db.is_files_filter_enabled:
func_code_info.always_filtered_out = func_code_info.filtered_out_force_checked
if func_code_info.always_filtered_out:
_code_to_func_code_info_cache[code_obj] = func_code_info
return func_code_info
else:
func_code_info.always_filtered_out = False
# Handle regular breakpoints
breakpoints: dict = py_db.breakpoints.get(func_code_info.canonical_normalized_filename)
function_breakpoint: object = py_db.function_breakpoint_name_to_breakpoint.get(func_code_info.co_name)
# print('\n---')
# print(py_db.breakpoints)
# print(func_code_info.canonical_normalized_filename)
# print(py_db.breakpoints.get(func_code_info.canonical_normalized_filename))
if function_breakpoint:
# Go directly into tracing mode
func_code_info.function_breakpoint_found = True
func_code_info.function_breakpoint = function_breakpoint
if breakpoints:
# if DEBUG:
# print('found breakpoints', code_obj_py.co_name, breakpoints)
bp_line_to_breakpoint = {}
for breakpoint_line, bp in breakpoints.items():
if breakpoint_line in line_to_offset:
bp_line_to_breakpoint[breakpoint_line] = bp
func_code_info.breakpoint_found = bool(bp_line_to_breakpoint)
func_code_info.bp_line_to_breakpoint = bp_line_to_breakpoint
if py_db.plugin:
plugin_manager = py_db.plugin
is_tracked_frame = plugin_manager.is_tracked_frame(frame)
if is_tracked_frame:
if py_db.has_plugin_line_breaks:
required_events_breakpoint = plugin_manager.required_events_breakpoint()
func_code_info.plugin_line_breakpoint_found = "line" in required_events_breakpoint
func_code_info.plugin_call_breakpoint_found = "call" in required_events_breakpoint
required_events_stepping = plugin_manager.required_events_stepping()
func_code_info.plugin_line_stepping: bool = "line" in required_events_stepping
func_code_info.plugin_call_stepping: bool = "call" in required_events_stepping
func_code_info.plugin_return_stepping: bool = "return" in required_events_stepping
_code_to_func_code_info_cache[code_obj] = func_code_info
return func_code_info
# fmt: off
# IFDEF CYTHON
# cdef _enable_line_tracing(code):
# ELSE
def _enable_line_tracing(code):
# ENDIF
# fmt: on
# print('enable line tracing', code)
_ensure_monitoring()
events = monitor.get_local_events(DEBUGGER_ID, code)
monitor.set_local_events(DEBUGGER_ID, code, events | monitor.events.LINE | monitor.events.JUMP)
# fmt: off
# IFDEF CYTHON
# cdef _enable_return_tracing(code):
# ELSE
def _enable_return_tracing(code):
# ENDIF
# fmt: on
# print('enable return tracing', code)
_ensure_monitoring()
events = monitor.get_local_events(DEBUGGER_ID, code)
monitor.set_local_events(DEBUGGER_ID, code, events | monitor.events.PY_RETURN)
# fmt: off
# IFDEF CYTHON
# cpdef disable_code_tracing(code):
# ELSE
def disable_code_tracing(code):
# ENDIF
# fmt: on
_ensure_monitoring()
monitor.set_local_events(DEBUGGER_ID, code, 0)
# fmt: off
# IFDEF CYTHON
# cpdef enable_code_tracing(unsigned long thread_ident, code, frame):
# ELSE
def enable_code_tracing(thread_ident: Optional[int], code, frame) -> bool:
# ENDIF
# fmt: on
"""
Note: this must enable code tracing for the given code/frame.
The frame can be from any thread!
:return: Whether code tracing was added in this function to the given code.
"""
# DEBUG = False # 'my_code.py' in code.co_filename or 'other.py' in code.co_filename
# if DEBUG:
# print('==== enable code tracing', code.co_filename[-30:], code.co_name)
py_db: object = GlobalDebuggerHolder.global_dbg
if py_db is None or py_db.pydb_disposed:
return False
func_code_info: FuncCodeInfo = _get_func_code_info(code, frame)
if func_code_info.always_skip_code:
# if DEBUG:
# print('disable (always skip)')
return False
try:
thread = threading._active.get(thread_ident)
if thread is None:
return False
additional_info = set_additional_thread_info(thread)
except:
# Cannot set based on stepping
return False
return _enable_code_tracing(py_db, additional_info, func_code_info, code, frame, False)
# fmt: off
# IFDEF CYTHON
# cdef bint _enable_code_tracing(py_db, PyDBAdditionalThreadInfo additional_info, FuncCodeInfo func_code_info, code, frame, bint warn_on_filtered_out):
# cdef int step_cmd
# cdef bint is_stepping
# cdef bint code_tracing_added
# ELSE
def _enable_code_tracing(py_db, additional_info, func_code_info: FuncCodeInfo, code, frame, warn_on_filtered_out) -> bool:
# ENDIF
# fmt: on
"""
:return: Whether code tracing was added in this function to the given code.
"""
# DEBUG = False # 'my_code.py' in code.co_filename or 'other.py' in code.co_filename
step_cmd = additional_info.pydev_step_cmd
is_stepping = step_cmd != -1
code_tracing_added = False
if func_code_info.always_filtered_out:
# if DEBUG:
# print('disable (always filtered out)')
if (
warn_on_filtered_out
and is_stepping
and additional_info.pydev_original_step_cmd in (CMD_STEP_INTO, CMD_STEP_INTO_MY_CODE)
and not _global_notify_skipped_step_in
):
_notify_skipped_step_in_because_of_filters(py_db, frame)
if is_stepping:
# Tracing may be needed for return value
_enable_step_tracing(py_db, code, step_cmd, additional_info, frame)
code_tracing_added = True
return code_tracing_added
if func_code_info.breakpoint_found or func_code_info.plugin_line_breakpoint_found:
_enable_line_tracing(code)
code_tracing_added = True
if is_stepping:
_enable_step_tracing(py_db, code, step_cmd, additional_info, frame)
code_tracing_added = True
return code_tracing_added
# fmt: off
# IFDEF CYTHON
# cdef _enable_step_tracing(py_db, code, step_cmd, PyDBAdditionalThreadInfo info, frame):
# ELSE
def _enable_step_tracing(py_db, code, step_cmd, info, frame):
# ENDIF
# fmt: on
if step_cmd in (CMD_STEP_INTO, CMD_STEP_INTO_MY_CODE, CMD_STEP_INTO_COROUTINE, CMD_SMART_STEP_INTO, CMD_THREAD_SUSPEND):
# Stepping (must have line/return tracing enabled).
_enable_line_tracing(code)
_enable_return_tracing(code)
elif step_cmd in (CMD_STEP_RETURN, CMD_STEP_RETURN_MY_CODE) and _is_same_frame(info, info.pydev_step_stop, frame):
_enable_return_tracing(code)
elif step_cmd in (CMD_STEP_OVER, CMD_STEP_OVER_MY_CODE):
if _is_same_frame(info, info.pydev_step_stop, frame):
_enable_line_tracing(code)
# Wee need to enable return tracing because if we have a return during a step over
# we need to stop too.
_enable_return_tracing(code)
elif py_db.show_return_values and _is_same_frame(info, info.pydev_step_stop, frame.f_back):
# Show return values on step over.
_enable_return_tracing(code)
# fmt: off
# IFDEF CYTHON
# cdef class _TryExceptContainerObj:
# cdef list try_except_infos
# ELSE
class _TryExceptContainerObj:
# ENDIF
# fmt: on
"""
A dumb container object just to contain the try..except info when needed. Meant to be
persistent among multiple PyDBFrames to the same code object.
"""
# fmt: off
# IFDEF CYTHON
# def __init__(self, list try_except_infos):
# self.try_except_infos = try_except_infos
# ELSE
def __init__(self, try_except_infos):
self.try_except_infos = try_except_infos
# ENDIF
# fmt: on
# fmt: off
# IFDEF CYTHON
# cdef _unwind_event(code, instruction, exc):
# cdef ThreadInfo thread_info
# cdef FuncCodeInfo func_code_info
# ELSE
def _unwind_event(code, instruction, exc):
# ENDIF
# fmt: on
try:
thread_info = _thread_local_info.thread_info
except:
thread_info = _get_thread_info(True, 1)
if thread_info is None:
return
py_db: object = GlobalDebuggerHolder.global_dbg
if py_db is None or py_db.pydb_disposed:
return
if not thread_info.trace or not thread_info.is_thread_alive():
# For thread-related stuff we can't disable the code tracing because other
# threads may still want it...
return
func_code_info: FuncCodeInfo = _get_func_code_info(code, 1)
if func_code_info.always_skip_code:
return
# print('_unwind_event', code, exc)
frame = _getframe(1)
arg = (type(exc), exc, exc.__traceback__)
has_caught_exception_breakpoint_in_pydb = (
py_db.break_on_caught_exceptions or py_db.break_on_user_uncaught_exceptions or py_db.has_plugin_exception_breaks
)
if has_caught_exception_breakpoint_in_pydb:
_should_stop, frame, user_uncaught_exc_info = should_stop_on_exception(
py_db, thread_info.additional_info, frame, thread_info.thread, arg, None, is_unwind=True
)
if user_uncaught_exc_info:
# TODO: Check: this may no longer be needed as in the unwind we know it's
# an exception bubbling up (wait for all tests to pass to check it).
if func_code_info.try_except_container_obj is None:
container_obj = _TryExceptContainerObj(py_db.collect_try_except_info(frame.f_code))
func_code_info.try_except_container_obj = container_obj
is_unhandled = is_unhandled_exception(
func_code_info.try_except_container_obj, py_db, frame, user_uncaught_exc_info[1], user_uncaught_exc_info[2]
)
if is_unhandled:
handle_exception(py_db, thread_info.thread, frame, user_uncaught_exc_info[0], EXCEPTION_TYPE_USER_UNHANDLED)
return
break_on_uncaught_exceptions = py_db.break_on_uncaught_exceptions
if break_on_uncaught_exceptions:
if frame is _get_unhandled_exception_frame(exc, 1):
stop_on_unhandled_exception(py_db, thread_info.thread, thread_info.additional_info, arg)
return
# fmt: off
# IFDEF CYTHON
# cdef _raise_event(code, instruction, exc):
# cdef ThreadInfo thread_info
# cdef FuncCodeInfo func_code_info
# ELSE
def _raise_event(code, instruction, exc):
# ENDIF
# fmt: on
"""
The way this should work is the following: when the user is using
pydevd to do the launch and we're on a managed stack, we should consider
unhandled only if it gets into a pydevd. If it's a thread, if it stops
inside the threading and if it's an unmanaged thread (i.e.: QThread)
then stop if it doesn't have a back frame.
Note: unlike other events, this one is global and not per-code (so,
it cannot be individually enabled/disabled for a given code object).
"""
try:
thread_info = _thread_local_info.thread_info
except:
thread_info = _get_thread_info(True, 1)
if thread_info is None:
return
py_db: object = GlobalDebuggerHolder.global_dbg
if py_db is None or py_db.pydb_disposed:
return
if not thread_info.trace or not thread_info.is_thread_alive():
# For thread-related stuff we can't disable the code tracing because other
# threads may still want it...
return
func_code_info: FuncCodeInfo = _get_func_code_info(code, 1)
if func_code_info.always_skip_code:
return
frame = _getframe(1)
arg = (type(exc), exc, exc.__traceback__)
# Compute the previous exception info (if any). We use it to check if the exception
# should be stopped
prev_exc_info = _thread_local_info._user_uncaught_exc_info if hasattr(_thread_local_info, "_user_uncaught_exc_info") else None
should_stop, frame, _user_uncaught_exc_info = should_stop_on_exception(
py_db, thread_info.additional_info, frame, thread_info.thread, arg, prev_exc_info
)
# Save the current exception info for the next raise event.
_thread_local_info._user_uncaught_exc_info = _user_uncaught_exc_info