]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gdb/python/lib/gdb/dap/io.py
Initial implementation of Debugger Adapter Protocol
[thirdparty/binutils-gdb.git] / gdb / python / lib / gdb / dap / io.py
1 # Copyright 2022 Free Software Foundation, Inc.
2
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation; either version 3 of the License, or
6 # (at your option) any later version.
7 #
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
12 #
13 # You should have received a copy of the GNU General Public License
14 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15
16 import json
17
18 from .startup import start_thread, send_gdb
19
20
21 def read_json(stream):
22 """Read a JSON-RPC message from STREAM.
23 The decoded object is returned."""
24 # First read and parse the header.
25 content_length = None
26 while True:
27 line = stream.readline()
28 line = line.strip()
29 if line == b"":
30 break
31 if line.startswith(b"Content-Length:"):
32 line = line[15:].strip()
33 content_length = int(line)
34 data = bytes()
35 while len(data) < content_length:
36 new_data = stream.read(content_length - len(data))
37 data += new_data
38 result = json.loads(data)
39 return result
40
41
42 def start_json_writer(stream, queue):
43 """Start the JSON writer thread.
44 It will read objects from QUEUE and write them to STREAM,
45 following the JSON-RPC protocol."""
46
47 def _json_writer():
48 seq = 1
49 while True:
50 obj = queue.get()
51 if obj is None:
52 # This is an exit request. The stream is already
53 # flushed, so all that's left to do is request an
54 # exit.
55 send_gdb("quit")
56 break
57 obj["seq"] = seq
58 seq = seq + 1
59 encoded = json.dumps(obj)
60 body_bytes = encoded.encode("utf-8")
61 header = f"Content-Length: {len(body_bytes)}\r\n\r\n"
62 header_bytes = header.encode("ASCII")
63 stream.write(header_bytes)
64 stream.write(body_bytes)
65 stream.flush()
66
67 start_thread("JSON writer", _json_writer)