forked from acidanthera/OpenCorePkg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupdate_generated.py
executable file
·308 lines (253 loc) · 9.95 KB
/
update_generated.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
#!/usr/bin/env python
"""
Update autogenerated source files from yaml database.
Copyright (c) 2019, vit9696
"""
from __future__ import print_function
import update_products
import fnmatch
import json
import operator
import os
import unicodedata
import sys
import yaml
def remove_accents(input_str):
nfkd_form = unicodedata.normalize('NFKD', input_str)
return u"".join([c for c in nfkd_form if not unicodedata.combining(c)])
def load_db(dbpath):
"""
Load yaml database and return in a list.
"""
if not os.path.exists(dbpath):
print("Cannot find %s directory, rerun from AppleModels directory!" % dbpath)
sys.exit(1)
db = []
for root, dirs, files in os.walk(dbpath):
for file in fnmatch.filter(files, '*.yaml'):
path = os.path.join(root, file)
with open(path, 'r') as fh:
try:
r = yaml.safe_load(fh)
if r.get('SystemProductName', None) is None:
print("WARN: Missing SystemProductName in %s, skipping!" % path)
continue
db.append(r)
except yaml.YAMLError as e:
print("Failed to parse file %s - %s" % (path, e))
sys.exit(1)
if len(db) == 0:
print("Empty database!")
sys.exit(1)
# Sorting is required for fast lookup.
return sorted(db, key=operator.itemgetter('SystemProductName'))
def gather_products(db, ptype='AppleModelCode', empty_valid=False, shared_valid=False, fatal=True):
"""
Obtain all product codes from the database
"""
products = []
for info in db:
pp = info.get(ptype, None)
if pp is None:
continue
for p in pp:
if p == '':
if not empty_valid:
print("ERROR: {} in contains empty {}, skipping!".format(info['SystemProductName'], ptype))
if fatal: sys.exit(1)
continue
if p == '000' or p == '0000':
print("WARN: {} in contains zero {}, skipping!".format(info['SystemProductName'], ptype))
continue
if p in products:
if not shared_valid:
print("ERROR: {} shares {} {} with other model!".format(info['SystemProductName'], ptype, p))
if fatal: sys.exit(1)
continue
products.append(p)
return products
def validate_products(db, dbpd):
usedproducts = gather_products(db)
# FIXME: Empty is not valid, but we let it be for now.
gather_products(db, 'AppleBoardCode', True, True, False)
knownproducts = dbpd
for product in usedproducts:
if knownproducts.get(product, None) is None:
print("ERROR: Model %s is used in DataBase but not present in Products!" % product)
sys.exit(1)
if knownproducts[product][update_products.KEY_STATUS] != update_products.STATUS_OK:
print("ERROR: Model %s is used in DataBase but not valid in Products!" % product)
sys.exit(1)
to_add = {}
for product in knownproducts:
if knownproducts[product][update_products.KEY_STATUS] != update_products.STATUS_OK:
continue
name = knownproducts[product][update_products.KEY_NAME]
if name.find('Mac') < 0 and name.find('Xserve') < 0:
continue
if len(product) > 3 and product not in usedproducts:
print("WARN: Model %s (%s) is known but is not used in DataBase!" % (product, name))
if to_add.get(name, None) is None:
to_add[name] = []
to_add[name].append(product)
continue
if len(to_add) > 0:
for sysname in to_add:
for info in db:
if sysname in info['Specifications']['SystemReportName']:
print("New AppleModelCode for {}:".format(info['SystemProductName']))
for model in to_add[sysname]:
print(" - \"{}\"".format(model))
def export_db_macinfolib(db, path, year=0):
"""
Export yaml database to MacInfoLib format.
TODO: use jinja2?
"""
with open(path, 'w') as fh:
print('// DO NOT EDIT! This is an autogenerated file.', file=fh)
print('#include "MacInfoInternal.h"', file=fh)
print('CONST MAC_INFO_INTERNAL_ENTRY gMacInfoModels[] = {', file=fh)
for info in db:
if max(info['AppleModelYear']) < year:
continue
print(' {\n'
' .SystemProductName = "%s",\n'
' .BoardProduct = "%s",\n'
' .BoardRevision = %s,\n'
' .SmcRevision = {%s},\n'
' .SmcBranch = {%s},\n'
' .SmcPlatform = {%s},\n'
' .BIOSVersion = "%s",\n'
' .BIOSReleaseDate = "%s",\n'
' .SystemVersion = "%s",\n'
' .SystemSKUNumber = "%s",\n'
' .SystemFamily = "%s",\n'
' .BoardVersion = "%s",\n'
' .BoardAssetTag = "%s",\n'
' .BoardLocationInChassis = "%s",\n'
' .SmcGeneration = 0x%X,\n'
' .BoardType = 0x%X,\n'
' .ChassisType = 0x%X,\n'
' .MemoryFormFactor = 0x%X,\n'
' .PlatformFeature = %s,\n'
' .ChassisAssetTag = "%s",\n'
' .FirmwareFeatures = 0x%XULL,\n'
' .FirmwareFeaturesMask = 0x%XULL,\n'
' },' % (
info['SystemProductName'],
info['BoardProduct'][0] if isinstance(info['BoardProduct'], list) else info['BoardProduct'],
'0x{:X}'.format(info['BoardRevision']) if 'BoardRevision' in info else 'MAC_INFO_BOARD_REVISION_MISSING',
', '.join(map(str, info.get('SmcRevision', [0x00]))),
', '.join(map(str, info.get('SmcBranch', [0x00]))),
', '.join(map(str, info.get('SmcPlatform', [0x00]))),
info['BIOSVersion'],
info['BIOSReleaseDate'],
info['SystemVersion'],
info['SystemSKUNumber'],
info['SystemFamily'],
info['BoardVersion'],
info['BoardAssetTag'],
info['BoardLocationInChassis'],
info['SmcGeneration'],
info['BoardType'],
info['ChassisType'],
info['MemoryFormFactor'],
'0x{:X}'.format(info['PlatformFeature']) if 'PlatformFeature' in info else 'MAC_INFO_PLATFORM_FEATURE_MISSING',
info['ChassisAssetTag'],
info.get('ExtendedFirmwareFeatures', info.get('FirmwareFeatures', 0)),
info.get('ExtendedFirmwareFeaturesMask', info.get('FirmwareFeaturesMask', 0))
), file=fh)
print('};', file=fh)
print('CONST UINTN gMacInfoModelCount = ARRAY_SIZE (gMacInfoModels);', file=fh)
print('CONST UINTN gMacInfoDefaultModel = 0;', file=fh)
def export_db_macserial(db, dbpd, path, year=0):
"""
Export yaml database to macserial format.
TODO: use jinja2?
"""
with open(path, 'w') as fh:
print('#ifndef GENSERIAL_MODELINFO_AUTOGEN_H', file=fh)
print('#define GENSERIAL_MODELINFO_AUTOGEN_H\n', file=fh)
print('// DO NOT EDIT! This is an autogenerated file.\n', file=fh)
print('#include "macserial.h"\n', file=fh)
print('typedef enum {', file=fh)
for info in db:
print(' {}, // {}'.format(
info['SystemProductName'].replace(',', '_'),
info['Specifications']['CPU'][0]
), file=fh)
print('} AppleModel;\n', file=fh)
print('#define APPLE_MODEL_MAX {}\n'.format(len(db)), file=fh)
print('static PLATFORMDATA ApplePlatformData[] = {', file=fh)
for info in db:
print(' {{ "{}", "{}" }},'.format(
info['SystemProductName'],
info['SystemSerialNumber']
), file=fh)
print('};\n', file=fh)
print('#define APPLE_MODEL_CODE_MAX {}'.format(max(len(info['AppleModelCode']) for info in db)), file=fh)
print('static const char *AppleModelCode[][APPLE_MODEL_CODE_MAX] = {', file=fh)
for info in db:
print(' /* {:14} */ {{"{}"}},'.format(
info['SystemProductName'],
'", "'.join(info['AppleModelCode'])
), file=fh)
print('};\n', file=fh)
print('#define APPLE_BOARD_CODE_MAX {}'.format(max(len(info['AppleBoardCode']) for info in db)), file=fh)
print('static const char *AppleBoardCode[][APPLE_BOARD_CODE_MAX] = {', file=fh)
for info in db:
print(' /* {:14} */ {{"{}"}},'.format(
info['SystemProductName'],
'", "'.join(info['AppleBoardCode'])
), file=fh)
print('};\n', file=fh)
print('#define APPLE_MODEL_YEAR_MAX {}'.format(max(len(info['AppleModelYear']) for info in db)), file=fh)
print('static uint32_t AppleModelYear[][APPLE_MODEL_YEAR_MAX] = {', file=fh)
for info in db:
print(' /* {:14} */ {{{}}},'.format(
info['SystemProductName'],
', '.join(str(year) for year in info['AppleModelYear'])
), file=fh)
print('};\n', file=fh)
print('static uint32_t ApplePreferredModelYear[] = {', file=fh)
for info in db:
print(' /* {:14} */ {},'.format(
info['SystemProductName'],
info.get('MacserialModelYear', 0)
), file=fh)
print('};\n', file=fh)
print('static APPLE_MODEL_DESC AppleModelDesc[] = {', file=fh)
models = sorted(dbpd.keys())
models.sort(key=len)
for model in models:
if dbpd[model][update_products.KEY_STATUS] == update_products.STATUS_OK:
print(' {{"{}", "{}"}},'.format(
model,
remove_accents(dbpd[model][update_products.KEY_NAME])
), file=fh)
print('};\n', file=fh)
print('#endif // GENSERIAL_MODELINFO_AUTOGEN_H', file=fh)
def export_mlb_boards(db, boards):
l = {}
for info in db:
if len(info['SystemSerialNumber']) == 12:
models = [info['BoardProduct']] if not isinstance(info['BoardProduct'], list) else info['BoardProduct']
for model in models:
if info['MaximumOSVersion'] is None:
l[model] = 'latest'
else:
l[model] = info['MaximumOSVersion']
with open(boards, 'w') as fh:
json.dump(l, fh, indent=1)
if __name__ == '__main__':
db = load_db('DataBase')
dbpd = update_products.load_products()
# Run test phase to validate the library
validate_products(db, dbpd)
export_db_macinfolib(db, os.devnull)
export_db_macserial(db, dbpd, os.devnull)
# Export new models
export_db_macinfolib(db, '../Library/OcMacInfoLib/AutoGenerated.c', 2012)
export_db_macserial(db, dbpd, '../Utilities/macserial/modelinfo_autogen.h')
# Export MLB models
export_mlb_boards(db, '../Utilities/macrecovery/boards.json')