forked from devicetree-org/lopper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lopper_fdt.py
1755 lines (1412 loc) · 65.5 KB
/
lopper_fdt.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 unittest
import os
import getopt
import re
import subprocess
import shutil
from pathlib import Path
from pathlib import PurePath
from io import StringIO
import contextlib
import importlib
from importlib.machinery import SourceFileLoader
import tempfile
# from enum import Enum
import atexit
import textwrap
from collections import UserDict
from collections import OrderedDict
from lopper_fmt import LopperFmt
import lopper_base
from lopper_tree import LopperTreePrinter
from string import printable
try:
import libfdt
from libfdt import Fdt, FdtException, QUIET_NOTFOUND, QUIET_ALL
except:
import site
python_version_dir = "python{}.{}".format( sys.version_info[0], sys.version_info[1] )
site.addsitedir('vendor/lib/{}/site-packages'.format( python_version_dir ))
import libfdt
from libfdt import Fdt, FdtException, QUIET_NOTFOUND, QUIET_ALL
# general retry count
MAX_RETRIES = 3
class LopperFDT(lopper_base.lopper_base):
"""The Lopper Class contains static methods for manipulating device trees
Use the lopper methods when manipulating device trees (in particular
libfdt FDT objects) or SystemDeviceTree classes.
"""
@staticmethod
def fdt_copy( fdt ):
"""Copy a fdt
Creats a new FDT that is a copy of the passed one.
Args:
fdt (FDT): reference FDT
Returns:
fdt: The newly created FDT
"""
return Fdt( fdt.as_bytearray() )
@staticmethod
def fdt( size=None, other_fdt=None ):
"""Create a new FDT
Creats a new FDT of a passed size. If other_fdt is passed, it
is used as the start size of the fdt.
If no size or other fdt is passed, 128 bytes is the default
size
Args:
size (int,optional): size in bytes of the FDT
other_fdt (FDT,optional): reference FDT for size
Returns:
fdt: The newly created FDT
"""
fdt = None
if other_fdt:
size = other_fdt.totalsize()
else:
if not size:
# size is in bytes
size = 128
fdt = libfdt.Fdt.create_empty_tree( size )
return fdt
@staticmethod
def node_getname( fdt, node_number_or_path ):
"""Gets the FDT name of a node
Args:
fdt (fdt): flattened device tree object
node_number_or_path: node number or path
Returns:
string: name of the node, or "" if node wasn't found
"""
node_number = -1
node_path = ""
try:
node_number = int(node_number_or_path)
node_path = LopperFDT.node_abspath( fdt, node_number_or_path )
except ValueError:
node_number = LopperFDT.node_find( fdt, node_number_or_path )
node_path = node_number_or_path
try:
name = fdt.get_name( node_number )
except:
name = ""
return name
@staticmethod
def node_setname( fdt, node_number_or_path, newname ):
"""Sets the FDT name of a node
Args:
fdt (fdt): flattened device tree object
node_number_or_path: node number or path
newname (string): name of the node
Returns:
boolean: True if the name was set, False otherwise
"""
node_number = -1
node_path = ""
try:
node_number = int(node_number_or_path)
node_path = LopperFDT.node_abspath( fdt, node_number_or_path )
except ValueError:
node_number = LopperFDT.node_find( fdt, node_number_or_path )
node_path = node_number_or_path
retval = False
if node_number == -1:
return retval
for _ in range(MAX_RETRIES):
try:
fdt.set_name( node_number, newname )
retval = True
except:
fdt.resize( fdt.totalsize() + 1024 )
continue
else:
break
return retval
@staticmethod
def node_find( fdt, node_prefix ):
"""Finds a node by its prefix
Args:
fdt (fdt): flattened device tree object
node_prefix (string): device tree path
Returns:
int: node number if successful, otherwise -1
"""
try:
node = fdt.path_offset( node_prefix )
except:
node = -1
return node
@staticmethod
def node_type( fdt, node_offset, verbose=0 ):
"""Utility function to get the "type" of a node
A small wrapper around the compatible property, but we can use this
instead of directly getting compatible, since if we switch formats or if
we want to infer anything based on the name of a node, we can hide it in
this routine
Args:
fdt (fdt): flattened device tree object
node_offset (int): node number
verbose (int): verbose output level
Returns:
string: compatible string of the node if successful, otherwise ''
"""
rt = LopperFDT.property_get( fdt, node_offset, "compatible" )
return rt
@staticmethod
def node_by_phandle( fdt, phandle, verbose=0 ):
"""Get a node offset by a phandle
Thin wrapper around the libfdt routine. The wrapper provides
consistent exception handling and verbosity level handling.
Args:
fdt (fdt): flattened device tree object
phandle(int): phandle to use as lookup key
verbose(bool,optional): verbosity level. Deafult is 0.
Returns:
int: if > 0, the node that was found. -1 if node was not found.
"""
anode = -1
try:
anode = fdt.node_offset_by_phandle( phandle )
except:
pass
return anode
@staticmethod
def node_find_by_name( fdt, node_name, starting_node = 0, multi_match=False ):
"""Finds a node by its name (not path)
Searches for a node by its name, and returns the offset of that same node
Note: use this when you don't know the full path of a node
Args:
fdt (fdt): flattened device tree object
node_name (string): name of the node
starting_node (int): node number to use as the search starting point
multi_match (bool,optional): flag to indicate if more than one matching
node should be found, default is False
Returns:
tuple: first matching node, list of matching nodes. -1 and [] if no match is found
"""
nn = starting_node
matching_nodes = []
matching_node = -1
# short circuit the search if they are looking for /
if node_name == "/":
depth = -1
else:
depth = 0
while depth >= 0:
nn_name = fdt.get_name(nn)
if nn_name:
# we search to support regex matching
if re.search( node_name, nn_name ):
matching_nodes.append(nn)
if matching_node == -1:
# this is the first match, so we capture the number
matching_node = nn
if not multi_match:
depth = -1
else:
# match, but mult-match is on .. get the next node
nn, depth = fdt.next_node(nn, depth, (libfdt.BADOFFSET,))
else:
# no match, get the next node
nn, depth = fdt.next_node(nn, depth, (libfdt.BADOFFSET,))
else:
# no name, get the next node
nn, depth = fdt.next_node(nn, depth, (libfdt.BADOFFSET,))
return matching_node, matching_nodes
@staticmethod
def node_find_by_regex( fdt, node_regex, starting_node = 0, multi_match=False, paths_not_numbers=False ):
"""Finds a node by a regex /path/<regex>/<name>
Searches for nodes that match a regex (path + name).
Note: if you pass the name of a node as the regex, you'll get a list of
that node + children
Note: if you pass no regex, you'll get all nodes from the starting point
to the end of the tree.
Args:
fdt (fdt): flattened device tree object
node_regex (string): regex to use for comparision
starting_node (int): node number to use as the search starting point
multi_match (bool,optional): flag to indicate if more than one matching
node should be found, default is False
paths_not_numbers (bool,optional): flag to request paths, not node numbers
be returned
Returns:
tuple: first matching node, list of matching nodes. -1 and [] if no match is found
"""
nn = starting_node
matching_nodes = []
matching_node = -1
depth = 0
while depth >= 0:
nn_name = fdt.get_name(nn)
node_path = ""
if nn > 0:
node_path = LopperFDT.node_abspath( fdt, nn )
if nn_name:
# we search to support regex matching
if re.search( node_regex, node_path ):
matching_nodes.append(nn)
if matching_node == -1:
# this is the first match, so we capture the number
matching_node = nn
if not multi_match:
depth = -1
else:
# match, but mult-match is on .. get the next node
nn, depth = fdt.next_node(nn, depth, (libfdt.BADOFFSET,))
else:
# no match, get the next node
nn, depth = fdt.next_node(nn, depth, (libfdt.BADOFFSET,))
else:
# no name, get the next node
nn, depth = fdt.next_node(nn, depth, (libfdt.BADOFFSET,))
# convert everything to paths if requested. This could have been in the
# loop, but let's keep it simple :D
if paths_not_numbers:
matching_node = LopperFDT.node_abspath( fdt, matching_node )
matching_node_list = matching_nodes
matching_nodes = []
for m in matching_node_list:
matching_nodes.append( LopperFDT.node_abspath( fdt, m ) )
return matching_node, matching_nodes
@staticmethod
def node_prop_check( fdt, node_name, property_name ):
"""Check if a node contains a property
Boolean check to see if a node contains a property.
The node name does not need to be a full path or path prefix, since
the node will be searched starting at the root node, which means that
a non-unique node name could match multiple nodes.
Args:
fdt (fdt): flattened device tree object
node_name (string): name of the node
property_name (string): name of the property to check
Returns:
bool: True if the node has the property, otherwise False
"""
node = LopperFDT.node_find( fdt, node_name )
if node == -1:
node, nodes = LopperFDT.node_find_by_name( fdt, node_name )
if node == -1:
return False
try:
fdt.getprop( node, property_name )
except:
return False
return True
# A thin wrapper + consistent logging and error handling around FDT's
# node delete
@staticmethod
def node_remove( fdt, target_node_offset, verbose = 0 ):
"""remove a node from the device tree
Thin wrapper and consistent logging around libfdt's node delete.
Args:
fdt (fdt): flattended device tree
target_node_offset (int): offset of the node to be deleted
Returns:
Boolean: True if node is removed, false otherwise
"""
target_node_name = fdt.get_name( target_node_offset )
if verbose > 1:
print( "[NOTE]: deleting node: %s" % target_node_name )
try:
fdt.del_node( target_node_offset, True )
except:
return False
return True
@staticmethod
def node_add( fdt_dest, node_full_path, create_parents = True, verbose = 0 ):
"""Add an empty node to a flattened device tree
Creates a new node in a flattened devide tree at a given path. If
desired a node structure (aka parents) will be created as part of
adding the node at the specified path.
Args:
fdt_dest (fdt): flattened device tree object
node_full_path (string): fully specified path (and name) of the node to create
create_parents (bool,optional): Should parent nodes be created. Default is True.
True: create parents as required, False: error if parents are missing
verbose (int,optional): verbosity level. default is 0.
Returns:
int: The node offset of the created node, if successfull, otherwise -1
"""
prev = 0
for p in os.path.split( node_full_path ):
n = LopperFDT.node_find( fdt_dest, p )
if n < 0:
if create_parents:
for _ in range(MAX_RETRIES):
try:
p = p.lstrip( '/' )
prev = fdt_dest.add_subnode( prev, p )
except Exception as e:
fdt_dest.resize( fdt_dest.totalsize() + 1024 )
continue
else:
break
else:
prev = n
return prev
@staticmethod
def node_properties( fdt, node_number_or_path ):
"""Get the list of properties for a node
Gather the list of FDT properties for a given node.
Args:
fdt (fdt): flattened device tree object
node_number_or_path: (string or int): node number or full path to
the target node.
Returns:
list (FDT prop): The properties of the node [] if no props
"""
prop_list = []
node = LopperFDT.node_number( fdt, node_number_or_path )
if node == -1:
return prop_list
poffset = fdt.first_property_offset(node, QUIET_NOTFOUND)
while poffset > 0:
prop = fdt.get_property_by_offset(poffset)
prop_list.append(prop)
poffset = fdt.next_property_offset(poffset, QUIET_NOTFOUND)
return prop_list
@staticmethod
def nodes( fdt, node_number_or_path, abs_paths = True ):
"""Get the nodes of a tree from a starting point
Gather the list nodes in the tree from a particular starting point
Args:
fdt (fdt): flattened device tree object
node_number_or_path: (string or int): node number or full path to
the target node.
abs_paths (boolean, optional): indicate if absolute paths should be returned
Returns:
list (strings): The nodes, [] if no nodes
"""
node_list = []
node = LopperFDT.node_number( fdt, node_number_or_path )
if node == -1:
return node_list
depth = 0
while depth >= 0:
if abs_paths:
node_list.append( LopperFDT.node_abspath( fdt, node ) )
else:
node_list.append( LopperFDT.node_getname( fdt, node ) )
node, depth = fdt.next_node(node, depth, (libfdt.BADOFFSET,))
return node_list
@staticmethod
def node_subnodes( fdt, node_number_or_path, abs_paths = True ):
"""Get the list of properties for a node
Gather the list of FDT properties for a given node.
Args:
fdt (fdt): flattened device tree object
node_number_or_path: (string or int): node number or full path to
the target node.
abs_paths (boolean, optional): indicate if absolute paths should be returned
Returns:
list (strings): The subnodes, [] if no subnodes
"""
node_list = []
node = LopperFDT.node_number( fdt, node_number_or_path )
if node == -1:
return node_list
offset = fdt.first_subnode(node, QUIET_NOTFOUND)
while offset > 0:
if abs_paths:
node_list.append( LopperFDT.node_abspath( fdt, offset ) )
else:
node_list.append( LopperFDT.node_getname( fdt, offset ) )
offset = fdt.next_subnode( offset, QUIET_NOTFOUND )
return node_list
@staticmethod
def node_parent( fdt, node_number_or_path ):
"""Get the parent offset / number of a node
Args:
fdt (fdt): flattened device tree object
node_number_or_path: (string or int): node number or full path to
the target node.
Returns:
int: the node number of the parent
"""
parent = -1
node_number = LopperFDT.node_number( fdt, node_number_or_path )
if node_number > 0:
parent = fdt.parent_offset( node_number, QUIET_NOTFOUND )
return parent
@staticmethod
def node_sync( fdt, node_in, parent = None, verbose = False ):
"""Write a node description to a FDT
This routine takes an input dictionary, and writes the details to
the passed fdt.
The dictionary contains a set of internal properties, as well as
a list of standand properties to the node. Internal properties have
a __ suffix and __ prefix.
In particular:
- __path__ : is the absolute path fo the node, and is used to lookup
the target node
- __fdt_name__ : is the name of the node and will be written to the
fdt name property
- __fdt_phandle__ : is the phandle for the node
All other '/' leading, or '__' leading properties will be written to
the FDT as node properties.
If the node doesn't exist, it will be created. If the node exists, then
the existing properties are read, and any that are no present in the
passed dictionary are deleted.
Args:
fdt (fdt): flattened device tree object
node_in: (dictionary): Node description dictionary
parent (string,optional): path to the parent node
verbose (bool,optional): verbosity level
Returns:
Nothing
"""
if verbose:
print( "[DBG]: lopper_fdt: node_sync: start: %s (%s)" % (node_in['__fdt_name__'],node_in['__path__'] ))
nn = LopperFDT.node_find( fdt, node_in['__path__'] )
if nn == -1:
# -1 means the node wasn't found
if verbose:
print( "[DBG]: lopper_fdt: adding node: %s" % node_in['__path__'] )
nn = LopperFDT.node_add( fdt, node_in['__path__'], True )
if nn == -1:
print( "[ERROR]: lopper_fdt: node could not be added, exiting" )
sys.exit(1)
nname = node_in['__fdt_name__']
LopperFDT.node_setname( fdt, nn, nname )
try:
ph = node_in['__fdt_phandle__']
if ph:
LopperFDT.property_set( fdt, nn, "phandle", ph )
except:
pass
props = LopperFDT.node_properties( fdt, nn )
props_to_delete = []
for p in props:
if node_in['__fdt_phandle__'] and p.name == "phandle":
# we just added this, it won't be in the node_in items under
# the name name
pass
else:
props_to_delete.append( p.name )
for prop, prop_val in node_in.items():
if re.search( "^__", prop ) or prop.startswith( '/' ):
if verbose:
print( " lopper_fdt: node sync: skipping internal property: %s" % prop)
continue
else:
if verbose:
print( " lopper_fdt: node sync: prop: %s val: %s" % (prop,prop_val) )
# We could supply a type hint via the __{}_type__ attribute
LopperFDT.property_set( fdt, nn, prop, prop_val, LopperFmt.COMPOUND )
if props_to_delete:
try:
props_to_delete.remove( prop )
except:
# if a node was added at the top of this routine, it
# won't have anything in the props_to_delete, and this
# would throw an exception. Since that's ok, we just
# catch it and move on.
pass
for p in props_to_delete:
if verbose:
print( "[DBG]: lopper_fdt: node sync, deleting property: %s" % p )
LopperFDT.property_remove( fdt, nname, p )
@staticmethod
def sync( fdt, dct, verbose = False ):
"""sync (write) a tree dictionary to a fdt
This routine takes an input dictionary, and writes the details to
the passed fdt.
The dictionary contains a set of internal properties, as well as
a list of standand properties to the node. Internal properties have
a __ suffix and __ prefix.
Child nodes are indexed by their absolute path. So any property that
starts with "/" and is a dictionary, represents another node in the
tree.
In particular:
- __path__ : is the absolute path fo the node, and is used to lookup
the target node
- __fdt_name__ : is the name of the node and will be written to the
fdt name property
- __fdt_phandle__ : is the phandle for the node
All other non '/' leading, or '__' leading properties will be written to
the FDT as node properties.
Passed nodes will be synced via the node_sync() function, and will
be created if they don't exist. Existing nodes will have their properties
deleted if they are not in the corresponding dictionary.
All of the existing nodes in the FDT are read, if they aren not found
in the passed dictionary, they will be deleted.
Args:
fdt (fdt): flattened device tree object
node_in: (dictionary): Node description dictionary
parent (dictionary,optional): parent node description dictionary
verbose (bool,optional): verbosity level
Returns:
Nothing
"""
# import a dictionary to a FDT
if not fdt:
return
if verbose:
print( "[DBG]: lopper_fdt sync: start" )
# we have a list of: containing dict, value, parent
dwalk = [ [dct,dct,None] ]
node_ordered_list = []
while dwalk:
firstitem = dwalk.pop()
if type(firstitem[1]) is OrderedDict:
node_ordered_list.append( [firstitem[1], firstitem[0]] )
for item,value in reversed(firstitem[1].items()):
dwalk.append([firstitem[1],value,firstitem[0]])
else:
pass
# this gets us a list of absolute paths. If we walk through the
# dictionary passed in, and delete them from the list, we have the list
# of nodes to delete with whatever is left over, and the nodes to add if
# they aren't in the list.
nodes_to_remove = LopperFDT.nodes( fdt, "/" )
nodes_to_add = []
for n_item in node_ordered_list:
try:
nodes_to_remove.remove( n_item[0]['__path__'] )
except:
nodes_to_add.append( n_item )
for node in nodes_to_remove:
nn = LopperFDT.node_find( fdt, node )
if nn != -1:
if verbose:
print( "[DBG]: lopper_fdt: sync: removing: node %s" % node )
LopperFDT.node_remove( fdt, nn )
else:
if verbose:
print( "[DBG]: lopper_fdt: sync: node %s was not found, and could not be remove" % node )
# child nodes are removed with their parent, and follow in the
# list, so this isn't an error.
pass
for n_item in node_ordered_list:
node_in = n_item[0]
node_in_parent = n_item[1]
node_path = node_in['__path__']
abs_path = node_path
nn = node_in['__fdt_number__']
LopperFDT.node_sync( fdt, node_in, node_in_parent )
@staticmethod
def export( fdt, start_node = "/", verbose = False, strict = False ):
"""export a FDT to a description / nested dictionary
This routine takes a FDT, a start node, and produces a nested dictionary
that describes the nodes and properties in the tree.
The dictionary contains a set of internal properties, as well as
a list of standand properties to the node. Internal properties have
a __ suffix and __ prefix.
Child nodes are indexed by their absolute path. So any property that
starts with "/" and is a dictionary, represents another node in the
tree.
In particular:
- __path__ : is the absolute path fo the node, and is used to lookup
the target node
- __fdt_name__ : is the name of the node and will be written to the
fdt name property
- __fdt_phandle__ : is the phandle for the node
All other "standard" properties are returned as entries in the dictionary.
if strict is enabled, structural issues in the input tree will be
flagged and an error triggered. Currently, this is duplicate nodes, but
may be extended in the future
Args:
fdt (fdt): flattened device tree object
start_node (string,optional): the starting node
verbose (bool,optional): verbosity level
strict (bool,optional): toggle validity checking
Returns:
OrderedDict describing the tree
"""
# export a FDT as a dictionary
dct = OrderedDict()
nodes = LopperFDT.node_subnodes( fdt, start_node )
if strict:
if len(nodes) != len(set(nodes)):
raise Exception( "lopper_fdt: duplicate node detected (%s)" % nodes )
dct["__path__"] = start_node
np = LopperFDT.node_properties_as_dict( fdt, start_node )
if np:
dct.update(np)
nn = LopperFDT.node_number( fdt, start_node )
dct["__fdt_number__"] = nn
dct["__fdt_name__"] = LopperFDT.node_getname( fdt, start_node )
dct["__fdt_phandle__"] = LopperFDT.node_getphandle( fdt, nn )
if verbose:
print( "[DBG]: lopper_fdt export: " )
print( "[DBG]: [startnode: %s]: subnodes: %s" % (start_node,nodes ))
print( "[DBG]: props: %s" % np )
for i,n in enumerate(nodes):
# Children are indexed by their path (/foo/bar), since properties
# cannot start with '/'
dct[n] = LopperFDT.export( fdt, n, verbose, strict )
return dct
@staticmethod
def node_properties_as_dict( fdt, node, type_hints=True, verbose=0 ):
"""Create a dictionary populated with the nodes properties.
Builds a dictionary that is propulated with a node's properties as
the keys, and their values. Used as a utility routine to avoid
multiple calls to check if a property exists, and then to fetch its
value.
Args:
fdt (fdt): flattened device tree object
node (int or string): either a node number or node path
type_hints (bool,optional): flag indicating if type hints should be returned
verbose (int,optional): verbosity level. default is 0.
Returns:
dict: dictionary of the properties, if successfull, otherwise and empty dict
"""
prop_dict = {}
# is the node a number ? or do we need to look it up ?
node_number = -1
node_path = ""
try:
node_number = int(node)
node_path = LopperFDT.node_abspath( fdt, node )
except ValueError:
node_number = LopperFDT.node_find( fdt, node )
node_path = node
if node_number == -1:
print( "[WARNING]: could not find node %s" % node_path )
return prop_dict
prop_list = LopperFDT.node_properties( fdt, node_path )
for p in prop_list:
# print( " export as dict: read: %s" % p.name )
property_val = LopperFDT.property_get( fdt, node_number, p.name, LopperFmt.COMPOUND )
prop_dict[p.name] = property_val
if type_hints:
prop_dict['__{}_type__'.format(p.name)] = LopperFDT.property_type_guess( p )
return prop_dict
@staticmethod
def node_copy_from_path( fdt_source, node_source_path, fdt_dest, node_full_dest, verbose=0 ):
"""Copies a node from one FDT to another
Copies a node between flattened device trees. The node (and
properties) will be copied to the specified target device tree and
path (ensure that a node does not already exist at the destination
path).
This routine is a wrapper around node_copy(), and will create a
parent node structure in the destination fdt as required.
Args:
fdt_source (fdt): source flattened device tree object
node_source_path: source device tree node path (fully specified)
fdt_dest (fdt): destination flattened device tree object
node_full_dest: destination device tree path for copied node (fully specified)
verbose (int,optional): verbosity level. default is 0.
Returns:
bool: True if the node was copied, otherise, False
"""
if verbose > 1:
print( "[DBG ]: node_copy_from_path: %s -> %s" % (node_source_path, node_full_dest) )
node_to_copy = LopperFDT.node_find( fdt_source, node_source_path )
node_dest_path = os.path.dirname( node_full_dest )
node_dest_name = os.path.basename( node_full_dest )
if node_dest_path == "/":
node_dest_parent_offset = 0
else:
# non root dest
node_dest_parent_offset = LopperFDT.node_find( fdt_dest, node_dest_path )
if node_dest_parent_offset == -1:
node_dest_parent_offset = LopperFDT.node_add( fdt_dest, node_dest_path )
if node_dest_parent_offset <= 0:
print( "[ERROR]: could not create new node" )
sys.exit(1)
if node_to_copy:
return LopperFDT.node_copy( fdt_source, node_to_copy, fdt_dest, node_dest_parent_offset, verbose )
return False
@staticmethod
def node_copy( fdt_source, node_source_offset, fdt_dest, node_dest_parent_offset, verbose=0 ):
"""Copies a node from one FDT to another
Copies a node between flattened device trees. The node (and
properties) will be copied to the specified target device tree and
path (ensure that a node does not already exist at the destination
path).
Note: the destination node parent must exist before calling this routine
Properties are iterated, decoded and then copied (encoded) to the
destination node. As such, the copies are limited by the
decode/encode capabilities. If properties do not look correct in the
copy, the decode/encode routines need to be checked.
Args:
fdt_source (fdt): source flattened device tree object
node_source_offset: source device tree node offset
fdt_dest (fdt): destination flattened device tree object
node_dest_parent_offset: destination device parent node
verbose (int,optional): verbosity level. default is 0.
Returns:
bool: True if the node was copied, otherise, False
"""
old_depth = -1
depth = 0
nn = node_source_offset
newoff = node_dest_parent_offset
while depth >= 0:
nn_name = fdt_source.get_name(nn)
for _ in range(MAX_RETRIES):
try:
copy_added_node_offset = fdt_dest.add_subnode( newoff, nn_name )
except Exception as e:
fdt_dest.resize( fdt_dest.totalsize() + 1024 )
continue
else:
break
else:
print( "[ERROR]: could not create subnode for node copy" )
sys.exit(1)
prop_offset = fdt_dest.subnode_offset( newoff, nn_name )
if verbose > 2:
print( "" )
print( "[DBG+]: properties for: %s" % fdt_source.get_name(nn) )
# TODO: Investigate whether or not we can just copy the properties
# byte array directly. Versus decode -> encode, which could
# introduce issues.
prop_list = []
poffset = fdt_source.first_property_offset(nn, QUIET_NOTFOUND)
while poffset > 0:
prop = fdt_source.get_property_by_offset(poffset)
# we insert, not append. So we can flip the order of way we are
# discovering the properties
prop_list.insert( 0, [ poffset, prop ] )
if verbose > 2:
print( " prop name: %s" % prop.name )
print( " prop raw: %s" % prop )
if verbose > 2:
prop_val = LopperFDT.property_value_decode( prop, 0 )
if not prop_val:
prop_val = LopperFDT.property_value_decode( prop, 0, LopperFmt.COMPOUND )
print( " prop decoded: %s" % prop_val )
print( " prop type: %s" % type(prop_val))
print( "" )
poffset = fdt_source.next_property_offset(poffset, QUIET_NOTFOUND)
# loop through the gathered properties and copy them over. We are reversing
# the order of the way we iterated them, due to the way that setprop inserts
# at zero every time. If we don't flip the order the copied node will have
# them in the opposite order!
for poffset, prop in prop_list:
prop_val = LopperFDT.property_get( fdt_source, nn, prop.name, LopperFmt.COMPOUND )
LopperFDT.property_set( fdt_dest, prop_offset, prop.name, prop_val )
old_depth = depth
nn, depth = fdt_source.next_node(nn, depth, (libfdt.BADOFFSET,))
# we need a new offset fo the next time through this loop (but only if our depth
# changed)
if depth >= 0 and old_depth != depth:
newoff = fdt_dest.subnode_offset( newoff, nn_name )