Skip to content

Instantly share code, notes, and snippets.

@cheshirekow
Created October 6, 2017 21:21
Show Gist options
  • Save cheshirekow/fc010260f8ae69391b811375782a142e to your computer and use it in GitHub Desktop.
Save cheshirekow/fc010260f8ae69391b811375782a142e to your computer and use it in GitHub Desktop.
#!/usr/bin/python
"""
Resolve phandle references from a device tree capture.
"""
import argparse
import logging
import sys
def get_phandle_map(infile):
"""
Return a map of phandle id's to
"""
phandle_map = {}
tree_path = []
for lineno, line in enumerate(infile):
if line.strip().endswith('{'):
tree_path.append(line.strip()[:-1].strip())
elif line.strip() == '};':
tree_path.pop(-1)
elif '=' in line:
lhs, rhs = line.split('=', 1)
if lhs.strip() == 'phandle':
key = int(rhs.strip()[1:-2], 16)
if key in phandle_map:
logging.warn('Duplicate phandle defined: %s on %d', key, lineno)
else:
phandle_map[key] = '/'.join(tree_path)
return phandle_map
def resolve_phandles(infile, outfile, path, keys, phandle_map):
"""
Process each line of infile and if the treepath to that line is a subpath of `path` then
replace all entries with `key` in keys with the path to the referenced node
"""
tree_path = []
for lineno, line in enumerate(infile):
if line.strip().endswith('{'):
tree_path.append(line.strip()[:-1].strip())
outfile.write(line)
elif line.strip() == '};':
tree_path.pop(-1)
outfile.write(line)
elif '=' in line:
if not '/'.join(tree_path).startswith(path):
outfile.write(line)
continue
lhs, rhs = line.split('=', 1)
key = lhs.strip()
if key in keys:
value = int(rhs.strip()[1:-2], 16)
index_of_eq = line.find('=')
outfile.write(line[0:index_of_eq])
outfile.write('= [')
outfile.write(phandle_map[value])
outfile.write('];\n')
else:
outfile.write(line)
def main(argv):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('infile')
parser.add_argument('-o', '--outfile', default='-')
parser.add_argument('-p', '--path', default='/')
parser.add_argument('keys', nargs=argparse.REMAINDER)
args = parser.parse_args(argv)
with open(args.infile, 'r') as infile:
phandle_map = get_phandle_map(infile)
with open(args.infile, 'r') as infile:
if args.outfile == '-':
outfile = sys.stdout
else:
outfile = open(args.outfile, 'w')
with outfile:
resolve_phandles(infile, outfile, args.path, args.keys, phandle_map)
if __name__ == '__main__':
main(sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment