emulator.py 7.4 KB

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