idf_size.py 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176
  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. # SPDX-FileCopyrightText: 2017-2022 Espressif Systems (Shanghai) CO LTD
  10. # SPDX-License-Identifier: Apache-2.0
  11. #
  12. import argparse
  13. import collections
  14. import json
  15. import os.path
  16. import re
  17. import sys
  18. from typing import Any, Callable, Collection, Dict, Iterable, List, Optional, TextIO, Tuple, Union
  19. import yaml
  20. class Section(Dict):
  21. # define for python type hints
  22. size: int
  23. address: int
  24. name: str
  25. sources: List[Dict]
  26. SectionDict = Dict[str, Section]
  27. try:
  28. basestring
  29. except NameError:
  30. basestring = str
  31. GLOBAL_JSON_INDENT = 4
  32. GLOBAL_JSON_SEPARATORS = (',', ': ')
  33. class MemRegions(object):
  34. """
  35. Regions determined by the chip target.
  36. """
  37. # DIRAM is not added here. The DIRAM is indicated by the `secondary_addr` of each MemRegDef
  38. (DRAM_ID, IRAM_ID, CACHE_D_ID, CACHE_I_ID, RTC_FAST_D_ID, RTC_FAST_I_ID, RTC_SLOW_D_ID) = range(7)
  39. # The order of variables in the tuple is the same as in the soc_memory_layout.c files
  40. MemRegDef = collections.namedtuple('MemRegDef', ['primary_addr', 'length', 'type', 'secondary_addr'])
  41. class Region(object):
  42. # Helper class to store region information
  43. def __init__(self, start: int, length: int, region: 'MemRegions.MemRegDef', section: Optional[str]=None) -> None:
  44. self.start = start
  45. self.len = length
  46. self.region = region
  47. self.section = section
  48. @staticmethod
  49. def get_mem_regions(target: str) -> List:
  50. """
  51. Get memory regions for specific target
  52. """
  53. # The target specific memory structure is deduced from soc_memory_types defined in
  54. # $IDF_PATH/components/soc/**/soc_memory_layout.c files.
  55. MemRegDef = MemRegions.MemRegDef
  56. def change_to_proper_format(length: Union[str, bytes]) -> Any:
  57. '''
  58. Change `length` if it is string like `'0x8000 + 6 * 0x10000'` to resolve of this math equation
  59. or if `length` is number function return it without changing.
  60. '''
  61. try:
  62. return eval(length)
  63. except TypeError:
  64. return length
  65. def get_mem_reg_def(chip_info: Dict, memory_reg: str) -> Tuple:
  66. chip_info[memory_reg]['secondary_address'] = chip_info[memory_reg].get('secondary_address') or 0
  67. return MemRegDef(chip_info[memory_reg]['primary_address'], change_to_proper_format(chip_info[memory_reg]['length']),
  68. getattr(MemRegions, memory_reg.strip('_12') + '_ID'), chip_info[memory_reg]['secondary_address'])
  69. try:
  70. with open(os.path.join(os.path.dirname(__file__), 'idf_size_yaml', target + '_data_info.yaml'), 'r') as stream:
  71. chip_info = (yaml.safe_load(stream))
  72. except FileNotFoundError:
  73. raise RuntimeError('Target not detected.')
  74. return sorted([get_mem_reg_def(chip_info, item) for item in chip_info])
  75. def __init__(self, target: str) -> None:
  76. self.chip_mem_regions = self.get_mem_regions(target)
  77. if not self.chip_mem_regions:
  78. raise RuntimeError('Target {} is not implemented in idf_size'.format(target))
  79. def _get_first_region(self, start: int, length: int) -> Tuple[Union['MemRegions.MemRegDef', None], int]:
  80. for region in self.chip_mem_regions: # type: ignore
  81. if region.primary_addr <= start < region.primary_addr + region.length:
  82. return (region, length)
  83. if region.secondary_addr and region.secondary_addr <= start < region.secondary_addr + region.length:
  84. return (region, length)
  85. print('WARNING: Given section not found in any memory region.')
  86. print('Check whether the LD file is compatible with the definitions in get_mem_regions in idf_size.py')
  87. return (None, length)
  88. def _get_regions(self, start: int, length: int, name: Optional[str]=None) -> List:
  89. ret = []
  90. while length > 0:
  91. (region, cur_len) = self._get_first_region(start, length)
  92. if region is None:
  93. # skip regions that not in given section
  94. length -= cur_len
  95. start += cur_len
  96. continue
  97. ret.append(MemRegions.Region(start, cur_len, region, name))
  98. length -= cur_len
  99. start += cur_len
  100. return ret
  101. def fit_segments_into_regions(self, segments: Dict) -> List:
  102. region_list = []
  103. for segment in segments.values():
  104. sorted_segments = self._get_regions(segment['origin'], segment['length'])
  105. region_list.extend(sorted_segments)
  106. return region_list
  107. def fit_sections_into_regions(self, sections: Dict) -> List:
  108. region_list = []
  109. for section in sections.values():
  110. sorted_sections = self._get_regions(section['address'], section['size'], section['name'])
  111. region_list.extend(sorted_sections)
  112. return region_list
  113. class LinkingSections(object):
  114. _section_type_dict = {key: re.compile(value) for key, value in {
  115. 'text': r'.*\.text',
  116. 'data': r'.*\.data',
  117. 'bss': r'.*\.bss',
  118. 'rodata': r'.*\.rodata',
  119. 'noinit': r'.*noinit',
  120. 'vectors': r'.*\.vectors',
  121. 'flash': r'.*flash.*',
  122. }.items()}
  123. @staticmethod
  124. def in_section(section: str, section_name_or_list: Union[str, Iterable]) -> bool:
  125. """
  126. Check if section in section_name_or_list
  127. """
  128. if isinstance(section_name_or_list, basestring):
  129. section_name_or_list = [section_name_or_list]
  130. for section_name in section_name_or_list:
  131. if LinkingSections._section_type_dict[section_name].match(section):
  132. return True
  133. return False
  134. @staticmethod
  135. def filter_sections(sections: Dict) -> Dict:
  136. return {key: v for key, v in sections.items()
  137. if LinkingSections.in_section(key, LinkingSections._section_type_dict.keys())}
  138. @staticmethod
  139. def get_display_name_order(section_name_list: List[str]) -> Tuple[List[str], List[str]]:
  140. '''
  141. Return two lists, in the suggested display order.
  142. First list is the reordered section_name_list, second list is the suggested display name, corresponding to the first list
  143. '''
  144. def get_memory_name(split_name: List) -> Tuple[str, str]:
  145. memory_name = '.{}'.format(split_name[1])
  146. display_name = section
  147. for seg_name in ['iram','dram','flash']:
  148. if seg_name in split_name[1]:
  149. memory_name = '.{}'.format(seg_name)
  150. seg_name = seg_name.upper() if seg_name != 'flash' else seg_name.capitalize()
  151. display_name = ''.join([seg_name,
  152. split_name[1].replace('iram', '') if seg_name == 'IRAM' else '',
  153. ' .{}'.format(split_name[2]) if len(split_name) > 2 else ''])
  154. return memory_name, display_name
  155. ordered_name_list = sorted(section_name_list)
  156. display_name_list = ordered_name_list.copy()
  157. memory_name = ''
  158. ordered_name_list = sort_dict(ordered_name_list)
  159. for i, section in enumerate(ordered_name_list):
  160. if memory_name and section.startswith(memory_name):
  161. # If the section has same memory type with the previous one, use shorter name
  162. display_name_list[i] = section.replace(memory_name, '& ')
  163. continue
  164. memory_name = ''
  165. split_name = section.split('.')
  166. if len(split_name) > 1:
  167. # If the section has a memory type, update the type and try to display the type properly
  168. assert split_name[0] == '', 'Unexpected section name "{}"'.format(section)
  169. memory_name, display_name_list[i] = get_memory_name(split_name)
  170. continue
  171. # Otherwise use its original name
  172. display_name_list[i] = section
  173. return ordered_name_list, display_name_list
  174. def scan_to_header(file: Iterable, header_line: str) -> None:
  175. """ Scan forward in a file until you reach 'header_line', then return """
  176. for line in file:
  177. if line.strip() == header_line:
  178. return
  179. raise RuntimeError("Didn't find line '%s' in file" % header_line)
  180. def format_json(json_object: Dict) -> str:
  181. return json.dumps(json_object,
  182. allow_nan=True,
  183. indent=GLOBAL_JSON_INDENT,
  184. separators=GLOBAL_JSON_SEPARATORS) + os.linesep
  185. def load_map_data(map_file: TextIO) -> Tuple[str, Dict, Dict]:
  186. segments = load_segments(map_file)
  187. detected_chip = detect_target_chip(map_file)
  188. sections = load_sections(map_file)
  189. # Exclude the dummy and .text_end section, which usually means shared region among I/D buses
  190. for key in list(sections.keys()):
  191. if key.endswith(('dummy', '.text_end')):
  192. sections.pop(key)
  193. return detected_chip, segments, sections
  194. def load_segments(map_file: TextIO) -> Dict:
  195. """ Memory Configuration section is the total size of each segment """
  196. result = {} # type: Dict[Any, Dict]
  197. scan_to_header(map_file, 'Memory Configuration')
  198. RE_MEMORY_SECTION = re.compile(r'(?P<name>[^ ]+) +0x(?P<origin>[\da-f]+) +0x(?P<length>[\da-f]+)')
  199. for line in map_file:
  200. match_section = RE_MEMORY_SECTION.match(line)
  201. if match_section is None:
  202. if len(result) == 0:
  203. continue # whitespace or a header, before the content we want
  204. else:
  205. return result # we're at the end of the Memory Configuration
  206. segment = {
  207. 'name': match_section.group('name'),
  208. 'origin': int(match_section.group('origin'), 16),
  209. 'length': int(match_section.group('length'), 16),
  210. }
  211. if segment['name'] != '*default*':
  212. result[segment['name']] = segment
  213. raise RuntimeError('End of file while scanning memory configuration?')
  214. def detect_target_chip(map_file: Iterable) -> str:
  215. ''' Detect target chip based on the target archive name in the linker script part of the MAP file '''
  216. scan_to_header(map_file, 'Linker script and memory map')
  217. RE_TARGET = re.compile(r'IDF_TARGET_(\S*) =')
  218. # For back-compatible with cmake in idf version before 5.0
  219. RE_TARGET_CMAKEv4x = re.compile(r'project_elf_src_(\S*)\.c.obj')
  220. # For back-compatible with make
  221. RE_TARGET_MAKE = re.compile(r'^LOAD .*?/xtensa-([^-]+)-elf/')
  222. for line in map_file:
  223. match_target = RE_TARGET.search(line)
  224. if match_target:
  225. return match_target.group(1).lower()
  226. match_target = RE_TARGET_CMAKEv4x.search(line)
  227. if match_target:
  228. return match_target.group(1)
  229. match_target = RE_TARGET_MAKE.search(line)
  230. if match_target:
  231. return match_target.group(1)
  232. line = line.strip()
  233. # There could be empty line(s) between the "Linker script and memory map" header and "LOAD lines". Therefore,
  234. # line stripping and length is checked as well. The "LOAD lines" are between START GROUP and END GROUP for
  235. # older MAP files.
  236. if not line.startswith(('LOAD', 'START GROUP', 'END GROUP')) and len(line) > 0:
  237. # This break is a failsafe to not process anything load_sections() might want to analyze.
  238. break
  239. raise RuntimeError('Target not detected')
  240. def load_sections(map_file: TextIO) -> Dict:
  241. """ Load section size information from the MAP file.
  242. Returns a dict of 'sections', where each key is a section name and the value
  243. is a dict with details about this section, including a "sources" key which holds a list of source file line
  244. information for each symbol linked into the section.
  245. There are two kinds of lines:
  246. - symbol_only: [optional space]<sym_name>
  247. - full line: [optional space][optional sym_name] <address> <size> [optional file_info]
  248. If <sym_name> doesn't exist, ues the symbol name from the symbol_only line above
  249. If the line is the starting of a section, the <file> should be empty, otherwise if the line is for a source
  250. line, the <file> must exist, or the <sym_name> should be is no *fill*. This rule is used to tell sections from
  251. source lines.
  252. """
  253. # Check for lines which only contain the sym name (and rest is on following lines)
  254. RE_SYMBOL_ONLY_LINE = re.compile(r'^\s*(?P<sym_name>\S*)$')
  255. # Fast check to see if line is a potential source line before running the slower full regex against it
  256. RE_PRE_FILTER = re.compile(r'.*0x[\da-f]+\s*0x[\da-f]+.*')
  257. # source file line, ie
  258. # 0x0000000040080400 0xa4 /home/gus/esp/32/idf/examples/get-started/hello_world/build/esp32/libesp32.a(cpu_start.o)
  259. # cmake build system links some object files directly, not part of any archive, so make that part optional
  260. # .xtensa.info 0x0000000000000000 0x38 CMakeFiles/hello_world.elf.dir/project_elf_src.c.obj
  261. # *fill* 0x00000000400e2967 0x1
  262. RE_FULL_LINE = re.compile(r'\s*(?P<sym_name>\S*) +0x(?P<address>[\da-f]+) +0x(?P<size>[\da-f]+)\s*(?P<file>.*)$')
  263. # Extract archive and object_file from the file_info field
  264. # The object file extention (.obj or .o) is optional including the dot. This is necessary for some third-party
  265. # libraries. Since the dot is optional and the search gready the parsing of the object name must stop at ). Hence
  266. # the [^ )] part of the regex.
  267. RE_FILE = re.compile(r'((?P<archive>[^ ]+\.a)?\(?(?P<object_file>[^ )]+(\.(o|obj))?)\)?)')
  268. def dump_src_line(src: Dict) -> str:
  269. return '%s(%s) addr: 0x%08x, size: 0x%x+%d' % (src['sym_name'], src['file'], src['address'], src['size'], src['fill'])
  270. sections = {} # type: Dict[Any, Dict]
  271. section = {} # type: Dict[str, Any]
  272. sym_backup = ''
  273. for line in map_file:
  274. if line.strip() == 'Cross Reference Table':
  275. # Stop processing lines because we are at the next section in the map file
  276. break
  277. match_line = RE_SYMBOL_ONLY_LINE.match(line)
  278. if match_line:
  279. # In some cases the section name appears on the previous line, back it up in here
  280. sym_backup = match_line.group('sym_name')
  281. continue
  282. if not RE_PRE_FILTER.match(line):
  283. # Line does not match our quick check, so skip to next line
  284. continue
  285. match_line = RE_FULL_LINE.match(line)
  286. if not match_line:
  287. assert not sym_backup, 'Symbol only line must be followed by a line with address and size'
  288. continue
  289. name = match_line.group('sym_name') if match_line.group('sym_name') else sym_backup
  290. sym_backup = ''
  291. is_section = not match_line.group('file') and name != '*fill*'
  292. if is_section:
  293. # section
  294. section = {
  295. 'name': name,
  296. 'address': int(match_line.group('address'), 16),
  297. 'size': int(match_line.group('size'), 16),
  298. 'sources': [],
  299. }
  300. sections[name] = section
  301. else:
  302. # symbol
  303. if not section:
  304. continue
  305. # There are some source lines in rodata section doesn't actually take any space, but have size
  306. # Make size of those sections zero
  307. srcs = section['sources'] # type: List[Dict]
  308. if srcs:
  309. last_src = srcs[-1]
  310. if last_src['size'] > 0 and last_src['address'] == int(match_line.group('address'), 16):
  311. if section['name'] not in ['.comment', '.debug_str', '.debug_line_str'] and 'rodata' not in last_src['sym_name']:
  312. raise RuntimeError('Due to overlap with following lines, size of the line set to 0:\n %s' % dump_src_line(last_src))
  313. last_src['size'] = 0
  314. # Count the padding size into the last valid (size > 0) source in the section
  315. if name == '*fill*':
  316. for src in reversed(srcs):
  317. if src['size'] > 0:
  318. src['fill'] += int(match_line.group('size'), 16)
  319. break
  320. continue
  321. # Extract archive and file information
  322. match_arch_and_file = RE_FILE.match(match_line.group('file'))
  323. assert match_arch_and_file, 'Archive and file information not found for "{}"'.format(match_line.group('file'))
  324. archive = match_arch_and_file.group('archive')
  325. if archive is None:
  326. # optional named group "archive" was not matched, so assign a value to it
  327. archive = '(exe)'
  328. file = match_arch_and_file.group('object_file')
  329. assert name
  330. source = {
  331. 'size': int(match_line.group('size'), 16),
  332. 'address': int(match_line.group('address'), 16),
  333. 'archive': os.path.basename(archive),
  334. 'object_file': os.path.basename(file),
  335. 'sym_name': name,
  336. 'fill': 0, # padding size ofter the source
  337. }
  338. source['file'] = '%s:%s' % (source['archive'], source['object_file'])
  339. section['sources'].append(source) # type: ignore
  340. # Validate the map file
  341. for section in sections.values():
  342. src_curr = {} # type: Dict[str, Any]
  343. for src in section['sources']:
  344. if src['size'] == 0:
  345. continue
  346. expected_addr = src_curr['address'] + src_curr['size'] + src_curr['fill'] if src_curr else section['sources'][0]['address']
  347. if src['address'] != expected_addr:
  348. print('Warning: source line overlap:')
  349. print(' ' + dump_src_line(src_curr))
  350. print(' ' + dump_src_line(src))
  351. src_curr = src
  352. return sections
  353. def check_target(target: str, map_file: TextIO) -> None:
  354. if target is None:
  355. raise RuntimeError('The target chip cannot be detected for {}. '
  356. 'Please report the issue.'.format(map_file.name))
  357. def main() -> None:
  358. parser = argparse.ArgumentParser(description='idf_size - a tool to print size information from an IDF MAP file')
  359. parser.add_argument(
  360. '--json',
  361. help='Output results as JSON',
  362. action='store_true')
  363. parser.add_argument(
  364. 'map_file', help='MAP file produced by linker',
  365. type=argparse.FileType('r'))
  366. parser.add_argument(
  367. '--archives', help='Print per-archive sizes', action='store_true')
  368. parser.add_argument(
  369. '--archive_details', help='Print detailed symbols per archive')
  370. parser.add_argument(
  371. '--files', help='Print per-file sizes', action='store_true')
  372. parser.add_argument(
  373. '--target', help='Set target chip', default=None)
  374. parser.add_argument(
  375. '--diff', help='Show the differences in comparison with another MAP file',
  376. metavar='ANOTHER_MAP_FILE',
  377. default=None,
  378. dest='another_map_file')
  379. parser.add_argument(
  380. '-o',
  381. '--output-file',
  382. type=argparse.FileType('w'),
  383. default=sys.stdout,
  384. help='Print output to the specified file instead of stdout')
  385. args = parser.parse_args()
  386. detected_target, segments, sections = load_map_data(args.map_file)
  387. args.map_file.close()
  388. check_target(detected_target, args.map_file)
  389. if args.another_map_file:
  390. with open(args.another_map_file, 'r') as f:
  391. detected_target_diff, segments_diff, sections_diff = load_map_data(f)
  392. check_target(detected_target_diff, f)
  393. if detected_target_diff != detected_target:
  394. print('WARNING: The target of the reference and other MAP files is {} and {}, respectively.'
  395. ''.format(detected_target, detected_target_diff))
  396. else:
  397. segments_diff, sections_diff, detected_target_diff = {}, {}, ''
  398. if args.target is not None:
  399. if args.target != detected_target or (detected_target_diff and args.target != detected_target_diff):
  400. print('WARNING: The detected chip target overwritten to {} by command line argument!'.format(args.target))
  401. detected_target = args.target
  402. detected_target_diff = args.target
  403. output = ''
  404. if not args.json or not (args.archives or args.files or args.archive_details):
  405. output += get_summary(args.map_file.name, segments, sections, detected_target,
  406. args.json,
  407. args.another_map_file, segments_diff, sections_diff, detected_target_diff, not (args.archives or args.files))
  408. if args.archives:
  409. output += get_detailed_sizes(sections, 'archive', 'Archive File', args.json, sections_diff)
  410. if args.files:
  411. output += get_detailed_sizes(sections, 'file', 'Object File', args.json, sections_diff)
  412. if args.archive_details:
  413. output += get_archive_symbols(sections, args.archive_details, args.json, sections_diff)
  414. args.output_file.write(output)
  415. args.output_file.close()
  416. class StructureForSummary(object):
  417. used_dram_data, used_dram_bss, used_dram_rodata, used_dram_other, used_dram, dram_total, dram_remain = (0, ) * 7
  418. used_dram_ratio = 0.
  419. used_iram_vectors, used_iram_text, used_iram_other, used_iram, iram_total, iram_remain = (0, ) * 6
  420. used_iram_ratio = 0.
  421. used_diram_data, used_diram_bss, used_diram_text, used_diram_vectors, used_diram_rodata, used_diram_other, diram_total, used_diram, diram_remain = (0, ) * 9
  422. used_diram_ratio = 0.
  423. used_flash_text, used_flash_rodata, used_flash_other, used_flash, total_size = (0, ) * 5
  424. def __sub__(self, rhs: 'StructureForSummary') -> 'StructureForSummary':
  425. assert isinstance(rhs, StructureForSummary)
  426. ret = self
  427. for key in StructureForSummary.get_required_items():
  428. setattr(ret, key, getattr(self, key) - getattr(rhs, key))
  429. return ret
  430. def get_dram_overflowed(self) -> bool:
  431. return self.used_dram_ratio > 1.0
  432. def get_iram_overflowed(self) -> bool:
  433. return self.used_iram_ratio > 1.0
  434. def get_diram_overflowed(self) -> bool:
  435. return self.used_diram_ratio > 1.0
  436. @classmethod
  437. def get_required_items(cls: Any) -> List:
  438. whole_list = list(filter(lambda x: not (x.startswith('__') or x.endswith('__') or callable(getattr(cls, x))), dir(cls)))
  439. return whole_list
  440. @staticmethod
  441. def get(segments: List, sections: List) -> 'StructureForSummary':
  442. def get_size(sections: Iterable) -> int:
  443. return sum([x.len for x in sections])
  444. def in_diram(x: MemRegions.Region) -> bool:
  445. return x.region.type in (MemRegions.DRAM_ID, MemRegions.IRAM_ID) and x.region.secondary_addr > 0
  446. def in_dram(x: MemRegions.Region) -> bool:
  447. return x.region.type == MemRegions.DRAM_ID and x.region.secondary_addr == 0 # type: ignore
  448. def in_iram(x: MemRegions.Region) -> bool:
  449. return x.region.type == MemRegions.IRAM_ID and x.region.secondary_addr == 0 # type: ignore
  450. r = StructureForSummary()
  451. diram_filter = filter(in_diram, segments)
  452. r.diram_total = int(get_size(diram_filter) / 2)
  453. dram_filter = filter(in_dram, segments)
  454. r.dram_total = get_size(dram_filter)
  455. iram_filter = filter(in_iram, segments)
  456. r.iram_total = get_size(iram_filter)
  457. def filter_in_section(sections: Iterable[MemRegions.Region], section_to_check: str) -> List[MemRegions.Region]:
  458. return list(filter(lambda x: LinkingSections.in_section(x.section, section_to_check), sections)) # type: ignore
  459. dram_sections = list(filter(in_dram, sections))
  460. iram_sections = list(filter(in_iram, sections))
  461. diram_sections = list(filter(in_diram, sections))
  462. flash_sections = filter_in_section(sections, 'flash')
  463. dram_data_list = filter_in_section(dram_sections, 'data')
  464. dram_bss_list = filter_in_section(dram_sections, 'bss')
  465. dram_rodata_list = filter_in_section(dram_sections, 'rodata')
  466. dram_other_list = [x for x in dram_sections if x not in dram_data_list + dram_bss_list + dram_rodata_list]
  467. iram_vectors_list = filter_in_section(iram_sections, 'vectors')
  468. iram_text_list = filter_in_section(iram_sections, 'text')
  469. iram_other_list = [x for x in iram_sections if x not in iram_vectors_list + iram_text_list]
  470. diram_vectors_list = filter_in_section(diram_sections, 'vectors')
  471. diram_data_list = filter_in_section(diram_sections, 'data')
  472. diram_bss_list = filter_in_section(diram_sections, 'bss')
  473. diram_text_list = filter_in_section(diram_sections, 'text')
  474. diram_rodata_list = filter_in_section(diram_sections, 'rodata')
  475. diram_other_list = [x for x in diram_sections if x not in diram_data_list + diram_bss_list + diram_text_list + diram_vectors_list + diram_rodata_list]
  476. flash_text_list = filter_in_section(flash_sections, 'text')
  477. flash_rodata_list = filter_in_section(flash_sections, 'rodata')
  478. flash_other_list = [x for x in flash_sections if x not in flash_text_list + flash_rodata_list]
  479. r.used_dram_data = get_size(dram_data_list)
  480. r.used_dram_bss = get_size(dram_bss_list)
  481. r.used_dram_rodata = get_size(dram_rodata_list)
  482. r.used_dram_other = get_size(dram_other_list)
  483. r.used_dram = r.used_dram_data + r.used_dram_bss + r.used_dram_other + r.used_dram_rodata
  484. try:
  485. r.used_dram_ratio = r.used_dram / r.dram_total
  486. except ZeroDivisionError:
  487. r.used_dram_ratio = float('nan') if r.used_dram != 0 else 0
  488. r.dram_remain = r.dram_total - r.used_dram
  489. r.used_iram_vectors = get_size((iram_vectors_list))
  490. r.used_iram_text = get_size((iram_text_list))
  491. r.used_iram_other = get_size((iram_other_list))
  492. r.used_iram = r.used_iram_vectors + r.used_iram_text + r.used_iram_other
  493. try:
  494. r.used_iram_ratio = r.used_iram / r.iram_total
  495. except ZeroDivisionError:
  496. r.used_iram_ratio = float('nan') if r.used_iram != 0 else 0
  497. r.iram_remain = r.iram_total - r.used_iram
  498. r.used_diram_data = get_size(diram_data_list)
  499. r.used_diram_bss = get_size(diram_bss_list)
  500. r.used_diram_text = get_size(diram_text_list)
  501. r.used_diram_vectors = get_size(diram_vectors_list)
  502. r.used_diram_rodata = get_size(diram_rodata_list)
  503. r.used_diram_other = get_size(diram_other_list)
  504. r.used_diram = r.used_diram_data + r.used_diram_bss + r.used_diram_text + r.used_diram_vectors + r.used_diram_other + r.used_diram_rodata
  505. try:
  506. r.used_diram_ratio = r.used_diram / r.diram_total
  507. except ZeroDivisionError:
  508. r.used_diram_ratio = float('nan') if r.used_diram != 0 else 0
  509. r.diram_remain = r.diram_total - r.used_diram
  510. r.used_flash_text = get_size(flash_text_list)
  511. r.used_flash_rodata = get_size(flash_rodata_list)
  512. r.used_flash_other = get_size(flash_other_list)
  513. r.used_flash = r.used_flash_text + r.used_flash_rodata + r.used_flash_other
  514. # The used DRAM BSS is counted into the "Used static DRAM" but not into the "Total image size"
  515. r.total_size = r.used_dram - r.used_dram_bss + r.used_iram + r.used_diram - r.used_diram_bss + r.used_flash
  516. return r
  517. def get_json_dic(self) -> collections.OrderedDict:
  518. ret = collections.OrderedDict([
  519. ('dram_data', self.used_dram_data),
  520. ('dram_bss', self.used_dram_bss),
  521. ('dram_rodata', self.used_dram_rodata),
  522. ('dram_other', self.used_dram_other),
  523. ('used_dram', self.used_dram),
  524. ('dram_total', self.dram_total),
  525. ('used_dram_ratio', self.used_dram_ratio if self.used_dram_ratio is not float('nan') else 0),
  526. ('dram_remain', self.dram_remain),
  527. ('iram_vectors', self.used_iram_vectors),
  528. ('iram_text', self.used_iram_text),
  529. ('iram_other', self.used_iram_other),
  530. ('used_iram', self.used_iram),
  531. ('iram_total', self.iram_total),
  532. ('used_iram_ratio', self.used_iram_ratio),
  533. ('iram_remain', self.iram_remain),
  534. ('diram_data', self.used_diram_data),
  535. ('diram_bss', self.used_diram_bss),
  536. ('diram_text', self.used_diram_text),
  537. ('diram_vectors', self.used_diram_vectors),
  538. ('diram_rodata', self.used_diram_rodata),
  539. ('diram_other', self.used_diram_other),
  540. ('diram_total', self.diram_total),
  541. ('used_diram', self.used_diram),
  542. ('used_diram_ratio', self.used_diram_ratio),
  543. ('diram_remain', self.diram_remain),
  544. ('flash_code', self.used_flash_text),
  545. ('flash_rodata', self.used_flash_rodata),
  546. ('flash_other', self.used_flash_other),
  547. ('used_flash_non_ram', self.used_flash), # text/data in D/I RAM not included
  548. ('total_size', self.total_size) # bss not included
  549. ])
  550. assert len(ret) == len(StructureForSummary.get_required_items())
  551. return ret
  552. def get_structure_for_target(segments: Dict, sections: Dict, target: str) -> StructureForSummary:
  553. """
  554. Return StructureForSummary for specific target
  555. """
  556. mem_regions = MemRegions(target)
  557. segment_layout = mem_regions.fit_segments_into_regions(segments)
  558. section_layout = mem_regions.fit_sections_into_regions(LinkingSections.filter_sections(sections))
  559. current = StructureForSummary.get(segment_layout, section_layout)
  560. return current
  561. def get_summary(path: str, segments: Dict, sections: Dict, target: str,
  562. as_json: bool=False,
  563. path_diff: str='', segments_diff: Optional[Dict]=None, sections_diff: Optional[Dict]=None,
  564. target_diff: str='', print_suggestions: bool=True) -> str:
  565. segments_diff = segments_diff or {}
  566. sections_diff = sections_diff or {}
  567. current = get_structure_for_target(segments, sections, target)
  568. if path_diff:
  569. diff_en = True
  570. mem_regions_diff = MemRegions(target_diff)
  571. segment_layout_diff = mem_regions_diff.fit_segments_into_regions(segments_diff)
  572. section_layout_diff = mem_regions_diff.fit_sections_into_regions(LinkingSections.filter_sections(sections_diff))
  573. reference = StructureForSummary.get(segment_layout_diff, section_layout_diff)
  574. else:
  575. diff_en = False
  576. reference = StructureForSummary()
  577. if as_json:
  578. current_json_dic = current.get_json_dic()
  579. if diff_en:
  580. reference_json_dic = reference.get_json_dic()
  581. diff_json_dic = collections.OrderedDict([
  582. (k, v - reference_json_dic[k]) for k, v in current_json_dic.items()])
  583. output = format_json(collections.OrderedDict([('current', current_json_dic),
  584. ('reference', reference_json_dic),
  585. ('diff', diff_json_dic),
  586. ]))
  587. else:
  588. output = format_json(current_json_dic)
  589. else:
  590. class LineDef(object):
  591. title = ''
  592. name = ''
  593. def __init__(self, title: str, name: str) -> None:
  594. self.title = title
  595. self.name = name
  596. def format_line(self) -> Tuple[str, str, str, str]:
  597. return (self.title + ': {%s:>7} bytes' % self.name,
  598. '{%s:>7}' % self.name,
  599. '{%s:+}' % self.name,
  600. '')
  601. class HeadLineDef(LineDef):
  602. remain = ''
  603. ratio = ''
  604. total = ''
  605. warning_message = ''
  606. def __init__(self, title: str, name: str, remain: str, ratio: str, total: str, warning_message: str) -> None:
  607. super(HeadLineDef, self).__init__(title, name)
  608. self.remain = remain
  609. self.ratio = ratio
  610. self.total = total
  611. self.warning_message = warning_message
  612. def format_line(self) -> Tuple[str, str, str, str]:
  613. return ('%s: {%s:>7} bytes ({%s:>7} remain, {%s:.1%%} used)%s' % (self.title, self.name, self.remain, self.ratio, self.warning_message),
  614. '{%s:>7}' % self.name,
  615. '{%s:+}' % self.name,
  616. '({%s:>+7} remain, {%s:>+7} total)' % (self.remain, self.total))
  617. class TotalLineDef(LineDef):
  618. def format_line(self) -> Tuple[str, str, str, str]:
  619. return (self.title + ': {%s:>7} bytes (.bin may be padded larger)' % self.name,
  620. '{%s:>7}' % self.name,
  621. '{%s:+}' % self.name,
  622. '')
  623. warning_message = ' Overflow detected!' + (' You can run idf.py size-files for more information.' if print_suggestions else '')
  624. format_list = [
  625. HeadLineDef('Used static DRAM', 'used_dram', remain='dram_remain', ratio='used_dram_ratio', total='dram_total',
  626. warning_message=warning_message if current.get_dram_overflowed() else ''),
  627. LineDef(' .data size', 'used_dram_data'),
  628. LineDef(' .bss size', 'used_dram_bss'),
  629. LineDef(' .rodata size', 'used_dram_rodata'),
  630. LineDef(' DRAM other size', 'used_dram_other'),
  631. HeadLineDef('Used static IRAM', 'used_iram', remain='iram_remain', ratio='used_iram_ratio', total='iram_total',
  632. warning_message=warning_message if current.get_iram_overflowed() else ''),
  633. LineDef(' .text size', 'used_iram_text'),
  634. LineDef(' .vectors size', 'used_iram_vectors'),
  635. HeadLineDef('Used stat D/IRAM', 'used_diram', remain='diram_remain', ratio='used_diram_ratio', total='diram_total',
  636. warning_message=warning_message if current.get_diram_overflowed() else ''),
  637. LineDef(' .data size', 'used_diram_data'),
  638. LineDef(' .bss size', 'used_diram_bss'),
  639. LineDef(' .text size', 'used_diram_text'),
  640. LineDef(' .vectors size', 'used_diram_vectors'),
  641. LineDef(' .rodata size', 'used_diram_rodata'),
  642. LineDef(' other ', 'used_diram_other'),
  643. LineDef('Used Flash size ', 'used_flash'),
  644. LineDef(' .text ', 'used_flash_text'),
  645. LineDef(' .rodata ', 'used_flash_rodata'),
  646. TotalLineDef('Total image size', 'total_size')
  647. ]
  648. def convert_to_fmt_dict(summary: StructureForSummary, suffix: str='') -> Dict:
  649. required_items = StructureForSummary.get_required_items()
  650. return dict([(key + suffix, getattr(summary, key)) for key in required_items])
  651. f_dic1 = convert_to_fmt_dict(current)
  652. if diff_en:
  653. f_dic2 = convert_to_fmt_dict(reference)
  654. f_dic_diff = convert_to_fmt_dict(current - reference)
  655. lf = '{:60}{:>15}{:>15} {}' # Width for a, b, c, d columns
  656. def print_in_columns(a: str, b: Optional[str]='', c: Optional[str]='', d: Optional[str]='') -> str:
  657. return lf.format(a, b, c, d).rstrip() + os.linesep
  658. output = ''
  659. if diff_en:
  660. output += print_in_columns('<CURRENT> MAP file: ' + path)
  661. output += print_in_columns('<REFERENCE> MAP file: ' + path_diff)
  662. output += print_in_columns('Difference is counted as <CURRENT> - <REFERENCE>, ',
  663. 'i.e. a positive number means that <CURRENT> is larger.')
  664. output += print_in_columns('Total sizes of <CURRENT>:', '<REFERENCE>', 'Difference', '')
  665. for line in format_list:
  666. if getattr(current, line.name) > 0 or getattr(reference, line.name) > 0 or line.name == 'total_size':
  667. main_string_format, reference_format, sign_format, main_diff_format = line.format_line()
  668. output += print_in_columns(
  669. main_string_format.format(**f_dic1),
  670. reference_format.format(**f_dic2),
  671. sign_format.format(**f_dic_diff) if not sign_format.format(**f_dic_diff).startswith('+0') else '',
  672. main_diff_format.format(**f_dic_diff))
  673. else:
  674. output += print_in_columns('Total sizes:')
  675. for line in format_list:
  676. if getattr(current, line.name) > 0 or line.name == 'total_size':
  677. main_string_format, reference_format, sign_format, main_diff_format = line.format_line()
  678. output += print_in_columns(main_string_format.format(**f_dic1))
  679. return output
  680. def sort_dict(non_sort_list: List) -> List:
  681. '''
  682. sort with keeping the order data, bss, other, iram, diram, ram_st_total, flash_text, flash_rodata, flash_total
  683. '''
  684. start_of_other = 0
  685. props_sort = [] # type: List
  686. props_elem = ['.data', '.bss', 'other', 'iram', 'diram', 'ram_st_total', 'flash.text', 'flash.rodata', 'flash', 'flash_total']
  687. for i in props_elem:
  688. for j in non_sort_list:
  689. if i == 'other':
  690. # remembering where 'other' will start
  691. start_of_other = len(props_sort)
  692. elif i in j and j not in props_sort:
  693. props_sort.append(j)
  694. for j in non_sort_list:
  695. if j not in props_sort:
  696. # add all item that fit in other in dict
  697. props_sort.insert(start_of_other, j)
  698. return props_sort
  699. class StructureForDetailedSizes(object):
  700. @staticmethod
  701. def sizes_by_key(sections: SectionDict, key: str, include_padding: Optional[bool]=False) -> Dict[str, Dict[str, int]]:
  702. """ Takes a dict of sections (from load_sections) and returns
  703. a dict keyed by 'key' with aggregate output size information.
  704. Key can be either "archive" (for per-archive data) or "file" (for per-file data) in the result.
  705. """
  706. result = {} # type: Dict[str, Dict[str, int]]
  707. for _, section in sections.items():
  708. for s in section['sources']:
  709. if not s[key] in result:
  710. result[s[key]] = {}
  711. archive = result[s[key]]
  712. if not section['name'] in archive:
  713. archive[section['name']] = 0
  714. archive[section['name']] += s['size']
  715. if include_padding:
  716. archive[section['name']] += s['fill']
  717. return result
  718. @staticmethod
  719. def get(sections: SectionDict, by_key: str) -> collections.OrderedDict:
  720. """
  721. Get the detailed structure before using the filter to remove undesired sections,
  722. to show entries without desired sections
  723. """
  724. sizes = StructureForDetailedSizes.sizes_by_key(sections, by_key)
  725. for key_name in sizes:
  726. sizes[key_name] = LinkingSections.filter_sections(sizes[key_name])
  727. s = []
  728. for key, section_dict in sizes.items():
  729. ram_st_total = sum([x[1] for x in section_dict.items() if not LinkingSections.in_section(x[0], 'flash')])
  730. flash_total = sum([x[1] for x in section_dict.items() if not LinkingSections.in_section(x[0], 'bss')]) # type: int
  731. section_dict['ram_st_total'] = ram_st_total
  732. section_dict['flash_total'] = flash_total
  733. sorted_dict = sorted(section_dict.items(), key=lambda elem: elem[0])
  734. s.append((key, collections.OrderedDict(sorted_dict)))
  735. s = sorted(s, key=lambda elem: elem[0])
  736. # do a secondary sort in order to have consistent order (for diff-ing the output)
  737. s = sorted(s, key=lambda elem: elem[1]['flash_total'], reverse=True)
  738. return collections.OrderedDict(s)
  739. def get_detailed_sizes(sections: Dict, key: str, header: str, as_json: bool=False, sections_diff: Dict=None) -> str:
  740. key_name_set = set()
  741. current = StructureForDetailedSizes.get(sections, key)
  742. for section_dict in current.values():
  743. key_name_set.update(section_dict.keys())
  744. if sections_diff:
  745. reference = StructureForDetailedSizes.get(sections_diff, key)
  746. for section_dict in reference.values():
  747. key_name_set.update(section_dict.keys())
  748. diff_en = True
  749. else:
  750. diff_en = False
  751. key_name_list = list(key_name_set)
  752. ordered_key_list, display_name_list = LinkingSections.get_display_name_order(key_name_list)
  753. if as_json:
  754. if diff_en:
  755. diff_json_dic = collections.OrderedDict()
  756. for name in sorted(list(frozenset(current.keys()) | frozenset(reference.keys()))):
  757. cur_name_dic = current.get(name, {})
  758. ref_name_dic = reference.get(name, {})
  759. all_keys = sorted(list(frozenset(cur_name_dic.keys()) | frozenset(ref_name_dic.keys())))
  760. diff_json_dic[name] = collections.OrderedDict([(k,
  761. cur_name_dic.get(k, 0) -
  762. ref_name_dic.get(k, 0)) for k in all_keys])
  763. output = format_json(collections.OrderedDict([('current', current),
  764. ('reference', reference),
  765. ('diff', diff_json_dic),
  766. ]))
  767. else:
  768. output = format_json(current)
  769. else:
  770. def _get_header_format(disp_list: List=display_name_list) -> str:
  771. len_list = [len(x) for x in disp_list]
  772. len_list.insert(0, 24)
  773. return ' '.join(['{:>%d}' % x for x in len_list]) + os.linesep
  774. def _get_output(data: Dict[str, Dict[str, int]], selection: Collection, key_list: List=ordered_key_list, disp_list: List=display_name_list) -> str:
  775. header_format = _get_header_format(disp_list)
  776. output = header_format.format(header, *disp_list)
  777. for key, data_info in data.items():
  778. if key not in selection:
  779. continue
  780. try:
  781. _, key = key.split(':', 1)
  782. # print subheadings for key of format archive:file
  783. except ValueError:
  784. # k remains the same
  785. pass
  786. def get_section_size(section_dict: Dict) -> Callable[[str], int]:
  787. return lambda x: section_dict.get(x, 0)
  788. section_size_list = map(get_section_size(section_dict=data_info), key_list)
  789. output += header_format.format(key[:24], *(section_size_list))
  790. return output
  791. def _get_header_format_diff(disp_list: List=display_name_list, columns: bool=False) -> str:
  792. if columns:
  793. len_list = (24, ) + (7, ) * 3 * len(disp_list)
  794. return '|'.join(['{:>%d}' % x for x in len_list]) + os.linesep
  795. len_list = (24, ) + (23, ) * len(disp_list)
  796. return ' '.join(['{:>%d}' % x for x in len_list]) + os.linesep
  797. def _get_output_diff(curr: Dict, ref: Dict, key_list: List=ordered_key_list, disp_list: List=display_name_list) -> str:
  798. # First header without Current/Ref/Diff columns
  799. header_format = _get_header_format_diff(columns=False)
  800. output = header_format.format(header, *disp_list)
  801. f_print = ('-' * 23, '') * len(key_list)
  802. f_print = f_print[0:len(key_list)]
  803. header_line = header_format.format('', *f_print)
  804. header_format = _get_header_format_diff(columns=True)
  805. f_print = ('<C>', '<R>', '<C>-<R>') * len(key_list)
  806. output += header_format.format('', *f_print)
  807. output += header_line
  808. for key, data_info in curr.items():
  809. try:
  810. v2 = ref[key]
  811. except KeyError:
  812. continue
  813. try:
  814. _, key = key.split(':', 1)
  815. # print subheadings for key of format archive:file
  816. except ValueError:
  817. # k remains the same
  818. pass
  819. def _get_items(name: str, section_dict: Dict=data_info, section_dict_ref: Dict=v2) -> Tuple[str, str, str]:
  820. a = section_dict.get(name, 0)
  821. b = section_dict_ref.get(name, 0)
  822. diff = a - b
  823. # the sign is added here and not in header_format in order to be able to print empty strings
  824. return (a or '', b or '', '' if diff == 0 else '{:+}'.format(diff))
  825. x = [] # type: List[str]
  826. for section in key_list:
  827. x.extend(_get_items(section))
  828. output += header_format.format(key[:24], *(x))
  829. return output
  830. output = 'Per-{} contributions to ELF file:{}'.format(key, os.linesep)
  831. if diff_en:
  832. output += _get_output_diff(current, reference)
  833. in_current = frozenset(current.keys())
  834. in_reference = frozenset(reference.keys())
  835. only_in_current = in_current - in_reference
  836. only_in_reference = in_reference - in_current
  837. if len(only_in_current) > 0:
  838. output += 'The following entries are present in <CURRENT> only:{}'.format(os.linesep)
  839. output += _get_output(current, only_in_current)
  840. if len(only_in_reference) > 0:
  841. output += 'The following entries are present in <REFERENCE> only:{}'.format(os.linesep)
  842. output += _get_output(reference, only_in_reference)
  843. else:
  844. output += _get_output(current, current)
  845. return output
  846. class StructureForArchiveSymbols(object):
  847. @staticmethod
  848. def get(archive: str, sections: Dict) -> Dict:
  849. interested_sections = LinkingSections.filter_sections(sections)
  850. result = dict([(t, {}) for t in interested_sections]) # type: Dict[str, Dict[str, int]]
  851. for _, section in sections.items():
  852. section_name = section['name']
  853. if section_name not in interested_sections:
  854. continue
  855. for s in section['sources']:
  856. if archive != s['archive']:
  857. continue
  858. s['sym_name'] = re.sub('(.text.|.literal.|.data.|.bss.|.rodata.)', '', s['sym_name'])
  859. result[section_name][s['sym_name']] = result[section_name].get(s['sym_name'], 0) + s['size']
  860. # build a new ordered dict of each section, where each entry is an ordereddict of symbols to sizes
  861. section_symbols = collections.OrderedDict()
  862. for t in sorted(list(interested_sections)):
  863. s = sorted(result[t].items(), key=lambda k_v: str(k_v[0]))
  864. # do a secondary sort in order to have consistent order (for diff-ing the output)
  865. s = sorted(s, key=lambda k_v: int(k_v[1]), reverse=True)
  866. section_symbols[t] = collections.OrderedDict(s)
  867. return section_symbols
  868. def get_archive_symbols(sections: Dict, archive: str, as_json: bool=False, sections_diff: Dict=None) -> str:
  869. diff_en = bool(sections_diff)
  870. current = StructureForArchiveSymbols.get(archive, sections)
  871. reference = StructureForArchiveSymbols.get(archive, sections_diff) if sections_diff else {}
  872. if as_json:
  873. if diff_en:
  874. diff_json_dic = collections.OrderedDict()
  875. for name in sorted(list(frozenset(current.keys()) | frozenset(reference.keys()))):
  876. cur_name_dic = current.get(name, {})
  877. ref_name_dic = reference.get(name, {})
  878. all_keys = sorted(list(frozenset(cur_name_dic.keys()) | frozenset(ref_name_dic.keys())))
  879. diff_json_dic[name] = collections.OrderedDict([(key,
  880. cur_name_dic.get(key, 0) -
  881. ref_name_dic.get(key, 0)) for key in all_keys])
  882. output = format_json(collections.OrderedDict([('current', current),
  883. ('reference', reference),
  884. ('diff', diff_json_dic),
  885. ]))
  886. else:
  887. output = format_json(current)
  888. else:
  889. def _get_item_pairs(name: str, section: collections.OrderedDict) -> collections.OrderedDict:
  890. return collections.OrderedDict([(key.replace(name + '.', ''), val) for key, val in section.items()])
  891. def _get_max_len(symbols_dict: Dict) -> Tuple[int, int]:
  892. # the lists have 0 in them because max() doesn't work with empty lists
  893. names_max_len = 0
  894. numbers_max_len = 0
  895. for t, s in symbols_dict.items():
  896. numbers_max_len = max([numbers_max_len, *[len(str(x)) for _, x in s.items()]])
  897. names_max_len = max([names_max_len, *[len(x) for x in _get_item_pairs(t, s)]])
  898. return names_max_len, numbers_max_len
  899. def _get_output(section_symbols: Dict) -> str:
  900. output = ''
  901. names_max_len, numbers_max_len = _get_max_len(section_symbols)
  902. for t, s in section_symbols.items():
  903. output += '{}Symbols from section: {}{}'.format(os.linesep, t, os.linesep)
  904. item_pairs = _get_item_pairs(t, s)
  905. for key, val in item_pairs.items():
  906. output += ' '.join([('\t{:<%d} : {:>%d}\n' % (names_max_len,numbers_max_len)).format(key, val)])
  907. section_total = sum([val for _, val in item_pairs.items()])
  908. output += 'Section total: {}{}'.format(section_total, os.linesep)
  909. return output
  910. output = '{}Symbols within the archive: {} (Not all symbols may be reported){}'.format(os.linesep, archive, os.linesep)
  911. if diff_en:
  912. def _generate_line_tuple(curr: collections.OrderedDict, ref: collections.OrderedDict, name: str) -> Tuple[str, int, int, str]:
  913. cur_val = curr.get(name, 0)
  914. ref_val = ref.get(name, 0)
  915. diff_val = cur_val - ref_val
  916. # string slicing is used just to make sure it will fit into the first column of line_format
  917. return ((' ' * 4 + name)[:40], cur_val, ref_val, '' if diff_val == 0 else '{:+}'.format(diff_val))
  918. line_format = '{:40} {:>12} {:>12} {:>25}'
  919. all_section_names = sorted(list(frozenset(current.keys()) | frozenset(reference.keys())))
  920. for section_name in all_section_names:
  921. current_item_pairs = _get_item_pairs(section_name, current.get(section_name, {}))
  922. reference_item_pairs = _get_item_pairs(section_name, reference.get(section_name, {}))
  923. output += os.linesep + line_format.format(section_name[:40],
  924. '<CURRENT>',
  925. '<REFERENCE>',
  926. '<CURRENT> - <REFERENCE>') + os.linesep
  927. current_section_total = sum([val for _, val in current_item_pairs.items()])
  928. reference_section_total = sum([val for _, val in reference_item_pairs.items()])
  929. diff_section_total = current_section_total - reference_section_total
  930. all_item_names = sorted(list(frozenset(current_item_pairs.keys()) |
  931. frozenset(reference_item_pairs.keys())))
  932. output += os.linesep.join([line_format.format(*_generate_line_tuple(current_item_pairs,
  933. reference_item_pairs,
  934. n)
  935. ).rstrip() for n in all_item_names])
  936. output += os.linesep if current_section_total > 0 or reference_section_total > 0 else ''
  937. output += line_format.format('Section total:',
  938. current_section_total,
  939. reference_section_total,
  940. '' if diff_section_total == 0 else '{:+}'.format(diff_section_total)
  941. ).rstrip() + os.linesep
  942. else:
  943. output += _get_output(current)
  944. return output
  945. if __name__ == '__main__':
  946. main()