Repository navigation
Expand file tree
/
Copy pathBuildiOSXCFramework.py
More file actions
executable file
Β·947 lines (829 loc) Β· 45.2 KB
/
Copy pathBuildiOSXCFramework.py
File metadata and controls
executable file
Β·947 lines (829 loc) Β· 45.2 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
#!/usr/bin/env python3
"""
Dolphin Core Build Script for Provenance
This script builds the Dolphin emulator core for iOS and tvOS platforms,
creating a universal XCFramework that can be used in Provenance.
"""
import os
import sys
import re
import subprocess
import shutil
import signal
import argparse
import glob
import multiprocessing
from pathlib import Path
from typing import List, Dict, Optional, Tuple, Set
# Configuration
CONFIG = {
"build_target": "Release",
"framework_name": "PVlibDolphin",
"ios_deployment_target": "17.0",
"tvos_deployment_target": "17.0",
"platforms": {
"OS64": { # iOS device (arm64)
"deployment_target": "17.0",
"arch_flags": "-mcpu=apple-a10 -mtune=apple-a15 -march=armv8-a+simd+crc+crypto",
"suffix": "-ios",
"xcode_platform": "iphoneos",
},
"SIMULATORARM64": { # iOS simulator (arm64)
"deployment_target": "17.0",
"arch_flags": "", # No architecture-specific flags for simulator
"suffix": "-ios-sim",
"xcode_platform": "iphonesimulator",
},
"TVOS": { # tvOS device (arm64)
"deployment_target": "17.0",
"arch_flags": "-mcpu=apple-a10 -mtune=apple-a15 -march=armv8-a+simd+crc+crypto",
"suffix": "-tvos",
"xcode_platform": "appletvos",
},
"SIMULATOR_TVOS": { # tvOS simulator (arm64)
"deployment_target": "17.0",
"arch_flags": "", # No architecture-specific flags for simulator
"suffix": "-tvos-sim",
"xcode_platform": "appletvsimulator",
},
"MAC_CATALYST": { # Mac Catalyst (arm64)
"deployment_target": "17.0",
"arch_flags": "", # Avoid device-specific tuning flags for macOS
"suffix": "-maccatalyst",
"xcode_platform": "macosx",
},
}
}
# Mangled-name prefixes of third-party C++ namespaces whose *weak* definitions (template
# instantiations, inline functions, guard variables) must not be exported from the dylib.
# dyld coalesces exported weak definitions across every loaded image, so another core
# framework that static-links a different glslang/fmt would bind to ours (Provenance's
# PVAzahar crashed inside glslang's parser after calling our addSwizzle<>). Dolphin's own
# namespaces stay exported: the PVDolphin bridge imports some of those instantiations.
THIRD_PARTY_WEAK_PREFIX = re.compile(
r"^__Z(?:GV|TV|TI|TS|TT|TH|TW)?Z?N?K?"
r"(?:3fmt|7glslang|3spv|11spirv_cross|5SPIRV|6ImPlot|5ImGui|8picojson|8tinygltf|St3__1)"
)
def third_party_weak_symbols(dylib: str) -> list[str]:
"""Exported weak symbols of `dylib` that belong to a third-party namespace."""
out = subprocess.check_output(["xcrun", "nm", "-m", dylib], text=True)
symbols = set()
for line in out.splitlines():
if "weak external" not in line:
continue
name = line.rsplit(" ", 1)[-1]
if THIRD_PARTY_WEAK_PREFIX.match(name):
symbols.add(name)
return sorted(symbols)
def _safe_job_count():
"""Parallel-job count capped by available RAM (~4 GB/job), not just core count.
The -Ofast build has a handful of very heavy TUs (implot_items, glslang, shader gen)
that each peak at multiple GB; running -j<cores> OOM-kills them intermittently and
fails the build nondeterministically. Capping by memory makes builds reliable.
"""
cores = multiprocessing.cpu_count()
try:
ram_bytes = os.sysconf("SC_PHYS_PAGES") * os.sysconf("SC_PAGE_SIZE")
ram_gb = ram_bytes / (1024 ** 3)
mem_cap = max(2, int(ram_gb // 4))
return max(2, min(cores, mem_cap))
except (ValueError, OSError, AttributeError):
return max(2, cores // 2)
def xcrun_find(tool: str) -> str:
"""Absolute path of a tool in the active Xcode toolchain (xcrun --find)."""
import subprocess
return subprocess.check_output(["xcrun", "--find", tool], text=True).strip()
class BuildError(Exception):
"""Exception raised for build errors."""
pass
class DolphinBuilder:
"""Handles building Dolphin core for multiple platforms and creating an XCFramework."""
def __init__(self, verbose: bool = False, clean: bool = False, static: bool = True):
"""Initialize the DolphinBuilder."""
self.verbose = verbose
self.clean = clean
self.static = static
self.script_dir = Path(os.path.dirname(os.path.abspath(__file__)))
self.repo_root_dir = self.script_dir
self.build_dir = self.script_dir / "build"
self.xcframework_dir = self.build_dir / "xcframework"
self.processes = {}
self.dylibs = {}
self.frameworks = {}
# Ensure necessary directories exist
self.build_dir.mkdir(exist_ok=True)
self.xcframework_dir.mkdir(exist_ok=True)
# Set compiler paths
self.cc = subprocess.check_output(["xcrun", "-find", "clang"]).decode().strip()
self.cxx = subprocess.check_output(["xcrun", "-find", "clang++"]).decode().strip()
# Set environment variables for compiler detection
os.environ["CC"] = self.cc
os.environ["CXX"] = self.cxx
# Xcode's /usr/bin/python3 shim (how the app's build phase and most people start this
# script) exports CPATH=/usr/local/include and LIBRARY_PATH=/usr/local/lib. clang searches
# CPATH ahead of -isystem directories, and CMake marks several Externals as -isystem, so a
# library installed under /usr/local replaces the vendored copy: a 2024 Vulkan SDK's
# glslang headers there broke every local slice build with "static assertion failed ...
# 5 == 6" in glslang_c_interface.cpp. The core builds only from this tree and the SDK.
for inherited in ("CPATH", "C_INCLUDE_PATH", "CPLUS_INCLUDE_PATH", "OBJC_INCLUDE_PATH",
"OBJCPLUS_INCLUDE_PATH", "LIBRARY_PATH"):
os.environ.pop(inherited, None)
# Check for required tools
self._check_required_tools()
def _ensure_externals_present(self) -> None:
"""Verify required Externals submodules exist; try to fetch them if missing.
This prevents CMake errors like "Cannot find source file" for vendored
dependencies when submodules haven't been initialized.
"""
# Check actual source files inside nested submodules, not just the wrapper
# CMakeLists.txt files that live in the main repo alongside the submodule dir.
projects = [
self.repo_root_dir / "Externals/zstd/zstd/lib/common/debug.c",
self.repo_root_dir / "Externals/SFML/SFML/src/SFML/Network/Http.cpp",
self.repo_root_dir / "Externals/watcher/watcher/include/watcher/watcher.hpp",
self.repo_root_dir / "Externals/rcheevos/CMakeLists.txt",
]
missing_roots = [str(p.relative_to(self.repo_root_dir)) for p in projects if not p.exists()]
if not missing_roots:
return
else:
self._log("Missing Externals source files (uninitialized submodules): " + ", ".join(missing_roots), "warning")
# Attempt to initialize/update submodules
self._log("Attempting to initialize/update git submodules for Externals...", "info")
git_cmd = [
"git",
"-C",
str(self.repo_root_dir),
"submodule",
"update",
"--init",
"--recursive",
]
try:
if self.verbose:
self._log(f"Running: {' '.join(git_cmd)}", "debug")
subprocess.check_call(git_cmd)
except (subprocess.CalledProcessError, FileNotFoundError):
# Either git is unavailable or repo is not a git checkout
self._log(
"Unable to update submodules automatically (git missing or not a git checkout).",
"warning",
)
# Re-check after attempted update; if roots still missing, warn but continue
missing_roots = [str(p.relative_to(self.repo_root_dir)) for p in projects if not p.exists()]
if missing_roots:
self._log(
"External project roots still missing: " + ", ".join(missing_roots) +
". Proceeding anyway; CMake may fetch dependencies dynamically.",
"warning",
)
def _check_required_tools(self):
"""Check if required build tools are installed."""
# Check for Homebrew CMake first
homebrew_cmake = "/opt/homebrew/bin/cmake"
if os.path.exists(homebrew_cmake):
self.cmake_path = homebrew_cmake
self._log(f"Found CMake at: {self.cmake_path}", "debug")
else:
# Try xcrun
try:
self.cmake_path = subprocess.check_output(["xcrun", "-find", "cmake"]).decode().strip()
self._log(f"Found CMake at: {self.cmake_path}", "debug")
except subprocess.CalledProcessError:
# Fallback to regular path
try:
self.cmake_path = subprocess.check_output(["which", "cmake"]).decode().strip()
self._log(f"Found CMake at: {self.cmake_path}", "debug")
except subprocess.CalledProcessError:
raise BuildError("Error: cmake not found. Please install it or ensure it's in your PATH.")
# Find xcodebuild
try:
self.xcodebuild_path = subprocess.check_output(["xcrun", "-find", "xcodebuild"]).decode().strip()
self._log(f"Found xcodebuild at: {self.xcodebuild_path}", "debug")
except subprocess.CalledProcessError:
raise BuildError("Error: xcodebuild not found. Please ensure Xcode is installed properly.")
# Optional tools
self.has_ninja = False
# Check for Homebrew Ninja first
homebrew_ninja = "/opt/homebrew/bin/ninja"
if os.path.exists(homebrew_ninja):
self.ninja_path = homebrew_ninja
self.has_ninja = True
self._log(f"Found Ninja at: {self.ninja_path}", "debug")
else:
# Try xcrun
try:
self.ninja_path = subprocess.check_output(["xcrun", "-find", "ninja"]).decode().strip()
self.has_ninja = True
self._log(f"Found Ninja at: {self.ninja_path}", "debug")
except subprocess.CalledProcessError:
# Fallback to regular path
try:
self.ninja_path = subprocess.check_output(["which", "ninja"]).decode().strip()
self.has_ninja = True
self._log(f"Found Ninja at: {self.ninja_path}", "debug")
except subprocess.CalledProcessError:
self._log("Ninja not found. Will use default CMake generator.", "warning")
def _log(self, message, level="info"):
"""Log a message with appropriate formatting."""
prefix_map = {
"info": "βΉοΈ",
"success": "β
",
"error": "β",
"warning": "β οΈ",
"debug": "π",
"build": "π¨",
"package": "π¦"
}
prefix = prefix_map.get(level, "βΉοΈ")
print(f"{prefix} {message}")
if level == "error":
sys.stderr.flush()
else:
sys.stdout.flush()
def build_all(self, platforms=None):
"""Build for specified platforms and create XCFramework.
Args:
platforms: List of platform names to build. If None, builds all platforms.
"""
try:
# Build for each platform
for platform, config in CONFIG["platforms"].items():
if platforms and platform not in platforms:
self._log(f"Skipping build for {platform} (not in requested platforms)", "info")
continue
self._log(f"Starting build for {platform}...", "build")
self.build_platform(platform)
# Create XCFramework
self._log("All builds completed successfully!", "success")
self.create_xcframework()
return True
except BuildError as e:
self._log(f"Build failed: {str(e)}", "error")
return False
except KeyboardInterrupt:
self._log("Build interrupted by user", "warning")
return False
except Exception as e:
self._log(f"Unexpected error: {str(e)}", "error")
return False
def resolve_pgo(self):
"""(mode, profile_path). Idiot-proof by default:
DOL_PGO=generate instrumented core (Tools/pgo/pgo.sh record sets this)
DOL_PGO=use optimize with DOL_PGO_PROFILE, or pgo/icube.profdata when unset
DOL_PGO=off never use a profile
DOL_PGO unset use pgo/icube.profdata when it exists, otherwise a normal build
The profile is recorded and merged by Tools/pgo/pgo.sh; a stale one is harmless (clang
ignores functions whose hash no longer matches), just less effective: see `pgo.sh status`.
"""
default_profile = self.repo_root_dir / "pgo" / "icube.profdata"
mode = os.environ.get("DOL_PGO", "").strip().lower()
profile = os.environ.get("DOL_PGO_PROFILE", "").strip()
if mode in ("", "auto"):
if default_profile.exists():
return "use", str(default_profile)
return "off", ""
if mode == "use" and not profile:
profile = str(default_profile)
return mode, profile
def build_platform(self, platform: str) -> bool:
"""Build Dolphin for a specific platform."""
print(f"π¨ Starting build for {platform}...")
# Get platform-specific configuration
platform_config = CONFIG["platforms"][platform]
arch_flags = platform_config["arch_flags"]
deployment_target = platform_config["deployment_target"]
suffix = platform_config["suffix"]
xcode_platform = platform_config["xcode_platform"]
# Create build directory
# The instrumented (DOL_PGO=generate) core gets a build dir of its own: every flag differs, so
# sharing one would force a full rebuild each time you switch between recording and shipping.
pgo_suffix = "-pgogen" if self.resolve_pgo()[0] == "generate" else ""
cmake_build_dir = (self.repo_root_dir /
f"build-{xcode_platform}-{CONFIG['build_target']}{pgo_suffix}")
# Clean build directory if requested
if self.clean and cmake_build_dir.exists():
print(f"π§Ή Cleaning build directory for {platform}...")
import shutil
shutil.rmtree(cmake_build_dir)
cmake_build_dir.mkdir(exist_ok=True)
# Invalidate stale CMakeCache if the cached sysroot no longer exists on disk.
# This happens after an Xcode SDK update (e.g. 26.0 β 26.4) where the old SDK
# path is cached as INTERNAL and CMake re-uses it without re-querying xcodebuild.
cmake_cache = cmake_build_dir / "CMakeCache.txt"
if cmake_cache.exists():
import re as _re
cache_text = cmake_cache.read_text()
m = _re.search(r"CMAKE_OSX_SYSROOT[^:]*:[^=]*=(.+)", cache_text)
if m:
cached_sysroot = m.group(1).strip()
if cached_sysroot and not Path(cached_sysroot).exists():
self._log(f"Stale sysroot in CMakeCache ({cached_sysroot}), clearing cache", "warning")
cmake_cache.unlink()
# Base optimization flags (common to all platforms)
# Matches BuildCore.sh aggressive flags
base_optimization_flags = (
"-O3 "
"-fvectorize "
# "-funsafe-math-optimizations "
"-funroll-loops "
"-ftree-vectorize "
# -fsplit-lto-unit REMOVED (2603 merge): with CMake IPO (ThinLTO, -flto=thin) it makes
# clang emit raw LLVM IR instead of Mach-O-wrapped bitcode, and Xcode 26's ar/ranlib/
# libtool cannot archive raw bitcode -> every static lib was a 96-byte symbol table and
# libdolphin failed to link. The flag only matters for CFI / -fwhole-program-vtables,
# which this build does not use.
# Value-affecting unsafe-math flags REMOVED: they corrupt the core's FP results.
# -freciprocal-math (approximate 1/x division) and -ffinite-math-only (assume no
# NaN/Inf, breaks ps_rsqrte / normalization) distort CPU-computed bone/skinning and
# perspective math -> e.g. NSMBW "cartoon hands". -fno-signed-zeros drops -0.0.
# The earlier "turn off fast math" pass only removed -ffast-math/-funsafe-math/
# -ffp-contract; these three survived and kept the build non-IEEE. Emulated FP must
# be exact, so keep them off (re-add selectively only if profiling demands it AND the
# geometry stays correct). NOTE: requires a CLEAN rebuild (wipe build-* + xcframework)
# to take effect β stale objects won't pick up the flag change.
# "-freciprocal-math "
"-fPIC "
"-fpermissive "
"-fomit-frame-pointer "
"-fno-trapping-math "
"-fno-strict-aliasing "
# "-fno-signed-zeros "
# "-fno-math-errno "
"-finline-functions "
"-ffunction-sections "
# "-ffp-contract=fast "
# "-ffinite-math-only "
# "-ffast-math "
"-fdata-sections"
).strip()
# --- Profile-Guided Optimization (env-driven; OFF by default -> normal builds unchanged) ---
# DOL_PGO=generate -> instrumented core (writes .profraw on device via the PGOFlush shim).
# DOL_PGO=use + DOL_PGO_PROFILE=<abs path to icube.profdata> -> profile-optimized core.
# IR-based PGO (-fprofile-generate/-use) places counters AFTER inlining, which is what the
# interpreter dispatch loop wants (block layout / branch ordering on the real hot path).
# The profile runtime must ALSO be on the link line β it goes into linker_flags below, which
# feeds CMAKE_SHARED_LINKER_FLAGS; without it the dylib fails to link with undefined
# __llvm_profile_* symbols. The -u force-keeps survive -dead_strip across the dylib boundary
# so the app's flush shim can resolve them.
pgo_mode, pgo_profile = self.resolve_pgo()
pgo_cflags = ""
pgo_ldflags = ""
if pgo_mode == "generate":
pgo_cflags = "-fprofile-generate"
pgo_ldflags = ("-fprofile-generate "
"-Wl,-u,___llvm_profile_write_file "
"-Wl,-u,___llvm_profile_set_filename")
elif pgo_mode == "use":
if not pgo_profile or not os.path.exists(pgo_profile):
raise RuntimeError(
f"DOL_PGO=use but the profile is missing or not found: {pgo_profile!r}")
print(f"[PGO] optimizing with profile {pgo_profile}")
pgo_cflags = (f"-fprofile-use={pgo_profile} "
"-Wno-profile-instr-unprofiled -Wno-profile-instr-out-of-date")
elif pgo_mode != "off":
raise RuntimeError(f"DOL_PGO must be off|generate|use, got {pgo_mode!r}")
# Curl build fixes - apply to all platforms to resolve build issues
curl_fixes = (
"-DHAVE_POSIX_STRERROR_R=1 -DHAVE_STRERROR_R=1 -DHAVE_FCNTL_O_NONBLOCK=1 "
"-Dsread=read -Dswrite=write -DSIZEOF_CURL_OFF_T=8 -DHAVE_STRUCT_TIMEVAL=1 "
"-DHAVE_STRUCT_SOCKADDR_IN=1 -DHAVE_NETINET_IN_H=1 -DHAVE_ARPA_INET_H=1 "
"-DHAVE_SYS_SOCKET_H=1 -DHAVE_SOCKET=1 -DHAVE_CONNECT=1 -DHAVE_RECV=1 -DHAVE_SEND=1 "
"-DHAVE_BIND=1 -DHAVE_LISTEN=1 -DHAVE_ACCEPT=1 -DHAVE_SOCKADDR_IN6=1 "
"-DHAVE_STRUCT_STAT=1 -DHAVE_FSTAT=1 -DHAVE_OPEN=1 -DO_WRONLY=1 -DO_CREAT=64 "
"-DO_EXCL=128 -DS_ISREG=1 -DHAVE_SELECT=1 -DHAVE_POLL=1 "
"-DHAVE_NETDB_H=1 -DHAVE_GETHOSTBYNAME=1 -DHAVE_STRUCT_HOSTENT=1 "
"-DHAVE_GETHOSTBYADDR=1 -DHAVE_GETADDRINFO=1 -DHAVE_FREEADDRINFO=1 "
"-DHAVE_SYS_STAT_H=1 -DHAVE_FCNTL_H=1 -DHAVE_UNISTD_H=1 -DHAVE_SYS_TYPES_H=1 "
"-DHAVE_POLL_H=1 -DHAVE_SYS_POLL_H=1"
)
# Combine flags with ARM64-only enforcement
arm64_defines = "-D_M_ARM_64 -U_M_X86_64 -U_M_IX86" # ARM64 only, explicitly undefine x86 macros
# iCube: DOL_FULL_LTO=1 restores the pre-2603 FULL (monolithic) LTO. CMake IPO on Clang is
# ThinLTO (-flto=thin); the old fork build used check_and_add_flag(LTO -flto). Full LTO gives
# the whole-program view the jitless interpreter benefits from, at a much longer link. A/B knob
# for the post-merge perf work; ENABLE_LTO is turned OFF so the two do not stack.
full_lto = os.environ.get("DOL_FULL_LTO", "0") == "1"
lto_cflags = "-flto" if full_lto else ""
c_flags = f"{base_optimization_flags} {pgo_cflags} {lto_cflags} -w {arm64_defines} {curl_fixes}".strip()
cxx_flags = f"{base_optimization_flags} {pgo_cflags} {lto_cflags} -w {arm64_defines} {curl_fixes}".strip()
# Add architecture-specific flags only for device builds (not simulators)
if platform not in ["SIMULATORARM64", "SIMULATOR_TVOS"]:
arch_flags = platform_config["arch_flags"]
else:
arch_flags = "" # No architecture-specific flags for simulators
# Apply architecture flags if present
if arch_flags:
c_flags += f" {arch_flags}"
cxx_flags += f" {arch_flags}"
# Explicit ARM device tuning (mirror BuildCore.sh)
if platform in ["OS64", "TVOS"]:
tune_flags = "-mcpu=apple-a10 -mtune=apple-a14 -march=armv8-a+simd+crc+crypto"
c_flags += f" {tune_flags}"
cxx_flags += f" {tune_flags}"
# Explicitly set deployment target flags to override toolchain defaults
if platform in ["SIMULATORARM64", "SIMULATOR_TVOS"]:
if platform == "SIMULATORARM64":
c_flags += f" -mios-simulator-version-min={deployment_target}"
cxx_flags += f" -mios-simulator-version-min={deployment_target}"
elif platform == "SIMULATOR_TVOS":
c_flags += f" -mtvos-simulator-version-min={deployment_target}"
cxx_flags += f" -mtvos-simulator-version-min={deployment_target}"
else:
if platform == "OS64":
c_flags += f" -miphoneos-version-min={deployment_target}"
cxx_flags += f" -miphoneos-version-min={deployment_target}"
elif platform == "TVOS":
c_flags += f" -mtvos-version-min={deployment_target}"
cxx_flags += f" -mtvos-version-min={deployment_target}"
elif platform == "MAC_CATALYST":
# Let ios-cmake handle Catalyst deployment target via -DPLATFORM=MAC_CATALYST and -DDEPLOYMENT_TARGET
pass
# Additional linker optimizations
# Use -noall_load to avoid force-loading every static lib member (conflicts with LTO/bitcode archives)
linker_flags = f"-Wl,-dead_strip -Wl,-noall_load {pgo_ldflags} {lto_cflags}".strip()
# Configure CMake command
cmake_cmd = [
self.cmake_path, str(self.repo_root_dir),
]
# iCube: silence CMake 4.x deprecation-warning spam from vendored externals that still declare
# pre-3.10 cmake_minimum_required values. Suppresses noise only β changes no policy/behavior.
cmake_cmd.append("-Wno-deprecated")
# Add generator if Ninja is available
if self.has_ninja:
cmake_cmd.extend(["-G", "Ninja"])
cmake_cmd.append(f"-DCMAKE_MAKE_PROGRAM={self.ninja_path}")
# FORCE ARM64-ONLY for ALL platforms (no x86_64 support)
cmake_cmd.append("-DCMAKE_OSX_ARCHITECTURES=arm64")
# Let the iOS toolchain set CMAKE_SYSTEM_PROCESSOR based on ARCHS
if platform in ["SIMULATORARM64", "SIMULATOR_TVOS"]:
# Explicitly set the correct SDK for simulator builds
if platform == "SIMULATORARM64":
simulator_sdk = subprocess.check_output(["xcrun", "--sdk", "iphonesimulator", "--show-sdk-path"]).decode().strip()
cmake_cmd.append(f"-DCMAKE_OSX_SYSROOT={simulator_sdk}")
elif platform == "SIMULATOR_TVOS":
simulator_sdk = subprocess.check_output(["xcrun", "--sdk", "appletvsimulator", "--show-sdk-path"]).decode().strip()
cmake_cmd.append(f"-DCMAKE_OSX_SYSROOT={simulator_sdk}")
elif platform == "OS64":
# Explicitly set device SDK so Xcode upgrades don't leave a stale cached path
device_sdk = subprocess.check_output(["xcrun", "--sdk", "iphoneos", "--show-sdk-path"]).decode().strip()
cmake_cmd.append(f"-DCMAKE_OSX_SYSROOT={device_sdk}")
elif platform == "TVOS":
device_sdk = subprocess.check_output(["xcrun", "--sdk", "appletvos", "--show-sdk-path"]).decode().strip()
cmake_cmd.append(f"-DCMAKE_OSX_SYSROOT={device_sdk}")
elif platform == "MAC_CATALYST":
# Use macOS SDK for Catalyst
macos_sdk = subprocess.check_output(["xcrun", "--sdk", "macosx", "--show-sdk-path"]).decode().strip()
cmake_cmd.append(f"-DCMAKE_OSX_SYSROOT={macos_sdk}")
# ios-cmake adds the macabi target triple and the iOSSupport search paths to
# CMAKE_C_FLAGS and CMAKE_CXX_FLAGS only. The core's .m/.mm files compile as OBJC and
# OBJCXX, which were left targeting plain macOS, where AVAudioSession and UIKit are
# unavailable ("'AVAudioSession' is unavailable: not available on macOS").
macabi_flags = (f"--target=arm64-apple-ios{deployment_target}-macabi "
f"-isystem {macos_sdk}/System/iOSSupport/usr/include "
f"-iframework {macos_sdk}/System/iOSSupport/System/Library/Frameworks")
cmake_cmd.append(f"-DCMAKE_OBJC_FLAGS={macabi_flags}")
cmake_cmd.append(f"-DCMAKE_OBJCXX_FLAGS={macabi_flags}")
# Ensure Externals (submodules) are present before configuring CMake
self._ensure_externals_present()
# iOS toolchain and platform configuration
cmake_cmd.extend([
f"-DCMAKE_TOOLCHAIN_FILE={str(self.repo_root_dir / 'Externals/ios-cmake/ios.toolchain.cmake')}",
f"-DPLATFORM={platform}",
f"-DDEPLOYMENT_TARGET={deployment_target}",
"-DARCHS=arm64", # Force ARM64 architecture for all builds
f"-DCMAKE_BUILD_TYPE={CONFIG['build_target']}",
"-DCMAKE_POLICY_VERSION_MINIMUM=3.5", # Fix pugixml compatibility
# iCube: LTO β cross-TU inlining of the jitless interpreter dispatch + op handlers.
# Worth ~15% on the interpreter hot path; kept ON. (Was briefly OFF as a
# geometry-corruption A/B in 16d5cc8fdd; that bug is upstream-drift/source, not an
# LTO miscompile, so LTO-off bought nothing and cost perf. Geometry bug tracked via
# the bisect plan, not by disabling LTO.)
f"-DENABLE_LTO={'OFF' if full_lto else 'ON'}",
# 2603 moved LTO to CMAKE_INTERPROCEDURAL_OPTIMIZATION. Under IPO, CMake archives
# with CMAKE_<LANG>_COMPILER_AR (llvm-ar), which Xcode does not ship; left empty,
# the archive step silently produced 4 KB archives holding only a symbol table and
# the dylib link failed with thousands of undefined symbols. Xcode's cctools ar/ranlib
# understand LTO bitcode via libLTO, so point IPO at them explicitly.
f"-DCMAKE_C_COMPILER_AR={xcrun_find('ar')}",
f"-DCMAKE_CXX_COMPILER_AR={xcrun_find('ar')}",
f"-DCMAKE_C_COMPILER_RANLIB={xcrun_find('ranlib')}",
f"-DCMAKE_CXX_COMPILER_RANLIB={xcrun_find('ranlib')}",
# iCube: emit debug info so crashes inside the core can be symbolicated.
#
# CMAKE_BUILD_TYPE=Release is -O3 -DNDEBUG with NO -g, so the shipped dylib carried zero
# DWARF sections. Every Sentry crash whose frames land in the core β ExecuteOneBlock and
# friends, hundreds of users β was unsymbolicatable BY CONSTRUCTION, and no amount of
# fixing the upload step could have helped: there was nothing to upload.
#
# -g changes no codegen at -O3. On Apple the linker leaves a debug map (N_OSO entries)
# pointing at the object files rather than embedding DWARF, so the dylib grows only by
# its symbol table; dsymutil then follows that map to build the .dSYM (see below).
"-DCMAKE_C_FLAGS_RELEASE=-O3 -DNDEBUG -g",
"-DCMAKE_CXX_FLAGS_RELEASE=-O3 -DNDEBUG -g",
])
# Override deployment target at CMake level to ensure it's respected
if platform in ["SIMULATORARM64", "SIMULATOR_TVOS"]:
if platform == "SIMULATORARM64":
cmake_cmd.append(f"-DCMAKE_OSX_DEPLOYMENT_TARGET={deployment_target}")
elif platform == "SIMULATOR_TVOS":
cmake_cmd.append(f"-DCMAKE_TVOS_DEPLOYMENT_TARGET={deployment_target}")
else:
if platform == "OS64":
cmake_cmd.append(f"-DCMAKE_OSX_DEPLOYMENT_TARGET={deployment_target}")
elif platform == "TVOS":
cmake_cmd.append(f"-DCMAKE_TVOS_DEPLOYMENT_TARGET={deployment_target}")
elif platform == "MAC_CATALYST":
# Do not set CMAKE_OSX_DEPLOYMENT_TARGET for Catalyst; ios-cmake derives proper -target ...-macabi
pass
# Continue with the rest of the CMake arguments
cmake_cmd.extend([
f"-DCMAKE_C_FLAGS={c_flags}",
f"-DCMAKE_CXX_FLAGS={cxx_flags}",
f"-DCMAKE_EXE_LINKER_FLAGS={linker_flags}",
f"-DCMAKE_SHARED_LINKER_FLAGS={linker_flags}",
"-DENABLE_VISIBILITY=ON",
"-DENABLE_BITCODE=OFF",
"-DENABLE_ARC=ON",
"-DUSE_SYSTEM_ZSTD=OFF",
# 2603 bumped curl and minizip-ng; both now auto-detect zstd through pkg-config and
# pull the HOST (Homebrew, macOS) libzstd into the iOS link ("building for iOS, but
# linking in dylib built for macOS"). Neither needs zstd on iOS.
"-DCURL_ZSTD=OFF",
"-DMZ_ZSTD=OFF",
"-DMZ_OPENSSL=OFF",
# 2606 enabled mGBA on Android and dropped the guard the fork used for iOS; mGBA does not
# build with Apple clang 21 (implicit popcount32) and GBA link cable is not a feature here.
"-DUSE_MGBA=OFF", # same leak via minizip-ng's OpenSSL probe (Homebrew libssl)
"-DUSE_SYSTEM_MINIZIP=OFF",
"-DUSE_SYSTEM_LZMA=OFF",
"-DUSE_SYSTEM_BZIP2=OFF",
"-DIOS=ON",
"-DENABLE_ANALYTICS=NO",
"-DUSE_SYSTEM_LIBS=OFF",
"-DENABLE_TESTS=OFF",
"-DCMAKE_POLICY_DEFAULT_CMP0080=NEW",
"-DCMAKE_POLICY_VERSION=3.19",
f"-DBUILD_SHARED_LIBS={'OFF' if self.static else 'ON'}",
# Force external libraries to respect our BUILD_SHARED_LIBS setting
"-DLZ4_BUNDLED_MODE=ON", # Prevent lz4 from overriding BUILD_SHARED_LIBS
"-DXXHASH_BUNDLED_MODE=ON", # Prevent xxhash from overriding BUILD_SHARED_LIBS
"-DCMAKE_XCODE_ATTRIBUTE_ENABLE_ARC=YES",
# ARM64-only enforcement - disable x86_64 specific code
"-DENABLE_X64_DEC=OFF",
"-DUSE_X64_DEC=OFF",
"-DENABLE_GENERIC=OFF", # Allow proper ARM64 context detection
"-DCMAKE_SYSTEM_PROCESSOR=aarch64", # Force aarch64 to override any detection
# CMake variables for architecture detection
"-D_M_ARM_64:BOOL=ON", # CMake variable for ARM64
"-D_M_X86_64:BOOL=OFF", # Explicitly disable x86_64
])
# Enable generic build for simulator platforms (no JIT needed)
if platform in ["SIMULATORARM64", "SIMULATOR_TVOS"]:
# cmake_cmd.append("-DENABLE_GENERIC=ON") # Removed to allow proper ARM64 context detection
# Don't set _M_X86_64 for generic builds to avoid x86_64-specific code compilation
pass # ARM64 context will be used instead of generic
cmake_cmd.append("-UDOLPHIN_UNEXPORTED_SYMBOLS_LIST") # second pass sets it (see below)
# Execute CMake configure
self._log(f"Configuring CMake for {platform}...", "build")
os.chdir(cmake_build_dir)
try:
if self.verbose:
self._log(f"Running: {' '.join(cmake_cmd)}", "debug")
subprocess.check_call(cmake_cmd)
# Build with appropriate command.
# Cap parallelism by available RAM, not just core count: the aggressive -Ofast flags
# (+ -funroll-loops/-fsplit-lto-unit) make a few heavy TUs (implot_items, glslang,
# the VideoCommon shader gen) consume multiple GB each. At -j<cores> they OOM-kill
# intermittently and fail the build at random spots. ~4 GB/job keeps it deterministic.
jobs = _safe_job_count()
if self.has_ninja:
self._log(f"Building {platform} with Ninja (-j {jobs})...", "build")
build_cmd = [self.ninja_path, "-j", str(jobs)]
else:
self._log(f"Building {platform} with CMake build (-j {jobs})...", "build")
build_cmd = [self.cmake_path, "--build", ".", "-j", str(jobs)]
if self.verbose:
self._log(f"Running: {' '.join(build_cmd)}", "debug")
subprocess.check_call(build_cmd)
# Find the built dylib robustly β filename may vary (suffix and version number differ per config)
dylib_search_dir = cmake_build_dir / "Source/iOS/Library"
candidate_patterns = [
f"libdolphin{suffix}*.dylib", # Prefer platform-suffixed names
"libdolphin-ios*.dylib", # Common iOS naming
"libdolphin*.dylib", # Any libdolphin dylib
]
found: list[str] = []
for pat in candidate_patterns:
found = glob.glob(str(dylib_search_dir / pat))
if found:
break
if not found:
raise BuildError(
f"Could not find built dylib for {platform} (xcode_platform: {xcode_platform}). "
f"Searched patterns: {candidate_patterns} in {dylib_search_dir}"
)
# If multiple, pick the newest by modification time
found.sort(key=lambda p: os.path.getmtime(p), reverse=True)
chosen = found[0]
self._log(f"Found dylib for {platform}: {os.path.basename(chosen)}", "debug")
# Second pass: relink with the third-party weak definitions unexported. The list can
# only be known after a link, and LTO is off by default so the relink is cheap.
hidden = third_party_weak_symbols(chosen)
if hidden:
list_path = cmake_build_dir / "unexported_weak_symbols.txt"
list_path.write_text("\n".join(hidden) + "\n")
self._log(f"Relinking {platform} with {len(hidden)} third-party weak symbols hidden", "build")
# Source/iOS/Library/CMakeLists.txt turns this into target_link_options; the
# global CMAKE_*_LINKER_FLAGS are overridden inside Dolphin's CMake.
subprocess.check_call(cmake_cmd + [f"-DDOLPHIN_UNEXPORTED_SYMBOLS_LIST={list_path}"])
subprocess.check_call(build_cmd)
left = third_party_weak_symbols(chosen)
if left:
raise BuildError(f"{len(left)} third-party weak symbols still exported from {chosen}")
# iCube: build the .dSYM beside the dylib. dsymutil resolves the debug map left by -g
# into a standalone bundle, which is what Sentry needs; the dylib itself stays as-is.
# Non-fatal: a missing dSYM costs symbolication, never a build.
try:
dsym_path = chosen + ".dSYM"
subprocess.check_call(["xcrun", "dsymutil", chosen, "-o", dsym_path])
self._log(f"dSYM: {os.path.basename(dsym_path)}", "success")
except (subprocess.CalledProcessError, OSError) as dsym_err:
self._log(f"dsymutil failed for {platform} ({dsym_err}); core frames will not "
f"symbolicate in Sentry", "warning")
self.dylibs[platform] = chosen
self._log(f"Build completed for {platform}", "success")
except subprocess.CalledProcessError as e:
raise BuildError(f"Build failed for {platform} with exit code {e.returncode}")
def create_framework(self, dylib_path: str, platform: str):
"""Create a framework from a dylib."""
framework_name = CONFIG["framework_name"]
framework_path = self.xcframework_dir / f"{framework_name}{CONFIG['platforms'][platform]['suffix']}.framework"
# Remove existing framework if it exists
if framework_path.is_symlink():
# A cached-core install may link this output to a shared cache. Replace
# the link for this build without deleting the cached framework itself.
framework_path.unlink()
elif framework_path.exists():
shutil.rmtree(framework_path)
# Get the actual filename without path
dylib_filename = os.path.basename(dylib_path)
platform_suffix = CONFIG['platforms'][platform]['suffix']
binary_name = f"{framework_name}{platform_suffix}"
# iOS and tvOS frameworks are flat. macOS, and so Mac Catalyst, requires the versioned
# layout: Xcode refuses to embed a flat one ("contains Info.plist, expected
# Versions/Current/Resources/Info.plist").
versioned = platform == "MAC_CATALYST"
content_path = framework_path / "Versions" / "A" if versioned else framework_path
resources_path = content_path / "Resources" if versioned else framework_path
resources_path.mkdir(parents=True)
install_name = (f"@rpath/{binary_name}.framework/Versions/A/{binary_name}" if versioned
else f"@rpath/{binary_name}.framework/{binary_name}")
# Copy dylib to framework and rename it to match framework name
shutil.copy(dylib_path, content_path / binary_name)
# Make sure the binary is executable
os.chmod(content_path / binary_name, 0o755)
# Fix the install name to match the framework structure
subprocess.check_call([
"install_name_tool",
"-id",
install_name,
str(content_path / binary_name)
])
if versioned:
os.symlink("A", framework_path / "Versions" / "Current")
os.symlink(f"Versions/Current/{binary_name}", framework_path / binary_name)
os.symlink("Versions/Current/Resources", framework_path / "Resources")
# Create Info.plist
info_plist = f"""<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>{binary_name}</string>
<key>CFBundleIdentifier</key>
<string>org.dolphin-emu.{binary_name}</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>{binary_name}</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>MinimumOSVersion</key>
<string>17.0</string>
</dict>
</plist>
"""
with open(resources_path / "Info.plist", "w") as f:
f.write(info_plist)
self._log(f"Framework created at {framework_path}", "success")
self.frameworks[platform] = str(framework_path)
return framework_path
def create_xcframework(self):
"""Create XCFramework from individual frameworks."""
self._log("Starting XCFramework creation process...", "package")
# Create frameworks for each platform that was built in this session
for platform, dylib_path in self.dylibs.items():
self.create_framework(dylib_path, platform)
# Find ALL existing .framework directories in the xcframework folder
framework_paths = list(self.xcframework_dir.glob("*.framework"))
if not framework_paths:
self._log("No frameworks found in xcframework directory", "warning")
return
# Create XCFramework
framework_name = CONFIG["framework_name"]
xcframework_path = self.xcframework_dir / f"{framework_name}.xcframework"
# Remove existing XCFramework if it exists
if xcframework_path.exists():
shutil.rmtree(xcframework_path)
# Build the xcodebuild command
xcframework_cmd = [self.xcodebuild_path, "-create-xcframework", "-output", str(xcframework_path)]
# Add ALL found frameworks to command
for framework_path in framework_paths:
xcframework_cmd.extend(["-framework", str(framework_path)])
self._log(f"Creating XCFramework with {len(framework_paths)} frameworks...", "package")
self._log(f"Executing: {' '.join(xcframework_cmd)}", "debug")
try:
subprocess.check_call(xcframework_cmd)
self._log(f"XCFramework created at {xcframework_path}", "success")
# List the contents of the XCFramework
self._log("XCFramework contents:", "info")
for item in xcframework_path.glob("**/*"):
if item.is_dir():
self._log(f" π {item.relative_to(xcframework_path)}", "debug")
else:
self._log(f" π {item.relative_to(xcframework_path)}", "debug")
# Copy XCFramework to the expected output location if BUILT_PRODUCTS_DIR is set
built_products_dir = os.environ.get("BUILT_PRODUCTS_DIR")
if built_products_dir:
output_path = Path(built_products_dir) / f"{framework_name}.xcframework"
self._log(f"Copying XCFramework to {output_path}", "package")
if output_path.exists():
shutil.rmtree(output_path)
shutil.copytree(xcframework_path, output_path)
except subprocess.CalledProcessError as e:
raise BuildError(f"XCFramework creation failed with exit code {e.returncode}")
def main():
"""Main entry point."""
parser = argparse.ArgumentParser(description="Build Dolphin core for iOS/tvOS platforms")
parser.add_argument("-v", "--verbose", action="store_true", help="Enable verbose output")
parser.add_argument("-p", "--platforms", nargs="+", choices=CONFIG["platforms"].keys(),
help="Specific platforms to build (default: OS64)")
parser.add_argument("-a", "--all-platforms", action="store_true",
help="Build all supported platforms (default: false)")
parser.add_argument("-c", "--clean", action="store_true",
help="Clean build directories before building (default: false)")
parser.add_argument("-s", "--static", action="store_true", default=True,
help="Build static libraries (default: true)")
parser.add_argument("-d", "--dynamic", action="store_true",
help="Build dynamic libraries (overrides --static)")
parser.add_argument("-x", "--xcframework-only", action="store_true",
help="Only create XCFramework from existing frameworks (skip building)")
args = parser.parse_args()
# Set up signal handler for clean termination
def signal_handler(sig, frame):
print("\nπ Build interrupted! Cleaning up...")
sys.exit(130) # Standard exit code for Ctrl+C
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
# Determine build type (static vs dynamic)
build_static = args.static and not args.dynamic # dynamic overrides static
# Start the build process
builder = DolphinBuilder(verbose=args.verbose, clean=args.clean, static=build_static)
# Handle XCFramework-only mode
if args.xcframework_only:
print("Creating XCFramework from existing frameworks...")
try:
builder.create_xcframework()
print("\nβ
XCFramework creation completed successfully!")
return 0
except Exception as e:
print(f"\nβ XCFramework creation failed: {e}")
return 1
# Determine which platforms to build
platforms_to_build = None # None means all platforms in the build_all method
if args.all_platforms:
# Build all platforms
print("Building all supported platforms")
elif args.platforms:
# Build specific platforms
platforms_to_build = args.platforms
print(f"Building specified platforms: {', '.join(platforms_to_build)}")
else:
# Default: only build iOS device (OS64)
platforms_to_build = ["OS64", "TVOS"]
print("Building default platform: OS64 (iOS device)")
if builder.build_all(platforms=platforms_to_build):
print("\nβ
Build completed successfully!")
return 0
else:
print("\nβ Build failed!")
return 1
if __name__ == "__main__":
sys.exit(main())