run 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  1. #!/usr/bin/env python3
  2. import os
  3. import re
  4. import shutil
  5. import subprocess
  6. import sys
  7. import time
  8. import common
  9. from shell_helpers import LF
  10. class Main(common.LkmcCliFunction):
  11. def __init__(self):
  12. super().__init__(
  13. description='''\
  14. Run some content on an emulator.
  15. '''
  16. )
  17. self.add_argument(
  18. '-c',
  19. '--cpus',
  20. default=1,
  21. type=int,
  22. help='Number of guest CPUs to emulate. Default: %(default)s'
  23. )
  24. self.add_argument(
  25. '--ctrl-c-host',
  26. default=False,
  27. help='''\
  28. Ctrl +C kills the QEMU simulator instead of being passed to the guest.
  29. '''
  30. )
  31. self.add_argument(
  32. '-D',
  33. '--debug-vm',
  34. default=False,
  35. help='''\
  36. Run GDB on the emulator itself.
  37. For --emulator native, this debugs the target program.
  38. '''
  39. )
  40. self.add_argument(
  41. '--debug-vm-args',
  42. default='',
  43. help='Pass arguments to GDB. Implies --debug-vm.'
  44. )
  45. self.add_argument(
  46. '--dtb',
  47. help='''\
  48. Use the specified DTB file. If not given, let the emulator generate a DTB for us,
  49. which is what you usually want.
  50. '''
  51. )
  52. self.add_argument(
  53. '-E',
  54. '--eval',
  55. help='''\
  56. Replace the normal init with a minimal init that just evals the given sh string.
  57. See: https://github.com/cirosantilli/linux-kernel-module-cheat#replace-init
  58. chdir into lkmc_home before running the command:
  59. https://github.com/cirosantilli/linux-kernel-module-cheat#lkmc_home
  60. '''
  61. )
  62. self.add_argument(
  63. '-F',
  64. '--eval-after',
  65. help='''\
  66. Similar to --eval, but the string gets evaled at the last init script,
  67. after the normal init finished.
  68. See: https://github.com/cirosantilli/linux-kernel-module-cheat#init-busybox
  69. '''
  70. )
  71. self.add_argument(
  72. '-G',
  73. '--gem5-exe-args',
  74. default='',
  75. help='''\
  76. Pass extra options to the gem5 executable.
  77. Do not confuse with the arguments passed to config scripts,
  78. like `fs.py`. Example:
  79. ./run --emulator gem5 --gem5-exe-args '--debug-flags=Exec --debug' -- --cpu-type=HPI --caches
  80. will run:
  81. gem.op5 --debug-flags=Exec fs.py --cpu-type=HPI --caches
  82. '''
  83. )
  84. self.add_argument(
  85. '--gdb',
  86. default=False,
  87. help='''\
  88. Shortcut for the most common GDB options that you want most of the time. Implies:
  89. * --gdb-wait
  90. * --tmux-args <main> where <main> is:
  91. ** start_kernel in full system
  92. ** main in user mode
  93. * --tmux-program gdb
  94. '''
  95. )
  96. self.add_argument(
  97. '--gdb-wait',
  98. default=False,
  99. help='''\
  100. Wait for GDB to connect before starting execution
  101. See: https://github.com/cirosantilli/linux-kernel-module-cheat#gdb
  102. '''
  103. )
  104. self.add_argument(
  105. '--gem5-script',
  106. default='fs',
  107. choices=['fs', 'biglittle'],
  108. help='Which gem5 script to use'
  109. )
  110. self.add_argument(
  111. '--gem5-readfile',
  112. default='',
  113. help='Set the contents of m5 readfile to this string.'
  114. )
  115. self.add_argument(
  116. '--gem5-restore',
  117. type=int,
  118. help='''\
  119. Restore the nth most recently taken gem5 checkpoint according to directory
  120. timestamps.
  121. '''
  122. )
  123. self.add_argument(
  124. '--graphic',
  125. default=False,
  126. help='''\
  127. Run in graphic mode.
  128. See: http://github.com/cirosantilli/linux-kernel-module-cheat#graphics
  129. '''
  130. )
  131. self.add_argument(
  132. '--kdb',
  133. default=False,
  134. help='''\
  135. Setup KDB kernel CLI options.
  136. See: http://github.com/cirosantilli/linux-kernel-module-cheat#kdb
  137. '''
  138. )
  139. self.add_argument(
  140. '--kernel-cli',
  141. help='''\
  142. Pass an extra Linux kernel command line options, and place them before
  143. the dash separator `-`. Only options that come before the `-`, i.e.
  144. "standard" options, should be passed with this option.
  145. Example: `./run --arch arm --kernel-cli 'init=/lkmc/poweroff.out'`
  146. '''
  147. )
  148. self.add_argument(
  149. '--kernel-cli-after-dash',
  150. help='''\
  151. Pass an extra Linux kernel command line options, add a dash `-`
  152. separator, and place the options after the dash. Intended for custom
  153. options understood by our `init` scripts, most of which are prefixed
  154. by `lkmc_`.
  155. Example: `./run --kernel-cli-after-dash 'lkmc_eval="wget google.com" lkmc_lala=y'`
  156. '''
  157. )
  158. self.add_argument(
  159. '--kernel-version',
  160. default=common.consts['linux_kernel_version'],
  161. help='''\
  162. Pass a base64 encoded command line parameter that gets evalled at the end of
  163. the normal init.
  164. See: https://github.com/cirosantilli/linux-kernel-module-cheat#init-busybox
  165. chdir into lkmc_home before running the command:
  166. https://github.com/cirosantilli/linux-kernel-module-cheat#lkmc_home
  167. Specify the Linux kernel version to be reported by syscall emulation.
  168. Defaults to the same kernel version as our default Buildroot build.
  169. Currently only works for QEMU.
  170. See: http://github.com/cirosantilli/linux-kernel-module-cheat#fatal-kernel-too-old
  171. '''
  172. )
  173. self.add_argument(
  174. '--kgdb',
  175. default=False,
  176. help='''\
  177. Setup KGDB kernel CLI options.
  178. See: http://github.com/cirosantilli/linux-kernel-module-cheat#kgdb
  179. '''
  180. )
  181. self.add_argument(
  182. '-K',
  183. '--kvm',
  184. default=False,
  185. help='''\
  186. Use KVM. Only works if guest arch == host arch.
  187. See: http://github.com/cirosantilli/linux-kernel-module-cheat#kvm
  188. '''
  189. )
  190. self.add_argument(
  191. '-m',
  192. '--memory',
  193. default='256M',
  194. help='''\
  195. Set the memory size of the guest. E.g.: `-m 512M`. We try to keep the default
  196. at the minimal ammount amount that boots all archs. Anything lower could lead
  197. some arch to fail to boot.
  198. Default: %(default)s
  199. '''
  200. )
  201. self.add_argument(
  202. '--quit-after-boot',
  203. default=False,
  204. help='''\
  205. Setup a kernel init parameter that makes the emulator quit immediately after boot.
  206. '''
  207. )
  208. self.add_argument(
  209. '-R',
  210. '--replay',
  211. default=False,
  212. help='Replay a QEMU run record deterministically'
  213. )
  214. self.add_argument(
  215. '-r',
  216. '--record',
  217. default=False,
  218. help='Record a QEMU run record for later replay with `-R`'
  219. )
  220. self.add_argument(
  221. '--show-stdout',
  222. default=True,
  223. help='''Show emulator stdout and stderr on the host terminal.'''
  224. )
  225. self.add_argument(
  226. '--terminal',
  227. default=False,
  228. help='''\
  229. Output directly to the terminal, don't pipe to tee as the default.
  230. With this, we don't not save the output to a file as is done by default,
  231. but we are able to do things that require not having a pipe such as
  232. using debuggers. This option is set automatically by --debug-vm, but you
  233. still need it to debug gem5 Python scripts with pdb.
  234. '''
  235. )
  236. self.add_argument(
  237. '-T',
  238. '--trace',
  239. help='''\
  240. Set trace events to be enabled. If not given, gem5 tracing is completely
  241. disabled, while QEMU tracing is enabled but uses default traces that are very
  242. rare and don't affect performance, because `./configure
  243. --enable-trace-backends=simple` seems to enable some traces by default, e.g.
  244. `pr_manager_run`, and I don't know how to get rid of them.
  245. See: http://github.com/cirosantilli/linux-kernel-module-cheat#tracing
  246. '''
  247. )
  248. self.add_argument(
  249. '--trace-stdout',
  250. default=False,
  251. help='''\
  252. Output trace to stdout instead of a file. Only works for gem5 currently.
  253. '''
  254. )
  255. self.add_argument(
  256. '--trace-insts-stdout',
  257. default=False,
  258. help='''\
  259. Trace instructions run to stdout. Shortcut for --trace --trace-stdout.
  260. '''
  261. )
  262. self.add_argument(
  263. '-t',
  264. '--tmux',
  265. default=False,
  266. help='''\
  267. Create a tmux split the window. You must already be inside of a `tmux` session
  268. to use this option:
  269. * on the main window, run the emulator as usual
  270. * on the split:
  271. ** if on QEMU and `-d` is given, GDB
  272. ** if on gem5, the gem5 terminal
  273. See: https://github.com/cirosantilli/linux-kernel-module-cheat#tmux
  274. '''
  275. )
  276. self.add_argument(
  277. '--tmux-args',
  278. help='''\
  279. Parameters to pass to the program running on the tmux split. Implies --tmux.
  280. '''
  281. )
  282. self.add_argument(
  283. '--tmux-program',
  284. choices=('gdb', 'shell'),
  285. help='''\
  286. Which program to run in tmux. Implies --tmux. Defaults:
  287. * 'gdb' in qemu
  288. * 'shell' in gem5. 'shell' is only supported in gem5 currently.
  289. '''
  290. )
  291. self.add_argument(
  292. '--vnc',
  293. default=False,
  294. help='''\
  295. Run QEMU with VNC instead of the default SDL. Connect to it with:
  296. `vinagre localhost:5900`.
  297. '''
  298. )
  299. self.add_argument(
  300. 'extra_emulator_args',
  301. nargs='*',
  302. default=[],
  303. help='''\
  304. Extra options to append at the end of the emulator command line.
  305. '''
  306. )
  307. def timed_main(self):
  308. show_stdout = self.env['show_stdout']
  309. # Common qemu / gem5 logic.
  310. # nokaslr:
  311. # * https://unix.stackexchange.com/questions/397939/turning-off-kaslr-to-debug-linux-kernel-using-qemu-and-gdb
  312. # * https://stackoverflow.com/questions/44612822/unable-to-debug-kernel-with-qemu-gdb/49840927#49840927
  313. # Turned on by default since v4.12
  314. kernel_cli = 'console_msg_format=syslog nokaslr norandmaps panic=-1 printk.devkmsg=on printk.time=y rw'
  315. if self.env['kernel_cli'] is not None:
  316. kernel_cli += ' {}'.format(self.env['kernel_cli'])
  317. if self.env['quit_after_boot']:
  318. kernel_cli += ' {}'.format(self.env['quit_init'])
  319. kernel_cli_after_dash = ' lkmc_home={}'.format(self.env['guest_lkmc_home'])
  320. extra_emulator_args = []
  321. extra_qemu_args = []
  322. if not self.env['_args_given']['tmux_program']:
  323. if self.env['emulator'] == 'qemu':
  324. self.env['tmux_program'] = 'gdb'
  325. elif self.env['emulator'] == 'gem5':
  326. self.env['tmux_program'] = 'shell'
  327. if self.env['gdb']:
  328. if not self.env['_args_given']['gdb_wait']:
  329. self.env['gdb_wait'] = True
  330. if not self.env['_args_given']['tmux_args']:
  331. if self.env['userland'] is None and self.env['baremetal'] is None:
  332. self.env['tmux_args'] = 'start_kernel'
  333. else:
  334. self.env['tmux_args'] = 'main'
  335. if not self.env['_args_given']['tmux_program']:
  336. self.env['tmux_program'] = 'gdb'
  337. if self.env['tmux_args'] is not None or self.env['_args_given']['tmux_program']:
  338. self.env['tmux'] = True
  339. if self.env['debug_vm'] or self.env['debug_vm_args']:
  340. debug_vm = ['gdb', LF, '-q', LF] + self.sh.shlex_split(self.env['debug_vm_args']) + ['--args', LF]
  341. else:
  342. debug_vm = []
  343. if self.env['gdb_wait']:
  344. extra_qemu_args.extend(['-S', LF])
  345. if self.env['eval_after'] is not None:
  346. kernel_cli_after_dash += ' lkmc_eval_base64="{}"'.format(self.sh.base64_encode(self.env['eval_after']))
  347. if self.env['kernel_cli_after_dash'] is not None:
  348. kernel_cli_after_dash += ' {}'.format(self.env['kernel_cli_after_dash'])
  349. if self.env['vnc']:
  350. vnc = ['-vnc', ':0', LF]
  351. else:
  352. vnc = []
  353. if self.env['eval'] is not None:
  354. kernel_cli += ' {}=/lkmc/eval_base64.sh'.format(self.env['initarg'])
  355. kernel_cli_after_dash += ' lkmc_eval="{}"'.format(self.sh.base64_encode(self.env['eval']))
  356. if not self.env['graphic']:
  357. extra_qemu_args.extend(['-nographic', LF])
  358. console = None
  359. console_type = None
  360. console_count = 0
  361. if self.env['arch'] == 'x86_64':
  362. console_type = 'ttyS'
  363. elif self.env['is_arm']:
  364. console_type = 'ttyAMA'
  365. console = '{}{}'.format(console_type, console_count)
  366. console_count += 1
  367. if not (self.env['arch'] == 'x86_64' and self.env['graphic']):
  368. kernel_cli += ' console={}'.format(console)
  369. extra_console = '{}{}'.format(console_type, console_count)
  370. console_count += 1
  371. if self.env['kdb'] or self.env['kgdb']:
  372. kernel_cli += ' kgdbwait'
  373. if self.env['kdb']:
  374. if self.env['graphic']:
  375. kdb_cmd = 'kbd,'
  376. else:
  377. kdb_cmd = ''
  378. kernel_cli += ' kgdboc={}{},115200'.format(kdb_cmd, console)
  379. if self.env['kgdb']:
  380. kernel_cli += ' kgdboc={},115200'.format(extra_console)
  381. if kernel_cli_after_dash:
  382. kernel_cli += " -{}".format(kernel_cli_after_dash)
  383. extra_env = {}
  384. if self.env['trace_insts_stdout']:
  385. if self.env['emulator'] == 'qemu':
  386. extra_emulator_args.extend(['-d', 'in_asm', LF])
  387. elif self.env['emulator'] == 'gem5':
  388. self.env['trace_stdout'] = True
  389. self.env['trace'] = 'ExecAll'
  390. if self.env['trace'] is None:
  391. do_trace = False
  392. # A dummy value that is already turned on by default and does not produce large output,
  393. # just to prevent QEMU from emitting a warning that '' is not valid.
  394. trace_type = 'load_file'
  395. else:
  396. do_trace = True
  397. trace_type = self.env['trace']
  398. def raise_rootfs_not_found():
  399. if not self.env['dry_run']:
  400. raise Exception('Root filesystem not found. Did you build it? ' \
  401. 'Tried to use: ' + self.env['disk_image'])
  402. def raise_image_not_found(image):
  403. if not self.env['dry_run']:
  404. raise Exception('Executable image not found. Did you build it? ' \
  405. 'Tried to use: ' + image)
  406. if not os.path.exists(self.env['image']):
  407. raise_image_not_found(self.env['image'])
  408. cmd = debug_vm.copy()
  409. if self.env['emulator'] == 'gem5':
  410. if self.env['quiet']:
  411. show_stdout = False
  412. if not self.env['baremetal'] is None:
  413. if not os.path.exists(self.env['gem5_fake_iso']):
  414. os.makedirs(os.path.dirname(self.env['gem5_fake_iso']), exist_ok=True)
  415. self.sh.write_string_to_file(self.env['gem5_fake_iso'], 'a' * 512)
  416. elif self.env['userland'] is None:
  417. if not os.path.exists(self.env['rootfs_raw_file']):
  418. if not os.path.exists(self.env['qcow2_file']):
  419. raise_rootfs_not_found()
  420. self.raw_to_qcow2(qemu_which=self.env['qemu_which'], reverse=True)
  421. if not os.path.exists(self.env['image']):
  422. # This is to run gem5 from a prebuilt download.
  423. if (
  424. self.env['baremetal'] is None and
  425. self.env['userland'] is None
  426. ):
  427. if not os.path.exists(self.env['linux_image']):
  428. raise_image_not_found(self.env['image'])
  429. self.sh.run_cmd([os.path.join(self.env['extract_vmlinux'], self.env['linux_image'])])
  430. os.makedirs(os.path.dirname(self.env['gem5_readfile']), exist_ok=True)
  431. self.sh.write_string_to_file(self.env['gem5_readfile'], self.env['gem5_readfile'])
  432. memory = '{}B'.format(self.env['memory'])
  433. gem5_exe_args = self.sh.shlex_split(self.env['gem5_exe_args'])
  434. if do_trace:
  435. gem5_exe_args.extend(['--debug-flags', trace_type, LF])
  436. extra_env['M5_PATH'] = self.env['gem5_system_dir']
  437. # https://stackoverflow.com/questions/52312070/how-to-modify-a-file-under-src-python-and-run-it-without-rebuilding-in-gem5/52312071#52312071
  438. extra_env['M5_OVERRIDE_PY_SOURCE'] = 'true'
  439. if self.env['trace_stdout']:
  440. debug_file = 'cout'
  441. else:
  442. debug_file = 'trace.txt'
  443. cmd.extend(
  444. [
  445. self.env['executable'], LF,
  446. '--debug-file', debug_file, LF,
  447. '--listener-mode', 'on', LF,
  448. '--outdir', self.env['m5out_dir'], LF,
  449. ] +
  450. gem5_exe_args
  451. )
  452. if self.env['userland'] is not None:
  453. cmd.extend([
  454. self.env['gem5_se_file'], LF,
  455. '--cmd', self.env['image'], LF,
  456. ])
  457. if self.env['userland_args'] is not None:
  458. cmd.extend(['--options', self.env['userland_args'], LF])
  459. else:
  460. if self.env['gem5_script'] == 'fs':
  461. # TODO port
  462. if self.env['gem5_restore'] is not None:
  463. cpt_dirs = self.gem5_list_checkpoint_dirs()
  464. cpt_dir = cpt_dirs[-self.env['gem5_restore']]
  465. extra_emulator_args.extend(['-r', str(sorted(cpt_dirs).index(cpt_dir) + 1)])
  466. cmd.extend([
  467. self.env['gem5_fs_file'], LF,
  468. '--disk-image', self.env['disk_image'], LF,
  469. '--kernel', self.env['image'], LF,
  470. '--mem-size', memory, LF,
  471. '--num-cpus', str(self.env['cpus']), LF,
  472. '--script', self.env['gem5_readfile'], LF,
  473. ])
  474. if self.env['arch'] == 'x86_64':
  475. if self.env['kvm']:
  476. cmd.extend(['--cpu-type', 'X86KvmCPU', LF])
  477. if self.env['baremetal'] is None:
  478. cmd.extend(['--command-line', 'earlyprintk={} lpj=7999923 root=/dev/sda {}'.format(console, kernel_cli), LF])
  479. elif self.env['is_arm']:
  480. if self.env['kvm']:
  481. cmd.extend(['--cpu-type', 'ArmV8KvmCPU', LF])
  482. if self.env['dp650']:
  483. dp650_cmd = 'dpu_'
  484. else:
  485. dp650_cmd = ''
  486. cmd.extend([
  487. # TODO why is it mandatory to pass mem= here? Not true for QEMU.
  488. # Anything smaller than physical blows up as expected, but why can't it auto-detect the right value?
  489. '--machine-type', self.env['machine'], LF,
  490. ])
  491. if self.env['baremetal'] is None:
  492. cmd.extend(['--command-line', 'earlyprintk=pl011,0x1c090000 lpj=19988480 rw loglevel=8 mem={} root=/dev/sda {}'.format(memory, kernel_cli), LF])
  493. dtb = None
  494. if self.env['dtb'] is not None:
  495. dtb = self.env['dtb']
  496. elif self.env['dp650']:
  497. dtb = os.path.join(
  498. self.env['gem5_system_dir'],
  499. 'arm',
  500. 'dt',
  501. 'armv{}_gem5_v1_{}{}cpu.dtb'.format(
  502. self.env['armv'],
  503. dp650_cmd,
  504. self.env['cpus']
  505. )
  506. )
  507. if dtb is not None:
  508. cmd.extend(['--dtb-filename', dtb, LF])
  509. if self.env['baremetal'] is None:
  510. cmd.extend(['--param', 'system.panic_on_panic = True', LF ])
  511. else:
  512. cmd.extend([
  513. '--bare-metal', LF,
  514. '--param', 'system.auto_reset_addr = True', LF,
  515. ])
  516. if self.env['arch'] == 'aarch64':
  517. # https://stackoverflow.com/questions/43682311/uart-communication-in-gem5-with-arm-bare-metal/50983650#50983650
  518. cmd.extend(['--param', 'system.highest_el_is_64 = True', LF])
  519. elif self.env['gem5_script'] == 'biglittle':
  520. if self.env['kvm']:
  521. cpu_type = 'kvm'
  522. else:
  523. cpu_type = 'atomic'
  524. if self.env['gem5_restore'] is not None:
  525. cpt_dir = self.gem5_list_checkpoint_dirs()[-self.env['gem5_restore']]
  526. extra_emulator_args.extend(['--restore-from', os.path.join(self.env['m5out_dir'], cpt_dir)])
  527. cmd.extend([
  528. os.path.join(
  529. self.env['gem5_source_dir'],
  530. 'configs',
  531. 'example',
  532. 'arm',
  533. 'fs_bigLITTLE.py'
  534. ), LF,
  535. '--big-cpus', '2', LF,
  536. '--cpu-type', cpu_type, LF,
  537. '--disk', self.env['disk_image'], LF,
  538. '--kernel', self.env['image'], LF,
  539. '--little-cpus', '2', LF,
  540. ])
  541. if self.env['dtb']:
  542. cmd.extend([
  543. '--dtb',
  544. os.path.join(self.env['gem5_system_dir'],
  545. 'arm',
  546. 'dt',
  547. 'armv8_gem5_v1_big_little_2_2.dtb'
  548. ),
  549. LF
  550. ])
  551. if self.env['gdb_wait']:
  552. # https://stackoverflow.com/questions/49296092/how-to-make-gem5-wait-for-gdb-to-connect-to-reliably-break-at-start-kernel-of-th
  553. cmd.extend(['--param', 'system.cpu[0].wait_for_remote_gdb = True', LF])
  554. elif self.env['emulator'] == 'qemu':
  555. qemu_user_and_system_options = [
  556. '-trace', 'enable={},file={}'.format(trace_type, self.env['qemu_trace_file']), LF,
  557. ]
  558. if self.env['userland'] is not None:
  559. if self.env['gdb_wait']:
  560. debug_args = ['-g', str(self.env['gdb_port']), LF]
  561. else:
  562. debug_args = []
  563. cmd.extend(
  564. [
  565. self.env['qemu_executable'], LF,
  566. '-L', self.env['userland_library_dir'], LF,
  567. '-r', self.env['kernel_version'], LF,
  568. '-seed', '0', LF,
  569. ] +
  570. qemu_user_and_system_options +
  571. debug_args
  572. )
  573. else:
  574. extra_emulator_args.extend(extra_qemu_args)
  575. self.make_run_dirs()
  576. if self.env['debug_vm']:
  577. serial_monitor = []
  578. else:
  579. if self.env['background']:
  580. serial_monitor = ['-serial', 'file:{}'.format(self.env['guest_terminal_file']), LF]
  581. if self.env['quiet']:
  582. show_stdout = False
  583. else:
  584. if self.env['ctrl_c_host']:
  585. serial = 'stdio'
  586. else:
  587. serial = 'mon:stdio'
  588. serial_monitor = ['-serial', serial, LF]
  589. if self.env['kvm']:
  590. extra_emulator_args.extend(['-enable-kvm', LF])
  591. extra_emulator_args.extend([
  592. '-serial',
  593. 'tcp::{},server,nowait'.format(self.env['extra_serial_port']), LF
  594. ])
  595. virtfs_data = [
  596. (self.env['p9_dir'], 'host_data'),
  597. (self.env['out_dir'], 'host_out'),
  598. (self.env['out_rootfs_overlay_dir'], 'host_out_rootfs_overlay'),
  599. (self.env['rootfs_overlay_dir'], 'host_rootfs_overlay'),
  600. ]
  601. virtfs_cmd = []
  602. for virtfs_dir, virtfs_tag in virtfs_data:
  603. if os.path.exists(virtfs_dir):
  604. virtfs_cmd.extend([
  605. '-virtfs',
  606. 'local,path={virtfs_dir},mount_tag={virtfs_tag},security_model=mapped,id={virtfs_tag}' \
  607. .format(virtfs_dir=virtfs_dir, virtfs_tag=virtfs_tag),
  608. LF,
  609. ])
  610. if self.env['machine2'] is not None:
  611. # Multiple -machine options can also be given comma separated in one -machine.
  612. # We use multiple because the machine is used as an identifier on baremetal tests
  613. # build paths, so better keep them clean.
  614. machine2 = ['-machine', self.env['machine2'], LF]
  615. else:
  616. machine2 = []
  617. cmd.extend(
  618. [
  619. self.env['qemu_executable'], LF,
  620. '-machine', self.env['machine'], LF,
  621. ] +
  622. machine2 +
  623. [
  624. '-device', 'rtl8139,netdev=net0', LF,
  625. '-gdb', 'tcp::{}'.format(self.env['gdb_port']), LF,
  626. '-kernel', self.env['image'], LF,
  627. '-m', self.env['memory'], LF,
  628. '-monitor', 'telnet::{},server,nowait'.format(self.env['qemu_monitor_port']), LF,
  629. '-netdev', 'user,hostfwd=tcp::{}-:{},hostfwd=tcp::{}-:22,id=net0'.format(
  630. self.env['qemu_hostfwd_generic_port'],
  631. self.env['qemu_hostfwd_generic_port'],
  632. self.env['qemu_hostfwd_ssh_port']
  633. ), LF,
  634. '-no-reboot', LF,
  635. '-smp', str(self.env['cpus']), LF,
  636. ] +
  637. virtfs_cmd +
  638. serial_monitor +
  639. vnc
  640. )
  641. if self.env['dtb'] is not None:
  642. cmd.extend(['-dtb', self.env['dtb'], LF])
  643. if not self.env['qemu_which'] == 'host':
  644. cmd.extend(qemu_user_and_system_options)
  645. if self.env['initrd']:
  646. extra_emulator_args.extend(['-initrd', self.env['buildroot_cpio'], LF])
  647. rr = self.env['record'] or self.env['replay']
  648. if self.env['ramfs']:
  649. # TODO why is this needed, and why any string works.
  650. root = 'root=/dev/anything'
  651. else:
  652. if rr:
  653. driveif = 'none'
  654. rrid = ',id=img-direct'
  655. root = 'root=/dev/sda'
  656. snapshot = ''
  657. else:
  658. driveif = 'virtio'
  659. root = 'root=/dev/vda'
  660. rrid = ''
  661. snapshot = ',snapshot'
  662. if self.env['baremetal'] is None:
  663. if not os.path.exists(self.env['qcow2_file']):
  664. if not os.path.exists(self.env['rootfs_raw_file']):
  665. raise_rootfs_not_found()
  666. self.raw_to_qcow2(qemu_which=self.env['qemu_which'])
  667. extra_emulator_args.extend([
  668. '-drive',
  669. 'file={},format=qcow2,if={}{}{}'.format(
  670. self.env['disk_image'],
  671. driveif,
  672. snapshot,
  673. rrid
  674. ),
  675. LF,
  676. ])
  677. if rr:
  678. extra_emulator_args.extend([
  679. '-drive', 'driver=blkreplay,if=none,image=img-direct,id=img-blkreplay', LF,
  680. '-device', 'ide-hd,drive=img-blkreplay', LF,
  681. ])
  682. if rr:
  683. extra_emulator_args.extend([
  684. '-object', 'filter-replay,id=replay,netdev=net0',
  685. '-icount', 'shift=7,rr={},rrfile={}'.format(
  686. 'record' if self.env['record'] else 'replay',
  687. self.env['qemu_rrfile']
  688. ),
  689. ])
  690. virtio_gpu_pci = []
  691. else:
  692. virtio_gpu_pci = ['-device', 'virtio-gpu-pci', LF]
  693. if self.env['arch'] == 'x86_64':
  694. append = ['-append', '{} nopat {}'.format(root, kernel_cli), LF]
  695. cmd.extend([
  696. '-device', 'edu', LF,
  697. ])
  698. elif self.env['is_arm']:
  699. extra_emulator_args.extend(['-semihosting', LF])
  700. if self.env['arch'] == 'arm':
  701. cpu = 'cortex-a15'
  702. else:
  703. cpu = 'cortex-a57'
  704. append = ['-append', '{} {}'.format(root, kernel_cli), LF]
  705. cmd.extend(
  706. [
  707. '-cpu', cpu, LF,
  708. ] +
  709. virtio_gpu_pci
  710. )
  711. if self.env['baremetal'] is None:
  712. cmd.extend(append)
  713. if self.env['tmux']:
  714. tmux_args = '--run-id {}'.format(self.env['run_id'])
  715. if self.env['tmux_program'] == 'shell':
  716. if self.env['emulator'] == 'gem5':
  717. tmux_cmd = './gem5-shell'
  718. else:
  719. raise Exception('--tmux-program is only supported in gem5 currently.')
  720. elif self.env['tmux_program'] == 'gdb':
  721. tmux_cmd = os.path.join(self.env['root_dir'], 'run-gdb')
  722. # TODO find a nicer way to forward all those args automatically.
  723. # Part of me wants to: https://github.com/jonathanslenders/pymux
  724. # but it cannot be used as a library properly it seems, and it is
  725. # slower than tmux.
  726. tmux_args += " --arch {} --emulator '{}' --gcc-which '{}' --linux-build-id '{}' --run-id '{}' --userland-build-id '{}'".format(
  727. self.env['arch'],
  728. self.env['emulator'],
  729. self.env['gcc_which'],
  730. self.env['linux_build_id'],
  731. self.env['run_id'],
  732. self.env['userland_build_id'],
  733. )
  734. if self.env['baremetal']:
  735. tmux_args += " --baremetal '{}'".format(self.env['baremetal'])
  736. if self.env['userland']:
  737. tmux_args += " --userland '{}'".format(self.env['userland'])
  738. if self.env['in_tree']:
  739. tmux_args += ' --in-tree'
  740. if self.env['tmux_args'] is not None:
  741. tmux_args += ' {}'.format(self.env['tmux_args'])
  742. tmux_cmd = [
  743. os.path.join(self.env['root_dir'], 'tmux-split'),
  744. "sleep 2;{} {}".format(tmux_cmd, tmux_args)
  745. ]
  746. self.log_info(self.sh.cmd_to_string(tmux_cmd))
  747. subprocess.Popen(tmux_cmd)
  748. cmd.extend(extra_emulator_args)
  749. cmd.extend(self.env['extra_emulator_args'])
  750. if self.env['userland'] and self.env['emulator'] in ('qemu', 'native'):
  751. # The program and arguments must come at the every end of the CLI.
  752. cmd.extend([self.env['image'], LF])
  753. if self.env['userland_args'] is not None:
  754. cmd.extend(self.sh.shlex_split(self.env['userland_args']))
  755. if debug_vm or self.env['terminal']:
  756. out_file = None
  757. else:
  758. out_file = self.env['termout_file']
  759. exit_status = self.sh.run_cmd(
  760. cmd,
  761. cmd_file=self.env['run_cmd_file'],
  762. extra_env=extra_env,
  763. out_file=out_file,
  764. raise_on_failure=False,
  765. show_stdout=show_stdout,
  766. )
  767. if exit_status == 0:
  768. error_string_found = False
  769. exit_status = 0
  770. if out_file is not None and not self.env['dry_run']:
  771. if self.env['emulator'] == 'gem5':
  772. with open(self.env['termout_file'], 'br') as logfile:
  773. # We have to do some parsing here because gem5 exits with status 0 even when panic happens.
  774. # Grepping for '^panic: ' does not work because some errors don't show that message...
  775. gem5_panic_re = re.compile(b'--- BEGIN LIBC BACKTRACE ---$')
  776. line = None
  777. for line in logfile:
  778. if gem5_panic_re.search(line):
  779. exit_status = 1
  780. if self.env['userland']:
  781. if line is not None:
  782. last_line = line.rstrip()
  783. match = re.search(b'Simulated exit code not 0! Exit code is (\d+)', last_line)
  784. if match:
  785. exit_status = int(match.group(1))
  786. if not self.env['userland']:
  787. if os.path.exists(self.env['guest_terminal_file']):
  788. with open(self.env['guest_terminal_file'], 'br') as logfile:
  789. linux_panic_re = re.compile(b'Kernel panic - not syncing')
  790. serial_magic_exit_status_regexp = re.compile(self.env['serial_magic_exit_status_regexp_string'])
  791. for line in logfile.readlines():
  792. line = line.rstrip()
  793. if not self.env['baremetal'] and linux_panic_re.search(line):
  794. exit_status = 1
  795. match = serial_magic_exit_status_regexp.match(line)
  796. if match:
  797. exit_status = int(match.group(1))
  798. if exit_status != 0 and self.env['show_stdout']:
  799. self.log_error('simulation error detected by parsing logs')
  800. return exit_status
  801. if __name__ == '__main__':
  802. Main().cli()