Merge pull request #230 from mlnx/memap_improvements

Memap improvements
Sam Grove 2016-06-09 22:16:44 +01:00 committed by GitHub
commit 10936e2e5f
2 changed files with 251 additions and 235 deletions

View File

@ -1,21 +1,20 @@
#!/usr/bin/env python #!/usr/bin/env python
# pylint: disable=too-many-arguments, too-many-locals, too-many-branches, too-many-lines, line-too-long, too-many-nested-blocks, too-many-public-methods, too-many-instance-attributes
# pylint: disable=invalid-name, missing-docstring
# Memory Map File Analyser for ARM mbed OS # Memory Map File Analyser for ARM mbed OS
import argparse
import sys import sys
import string
import os import os
import re import re
import csv
import json import json
import time import argparse
import string
import StringIO
from prettytable import PrettyTable from prettytable import PrettyTable
debug = False debug = False
class MemmapParser(object): class MemapParser(object):
def __init__(self): def __init__(self):
""" """
@ -27,14 +26,15 @@ class MemmapParser(object):
self.misc_flash_sections = ('.interrupts', '.flash_config') self.misc_flash_sections = ('.interrupts', '.flash_config')
self.other_sections = ('.interrupts_ram', '.init', '.ARM.extab', '.ARM.exidx', '.ARM.attributes', \ self.other_sections = ('.interrupts_ram', '.init', '.ARM.extab', \
'.eh_frame', '.init_array', '.fini_array', '.jcr', '.stab', '.stabstr', \ '.ARM.exidx', '.ARM.attributes', '.eh_frame', \
'.ARM.exidx','.ARM' ) '.init_array', '.fini_array', '.jcr', '.stab', \
'.stabstr', '.ARM.exidx', '.ARM')
# sections to print info (generic for all toolchains) # sections to print info (generic for all toolchains)
self.sections = ('.text', '.data', '.bss', '.heap', '.stack',) self.sections = ('.text', '.data', '.bss', '.heap', '.stack')
# need to have sections merged in this order () # sections must be defined in this order to take irrelevant out
self.all_sections = self.sections + self.other_sections + \ self.all_sections = self.sections + self.other_sections + \
self.misc_flash_sections + ('unknown', 'OUTPUT') self.misc_flash_sections + ('unknown', 'OUTPUT')
@ -43,77 +43,6 @@ class MemmapParser(object):
# list of all object files and mappting to module names # list of all object files and mappting to module names
self.object_to_module = dict() self.object_to_module = dict()
def generate_output(self, file, json_mode):
"""
Generates summary of memory map data
Parameters
file: descriptor (either stdout or file)
json_mode: generates output in json formal (True/False)
"""
buf = StringIO.StringIO()
# Calculate misc flash sections
misc_flash_mem = 0
for i in self.modules:
for k in self.misc_flash_sections:
if self.modules[i][k]:
misc_flash_mem += self.modules[i][k]
# Create table
colums = ['Module']
for i in list(self.print_sections):
colums.append(i)
table = PrettyTable(colums)
table.align["Module"] = "l"
subtotal = dict()
for k in self.sections:
subtotal[k] = 0
json_obj = []
for i in sorted(self.modules):
row = []
row.append(i)
for k in self.sections:
subtotal[k] += self.modules[i][k]
for k in self.print_sections:
row.append(self.modules[i][k])
json_obj.append({ "module":i, "size":{k:self.modules[i][k] for k in self.print_sections}})
table.add_row(row)
subtotal_row = ['Subtotals']
for k in self.print_sections:
subtotal_row.append(subtotal[k])
table.add_row(subtotal_row)
if json_mode:
json_obj.append({ "summary":{'static_ram':(subtotal['.data']+subtotal['.bss']),
'heap':(subtotal['.heap']),
'stack':(subtotal['.stack']),
'total_ram':(subtotal['.data']+subtotal['.bss']+subtotal['.heap']+subtotal['.stack']),
'total_flash':(subtotal['.text']+subtotal['.data']+misc_flash_mem),}})
file.write(json.dumps(json_obj, indent=4))
file.write('\n')
else:
file.write(table.get_string())
file.write('\n')
file.write("Static RAM memory (data + bss): %s\n" % (str(subtotal['.data']+subtotal['.bss'])))
file.write("Heap: %s\n" % str(subtotal['.heap']))
file.write("Stack: %s\n" % str(subtotal['.stack']))
file.write("Total RAM memory (data + bss + heap + stack): %s\n" % (str(subtotal['.data']+subtotal['.bss']+subtotal['.heap']+subtotal['.stack'])))
file.write("Total Flash memory (text + data + misc): %s\n" % (str(subtotal['.text']+subtotal['.data']+misc_flash_mem)))
return
def module_add(self, module_name, size, section): def module_add(self, module_name, size, section):
""" """
Adds a module / section to the list Adds a module / section to the list
@ -123,38 +52,11 @@ class MemmapParser(object):
self.modules[module_name][section] += size self.modules[module_name][section] += size
else: else:
temp_dic = dict() temp_dic = dict()
for x in self.all_sections: for section_idx in self.all_sections:
temp_dic[x] = 0 temp_dic[section_idx] = 0
temp_dic[section] = size temp_dic[section] = size
self.modules[module_name] = temp_dic self.modules[module_name] = temp_dic
def find_start_gcc(self,line):
"""
Checks location of gcc map file to start parsing map file
"""
if line.startswith('Linker script and memory map'):
return True
else:
return False
def find_start_armcc(self,line):
"""
Checks location of armcc map file to start parsing map file
"""
if line.startswith(' Base Addr Size'):
return True
else:
return False
def find_start_iar(self,line):
"""
Checks location of armcc map file to start parsing map file
"""
if line.startswith(' Section '):
return True
else:
return False
def check_new_section_gcc(self, line): def check_new_section_gcc(self, line):
""" """
Check whether a new section in a map file has been detected (only applies to gcc) Check whether a new section in a map file has been detected (only applies to gcc)
@ -214,7 +116,7 @@ class MemmapParser(object):
m_size = int(test_address_len_name.group(2), 16) m_size = int(test_address_len_name.group(2), 16)
return [m_name, m_size] return [m_name, m_size]
else: # special cortner case for *fill* sections else: # special corner case for *fill* sections
# example # example
# *fill* 0x0000abe4 0x4 # *fill* 0x0000abe4 0x4
rex_address_len = r'^\s+\*fill\*\s+0x(\w{8,16})\s+0x(\w+).*$' rex_address_len = r'^\s+\*fill\*\s+0x(\w{8,16})\s+0x(\w+).*$'
@ -224,24 +126,24 @@ class MemmapParser(object):
if int(test_address_len.group(2), 16) == 0: # size == 0 if int(test_address_len.group(2), 16) == 0: # size == 0
return ["", 0] # no valid entry return ["", 0] # no valid entry
else: else:
m_name = 'Misc' m_name = 'Fill'
m_size = int(test_address_len.group(2), 16) m_size = int(test_address_len.group(2), 16)
return [m_name, m_size] return [m_name, m_size]
else: else:
return ["", 0] # no valid entry return ["", 0] # no valid entry
def parse_map_file_gcc(self, file): def parse_map_file_gcc(self, file_desc):
""" """
Main logic to decode gcc map files Main logic to decode gcc map files
""" """
current_section = 'unknown' current_section = 'unknown'
with file as infile: with file_desc as infile:
# Search area to parse # Search area to parse
for line in infile: for line in infile:
if self.find_start_gcc(line) == True: if line.startswith('Linker script and memory map'):
current_section = "unknown" current_section = "unknown"
break break
@ -331,7 +233,6 @@ class MemmapParser(object):
if test_rex_iar.group(2) == 'const' or test_rex_iar.group(2) == 'ro code': if test_rex_iar.group(2) == 'const' or test_rex_iar.group(2) == 'ro code':
section = '.text' section = '.text'
elif test_rex_iar.group(2) == 'zero' or test_rex_iar.group(2) == 'uninit': elif test_rex_iar.group(2) == 'zero' or test_rex_iar.group(2) == 'uninit':
if test_rex_iar.group(1)[0:4] == 'HEAP': if test_rex_iar.group(1)[0:4] == 'HEAP':
section = '.heap' section = '.heap'
elif test_rex_iar.group(1)[0:6] == 'CSTACK': elif test_rex_iar.group(1)[0:6] == 'CSTACK':
@ -357,16 +258,16 @@ class MemmapParser(object):
else: else:
return ["", 0, ""] # no valid entry return ["", 0, ""] # no valid entry
def parse_map_file_armcc(self, file): def parse_map_file_armcc(self, file_desc):
""" """
Main logic to decode armcc map files Main logic to decode armcc map files
""" """
with file as infile: with file_desc as infile:
# Search area to parse # Search area to parse
for line in infile: for line in infile:
if self.find_start_armcc(line) == True: if line.startswith(' Base Addr Size'):
break break
# Start decoding the map file # Start decoding the map file
@ -379,16 +280,16 @@ class MemmapParser(object):
else: else:
self.module_add(name, size, section) self.module_add(name, size, section)
def parse_map_file_iar(self, file): def parse_map_file_iar(self, file_desc):
""" """
Main logic to decode armcc map files Main logic to decode armcc map files
""" """
with file as infile: with file_desc as infile:
# Search area to parse # Search area to parse
for line in infile: for line in infile:
if self.find_start_iar(line) == True: if line.startswith(' Section '):
break break
# Start decoding the map file # Start decoding the map file
@ -421,37 +322,177 @@ class MemmapParser(object):
print "Warning: specified toolchain doesn't match with path to the memory map file." print "Warning: specified toolchain doesn't match with path to the memory map file."
return return
for root, dirs, files in os.walk(search_path): for root, dir, obj_files in os.walk(search_path):
for file in files: for obj_file in obj_files:
if file.endswith(".o"): if obj_file.endswith(".o"):
module_name, object_name = self.path_object_to_module_name(os.path.join(root, file)) module_name, object_name = self.path_object_to_module_name(os.path.join(root, obj_file))
if object_name in self.object_to_module: if object_name in self.object_to_module:
if debug:
print "WARNING: multiple usages of object file: %s" % object_name print "WARNING: multiple usages of object file: %s" % object_name
print " Current: %s" % self.object_to_module[object_name] print " Current: %s" % self.object_to_module[object_name]
print " New: %s" % module_name print " New: %s" % module_name
print " " print " "
else: else:
self.object_to_module.update({object_name:module_name}) self.object_to_module.update({object_name:module_name})
def generate_output(self, export_format, file_output=None):
"""
Generates summary of memory map data
Parameters
json_mode: generates output in json formal (True/False)
file_desc: descriptor (either stdout or file)
"""
try:
if file_output:
file_desc = open(file_output, 'wb')
else:
file_desc = sys.stdout
except IOError as error:
print "I/O error({0}): {1}".format(error.errno, error.strerror)
return False
# Calculate misc flash sections
misc_flash_mem = 0
for i in self.modules:
for k in self.misc_flash_sections:
if self.modules[i][k]:
misc_flash_mem += self.modules[i][k]
# Create table
columns = ['Module']
for i in list(self.print_sections):
columns.append(i)
table = PrettyTable(columns)
table.align["Module"] = "l"
subtotal = dict()
for k in self.sections:
subtotal[k] = 0
json_obj = []
for i in sorted(self.modules):
row = []
row.append(i)
for k in self.sections:
subtotal[k] += self.modules[i][k]
for k in self.print_sections:
row.append(self.modules[i][k])
json_obj.append({"module":i, "size":{\
k:self.modules[i][k] for k in self.print_sections}})
table.add_row(row)
subtotal_row = ['Subtotals']
for k in self.print_sections:
subtotal_row.append(subtotal[k])
table.add_row(subtotal_row)
if export_format == 'json':
json_obj.append({\
'summary':{\
'static_ram':(subtotal['.data']+subtotal['.bss']),\
'heap':(subtotal['.heap']),\
'stack':(subtotal['.stack']),\
'total_ram':(subtotal['.data']+subtotal['.bss']+subtotal['.heap']+subtotal['.stack']),\
'total_flash':(subtotal['.text']+subtotal['.data']+misc_flash_mem),}})
file_desc.write(json.dumps(json_obj, indent=4))
file_desc.write('\n')
elif export_format == 'csv-ci': # CSV format for the CI system
csv_writer = csv.writer(file_desc, delimiter=',', quoting=csv.QUOTE_NONE)
csv_module_section = []
csv_sizes = []
for i in sorted(self.modules):
for k in self.print_sections:
csv_module_section += [i+k]
csv_sizes += [self.modules[i][k]]
csv_module_section += ['static_ram']
csv_sizes += [subtotal['.data']+subtotal['.bss']]
csv_module_section += ['heap']
csv_sizes += [subtotal['.heap']]
csv_module_section += ['stack']
csv_sizes += [subtotal['.stack']]
csv_module_section += ['total_ram']
csv_sizes += [subtotal['.data']+subtotal['.bss']+subtotal['.heap']+subtotal['.stack']]
csv_module_section += ['total_flash']
csv_sizes += [subtotal['.text']+subtotal['.data']+misc_flash_mem]
csv_writer.writerow(csv_module_section)
csv_writer.writerow(csv_sizes)
else: # default format is 'table'
file_desc.write(table.get_string())
file_desc.write('\n')
file_desc.write("Static RAM memory (data + bss): %s\n" % (str(subtotal['.data']+subtotal['.bss'])))
file_desc.write("Heap: %s\n" % str(subtotal['.heap']))
file_desc.write("Stack: %s\n" % str(subtotal['.stack']))
file_desc.write("Total RAM memory (data + bss + heap + stack): %s\n" % (str(subtotal['.data']+subtotal['.bss']+subtotal['.heap']+subtotal['.stack'])))
file_desc.write("Total Flash memory (text + data + misc): %s\n" % (str(subtotal['.text']+subtotal['.data']+misc_flash_mem)))
if file_desc is not sys.stdout:
file_desc.close()
return True
def parse(self, mapfile, toolchain):
"""
Parse and decode map file depending on the toolchain
"""
try:
file_input = open(mapfile, 'rt')
except IOError as error:
print "I/O error({0}): {1}".format(error.errno, error.strerror)
return False
if toolchain == "ARM" or toolchain == "ARM_STD" or toolchain == "ARM_MICRO":
self.search_objects(os.path.abspath(mapfile), "ARM")
self.parse_map_file_armcc(file_input)
elif toolchain == "GCC_ARM":
self.parse_map_file_gcc(file_input)
elif toolchain == "IAR":
self.search_objects(os.path.abspath(mapfile), toolchain)
self.parse_map_file_iar(file_input)
else:
return False
file_input.close()
return True
def main(): def main():
version = '0.3.7' version = '0.3.10'
time_start = time.clock()
# Parser handling # Parser handling
parser = argparse.ArgumentParser(description="Memory Map File Analyser for ARM mbed OS\nversion %s" % version) parser = argparse.ArgumentParser(description="Memory Map File Analyser for ARM mbed OS\nversion %s" % version)
parser.add_argument('file', help='memory map file') parser.add_argument('file', help='memory map file')
parser.add_argument('-t','--toolchain', dest='toolchain', help='select a toolchain that corresponds to the memory map file (ARM, GCC_ARM, IAR)', parser.add_argument('-t', '--toolchain', dest='toolchain', help='select a toolchain used to build the memory map file (ARM, GCC_ARM, IAR)',\
required=True) required=True)
parser.add_argument('-o', '--output', help='output file name', required=False) parser.add_argument('-o', '--output', help='output file name', required=False)
parser.add_argument('-j', '--json', dest='json', required=False, action="store_true", parser.add_argument('-e', '--export', dest='export', required=False,\
help='output in JSON formatted list') help="export format (examples: 'json', 'csv-ci', 'table': default)")
parser.add_argument('-v', '--version', action='version', version=version) parser.add_argument('-v', '--version', action='version', version=version)
@ -460,47 +501,27 @@ def main():
parser.print_help() parser.print_help()
sys.exit(1) sys.exit(1)
args, remainder = parser.parse_known_args() args, remainder = parser.parse_known_args()
try: # Create memap object
file_input = open(args.file,'rt') memap = MemapParser()
except IOError as e:
print "I/O error({0}): {1}".format(e.errno, e.strerror) # Parse and decode a map file
if args.file and args.toolchain:
if memap.parse(args.file, args.toolchain) is False:
print "Unknown toolchain for memory statistics %s" % args.toolchain
sys.exit(0) sys.exit(0)
# Creates parser object # default export format is table
t = MemmapParser() if not args.export:
args.export = 'table'
# Decode map file depending on the toolchain
if args.toolchain == "ARM":
t.search_objects(os.path.abspath(args.file),args.toolchain)
t.parse_map_file_armcc(file_input)
elif args.toolchain == "GCC_ARM":
t.parse_map_file_gcc(file_input)
elif args.toolchain == "IAR":
print "WARNING: IAR Compiler not fully supported (yet)"
print " "
t.search_objects(os.path.abspath(args.file),args.toolchain)
t.parse_map_file_iar(file_input)
else:
print "Invalid toolchain. Options are: ARM, GCC_ARM, IAR"
sys.exit(0)
# Write output in file # Write output in file
if args.output != None: if args.output != None:
try: memap.generate_output(args.export, args.output)
file_output = open(args.output,'w')
t.generate_output(file_output,args.json)
file_output.close()
except IOError as e:
print "I/O error({0}): {1}".format(e.errno, e.strerror)
sys.exit(0)
else: # Write output in screen else: # Write output in screen
t.generate_output(sys.stdout,args.json) memap.generate_output(args.export)
file_input.close()
print "Elapsed time: %smS" %int(round((time.clock()-time_start)*1000))
sys.exit(0) sys.exit(0)

