aboutsummaryrefslogtreecommitdiff
path: root/pw_emu/py/pw_emu/__main__.py
blob: 253edd931c573b9c85e9730abc7fbdd3f6c9641d (plain)
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
# Copyright 2023 The Pigweed Authors
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
"""Command line interface for the Pigweed emulators frontend"""

import argparse
import json
import os
from pathlib import Path
import signal
import subprocess
import sys
import threading

from typing import Any

from pw_emu.core import Error
from pw_emu.frontend import Emulator
from serial import serial_for_url, SerialException
from serial.tools.miniterm import Miniterm, key_description

_TERM_CMD = ['python', '-m', 'serial', '--raw']


def _cmd_gdb_cmds(emu, args: argparse.Namespace) -> None:
    """Run gdb commands in batch mode."""

    emu.run_gdb_cmds(args.gdb_cmd, executable=args.executable, pause=args.pause)


def _cmd_load(emu: Emulator, args: argparse.Namespace) -> None:
    """Load an executable image via gdb start executing it if pause is
    not set"""

    args.gdb_cmd = ['load']
    _cmd_gdb_cmds(emu, args)


def _cmd_start(emu: Emulator, args: argparse.Namespace) -> None:
    """Launch the emulator and start executing, unless pause is set."""

    if args.runner:
        emu.set_emu(args.runner)

    emu.start(
        target=args.target,
        file=args.file,
        pause=args.pause,
        args=args.args,
        debug=args.debug,
        foreground=args.foreground,
    )


def _get_miniterm(emu: Emulator, chan: str) -> Miniterm:
    chan_type = emu.get_channel_type(chan)
    if chan_type == 'tcp':
        host, port = emu.get_channel_addr(chan)
        url = f'socket://[{host}]:{port}'
    elif chan_type == 'pty':
        url = emu.get_channel_path(chan)
    else:
        raise Error(f'unknown channel type `{chan_type}`')
    ser = serial_for_url(url)
    ser.timeout = 1
    miniterm = Miniterm(ser)
    miniterm.raw = True
    miniterm.set_tx_encoding('UTF-8')
    miniterm.set_rx_encoding('UTF-8')

    quit_key = key_description(miniterm.exit_character)
    menu_key = key_description(miniterm.menu_character)
    help_key = key_description('\x08')
    help_desc = f'Help: {menu_key} followed by {help_key} ---'

    print(f'--- Miniterm on {chan} ---')
    print(f'--- Quit: {quit_key} | Menu: {menu_key} | {help_desc}')

    # On POSIX systems miniterm uses TIOCSTI to "cancel" the TX thread
    # (reading from the console, sending to the serial) which is
    # disabled on Linux kernels > 6.2 see
    # https://github.com/pyserial/pyserial/issues/243
    #
    # On Windows the cancel method does not seem to work either with
    # recent win10 versions.
    #
    # Workaround by terminating the process for exceptions in the read
    # and write threads.
    threading.excepthook = lambda args: signal.raise_signal(signal.SIGTERM)

    return miniterm


def _cmd_run(emu: Emulator, args: argparse.Namespace) -> None:
    """Start the emulator and connect the terminal to a channel. Stop
    the emulator when exiting the terminal"""

    emu.start(
        target=args.target,
        file=args.file,
        pause=True,
        args=args.args,
    )

    ctrl_chans = ['gdb', 'monitor', 'qmp', 'robot']
    if not args.channel:
        for chan in emu.get_channels():
            if chan not in ctrl_chans:
                args.channel = chan
                break
    if not args.channel:
        raise Error(f'only control channels {ctrl_chans} found')

    try:
        miniterm = _get_miniterm(emu, args.channel)
        emu.cont()
        miniterm.start()
        miniterm.join(True)
        print('--- exit ---')
        miniterm.stop()
        miniterm.join()
        miniterm.close()
    except SerialException as err:
        raise Error(f'error connecting to channel `{args.channel}`: {err}')
    finally:
        emu.stop()


def _cmd_restart(emu: Emulator, args: argparse.Namespace) -> None:
    """Restart the emulator and start executing, unless pause is set."""

    if emu.running():
        emu.stop()
    _cmd_start(emu, args)


def _cmd_stop(emu: Emulator, _args: argparse.Namespace) -> None:
    """Stop the emulator"""

    emu.stop()


def _cmd_reset(emu: Emulator, _args: argparse.Namespace) -> None:
    """Perform a software reset."""

    emu.reset()


def _cmd_gdb(emu: Emulator, args: argparse.Namespace) -> None:
    """Start a gdb interactive session"""

    executable = args.executable if args.executable else ""

    signal.signal(signal.SIGINT, signal.SIG_IGN)
    try:
        cmd = emu.get_gdb_cmd() + [
            '-ex',
            f'target remote {emu.get_gdb_remote()}',
            executable,
        ]
        subprocess.run(cmd)
    finally:
        signal.signal(signal.SIGINT, signal.SIG_DFL)


def _cmd_prop_ls(emu: Emulator, args: argparse.Namespace) -> None:
    """List emulator object properties."""

    props = emu.list_properties(args.path)
    print(json.dumps(props, indent=4))


def _cmd_prop_get(emu: Emulator, args: argparse.Namespace) -> None:
    """Show the emulator's object properties."""

    print(emu.get_property(args.path, args.property))


def _cmd_prop_set(emu: Emulator, args: argparse.Namespace) -> None:
    """Set emulator's object properties."""

    emu.set_property(args.path, args.property, args.value)


