forked from corpnewt/SSDTTime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SSDTTime.py
executable file
·2009 lines (1961 loc) · 84.4 KB
/
SSDTTime.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
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from Scripts import *
import getpass, os, tempfile, shutil, plistlib, sys, binascii, zipfile, re, string
class SSDT:
def __init__(self, **kwargs):
self.dl = downloader.Downloader()
self.u = utils.Utils("SSDT Time")
self.r = run.Run()
self.re = reveal.Reveal()
try:
self.d = dsdt.DSDT()
except Exception as e:
print("Something went wrong :( - Aborting!\n - {}".format(e))
exit(1)
self.w = 80
self.h = 24
if os.name == "nt":
os.system("color") # Allow ASNI color escapes.
self.w = 120
self.h = 30
self.iasl = None
self.dsdt = None
self.scripts = "Scripts"
self.output = "Results"
self.legacy_irq = ["TMR","TIMR","IPIC","RTC"] # Could add HPET for extra patch-ness, but shouldn't be needed
self.target_irqs = [0,2,8,11]
self.illegal_names = ("XHC1","EHC1","EHC2","PXSX")
# _OSI Strings found here: https://learn.microsoft.com/en-us/windows-hardware/drivers/acpi/winacpi-osi
self.osi_strings = {
"Windows 2000": "Windows 2000",
"Windows XP": "Windows 2001",
"Windows XP SP1": "Windows 2001 SP1",
"Windows Server 2003": "Windows 2001.1",
"Windows XP SP2": "Windows 2001 SP2",
"Windows Server 2003 SP1": "Windows 2001.1 SP1",
"Windows Vista": "Windows 2006",
"Windows Vista SP1": "Windows 2006 SP1",
"Windows Server 2008": "Windows 2006.1",
"Windows 7, Win Server 2008 R2": "Windows 2009",
"Windows 8, Win Server 2012": "Windows 2012",
"Windows 8.1": "Windows 2013",
"Windows 10": "Windows 2015",
"Windows 10, version 1607": "Windows 2016",
"Windows 10, version 1703": "Windows 2017",
"Windows 10, version 1709": "Windows 2017.2",
"Windows 10, version 1803": "Windows 2018",
"Windows 10, version 1809": "Windows 2018.2",
"Windows 10, version 1903": "Windows 2019",
"Windows 10, version 2004": "Windows 2020",
"Windows 11": "Windows 2021",
"Windows 11, version 22H2": "Windows 2022"
}
def select_dsdt(self):
self.u.head("Select DSDT")
print(" ")
print("M. Main")
print("Q. Quit")
print(" ")
dsdt = self.u.grab("Please drag and drop a DSDT.aml or origin folder here: ")
if dsdt.lower() == "m":
return self.dsdt
if dsdt.lower() == "q":
self.u.custom_quit()
out = self.u.check_path(dsdt)
if out:
self.u.head("Loading DSDT")
print("")
print("Loading {}...".format(out))
print("")
if self.d.load(out):
return out
else:
self.u.grab("\nPress [enter] to return...")
return self.select_dsdt()
def ensure_dsdt(self):
if self.dsdt and self.d.dsdt:
# Got it already
return True
# Need to prompt
self.dsdt = self.select_dsdt()
if self.dsdt and self.d.dsdt:
return True
return False
def write_ssdt(self, ssdt_name, ssdt):
res = self.d.check_output(self.output)
dsl_path = os.path.join(res,ssdt_name+".dsl")
aml_path = os.path.join(res,ssdt_name+".aml")
iasl_path = self.d.iasl
with open(dsl_path,"w") as f:
f.write(ssdt)
print("Compiling...")
out = self.r.run({"args":[iasl_path, dsl_path]})
if out[2] != 0:
print(" - {}".format(out[1]))
self.re.reveal(dsl_path,True)
return False
else:
self.re.reveal(aml_path,True)
return True
def ensure_path(self, plist_data, path_list, final_type = list):
if not path_list: return plist_data
last = plist_data
for index,path in enumerate(path_list):
if not path in last:
if index >= len(path_list)-1:
last[path] = final_type()
else:
last[path] = {}
last = last[path]
return plist_data
def make_plist(self, oc_acpi, cl_acpi, patches, replace=False):
# if not len(patches): return # No patches to add - bail
repeat = False
print("Building patches_OC and patches_Clover plists...")
output = self.d.check_output(self.output)
oc_plist = {}
cl_plist = {}
# Check for the plists
if os.path.isfile(os.path.join(output,"patches_OC.plist")):
e = os.path.join(output,"patches_OC.plist")
with open(e, "rb") as f:
oc_plist = plist.load(f)
if os.path.isfile(os.path.join(output,"patches_Clover.plist")):
e = os.path.join(output,"patches_Clover.plist")
with open(e,"rb") as f:
cl_plist = plist.load(f)
# Ensure all the pathing is where it needs to be
oc_plist = self.ensure_path(oc_plist,("ACPI","Add"))
oc_plist = self.ensure_path(oc_plist,("ACPI","Patch"))
cl_plist = self.ensure_path(cl_plist,("ACPI","SortedOrder"))
cl_plist = self.ensure_path(cl_plist,("ACPI","DSDT","Patches"))
# Add the .aml references
if replace: # Remove any conflicting entries
oc_plist["ACPI"]["Add"] = [x for x in oc_plist["ACPI"]["Add"] if oc_acpi["Path"] != x["Path"]]
cl_plist["ACPI"]["SortedOrder"] = [x for x in cl_plist["ACPI"]["SortedOrder"] if cl_acpi != x]
if any(oc_acpi["Path"] == x["Path"] for x in oc_plist["ACPI"]["Add"]):
print(" -> Add \"{}\" already in OC plist!".format(oc_acpi["Path"]))
else:
oc_plist["ACPI"]["Add"].append(oc_acpi)
if cl_acpi in cl_plist["ACPI"]["SortedOrder"]:
print(" -> \"{}\" already in Clover plist!".format(cl_acpi))
else:
cl_plist["ACPI"]["SortedOrder"].append(cl_acpi)
# Iterate the patches
for p in patches:
ocp = self.get_oc_patch(p)
cp = self.get_clover_patch(p)
if replace: # Remove any conflicting entries
oc_plist["ACPI"]["Patch"] = [x for x in oc_plist["ACPI"]["Patch"] if ocp["Find"] != x["Find"] and ocp["Replace"] != x["Replace"]]
cl_plist["ACPI"]["DSDT"]["Patches"] = [x for x in cl_plist["ACPI"]["DSDT"]["Patches"] if cp["Find"] != x["Find"] and cp["Replace"] != x["Replace"]]
if any(x["Find"] == ocp["Find"] and x["Replace"] == ocp["Replace"] for x in oc_plist["ACPI"]["Patch"]):
print(" -> Patch \"{}\" already in OC plist!".format(p["Comment"]))
else:
print(" -> Adding Patch \"{}\" to OC plist!".format(p["Comment"]))
oc_plist["ACPI"]["Patch"].append(ocp)
if any(x["Find"] == cp["Find"] and x["Replace"] == cp["Replace"] for x in cl_plist["ACPI"]["DSDT"]["Patches"]):
print(" -> Patch \"{}\" already in Clover plist!".format(p["Comment"]))
else:
print(" -> Adding Patch \"{}\" to Clover plist!".format(p["Comment"]))
cl_plist["ACPI"]["DSDT"]["Patches"].append(cp)
# Write the plists
with open(os.path.join(output,"patches_OC.plist"),"wb") as f:
plist.dump(oc_plist,f)
with open(os.path.join(output,"patches_Clover.plist"),"wb") as f:
plist.dump(cl_plist,f)
def patch_warn(self):
# Warn users to ensure they merge the patches_XX.plist contents with their config.plist
print("\n\u001b[41;1m!! WARNING !!\u001b[0m Make sure you merge the contents of patches_[OC/Clover].plist")
print(" with your config.plist!\n")
def fake_ec(self, laptop = False):
rename = False
if not self.ensure_dsdt():
return
self.u.head("Fake EC")
print("")
print("Locating PNP0C09 (EC) devices...")
ec_list = self.d.get_device_paths_with_hid("PNP0C09")
ec_to_patch = []
patches = []
lpc_name = None
if len(ec_list):
lpc_name = ".".join(ec_list[0][0].split(".")[:-1])
print(" - Got {}".format(len(ec_list)))
print(" - Validating...")
for x in ec_list:
device = x[0]
print(" --> {}".format(device))
if device.split(".")[-1] == "EC":
if laptop:
print(" ----> Named EC device located - no fake needed.")
print("")
self.u.grab("Press [enter] to return to main menu...")
return
print(" ----> EC called EC. Renaming")
device = ".".join(device.split(".")[:-1]+["EC0"])
rename = True
scope = "\n".join(self.d.get_scope(x[1],strip_comments=True))
# We need to check for _HID, _CRS, and _GPE
if all((y in scope for y in ["_HID","_CRS","_GPE"])):
print(" ----> Valid EC Device")
sta = self.d.get_method_paths(device+"._STA")
if len(sta):
print(" ----> Contains _STA method. Skipping")
continue
if not laptop:
ec_to_patch.append(device)
else:
print(" ----> NOT Valid EC Device")
else:
print(" - None found - only needs a Fake EC device")
print("Locating LPC(B)/SBRG...")
if lpc_name == None:
for x in ("LPCB", "LPC0", "LPC", "SBRG", "PX40"):
try:
lpc_name = self.d.get_device_paths(x)[0][0]
break
except: pass
if not lpc_name:
print(" - Could not locate LPC(B)! Aborting!")
print("")
self.u.grab("Press [enter] to return to main menu...")
return
print(" - Found {}".format(lpc_name))
comment = "SSDT-EC"
if rename == True:
patches.append({"Comment":"EC to EC0","Find":"45435f5f","Replace":"4543305f"})
comment += " (Needs EC to EC0 rename)"
oc = {"Comment":comment,"Enabled":True,"Path":"SSDT-EC.aml"}
self.make_plist(oc, "SSDT-EC.aml", patches)
print("Creating SSDT-EC...")
ssdt = """
DefinitionBlock ("", "SSDT", 2, "CORP ", "SsdtEC", 0x00001000)
{
External ([[LPCName]], DeviceObj)
""".replace("[[LPCName]]",lpc_name)
for x in ec_to_patch:
ssdt += " External ({}, DeviceObj)\n".format(x)
# Walk them again and add the _STAs
for x in ec_to_patch:
ssdt += """
Scope ([[ECName]])
{
Method (_STA, 0, NotSerialized) // _STA: Status
{
If (_OSI ("Darwin"))
{
Return (0)
}
Else
{
Return (0x0F)
}
}
}
""".replace("[[LPCName]]",lpc_name).replace("[[ECName]]",x)
# Create the faked EC
ssdt += """
Scope ([[LPCName]])
{
Device (EC)
{
Name (_HID, "ACID0001") // _HID: Hardware ID
Method (_STA, 0, NotSerialized) // _STA: Status
{
If (_OSI ("Darwin"))
{
Return (0x0F)
}
Else
{
Return (Zero)
}
}
}
}
}""".replace("[[LPCName]]",lpc_name)
self.write_ssdt("SSDT-EC",ssdt)
print("")
print("Done.")
self.patch_warn()
self.u.grab("Press [enter] to return...")
def plugin_type(self):
if not self.ensure_dsdt():
return
self.u.head("Plugin Type")
print("")
ssdt_name = "SSDT-PLUG"
print("Determining CPU name scheme...")
try: cpu_name = self.d.get_processor_paths("")[0][0]
except: cpu_name = None
if cpu_name:
print(" - Found {}".format(cpu_name))
oc = {"Comment":"Sets plugin-type to 1 on first Processor object","Enabled":True,"Path":ssdt_name+".aml"}
print("Creating SSDT-PLUG...")
ssdt = """//
// Based on the sample found at https://github.com/acidanthera/OpenCorePkg/blob/master/Docs/AcpiSamples/SSDT-PLUG.dsl
//
DefinitionBlock ("", "SSDT", 2, "CORP", "CpuPlug", 0x00003000)
{
External ([[CPUName]], ProcessorObj)
Scope ([[CPUName]])
{
If (_OSI ("Darwin")) {
Method (_DSM, 4, NotSerialized) // _DSM: Device-Specific Method
{
If (!Arg2)
{
Return (Buffer (One)
{
0x03
})
}
Return (Package (0x02)
{
"plugin-type",
One
})
}
}
}
}""".replace("[[CPUName]]",cpu_name)
else:
ssdt_name += "-ALT"
print("No Processor objects found...")
print("Checking for ACPI0007 devices...")
procs = self.d.get_device_paths_with_hid(hid="ACPI0007")
if not procs:
print("Could not find any Processor objects or ACPI0007 devices!")
print("")
self.u.grab("Press [enter] to return...")
return
parent = procs[0][0].split(".")[0]
print("Got {:,} with parent {}, iterating...".format(len(procs),parent))
proc_list = []
for proc in procs:
print(" - Checking {}...".format(proc[0].split(".")[-1]))
uid = self.d.get_path_of_type(obj_type="Name",obj=proc[0]+"._UID")
if not uid:
print(" --> Not found! Skipping...")
continue
# Let's get the actual _UID value
try:
_uid = self.d.dsdt_lines[uid[0][1]].split("_UID, ")[1].split(")")[0]
print(" --> _UID: {}".format(_uid))
proc_list.append((proc[0],_uid))
except:
print(" --> Not found! Skipping...")
if not proc_list:
print("No valid processor devices found! Aborting...")
print("")
self.u.grab("Press [enter] to return...")
return
print("Iterating {:,} valid processor device{}...".format(len(proc_list),"" if len(proc_list)==1 else "s"))
ssdt = """//
// Based on the sample found at https://github.com/acidanthera/OpenCorePkg/blob/master/Docs/AcpiSamples/Source/SSDT-PLUG-ALT.dsl
//
DefinitionBlock ("", "SSDT", 2, "CORP", "CpuPlugA", 0x00003000)
{
External ([[parent]], DeviceObj)
Scope ([[parent]])
{""".replace("[[parent]]",parent)
# Walk the processor objects, and add them to the SSDT
for i,proc_uid in enumerate(proc_list):
proc,uid = proc_uid
adr = hex(i)[2:].upper()
name = "CP00"[:-len(adr)]+adr
ssdt+="""
Processor ([[name]], [[uid]], 0x00000510, 0x06)
{
// [[proc]]
Name (_HID, "ACPI0007" /* Processor Device */) // _HID: Hardware ID
Name (_UID, [[uid]])
Method (_STA, 0, NotSerialized) // _STA: Status
{
If (_OSI ("Darwin"))
{
Return (0x0F)
}
Else
{
Return (Zero)
}
}""".replace("[[name]]",name).replace("[[uid]]",uid).replace("[[proc]]",proc)
if i == 0: # Got the first, add plugin-type as well
ssdt += """
Method (_DSM, 4, NotSerialized)
{
If (LEqual (Arg2, Zero)) {
Return (Buffer (One) { 0x03 })
}
Return (Package (0x02)
{
"plugin-type",
One
})
}"""
# Close up the SSDT
ssdt += """
}"""
ssdt += """
}
}"""
oc = {"Comment":"Redefines modern CPU Devices as legacy Processor objects and sets plugin-type to 1 on the first","Enabled":True,"Path":ssdt_name+".aml"}
self.make_plist(oc, ssdt_name+".aml", ())
self.write_ssdt(ssdt_name,ssdt)
print("")
print("Done.")
self.patch_warn()
self.u.grab("Press [enter] to return...")
def list_irqs(self):
# Walks the DSDT keeping track of the current device and
# saving the IRQNoFlags if found
devices = {}
current_device = None
current_hid = None
irq = False
last_irq = False
irq_index = 0
for index,line in enumerate(self.d.dsdt_lines):
if self.d.is_hex(line):
# Skip all hex lines
continue
if irq:
# Get the values
num = line.split("{")[1].split("}")[0].replace(" ","")
num = "#" if not len(num) else num
if current_device in devices:
if last_irq: # In a row
devices[current_device]["irq"] += ":"+num
else: # Skipped at least one line
irq_index = self.d.find_next_hex(index)[1]
devices[current_device]["irq"] += "-"+str(irq_index)+"|"+num
else:
irq_index = self.d.find_next_hex(index)[1]
devices[current_device] = {"irq":str(irq_index)+"|"+num}
irq = False
last_irq = True
elif "Device (" in line:
# Check if we retain the _HID here
if current_device and current_device in devices and current_hid:
# Save it
devices[current_device]["hid"] = current_hid
last_irq = False
current_hid = None
try: current_device = line.split("(")[1].split(")")[0]
except:
current_device = None
continue
elif "_HID, " in line and current_device:
try: current_hid = line.split('"')[1]
except: pass
elif "IRQNoFlags" in line and current_device:
# Next line has our interrupts
irq = True
# Check if just a filler line
elif len(line.replace("{","").replace("}","").replace("(","").replace(")","").replace(" ","").split("//")[0]):
# Reset last IRQ as it's not in a row
last_irq = False
# Retain the final _HID if needed
if current_device and current_device in devices and current_hid:
devices[current_device]["hid"] = current_hid
return devices
def get_hex_from_irqs(self, irq, rem_irq = None):
# We need to search for a few different types:
#
# 22 XX XX 22 XX XX 22 XX XX (multiples on different lines)
# 22 XX XX (summed multiples in the same bracket - {0,8,11})
# 22 XX XX (single IRQNoFlags entry)
#
# Can end with 79 [00] (end of method), 86 09 (middle of method) or 47 01 (unknown)
lines = []
remd = []
for a in irq.split("-"):
index,i = a.split("|") # Get the index
index = int(index)
find = self.get_int_for_line(i)
repl = [0]*len(find)
# Now we need to verify if we're patching *all* IRQs, or just some specifics
if rem_irq:
repl = [x for x in find]
matched = []
for x in rem_irq:
# Get the int
rem = self.convert_irq_to_int(x)
repl1 = [y&(rem^0xFFFF) if y >= rem else y for y in repl]
if repl1 != repl:
# Changes were made
remd.append(x)
repl = [y for y in repl1]
# Get the hex
d = {
"irq":i,
"find": "".join(["22"+self.d.get_hex_from_int(x) for x in find]),
"repl": "".join(["22"+self.d.get_hex_from_int(x) for x in repl]),
"remd": remd,
"index": index
}
d["changed"] = not (d["find"]==d["repl"])
lines.append(d)
return lines
def get_int_for_line(self, irq):
irq_list = []
for i in irq.split(":"):
irq_list.append(self.same_line_irq(i))
return irq_list
def convert_irq_to_int(self, irq):
b = "0"*(16-irq)+"1"+"0"*(irq)
return int(b,2)
def same_line_irq(self, irq):
# We sum the IRQ values and return the int
total = 0
for i in irq.split(","):
if i == "#":
continue # Null value
try: i=int(i)
except: continue # Not an int
if i > 15 or i < 0:
continue # Out of range
total = total | self.convert_irq_to_int(i)
return total
def get_all_irqs(self, irq):
irq_list = []
for a in irq.split("-"):
i = a.split("|")[1]
for x in i.split(":"):
for y in x.split(","):
if y == "#":
continue
irq_list.append(int(y))
return irq_list
def get_data(self, data):
if sys.version_info >= (3, 0):
return data
else:
return plistlib.Data(data)
def get_clover_patch(self, patch):
return {
"Comment": patch["Comment"],
"Disabled": patch.get("Disabled",False),
"Find": self.get_data(self.d.get_hex_bytes(patch["Find"])),
"Replace": self.get_data(self.d.get_hex_bytes(patch["Replace"]))
}
def get_oc_patch(self, patch):
zero = self.get_data(self.d.get_hex_bytes("00000000"))
return {
"Base": "",
"BaseSkip": 0,
"Comment": patch["Comment"],
"Count": 0,
"Enabled": patch.get("Enabled",True),
"Find": self.get_data(self.d.get_hex_bytes(patch["Find"])),
"Limit": 0,
"Mask": self.get_data(b""),
"OemTableId": zero,
"Replace": self.get_data(self.d.get_hex_bytes(patch["Replace"])),
"ReplaceMask": self.get_data(b""),
"Skip": 0,
"TableLength": 0,
"TableSignature": zero
}
def get_irq_choice(self, irqs):
hid_pad = max((len(irqs[x].get("hid","")) for x in irqs))
names_and_hids = ["PIC","IPIC","TMR","TIMR","RTC","RTC0","RTC1","PNPC0000","PNP0100","PNP0B00"]
defaults = [x for x in irqs if x.upper() in names_and_hids or irqs[x].get("hid","").upper() in names_and_hids]
while True:
pad = 24
self.u.head("Select IRQs To Nullify")
print("")
print("Current Legacy IRQs:")
print("")
if not len(irqs):
print(" - None Found")
pad+=len(irqs) if len(irqs) else 1
for x in irqs:
if not hid_pad:
print(" {} {}: {}".format(
"*" if x.upper() in names_and_hids else " ",
x.rjust(4," "),
self.get_all_irqs(irqs[x]["irq"])
))
else:
print(" {} {} {}: {}".format(
"*" if x.upper() in names_and_hids or irqs[x].get("hid","").upper() in names_and_hids else " ",
x.rjust(4," "),
("- "+irqs[x].get("hid","").rjust(hid_pad," ")) if irqs[x].get("hid") else "".rjust(hid_pad+2," "),
self.get_all_irqs(irqs[x]["irq"])
))
print("")
print("C. Only Conflicting IRQs from Legacy Devices ({} from * devices)".format(",".join([str(x) for x in self.target_irqs]) if len(self.target_irqs) else "None"))
print("O. Only Conflicting IRQs ({})".format(",".join([str(x) for x in self.target_irqs]) if len(self.target_irqs) else "None"))
print("L. Legacy IRQs (from * devices)")
print("N. None")
print("")
print("M. Main Menu")
print("Q. Quit")
print("")
print("* Indicates a typically troublesome device")
print("You can also type your own list of Devices and IRQs")
print("The format is DEV1:IRQ1,IRQ2 DEV2:IRQ3,IRQ4")
print("You can omit the IRQ# to remove all from that device (DEV1: DEV2:1,2,3)")
print("For example, to remove IRQ 0 from RTC, all from IPIC, and 8 and 11 from TMR:\n")
print("RTC:0 IPIC: TMR:8,11")
self.u.resize(self.w, max(pad,self.h))
menu = self.u.grab("Please select an option (default is C): ")
if not len(menu):
menu = "c"
if menu.lower() == "m": return None
elif menu.lower() == "q":
self.u.resize(self.w,self.h)
self.u.custom_quit()
d = {}
if menu.lower() == "n":
pass # Don't populate d at all
elif menu.lower() == "o":
for x in irqs:
d[x] = self.target_irqs
elif menu.lower() == "l":
for x in defaults:
d[x] = []
elif menu.lower() == "c":
for x in defaults:
d[x] = self.target_irqs
else:
# User supplied
for i in menu.split(" "):
if not len(i):
continue
try:
name,val = i.split(":")
val = [int(x) for x in val.split(",") if len(x)]
except Exception as e:
# Incorrectly formatted
print("!! Incorrect Custom IRQ List Format !!\n - {}".format(e))
d = None
break
d[name.upper()] = val
if d == None:
continue
self.u.resize(self.w,self.h)
return d
def fix_hpet(self):
if not self.ensure_dsdt():
return
self.u.head("Fix HPET")
print("")
print("Locating PNP0103 (HPET) devices...")
hpets = self.d.get_device_paths_with_hid("PNP0103")
hpet_fake = not hpets
if hpets:
name = hpets[0][0]
print("Locating HPET's _CRS Method/Name...")
hpet = self.d.get_method_paths(name+"._CRS") or self.d.get_name_paths(name+"._CRS")
if not hpet:
print(" - Could not locate {}._CRS! Aborting!".format(name))
# Check for XCRS to see if the rename is already applied
if self.d.get_method_paths(name+".XCRS") or self.d.get_name_paths(name+".XCRS"):
print(" --> Appears to already be named XCRS!")
print("")
self.u.grab("Press [enter] to return to main menu...")
return
print(" - Located at {}._CRS".format(name))
crs_index = self.d.find_next_hex(hpet[0][1])[1]
print(" - Found at index {}".format(crs_index))
print(" - Type: {}".format(hpet[0][-1]))
# Let's find the Memory32Fixed portion within HPET's _CRS method
print(" - Checking for Memory32Fixed...")
mem_base = mem_length = primed = None
for line in self.d.get_scope(hpets[0][1],strip_comments=True):
if "Memory32Fixed (" in line:
primed = True
continue
if not primed:
continue
elif ")" in line: # Reached the end of the scope
break
# We're primed, and not at the end - let's try to get the base and length
try:
val = line.strip().split(",")[0].replace("Zero","0x0").replace("One","0x1")
check = int(val,16)
except:
# Couldn't convert to an int - likely using vars, fall back to defaults
print(" --> Could not convert Base or Length to Integer!")
break
# Set them in order
if mem_base is None:
mem_base = val
else:
mem_length = val
break # Leave after we get both values
# Check if we found the values
got_mem = mem_base and mem_length
if got_mem:
print(" --> Got {} -> {}".format(mem_base,mem_length))
else:
mem_base = "0xFED00000"
mem_length = "0x00000400"
print(" --> Not located!")
print(" --> Using defaults {} -> {}".format(mem_base,mem_length))
crs = "5F435253"
xcrs = "58435253"
padl,padr = self.d.get_shortest_unique_pad(crs, crs_index)
patches = [{"Comment":"{} _CRS to XCRS Rename".format(name.split(".")[-1]),"Find":padl+crs+padr,"Replace":padl+xcrs+padr}]
else:
print(" - None located!")
print(" - Locating LPC(B)/SBRG...")
ec_list = self.d.get_device_paths_with_hid("PNP0C09")
name = None
if len(ec_list):
name = ".".join(ec_list[0][0].split(".")[:-1])
if name == None:
for x in ("LPCB", "LPC0", "LPC", "SBRG", "PX40"):
try:
name = self.d.get_device_paths(x)[0][0]
break
except: pass
if not name:
print(" - Could not locate LPC(B)! Aborting!")
print("")
self.u.grab("Press [enter] to return to main menu...")
return
patches = []
devs = self.list_irqs()
target_irqs = self.get_irq_choice(devs)
if target_irqs is None: return # Bailed, going to the main menu
self.u.head("Creating IRQ Patches")
print("")
if not hpet_fake:
print(" - {} _CRS to XCRS Rename:".format(name.split(".")[-1]))
print(" Find: {}".format(padl+crs+padr))
print(" Replace: {}".format(padl+xcrs+padr))
print("")
print("Checking IRQs...")
print("")
if not devs:
print(" - Nothing to patch!")
print("")
# Let's apply patches as we go
saved_dsdt = self.d.dsdt_raw
unique_patches = {}
generic_patches = []
for dev in devs:
if not dev in target_irqs:
continue
irq_patches = self.get_hex_from_irqs(devs[dev]["irq"],target_irqs[dev])
i = [x for x in irq_patches if x["changed"]]
for a,t in enumerate(i):
if not t["changed"]:
# Nothing patched - skip
continue
# Try our endings here - 7900, 8609, and 4701 - also allow for up to 8 chars of pad (thanks MSI)
matches = re.findall("("+t["find"]+"(.{0,8})(7900|4701|8609))",self.d.get_hex_starting_at(t["index"])[0])
if not len(matches):
print("Missing IRQ Patch ending for {} ({})! Skipping...".format(dev,t["find"]))
continue
if len(matches) > 1:
# Found too many matches!
# Add them all as find/replace entries
for x in matches:
generic_patches.append({
"remd":",".join([str(y) for y in set(t["remd"])]),
"orig":t["find"],
"find":t["find"]+"".join(x[1:]),
"repl":t["repl"]+"".join(x[1:])
})
continue
ending = "".join(matches[0][1:])
padl,padr = self.d.get_shortest_unique_pad(t["find"]+ending, t["index"])
t_patch = padl+t["find"]+ending+padr
r_patch = padl+t["repl"]+ending+padr
if not dev in unique_patches:
unique_patches[dev] = []
unique_patches[dev].append({
"dev":dev,
"remd":",".join([str(y) for y in set(t["remd"])]),
"orig":t["find"],
"find":t_patch,
"repl":r_patch
})
# Walk the unique patches if any
if len(unique_patches):
for x in unique_patches:
for i,p in enumerate(unique_patches[x]):
patch_name = "{} IRQ {} Patch".format(x, p["remd"])
if len(unique_patches[x]) > 1:
patch_name += " - {} of {}".format(i+1, len(unique_patches[x]))
patches.append({"Comment":patch_name,"Find":p["find"],"Replace":p["repl"]})
print(" - {}".format(patch_name))
print(" Find: {}".format(p["find"]))
print(" Replace: {}".format(p["repl"]))
print("")
# Walk the generic patches if any
if len(generic_patches):
generic_set = [] # Make sure we don't repeat find values
for x in generic_patches:
if x in generic_set:
continue
generic_set.append(x)
print("The following may not be unique and are disabled by default!")
print("")
for i,x in enumerate(generic_set):
patch_name = "Generic IRQ Patch {} of {} - {} - {}".format(i+1,len(generic_set),x["remd"],x["orig"])
patches.append({"Comment":patch_name,"Find":x["find"],"Replace":x["repl"],"Disabled":True,"Enabled":False})
print(" - {}".format(patch_name))
print(" Find: {}".format(x["find"]))
print(" Replace: {}".format(x["repl"]))
print("")
# Restore the original DSDT in memory
self.d.dsdt_raw = saved_dsdt
oc = {"Comment":"{} _CRS (Needs _CRS to XCRS Rename)".format(name.split(".")[-1]),"Enabled":True,"Path":"SSDT-HPET.aml"}
self.make_plist(oc, "SSDT-HPET.aml", patches)
print("Creating SSDT-HPET...")
if hpet_fake:
ssdt = """// Fake HPET device
//
DefinitionBlock ("", "SSDT", 2, "CORP", "HPET", 0x00000000)
{
External ([[name]], DeviceObj)
Scope ([[name]])
{
Device (HPET)
{
Name (_HID, EisaId ("PNP0103") /* HPET System Timer */) // _HID: Hardware ID
Name (_CID, EisaId ("PNP0C01") /* System Board */) // _CID: Compatible ID
Method (_STA, 0, NotSerialized) // _STA: Status
{
If (_OSI ("Darwin"))
{
Return (0x0F)
}
Else
{
Return (Zero)
}
}
Name (_CRS, ResourceTemplate () // _CRS: Current Resource Settings
{
IRQNoFlags ()
{0,8,11}
Memory32Fixed (ReadWrite,
0xFED00000, // Address Base
0x00000400, // Address Length
)
})
}
}
}""".replace("[[name]]",name)
else:
ssdt = """//
// Supplementary HPET _CRS from Goldfish64
// Requires the HPET's _CRS to XCRS rename
//
DefinitionBlock ("", "SSDT", 2, "CORP", "HPET", 0x00000000)
{
External ([[name]], DeviceObj)
External ([[name]].XCRS, [[type]])
Scope ([[name]])
{
Name (BUFX, ResourceTemplate ()
{
IRQNoFlags ()
{0,8,11}
Memory32Fixed (ReadWrite,
// [[mem]]
[[mem_base]], // Address Base
[[mem_length]], // Address Length
)
})
Method (_CRS, 0, Serialized)
{
// Return our buffer if booting macOS or the XCRS method
// no longer exists for some reason
If (_OSI ("Darwin") || ! CondRefOf ([[name]].XCRS))
{
Return (BUFX)
}
// Not macOS and XCRS exists - return its result
Return ([[name]].XCRS[[method]])
}
}
}""".replace("[[name]]",name) \
.replace("[[type]]","MethodObj" if hpet[0][-1] == "Method" else "BuffObj") \
.replace("[[mem]]","Base/Length pulled from DSDT" if got_mem else "Default Base/Length - verify with your DSDT!") \
.replace("[[mem_base]]",mem_base) \
.replace("[[mem_length]]",mem_length) \
.replace("[[method]]"," ()" if hpet[0][-1]=="Method" else "")
self.write_ssdt("SSDT-HPET",ssdt)
print("")
print("Done.")
self.patch_warn()
self.u.grab("Press [enter] to return...")
def ssdt_pmc(self):
if not self.ensure_dsdt():
return
self.u.head("SSDT PMC")
print("")
print("Locating LPC(B)/SBRG...")
ec_list = self.d.get_device_paths_with_hid("PNP0C09")
lpc_name = None
if len(ec_list):
lpc_name = ".".join(ec_list[0][0].split(".")[:-1])
if lpc_name == None:
for x in ("LPCB", "LPC0", "LPC", "SBRG", "PX40"):
try:
lpc_name = self.d.get_device_paths(x)[0][0]
break
except: pass
if not lpc_name:
print(" - Could not locate LPC(B)! Aborting!")
print("")
self.u.grab("Press [enter] to return to main menu...")
return
print(" - Found {}".format(lpc_name))
oc = {"Comment":"PMCR for native 300-series NVRAM","Enabled":True,"Path":"SSDT-PMC.aml"}
self.make_plist(oc, "SSDT-PMC.aml", ())
print("Creating SSDT-PMC...")
ssdt = """//
// SSDT-PMC source from Acidanthera
// Original found here: https://github.com/acidanthera/OpenCorePkg/blob/master/Docs/AcpiSamples/SSDT-PMC.dsl
//
// Uses the CORP name to denote where this was created for troubleshooting purposes.
//
DefinitionBlock ("", "SSDT", 2, "CORP", "PMCR", 0x00001000)
{
External ([[LPCName]], DeviceObj)
Scope ([[LPCName]])
{
Device (PMCR)
{
Name (_HID, EisaId ("APP9876")) // _HID: Hardware ID
Method (_STA, 0, NotSerialized) // _STA: Status
{
If (_OSI ("Darwin"))
{
Return (0x0B)
}
Else
{
Return (Zero)
}
}
Name (_CRS, ResourceTemplate () // _CRS: Current Resource Settings
{
Memory32Fixed (ReadWrite,
0xFE000000, // Address Base
0x00010000, // Address Length
)
})
}
}
}""".replace("[[LPCName]]",lpc_name)
self.write_ssdt("SSDT-PMC",ssdt)
print("")
print("Done.")
self.patch_warn()
self.u.grab("Press [enter] to return...")
def get_sta_var(self,var="STAS",dev_hid="ACPI000E",dev_name="AWAC"):
# Helper to check for a device, check for (and qualify) an _STA method,
# and look for a specific variable in the _STA scope
#
# Returns a dict with device info - only "valid" parameter is
# guaranteed.
print("Locating {} ({}) devices...".format(dev_hid,dev_name))
dev_list = self.d.get_device_paths_with_hid(dev_hid)
has_var = False
patches = []
root = None
if not len(dev_list):
print(" - Could not locate any {} devices".format(dev_hid))
return {"valid":False}
dev = dev_list[0]
root = dev[0].split(".")[0]