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