Repository: google/OpenSK
File: deploy.py (Python)

Code before:

  def read_kernel(self):
    board_props = SUPPORTED_BOARDS[self.args.board]
    kernel_file = os.path.join("third_party", "tock", "target",
                               board_props.arch, "release",
                               f"{self.args.board}.bin")
    if not os.path.exists(kernel_file):
      fatal(f"File not found: {kernel_file}")
    with open(kernel_file, "rb") as firmware:
      kernel = firmware.read()
    return kernel

  def install_tock_os(self):
    kernel = self.read_kernel()
    board_props = SUPPORTED_BOARDS[self.args.board]
    self.write_binary(kernel, board_props.kernel_address)

  def install_padding(self):
    board_props = SUPPORTED_BOARDS[self.args.board]
    if board_props.padding_address is None:
      return
    info("Flashing padding application")
    self.write_binary(self.get_padding(), board_props.padding_address)

  def clear_unused_pages(self, padding_address, padding_size, page_size):
    cleared_size = padding_size - (padding_size % page_size)
    clear_address = padding_address + padding_size - cleared_size
    self.clear_flash(clear_address, cleared_size)

  def install_metadata(self):

    def pad_to(binary, length):
      if len(binary) > length:
        fatal(f"Binary size {len(binary)} exceeds flash partition {length}.")
      padding = bytes([0xFF] * (length - len(binary)))
      return binary + padding

    board_props = SUPPORTED_BOARDS[self.args.board]
    if board_props.metadata_address is None:
      return
    kernel_address = board_props.kernel_address
    app_address = board_props.app_address
    page_size = board_props.page_size

    kernel = self.read_kernel()
    app_tab_path = "target/tab/ctap2.tab"
    if not os.path.exists(app_tab_path):
      fatal(f"File not found: {app_tab_path}")
    app_tab = tab.TAB(app_tab_path)
    arch = board_props.arch
    if arch not in app_tab.get_supported_architectures():

Review comment (suggestion):
Maybe we should start adding some documentation because `deploy.py` keeps growing.
Here I don't quite follow the logic, especially around `clear_address` computation.

Code after:
    for arch, app_file in binary_names.items():
      dest_file = os.path.join(self.tab_folder, f"{arch}.elf")
      shutil.copyfile(app_file, dest_file)
      elf2tab_args.append(dest_file)
      # extract required stack size directly from binary
      nm = self.checked_command_output(
          ["nm", "--print-size", "--radix=x", app_file])
      for line in nm.splitlines():
        if "STACK_MEMORY" in line:
          required_stack_size = int(line.split(" ", maxsplit=2)[1], 16)
          stack_sizes.add(required_stack_size)
    if len(stack_sizes) != 1:
      error("Detected different stack sizes across tab files.")

    elf2tab_args.extend([
        f"--stack={stack_sizes.pop()}", f"--app-heap={APP_HEAP_SIZE}",
        "--kernel-heap=1024", "--protected-region-size=64"
    ])
    if self.args.elf2tab_output:
      output = self.checked_command_output(elf2tab_args)
      self.args.elf2tab_output.write(output)
    else:
      self.checked_command(elf2tab_args)

  def install_tab_file(self, tab_filename: str):
    """Calls Tockloader to install a TAB file."""
    assert self.args.application
    info(f"Installing Tock application {self.args.application}")
    args = copy.copy(self.tockloader_default_args)
    setattr(args, "erase", self.args.clear_apps)
    setattr(args, "make", False)
    setattr(args, "no_replace", False)
    tock = loader.TockLoader(args)
    tock.open()
    tabs = [tab.TAB(tab_filename)]
    try:
      tock.install(tabs, replace="yes", erase=args.erase)
    except TockLoaderException as e:
      fatal("Couldn't install Tock application "
            f"{self.args.application}: {str(e)}")

  def get_padding(self) -> bytes:
    """Creates a padding application binary."""
    padding = tbfh.TBFHeaderPadding(
        SUPPORTED_BOARDS[self.args.board].app_address -
        SUPPORTED_BOARDS[self.args.board].padding_address)
    return padding.get_binary()

  def write_binary(self, binary: bytes, address: int):
    """Writes a binary to the device's flash at the given address."""
    tock = loader.TockLoader(self.tockloader_default_args)