-
Notifications
You must be signed in to change notification settings - Fork 571
/
dtlib.py
2197 lines (1759 loc) · 74.1 KB
/
dtlib.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2019, Nordic Semiconductor
# SPDX-License-Identifier: BSD-3-Clause
# Tip: You can view just the documentation with 'pydoc3 devicetree.dtlib'
"""
A library for extracting information from .dts (devicetree) files. See the
documentation for the DT and Node classes for more information.
The top-level entry point of the library is the DT class. DT.__init__() takes a
.dts file to parse and a list of directories to search for any /include/d
files.
"""
import collections
import enum
import errno
import os
import re
import string
import sys
import textwrap
from typing import Any, Dict, Iterable, List, \
NamedTuple, NoReturn, Optional, Set, Tuple, TYPE_CHECKING, Union
# NOTE: tests/test_dtlib.py is the test suite for this library.
class DTError(Exception):
"Exception raised for devicetree-related errors"
class Node:
r"""
Represents a node in the devicetree ('node-name { ... };').
These attributes are available on Node instances:
name:
The name of the node (a string).
unit_addr:
The portion after the '@' in the node's name, or the empty string if the
name has no '@' in it.
Note that this is a string. Run int(node.unit_addr, 16) to get an
integer.
props:
A dict that maps the properties defined on the node to
their values. 'props' is indexed by property name (a string), and values
are Property objects.
To convert property values to Python numbers or strings, use
dtlib.to_num(), dtlib.to_nums(), or dtlib.to_string().
Property values are represented as 'bytes' arrays to support the full
generality of DTS, which allows assignments like
x = "foo", < 0x12345678 >, [ 9A ];
This gives x the value b"foo\0\x12\x34\x56\x78\x9A". Numbers in DTS are
stored in big-endian format.
nodes:
A dict containing the subnodes of the node, indexed by name.
labels:
A list with all labels pointing to the node, in the same order as the
labels appear, but with duplicates removed.
'label_1: label_2: node { ... };' gives 'labels' the value
["label_1", "label_2"].
parent:
The parent Node of the node. 'None' for the root node.
path:
The path to the node as a string, e.g. "/foo/bar".
dt:
The DT instance this node belongs to.
"""
#
# Public interface
#
def __init__(self, name: str, parent: Optional['Node'], dt: 'DT'):
"""
Node constructor. Not meant to be called directly by clients.
"""
# Remember to update DT.__deepcopy__() if you change this.
self._name = name
self.props: Dict[str, 'Property'] = {}
self.nodes: Dict[str, 'Node'] = {}
self.labels: List[str] = []
self.parent = parent
self.dt = dt
self._omit_if_no_ref = False
self._is_referenced = False
if name.count("@") > 1:
dt._parse_error("multiple '@' in node name")
if not name == "/":
for char in name:
if char not in _nodename_chars:
dt._parse_error(f"{self.path}: bad character '{char}' "
"in node name")
@property
def name(self) -> str:
"""
See the class documentation.
"""
# Converted to a property to discourage renaming -- that has to be done
# via DT.move_node.
return self._name
@property
def unit_addr(self) -> str:
"""
See the class documentation.
"""
return self.name.partition("@")[2]
@property
def path(self) -> str:
"""
See the class documentation.
"""
node_names = []
# This dynamic computation is required to be able to move
# nodes in the DT class.
cur = self
while cur.parent:
node_names.append(cur.name)
cur = cur.parent
return "/" + "/".join(reversed(node_names))
def node_iter(self) -> Iterable['Node']:
"""
Returns a generator for iterating over the node and its children,
recursively.
For example, this will iterate over all nodes in the tree (like
dt.node_iter()).
for node in dt.root.node_iter():
...
"""
yield self
for node in self.nodes.values():
yield from node.node_iter()
def _get_prop(self, name: str) -> 'Property':
# Returns the property named 'name' on the node, creating it if it
# doesn't already exist
prop = self.props.get(name)
if not prop:
prop = Property(self, name)
self.props[name] = prop
return prop
def _del(self) -> None:
# Removes the node from the tree
self.parent.nodes.pop(self.name) # type: ignore
def __str__(self):
"""
Returns a DTS representation of the node. Called automatically if the
node is print()ed.
"""
s = "".join(label + ": " for label in self.labels)
s += f"{self.name} {{\n"
for prop in self.props.values():
s += "\t" + str(prop) + "\n"
for child in self.nodes.values():
s += textwrap.indent(child.__str__(), "\t") + "\n"
s += "};"
return s
def __repr__(self):
"""
Returns some information about the Node instance. Called automatically
if the Node instance is evaluated.
"""
return f"<Node {self.path} in '{self.dt.filename}'>"
# See Property.type
class Type(enum.IntEnum):
EMPTY = 0
BYTES = 1
NUM = 2
NUMS = 3
STRING = 4
STRINGS = 5
PATH = 6
PHANDLE = 7
PHANDLES = 8
PHANDLES_AND_NUMS = 9
COMPOUND = 10
class _MarkerType(enum.IntEnum):
# Types of markers in property values
# References
PATH = 0 # &foo
PHANDLE = 1 # <&foo>
LABEL = 2 # foo: <1 2 3>
# Start of data blocks of specific type
UINT8 = 3 # [00 01 02] (and also used for /incbin/)
UINT16 = 4 # /bits/ 16 <1 2 3>
UINT32 = 5 # <1 2 3>
UINT64 = 6 # /bits/ 64 <1 2 3>
STRING = 7 # "foo"
class Property:
"""
Represents a property ('x = ...').
These attributes are available on Property instances:
name:
The name of the property (a string).
value:
The value of the property, as a 'bytes' string. Numbers are stored in
big-endian format, and strings are null-terminated. Putting multiple
comma-separated values in an assignment (e.g., 'x = < 1 >, "foo"') will
concatenate the values.
See the to_*() methods for converting the value to other types.
type:
The type of the property, inferred from the syntax used in the
assignment. This is one of the following constants (with example
assignments):
Assignment | Property.type
----------------------------+------------------------
foo; | dtlib.Type.EMPTY
foo = []; | dtlib.Type.BYTES
foo = [01 02]; | dtlib.Type.BYTES
foo = /bits/ 8 <1>; | dtlib.Type.BYTES
foo = <1>; | dtlib.Type.NUM
foo = <>; | dtlib.Type.NUMS
foo = <1 2 3>; | dtlib.Type.NUMS
foo = <1 2>, <3>; | dtlib.Type.NUMS
foo = "foo"; | dtlib.Type.STRING
foo = "foo", "bar"; | dtlib.Type.STRINGS
foo = <&l>; | dtlib.Type.PHANDLE
foo = <&l1 &l2 &l3>; | dtlib.Type.PHANDLES
foo = <&l1 &l2>, <&l3>; | dtlib.Type.PHANDLES
foo = <&l1 1 2 &l2 3 4>; | dtlib.Type.PHANDLES_AND_NUMS
foo = <&l1 1 2>, <&l2 3 4>; | dtlib.Type.PHANDLES_AND_NUMS
foo = &l; | dtlib.Type.PATH
*Anything else* | dtlib.Type.COMPOUND
*Anything else* includes properties mixing phandle (<&label>) and node
path (&label) references with other data.
Data labels in the property value do not influence the type.
labels:
A list with all labels pointing to the property, in the same order as the
labels appear, but with duplicates removed.
'label_1: label2: x = ...' gives 'labels' the value
["label_1", "label_2"].
offset_labels:
A dictionary that maps any labels within the property's value to their
offset, in bytes. For example, 'x = < 0 label_1: 1 label_2: >' gives
'offset_labels' the value {"label_1": 4, "label_2": 8}.
Iteration order will match the order of the labels on Python versions
that preserve dict insertion order.
node:
The Node the property is on.
"""
#
# Public interface
#
def __init__(self, node: Node, name: str):
# Remember to update DT.__deepcopy__() if you change this.
if "@" in name:
node.dt._parse_error("'@' is only allowed in node names")
self.name = name
self.value = b""
self.labels: List[str] = []
# We have to wait to set this until later, when we've got
# the entire tree.
self.offset_labels: Dict[str, int] = {}
self.node: Node = node
self._label_offset_lst: List[Tuple[str, int]] = []
# A list of [offset, label, type] lists (sorted by offset),
# giving the locations of references within the value. 'type'
# is either _MarkerType.PATH, for a node path reference,
# _MarkerType.PHANDLE, for a phandle reference, or
# _MarkerType.LABEL, for a label on/within data. Node paths
# and phandles need to be patched in after parsing.
self._markers: List[List] = []
@property
def type(self) -> Type:
"""
See the class documentation.
"""
# Data labels (e.g. 'foo = label: <3>') are irrelevant, so filter them
# out
types = [marker[1] for marker in self._markers
if marker[1] != _MarkerType.LABEL]
if not types:
return Type.EMPTY
if types == [_MarkerType.UINT8]:
return Type.BYTES
if types == [_MarkerType.UINT32]:
return Type.NUM if len(self.value) == 4 else Type.NUMS
# Treat 'foo = <1 2 3>, <4 5>, ...' as Type.NUMS too
if set(types) == {_MarkerType.UINT32}:
return Type.NUMS
if set(types) == {_MarkerType.STRING}:
return Type.STRING if len(types) == 1 else Type.STRINGS
if types == [_MarkerType.PATH]:
return Type.PATH
if types == [_MarkerType.UINT32, _MarkerType.PHANDLE] and \
len(self.value) == 4:
return Type.PHANDLE
if set(types) == {_MarkerType.UINT32, _MarkerType.PHANDLE}:
if len(self.value) == 4*types.count(_MarkerType.PHANDLE):
# Array with just phandles in it
return Type.PHANDLES
# Array with both phandles and numbers
return Type.PHANDLES_AND_NUMS
return Type.COMPOUND
def to_num(self, signed=False) -> int:
"""
Returns the value of the property as a number.
Raises DTError if the property was not assigned with this syntax (has
Property.type Type.NUM):
foo = < 1 >;
signed (default: False):
If True, the value will be interpreted as signed rather than
unsigned.
"""
if self.type is not Type.NUM:
_err("expected property '{0}' on {1} in {2} to be assigned with "
"'{0} = < (number) >;', not '{3}'"
.format(self.name, self.node.path, self.node.dt.filename,
self))
return int.from_bytes(self.value, "big", signed=signed)
def to_nums(self, signed=False) -> List[int]:
"""
Returns the value of the property as a list of numbers.
Raises DTError if the property was not assigned with this syntax (has
Property.type Type.NUM or Type.NUMS):
foo = < 1 2 ... >;
signed (default: False):
If True, the values will be interpreted as signed rather than
unsigned.
"""
if self.type not in (Type.NUM, Type.NUMS):
_err("expected property '{0}' on {1} in {2} to be assigned with "
"'{0} = < (number) (number) ... >;', not '{3}'"
.format(self.name, self.node.path, self.node.dt.filename,
self))
return [int.from_bytes(self.value[i:i + 4], "big", signed=signed)
for i in range(0, len(self.value), 4)]
def to_bytes(self) -> bytes:
"""
Returns the value of the property as a raw 'bytes', like
Property.value, except with added type checking.
Raises DTError if the property was not assigned with this syntax (has
Property.type Type.BYTES):
foo = [ 01 ... ];
"""
if self.type is not Type.BYTES:
_err("expected property '{0}' on {1} in {2} to be assigned with "
"'{0} = [ (byte) (byte) ... ];', not '{3}'"
.format(self.name, self.node.path, self.node.dt.filename,
self))
return self.value
def to_string(self) -> str:
"""
Returns the value of the property as a string.
Raises DTError if the property was not assigned with this syntax (has
Property.type Type.STRING):
foo = "string";
This function might also raise UnicodeDecodeError if the string is
not valid UTF-8.
"""
if self.type is not Type.STRING:
_err("expected property '{0}' on {1} in {2} to be assigned with "
"'{0} = \"string\";', not '{3}'"
.format(self.name, self.node.path, self.node.dt.filename,
self))
try:
ret = self.value.decode("utf-8")[:-1] # Strip null
except UnicodeDecodeError:
_err(f"value of property '{self.name}' ({self.value!r}) "
f"on {self.node.path} in {self.node.dt.filename} "
"is not valid UTF-8")
return ret # The separate 'return' appeases the type checker.
def to_strings(self) -> List[str]:
"""
Returns the value of the property as a list of strings.
Raises DTError if the property was not assigned with this syntax (has
Property.type Type.STRING or Type.STRINGS):
foo = "string", "string", ... ;
Also raises DTError if any of the strings are not valid UTF-8.
"""
if self.type not in (Type.STRING, Type.STRINGS):
_err("expected property '{0}' on {1} in {2} to be assigned with "
"'{0} = \"string\", \"string\", ... ;', not '{3}'"
.format(self.name, self.node.path, self.node.dt.filename,
self))
try:
ret = self.value.decode("utf-8").split("\0")[:-1]
except UnicodeDecodeError:
_err(f"value of property '{self.name}' ({self.value!r}) "
f"on {self.node.path} in {self.node.dt.filename} "
"is not valid UTF-8")
return ret # The separate 'return' appeases the type checker.
def to_node(self) -> Node:
"""
Returns the Node the phandle in the property points to.
Raises DTError if the property was not assigned with this syntax (has
Property.type Type.PHANDLE).
foo = < &bar >;
"""
if self.type is not Type.PHANDLE:
_err("expected property '{0}' on {1} in {2} to be assigned with "
"'{0} = < &foo >;', not '{3}'"
.format(self.name, self.node.path, self.node.dt.filename,
self))
return self.node.dt.phandle2node[int.from_bytes(self.value, "big")]
def to_nodes(self) -> List[Node]:
"""
Returns a list with the Nodes the phandles in the property point to.
Raises DTError if the property value contains anything other than
phandles. All of the following are accepted:
foo = < >
foo = < &bar >;
foo = < &bar &baz ... >;
foo = < &bar ... >, < &baz ... >;
"""
def type_ok():
if self.type in (Type.PHANDLE, Type.PHANDLES):
return True
# Also accept 'foo = < >;'
return self.type is Type.NUMS and not self.value
if not type_ok():
_err("expected property '{0}' on {1} in {2} to be assigned with "
"'{0} = < &foo &bar ... >;', not '{3}'"
.format(self.name, self.node.path,
self.node.dt.filename, self))
return [self.node.dt.phandle2node[int.from_bytes(self.value[i:i + 4],
"big")]
for i in range(0, len(self.value), 4)]
def to_path(self) -> Node:
"""
Returns the Node referenced by the path stored in the property.
Raises DTError if the property was not assigned with either of these
syntaxes (has Property.type Type.PATH or Type.STRING):
foo = &bar;
foo = "/bar";
For the second case, DTError is raised if the path does not exist.
"""
if self.type not in (Type.PATH, Type.STRING):
_err("expected property '{0}' on {1} in {2} to be assigned with "
"either '{0} = &foo' or '{0} = \"/path/to/node\"', not '{3}'"
.format(self.name, self.node.path, self.node.dt.filename,
self))
try:
path = self.value.decode("utf-8")[:-1]
except UnicodeDecodeError:
_err(f"value of property '{self.name}' ({self.value!r}) "
f"on {self.node.path} in {self.node.dt.filename} "
"is not valid UTF-8")
try:
ret = self.node.dt.get_node(path)
except DTError:
_err(f"property '{self.name}' on {self.node.path} in "
f"{self.node.dt.filename} points to the non-existent node "
f'"{path}"')
return ret # The separate 'return' appeases the type checker.
def __str__(self):
s = "".join(label + ": " for label in self.labels) + self.name
if not self.value:
return s + ";"
s += " ="
for i, (pos, marker_type, ref) in enumerate(self._markers):
if i < len(self._markers) - 1:
next_marker = self._markers[i + 1]
else:
next_marker = None
# End of current marker
end = next_marker[0] if next_marker else len(self.value)
if marker_type is _MarkerType.STRING:
# end - 1 to strip off the null terminator
s += f' "{_decode_and_escape(self.value[pos:end - 1])}"'
if end != len(self.value):
s += ","
elif marker_type is _MarkerType.PATH:
s += " &" + ref
if end != len(self.value):
s += ","
else:
# <> or []
if marker_type is _MarkerType.LABEL:
s += f" {ref}:"
elif marker_type is _MarkerType.PHANDLE:
s += " &" + ref
pos += 4
# Subtle: There might be more data between the phandle and
# the next marker, so we can't 'continue' here
else: # marker_type is _MarkerType.UINT*
elm_size = _TYPE_TO_N_BYTES[marker_type]
s += _N_BYTES_TO_START_STR[elm_size]
while pos != end:
num = int.from_bytes(self.value[pos:pos + elm_size],
"big")
if elm_size == 1:
s += f" {num:02X}"
else:
s += f" {hex(num)}"
pos += elm_size
if pos != 0 and \
(not next_marker or
next_marker[1] not in (_MarkerType.PHANDLE, _MarkerType.LABEL)):
s += _N_BYTES_TO_END_STR[elm_size]
if pos != len(self.value):
s += ","
return s + ";"
def __repr__(self):
return f"<Property '{self.name}' at '{self.node.path}' in " \
f"'{self.node.dt.filename}'>"
#
# Internal functions
#
def _add_marker(self, marker_type: _MarkerType, data: Any = None):
# Helper for registering markers in the value that are processed after
# parsing. See _fixup_props(). 'marker_type' identifies the type of
# marker, and 'data' has any optional data associated with the marker.
# len(self.value) gives the current offset. This function is called
# while the value is built. We use a list instead of a tuple to be able
# to fix up offsets later (they might increase if the value includes
# path references, e.g. 'foo = &bar, <3>;', which are expanded later).
self._markers.append([len(self.value), marker_type, data])
# For phandle references, add a dummy value with the same length as a
# phandle. This is handy for the length check in _register_phandles().
if marker_type is _MarkerType.PHANDLE:
self.value += b"\0\0\0\0"
class _T(enum.IntEnum):
# Token IDs used by the DT lexer.
# These values must be contiguous and start from 1.
INCLUDE = 1
LINE = 2
STRING = 3
DTS_V1 = 4
PLUGIN = 5
MEMRESERVE = 6
BITS = 7
DEL_PROP = 8
DEL_NODE = 9
OMIT_IF_NO_REF = 10
LABEL = 11
CHAR_LITERAL = 12
REF = 13
INCBIN = 14
SKIP = 15
EOF = 16
# These values must be larger than the above contiguous range.
NUM = 17
PROPNODENAME = 18
MISC = 19
BYTE = 20
BAD = 21
class _FileStackElt(NamedTuple):
# Used for maintaining the /include/ stack.
filename: str
lineno: int
contents: str
pos: int
_TokVal = Union[int, str]
class _Token(NamedTuple):
id: int
val: _TokVal
def __repr__(self):
id_repr = _T(self.id).name
return f'Token(id=_T.{id_repr}, val={repr(self.val)})'
class DT:
"""
Represents a devicetree parsed from a .dts file (or from many files, if the
.dts file /include/s other files). Creating many instances of this class is
fine. The library has no global state.
These attributes are available on DT instances:
root:
A Node instance representing the root (/) node.
alias2node:
A dictionary that maps maps alias strings (from /aliases) to Node
instances
label2node:
A dictionary that maps each node label (a string) to the Node instance
for the node.
label2prop:
A dictionary that maps each property label (a string) to a Property
instance.
label2prop_offset:
A dictionary that maps each label (a string) within a property value
(e.g., 'x = label_1: < 1 label2: 2 >;') to a (prop, offset) tuple, where
'prop' is a Property instance and 'offset' the byte offset (0 for label_1
and 4 for label_2 in the example).
phandle2node:
A dictionary that maps each phandle (a number) to a Node instance.
memreserves:
A list of (labels, address, length) tuples for the /memreserve/s in the
.dts file, in the same order as they appear in the file.
'labels' is a possibly empty set with all labels preceding the memreserve
(e.g., 'label1: label2: /memreserve/ ...'). 'address' and 'length' are
numbers.
filename:
The filename passed to the DT constructor.
"""
#
# Public interface
#
def __init__(self, filename: Optional[str], include_path: Iterable[str] = (),
force: bool = False):
"""
Parses a DTS file to create a DT instance. Raises OSError if 'filename'
can't be opened, and DTError for any parse errors.
filename:
Path to the .dts file to parse. (If None, an empty devicetree
is created; this is unlikely to be what you want.)
include_path:
An iterable (e.g. list or tuple) containing paths to search for
/include/d and /incbin/'d files. By default, files are only looked up
relative to the .dts file that contains the /include/ or /incbin/.
force:
Try not to raise DTError even if the input tree has errors.
For experimental use; results not guaranteed.
"""
# Remember to update __deepcopy__() if you change this.
self._root: Optional[Node] = None
self.alias2node: Dict[str, Node] = {}
self.label2node: Dict[str, Node] = {}
self.label2prop: Dict[str, Property] = {}
self.label2prop_offset: Dict[str, Tuple[Property, int]] = {}
self.phandle2node: Dict[int, Node] = {}
self.memreserves: List[Tuple[Set[str], int, int]] = []
self.filename = filename
self._force = force
if filename is not None:
self._parse_file(filename, include_path)
else:
self._include_path: List[str] = []
@property
def root(self) -> Node:
"""
See the class documentation.
"""
# This is necessary because mypy can't tell that we never
# treat self._root as a non-None value until it's initialized
# properly in _parse_dt().
return self._root # type: ignore
def get_node(self, path: str) -> Node:
"""
Returns the Node instance for the node with path or alias 'path' (a
string). Raises DTError if the path or alias doesn't exist.
For example, both dt.get_node("/foo/bar") and dt.get_node("bar-alias")
will return the 'bar' node below:
/dts-v1/;
/ {
foo {
bar_label: bar {
baz {
};
};
};
aliases {
bar-alias = &bar-label;
};
};
Fetching subnodes via aliases is supported:
dt.get_node("bar-alias/baz") returns the 'baz' node.
"""
if path.startswith("/"):
return _root_and_path_to_node(self.root, path, path)
# Path does not start with '/'. First component must be an alias.
alias, _, rest = path.partition("/")
if alias not in self.alias2node:
_err(f"no alias '{alias}' found -- did you forget the leading "
"'/' in the node path?")
return _root_and_path_to_node(self.alias2node[alias], rest, path)
def has_node(self, path: str) -> bool:
"""
Returns True if the path or alias 'path' exists. See DT.get_node().
"""
try:
self.get_node(path)
return True
except DTError:
return False
def move_node(self, node: Node, new_path: str):
"""
Move a node 'node' to a new path 'new_path'. The entire subtree
rooted at 'node' is moved along with it.
You cannot move the root node or provide a 'new_path' value
where a node already exists. This method raises an exception
in both cases.
As a restriction on the current implementation, the parent node
of the new path must exist.
"""
if node is self.root:
_err("the root node can't be moved")
if self.has_node(new_path):
_err(f"can't move '{node.path}' to '{new_path}': "
'destination node exists')
if not new_path.startswith('/'):
_err(f"path '{new_path}' doesn't start with '/'")
for component in new_path.split('/'):
for char in component:
if char not in _nodename_chars:
_err(f"new path '{new_path}': bad character '{char}'")
old_name = node.name
old_path = node.path
new_parent_path, _, new_name = new_path.rpartition('/')
if new_parent_path == '':
# '/foo'.rpartition('/') is ('', '/', 'foo').
new_parent_path = '/'
if not self.has_node(new_parent_path):
_err(f"can't move '{old_path}' to '{new_path}': "
f"parent node '{new_parent_path}' doesn't exist")
new_parent = self.get_node(new_parent_path)
if TYPE_CHECKING:
assert new_parent is not None
assert node.parent is not None
del node.parent.nodes[old_name]
node._name = new_name
node.parent = new_parent
new_parent.nodes[new_name] = node
def node_iter(self) -> Iterable[Node]:
"""
Returns a generator for iterating over all nodes in the devicetree.
For example, this will print the name of each node that has a property
called 'foo':
for node in dt.node_iter():
if "foo" in node.props:
print(node.name)
"""
yield from self.root.node_iter()
def __str__(self):
"""
Returns a DTS representation of the devicetree. Called automatically if
the DT instance is print()ed.
"""
s = "/dts-v1/;\n\n"
if self.memreserves:
for labels, address, offset in self.memreserves:
# List the labels in a consistent order to help with testing
for label in labels:
s += f"{label}: "
s += f"/memreserve/ {address:#018x} {offset:#018x};\n"
s += "\n"
return s + str(self.root)
def __repr__(self):
"""
Returns some information about the DT instance. Called automatically if
the DT instance is evaluated.
"""
if self.filename:
return f"DT(filename='{self.filename}', " \
f"include_path={self._include_path})"
return super().__repr__()
def __deepcopy__(self, memo):
"""
Implements support for the standard library copy.deepcopy()
function on DT instances.
"""
# We need a new DT, obviously. Make a new, empty one.
ret = DT(None, (), self._force)
# Now allocate new Node objects for every node in self, to use
# in the new DT. Set their parents to None for now and leave
# them without any properties. We will recursively initialize
# copies of parents before copies of children next.
path2node_copy = {
node.path: Node(node.name, None, ret)
for node in self.node_iter()
}
# Point each copy of a node to the copy of its parent and set up
# copies of each property.
#
# Share data when possible. For example, Property.value has
# type 'bytes', which is immutable. We therefore don't need a
# copy and can just point to the original data.
for node in self.node_iter():
node_copy = path2node_copy[node.path]
parent = node.parent
if parent is not None:
node_copy.parent = path2node_copy[parent.path]
prop_name2prop_copy = {
prop.name: Property(node_copy, prop.name)
for prop in node.props.values()
}
for prop_name, prop_copy in prop_name2prop_copy.items():
prop = node.props[prop_name]
prop_copy.value = prop.value
prop_copy.labels = prop.labels[:]
prop_copy.offset_labels = prop.offset_labels.copy()
prop_copy._label_offset_lst = prop._label_offset_lst[:]
prop_copy._markers = [marker[:] for marker in prop._markers]
node_copy.props = prop_name2prop_copy
node_copy.nodes = {
child_name: path2node_copy[child_node.path]
for child_name, child_node in node.nodes.items()
}
node_copy.labels = node.labels[:]
node_copy._omit_if_no_ref = node._omit_if_no_ref
node_copy._is_referenced = node._is_referenced
# The copied nodes and properties are initialized, so
# we can finish initializing the copied DT object now.
ret._root = path2node_copy['/']
def copy_node_lookup_table(attr_name):
original = getattr(self, attr_name)
copy = {
key: path2node_copy[original[key].path]
for key in original
}
setattr(ret, attr_name, copy)
copy_node_lookup_table('alias2node')
copy_node_lookup_table('label2node')
copy_node_lookup_table('phandle2node')
ret_label2prop = {}
for label, prop in self.label2prop.items():
node_copy = path2node_copy[prop.node.path]
prop_copy = node_copy.props[prop.name]
ret_label2prop[label] = prop_copy
ret.label2prop = ret_label2prop
ret_label2prop_offset = {}
for label, prop_offset in self.label2prop_offset.items():
prop, offset = prop_offset
node_copy = path2node_copy[prop.node.path]
prop_copy = node_copy.props[prop.name]
ret_label2prop_offset[label] = (prop_copy, offset)
ret.label2prop_offset = ret_label2prop_offset