emulator.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. # SPDX-License-Identifier: GPL-2.0
  2. # SPDX-License-Identifier: ISC
  3. import pexpect
  4. import pexpect.replwrap
  5. import infra
  6. BR_PROMPT = '[BRTEST# '
  7. BR_CONTINUATION_PROMPT = '[BRTEST+ '
  8. def _repl_sh_child(child, orig_prompt, extra_init_cmd):
  9. """Wrap the shell prompt to handle command output
  10. Based on pexpect.replwrap._repl_sh() (ISC licensed)
  11. https://github.com/pexpect/pexpect/blob/aa989594e1e413f45c18b26ded1783f7d5990fe5/pexpect/replwrap.py#L115
  12. """
  13. # If the user runs 'env', the value of PS1 will be in the output. To avoid
  14. # replwrap seeing that as the next prompt, we'll embed the marker characters
  15. # for invisible characters in the prompt; these show up when inspecting the
  16. # environment variable, but not when bash displays the prompt.
  17. non_printable_insert = '\\[\\]'
  18. ps1 = BR_PROMPT[:5] + non_printable_insert + BR_PROMPT[5:]
  19. ps2 = (BR_CONTINUATION_PROMPT[:5] + non_printable_insert +
  20. BR_CONTINUATION_PROMPT[5:])
  21. prompt_change = "PS1='{0}' PS2='{1}' PROMPT_COMMAND=''".format(ps1, ps2)
  22. # Note: this will run various commands, each with the default timeout defined
  23. # when qemu was spawned.
  24. return pexpect.replwrap.REPLWrapper(
  25. child,
  26. orig_prompt,
  27. prompt_change,
  28. new_prompt=BR_PROMPT,
  29. continuation_prompt=BR_CONTINUATION_PROMPT,
  30. extra_init_cmd=extra_init_cmd
  31. )
  32. class Emulator(object):
  33. def __init__(self, builddir, downloaddir, logtofile, timeout_multiplier):
  34. self.qemu = None
  35. self.repl = None
  36. self.downloaddir = downloaddir
  37. self.logfile = infra.open_log_file(builddir, "run", logtofile)
  38. # We use elastic runners on the cloud to runs our tests. Those runners
  39. # can take a long time to run the emulator. Use a timeout multiplier
  40. # when running the tests to avoid sporadic failures.
  41. self.timeout_multiplier = timeout_multiplier
  42. # Start Qemu to boot the system
  43. #
  44. # arch: Qemu architecture to use
  45. #
  46. # kernel: path to the kernel image, or the special string
  47. # 'builtin'. 'builtin' means a pre-built kernel image will be
  48. # downloaded from ARTIFACTS_URL and suitable options are
  49. # automatically passed to qemu and added to the kernel cmdline. So
  50. # far only armv5, armv7 and i386 builtin kernels are available.
  51. # If None, then no kernel is used, and we assume a bootable device
  52. # will be specified.
  53. #
  54. # kernel_cmdline: array of kernel arguments to pass to Qemu -append option
  55. #
  56. # options: array of command line options to pass to Qemu
  57. #
  58. def boot(self, arch, kernel=None, kernel_cmdline=None, options=None):
  59. if arch in ["armv7", "armv5"]:
  60. qemu_arch = "arm"
  61. else:
  62. qemu_arch = arch
  63. qemu_cmd = ["qemu-system-{}".format(qemu_arch),
  64. "-serial", "stdio",
  65. "-display", "none",
  66. "-m", "256"]
  67. if options:
  68. qemu_cmd += options
  69. if kernel_cmdline is None:
  70. kernel_cmdline = []
  71. if kernel:
  72. if kernel == "builtin":
  73. if arch in ["armv7", "armv5"]:
  74. kernel_cmdline.append("console=ttyAMA0")
  75. if arch == "armv7":
  76. kernel = infra.download(self.downloaddir,
  77. "kernel-vexpress-5.10.202")
  78. dtb = infra.download(self.downloaddir,
  79. "vexpress-v2p-ca9-5.10.202.dtb")
  80. qemu_cmd += ["-dtb", dtb]
  81. qemu_cmd += ["-M", "vexpress-a9"]
  82. elif arch == "armv5":
  83. kernel = infra.download(self.downloaddir,
  84. "kernel-versatile-5.10.202")
  85. dtb = infra.download(self.downloaddir,
  86. "versatile-pb-5.10.202.dtb")
  87. qemu_cmd += ["-dtb", dtb]
  88. qemu_cmd += ["-M", "versatilepb"]
  89. qemu_cmd += ["-device", "virtio-rng-pci"]
  90. qemu_cmd += ["-kernel", kernel]
  91. if kernel_cmdline:
  92. qemu_cmd += ["-append", " ".join(kernel_cmdline)]
  93. self.logfile.write("> starting qemu with '%s'\n" % " ".join(qemu_cmd))
  94. self.qemu = pexpect.spawn(qemu_cmd[0], qemu_cmd[1:],
  95. timeout=5 * self.timeout_multiplier,
  96. encoding='utf-8',
  97. codec_errors='replace',
  98. env={"QEMU_AUDIO_DRV": "none"})
  99. # We want only stdout into the log to avoid double echo
  100. self.qemu.logfile_read = self.logfile
  101. # Wait for the login prompt to appear, and then login as root with
  102. # the provided password, or no password if not specified.
  103. def login(self, password=None, timeout=60):
  104. # The login prompt can take some time to appear when running multiple
  105. # instances in parallel, so set the timeout to a large value
  106. index = self.qemu.expect(["buildroot login:", pexpect.TIMEOUT],
  107. timeout=timeout * self.timeout_multiplier)
  108. if index != 0:
  109. self.logfile.write("==> System does not boot")
  110. raise SystemError("System does not boot")
  111. self.qemu.sendline("root")
  112. if password:
  113. self.qemu.expect("Password:")
  114. self.qemu.sendline(password)
  115. extra_init_cmd = " && ".join([
  116. 'export PAGER=cat',
  117. 'dmesg -n 1',
  118. # Prevent the shell from wrapping the commands at 80 columns.
  119. 'stty columns 29999',
  120. # Fix the prompt of any subshells that get run
  121. 'printf "%s\n" "PS1=\'$PS1\'" "PS2=\'$PS2\'" "PROMPT_COMMAND=\'\'" >>/etc/profile'
  122. ])
  123. self.repl = _repl_sh_child(self.qemu, '# ', extra_init_cmd)
  124. if not self.repl:
  125. raise SystemError("Cannot initialize REPL prompt")
  126. # Run the given 'cmd' with a 'timeout' on the target
  127. # return a tuple (output, exit_code)
  128. def run(self, cmd, timeout=-1):
  129. if timeout != -1:
  130. timeout *= self.timeout_multiplier
  131. output = self.repl.run_command(cmd, timeout=timeout)
  132. # Remove double carriage return from qemu stdout so str.splitlines()
  133. # works as expected.
  134. output = output.replace("\r\r", "\r").splitlines()[1:]
  135. exit_code = self.repl.run_command("echo $?")
  136. exit_code = self.qemu.before.splitlines()[2]
  137. exit_code = int(exit_code)
  138. return output, exit_code
  139. def stop(self):
  140. if self.qemu is None:
  141. return
  142. self.qemu.terminate(force=True)