1#!/usr/bin/env python3 2# ===----------------------------------------------------------------------===## 3# 4# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 5# See https://llvm.org/LICENSE.txt for license information. 6# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 7# 8# ===----------------------------------------------------------------------===## 9 10"""qemu_baremetal.py is a utility for running a program with QEMU's system mode. 11 12It is able to pass command line arguments to the program and forward input and 13output (if the underlying baremetal enviroment supports QEMU semihosting). 14""" 15 16import argparse 17import os 18import sys 19import shutil 20 21 22def main(): 23 parser = argparse.ArgumentParser() 24 parser.add_argument("--qemu", type=str, required=True) 25 parser.add_argument("--cpu", type=str, required=False) 26 parser.add_argument("--machine", type=str, default="virt") 27 parser.add_argument( 28 "--qemu-arg", dest="qemu_args", type=str, action="append", default=[] 29 ) 30 parser.add_argument("--semihosting", action="store_true", default=True) 31 parser.add_argument("--no-semihosting", dest="semihosting", action="store_false") 32 parser.add_argument("--execdir", type=str, required=True) 33 parser.add_argument("test_binary") 34 parser.add_argument("test_args", nargs=argparse.ZERO_OR_MORE, default=[]) 35 args = parser.parse_args() 36 37 if not shutil.which(args.qemu): 38 sys.exit(f"Failed to find QEMU binary from --qemu value: '{args.qemu}'") 39 40 if not os.path.exists(args.test_binary): 41 sys.exit(f"Expected argument to be a test executable: '{args.test_binary}'") 42 43 qemu_commandline = [ 44 args.qemu, 45 "-chardev", 46 "stdio,mux=on,id=stdio0", 47 "-monitor", 48 "none", 49 "-serial", 50 "none", 51 "-machine", 52 f"{args.machine},accel=tcg", 53 "-device", 54 f"loader,file={args.test_binary},cpu-num=0", 55 "-nographic", 56 *args.qemu_args, 57 ] 58 if args.cpu: 59 qemu_commandline += ["-cpu", args.cpu] 60 61 if args.semihosting: 62 # Use QEMU's semihosting support to pass argv (supported by picolibc) 63 semihosting_config = f"enable=on,chardev=stdio0,arg={args.test_binary}" 64 for arg in args.test_args: 65 semihosting_config += f",arg={arg}" 66 qemu_commandline += ["-semihosting-config", semihosting_config] 67 elif args.test_args: 68 sys.exit( 69 "Got non-empty test arguments but do no know how to pass them to " 70 "QEMU without semihosting support" 71 ) 72 os.execvp(qemu_commandline[0], qemu_commandline) 73 74 75if __name__ == "__main__": 76 exit(main()) 77