idf_size.py 13 KB

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