app_pkg.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # -*- coding: utf-8 -*-
  2. from __future__ import print_function # 确保 print 在 Python 2 和 3 中都是函数
  3. import os
  4. import struct
  5. import zlib
  6. import re
  7. import sys
  8. MAGIC = struct.unpack("<I", b"app\0")[0] # 使用 b"" 定义字节串
  9. LOAD_ADDR = 0x4000000 + 0x40
  10. APP_SIZE = 0x1000000 # 16M
  11. VERSION_IDENT = 0x11112223
  12. def parse_map_for_entrypoint(map_file):
  13. with open(map_file, "r") as f:
  14. content = f.read()
  15. match = re.search(r"(\b0x[0-9a-fA-F]+)\s+_START", content)
  16. if match:
  17. return int(match.group(1), 16)
  18. raise ValueError("not find .text.app_entrypoint")
  19. def compute_crc32(file_path):
  20. with open(file_path, "rb") as f:
  21. data = f.read()
  22. return zlib.crc32(data) & 0xFFFFFFFF # 确保结果是无符号的 32 位整数
  23. def pack_bin(build_path, debug_mode=0):
  24. bin_file = os.path.join(build_path, 'app.bin')
  25. map_file = os.path.join(build_path, 'app.map')
  26. if debug_mode:
  27. out_file = os.path.join(build_path, 'app_debug.img')
  28. else:
  29. out_file = os.path.join(build_path, 'app.img')
  30. start_addr = parse_map_for_entrypoint(map_file)
  31. with open(bin_file, "rb") as f:
  32. bin_data = f.read()
  33. crc_value = compute_crc32(bin_file)
  34. size = os.path.getsize(bin_file)
  35. # 定义 8 个保留字段,初始化为 0,并添加 crc_value
  36. res = [0] * 7 + [crc_value]
  37. # 按照结构体 smodule_head 的排布打包头信息
  38. header = struct.pack("<I I I I I 11I",
  39. MAGIC, # magic
  40. LOAD_ADDR, # load_addr
  41. start_addr, # start_addr
  42. size, # size
  43. 1, # update
  44. 0, # download
  45. debug_mode, # debug
  46. VERSION_IDENT, # 版本标识符
  47. *res) # res[7] + crc_value
  48. with open(out_file, "wb") as f:
  49. f.write(header)
  50. f.write(bin_data)
  51. print("%s firmware packaged success" %out_file)
  52. print("info:")
  53. print(" {:<10}: 0x{:08X}".format("start_addr", start_addr))
  54. print(" {:<10}: 0x{:08X}".format("load_addr", LOAD_ADDR))
  55. print(" {:<10}: 0x{:08X}".format("size", size))