idf_size.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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-2018 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. from __future__ import print_function
  24. from __future__ import unicode_literals
  25. from builtins import dict
  26. import argparse, sys, subprocess, re
  27. import os.path
  28. import pprint
  29. import operator
  30. DEFAULT_TOOLCHAIN_PREFIX = "xtensa-esp32-elf-"
  31. CHIP_SIZES = {
  32. "esp32" : {
  33. "total_iram" : 0x20000,
  34. "total_irom" : 0x330000,
  35. "total_drom" : 0x800000,
  36. # total dram is determined from objdump output
  37. }
  38. }
  39. def scan_to_header(f, header_line):
  40. """ Scan forward in a file until you reach 'header_line', then return """
  41. for line in f:
  42. if line.strip() == header_line:
  43. return
  44. raise RuntimeError("Didn't find line '%s' in file" % header_line)
  45. def load_map_data(map_file):
  46. memory_config = load_memory_config(map_file)
  47. sections = load_sections(map_file)
  48. return memory_config, sections
  49. def load_memory_config(map_file):
  50. """ Memory Configuration section is the total size of each output section """
  51. result = {}
  52. scan_to_header(map_file, "Memory Configuration")
  53. RE_MEMORY_SECTION = r"(?P<name>[^ ]+) +0x(?P<origin>[\da-f]+) +0x(?P<length>[\da-f]+)"
  54. for line in map_file:
  55. m = re.match(RE_MEMORY_SECTION, line)
  56. if m is None:
  57. if len(result) == 0:
  58. continue # whitespace or a header, before the content we want
  59. else:
  60. return result # we're at the end of the Memory Configuration
  61. section = {
  62. "name" : m.group("name"),
  63. "origin" : int(m.group("origin"), 16),
  64. "length" : int(m.group("length"), 16),
  65. }
  66. if section["name"] != "*default*":
  67. result[section["name"]] = section
  68. raise RuntimeError("End of file while scanning memory configuration?")
  69. def load_sections(map_file):
  70. """ Load section size information from the MAP file.
  71. Returns a dict of 'sections', where each key is a section name and the value
  72. 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.
  73. """
  74. scan_to_header(map_file, "Linker script and memory map")
  75. scan_to_header(map_file, "END GROUP")
  76. sections = {}
  77. section = None
  78. sym_backup = None
  79. for line in map_file:
  80. # output section header, ie '.iram0.text 0x0000000040080400 0x129a5'
  81. RE_SECTION_HEADER = r"(?P<name>[^ ]+) +0x(?P<address>[\da-f]+) +0x(?P<size>[\da-f]+)$"
  82. m = re.match(RE_SECTION_HEADER, line)
  83. if m is not None: # start of a new section
  84. section = {
  85. "name" : m.group("name"),
  86. "address" : int(m.group("address"), 16),
  87. "size" : int(m.group("size"), 16),
  88. "sources" : [],
  89. }
  90. sections[section["name"]] = section
  91. continue
  92. # source file line, ie
  93. # 0x0000000040080400 0xa4 /home/gus/esp/32/idf/examples/get-started/hello_world/build/esp32/libesp32.a(cpu_start.o)
  94. RE_SOURCE_LINE = r"\s*(?P<sym_name>\S*).* +0x(?P<address>[\da-f]+) +0x(?P<size>[\da-f]+) (?P<archive>.+\.a)\((?P<object_file>.+\.o)\)"
  95. m = re.match(RE_SOURCE_LINE, line, re.M)
  96. if section is not None and m is not None: # input source file details
  97. sym_name = m.group("sym_name") if len(m.group("sym_name")) > 0 else sym_backup
  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. "sym_name" : sym_name,
  104. }
  105. source["file"] = "%s:%s" % (source["archive"], source["object_file"])
  106. section["sources"] += [ source ]
  107. # In some cases the section name appears on the previous line, back it up in here
  108. RE_SYMBOL_ONLY_LINE = r"^ (?P<sym_name>\S*)$"
  109. m = re.match(RE_SYMBOL_ONLY_LINE, line)
  110. if section is not None and m is not None:
  111. sym_backup = m.group("sym_name")
  112. return sections
  113. def sizes_by_key(sections, key):
  114. """ Takes a dict of sections (from load_sections) and returns
  115. a dict keyed by 'key' with aggregate output size information.
  116. Key can be either "archive" (for per-archive data) or "file" (for per-file data) in the result.
  117. """
  118. result = {}
  119. for section in sections.values():
  120. for s in section["sources"]:
  121. if not s[key] in result:
  122. result[s[key]] = {}
  123. archive = result[s[key]]
  124. if not section["name"] in archive:
  125. archive[section["name"]] = 0
  126. archive[section["name"]] += s["size"]
  127. return result
  128. def main():
  129. parser = argparse.ArgumentParser("idf_size - a tool to print IDF elf file sizes")
  130. parser.add_argument(
  131. '--toolchain-prefix',
  132. help="Triplet prefix to add before objdump executable",
  133. default=DEFAULT_TOOLCHAIN_PREFIX)
  134. parser.add_argument(
  135. 'map_file', help='MAP file produced by linker',
  136. type=argparse.FileType('r'))
  137. parser.add_argument(
  138. '--archives', help='Print per-archive sizes', action='store_true')
  139. parser.add_argument(
  140. '--archive_details', help='Print detailed symbols per archive')
  141. parser.add_argument(
  142. '--files', help='Print per-file sizes', action='store_true')
  143. args = parser.parse_args()
  144. memory_config, sections = load_map_data(args.map_file)
  145. print_summary(memory_config, sections)
  146. if args.archives:
  147. print("Per-archive contributions to ELF file:")
  148. print_detailed_sizes(sections, "archive", "Archive File")
  149. if args.files:
  150. print("Per-file contributions to ELF file:")
  151. print_detailed_sizes(sections, "file", "Object File")
  152. if args.archive_details:
  153. print("Symbols within the archive:", args.archive_details, "(Not all symbols may be reported)")
  154. print_archive_symbols(sections, args.archive_details)
  155. def print_summary(memory_config, sections):
  156. def get_size(section):
  157. try:
  158. return sections[section]["size"]
  159. except KeyError:
  160. return 0
  161. # if linker script changes, these need to change
  162. total_iram = memory_config["iram0_0_seg"]["length"]
  163. total_dram = memory_config["dram0_0_seg"]["length"]
  164. used_data = get_size(".dram0.data")
  165. used_bss = get_size(".dram0.bss")
  166. used_dram = used_data + used_bss
  167. used_iram = sum( get_size(s) for s in sections if s.startswith(".iram0") )
  168. flash_code = get_size(".flash.text")
  169. flash_rodata = get_size(".flash.rodata")
  170. total_size = used_data + used_iram + flash_code + flash_rodata
  171. print("Total sizes:")
  172. print(" DRAM .data size: %7d bytes" % used_data)
  173. print(" DRAM .bss size: %7d bytes" % used_bss)
  174. print("Used static DRAM: %7d bytes (%7d available, %.1f%% used)" %
  175. (used_dram, total_dram - used_dram,
  176. 100.0 * used_dram / total_dram))
  177. print("Used static IRAM: %7d bytes (%7d available, %.1f%% used)" %
  178. (used_iram, total_iram - used_iram,
  179. 100.0 * used_iram / total_iram))
  180. print(" Flash code: %7d bytes" % flash_code)
  181. print(" Flash rodata: %7d bytes" % flash_rodata)
  182. print("Total image size:~%7d bytes (.bin may be padded larger)" % (total_size))
  183. def print_detailed_sizes(sections, key, header):
  184. sizes = sizes_by_key(sections, key)
  185. sub_heading = None
  186. headings = (header,
  187. "DRAM .data",
  188. "& .bss",
  189. "IRAM",
  190. "Flash code",
  191. "& rodata",
  192. "Total")
  193. print("%24s %10s %6s %6s %10s %8s %7s" % headings)
  194. result = {}
  195. for k in sizes:
  196. v = sizes[k]
  197. result[k] = {}
  198. result[k]["data"] = v.get(".dram0.data", 0)
  199. result[k]["bss"] = v.get(".dram0.bss", 0)
  200. result[k]["iram"] = sum(t for (s,t) in v.items() if s.startswith(".iram0"))
  201. result[k]["flash_text"] = v.get(".flash.text", 0)
  202. result[k]["flash_rodata"] = v.get(".flash.rodata", 0)
  203. result[k]["total"] = sum(result[k].values())
  204. def return_total_size(elem):
  205. val = elem[1]
  206. return val["total"]
  207. def return_header(elem):
  208. return elem[0]
  209. s = sorted(list(result.items()), key=return_header)
  210. # do a secondary sort in order to have consistent order (for diff-ing the output)
  211. for k,v in sorted(s, key=return_total_size, reverse=True):
  212. if ":" in k: # print subheadings for key of format archive:file
  213. sh,k = k.split(":")
  214. print("%24s %10d %6d %6d %10d %8d %7d" % (k[:24],
  215. v["data"],
  216. v["bss"],
  217. v["iram"],
  218. v["flash_text"],
  219. v["flash_rodata"],
  220. v["total"]))
  221. def print_archive_symbols(sections, archive):
  222. interested_sections = [".dram0.data", ".dram0.bss", ".iram0.text", ".iram0.vectors", ".flash.text", ".flash.rodata"]
  223. result = {}
  224. for t in interested_sections:
  225. result[t] = {}
  226. for section in sections.values():
  227. section_name = section["name"]
  228. if section_name not in interested_sections:
  229. continue
  230. for s in section["sources"]:
  231. if archive != s["archive"]:
  232. continue
  233. s["sym_name"] = re.sub("(.text.|.literal.|.data.|.bss.|.rodata.)", "", s["sym_name"]);
  234. result[section_name][s["sym_name"]] = result[section_name].get(s["sym_name"], 0) + s["size"]
  235. for t in interested_sections:
  236. print("\nSymbols from section:", t)
  237. section_total = 0
  238. s = sorted(list(result[t].items()), key=lambda k_v: k_v[0])
  239. # do a secondary sort in order to have consistent order (for diff-ing the output)
  240. for key,val in sorted(s, key=lambda k_v: k_v[1], reverse=True):
  241. print(("%s(%d)"% (key.replace(t + ".", ""), val)), end=' ')
  242. section_total += val
  243. print("\nSection total:",section_total)
  244. if __name__ == "__main__":
  245. main()