flash_ram_usage.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. """
  2. File name : keil_map_parser.py
  3. Create date : 2025-02-19
  4. Author : Panchip
  5. Description : Used to parse the keil map file to obtain the usage of FLASH and RAM.
  6. """
  7. import sys
  8. import re
  9. import os
  10. __version__ = '1.0'
  11. if len(sys.argv) != 2:
  12. print("Usage: python keil_map_parser.py <keil-map-file>")
  13. map_file = sys.argv[1]
  14. # print("map file path:", map_file)
  15. def getFileData(file_path):
  16. try:
  17. with open(file_path, "r") as file:
  18. file_size = os.path.getsize(file_path)
  19. # print(f"file_size: {file_size} B")
  20. file_data = file.read(file_size)
  21. file.close()
  22. return file_data
  23. except FileNotFoundError:
  24. print("Error: open map file error!!!")
  25. return ""
  26. map_data = getFileData(map_file)
  27. if len(map_data) == 0:
  28. print("No map data found")
  29. exit(1)
  30. obj1 = re.compile(r'Load Region (?P<section_name>.*?) \(Base: (.*?), Size: (?P<used_size>.*?), Max: (?P<flash_max_size>.*?), ABSOLUTE',re.S)
  31. obj2 = re.compile(r"Execution Region (?P<section_name>.*?) \(Exec base: (?P<base_addr>.*?), Load base: (.*?), Size: (?P<usage_size>.*?), Max: (?P<region_size>.*?), ABSOLUTE", re.S)
  32. obj3 = re.compile(r"0x(.*?) \s*0x(.*?) \s*0x(?P<ramfunc_size>.*?) Code\s*RO(.*?)\.ramfunc")
  33. # find LOAD Flash section
  34. flash_max_size = 0xFFFFFF
  35. result = re.finditer(obj1, map_data)
  36. for it in result:
  37. flash_max_size = int(it.group("flash_max_size"), 16)
  38. # find .ramfunc
  39. ram_func_size = 0
  40. result = re.finditer(obj3, map_data)
  41. for item in result:
  42. ram_func_size += int(item.group("ramfunc_size"), 16)
  43. print("Memory Usage Info:")
  44. print("*"*80)
  45. print(" Memory region\t\tStart Addr\tUsed Size\tRegion Size\t %age Used")
  46. # find others section
  47. result = re.finditer(obj2, map_data)
  48. for item in result:
  49. base_addr = int(item.group("base_addr"),16)
  50. section_name = item.group("section_name")
  51. usage_size = int(item.group("usage_size"),16)
  52. region_size = int(item.group("region_size"),16)
  53. if section_name == "IMG_HEADER" or section_name == "FLASH_TEXT_ENC" or section_name == "FLASH_TEXT_1":
  54. continue
  55. if section_name == "FLASH_TEXT" or section_name == "FLASH_TEXT_0" or section_name == "ER_IROM1":
  56. region_size = flash_max_size
  57. usage_size += ram_func_size
  58. print(f" {section_name:<13}\t\t0x{base_addr:08X}\t{usage_size:>8} B\t{region_size/1024:>8.2f} KB\t{usage_size/region_size*100: >8.2f} %")
  59. print("*"*80)