View File

@ -29,7 +29,7 @@ from multiprocessing import Pool, cpu_count
from tools.utils import run_cmd, mkdir, rel_path, ToolException, NotSupportedException, split_path from tools.utils import run_cmd, mkdir, rel_path, ToolException, NotSupportedException, split_path
from tools.settings import BUILD_OPTIONS, MBED_ORG_USER from tools.settings import BUILD_OPTIONS, MBED_ORG_USER
import tools.hooks as hooks import tools.hooks as hooks
from tools.memap import MemmapParser from tools.memap import MemapParser
from hashlib import md5 from hashlib import md5
import fnmatch import fnmatch
@ -824,30 +824,25 @@ class mbedToolchain:
def mem_stats(self, map): def mem_stats(self, map):
# Creates parser object # Creates parser object
toolchain = self.__class__.__name__ toolchain = self.__class__.__name__
t = MemmapParser()
try: # Create memap object
with open(map, 'rt') as f: memap = MemapParser()
# Decode map file depending on the toolchain
if toolchain == "ARM_STD" or toolchain == "ARM_MICRO": # Parse and decode a map file
t.search_objects(abspath(map), "ARM") if memap.parse(abspath(map), toolchain) is False:
t.parse_map_file_armcc(f)
elif toolchain == "GCC_ARM":
t.parse_map_file_gcc(f)
elif toolchain == "IAR":
self.info("[WARNING] IAR Compiler not fully supported (yet)")
t.search_objects(abspath(map), toolchain)
t.parse_map_file_iar(f)
else:
self.info("Unknown toolchain for memory statistics %s" % toolchain) self.info("Unknown toolchain for memory statistics %s" % toolchain)
return return
t.generate_output(sys.stdout, False) # Write output to stdout in text (pretty table) format
memap.generate_output('table')
# Write output to file in JSON format
map_out = splitext(map)[0] + "_map.json" map_out = splitext(map)[0] + "_map.json"
with open(map_out, 'w') as fo: memap.generate_output('json', map_out)
t.generate_output(fo, True)
except OSError: # Write output to file in CSV format for the CI
return map_csv = splitext(map)[0] + "_map.csv"
memap.generate_output('csv-ci', map_csv)
from tools.settings import ARM_BIN from tools.settings import ARM_BIN