forked from robseb/LinuxBootImageFileGenerator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinuxBootImageGenerator.py
1876 lines (1634 loc) · 82.6 KB
/
LinuxBootImageGenerator.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
#!/usr/bin/env python
#
# ######## ###### ## ## ####### ###### ######## #######
# ## ## ## ## ## ## ## ## ## ## ## ## ##
# ## ## ## #### ## ## ## ## ## ##
# ######## ###### ## ## ## ## ## ## ##
# ## ## ## ## ## ## ## ## ## ##
# ## ## ## ## ## ## ## ## ## ## ## ##
# ## ## ###### ## ####### ###### ## #######
# ___ _ _ _ ___ _
# | _ ) _ _ (_) | | __| | / __| _ _ ___ | |_ ___ _ __
# | _ \ | || | | | | | / _` | \__ \ | || | (_-< | _| / -_) | ' \
# |___/ \_,_| |_| |_| \__,_| |___/ \_, | /__/ \__| \___| |_|_|_|
# |__/
#
#
# Robin Sebastian (https://github.com/robseb)
# Contact: [email protected]
# Repository: https://github.com/robseb/LinuxBootImageFileGenerator
#
# Python Script to automatically generate a bootable Image file with
# a specifiable partition table for embedded Linux distributions
# (2020-07-17) Vers.1.0
# first Version
#
# (2020-07-23) Vers.1.01
# date code in output file names
#
# (2020-07-26) Vers. 1.02
# delate unziped files after build
#
# (2020-08-04) Vers. 1.03
# fixed an issue with improperly copied symbolic links
# Bug Reporter: github.com/NignetShark
#
# (2020-08-04) Vers. 1.04
# fixed an issue with file ownerships and adding deconstructor to unmout
# all open loopback devices
# Bug Reporter: github.com/NignetShark
#
# (2020-08-09) Vers. 1.05
# adding u-boot script compilation feature
#
# (2020-11-24) Vers. 1.06
# Detection of wrong Device Tree compilation
#
# (2020-12-03) Vers. 1.07
# Bug fix for wrong file/build detection
version = "1.07"
import os
import sys
import time
import io
import re
import shutil
import subprocess
import xml.etree.ElementTree as ET
from typing import NamedTuple
import math
import glob
from pathlib import Path
from datetime import datetime
#
#
#
############################################ Const ###########################################
#
#
#
DELAY_MS = 5 # Delay after critical tasks in milliseconds
#
#
# @brief Class for discripting a filesystem partition
#
class Partition:
scan_mode: int # File scan mode: 1= List every file | 0= List only top files and folders
id: int # Number of Partition (O is the lowest)
type: str # Partition Filesystem
type_hex: str # Partition Filesystem as HEX value for "fdisk"
type_mkfs: str # Partition Filesystem as MKFS value for "mkfs."
size_str: str # Partition size as string with unit (KB,MB)
size : int # Partition size in Byte (0 => dynamic file size)
offset_str: str # Partition offset space as string to a dynamic size
offset: int # Partition offset space as byte to a dynamic size
fileDirectories =[] # File directory of each file to be imported to the partition
totalFileSize: int # Total file size of the partition (Byte)
totalFileSizeStr: str # Total file size of the partition (string 1GB,1MB)
totalSize: str # Total size of the partition (Byte)
totalSizeStr: str # Total size of the partition (string 1GB, 1MB)
comp_devicetree: bool # Compile a Linux dts devicetree file if available
comp_ubootscript: str # Compile u-boot script "boot.script" for architecture "arm" or "arm64"
unzip_file: bool # unzip a compressed file if available
startSector: int # Partition Start sector
BlockSectorSize: int # Block size of the partition
__filesImported:bool # Indicates that files are imported to the list
__unzipedFiles =[] # List of all unziped files/folder to remove in the deconstructor
__dtsFileDir: str # Direcortry of the DTS file to remove from the partition
__ubootscrFileDir: str # Direcortry of the u-boot script file to remove from the partition
__uncompressedFilesDir =[]# Direcortries of the uncompressed archive files
#
#
#
# @brief Constructor
# @param diagnosticOutput Enable/Disable the console printout
# @param id Partition Number of the partition table (1-4)
# @param type Filesystem name as string "ext[2-4], Linux, xfs, vfat, fat, none, raw, swap"
# @param size_str Size of the partition as string
# Format: <no>: Byte, <no>K: Kilobyte, <no>M: Megabyte or <no>G: Gigabyte
# "*" dynamic file size => Size of the files2copy + offset
# @param offset_str In case a dynamic size is used the offset value is added to file size
# @param devicetree Compile the Linux Device (.dts) inside the partition if available
# @param unzip Unzip a compressed file if available
# @param ubootscript Compile the u-boot script "boot.script" for architecture "arm" or "arm64"
# @param operation_mode File scan mode: 1= List every file | 0= List only top files and folders
#
def __init__(self,diagnosticOutput=True, id=None, type=None,size_str=None,
offset_str=None,devicetree=False,unzip=False,ubootscript=None, operation_mode=0):
# Convert the partition number to int
try:
self.id = int(id)
except ValueError:
raise Exception('Failed to convert "id" to integer!')
# Check that the selected filesystem is supported
if not re.search("^(ext[2-4]|Linux|xfs|vfat|fat|none|raw|swap)$", type, re.I):
raise Exception('Filesize "'+type+'" of "type" and id '+str(id)+' is unknown!')
# Convert type to lowercase
self.type = type.lower()
# Convert the format to "fdisk" HEX codes and to "mkfs" for "mkfs.xxx"
# ext2, ext3,ext4,xfs ... -> LINUX
if re.match('^ext[2-4]|xfs|Linux$', self.type):
self.type_hex = '83' # Linux
self.type_mkfs = "mkfs."+self.type # mkfs.ext3, ...
# vfat, fat --> FAT32
elif re.match('^vfat|fat$', self.type):
self.type_hex = 'b' # FAT32
self.type_mkfs = 'mkfs.vfat'
# raw, none -> Empty
elif re.match('^raw|none$', self.type):
self.type_hex = 'a2' # Empty
self.type_mkfs = None
# Linux swap drive (RAM -> HHD)
elif self.type in 'swap':
self.type_hex = '82' # Swap
self.type_mkfs = None
else:
raise Exception('Failed to decode partition type '+str(self.type))
self.size_str = size_str
# Convert size format to integer
self.size = self.__size2uint(size_str)
# Use the offset value only by a dynamic size
if self.size == 0:
if offset_str == '*':
raise Exception('A dynamic size (*) is for the offset not allowed!')
self.offset_str = offset_str
self.offset = self.__size2uint(offset_str)
else:
self.offset = 0
self.offset_str ='0'
if not offset == '0':
self.__print(diagnosticOutput,'NOTE: The offset value will be ignored!')
# Should a dts Linux devicetree file be compiled?
self.comp_devicetree = devicetree
# Should compressed files be unziped?
self.unzip_file = unzip
self.scan_mode = operation_mode
# should the u-boot script "u-boot.script" be complied?
if not re.match('^arm|arm|$', ubootscript):
raise Exception('The ubootscript input is for parrtion No. '+str(self.id)+ \
' not allowed. Use "","arm" or "arm64" ')
self.comp_ubootscript = ubootscript
self.totalSize = None
self.__dtsFileDir = None
self.__ubootscrFileDir=None
self.__uncompressedFilesDir=[]
#
#
#
# @brief Deconstructor
# Remove the content of all unziped files
def __del__(self):
for it in self.__unzipedFiles:
if os.path.isfile(it):
try:
os.system('sudo rm '+it)
except Exception:
raise Exception('Failed to remove the archive content file "'+str(it)+'"')
elif os.path.isdir(it):
try:
os.system('sudo rm -r '+it)
except Exception:
raise Exception('Failed to remove the archive content folder "'+str(it)+'"')
#
#
#
# @brief Import files to the file list
# These files will then be added to the partition
# @param diagnosticOutput Enable/Disable the console printout
# @param fileDirectories List of File directories to import
#
def importFileDirectories(self,diagnosticOutput,*fileDirectories):
self.__print(diagnosticOutput,'--> Import files to the file list'+\
'for the partition No.'+str(self.id))
if fileDirectories == None:
raise Exception('The file list to import must be specified')
# Check that all phases are valid
for file in fileDirectories:
if os.path.isdir(file):
# In RAW partitions folders are not allowed
if self.type_hex =='a2':
raise Exception('For RAW partitions are no folders allowed')
elif not os.path.isfile(file):
raise Exception(' File/Folder "'+str(file)+'" does not exist!')
# Compile the Linux Device Tree if necessary
dtsFileDir = None
if self.comp_devicetree == True:
dtsFileDir = self.__compileDeviceTree(diagnosticOutput,file)
# Compile the u-boot script
ubootscrFileDir = None
if self.comp_ubootscript == "arm" or self.comp_devicetree == "arm64":
ubootscrFileDir = self.__compileubootscript(diagnosticOutput,file)
# Uncompress archive files if necessary
uncompressedFilesDir =[]
if self.unzip_file == True:
uncompressedFilesDir = self.__uncompressArchivefiles(diagnosticOutput,file)
# Remove the to uncompiled Linux device tree file from the list
if not dtsFileDir == None:
self.__print(diagnosticOutput,' Exclute the file "'+dtsFileDir+'" from the list')
if not dtsFileDir in self.fileDirectories:
raise Exception('Failed to find the uncompiled device tree file '+dtsFileDir)
self.fileDirectories.remove(dtsFileDir)
# Remove the to uncompiled u-boot script from the list
if not ubootscrFileDir == None:
self.__print(diagnosticOutput,' Exclute the file "'+ubootscrFileDir+'" from the list')
if not ubootscrFileDir in self.fileDirectories:
raise Exception('Failed to find the uncompiled u-boot script: '+ubootscrFileDir)
self.fileDirectories.remove(ubootscrFileDir)
# Remove all uncompressed archive file from the list
if not uncompressedFilesDir == None:
for arch in uncompressedFilesDir:
self.__print(diagnosticOutput,' Exclute the archive file "'+arch+'" from the list')
if not arch in self.fileDirectories:
raise Exception('Failed to find the unzip file '+arch)
self.fileDirectories.remove(arch)
self.__filesImported = True
self.fileDirectories=fileDirectories
#
#
#
# @brief Find files in a directory and add them to the file list
# These files will then be added to the partition
# Archive files will be unziped, devicetree files and u-boot
# scripts will be complied and the output will be added to the partition
# @param diagnosticOutput Enable/Disable the console printout
# @param searchPath Directory to search
# @param compileDevTreeUboot Do complie the devicetree and a u-boot script
# @param unzipArchive Do unzip archvie files (such as the rootfs)
#
def findFileDirectories(self,diagnosticOutput=True,searchPath = None, \
compileDevTreeUboot = True, unzipArchive=True):
self.__print(diagnosticOutput,'--> Scan path "'+str(searchPath)+'" to find a files inside it')
if len(os.listdir(searchPath)) == 0:
# Folder has no content
self.__print(diagnosticOutput,' Has no content')
return
# Compile the Linux Device Tree if necessary
if compileDevTreeUboot:
if self.comp_devicetree == True:
self.__dtsFileDir = self.__compileDeviceTree(diagnosticOutput,searchPath)
if self.__dtsFileDir==None:
raise Exception('Device Tree complation Failed! Please check this file!')
# Compile the u-boot script
if self.comp_ubootscript == "arm" or self.comp_devicetree == "arm64":
self.__ubootscrFileDir = self.__compileubootscript(diagnosticOutput,searchPath)
if self.__ubootscrFileDir==None:
raise Exception('U-boot script complation Failed! Please check this file!')
if unzipArchive:
# Uncompress archive files if necessary
if self.unzip_file == True:
self.__uncompressedFilesDir = self.__uncompressArchivefiles(diagnosticOutput,searchPath)
fileDirectories = []
# Scan operating mode: Scan Mode 0 -> Scan only the top folder
# Add folders and files of the top folder to the list
if self.scan_mode == 0:
try:
# Scan the top folder
for folder in os.listdir(searchPath):
if os.path.isdir(searchPath+'/'+folder):
# In RAW partition folders are not allowed
if self.type_hex =='a2':
raise Exception('For RAW partitions are no folders allowed')
fileDirectories.append(searchPath+'/'+folder)
elif os.path.isfile(searchPath+'/'+folder):
fileDirectories.append(searchPath+'/'+folder)
except OSError as ex:
raise Exception('Failed process a file for importing! Msg:'+str(ex))
# Scan operating mode: Scan Mode 1 -> Scan each file in every folder
# Find every file in the top folder and in sub-folders
# and add them to the list
else:
# List every file
# List the pathes of all folders inside the folder
folderDirectories =[]
scanedFolders =[]
scanpath =searchPath
try:
# Scan the folder for new directories
while True:
for folder in os.listdir(scanpath):
if os.path.isdir(scanpath+'/'+folder):
folderDirectories.append(scanpath+'/'+folder)
self.__print(diagnosticOutput,' Folder: '+scanpath+'/'+folder)
# Mark the folder as scanned
scanedFolders.append(scanpath)
# Find a folder that is not processed jet
scanpath = None
for proc in folderDirectories:
if not proc in scanedFolders:
scanpath = proc
if scanpath == None:
# all directories are processed
break
# For RAW partitions are only files allowed
if self.type_hex =='a2' and len(folderDirectories) >0:
raise Exception('For RAW partitions are no folders allowed')
# always scan the top folder for files
for file in os.listdir(searchPath):
if os.path.isfile(searchPath+'/'+file):
self.__print(diagnosticOutput,' File: '+searchPath+'/'+file)
fileDirectories.append(searchPath+'/'+file)
# Find every file inside these folders
for folder in folderDirectories:
for file in os.listdir(folder):
if os.path.isfile(folder+'/'+file):
self.__print(diagnosticOutput,' File: '+folder+'/'+file)
fileDirectories.append(folder+'/'+file)
except OSError as ex:
raise Exception('Failed process a file for importing! Msg:'+str(ex))
# For every mode:
# Avoid issues by removing all doubled files from the list
self.fileDirectories = list(set(fileDirectories))
# Remove the uncompiled Linux device tree file from the list
if not self.__dtsFileDir == None:
self.__print(diagnosticOutput,' Exclute the file "'+\
self.__dtsFileDir+'" from the list')
if not self.__dtsFileDir in self.fileDirectories:
raise Exception('Failed to find the uncompliled device tree file '+\
self.__dtsFileDir)
self.fileDirectories.remove(self.__dtsFileDir)
# Remove the to uncompiled u-boot script from the list
if not self.__ubootscrFileDir == None:
self.__print(diagnosticOutput,' Exclute the file "'+\
self.__ubootscrFileDir+'" from the list')
if not self.__ubootscrFileDir in self.fileDirectories:
raise Exception('Failed to find the uncompiled u-boot script: '+\
self.__ubootscrFileDir)
self.fileDirectories.remove(self.__ubootscrFileDir)
# Remove all uncompressed archive files form the list
if not self.__uncompressedFilesDir == None:
for arch in self.__uncompressedFilesDir:
self.__print(diagnosticOutput,' Exclute the archive file "'+arch+'" from the list')
if not arch in self.fileDirectories:
raise Exception('Failed to find the unzip file '+arch)
self.fileDirectories.remove(arch)
self.__print(diagnosticOutput,'== File processing for the folder is done')
self.__print(diagnosticOutput,'Number of files: '+str(len(self.fileDirectories)))
self.__filesImported = True
#
#
#
# @brief Update the Block and Sector sizes of the partition
# @param startSector start sector
# @param BlockSectorSize block size
#
def updateSectores(self,startSector=0, BlockSectorSize=0):
self.startSector = round(startSector)
self.BlockSectorSize = round(BlockSectorSize)
#
#
# @brief Return a folder name for the partition for user file import
# @param diagnosticOutput Enable/Disable the console printout
# @return working folder name
#
def giveWorkingFolderName(self,diagnosticOutput=True):
working_folder_pat ='Pat_'+str(self.id)+'_'+str(self.type)
self.__print(diagnosticOutput,'--> Working folder name:"'+working_folder_pat+'"')
return working_folder_pat
#
#
# @brief Calculate the total file size of all files to import to the partition
# @param diagnosticOutput Enable/Disable the console printout
#
def calculatePartitionFilesize(self,diagnosticOutput=True):
self.totalFileSize =0
# Files in the list to progress ?
if self.__compileDeviceTree == None:
raise Exception('Error: Import files before running the'+\
' method "calculatePartitionFilesize()"!')
if self.fileDirectories == None or self.fileDirectories ==[]:
if not self.type_hex=='a2':
raise Exception(' The partition '+str(self.id)+' has no files to import!\n'+ \
' This is not allowed! Please delate the partition from the table\n'+\
' or import some files!')
else:
self.__print(diagnosticOutput,'Warning: The partition '+str(self.id)+' has no files to import')
return
self.__print(diagnosticOutput,'--> Calculate the entire size of partition no.'+str(self.id))
# Calculate total size of the files to add to the partition
for file in self.fileDirectories:
self.__print(diagnosticOutput,' Read file size of: '+str(file))
if(os.path.isfile(file)):
try:
self.totalFileSize += os.path.getsize(file)
except Exception:
raise Exception("Failed to get size of the file: "+str(file))
else:
if self.scan_mode == 1:
self.__print(diagnosticOutput,'WARNING: File path: '+str(file)+' does not exist')
else:
self.__print(diagnosticOutput,' Calculate folder size of folder "'+file+'"')
# Calculate the size of a folder
dir = Path(file)
self.totalFileSize += sum(f.stat().st_size for f in dir.glob('**/*') if f.is_file())
# Check that the files fit in the partition
if self.size != 0:
if self.totalFileSize > self.size:
raise Exception('ERROR: NOT ENOUGH DISK SPACE CONFIGURED ON PARTITION NO.'+str(self.id)+'\n'+ \
'The chosen size of '+str(self.size_str)+ \
' ['+str(self.size)+'B] is to small to fit all files (total size:'+ \
self.__convert_byte2str(self.totalFileSize)+' ['+ \
str(self.totalFileSize)+'B])')
self.totalSize= self.size
else:
# In dynamic file size mode: add the offset to the total size of the files
self.totalSize = self.totalFileSize + self.offset
if self.totalSize == 0:
raise Exception('The partition No.'+str(self.id)+' has no size!')
# Convert byte size to string (1MB, 1GB,...)
self.totalFileSizeStr = self.__convert_byte2str(self.totalFileSize)
self.totalSizeStr = self.__convert_byte2str(self.totalSize)
#####################################################################################################################
#
#
#
# @brief Debug Print
# @param diagnosticOutput Enable/Disable the console printout
def __print(self,diagnosticOutput,str):
if diagnosticOutput:
print(str)
#
#
#
# @brief Convert a byte size as string (1GB,1MB...)
# @param size_bytes Byte value to convert
# @retrun Size in string format
#
def __convert_byte2str(self, size_bytes):
if size_bytes == 0:
return "0B"
size_name = ("B", "K", "M", "G", "T", "P", "E", "Z", "Y")
i = int(math.floor(math.log(size_bytes, 1024)))
p = math.pow(1024, i)
s = math.ceil(size_bytes / p)
s = round(s,0)
s = int(s)
ret = "%s %s" % (s, size_name[i])
return ret.replace(" ","")
#
#
#
# @brief Convert the size format to unsigned integer
# @param size_value Size value as String to convert
# @return size in byte
#
def __size2uint(self,size_value):
factor = 1
# check if size contains a "*" -> return 0 to indicate dynamic
if size_value == "*":
return 0
inp = re.match("^[0-9]+[KMG]?$", size_value, re.I)
# Is the input valid?
if inp == None:
raise Exception(str(size_value)+' is not in the right format!')
else:
# Decode the unit (KB,MB,GB) and the value
size_unit = re.search("[KMG]+$", inp.group(0), re.I)
size_value = re.search("^[0-9]+", inp.group(0), re.I)
# Multiply with the depending factor of the unit
if size_unit :
# Read the upper character
unit = size_unit.group(0).upper()
if unit == 'K':
factor = 1024
elif unit == 'M':
factor = 1024*1024
elif unit == 'G':
factor = 1024*1024*1024
# Convert the value string to integer
try:
size = int(size_value.group(0))
except ValueError:
raise Exception('Failed to convert size value '+str(size_value)+' to integer!')
size = size * factor
return size
#
#
#
# @brief Compile a Linux Device Tree file (dts) if available
# @param diagnosticOutput Enable/Disable the console printout
# @param searchPath Directory to search
# @return File path of the compiled device tree file
#
def __compileDeviceTree(self,diagnosticOutput=True,searchPath =None):
singleFile = len(os.listdir(searchPath)) == 0
self.__print(diagnosticOutput,'--> Compile a Linux Device Tree (.dts) file')
if not singleFile:
self.__print(diagnosticOutput,' Looking for a .dts in the top folder')
dts_file_name = None
dts_file_dir = None
dts_file_found = False
suffix_pos =0
if singleFile:
suffix_pos = searchPath.find('dts')
if suffix_pos >=0:
dts_file_name = searchPath
dts_file_dir = searchPath
else:
# Look for a .dts file in the top folder
for file in os.listdir(searchPath):
if os.path.isfile(searchPath+'/'+file):
suffix_pos = file.find('dts')
if suffix_pos >=0:
if dts_file_found:
raise Exception('More than one .dts file found!\n'+\
'This feature is not supported')
self.__print(diagnosticOutput,'DTS File: '+file)
dts_file_name = file
dts_file_dir = searchPath+'/'+file
dts_file_found = True
# Check if a dts file is found
if dts_file_name == None:
self.__print(diagnosticOutput,'NOTE: No Linux Devicetree '+\
'.dts file is found in the top folder!')
return None
outputfile = dts_file_name[:suffix_pos-3]+'.dtb'
if not singleFile:
# Check that the output file is not already available
for file in os.listdir(searchPath):
if os.path.isfile(searchPath+'/'+file):
if file == outputfile:
self.__print(diagnosticOutput,'Remove the old output file'+file)
try:
os.remove(searchPath+'/'+file)
except Exception:
raise Exception('Failed to delete the old Linux device Tree file')
# Compile the dts file
try:
if singleFile:
os.system('dtc -O dtb -o '+searchPath+' '+dts_file_name)
else:
os.system('dtc -O dtb -o '+searchPath+'/'+outputfile+' '+searchPath+'/'+dts_file_name)
except subprocess.CalledProcessError:
raise Exception('Failed to compile the Linux Devicetree file "'+dts_file_name+'"\n'+ \
'Is the Linux Device compiler "dtc" installed?')
time.sleep(DELAY_MS)
# Check that the Device Tree File exist!
if not os.path.isfile(searchPath+'/'+outputfile):
self.__print(diagnosticOutput,'ERROR: Compilation of the Linux Device Tree failed!')
return None
self.__print(diagnosticOutput,'--> Compilation of the Linux Device Tree file "'+\
dts_file_name+'" done')
self.__print(diagnosticOutput,' Name of outputfile: "'+outputfile+'"')
# Return the uncompiled file directory
return dts_file_dir
#
#
#
# @brief Compile the u-boot script file "boot.script"
# @param diagnosticOutput Enable/Disable the console printout
# @param searchPath Directory to search
# @return File path of the compiled device tree file
#
def __compileubootscript(self,diagnosticOutput=True,searchPath =None):
singleFile = len(os.listdir(searchPath)) == 0
self.__print(diagnosticOutput,'--> Compile the u-boot script "boot.script"')
if not singleFile:
self.__print(diagnosticOutput,' Looking for the "boot.script" file '+ \
'in the top folder')
ubootscr_file_dir = None
ubootscript_file_dir = None
uboot_file_found = False
if singleFile:
pos = searchPath.find('boot.script')
if pos ==-1:
self.__print(diagnosticOutput,'NOTE: No "boot.script" was found '+ \
'in the partition '+str(self.id))
else:
ubootscript_file_dir = searchPath
ubootscr_file_dir = searchPath[:pos]+'boot.script'
else:
# Look for the "boot.script" file in the top folder
for file in os.listdir(searchPath):
if os.path.isfile(searchPath+'/'+file):
if file == 'boot.script':
if uboot_file_found:
raise Exception('More than one "boot.script" file found!\n'+\
'Only one is allowed!')
self.__print(diagnosticOutput,'DTS File: '+file)
ubootscr_file_dir = searchPath+'/boot.scr'
ubootscript_file_dir = searchPath+'/'+file
uboot_file_found = True
# Check if the "boot.script" is found
if ubootscript_file_dir == None:
self.__print(diagnosticOutput,'NOTE: No "boot.script" file '+\
'is found in the top folder!')
return None
if not singleFile:
# Check that the output file is not already available
for file in os.listdir(searchPath):
if os.path.isfile(searchPath+'/'+file):
if file == 'boot.scr':
self.__print(diagnosticOutput,'Remove the old complied u-boot'+ \
' script file: "'+file+'"')
try:
os.remove(searchPath+'/'+file)
except Exception:
raise Exception('Failed to delete the old complied u-boot script')
comand = 'mkimage -A '+self.comp_ubootscript+' -O linux -T script -C none -a 0 -e 0'+ \
' -n u-boot -d '+ubootscript_file_dir+' '+ubootscr_file_dir
self.__print(diagnosticOutput,'--> Compile the u-boot script')
try:
os.system(comand)
except Exception as ex:
raise Exception('Failed to compile the u-boot script "boot.script"\n'+ \
'Are the u-boot tools installed?')
time.sleep(DELAY_MS)
if not os.path.isfile(ubootscr_file_dir):
raise Exception('Failed to complie the u-boot script')
self.__print(diagnosticOutput,' = Done')
# Return the uncompiled file directory
return ubootscript_file_dir
#
#
# @brief Uncompress archive files if available
# @param diagnosticOutput Enable/Disable the console printout
# @param searchPath Directory to search
# @return File path list of uncompressed archive files
#
def __uncompressArchivefiles(self,diagnosticOutput=True,searchPath =None):
singleFile = len(os.listdir(searchPath)) == 0
self.__print(diagnosticOutput,'--> Uncompress Archive files')
if not singleFile:
self.__print(diagnosticOutput,' Looking for archive files '+\
'inside the top folder')
tar_files= []
tar_gz_files =[]
zip_files =[]
searchPath_beforeZip =[]
searchPath_afterZip =[]
if singleFile:
# Look for a archive file in the top folder
if os.path.isfile(searchPath):
if searchPath.find('.tar.gz') >0:
tar_gz_files.append(searchPath)
elif searchPath.find('.tar') >0:
tar_files.append(searchPath)
elif searchPath.find('.zip') >0:
zip_files.append(searchPath)
else:
# Look for a archive file in the top folder
for file in os.listdir(searchPath):
if os.path.isfile(searchPath+'/'+file):
if file.find('.tar.gz') >0:
tar_gz_files.append(searchPath+'/'+file)
elif file.find('.tar') >0:
tar_files.append(searchPath+'/'+file)
elif file.find('.zip') >0:
zip_files.append(searchPath+'/'+file)
# Archive files for processing available ?
if (not tar_files == None) or (not tar_gz_files == None) or (not zip_files == None):
# List all files in the folder to notice the changes after the unziping
if singleFile:
searchPath_beforeZip.append(searchPath)
else:
searchPath_beforeZip = os.listdir(searchPath)
# Progress all tar files
if not tar_files == None:
self.__print(diagnosticOutput,'Process .tar files')
for arch in tar_files:
self.__print(diagnosticOutput,'Unzip the file:" '+arch+'"')
try:
os.system('sudo tar --same-owner xhfv '+arch+' -C '+searchPath)
except subprocess.CalledProcessError:
raise Exception('Failed to unzip the file "'+arch+'"\n')
self.__print(diagnosticOutput,' == Done')
# Progress all tar.gz files
if not tar_gz_files == None:
self.__print(diagnosticOutput,'Process .tar.gz files')
for arch in tar_gz_files:
self.__print(diagnosticOutput,'Unzip the file:" '+arch+'"')
try:
os.system('sudo tar --same-owner -xzvpf '+arch+' -C '+searchPath)
except subprocess.CalledProcessError:
raise Exception('Failed to unzip the file "'+arch+'"\n')
self.__print(diagnosticOutput,' == Done')
# Progress all zip files
if not zip_files == None:
self.__print(diagnosticOutput,'Process .tar.gz files')
for arch in zip_files:
self.__print(diagnosticOutput,'Unzip the file:" '+arch+'"')
try:
os.system('unzip '+arch+' -d '+searchPath)
except subprocess.CalledProcessError:
raise Exception('Failed to unzip the file "'+arch+'"\n')
self.__print(diagnosticOutput,' == Done')
# Archive files for processing available ?
if (not tar_files == None) or (not tar_gz_files == None) or (not zip_files == None):
# List all files in the folder to notice the changes after the unziping
if singleFile:
searchPath_afterZip.append(searchPath)
else:
searchPath_afterZip = os.listdir(searchPath)
# Remove double files from the list
for iteam in searchPath_afterZip:
if not iteam in searchPath_beforeZip:
self.__unzipedFiles.append(searchPath+'/'+iteam)
# List the content off all unzip archive files
self.__print(diagnosticOutput,' -- List of the content of all unzip files/folders --')
for it in self.__unzipedFiles:
self.__print(diagnosticOutput,' '+it)
self.__print(diagnosticOutput,'--> Uncompressing of all files is done')
# Return the uncompiled file directories
return (tar_files+tar_gz_files+zip_files)
###################################################################
#
#
# @brief Class of the BootImage Creater
#
class BootImageCreator:
partitionTable=[] # Partition list decoded from the XML file
outputFileName: str # Name of the output image file with ".img"
pathOfOutputImageDir: str # Directory of the output file
totalImageSize : int # Total image size of all partitions in byte
totalImageSizeStr : str # Total image size of all partitions as string (1MB,1GB)
__loopback_used = [] # list of used loopback devices
__mounted_fs = [] # list of mounted loopback devices
__imageFilepath : str # Directory of the output file with name
__usedLoopback : str # Used loopback device
#
#
#
# @brief Constructor
# @param partitionTable partitionTable as list of "Partition" class objects
# @param outputImageFileName Name of the output image file with the suffix ".img"
# @param pathOfOutputImageDir File path of the output image file
#
def __init__(self, partitionTable=None,outputImageFileName=None,pathOfOutputImageDir=None):
# Check that the partition number is only available once
partitionTable_local = []
id_list_local =[]
for pat in partitionTable:
if pat.id == 0:
raise Exception('Partition No. 0 is not allowed; begin with 1')
if pat.totalSize == None:
raise Exception('Run the methode "calculatePartitionFilesize()"'+\
'before the constructor of "BootImageCreator"')
# Something to copy available ?
temp_total_file=0
for pat in partitionTable:
temp_total_file =temp_total_file+ pat.totalFileSize
if temp_total_file ==0:
raise Exception('No partition has files to copy to it')
if len(partitionTable) > 4:
raise Exception('Not more than 4 partitions are allowed')
for pat in partitionTable:
for pat_loc in partitionTable_local:
if pat_loc.id == pat.id:
raise Exception('The partition number '+str(pat.id)+' exists twice!')
partitionTable_local.append(pat)
id_list_local.append(pat.id)
# Sort the table by the partition number
partitionTable_local = sorted(partitionTable_local, key=lambda x: x.id)
id_list_local = sorted(id_list_local)
# Check that the partition numbers are in a row
for i in range(0,len(id_list_local)-1):
if not id_list_local[i]+1==id_list_local[i+1]:
raise Exception('The partition numbers are not in a row from '+\
+str(id_list_local[i])+' to '+str(id_list_local[i+1]))
self.partitionTable = partitionTable_local
#Check that the path of file location exists
if not os.path.isdir(pathOfOutputImageDir):
raise Exception('The selected output file path does not exist!')
self.pathOfOutputImageDir= pathOfOutputImageDir
# Check that the name of output file is okay
if not re.match("^[a-z0-9\._]+$", outputImageFileName, re.I):
raise Exception('The name '+str(outputImageFileName)+' can not be used as Linux file name!')
if outputImageFileName.find(".img")==-1:
raise Exception('The selected output file name has not the suffix ".img"!')
self.outputFileName = outputImageFileName
self.__imageFilepath = pathOfOutputImageDir + '/'+outputImageFileName
# Calculate the total image size
self.totalImageSize =0
for part in self.partitionTable:
self.totalImageSize = self.totalImageSize + part.totalSize
# Remove ".0" to avoid issues
self.totalImageSize = round(self.totalImageSize)
self.totalImageSizeStr = self.__convert_byte2str(self.totalImageSize)
#
#
#
# @brief Print the loaded partition table
#
def printPartitionTable(self):
print('-------------------------------------------------------------------')
print(' -- Partition Table -- ')
for item in self.partitionTable:
print(' --- Partition No. '+str(item.id)+' ---')
print(' Filesystem: '+ item.type+' | Size: '+item.size_str)
print(' Offset: '+item.offset_str)
print(' File2copy: '+item.totalFileSizeStr+' | Total: '+item.totalSizeStr)
if(item.totalFileSize ==0 or item.totalSize == 0):
print(' Filled: 0%')
else:
print(' Filled: '+str(round((item.totalFileSize/item.totalSize)*100))+'%')
print(' L-- Size: '+str(item.size)+'B | Offset: '+str(item.offset)+\
'B | Total: '+str(item.totalSize)+'B')
print('-------------------------------------------------------------------')
print(' Total Image size: '+self.totalImageSizeStr+' '+str(self.totalImageSize)+'B')
print('-------------------------------------------------------------------')
print(' Image File Name: "'+self.outputFileName+'"')
print('-------------------------------------------------------------------')
#
#
#
# @brief Generate a new Image file with the selected partitions
# @param diagnosticOutput Enable/Disable the console printout
#
def generateImage(self, diagnosticOutput = True):
self.__print(diagnosticOutput,'--> Start generating all partitions of the table')
# Step 1: Create and mount a new image
self.__createEmptyImage(diagnosticOutput)
# Step 2: Create a loopback device
self.__createLoopbackDevice(diagnosticOutput,str(self.totalImageSize), 0)
# Step 3: Calculate partition offsets and sectors for all partitions of the table
self._calculateTableSectores(diagnosticOutput)
# Step 4: Create the partition table with "fdisk"
self.__createPartitonTable(diagnosticOutput)
# Step 5: Clear and unmount the used loopback device
self.__delete_loopback(diagnosticOutput,self.__usedLoopback)
# Step 6: Copy the files to the partition table
for parts in self.partitionTable:
self.__print(diagnosticOutput,' + Prase partition Number '+ str(parts.id))
self.__prase_partition(diagnosticOutput,parts)
# Step 7: Unmount and delate all open loopback devices
self.__unmountDeleteLoopbacks(diagnosticOutput)
#
#
#
# @brief Compress the output image file to ".zip"
# @param diagnosticOutput Enable/Disable the console printout
# @param zipfileName Path with name of the zip file
#
def compressOutput(self, diagnosticOutput=True,zipfileName=None):
if zipfileName == None:
raise Exception('The zip file must be specified')
if not os.path.isfile(self.__imageFilepath):
raise Exception('The output image file does not exist')
# delete the old zip file
if os.path.isfile(zipfileName):
self.__print(diagnosticOutput,' Remove the old zip file ')
try:
os.remove(zipfileName)