GDB (xrefs)
Loading...
Searching...
No Matches
io.py
Go to the documentation of this file.
1# Copyright 2022-2023 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
16import json
17
18from .startup import start_thread, send_gdb, log
19
20
21def 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 continue
35 log("IGNORED: <<<%s>>>" % line)
36 data = bytes()
37 while len(data) < content_length:
38 new_data = stream.read(content_length - len(data))
39 data += new_data
40 result = json.loads(data)
41 return result
42
43
44def start_json_writer(stream, queue):
45 """Start the JSON writer thread.
46 It will read objects from QUEUE and write them to STREAM,
47 following the JSON-RPC protocol."""
48
49 def _json_writer():
50 seq = 1
51 while True:
52 obj = queue.get()
53 if obj is None:
54 # This is an exit request. The stream is already
55 # flushed, so all that's left to do is request an
56 # exit.
57 send_gdb("quit")
58 break
59 obj["seq"] = seq
60 seq = seq + 1
61 encoded = json.dumps(obj)
62 body_bytes = encoded.encode("utf-8")
63 header = "Content-Length: " + str(len(body_bytes)) + "\r\n\r\n"
64 header_bytes = header.encode("ASCII")
65 stream.write(header_bytes)
66 stream.write(body_bytes)
67 stream.flush()
68
69 start_thread("JSON writer", _json_writer)