idf_size.py 11 KB

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