run 37 KB

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