run 37 KB

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