-
-
Notifications
You must be signed in to change notification settings - Fork 122
/
pydevd_comm.py
1920 lines (1615 loc) · 76.9 KB
/
pydevd_comm.py
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
""" pydevd - a debugging daemon
This is the daemon you launch for python remote debugging.
Protocol:
each command has a format:
id\tsequence-num\ttext
id: protocol command number
sequence-num: each request has a sequence number. Sequence numbers
originating at the debugger are odd, sequence numbers originating
at the daemon are even. Every response uses the same sequence number
as the request.
payload: it is protocol dependent. When response is a complex structure, it
is returned as XML. Each attribute value is urlencoded, and then the whole
payload is urlencoded again to prevent stray characters corrupting protocol/xml encodings
Commands:
NUMBER NAME FROM* ARGUMENTS RESPONSE NOTE
100 series: program execution
101 RUN JAVA - -
102 LIST_THREADS JAVA RETURN with XML listing of all threads
103 THREAD_CREATE PYDB - XML with thread information
104 THREAD_KILL JAVA id (or * to exit) kills the thread
PYDB id nofies JAVA that thread was killed
105 THREAD_SUSPEND JAVA XML of the stack, suspends the thread
reason for suspension
PYDB id notifies JAVA that thread was suspended
106 CMD_THREAD_RUN JAVA id resume the thread
PYDB id \t reason notifies JAVA that thread was resumed
107 STEP_INTO JAVA thread_id
108 STEP_OVER JAVA thread_id
109 STEP_RETURN JAVA thread_id
110 GET_VARIABLE JAVA thread_id \t frame_id \t GET_VARIABLE with XML of var content
FRAME|GLOBAL \t attributes*
111 SET_BREAK JAVA file/line of the breakpoint
112 REMOVE_BREAK JAVA file/line of the return
113 CMD_EVALUATE_EXPRESSION JAVA expression result of evaluating the expression
114 CMD_GET_FRAME JAVA request for frame contents
115 CMD_EXEC_EXPRESSION JAVA
116 CMD_WRITE_TO_CONSOLE PYDB
117 CMD_CHANGE_VARIABLE
118 CMD_RUN_TO_LINE
119 CMD_RELOAD_CODE
120 CMD_GET_COMPLETIONS JAVA
200 CMD_REDIRECT_OUTPUT JAVA streams to redirect as string -
'STDOUT' (redirect only STDOUT)
'STDERR' (redirect only STDERR)
'STDOUT STDERR' (redirect both streams)
500 series diagnostics/ok
501 VERSION either Version string (1.0) Currently just used at startup
502 RETURN either Depends on caller -
900 series: errors
901 ERROR either - This is reserved for unexpected errors.
* JAVA - remote debugger, the java end
* PYDB - pydevd, the python end
"""
import linecache
import os
from _pydev_bundle.pydev_imports import _queue
from _pydev_bundle._pydev_saved_modules import time, ThreadingEvent
from _pydev_bundle._pydev_saved_modules import socket as socket_module
from _pydevd_bundle.pydevd_constants import (
DebugInfoHolder,
IS_WINDOWS,
IS_JYTHON,
IS_WASM,
IS_PY36_OR_GREATER,
STATE_RUN,
ASYNC_EVAL_TIMEOUT_SEC,
get_global_debugger,
GetGlobalDebugger,
set_global_debugger, # Keep for backward compatibility @UnusedImport
silence_warnings_decorator,
filter_all_warnings,
IS_PY311_OR_GREATER,
)
from _pydev_bundle.pydev_override import overrides
import weakref
from _pydev_bundle._pydev_completer import extract_token_and_qualifier
from _pydevd_bundle._debug_adapter.pydevd_schema import (
VariablesResponseBody,
SetVariableResponseBody,
StepInTarget,
StepInTargetsResponseBody,
)
from _pydevd_bundle._debug_adapter import pydevd_base_schema, pydevd_schema
from _pydevd_bundle.pydevd_net_command import NetCommand
from _pydevd_bundle.pydevd_xml import ExceptionOnEvaluate
from _pydevd_bundle.pydevd_constants import ForkSafeLock, NULL
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread
from _pydevd_bundle.pydevd_thread_lifecycle import pydevd_find_thread_by_id, resume_threads
from _pydevd_bundle.pydevd_dont_trace_files import PYDEV_FILE
import dis
import pydevd_file_utils
import itertools
from urllib.parse import quote_plus, unquote_plus
import pydevconsole
from _pydevd_bundle import pydevd_vars, pydevd_io, pydevd_reload
from _pydevd_bundle import pydevd_bytecode_utils
from _pydevd_bundle import pydevd_xml
from _pydevd_bundle import pydevd_vm_type
import sys
import traceback
from _pydevd_bundle.pydevd_utils import (
quote_smart as quote,
compare_object_attrs_key,
notify_about_gevent_if_needed,
isinstance_checked,
ScopeRequest,
getattr_checked,
Timer,
is_current_thread_main_thread,
)
from _pydev_bundle import pydev_log, fsnotify
from _pydev_bundle.pydev_log import exception as pydev_log_exception
from _pydev_bundle import _pydev_completer
from pydevd_tracing import get_exception_traceback_str
from _pydevd_bundle import pydevd_console
from _pydev_bundle.pydev_monkey import disable_trace_thread_modules, enable_trace_thread_modules
from io import StringIO
# CMD_XXX constants imported for backward compatibility
from _pydevd_bundle.pydevd_comm_constants import * # @UnusedWildImport
# Socket import aliases:
AF_INET, AF_INET6, SOCK_STREAM, SHUT_WR, SOL_SOCKET, IPPROTO_TCP, socket = (
socket_module.AF_INET,
socket_module.AF_INET6,
socket_module.SOCK_STREAM,
socket_module.SHUT_WR,
socket_module.SOL_SOCKET,
socket_module.IPPROTO_TCP,
socket_module.socket,
)
if IS_WINDOWS and not IS_JYTHON:
SO_EXCLUSIVEADDRUSE = socket_module.SO_EXCLUSIVEADDRUSE
if not IS_WASM:
SO_REUSEADDR = socket_module.SO_REUSEADDR
class ReaderThread(PyDBDaemonThread):
"""reader thread reads and dispatches commands in an infinite loop"""
def __init__(self, sock, py_db, PyDevJsonCommandProcessor, process_net_command, terminate_on_socket_close=True):
assert sock is not None
PyDBDaemonThread.__init__(self, py_db)
self.__terminate_on_socket_close = terminate_on_socket_close
self.sock = sock
self._buffer = b""
self.name = "pydevd.Reader"
self.process_net_command = process_net_command
self.process_net_command_json = PyDevJsonCommandProcessor(self._from_json).process_net_command_json
def _from_json(self, json_msg, update_ids_from_dap=False):
return pydevd_base_schema.from_json(json_msg, update_ids_from_dap, on_dict_loaded=self._on_dict_loaded)
def _on_dict_loaded(self, dct):
for listener in self.py_db.dap_messages_listeners:
listener.after_receive(dct)
@overrides(PyDBDaemonThread.do_kill_pydev_thread)
def do_kill_pydev_thread(self):
PyDBDaemonThread.do_kill_pydev_thread(self)
# Note that we no longer shutdown the reader, just the writer. The idea is that we shutdown
# the writer to send that the communication has finished, then, the client will shutdown its
# own writer when it receives an empty read, at which point this reader will also shutdown.
# That way, we can *almost* guarantee that all messages have been properly sent -- it's not
# completely guaranteed because it's possible that the process exits before the whole
# message was sent as having this thread alive won't stop the process from exiting -- we
# have a timeout when exiting the process waiting for this thread to finish -- see:
# PyDB.dispose_and_kill_all_pydevd_threads()).
# try:
# self.sock.shutdown(SHUT_RD)
# except:
# pass
# try:
# self.sock.close()
# except:
# pass
def _read(self, size):
while True:
buffer_len = len(self._buffer)
if buffer_len == size:
ret = self._buffer
self._buffer = b""
return ret
if buffer_len > size:
ret = self._buffer[:size]
self._buffer = self._buffer[size:]
return ret
try:
r = self.sock.recv(max(size - buffer_len, 1024))
except OSError:
return b""
if not r:
return b""
self._buffer += r
def _read_line(self):
while True:
i = self._buffer.find(b"\n")
if i != -1:
i += 1 # Add the newline to the return
ret = self._buffer[:i]
self._buffer = self._buffer[i:]
return ret
else:
try:
r = self.sock.recv(1024)
except OSError:
return b""
if not r:
return b""
self._buffer += r
@overrides(PyDBDaemonThread._on_run)
def _on_run(self):
try:
content_len = -1
while True:
# i.e.: even if we received a kill, we should only exit the ReaderThread when the
# client itself closes the connection (although on kill received we stop actually
# processing anything read).
try:
notify_about_gevent_if_needed()
line = self._read_line()
if len(line) == 0:
pydev_log.debug("ReaderThread: empty contents received (len(line) == 0).")
self._terminate_on_socket_close()
return # Finished communication.
if self._kill_received:
continue
if line.startswith(b"Content-Length:"):
content_len = int(line.strip().split(b":", 1)[1])
continue
if content_len != -1:
# If we previously received a content length, read until a '\r\n'.
if line == b"\r\n":
json_contents = self._read(content_len)
content_len = -1
if len(json_contents) == 0:
pydev_log.debug("ReaderThread: empty contents received (len(json_contents) == 0).")
self._terminate_on_socket_close()
return # Finished communication.
if self._kill_received:
continue
# We just received a json message, let's process it.
self.process_net_command_json(self.py_db, json_contents)
continue
else:
# No content len, regular line-based protocol message (remove trailing new-line).
if line.endswith(b"\n\n"):
line = line[:-2]
elif line.endswith(b"\n"):
line = line[:-1]
elif line.endswith(b"\r"):
line = line[:-1]
except:
if not self._kill_received:
pydev_log_exception()
self._terminate_on_socket_close()
return # Finished communication.
# Note: the java backend is always expected to pass utf-8 encoded strings. We now work with str
# internally and thus, we may need to convert to the actual encoding where needed (i.e.: filenames
# on python 2 may need to be converted to the filesystem encoding).
if hasattr(line, "decode"):
line = line.decode("utf-8")
if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 3:
pydev_log.debug("debugger: received >>%s<<\n", line)
args = line.split("\t", 2)
try:
cmd_id = int(args[0])
if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 3:
pydev_log.debug("Received command: %s %s\n", ID_TO_MEANING.get(str(cmd_id), "???"), line)
self.process_command(cmd_id, int(args[1]), args[2])
except:
if sys is not None and pydev_log_exception is not None: # Could happen at interpreter shutdown
pydev_log_exception("Can't process net command: %s.", line)
except:
if not self._kill_received:
if sys is not None and pydev_log_exception is not None: # Could happen at interpreter shutdown
pydev_log_exception()
self._terminate_on_socket_close()
finally:
pydev_log.debug("ReaderThread: exit")
def _terminate_on_socket_close(self):
if self.__terminate_on_socket_close:
self.py_db.dispose_and_kill_all_pydevd_threads()
def process_command(self, cmd_id, seq, text):
self.process_net_command(self.py_db, cmd_id, seq, text)
class FSNotifyThread(PyDBDaemonThread):
def __init__(self, py_db, api, watch_dirs):
PyDBDaemonThread.__init__(self, py_db)
self.api = api
self.name = "pydevd.FSNotifyThread"
self.watcher = fsnotify.Watcher()
self.watch_dirs = watch_dirs
@overrides(PyDBDaemonThread._on_run)
def _on_run(self):
try:
pydev_log.info("Watching directories for code reload:\n---\n%s\n---" % ("\n".join(sorted(self.watch_dirs))))
# i.e.: The first call to set_tracked_paths will do a full scan, so, do it in the thread
# too (after everything is configured).
self.watcher.set_tracked_paths(self.watch_dirs)
while not self._kill_received:
for change_enum, change_path in self.watcher.iter_changes():
# We're only interested in modified events
if change_enum == fsnotify.Change.modified:
pydev_log.info("Modified: %s", change_path)
self.api.request_reload_code(self.py_db, -1, None, change_path)
else:
pydev_log.info("Ignored (add or remove) change in: %s", change_path)
except:
pydev_log.exception("Error when waiting for filesystem changes in FSNotifyThread.")
@overrides(PyDBDaemonThread.do_kill_pydev_thread)
def do_kill_pydev_thread(self):
self.watcher.dispose()
PyDBDaemonThread.do_kill_pydev_thread(self)
class WriterThread(PyDBDaemonThread):
"""writer thread writes out the commands in an infinite loop"""
def __init__(self, sock, py_db, terminate_on_socket_close=True):
PyDBDaemonThread.__init__(self, py_db)
self.sock = sock
self.__terminate_on_socket_close = terminate_on_socket_close
self.name = "pydevd.Writer"
self._cmd_queue = _queue.Queue()
if pydevd_vm_type.get_vm_type() == "python":
self.timeout = 0
else:
self.timeout = 0.1
def add_command(self, cmd):
"""cmd is NetCommand"""
if not self._kill_received: # we don't take new data after everybody die
self._cmd_queue.put(cmd, False)
@overrides(PyDBDaemonThread._on_run)
def _on_run(self):
"""just loop and write responses"""
try:
while True:
try:
try:
cmd = self._cmd_queue.get(True, 0.1)
except _queue.Empty:
if self._kill_received:
pydev_log.debug("WriterThread: kill_received (sock.shutdown(SHUT_WR))")
try:
self.sock.shutdown(SHUT_WR)
except:
pass
# Note: don't close the socket, just send the shutdown,
# then, when no data is received on the reader, it can close
# the socket.
# See: https://blog.netherlabs.nl/articles/2009/01/18/the-ultimate-so_linger-page-or-why-is-my-tcp-not-reliable
# try:
# self.sock.close()
# except:
# pass
return # break if queue is empty and _kill_received
else:
continue
except:
# pydev_log.info('Finishing debug communication...(1)')
# when liberating the thread here, we could have errors because we were shutting down
# but the thread was still not liberated
return
if cmd.as_dict is not None:
for listener in self.py_db.dap_messages_listeners:
listener.before_send(cmd.as_dict)
notify_about_gevent_if_needed()
cmd.send(self.sock)
if cmd.id == CMD_EXIT:
pydev_log.debug("WriterThread: CMD_EXIT received")
break
if time is None:
break # interpreter shutdown
time.sleep(self.timeout)
except Exception:
if self.__terminate_on_socket_close:
self.py_db.dispose_and_kill_all_pydevd_threads()
if DebugInfoHolder.DEBUG_TRACE_LEVEL > 0:
pydev_log_exception()
finally:
pydev_log.debug("WriterThread: exit")
def empty(self):
return self._cmd_queue.empty()
@overrides(PyDBDaemonThread.do_kill_pydev_thread)
def do_kill_pydev_thread(self):
if not self._kill_received:
# Add command before setting the kill flag (otherwise the command may not be added).
exit_cmd = self.py_db.cmd_factory.make_exit_command(self.py_db)
self.add_command(exit_cmd)
PyDBDaemonThread.do_kill_pydev_thread(self)
def create_server_socket(host, port):
try:
server = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)
if IS_WINDOWS and not IS_JYTHON:
server.setsockopt(SOL_SOCKET, SO_EXCLUSIVEADDRUSE, 1)
elif not IS_WASM:
server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
server.bind((host, port))
server.settimeout(None)
except Exception:
server.close()
raise
return server
def start_server(port):
"""binds to a port, waits for the debugger to connect"""
s = create_server_socket(host="", port=port)
try:
s.listen(1)
# Let the user know it's halted waiting for the connection.
host, port = s.getsockname()
msg = f"pydevd: waiting for connection at: {host}:{port}"
print(msg, file=sys.stderr)
pydev_log.info(msg)
new_socket, _addr = s.accept()
pydev_log.info("Connection accepted")
# closing server socket is not necessary but we don't need it
s.close()
return new_socket
except:
pydev_log.exception("Could not bind to port: %s\n", port)
raise
def start_client(host, port):
"""connects to a host/port"""
pydev_log.info("Connecting to %s:%s", host, port)
address_family = AF_INET
for res in socket_module.getaddrinfo(host, port, 0, SOCK_STREAM):
if res[0] == AF_INET:
address_family = res[0]
# Prefer IPv4 addresses for backward compat.
break
if res[0] == AF_INET6:
# Don't break after this - if the socket is dual-stack prefer IPv4.
address_family = res[0]
s = socket(address_family, SOCK_STREAM)
# Set TCP keepalive on an open socket.
# It activates after 1 second (TCP_KEEPIDLE,) of idleness,
# then sends a keepalive ping once every 3 seconds (TCP_KEEPINTVL),
# and closes the connection after 5 failed ping (TCP_KEEPCNT), or 15 seconds
try:
s.setsockopt(SOL_SOCKET, socket_module.SO_KEEPALIVE, 1)
except (AttributeError, OSError):
pass # May not be available everywhere.
try:
s.setsockopt(socket_module.IPPROTO_TCP, socket_module.TCP_KEEPIDLE, 1)
except (AttributeError, OSError):
pass # May not be available everywhere.
try:
s.setsockopt(socket_module.IPPROTO_TCP, socket_module.TCP_KEEPINTVL, 3)
except (AttributeError, OSError):
pass # May not be available everywhere.
try:
s.setsockopt(socket_module.IPPROTO_TCP, socket_module.TCP_KEEPCNT, 5)
except (AttributeError, OSError):
pass # May not be available everywhere.
try:
# 10 seconds default timeout
timeout = int(os.environ.get("PYDEVD_CONNECT_TIMEOUT", 10))
s.settimeout(timeout)
s.connect((host, port))
s.settimeout(None) # no timeout after connected
pydev_log.info(f"Connected to: {s}.")
return s
except:
pydev_log.exception("Could not connect to %s: %s", host, port)
raise
INTERNAL_TERMINATE_THREAD = 1
INTERNAL_SUSPEND_THREAD = 2
class InternalThreadCommand(object):
"""internal commands are generated/executed by the debugger.
The reason for their existence is that some commands have to be executed
on specific threads. These are the InternalThreadCommands that get
get posted to PyDB.
"""
def __init__(self, thread_id, method=None, *args, **kwargs):
self.thread_id = thread_id
self.method = method
self.args = args
self.kwargs = kwargs
def can_be_executed_by(self, thread_id):
"""By default, it must be in the same thread to be executed"""
return self.thread_id == thread_id or self.thread_id.endswith("|" + thread_id)
def do_it(self, dbg):
try:
if self.method is not None:
self.method(dbg, *self.args, **self.kwargs)
else:
raise NotImplementedError("you have to override do_it")
finally:
self.args = None
self.kwargs = None
def __str__(self):
return "InternalThreadCommands(%s, %s, %s)" % (self.method, self.args, self.kwargs)
__repr__ = __str__
class InternalThreadCommandForAnyThread(InternalThreadCommand):
def __init__(self, thread_id, method=None, *args, **kwargs):
assert thread_id == "*"
InternalThreadCommand.__init__(self, thread_id, method, *args, **kwargs)
self.executed = False
self.lock = ForkSafeLock()
def can_be_executed_by(self, thread_id):
return True # Can be executed by any thread.
def do_it(self, dbg):
with self.lock:
if self.executed:
return
self.executed = True
InternalThreadCommand.do_it(self, dbg)
def _send_io_message(py_db, s):
cmd = py_db.cmd_factory.make_io_message(s, 2)
if py_db.writer is not None:
py_db.writer.add_command(cmd)
def internal_reload_code(dbg, seq, module_name, filename):
try:
found_module_to_reload = False
if module_name is not None:
module_name = module_name
if module_name not in sys.modules:
if "." in module_name:
new_module_name = module_name.split(".")[-1]
if new_module_name in sys.modules:
module_name = new_module_name
modules_to_reload = {}
module = sys.modules.get(module_name)
if module is not None:
modules_to_reload[id(module)] = (module, module_name)
if filename:
filename = pydevd_file_utils.normcase(filename)
for module_name, module in sys.modules.copy().items():
f = getattr_checked(module, "__file__")
if f is not None:
if f.endswith((".pyc", ".pyo")):
f = f[:-1]
if pydevd_file_utils.normcase(f) == filename:
modules_to_reload[id(module)] = (module, module_name)
if not modules_to_reload:
if filename and module_name:
_send_io_message(dbg, "code reload: Unable to find module %s to reload for path: %s\n" % (module_name, filename))
elif filename:
_send_io_message(dbg, "code reload: Unable to find module to reload for path: %s\n" % (filename,))
elif module_name:
_send_io_message(dbg, "code reload: Unable to find module to reload: %s\n" % (module_name,))
else:
# Too much info...
# _send_io_message(dbg, 'code reload: This usually means you are trying to reload the __main__ module (which cannot be reloaded).\n')
for module, module_name in modules_to_reload.values():
_send_io_message(dbg, 'code reload: Start reloading module: "' + module_name + '" ... \n')
found_module_to_reload = True
if pydevd_reload.xreload(module):
_send_io_message(dbg, "code reload: reload finished\n")
else:
_send_io_message(dbg, "code reload: reload finished without applying any change\n")
cmd = dbg.cmd_factory.make_reloaded_code_message(seq, found_module_to_reload)
dbg.writer.add_command(cmd)
except:
pydev_log.exception("Error reloading code")
class InternalGetThreadStack(InternalThreadCommand):
"""
This command will either wait for a given thread to be paused to get its stack or will provide
it anyways after a timeout (in which case the stack will be gotten but local variables won't
be available and it'll not be possible to interact with the frame as it's not actually
stopped in a breakpoint).
"""
def __init__(self, seq, thread_id, py_db, set_additional_thread_info, fmt, timeout=0.5, start_frame=0, levels=0):
InternalThreadCommand.__init__(self, thread_id)
self._py_db = weakref.ref(py_db)
self._timeout = time.time() + timeout
self.seq = seq
self._cmd = None
self._fmt = fmt
self._start_frame = start_frame
self._levels = levels
# Note: receives set_additional_thread_info to avoid a circular import
# in this module.
self._set_additional_thread_info = set_additional_thread_info
@overrides(InternalThreadCommand.can_be_executed_by)
def can_be_executed_by(self, _thread_id):
timed_out = time.time() >= self._timeout
py_db = self._py_db()
t = pydevd_find_thread_by_id(self.thread_id)
frame = None
if t and not getattr(t, "pydev_do_not_trace", None):
additional_info = self._set_additional_thread_info(t)
frame = additional_info.get_topmost_frame(t)
try:
self._cmd = py_db.cmd_factory.make_get_thread_stack_message(
py_db,
self.seq,
self.thread_id,
frame,
self._fmt,
must_be_suspended=not timed_out,
start_frame=self._start_frame,
levels=self._levels,
)
finally:
frame = None
t = None
return self._cmd is not None or timed_out
@overrides(InternalThreadCommand.do_it)
def do_it(self, dbg):
if self._cmd is not None:
dbg.writer.add_command(self._cmd)
self._cmd = None
def internal_step_in_thread(py_db, thread_id, cmd_id, set_additional_thread_info):
thread_to_step = pydevd_find_thread_by_id(thread_id)
if thread_to_step is not None:
info = set_additional_thread_info(thread_to_step)
info.pydev_original_step_cmd = cmd_id
info.pydev_step_cmd = cmd_id
info.pydev_step_stop = None
info.pydev_state = STATE_RUN
info.update_stepping_info()
if py_db.stepping_resumes_all_threads:
resume_threads("*", except_thread=thread_to_step)
def internal_smart_step_into(py_db, thread_id, offset, child_offset, set_additional_thread_info):
thread_to_step = pydevd_find_thread_by_id(thread_id)
if thread_to_step is not None:
info = set_additional_thread_info(thread_to_step)
info.pydev_original_step_cmd = CMD_SMART_STEP_INTO
info.pydev_step_cmd = CMD_SMART_STEP_INTO
info.pydev_step_stop = None
info.pydev_smart_parent_offset = int(offset)
info.pydev_smart_child_offset = int(child_offset)
info.pydev_state = STATE_RUN
info.update_stepping_info()
if py_db.stepping_resumes_all_threads:
resume_threads("*", except_thread=thread_to_step)
class InternalSetNextStatementThread(InternalThreadCommand):
def __init__(self, thread_id, cmd_id, line, func_name, seq=0):
"""
cmd_id may actually be one of:
CMD_RUN_TO_LINE
CMD_SET_NEXT_STATEMENT
CMD_SMART_STEP_INTO
"""
self.thread_id = thread_id
self.cmd_id = cmd_id
self.line = line
self.seq = seq
self.func_name = func_name
def do_it(self, dbg):
t = pydevd_find_thread_by_id(self.thread_id)
if t is not None:
info = t.additional_info
info.pydev_original_step_cmd = self.cmd_id
info.pydev_step_cmd = self.cmd_id
info.pydev_step_stop = None
info.pydev_next_line = int(self.line)
info.pydev_func_name = self.func_name
info.pydev_message = str(self.seq)
info.pydev_smart_parent_offset = -1
info.pydev_smart_child_offset = -1
info.pydev_state = STATE_RUN
info.update_stepping_info()
@silence_warnings_decorator
def internal_get_variable_json(py_db, request):
"""
:param VariablesRequest request:
"""
arguments = request.arguments # : :type arguments: VariablesArguments
variables_reference = arguments.variablesReference
scope = None
if isinstance_checked(variables_reference, ScopeRequest):
scope = variables_reference
variables_reference = variables_reference.variable_reference
fmt = arguments.format
if hasattr(fmt, "to_dict"):
fmt = fmt.to_dict()
variables = []
try:
try:
variable = py_db.suspended_frames_manager.get_variable(variables_reference)
except KeyError:
pass
else:
for child_var in variable.get_children_variables(fmt=fmt, scope=scope):
variables.append(child_var.get_var_data(fmt=fmt))
except:
try:
exc, exc_type, tb = sys.exc_info()
err = "".join(traceback.format_exception(exc, exc_type, tb))
variables = [{"name": "<error>", "value": err, "type": "<error>", "variablesReference": 0}]
except:
err = "<Internal error - unable to get traceback when getting variables>"
pydev_log.exception(err)
variables = []
body = VariablesResponseBody(variables)
variables_response = pydevd_base_schema.build_response(request, kwargs={"body": body})
py_db.writer.add_command(NetCommand(CMD_RETURN, 0, variables_response, is_json=True))
class InternalGetVariable(InternalThreadCommand):
"""gets the value of a variable"""
def __init__(self, seq, thread_id, frame_id, scope, attrs):
self.sequence = seq
self.thread_id = thread_id
self.frame_id = frame_id
self.scope = scope
self.attributes = attrs
@silence_warnings_decorator
def do_it(self, dbg):
"""Converts request into python variable"""
try:
xml = StringIO()
xml.write("<xml>")
type_name, val_dict = pydevd_vars.resolve_compound_variable_fields(
dbg, self.thread_id, self.frame_id, self.scope, self.attributes
)
if val_dict is None:
val_dict = {}
# assume properly ordered if resolver returns 'OrderedDict'
# check type as string to support OrderedDict backport for older Python
keys = list(val_dict)
if not (type_name == "OrderedDict" or val_dict.__class__.__name__ == "OrderedDict" or IS_PY36_OR_GREATER):
keys = sorted(keys, key=compare_object_attrs_key)
timer = Timer()
for k in keys:
val = val_dict[k]
evaluate_full_value = pydevd_xml.should_evaluate_full_value(val)
xml.write(pydevd_xml.var_to_xml(val, k, evaluate_full_value=evaluate_full_value))
timer.report_if_compute_repr_attr_slow(self.attributes, k, type(val))
xml.write("</xml>")
cmd = dbg.cmd_factory.make_get_variable_message(self.sequence, xml.getvalue())
xml.close()
dbg.writer.add_command(cmd)
except Exception:
cmd = dbg.cmd_factory.make_error_message(self.sequence, "Error resolving variables %s" % (get_exception_traceback_str(),))
dbg.writer.add_command(cmd)
class InternalGetArray(InternalThreadCommand):
def __init__(self, seq, roffset, coffset, rows, cols, format, thread_id, frame_id, scope, attrs):
self.sequence = seq
self.thread_id = thread_id
self.frame_id = frame_id
self.scope = scope
self.name = attrs.split("\t")[-1]
self.attrs = attrs
self.roffset = int(roffset)
self.coffset = int(coffset)
self.rows = int(rows)
self.cols = int(cols)
self.format = format
def do_it(self, dbg):
try:
frame = dbg.find_frame(self.thread_id, self.frame_id)
var = pydevd_vars.eval_in_context(self.name, frame.f_globals, frame.f_locals, py_db=dbg)
xml = pydevd_vars.table_like_struct_to_xml(var, self.name, self.roffset, self.coffset, self.rows, self.cols, self.format)
cmd = dbg.cmd_factory.make_get_array_message(self.sequence, xml)
dbg.writer.add_command(cmd)
except:
cmd = dbg.cmd_factory.make_error_message(self.sequence, "Error resolving array: " + get_exception_traceback_str())
dbg.writer.add_command(cmd)
def internal_change_variable(dbg, seq, thread_id, frame_id, scope, attr, value):
"""Changes the value of a variable"""
try:
frame = dbg.find_frame(thread_id, frame_id)
if frame is not None:
result = pydevd_vars.change_attr_expression(frame, attr, value, dbg)
else:
result = None
xml = "<xml>"
xml += pydevd_xml.var_to_xml(result, "")
xml += "</xml>"
cmd = dbg.cmd_factory.make_variable_changed_message(seq, xml)
dbg.writer.add_command(cmd)
except Exception:
cmd = dbg.cmd_factory.make_error_message(
seq, "Error changing variable attr:%s expression:%s traceback:%s" % (attr, value, get_exception_traceback_str())
)
dbg.writer.add_command(cmd)
def internal_change_variable_json(py_db, request):
"""
The pydevd_vars.change_attr_expression(thread_id, frame_id, attr, value, dbg) can only
deal with changing at a frame level, so, currently changing the contents of something
in a different scope is currently not supported.
:param SetVariableRequest request:
"""
# : :type arguments: SetVariableArguments
arguments = request.arguments
variables_reference = arguments.variablesReference
scope = None
if isinstance_checked(variables_reference, ScopeRequest):
scope = variables_reference
variables_reference = variables_reference.variable_reference
fmt = arguments.format
if hasattr(fmt, "to_dict"):
fmt = fmt.to_dict()
try:
variable = py_db.suspended_frames_manager.get_variable(variables_reference)
except KeyError:
variable = None
if variable is None:
_write_variable_response(
py_db, request, value="", success=False, message="Unable to find variable container to change: %s." % (variables_reference,)
)
return
child_var = variable.change_variable(arguments.name, arguments.value, py_db, fmt=fmt)
if child_var is None:
_write_variable_response(py_db, request, value="", success=False, message="Unable to change: %s." % (arguments.name,))
return
var_data = child_var.get_var_data(fmt=fmt)
body = SetVariableResponseBody(
value=var_data["value"],
type=var_data["type"],
variablesReference=var_data.get("variablesReference"),
namedVariables=var_data.get("namedVariables"),
indexedVariables=var_data.get("indexedVariables"),
)
variables_response = pydevd_base_schema.build_response(request, kwargs={"body": body})
py_db.writer.add_command(NetCommand(CMD_RETURN, 0, variables_response, is_json=True))
def _write_variable_response(py_db, request, value, success, message):
body = SetVariableResponseBody("")
variables_response = pydevd_base_schema.build_response(request, kwargs={"body": body, "success": False, "message": message})
cmd = NetCommand(CMD_RETURN, 0, variables_response, is_json=True)
py_db.writer.add_command(cmd)
@silence_warnings_decorator
def internal_get_frame(dbg, seq, thread_id, frame_id):
"""Converts request into python variable"""
try:
frame = dbg.find_frame(thread_id, frame_id)
if frame is not None:
hidden_ns = pydevconsole.get_ipython_hidden_vars()
xml = "<xml>"
xml += pydevd_xml.frame_vars_to_xml(frame.f_locals, hidden_ns)
del frame
xml += "</xml>"
cmd = dbg.cmd_factory.make_get_frame_message(seq, xml)
dbg.writer.add_command(cmd)
else:
# pydevd_vars.dump_frames(thread_id)
# don't print this error: frame not found: means that the client is not synchronized (but that's ok)
cmd = dbg.cmd_factory.make_error_message(seq, "Frame not found: %s from thread: %s" % (frame_id, thread_id))
dbg.writer.add_command(cmd)
except:
cmd = dbg.cmd_factory.make_error_message(seq, "Error resolving frame: %s from thread: %s" % (frame_id, thread_id))
dbg.writer.add_command(cmd)
def internal_get_smart_step_into_variants(dbg, seq, thread_id, frame_id, start_line, end_line, set_additional_thread_info):
try:
thread = pydevd_find_thread_by_id(thread_id)
frame = dbg.find_frame(thread_id, frame_id)
if thread is None or frame is None:
cmd = dbg.cmd_factory.make_error_message(seq, "Frame not found: %s from thread: %s" % (frame_id, thread_id))
dbg.writer.add_command(cmd)
return
if pydevd_bytecode_utils is None:
variants = []
else:
variants = pydevd_bytecode_utils.calculate_smart_step_into_variants(frame, int(start_line), int(end_line))
info = set_additional_thread_info(thread)