-
-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathmain.py
More file actions
1264 lines (1093 loc) · 49.7 KB
/
main.py
File metadata and controls
1264 lines (1093 loc) · 49.7 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
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
#!/usr/bin/python3
# SPDX-License-Identifier: MIT
import os, os.path, shlex, subprocess, sys, time, termios, json, getpass, reporting
from dataclasses import dataclass
import system, osenum, stub, diskutil, osinstall, asahi_firmware, m1n1, bugs
from urlcache import NetworkError
from util import *
PART_ALIGN = psize("1MiB")
STUB_SIZE = align_down(psize("2.5GB"), PART_ALIGN)
# Minimum free space to leave when resizing, to allow for OS upgrades
MIN_FREE_OS = psize("38GB")
# Minimum free space to leave for non-OS containers
MIN_FREE = psize("1GB")
# 2.5GB stub + 5GB OS + 0.5GB EFI = 8GB, round up to 10GB
MIN_INSTALL_FREE = psize("10GB")
MIN_MACOS_VERSION = "13.5"
MIN_MACOS_VERSION_EXPERT = "12.3"
@dataclass
class IPSW:
version: str
min_macos: str
min_iboot: str
min_sfr: str
expert_only: bool
devices: list
url: str
@dataclass
class Device:
min_ver: str
expert_only: bool
CHIP_MIN_VER = {
0x8103: "11.0", # T8103, M1
0x6000: "12.0", # T6000, M1 Pro
0x6001: "12.0", # T6001, M1 Max
0x6002: "12.3", # T6002, M1 Ultra
0x8112: "12.4", # T8112, M2
0x6020: "13.1", # T6020, M2 Pro
0x6021: "13.1", # T6021, M2 Max
0x6022: "13.4", # T6022, M2 Ultra
}
DEVICES = {
"j274ap": Device("11.0", False), # Mac mini (M1, 2020)
"j293ap": Device("11.0", False), # MacBook Pro (13-inch, M1, 2020)
"j313ap": Device("11.0", False), # MacBook Air (M1, 2020)
"j456ap": Device("11.3", False), # iMac (24-inch, M1, 2021)
"j457ap": Device("11.3", False), # iMac (24-inch, M1, 2021)
"j314cap": Device("12.0", False), # MacBook Pro (14-inch, M1 Max, 2021)
"j314sap": Device("12.0", False), # MacBook Pro (14-inch, M1 Pro, 2021)
"j316cap": Device("12.0", False), # MacBook Pro (16-inch, M1 Max, 2021)
"j316sap": Device("12.0", False), # MacBook Pro (16-inch, M1 Pro, 2021)
"j375cap": Device("12.3", False), # Mac Studio (M1 Max, 2022)
"j375dap": Device("12.3", False), # Mac Studio (M1 Ultra, 2022)
"j413ap": Device("12.4", False), # MacBook Air (M2, 2022)
"j493ap": Device("12.4", False), # MacBook Pro (13-inch, M2, 2022)
"j414cap": Device("13.2", False), # MacBook Pro (14-inch, M2 Max, 2023)
"j414sap": Device("13.2", False), # MacBook Pro (14-inch, M2 Pro, 2023)
"j416cap": Device("13.2", False), # MacBook Pro (16-inch, M2 Max, 2023)
"j416sap": Device("13.2", False), # MacBook Pro (16-inch, M2 Pro, 2023)
"j473ap": Device("13.2", False), # Mac mini (M2, 2023)
"j474sap": Device("13.2", False), # Mac mini (M2 Pro, 2023)
"j415ap": Device("13.4", False), # MacBook Air (15-inch, M2, 2023)
"j475cap": Device("13.4", False), # Mac Studio (M2 Max, 2023)
"j475dap": Device("13.4", False), # Mac Studio (M2 Ultra, 2023)
"j180dap": Device("13.4", True), # Mac Pro (M2 Ultra, 2023)
}
IPSW_VERSIONS = [
IPSW("12.3.1",
"12.1",
"iBoot-7459.101.3",
"21.5.258.0.0,0",
False,
None,
"https://updates.cdn-apple.com/2022SpringFCS/fullrestores/002-79219/851BEDF0-19DB-4040-B765-0F4089D1530D/UniversalMac_12.3.1_21E258_Restore.ipsw"),
IPSW("12.3",
"12.1",
"iBoot-7459.101.2",
"21.5.230.0.0,0",
False,
None,
"https://updates.cdn-apple.com/2022SpringFCS/fullrestores/071-08757/74A4F2A1-C747-43F9-A22A-C0AD5FB4ECB6/UniversalMac_12.3_21E230_Restore.ipsw"),
IPSW("13.5",
"13.0",
"iBoot-8422.141.2",
"22.7.74.0.0,0",
False,
None,
"https://updates.cdn-apple.com/2023SummerFCS/fullrestores/032-69606/D3E05CDF-E105-434C-A4A1-4E3DC7668DD0/UniversalMac_13.5_22G74_Restore.ipsw"),
]
class InstallerMain:
def __init__(self, version):
self.version = version
self.data = json.load(open("installer_data.json"))
self.credentials_validated = False
self.expert = False
self.ipsw = None
self.osins = None
self.osi = None
self.m1n1 = "boot/m1n1.bin"
self.m1n1_ver = m1n1.get_version(self.m1n1)
self.sys_disk = None
self.cur_disk = None
def input(self):
self.flush_input()
return input()
def get_size(self, prompt, default=None, min=None, max=None, total=None):
self.flush_input()
if default is not None:
prompt += f" ({default})"
new_size = input_prompt(prompt + f": ").strip()
try:
if default is not None and not new_size:
new_size = default
if new_size.lower() == "min" and min is not None:
val = min
elif new_size.lower() == "max" and max is not None:
val = max
elif new_size.endswith("%") and total is not None:
val = int(float(new_size[:-1]) * total / 100)
elif new_size.endswith("B"):
val = psize(new_size.upper())
else:
val = psize(new_size.upper() + "B")
except Exception as e:
print(e)
val = None
if val is None:
p_error(f"Invalid size '{new_size}'.")
return val
def choice(self, prompt, options, default=None):
is_array = False
if isinstance(options, list):
is_array = True
options = {str(i+1): v for i, v in enumerate(options)}
if default is not None:
default += 1
int_keys = all(isinstance(i, int) for i in options.keys())
for k, v in options.items():
p_choice(f" {col(BRIGHT)}{k}{col(NORMAL)}: {v}")
if default:
prompt += f" ({default})"
while True:
self.flush_input()
res = input_prompt(prompt + ": ").strip()
if res == "" and default is not None:
res = str(default)
if res not in options:
p_warning(f"Enter one of the following: {', '.join(map(str, options.keys()))}")
continue
print()
if is_array:
return int(res) - 1
else:
return res
def yesno(self, prompt, default=False):
if default:
prompt += " (Y/n): "
else:
prompt += " (y/N): "
while True:
self.flush_input()
res = input_prompt(prompt).strip()
if not res:
return default
elif res.lower() in ("y", "yes", "1", "true"):
return True
elif res.lower() in ("n", "no", "0", "false"):
return False
p_warning(f"Please enter 'Y' or 'N'")
def check_cur_os(self):
if self.cur_os is None:
p_error("Unable to determine primary OS.")
p_error("This installer requires you to already have a macOS install with")
p_error("at least one administrator user that is a machine owner.")
p_error("Please run this installer from your main macOS instance or its")
p_error("paired recovery, or ensure the default boot volume is set correctly.")
sys.exit(1)
p_progress(f"Using OS '{self.cur_os.label}' ({self.cur_os.sys_volume}) for machine authentication.")
logging.info(f"Current OS: {self.cur_os.label} / {self.cur_os.sys_volume}")
if not self.cur_os.admin_users or self.cur_os.admin_users == ["_mbsetupuser"] or (
self.sysinfo.boot_mode == "macOS" and self.sysinfo.login_user not in self.cur_os.admin_users):
# Out of date Preboot partition?
p_message(f"Oops, your Preboot volume may be out of date. Fixing that for you...")
p = subprocess.run(["diskutil", "apfs", "updatePreboot", self.cur_os.system], check=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
logging.debug(f"process output: {p.stdout}")
self.cur_os.update_admin_users()
p_message(f"Preboot volume updated.")
if not self.cur_os.admin_users or self.cur_os.admin_users == ["_mbsetupuser"]:
p_error("No admin users found in the primary OS. Cannot continue.")
p_message("If this is a new or freshly reset machine, you will have to go through macOS")
p_message("initial user set-up and create an admin user before using this installer.")
sys.exit(1)
if self.sysinfo.boot_mode == "macOS" and self.sysinfo.login_user not in self.cur_os.admin_users:
p_error(f"Your login user {self.sysinfo.login_user} is not a machine admin.")
print()
p_info(f"These users are machine admins: {' '.join(self.cur_os.admin_users)}")
print()
p_message(f"You have to be a machine admin to install {DISTRO}.")
sys.exit(1)
def get_admin_credentials(self):
if self.credentials_validated:
return
print()
p_message("To continue the installation, you will need to enter your macOS")
p_message("admin credentials.")
print()
if self.sysinfo.boot_mode == "macOS":
self.admin_user = self.sysinfo.login_user
else:
if len(self.cur_os.admin_users) > 1:
p_question("Choose an admin user for authentication:")
idx = self.choice("User", self.cur_os.admin_users)
else:
idx = 0
self.admin_user = self.cur_os.admin_users[idx]
self.admin_password = getpass.getpass(f'Password for {self.admin_user}: ')
def action_install_into_container(self, avail_parts):
template = self.choose_os()
containers = {str(i): p.desc for i,p in enumerate(self.parts) if p in avail_parts}
print()
p_question("Choose a container to install into:")
idx = self.choice("Target container", containers)
self.part = self.parts[int(idx)]
ipsw = self.choose_ipsw(template.get("supported_fw", None))
logging.info(f"Chosen IPSW version: {ipsw.version}")
self.ins = stub.StubInstaller(self.sysinfo, self.dutil, self.osinfo)
self.osins = osinstall.OSInstaller(self.dutil, self.data, template)
while True:
try:
self.ins.load_ipsw(ipsw)
self.osins.load_package()
break
except NetworkError as e:
logging.error(f"Network error: {e}")
print()
p_error(f"Download failed: {e}")
p_message("Please check your internet connection.")
if not self.yesno("Retry"):
return True
print()
try:
self.do_install()
except NetworkError as e:
self._handle_post_partition_network_error(e)
def action_wipe(self):
p_warning("This will wipe all data on the currently selected disk.")
p_warning("Are you sure you want to continue?")
if not self.yesno("Wipe my disk"):
return True
print()
template = self.choose_os()
self.osins = osinstall.OSInstaller(self.dutil, self.data, template)
while True:
try:
self.osins.load_package()
break
except NetworkError as e:
logging.error(f"Network error: {e}")
print()
p_error(f"Download failed: {e}")
p_message("Please check your internet connection.")
if not self.yesno("Retry"):
return True
print()
min_size = STUB_SIZE + (self.osins.min_size if self.expert else self.osins.min_recommended_size)
print()
p_message(f"Minimum required space for this OS: {ssize(min_size)}")
start, end = self.dutil.get_disk_usable_range(self.cur_disk)
while True:
try:
os_size = self.get_os_size_and_info(end - start, min_size, template)
break
except NetworkError as e:
logging.error(f"Network error: {e}")
print()
p_error(f"Download failed: {e}")
p_message("Please check your internet connection.")
if not self.yesno("Retry"):
return True
print()
p_progress(f"Partitioning the whole disk ({self.cur_disk})")
self.part = self.dutil.partitionDisk(self.cur_disk, "apfs", self.osins.name, STUB_SIZE)
p_progress(f"Creating new stub macOS named {self.osins.name}")
logging.info(f"Creating stub macOS: {self.osins.name}")
try:
self.do_install(os_size)
except NetworkError as e:
self._handle_post_partition_network_error(e)
def action_install_into_free(self, avail_free):
template = self.choose_os()
self.osins = osinstall.OSInstaller(self.dutil, self.data, template)
while True:
try:
self.osins.load_package()
break
except NetworkError as e:
logging.error(f"Network error: {e}")
print()
p_error(f"Download failed: {e}")
p_message("Please check your internet connection.")
if not self.yesno("Retry"):
return True
print()
min_size = STUB_SIZE + (self.osins.min_size if self.expert else self.osins.min_recommended_size)
print()
p_message(f"Minimum required space for this OS: {ssize(min_size)}")
frees = {str(i): p.desc for i,p in enumerate(self.parts)
if p in avail_free and align_down(p.size, PART_ALIGN) >= min_size}
if len(frees) < 1:
p_error( "There is not enough free space to install this OS.")
print()
p_message("Press enter to go back to the main menu.")
self.input()
return True
if len(frees) > 1:
print()
p_question("Choose a free area to install into:")
idx = self.choice("Target area", frees)
else:
idx = list(frees.keys())[0]
free_part = self.parts[int(idx)]
print()
p_message(f"Available free space: {ssize(free_part.size)}")
while True:
try:
os_size = self.get_os_size_and_info(free_part.size, min_size, template)
break
except NetworkError as e:
logging.error(f"Network error: {e}")
print()
p_error(f"Download failed: {e}")
p_message("Please check your internet connection.")
if not self.yesno("Retry"):
return True
print()
p_progress(f"Creating new stub macOS named {self.osins.name}")
logging.info(f"Creating stub macOS: {self.osins.name}")
self.part = self.dutil.addPartition(free_part.name, "apfs", self.osins.name, STUB_SIZE)
try:
self.do_install(os_size)
except NetworkError as e:
self._handle_post_partition_network_error(e)
def get_os_size_and_info(self, free_size, min_size, template):
os_size = None
if self.osins.expandable:
print()
p_question("How much space should be allocated to the new OS?")
p_message(" You can enter a size such as '1GB', a fraction such as '50%',")
p_message(" the word 'min' for the smallest allowable size, or")
p_message(" the word 'max' to use all available space.")
min_perc = 100 * min_size / free_size
while True:
os_size = self.get_size("New OS size", default="max",
min=min_size, max=free_size,
total=free_size)
if os_size is None:
continue
os_size = align_down(os_size, PART_ALIGN)
if os_size < min_size:
p_error(f"Size is too small, please enter a value > {ssize(min_size)} ({min_perc:.2f}%)")
continue
if os_size > free_size:
p_error(f"Size is too large, please enter a value < {ssize(free_size)}")
continue
break
print()
p_message(f"The new OS will be allocated {ssize(os_size)} of space,")
p_message(f"leaving {ssize(free_size - os_size)} of free space.")
os_size -= STUB_SIZE
print()
self.flush_input()
p_question("Enter a name for your OS")
label = input_prompt(f"OS name ({self.osins.name}): ") or self.osins.name
self.osins.name = label
logging.info(f"New OS name: {label}")
print()
ipsw = self.choose_ipsw(template.get("supported_fw", None))
logging.info(f"Chosen IPSW version: {ipsw.version}")
self.ins = stub.StubInstaller(self.sysinfo, self.dutil, self.osinfo)
self.ins.load_ipsw(ipsw)
return os_size
def action_repair_or_upgrade(self, oses, upgrade):
choices = {str(i): f"{p.desc}\n {str(o)}" for i, (p, o) in enumerate(oses)}
if len(choices) > 1:
print()
if upgrade:
p_question("Choose an existing install to upgrade:")
else:
p_question("Choose an incomplete install to repair:")
idx = self.choice("Installed OS", choices)
else:
idx = list(choices.keys())[0]
self.part, osi = oses[int(idx)]
if upgrade:
p_progress(f"Upgrading installation {self.part.name} ({self.part.label})")
p_info(f" Old m1n1 stage 1 version: {osi.m1n1_ver}")
p_info(f" New m1n1 stage 1 version: {self.m1n1_ver}")
print()
else:
p_progress(f"Resuming installation into {self.part.name} ({self.part.label})")
self.ins = stub.StubInstaller(self.sysinfo, self.dutil, self.osinfo)
if not self.ins.check_existing_install(osi):
op = "upgrade" if upgrade else "repair"
p_error( "The existing installation is missing files.")
p_message(f"This tool can only {op} installations that completed the first")
p_message( "stage of the installation process. If it was interrupted, please")
p_message( "delete the partitions manually and reinstall from scratch.")
return False
self.dutil.remount_rw(self.ins.osi.system)
self.ins.repair(self.cur_os)
if upgrade:
# Note: we get the vars out of the boot.bin in the system volume instead of the
# actual installed fuOS. This is arguably the better option, since it allows
# users to fix their install using this functionality if they messed up the boot
# object.
vars = m1n1.extract_vars(self.ins.boot_obj_path)
if vars is None:
p_error("Could not get variables from the installed m1n1")
p_message(f"Path: {self.ins.boot_obj_path}")
return False
p_progress(f"Transferring m1n1 variables:")
for v in vars:
p_info(f" {v}")
print()
m1n1.build(self.m1n1, self.ins.boot_obj_path, vars)
# Unhide the SystemVersion, if hidden
self.ins.prepare_for_bless()
# Go for step2 again
self.step2()
def action_rebuild_vendorfw(self, oses):
choices = {str(i): f"{p.desc}\n {str(o)}" for i, (p, o) in enumerate(oses)}
if len(choices) > 1:
print()
p_question("Choose an install to rebuild firmware for:")
idx = self.choice("Installed OS", choices)
else:
idx = list(choices.keys())[0]
self.part, osi = oses[int(idx)]
self.ins = stub.StubInstaller(self.sysinfo, self.dutil, self.osinfo)
if not self.ins.check_existing_install(osi):
p_error( "The existing installation is missing files.")
p_message(f"This tool can only rebuild firmware on installations that completed the first")
p_message( "stage of the installation process. If it was interrupted, please")
p_message( "delete the partitions manually and reinstall from scratch.")
return False
vars = m1n1.extract_vars(self.ins.boot_obj_path)
if vars is None:
p_error("Could not get variables from the installed m1n1")
p_message(f"Path: {self.ins.boot_obj_path}")
return False
esp_id = None
for var in vars:
k, v = var.split('=')
if k == "chosen.asahi,efi-system-partition":
esp_id = v
break
if esp_id is None:
p_error("Unable to determine the associated EFI system partition for this install.")
p_message("Is first stage m1n1 corrupted?")
return False
target = self.dutil.get_partition_info(esp_id)
mountpoint = self.dutil.mount(target.name)
os.makedirs("vendorfw", exist_ok=True)
fw_pkg = asahi_firmware.core.FWPackage("vendorfw")
ipsw = None
for ver in IPSW_VERSIONS:
if ver.version == osi.version:
ipsw = ver
break
if ipsw is None:
p_error(f"This install is using an unsupported macOS version {osi.version}")
p_message("Unable to rebuild firmware")
return False
try:
self.ins.load_ipsw(ipsw)
self.ins.load_identity()
self.ins.collect_firmware(fw_pkg)
except NetworkError as e:
logging.error(f"Network error during firmware rebuild: {e}")
print()
p_error(f"Firmware rebuild failed: {e}")
p_message("Please check your internet connection and try again.")
print()
p_message("Press enter to return to the main menu.")
self.input()
return True
fw_pkg.close()
p_plain(f" Copying firmware into {target.name} partition...")
base = os.path.join(mountpoint, "vendorfw")
logging.info(f"Firmware -> {base}")
shutil.copytree(fw_pkg.path, base, dirs_exist_ok=True)
print()
p_success(f"Firmware rebuild complete. Press enter to continue.")
self.input()
print()
return True
def _handle_post_partition_network_error(self, e):
logging.error(f"Network error during installation: {e}")
print()
p_error("Installation failed due to a network error.")
p_error(f" {e}")
print()
p_message("Please check your internet connection, then re-run the installer.")
p_message("The installer will detect the incomplete installation and offer")
p_message("to repair it.")
print()
p_warning("If you need to file a bug report, please attach the log file:")
p_warning(f" {os.getcwd()}/installer.log")
print()
p_message("Press enter to exit.")
self.input()
sys.exit(1)
def do_install(self, total_size=None):
p_progress(f"Installing stub macOS into {self.part.name} ({self.part.label})")
self.ins.prepare_volume(self.part)
self.ins.check_volume()
self.ins.install_files(self.cur_os)
self.osins.partition_disk(self.part.name, total_size)
pkg = None
if self.osins.needs_firmware:
os.makedirs("vendorfw", exist_ok=True)
pkg = asahi_firmware.core.FWPackage("vendorfw")
self.ins.collect_firmware(pkg)
pkg.close()
self.osins.firmware_package = pkg
self.osins.install(self.ins)
for i in self.osins.idata_targets:
self.ins.collect_installer_data(i)
shutil.copy("installer.log", os.path.join(i, "installer.log"))
self.step2(report=True)
def choose_ipsw(self, supported_fw=None):
sys_iboot = split_ver(self.sysinfo.sys_firmware)
sys_macos = split_ver(self.sysinfo.macos_ver)
sys_sfr = split_ver(self.sysinfo.sfr_full_ver)
chip_min = split_ver(CHIP_MIN_VER.get(self.sysinfo.chip_id, "0"))
device_min = split_ver(self.device.min_ver)
minver = [ipsw for ipsw in IPSW_VERSIONS
if split_ver(ipsw.version) >= max(chip_min, device_min)
and (supported_fw is None or ipsw.version in supported_fw)
and (ipsw.devices is None or self.sysinfo.device_class in ipsw.devices)]
avail = [ipsw for ipsw in minver
if split_ver(ipsw.min_iboot) <= sys_iboot
and split_ver(ipsw.min_macos) <= sys_macos
and split_ver(ipsw.min_sfr) <= sys_sfr
and (not ipsw.expert_only or self.expert)]
minver.sort(key=lambda ipsw: split_ver(ipsw.version))
if not avail:
p_error("Your system firmware is too old.")
p_error(f"Please upgrade to macOS {minver[0].version} or newer.")
sys.exit(1)
if self.expert:
p_question("Choose the macOS version to use for boot firmware:")
p_plain("(If unsure, just press enter)")
p_warning("Picking a non-default option here is UNSUPPORTED and will BREAK YOUR SYSTEM.")
p_warning("DO NOT FILE BUGS. YOU HAVE BEEN WARNED.")
idx = self.choice("Version", [i.version for i in avail], len(avail)-1)
else:
idx = len(avail)-1
self.ipsw = ipsw = avail[idx]
p_message(f"Using macOS {ipsw.version} for OS firmware")
print()
return ipsw
def choose_os(self):
os_list = self.data["os_list"]
if not self.expert:
os_list = [i for i in os_list if not i.get("expert", False)]
if self.cur_disk != self.sys_disk:
os_list = [i for i in os_list if i.get("external_boot", False)]
p_question("Choose an OS to install:")
idx = self.choice("OS", [i["name"] for i in os_list])
os = os_list[idx]
logging.info(f"Chosen OS: {os['name']}")
return os
def set_reduced_security(self):
while True:
self.get_admin_credentials()
print()
p_progress("Preparing the new OS for booting in Reduced Security mode...")
try:
subprocess.run(["bputil", "-g", "-v", self.ins.osi.vgid,
"-u", self.admin_user, "-p", self.admin_password], check=True)
break
except subprocess.CalledProcessError:
p_error("Failed to run bputil. Press enter to try again.")
self.input()
self.credentials_validated = True
print()
def bless(self):
while True:
self.get_admin_credentials()
print()
p_progress("Setting the new OS as the default boot volume...")
try:
subprocess.run(["bless", "--setBoot",
"--device", "/dev/" + self.ins.osi.sys_volume,
"--user", self.admin_user, "--stdinpass"],
input=self.admin_password.encode("utf-8"),
check=True)
break
except subprocess.CalledProcessError:
if self.admin_password.strip() != self.admin_password:
p_warning("Failed to run bless.")
p_warning("This is probably because your password starts or ends with a space,")
p_warning("and that doesn't work due to a silly Apple bug.")
p_warning("Let's try a different way. Sorry, you'll have to type it in again.")
try:
subprocess.run(["bless", "--setBoot",
"--device", "/dev/" + self.ins.osi.sys_volume,
"--user", self.admin_user], check=True)
print()
return
except subprocess.CalledProcessError:
pass
p_error("Failed to run bless. Press enter to try again.")
self.input()
self.credentials_validated = True
print()
def step2(self, report=False):
is_1tr = self.sysinfo.boot_mode == "one true recoveryOS"
is_recovery = "recoveryOS" in self.sysinfo.boot_mode
sys_ver = split_ver(self.sysinfo.macos_ver)
if is_1tr and self.ins.osi.paired:
subprocess.run([self.ins.step2_sh], check=True)
self.bless()
self.step2_completed(report)
elif is_recovery:
self.set_reduced_security()
self.bless()
self.step2_indirect(report)
else:
self.bless()
self.step2_indirect(report)
def flush_input(self):
try:
termios.tcflush(sys.stdin, termios.TCIFLUSH)
except:
pass
def install_info(self, report):
# Hide the new volume until step2 is done
self.ins.prepare_for_step2()
p_success( "Installation successful!")
print()
p_progress("Install information:")
p_info( f" APFS VGID: {col()}{self.ins.osi.vgid}")
if self.osins and self.osins.efi_part:
p_info(f" EFI PARTUUID: {col()}{self.osins.efi_part.uuid.lower()}")
print()
if report:
reporting.report(self)
def step2_completed(self, report=False):
self.install_info(report)
print()
time.sleep(2)
p_prompt( "Press enter to reboot the system.")
self.input()
time.sleep(1)
os.system("shutdown -r now")
def step2_indirect(self, report=False):
# Hide the new volume until step2 is done
self.ins.prepare_for_step2()
self.install_info(report)
p_message( "To be able to boot your new OS, you will need to complete one more step.")
p_warning( "Please read the following instructions carefully. Failure to do so")
p_warning( "will leave your new installation in an unbootable state.")
print()
p_question( "Press enter to continue.")
self.input()
print()
print()
print()
p_message( "When the system shuts down, follow these steps:")
print()
p_message( "1. Wait 25 seconds for the system to fully shut down.")
p_message(f"2. Press and {col(BRIGHT, YELLOW)}hold{col()}{col(BRIGHT)} down the power button to power on the system.")
p_warning( " * It is important that the system be fully powered off before this step,")
p_warning( " and that you press and hold down the button once, not multiple times.")
p_warning( " This is required to put the machine into the right mode.")
p_message( "3. Release it once you see 'Loading startup options...' or a spinner.")
p_message( "4. Wait for the volume list to appear.")
p_message(f"5. Choose '{self.part.label}'.")
p_message( "6. You will briefly see a 'macOS Recovery' dialog.")
p_plain( " * If you are asked to 'Select a volume to recover',")
p_plain( " then choose your normal macOS volume and click Next.")
p_plain( " You may need to authenticate yourself with your macOS credentials.")
p_message(f"7. Once the '{DISTRO} installer' screen appears, follow the prompts.")
print()
p_warning( "If you end up in a bootloop or get a message telling you that macOS needs to")
p_warning( "be reinstalled, that means you didn't follow the steps above properly.")
p_message( "Fully shut down your system without doing anything, and try again.")
p_message( "If in trouble, hold down the power button to boot, select macOS, run")
p_message( "this installer again, and choose the 'p' option to retry the process.")
print()
time.sleep(2)
p_prompt( "Press enter to shut down the system.")
self.input()
time.sleep(1)
os.system("shutdown -h now")
def get_min_free_space(self, p):
if p.os and any(os.version for os in p.os) and not self.expert:
logging.info(" Has OS")
return MIN_FREE_OS
else:
return MIN_FREE
def can_resize(self, p):
logging.info(f"Checking resizability of {p.name}")
if p.type != "Apple_APFS":
logging.info(f" Not APFS or system container")
return False
if p.container is None:
logging.info(f" No container?")
return False
min_space = self.get_min_free_space(p) + psize("500MB")
logging.info(f" Min space required: {min_space}")
free = p.container["CapacityFree"]
logging.info(f" Free space: {free}")
if free <= min_space:
logging.info(f" Cannot resize")
return False
else:
logging.info(f" Can resize")
return True
def action_resize(self, resizable):
choices = {str(i): p.desc for i,p in enumerate(self.parts) if p in resizable}
print()
if len(resizable) > 1 or self.expert:
p_question("Choose an existing partition to resize:")
idx = self.choice("Partition", choices)
target = self.parts[int(idx)]
else:
target = resizable[0]
limits = self.dutil.get_resize_limits(target.name)
total = target.container["CapacityCeiling"]
free = target.container["CapacityFree"]
min_free = self.get_min_free_space(target)
# Minimum size, ignoring APFS snapshots & co, but with a conservative buffer
min_size_raw = align_up(total - free + min_free, PART_ALIGN)
# Minimum size reported by diskutil, considering APFS snapshots & co but with a less conservative buffer
min_size_safe = limits["MinimumSizePreferred"]
min_size = max(min_size_raw, min_size_safe)
overhead = min_size - min_size_raw
avail = total - min_size
min_perc = 100 * min_size / total
assert free > min_free
p_message( "We're going to resize this partition:")
p_message(f" {target.desc}")
p_info( f" Total size: {col()}{ssize(total)}")
p_info( f" Free space: {col()}{ssize(free)}")
p_info( f" Available space: {col()}{ssize(avail)}")
p_info( f" Overhead: {col()}{ssize(overhead)}")
p_info( f" Minimum new size: {col()}{ssize(min_size)} ({min_perc:.2f}%)")
print()
if overhead > 16_000_000_000:
p_warning(" Warning: The selected partition has a large amount of overhead space.")
p_warning(" This prevents you from resizing the partition to a smaller size, even")
p_warning(" though macOS reports that space as free.")
print()
p_message(" This is usually caused by APFS snapshots used by Time Machine, which")
p_message(" use up free disk space and block resizing the partition to a smaller")
p_message(" size. It can also be caused by having a pending macOS upgrade.")
print()
p_message(" If you want to resize your partition to a smaller size, please complete")
p_message(" any pending macOS upgrades and visit this link to learn how to manually")
p_message(" delete Time Machine snapshots:")
print()
p_plain( f" {col(BLUE, BRIGHT)}https://alx.sh/tmcleanup{col()}")
print()
if avail < 2 * PART_ALIGN:
p_error(" Not enough available space to resize. Please follow the instructions")
p_error(" above to continue.")
return False
if not self.yesno("Continue anyway?"):
return False
print()
if avail < 2 * PART_ALIGN:
p_error("Not enough available space to resize.")
return False
p_question("Enter the new size for your existing partition:")
p_message( " You can enter a size such as '1GB', a fraction such as '50%',")
p_message( " or the word 'min' for the smallest allowable size.")
print()
p_message( " Examples:")
p_message( " 30% - 30% to macOS, 70% to the new OS")
p_message( " 80GB - 80GB to macOS, the rest to your new OS")
p_message( " min - Shrink macOS as much as (safely) possible")
print()
default = "50%"
if total / 2 < min_size:
default = "min"
while True:
val = self.get_size("New size", default=default, min=min_size, total=total)
if val is None:
continue
val = align_up(val, PART_ALIGN)
if val < min_size:
p_error(f"Size is too small, please enter a value > {ssize(min_size)} ({min_perc:.2f}%)")
continue
if val >= total:
p_error(f"Size is too large, please enter a value < {ssize(total)}")
continue
freeing = total - val
print()
p_message(f"Resizing will free up {ssize(freeing)} of space.")
if freeing <= MIN_INSTALL_FREE:
if not self.expert:
p_error(f"That's not enough free space for an OS install.")
continue
else:
p_warning(f"That's not enough free space for an OS install.")
print()
p_message("Note: your system may appear to freeze during the resize.")
p_message("This is normal, just wait until the process completes.")
if self.yesno("Continue?"):
break
print()
try:
self.dutil.resizeContainer(target.name, val)
except subprocess.CalledProcessError as e:
print()
p_error(f"Resize failed. This is usually caused by pre-existing APFS filesystem corruption.")
p_warning("Carefully read the diskutil logs above for more information about the cause.")
p_warning("This can usually be solved by doing a First Aid repair from Disk Utility in Recovery Mode.")
return False
print()
p_success(f"Resize complete. Press enter to continue.")
self.input()
print()
return True
def action_select_disk(self):
choices = {"1": "Internal storage"}
for i, disk in enumerate(self.external_disks):
choices[str(i + 2)] = f"{disk['IORegistryEntryName']} ({ssize(disk['Size'])})"
print()
p_question("Choose a disk:")
idx = int(self.choice("Disk", choices))
if idx == 1:
self.cur_disk = self.sys_disk
else:
self.cur_disk = self.external_disks[idx - 2]["DeviceIdentifier"]
return True
def main(self):
print()
p_message(f"Welcome to the {DISTRO} installer!")
print()
p_message("This installer will guide you through the process of setting up")
p_message(f"{DISTRO} on your Mac.")
print()
p_message("Please make sure you are familiar with our documentation at:")
p_plain( f" {col(BLUE, BRIGHT)}{DISTRO_DOCS}{col()}")
print()
p_question("Press enter to continue.")
self.input()
print()
self.expert = False
if os.environ.get("EXPERT", None):
p_message("By default, this installer will hide certain advanced options that")
p_message("are only useful for Asahi Linux developers. You can enable expert mode")
p_message("to show them. Do not enable this unless you know what you are doing.")
p_message("Please do not file bugs if things go wrong in expert mode.")
self.expert = self.yesno("Enable expert mode?")
print()