2 # SPDX-License-Identifier: BSD-2-Clause
6 from io
import SEEK_SET
, SEEK_END
10 print("Initialize IDBTool")
12 def p_rc4(self
, buf
, length
):
13 key
= (124,78,3,4,85,5,9,7,45,44,123,56,23,13,23,17)
15 S
= [i
for i
in range(256)]
19 j
= (j
+ S
[i
] + K
[i
]) % 256
20 temp
= S
[i
]; S
[i
] = S
[j
]; S
[j
] = temp
;
23 for x
in range(length
):
26 temp
= S
[i
]; S
[i
] = S
[j
]; S
[j
] = temp
27 k
= (S
[i
] + S
[j
]) % 256
28 buf
[x
] = struct
.pack('B', buf
[x
] ^ S
[k
])[0]
30 def makeIDB(self
, chip
, from_file
, to_file
, rc4_flag
= False, align_flag
= False):
32 fin
= open(from_file
, 'rb')
34 sys
.exit("Failed to open file : " + from_file
)
38 if (fin
.tell() > 4 * 1024 * 1024):
39 sys
.exit("Input file is more than 4MB")
48 sectors
= (data_len
+ 4 - 1) // SECTOR_SIZE
+ 1
49 pages
= (sectors
- 1) // PAGE_ALIGN
+ 1
50 sectors
= pages
* PAGE_ALIGN
52 buf
= bytearray(sectors
* SECTOR_SIZE
)
54 buf
[:4] = chip
.encode('ascii')
55 buf
[4 : 4+data_len
] = data
57 idblock
= bytearray(4 * SECTOR_SIZE
)
58 blank
= bytearray(4 * SECTOR_SIZE
)
59 idblock
[:4] = b
'\x55\xAA\xF0\x0F'
62 idblock
[8:12] = struct
.pack("<I", 1)
64 for i
in range(sectors
):
65 list_tmp
= buf
[SECTOR_SIZE
*i
: SECTOR_SIZE
*(i
+1)]
66 self
.p_rc4(list_tmp
, SECTOR_SIZE
)
67 buf
[SECTOR_SIZE
*i
: SECTOR_SIZE
*(i
+1)] = list_tmp
69 idblock
[12:16] = struct
.pack("<HH", 4, 4)
70 idblock
[506:510] = struct
.pack("<HH", sectors
, sectors
)
71 self
.p_rc4(idblock
, SECTOR_SIZE
)
74 fout
= open(to_file
, "wb+")
76 sys
.exit("Failed to open output file : " + to_file
)
83 for s
in range(0, sectors
* SECTOR_SIZE
, PAGE_ALIGN
* SECTOR_SIZE
):
84 fout
.write(buf
[s
: s
+ PAGE_ALIGN
* SECTOR_SIZE
])
91 sys
.exit("Failed to write data to : " + to_file
)
97 print("Usage: make_idb.py [--chip=RKXX] [--enable-rc4] [--enable-align] [--to=out] --from=in")
98 print(" --chip: default is RK32")
100 if __name__
== '__main__':
101 rc4_flag
= align_flag
= False
102 to_file
= "IDBlock.bin"
105 for para
in sys
.argv
[1:]:
106 if (para
== "--enable-rc4"):
108 elif (para
== "--enable-align"):
110 elif (para
.startswith("--to=")):
111 to_file
= para
.split('=')[1]
112 elif (para
.startswith("--from=")):
113 from_file
= para
.split('=')[1]
114 elif (para
.startswith("--chip=")):
115 chip
= para
.split('=')[1]
116 elif (para
== "--help" or para
== "-h"):
122 if ('from_file' not in vars() or to_file
== ''):
127 idbtool
.makeIDB(chip
, from_file
, to_file
, rc4_flag
, align_flag
)