Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/ggml/blob/master/src/ggml-hexagon/htp/htp-swiv.py # ggml [Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685) Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `ggml / src / ggml-hexagon / htp / htp-swiv.py` 512 lines ยท 15832 bytes Raw Blame History 1 #!/usr/bin/env python3 2 3 import argparse 4 import logging 5 import os 6 import shutil 7 import struct 8 import sys 9 import tempfile 10 import zlib 11 12 ELF_MAGIC = b'\x7fELF' 13 ELF_CLASS_INDEX = 4 14 ELFCLASS32 = 1 15 ELFCLASS64 = 2 16 ELF_VERSION_INDEX = 6 17 EV_CURRENT = 1 18 MAX_PHDR_COUNT = 100 19 20 LOAD_TYPE = 0x1 21 22 SHT_NOBITS = 8 23 24 SWIV_MAGIC = b'SWIV' 25 SWIV_SEG_SIZE_MIN = 16 26 # SHT_LOUSER plus ASCII "SWIV". 27 SWIV_SECTION_TYPE = 0xD3574956 28 29 logger = logging.getLogger("htp-swiv") 30 31 32 class Elf_Ehdr_common: 33 s = struct.Struct('16sHHI') 34 35 def __init__(self, data): 36 unpacked_data = (Elf_Ehdr_common.s).unpack(data) 37 self.e_ident = unpacked_data[0] 38 self.e_type = unpacked_data[1] 39 self.e_machine = unpacked_data[2] 40 self.e_version = unpacked_data[3] 41 42 43 class Elf32_Ehdr: 44 s = struct.Struct('16sHHIIIIIHHHHHH') 45 46 def __init__(self, data): 47 unpacked_data = (Elf32_Ehdr.s).unpack(data) 48 self.e_ident = unpacked_data[0] 49 self.e_type = unpacked_data[1] 50 self.e_machine = unpacked_data[2] 51 self.e_version = unpacked_data[3] 52 self.e_entry = unpacked_data[4] 53 self.e_phoff = unpacked_data[5] 54 self.e_shoff = unpacked_data[6] 55 self.e_flags = unpacked_data[7] 56 self.e_ehsize = unpacked_data[8] 57 self.e_phentsize = unpacked_data[9] 58 self.e_phnum = unpacked_data[10] 59 self.e_shentsize = unpacked_data[11] 60 self.e_shnum = unpacked_data[12] 61 self.e_shstrndx = unpacked_data[13] 62 63 def get_packed_data(self): 64 values = [self.e_ident, 65 self.e_type, 66 self.e_machine, 67 self.e_version, 68 self.e_entry, 69 self.e_phoff, 70 self.e_shoff, 71 self.e_flags, 72 self.e_ehsize, 73 self.e_phentsize, 74 self.e_phnum, 75 self.e_shentsize, 76 self.e_shnum, 77 self.e_shstrndx 78 ] 79 80 return (Elf32_Ehdr.s).pack(*values) 81 82 83 class Elf32_Phdr: 84 s = struct.Struct('I' * 8) 85 86 def __init__(self, data): 87 unpacked_data = (Elf32_Phdr.s).unpack(data) 88 self.p_type = unpacked_data[0] 89 self.p_offset = unpacked_data[1] 90 self.p_vaddr = unpacked_data[2] 91 self.p_paddr = unpacked_data[3] 92 self.p_filesz = unpacked_data[4] 93 self.p_memsz = unpacked_data[5] 94 self.p_flags = unpacked_data[6] 95 self.p_align = unpacked_data[7] 96 97 def get_packed_data(self): 98 values = [self.p_type, 99 self.p_offset, 100 self.p_vaddr, 101 self.p_paddr, 102 self.p_filesz, 103 self.p_memsz, 104 self.p_flags, 105 self.p_align 106 ] 107 108 return (Elf32_Phdr.s).pack(*values) 109 110 111 class Elf32_Shdr: 112 s = struct.Struct('I' * 10) 113 114 def __init__(self, data): 115 unpacked_data = (Elf32_Shdr.s).unpack(data) 116 self.sh_name = unpacked_data[0] 117 self.sh_type = unpacked_data[1] 118 self.sh_flags = unpacked_data[2] 119 self.sh_addr = unpacked_data[3] 120 self.sh_offset = unpacked_data[4] 121 self.sh_size = unpacked_data[5] 122 self.sh_link = unpacked_data[6] 123 self.sh_info = unpacked_data[7] 124 self.sh_addralign = unpacked_data[8] 125 self.sh_entsize = unpacked_data[9] 126 self.sh_name_str = "" 127 128 def get_packed_data(self): 129 values = [self.sh_name, 130 self.sh_type, 131 self.sh_flags, 132 self.sh_addr, 133 self.sh_offset, 134 self.sh_size, 135 self.sh_link, 136 self.sh_info, 137 self.sh_addralign, 138 self.sh_entsize] 139 140 return (Elf32_Shdr.s).pack(*values) 141 142 143 class Elf64_Ehdr: 144 s = struct.Struct('16sHHIQQQIHHHHHH') 145 146 def __init__(self, data): 147 unpacked_data = (Elf64_Ehdr.s).unpack(data) 148 self.e_ident = unpacked_data[0] 149 self.e_type = unpacked_data[1] 150 self.e_machine = unpacked_data[2] 151 self.e_version = unpacked_data[3] 152 self.e_entry = unpacked_data[4] 153 self.e_phoff = unpacked_data[5] 154 self.e_shoff = unpacked_data[6] 155 self.e_flags = unpacked_data[7] 156 self.e_ehsize = unpacked_data[8] 157 self.e_phentsize = unpacked_data[9] 158 self.e_phnum = unpacked_data[10] 159 self.e_shentsize = unpacked_data[11] 160 self.e_shnum = unpacked_data[12] 161 self.e_shstrndx = unpacked_data[13] 162 163 def get_packed_data(self): 164 values = [self.e_ident, 165 self.e_type, 166 self.e_machine, 167 self.e_version, 168 self.e_entry, 169 self.e_phoff, 170 self.e_shoff, 171 self.e_flags, 172 self.e_ehsize, 173 self.e_phentsize, 174 self.e_phnum, 175 self.e_shentsize, 176 self.e_shnum, 177 self.e_shstrndx 178 ] 179 180 return (Elf64_Ehdr.s).pack(*values) 181 182 183 class Elf64_Phdr: 184 s = struct.Struct('IIQQQQQQ') 185 186 def __init__(self, data): 187 unpacked_data = (Elf64_Phdr.s).unpack(data) 188 self.p_type = unpacked_data[0] 189 self.p_flags = unpacked_data[1] 190 self.p_offset = unpacked_data[2] 191 self.p_vaddr = unpacked_data[3] 192 self.p_paddr = unpacked_data[4] 193 self.p_filesz = unpacked_data[5] 194 self.p_memsz = unpacked_data[6] 195 self.p_align = unpacked_data[7] 196 197 def get_packed_data(self): 198 values = [self.p_type, 199 self.p_flags, 200 self.p_offset, 201 self.p_vaddr, 202 self.p_paddr, 203 self.p_filesz, 204 self.p_memsz, 205 self.p_align 206 ] 207 208 return (Elf64_Phdr.s).pack(*values) 209 210 211 class Elf64_Shdr: 212 s = struct.Struct('IIQQQQIIQQ') 213 214 def __init__(self, data): 215 unpacked_data = (Elf64_Shdr.s).unpack(data) 216 self.sh_name = unpacked_data[0] 217 self.sh_type = unpacked_data[1] 218 self.sh_flags = unpacked_data[2] 219 self.sh_addr = unpacked_data[3] 220 self.sh_offset = unpacked_data[4] 221 self.sh_size = unpacked_data[5] 222 self.sh_link = unpacked_data[6] 223 self.sh_info = unpacked_data[7] 224 self.sh_addralign = unpacked_data[8] 225 self.sh_entsize = unpacked_data[9] 226 self.sh_name_str = "" 227 228 def get_packed_data(self): 229 values = [self.sh_name, 230 self.sh_type, 231 self.sh_flags, 232 self.sh_addr, 233 self.sh_offset, 234 self.sh_size, 235 self.sh_link, 236 self.sh_info, 237 self.sh_addralign, 238 self.sh_entsize] 239 240 return (Elf64_Shdr.s).pack(*values) 241 242 243 class SWIV_Seg: 244 s = struct.Struct('4sIQ') 245 246 def __init__(self): 247 self.magic = SWIV_MAGIC 248 self.crc = 0 249 self.padding = 0 250 251 def get_packed_data(self): 252 values = [self.magic, 253 self.crc, 254 self.padding 255 ] 256 257 return (SWIV_Seg.s).pack(*values) 258 259 260 def is_elf64(elf_header): 261 return elf_header.e_ident[ELF_CLASS_INDEX] == ELFCLASS64 262 263 264 def verify_elf_header(elf_header): 265 ident = elf_header.e_ident 266 return (ident.startswith(ELF_MAGIC) 267 and ident[ELF_CLASS_INDEX] in (ELFCLASS32, ELFCLASS64) 268 and ident[ELF_VERSION_INDEX] == EV_CURRENT) 269 270 271 def file_copy_offset(in_fp, in_off, out_fp, out_off, num_bytes): 272 in_fp.seek(in_off) 273 read_in = in_fp.read(num_bytes) 274 out_fp.seek(out_off) 275 out_fp.write(read_in) 276 277 return num_bytes 278 279 280 def preprocess_elf_file(elf_file_name): 281 with open(elf_file_name, 'rb') as elf_fp: 282 elf_header = Elf_Ehdr_common(elf_fp.read(Elf_Ehdr_common.s.size)) 283 284 if verify_elf_header(elf_header) is False: 285 raise RuntimeError("Input ELF verification failed : " + elf_file_name) 286 287 elf_fp.seek(0) 288 289 if is_elf64(elf_header): 290 elf_header = Elf64_Ehdr(elf_fp.read(Elf64_Ehdr.s.size)) 291 else: 292 elf_header = Elf32_Ehdr(elf_fp.read(Elf32_Ehdr.s.size)) 293 294 phdr_table = [] 295 296 phdr_size = elf_header.e_phentsize 297 298 file_offset = elf_header.e_phoff 299 elf_fp.seek(file_offset) 300 301 for _ in range(elf_header.e_phnum): 302 if is_elf64(elf_header): 303 phdr_table.append(Elf64_Phdr(elf_fp.read(phdr_size))) 304 else: 305 phdr_table.append(Elf32_Phdr(elf_fp.read(phdr_size))) 306 307 return [elf_header, phdr_table] 308 309 310 def process_section_header(elf_file_name): 311 with open(elf_file_name, 'rb') as elf_fp: 312 elf_header = Elf_Ehdr_common(elf_fp.read(Elf_Ehdr_common.s.size)) 313 314 if verify_elf_header(elf_header) is False: 315 raise RuntimeError("Input ELF verification failed : " + elf_file_name) 316 317 elf_fp.seek(0) 318 319 if is_elf64(elf_header): 320 elf_header = Elf64_Ehdr(elf_fp.read(Elf64_Ehdr.s.size)) 321 else: 322 elf_header = Elf32_Ehdr(elf_fp.read(Elf32_Ehdr.s.size)) 323 324 shdr_table = [] 325 326 shdr_size = elf_header.e_shentsize 327 elf_fp.seek(elf_header.e_shoff) 328 329 for _ in range(elf_header.e_shnum): 330 if is_elf64(elf_header): 331 shdr_table.append(Elf64_Shdr(elf_fp.read(shdr_size))) 332 else: 333 shdr_table.append(Elf32_Shdr(elf_fp.read(shdr_size))) 334 335 return shdr_table 336 337 338 def crc32_update_file(elf_fp, offset, size, crc): 339 elf_fp.seek(offset) 340 remaining = size 341 while remaining > 0: 342 chunk = elf_fp.read(min(1024 * 1024, remaining)) 343 if not chunk: 344 raise RuntimeError("Unexpected EOF while calculating CRC") 345 crc = zlib.crc32(chunk, crc) 346 remaining -= len(chunk) 347 return crc 348 349 350 def crc32_update_zeros(size, crc): 351 zero_chunk = b'\x00' * min(1024 * 1024, size) 352 remaining = size 353 while remaining > 0: 354 chunk = zero_chunk[:min(len(zero_chunk), remaining)] 355 crc = zlib.crc32(chunk, crc) 356 remaining -= len(chunk) 357 return crc 358 359 360 def crc32_calculate(elf_fp, phdr_table): 361 crc = 0 362 363 # SWIV validates loadable segment contents, including BSS as zeros. 364 for curr_phdr in phdr_table: 365 if curr_phdr.p_type != LOAD_TYPE: 366 continue 367 368 crc = crc32_update_file(elf_fp, curr_phdr.p_offset, curr_phdr.p_filesz, crc) 369 370 zero_size = curr_phdr.p_memsz - curr_phdr.p_filesz 371 if zero_size > 0: 372 crc = crc32_update_zeros(zero_size, crc) 373 374 crc &= 0xffffffff 375 logger.info("calculated CRC: %#x", crc) 376 377 return crc 378 379 380 def verify_swiv_seg(elf_in_fp, offset): 381 382 elf_in_fp.seek(offset) 383 swiv_seg = SWIV_Seg() 384 unpacked_data = (SWIV_Seg.s).unpack(elf_in_fp.read(SWIV_SEG_SIZE_MIN)) 385 swiv_seg.magic = unpacked_data[0] 386 387 return swiv_seg.magic == SWIV_MAGIC 388 389 390 def same_output_file(input_elf, output_elf): 391 try: 392 return os.path.exists(output_elf) and os.path.samefile(input_elf, output_elf) 393 except FileNotFoundError: 394 return False 395 396 397 def make_output_target(input_elf, output_elf): 398 if not same_output_file(input_elf, output_elf): 399 return output_elf, None 400 401 output_dir = os.path.dirname(os.path.abspath(output_elf)) 402 output_base = os.path.basename(output_elf) 403 fd, temp_output = tempfile.mkstemp(prefix=output_base + ".", suffix=".tmp", dir=output_dir) 404 os.close(fd) 405 shutil.copymode(input_elf, temp_output) 406 return temp_output, temp_output 407 408 409 def swiv_generate(input_elf, output_elf): 410 output_target, temp_output = make_output_target(input_elf, output_elf) 411 412 try: 413 with open(input_elf, "rb") as elf_in_fp, open(output_target, "wb+") as elf_out_fp: 414 [elf_header, phdr_table] = preprocess_elf_file(input_elf) 415 416 num_phdrs = elf_header.e_phnum 417 num_shdrs = elf_header.e_shnum 418 phdr_size = elf_header.e_phentsize 419 420 if num_phdrs == 0 or num_phdrs > MAX_PHDR_COUNT: 421 raise RuntimeError("Input ELF has invalid number of program headers.") 422 423 if elf_header.e_shoff == 0 or num_shdrs == 0: 424 raise RuntimeError("Input ELF does not contain a section header table.") 425 426 shdr_table_input = process_section_header(input_elf) 427 shdr_table_output = process_section_header(input_elf) 428 429 last_phdr = phdr_table[num_phdrs - 1] 430 if last_phdr.p_memsz == SWIV_SEG_SIZE_MIN and verify_swiv_seg(elf_in_fp, last_phdr.p_offset): 431 raise RuntimeError("A SWIV segment is detected in the input ELF.") 432 433 last_shdr = shdr_table_input[elf_header.e_shnum - 1] 434 if last_shdr.sh_size == SWIV_SEG_SIZE_MIN and verify_swiv_seg(elf_in_fp, last_shdr.sh_offset): 435 raise RuntimeError("A SWIV section is detected in the input ELF.") 436 437 if is_elf64(elf_header): 438 swiv_shdr = Elf64_Shdr(b'\0' * Elf64_Shdr.s.size) 439 else: 440 swiv_shdr = Elf32_Shdr(b'\0' * Elf32_Shdr.s.size) 441 442 swiv_shdr.sh_name = 0 443 swiv_shdr.sh_type = SWIV_SECTION_TYPE 444 swiv_shdr.sh_flags = 0 445 swiv_shdr.sh_addr = 0 446 swiv_shdr.sh_size = SWIV_SEG_SIZE_MIN 447 swiv_shdr.sh_offset = elf_header.e_shoff + (elf_header.e_shnum + 1) * elf_header.e_shentsize 448 shdr_table_output.append(swiv_shdr) 449 elf_header.e_shnum += 1 450 451 if elf_header.e_phoff != 0: 452 for phdr in phdr_table: 453 file_copy_offset(elf_in_fp, phdr.p_offset, elf_out_fp, phdr.p_offset, phdr.p_filesz) 454 455 elf_out_fp.seek(0) 456 elf_out_fp.write(elf_header.get_packed_data()) 457 458 phdr_start = elf_header.e_phoff 459 for phdr in phdr_table: 460 elf_out_fp.seek(phdr_start) 461 elf_out_fp.write(phdr.get_packed_data()) 462 phdr_start += phdr_size 463 464 for shdr in shdr_table_input[:num_shdrs]: 465 if shdr.sh_type == SHT_NOBITS or shdr.sh_size == 0: 466 continue 467 file_copy_offset(elf_in_fp, shdr.sh_offset, elf_out_fp, shdr.sh_offset, shdr.sh_size) 468 469 shdr_start = elf_header.e_shoff 470 for shdr in shdr_table_output: 471 elf_out_fp.seek(shdr_start) 472 elf_out_fp.write(shdr.get_packed_data()) 473 shdr_start += elf_header.e_shentsize 474 475 elf_out_fp.flush() 476 477 swiv_seg = SWIV_Seg() 478 swiv_seg.crc = crc32_calculate(elf_out_fp, phdr_table) 479 elf_out_fp.seek(swiv_shdr.sh_offset) 480 elf_out_fp.write(swiv_seg.get_packed_data()) 481 482 if temp_output is not None: 483 os.replace(temp_output, output_elf) 484 temp_output = None 485 486 return 0 487 finally: 488 if temp_output is not None and os.path.exists(temp_output): 489 os.unlink(temp_output) 490 491 492 def main(argv): 493 parser = argparse.ArgumentParser(description="Add a Software Image Validation (SWIV) section to an HTP ELF file.") 494 parser.add_argument("-i", "--input", dest="input_file", metavar="INPUT", required=True) 495 parser.add_argument("-o", "--output", dest="output_file", metavar="OUTPUT", required=True) 496 parser.add_argument("-v", "--verbose", action="store_true", help="show calculated CRC") 497 args = parser.parse_args(argv) 498 499 logging.basicConfig( 500 level=logging.INFO if args.verbose else logging.WARNING, 501 format="%(message)s", 502 ) 503 504 try: 505 return swiv_generate(args.input_file, args.output_file) 506 except RuntimeError as exc: 507 logger.error("ERROR: %s", exc) 508 return 2 509 510 511 if __name__ == "__main__": 512 sys.exit(main(sys.argv[1:]))