1#!/usr/bin/env python
2
3import binascii
4import json
5import optparse
6import os
7import pprint
8import socket
9import string
10import subprocess
11import sys
12import threading
13
14
15def dump_memory(base_addr, data, num_per_line, outfile):
16
17    data_len = len(data)
18    hex_string = binascii.hexlify(data)
19    addr = base_addr
20    ascii_str = ''
21    i = 0
22    while i < data_len:
23        outfile.write('0x%8.8x: ' % (addr + i))
24        bytes_left = data_len - i
25        if bytes_left >= num_per_line:
26            curr_data_len = num_per_line
27        else:
28            curr_data_len = bytes_left
29        hex_start_idx = i * 2
30        hex_end_idx = hex_start_idx + curr_data_len * 2
31        curr_hex_str = hex_string[hex_start_idx:hex_end_idx]
32        # 'curr_hex_str' now contains the hex byte string for the
33        # current line with no spaces between bytes
34        t = iter(curr_hex_str)
35        # Print hex bytes separated by space
36        outfile.write(' '.join(a + b for a, b in zip(t, t)))
37        # Print two spaces
38        outfile.write('  ')
39        # Calculate ASCII string for bytes into 'ascii_str'
40        ascii_str = ''
41        for j in range(i, i + curr_data_len):
42            ch = data[j]
43            if ch in string.printable and ch not in string.whitespace:
44                ascii_str += '%c' % (ch)
45            else:
46                ascii_str += '.'
47        # Print ASCII representation and newline
48        outfile.write(ascii_str)
49        i = i + curr_data_len
50        outfile.write('\n')
51
52
53def read_packet(f, verbose=False, trace_file=None):
54    '''Decode a JSON packet that starts with the content length and is
55       followed by the JSON bytes from a file 'f'. Returns None on EOF.
56    '''
57    line = f.readline().decode("utf-8")
58    if len(line) == 0:
59        return None  # EOF.
60
61    # Watch for line that starts with the prefix
62    prefix = 'Content-Length: '
63    if line.startswith(prefix):
64        # Decode length of JSON bytes
65        if verbose:
66            print('content: "%s"' % (line))
67        length = int(line[len(prefix):])
68        if verbose:
69            print('length: "%u"' % (length))
70        # Skip empty line
71        line = f.readline()
72        if verbose:
73            print('empty: "%s"' % (line))
74        # Read JSON bytes
75        json_str = f.read(length)
76        if verbose:
77            print('json: "%s"' % (json_str))
78        if trace_file:
79            trace_file.write('from adaptor:\n%s\n' % (json_str))
80        # Decode the JSON bytes into a python dictionary
81        return json.loads(json_str)
82
83    return None
84
85
86def packet_type_is(packet, packet_type):
87    return 'type' in packet and packet['type'] == packet_type
88
89
90def read_packet_thread(vs_comm):
91    done = False
92    while not done:
93        packet = read_packet(vs_comm.recv, trace_file=vs_comm.trace_file)
94        # `packet` will be `None` on EOF. We want to pass it down to
95        # handle_recv_packet anyway so the main thread can handle unexpected
96        # termination of lldb-vscode and stop waiting for new packets.
97        done = not vs_comm.handle_recv_packet(packet)
98
99
100class DebugCommunication(object):
101
102    def __init__(self, recv, send, init_commands):
103        self.trace_file = None
104        self.send = send
105        self.recv = recv
106        self.recv_packets = []
107        self.recv_condition = threading.Condition()
108        self.recv_thread = threading.Thread(target=read_packet_thread,
109                                            args=(self,))
110        self.process_event_body = None
111        self.exit_status = None
112        self.initialize_body = None
113        self.thread_stop_reasons = {}
114        self.breakpoint_events = []
115        self.sequence = 1
116        self.threads = None
117        self.recv_thread.start()
118        self.output_condition = threading.Condition()
119        self.output = {}
120        self.configuration_done_sent = False
121        self.frame_scopes = {}
122        self.init_commands = init_commands
123
124    @classmethod
125    def encode_content(cls, s):
126        return ("Content-Length: %u\r\n\r\n%s" % (len(s), s)).encode("utf-8")
127
128    @classmethod
129    def validate_response(cls, command, response):
130        if command['command'] != response['command']:
131            raise ValueError('command mismatch in response')
132        if command['seq'] != response['request_seq']:
133            raise ValueError('seq mismatch in response')
134
135    def get_output(self, category, timeout=0.0, clear=True):
136        self.output_condition.acquire()
137        output = None
138        if category in self.output:
139            output = self.output[category]
140            if clear:
141                del self.output[category]
142        elif timeout != 0.0:
143            self.output_condition.wait(timeout)
144            if category in self.output:
145                output = self.output[category]
146                if clear:
147                    del self.output[category]
148        self.output_condition.release()
149        return output
150
151    def enqueue_recv_packet(self, packet):
152        self.recv_condition.acquire()
153        self.recv_packets.append(packet)
154        self.recv_condition.notify()
155        self.recv_condition.release()
156
157    def handle_recv_packet(self, packet):
158        '''Called by the read thread that is waiting for all incoming packets
159           to store the incoming packet in "self.recv_packets" in a thread safe
160           way. This function will then signal the "self.recv_condition" to
161           indicate a new packet is available. Returns True if the caller
162           should keep calling this function for more packets.
163        '''
164        # If EOF, notify the read thread by enqueuing a None.
165        if not packet:
166            self.enqueue_recv_packet(None)
167            return False
168
169        # Check the packet to see if is an event packet
170        keepGoing = True
171        packet_type = packet['type']
172        if packet_type == 'event':
173            event = packet['event']
174            body = None
175            if 'body' in packet:
176                body = packet['body']
177            # Handle the event packet and cache information from these packets
178            # as they come in
179            if event == 'output':
180                # Store any output we receive so clients can retrieve it later.
181                category = body['category']
182                output = body['output']
183                self.output_condition.acquire()
184                if category in self.output:
185                    self.output[category] += output
186                else:
187                    self.output[category] = output
188                self.output_condition.notify()
189                self.output_condition.release()
190                # no need to add 'output' event packets to our packets list
191                return keepGoing
192            elif event == 'process':
193                # When a new process is attached or launched, remember the
194                # details that are available in the body of the event
195                self.process_event_body = body
196            elif event == 'stopped':
197                # Each thread that stops with a reason will send a
198                # 'stopped' event. We need to remember the thread stop
199                # reasons since the 'threads' command doesn't return
200                # that information.
201                self._process_stopped()
202                tid = body['threadId']
203                self.thread_stop_reasons[tid] = body
204            elif event == 'breakpoint':
205                # Breakpoint events come in when a breakpoint has locations
206                # added or removed. Keep track of them so we can look for them
207                # in tests.
208                self.breakpoint_events.append(packet)
209                # no need to add 'breakpoint' event packets to our packets list
210                return keepGoing
211        elif packet_type == 'response':
212            if packet['command'] == 'disconnect':
213                keepGoing = False
214        self.enqueue_recv_packet(packet)
215        return keepGoing
216
217    def send_packet(self, command_dict, set_sequence=True):
218        '''Take the "command_dict" python dictionary and encode it as a JSON
219           string and send the contents as a packet to the VSCode debug
220           adaptor'''
221        # Set the sequence ID for this command automatically
222        if set_sequence:
223            command_dict['seq'] = self.sequence
224            self.sequence += 1
225        # Encode our command dictionary as a JSON string
226        json_str = json.dumps(command_dict, separators=(',', ':'))
227        if self.trace_file:
228            self.trace_file.write('to adaptor:\n%s\n' % (json_str))
229        length = len(json_str)
230        if length > 0:
231            # Send the encoded JSON packet and flush the 'send' file
232            self.send.write(self.encode_content(json_str))
233            self.send.flush()
234
235    def recv_packet(self, filter_type=None, filter_event=None, timeout=None):
236        '''Get a JSON packet from the VSCode debug adaptor. This function
237           assumes a thread that reads packets is running and will deliver
238           any received packets by calling handle_recv_packet(...). This
239           function will wait for the packet to arrive and return it when
240           it does.'''
241        while True:
242            try:
243                self.recv_condition.acquire()
244                packet = None
245                while True:
246                    for (i, curr_packet) in enumerate(self.recv_packets):
247                        if not curr_packet:
248                            raise EOFError
249                        packet_type = curr_packet['type']
250                        if filter_type is None or packet_type in filter_type:
251                            if (filter_event is None or
252                                (packet_type == 'event' and
253                                 curr_packet['event'] in filter_event)):
254                                packet = self.recv_packets.pop(i)
255                                break
256                    if packet:
257                        break
258                    # Sleep until packet is received
259                    len_before = len(self.recv_packets)
260                    self.recv_condition.wait(timeout)
261                    len_after = len(self.recv_packets)
262                    if len_before == len_after:
263                        return None  # Timed out
264                return packet
265            except EOFError:
266                return None
267            finally:
268                self.recv_condition.release()
269
270        return None
271
272    def send_recv(self, command):
273        '''Send a command python dictionary as JSON and receive the JSON
274           response. Validates that the response is the correct sequence and
275           command in the reply. Any events that are received are added to the
276           events list in this object'''
277        self.send_packet(command)
278        done = False
279        while not done:
280            response = self.recv_packet(filter_type='response')
281            if response is None:
282                desc = 'no response for "%s"' % (command['command'])
283                raise ValueError(desc)
284            self.validate_response(command, response)
285            return response
286        return None
287
288    def wait_for_event(self, filter=None, timeout=None):
289        while True:
290            return self.recv_packet(filter_type='event', filter_event=filter,
291                                    timeout=timeout)
292        return None
293
294    def wait_for_stopped(self, timeout=None):
295        stopped_events = []
296        stopped_event = self.wait_for_event(filter=['stopped', 'exited'],
297                                            timeout=timeout)
298        exited = False
299        while stopped_event:
300            stopped_events.append(stopped_event)
301            # If we exited, then we are done
302            if stopped_event['event'] == 'exited':
303                self.exit_status = stopped_event['body']['exitCode']
304                exited = True
305                break
306            # Otherwise we stopped and there might be one or more 'stopped'
307            # events for each thread that stopped with a reason, so keep
308            # checking for more 'stopped' events and return all of them
309            stopped_event = self.wait_for_event(filter='stopped', timeout=0.25)
310        if exited:
311            self.threads = []
312        return stopped_events
313
314    def wait_for_exited(self):
315        event_dict = self.wait_for_event('exited')
316        if event_dict is None:
317            raise ValueError("didn't get stopped event")
318        return event_dict
319
320    def get_initialize_value(self, key):
321        '''Get a value for the given key if it there is a key/value pair in
322           the "initialize" request response body.
323        '''
324        if self.initialize_body and key in self.initialize_body:
325            return self.initialize_body[key]
326        return None
327
328    def get_threads(self):
329        if self.threads is None:
330            self.request_threads()
331        return self.threads
332
333    def get_thread_id(self, threadIndex=0):
334        '''Utility function to get the first thread ID in the thread list.
335           If the thread list is empty, then fetch the threads.
336        '''
337        if self.threads is None:
338            self.request_threads()
339        if self.threads and threadIndex < len(self.threads):
340            return self.threads[threadIndex]['id']
341        return None
342
343    def get_stackFrame(self, frameIndex=0, threadId=None):
344        '''Get a single "StackFrame" object from a "stackTrace" request and
345           return the "StackFrame as a python dictionary, or None on failure
346        '''
347        if threadId is None:
348            threadId = self.get_thread_id()
349        if threadId is None:
350            print('invalid threadId')
351            return None
352        response = self.request_stackTrace(threadId, startFrame=frameIndex,
353                                           levels=1)
354        if response:
355            return response['body']['stackFrames'][0]
356        print('invalid response')
357        return None
358
359    def get_completions(self, text):
360        response = self.request_completions(text)
361        return response['body']['targets']
362
363    def get_scope_variables(self, scope_name, frameIndex=0, threadId=None):
364        stackFrame = self.get_stackFrame(frameIndex=frameIndex,
365                                         threadId=threadId)
366        if stackFrame is None:
367            return []
368        frameId = stackFrame['id']
369        if frameId in self.frame_scopes:
370            frame_scopes = self.frame_scopes[frameId]
371        else:
372            scopes_response = self.request_scopes(frameId)
373            frame_scopes = scopes_response['body']['scopes']
374            self.frame_scopes[frameId] = frame_scopes
375        for scope in frame_scopes:
376            if scope['name'] == scope_name:
377                varRef = scope['variablesReference']
378                variables_response = self.request_variables(varRef)
379                if variables_response:
380                    if 'body' in variables_response:
381                        body = variables_response['body']
382                        if 'variables' in body:
383                            vars = body['variables']
384                            return vars
385        return []
386
387    def get_global_variables(self, frameIndex=0, threadId=None):
388        return self.get_scope_variables('Globals', frameIndex=frameIndex,
389                                        threadId=threadId)
390
391    def get_local_variables(self, frameIndex=0, threadId=None):
392        return self.get_scope_variables('Locals', frameIndex=frameIndex,
393                                        threadId=threadId)
394
395    def get_local_variable(self, name, frameIndex=0, threadId=None):
396        locals = self.get_local_variables(frameIndex=frameIndex,
397                                          threadId=threadId)
398        for local in locals:
399            if 'name' in local and local['name'] == name:
400                return local
401        return None
402
403    def get_local_variable_value(self, name, frameIndex=0, threadId=None):
404        variable = self.get_local_variable(name, frameIndex=frameIndex,
405                                           threadId=threadId)
406        if variable and 'value' in variable:
407            return variable['value']
408        return None
409
410    def replay_packets(self, replay_file_path):
411        f = open(replay_file_path, 'r')
412        mode = 'invalid'
413        set_sequence = False
414        command_dict = None
415        while mode != 'eof':
416            if mode == 'invalid':
417                line = f.readline()
418                if line.startswith('to adapter:'):
419                    mode = 'send'
420                elif line.startswith('from adapter:'):
421                    mode = 'recv'
422            elif mode == 'send':
423                command_dict = read_packet(f)
424                # Skip the end of line that follows the JSON
425                f.readline()
426                if command_dict is None:
427                    raise ValueError('decode packet failed from replay file')
428                print('Sending:')
429                pprint.PrettyPrinter(indent=2).pprint(command_dict)
430                # raw_input('Press ENTER to send:')
431                self.send_packet(command_dict, set_sequence)
432                mode = 'invalid'
433            elif mode == 'recv':
434                print('Replay response:')
435                replay_response = read_packet(f)
436                # Skip the end of line that follows the JSON
437                f.readline()
438                pprint.PrettyPrinter(indent=2).pprint(replay_response)
439                actual_response = self.recv_packet()
440                if actual_response:
441                    type = actual_response['type']
442                    print('Actual response:')
443                    if type == 'response':
444                        self.validate_response(command_dict, actual_response)
445                    pprint.PrettyPrinter(indent=2).pprint(actual_response)
446                else:
447                    print("error: didn't get a valid response")
448                mode = 'invalid'
449
450    def request_attach(self, program=None, pid=None, waitFor=None, trace=None,
451                       initCommands=None, preRunCommands=None,
452                       stopCommands=None, exitCommands=None,
453                       attachCommands=None, coreFile=None):
454        args_dict = {}
455        if pid is not None:
456            args_dict['pid'] = pid
457        if program is not None:
458            args_dict['program'] = program
459        if waitFor is not None:
460            args_dict['waitFor'] = waitFor
461        if trace:
462            args_dict['trace'] = trace
463        args_dict['initCommands'] = self.init_commands
464        if initCommands:
465            args_dict['initCommands'].extend(initCommands)
466        if preRunCommands:
467            args_dict['preRunCommands'] = preRunCommands
468        if stopCommands:
469            args_dict['stopCommands'] = stopCommands
470        if exitCommands:
471            args_dict['exitCommands'] = exitCommands
472        if attachCommands:
473            args_dict['attachCommands'] = attachCommands
474        if coreFile:
475            args_dict['coreFile'] = coreFile
476        command_dict = {
477            'command': 'attach',
478            'type': 'request',
479            'arguments': args_dict
480        }
481        return self.send_recv(command_dict)
482
483    def request_configurationDone(self):
484        command_dict = {
485            'command': 'configurationDone',
486            'type': 'request',
487            'arguments': {}
488        }
489        response = self.send_recv(command_dict)
490        if response:
491            self.configuration_done_sent = True
492        return response
493
494    def _process_stopped(self):
495        self.threads = None
496        self.frame_scopes = {}
497
498    def request_continue(self, threadId=None):
499        if self.exit_status is not None:
500            raise ValueError('request_continue called after process exited')
501        # If we have launched or attached, then the first continue is done by
502        # sending the 'configurationDone' request
503        if not self.configuration_done_sent:
504            return self.request_configurationDone()
505        args_dict = {}
506        if threadId is None:
507            threadId = self.get_thread_id()
508        args_dict['threadId'] = threadId
509        command_dict = {
510            'command': 'continue',
511            'type': 'request',
512            'arguments': args_dict
513        }
514        response = self.send_recv(command_dict)
515        # Caller must still call wait_for_stopped.
516        return response
517
518    def request_disconnect(self, terminateDebuggee=None):
519        args_dict = {}
520        if terminateDebuggee is not None:
521            if terminateDebuggee:
522                args_dict['terminateDebuggee'] = True
523            else:
524                args_dict['terminateDebuggee'] = False
525        command_dict = {
526            'command': 'disconnect',
527            'type': 'request',
528            'arguments': args_dict
529        }
530        return self.send_recv(command_dict)
531
532    def request_evaluate(self, expression, frameIndex=0, threadId=None):
533        stackFrame = self.get_stackFrame(frameIndex=frameIndex,
534                                         threadId=threadId)
535        if stackFrame is None:
536            return []
537        args_dict = {
538            'expression': expression,
539            'frameId': stackFrame['id'],
540        }
541        command_dict = {
542            'command': 'evaluate',
543            'type': 'request',
544            'arguments': args_dict
545        }
546        return self.send_recv(command_dict)
547
548    def request_initialize(self):
549        command_dict = {
550            'command': 'initialize',
551            'type': 'request',
552            'arguments': {
553                'adapterID': 'lldb-native',
554                'clientID': 'vscode',
555                'columnsStartAt1': True,
556                'linesStartAt1': True,
557                'locale': 'en-us',
558                'pathFormat': 'path',
559                'supportsRunInTerminalRequest': True,
560                'supportsVariablePaging': True,
561                'supportsVariableType': True
562            }
563        }
564        response = self.send_recv(command_dict)
565        if response:
566            if 'body' in response:
567                self.initialize_body = response['body']
568        return response
569
570    def request_launch(self, program, args=None, cwd=None, env=None,
571                       stopOnEntry=False, disableASLR=True,
572                       disableSTDIO=False, shellExpandArguments=False,
573                       trace=False, initCommands=None, preRunCommands=None,
574                       stopCommands=None, exitCommands=None, sourcePath=None,
575                       debuggerRoot=None, launchCommands=None, sourceMap=None):
576        args_dict = {
577            'program': program
578        }
579        if args:
580            args_dict['args'] = args
581        if cwd:
582            args_dict['cwd'] = cwd
583        if env:
584            args_dict['env'] = env
585        if stopOnEntry:
586            args_dict['stopOnEntry'] = stopOnEntry
587        if disableASLR:
588            args_dict['disableASLR'] = disableASLR
589        if disableSTDIO:
590            args_dict['disableSTDIO'] = disableSTDIO
591        if shellExpandArguments:
592            args_dict['shellExpandArguments'] = shellExpandArguments
593        if trace:
594            args_dict['trace'] = trace
595        args_dict['initCommands'] = self.init_commands
596        if initCommands:
597            args_dict['initCommands'].extend(initCommands)
598        if preRunCommands:
599            args_dict['preRunCommands'] = preRunCommands
600        if stopCommands:
601            args_dict['stopCommands'] = stopCommands
602        if exitCommands:
603            args_dict['exitCommands'] = exitCommands
604        if sourcePath:
605            args_dict['sourcePath'] = sourcePath
606        if debuggerRoot:
607            args_dict['debuggerRoot'] = debuggerRoot
608        if launchCommands:
609            args_dict['launchCommands'] = launchCommands
610        if sourceMap:
611            args_dict['sourceMap'] = sourceMap
612        command_dict = {
613            'command': 'launch',
614            'type': 'request',
615            'arguments': args_dict
616        }
617        response = self.send_recv(command_dict)
618
619        # Wait for a 'process' and 'initialized' event in any order
620        self.wait_for_event(filter=['process', 'initialized'])
621        self.wait_for_event(filter=['process', 'initialized'])
622        return response
623
624    def request_next(self, threadId):
625        if self.exit_status is not None:
626            raise ValueError('request_continue called after process exited')
627        args_dict = {'threadId': threadId}
628        command_dict = {
629            'command': 'next',
630            'type': 'request',
631            'arguments': args_dict
632        }
633        return self.send_recv(command_dict)
634
635    def request_stepIn(self, threadId):
636        if self.exit_status is not None:
637            raise ValueError('request_continue called after process exited')
638        args_dict = {'threadId': threadId}
639        command_dict = {
640            'command': 'stepIn',
641            'type': 'request',
642            'arguments': args_dict
643        }
644        return self.send_recv(command_dict)
645
646    def request_stepOut(self, threadId):
647        if self.exit_status is not None:
648            raise ValueError('request_continue called after process exited')
649        args_dict = {'threadId': threadId}
650        command_dict = {
651            'command': 'stepOut',
652            'type': 'request',
653            'arguments': args_dict
654        }
655        return self.send_recv(command_dict)
656
657    def request_pause(self, threadId=None):
658        if self.exit_status is not None:
659            raise ValueError('request_continue called after process exited')
660        if threadId is None:
661            threadId = self.get_thread_id()
662        args_dict = {'threadId': threadId}
663        command_dict = {
664            'command': 'pause',
665            'type': 'request',
666            'arguments': args_dict
667        }
668        return self.send_recv(command_dict)
669
670    def request_scopes(self, frameId):
671        args_dict = {'frameId': frameId}
672        command_dict = {
673            'command': 'scopes',
674            'type': 'request',
675            'arguments': args_dict
676        }
677        return self.send_recv(command_dict)
678
679    def request_setBreakpoints(self, file_path, line_array, condition=None,
680                               hitCondition=None):
681        (dir, base) = os.path.split(file_path)
682        breakpoints = []
683        for line in line_array:
684            bp = {'line': line}
685            if condition is not None:
686                bp['condition'] = condition
687            if hitCondition is not None:
688                bp['hitCondition'] = hitCondition
689            breakpoints.append(bp)
690        source_dict = {
691            'name': base,
692            'path': file_path
693        }
694        args_dict = {
695            'source': source_dict,
696            'breakpoints': breakpoints,
697            'lines': '%s' % (line_array),
698            'sourceModified': False,
699        }
700        command_dict = {
701            'command': 'setBreakpoints',
702            'type': 'request',
703            'arguments': args_dict
704        }
705        return self.send_recv(command_dict)
706
707    def request_setExceptionBreakpoints(self, filters):
708        args_dict = {'filters': filters}
709        command_dict = {
710            'command': 'setExceptionBreakpoints',
711            'type': 'request',
712            'arguments': args_dict
713        }
714        return self.send_recv(command_dict)
715
716    def request_setFunctionBreakpoints(self, names, condition=None,
717                                       hitCondition=None):
718        breakpoints = []
719        for name in names:
720            bp = {'name': name}
721            if condition is not None:
722                bp['condition'] = condition
723            if hitCondition is not None:
724                bp['hitCondition'] = hitCondition
725            breakpoints.append(bp)
726        args_dict = {'breakpoints': breakpoints}
727        command_dict = {
728            'command': 'setFunctionBreakpoints',
729            'type': 'request',
730            'arguments': args_dict
731        }
732        return self.send_recv(command_dict)
733
734    def request_completions(self, text):
735        args_dict = {
736            'text': text,
737            'column': len(text)
738        }
739        command_dict = {
740            'command': 'completions',
741            'type': 'request',
742            'arguments': args_dict
743        }
744        return self.send_recv(command_dict)
745
746    def request_stackTrace(self, threadId=None, startFrame=None, levels=None,
747                           dump=False):
748        if threadId is None:
749            threadId = self.get_thread_id()
750        args_dict = {'threadId': threadId}
751        if startFrame is not None:
752            args_dict['startFrame'] = startFrame
753        if levels is not None:
754            args_dict['levels'] = levels
755        command_dict = {
756            'command': 'stackTrace',
757            'type': 'request',
758            'arguments': args_dict
759        }
760        response = self.send_recv(command_dict)
761        if dump:
762            for (idx, frame) in enumerate(response['body']['stackFrames']):
763                name = frame['name']
764                if 'line' in frame and 'source' in frame:
765                    source = frame['source']
766                    if 'sourceReference' not in source:
767                        if 'name' in source:
768                            source_name = source['name']
769                            line = frame['line']
770                            print("[%3u] %s @ %s:%u" % (idx, name, source_name,
771                                                        line))
772                            continue
773                print("[%3u] %s" % (idx, name))
774        return response
775
776    def request_threads(self):
777        '''Request a list of all threads and combine any information from any
778           "stopped" events since those contain more information about why a
779           thread actually stopped. Returns an array of thread dictionaries
780           with information about all threads'''
781        command_dict = {
782            'command': 'threads',
783            'type': 'request',
784            'arguments': {}
785        }
786        response = self.send_recv(command_dict)
787        body = response['body']
788        # Fill in "self.threads" correctly so that clients that call
789        # self.get_threads() or self.get_thread_id(...) can get information
790        # on threads when the process is stopped.
791        if 'threads' in body:
792            self.threads = body['threads']
793            for thread in self.threads:
794                # Copy the thread dictionary so we can add key/value pairs to
795                # it without affecting the original info from the "threads"
796                # command.
797                tid = thread['id']
798                if tid in self.thread_stop_reasons:
799                    thread_stop_info = self.thread_stop_reasons[tid]
800                    copy_keys = ['reason', 'description', 'text']
801                    for key in copy_keys:
802                        if key in thread_stop_info:
803                            thread[key] = thread_stop_info[key]
804        else:
805            self.threads = None
806        return response
807
808    def request_variables(self, variablesReference, start=None, count=None):
809        args_dict = {'variablesReference': variablesReference}
810        if start is not None:
811            args_dict['start'] = start
812        if count is not None:
813            args_dict['count'] = count
814        command_dict = {
815            'command': 'variables',
816            'type': 'request',
817            'arguments': args_dict
818        }
819        return self.send_recv(command_dict)
820
821    def request_setVariable(self, containingVarRef, name, value, id=None):
822        args_dict = {
823            'variablesReference': containingVarRef,
824            'name': name,
825            'value': str(value)
826        }
827        if id is not None:
828            args_dict['id'] = id
829        command_dict = {
830            'command': 'setVariable',
831            'type': 'request',
832            'arguments': args_dict
833        }
834        return self.send_recv(command_dict)
835
836    def request_testGetTargetBreakpoints(self):
837        '''A request packet used in the LLDB test suite to get all currently
838           set breakpoint infos for all breakpoints currently set in the
839           target.
840        '''
841        command_dict = {
842            'command': '_testGetTargetBreakpoints',
843            'type': 'request',
844            'arguments': {}
845        }
846        return self.send_recv(command_dict)
847
848    def terminate(self):
849        self.send.close()
850        # self.recv.close()
851
852
853class DebugAdaptor(DebugCommunication):
854    def __init__(self, executable=None, port=None, init_commands=[], log_file=None):
855        self.process = None
856        if executable is not None:
857            adaptor_env = os.environ.copy()
858            if log_file:
859                adaptor_env['LLDBVSCODE_LOG'] = log_file
860            self.process = subprocess.Popen([executable],
861                                            stdin=subprocess.PIPE,
862                                            stdout=subprocess.PIPE,
863                                            stderr=subprocess.PIPE,
864                                            env=adaptor_env)
865            DebugCommunication.__init__(self, self.process.stdout,
866                                        self.process.stdin, init_commands)
867        elif port is not None:
868            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
869            s.connect(('127.0.0.1', port))
870            DebugCommunication.__init__(self, s.makefile('r'), s.makefile('w'),
871                init_commands)
872
873    def get_pid(self):
874        if self.process:
875            return self.process.pid
876        return -1
877
878    def terminate(self):
879        super(DebugAdaptor, self).terminate()
880        if self.process is not None:
881            self.process.terminate()
882            self.process.wait()
883            self.process = None
884
885
886def attach_options_specified(options):
887    if options.pid is not None:
888        return True
889    if options.waitFor:
890        return True
891    if options.attach:
892        return True
893    if options.attachCmds:
894        return True
895    return False
896
897
898def run_vscode(dbg, args, options):
899    dbg.request_initialize()
900    if attach_options_specified(options):
901        response = dbg.request_attach(program=options.program,
902                                      pid=options.pid,
903                                      waitFor=options.waitFor,
904                                      attachCommands=options.attachCmds,
905                                      initCommands=options.initCmds,
906                                      preRunCommands=options.preRunCmds,
907                                      stopCommands=options.stopCmds,
908                                      exitCommands=options.exitCmds)
909    else:
910        response = dbg.request_launch(options.program,
911                                      args=args,
912                                      env=options.envs,
913                                      cwd=options.workingDir,
914                                      debuggerRoot=options.debuggerRoot,
915                                      sourcePath=options.sourcePath,
916                                      initCommands=options.initCmds,
917                                      preRunCommands=options.preRunCmds,
918                                      stopCommands=options.stopCmds,
919                                      exitCommands=options.exitCmds)
920
921    if response['success']:
922        if options.sourceBreakpoints:
923            source_to_lines = {}
924            for file_line in options.sourceBreakpoints:
925                (path, line) = file_line.split(':')
926                if len(path) == 0 or len(line) == 0:
927                    print('error: invalid source with line "%s"' %
928                          (file_line))
929
930                else:
931                    if path in source_to_lines:
932                        source_to_lines[path].append(int(line))
933                    else:
934                        source_to_lines[path] = [int(line)]
935            for source in source_to_lines:
936                dbg.request_setBreakpoints(source, source_to_lines[source])
937        if options.funcBreakpoints:
938            dbg.request_setFunctionBreakpoints(options.funcBreakpoints)
939        dbg.request_configurationDone()
940        dbg.wait_for_stopped()
941    else:
942        if 'message' in response:
943            print(response['message'])
944    dbg.request_disconnect(terminateDebuggee=True)
945
946
947def main():
948    parser = optparse.OptionParser(
949        description=('A testing framework for the Visual Studio Code Debug '
950                     'Adaptor protocol'))
951
952    parser.add_option(
953        '--vscode',
954        type='string',
955        dest='vscode_path',
956        help=('The path to the command line program that implements the '
957              'Visual Studio Code Debug Adaptor protocol.'),
958        default=None)
959
960    parser.add_option(
961        '--program',
962        type='string',
963        dest='program',
964        help='The path to the program to debug.',
965        default=None)
966
967    parser.add_option(
968        '--workingDir',
969        type='string',
970        dest='workingDir',
971        default=None,
972        help='Set the working directory for the process we launch.')
973
974    parser.add_option(
975        '--sourcePath',
976        type='string',
977        dest='sourcePath',
978        default=None,
979        help=('Set the relative source root for any debug info that has '
980              'relative paths in it.'))
981
982    parser.add_option(
983        '--debuggerRoot',
984        type='string',
985        dest='debuggerRoot',
986        default=None,
987        help=('Set the working directory for lldb-vscode for any object files '
988              'with relative paths in the Mach-o debug map.'))
989
990    parser.add_option(
991        '-r', '--replay',
992        type='string',
993        dest='replay',
994        help=('Specify a file containing a packet log to replay with the '
995              'current Visual Studio Code Debug Adaptor executable.'),
996        default=None)
997
998    parser.add_option(
999        '-g', '--debug',
1000        action='store_true',
1001        dest='debug',
1002        default=False,
1003        help='Pause waiting for a debugger to attach to the debug adaptor')
1004
1005    parser.add_option(
1006        '--port',
1007        type='int',
1008        dest='port',
1009        help="Attach a socket to a port instead of using STDIN for VSCode",
1010        default=None)
1011
1012    parser.add_option(
1013        '--pid',
1014        type='int',
1015        dest='pid',
1016        help="The process ID to attach to",
1017        default=None)
1018
1019    parser.add_option(
1020        '--attach',
1021        action='store_true',
1022        dest='attach',
1023        default=False,
1024        help=('Specify this option to attach to a process by name. The '
1025              'process name is the basename of the executable specified with '
1026              'the --program option.'))
1027
1028    parser.add_option(
1029        '-f', '--function-bp',
1030        type='string',
1031        action='append',
1032        dest='funcBreakpoints',
1033        help=('Specify the name of a function to break at. '
1034              'Can be specified more than once.'),
1035        default=[])
1036
1037    parser.add_option(
1038        '-s', '--source-bp',
1039        type='string',
1040        action='append',
1041        dest='sourceBreakpoints',
1042        default=[],
1043        help=('Specify source breakpoints to set in the format of '
1044              '<source>:<line>. '
1045              'Can be specified more than once.'))
1046
1047    parser.add_option(
1048        '--attachCommand',
1049        type='string',
1050        action='append',
1051        dest='attachCmds',
1052        default=[],
1053        help=('Specify a LLDB command that will attach to a process. '
1054              'Can be specified more than once.'))
1055
1056    parser.add_option(
1057        '--initCommand',
1058        type='string',
1059        action='append',
1060        dest='initCmds',
1061        default=[],
1062        help=('Specify a LLDB command that will be executed before the target '
1063              'is created. Can be specified more than once.'))
1064
1065    parser.add_option(
1066        '--preRunCommand',
1067        type='string',
1068        action='append',
1069        dest='preRunCmds',
1070        default=[],
1071        help=('Specify a LLDB command that will be executed after the target '
1072              'has been created. Can be specified more than once.'))
1073
1074    parser.add_option(
1075        '--stopCommand',
1076        type='string',
1077        action='append',
1078        dest='stopCmds',
1079        default=[],
1080        help=('Specify a LLDB command that will be executed each time the'
1081              'process stops. Can be specified more than once.'))
1082
1083    parser.add_option(
1084        '--exitCommand',
1085        type='string',
1086        action='append',
1087        dest='exitCmds',
1088        default=[],
1089        help=('Specify a LLDB command that will be executed when the process '
1090              'exits. Can be specified more than once.'))
1091
1092    parser.add_option(
1093        '--env',
1094        type='string',
1095        action='append',
1096        dest='envs',
1097        default=[],
1098        help=('Specify environment variables to pass to the launched '
1099              'process.'))
1100
1101    parser.add_option(
1102        '--waitFor',
1103        action='store_true',
1104        dest='waitFor',
1105        default=False,
1106        help=('Wait for the next process to be launched whose name matches '
1107              'the basename of the program specified with the --program '
1108              'option'))
1109
1110    (options, args) = parser.parse_args(sys.argv[1:])
1111
1112    if options.vscode_path is None and options.port is None:
1113        print('error: must either specify a path to a Visual Studio Code '
1114              'Debug Adaptor vscode executable path using the --vscode '
1115              'option, or a port to attach to for an existing lldb-vscode '
1116              'using the --port option')
1117        return
1118    dbg = DebugAdaptor(executable=options.vscode_path, port=options.port)
1119    if options.debug:
1120        raw_input('Waiting for debugger to attach pid "%i"' % (
1121                  dbg.get_pid()))
1122    if options.replay:
1123        dbg.replay_packets(options.replay)
1124    else:
1125        run_vscode(dbg, args, options)
1126    dbg.terminate()
1127
1128
1129if __name__ == '__main__':
1130    main()
1131