blob: c74dc90ff01dc2204ec9066672b1fbc37e194c84 [file] [log] [blame]
Leandro Pereiraca42e852016-12-08 12:55:45 -08001#!/usr/bin/python
2#
3# Copyright (c) 2017 Intel Corporation
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16#
17
18import sys
19import pprint
20
21def read_until(line, fd, end):
22 out = [line]
23 while True:
24 idx = line.find(end)
25 if idx < 0:
26 line = clean_line(fd.readline(), fd)
27 out.append(line)
28 else:
29 out.append(line[idx + len(end):])
30 return out
31
32def remove_comment(line, fd):
33 out = []
34 while True:
35 idx = line.find('/*')
36 if idx < 0:
37 idx = line.find('//')
38 if idx < 0:
39 out.append(line)
40 else:
41 out.append(line[:idx])
42 return ' '.join(out)
43
44 out.append(line[:idx])
45 line = read_until(line[idx:], fd, '*/')[-1]
46
47def clean_line(line, fd):
48 return remove_comment(line, fd).strip()
49
50def parse_node_name(line):
51 line = line[:-1]
52
53 if '@' in line:
54 line, addr = line.split('@')
55 else:
56 addr = None
57
58 if ':' in line:
59 label, name = line.split(':')
60 else:
61 name = line
62 label = None
63
64 if addr is None:
65 return label, name.strip(), None
66
67 return label, name.strip(), int(addr, 16)
68
69def parse_values_internal(value, start, end, separator):
70 out = []
71
72 inside = False
73 accum = []
74 for ch in value:
75 if not inside:
76 if ch == start:
77 inside = True
78 accum = []
79 else:
80 if ch == end:
81 inside = False
82 out.append(''.join(accum))
83 accum = []
84 else:
85 accum.append(ch)
86
87 if separator == ' ':
88 out = [v.split() for v in out]
89
90 if len(out) == 1:
91 return parse_value(out[0])
92
93 return [parse_value(v) for v in out]
94
95def parse_values(value, start, end, separator):
96 out = parse_values_internal(value, start, end, separator)
97 if isinstance(out, list) and all(isinstance(v, str) and len(v) == 1 and not v.isalpha() for v in out):
98 return bytearray(out)
99 return out
100
101def parse_value(value):
102 if value == '':
103 return value
104
105 if isinstance(value, list):
106 out = [parse_value(v) for v in value]
107 return out[0] if len(out) == 1 else out
108
109 if value[0] == '<':
110 return parse_values(value, '<', '>', ' ')
111 if value[0] == '"':
112 return parse_values(value, '"', '"', ',')
113 if value[0] == '[':
114 return parse_values(value, '[', ']', ' ')
115
116 if value[0] == '&':
117 return {'ref': value[1:]}
118
119 if value[0].isdigit():
120 if value.startswith("0x"):
121 return int(value, 16)
122 if value[0] == '0':
123 return int(value, 8)
124 return int(value, 10)
125
126 return value
127
128def parse_property(property, fd):
129 if '=' in property:
130 key, value = property.split('=', 1)
131 value = ' '.join(read_until(value, fd, ';')).strip()
132 if not value.endswith(';'):
133 raise SyntaxError("parse_property: missing semicolon: %s" % value)
134 return key.strip(), parse_value(value[:-1])
135
136 property = property.strip()
137 if not property.endswith(';'):
138 raise SyntaxError("parse_property: missing semicolon: %s" % property)
139
140 return property[:-1].strip(), True
141
142def build_node_name(name, addr):
143 if addr is None:
144 return name
145 return '%s@%x' % (name, addr)
146
147def parse_node(line, fd):
148 label, name, addr = parse_node_name(line)
149
150 node = {
151 'label': label,
152 'type': type,
153 'addr': addr,
154 'children': {},
155 'props': {},
156 'name': build_node_name(name, addr)
157 }
158 while True:
159 line = fd.readline()
160 if not line:
161 raise SyntaxError("parse_node: Missing } while parsing node")
162
163 line = clean_line(line, fd)
164 if not line:
165 continue
166
167 if line == "};":
168 break
169
170 if line.endswith('{'):
171 new_node = parse_node(line, fd)
172 node['children'][new_node['name']] = new_node
173 else:
174 key, value = parse_property(line, fd)
175 node['props'][key] = value
176
177 return node
178
179def parse_file(fd, ignore_dts_version=False):
180 nodes = {}
181 has_v1_tag = False
182 while True:
183 line = fd.readline()
184 if not line:
185 break
186
187 line = clean_line(line, fd)
188 if not line:
189 continue
190
191 if line.startswith('/include/ '):
192 tag, filename = line.split()
193 with open(filename.strip()[1:-1], "r") as new_fd:
194 nodes.update(parse_file(new_fd, True))
195 elif line == '/dts-v1/;':
196 has_v1_tag = True
197 elif line.startswith('/memreserve/ ') and line.endswith(';'):
198 tag, start, end = line.split()
199 start = int(start, 16)
200 end = int(end[:-1], 16)
201 label = "reserved_memory_0x%x_0x%x" % (start, end)
202 nodes[label] = {
203 'type': 'memory',
204 'reg': [start, end],
205 'label': label,
206 'addr': start,
207 'name': build_node_name(name, start)
208 }
209 elif line.endswith('{'):
210 if not has_v1_tag and not ignore_dts_version:
211 raise SyntaxError("parse_file: Missing /dts-v1/ tag")
212
213 new_node = parse_node(line, fd)
214 nodes[new_node['name']] = new_node
215 else:
216 raise SyntaxError("parse_file: Couldn't understand the line: %s" % line)
217 return nodes
218
219def dump_refs(name, value, indent=0):
220 spaces = ' ' * indent
221
222 out = []
223 if isinstance(value, dict) and 'ref' in value:
224 out.append('%s\"%s\" -> \"%s\";' % (spaces, name, value['ref']))
225 elif isinstance(value, list):
226 for elem in value:
227 out.extend(dump_refs(name, elem, indent))
228
229 return out
230
231def dump_all_refs(name, props, indent=0):
232 out = []
233 for key, value in props.items():
234 out.extend(dump_refs(name, value, indent))
235 return out
236
237def next_subgraph(count=[0]):
238 count[0] += 1
239 return 'subgraph cluster_%d' % count[0]
240
241def get_dot_node_name(node):
242 name = node['name']
243 return name[1:] if name[0] == '&' else name
244
245def dump_to_dot(nodes, indent=0, start_string='digraph devicetree', name=None):
246 spaces = ' ' * indent
247
248 print("%s%s {" % (spaces, start_string))
249
250 if name is not None:
251 print("%slabel = \"%s\";" % (spaces, name))
252 print("%s\"%s\";" % (spaces, name))
253
254 ref_list = []
255 for key, value in nodes.items():
256 if value.get('children'):
257 refs = dump_to_dot(value['children'], indent + 1, next_subgraph(), get_dot_node_name(value))
258 ref_list.extend(refs)
259 else:
260 print("%s\"%s\";" % (spaces, get_dot_node_name(value)))
261
262 for key, value in nodes.items():
263 refs = dump_all_refs(get_dot_node_name(value), value.get('props', {}), indent)
264 ref_list.extend(refs)
265
266 if start_string.startswith("digraph"):
267 print("%s%s" % (spaces, '\n'.join(ref_list)))
268
269 print("%s}" % spaces)
270
271 return ref_list
272
273def main(args):
274 if len(args) == 1:
275 print('Usage: %s filename.dts' % args[0])
276 return 1
277
278 if '--dot' in args:
279 formatter = dump_to_dot
280 args.remove('--dot')
281 else:
282 formatter = lambda nodes: pprint.pprint(nodes, indent=2)
283
284 with open(args[1], "r") as fd:
285 formatter(parse_file(fd))
286
287 return 0
288
289if __name__ == '__main__':
290 sys.exit(main(sys.argv))