forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdap_server.py
1616 lines (1484 loc) · 56.5 KB
/
dap_server.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
#!/usr/bin/env python
import binascii
import json
import optparse
import os
import pprint
import socket
import string
import subprocess
import sys
import threading
import time
def dump_memory(base_addr, data, num_per_line, outfile):
data_len = len(data)
hex_string = binascii.hexlify(data)
addr = base_addr
ascii_str = ""
i = 0
while i < data_len:
outfile.write("0x%8.8x: " % (addr + i))
bytes_left = data_len - i
if bytes_left >= num_per_line:
curr_data_len = num_per_line
else:
curr_data_len = bytes_left
hex_start_idx = i * 2
hex_end_idx = hex_start_idx + curr_data_len * 2
curr_hex_str = hex_string[hex_start_idx:hex_end_idx]
# 'curr_hex_str' now contains the hex byte string for the
# current line with no spaces between bytes
t = iter(curr_hex_str)
# Print hex bytes separated by space
outfile.write(" ".join(a + b for a, b in zip(t, t)))
# Print two spaces
outfile.write(" ")
# Calculate ASCII string for bytes into 'ascii_str'
ascii_str = ""
for j in range(i, i + curr_data_len):
ch = data[j]
if ch in string.printable and ch not in string.whitespace:
ascii_str += "%c" % (ch)
else:
ascii_str += "."
# Print ASCII representation and newline
outfile.write(ascii_str)
i = i + curr_data_len
outfile.write("\n")
def read_packet(f, verbose=False, trace_file=None):
"""Decode a JSON packet that starts with the content length and is
followed by the JSON bytes from a file 'f'. Returns None on EOF.
"""
line = f.readline().decode("utf-8")
if len(line) == 0:
return None # EOF.
# Watch for line that starts with the prefix
prefix = "Content-Length: "
if line.startswith(prefix):
# Decode length of JSON bytes
if verbose:
print('content: "%s"' % (line))
length = int(line[len(prefix) :])
if verbose:
print('length: "%u"' % (length))
# Skip empty line
line = f.readline()
if verbose:
print('empty: "%s"' % (line))
# Read JSON bytes
json_str = f.read(length)
if verbose:
print('json: "%s"' % (json_str))
if trace_file:
trace_file.write("from adapter:\n%s\n" % (json_str))
# Decode the JSON bytes into a python dictionary
return json.loads(json_str)
raise Exception("unexpected malformed message from lldb-dap: " + line)
def packet_type_is(packet, packet_type):
return "type" in packet and packet["type"] == packet_type
def dump_dap_log(log_file):
print("========= DEBUG ADAPTER PROTOCOL LOGS =========", file=sys.stderr)
if log_file is None:
print("no log file available", file=sys.stderr)
else:
with open(log_file, "r") as file:
print(file.read(), file=sys.stderr)
print("========= END =========", file=sys.stderr)
def read_packet_thread(vs_comm, log_file):
done = False
try:
while not done:
packet = read_packet(vs_comm.recv, trace_file=vs_comm.trace_file)
# `packet` will be `None` on EOF. We want to pass it down to
# handle_recv_packet anyway so the main thread can handle unexpected
# termination of lldb-dap and stop waiting for new packets.
done = not vs_comm.handle_recv_packet(packet)
finally:
# Wait for the process to fully exit before dumping the log file to
# ensure we have the entire log contents.
if vs_comm.process is not None:
try:
# Do not wait forever, some logs are better than none.
vs_comm.process.wait(timeout=20)
except subprocess.TimeoutExpired:
pass
dump_dap_log(log_file)
class DebugCommunication(object):
def __init__(self, recv, send, init_commands, log_file=None):
self.trace_file = None
self.send = send
self.recv = recv
self.recv_packets = []
self.recv_condition = threading.Condition()
self.recv_thread = threading.Thread(
target=read_packet_thread, args=(self, log_file)
)
self.process_event_body = None
self.exit_status = None
self.initialize_body = None
self.thread_stop_reasons = {}
self.breakpoint_events = []
self.progress_events = []
self.reverse_requests = []
self.sequence = 1
self.threads = None
self.recv_thread.start()
self.output_condition = threading.Condition()
self.output = {}
self.configuration_done_sent = False
self.frame_scopes = {}
self.init_commands = init_commands
self.disassembled_instructions = {}
@classmethod
def encode_content(cls, s):
return ("Content-Length: %u\r\n\r\n%s" % (len(s), s)).encode("utf-8")
@classmethod
def validate_response(cls, command, response):
if command["command"] != response["command"]:
raise ValueError("command mismatch in response")
if command["seq"] != response["request_seq"]:
raise ValueError("seq mismatch in response")
def get_modules(self):
module_list = self.request_modules()["body"]["modules"]
modules = {}
for module in module_list:
modules[module["name"]] = module
return modules
def get_output(self, category, timeout=0.0, clear=True):
self.output_condition.acquire()
output = None
if category in self.output:
output = self.output[category]
if clear:
del self.output[category]
elif timeout != 0.0:
self.output_condition.wait(timeout)
if category in self.output:
output = self.output[category]
if clear:
del self.output[category]
self.output_condition.release()
return output
def collect_output(self, category, timeout_secs, pattern, clear=True):
end_time = time.time() + timeout_secs
collected_output = ""
while end_time > time.time():
output = self.get_output(category, timeout=0.25, clear=clear)
if output:
collected_output += output
if pattern is not None and pattern in output:
break
return collected_output if collected_output else None
def enqueue_recv_packet(self, packet):
self.recv_condition.acquire()
self.recv_packets.append(packet)
self.recv_condition.notify()
self.recv_condition.release()
def handle_recv_packet(self, packet):
"""Called by the read thread that is waiting for all incoming packets
to store the incoming packet in "self.recv_packets" in a thread safe
way. This function will then signal the "self.recv_condition" to
indicate a new packet is available. Returns True if the caller
should keep calling this function for more packets.
"""
# If EOF, notify the read thread by enqueuing a None.
if not packet:
self.enqueue_recv_packet(None)
return False
# Check the packet to see if is an event packet
keepGoing = True
packet_type = packet["type"]
if packet_type == "event":
event = packet["event"]
body = None
if "body" in packet:
body = packet["body"]
# Handle the event packet and cache information from these packets
# as they come in
if event == "output":
# Store any output we receive so clients can retrieve it later.
category = body["category"]
output = body["output"]
self.output_condition.acquire()
if category in self.output:
self.output[category] += output
else:
self.output[category] = output
self.output_condition.notify()
self.output_condition.release()
# no need to add 'output' event packets to our packets list
return keepGoing
elif event == "process":
# When a new process is attached or launched, remember the
# details that are available in the body of the event
self.process_event_body = body
elif event == "stopped":
# Each thread that stops with a reason will send a
# 'stopped' event. We need to remember the thread stop
# reasons since the 'threads' command doesn't return
# that information.
self._process_stopped()
tid = body["threadId"]
self.thread_stop_reasons[tid] = body
elif event == "breakpoint":
# Breakpoint events come in when a breakpoint has locations
# added or removed. Keep track of them so we can look for them
# in tests.
self.breakpoint_events.append(packet)
# no need to add 'breakpoint' event packets to our packets list
return keepGoing
elif event.startswith("progress"):
# Progress events come in as 'progressStart', 'progressUpdate',
# and 'progressEnd' events. Keep these around in case test
# cases want to verify them.
self.progress_events.append(packet)
# No need to add 'progress' event packets to our packets list.
return keepGoing
elif packet_type == "response":
if packet["command"] == "disconnect":
keepGoing = False
self.enqueue_recv_packet(packet)
return keepGoing
def send_packet(self, command_dict, set_sequence=True):
"""Take the "command_dict" python dictionary and encode it as a JSON
string and send the contents as a packet to the VSCode debug
adapter"""
# Set the sequence ID for this command automatically
if set_sequence:
command_dict["seq"] = self.sequence
self.sequence += 1
# Encode our command dictionary as a JSON string
json_str = json.dumps(command_dict, separators=(",", ":"))
if self.trace_file:
self.trace_file.write("to adapter:\n%s\n" % (json_str))
length = len(json_str)
if length > 0:
# Send the encoded JSON packet and flush the 'send' file
self.send.write(self.encode_content(json_str))
self.send.flush()
def recv_packet(self, filter_type=None, filter_event=None, timeout=None):
"""Get a JSON packet from the VSCode debug adapter. This function
assumes a thread that reads packets is running and will deliver
any received packets by calling handle_recv_packet(...). This
function will wait for the packet to arrive and return it when
it does."""
while True:
try:
self.recv_condition.acquire()
packet = None
while True:
for i, curr_packet in enumerate(self.recv_packets):
if not curr_packet:
raise EOFError
packet_type = curr_packet["type"]
if filter_type is None or packet_type in filter_type:
if filter_event is None or (
packet_type == "event"
and curr_packet["event"] in filter_event
):
packet = self.recv_packets.pop(i)
break
if packet:
break
# Sleep until packet is received
len_before = len(self.recv_packets)
self.recv_condition.wait(timeout)
len_after = len(self.recv_packets)
if len_before == len_after:
return None # Timed out
return packet
except EOFError:
return None
finally:
self.recv_condition.release()
return None
def send_recv(self, command):
"""Send a command python dictionary as JSON and receive the JSON
response. Validates that the response is the correct sequence and
command in the reply. Any events that are received are added to the
events list in this object"""
self.send_packet(command)
done = False
while not done:
response_or_request = self.recv_packet(filter_type=["response", "request"])
if response_or_request is None:
desc = 'no response for "%s"' % (command["command"])
raise ValueError(desc)
if response_or_request["type"] == "response":
self.validate_response(command, response_or_request)
return response_or_request
else:
self.reverse_requests.append(response_or_request)
if response_or_request["command"] == "runInTerminal":
subprocess.Popen(
response_or_request["arguments"]["args"],
env=response_or_request["arguments"]["env"],
)
self.send_packet(
{
"type": "response",
"seq": 0,
"request_seq": response_or_request["seq"],
"success": True,
"command": "runInTerminal",
"body": {},
},
set_sequence=False,
)
elif response_or_request["command"] == "startDebugging":
self.send_packet(
{
"type": "response",
"seq": 0,
"request_seq": response_or_request["seq"],
"success": True,
"command": "startDebugging",
"body": {},
},
set_sequence=False,
)
else:
desc = 'unknown reverse request "%s"' % (
response_or_request["command"]
)
raise ValueError(desc)
return None
def wait_for_event(self, filter=None, timeout=None):
while True:
return self.recv_packet(
filter_type="event", filter_event=filter, timeout=timeout
)
return None
def wait_for_stopped(self, timeout=None):
stopped_events = []
stopped_event = self.wait_for_event(
filter=["stopped", "exited"], timeout=timeout
)
exited = False
while stopped_event:
stopped_events.append(stopped_event)
# If we exited, then we are done
if stopped_event["event"] == "exited":
self.exit_status = stopped_event["body"]["exitCode"]
exited = True
break
# Otherwise we stopped and there might be one or more 'stopped'
# events for each thread that stopped with a reason, so keep
# checking for more 'stopped' events and return all of them
stopped_event = self.wait_for_event(filter="stopped", timeout=0.25)
if exited:
self.threads = []
return stopped_events
def wait_for_exited(self):
event_dict = self.wait_for_event("exited")
if event_dict is None:
raise ValueError("didn't get exited event")
return event_dict
def wait_for_terminated(self):
event_dict = self.wait_for_event("terminated")
if event_dict is None:
raise ValueError("didn't get terminated event")
return event_dict
def get_initialize_value(self, key):
"""Get a value for the given key if it there is a key/value pair in
the "initialize" request response body.
"""
if self.initialize_body and key in self.initialize_body:
return self.initialize_body[key]
return None
def get_threads(self):
if self.threads is None:
self.request_threads()
return self.threads
def get_thread_id(self, threadIndex=0):
"""Utility function to get the first thread ID in the thread list.
If the thread list is empty, then fetch the threads.
"""
if self.threads is None:
self.request_threads()
if self.threads and threadIndex < len(self.threads):
return self.threads[threadIndex]["id"]
return None
def get_stackFrame(self, frameIndex=0, threadId=None):
"""Get a single "StackFrame" object from a "stackTrace" request and
return the "StackFrame" as a python dictionary, or None on failure
"""
if threadId is None:
threadId = self.get_thread_id()
if threadId is None:
print("invalid threadId")
return None
response = self.request_stackTrace(threadId, startFrame=frameIndex, levels=1)
if response:
return response["body"]["stackFrames"][0]
print("invalid response")
return None
def get_completions(self, text, frameId=None):
if frameId is None:
stackFrame = self.get_stackFrame()
frameId = stackFrame["id"]
response = self.request_completions(text, frameId)
return response["body"]["targets"]
def get_scope_variables(self, scope_name, frameIndex=0, threadId=None, is_hex=None):
stackFrame = self.get_stackFrame(frameIndex=frameIndex, threadId=threadId)
if stackFrame is None:
return []
frameId = stackFrame["id"]
if frameId in self.frame_scopes:
frame_scopes = self.frame_scopes[frameId]
else:
scopes_response = self.request_scopes(frameId)
frame_scopes = scopes_response["body"]["scopes"]
self.frame_scopes[frameId] = frame_scopes
for scope in frame_scopes:
if scope["name"] == scope_name:
varRef = scope["variablesReference"]
variables_response = self.request_variables(varRef, is_hex=is_hex)
if variables_response:
if "body" in variables_response:
body = variables_response["body"]
if "variables" in body:
vars = body["variables"]
return vars
return []
def get_global_variables(self, frameIndex=0, threadId=None):
return self.get_scope_variables(
"Globals", frameIndex=frameIndex, threadId=threadId
)
def get_local_variables(self, frameIndex=0, threadId=None, is_hex=None):
return self.get_scope_variables(
"Locals", frameIndex=frameIndex, threadId=threadId, is_hex=is_hex
)
def get_registers(self, frameIndex=0, threadId=None):
return self.get_scope_variables(
"Registers", frameIndex=frameIndex, threadId=threadId
)
def get_local_variable(self, name, frameIndex=0, threadId=None, is_hex=None):
locals = self.get_local_variables(
frameIndex=frameIndex, threadId=threadId, is_hex=is_hex
)
for local in locals:
if "name" in local and local["name"] == name:
return local
return None
def get_local_variable_value(self, name, frameIndex=0, threadId=None, is_hex=None):
variable = self.get_local_variable(
name, frameIndex=frameIndex, threadId=threadId, is_hex=is_hex
)
if variable and "value" in variable:
return variable["value"]
return None
def get_local_variable_child(
self, name, child_name, frameIndex=0, threadId=None, is_hex=None
):
local = self.get_local_variable(name, frameIndex, threadId)
if local["variablesReference"] == 0:
return None
children = self.request_variables(local["variablesReference"], is_hex=is_hex)[
"body"
]["variables"]
for child in children:
if child["name"] == child_name:
return child
return None
def replay_packets(self, replay_file_path):
f = open(replay_file_path, "r")
mode = "invalid"
set_sequence = False
command_dict = None
while mode != "eof":
if mode == "invalid":
line = f.readline()
if line.startswith("to adapter:"):
mode = "send"
elif line.startswith("from adapter:"):
mode = "recv"
elif mode == "send":
command_dict = read_packet(f)
# Skip the end of line that follows the JSON
f.readline()
if command_dict is None:
raise ValueError("decode packet failed from replay file")
print("Sending:")
pprint.PrettyPrinter(indent=2).pprint(command_dict)
# raw_input('Press ENTER to send:')
self.send_packet(command_dict, set_sequence)
mode = "invalid"
elif mode == "recv":
print("Replay response:")
replay_response = read_packet(f)
# Skip the end of line that follows the JSON
f.readline()
pprint.PrettyPrinter(indent=2).pprint(replay_response)
actual_response = self.recv_packet()
if actual_response:
type = actual_response["type"]
print("Actual response:")
if type == "response":
self.validate_response(command_dict, actual_response)
pprint.PrettyPrinter(indent=2).pprint(actual_response)
else:
print("error: didn't get a valid response")
mode = "invalid"
def request_attach(
self,
program=None,
pid=None,
waitFor=None,
trace=None,
initCommands=None,
preRunCommands=None,
stopCommands=None,
exitCommands=None,
attachCommands=None,
terminateCommands=None,
coreFile=None,
postRunCommands=None,
sourceMap=None,
gdbRemotePort=None,
gdbRemoteHostname=None,
):
args_dict = {}
if pid is not None:
args_dict["pid"] = pid
if program is not None:
args_dict["program"] = program
if waitFor is not None:
args_dict["waitFor"] = waitFor
if trace:
args_dict["trace"] = trace
args_dict["initCommands"] = self.init_commands
if initCommands:
args_dict["initCommands"].extend(initCommands)
if preRunCommands:
args_dict["preRunCommands"] = preRunCommands
if stopCommands:
args_dict["stopCommands"] = stopCommands
if exitCommands:
args_dict["exitCommands"] = exitCommands
if terminateCommands:
args_dict["terminateCommands"] = terminateCommands
if attachCommands:
args_dict["attachCommands"] = attachCommands
if coreFile:
args_dict["coreFile"] = coreFile
if postRunCommands:
args_dict["postRunCommands"] = postRunCommands
if sourceMap:
args_dict["sourceMap"] = sourceMap
if gdbRemotePort is not None:
args_dict["gdb-remote-port"] = gdbRemotePort
if gdbRemoteHostname is not None:
args_dict["gdb-remote-hostname"] = gdbRemoteHostname
command_dict = {"command": "attach", "type": "request", "arguments": args_dict}
return self.send_recv(command_dict)
def request_breakpointLocations(
self, file_path, line, end_line=None, column=None, end_column=None
):
(dir, base) = os.path.split(file_path)
source_dict = {"name": base, "path": file_path}
args_dict = {}
args_dict["source"] = source_dict
if line is not None:
args_dict["line"] = line
if end_line is not None:
args_dict["endLine"] = end_line
if column is not None:
args_dict["column"] = column
if end_column is not None:
args_dict["endColumn"] = end_column
command_dict = {
"command": "breakpointLocations",
"type": "request",
"arguments": args_dict,
}
return self.send_recv(command_dict)
def request_configurationDone(self):
command_dict = {
"command": "configurationDone",
"type": "request",
"arguments": {},
}
response = self.send_recv(command_dict)
if response:
self.configuration_done_sent = True
return response
def _process_stopped(self):
self.threads = None
self.frame_scopes = {}
def request_continue(self, threadId=None):
if self.exit_status is not None:
raise ValueError("request_continue called after process exited")
# If we have launched or attached, then the first continue is done by
# sending the 'configurationDone' request
if not self.configuration_done_sent:
return self.request_configurationDone()
args_dict = {}
if threadId is None:
threadId = self.get_thread_id()
args_dict["threadId"] = threadId
command_dict = {
"command": "continue",
"type": "request",
"arguments": args_dict,
}
response = self.send_recv(command_dict)
# Caller must still call wait_for_stopped.
return response
def request_restart(self, restartArguments=None):
command_dict = {
"command": "restart",
"type": "request",
}
if restartArguments:
command_dict["arguments"] = restartArguments
response = self.send_recv(command_dict)
# Caller must still call wait_for_stopped.
return response
def request_disconnect(self, terminateDebuggee=None):
args_dict = {}
if terminateDebuggee is not None:
if terminateDebuggee:
args_dict["terminateDebuggee"] = True
else:
args_dict["terminateDebuggee"] = False
command_dict = {
"command": "disconnect",
"type": "request",
"arguments": args_dict,
}
return self.send_recv(command_dict)
def request_disassemble(
self, memoryReference, offset=-50, instructionCount=200, resolveSymbols=True
):
args_dict = {
"memoryReference": memoryReference,
"offset": offset,
"instructionCount": instructionCount,
"resolveSymbols": resolveSymbols,
}
command_dict = {
"command": "disassemble",
"type": "request",
"arguments": args_dict,
}
instructions = self.send_recv(command_dict)["body"]["instructions"]
for inst in instructions:
self.disassembled_instructions[inst["address"]] = inst
def request_readMemory(self, memoryReference, offset, count):
args_dict = {
"memoryReference": memoryReference,
"offset": offset,
"count": count,
}
command_dict = {
"command": "readMemory",
"type": "request",
"arguments": args_dict,
}
return self.send_recv(command_dict)
def request_evaluate(self, expression, frameIndex=0, threadId=None, context=None):
stackFrame = self.get_stackFrame(frameIndex=frameIndex, threadId=threadId)
if stackFrame is None:
return []
args_dict = {
"expression": expression,
"context": context,
"frameId": stackFrame["id"],
}
command_dict = {
"command": "evaluate",
"type": "request",
"arguments": args_dict,
}
return self.send_recv(command_dict)
def request_exceptionInfo(self, threadId=None):
if threadId is None:
threadId = self.get_thread_id()
args_dict = {"threadId": threadId}
command_dict = {
"command": "exceptionInfo",
"type": "request",
"arguments": args_dict,
}
return self.send_recv(command_dict)
def request_initialize(self, sourceInitFile):
command_dict = {
"command": "initialize",
"type": "request",
"arguments": {
"adapterID": "lldb-native",
"clientID": "vscode",
"columnsStartAt1": True,
"linesStartAt1": True,
"locale": "en-us",
"pathFormat": "path",
"supportsRunInTerminalRequest": True,
"supportsVariablePaging": True,
"supportsVariableType": True,
"supportsStartDebuggingRequest": True,
"supportsProgressReporting": True,
"$__lldb_sourceInitFile": sourceInitFile,
},
}
response = self.send_recv(command_dict)
if response:
if "body" in response:
self.initialize_body = response["body"]
return response
def request_launch(
self,
program,
args=None,
cwd=None,
env=None,
stopOnEntry=False,
disableASLR=True,
disableSTDIO=False,
shellExpandArguments=False,
trace=False,
initCommands=None,
preRunCommands=None,
stopCommands=None,
exitCommands=None,
terminateCommands=None,
sourcePath=None,
debuggerRoot=None,
launchCommands=None,
sourceMap=None,
runInTerminal=False,
postRunCommands=None,
enableAutoVariableSummaries=False,
displayExtendedBacktrace=False,
enableSyntheticChildDebugging=False,
commandEscapePrefix=None,
customFrameFormat=None,
customThreadFormat=None,
):
args_dict = {"program": program}
if args:
args_dict["args"] = args
if cwd:
args_dict["cwd"] = cwd
if env:
args_dict["env"] = env
if stopOnEntry:
args_dict["stopOnEntry"] = stopOnEntry
if disableSTDIO:
args_dict["disableSTDIO"] = disableSTDIO
if shellExpandArguments:
args_dict["shellExpandArguments"] = shellExpandArguments
if trace:
args_dict["trace"] = trace
args_dict["initCommands"] = self.init_commands
if initCommands:
args_dict["initCommands"].extend(initCommands)
if preRunCommands:
args_dict["preRunCommands"] = preRunCommands
if stopCommands:
args_dict["stopCommands"] = stopCommands
if exitCommands:
args_dict["exitCommands"] = exitCommands
if terminateCommands:
args_dict["terminateCommands"] = terminateCommands
if sourcePath:
args_dict["sourcePath"] = sourcePath
if debuggerRoot:
args_dict["debuggerRoot"] = debuggerRoot
if launchCommands:
args_dict["launchCommands"] = launchCommands
if sourceMap:
args_dict["sourceMap"] = sourceMap
if runInTerminal:
args_dict["runInTerminal"] = runInTerminal
if postRunCommands:
args_dict["postRunCommands"] = postRunCommands
if customFrameFormat:
args_dict["customFrameFormat"] = customFrameFormat
if customThreadFormat:
args_dict["customThreadFormat"] = customThreadFormat
args_dict["disableASLR"] = disableASLR
args_dict["enableAutoVariableSummaries"] = enableAutoVariableSummaries
args_dict["enableSyntheticChildDebugging"] = enableSyntheticChildDebugging
args_dict["displayExtendedBacktrace"] = displayExtendedBacktrace
args_dict["commandEscapePrefix"] = commandEscapePrefix
command_dict = {"command": "launch", "type": "request", "arguments": args_dict}
response = self.send_recv(command_dict)
if response["success"]:
# Wait for a 'process' and 'initialized' event in any order
self.wait_for_event(filter=["process", "initialized"])
self.wait_for_event(filter=["process", "initialized"])
return response
def request_next(self, threadId, granularity="statement"):
if self.exit_status is not None:
raise ValueError("request_continue called after process exited")
args_dict = {"threadId": threadId, "granularity": granularity}
command_dict = {"command": "next", "type": "request", "arguments": args_dict}
return self.send_recv(command_dict)
def request_stepIn(self, threadId, targetId, granularity="statement"):
if self.exit_status is not None:
raise ValueError("request_stepIn called after process exited")
if threadId is None:
threadId = self.get_thread_id()
args_dict = {
"threadId": threadId,
"targetId": targetId,
"granularity": granularity,
}
command_dict = {"command": "stepIn", "type": "request", "arguments": args_dict}
return self.send_recv(command_dict)
def request_stepInTargets(self, frameId):
if self.exit_status is not None:
raise ValueError("request_stepInTargets called after process exited")
args_dict = {"frameId": frameId}
command_dict = {
"command": "stepInTargets",
"type": "request",
"arguments": args_dict,
}
return self.send_recv(command_dict)
def request_stepOut(self, threadId):
if self.exit_status is not None:
raise ValueError("request_stepOut called after process exited")
args_dict = {"threadId": threadId}
command_dict = {"command": "stepOut", "type": "request", "arguments": args_dict}
return self.send_recv(command_dict)
def request_pause(self, threadId=None):
if self.exit_status is not None:
raise ValueError("request_pause called after process exited")
if threadId is None:
threadId = self.get_thread_id()
args_dict = {"threadId": threadId}
command_dict = {"command": "pause", "type": "request", "arguments": args_dict}
return self.send_recv(command_dict)
def request_scopes(self, frameId):
args_dict = {"frameId": frameId}
command_dict = {"command": "scopes", "type": "request", "arguments": args_dict}
return self.send_recv(command_dict)
def request_setBreakpoints(self, file_path, line_array, data=None):
"""data is array of parameters for breakpoints in line_array.
Each parameter object is 1:1 mapping with entries in line_entry.
It contains optional location/hitCondition/logMessage parameters.
"""
(dir, base) = os.path.split(file_path)
source_dict = {"name": base, "path": file_path}
args_dict = {
"source": source_dict,
"sourceModified": False,
}
if line_array is not None:
args_dict["lines"] = line_array
breakpoints = []
for i, line in enumerate(line_array):
breakpoint_data = None
if data is not None and i < len(data):
breakpoint_data = data[i]
bp = {"line": line}
if breakpoint_data is not None:
if breakpoint_data.get("condition"):
bp["condition"] = breakpoint_data["condition"]
if breakpoint_data.get("hitCondition"):
bp["hitCondition"] = breakpoint_data["hitCondition"]
if breakpoint_data.get("logMessage"):
bp["logMessage"] = breakpoint_data["logMessage"]
if breakpoint_data.get("column"):
bp["column"] = breakpoint_data["column"]
breakpoints.append(bp)
args_dict["breakpoints"] = breakpoints
command_dict = {
"command": "setBreakpoints",
"type": "request",
"arguments": args_dict,
}
return self.send_recv(command_dict)
def request_setExceptionBreakpoints(self, filters):
args_dict = {"filters": filters}
command_dict = {
"command": "setExceptionBreakpoints",
"type": "request",
"arguments": args_dict,
}
return self.send_recv(command_dict)
def request_setFunctionBreakpoints(self, names, condition=None, hitCondition=None):
breakpoints = []
for name in names:
bp = {"name": name}
if condition is not None:
bp["condition"] = condition
if hitCondition is not None:
bp["hitCondition"] = hitCondition
breakpoints.append(bp)
args_dict = {"breakpoints": breakpoints}
command_dict = {
"command": "setFunctionBreakpoints",
"type": "request",
"arguments": args_dict,
}
return self.send_recv(command_dict)
def request_dataBreakpointInfo(
self, variablesReference, name, frameIndex=0, threadId=None
):
stackFrame = self.get_stackFrame(frameIndex=frameIndex, threadId=threadId)
if stackFrame is None:
return []
args_dict = {
"variablesReference": variablesReference,
"name": name,
"frameId": stackFrame["id"],