forked from devicetree-org/lopper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lopper_tree.py
3579 lines (2756 loc) · 120 KB
/
lopper_tree.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,2020 Xilinx Inc. All rights reserved.
# *
# * Author:
# * Bruce Ashfield <bruce.ashfield@xilinx.com>
# *
# * SPDX-License-Identifier: BSD-3-Clause
# */
import struct
import sys
import types
import os
import re
import shutil
from pathlib import Path
from pathlib import PurePath
import tempfile
from enum import Enum
import textwrap
from collections import UserDict
from collections import OrderedDict
from collections import Counter
import copy
# used in node_filter
class LopperAction(Enum):
"""Enum class to define the actions available in Lopper's node_filter function
"""
DELETE = 1
REPORT = 2
WHITELIST = 3
BLACKLIST = 4
NONE = 5
class LopperProp():
"""Class representing a device tree property
This class implements:
- resolve(): to update information / state against a device tree
- sync(): to write changes back to the device tree
- utility routines for easy access and iteration of the values
Attributes:
- __modified__: Flag to indicate if the property has been changed
- __pstate__: The state of the property. For internal use only.
Values can be: "init", "resolved", "syncd" or "deleted"
- __dbg__: The debug/verbosity level of property operations. 0 is no
debug, and levels increase from there.
- name: The property name
- value: The property value (always as a list of values)
- node: The node that contains this property
- number: The property offset within the containing node (rarely used)
- string_val: The enhanced printed string representation of a property
- type: The type of a property, "comment", "preamble" or "list"
- abs_path: The absolute device tree path to this property
"""
def __init__(self, name, number = -1, node = None, value = None, debug_lvl = 0 ):
self.__modified__ = True
self.__pstate__ = "init"
self.__dbg__ = debug_lvl
self.name = name
self.node = node
self.number = number
if value == None:
self.value = []
else:
# we want to avoid the overriden __setattr__ below
self.__dict__["value"] = value
self.string_val = "**unresolved**"
self.pclass = ""
self.ptype = ""
self.binary = False
self.abs_path = ""
def __deepcopy__(self, memodict={}):
""" Create a deep copy of a property
Properties have links to nodes, so we need to ensure that they are
cleared as part of a deep copy.
"""
if self.__dbg__ > 1:
print( "[DBG++]: property '%s' deepcopy start: %s" % (self.name,[self]) )
new_instance = LopperProp(self.name)
# if we blindly want everything, we'd do this update. But it
# is easier to pick out the properties that we do want, versus
# copying and undoing.
# new_instance.__dict__.update(self.__dict__)
new_instance.__dbg__ = copy.deepcopy( self.number, memodict )
new_instance.value = copy.deepcopy( self.value, memodict )
new_instance.__pstate__ = "init"
new_instance.node = None
if self.__dbg__ > 1:
print( "[DBG++]: property deep copy done: %s" % [self] )
return new_instance
def __str__( self ):
"""The string representation of the property
Returns the enhanced printed property when str() is used to access
an object.
The string_val is composed in the resolv() function, and takes the
format of: <property name> = <property value>;
Args:
None
Returns:
string
"""
return self.string_val
def int(self):
"""Get the property value as a list of integers
Args:
None
Returns:
list: integer formatted property value
"""
ret_val = []
for p in self.value:
ret_val.append( p )
return ret_val
def hex(self):
"""Get the property value as a list of hex formatted numbers
Args:
None
Returns:
list: hex formatted property value
"""
ret_val = []
for p in self.value:
ret_val.append( hex(p) )
return ret_val
def __setattr__(self, name, value):
"""magic method to check the setting of a LopperProp attribute
If the attribute being set is "value" (i.e. LopperProp.value), this
method makes sure that it is stored as a list, that the property is
marked as modified (for future write backs) and triggers a resolve()
of the property value.
Args:
name: attribute name
value: attribute value
Returns:
Nothing
"""
# a little helper to make sure that we keep up our list-ness!
if name == "value":
try:
old_value = self.__dict__[name]
except:
old_value = []
if type(value) != list:
self.__dict__[name] = [ value ]
else:
self.__dict__[name] = value
if Counter(old_value) != Counter(self.__dict__[name]):
self.__modified__ = True
self.resolve()
else:
self.__dict__[name] = value
def compare( self, other_prop ):
"""Compare one property to another
Due to the complexity of property representations, this compare is
not a strict 1:1 value equality. It looks through various elements
of the source and comparision properties to decide if they have
common components.
The following metrics are used, where "single" means a property with
a single value (string or number) and "list" is a property with
multiple strings or integer properties.
comparison types:
single -> list: single must be somewhere in the list
- for strings, single may be a regex
single -> single: single must be in or equal the other
- for strings, single may be a regex
list -> single: any value in list must match single
- for strings, list elements can be regexs
list -> list: all individual elements must match
- NO regexs allowed
Args:
other_prop (LopperProp): comparison target
value: attribute value
Returns:
boolean: True there is a match, false otherwise
"""
if self.__dbg__ > 1:
print( "[DBG++]: property compare (%s) vs (%s)" % (self,other_prop) )
ret_val = False
invert_check = ""
if len(self.value) == 1:
# single comparison value
lop_compare_value = self.value[0]
if len( other_prop.value ) == 1:
# check if this is actually a phandle property
idx, pfields = self.phandle_params()
# idx2, pfields2 = other_prop.phandle_params()
if pfields > 0:
if self.ptype == LopperFmt.STRING:
# check for "&" to designate that it is a phandle, if it isn't
# there, throw an error. If it is there, remove it, since we
# don't use it for the lookup.
if re.search( '&', lop_compare_value ):
lop_compare_value = re.sub( '&', '', lop_compare_value )
else:
print( "[ERROR]: phandle is being compared, and target node does not start with &" )
sys.exit(1)
# this is a phandle, but is currently a string, we need to
# resolve the value.
nodes = other_prop.node.tree.nodes( lop_compare_value )
if not nodes:
nodes = other_prop.node.tree.lnodes( lop_compare_value )
if nodes:
phandle = nodes[0].phandle
else:
phandle = 0
# update our value so the rest of the code can stay the same
self.ptype = LopperFmt.UINT32
self.value[0] = phandle
# single -> single: single must be in or equal the other
lop_compare_value = self.value[0]
tgt_node_compare_value = other_prop.value[0]
if other_prop.ptype == LopperFmt.STRING or \
self.ptype == LopperFmt.STRING: # type(lop_compare_value) == str:
constructed_condition = "{0} re.search(\"{1}\",\"{2}\")".format(invert_check,lop_compare_value,tgt_node_compare_value)
elif other_prop.ptype == LopperFmt.UINT32: # type(lop_compare_value) == int:
constructed_condition = "{0} {1} == {2}".format(invert_check,lop_compare_value,tgt_node_compare_value)
if self.__dbg__ > 2:
print( "[DBG+++]: single:single. Condition: %s" % (constructed_condition))
constructed_check = eval(constructed_condition)
if constructed_check:
ret_val = True
else:
ret_val = False
else:
# single -> list: single must be somewhere in the list
# - for strings, single may be a regex
lop_compare_value = self.value[0]
ret_val = False
for tgt_node_compare_value in other_prop.value:
# if we have found a match, we are done and can stop comparing
if ret_val:
continue
# otherwise, run the compare
if self.ptype == LopperFmt.STRING: # type(lop_compare_value) == str:
constructed_condition = "{0} re.search(\"{1}\",\"{2}\")".format(invert_check,lop_compare_value,tgt_node_compare_value)
elif self.ptype == LopperFmt.UINT32: # type(lop_compare_value) == int:
constructed_condition = "{0} {1} == {2}".format(invert_check,lop_compare_value,tgt_node_compare_value)
if self.__dbg__ > 2:
print( "[DBG+++]: single:list. Condition: %s" % (constructed_condition))
constructed_check = eval(constructed_condition)
if constructed_check:
ret_val = True
else:
ret_val = False
else:
# list comparison value
if len( other_prop.value ) == 1:
# list -> single: any value in list must match single
# - for strings, list elements can be regexs
tgt_node_compare_value = other_prop.value[0]
for lop_compare_value in self.value:
# if we have found a match, we are done and can stop comparing
if ret_val:
continue
# otherwise, run the compare
if self.ptype == LopperFmt.STRING: # type(lop_compare_value) == str:
constructed_condition = "{0} re.search(\"{1}\",\"{2}\")".format(invert_check,lop_compare_value,tgt_node_compare_value)
elif self.ptype == LopperFmt.UINT32: # type(lop_compare_value) == int:
constructed_condition = "{0} {1} == {2}".format(invert_check,lop_compare_value,tgt_node_compare_value)
if self.__dbg__ > 2:
print( "[DBG+++]: list:single. Condition: %s" % (constructed_condition))
constructed_check = eval(constructed_condition)
if constructed_check:
ret_val = True
else:
ret_val = False
else:
lop_compare_value = self.value
tgt_node_compare_value = other_prop.value
# list -> list
# regex are not supported (since we'd have to index iterate and run
# different compares. So instead, we just compare the lists directly
if self.__dbg__ > 2:
print( "[DBG+++]: list:list. Condition: %s == %s" % (lop_compare_value,tgt_node_compare_value))
if lop_compare_value == tgt_node_compare_value:
ret_val = True
else:
ret_val = False
if self.__dbg__ > 2:
print( "[DBG+++]: prop compare: %s" % (ret_val))
return ret_val
def phandle_params( self ):
"""Determines the phandle elements/params of a property
Takes a property name and returns where to find a phandle in
that property.
Both the index of the phandle, and the number of fields in
the property are returned.
Args:
None
Returns:
The the phandle index and number of fields, if the node can't
be found 0, 0 are returned.
"""
phandle_props = Lopper.phandle_possible_properties()
if self.name in phandle_props.keys():
property_description = phandle_props[self.name]
property_fields = property_description[0].split()
phandle_idx = 0
phandle_field_count = 0
for f in property_fields:
if re.search( '^#.*', f ):
try:
field_val = self.node.__props__[f].value[0]
except:
field_val = 0
if not field_val:
field_val = 1
phandle_field_count = phandle_field_count + field_val
elif re.search( '^phandle', f ):
phandle_field_count = phandle_field_count + 1
phandle_idx = phandle_field_count
# if a phandle field is of the format "phandle:<#property>", then
# we need to dereference the phandle, and get the value of #property
# to figure out the indexes.
derefs = f.split(':')
if len(derefs) == 2:
# we have to deference the phandle, and look at the property
# specified to know the count
try:
phandle_tgt_val = self.value[phandle_field_count - 1]
tgn = self.node.tree.pnode( phandle_tgt_val )
if tgn == None:
# if we couldn't find the target, maybe it is in
# as a string. So let's check that way.
tgn2 = self.node.tree.nodes( phandle_tgt_val )
if not tgn2:
tgn2 = self.node.tree.lnodes( phandle_tgt_val )
if tgn2:
tgn = tgn2[0]
if tgn:
try:
cell_count = tgn[derefs[1]].value[0]
except:
cell_count = 0
phandle_field_count = phandle_field_count + cell_count
except:
# either we had no value, or something else wasn't defined
# yet, so we continue on with the initial values set at
# the top (i.e. treat it just as a non dereferenced phandle
pass
else:
# it's a placeholder field, count it as one
phandle_field_count = phandle_field_count + 1
else:
phandle_idx = 0
phandle_field_count = 0
return phandle_idx, phandle_field_count
def sync( self, fdt ):
"""sync the property to a backing FDT
Writes the property value to the backing flattended device tree. After
write, the state is set to "syncd" and the modified flat is cleared.
Args:
fdt (FDT): flattened device tree to sync to
Returns:
boolean: True if the property was sync'd, otherwise False
"""
# we could do a read-and-set-if-different
if self.__dbg__ > 2:
print( "[DBG+++]: property sync: node: %s [%s], name: %s value: %s" %
([self.node],self.node.number,self.name,self.value))
# TODO (possibly). This should just return the value as a dictionary entry,
# which is actually sync'd by some controller caller OR
# It really does sync by calling lopper with an exported
# dictionary entry.
#
# For now, it is here for compatibility with older assists, and simply updates
# the state of the property.
#
self.__modified__ = False
self.__pstate__ = "syncd"
return True
def resolve_phandles( self ):
"""Resolve the targets of any phandles in a property
Args:
None
Returns:
A list of all resolved phandle node numbers, [] if no phandles are present
"""
phandle_targets = []
idx, pfields = self.phandle_params()
if idx == 0:
return phandle_targets
# we need the values in hex. This could be a utility routine in the
# future .. convert to hex.
prop_val = []
for f in self.value:
if type(f) == str:
prop_val.append( f )
else:
prop_val.append( hex(f) )
if not prop_val:
return phandle_targets
phandle_idxs = list(range(1,len(prop_val) + 1))
phandle_idxs = phandle_idxs[idx - 1::pfields]
element_count = 1
element_total = len(prop_val)
for i in prop_val:
base = 10
if re.search( "0x", i ):
base = 16
try:
i_as_int = int(i,base)
i = i_as_int
except:
pass
if element_count in phandle_idxs:
try:
lnode = self.node.tree.pnode( i )
if lnode:
phandle_targets.append( lnode )
else:
# was it a label ?
lnode = self.node.tree.lnodes( re.escape(i) )
if lnode:
phandle_targets.append( lnode )
except:
pass
element_count = element_count + 1
return phandle_targets
def print( self, output ):
"""print a property
Print the resolved value of a property to the passed output
stream.
The property will be indented to match the depth of a node
in a tree.
Args:
output (output stream).
Returns:
Nothing
"""
indent = (self.node.depth * 8) + 8
outstring = self.string_val
if self.pclass == "comment":
# we have to substitute \n for better indentation, since comments
# are multiline
dstring = ""
dstring = dstring.rjust(len(dstring) + indent + 1, " " )
outstring = re.sub( '\n\s*', '\n' + dstring, outstring, 0, re.MULTILINE | re.DOTALL)
if self.pclass == "preamble":
# start tree peeked at this, so we do nothing
outstring = ""
if outstring:
print(outstring.rjust(len(outstring)+indent," " ), file=output)
def resolve( self ):
"""resolve (calculate) property details
Some attributes of a property are not known at initialization
time, or may change due to tree operations.
This method calculates those values using information in the
property and in the tree
Fields resolved:
- abs_path
- type
- string_val (with phandles resolved)
- __pstate__
Args:
None
Returns:
Nothing
"""
outstring = "{0} = {1};".format( self.name, self.value )
prop_val = self.value
if self.node:
self.abs_path = self.node.abs_path + "/" + self.name
else:
self.abs_path = self.name
if re.search( "lopper-comment.*", self.name ):
prop_type = "comment"
elif re.search( "lopper-preamble", self.name ):
prop_type = "preamble"
elif re.search( "lopper-label.*", self.name ):
prop_type = "label"
else:
# we could make this smarter, and use the Lopper Guessed type
prop_type = type(prop_val)
if self.__dbg__ > 1:
print( "[DBG+]: property [%s] resolve: %s val: %s" % (prop_type,self.name,self.value) )
self.pclass = prop_type
# this is the actual type of the elements (if a list, or the
# value if not a list).
self.ptype = prop_type
phandle_idx, phandle_field_count = self.phandle_params()
phandle_tgts = self.resolve_phandles()
if prop_type == "comment":
outstring = ""
for s in prop_val:
outstring += s
elif prop_type == "label":
outstring = ""
elif prop_type == "preamble":
outstring = "/*\n"
# print everything but the last element, we'll print it with no newline
for p in prop_val[:-1]:
outstring += "{0}\n".format(p)
outstring += "{0}*/\n".format(prop_val[-1])
elif prop_type == int:
outstring = "{0} = <{1}>;".format( self.name, hex(prop_val) )
elif prop_type == list:
# if the length is one, and the only element is empty '', then
# we just put out the name
if len(prop_val) == 0:
# outstring = ""
outstring = "{0};".format( self.name )
elif len(prop_val) == 1 and prop_val[0] == '':
outstring = "{0};".format( self.name )
else:
# otherwise, we need to iterate and output the elements
# as a comma separated list, except for the last item which
# ends with a ;
outstring = ""
outstring_list = "{0} = ".format( self.name )
# if the attribute was detected as potentially having a
# phandle, phandle_idx will be non zero.
#
# To more easily pick out the elements that we should
# check for phandle replacement, we generate a list of
# element numbers that are potential phandles.
#
# We generate that list by generating all indexes from 1
# to the number of elments in our list (+1), and then we
# slice the list. The slice starts at the phandle index
# - 1 (since our list starts at position 0), and grabs
# every "nth" item, where "n" is the number of fields in
# the element block (number of fields).
if phandle_idx != 0:
phandle_idxs = list(range(1,len(prop_val) + 1))
phandle_idxs = phandle_idxs[phandle_idx - 1::phandle_field_count]
# is this a list of ints, or string ? Test the first
# item to know.
if phandle_tgts:
list_of_nums = True
else:
list_of_nums = False
if type(prop_val[0]) == str:
# is it really a number, hiding as a string ?
base = 10
if re.search( "0x", prop_val[0] ):
base = 16
try:
i = int(prop_val[0],base)
list_of_nums = True
except:
pass
else:
list_of_nums = True
if list_of_nums:
self.ptype = LopperFmt.UINT32
if self.binary:
outstring_list += "["
else:
# we have to open with a '<', if this is a list of numbers
outstring_list += "<"
else:
self.ptype = LopperFmt.STRING
element_count = 1
element_total = len(prop_val)
outstring_record = ""
drop_record = False
drop_all = False
for i in prop_val:
if list_of_nums:
base = 10
if re.search( "0x", str(i) ):
base = 16
try:
i_as_int = int(i,base)
i = i_as_int
except:
pass
else:
i_as_int = 0
phandle_tgt_name = ""
if phandle_idx != 0:
# if we we are on the phandle field, within the number of fields
# per element, then we need to look for a phandle replacement
if element_count in phandle_idxs:
try:
try:
tgn = self.node.tree.pnode( i )
if tgn == None:
# if we couldn't find the target, maybe it is in
# as a string. So let's check that way.
tgn2 = self.node.tree.nodes( re.escape(i) )
if not tgn2:
tgn2 = self.node.tree.lnodes( re.escape(i) )
if tgn2:
tgn = tgn2[0]
except Exception as e:
tgn = 0
try:
phandle_tgt_name = tgn.label
except:
phandle_tgt_name = ""
if not phandle_tgt_name and tgn:
phandle_tgt_name = Lopper.phandle_safe_name( tgn.name )
if not phandle_tgt_name:
raise ValueError( "phandle is not resolvable" )
if self.__dbg__ > 1:
print( "[DBG+]: [%s:%s] phandle replacement of: %s with %s" %
( self.node.name, self.name, i, phandle_tgt_name))
except Exception as e:
# we need to drop the entire record from the output, the phandle wasn't found
if self.__dbg__ > 1:
if self.node and self.node.tree.strict:
print( "[DBG+]: [%s:%s] phandle: %s not found, dropping %s fields" %
( self.node.name, self.name, i, phandle_field_count))
else:
print( "[DBG+]: [%s:%s] phandle: %s not found, but not dropping (permissive mode)" %
( self.node.name, self.name, i))
if self.node and self.node.tree.strict:
drop_record = True
if len(prop_val) == phandle_field_count or len(prop_val) < phandle_field_count:
drop_all = True
# if we are on a "record" boundry, latch what we have (unless the drop
# flag is set) and start gathering more
if element_count % phandle_field_count == 0 and element_count != 0:
if not drop_record:
outstring_list += outstring_record
# reset for the next set of fields
outstring_record = ""
drop_record = False
# is this the last item ?
if element_count == element_total:
# last item, semicolon to close
if list_of_nums:
if phandle_tgt_name:
outstring_record += "&{0}>;".format( phandle_tgt_name )
else:
if self.binary:
outstring_record += "{0:02X}];".format( i )
else:
outstring_record += "{0}>;".format( hex(i) )
else:
outstring_record += "\"{0}\";".format( i )
else:
# not the last item ..
if list_of_nums:
if phandle_tgt_name:
outstring_record += "&{0} ".format( phandle_tgt_name )
else:
if self.binary:
outstring_record += "{0:02X} ".format( i )
else:
outstring_record += "{0} ".format( hex(i) )
else:
outstring_record += "\"{0}\",".format( i )
element_count = element_count + 1
# gather the last record
if not drop_all:
outstring_list += outstring_record
# add the lists string output to the overall output string
outstring += outstring_list
else:
outstring = "{0} = \"{1}\";".format( self.name, prop_val )
self.string_val = outstring
self.__pstate__ = "resolved"
class LopperNode(object):
"""Class representing a device tree node
This class implements:
- a property iterator
- dictionary access to properties
- str(): string cast
- equality check (==): for comparison
- ref counting: set, get, clear
- property add, modify, delete (via methods and '-', '+')
- resolve(): to update/calculate properties against the tree
- sync(): sync modified node elements (and properties)
- deep node copy via LopperNode()
Attributes:
- number: the node number in the backing structure
- name: the node name in the backing structure (this is not the node path)
- parent: a link to the parent LopperNode object
- tree: the tree which contains this node
- depth: the nodes depth in the backing structure (0 is root, 1 for first level children)
- child_nodes: the list of child LopperNodes
- phandle: the phandle in the backing FDT (optional)
- type: the type of the node (based on 'compatible' property)
- abs_path: the full/absolute path to this node in the backing FDT
- _ref: the refcount for this node
- __props__: ordered dictionary of LopperProp
- __current_property__: place holder for property iterator
- __dbg__: debug level for the node
- __nstate__: the state of the node ("init", "resolved" )
- __modified__: flag indicating if the node has been modified
"""
def __init__(self, number = -1, abspath="", tree = None, phandle = -1, name = "", debug=0 ):
self.number = number
self.name = name
self.parent = None
self.tree = tree
self.depth = 0
self.child_nodes = OrderedDict()
self.phandle = phandle
self.label = ""
# 'type' is roughly equivalent to a compatible property in
# the node if it exists.
self.type = []
self.abs_path = abspath
self._ref = 0
# currently this can be: "dts", "yaml" or "none"
self._source = "dts"
# ordered dict, since we want properties to come back out in
# the order we put them in (when we iterate).
self.__props__ = OrderedDict()
self.__current_property__ = -1
self.__props_pending_delete__ = OrderedDict()
self.__dbg__ = debug
# states could be enumerated types
self.__nstate__ = "init"
self.__modified__ = False
def __deepcopy__(self, memodict={}):
""" Create a deep copy of a node
Only certain parts of a node need to be copied, we also have to
trigger deep copies of properties, since they have references
to nodes.
We leave most values as the defaults on the new node instance,
since the copied node needs to be added to a tree, where they'll
be filled in.
"""
if self.__dbg__ > 1:
print( "[DBG++]: node deepcopy start: %s" % [self.abs_path] )
new_instance = LopperNode()
# if we blindly want everything, we'd do this update. But it
# is easier to pick out the properties that we do want, versus
# copying and undoing.
# new_instance.__dict__.update(self.__dict__)
# we loop instead of the copy below, since we want to preserve the order
# new_instance.__props__ = copy.deepcopy( self.__props__, memodict )
new_instance.__props__ = OrderedDict()
for p in reversed(self.__props__):
new_instance[p] = copy.deepcopy( self.__props__[p], memodict )
new_instance[p].node = new_instance
new_instance.name = copy.deepcopy( self.name, memodict )
new_instance.number = -1 # copy.deepcopy( self.number, memodict )
new_instance.depth = copy.deepcopy( self.depth, memodict )
new_instance.label = copy.deepcopy( self.label, memodict )
new_instance.type = copy.deepcopy( self.type, memodict )
new_instance.abs_path = copy.deepcopy( self.abs_path, memodict )
new_instance._source = self._source
new_instance.tree = None
new_instance.child_nodes = OrderedDict()
for c in reversed(self.child_nodes.values()):
new_instance.child_nodes[c.abs_path] = copy.deepcopy( c, memodict )
new_instance.child_nodes[c.abs_path].number = -1
new_instance.child_nodes[c.abs_path].parent = new_instance
if self.__dbg__ > 1:
print( "[DBG++]: deep copy done: %s" % [self] )
return new_instance
# supports NodeA( NodeB ) to copy state
def __call__( self, othernode=None ):
"""Callable implementation for the node class
When used, this creates a deep copy of the current node, versus
a reference. This allows a node to be cloned and used in a secondary
tree, free from changes to the original node.
Two modes are supported:
A) <LopperNode Object>()
B) <LopperNode Object>( <other node> )
When no other node is passed (mode A) a copy of the existing node is
made, including properties with the state is set to "init", this node
should then be resolved to fill in missing information.
When mode B is used, the current node is updated using copies of the
values from the other node. This is used on a newly created node, to
initalize it with values from an existing node.
Args:
othernode (LopperNode,optional): node to use for initalization values
Returns:
The copied node, or self (if updating).
"""
if othernode == None:
nn = copy.deepcopy( self )
for p in nn.__props__.values():
p.__modified__ = True
p.__pstate__ = "init"
p.node = nn
# invalidate a few things
nn.__nstate__ = "init"
nn.__modified__ = True
return nn
else:
# we are updating ourself
nn = copy.deepcopy( othernode )
# copy everything
self.__dict__.update(nn.__dict__)
for p in self.__props__.values():
p.__modified__ = True
# invalidate a few things
self.__nstate__ = "init"
self.__modified__ = True
return self
def __setattr__(self, name, value):
"""magic method to check the setting of a LopperNode attribute
If the attribute being set is the debug level (__dbg__), this wrapper
chains the setting to any LopperProps of the node.
If the attribute is any other, we set the value and tag the node as
modified, so it can be sync'd later.
Args:
name: attribute name
value: attribute value
Returns:
Nothing
"""
if name == "__dbg__":
self.__dict__[name] = value
for p in self.__props__.values():
p.__dbg__ = value
else:
# we do it this way, otherwise the property "ref" breaks
super().__setattr__(name, value)