def _cmd_term(emu: Emulator, args: argparse.Namespace) -> None:
    """Connect with an interactive terminal to an emulator channel"""

    try:
        miniterm = _get_miniterm(emu, args.channel)
        miniterm.start()
        miniterm.join(True)
        print('--- exit ---')
        miniterm.stop()
        miniterm.join()
        miniterm.close()
    except SerialException as err:
        raise Error(f'error connecting to channel `{args.channel}`: {err}')


def _cmd_resume(emu: Emulator, _args: argparse.Namespace) -> None:
    """Resume the execution of a paused emulator."""

    emu.cont()


def get_parser() -> argparse.ArgumentParser:
    """Command line parser"""

    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    parser.add_argument(
        '-i',
        '--instance',
        help='instance to use (default: %(default)s)',
        type=str,
        metavar='STRING',
        default='default',
    )
    parser.add_argument(
        '-C',
        '--working-dir',
        help='path to working directory (default: %(default)s)',
        type=Path,
        default=os.getenv('PW_EMU_WDIR'),
    )
    parser.add_argument(
        '-c',
        '--config',
        help='path config file (default: %(default)s)',
        type=str,
        default=None,
    )

    subparsers = parser.add_subparsers(dest='command', required=True)

    def add_cmd(name: str, func: Any) -> argparse.ArgumentParser:
        subparser = subparsers.add_parser(
            name, description=func.__doc__, help=func.__doc__
        )
        subparser.set_defaults(func=func)
        return subparser

    start = add_cmd('start', _cmd_start)
    restart = add_cmd('restart', _cmd_restart)

    for subparser in [start, restart]:
        subparser.add_argument(
            'target',
            type=str,
        )
        subparser.add_argument(
            '--file',
            '-f',
            metavar='FILE',
            help='file to load before starting',
        )
        subparser.add_argument(
            '--runner',
            '-r',
            help='emulator to use, automatically detected if not set',
            choices=[None, 'qemu', 'renode'],
            default=None,
        )
        subparser.add_argument(
            '--args',
            '-a',
            help='options to pass to the emulator',
        )
        subparser.add_argument(
            '--pause',
            '-p',
            action='store_true',
            help='pause the emulator after starting it',
        )
        subparser.add_argument(
            '--debug',
            '-d',
            action='store_true',
            help='start the emulator in debug mode',
        )
        subparser.add_argument(
            '--foreground',
            '-F',
            action='store_true',
            help='start the emulator in foreground mode',
        )

    run = add_cmd('run', _cmd_run)
    run.add_argument(
        'target',
        type=str,
    )
    run.add_argument(
        'file',
        metavar='FILE',
        help='file to load before starting',
    )
    run.add_argument(
        '--args',
        '-a',
        help='options to pass to the emulator',
    )
    run.add_argument(
        '--channel',
        '-n',
        help='channel to connect the terminal to',
    )

    stop = add_cmd('stop', _cmd_stop)

    load = add_cmd('load', _cmd_load)
    load.add_argument(
        'executable',
        metavar='FILE',
        help='file to load via gdb',
    )
    load.add_argument(
        '--pause',
        '-p',
        help='pause the emulator after loading the file',
        action='store_true',
    )
    load.add_argument(
        '--offset',
        '-o',
        metavar='ADDRESS',
        help='address to load the file at',
    )

    reset = add_cmd('reset', _cmd_reset)

    gdb = add_cmd('gdb', _cmd_gdb)
    gdb.add_argument(
        '--executable',
        '-e',
        metavar='FILE',
        help='file to use for the debugging session',
    )

    prop_ls = add_cmd('prop-ls', _cmd_prop_ls)
    prop_ls.add_argument(
        'path',
        help='path of the emulator object',
    )

    prop_get = add_cmd('prop-get', _cmd_prop_get)
    prop_get.add_argument(
        'path',
        help='path of the emulator object',
    )
    prop_get.add_argument(
        'property',
        help='name of the object property',
    )

    prop_set = add_cmd('prop-set', _cmd_prop_set)
    prop_set.add_argument(
        'path',
        help='path of the emulator object',
    )
    prop_set.add_argument(
        'property',
        help='name of the object property',
    )
    prop_set.add_argument(
        'value',
        help='value to set for the object property',
    )

    gdb_cmds = add_cmd('gdb-cmds', _cmd_gdb_cmds)
    gdb_cmds.add_argument(
        '--pause',
        '-p',
        help='do not resume execution after running the commands',
        action='store_true',
    )
    gdb_cmds.add_argument(
        '--executable',
        '-e',
        metavar='FILE',
        help='executable to use while running the gdb commands',
    )
    gdb_cmds.add_argument(
        'gdb_cmd',
        nargs='+',
        help='gdb command to execute',
    )

    term = add_cmd('term', _cmd_term)
    term.add_argument(
        'channel',
        help='channel name',
    )

    resume = add_cmd('resume', _cmd_resume)

    parser.epilog = f"""commands usage:
        {start.format_usage().strip()}
        {restart.format_usage().strip()}
        {stop.format_usage().strip()}
        {run.format_usage().strip()}
        {load.format_usage().strip()}
        {reset.format_usage().strip()}
        {gdb.format_usage().strip()}
        {prop_ls.format_usage().strip()}
        {prop_get.format_usage().strip()}
        {prop_set.format_usage().strip()}
        {gdb_cmds.format_usage().strip()}
        {term.format_usage().strip()}
        {resume.format_usage().strip()}
    """

    return parser


def main() -> int:
    """Emulators frontend command line interface."""

    args = get_parser().parse_args()
    if not args.working_dir:
        args.working_dir = (
            f'{os.getenv("PW_PROJECT_ROOT")}/.pw_emu/{args.instance}'
        )

    try:
        emu = Emulator(args.working_dir, args.config)
        args.func(emu, args)
    except Error as err:
        print(err)
        return 1

    return 0


if __name__ == '__main__':
    sys.exit(main())