]> granicus.if.org Git - esp-idf/blob - tools/idf_size.py
Merge branch 'bugfix/esp_ping_ms_pr1638' 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 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 import operator
27
28 DEFAULT_TOOLCHAIN_PREFIX = "xtensa-esp32-elf-"
29
30 CHIP_SIZES = {
31     "esp32" : {
32         "total_iram" : 0x20000,
33         "total_irom" : 0x330000,
34         "total_drom" : 0x800000,
35         # total dram is determined from objdump output
36     }
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
46 def load_map_data(map_file):
47     memory_config = load_memory_config(map_file)
48     sections  = load_sections(map_file)
49     return memory_config, sections
50
51 def output_section_for_address(memory_config, address):
52     for m in memory_config.values():
53         if m["origin"] <= address and m["origin"] + m["length"] > address:
54             return m["name"]
55     return None
56
57 def load_memory_config(map_file):
58     """ Memory Configuration section is the total size of each output section """
59     result = {}
60     scan_to_header(map_file, "Memory Configuration")
61     RE_MEMORY_SECTION = r"(?P<name>[^ ]+) +0x(?P<origin>[\da-f]+) +0x(?P<length>[\da-f]+)"
62     for line in map_file:
63         m = re.match(RE_MEMORY_SECTION, line)
64         if m is None:
65             if len(result) == 0:
66                 continue  # whitespace or a header, before the content we want
67             else:
68                 return result  # we're at the end of the Memory Configuration
69         section = {
70             "name" : m.group("name"),
71             "origin" : int(m.group("origin"), 16),
72             "length" : int(m.group("length"), 16),
73         }
74         if section["name"] != "*default*":
75             result[section["name"]] = section
76     raise RuntimeError("End of file while scanning memory configuration?")
77
78 def load_sections(map_file):
79     """ Load section size information from the MAP file.
80
81     Returns a dict of 'sections', where each key is a section name and the value
82     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.
83     """
84     scan_to_header(map_file, "Linker script and memory map")
85     scan_to_header(map_file, "END GROUP")
86     sections = {}
87     section = 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".*? +0x(?P<address>[\da-f]+) +0x(?P<size>[\da-f]+) (?P<archive>.+\.a)\((?P<object_file>.+\.o)\)"
105         m = re.match(RE_SOURCE_LINE, line)
106         if section is not None and m is not None:  # input source file details
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             }
113             source["file"] = "%s:%s" % (source["archive"], source["object_file"])
114             section["sources"] += [ source ]
115
116     return sections
117
118 def sizes_by_key(sections, key):
119     """ Takes a dict of sections (from load_sections) and returns
120     a dict keyed by 'key' with aggregate output size information.
121
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
135 def main():
136     parser = argparse.ArgumentParser("idf_size - a tool to print IDF elf file sizes")
137
138     parser.add_argument(
139         '--toolchain-prefix',
140         help="Triplet prefix to add before objdump executable",
141         default=DEFAULT_TOOLCHAIN_PREFIX)
142
143     parser.add_argument(
144         'map_file', help='MAP file produced by linker',
145         type=argparse.FileType('r'))
146
147     parser.add_argument(
148         '--archives', help='Print per-archive sizes', action='store_true')
149
150     parser.add_argument(
151         '--files', help='Print per-file sizes', action='store_true')
152
153     args = parser.parse_args()
154
155     memory_config, sections = load_map_data(args.map_file)
156     print_summary(memory_config, sections)
157
158     if args.archives:
159         print("Per-archive contributions to ELF file:")
160         print_detailed_sizes(sections, "archive", "Archive File")
161     if args.files:
162         print("Per-file contributions to ELF file:")
163         print_detailed_sizes(sections, "file", "Object File")
164
165 def print_summary(memory_config, sections):
166     def get_size(section):
167         try:
168             return sections[section]["size"]
169         except KeyError:
170             return 0
171
172     # if linker script changes, these need to change
173     total_iram = memory_config["iram0_0_seg"]["length"]
174     total_dram = memory_config["dram0_0_seg"]["length"]
175     used_data = get_size(".dram0.data")
176     used_bss = get_size(".dram0.bss")
177     used_dram = used_data + used_bss
178     used_iram = sum( get_size(s) for s in sections.keys() if s.startswith(".iram0") )
179     flash_code = get_size(".flash.text")
180     flash_rodata = get_size(".flash.rodata")
181     total_size = used_data + used_iram + flash_code + flash_rodata
182
183     print("Total sizes:")
184     print(" DRAM .data size: %7d bytes" % used_data)
185     print(" DRAM .bss  size: %7d bytes" % used_bss)
186     print("Used static DRAM: %7d bytes (%7d available, %.1f%% used)" %
187           (used_dram, total_dram - used_dram,
188            100.0 * used_dram / total_dram))
189     print("Used static IRAM: %7d bytes (%7d available, %.1f%% used)" %
190           (used_iram, total_iram - used_iram,
191            100.0 * used_iram / total_iram))
192     print("      Flash code: %7d bytes" % flash_code)
193     print("    Flash rodata: %7d bytes" % flash_rodata)
194     print("Total image size:~%7d bytes (.bin may be padded larger)" % (total_size))
195
196 def print_detailed_sizes(sections, key, header):
197     sizes = sizes_by_key(sections, key)
198
199     sub_heading = None
200     headings = (header,
201                 "DRAM .data",
202                 "& .bss",
203                 "IRAM",
204                 "Flash code",
205                 "& rodata",
206                 "Total")
207     print("%24s %10s %6s %6s %10s %8s %7s" % headings)
208     result = {}
209     for k in (sizes.keys()):
210         v = sizes[k]
211         result[k] = {}
212         result[k]["data"] = v.get(".dram0.data", 0)
213         result[k]["bss"] = v.get(".dram0.bss", 0)
214         result[k]["iram"] = sum(t for (s,t) in v.items() if s.startswith(".iram0"))
215         result[k]["flash_text"] = v.get(".flash.text", 0)
216         result[k]["flash_rodata"] = v.get(".flash.rodata", 0)
217         result[k]["total"] = sum(result[k].values())
218
219     def return_total_size(elem):
220         val = elem[1]
221         return val["total"]
222     for k,v in sorted(result.items(), key=return_total_size, reverse=True):
223         if ":" in k:  # print subheadings for key of format archive:file
224             sh,k = k.split(":")
225         print("%24s %10d %6d %6d %10d %8d %7d" % (k[:24],
226                                                   v["data"],
227                                                   v["bss"],
228                                                   v["iram"],
229                                                   v["flash_text"],
230                                                   v["flash_rodata"],
231                                                   v["total"]))
232
233 if __name__ == "__main__":
234     main()
235