/
create_flashable_firmware.py
executable file
·283 lines (256 loc) · 10.6 KB
/
create_flashable_firmware.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
#!/usr/bin/env python3.7
"""Xiaomi Flashable Firmware Creator"""
from argparse import ArgumentParser
from datetime import datetime
from distutils.dir_util import copy_tree
from os import makedirs, rename, remove, path
from shutil import move, make_archive, rmtree
from socket import gethostname
from zipfile import ZipFile
import re
def arg_parse():
"""
Parses command-line arguments
:return: rom, process
"""
process = None
rom = None
switches = ArgumentParser(description='Xiaomi Flashable Firmware Creator', )
group = switches.add_mutually_exclusive_group(required=True)
group.add_argument("-F", "--firmware", help="Create normal Firmware zip")
group.add_argument("-N", "--nonarb", help="Create non-ARB Firmware zip")
group.add_argument("-L", "--firmwareless", help="Create Firmware-less zip")
group.add_argument("-V", "--vendor", help="Create Firmware+Vendor zip")
args = vars(switches.parse_args())
firmware = args["firmware"]
firmwareless = args["firmwareless"]
nonarb = args["nonarb"]
vendor = args["vendor"]
if firmware is not None:
process = "firmware"
rom = firmware
elif nonarb is not None:
process = "nonarb"
rom = nonarb
elif firmwareless is not None:
process = "firmwareless"
rom = firmwareless
elif vendor is not None:
process = "vendor"
rom = vendor
return rom, process
def pre():
"""
Sets today data and hostname
:return: today, host
"""
today = str(datetime.today()).split('.')[0]
host = str(gethostname())
return today, host
def check_firmware():
"""
Checks firmware existence and type
:return: fw_type
"""
valid = None
if path.exists('tmp/META-INF/com/google/android/update-binary') \
or path.exists('tmp/META-INF/com/google/android/updater-script'):
valid = True
fw_type = None
if valid is True:
if path.exists('tmp/firmware-update'):
fw_type = 'qcom'
elif path.exists('tmp/lk.img') \
or path.exists('tmp/preloader.img') \
or path.exists('tmp/scatter.txt'):
fw_type = 'mtk'
else:
print("This zip isn't a valid ROM or I couldn't find firmware! Exiting.")
rmtree("tmp")
exit(2)
return fw_type
def firmware_extract():
"""
Extracts firmware from qcom device's ROM
"""
rom, process = arg_parse()
if process == "firmware":
with ZipFile(rom, 'r') as zip_file:
files = [n for n in zip_file.namelist()
if n.startswith('firmware-update/') or n.startswith('META-INF/')]
to_extract = [i for i in files if 'dtbo' not in i
and 'splash' not in i and 'vbmeta' not in i]
zip_file.extractall(path="tmp", members=to_extract)
elif process == "nonarb":
with ZipFile(rom, 'r') as zip_file:
files = [n for n in zip_file.namelist()
if n.startswith('firmware-update/dspso.bin')
or n.startswith('firmware-update/BTFM.bin')
or n.startswith('firmware-update/NON-HLOS.bin')
or n.startswith('META-INF/')]
zip_file.extractall(path="tmp", members=files)
check_firmware()
move('tmp/firmware-update/', 'out/firmware-update/')
move('tmp/META-INF/com/google/android/update-binary', 'out/META-INF/com/google/android/')
def rom_extract():
"""
Extracts ROM without firmware for qcom device
:return:
"""
rom = arg_parse()[0]
with ZipFile(rom, 'r') as zip_file:
files = [n for n in zip_file.namelist()
if not n.startswith('firmware-update/')]
zip_file.extractall(path="tmp", members=files)
check_firmware()
copy_tree('tmp/', 'out/')
def vendor_extract():
"""
Extracts vendor and firmware
:return:
"""
rom = arg_parse()[0]
with ZipFile(rom, 'r') as zip_file:
files = [n for n in zip_file.namelist()
if not n.startswith('system') and not n.startswith('boot')]
zip_file.extractall(path="tmp", members=files)
check_firmware()
copy_tree('tmp/', 'out/')
remove("out/META-INF/com/google/android/updater-script")
def firmware_updater():
"""
Generates updater-script for firmware zip
"""
today, host = pre()
with open("tmp/META-INF/com/google/android/updater-script", 'r') as i, \
open("out/updater-script", "w", newline='\n') as out:
out.writelines("show_progress(0.200000, 10);\n\n")
out.writelines("# Generated by Xiaomi Flashable Firmware Creator\n"
+ f"# {today} - {host}\n'\n")
out.writelines('ui_print("Flashing Normal firmware...");\n')
out.writelines(line for line in i if "getprop" in line or "Target" in line
or "firmware-update" in line and 'splash' not in line
and 'dtbo' not in line and 'vbmeta' not in line)
out.writelines('\nshow_progress(0.100000, 2);\nset_progress(1.000000);\n')
with open("out/updater-script", 'r') as i, \
open("out/META-INF/com/google/android/updater-script", "w", newline='\n') as out:
correct = i.read().replace('/firmware/image/sec.dat', '/dev/block/bootdevice/by-name/sec') \
.replace('/firmware/image/splash.img', '/dev/block/bootdevice/by-name/splash')
out.write(correct)
remove("out/updater-script")
def nonarb_updater():
"""
Generates updater-script for non-arb firmware zip
"""
today, host = pre()
with open("tmp/META-INF/com/google/android/updater-script", 'r') as i, \
open("out/updater-script", "w", newline='\n') as out:
out.writelines("show_progress(0.200000, 10);\n\n")
out.writelines("# Generated by Xiaomi Flashable Firmware Creator\n"
+ f"# {today} - {host}\n'\n")
out.writelines('ui_print("Flashing non-ARB firmware...");\n')
out.writelines(line for line in i if "getprop" in line or "Target" in line
or "modem" in line or "bluetooth" in line or "dsp" in line)
out.writelines('\nshow_progress(0.100000, 2);\nset_progress(1.000000);\n')
with open("out/updater-script", 'r') as i, \
open("out/META-INF/com/google/android/updater-script", "w", newline='\n') as out:
correct = i.read().replace('/firmware/image/sec.dat', '/dev/block/bootdevice/by-name/sec') \
.replace('/firmware/image/splash.img', '/dev/block/bootdevice/by-name/splash')
out.write(correct)
remove("out/updater-script")
def firmwareless_updater():
"""
Generates updater-script for fw-less zip
"""
today, host = pre()
with open("tmp/META-INF/com/google/android/updater-script", 'r') as i, \
open("out/META-INF/com/google/android/updater-script", "w", newline='\n') as out:
out.writelines("show_progress(0.200000, 10);\n\n")
out.writelines("# Generated by Xiaomi Flashable Firmware Creator\n"
+ f"# {today} - {host}\n'\n")
out.writelines('ui_print("Flashing firmware-less ROM...");\n')
out.writelines(line for line in i if "getprop" in line or "Target" in line
or "boot.img" in line or "system" in line or "vendor" in line)
out.writelines('\nshow_progress(0.100000, 2);\nset_progress(1.000000);\n')
def vendor_updater():
"""
Generates updater-script for fw-vendor zip
"""
today, host = pre()
with open("tmp/META-INF/com/google/android/updater-script", 'r') as i, \
open("out/updater-script", "w", newline='\n') as out:
out.writelines("show_progress(0.200000, 10);\n\n")
out.writelines("# Generated by Xiaomi Flashable Firmware Creator\n"
+ f"# {today} - {host}\n'\n")
out.writelines('ui_print("Flashing firmware+vendor...");\n')
out.writelines(line for line in i if "getprop" in line or "Target" in line
or "firmware-update" in line or "vendor" in line
and 'splash' not in line and 'dtbo' not in line and 'vbmeta' not in line)
out.writelines('\nshow_progress(0.100000, 2);\nset_progress(1.000000);\n')
with open("out/updater-script", 'r') as i, \
open("out/META-INF/com/google/android/updater-script", "w", newline='\n') as out:
correct = i.read().replace('/firmware/image/sec.dat', '/dev/block/bootdevice/by-name/sec') \
.replace('/firmware/image/splash.img', '/dev/block/bootdevice/by-name/splash')
out.write(correct)
remove("out/updater-script")
def make_zip():
"""
Creates zip from extracted files
"""
rom, process = arg_parse()
rom = path.basename(rom)
with open("out/META-INF/com/google/android/updater-script", 'r') as i:
# codename = str(i.readlines()[7].split('/', 3)[2]).split(':', 1)[0].replace('_', '-')
codename = re.findall(r'Target:.*/[a-z]*/', i.read())[0].split('/')[1]
print(f"Creating {process} zip from {rom} for {codename}")
make_archive('firmware', 'zip', 'out/')
if path.exists('firmware.zip'):
if process == "firmware":
rename('firmware.zip', f'fw_{codename}_{rom}')
elif process == "nonarb":
rename('firmware.zip', f'fw-non-arb_{codename}_{rom}')
elif process == "firmwareless":
rename('firmware.zip', f'fw-less_{codename}_{rom}')
elif process == "vendor":
rename('firmware.zip', f'fw-vendor_{codename}_{rom}')
print("All done!")
rmtree("tmp")
rmtree('out')
else:
print("Failed!\n Check out folder!")
def main():
"""
Xiaomi Flashable Firmware Creator
"""
process = arg_parse()[1]
if path.exists('out'):
rmtree('out')
if path.exists('tmp'):
rmtree('tmp')
makedirs("tmp", exist_ok=True)
makedirs("out", exist_ok=True)
makedirs("out/META-INF/com/google/android", exist_ok=True)
if process == "firmware":
print("Unzipping MIUI..")
firmware_extract()
print("Generating updater-script..")
firmware_updater()
elif process == "nonarb":
print("Unzipping MIUI..")
firmware_extract()
print("Generating updater-script..")
nonarb_updater()
elif process == "firmwareless":
print("Unzipping MIUI..")
rom_extract()
print("Generating updater-script..")
firmwareless_updater()
elif process == "vendor":
print("Unzipping MIUI..")
vendor_extract()
print("Generating updater-script..")
vendor_updater()
make_zip()
if __name__ == '__main__':
arg_parse()
main()