Debian Codegraph @

util/qualcomm/mbn_tools.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 #===============================================================================
3 #
4 # MBN TOOLS
5 #
6 # GENERAL DESCRIPTION
7 # Contains all MBN Utilities for image generation
8 #
9 # SPDX-License-Identifier: BSD-3-Clause
10
11 #-------------------------------------------------------------------------------
12 # EDIT HISTORY FOR FILE
13 #
14 # This section contains comments describing changes made to the module.
15 # Notice that changes are listed in reverse chronological order.
16 #
17 # when who what, where, why
18 # -------- --- ---------------------------------------------------------
19 # 05/21/18 rissha Added support for extended MBNV6 and Add support for hashing elf segments with SHA384
20 # 03/22/18 thiru Added support for extended MBNV5.
21 # 06/06/13 yliong CR 497042: Signed and encrypted image is corrupted. MRC features.
22 # 03/18/13 dhaval Add support for hashing elf segments with SHA256 and
23 # sync up to mpss, adsp mbn-tools
24 # 01/14/13 kedara Remove dependency on .builds, cust<bid>.h, targ<bid>.h files
25 # 08/30/12 kedara Add virtual block suppport
26 # 02/24/12 dh Add ssd side effect file names
27 # 07/08/11 aus Added support for image_id in SBL image header as required by PBL
28 # Sahara mode
29 # 10/20/11 dxiang Clean up
30 #===============================================================================
31
32 import stat
33 import csv
34 import itertools
35 import struct
36 import os
37 import shutil
38 import hashlib
39
40 #----------------------------------------------------------------------------
41 # GLOBAL VARIABLES BEGIN
42 #----------------------------------------------------------------------------
43 PAD_BYTE_1 = 255 # Padding byte 1s
44 PAD_BYTE_0 = 0 # Padding byte 0s
45 SHA256_SIGNATURE_SIZE = 256 # Support SHA256
46 MAX_NUM_ROOT_CERTS = 4 # Maximum number of OEM root certificates
47 MI_BOOT_SBL_HDR_SIZE = 80 # sizeof(sbl_header)
48 BOOT_HEADER_LENGTH = 20 # Boot Header Number of Elements
49 SBL_HEADER_LENGTH = 20 # SBL Header Number of Elements
50 MAX_PHDR_COUNT = 100 # Maximum allowable program headers
51 CERT_CHAIN_ONEROOT_MAXSIZE = 6*1024 # Default Cert Chain Max Size for one root
52 VIRTUAL_BLOCK_SIZE = 131072 # Virtual block size for MCs insertion in SBL1 if ENABLE_VIRTUAL_BLK ON
53 MAGIC_COOKIE_LENGTH = 12 # Length of magic Cookie inserted per VIRTUAL_BLOCK_SIZE
54 MIN_IMAGE_SIZE_WITH_PAD = 256*1024 # Minimum image size for sbl1 Nand based OTA feature
55
56 SBL_AARCH64 = 0xF # Indicate that SBL is a Aarch64 image
57 SBL_AARCH32 = 0x0 # Indicate that SBL is a Aarch32 image
58
59 # Magic numbers filled in for boot headers
60 FLASH_CODE_WORD = 0x844BDCD1
61 UNIFIED_BOOT_COOKIE_MAGIC_NUMBER = 0x33836685
62 MAGIC_NUM = 0x73D71034
63 AUTODETECT_PAGE_SIZE_MAGIC_NUM = 0x7D0B435A
64 AUTODETECT_PAGE_SIZE_MAGIC_NUM64 = 0x7D0B5436
65 AUTODETECT_PAGE_SIZE_MAGIC_NUM128 = 0x7D0B6577
66 SBL_VIRTUAL_BLOCK_MAGIC_NUM = 0xD48B54C6
67
68 # ELF Definitions
69 ELF_HDR_COMMON_SIZE = 24
70 ELF32_HDR_SIZE = 52
71 ELF32_PHDR_SIZE = 32
72 ELF64_HDR_SIZE = 64
73 ELF64_PHDR_SIZE = 56
74 ELFINFO_MAG0_INDEX = 0
75 ELFINFO_MAG1_INDEX = 1
76 ELFINFO_MAG2_INDEX = 2
77 ELFINFO_MAG3_INDEX = 3
78 ELFINFO_MAG0 = 127 # 0x7F
79 ELFINFO_MAG1 = 69 # E
80 ELFINFO_MAG2 = 76 # L
81 ELFINFO_MAG3 = 70 # F
82 ELFINFO_CLASS_INDEX = 4
83 ELFINFO_CLASS_32 = 1
84 ELFINFO_CLASS_64 = 2
85 ELFINFO_VERSION_INDEX = 6
86 ELFINFO_VERSION_CURRENT = 1
87 ELF_BLOCK_ALIGN = 0x1000
88 ALIGNVALUE_1MB = 0x100000
89 ALIGNVALUE_4MB = 0x400000
90 ELFINFO_DATA2LSB = b'\x01'
91 ELFINFO_EXEC_ETYPE = b'\x02\x00'
92 ELFINFO_ARM_MACHINETYPE = b'\x28\x00'
93 ELFINFO_VERSION_EV_CURRENT = b'\x01\x00\x00\x00'
94 ELFINFO_SHOFF = 0x00
95 ELFINFO_PHNUM = b'\x01\x00'
96 ELFINFO_RESERVED = 0x00
97
98 # ELF Program Header Types
99 NULL_TYPE = 0x0
100 LOAD_TYPE = 0x1
101 DYNAMIC_TYPE = 0x2
102 INTERP_TYPE = 0x3
103 NOTE_TYPE = 0x4
104 SHLIB_TYPE = 0x5
105 PHDR_TYPE = 0x6
106 TLS_TYPE = 0x7
107
108 """
109 The eight bits between 20 and 27 in the p_flags field in ELF program headers
110 is not used by the standard ELF format. We use this byte to hold OS and processor
111 specific fields as recommended by ARM.
112
113 The bits in this byte are defined as follows:
114
115 Pool Indx Segment type Access type Page/non page
116 bits in p_flags /-----27-----/----26-24-------/---- 23-21----/------20-------/
117
118 After parsing segment description strings in the SCL file, the appropriate segment
119 flag values are chosen from the follow definitions. The mask defined below is then
120 used to update the existing p_flags field in the program headers with the updated
121 values.
122 """
123 # Mask for bits 20-27 to parse program header p_flags
124 MI_PBT_FLAGS_MASK = 0x0FF00000
125
126 # Helper defines to help parse ELF program headers
127 MI_PBT_FLAG_SEGMENT_TYPE_MASK = 0x07000000
128 MI_PBT_FLAG_SEGMENT_TYPE_SHIFT = 0x18
129 MI_PBT_FLAG_PAGE_MODE_MASK = 0x00100000
130 MI_PBT_FLAG_PAGE_MODE_SHIFT = 0x14
131 MI_PBT_FLAG_ACCESS_TYPE_MASK = 0x00E00000
132 MI_PBT_FLAG_ACCESS_TYPE_SHIFT = 0x15
133 MI_PBT_FLAG_POOL_INDEX_MASK = 0x08000000
134 MI_PBT_FLAG_POOL_INDEX_SHIFT = 0x1B
135
136 # Segment Type
137 MI_PBT_L4_SEGMENT = 0x0
138 MI_PBT_AMSS_SEGMENT = 0x1
139 MI_PBT_HASH_SEGMENT = 0x2
140 MI_PBT_BOOT_SEGMENT = 0x3
141 MI_PBT_L4BSP_SEGMENT = 0x4
142 MI_PBT_SWAPPED_SEGMENT = 0x5
143 MI_PBT_XBL_SEC_SEGMENT = 0x5
144 MI_PBT_SWAP_POOL_SEGMENT = 0x6
145 MI_PBT_PHDR_SEGMENT = 0x7
146
147 # Page/Non-Page Type
148 MI_PBT_NON_PAGED_SEGMENT = 0x0
149 MI_PBT_PAGED_SEGMENT = 0x1
150
151 # Access Type
152 MI_PBT_RW_SEGMENT = 0x0
153 MI_PBT_RO_SEGMENT = 0x1
154 MI_PBT_ZI_SEGMENT = 0x2
155 MI_PBT_NOTUSED_SEGMENT = 0x3
156 MI_PBT_SHARED_SEGMENT = 0x4
157 MI_PBT_RWE_SEGMENT = 0x7
158
159 # ELF Segment Flag Definitions
160 MI_PBT_ELF_AMSS_NON_PAGED_RO_SEGMENT = 0x01200000
161 MI_PBT_ELF_AMSS_PAGED_RO_SEGMENT = 0x01300000
162 MI_PBT_ELF_SWAP_POOL_NON_PAGED_ZI_SEGMENT_INDEX0 = 0x06400000
163 MI_PBT_ELF_SWAPPED_PAGED_RO_SEGMENT_INDEX0 = 0x05300000
164 MI_PBT_ELF_SWAP_POOL_NON_PAGED_ZI_SEGMENT_INDEX1 = 0x0E400000
165 MI_PBT_ELF_SWAPPED_PAGED_RO_SEGMENT_INDEX1 = 0x0D300000
166 MI_PBT_ELF_AMSS_NON_PAGED_ZI_SEGMENT = 0x01400000
167 MI_PBT_ELF_AMSS_PAGED_ZI_SEGMENT = 0x01500000
168 MI_PBT_ELF_AMSS_NON_PAGED_RW_SEGMENT = 0x01000000
169 MI_PBT_ELF_AMSS_PAGED_RW_SEGMENT = 0x01100000
170 MI_PBT_ELF_AMSS_NON_PAGED_NOTUSED_SEGMENT = 0x01600000
171 MI_PBT_ELF_AMSS_PAGED_NOTUSED_SEGMENT = 0x01700000
172 MI_PBT_ELF_AMSS_NON_PAGED_SHARED_SEGMENT = 0x01800000
173 MI_PBT_ELF_AMSS_PAGED_SHARED_SEGMENT = 0x01900000
174 MI_PBT_ELF_HASH_SEGMENT = 0x02200000
175 MI_PBT_ELF_BOOT_SEGMENT = 0x03200000
176 MI_PBT_ELF_PHDR_SEGMENT = 0x07000000
177 MI_PBT_ELF_NON_PAGED_L4BSP_SEGMENT = 0x04000000
178 MI_PBT_ELF_PAGED_L4BSP_SEGMENT = 0x04100000
179 MI_PBT_ELF_AMSS_RELOCATABLE_IMAGE = 0x8000000
180
181 # New definitions for EOS demap paging requirement
182 # Bit 20 (0b) Bit 24-26(000): Non Paged = 0x0000_0000
183 # Bit 20 (1b) Bit 24-26(000): Locked Paged = 0x0010_0000
184 # Bit 20 (1b) Bit 24-26(001): Unlocked Paged = 0x0110_0000
185 # Bit 20 (0b) Bit 24-26(011): non secure = 0x0310_0000
186 MI_PBT_ELF_RESIDENT_SEGMENT = 0x00000000
187 MI_PBT_ELF_PAGED_LOCKED_SEGMENT = 0x00100000
188 MI_PBT_ELF_PAGED_UNLOCKED_SEGMENT = 0x01100000
189 MI_PBT_ELF_UNSECURE_SEGMENT = 0x03100000
190 #----------------------------------------------------------------------------
191 # GLOBAL VARIABLES END
192 #----------------------------------------------------------------------------
193
194 #----------------------------------------------------------------------------
195 # CLASS DEFINITIONS BEGIN
196 #----------------------------------------------------------------------------
197 #----------------------------------------------------------------------------
198 # OS Type ID Class
199 #----------------------------------------------------------------------------
200 class OSType:
201 BMP_BOOT_OS = 0
202 WM_BOOT_OS = 1
203 ANDROID_BOOT_OS = 2
204 CHROME_BOOT_OS = 3
205 SYMBIAN_BOOT_OS = 4
206 LINUX_BOOT_OS = 5
207
208 #----------------------------------------------------------------------------
209 # Image Type ID Class - These values must be kept consistent with mibib.h
210 #----------------------------------------------------------------------------
211 class ImageType:
212 NONE_IMG = 0
213 OEM_SBL_IMG = 1
214 AMSS_IMG = 2
215 QCSBL_IMG = 3
216 HASH_IMG = 4
217 APPSBL_IMG = 5
218 APPS_IMG = 6
219 HOSTDL_IMG = 7
220 DSP1_IMG = 8
221 FSBL_IMG = 9
222 DBL_IMG = 10
223 OSBL_IMG = 11
224 DSP2_IMG = 12
225 EHOSTDL_IMG = 13
226 NANDPRG_IMG = 14
227 NORPRG_IMG = 15
228 RAMFS1_IMG = 16
229 RAMFS2_IMG = 17
230 ADSP_Q5_IMG = 18
231 APPS_KERNEL_IMG = 19
232 BACKUP_RAMFS_IMG = 20
233 SBL1_IMG = 21
234 SBL2_IMG = 22
235 RPM_IMG = 23
236 SBL3_IMG = 24
237 TZ_IMG = 25
238 PSI_IMG = 32
239
240 #----------------------------------------------------------------------------
241 # Global Image Type Table
242 # Format of the look-up table:
243 # KEY - IMAGE_TYPE string as passed into mbn_builder.py
244 # VALUE - [Specific ImageType ID enum, Template key string, MBN Type]
245 #----------------------------------------------------------------------------
246 image_id_table = {
247 'appsbl': [ImageType.APPSBL_IMG, 'APPSBL_IMG', 'bin'],
248 'dbl': [ImageType.DBL_IMG, 'DBL_IMG', 'bin'],
249 'osbl': [ImageType.OSBL_IMG, 'OSBL_IMG', 'bin'],
250 'amss': [ImageType.AMSS_IMG, 'AMSS_IMG', 'elf'],
251 'amss_mbn': [ImageType.HASH_IMG, 'HASH_IMG', 'elf'],
252 'apps': [ImageType.APPS_IMG, 'APPS_IMG', 'bin'],
253 'hostdl': [ImageType.HOSTDL_IMG, 'HOSTDL_IMG', 'bin'],
254 'ehostdl': [ImageType.EHOSTDL_IMG, 'EHOSTDL_IMG', 'bin'],
255 'emmcbld': [ImageType.EHOSTDL_IMG, 'EMMCBLD_IMG', 'bin'],
256 'qdsp6fw': [ImageType.DSP1_IMG, 'DSP1_IMG', 'elf'],
257 'qdsp6sw': [ImageType.DSP2_IMG, 'DSP2_IMG', 'elf'],
258 'qdsp5': [ImageType.ADSP_Q5_IMG, 'ADSP_Q5_IMG', 'bin'],
259 'tz': [ImageType.TZ_IMG, 'TZ_IMG', 'elf'],
260 'tz_rumi': [ImageType.TZ_IMG, 'TZ_IMG', 'elf'],
261 'tz_virtio': [ImageType.TZ_IMG, 'TZ_IMG', 'elf'],
262 'tzbsp_no_xpu': [ImageType.TZ_IMG, 'TZ_IMG', 'elf'],
263 'tzbsp_with_test': [ImageType.TZ_IMG, 'TZ_IMG', 'elf'],
264 'rpm': [ImageType.RPM_IMG, 'RPM_IMG', 'elf'],
265 'sbl1': [ImageType.SBL1_IMG, 'SBL1_IMG', 'bin'],
266 'sbl2': [ImageType.SBL2_IMG, 'SBL2_IMG', 'bin'],
267 'sbl3': [ImageType.SBL3_IMG, 'SBL3_IMG', 'bin'],
268 'efs1': [ImageType.RAMFS1_IMG, 'RAMFS1_IMG', 'bin'],
269 'efs2': [ImageType.RAMFS2_IMG, 'RAMFS2_IMG', 'bin'],
270 'pmic': [ImageType.PSI_IMG, 'PSI_IMG', 'elf'],
271 # DO NOT add any additional image information
272 }
273
274 #----------------------------------------------------------------------------
275 # Header Class Notes:
276 # In order to properly read and write the header structures as binary data,
277 # the Python Struct library is used to align and package up the header objects
278 # All Struct objects are initialized by a special string with the following
279 # notation. These structure objects are then used to decode binary data in order
280 # to fill out the appropriate class in Python, or they are used to package up
281 # the Python class so that we may write the binary data out.
282 #----------------------------------------------------------------------------
283 """
284 Format | C Type | Python Type | Standard Size
285 -----------------------------------------------------
286 1) 'X's | char * | string | 'X' bytes
287 2) H | unsigned short | integer | 2 bytes
288 3) I | unsigned int | integer | 4 bytes
289
290 """
291
292 #----------------------------------------------------------------------------
293 # ELF Header Class
294 #----------------------------------------------------------------------------
295 class Elf_Ehdr_common:
296 # Structure object to align and package the ELF Header
297 s = struct.Struct('16sHHI')
298
299 def __init__(self, data):
300 unpacked_data = (Elf_Ehdr_common.s).unpack(data)
301 self.unpacked_data = unpacked_data
302 self.e_ident = unpacked_data[0]
303 self.e_type = unpacked_data[1]
304 self.e_machine = unpacked_data[2]
305 self.e_version = unpacked_data[3]
306
307 def printValues(self):
308 print("ATTRIBUTE / VALUE")
309 for attr, value in self.__dict__.items():
310 print(attr, value)
311
312
313
314 #----------------------------------------------------------------------------
315 # ELF Header Class
316 #----------------------------------------------------------------------------
317 class Elf32_Ehdr:
318 # Structure object to align and package the ELF Header
319 s = struct.Struct('16sHHIIIIIHHHHHH')
320
321 def __init__(self, data):
322 unpacked_data = (Elf32_Ehdr.s).unpack(data)
323 self.unpacked_data = unpacked_data
324 self.e_ident = unpacked_data[0]
325 self.e_type = unpacked_data[1]
326 self.e_machine = unpacked_data[2]
327 self.e_version = unpacked_data[3]
328 self.e_entry = unpacked_data[4]
329 self.e_phoff = unpacked_data[5]
330 self.e_shoff = unpacked_data[6]
331 self.e_flags = unpacked_data[7]
332 self.e_ehsize = unpacked_data[8]
333 self.e_phentsize = unpacked_data[9]
334 self.e_phnum = unpacked_data[10]
335 self.e_shentsize = unpacked_data[11]
336 self.e_shnum = unpacked_data[12]
337 self.e_shstrndx = unpacked_data[13]
338
339 def printValues(self):
340 print("ATTRIBUTE / VALUE")
341 for attr, value in self.__dict__.items():
342 print(attr, value)
343
344 def getPackedData(self):
345 if type(self.e_ident) == str:
346 packvalue = bytes(self.e_ident, 'utf-8')
347 else:
348 packvalue = self.e_ident
349 values = [packvalue,
350 self.e_type,
351 self.e_machine,
352 self.e_version,
353 self.e_entry,
354 self.e_phoff,
355 self.e_shoff,
356 self.e_flags,
357 self.e_ehsize,
358 self.e_phentsize,
359 self.e_phnum,
360 self.e_shentsize,
361 self.e_shnum,
362 self.e_shstrndx
363 ]
364
365 return (Elf32_Ehdr.s).pack(*values)
366
367 #----------------------------------------------------------------------------
368 # ELF Program Header Class
369 #----------------------------------------------------------------------------
370 class Elf32_Phdr:
371
372 # Structure object to align and package the ELF Program Header
373 s = struct.Struct('I' * 8)
374
375 def __init__(self, data):
376 unpacked_data = (Elf32_Phdr.s).unpack(data)
377 self.unpacked_data = unpacked_data
378 self.p_type = unpacked_data[0]
379 self.p_offset = unpacked_data[1]
380 self.p_vaddr = unpacked_data[2]
381 self.p_paddr = unpacked_data[3]
382 self.p_filesz = unpacked_data[4]
383 self.p_memsz = unpacked_data[5]
384 self.p_flags = unpacked_data[6]
385 self.p_align = unpacked_data[7]
386
387 def printValues(self):
388 print("ATTRIBUTE / VALUE")
389 for attr, value in self.__dict__.items():
390 print(attr, value)
391
392 def getPackedData(self):
393 values = [self.p_type,
394 self.p_offset,
395 self.p_vaddr,
396 self.p_paddr,
397 self.p_filesz,
398 self.p_memsz,
399 self.p_flags,
400 self.p_align
401 ]
402
403 return (Elf32_Phdr.s).pack(*values)
404
405 #----------------------------------------------------------------------------
406 # ELF Header Class
407 #----------------------------------------------------------------------------
408 class Elf64_Ehdr:
409 # Structure object to align and package the ELF Header
410 s = struct.Struct('16sHHIQQQIHHHHHH')
411
412 def __init__(self, data):
413 unpacked_data = (Elf64_Ehdr.s).unpack(data)
414 self.unpacked_data = unpacked_data
415 self.e_ident = unpacked_data[0]
416 self.e_type = unpacked_data[1]
417 self.e_machine = unpacked_data[2]
418 self.e_version = unpacked_data[3]
419 self.e_entry = unpacked_data[4]
420 self.e_phoff = unpacked_data[5]
421 self.e_shoff = unpacked_data[6]
422 self.e_flags = unpacked_data[7]
423 self.e_ehsize = unpacked_data[8]
424 self.e_phentsize = unpacked_data[9]
425 self.e_phnum = unpacked_data[10]
426 self.e_shentsize = unpacked_data[11]
427 self.e_shnum = unpacked_data[12]
428 self.e_shstrndx = unpacked_data[13]
429
430 def printValues(self):
431 print("ATTRIBUTE / VALUE")
432 for attr, value in self.__dict__.items():
433 print(attr, value)
434
435 def getPackedData(self):
436 if type(self.e_ident) == str:
437 packvalue = bytes(self.e_ident, 'utf-8')
438 else:
439 packvalue = self.e_ident
440 values = [packvalue,
441 self.e_type,
442 self.e_machine,
443 self.e_version,
444 self.e_entry,
445 self.e_phoff,
446 self.e_shoff,
447 self.e_flags,
448 self.e_ehsize,
449 self.e_phentsize,
450 self.e_phnum,
451 self.e_shentsize,
452 self.e_shnum,
453 self.e_shstrndx
454 ]
455
456 return (Elf64_Ehdr.s).pack(*values)
457
458 #----------------------------------------------------------------------------
459 # ELF Program Header Class
460 #----------------------------------------------------------------------------
461 class Elf64_Phdr:
462
463 # Structure object to align and package the ELF Program Header
464 s = struct.Struct('IIQQQQQQ')
465
466 def __init__(self, data):
467 unpacked_data = (Elf64_Phdr.s).unpack(data)
468 self.unpacked_data = unpacked_data
469 self.p_type = unpacked_data[0]
470 self.p_flags = unpacked_data[1]
471 self.p_offset = unpacked_data[2]
472 self.p_vaddr = unpacked_data[3]
473 self.p_paddr = unpacked_data[4]
474 self.p_filesz = unpacked_data[5]
475 self.p_memsz = unpacked_data[6]
476 self.p_align = unpacked_data[7]
477
478 def printValues(self):
479 print("ATTRIBUTE / VALUE")
480 for attr, value in self.__dict__.items():
481 print(attr, value)
482
483 def getPackedData(self):
484 values = [self.p_type,
485 self.p_flags,
486 self.p_offset,
487 self.p_vaddr,
488 self.p_paddr,
489 self.p_filesz,
490 self.p_memsz,
491 self.p_align
492 ]
493
494 return (Elf64_Phdr.s).pack(*values)
495
496
497 #----------------------------------------------------------------------------
498 # ELF Segment Information Class
499 #----------------------------------------------------------------------------
500 class SegmentInfo:
501 def __init__(self):
502 self.flag = 0
503 def printValues(self):
504 print('Flag: ' + str(self.flag))
505
506 #----------------------------------------------------------------------------
507 # Regular Boot Header Class
508 #----------------------------------------------------------------------------
509 class Boot_Hdr:
510 def __init__(self, init_val):
511 self.image_id = ImageType.NONE_IMG
512 self.flash_parti_ver = 3
513 self.image_src = init_val
514 self.image_dest_ptr = init_val
515 self.image_size = init_val
516 self.code_size = init_val
517 self.sig_ptr = init_val
518 self.sig_size = init_val
519 self.cert_chain_ptr = init_val
520 self.cert_chain_size = init_val
521 self.magic_number1 = init_val
522 self.version = init_val
523 self.OS_type = init_val
524 self.boot_apps_parti_entry = init_val
525 self.boot_apps_size_entry = init_val
526 self.boot_apps_ram_loc = init_val
527 self.reserved_ptr = init_val
528 self.reserved_1 = init_val
529 self.reserved_2 = init_val
530 self.reserved_3 = init_val
531 self.reserved = 0
532 self.common_metadata_size = init_val
533
534 # Common Metadata members. These are needed for an MBNv7.
535 # Common Metadata is placed just after the header, hence, clubbed with
536 # this header.
537 self.common_metadata_major_version = 0
538 self.common_metadata_minor_version = 0
539 self.software_id = init_val
540 self.secondary_software_id = 0
541 self.hash_table_algorithm = 3
542 self.measurement_register_target = 0
543
544 # OEM Metadata 2.0 Members added for MBNv7.
545 self.major_version = 2
546 self.minor_version = 0
547 self.anti_rollback_version = 0
548 self.mrc_index = 0
549 self.soc_hw_ver_0 = 0
550 self.soc_hw_ver_1 = 0
551 self.soc_hw_ver_2 = 0
552 self.soc_hw_ver_3 = 0
553 self.soc_hw_ver_4 = 0
554 self.soc_hw_ver_5 = 0
555 self.soc_hw_ver_6 = 0
556 self.soc_hw_ver_7 = 0
557 self.soc_hw_ver_8 = 0
558 self.soc_hw_ver_9 = 0
559 self.soc_hw_ver_10 = 0
560 self.soc_hw_ver_11 = 0
561 self.soc_feature_id = 0
562 self.jtag_id = 0
563 self.serial_number_0 = 0
564 self.serial_number_1 = 0
565 self.serial_number_2 = 0
566 self.serial_number_3 = 0
567 self.serial_number_4 = 0
568 self.serial_number_5 = 0
569 self.serial_number_6 = 0
570 self.serial_number_7 = 0
571 self.oem_id = 0
572 self.oem_product_id = 0
573 self.soc_lifecycle_state = 0
574 self.oem_lifecycle_state = 0
575 self.oem_root_certificate_hash_algorithm = 0
576 self.oem_root_certificate_hash = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
577 self.flags = 1398101
578
579 def getLength(self):
580 return BOOT_HEADER_LENGTH
581
582 def writePackedData(self, target, write_full_hdr):
583 if self.flash_parti_ver == 7:
584 values = [self.reserved,
585 self.flash_parti_ver,
586 self.common_metadata_size,
587 self.metadata_size_qti,
588 self.metadata_size,
589 self.code_size,
590 self.image_src, # QTI signature size per MBNv6/v5/v3 structure below.
591 self.image_dest_ptr, # QTI certificate chain size per MBNv6/v5/v3 structure below.
592 self.sig_size,
593 self.cert_chain_size,
594 # Common Metadata members.
595 self.common_metadata_major_version,
596 self.common_metadata_minor_version,
597 self.software_id,
598 self.secondary_software_id,
599 self.hash_table_algorithm,
600 self.measurement_register_target,
601 # OEM Metadata 2.0 members.
602 self.major_version,
603 self.minor_version,
604 self.anti_rollback_version,
605 self.mrc_index,
606 self.soc_hw_ver_0,
607 self.soc_hw_ver_1,
608 self.soc_hw_ver_2,
609 self.soc_hw_ver_3,
610 self.soc_hw_ver_4,
611 self.soc_hw_ver_5,
612 self.soc_hw_ver_6,
613 self.soc_hw_ver_7,
614 self.soc_hw_ver_8,
615 self.soc_hw_ver_9,
616 self.soc_hw_ver_10,
617 self.soc_hw_ver_11,
618 self.soc_feature_id,
619 self.jtag_id,
620 self.serial_number_0,
621 self.serial_number_1,
622 self.serial_number_2,
623 self.serial_number_3,
624 self.serial_number_4,
625 self.serial_number_5,
626 self.serial_number_6,
627 self.serial_number_7,
628 self.oem_id,
629 self.oem_product_id,
630 self.soc_lifecycle_state,
631 self.oem_lifecycle_state,
632 self.oem_root_certificate_hash_algorithm,
633 self.oem_root_certificate_hash,
634 self.flags]
635 else:
636 values = [self.image_id,
637 self.flash_parti_ver,
638 self.image_src,
639 self.image_dest_ptr,
640 self.image_size,
641 self.code_size ,
642 self.sig_ptr,
643 self.sig_size,
644 self.cert_chain_ptr,
645 self.cert_chain_size,
646 self.magic_number1,
647 self.version,
648 self.OS_type,
649 self.boot_apps_parti_entry,
650 self.boot_apps_size_entry,
651 self.boot_apps_ram_loc,
652 self.reserved_ptr,
653 self.reserved_1,
654 self.reserved_2,
655 self.reserved_3 ]
656
657 if self.flash_parti_ver == 6:
658 values.insert(10, self.metadata_size_qti)
659 values.insert(11, self.metadata_size)
660
661 if self.image_dest_ptr >= 0x100000000:
662 values[3] = 0xFFFFFFFF
663
664 if self.cert_chain_ptr >= 0x100000000:
665 values[6] = 0xFFFFFFFF
666
667 if self.sig_ptr >= 0x100000000:
668 values[8] = 0xFFFFFFFF
669
670 # Write 10 entries(40B) or 20 entries(80B) of boot header
671 if write_full_hdr is False:
672 if self.flash_parti_ver == 6:
673 s = struct.Struct('I'* 12)
674 values = values[:12]
675 elif self.flash_parti_ver == 7:
676 # MBNv7 Header is 40 bytes. Common Metadata is 24 bytes,
677 # OEM Metadata is 224 bytes and of the format: "I*18 + Q*8 + I*5+ 64s + I".
678 s = struct.Struct('I'*34 + 'Q'*8 + 'I'*5 + '64sI')
679 else:
680 s = struct.Struct('I'* 10)
681 values = values[:10]
682 else:
683 s = struct.Struct('I' * self.getLength())
684
685 packed_data = s.pack(*values)
686
687 fp = OPEN(target,'wb')
688 fp.write(packed_data)
689 fp.close()
690
691 return s.size
692
693 #----------------------------------------------------------------------------
694 # SBL Boot Header Class
695 #----------------------------------------------------------------------------
696 class Sbl_Hdr:
697 def __init__(self, init_val):
698 self.codeword = init_val
699 self.magic = init_val
700 self.image_id = init_val
701 self.reserved_1 = init_val
702 self.reserved_2 = init_val
703 self.image_src = init_val
704 self.image_dest_ptr = init_val
705 self.image_size = init_val
706 self.code_size = init_val
707 self.sig_ptr = init_val
708 self.sig_size = init_val
709 self.cert_chain_ptr = init_val
710 self.cert_chain_size = init_val
711 self.oem_root_cert_sel = init_val
712 self.oem_num_root_certs = init_val
713 self.booting_image_config = init_val
714 self.reserved_6 = init_val
715 self.reserved_7 = init_val
716 self.reserved_8 = init_val
717 self.reserved_9 = init_val
718
719 def getLength(self):
720 return SBL_HEADER_LENGTH
721
722 def writePackedData(self, target):
723 values = [self.codeword,
724 self.magic,
725 self.image_id,
726 self.reserved_1,
727 self.reserved_2,
728 self.image_src,
729 self.image_dest_ptr,
730 self.image_size,
731 self.code_size,
732 self.sig_ptr,
733 self.sig_size,
734 self.cert_chain_ptr,
735 self.cert_chain_size,
736 self.oem_root_cert_sel,
737 self.oem_num_root_certs,
738 self.booting_image_config,
739 self.reserved_6,
740 self.reserved_7,
741 self.reserved_8,
742 self.reserved_9 ]
743
744 s = struct.Struct('I' * self.getLength())
745 packed_data = s.pack(*values)
746
747 fp = OPEN(target,'wb')
748 fp.write(packed_data)
749 fp.close()
750
751 return s.size
752
753 #----------------------------------------------------------------------------
754 # CLASS DEFINITIONS END
755 #----------------------------------------------------------------------------
756
757 #------------------------------------------------------------------------------
758 # Hooks for Scons
759 #------------------------------------------------------------------------------
760 def exists(env):
761 return env.Detect('mbn_tools')
762
763 def generate(env):
764
765 #----------------------------------------------------------------------------
766 # Generate Global Dictionary
767 #----------------------------------------------------------------------------
768 generate_global_dict(env)
769
770 #----------------------------------------------------------------------------
771 # Assign Build Configurable Values
772 #----------------------------------------------------------------------------
773 init_build_vars(env)
774
775 #----------------------------------------------------------------------------
776 # Add Methods to Environment
777 #----------------------------------------------------------------------------
778 env.AddMethod(filter_dictionary, "FilterDictionary")
779 env.AddMethod(image_auth, "ImageAuth")
780 env.AddMethod(image_header, "ImageHeader")
781 env.AddMethod(pboot_gen_elf, "PBootGenElf")
782 env.AddMethod(pboot_add_hash, "PBootAddHash")
783 env.AddMethod(modify_elf_flags, "ModifyElfFlags")
784 env.AddMethod(generate_code_hash, "GenerateCodeHash")
785 env.AddMethod(insert_SBL1_magicCookie, "InsertSBLMagicCookie")
786 env.AddMethod(modify_relocatable_flags, "ModifyRelocatableFlags")
787
788 #----------------------------------------------------------------------------
789 # Load Encryption Tools and Methods if required
790 #----------------------------------------------------------------------------
791 if 'USES_ENCRYPT_MBN' in env:
792 # Add Encryption Tools to environment
793 env.Tool('pil_encrypt', toolpath = ['${BUILD_ROOT}/core/securemsm/ssd/tools/pil_encrypt'])
794 env.AddMethod(get_ssd_se_fname, "GetSSDSideEffectFileName")
795 env.AddMethod(encrypt_elf_segments, "EncryptElfSegments")
796 env.AddMethod(generate_meta_data, "GenerateMetaData")
797 env.AddMethod(encrypt_mbn, "EncryptMBN")
798 return None
799
800 #----------------------------------------------------------------------------
801 # BOOT TOOLS BEGIN
802 #----------------------------------------------------------------------------
803
804 #----------------------------------------------------------------------------
805 # generate_meta_data
806 #----------------------------------------------------------------------------
807 def generate_meta_data(env, meta_out_file_name, add_magic_num = False):
808
809 '''
810 Make call to SSD API to return buffer filled with XML header information.
811 The XML header which we write contains information regarding the algorithms
812 being used along with specific key values which are to be used for encrpytion.
813 '''
814 xml_header = env.SSDGetMetaData(add_magic_num)
815
816 # Initialize
817 xml_target_file = open(meta_out_file_name,'wb')
818 xml_header_size = len(xml_header)
819
820 # Write XML buffer into target file
821 xml_target_file.write(xml_header)
822
823 # Pad if necessary to the maximum size
824 if xml_header_size <= XML_HEADER_MAXSIZE:
825 bytes_to_pad = XML_HEADER_MAXSIZE - xml_header_size
826 pad_file(xml_target_file, bytes_to_pad, PAD_BYTE_1)
827 xml_target_file.close()
828 else:
829 xml_target_file.close()
830 raise RuntimeError("XML Size too large: " + str(xml_header_size))
831
832 #----------------------------------------------------------------------------
833 # encrypt_mbn
834 #----------------------------------------------------------------------------
835 def encrypt_mbn(env, mbn_in_file_name, mbn_out_file_name):
836 # Open Files
837 mbn_in_fp = OPEN(mbn_in_file_name, "rb")
838 mbn_out_fp = OPEN(mbn_out_file_name, "wb+")
839
840 # encrypt the input file content and write to output file
841 mbn_file_size = os.path.getsize(mbn_in_file_name)
842 file_buff = mbn_in_fp.read(mbn_file_size)
843 encrypted_buf = env.SSDEncryptSegment(0, file_buff, mbn_file_size)
844 mbn_out_fp.write(encrypted_buf)
845
846 # Close Files
847 mbn_in_fp.close()
848 mbn_out_fp.close()
849
850 # Clean up encryption files
851 env.SSDDeInit()
852
853 #----------------------------------------------------------------------------
854 # get_ssd_se_fname
855 #----------------------------------------------------------------------------
856 def get_ssd_se_fname(env):
857 return env.SSDGetSideEffectFileName()
858
859 #----------------------------------------------------------------------------
860 # encrypt_elf_segments
861 #----------------------------------------------------------------------------
862 def encrypt_elf_segments(env, elf_in_file_name,
863 elf_out_file_name):
864
865 # Open Files
866 elf_in_fp = OPEN(elf_in_file_name, "rb")
867 elf_out_fp = OPEN(elf_out_file_name, "wb+")
868
869 # Initialize
870 [elf_header, phdr_table] = preprocess_elf_file(elf_in_file_name)
871 encrypted_seg_counter = 0
872
873 # Copy input file to output file
874 shutil.copyfileobj(elf_in_fp, elf_out_fp, os.path.getsize(elf_in_file_name))
875
876 # Begin ELF segment encryption
877 for i in range(elf_header.e_phnum):
878 curr_phdr = phdr_table[i]
879
880 # Only encrypt segments of LOAD_TYPE. Do not encrypt the hash segment.
881 if curr_phdr.p_type == LOAD_TYPE and \
882 MI_PBT_SEGMENT_TYPE_VALUE(curr_phdr.p_flags) != MI_PBT_HASH_SEGMENT:
883
884 # Read full segment into buffer
885 elf_in_fp.seek(curr_phdr.p_offset)
886 data_len = curr_phdr.p_filesz
887 file_buff = elf_in_fp.read(data_len)
888
889 # Call encryption routine on buffer
890 encrypted_buf = env.SSDEncryptSegment(encrypted_seg_counter, file_buff, data_len)
891 encrypted_seg_counter += 1
892
893 # Write encrypted segment into output file in same location
894 elf_out_fp.seek(curr_phdr.p_offset)
895 elf_out_fp.write(encrypted_buf)
896
897 # Close Files
898 elf_in_fp.close()
899 elf_out_fp.close()
900
901 # Clean up encryption files
902 env.SSDDeInit()
903
904 #----------------------------------------------------------------------------
905 # Converts integer to bytes. If length after conversion
906 # is smaller than given length of byte string, returned value is right-filled
907 # with 0x00 bytes. Use Little-endian byte order.
908 #----------------------------------------------------------------------------
909 def convert_int_to_byte_string(n, l):
910 return b''.join([chr((n >> ((l - i - 1) * 8)) % 256) for i in xrange(l)][::-1])
911
912 #----------------------------------------------------------------------------
913 # Create default elf header
914 #----------------------------------------------------------------------------
915 def create_elf_header( output_file_name,
916 image_dest,
917 image_size,
918 is_elf_64_bit = False):
919
920 if (output_file_name is None):
921 raise RuntimeError("Requires a ELF header file")
922
923 # Create a elf header and program header
924 # Write the headers to the output file
925 elf_fp = file(output_file_name, "wb")
926
927 if (is_elf_64_bit is True):
928 # ELf header
929 elf_fp.write(ELFINFO_MAG0)
930 elf_fp.write(ELFINFO_MAG1)
931 elf_fp.write(ELFINFO_MAG2)
932 elf_fp.write(ELFINFO_MAG3)
933 elf_fp.write(ELFINFO_CLASS_64)
934 elf_fp.write(ELFINFO_DATA2LSB)
935 elf_fp.write(ELFINFO_VERSION_CURRENT)
936 elf_fp.write(''.rjust(9, chr(ELFINFO_RESERVED)))
937 elf_fp.write(ELFINFO_EXEC_ETYPE)
938 elf_fp.write(ELFINFO_ARM_MACHINETYPE)
939 elf_fp.write(ELFINFO_VERSION_EV_CURRENT)
940 elf_fp.write(convert_int_to_byte_string(image_dest, 8))
941 elf_fp.write(convert_int_to_byte_string(ELF64_HDR_SIZE, 8))
942 elf_fp.write(convert_int_to_byte_string(ELFINFO_SHOFF, 8))
943 elf_fp.write(''.rjust(4, chr(ELFINFO_RESERVED)))
944 elf_fp.write(convert_int_to_byte_string(ELF64_HDR_SIZE, 2))
945 elf_fp.write(convert_int_to_byte_string(ELF64_PHDR_SIZE, 2))
946 elf_fp.write(ELFINFO_PHNUM)
947 elf_fp.write(''.rjust(6, chr(ELFINFO_RESERVED)))
948
949 # Program Header
950 elf_fp.write(convert_int_to_byte_string(LOAD_TYPE, 4))
951 elf_fp.write(convert_int_to_byte_string(MI_PBT_RWE_SEGMENT, 4))
952 elf_fp.write(convert_int_to_byte_string(ELF64_HDR_SIZE+ELF64_PHDR_SIZE, 8))
953 elf_fp.write(convert_int_to_byte_string(image_dest, 8))
954 elf_fp.write(convert_int_to_byte_string(image_dest, 8))
955 elf_fp.write(convert_int_to_byte_string(image_size, 8))
956 elf_fp.write(convert_int_to_byte_string(image_size, 8))
957 elf_fp.write(convert_int_to_byte_string(ELF_BLOCK_ALIGN, 8))
958 else:
959 # ELf header
960 elf_fp.write(ELFINFO_MAG0)
961 elf_fp.write(ELFINFO_MAG1)
962 elf_fp.write(ELFINFO_MAG2)
963 elf_fp.write(ELFINFO_MAG3)
964 elf_fp.write(ELFINFO_CLASS_32)
965 elf_fp.write(ELFINFO_DATA2LSB)
966 elf_fp.write(ELFINFO_VERSION_CURRENT)
967 elf_fp.write(''.rjust(9, chr(ELFINFO_RESERVED)))
968 elf_fp.write(ELFINFO_EXEC_ETYPE)
969 elf_fp.write(ELFINFO_ARM_MACHINETYPE)
970 elf_fp.write(ELFINFO_VERSION_EV_CURRENT)
971 elf_fp.write(convert_int_to_byte_string(image_dest, 4))
972 elf_fp.write(convert_int_to_byte_string(ELF32_HDR_SIZE, 4))
973 elf_fp.write(convert_int_to_byte_string(ELFINFO_SHOFF, 4))
974 elf_fp.write(''.rjust(4, chr(ELFINFO_RESERVED)))
975 elf_fp.write(convert_int_to_byte_string(ELF32_HDR_SIZE, 2))
976 elf_fp.write(convert_int_to_byte_string(ELF32_PHDR_SIZE, 2))
977 elf_fp.write(ELFINFO_PHNUM)
978 elf_fp.write(''.rjust(6, chr(ELFINFO_RESERVED)))
979
980 # Program Header
981 elf_fp.write(convert_int_to_byte_string(LOAD_TYPE, 4))
982 elf_fp.write(convert_int_to_byte_string(ELF32_HDR_SIZE+ELF32_PHDR_SIZE, 4))
983 elf_fp.write(convert_int_to_byte_string(image_dest, 4))
984 elf_fp.write(convert_int_to_byte_string(image_dest, 4))
985 elf_fp.write(convert_int_to_byte_string(image_size, 4))
986 elf_fp.write(convert_int_to_byte_string(image_size, 4))
987 elf_fp.write(convert_int_to_byte_string(MI_PBT_RWE_SEGMENT, 4))
988 elf_fp.write(convert_int_to_byte_string(ELF_BLOCK_ALIGN, 4))
989
990 elf_fp.close()
991 return 0
992
993 #----------------------------------------------------------------------------
994 # image_header
995 #----------------------------------------------------------------------------
996 def image_header(env, gen_dict,
997 code_file_name,
998 output_file_name,
999 secure_type,
1000 header_format = 'reg',
1001 requires_preamble = False,
1002 preamble_file_name = None,
1003 elf_file_name = None,
1004 write_full_hdr = False,
1005 in_code_size = None,
1006 cert_chain_size_in = CERT_CHAIN_ONEROOT_MAXSIZE,
1007 num_of_pages = None,
1008 header_version = None):
1009
1010 # Preliminary checks
1011 if (requires_preamble is True) and (preamble_file_name is None):
1012 raise RuntimeError("Image Header requires a preamble file")
1013
1014 if (gen_dict['IMAGE_KEY_MBN_TYPE'] == 'elf') and (elf_file_name is None):
1015 raise RuntimeError("ELF Image Headers require an elf file")
1016
1017 if (in_code_size is None) and (os.path.exists(code_file_name) is False):
1018 raise RuntimeError("Code size unavailable, and input file does not exist")
1019
1020 # Initialize
1021 if in_code_size is not None:
1022 code_size = in_code_size
1023 else:
1024 code_size = os.path.getsize(code_file_name)
1025
1026 image_dest = 0
1027 image_source = 0
1028
1029 # If secure build, set signature and cert chain sizes
1030 if secure_type == 'secure':
1031 signature_size = SHA256_SIGNATURE_SIZE
1032 cert_chain_size = cert_chain_size_in
1033 image_size = code_size + cert_chain_size + signature_size
1034 if (image_size % 4) != 0:
1035 image_size += (4 - (image_size % 4))
1036 else:
1037 signature_size = 0
1038 cert_chain_size = 0
1039 image_size = code_size
1040
1041 if header_version:
1042 assert header_version in [3, 5, 6, 7], 'Not a valid MBN header version'
1043
1044 # For ELF or hashed images, image destination will be determined from an ELF input file
1045 if gen_dict['IMAGE_KEY_MBN_TYPE'] == 'elf':
1046 image_dest = get_hash_address(elf_file_name) + (header_size(header_version))
1047 elif gen_dict['IMAGE_KEY_MBN_TYPE'] == 'bin':
1048 image_dest = gen_dict['IMAGE_KEY_IMAGE_DEST']
1049 image_source = gen_dict['IMAGE_KEY_IMAGE_SOURCE']
1050
1051 # Build the header based on format specified
1052 if header_format == 'sbl':
1053 boot_sbl_header = Sbl_Hdr(init_val = int('0xFFFFFFFF',16))
1054 boot_sbl_header.codeword = FLASH_CODE_WORD
1055 boot_sbl_header.magic = MAGIC_NUM
1056 boot_sbl_header.image_id = gen_dict['IMAGE_KEY_IMAGE_ID']
1057 boot_sbl_header.image_src = MI_BOOT_SBL_HDR_SIZE
1058 boot_sbl_header.image_dest_ptr = image_dest
1059 boot_sbl_header.image_size = image_size
1060 boot_sbl_header.code_size = code_size
1061 boot_sbl_header.sig_ptr = image_dest + code_size
1062 boot_sbl_header.sig_size = signature_size
1063 boot_sbl_header.cert_chain_ptr = image_dest + code_size + signature_size
1064 boot_sbl_header.cert_chain_size = cert_chain_size
1065 boot_sbl_header.oem_root_cert_sel = gen_dict['IMAGE_KEY_OEM_ROOT_CERT_SEL']
1066 boot_sbl_header.oem_num_root_certs = gen_dict['IMAGE_KEY_OEM_NUM_ROOT_CERTS']
1067 if 'USES_SBL_FOR_AARCH64' in env:
1068 boot_sbl_header.booting_image_config = SBL_AARCH64
1069 elif 'USES_SBL_FOR_AARCH632' in env:
1070 boot_sbl_header.booting_image_config = SBL_AARCH32
1071
1072 # If preamble is required, output the preamble file and update the boot_sbl_header
1073 if requires_preamble is True:
1074 boot_sbl_header = image_preamble(gen_dict, preamble_file_name, boot_sbl_header, num_of_pages)
1075
1076 # Package up the header and write to output file
1077 boot_sbl_header.writePackedData(target = output_file_name)
1078
1079 elif header_format == 'reg':
1080 boot_header = Boot_Hdr(init_val = int('0x0',16))
1081 boot_header.image_id = gen_dict['IMAGE_KEY_IMAGE_ID']
1082 boot_header.image_src = image_source
1083 boot_header.image_dest_ptr = image_dest
1084 boot_header.image_size = image_size
1085 boot_header.code_size = code_size
1086 boot_header.sig_ptr = image_dest + code_size
1087 boot_header.sig_size = signature_size
1088 boot_header.cert_chain_ptr = image_dest + code_size + signature_size
1089 boot_header.cert_chain_size = cert_chain_size
1090 boot_header.flash_parti_ver = header_version # version
1091
1092 if header_version >= 5:
1093 boot_header.image_src = 0 # sig_size_qc
1094 boot_header.image_dest_ptr = 0 # cert_chain_size_qc
1095
1096 if header_version >= 6:
1097 boot_header.metadata_size_qti = 0 # qti_metadata size
1098 boot_header.metadata_size = 0 # oem_metadata size
1099
1100 if header_version == 7:
1101 boot_header.software_id = 0x7B # Hardcoded to BOOTBLOCK SW ID
1102 boot_header.common_metadata_size = 24
1103 boot_header.metadata_size = 224
1104
1105
1106 # If preamble is required, output the preamble file and update the boot_header
1107 if requires_preamble is True:
1108 boot_header = image_preamble(gen_dict, preamble_file_name, boot_header, num_of_pages)
1109
1110 # Package up the header and write to output file
1111 boot_header.writePackedData(target = output_file_name, write_full_hdr = write_full_hdr)
1112
1113 else:
1114 raise RuntimeError("Header format not supported: " + str(header_format))
1115 return 0
1116
1117
1118 #----------------------------------------------------------------------------
1119 # pboot_gen_elf
1120 #----------------------------------------------------------------------------
1121 def pboot_gen_elf(env, elf_in_file_name,
1122 hash_out_file_name,
1123 elf_out_file_name,
1124 secure_type = 'non_secure',
1125 hash_seg_max_size = None,
1126 last_phys_addr = None,
1127 append_xml_hdr = False,
1128 is_sha256_algo = True,
1129 cert_chain_size_in = CERT_CHAIN_ONEROOT_MAXSIZE,
1130 header_version = None):
1131 sha_algo = 'SHA1'
1132 if is_sha256_algo:
1133 sha_algo = 'SHA256'
1134
1135 if header_version >= 6:
1136 sha_algo = 'SHA384'
1137 image_header_size = header_size(header_version)
1138
1139 if (sha_algo == 'SHA384'):
1140 mi_prog_boot_digest_size = 48
1141 elif sha_algo == 'SHA256':
1142 mi_prog_boot_digest_size = 32
1143 else:
1144 mi_prog_boot_digest_size = 20
1145
1146 # Open Files
1147 elf_in_fp = OPEN(elf_in_file_name, "rb")
1148 hash_out_fp = OPEN(hash_out_file_name, "wb+")
1149
1150 if elf_out_file_name is not None:
1151 elf_out_fp = OPEN(elf_out_file_name, "wb+")
1152
1153 # Initialize
1154 [elf_header, phdr_table] = preprocess_elf_file(elf_in_file_name)
1155 num_phdrs = elf_header.e_phnum
1156 phdr_total_size = num_phdrs * elf_header.e_phentsize
1157 phdr_size = elf_header.e_phentsize
1158 hashtable_size = 0
1159 hashtable_shift = 0
1160
1161 if elf_header.e_ident[ELFINFO_CLASS_INDEX] == ELFINFO_CLASS_64:
1162 new_phdr = Elf64_Phdr(b'\0' * ELF64_PHDR_SIZE)
1163 elf_header_size = ELF64_HDR_SIZE
1164 is_elf64 = True
1165 else:
1166 new_phdr = Elf32_Phdr(b'\0' * ELF32_PHDR_SIZE)
1167 elf_header_size = ELF32_HDR_SIZE
1168 is_elf64 = False
1169
1170 hash = b'\0' * mi_prog_boot_digest_size
1171 phdr_start = 0
1172 bytes_to_pad = 0
1173 hash_seg_end = 0
1174
1175 # Process program headers if an output elf is specified
1176 if elf_out_file_name is not None:
1177 # Assert limit on number of program headers in input ELF
1178 if num_phdrs > MAX_PHDR_COUNT:
1179 raise RuntimeError("Input ELF has exceeded maximum number of program headers")
1180
1181 # Create new program header for the ELF Header + Program Headers
1182 new_phdr.p_type = NULL_TYPE
1183 new_phdr.p_flags = MI_PBT_ELF_PHDR_SEGMENT
1184
1185 # If hash table program header is not found, make sure to include it
1186 elf_header.e_phnum += 2
1187
1188 # Create an empty hash entry for PHDR_TYPE
1189 hash_out_fp.write(b'\0' * mi_prog_boot_digest_size)
1190 hashtable_size += mi_prog_boot_digest_size
1191
1192 # Create an empty hash entry for the hash segment itself
1193 hash_out_fp.write(b'\0' * mi_prog_boot_digest_size)
1194 hashtable_size += mi_prog_boot_digest_size
1195
1196 # Begin hash table generation
1197 for i in range(num_phdrs):
1198 curr_phdr = phdr_table[i]
1199
1200 if (MI_PBT_PAGE_MODE_VALUE(curr_phdr.p_flags) == MI_PBT_PAGED_SEGMENT):
1201 seg_offset = curr_phdr.p_offset
1202 seg_size = curr_phdr.p_filesz
1203 hash_size = 0
1204
1205 # Check if the vaddr is page aligned
1206 off = curr_phdr.p_vaddr & (ELF_BLOCK_ALIGN - 1)
1207 if int(off) != 0:
1208 seg_size -= (ELF_BLOCK_ALIGN - off)
1209 seg_offset += (ELF_BLOCK_ALIGN - off)
1210
1211 # Seg_size should be page aligned
1212 if (seg_size & (ELF_BLOCK_ALIGN - 1)) > 0:
1213 raise RuntimeError("seg_size: " + hex(seg_size) + " is not ELF page aligned!")
1214
1215 off = seg_offset + seg_size
1216
1217 while seg_offset < off:
1218
1219 if seg_offset < ELF_BLOCK_ALIGN:
1220 hash_size = seg_offset
1221 else:
1222 hash_size = ELF_BLOCK_ALIGN
1223
1224 elf_in_fp.seek(seg_offset)
1225 fbuf = elf_in_fp.read(hash_size)
1226
1227 if MI_PBT_CHECK_FLAG_TYPE(curr_phdr.p_flags) is True:
1228 hash = generate_hash(fbuf, sha_algo)
1229 else:
1230 hash = b'\0' * mi_prog_boot_digest_size
1231
1232 # Write hash to file
1233 hash_out_fp.write(hash)
1234
1235 hashtable_size += mi_prog_boot_digest_size
1236 seg_offset += ELF_BLOCK_ALIGN
1237
1238 # Copy the hash entry for all that are PAGED segments and those that are not the PHDR type. This is for
1239 # backward tool compatibility where some images are generated using older exe tools.
1240 elif((MI_PBT_PAGE_MODE_VALUE(curr_phdr.p_flags) == MI_PBT_NON_PAGED_SEGMENT) and (curr_phdr.p_type is not PHDR_TYPE)):
1241 # Read full hash entry into buffer
1242 elf_in_fp.seek(curr_phdr.p_offset)
1243 data_len = curr_phdr.p_filesz
1244 file_buff = elf_in_fp.read(data_len)
1245
1246 if (MI_PBT_CHECK_FLAG_TYPE(curr_phdr.p_flags) is True) and (data_len > 0):
1247 hash = generate_hash(file_buff, sha_algo)
1248 else:
1249 hash = b'\0' * mi_prog_boot_digest_size
1250
1251 # Write hash to file
1252 hash_out_fp.write(hash)
1253
1254 hashtable_size += mi_prog_boot_digest_size
1255 # End hash table generation
1256
1257 # Generate the rest of the ELF output file if specified
1258 if elf_out_file_name is not None:
1259
1260 # Preempt hash table size if necessary
1261 if secure_type == 'secure':
1262 hashtable_size += (SHA256_SIGNATURE_SIZE + cert_chain_size_in)
1263
1264 if append_xml_hdr is True:
1265 hashtable_size += XML_HEADER_MAXSIZE
1266
1267 # Initialize the hash table program header
1268 [hash_Phdr, pad_hash_segment, hash_tbl_end_addr, hash_tbl_offset] = \
1269 initialize_hash_phdr(elf_in_file_name, hashtable_size, image_header_size, ELF_BLOCK_ALIGN, is_elf64)
1270
1271 # Check if hash segment max size parameter was passed
1272 if (hash_seg_max_size is not None):
1273 # Error checking for hash segment size validity
1274 if hashtable_size > hash_seg_max_size:
1275 raise RuntimeError("Hash table exceeds maximum hash segment size: " + hex(hash_seg_max_size))
1276 if (hash_seg_max_size & (ELF_BLOCK_ALIGN-1)) != 0:
1277 raise RuntimeError("Hash segment size passed is not ELF Block Aligned: " + hex(hash_seg_max_size))
1278
1279 # Check if hash physical address parameter was passed
1280 if last_phys_addr is not None:
1281 hash_Phdr.p_vaddr = last_phys_addr
1282 hash_Phdr.p_paddr = last_phys_addr
1283
1284 # Check if hash segment max size was passed
1285 if hash_seg_max_size is not None:
1286 hash_Phdr.p_memsz = hash_seg_max_size
1287
1288 # Determine the end of the hash segment, make sure it's block aligned
1289 bytes_to_pad = ELF_BLOCK_ALIGN - pad_hash_segment
1290 hash_seg_end = hash_tbl_end_addr + bytes_to_pad
1291
1292 # Check if a shifting is required to accommodate for the hash segment.
1293 # Get the minimum offset by going through the program headers.
1294 # Note that the program headers in the input file do not contain
1295 # the dummy program header for ELF + Program header, and the
1296 # program header for the hashtable.
1297 min_offset = phdr_table[0].p_offset
1298 for i in range(num_phdrs):
1299 curr_phdr = phdr_table[i]
1300 if curr_phdr.p_offset < min_offset:
1301 min_offset = curr_phdr.p_offset
1302
1303 if min_offset < hash_seg_end:
1304 hashtable_shift = hash_seg_end - min_offset
1305
1306 # Move program headers to after ELF header
1307 phdr_start = elf_header_size
1308
1309 # We copy over no section headers so assign these values to 0 in ELF Header
1310 elf_header.e_shnum = 0
1311 elf_header.e_shstrndx = 0
1312 elf_header.e_shoff = 0
1313
1314 # Output remaining ELF segments
1315 for i in range(num_phdrs):
1316
1317 # Increment the file offset before writing to the destination file
1318 curr_phdr = phdr_table[i]
1319
1320 # We do not copy over program headers of PHDR type, decrement the program
1321 # header count and continue the loop
1322 if curr_phdr.p_type is PHDR_TYPE:
1323 elf_header.e_phnum -= 1
1324 continue
1325
1326 src_offset = curr_phdr.p_offset
1327
1328 # Copy the ELF segment
1329 file_copy_offset(elf_in_fp, src_offset, elf_out_fp, curr_phdr.p_offset + hashtable_shift, curr_phdr.p_filesz)
1330
1331 # Output remaining program headers and ELF segments
1332 elf_header.e_phoff = phdr_start
1333
1334 # Output new program headers which we have generated
1335 elf_out_fp.seek(phdr_start)
1336 new_phdr.p_filesz = elf_header_size + (elf_header.e_phnum * phdr_size)
1337 elf_out_fp.write(new_phdr.getPackedData())
1338 elf_out_fp.write(hash_Phdr.getPackedData())
1339 phdr_start += (2 * phdr_size)
1340
1341 # Increment the file offset before writing to the destination file
1342 for i in range(num_phdrs):
1343 curr_phdr = phdr_table[i]
1344
1345 if curr_phdr.p_type is PHDR_TYPE:
1346 continue
1347
1348 curr_phdr.p_offset += hashtable_shift
1349
1350 # Copy the program header
1351 elf_out_fp.seek(phdr_start)
1352 elf_out_fp.write(curr_phdr.getPackedData())
1353
1354 # Update phdr_start
1355 phdr_start += phdr_size
1356
1357 # Finally, copy the new ELF header to the destination file
1358 elf_out_fp.seek(0)
1359 elf_out_fp.write(elf_header.getPackedData())
1360
1361 # Recalculate hash of ELF + program headers and output to hash output file
1362 elf_out_fp.seek(0)
1363 # Read the elf header
1364 elfhdr_buff = elf_out_fp.read(elf_header_size)
1365 # Seek to the program header offset listed in elf header.
1366 elf_out_fp.seek(elf_header.e_phoff)
1367 # Read the program header and compute hash
1368 proghdr_buff = elf_out_fp.read(elf_header.e_phnum * phdr_size)
1369
1370 hash = generate_hash(elfhdr_buff + proghdr_buff, sha_algo)
1371
1372 # Write hash to file as first hash table entry
1373 hash_out_fp.seek(0)
1374 hash_out_fp.write(hash)
1375
1376 # Close files
1377 elf_in_fp.close()
1378 hash_out_fp.close()
1379
1380 if elf_out_file_name is not None:
1381 elf_out_fp.close()
1382
1383 return 0
1384
1385
1386 #----------------------------------------------------------------------------
1387 # pboot_add_hash
1388 #----------------------------------------------------------------------------
1389 def pboot_add_hash(env, elf_in_file_name,
1390 hash_tbl_file_name,
1391 elf_out_file_name):
1392
1393 # Open files
1394 elf_in_fp = OPEN(elf_in_file_name, "rb")
1395 hash_tbl_fp = OPEN(hash_tbl_file_name, "rb")
1396 elf_out_fp = OPEN(elf_out_file_name, "wb+")
1397
1398 # Initialize
1399 [elf_header, phdr_table] = preprocess_elf_file(elf_in_file_name)
1400
1401 hash_size = os.path.getsize(hash_tbl_file_name)
1402 hash_segment_found = False
1403
1404 # Attempt to find the location of the hash program header
1405 for i in range(elf_header.e_phnum):
1406 curr_phdr = phdr_table[i]
1407 if curr_phdr.p_flags == MI_PBT_ELF_HASH_SEGMENT:
1408 hash_segment_found = True
1409 break
1410
1411 if hash_segment_found is True:
1412 # Copy input file to output file
1413 shutil.copyfileobj(elf_in_fp, elf_out_fp, os.path.getsize(elf_in_file_name))
1414
1415 # Update ELF to insert hash table at corresponding file offset
1416 hash_hdr_offset = curr_phdr.p_offset
1417 file_copy_offset(hash_tbl_fp, 0, elf_out_fp, hash_hdr_offset, hash_size)
1418
1419 else:
1420 raise RuntimeError("Hash segment program header not found in file " + elf_in_file_name)
1421
1422 # Close files
1423 elf_in_fp.close()
1424 hash_tbl_fp.close()
1425 elf_out_fp.close()
1426
1427 return 0
1428
1429 #----------------------------------------------------------------------------
1430 # image_auth
1431 #----------------------------------------------------------------------------
1432 def image_auth(env, *args):
1433
1434 if len(args) < 7 or len(args) > 8:
1435 raise RuntimeError("Usage Invalid")
1436
1437 # Initialize File Names
1438 binary_in = args[0]
1439 signature = args[1]
1440 attestation_cert = args[2]
1441 attestation_ca_cert = args[3]
1442 root_cert = args[4]
1443 cert_chain_out = args[5]
1444 signed_image_out = args[6]
1445 if len(args) == 8:
1446 cert_size_max_in = args[7]
1447 else:
1448 cert_size_max_in = CERT_CHAIN_ONEROOT_MAXSIZE
1449
1450 # Creating list of certificates to support creation of certificate chains
1451 # of lenth 1, 2, or 3 certificates
1452 cert_list = []
1453 num_certs = 0
1454 if (os.path.exists(attestation_cert)):
1455 cert_list.append(attestation_cert)
1456 num_certs = num_certs + 1
1457 if (os.path.exists(attestation_ca_cert)):
1458 cert_list.append(attestation_ca_cert)
1459 num_certs = num_certs + 1
1460 if (os.path.exists(root_cert)):
1461 cert_list.append(root_cert)
1462 num_certs = num_certs + 1
1463
1464 if (num_certs == 0):
1465 raise RuntimeError("Missing file(s) required for signing.\n")
1466
1467 # Create the Certificate Chain
1468 concat_files (cert_chain_out, cert_list)
1469
1470 # Pad to ensure Certificate Chain Size is CERT_CHAIN_MAX_SIZE
1471 cert_size = os.path.getsize(cert_chain_out)
1472
1473 if cert_size <= cert_size_max_in:
1474 bytes_to_pad = cert_size_max_in - cert_size
1475 cert_fp = OPEN(cert_chain_out,'ab')
1476 pad_file(cert_fp, bytes_to_pad, PAD_BYTE_1)
1477 cert_fp.close()
1478 else:
1479 raise RuntimeError("Certificate Size too large: " + str(cert_size))
1480
1481 # Create the Final Signed Image File
1482 concat_files (signed_image_out, [binary_in, signature, cert_chain_out])
1483
1484 return 0
1485
1486 #----------------------------------------------------------------------------
1487 # modify_relocatable_flags
1488 #----------------------------------------------------------------------------
1489 def modify_relocatable_flags(env, output_elf ):
1490
1491 # Offset into program header where the p_flags field is stored
1492 phdr_align_flag_offset = 28
1493 phdr_reloc_flag_offset = 24
1494
1495 # Initialize
1496 [elf_header, phdr_table] = preprocess_elf_file(output_elf)
1497
1498 if elf_header.e_ident[ELFINFO_CLASS_INDEX] == ELFINFO_CLASS_64:
1499 curr_phdr = Elf64_Phdr('\0' * ELF64_PHDR_SIZE)
1500 elf_header_size = ELF64_HDR_SIZE
1501 is_elf64 = True
1502 else:
1503 curr_phdr = Elf32_Phdr('\0' * ELF32_PHDR_SIZE)
1504 elf_header_size = ELF32_HDR_SIZE
1505 is_elf64 = False
1506
1507 # Open files
1508 elf_in_fp = OPEN(output_elf, "r+")
1509
1510 # Go to the start of the p_flag entry in the first program header
1511 file_offset_align_flag = elf_header.e_phoff + phdr_align_flag_offset
1512
1513 # Change the align field in the program header in the ELF file
1514 elf_in_fp.seek(file_offset_align_flag)
1515 curr_phdr = phdr_table[0]
1516
1517 #default alignment value is 1MB unless otherwise specified
1518 if 'USES_RELOC_ALIGN_VALUE_4MB' in env:
1519 alignment_value = ALIGNVALUE_4MB
1520 else:
1521 alignment_value = ALIGNVALUE_1MB
1522
1523
1524
1525 #create new alignment value
1526 new_align = (curr_phdr.p_align & 0) | alignment_value
1527
1528 # Create structure to package new flag field
1529 s = struct.Struct('I')
1530 new_flag_bytes = s.pack(new_align)
1531
1532 # Write the new flag value and incr ement offset
1533 elf_in_fp.write(new_flag_bytes)
1534
1535 # Go to the start of the p_flag entry in the first program header
1536 file_offset_reloc_flag = elf_header.e_phoff + phdr_reloc_flag_offset
1537
1538 # Change each program header flag in the ELF file with relocatable flag
1539 for i in range(elf_header.e_phnum):
1540 # Seek to correct location and create new p_flag value
1541 elf_in_fp.seek(file_offset_reloc_flag)
1542 curr_phdr = phdr_table[i]
1543 new_flag = (curr_phdr.p_flags & ~MI_PBT_FLAGS_MASK) | (MI_PBT_ELF_AMSS_RELOCATABLE_IMAGE)
1544
1545 # Create structure to package new flag field
1546 s = struct.Struct('I')
1547 new_flag_bytes = s.pack(new_flag)
1548
1549 # Write the new flag value and increment offset
1550 elf_in_fp.write(new_flag_bytes)
1551 file_offset_reloc_flag += elf_header.e_phentsize
1552
1553 # Close files
1554 elf_in_fp.close()
1555
1556
1557 return 0
1558
1559
1560 #----------------------------------------------------------------------------
1561 # modify_elf_flags
1562 #----------------------------------------------------------------------------
1563 def modify_elf_flags(env, elf_in_file_name,
1564 scl_file_name):
1565
1566 # Initialize
1567 [elf_header, phdr_table] = preprocess_elf_file(elf_in_file_name)
1568 segment_list = readSCL(scl_file_name, env['GLOBAL_DICT'])
1569
1570 if elf_header.e_ident[ELFINFO_CLASS_INDEX] == ELFINFO_CLASS_64:
1571 curr_phdr = Elf64_Phdr('\0' * ELF64_PHDR_SIZE)
1572 # Offset into program header where the p_flags field is stored
1573 phdr_flag_off = 4
1574 else:
1575 curr_phdr = Elf32_Phdr('\0' * ELF32_PHDR_SIZE)
1576 # Offset into program header where the p_flags field is stored
1577 phdr_flag_off = 24
1578
1579 # Open files
1580 elf_in_fp = OPEN(elf_in_file_name, "r+")
1581
1582 # Check for corresponding number of segments
1583 if len(segment_list) is not elf_header.e_phnum:
1584 raise RuntimeError('SCL file and ELF file have different number of segments!')
1585
1586 # Go to the start of the p_flag entry in the first program header
1587 file_offset = elf_header.e_phoff + phdr_flag_off
1588
1589 # Change each program header flag in the ELF file based off the SCL file
1590 for i in range(elf_header.e_phnum):
1591 # Seek to correct location and create new p_flag value
1592 elf_in_fp.seek(file_offset)
1593 curr_phdr = phdr_table[i]
1594 new_flag = (curr_phdr.p_flags & ~MI_PBT_FLAGS_MASK) | (segment_list[i].flag)
1595
1596 # Create structure to package new flag field
1597 s = struct.Struct('I')
1598 new_flag_bytes = s.pack(new_flag)
1599
1600 # Write the new flag value and increment offset
1601 elf_in_fp.write(new_flag_bytes)
1602 file_offset += elf_header.e_phentsize
1603
1604 # Close files
1605 elf_in_fp.close()
1606
1607 return 0
1608
1609 #----------------------------------------------------------------------------
1610 # generate_code_hash
1611 #----------------------------------------------------------------------------
1612 def generate_code_hash(env, elf_in_file_name):
1613
1614 # Initialize
1615 [elf_header, phdr_table] = preprocess_elf_file(elf_in_file_name)
1616
1617 if elf_header.e_ident[ELFINFO_CLASS_INDEX] == ELFINFO_CLASS_64:
1618 curr_phdr = Elf64_Phdr('\0' * ELF64_PHDR_SIZE)
1619 # Offset into program header where the p_flags field is stored
1620 phdr_flag_off = 4
1621 else:
1622 curr_phdr = Elf32_Phdr('\0' * ELF32_PHDR_SIZE)
1623 # Offset into program header where the p_flags field is stored
1624 phdr_flag_off = 24
1625
1626 # Open files
1627 elf_in_fp = OPEN(elf_in_file_name, "rb+")
1628
1629 # Go to the start of the p_flag entry in the first program header
1630 file_offset = elf_header.e_phoff + phdr_flag_off
1631
1632 # XXX Get these from env?
1633 DP_CODE_ALIGN = 0x100
1634 DP_PAGE_SIZE = 4096
1635 DP_HASH_SIZE = 32 # SHA-256
1636 DP_HASH_MAGIC = 0xC0DEDEC0
1637 PH_PERM_RW = 0x06
1638 PH_PERM_RX = 0x05
1639 PH_PERM_RO = 0x04
1640 PH_PERM_MASK = 0x07
1641
1642 page_size = DP_PAGE_SIZE
1643 hash_size = DP_HASH_SIZE
1644
1645 # First identify the hash segment. It is the first RW section.
1646 # Its Align should be 8, and its size a multiple of DP_HASH_SIZE;
1647
1648 hash_seg_idx = -1
1649 for i in range(elf_header.e_phnum):
1650 curr_phdr = phdr_table[i]
1651
1652 if (curr_phdr.p_align == 8 and
1653 (curr_phdr.p_flags & PH_PERM_MASK) == PH_PERM_RW and
1654 curr_phdr.p_filesz != 0 and (curr_phdr.p_filesz % DP_HASH_SIZE) == 0):
1655 hash_seg_idx = i
1656 # Validate the contents of the hash segment. It should be
1657 # filled with DP_HASH_MAGIC
1658 elf_in_fp.seek(curr_phdr.p_offset)
1659 hash_data = "";
1660 while (len(hash_data) < curr_phdr.p_filesz):
1661 hash_data = hash_data + elf_in_fp.read(curr_phdr.p_filesz - len(hash_data))
1662
1663 hash_data = struct.unpack("I" * (curr_phdr.p_filesz / 4), hash_data)
1664
1665 for v in hash_data[:]:
1666 if (v != DP_HASH_MAGIC):
1667 hash_seg_idx = -1
1668 break;
1669
1670 if (hash_seg_idx != -1):
1671 break
1672
1673 if (hash_seg_idx == -1):
1674 # return if there is no hash segment.
1675 return 0
1676
1677 hash_phdr = phdr_table[hash_seg_idx]
1678
1679 # Now find the code segment for the hashes. Look for matching number of pages
1680 code_seg_idx = -1
1681 code_seg_pages = hash_phdr.p_filesz / DP_HASH_SIZE
1682
1683 for i in range(elf_header.e_phnum):
1684 curr_phdr = phdr_table[i]
1685 curr_pages = (curr_phdr.p_filesz + DP_PAGE_SIZE - 1) / DP_PAGE_SIZE
1686
1687 if (curr_phdr.p_align == DP_CODE_ALIGN and
1688 (curr_phdr.p_flags & PH_PERM_MASK) == PH_PERM_RX and
1689 curr_pages == code_seg_pages):
1690 if (code_seg_idx != -1):
1691 raise RuntimeError('Multiple code segments match for: ' + code_seg_pages + ' pages')
1692 code_seg_idx = i
1693
1694 if (code_seg_idx == -1):
1695 raise RuntimeError('No matching code segment found')
1696
1697 code_phdr = phdr_table[code_seg_idx]
1698
1699 # Now hash the pages in the code segment
1700 hashes = []
1701 elf_in_fp.seek(code_phdr.p_offset)
1702 bytes_left = code_phdr.p_filesz;
1703 while (bytes_left > 0):
1704 bytes_in_page = min(bytes_left, DP_PAGE_SIZE)
1705 page = "";
1706 while (len(page) < bytes_in_page):
1707 page = page + elf_in_fp.read(bytes_in_page - len(page))
1708 if (len(page) < DP_PAGE_SIZE):
1709 page = page + (struct.pack('b', 0) * (DP_PAGE_SIZE - len(page)))
1710 hashes = hashes + [generate_hash(page, 'SHA256')]
1711 bytes_left -= bytes_in_page
1712
1713 # And write them to the hash segment
1714 elf_in_fp.seek(hash_phdr.p_offset)
1715
1716 for h in hashes[:]:
1717 elf_in_fp.write(h)
1718
1719 # Close files
1720 elf_in_fp.close()
1721
1722 return 0
1723
1724 #----------------------------------------------------------------------------
1725 # BOOT TOOLS END
1726 #----------------------------------------------------------------------------
1727
1728 #----------------------------------------------------------------------------
1729 # HELPER FUNCTIONS BEGIN
1730 #----------------------------------------------------------------------------
1731
1732 #----------------------------------------------------------------------------
1733 # Create a list to hold all segment information from an input SCL file
1734 #----------------------------------------------------------------------------
1735 def readSCL(filename, global_dict):
1736
1737 scl_fp = OPEN(filename,'r')
1738
1739 # Initialize
1740 file_data = scl_fp.readlines()
1741 num_lines = len(file_data)
1742 current_line = ''
1743 previous_line = ''
1744 strip_chars = '(){}[]'
1745 i = 0
1746 bracket_counter = 0
1747 seg_list = []
1748
1749 # Parse through all lines
1750 while i < num_lines:
1751
1752 # Save the last line read
1753 previous_line = current_line
1754 current_line = file_data[i]
1755
1756 # Look for the symbol '{' for the line to read.
1757 # Use bracket counter to skip nested '{ }'
1758 if ('{' in current_line):
1759 if bracket_counter == 0:
1760 # Create a new SegmentInfo class and set up tokens
1761 new_scl_entry = SegmentInfo()
1762 previous_line = previous_line.strip()
1763 tokens = previous_line.split(' ')
1764
1765 # Check that at least two tokens were parsed
1766 # Token 1: Segment Name
1767 # Token 2: Start Address -- not used in MBN tools
1768 if len(tokens) < 2:
1769 raise RuntimeError('SCL Segment Syntax malformed: ' + previous_line)
1770
1771 # Get the segment flags corresponding to the segment name description
1772 new_scl_entry.flag = getSegmentFlag(tokens[0].strip(strip_chars))
1773 seg_list.append(new_scl_entry)
1774
1775 bracket_counter += 1
1776 elif '}' in current_line:
1777 bracket_counter -= 1
1778
1779 i+=1
1780
1781 scl_fp.close()
1782 return seg_list
1783
1784 #----------------------------------------------------------------------------
1785 # Given a string parsed from a SCL file, returns the ELF segment flags
1786 #----------------------------------------------------------------------------
1787 def getSegmentFlag(seg_info):
1788
1789 ret_val = None
1790
1791 # Define string values for various types of segments
1792 RO = "RO"
1793 RW = "RW"
1794 ZI = "ZI"
1795 PAGEABLE = "PAGED"
1796 NOTPAGEABLE = "NOTPAGED"
1797 SWAPABLE = "SWAPPED"
1798 SWAP_POOL = "SWAP_POOL"
1799 RESERVED = "RESERVED"
1800 HASHTBL = "HASH"
1801 SHARED = "SHARED"
1802 NOTUSED = "NOTUSED"
1803 BOOT_SEGMENT = "BOOT_SEGMENT"
1804 CODE = "CODE"
1805 L4BSP = "L4BSP"
1806 POOL_INDEX_0 = "INDEX_0"
1807 POOL_INDEX_1 = "INDEX_1"
1808
1809 # New definitions for EOS demand paging
1810 NONPAGE = "NONPAGE"
1811 PAGEUNLOCKED = "PAGEUNLOCKED"
1812 PAGELOCKED = "PAGELOCKED"
1813 UNSECURE = "UNSECURE"
1814
1815 if seg_info is None or len(seg_info) == 0:
1816 raise RuntimeError('Invalid segment information passed: ' + seg_info)
1817
1818 # Conditional checks and assignments of the corresponding segment flag values
1819 if NOTPAGEABLE in seg_info:
1820 if RO in seg_info:
1821 ret_val = MI_PBT_ELF_AMSS_NON_PAGED_RO_SEGMENT
1822 elif CODE in seg_info:
1823 ret_val = MI_PBT_ELF_AMSS_NON_PAGED_RO_SEGMENT
1824 elif ZI in seg_info:
1825 if SWAP_POOL in seg_info:
1826 if POOL_INDEX_0 in seg_info:
1827 ret_val = MI_PBT_ELF_SWAP_POOL_NON_PAGED_ZI_SEGMENT_INDEX0
1828 else:
1829 ret_val = MI_PBT_ELF_SWAP_POOL_NON_PAGED_ZI_SEGMENT_INDEX1
1830 else:
1831 ret_val = MI_PBT_ELF_AMSS_NON_PAGED_ZI_SEGMENT
1832
1833 elif NOTUSED in seg_info:
1834 ret_val = MI_PBT_ELF_AMSS_NON_PAGED_NOTUSED_SEGMENT
1835
1836 elif SHARED in seg_info:
1837 ret_val = MI_PBT_ELF_AMSS_NON_PAGED_SHARED_SEGMENT
1838 elif HASHTBL in seg_info:
1839 ret_val = MI_PBT_ELF_HASH_SEGMENT
1840 elif BOOT_SEGMENT in seg_info:
1841 ret_val = MI_PBT_ELF_BOOT_SEGMENT
1842 elif L4BSP in seg_info:
1843 ret_val = MI_PBT_ELF_NON_PAGED_L4BSP_SEGMENT
1844 else:
1845 ret_val = MI_PBT_ELF_AMSS_NON_PAGED_RW_SEGMENT
1846
1847 elif PAGEABLE in seg_info:
1848 if RO in seg_info or CODE in seg_info:
1849 if SWAPABLE in seg_info:
1850 if POOL_INDEX_0 in seg_info:
1851 ret_val = MI_PBT_ELF_SWAPPED_PAGED_RO_SEGMENT_INDEX0
1852 else:
1853 ret_val = MI_PBT_ELF_SWAPPED_PAGED_RO_SEGMENT_INDEX1
1854 else:
1855 ret_val = MI_PBT_ELF_AMSS_PAGED_RO_SEGMENT
1856 elif ZI in seg_info:
1857 ret_val = MI_PBT_ELF_AMSS_PAGED_ZI_SEGMENT
1858
1859 elif NOTUSED in seg_info:
1860 ret_val = MI_PBT_ELF_AMSS_PAGED_NOTUSED_SEGMENT
1861 elif SHARED in seg_info:
1862 ret_val = MI_PBT_ELF_AMSS_PAGED_SHARED_SEGMENT
1863 elif L4BSP in seg_info:
1864 ret_val = MI_PBT_ELF_PAGED_L4BSP_SEGMENT
1865 else:
1866 ret_val = MI_PBT_ELF_AMSS_PAGED_RW_SEGMENT
1867
1868 elif PAGELOCKED in seg_info:
1869 ret_val = MI_PBT_ELF_PAGED_LOCKED_SEGMENT
1870 elif PAGEUNLOCKED in seg_info:
1871 ret_val = MI_PBT_ELF_PAGED_UNLOCKED_SEGMENT
1872 elif NONPAGE in seg_info:
1873 ret_val = MI_PBT_ELF_RESIDENT_SEGMENT
1874 elif UNSECURE in seg_info:
1875 ret_val = MI_PBT_ELF_UNSECURE_SEGMENT
1876
1877 else:
1878 raise RuntimeError('The segment name is wrongly defined in the SCL file: ' + seg_info)
1879
1880 return ret_val
1881
1882 #----------------------------------------------------------------------------
1883 # Pad a file with specific number of bytes
1884 # Note: Assumes the fp is seeked to the correct location of padding
1885 #----------------------------------------------------------------------------
1886 def pad_file(fp, num_bytes, value):
1887
1888 if num_bytes < 0:
1889 raise RuntimeError("Number of bytes to pad must be greater than zero")
1890
1891 while num_bytes > 0:
1892 fp.write('%c' % value)
1893 num_bytes -= 1
1894
1895 return
1896
1897 #----------------------------------------------------------------------------
1898 # Concatenates the files listed in 'sources' in order and writes to 'target'
1899 #----------------------------------------------------------------------------
1900 def concat_files (target, sources):
1901 if type(sources) is not list:
1902 sources = [sources]
1903
1904 target_file = OPEN(target,'wb')
1905
1906 for fname in sources:
1907 file = OPEN(fname,'rb')
1908 while True:
1909 bin_data = file.read(65536)
1910 if not bin_data:
1911 break
1912 target_file.write(bin_data)
1913 file.close()
1914 target_file.close()
1915
1916 #----------------------------------------------------------------------------
1917 # Parse build configurable values and assign to global variables for tools
1918 #----------------------------------------------------------------------------
1919 def init_build_vars(env):
1920
1921 # Maximum size of Certificate Chain used in Secure Boot
1922 global CERT_CHAIN_ONEROOT_MAXSIZE
1923 CERT_CHAIN_ONEROOT_MAXSIZE = get_dict_value(env['GLOBAL_DICT'], 'CERT_CHAIN_MAXSIZE', (6*1024))
1924
1925 # Maximum size of the XML Header used in encrypted ELF images
1926 global XML_HEADER_MAXSIZE
1927 XML_HEADER_MAXSIZE = get_dict_value(env['GLOBAL_DICT'], 'XML_HEADER_MAXSIZE', (2*1024))
1928
1929 #----------------------------------------------------------------------------
1930 # Generates the global dictionary and add to the environment
1931 #----------------------------------------------------------------------------
1932 def generate_global_dict(env):
1933
1934 # Get file names for 'cust' and 'targ' auto-generated files inside 'build/ms'
1935 cust_h = env.subst('CUST${BUILD_ID}.H').lower()
1936 targ_h = env.subst('TARG${BUILD_ID}.H').lower()
1937 cust_file_name = str(env.FindFile(cust_h, "${INC_ROOT}/build/ms"))
1938 targ_file_name = str(env.FindFile(targ_h, "${INC_ROOT}/build/ms"))
1939
1940 # Check that files are present
1941 if (os.path.exists(cust_file_name) is True) and \
1942 (os.path.exists(targ_file_name) is True):
1943
1944 # Populate the dictionary from the auto-generated files
1945 global_dict = populate_dictionary(targ_file_name, cust_file_name)
1946 else:
1947 global_dict = {}
1948
1949 # Add the dictionary to the environment
1950 env.Replace(GLOBAL_DICT = global_dict)
1951
1952 #----------------------------------------------------------------------------
1953 # Populate the dictionary from a list of input files
1954 #----------------------------------------------------------------------------
1955 def populate_dictionary(*args):
1956
1957 if len(args) < 1:
1958 raise RuntimeError("At least 1 file must be specified as an input")
1959
1960 global_dict = {}
1961 Fields = ["Define", "Key", "Value"]
1962
1963 # For each input file
1964 for i in range(len(args)):
1965
1966 template_file_path = args[i]
1967 instream = OPEN(template_file_path, 'r')
1968 # Tokenize each line with a white space
1969 values = csv.DictReader(instream, Fields, delimiter=" ")
1970
1971 for values in itertools.izip(values):
1972 new_entry = values[0]
1973 # Verify the parsed tokens
1974 if (new_entry['Define'] == '#define') and \
1975 (new_entry['Key'] != None) and \
1976 (new_entry['Value'] != None):
1977
1978 new_key = new_entry['Key'].strip()
1979 new_value = new_entry['Value'].strip()
1980
1981 # If value pair is empty string, assume feature definition is true
1982 if new_value == '':
1983 new_value = 'yes'
1984
1985 # Check for and handle text replacements as we parse
1986 if global_dict is not None and len(global_dict.keys()) > 0:
1987 for key in global_dict:
1988 new_value = new_value.replace(key, str(global_dict.get(key)))
1989
1990 # Attempt to evaluate value
1991 try:
1992 new_value = eval(new_value)
1993 # Catch exceptions and do not evaluate
1994 except:
1995 pass
1996
1997 # Add to global dictionary
1998 global_dict[new_key] = new_value
1999 instream.close()
2000
2001 return global_dict
2002
2003 #----------------------------------------------------------------------------
2004 # Filter out a generic dictionary from the global dictionary
2005 #----------------------------------------------------------------------------
2006 def filter_dictionary(env, global_dict, **kwargs):
2007
2008 # Check for Image Type
2009 # If IMAGE_TYPE parameter is not provided, raise error
2010 if not kwargs.has_key('IMAGE_TYPE'):
2011 raise RuntimeError("IMAGE_TYPE must be defined to use FilterDictionary.")
2012 else:
2013 image_type = kwargs.get('IMAGE_TYPE')
2014 if type(image_type) is not str:
2015 raise RuntimeError("IMAGE_TYPE must be of string type.")
2016
2017 # Check for Flash Type
2018 # If FLASH_TYPE parameter is not provided, default to 'nand'
2019 if not kwargs.has_key('FLASH_TYPE'):
2020 flash_type = 'nand'
2021 else:
2022 flash_type = kwargs.get('FLASH_TYPE')
2023 if type(flash_type) is not str:
2024 raise RuntimeError("FLASH_TYPE must be of string type. ")
2025
2026 # Check for MBN Type
2027 # If MBN_TYPE parameter is not provided, default to 'elf'
2028 if not kwargs.has_key('MBN_TYPE'):
2029 mbn_type = 'elf'
2030 else:
2031 mbn_type = kwargs.get('MBN_TYPE')
2032 if mbn_type != 'elf' and mbn_type != 'bin':
2033 raise RuntimeError("MBN_TYPE currently not supported: " + mbn_type)
2034
2035 # Check for Image ID
2036 # If IMAGE_ID parameter is not provided, default to ID 0
2037 if not kwargs.has_key('IMAGE_ID'):
2038 image_id = ImageType.NONE_IMG
2039 else:
2040 image_id = kwargs.get('IMAGE_ID')
2041 if type(image_id) is not int:
2042 raise RuntimeError("IMAGE_ID must be of integer type.")
2043
2044 # Initialize
2045 gen_dict = {}
2046 image_dest = 0
2047 image_source = 0
2048
2049 # Check for image_type
2050 if image_type not in image_id_table:
2051 id = image_id
2052 id_match_str = image_type.upper() + "_IMG"
2053 id_mbn_type = mbn_type
2054 else:
2055 id = image_id_table[image_type][0]
2056 id_match_str = image_id_table[image_type][1]
2057 id_mbn_type = image_id_table[image_type][2]
2058
2059 # Handle MBN Type and assign image destination address
2060 if id_mbn_type == 'elf':
2061 pass
2062 elif id_mbn_type == 'bin':
2063 template_key_match = 'IMAGE_KEY_' + id_match_str + "_DEST_ADDR"
2064 if template_key_match in global_dict:
2065 image_dest = global_dict[template_key_match]
2066 else:
2067 raise RuntimeError("Builds file does not have IMAGE_KEY pair for: " + image_type)
2068 else:
2069 raise RuntimeError("MBN_TYPE currently not supported: " + mbn_type)
2070
2071 # Assign generic dictionary key/value pairs
2072 gen_dict['IMAGE_KEY_IMAGE_ID'] = id
2073 gen_dict['IMAGE_KEY_IMAGE_DEST'] = image_dest
2074 gen_dict['IMAGE_KEY_IMAGE_SOURCE'] = image_source
2075 gen_dict['IMAGE_KEY_FLASH_TYPE'] = flash_type
2076 gen_dict['IMAGE_KEY_MBN_TYPE'] = id_mbn_type
2077 gen_dict['IMAGE_KEY_ID_MATCH_STR'] = id_match_str
2078 gen_dict['IMAGE_KEY_FLASH_AUTO_DETECT_MAX_PAGE'] = \
2079 get_dict_value(global_dict,'FLASH_AUTO_DETECT_MAX_PAGE', 8192)
2080 gen_dict['IMAGE_KEY_FLASH_AUTO_DETECT_MIN_PAGE'] = \
2081 get_dict_value(global_dict,'FLASH_AUTO_DETECT_MIN_PAGE', 2048)
2082 gen_dict['IMAGE_KEY_MAX_SIZE_OF_VERIFY_BUFFER'] = \
2083 get_dict_value(global_dict,'MAX_SIZE_OF_VERIFY_BUFFER', 8192)
2084 gen_dict['IMAGE_KEY_BOOT_SMALL_PREAMBLE'] = \
2085 get_dict_value(global_dict,'BOOT_SMALL_PREAMBLE', 1)
2086
2087 # Get OEM root certificate select and number
2088 oem_root_cert_sel = get_dict_value(global_dict,'OEM_ROOT_CERT_SEL', 1)
2089 oem_num_root_certs = get_dict_value(global_dict,'OEM_NUM_ROOT_CERTS', 1)
2090
2091 # Error checking for OEM configurable values
2092 if oem_root_cert_sel in range(1, MAX_NUM_ROOT_CERTS + 1) and \
2093 oem_num_root_certs in range(1, MAX_NUM_ROOT_CERTS + 1) and \
2094 oem_root_cert_sel <= oem_num_root_certs:
2095
2096 gen_dict['IMAGE_KEY_OEM_ROOT_CERT_SEL'] = oem_root_cert_sel
2097 gen_dict['IMAGE_KEY_OEM_NUM_ROOT_CERTS'] = oem_num_root_certs
2098
2099 else:
2100 raise RuntimeError("Invalid OEM root certificate configuration values")
2101
2102 # Assign additional dictionary key/values pair as needed by tools.
2103
2104 return gen_dict
2105
2106
2107 #----------------------------------------------------------------------------
2108 # Get index value from dictionary if exists, otherwise return default
2109 #----------------------------------------------------------------------------
2110 def get_dict_value(dict, key_string, default):
2111
2112 key = 'IMAGE_KEY_' + key_string
2113
2114 if key in dict:
2115 return dict[key]
2116 else:
2117 return default
2118
2119 #----------------------------------------------------------------------------
2120 # Preprocess an ELF file and return the ELF Header Object and an
2121 # array of ELF Program Header Objects
2122 #----------------------------------------------------------------------------
2123 def preprocess_elf_file(elf_file_name):
2124
2125 # Initialize
2126 elf_fp = OPEN(elf_file_name, 'rb')
2127 elf_header = Elf_Ehdr_common(elf_fp.read(ELF_HDR_COMMON_SIZE))
2128
2129 if verify_elf_header(elf_header) is False:
2130 raise RuntimeError("ELF file failed verification: " + elf_file_name)
2131
2132 elf_fp.seek(0)
2133
2134 if elf_header.e_ident[ELFINFO_CLASS_INDEX] == ELFINFO_CLASS_64:
2135 elf_header = Elf64_Ehdr(elf_fp.read(ELF64_HDR_SIZE))
2136 else:
2137 elf_header = Elf32_Ehdr(elf_fp.read(ELF32_HDR_SIZE))
2138
2139 phdr_table = []
2140
2141 # Verify ELF header information
2142 if verify_elf_header(elf_header) is False:
2143 raise RuntimeError("ELF file failed verification: " + elf_file_name)
2144
2145 # Get program header size
2146 phdr_size = elf_header.e_phentsize
2147
2148 # Find the program header offset
2149 file_offset = elf_header.e_phoff
2150 elf_fp.seek(file_offset)
2151
2152 # Read in the program headers
2153 for i in range(elf_header.e_phnum):
2154 if elf_header.e_ident[ELFINFO_CLASS_INDEX] == ELFINFO_CLASS_64:
2155 phdr_table.append(Elf64_Phdr(elf_fp.read(phdr_size)))
2156 else:
2157 phdr_table.append(Elf32_Phdr(elf_fp.read(phdr_size)))
2158
2159 elf_fp.close()
2160 return [elf_header, phdr_table]
2161
2162 #----------------------------------------------------------------------------
2163 # Get the hash table address from an input ELF file
2164 #----------------------------------------------------------------------------
2165 def get_hash_address(elf_file_name):
2166
2167 [elf_header, phdr_table] = preprocess_elf_file(elf_file_name)
2168
2169 last_paddr = 0
2170 last_paddr_segment = 0
2171
2172 # Find the segment with the largest physical address.
2173 # Hash segment's physical address will be immediately after this segment.
2174 for i in range(elf_header.e_phnum):
2175 curr_phdr = phdr_table[i]
2176 if curr_phdr.p_paddr > last_paddr:
2177 # Skip the demand paging segment as it would be outside the physical RAM location
2178 if MI_PBT_SEGMENT_TYPE_VALUE(curr_phdr.p_flags) != MI_PBT_XBL_SEC_SEGMENT:
2179 last_paddr = curr_phdr.p_paddr;
2180 last_paddr_segment = i;
2181
2182 max_phdr = phdr_table[last_paddr_segment]
2183
2184 ret_val = (((max_phdr.p_paddr + max_phdr.p_memsz - 1) & \
2185 ~(ELF_BLOCK_ALIGN-1)) + ELF_BLOCK_ALIGN)
2186
2187 return ret_val
2188
2189 #----------------------------------------------------------------------------
2190 # Verify ELF header contents from an input ELF file
2191 #----------------------------------------------------------------------------
2192 def verify_elf_header(elf_header):
2193 if (elf_header.e_ident[ELFINFO_MAG0_INDEX] != ELFINFO_MAG0):
2194 print("MAG0[{:d}]\n".format((elf_header.e_ident[ELFINFO_MAG0_INDEX])))
2195 return False
2196 if (elf_header.e_ident[ELFINFO_MAG1_INDEX] != ELFINFO_MAG1):
2197 print("MAG1[{:d}]\n".format((elf_header.e_ident[ELFINFO_MAG1_INDEX])))
2198 return False
2199 if (elf_header.e_ident[ELFINFO_MAG2_INDEX] != ELFINFO_MAG2):
2200 print("MAG2[{:d}]\n".format((elf_header.e_ident[ELFINFO_MAG2_INDEX])))
2201 return False
2202 if (elf_header.e_ident[ELFINFO_MAG3_INDEX] != ELFINFO_MAG3):
2203 print("MAG3[{:d}]\n".format((elf_header.e_ident[ELFINFO_MAG3_INDEX])))
2204 return False
2205 if ((elf_header.e_ident[ELFINFO_CLASS_INDEX] != ELFINFO_CLASS_64) and \
2206 (elf_header.e_ident[ELFINFO_CLASS_INDEX] != ELFINFO_CLASS_32)):
2207 print("ELFINFO_CLASS_INDEX[{:d}]\n".format((elf_header.e_ident[ELFINFO_CLASS_INDEX])))
2208 return False
2209 if (elf_header.e_ident[ELFINFO_VERSION_INDEX] != ELFINFO_VERSION_CURRENT):
2210 print("ELFINFO_VERSION_INDEX[{:d}]\n".format((elf_header.e_ident[ELFINFO_VERSION_INDEX])))
2211 return False
2212 return True
2213
2214 #----------------------------------------------------------------------------
2215 # Perform file copy given offsets and the number of bytes to copy
2216 #----------------------------------------------------------------------------
2217 def file_copy_offset(in_fp, in_off, out_fp, out_off, num_bytes):
2218 in_fp.seek(in_off)
2219 read_in = in_fp.read(num_bytes)
2220 out_fp.seek(out_off)
2221 out_fp.write(read_in)
2222
2223 return num_bytes
2224
2225 #----------------------------------------------------------------------------
2226 # Return header_size based on version
2227 #----------------------------------------------------------------------------
2228 def header_size(header_version):
2229 if header_version == 6:
2230 return 48
2231 elif header_version == 7:
2232 return 288
2233 else:
2234 return 40
2235
2236 #----------------------------------------------------------------------------
2237 # sha1/sha256 hash routine wrapper
2238 #----------------------------------------------------------------------------
2239 def generate_hash(in_buf, sha_algo):
2240 # Initialize a SHA1 object from the Python hash library
2241 if sha_algo == 'SHA384':
2242 m = hashlib.sha384()
2243 elif sha_algo == 'SHA256':
2244 m = hashlib.sha256()
2245 else:
2246 m = hashlib.sha1()
2247
2248 # Set the input buffer and return the output digest
2249 m.update(in_buf)
2250 return m.digest()
2251
2252 #----------------------------------------------------------------------------
2253 # Initialize the hash program header.
2254 #----------------------------------------------------------------------------
2255 def initialize_hash_phdr(elf_in_file_name, hash_tbl_size, hdr_size, hdr_offset, is_elf64):
2256 # Set hash header offset to page size boundary. Hash table will be
2257 # located at first segment of elf image.
2258 hash_hdr_size = hdr_size
2259 hash_hdr_offset = hdr_offset
2260 hash_tbl_offset = hash_hdr_offset + hash_hdr_size
2261 hash_tbl_end_addr = hash_tbl_offset + hash_tbl_size;
2262 pad_hash_segment = (hash_tbl_end_addr) & (ELF_BLOCK_ALIGN-1)
2263
2264 # Update the hash table program header
2265 if is_elf64 is True:
2266 hash_Phdr = Elf64_Phdr(b'\0'*ELF64_PHDR_SIZE)
2267 else:
2268 hash_Phdr = Elf32_Phdr(b'\0'*ELF32_PHDR_SIZE)
2269 hash_Phdr.p_flags = MI_PBT_ELF_HASH_SEGMENT
2270 hash_Phdr.p_align = ELF_BLOCK_ALIGN
2271 hash_Phdr.p_offset = hash_hdr_offset
2272 hash_Phdr.p_memsz = hash_hdr_size + hash_tbl_size + (ELF_BLOCK_ALIGN - pad_hash_segment)
2273 hash_Phdr.p_filesz = hash_hdr_size + hash_tbl_size
2274 hash_Phdr.p_type = NULL_TYPE
2275 hash_Phdr.p_vaddr = get_hash_address(elf_in_file_name)
2276 hash_Phdr.p_paddr = hash_Phdr.p_vaddr
2277
2278 return [hash_Phdr, pad_hash_segment, hash_tbl_end_addr, hash_tbl_offset]
2279
2280 #----------------------------------------------------------------------------
2281 # image_preamble
2282 #----------------------------------------------------------------------------
2283 def image_preamble(gen_dict, preamble_file_name, boot_sbl_header, num_of_pages=None):
2284 # Generate the preamble file
2285 preamble_fp = OPEN(preamble_file_name, 'wb')
2286
2287 # Initialize
2288 max_size_verify = gen_dict['IMAGE_KEY_MAX_SIZE_OF_VERIFY_BUFFER']
2289 flash_max_page = gen_dict['IMAGE_KEY_FLASH_AUTO_DETECT_MAX_PAGE']
2290 flash_min_page = gen_dict['IMAGE_KEY_FLASH_AUTO_DETECT_MIN_PAGE']
2291 autodetectpage = [int('0xFFFFFFFF',16)] * max_size_verify
2292
2293 # The first three entries in the preamble must include the following values
2294 autodetectpage[0] = FLASH_CODE_WORD
2295 autodetectpage[1] = MAGIC_NUM
2296 if (num_of_pages == 64):
2297 autodetectpage[2] = AUTODETECT_PAGE_SIZE_MAGIC_NUM64
2298 elif (num_of_pages == 128):
2299 autodetectpage[2] = AUTODETECT_PAGE_SIZE_MAGIC_NUM128
2300 else:
2301 autodetectpage[2] = AUTODETECT_PAGE_SIZE_MAGIC_NUM
2302
2303 # Package the list into binary data to be written to the preamble
2304 s = struct.Struct('I' * max_size_verify)
2305 packed_data = s.pack(*autodetectpage)
2306
2307 # Output preamble pages based on maximum/minimum page size support
2308 for i in range(flash_max_page/flash_min_page):
2309 preamble_fp.write(packed_data[:flash_min_page])
2310
2311 # Determine appropriate amount of padding for the preamble and
2312 # update the boot_sbl_header accordingly
2313 if gen_dict['IMAGE_KEY_BOOT_SMALL_PREAMBLE'] == 1:
2314 boot_sbl_header.image_src += (flash_max_page + flash_min_page)
2315 amount_to_write = flash_min_page
2316 else:
2317 boot_sbl_header.image_src += flash_max_page * 2
2318 amount_to_write = flash_max_page
2319
2320 pad_file(preamble_fp, amount_to_write, PAD_BYTE_1)
2321 preamble_fp.close()
2322
2323 return boot_sbl_header
2324
2325 #----------------------------------------------------------------------------
2326 # Helper functions to parse ELF program headers
2327 #----------------------------------------------------------------------------
2328 def MI_PBT_SEGMENT_TYPE_VALUE(x):
2329 return ( ((x) & MI_PBT_FLAG_SEGMENT_TYPE_MASK) >> MI_PBT_FLAG_SEGMENT_TYPE_SHIFT )
2330
2331 def MI_PBT_PAGE_MODE_VALUE(x):
2332 return ( ((x) & MI_PBT_FLAG_PAGE_MODE_MASK) >> MI_PBT_FLAG_PAGE_MODE_SHIFT )
2333
2334 def MI_PBT_ACCESS_TYPE_VALUE(x):
2335 return ( ((x) & MI_PBT_FLAG_ACCESS_TYPE_MASK) >> MI_PBT_FLAG_ACCESS_TYPE_SHIFT )
2336
2337 def MI_PBT_CHECK_FLAG_TYPE(x):
2338 return (MI_PBT_SEGMENT_TYPE_VALUE(x) != MI_PBT_HASH_SEGMENT) and \
2339 (MI_PBT_ACCESS_TYPE_VALUE(x) != MI_PBT_NOTUSED_SEGMENT) and \
2340 (MI_PBT_ACCESS_TYPE_VALUE(x) != MI_PBT_SHARED_SEGMENT)
2341
2342
2343 #----------------------------------------------------------------------------
2344 # Helper functions to open a file and return a valid file object
2345 #----------------------------------------------------------------------------
2346 def OPEN(file_name, mode):
2347 try:
2348 fp = open(file_name, mode)
2349 except IOError:
2350 raise RuntimeError("The file could not be opened: " + file_name)
2351
2352 # File open has succeeded with the given mode, return the file object
2353 return fp
2354
2355 #----------------------------------------------------------------------------
2356 # Helper functions to insert MCs in SBL1(Badger) if ENABLE_VIRTUAL_BLK is ON
2357 #----------------------------------------------------------------------------
2358 def insert_SBL1_magicCookie (env, target):
2359 file = open(target, "rb")
2360 #read the file contents
2361 filedata = file.read()
2362 length = len(filedata)
2363 file.close()
2364
2365 if (length <= VIRTUAL_BLOCK_SIZE):
2366 return None
2367 else:
2368 #remove the previous file
2369 os.remove(target)
2370 #generate new file for appending target data + required MCs
2371 file = open(target, "ab")
2372
2373 while length > VIRTUAL_BLOCK_SIZE:
2374 filedata_till_128kb = filedata[0:VIRTUAL_BLOCK_SIZE]
2375 filedata_after_128kb = filedata[VIRTUAL_BLOCK_SIZE:length]
2376
2377 a = str(hex(FLASH_CODE_WORD))
2378 mc1 = chr(int(a[8:10],16)) + chr(int(a[6:8],16)) + chr(int(a[4:6],16)) + chr(int(a[2:4],16))
2379
2380 b = str(hex(MAGIC_NUM))
2381 mc2 = chr(int(b[8:10],16)) + chr(int(b[6:8],16)) + chr(int(b[4:6],16)) + chr(int(b[2:4],16))
2382
2383 c = str(hex(SBL_VIRTUAL_BLOCK_MAGIC_NUM))
2384 mc3 = chr(int(c[8:10],16)) + chr(int(c[6:8],16)) + chr(int(c[4:6],16)) + chr(int(c[2:4],16))
2385
2386 MC_inserted_data = filedata_till_128kb + mc1 + mc2 + mc3
2387 file.write(MC_inserted_data)
2388
2389 filedata = filedata_after_128kb
2390 length = len(filedata)
2391
2392 #copy the leftover data (<128KB) in output file
2393 if length > 0:
2394 file.write(filedata)
2395
2396 #close the final output file
2397 file.close()
2398 # MC_insertion code end
2399
2400 #----------------------------------------------------------------------------
2401 # Helper functions to remove MCs in SBL1(Badger)
2402 #----------------------------------------------------------------------------
2403 def remove_SBL1_magicCookie (env, target, dest):
2404 file = open(target, "rb")
2405 #read the file contents
2406 filedata = file.read()
2407 length = len(filedata)
2408 file.close()
2409
2410 #generate new file for appending target data + required MCs
2411 file = open(dest, "ab")
2412
2413 while length > VIRTUAL_BLOCK_SIZE:
2414 filedata_till_128kb = filedata[0:VIRTUAL_BLOCK_SIZE]
2415 # skipped 12 byte of Virtual Block Magic Cookie Header
2416 filedata_after_128kb = filedata[VIRTUAL_BLOCK_SIZE+MAGIC_COOKIE_LENGTH:length]
2417
2418 file.write(filedata_till_128kb)
2419
2420 filedata = filedata_after_128kb
2421 length = len(filedata)
2422
2423 #copy the leftover data (<128KB) in output file
2424 if length > 0:
2425 file.write(filedata)
2426
2427 #close the final output file
2428 file.close()
2429
2430 # MC_removal code end
2431
2432 #----------------------------------------------------------------------------
2433 # Helper functions to pad SBL1 image
2434 # min_size defaults to 256k
2435 # If page_size or num_of_pages is set to 0, the variable is unset
2436 #----------------------------------------------------------------------------
2437 def pad_SBL1_image (env, target, min_size_with_pad=MIN_IMAGE_SIZE_WITH_PAD, page_size=0, num_of_pages=0):
2438 file = open(target, "rb")
2439 #read the file contents
2440 filedata = file.read()
2441 length = len(filedata)
2442 file.close()
2443
2444 multiple = 1
2445 alignment = page_size * num_of_pages
2446
2447 if (length > alignment and alignment > 0):
2448 import math
2449 multiple = math.ceil(length/float(alignment))
2450
2451 final_image_size = max(min_size_with_pad, multiple * alignment)
2452
2453 if length < final_image_size:
2454 sbl1_fp = open(target, 'ab')
2455 pad_file (sbl1_fp, (final_image_size-length), PAD_BYTE_0)
2456 sbl1_fp.close()
2457
2458 # SBL1 pad code end
2459 #----------------------------------------------------------------------------
2460 # HELPER FUNCTIONS END
2461 #----------------------------------------------------------------------------