idf_size.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. #!/usr/bin/env python
  2. #
  3. # esp-idf alternative to "size" to print ELF file sizes, also analyzes
  4. # the linker map file to dump higher resolution details.
  5. #
  6. # Includes information which is not shown in "xtensa-esp32-elf-size",
  7. # or easy to parse from "xtensa-esp32-elf-objdump" or raw map files.
  8. #
  9. # Copyright 2017 Espressif Systems (Shanghai) PTE LTD
  10. #
  11. # Licensed under the Apache License, Version 2.0 (the "License");
  12. # you may not use this file except in compliance with the License.
  13. # You may obtain a copy of the License at
  14. #
  15. # http://www.apache.org/licenses/LICENSE-2.0
  16. #
  17. # Unless required by applicable law or agreed to in writing, software
  18. # distributed under the License is distributed on an "AS IS" BASIS,
  19. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20. # See the License for the specific language governing permissions and
  21. # limitations under the License.
  22. #
  23. import argparse, sys, subprocess, re
  24. import os.path
  25. import pprint
  26. import operator
  27. DEFAULT_TOOLCHAIN_PREFIX = "xtensa-esp32-elf-"
  28. CHIP_SIZES = {
  29. "esp32" : {
  30. "total_iram" : 0x20000,
  31. "total_irom" : 0x330000,
  32. "total_drom" : 0x800000,
  33. # total dram is determined from objdump output
  34. }
  35. }
  36. def scan_to_header(f, header_line):
  37. """ Scan forward in a file until you reach 'header_line', then return """
  38. for line in f:
  39. if line.strip() == header_line:
  40. return
  41. raise RuntimeError("Didn't find line '%s' in file" % header_line)
  42. def load_map_data(map_file):
  43. memory_config = load_memory_config(map_file)
  44. sections = load_sections(map_file)
  45. return memory_config, sections
  46. def output_section_for_address(memory_config, address):
  47. for m in memory_config.values():
  48. if m["origin"] <= address and m["origin"] + m["length"] > address:
  49. return m["name"]
  50. return None
  51. def load_memory_config(map_file):
  52. """ Memory Configuration section is the total size of each output section """
  53. result = {}
  54. scan_to_header(map_file, "Memory Configuration")
  55. RE_MEMORY_SECTION = r"(?P<name>[^ ]+) +0x(?P<origin>[\da-f]+) +0x(?P<length>[\da-f]+)"
  56. for line in map_file:
  57. m = re.match(RE_MEMORY_SECTION, line)
  58. if m is None:
  59. if len(result) == 0:
  60. continue # whitespace or a header, before the content we want
  61. else:
  62. return result # we're at the end of the Memory Configuration
  63. section = {
  64. "name" : m.group("name"),
  65. "origin" : int(m.group("origin"), 16),
  66. "length" : int(m.group("length"), 16),
  67. }
  68. if section["name"] != "*default*":
  69. result[section["name"]] = section
  70. raise RuntimeError("End of file while scanning memory configuration?")
  71. def load_sections(map_file):
  72. """ Load section size information from the MAP file.
  73. Returns a dict of 'sections', where each key is a section name and the value
  74. is a dict with details about this section, including a "sources" key which holds a list of source file line information for each symbol linked into the section.
  75. """
  76. scan_to_header(map_file, "Linker script and memory map")
  77. scan_to_header(map_file, "END GROUP")
  78. sections = {}
  79. section = None
  80. for line in map_file:
  81. # output section header, ie '.iram0.text 0x0000000040080400 0x129a5'
  82. RE_SECTION_HEADER = r"(?P<name>[^ ]+) +0x(?P<address>[\da-f]+) +0x(?P<size>[\da-f]+)$"
  83. m = re.match(RE_SECTION_HEADER, line)
  84. if m is not None: # start of a new section
  85. section = {
  86. "name" : m.group("name"),
  87. "address" : int(m.group("address"), 16),
  88. "size" : int(m.group("size"), 16),
  89. "sources" : [],
  90. }
  91. sections[section["name"]] = section
  92. continue
  93. # source file line, ie
  94. # 0x0000000040080400 0xa4 /home/gus/esp/32/idf/examples/get-started/hello_world/build/esp32/libesp32.a(cpu_start.o)
  95. RE_SOURCE_LINE = r".*? +0x(?P<address>[\da-f]+) +0x(?P<size>[\da-f]+) (?P<archive>.+\.a)\((?P<object_file>.+\.o)\)"
  96. m = re.match(RE_SOURCE_LINE, line)
  97. if section is not None and m is not None: # input source file details
  98. source = {
  99. "size" : int(m.group("size"), 16),
  100. "address" : int(m.group("address"), 16),
  101. "archive" : os.path.basename(m.group("archive")),
  102. "object_file" : m.group("object_file"),
  103. }
  104. source["file"] = "%s:%s" % (source["archive"], source["object_file"])
  105. section["sources"] += [ source ]
  106. return sections
  107. def sizes_by_key(sections, key):
  108. """ Takes a dict of sections (from load_sections) and returns
  109. a dict keyed by 'key' with aggregate output size information.
  110. Key can be either "archive" (for per-archive data) or "file" (for per-file data) in the result.
  111. """
  112. result = {}
  113. for section in sections.values():
  114. for s in section["sources"]:
  115. if not s[key] in result:
  116. result[s[key]] = {}
  117. archive = result[s[key]]
  118. if not section["name"] in archive:
  119. archive[section["name"]] = 0
  120. archive[section["name"]] += s["size"]
  121. return result
  122. def main():
  123. parser = argparse.ArgumentParser("idf_size - a tool to print IDF elf file sizes")
  124. parser.add_argument(
  125. '--toolchain-prefix',
  126. help="Triplet prefix to add before objdump executable",
  127. default=DEFAULT_TOOLCHAIN_PREFIX)
  128. parser.add_argument(
  129. 'map_file', help='MAP file produced by linker',
  130. type=argparse.FileType('r'))
  131. parser.add_argument(
  132. '--archives', help='Print per-archive sizes', action='store_true')
  133. parser.add_argument(
  134. '--files', help='Print per-file sizes', action='store_true')
  135. args = parser.parse_args()
  136. memory_config, sections = load_map_data(args.map_file)
  137. print_summary(memory_config, sections)
  138. if args.archives:
  139. print("Per-archive contributions to ELF file:")
  140. print_detailed_sizes(sections, "archive", "Archive File")
  141. if args.files:
  142. print("Per-file contributions to ELF file:")
  143. print_detailed_sizes(sections, "file", "Object File")
  144. def print_summary(memory_config, sections):
  145. def get_size(section):
  146. try:
  147. return sections[section]["size"]
  148. except KeyError:
  149. return 0
  150. # if linker script changes, these need to change
  151. total_iram = memory_config["iram0_0_seg"]["length"]
  152. total_dram = memory_config["dram0_0_seg"]["length"]
  153. used_data = get_size(".dram0.data")
  154. used_bss = get_size(".dram0.bss")
  155. used_dram = used_data + used_bss
  156. used_iram = sum( get_size(s) for s in sections.keys() if s.startswith(".iram0") )
  157. flash_code = get_size(".flash.text")
  158. flash_rodata = get_size(".flash.rodata")
  159. total_size = used_data + used_iram + flash_code + flash_rodata
  160. print("Total sizes:")
  161. print(" DRAM .data size: %7d bytes" % used_data)
  162. print(" DRAM .bss size: %7d bytes" % used_bss)
  163. print("Used static DRAM: %7d bytes (%7d available, %.1f%% used)" %
  164. (used_dram, total_dram - used_dram,
  165. 100.0 * used_dram / total_dram))
  166. print("Used static IRAM: %7d bytes (%7d available, %.1f%% used)" %
  167. (used_iram, total_iram - used_iram,
  168. 100.0 * used_iram / total_iram))
  169. print(" Flash code: %7d bytes" % flash_code)
  170. print(" Flash rodata: %7d bytes" % flash_rodata)
  171. print("Total image size:~%7d bytes (.bin may be padded larger)" % (total_size))
  172. def print_detailed_sizes(sections, key, header):
  173. sizes = sizes_by_key(sections, key)
  174. sub_heading = None
  175. headings = (header,
  176. "DRAM .data",
  177. "& .bss",
  178. "IRAM",
  179. "Flash code",
  180. "& rodata",
  181. "Total")
  182. print("%24s %10s %6s %6s %10s %8s %7s" % headings)
  183. result = {}
  184. for k in (sizes.keys()):
  185. v = sizes[k]
  186. result[k] = {}
  187. result[k]["data"] = v.get(".dram0.data", 0)
  188. result[k]["bss"] = v.get(".dram0.bss", 0)
  189. result[k]["iram"] = sum(t for (s,t) in v.items() if s.startswith(".iram0"))
  190. result[k]["flash_text"] = v.get(".flash.text", 0)
  191. result[k]["flash_rodata"] = v.get(".flash.rodata", 0)
  192. result[k]["total"] = sum(result[k].values())
  193. def return_total_size(elem):
  194. val = elem[1]
  195. return val["total"]
  196. for k,v in sorted(result.items(), key=return_total_size, reverse=True):
  197. if ":" in k: # print subheadings for key of format archive:file
  198. sh,k = k.split(":")
  199. print("%24s %10d %6d %6d %10d %8d %7d" % (k[:24],
  200. v["data"],
  201. v["bss"],
  202. v["iram"],
  203. v["flash_text"],
  204. v["flash_rodata"],
  205. v["total"]))
  206. if __name__ == "__main__":
  207. main()