|
| 1 | +# Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +# or more contributor license agreements. See the NOTICE file |
| 3 | +# distributed with this work for additional information |
| 4 | +# regarding copyright ownership. The ASF licenses this file |
| 5 | +# to you under the Apache License, Version 2.0 (the |
| 6 | +# "License"); you may not use this file except in compliance |
| 7 | +# with the License. You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, |
| 12 | +# software distributed under the License is distributed on an |
| 13 | +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +# KIND, either express or implied. See the License for the |
| 15 | +# specific language governing permissions and limitations |
| 16 | +# under the License. |
| 17 | + |
| 18 | +"""Utilities for binary file manipulation""" |
| 19 | +import os |
| 20 | +import subprocess |
| 21 | +from . import util |
| 22 | +from .._ffi.base import py_str |
| 23 | +from ..api import register_func |
| 24 | + |
| 25 | +@register_func("tvm_callback_get_section_size") |
| 26 | +def tvm_callback_get_section_size(binary_path, section_name, toolchain_prefix): |
| 27 | + """Finds size of the section in the binary. |
| 28 | + Assumes `size` shell command exists (typically works only on Linux machines) |
| 29 | +
|
| 30 | + Parameters |
| 31 | + ---------- |
| 32 | + binary_path : str |
| 33 | + path of the binary file |
| 34 | +
|
| 35 | + section_name : str |
| 36 | + name of section |
| 37 | +
|
| 38 | + toolchain_prefix : str |
| 39 | + prefix for binary names in target compiler toolchain |
| 40 | +
|
| 41 | + Returns |
| 42 | + ------- |
| 43 | + size : integer |
| 44 | + size of the section in bytes |
| 45 | + """ |
| 46 | + if not os.path.isfile(binary_path): |
| 47 | + raise RuntimeError("no such file \"{}\"".format(binary_path)) |
| 48 | + # We use the "-A" flag here to get the ".rodata" section's size, which is |
| 49 | + # not included by default. |
| 50 | + size_proc = subprocess.Popen( |
| 51 | + ["{}size".format(toolchain_prefix), "-A", binary_path], stdout=subprocess.PIPE) |
| 52 | + (size_output, _) = size_proc.communicate() |
| 53 | + size_output = size_output.decode("utf-8") |
| 54 | + if size_proc.returncode != 0: |
| 55 | + msg = "error in finding section size:\n" |
| 56 | + msg += py_str(out) |
| 57 | + raise RuntimeError(msg) |
| 58 | + |
| 59 | + # TODO(weberlo): Refactor this method and `*relocate_binary` so they are |
| 60 | + # both aware of [".bss", ".sbss", ".sdata"] being relocated to ".bss". |
| 61 | + section_mapping = { |
| 62 | + ".text": [".text"], |
| 63 | + ".rodata": [".rodata"], |
| 64 | + ".data": [".data", ".sdata"], |
| 65 | + ".bss": [".bss", ".sbss"], |
| 66 | + } |
| 67 | + sections_to_sum = section_mapping["." + section_name] |
| 68 | + section_size = 0 |
| 69 | + # Skip the first two header lines in the `size` output. |
| 70 | + for line in size_output.split("\n")[2:]: |
| 71 | + tokens = list(filter(lambda s: len(s) != 0, line.split(" "))) |
| 72 | + if len(tokens) != 3: |
| 73 | + continue |
| 74 | + entry_name = tokens[0] |
| 75 | + entry_size = int(tokens[1]) |
| 76 | + if entry_name in sections_to_sum: |
| 77 | + section_size += entry_size |
| 78 | + return section_size |
| 79 | + |
| 80 | + |
| 81 | +@register_func("tvm_callback_relocate_binary") |
| 82 | +def tvm_callback_relocate_binary( |
| 83 | + binary_path, text_addr, rodata_addr, data_addr, bss_addr, toolchain_prefix): |
| 84 | + """Relocates sections in the binary to new addresses |
| 85 | +
|
| 86 | + Parameters |
| 87 | + ---------- |
| 88 | + binary_path : str |
| 89 | + path of the binary file |
| 90 | +
|
| 91 | + text_addr : str |
| 92 | + text section absolute address |
| 93 | +
|
| 94 | + rodata_addr : str |
| 95 | + rodata section absolute address |
| 96 | +
|
| 97 | + data_addr : str |
| 98 | + data section absolute address |
| 99 | +
|
| 100 | + bss_addr : str |
| 101 | + bss section absolute address |
| 102 | +
|
| 103 | + toolchain_prefix : str |
| 104 | + prefix for binary names in target compiler toolchain |
| 105 | +
|
| 106 | + Returns |
| 107 | + ------- |
| 108 | + rel_bin : bytearray |
| 109 | + the relocated binary |
| 110 | + """ |
| 111 | + tmp_dir = util.tempdir() |
| 112 | + rel_obj_path = tmp_dir.relpath("relocated.o") |
| 113 | + ld_script_contents = "" |
| 114 | + # TODO(weberlo): There should be a better way to configure this for different archs. |
| 115 | + if "riscv" in toolchain_prefix: |
| 116 | + ld_script_contents += "OUTPUT_ARCH( \"riscv\" )\n\n" |
| 117 | + # TODO(weberlo): Generate the script in a more procedural manner. |
| 118 | + ld_script_contents += """ |
| 119 | +SECTIONS |
| 120 | +{ |
| 121 | + . = %s; |
| 122 | + . = ALIGN(8); |
| 123 | + .text : |
| 124 | + { |
| 125 | + *(.text) |
| 126 | + . = ALIGN(8); |
| 127 | + *(.text*) |
| 128 | + } |
| 129 | + . = %s; |
| 130 | + . = ALIGN(8); |
| 131 | + .rodata : |
| 132 | + { |
| 133 | + *(.rodata) |
| 134 | + . = ALIGN(8); |
| 135 | + *(.rodata*) |
| 136 | + } |
| 137 | + . = %s; |
| 138 | + . = ALIGN(8); |
| 139 | + .data : |
| 140 | + { |
| 141 | + *(.data) |
| 142 | + . = ALIGN(8); |
| 143 | + *(.data*) |
| 144 | + . = ALIGN(8); |
| 145 | + *(.sdata) |
| 146 | + } |
| 147 | + . = %s; |
| 148 | + . = ALIGN(8); |
| 149 | + .bss : |
| 150 | + { |
| 151 | + *(.bss) |
| 152 | + . = ALIGN(8); |
| 153 | + *(.bss*) |
| 154 | + . = ALIGN(8); |
| 155 | + *(.sbss) |
| 156 | + } |
| 157 | +} |
| 158 | + """ % (text_addr, rodata_addr, data_addr, bss_addr) |
| 159 | + rel_ld_script_path = tmp_dir.relpath("relocated.lds") |
| 160 | + with open(rel_ld_script_path, "w") as f: |
| 161 | + f.write(ld_script_contents) |
| 162 | + ld_proc = subprocess.Popen(["{}ld".format(toolchain_prefix), binary_path, |
| 163 | + "-T", rel_ld_script_path, |
| 164 | + "-o", rel_obj_path], |
| 165 | + stdout=subprocess.PIPE, |
| 166 | + stderr=subprocess.STDOUT) |
| 167 | + (out, _) = ld_proc.communicate() |
| 168 | + if ld_proc.returncode != 0: |
| 169 | + msg = "linking error using ld:\n" |
| 170 | + msg += py_str(out) |
| 171 | + raise RuntimeError(msg) |
| 172 | + with open(rel_obj_path, "rb") as f: |
| 173 | + rel_bin = bytearray(f.read()) |
| 174 | + return rel_bin |
| 175 | + |
| 176 | + |
| 177 | +@register_func("tvm_callback_read_binary_section") |
| 178 | +def tvm_callback_read_binary_section(binary, section, toolchain_prefix): |
| 179 | + """Returns the contents of the specified section in the binary byte array |
| 180 | +
|
| 181 | + Parameters |
| 182 | + ---------- |
| 183 | + binary : bytearray |
| 184 | + contents of the binary |
| 185 | +
|
| 186 | + section : str |
| 187 | + type of section |
| 188 | +
|
| 189 | + toolchain_prefix : str |
| 190 | + prefix for binary names in target compiler toolchain |
| 191 | +
|
| 192 | + Returns |
| 193 | + ------- |
| 194 | + section_bin : bytearray |
| 195 | + contents of the read section |
| 196 | + """ |
| 197 | + tmp_dir = util.tempdir() |
| 198 | + tmp_bin = tmp_dir.relpath("temp.bin") |
| 199 | + tmp_section = tmp_dir.relpath("tmp_section.bin") |
| 200 | + with open(tmp_bin, "wb") as out_file: |
| 201 | + out_file.write(bytes(binary)) |
| 202 | + objcopy_proc = subprocess.Popen(["{}objcopy".format(toolchain_prefix), "--dump-section", |
| 203 | + ".{}={}".format(section, tmp_section), |
| 204 | + tmp_bin], |
| 205 | + stdout=subprocess.PIPE, |
| 206 | + stderr=subprocess.STDOUT) |
| 207 | + (out, _) = objcopy_proc.communicate() |
| 208 | + if objcopy_proc.returncode != 0: |
| 209 | + msg = "error in using objcopy:\n" |
| 210 | + msg += py_str(out) |
| 211 | + raise RuntimeError(msg) |
| 212 | + if os.path.isfile(tmp_section): |
| 213 | + # Get section content if it exists. |
| 214 | + with open(tmp_section, "rb") as f: |
| 215 | + section_bin = bytearray(f.read()) |
| 216 | + else: |
| 217 | + # Return empty bytearray if the section does not exist. |
| 218 | + section_bin = bytearray("", "utf-8") |
| 219 | + return section_bin |
| 220 | + |
| 221 | + |
| 222 | +@register_func("tvm_callback_get_symbol_map") |
| 223 | +def tvm_callback_get_symbol_map(binary, toolchain_prefix): |
| 224 | + """Obtains a map of symbols to addresses in the passed binary |
| 225 | +
|
| 226 | + Parameters |
| 227 | + ---------- |
| 228 | + binary : bytearray |
| 229 | + contents of the binary |
| 230 | +
|
| 231 | + toolchain_prefix : str |
| 232 | + prefix for binary names in target compiler toolchain |
| 233 | +
|
| 234 | + Returns |
| 235 | + ------- |
| 236 | + map_str : str |
| 237 | + map of defined symbols to addresses, encoded as a series of |
| 238 | + alternating newline-separated keys and values |
| 239 | + """ |
| 240 | + tmp_dir = util.tempdir() |
| 241 | + tmp_obj = tmp_dir.relpath("tmp_obj.bin") |
| 242 | + with open(tmp_obj, "wb") as out_file: |
| 243 | + out_file.write(bytes(binary)) |
| 244 | + nm_proc = subprocess.Popen(["{}nm".format(toolchain_prefix), "-C", "--defined-only", tmp_obj], |
| 245 | + stdout=subprocess.PIPE, |
| 246 | + stderr=subprocess.STDOUT) |
| 247 | + (nm_output, _) = nm_proc.communicate() |
| 248 | + if nm_proc.returncode != 0: |
| 249 | + msg = "error in using nm:\n" |
| 250 | + msg += py_str(nm_output) |
| 251 | + raise RuntimeError(msg) |
| 252 | + nm_output = nm_output.decode("utf8").splitlines() |
| 253 | + map_str = "" |
| 254 | + for line in nm_output: |
| 255 | + line = line.split() |
| 256 | + map_str += line[2] + "\n" |
| 257 | + map_str += line[0] + "\n" |
| 258 | + return map_str |
0 commit comments