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