Skip to content

Instantly share code, notes, and snippets.

@nmenon
Last active May 12, 2022 05:59
Show Gist options
  • Save nmenon/13b135e8ba29531395de205903471b15 to your computer and use it in GitHub Desktop.
Save nmenon/13b135e8ba29531395de205903471b15 to your computer and use it in GitHub Desktop.
Ridiculous memory map creator
#!/usr/bin/env python3
import argparse
import humanize
def args_auto_int(x):
return int(x, 0)
def args_memory_map_entry(x):
try:
entry = x.split(':')
map = {}
map['name'] = entry[0]
map['size'] = int(entry[1], 0)
except Exception as e:
raise ValueError(str(e) + ": should be map_name:size_in_bytes")
return map
def parse_args():
""" Helper to parse the command line arguments
"""
help_text = "Memory Map Creator\n"
epilog_help = "Copyright (C) Texas Instruments, Inc https://www.ti.com"
parser = argparse.ArgumentParser(prog=__file__,
description=help_text,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
epilog=epilog_help)
optional = parser._action_groups.pop()
# Required input arguments
mandatory_group = parser.add_argument_group(
'Required arguments:')
mandatory_group.add_argument(
'-b',
'--base_address',
help="Base Address(Hex)",
type=args_auto_int,
action="store",
required=True)
mandatory_group.add_argument(
'-m',
'--mem_region',
help="memory_region_name:memory_region_size_bytes(hex)",
type=args_memory_map_entry,
action="store",
nargs='+',
required=True)
# Optional arguments
optional.add_argument(
'-i',
'--invert_allocation',
help="Allocate with base_address as max and towards lowmem",
default=False,
action="store_true")
optional.add_argument(
'-o',
'--output_type',
help="Select type of output type to generate",
default='table',
choices=['table', 'dts'],
action="store")
optional.add_argument(
'-s',
'--sort_descending',
help="Sort output in decrementing order of start section",
default=False,
action="store_true")
parser._action_groups.append(mandatory_group)
parser._action_groups.append(optional)
return parser.parse_args()
def calculate_map(args):
base_address = args.base_address
map_list = args.mem_region
allocate_down = args.invert_allocation
memory_map = []
current_address = base_address
total_size = 0
for m in map_list:
section_name = m['name']
section_size = m['size']
if allocate_down:
section_end_address = current_address
current_address -= section_size
section_start_address = current_address
else:
section_start_address = current_address
current_address += section_size
section_end_address = current_address
total_size += section_size
memory_entry = {
'name': section_name,
'size': section_size,
'size_human': humanize.naturalsize(section_size, binary=True),
'start': section_start_address,
'end': section_end_address - 1,
}
memory_map.append(memory_entry)
memory_map = sorted(memory_map, key=lambda k: k.get('start', 0), reverse=args.sort_descending)
total_view = {
'start': base_address,
'end': current_address,
'size': total_size,
'size_human': humanize.naturalsize(total_size, binary=True),
}
if allocate_down:
total_view['start'] = current_address
total_view['end'] = base_address
return total_view, memory_map
def generate_output_table(total, memory):
import tabulate
total_table = [
['Start', "End", "Size(in bytes)", "Size(in Hex)",
"Size(human readable)"],
["0x%08x" % total['start'],
"0x%08x" % total['end'],
"%d" % total['size'],
"0x%08x" % total['size'],
total['size_human'],
]
]
memory_table = [
['Section Name',
'Start',
"End",
"Size(in bytes)",
"Size(in Hex)",
"Size(human readable)"],
]
for mem in memory:
section_table = []
section_table.append(mem['name'])
section_table.append("0x%08x" % mem['start'])
section_table.append("0x%08x" % mem['end'])
section_table.append("%d" % mem['size'])
section_table.append("0x%08x" % mem['size'])
section_table.append(mem['size_human'])
memory_table.append(section_table)
print(
tabulate.tabulate(
total_table,
headers='firstrow',
tablefmt='fancy_grid'))
print(
tabulate.tabulate(
memory_table,
headers='firstrow',
tablefmt='fancy_grid'))
def generate_output_dts(total, memory):
print ("reserved_memory: reserved-memory {")
print ("\t#address-cells = <2>;")
print ("\t#size-cells = <2>;")
print ("\t#ranges")
for mem in memory:
name = mem['name']
start = mem['start']
size = mem['size']
print()
print("\t%s: %s@%x {" % (name, name, start))
print('\t\tcompatible = "shared-dma-pool";')
print('\t\treg = <0x00 0x%08x 0x00 0x%08x>;' % (start, size))
print('\t\tno-map;')
print("\t};")
print("};")
def cli_wrapper():
""" If we make this a pypi package eventually, this would be the entry point
"""
cmd_args = parse_args()
total, memory = calculate_map(cmd_args)
if cmd_args.output_type == "table":
generate_output_table(total, memory)
if cmd_args.output_type == "dts":
generate_output_dts(total, memory)
if __name__ == '__main__':
cli_wrapper()
# Format via !autopep8 -i -a %
# vim: et:ts=4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment