-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_memory_map_en.py
More file actions
379 lines (319 loc) · 12.6 KB
/
Copy pathgenerate_memory_map_en.py
File metadata and controls
379 lines (319 loc) · 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
#!/usr/bin/env python3
import os
import sys
sys.dont_write_bytecode = True
import re
import shutil
import urllib.request
import json
import zipfile
import subprocess
import plistlib
import ssl
DMIDECODE_BIN = os.path.join(os.path.dirname(os.path.abspath(__file__)), "dmidecode")
DMI_TYPE_MAP = {
"Other": 1,
"Unknown": 2,
"None": 3,
"Parity": 4,
"Single-bit ECC": 5,
"Multi-bit ECC": 6,
"CRC": 7,
"DIMM": 9,
"SODIMM": 13,
"FB-DIMM": 15,
"SDRAM": 15,
"DDR": 18,
"DDR2": 19,
"DDR2 FB-DIMM": 20,
"DDR3": 24,
"DDR4": 26,
"DDR5": 27,
"LPDDR": 27,
"LPDDR2": 28,
"LPDDR3": 29,
"LPDDR4": 30,
}
DMI_TYPE_NAMES = {v: k for k, v in DMI_TYPE_MAP.items()}
TYPE_DETAIL_MAP = {
"Other": 0x0002,
"Unknown": 0x0004,
"Synchronous": 0x0080,
"Registered (Buffered)": 0x2000,
"Unbuffered (Unregistered)": 0x4000,
"LRDIMM": 0x1000,
"LOGICAL NON-VOLATILE": 0x0400,
}
RAM_TYPES = {
"DDR3": 24,
"DDR4": 26,
"DDR5": 27,
"LPDDR": 27,
"LPDDR2": 28,
"LPDDR3": 29,
"LPDDR4": 30,
}
FORM_FACTORS = {
"DIMM": 9,
"SODIMM": 13,
"FB-DIMM": 15,
}
STUB_VALUES = {"Not Specified", "Unknown", "0x0000", "NO DIMM", "No Asset Information", ""}
def clean_val(v):
return "" if v in STUB_VALUES else v
def parse_dmi_block(block):
data = {}
for line in block.split("\n"):
if ":" in line:
key, val = line.split(":", 1)
data[key.strip()] = val.strip()
return data
def parse_size_mb(size_str):
match = re.search(r"(\d+)\s*(MB|GB|TB)", size_str, re.IGNORECASE)
if not match:
return 0
val, unit = int(match.group(1)), match.group(2).upper()
if unit == "TB":
return val * 1024 * 1024
if unit == "GB":
return val * 1024
return val
def parse_speed_mhz(speed_str):
match = re.search(r"(\d+)", speed_str)
return int(match.group(1)) if match else 0
def parse_type_detail(td_str):
value = 0
for key, bits in TYPE_DETAIL_MAP.items():
if key.lower() in td_str.lower():
value |= bits
return value
def parse_max_capacity(mc_str):
if "No Limit" in mc_str:
return 274877906944
for pattern, multiplier in (r"(\d+)\s*GB", 1024**3), (r"(\d+)\s*MB", 1024**2), (r"(\d+)\s*kB", 1024):
match = re.search(pattern, mc_str, re.IGNORECASE)
if match:
return int(match.group(1)) * multiplier
return 0
def parse_dmidecode(output):
global_props = {
"DataWidth": 64,
"ErrorCorrection": 3,
"FormFactor": 9,
"MaxCapacity": 0,
"TotalWidth": 64,
"Type": 26,
"TypeDetail": 128,
}
modules = []
found_populated = False
for block in output.split("Physical Memory Array")[1:]:
data = parse_dmi_block(block)
mc = data.get("Maximum Capacity", "")
if mc:
global_props["MaxCapacity"] = parse_max_capacity(mc)
break
for block in output.split("Memory Device")[1:]:
data = parse_dmi_block(block)
size_str = data.get("Size", "")
is_populated = size_str and "No Module Installed" not in size_str
if is_populated and not found_populated:
found_populated = True
dw = re.search(r"(\d+)", data.get("Data Width", ""))
tw = re.search(r"(\d+)", data.get("Total Width", ""))
if dw:
global_props["DataWidth"] = int(dw.group(1))
if tw:
global_props["TotalWidth"] = int(tw.group(1))
ec = data.get("Error Correction Type", "")
if ec in DMI_TYPE_MAP:
global_props["ErrorCorrection"] = DMI_TYPE_MAP[ec]
ff = data.get("Form Factor", "")
if ff in DMI_TYPE_MAP:
global_props["FormFactor"] = DMI_TYPE_MAP[ff]
tp = data.get("Type", "")
if tp in DMI_TYPE_MAP:
global_props["Type"] = DMI_TYPE_MAP[tp]
td = data.get("Type Detail", "")
if td:
global_props["TypeDetail"] = parse_type_detail(td)
if is_populated:
modules.append({
"AssetTag": clean_val(data.get("Asset Tag", "")),
"BankLocator": clean_val(data.get("Bank Locator", "")),
"DeviceLocator": clean_val(data.get("Device Locator", "")),
"Manufacturer": clean_val(data.get("Manufacturer", "")),
"PartNumber": clean_val(data.get("Part Number", "")),
"SerialNumber": clean_val(data.get("Serial Number", "")),
"Size": parse_size_mb(size_str),
"Speed": parse_speed_mhz(data.get("Speed", "")),
})
return global_props, modules
def ensure_dmidecode():
system_dmidecode = shutil.which("dmidecode")
if system_dmidecode:
print(f"[i] System dmidecode found: {system_dmidecode}")
return system_dmidecode
if os.path.exists(DMIDECODE_BIN):
return DMIDECODE_BIN
print("[i] dmidecode not found. Downloading from GitHub Acidanthera...")
try:
ssl_context = ssl._create_unverified_context()
api_url = "https://api.github.com/repos/acidanthera/dmidecode/releases/latest"
req = urllib.request.Request(api_url, headers={"User-Agent": "Mozilla/5.0"})
with urllib.request.urlopen(req, context=ssl_context) as response:
release_data = json.loads(response.read().decode())
assets = release_data.get("assets", [])
zip_url = None
for asset in assets:
name = asset["name"]
if name.endswith(".zip") and ("linux" in name.lower() or "mac" in name.lower() or "darwin" in name.lower()):
zip_url = asset["browser_download_url"]
break
if not zip_url:
zip_url = next((a["browser_download_url"] for a in assets if a["name"].endswith(".zip")), None)
if not zip_url:
print("[!] Could not find zip archive in releases.")
return None
print(f"[i] Downloading: {zip_url}")
zip_path = os.path.join(os.path.dirname(DMIDECODE_BIN), "dmidecode.zip")
with urllib.request.urlopen(zip_url, context=ssl_context) as response, open(zip_path, "wb") as out_file:
out_file.write(response.read())
with zipfile.ZipFile(zip_path, "r") as zip_ref:
for member in zip_ref.namelist():
if member.endswith("dmidecode") or member == "dmidecode":
zip_ref.extract(member, os.path.dirname(DMIDECODE_BIN))
extracted_path = os.path.join(os.path.dirname(DMIDECODE_BIN), member)
if extracted_path != DMIDECODE_BIN:
os.rename(extracted_path, DMIDECODE_BIN)
break
if os.path.exists(zip_path):
os.remove(zip_path)
os.chmod(DMIDECODE_BIN, 0o755)
print("[✓] dmidecode ready.")
return DMIDECODE_BIN
except Exception as e:
print(f"[!] Failed to download dmidecode: {e}")
return None
def run_dmidecode(dmidecode_path):
if os.geteuid() != 0:
print("[!] Script must be run as root to access DMI tables.")
print(" Restart with: sudo python3 generate_memory_map_en.py")
sys.exit(1)
try:
return subprocess.check_output(
[dmidecode_path, "-t", "memory"], stderr=subprocess.STDOUT
).decode("utf-8", errors="ignore")
except Exception as e:
print(f"[!] Failed to run dmidecode: {e}")
return ""
def interactive_override(detected_count, auto_props):
print("=" * 60)
print(" OPENCORE MEMORY MAP GENERATOR (MacPro7,1) ")
print("=" * 60)
print(f"Detected installed modules: {detected_count}\n")
print("[i] Auto-detected from dmidecode:")
print(f" DataWidth: {auto_props['DataWidth']}")
print(f" TotalWidth: {auto_props['TotalWidth']}")
print(f" ErrorCorrection: {auto_props['ErrorCorrection']} ({DMI_TYPE_NAMES.get(auto_props['ErrorCorrection'], '?')})")
print(f" FormFactor: {auto_props['FormFactor']} ({DMI_TYPE_NAMES.get(auto_props['FormFactor'], '?')})")
print(f" Type: {auto_props['Type']} ({DMI_TYPE_NAMES.get(auto_props['Type'], '?')})")
print(f" TypeDetail: {auto_props['TypeDetail']}")
if auto_props["MaxCapacity"]:
print(f" MaxCapacity: {auto_props['MaxCapacity'] // (1024**3)} GB")
print()
print("Press Enter to accept auto-values, or choose from the list:")
print()
ram_list = list(RAM_TYPES.items())
current_type = DMI_TYPE_NAMES.get(auto_props["Type"], "DDR4")
print("1. RAM Type:")
for idx, (name, _) in enumerate(ram_list, 1):
print(f" [{idx}] {name}" + (" <<<" if name == current_type else ""))
choice = input(f" Choice [{current_type}]: ").strip()
if choice.isdigit() and 1 <= int(choice) <= len(ram_list):
auto_props["Type"] = ram_list[int(choice) - 1][1]
elif choice.upper() in RAM_TYPES:
auto_props["Type"] = RAM_TYPES[choice.upper()]
print()
ff_list = list(FORM_FACTORS.items())
current_ff = DMI_TYPE_NAMES.get(auto_props["FormFactor"], "DIMM")
print("2. Form Factor:")
for idx, (name, _) in enumerate(ff_list, 1):
print(f" [{idx}] {name}" + (" <<<" if name == current_ff else ""))
choice = input(f" Choice [{current_ff}]: ").strip()
if choice.isdigit() and 1 <= int(choice) <= len(ff_list):
auto_props["FormFactor"] = ff_list[int(choice) - 1][1]
elif choice.upper() in FORM_FACTORS:
auto_props["FormFactor"] = FORM_FACTORS[choice.upper()]
print()
max_gb = auto_props["MaxCapacity"] // (1024**3) if auto_props["MaxCapacity"] else 128
max_input = input(f"3. Max memory capacity in GB [{max_gb}]: ").strip()
if max_input:
try:
auto_props["MaxCapacity"] = int(max_input) * 1024**3
except ValueError:
pass
elif not auto_props["MaxCapacity"]:
auto_props["MaxCapacity"] = max_gb * 1024**3
return auto_props
def generate_memory_mapping():
dmidecode_path = ensure_dmidecode()
if not dmidecode_path:
print("[!] Could not find or download dmidecode.")
print(" Install dmidecode manually and place it next to this script.")
sys.exit(1)
dmi_output = run_dmidecode(dmidecode_path)
auto_props, active_modules = parse_dmidecode(dmi_output)
preferences = interactive_override(len(active_modules), auto_props)
total_slots = 12
devices = []
real_speed = active_modules[0]["Speed"] if active_modules else 0
for i in range(total_slots):
if i < len(active_modules):
m = active_modules[i]
device_locator = m["DeviceLocator"] or f"Slot {i + 1}"
manufacturer = m["Manufacturer"]
if not manufacturer:
size_gb = m["Size"] // 1024 if m["Size"] >= 1024 else m["Size"]
print(f" Module #{i + 1} ({size_gb} GB):")
user_mfg = input(" [!] Enter manufacturer [Acidanthera]: ").strip()
manufacturer = user_mfg or "Acidanthera"
devices.append({
"AssetTag": m["AssetTag"],
"BankLocator": m["BankLocator"],
"DeviceLocator": device_locator,
"Manufacturer": manufacturer,
"PartNumber": m["PartNumber"],
"SerialNumber": m["SerialNumber"],
"Size": m["Size"],
"Speed": m["Speed"],
})
else:
devices.append({
"AssetTag": "",
"BankLocator": "",
"DeviceLocator": "DIMM_EMPTY",
"Manufacturer": "",
"PartNumber": "EmptyDIMM",
"SerialNumber": "EmptyDIMM",
"Size": 1,
"Speed": real_speed,
})
memory_dict = {
"DataWidth": preferences["DataWidth"],
"ErrorCorrection": preferences["ErrorCorrection"],
"FormFactor": preferences["FormFactor"],
"MaxCapacity": preferences["MaxCapacity"],
"TotalWidth": preferences["TotalWidth"],
"Type": preferences["Type"],
"TypeDetail": preferences["TypeDetail"],
"Devices": devices,
}
output_filename = "custom_memory.plist"
with open(output_filename, "wb") as f:
plistlib.dump({"PlatformInfo": {"Memory": memory_dict}}, f, sort_keys=False)
print(f"\n[✓] Done! Configuration saved to '{output_filename}'")
print(f" Enable PlatformInfo → CustomMemory in config.plist")
print(f" and copy the Memory section from custom_memory.plist to your config.plist.")
if __name__ == "__main__":
generate_memory_mapping()