XNU as a loadable kernel module inside Linux (macOS personality for arm64 Linux)
C
Kernel collections without Apple's binaries: PureDarwin by default, Apple's kexts linked on the user's machine (#14)
Heyang Zhou27117afa2911
diff --git a/LICENSE b/LICENSEindex de08783..d2d9b58 100644--- a/LICENSE+++ b/LICENSE@@ -3,9 +3,10 @@ Each source file names its license in an SPDX-License-Identifier line; the fullGPL-2.0-only fki-ko/, linux/, scripts/, tools/, tests/, docs/, gpu/xnu-drm/xnudrmd.c, gpu/venus/GPL-2.0-or-later gpu/xnu-cpu-metal/- APSL-2.0 xnu-ko/, xnu-patches/, kexts/+ APSL-2.0 xnu-ko/, xnu-patches/, kexts/ (kexts/free/compat/ too)BSD-2-Clause-Patent kexts/XnuDisplay/, kexts/XnuEthernet/, kexts/XnuInput/ (from macOS-DroidVM),gpu/xnu-cpu-metal/src/xnu-cpu-metal-bundle/XnuCpuMetalShim.h (from UniXNU/AdrenoMetal)+ MPL-2.0 kexts/free/patches/corecrypto-arm64e-sptr.patch (a patch to corecrypto, under its license)MIT gpu/xnu-drm/darwin/, gpu/xnu-drm/xnudrm_proto.h; the patches to Mesa and virglrenderer(under their upstream's license, as are the patches to metal2vulkan: GPL-2.0-or-later)diff --git a/LICENSES/MPL-2.0.txt b/LICENSES/MPL-2.0.txtnew file mode 100644index 0000000..d0a1fa1--- /dev/null+++ b/LICENSES/MPL-2.0.txt@@ -0,0 +1,373 @@+Mozilla Public License Version 2.0+==================================++1. Definitions+--------------++1.1. "Contributor"+ means each individual or legal entity that creates, contributes to+ the creation of, or owns Covered Software.++1.2. "Contributor Version"+ means the combination of the Contributions of others (if any) used+ by a Contributor and that particular Contributor's Contribution.++1.3. "Contribution"+ means Covered Software of a particular Contributor.++1.4. "Covered Software"+ means Source Code Form to which the initial Contributor has attached+ the notice in Exhibit A, the Executable Form of such Source Code+ Form, and Modifications of such Source Code Form, in each case+ including portions thereof.++1.5. "Incompatible With Secondary Licenses"+ means++ (a) that the initial Contributor has attached the notice described+ in Exhibit B to the Covered Software; or++ (b) that the Covered Software was made available under the terms of+ version 1.1 or earlier of the License, but not also under the+ terms of a Secondary License.++1.6. "Executable Form"+ means any form of the work other than Source Code Form.++1.7. "Larger Work"+ means a work that combines Covered Software with other material, in+ a separate file or files, that is not Covered Software.++1.8. "License"+ means this document.++1.9. "Licensable"+ means having the right to grant, to the maximum extent possible,+ whether at the time of the initial grant or subsequently, any and+ all of the rights conveyed by this License.++1.10. "Modifications"+ means any of the following:++ (a) any file in Source Code Form that results from an addition to,+ deletion from, or modification of the contents of Covered+ Software; or++ (b) any new file in Source Code Form that contains any Covered+ Software.++1.11. "Patent Claims" of a Contributor+ means any patent claim(s), including without limitation, method,+ process, and apparatus claims, in any patent Licensable by such+ Contributor that would be infringed, but for the grant of the+ License, by the making, using, selling, offering for sale, having+ made, import, or transfer of either its Contributions or its+ Contributor Version.++1.12. "Secondary License"+ means either the GNU General Public License, Version 2.0, the GNU+ Lesser General Public License, Version 2.1, the GNU Affero General+ Public License, Version 3.0, or any later versions of those+ licenses.++1.13. "Source Code Form"+ means the form of the work preferred for making modifications.++1.14. "You" (or "Your")+ means an individual or a legal entity exercising rights under this+ License. For legal entities, "You" includes any entity that+ controls, is controlled by, or is under common control with You. For+ purposes of this definition, "control" means (a) the power, direct+ or indirect, to cause the direction or management of such entity,+ whether by contract or otherwise, or (b) ownership of more than+ fifty percent (50%) of the outstanding shares or beneficial+ ownership of such entity.++2. License Grants and Conditions+--------------------------------++2.1. Grants++Each Contributor hereby grants You a world-wide, royalty-free,+non-exclusive license:++(a) under intellectual property rights (other than patent or trademark)+ Licensable by such Contributor to use, reproduce, make available,+ modify, display, perform, distribute, and otherwise exploit its+ Contributions, either on an unmodified basis, with Modifications, or+ as part of a Larger Work; and++(b) under Patent Claims of such Contributor to make, use, sell, offer+ for sale, have made, import, and otherwise transfer either its+ Contributions or its Contributor Version.++2.2. Effective Date++The licenses granted in Section 2.1 with respect to any Contribution+become effective for each Contribution on the date the Contributor first+distributes such Contribution.++2.3. Limitations on Grant Scope++The licenses granted in this Section 2 are the only rights granted under+this License. No additional rights or licenses will be implied from the+distribution or licensing of Covered Software under this License.+Notwithstanding Section 2.1(b) above, no patent license is granted by a+Contributor:++(a) for any code that a Contributor has removed from Covered Software;+ or++(b) for infringements caused by: (i) Your and any other third party's+ modifications of Covered Software, or (ii) the combination of its+ Contributions with other software (except as part of its Contributor+ Version); or++(c) under Patent Claims infringed by Covered Software in the absence of+ its Contributions.++This License does not grant any rights in the trademarks, service marks,+or logos of any Contributor (except as may be necessary to comply with+the notice requirements in Section 3.4).++2.4. Subsequent Licenses++No Contributor makes additional grants as a result of Your choice to+distribute the Covered Software under a subsequent version of this+License (see Section 10.2) or under the terms of a Secondary License (if+permitted under the terms of Section 3.3).++2.5. Representation++Each Contributor represents that the Contributor believes its+Contributions are its original creation(s) or it has sufficient rights+to grant the rights to its Contributions conveyed by this License.++2.6. Fair Use++This License is not intended to limit any rights You have under+applicable copyright doctrines of fair use, fair dealing, or other+equivalents.++2.7. Conditions++Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted+in Section 2.1.++3. Responsibilities+-------------------++3.1. Distribution of Source Form++All distribution of Covered Software in Source Code Form, including any+Modifications that You create or to which You contribute, must be under+the terms of this License. You must inform recipients that the Source+Code Form of the Covered Software is governed by the terms of this+License, and how they can obtain a copy of this License. You may not+attempt to alter or restrict the recipients' rights in the Source Code+Form.++3.2. Distribution of Executable Form++If You distribute Covered Software in Executable Form then:++(a) such Covered Software must also be made available in Source Code+ Form, as described in Section 3.1, and You must inform recipients of+ the Executable Form how they can obtain a copy of such Source Code+ Form by reasonable means in a timely manner, at a charge no more+ than the cost of distribution to the recipient; and++(b) You may distribute such Executable Form under the terms of this+ License, or sublicense it under different terms, provided that the+ license for the Executable Form does not attempt to limit or alter+ the recipients' rights in the Source Code Form under this License.++3.3. Distribution of a Larger Work++You may create and distribute a Larger Work under terms of Your choice,+provided that You also comply with the requirements of this License for+the Covered Software. If the Larger Work is a combination of Covered+Software with a work governed by one or more Secondary Licenses, and the+Covered Software is not Incompatible With Secondary Licenses, this+License permits You to additionally distribute such Covered Software+under the terms of such Secondary License(s), so that the recipient of+the Larger Work may, at their option, further distribute the Covered+Software under the terms of either this License or such Secondary+License(s).++3.4. Notices++You may not remove or alter the substance of any license notices+(including copyright notices, patent notices, disclaimers of warranty,+or limitations of liability) contained within the Source Code Form of+the Covered Software, except that You may alter any license notices to+the extent required to remedy known factual inaccuracies.++3.5. Application of Additional Terms++You may choose to offer, and to charge a fee for, warranty, support,+indemnity or liability obligations to one or more recipients of Covered+Software. However, You may do so only on Your own behalf, and not on+behalf of any Contributor. You must make it absolutely clear that any+such warranty, support, indemnity, or liability obligation is offered by+You alone, and You hereby agree to indemnify every Contributor for any+liability incurred by such Contributor as a result of warranty, support,+indemnity or liability terms You offer. You may include additional+disclaimers of warranty and limitations of liability specific to any+jurisdiction.++4. Inability to Comply Due to Statute or Regulation+---------------------------------------------------++If it is impossible for You to comply with any of the terms of this+License with respect to some or all of the Covered Software due to+statute, judicial order, or regulation then You must: (a) comply with+the terms of this License to the maximum extent possible; and (b)+describe the limitations and the code they affect. Such description must+be placed in a text file included with all distributions of the Covered+Software under this License. Except to the extent prohibited by statute+or regulation, such description must be sufficiently detailed for a+recipient of ordinary skill to be able to understand it.++5. Termination+--------------++5.1. The rights granted under this License will terminate automatically+if You fail to comply with any of its terms. However, if You become+compliant, then the rights granted under this License from a particular+Contributor are reinstated (a) provisionally, unless and until such+Contributor explicitly and finally terminates Your grants, and (b) on an+ongoing basis, if such Contributor fails to notify You of the+non-compliance by some reasonable means prior to 60 days after You have+come back into compliance. Moreover, Your grants from a particular+Contributor are reinstated on an ongoing basis if such Contributor+notifies You of the non-compliance by some reasonable means, this is the+first time You have received notice of non-compliance with this License+from such Contributor, and You become compliant prior to 30 days after+Your receipt of the notice.++5.2. If You initiate litigation against any entity by asserting a patent+infringement claim (excluding declaratory judgment actions,+counter-claims, and cross-claims) alleging that a Contributor Version+directly or indirectly infringes any patent, then the rights granted to+You by any and all Contributors for the Covered Software under Section+2.1 of this License shall terminate.++5.3. In the event of termination under Sections 5.1 or 5.2 above, all+end user license agreements (excluding distributors and resellers) which+have been validly granted by You or Your distributors under this License+prior to termination shall survive termination.++************************************************************************+* *+* 6. Disclaimer of Warranty *+* ------------------------- *+* *+* Covered Software is provided under this License on an "as is" *+* basis, without warranty of any kind, either expressed, implied, or *+* statutory, including, without limitation, warranties that the *+* Covered Software is free of defects, merchantable, fit for a *+* particular purpose or non-infringing. The entire risk as to the *+* quality and performance of the Covered Software is with You. *+* Should any Covered Software prove defective in any respect, You *+* (not any Contributor) assume the cost of any necessary servicing, *+* repair, or correction. This disclaimer of warranty constitutes an *+* essential part of this License. No use of any Covered Software is *+* authorized under this License except under this disclaimer. *+* *+************************************************************************++************************************************************************+* *+* 7. Limitation of Liability *+* -------------------------- *+* *+* Under no circumstances and under no legal theory, whether tort *+* (including negligence), contract, or otherwise, shall any *+* Contributor, or anyone who distributes Covered Software as *+* permitted above, be liable to You for any direct, indirect, *+* special, incidental, or consequential damages of any character *+* including, without limitation, damages for lost profits, loss of *+* goodwill, work stoppage, computer failure or malfunction, or any *+* and all other commercial damages or losses, even if such party *+* shall have been informed of the possibility of such damages. This *+* limitation of liability shall not apply to liability for death or *+* personal injury resulting from such party's negligence to the *+* extent applicable law prohibits such limitation. Some *+* jurisdictions do not allow the exclusion or limitation of *+* incidental or consequential damages, so this exclusion and *+* limitation may not apply to You. *+* *+************************************************************************++8. Litigation+-------------++Any litigation relating to this License may be brought only in the+courts of a jurisdiction where the defendant maintains its principal+place of business and such litigation shall be governed by laws of that+jurisdiction, without reference to its conflict-of-law provisions.+Nothing in this Section shall prevent a party's ability to bring+cross-claims or counter-claims.++9. Miscellaneous+----------------++This License represents the complete agreement concerning the subject+matter hereof. If any provision of this License is held to be+unenforceable, such provision shall be reformed only to the extent+necessary to make it enforceable. Any law or regulation which provides+that the language of a contract shall be construed against the drafter+shall not be used to construe this License against a Contributor.++10. Versions of the License+---------------------------++10.1. New Versions++Mozilla Foundation is the license steward. Except as provided in Section+10.3, no one other than the license steward has the right to modify or+publish new versions of this License. Each version will be given a+distinguishing version number.++10.2. Effect of New Versions++You may distribute the Covered Software under the terms of the version+of the License under which You originally received the Covered Software,+or under the terms of any subsequent version published by the license+steward.++10.3. Modified Versions++If you create software not governed by this License, and you want to+create a new license for such software, you may create and use a+modified version of this License if you rename the license and remove+any references to the name of the license steward (except to note that+such modified license differs from this License).++10.4. Distributing Source Code Form that is Incompatible With Secondary+Licenses++If You choose to distribute Source Code Form that is Incompatible With+Secondary Licenses under the terms of this version of the License, the+notice described in Exhibit B of this License must be attached.++Exhibit A - Source Code Form License Notice+-------------------------------------------++ This Source Code Form is subject to the terms of the Mozilla Public+ License, v. 2.0. If a copy of the MPL was not distributed with this+ file, You can obtain one at https://mozilla.org/MPL/2.0/.++If it is not possible or desirable to put the notice in a particular+file, then You may include the notice in a location (such as a LICENSE+file in a relevant directory) where a recipient would be likely to look+for such a notice.++You may add additional accurate notices of copyright ownership.++Exhibit B - "Incompatible With Secondary Licenses" Notice+---------------------------------------------------------++ This Source Code Form is "Incompatible With Secondary Licenses", as+ defined by the Mozilla Public License, v. 2.0.diff --git a/README.md b/README.mdindex 6cdcb29..57639d6 100644--- a/README.md+++ b/README.md@@ -83,6 +83,9 @@ Working on two arm64 Linux setups:- Currently renders on the CPU (Mesa lavapipe, `GPU=off`): `xnudrmd` only forwards `virtio-gpu` (Venus) ioctls today,so hardware GPU pass-through on the GB10 GPU requires a new DRM bridge backend.+Shipping it as a hosted service (what is distributed, what a user installs to run Apple's macOS) is in+[`docs/hosted-service.md`](docs/hosted-service.md).+What is still a stopgap is listed in [`docs/production.md`](docs/production.md). Notably: the OS cryptex is merged intothe system volume, AMFI is patched and SIP relaxed, and memory access is slower than a native VM (4K pages vs 16K).@@ -102,7 +105,9 @@ the system volume, AMFI is patched and SIP relaxed, and memory access is slower1. `scripts/vm-xnu-build.sh` (on the arm64 Linux host, once): sets up the macOS-DroidVM Linux toolchain and builds XNU(`xnu-12377.121.6`) natively on arm64.2. `scripts/vm-xnu-rebuild.sh`: applies `xnu-patches/`, builds the kernel and `kexts/`, and links the kernel collection- with Apple's kexts from your macOS installation.+ with Apple's kexts from your macOS installation (`scripts/kclink`). To link that collection without building+ anything, `scripts/apple-kc/link.sh`, on the machine that runs `xnu.ko`, takes a kit of the built kernel and kexts+ and macOS 27.2's kernelcache, read from Apple's IPSW ([docs/free-kc.md](docs/free-kc.md)).3. `scripts/mk-macvm-disk.sh` (on the Mac): turns a macOS VM disk made by Apple's installer into the hosted system's diskand copies it into the Linux VM.4. `scripts/xnulinux-boot.sh` (on the arm64 Linux host): builds `fki.ko` and `xnu.ko` against the running kernel, bringsdiff --git a/docs/free-kc.md b/docs/free-kc.mdnew file mode 100644index 0000000..e455f83--- /dev/null+++ b/docs/free-kc.md@@ -0,0 +1,95 @@+<!-- SPDX-License-Identifier: GPL-2.0-only -->+# A kernel collection without Apple's kexts, and PureDarwin's userland++The kernel collection `scripts/vm-xnu-rebuild.sh` links is the source-built XNU and xnulinux's own kexts, plus Apple's+kexts from a macOS kernelcache (APFS, AMFI, IOKit families...). `scripts/free-kc/build.sh` links one with none of+Apple's kexts. That collection boots [PureDarwin](https://github.com/PureDarwin/PureDarwin)'s arm64 userland (its own+dyld, libSystem, launchd, zsh and toybox) to its console shell.++## What is in it++| Kext | From | Built as |+|---|---|---|+| XNU, `XnuCPU`, `XnuDisk`, `XnuDrm` | this repository | as for macOS (`vm-xnu-rebuild.sh`) |+| `com.apple.kec.corecrypto` | PureDarwin's interim corecrypto fork (MPL-2.0), pinned | `kexts/free/patches/corecrypto-arm64e-sptr.patch` |+| `com.apple.kec.amfi` | PureDarwin's permissive AMFI stub | |+| `com.apple.kec.pthread` | PureDarwin (Apple's libpthread kext) | |+| `com.apple.iokit.IOStorageFamily`, `HFSEncodings`, `hfs` | PureDarwin (Apple's open-source projects) | |++Every kext is compiled from source as arm64e with this kernel's own compile flags (`scripts/free-kc/kcc.py`), and+linked into the collection by `scripts/kclink` the way xnulinux's own kexts are.++Nothing of Apple's is read to make it. `kclink` links kexts into an existing collection, so `scripts/free-kc/mk-template.py`+first makes an empty one: an `MH_FILESET` with the kernel's segments at the addresses in `scripts/free-kc/layout.json`+(region sizes, nothing else), the kernel's pseudo-extensions (`com.apple.kpi.*`, from XNU's own+`config/System.kext/PlugIns/*/Info.plist`) as the prelink info, and empty chained fixups. Built with every+kernelcache and kernel collection of Apple's hidden from the build (a mount namespace with them replaced by empty files),+the result is the same byte for byte. It also boots with no static trust cache (`TRUSTCACHE=`).++PureDarwin's prebuilt kexts cannot be used. They are arm64 and this kernel is arm64e, so calls from the kernel through their C++ vtables and+function pointers would fail pointer authentication. For the same reason the corecrypto patch signs the function+pointers that corecrypto shares with the kernel (digest and mode descriptors, the PRNG's function table, RNG handles) as+Apple's headers declare them (`CC_SPTR`).++`kexts/free/compat/` fills the few gaps between those sources and this kernel: `OSMalloc`, which this kernel no longer+has; the kernel-internal `kalloc_type_impl` that pthread and AMFI reach for; `devfs_is_ready`, which only PureDarwin's+kernel has; and a kext's load tag.++## Using it++1. `scripts/puredarwin-root.sh IMAGE root.tar.gz` (Linux) unpacks the root of a PureDarwin arm64 image, for example+ `nix build github:PureDarwin/PureDarwin#image-arm64-virt-minimal`.+2. `scripts/mk-puredarwin-disk.sh root.tar.gz pd.img > pd.conf` (Mac) makes the HFS+ disk and prints its UUIDs.+3. In the VM, after `scripts/vm-xnu-rebuild.sh`: `scripts/free-kc/build.sh`, which writes `/lib/firmware/xnu/kc-free.bin`.+4. Boot it: `MAC_CONF=pd.conf DISK=pd.img IMAGE=xnu/kc-free.bin TRUSTCACHE= GPU=off scripts/xnulinux-boot.sh`. The console+ (`CONSOLE_IN`) is PureDarwin's zsh. Its `halt` and `reboot` end the run.++## Apple's kexts, linked on the user's machine++What can be distributed is the kernel, xnulinux's own kexts and `kc-free.bin`. A user who wants to boot macOS links+Apple's kexts from their own copy of macOS into a collection of their own, and chooses which collection to boot with+`IMAGE=` (`image=` of `xnu.ko`):++1. In the VM, after `scripts/vm-xnu-rebuild.sh`: `scripts/apple-kc/package.sh KIT` writes the kit: the kernel,+ xnulinux's kexts (objects and descriptions), `kc-free.bin`, and `kit.json` (the kernelcache it links, by sha256; the+ Apple kexts to keep, `scripts/apple-kc/keep.txt`; the pointers to rebind, `scripts/apple-kc/rebind.txt`; AMFI's+ platform version). Nothing of Apple's is in it.+2. On the machine that runs `xnu.ko` (python3, and `lzfse` for Apple's LZFSE: `apt install lzfse`):+ `scripts/apple-kc/link.sh KIT`. It reads macOS 27.2's `kernelcache.release.vma2` straight from Apple's IPSW (its URL+ is in `kit.json`; only that member is downloaded, with HTTP range requests), links the collection with+ `scripts/kclink` and installs it as `/lib/firmware/xnu/kc-apple.bin`. A second argument gives the+ kernelcache instead: an IPSW or its URL, the IM4P, or that unpacked (`scripts/apple-kc/im4p.py`). The collection is+ the one `vm-xnu-rebuild.sh` links from the same kernelcache, byte for byte. Another kernelcache is refused: the+ kernel's segment slots were laid out for that one.+3. `IMAGE=xnu/kc-apple.bin scripts/xnulinux-boot.sh` boots macOS on it; `IMAGE=xnu/kc-free.bin` boots PureDarwin.++An auxiliary collection (Apple's kexts as a layer over `kc-free.bin`, chosen when `xnu.ko` loads) is not used: on arm64+XNU takes one only from the booter, and adds its kexts only when macOS's `kernelmanagerd` asks, after the root (APFS)+is mounted, so APFS could not be in it.++## The linker++`scripts/kclink/kclink.py` links every collection here (`vm-xnu-rebuild.sh`, `free-kc/build.sh`, `apple-kc/link.sh`).+It is written from the formats alone (`<mach-o/loader.h>`, `<mach-o/fixup-chains.h>`, the arm64 relocations, the+prelink info XNU's `OSKext` reads):++- It takes a collection to lay the output out like (macOS's kernelcache, or `mk-template.py`'s empty one) and the+ kernel, linked at the addresses of its slots. The kernel's threaded rebases (`__TEXT,__thread_starts`) become the+ collection's chained fixups (`DYLD_CHAINED_PTR_64_KERNEL_CACHE`).+- `--keep` keeps kexts of that collection, with every kext they depend on, where they are and byte for byte. Their+ pointers into the old kernel go to the same symbols in this one (the old kernel's symbol table names them); `--rebind`+ sends one to another symbol.+- `--native` links kexts from arm64e objects (`scripts/kclink/kextld.py`: their sections laid out into a kext's+ segments, a GOT, `kmod_info`, the relocations) into space no kernel or kept kext uses. A C++ class whose superclass+ is in a kept kext (the spec's `vtable`) gets the superclass's vtable slots for methods no kext exports, and every slot+ it does not override is checked against the superclass's.++`scripts/kclink/kccompare.py` compares two collections (pointers decoded, each kext's bytes, the prelink info).++## Not done yet++- corecrypto here is PureDarwin's interim fork. By its own README it is LLM-written and unaudited, and it must not be+ relied on to protect anything.+- The kernel headers the kexts build against come from this kernel's `installhdrs`. PureDarwin's AMFI stub also needs+ PureDarwin's CoreEntitlements and TrustCache headers.+- Tested in the krunkit VM with 1 and 2 hosted CPUs: console shell, `launchctl list`, writes to the root, `halt`.diff --git a/docs/hosted-service.md b/docs/hosted-service.mdnew file mode 100644index 0000000..5d5a1ac--- /dev/null+++ b/docs/hosted-service.md@@ -0,0 +1,152 @@+<!-- SPDX-License-Identifier: GPL-2.0-only -->+# Running xnulinux as a hosted service++This manual covers what a hosted xnulinux service ships and what a user installs to run Apple's macOS on it. The+default system is PureDarwin, in which nothing is Apple's. A user who wants Apple's macOS adds it themselves, from+Apple's own downloads. Nothing of Apple's is shipped, stored or cached by the service, and complying with Apple's license+for what they install is the user's responsibility.++## 1. Two systems++| | **PureDarwin** (default) | **Apple's macOS** (the user adds it) |+|---|---|---|+| Kernel collection | `kc-free.bin`: our XNU, our kexts, PureDarwin's kexts built from source | `kc-apple.bin`: the same kernel and our kexts, plus Apple's kexts, linked on the user's machine |+| System disk | PureDarwin's userland on HFS+ (we build it) | made by Apple's installer from Apple's IPSW (the user makes it) |+| Licenses | APSL-2.0, BSD, MIT; MPL-2.0 for corecrypto (§2.3) | Apple's, accepted by the user |++Both boot on the same `xnu.ko` and kernel, so a host can switch between them with `IMAGE=` (§4).++## 2. What we ship++Everything below is built from source in this repository and pinned upstreams. None of it is Apple's, and every+artifact comes with its source.++### 2.1 The host layer (Linux side)++| Artifact | From | License | Notes |+|---|---|---|---|+| `fki.ko` | `fki-ko/` | GPL-2.0-only | the foreign kernel interface: CPUs, memory carve-out, faults, IPIs, host calls |+| `xnu.ko` | `xnu-ko/` | APSL-2.0 | loads and runs the kernel collection. It is a non-GPL module that taints the kernel, like ZFS: ship its **source** and build it on the host against the running kernel (`xnulinux-boot.sh` does this on every boot, and a DKMS package would do it on kernel updates). Do not ship it prebuilt inside a kernel package |+| `xnudrmd` | `gpu/xnu-drm/xnudrmd.c` | GPL-2.0-only | the GPU bridge's Linux service (virtio-gpu Venus render nodes only so far) |+| boot and service scripts | `scripts/xnulinux-boot.sh`, `install-service.sh`, `vm-install-fki-service.sh`, `vm-net-up.sh` | GPL-2.0-only | `xnulinux.service`, `xnulinux-fki.service`, `/etc/xnulinux.conf` |+| kernel command line | `vm-install-fki-service.sh` | | `mem=`, `nokaslr`, `log_buf_len=`; the carve-out (`carve_base`, `carve_mb`) sized for each host model |+| on Mac hosts | `scripts/krun-vm.sh`, `install-krun-agent.sh`, krunkit (Apache-2.0) | | the Linux VM with virtio-gpu Venus; a launchd agent keeps it running |++The host Linux is a stock arm64 distribution kernel (Ubuntu 24.04 is tested) with 4K pages. The CPU needs PAC+(`FEAT_PAuth`), and Linux must run at EL1, not as a bare-metal VHE kernel at EL2. `fki.ko` refuses to load otherwise.++### 2.2 The kernel kit++`scripts/apple-kc/package.sh KIT` (after `scripts/vm-xnu-rebuild.sh`) writes it. It is about 95 MB:++| File | What |+|---|---|+| `kernel.macho` | XNU `xnu-12377.121.6` with `xnu-patches/`, built from source (APSL-2.0). It links no Apple binaries: compiler-rt's kext-PGO functions are stubbed. |+| `kexts/NAME/` | our kexts as arm64e objects plus the description `kclink` links them from (`XnuCPU`, `XnuDisk`, `XnuDrm`, display, input, ethernet...) |+| `kc-free.bin` | the PureDarwin kernel collection (`scripts/free-kc/build.sh`). It is the same byte for byte whether or not any Apple kernelcache is visible to the build. |+| `kit.json` | for `link.sh`: the sha256 of the one kernelcache it links against and Apple's IPSW URL for it, the Apple kexts to keep (`scripts/apple-kc/keep.txt`), the pointers to rebind, AMFI's platform version |+| `scripts/kclink`, `scripts/apple-kc` | the linker and the user-side scripts (GPL-2.0-only), shipped with the kit |++The kernel's segment slots are laid out for one macOS build (today 27.2, `26B123`, `kernelcache.release.vma2`). Each+macOS build we support gets its own kit, and `link.sh` refuses any other kernelcache.++### 2.3 The PureDarwin system disk++- `scripts/puredarwin-root.sh` takes the root file system from PureDarwin's `image-arm64-virt-minimal`, and+ `scripts/mk-puredarwin-disk.sh` makes the HFS+ disk and its `MAC_CONF`. Pin the PureDarwin revision, and ship its+ source references with the disk.+- PureDarwin's kexts in `kc-free.bin` (`IOStorageFamily`, `HFSEncodings`, `hfs`, `pthread`, the AMFI stub,+ corecrypto) are built from source as arm64e with this kernel's flags (`docs/free-kc.md`).+- **Blocker for a production launch:** the corecrypto in it is PureDarwin's interim fork. Its own README says it is+ LLM-written and unaudited, and it is not to be relied on. Replace it before offering PureDarwin instances to anyone+ who would store secrets in them.++### 2.4 The GPU parts for macOS users++We ship these. The user's disk script installs them into their own macOS disk:++| Artifact | License |+|---|---|+| `gpu/xnu-cpu-metal` (the Metal plugin `XnuCpuMetal.bundle`: metal2vulkan, lavapipe) | GPL-2.0-or-later |+| the Darwin Venus driver (`gpu/venus/build-darwin.sh`) and `gpu/xnu-drm/darwin` (libxnudrm) | MIT |++### 2.5 What we never ship, store or cache++- Apple's kernelcache, or any kernel collection made from it (`kc-apple.bin`, `kc.bin`)+- macOS system disks, IPSWs or installers, or anything taken from them: cryptexes, the static trust cache+ (`trustcache-mac.bin`), keybags+- screenshots of macOS for marketing. `docs/images/` shows macOS for documentation, and Apple's interface and+ wallpaper in them are Apple's.++## 3. Operator: preparing a host++1. **Host OS.** arm64 Ubuntu, either directly on the hardware or as a VM. On an Apple Silicon Mac the VM runs under+ krunkit (krunkit, libkrun, virglrenderer, MoltenVK and gvproxy under `$KRUN`; `scripts/krun-vm.sh`,+ `scripts/install-krun-agent.sh`), which gives it the host GPU through virtio-gpu Venus.+2. **Memory.** `scripts/vm-install-fki-service.sh` with `LINUX_MEM`, `CARVE_BASE` and `CARVE_MB` for that host's+ physical memory map. The carve-out is RAM Linux never manages. The hosted kernel's `RAM_MB` has to fit inside it+ (8 GB → `RAM_MB=7900`). Reboot once.+3. **Kit.** Unpack it to `/opt/xnulinux/kit`, and install `kc-free.bin` as `/lib/firmware/xnu/kc-free.bin`.+4. **Default system.** Put the PureDarwin disk at `/var/lib/xnulinux/pd.img` with its `pd.conf`. Configure+ `/etc/xnulinux.conf` as follows, then run `scripts/install-service.sh`:+ ```+ IMAGE=xnu/kc-free.bin+ TRUSTCACHE=+ MAC_CONF=/var/lib/xnulinux/pd.conf+ DISK=/var/lib/xnulinux/pd.img+ GPU=off+ CPUS=2+ RAM_MB=7900+ ```+5. **Isolation.** The hosted kernel runs at EL1 inside the Linux kernel, so a hosted system that is compromised owns+ that Linux. **The tenant boundary is the VM (or the machine), never the Linux.** Run one Linux VM per tenant, with one+ hosted system in it. Never run two users' hosted systems in one Linux.++## 4. Running Apple's macOS++The user runs these steps themselves: they download Apple's files and accept Apple's license. They need python3, `lzfse`+(`apt install lzfse`) and network access to Apple's CDN on the Linux host, and a Mac to make the system disk with+Apple's installer (`tart` or another Virtualization.framework installer).++1. **Kernel collection: link Apple's kexts into the shipped kit.** On the Linux host:+ ```+ /opt/xnulinux/scripts/apple-kc/link.sh /opt/xnulinux/kit+ ```+ It downloads only `kernelcache.release.vma2` from Apple's macOS 27.2 IPSW (HTTP range requests, about 81 MB, not the+ whole IPSW) and checks its sha256 against `kit.json`. It then links the Apple kexts the kit names (31, 72 with their dependencies) with our kernel+ and kexts using `scripts/kclink`, and installs the result as `/lib/firmware/xnu/kc-apple.bin`. A local IPSW, its URL,+ the IM4P or an unpacked kernelcache can be given as a second argument instead. The output is the same byte for byte+ on every machine.+2. **System disk: Apple's installer, on a Mac.** Install macOS from Apple's IPSW into a Virtualization.framework+ disk (`tart create NAME --from-ipsw …`), then run `scripts/mk-macvm-disk.sh` on an APFS clone of it. It merges the+ OS cryptex into the system volume (`docs/production.md` §3), adds to the Data volume: the local user and automatic login, the Metal plugin (§2.4), the+ console shell, and a list of disabled hardware daemons. It also takes the static trust cache from the disk's own+ Preboot volume. It sends `mac.img`, `mac.conf` and `trustcache-mac.bin` to the Linux host.+3. **Boot it.** Edit `/etc/xnulinux.conf`, then run `sudo systemctl restart xnulinux`:+ ```+ IMAGE=xnu/kc-apple.bin+ TRUSTCACHE=xnu/trustcache-mac.bin+ MAC_CONF=/var/tmp/mac.conf+ DISK=/var/tmp/mac.img+ GPU=auto+ ```+ Switching back to PureDarwin is `IMAGE=xnu/kc-free.bin` with its disk. Both collections share the same kernel and+ `xnu.ko`.+4. **macOS updates.** The user's disk and kernel collection must come from the builds the kit supports. When we+ ship a kit for a new macOS build, the user reruns step 1 (`link.sh` with the new kit) and step 2. Until then,+ macOS's Software Update must stay off: an updated disk will not match the kernel collection. If the disk's build is+ older than the kernelcache's, set `AMFI_PLATFORM` (default 26; `scripts/kc-amfi-platform.py`) when running+ `link.sh`.++## 5. Not ready yet++| Gap | Effect on the service |+|---|---|+| PureDarwin's corecrypto is unaudited (§2.3) | blocks offering PureDarwin for anything that keeps secrets |+| Making the macOS disk needs a Mac with Xcode and `tart` (`mk-macvm-disk.sh`), and the PureDarwin disk needs `hdiutil` (`mk-puredarwin-disk.sh`) | users need a Mac to make their macOS disk; a Linux disk maker (from the IPSW's APFS images) would remove that. Check `tart`'s own license for commercial use, or use another Virtualization.framework installer. The PureDarwin disk should move to a Linux build (`mkfs.hfsplus`) so the pipeline runs without a Mac |+| One kit per macOS build, fixed segment slots | each macOS release needs a new kit before users can update |+| AMFI relaxed (`amfi_get_out_of_my_way=1`) and SIP partly off (`lp-sip0`); the OS cryptex merged into the system volume | the hosted macOS is less locked down than a real Mac. State this in the service's documentation (`docs/production.md` §3) |+| The keystore is fresh at every boot | FileVault-style data protection does not persist across reboots |+| GPU bridge only for virtio-gpu (Venus) | Mac hosts get the host GPU. Bare-metal hosts render on the CPU |+| Bare-metal hosts need their own carve-out layout (`mem=`, `carve_base`) | one layout per host model, set up when it is provisioned |+| `xnu.ko` built on the host at boot | needs kernel headers and a compiler on the host. Package it as DKMS |diff --git a/kexts/XnuCpuMetal/XnuCpuMetal.cpp b/kexts/XnuCpuMetal/XnuCpuMetal.cppindex 2b5ac4a..f0ceae4 100644--- a/kexts/XnuCpuMetal/XnuCpuMetal.cpp+++ b/kexts/XnuCpuMetal/XnuCpuMetal.cpp@@ -8,7 +8,7 @@#include <IOKit/IOLib.h>#include <mach/kmod.h>-// IOGraphicsFamily's abstract accelerator class; kc-build fills the subclass's vtable from it (the JSON's "vtable").+// IOGraphicsFamily's abstract accelerator class; scripts/kclink fills the subclass's vtable from it (the JSON's "vtable").class IOAccelerator : public IOService {OSDeclareAbstractStructors(IOAccelerator)};diff --git a/kexts/free/compat/devfs-ready.h b/kexts/free/compat/devfs-ready.hnew file mode 100644index 0000000..3db711c--- /dev/null+++ b/kexts/free/compat/devfs-ready.h@@ -0,0 +1,14 @@+// SPDX-License-Identifier: APSL-2.0+// PureDarwin's IOMediaBSDClient waits on devfs_is_ready(), a call PureDarwin's kernel adds. This kernel has devfs up+// before IOKit matches the storage stack, as macOS does, so it is always ready here. Included with -include.+#ifdef __cplusplus+extern "C" {+#endif+static inline int+devfs_is_ready(void)+{+ return 1;+}+#ifdef __cplusplus+}+#endifdiff --git a/kexts/free/compat/include/stdio.h b/kexts/free/compat/include/stdio.hnew file mode 100644index 0000000..f07fb06--- /dev/null+++ b/kexts/free/compat/include/stdio.h@@ -0,0 +1,8 @@+// SPDX-License-Identifier: APSL-2.0+// The kernel has no <stdio.h>; PureDarwin's AMFI stub includes it for printf and snprintf only.+#ifndef XNULINUX_KEXT_STDIO_H+#define XNULINUX_KEXT_STDIO_H+#include <stddef.h>+int printf(const char *fmt, ...) __attribute__((format(printf, 1, 2)));+int snprintf(char *buf, size_t len, const char *fmt, ...) __attribute__((format(printf, 3, 4)));+#endifdiff --git a/kexts/free/compat/kalloc-type.c b/kexts/free/compat/kalloc-type.cnew file mode 100644index 0000000..c60548e--- /dev/null+++ b/kexts/free/compat/kalloc-type.c@@ -0,0 +1,23 @@+// SPDX-License-Identifier: APSL-2.0+// PureDarwin's pthread and AMFI kexts build with XNU_KERNEL_PRIVATE (they reach into kernel structures), so their typed+// allocations call the kernel-internal kalloc_type_impl/kfree_type_impl, which a kext cannot link against: these forward+// them to the entry points the kernel exports to kexts.+#include <stdint.h>++extern void *kalloc_type_impl_external(const void *kt_view, uint32_t flags);+extern void kfree_type_impl_external(const void *kt_view, void *ptr);++void *kalloc_type_impl(const void *kt_view, uint32_t flags);+void kfree_type_impl(const void *kt_view, void *ptr);++void *+kalloc_type_impl(const void *kt_view, uint32_t flags)+{+ return kalloc_type_impl_external(kt_view, flags);+}++void+kfree_type_impl(const void *kt_view, void *ptr)+{+ kfree_type_impl_external(kt_view, ptr);+}diff --git a/kexts/free/compat/kmod-start.c b/kexts/free/compat/kmod-start.cnew file mode 100644index 0000000..c6d5082--- /dev/null+++ b/kexts/free/compat/kmod-start.c@@ -0,0 +1,21 @@+// SPDX-License-Identifier: APSL-2.0+// kmod start and stop for the free kexts whose work is done by their IOKit classes (static constructors run by OSKext):+// scripts/kclink/kclink.py --native wants a start and a stop routine in every kext it links from objects.+#include <mach/kmod.h>++kern_return_t native_kext_start(kmod_info_t *ki, void *d);+kern_return_t native_kext_stop(kmod_info_t *ki, void *d);++kern_return_t+native_kext_start(kmod_info_t *ki, void *d)+{+ (void)ki; (void)d;+ return KERN_SUCCESS;+}++kern_return_t+native_kext_stop(kmod_info_t *ki, void *d)+{+ (void)ki; (void)d;+ return KERN_SUCCESS;+}diff --git a/kexts/free/compat/loadtag.c b/kexts/free/compat/loadtag.cnew file mode 100644index 0000000..0427d69--- /dev/null+++ b/kexts/free/compat/loadtag.c@@ -0,0 +1,14 @@+// SPDX-License-Identifier: APSL-2.0+// What libkmod gives a kext linked as a bundle: its load tag, from its own kmod_info. A kext linked into the collection+// from objects has no libkmod; hfs only uses the tag to hold itself loaded while a volume is mounted, and a kext of the+// boot collection never unloads, so there is no tag to give (kOSKextInvalidLoadTag: the retain and release are refused,+// which changes nothing).+#include <stdint.h>++uint32_t OSKextGetCurrentLoadTag(void);++uint32_t+OSKextGetCurrentLoadTag(void)+{+ return (uint32_t)-1;+}diff --git a/kexts/free/compat/osmalloc.c b/kexts/free/compat/osmalloc.cnew file mode 100644index 0000000..bc13316--- /dev/null+++ b/kexts/free/compat/osmalloc.c@@ -0,0 +1,47 @@+// SPDX-License-Identifier: APSL-2.0+// The OSMalloc KPI (libkern/OSMalloc.h) that PureDarwin's IOStorageFamily still calls and this kernel no longer+// implements: a tag is a small allocation of its own, memory is IOMallocData. Tags are opaque to the callers, so the+// header (whose types this kernel does not export to kexts any more) is not needed.+#include <IOKit/IOLib.h>++#define TAG_SIZE 64++void *OSMalloc_Tagalloc(const char *name, uint32_t flags);+void OSMalloc_Tagfree(void *tag);+void *OSMalloc(uint32_t size, void *tag);+void *OSMalloc_noblock(uint32_t size, void *tag);+void OSFree(void *addr, uint32_t size, void *tag);++void *+OSMalloc_Tagalloc(const char *name, uint32_t flags)+{+ (void)name; (void)flags;+ return IOMallocZeroData(TAG_SIZE);+}++void+OSMalloc_Tagfree(void *tag)+{+ IOFreeData(tag, TAG_SIZE);+}++void *+OSMalloc(uint32_t size, void *tag)+{+ (void)tag;+ return IOMallocData(size);+}++void *+OSMalloc_noblock(uint32_t size, void *tag)+{+ (void)tag;+ return IOMallocData(size);+}++void+OSFree(void *addr, uint32_t size, void *tag)+{+ (void)tag;+ IOFreeData(addr, size);+}diff --git a/kexts/free/patches/corecrypto-arm64e-sptr.patch b/kexts/free/patches/corecrypto-arm64e-sptr.patchnew file mode 100644index 0000000..6df7a5d--- /dev/null+++ b/kexts/free/patches/corecrypto-arm64e-sptr.patch@@ -0,0 +1,351 @@+diff --git a/cc/include/corecrypto/cc_config.h b/cc/include/corecrypto/cc_config.h+index e32f0d3..753e64e 100644+--- a/cc/include/corecrypto/cc_config.h++++ b/cc/include/corecrypto/cc_config.h+@@ -235,4 +235,20 @@+ #define CC_SMALL_CODE 0+ #endif+++++/*++ * xnulinux: function pointers in the structures the kernel shares with corecrypto (digest and mode descriptors, the++ * kernel PRNG's function table) are signed on arm64e kernels as Apple's corecrypto headers declare them (CC_SPTR), so++ * the kernel's authenticated calls through them check out.++ */++#ifndef CC_SPTR++#if __has_feature(ptrauth_calls) && defined(KERNEL)++#include <ptrauth.h>++#define CC_SPTR(_sn_, _n_) \++ __ptrauth(ptrauth_key_process_independent_code, 1, ptrauth_string_discriminator("cc_" #_sn_ #_n_)) _n_++#else++#define CC_SPTR(_sn_, _n_) _n_++#endif++#endif+++ #endif /* __CORECRYPTO_CC_CONFIG_H__ */+diff --git a/ccdigest/include/corecrypto/ccdigest.h b/ccdigest/include/corecrypto/ccdigest.h+index 3c77856..7249bc2 100644+--- a/ccdigest/include/corecrypto/ccdigest.h++++ b/ccdigest/include/corecrypto/ccdigest.h+@@ -76,11 +76,11 @@ struct ccdigest_info {+ /* the initial state of the hash */+ const void *initial_state;++- void (*compress)(ccdigest_state_t state,++ void (*CC_SPTR(ccdigest_info, compress))(ccdigest_state_t state,+ size_t nblocks,+ const void *in);++- void (*final)(const struct ccdigest_info *di,++ void (*CC_SPTR(ccdigest_info, final))(const struct ccdigest_info *di,+ ccdigest_ctx_t ctx,+ void *digest);++diff --git a/ccdrbg/include/corecrypto/ccdrbg_impl.h b/ccdrbg/include/corecrypto/ccdrbg_impl.h+index ec1c390..95bcc50 100644+--- a/ccdrbg/include/corecrypto/ccdrbg_impl.h++++ b/ccdrbg/include/corecrypto/ccdrbg_impl.h+@@ -16,7 +16,7 @@ struct ccdrbg_state;+ struct ccdrbg_info {+ size_t size;++- ccdrbg_status_t (*init)(const struct ccdrbg_info *info,++ ccdrbg_status_t (*CC_SPTR(ccdrbg_info, init))(const struct ccdrbg_info *info,+ struct ccdrbg_state *state,+ size_t entropy_length,+ const void *entropy,+@@ -25,19 +25,19 @@ struct ccdrbg_info {+ size_t ps_length,+ const void *ps);++- ccdrbg_status_t (*reseed)(struct ccdrbg_state *state,++ ccdrbg_status_t (*CC_SPTR(ccdrbg_info, reseed))(struct ccdrbg_state *state,+ size_t entropy_length,+ const void *entropy,+ size_t ad_length,+ const void *ad);++- ccdrbg_status_t (*generate)(struct ccdrbg_state *state,++ ccdrbg_status_t (*CC_SPTR(ccdrbg_info, generate))(struct ccdrbg_state *state,+ size_t out_length,+ void *out,+ size_t ad_length,+ const void *ad);++- void (*done)(struct ccdrbg_state *state);++ void (*CC_SPTR(ccdrbg_info, done))(struct ccdrbg_state *state);++ const void *custom;+ };+diff --git a/cckprng/include/corecrypto/cckprng.h b/cckprng/include/corecrypto/cckprng.h+index ab86b8e..87ef125 100644+--- a/cckprng/include/corecrypto/cckprng.h++++ b/cckprng/include/corecrypto/cckprng.h+@@ -45,13 +45,13 @@ struct cckprng_ctx {+ };++ struct cckprng_funcs {+- void (*init)(struct cckprng_ctx *ctx, size_t seed_nbytes, const void *seed, size_t nonce_nbytes, const void *nonce,++ void (*CC_SPTR(cckprng_funcs, init))(struct cckprng_ctx *ctx, size_t seed_nbytes, const void *seed, size_t nonce_nbytes, const void *nonce,+ cckprng_getentropy getentropy, void *getentropy_arg);+- void (*initgen)(struct cckprng_ctx *ctx, unsigned gen_idx);+- void (*reseed)(struct cckprng_ctx *ctx, size_t nbytes, const void *seed);+- void (*refresh)(struct cckprng_ctx *ctx);+- void (*generate)(struct cckprng_ctx *ctx, unsigned gen_idx, size_t nbytes, void *out);+- void (*init_with_getentropy)(struct cckprng_ctx *ctx, unsigned max_ngens, size_t seed_nbytes, const void *seed,++ void (*CC_SPTR(cckprng_funcs, initgen))(struct cckprng_ctx *ctx, unsigned gen_idx);++ void (*CC_SPTR(cckprng_funcs, reseed))(struct cckprng_ctx *ctx, size_t nbytes, const void *seed);++ void (*CC_SPTR(cckprng_funcs, refresh))(struct cckprng_ctx *ctx);++ void (*CC_SPTR(cckprng_funcs, generate))(struct cckprng_ctx *ctx, unsigned gen_idx, size_t nbytes, void *out);++ void (*CC_SPTR(cckprng_funcs, init_with_getentropy))(struct cckprng_ctx *ctx, unsigned max_ngens, size_t seed_nbytes, const void *seed,+ size_t nonce_nbytes, const void *nonce, cckprng_getentropy getentropy, void *getentropy_arg);+ };++diff --git a/ccmode/include/corecrypto/ccmode_impl.h b/ccmode/include/corecrypto/ccmode_impl.h+index 4178f73..d0e6018 100644+--- a/ccmode/include/corecrypto/ccmode_impl.h++++ b/ccmode/include/corecrypto/ccmode_impl.h+@@ -87,12 +87,12 @@ struct ccmode_ecb {+ size_t size;+ size_t block_size;++- cc_error_t (*init)(const struct ccmode_ecb *ecb,++ cc_error_t (*CC_SPTR(ccmode_ecb, init))(const struct ccmode_ecb *ecb,+ ccecb_ctx *ctx,+ size_t key_size,+ const void *key);++- cc_error_t (*ecb)(const ccecb_ctx *ctx, size_t nblocks, const void *in,++ cc_error_t (*CC_SPTR(ccmode_ecb, ecb))(const ccecb_ctx *ctx, size_t nblocks, const void *in,+ void *out);++ void *pad;+@@ -151,12 +151,12 @@ struct ccmode_cbc {+ size_t size;+ size_t block_size;++- cc_error_t (*init)(const struct ccmode_cbc *cbc,++ cc_error_t (*CC_SPTR(ccmode_cbc, init))(const struct ccmode_cbc *cbc,+ cccbc_ctx *ctx,+ size_t key_size,+ const void *key);++- cc_error_t (*cbc)(const cccbc_ctx *ctx,++ cc_error_t (*CC_SPTR(ccmode_cbc, cbc))(const cccbc_ctx *ctx,+ cccbc_iv *iv,+ size_t nblocks,+ const void *in,+@@ -177,13 +177,13 @@ struct ccmode_cfb {+ size_t size;+ size_t block_size;++- cc_error_t (*init)(const struct ccmode_cfb *ofb,++ cc_error_t (*CC_SPTR(ccmode_cfb, init))(const struct ccmode_cfb *ofb,+ cccfb_ctx *ctx,+ size_t key_size,+ const void *key,+ const void *iv);++- cc_error_t (*cfb)(cccfb_ctx *ctx,++ cc_error_t (*CC_SPTR(ccmode_cfb, cfb))(cccfb_ctx *ctx,+ size_t nbytes,+ const void *in,+ void *out);+@@ -200,13 +200,13 @@ struct ccmode_cfb8 {+ size_t size;+ size_t block_size;++- cc_error_t (*init)(const struct ccmode_cfb8 *ofb,++ cc_error_t (*CC_SPTR(ccmode_cfb8, init))(const struct ccmode_cfb8 *ofb,+ cccfb8_ctx *ctx,+ size_t key_size,+ const void *key,+ const void *iv);++- cc_error_t (*cfb8)(cccfb8_ctx *ctx,++ cc_error_t (*CC_SPTR(ccmode_cfb8, cfb8))(cccfb8_ctx *ctx,+ size_t nbytes,+ const void *in,+ void *out);+@@ -223,13 +223,13 @@ struct ccmode_ofb {+ size_t size;+ size_t block_size;++- cc_error_t (*init)(const struct ccmode_ofb *ofb,++ cc_error_t (*CC_SPTR(ccmode_ofb, init))(const struct ccmode_ofb *ofb,+ ccofb_ctx *ctx,+ size_t key_size,+ const void *key,+ const void *iv);++- cc_error_t (*ofb)(ccofb_ctx *ctx,++ cc_error_t (*CC_SPTR(ccmode_ofb, ofb))(ccofb_ctx *ctx,+ size_t nbytes,+ const void *in,+ void *out);+@@ -249,17 +249,17 @@ struct ccmode_ctr {+ size_t block_size;+ size_t ecb_block_size;++- cc_error_t (*init)(const struct ccmode_ctr *ctr,++ cc_error_t (*CC_SPTR(ccmode_ctr, init))(const struct ccmode_ctr *ctr,+ ccctr_ctx *ctx,+ size_t key_size,+ const void *key,+ const void *iv);++- cc_error_t (*setctr)(const struct ccmode_ctr *ctr,++ cc_error_t (*CC_SPTR(ccmode_ctr, setctr))(const struct ccmode_ctr *ctr,+ ccctr_ctx *ctx,+ const void *counter);++- cc_error_t (*ctr)(ccctr_ctx *ctx,++ cc_error_t (*CC_SPTR(ccmode_ctr, ctr))(ccctr_ctx *ctx,+ size_t nbytes,+ const void *in,+ void *out);+@@ -287,29 +287,29 @@ struct ccmode_gcm {+ int encdec;+ size_t block_size;++- cc_error_t (*init)(const struct ccmode_gcm *gcm,++ cc_error_t (*CC_SPTR(ccmode_gcm, init))(const struct ccmode_gcm *gcm,+ ccgcm_ctx *cyx,+ size_t key_size,+ const void *key);++- cc_error_t (*set_iv)(ccgcm_ctx *ctx,++ cc_error_t (*CC_SPTR(ccmode_gcm, set_iv))(ccgcm_ctx *ctx,+ size_t iv_size,+ const void *iv);++- cc_error_t (*gmac)(ccgcm_ctx *ctx,++ cc_error_t (*CC_SPTR(ccmode_gcm, gmac))(ccgcm_ctx *ctx,+ size_t nbytes,+ const void *in);++- cc_error_t (*gcm)(ccgcm_ctx *ctx,++ cc_error_t (*CC_SPTR(ccmode_gcm, gcm))(ccgcm_ctx *ctx,+ size_t nbytes,+ const void *in,+ void *out);++- cc_error_t (*finalize)(ccgcm_ctx *ctx,++ cc_error_t (*CC_SPTR(ccmode_gcm, finalize))(ccgcm_ctx *ctx,+ size_t tag_size,+ void *tag);++- cc_error_t (*reset)(ccgcm_ctx *ctx);++ cc_error_t (*CC_SPTR(ccmode_gcm, reset))(ccgcm_ctx *ctx);++ const void *custom;+ };+@@ -327,23 +327,23 @@ struct ccmode_xts {+ size_t tweak_size;+ size_t block_size;++- cc_error_t (*init)(const struct ccmode_xts *xts,++ cc_error_t (*CC_SPTR(ccmode_xts, init))(const struct ccmode_xts *xts,+ ccxts_ctx *ctx,+ size_t key_size,+ const void *data_key,+ const void *tweak_key);++- cc_error_t (*key_sched)(const struct ccmode_xts *xts,++ cc_error_t (*CC_SPTR(ccmode_xts, key_sched))(const struct ccmode_xts *xts,+ ccxts_ctx *ctx,+ size_t key_size,+ const void *data_key,+ const void *tweak_key);++- cc_error_t (*set_tweak)(const ccxts_ctx *ctx,++ cc_error_t (*CC_SPTR(ccmode_xts, set_tweak))(const ccxts_ctx *ctx,+ ccxts_tweak *tweak,+ const void *iv);++- void *(*xts)(const ccxts_ctx *ctx,++ void *(*CC_SPTR(ccmode_xts, xts))(const ccxts_ctx *ctx,+ ccxts_tweak *tweak,+ size_t nblocks,+ const void *in,+@@ -368,12 +368,12 @@ struct ccmode_ccm {+ size_t nonce_size;+ size_t block_size;++- cc_error_t (*init)(const struct ccmode_ccm *ccm,++ cc_error_t (*CC_SPTR(ccmode_ccm, init))(const struct ccmode_ccm *ccm,+ ccccm_ctx *ctx,+ size_t key_size,+ const void *key);++- cc_error_t (*set_iv)(ccccm_ctx *ctx,++ cc_error_t (*CC_SPTR(ccmode_ccm, set_iv))(ccccm_ctx *ctx,+ ccccm_nonce *nonce_ctx,+ size_t nonce_len,+ const void *nonce,+@@ -381,22 +381,22 @@ struct ccmode_ccm {+ size_t auth_len,+ size_t data_len);++- cc_error_t (*cbcmac)(ccccm_ctx *ctx,++ cc_error_t (*CC_SPTR(ccmode_ccm, cbcmac))(ccccm_ctx *ctx,+ ccccm_nonce *nonce,+ size_t nbytes,+ const void *in);++- cc_error_t (*ccm)(ccccm_ctx *ctx,++ cc_error_t (*CC_SPTR(ccmode_ccm, ccm))(ccccm_ctx *ctx,+ ccccm_nonce *nonce,+ size_t nbytes,+ const void *in,+ void *out);++- cc_error_t (*finalize)(ccccm_ctx *ctx,++ cc_error_t (*CC_SPTR(ccmode_ccm, finalize))(ccccm_ctx *ctx,+ ccccm_nonce *nonce,+ void *mac);++- cc_error_t (*reset)(ccccm_ctx *ctx,++ cc_error_t (*CC_SPTR(ccmode_ccm, reset))(ccccm_ctx *ctx,+ ccccm_nonce *nonce);++ const void *custom;+diff --git a/ccrng/include/corecrypto/ccrng.h b/ccrng/include/corecrypto/ccrng.h+index 8cf93c8..94d5400 100644+--- a/ccrng/include/corecrypto/ccrng.h++++ b/ccrng/include/corecrypto/ccrng.h+@@ -14,7 +14,7 @@+ CC_BEGIN_DECLS++ struct ccrng_state {+- cc_error_t (*generate)(struct ccrng_state *rng,++ cc_error_t (*CC_SPTR(ccrng_state, generate))(struct ccrng_state *rng,+ size_t out_length,+ void *out);+ };+diff --git a/ccrng/include/corecrypto/ccrng_system.h b/ccrng/include/corecrypto/ccrng_system.h+index 16d83d0..6f3843c 100644+--- a/ccrng/include/corecrypto/ccrng_system.h++++ b/ccrng/include/corecrypto/ccrng_system.h+@@ -15,7 +15,7 @@ CC_BEGIN_DECLS++ // deprecated wrapper over ccrng(), kept for existing callers+ struct ccrng_system_state {+- cc_error_t (*generate)(struct ccrng_state *rng, size_t out_length, void *out);++ cc_error_t (*CC_SPTR(ccrng_state, generate))(struct ccrng_state *rng, size_t out_length, void *out); /* xnulinux: read as a ccrng_state */+ int fd;+ };++diff --git a/corecrypto_kext/main.c b/corecrypto_kext/main.c+index 3e992cb..a3a859c 100644+--- a/corecrypto_kext/main.c++++ b/corecrypto_kext/main.c+@@ -173,7 +173,7 @@ static bool crypto_hmac_verify(crypto_digest_alg_t alg, const void *key, size_t++ // pd: random handles are ccrng_state shaped, the kmem one is a lock-free integer-only chacha20 stream+ struct kmem_rng {+- cc_error_t (*generate)(struct ccrng_state *rng, size_t nbytes, void *out);++ cc_error_t (*CC_SPTR(ccrng_state, generate))(struct ccrng_state *rng, size_t nbytes, void *out); /* xnulinux: read as a ccrng_state */+ ccchacha20_ctx chacha;+ };+diff --git a/scripts/apple-kc/im4p.py b/scripts/apple-kc/im4p.pynew file mode 100755index 0000000..6f630ac--- /dev/null+++ b/scripts/apple-kc/im4p.py@@ -0,0 +1,175 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: GPL-2.0-only+"""Unpack a kernelcache for scripts/apple-kc/link.sh, with python3 alone (and lzfse for an LZFSE payload):++ im4p.py INPUT OUTPUT [MEMBER]++INPUT is an IPSW (a zip: MEMBER, default kernelcache.release.vma2, is read from it), an IPSW's URL (Apple's own:+only the member is downloaded, with HTTP range requests), an IM4P, or an unpacked Mach-O (copied). An IM4P is DER: SEQUENCE { "IM4P", type, description, OCTET STRING payload, ... }; the payload is LZFSE+("bvx2...", decoded by the lzfse tool: apt install lzfse), LZSS ("complzss" with Apple's 0x180-byte header), or plain.+"""+import http.client+import shutil+import struct+import subprocess+import sys+import tempfile+import time+import urllib.request+import zipfile+++class Remote:+ """A read-only, seekable file over HTTP range requests (what zipfile needs to read one member of a remote zip).+ Small reads (zip records) go through a cache of 256 KiB blocks; large ones (the member) are fetched as they are, in+ 16 MiB pieces. A piece whose transfer breaks off is asked for again (a few times): a download over a long path does."""+ BLOCK, PIECE, TRIES = 1 << 18, 1 << 24, 6++ def __init__(self, url):+ self.url, self.pos, self.cache = url, 0, {}+ with urllib.request.urlopen(urllib.request.Request(url, method='HEAD'), timeout=60) as r:+ self.size = int(r.headers['Content-Length'])++ def seekable(self):+ return True++ def tell(self):+ return self.pos++ def seek(self, offset, whence=0):+ self.pos = offset if whence == 0 else self.pos + offset if whence == 1 else self.size + offset+ return self.pos++ def fetch(self, start, end):+ """Bytes start..end (inclusive)."""+ for attempt in range(self.TRIES):+ try:+ req = urllib.request.Request(self.url, headers={'Range': f'bytes={start}-{end}', 'Accept-Encoding': 'identity'})+ with urllib.request.urlopen(req, timeout=120) as r:+ if r.status != 206:+ raise SystemExit(f'{self.url}: the server does not serve byte ranges')+ data = r.read()+ if len(data) == end - start + 1:+ return data+ error = f'{len(data)} of {end - start + 1} bytes'+ except (OSError, http.client.HTTPException) as e:+ error = e+ print(f'bytes {start}-{end}: {error}; again', file=sys.stderr)+ time.sleep(2 ** attempt)+ raise SystemExit(f'{self.url}: bytes {start}-{end} could not be read')++ def read(self, n=-1):+ if n < 0:+ n = self.size - self.pos+ n = max(0, min(n, self.size - self.pos))+ out = bytearray()+ if n > self.BLOCK:+ while len(out) < n:+ k = min(self.PIECE, n - len(out))+ out += self.fetch(self.pos, self.pos + k - 1)+ self.pos += k+ return bytes(out)+ while len(out) < n:+ i = self.pos // self.BLOCK+ if i not in self.cache:+ self.cache[i] = self.fetch(i * self.BLOCK, min((i + 1) * self.BLOCK, self.size) - 1)+ k = self.pos % self.BLOCK+ piece = self.cache[i][k:k + n - len(out)]+ out += piece+ self.pos += len(piece)+ return bytes(out)+++def der(data, at):+ """(tag, start of contents, end of contents) of the DER element at `at`."""+ tag, n = data[at], data[at + 1]+ at += 2+ if n & 0x80:+ k = n & 0x7f+ n = int.from_bytes(data[at:at + k], 'big')+ at += k+ return tag, at, at + n+++def payload(data):+ tag, at, end = der(data, 0)+ if tag != 0x30:+ raise SystemExit('not an IM4P (no DER SEQUENCE)')+ items = []+ while at < end:+ t, s, e = der(data, at)+ items.append((t, s, e))+ at = e+ if len(items) < 4 or data[items[0][1]:items[0][2]] != b'IM4P' or items[3][0] != 0x04:+ raise SystemExit('not an IM4P')+ return data[items[3][1]:items[3][2]]+++def lzss(src, size):+ """Apple's kernelcache LZSS (4096-byte window, 18-byte matches, threshold 2)."""+ N, F, T = 4096, 18, 2+ text = bytearray(b' ' * (N - F)) + bytearray(F)+ r, out, i, flags = N - F, bytearray(), 0, 0+ while i < len(src) and len(out) < size:+ flags >>= 1+ if not flags & 0x100:+ flags = src[i] | 0xff00+ i += 1+ if i >= len(src):+ break+ if flags & 1:+ c = src[i]+ i += 1+ out.append(c)+ text[r] = c+ r = (r + 1) & (N - 1)+ else:+ if i + 1 >= len(src):+ break+ p, q = src[i], src[i + 1]+ i += 2+ p |= (q & 0xf0) << 4+ for k in range((q & 0x0f) + T + 1):+ c = text[(p + k) & (N - 1)]+ out.append(c)+ text[r] = c+ r = (r + 1) & (N - 1)+ return bytes(out[:size])+++def main():+ if len(sys.argv) < 3:+ raise SystemExit(__doc__)+ src, dst = sys.argv[1], sys.argv[2]+ member = sys.argv[3] if len(sys.argv) > 3 else 'kernelcache.release.vma2'+ if src.startswith(('https://', 'http://')):+ print(f'reading {member} from {src}', file=sys.stderr)+ with zipfile.ZipFile(Remote(src)) as z:+ data = z.read(member)+ elif zipfile.is_zipfile(src):+ with zipfile.ZipFile(src) as z:+ data = z.read(member)+ else:+ data = open(src, 'rb').read()+ if data[:4] == b'\xcf\xfa\xed\xfe':+ open(dst, 'wb').write(data)+ return+ body = payload(data)+ if body[:4] == b'bvx2':+ lz = shutil.which('lzfse')+ if not lz:+ raise SystemExit('the kernelcache is LZFSE-compressed: install lzfse (apt install lzfse)')+ with tempfile.NamedTemporaryFile() as f:+ f.write(body)+ f.flush()+ subprocess.run([lz, '-decode', '-i', f.name, '-o', dst], check=True)+ elif body[:8] == b'complzss':+ size, = struct.unpack('>I', body[12:16])+ open(dst, 'wb').write(lzss(body[0x180:], size))+ elif body[:4] == b'\xcf\xfa\xed\xfe':+ open(dst, 'wb').write(body)+ else:+ raise SystemExit(f'unknown IM4P payload ({body[:8]!r})')+++main()diff --git a/scripts/apple-kc/keep.txt b/scripts/apple-kc/keep.txtnew file mode 100644index 0000000..69f32f3--- /dev/null+++ b/scripts/apple-kc/keep.txt@@ -0,0 +1,37 @@+# Apple's kexts the hosted macOS keeps from macOS 27.2's kernelcache (bundle IDs, one per line), with every kext they+# depend on (scripts/kclink/kclink.py --keep)+com.apple.security.AppleImage4+com.apple.driver.AppleMobileFileIntegrity+com.apple.security.sandbox+com.apple.security.quarantine+com.apple.AppleSystemPolicy+com.apple.kec.pthread+com.apple.filesystems.apfs+com.apple.AppleFSCompression.AppleFSCompressionTypeZlib+com.apple.AppleFSCompression.AppleFSCompressionTypeDataless+com.apple.iokit.IOHIDFamily+com.apple.iokit.IOTimeSyncFamily+com.apple.plugin.IOgPTPPlugin+com.apple.driver.AppleDiskImages2+com.apple.filesystems.hfs.kext+com.apple.driver.AppleMultitouchDriver+com.apple.iokit.IOBluetoothFamily+com.apple.driver.driverkit.serial+# hdiutil's disk images (IOHDIXController)+com.apple.driver.DiskImages+com.apple.driver.DiskImages.FileBackingStore+com.apple.driver.DiskImages.KernelBacked+com.apple.driver.DiskImages.RAMBackingStore+com.apple.driver.DiskImages.ReadWriteDiskImage+com.apple.driver.DiskImages.UDIFDiskImage+# IOSurface for actool, the graphics families XnuDisplay and XnuCpuMetal subclass, and lifs+com.apple.iokit.IOSurface+com.apple.iokit.IOGraphicsFamily+com.apple.filesystems.lifs+com.apple.iokit.IOMobileGraphicsFamily+com.apple.iokit.IOAVFamily+# the keystore of Apple's virtual platform (VirtualMac): AppleKeyStore and AppleCredentialManager in software, no SEP+# hardware; AppleVirtualPlatform is their library+com.apple.driver.AppleVirtualPlatform+com.apple.driver.AppleVPCredentialManager+com.apple.driver.AppleVPKeyStorediff --git a/scripts/apple-kc/link.sh b/scripts/apple-kc/link.shnew file mode 100755index 0000000..6e9e1f4--- /dev/null+++ b/scripts/apple-kc/link.sh@@ -0,0 +1,48 @@+#!/bin/bash+# SPDX-License-Identifier: GPL-2.0-only+# On the machine that runs xnu.ko (or any Linux or macOS with python3): link Apple's kexts from the user's own+# copy of macOS's kernelcache with the kernel and kexts of a kit (scripts/apple-kc/package.sh) into a kernel collection+# to boot macOS with:+# scripts/apple-kc/link.sh KIT [KERNELCACHE [OUTPUT]] (OUTPUT: /lib/firmware/xnu/kc-apple.bin where that exists)+# then IMAGE=xnu/kc-apple.bin scripts/xnulinux-boot.sh. Nothing of Apple's is in the kit; the collection this makes is+# the one scripts/vm-xnu-rebuild.sh makes from the same kernelcache, byte for byte (both link with scripts/kclink).+#+# KERNELCACHE is macOS 27.2's kernelcache.release.vma2 (Apple's virtual Mac): the 27.2 IPSW itself or its URL (by+# default Apple's, KIT/kit.json: only the kernelcache is downloaded), the IM4P from it, or that unpacked+# (scripts/apple-kc/im4p.py; an LZFSE payload needs the lzfse tool). The kit's kernel was linked to fit that+# collection, so any other one is refused (sha256 in KIT/kit.json).+set -euo pipefail+POC=$(cd "$(dirname "$0")/../.." && pwd)+[ $# -ge 1 ] || { sed -n '3,6p' "$0" >&2; exit 2; }+abs() { python3 -c 'import os,sys; print(os.path.abspath(sys.argv[1]))' "$1"; }+KIT=$(abs "$1"); OUT=$(abs "${3:-$KIT/kc-apple.bin}")+INSTALL=; [ $# -lt 3 ] && [ -d /lib/firmware/xnu ] && INSTALL=/lib/firmware/xnu/kc-apple.bin+W=${APPLE_KC_WORK:-$KIT/.work}; mkdir -p "$W"+kit() { python3 -c 'import json,sys; v=json.load(open(sys.argv[1]))+for k in sys.argv[2].split("."): v=v[k]+print(" ".join(v) if isinstance(v, list) else v)' "$KIT/kit.json" "$1"; }+sha() { python3 -c 'import hashlib,sys; h=hashlib.sha256(); f=open(sys.argv[1],"rb")+for b in iter(lambda: f.read(1<<24), b""): h.update(b)+print(h.hexdigest())' "$1"; }+magic() { python3 -c 'import sys; print(open(sys.argv[1],"rb").read(4).hex())' "$1"; }++KC=${2:-$(kit ipsw)}; case "$KC" in http://*|https://*) ;; *) KC=$(abs "$KC") ;; esac+# the kernelcache, unpacked (a Mach-O starts cffaedfe; else an IPSW, its URL or an IM4P)+if [[ "$KC" == http* ]] || [ "$(magic "$KC")" != cffaedfe ]; then+ rm -f "$W/kernelcache"; python3 "$POC/scripts/apple-kc/im4p.py" "$KC" "$W/kernelcache"; KC=$W/kernelcache+fi+want=$(kit kernelcache_sha256); have=$(sha "$KC")+if [ "$want" != "$have" ]; then+ echo "this kit links $(kit kernelcache) (sha256 $want); ${2:-$(kit ipsw)} is another one ($have)" >&2; exit 1+fi++( cd "$KIT" && python3 "$POC/scripts/kclink/kclink.py" "$KC" kernel.macho "$OUT" --keep $(kit keep) \+ --native $(kit native) --rebind $(kit rebind) > "$W/kclink.log" 2>&1 ) ||+ { tail -5 "$W/kclink.log" >&2; echo "kclink failed: $W/kclink.log" >&2; exit 1; }+grep -E "^wrote" "$W/kclink.log" || true+# AMFI of 27.2 expects platform version 27; the system disks the kit was made for carry 26 (scripts/kc-amfi-platform.py)+python3 "$POC/scripts/kc-amfi-platform.py" "$OUT" "${AMFI_PLATFORM:-$(kit amfi_platform)}"+if [ -n "$INSTALL" ]; then+ sudo install -m 644 "$OUT" "$INSTALL" && OUT=$INSTALL+fi+echo "kernel collection with Apple's kexts: $OUT (boot it: IMAGE=xnu/$(basename "$OUT") scripts/xnulinux-boot.sh)"diff --git a/scripts/apple-kc/package.sh b/scripts/apple-kc/package.shnew file mode 100755index 0000000..184a912--- /dev/null+++ b/scripts/apple-kc/package.sh@@ -0,0 +1,59 @@+#!/bin/bash+# SPDX-License-Identifier: GPL-2.0-only+# In the VM, after scripts/vm-xnu-rebuild.sh: the kit a user links Apple's kexts with on their own machine+# (scripts/apple-kc/link.sh), so that what is distributed holds nothing of Apple's:+# KIT/kernel.macho the hosted kernel, as vm-xnu-rebuild.sh linked it (its segment slots fit macOS 27.2's collection)+# KIT/kexts/NAME/ xnulinux's own kexts, the objects and the description scripts/kclink links them from+# KIT/kc-free.bin the collection without Apple's kexts (scripts/free-kc/build.sh), when it was built+# KIT/kit.json what link.sh needs to make the same collection vm-xnu-rebuild.sh makes: the kernelcache it must+# be given (sha256) and where Apple has it, the Apple kexts to keep (scripts/apple-kc/keep.txt),+# the pointers to rebind (scripts/apple-kc/rebind.txt), the kexts of ours, AMFI's platform version+# scripts/apple-kc/package.sh [KIT] (default ~/w/apple-kc-kit)+set -euo pipefail+POC=$(cd "$(dirname "$0")/../.." && pwd)+DVM=${DVM:-$HOME/w/dvm}; KIT=${1:-$HOME/w/apple-kc-kit}+[ -s $DVM/out/k27/natives.txt ] || { echo "$DVM/out/k27/natives.txt: run scripts/vm-xnu-rebuild.sh (with out/kc/kc27.bin) first" >&2; exit 1; }+rm -rf $KIT; mkdir -p $KIT/kexts+cp $DVM/out/k27/kernel-k27.macho $KIT/kernel.macho+[ -e /lib/firmware/xnu/kc-free.bin ] && cp /lib/firmware/xnu/kc-free.bin $KIT/kc-free.bin+python3 - $DVM $KIT "$(sha256sum $DVM/out/kc/kc27.bin | cut -d' ' -f1)" \+ "$(git -C $POC rev-parse HEAD 2>/dev/null || echo unknown)" "${AMFI_PLATFORM:-26}" $(cat $DVM/out/k27/natives.txt) -- \+ $(grep -v '^#' $POC/scripts/apple-kc/keep.txt) -- $(grep -v '^#' $POC/scripts/apple-kc/rebind.txt) <<'PY'+import json, os, shutil, sys+from pathlib import Path+dvm, kit, kc_sha, poc_rev, amfi = sys.argv[1:6]+rest = sys.argv[6:]+natives, rest = rest[:rest.index('--')], rest[rest.index('--') + 1:]+keep, rebind = rest[:rest.index('--')], rest[rest.index('--') + 1:]+kit = Path(kit)+specs = []+for path in natives:+ spec = json.loads(Path(path).read_text())+ name = spec['name']+ objects = Path(dvm, spec['objects']) # relative to macOS-DroidVM's root, where vm-xnu-rebuild.sh links+ d = kit / 'kexts' / name+ d.mkdir(parents=True)+ copied = []+ for o in json.loads(objects.read_text()):+ assert not (d / Path(o).name).exists(), (name, o)+ shutil.copy(o, d / Path(o).name)+ copied.append(f'kexts/{name}/{Path(o).name}')+ (d / 'objects.json').write_text(json.dumps(copied, indent=1) + '\n')+ spec['objects'] = f'kexts/{name}/objects.json' # relative to the kit, where link.sh runs kclink+ (d / f'{name}.json').write_text(json.dumps(spec, indent=2) + '\n')+ specs.append(f'kexts/{name}/{name}.json')+seen = set()+keep = [k for k in keep if k and not (k in seen or seen.add(k))]+(kit / 'kit.json').write_text(json.dumps({+ 'kernelcache_sha256': kc_sha,+ 'kernelcache': "macOS 27.2 (26B123) kernelcache.release.vma2, unpacked from its IM4P",+ 'ipsw': json.loads(Path(dvm, 'configs/macos-27.2-26B123.json').read_text())['ipsw']['url'],+ 'xnulinux_rev': poc_rev,+ 'amfi_platform': int(amfi),+ 'keep': keep,+ 'rebind': rebind,+ 'native': specs,+}, indent=1) + '\n')+print(f'{kit}: kernel, {len(specs)} kexts of ours, {len(keep)} Apple kexts to keep')+PY+du -sh $KITdiff --git a/scripts/apple-kc/rebind.txt b/scripts/apple-kc/rebind.txtnew file mode 100644index 0000000..9f3b9a9--- /dev/null+++ b/scripts/apple-kc/rebind.txt@@ -0,0 +1,9 @@+# Pointers of Apple's kexts that go to another of the kernel's symbols than the one they were linked to+# (scripts/kclink/kclink.py --rebind ADDRESS=SYMBOL; ADDRESS in macOS 27.2's vma2 kernelcache), one per line.+#+# AMFI's GOT slot for PAGE_SHIFT_CONST (the second of its __DATA_CONST,__got), which only CoreEntitlements'+# CEElementIterate reads: with it, the iteration fails whenever the stack pointer is within 0x80 bytes of a page start.+# On page-aligned kernel stacks and a fixed call chain that is a fixed outcome, and with this kernel's frames every+# spawn's entitlement dictionary copy failed ("failed to create OSDictionary copy: 14" panic). The kernel's+# k27_amfi_page_shift (31) stands in for it; AMFI's bytes stay as shipped.+0xfffffe0007b4bbc8=_k27_amfi_page_shiftdiff --git a/scripts/free-kc/build.sh b/scripts/free-kc/build.shnew file mode 100755index 0000000..4a7c5ae--- /dev/null+++ b/scripts/free-kc/build.sh@@ -0,0 +1,90 @@+#!/bin/bash+# SPDX-License-Identifier: GPL-2.0-only+# In the VM, after scripts/vm-xnu-rebuild.sh: a kernel collection with none of Apple's kexts. The hosted kernel and xnulinux's+# own kexts (XnuCPU, XnuDisk, XnuDrm), plus the kexts a Darwin userland needs, built from PureDarwin's sources as arm64e with+# this kernel's own compile flags and headers (scripts/free-kc/kcc.py): corecrypto, a permissive AMFI, pthread,+# IOStorageFamily, HFSEncodings and hfs. It boots PureDarwin's userland from an HFS+ disk (scripts/mk-puredarwin-disk.sh):+# IMAGE=xnu/kc-free.bin DISK=... ROOT_UUID=... scripts/xnulinux-boot.sh+# Sources are fetched at pinned revisions; corecrypto gets kexts/free/patches/corecrypto-arm64e-sptr.patch.+#+# Nothing of Apple's is read: the collection is linked into an empty one that mk-template.py makes from layout numbers+# (layout.json) and XNU's own pseudo-extensions.+set -euo pipefail+POC=$(cd "$(dirname "$0")/../.." && pwd)+DVM=${DVM:-$HOME/w/dvm}; W=${FREE_KC_WORK:-$HOME/w/free-kc}; OUT=${OUT:-/lib/firmware/xnu/kc-free.bin}+PD_URL=https://github.com/PureDarwin/PureDarwin PD_REV=0c1990c803c13b68cad4df3f6dc34ba4306fc789+CC_URL=https://github.com/Vali0004/corecrypto CC_REV=fa94ec601f8d6b3a2a39b974f29c5acaf8a9fa2d+export DVM NETINC=${NETINC:-$POC/build/netinc}+K="python3 $POC/scripts/free-kc/kcc.py --macos"; O=$W/obj; S=$W/src; F=$POC/kexts/free+mkdir -p $S $O++fetch() { # repo rev dir [paths...]: a shallow checkout of one revision, only the paths given+ local url=$1 rev=$2 dir=$3; shift 3+ [ "$(git -C $dir rev-parse HEAD 2>/dev/null)" = "$rev" ] && return+ rm -rf $dir; git init -q $dir+ [ $# -gt 0 ] && { git -C $dir sparse-checkout init --no-cone; printf '%s\n' "$@" | git -C $dir sparse-checkout set --stdin; }+ git -C $dir fetch -q --depth 1 $url $rev && git -C $dir checkout -q FETCH_HEAD+}+E=src/Kernel/Extensions+fetch $PD_URL $PD_REV $S/pd /$E/IOStorageFamily/ /$E/HFSEncodings/ /$E/hfs/ /$E/pthread/ /$E/amfi/ /src/Kernel/xnu/EXTERNAL_HEADERS/ \+ /src/Libraries/libSystem/pthread/include/ /src/Libraries/libSystem/pthread/private/+fetch $CC_URL $CC_REV $S/corecrypto+git -C $S/corecrypto apply --check $F/patches/corecrypto-arm64e-sptr.patch 2>/dev/null && git -C $S/corecrypto apply $F/patches/corecrypto-arm64e-sptr.patch+E=$S/pd/src/Kernel/Extensions++# this kernel's Kernel.framework (xnu installhdrs into objects of its own, k27h-*), what --kext-view builds against+KF=$DVM/out/x12377/build/xnu/k27h-dst/System/Library/Frameworks/Kernel.framework/Versions/A+if [ ! -d $KF/PrivateHeaders ]; then+ HO=$DVM/out/x12377/build/xnu/k27h-obj; mkdir -p $HO+ ( cd $DVM/k27/iig && find DEVELOPMENT_ARM64_BCM2837 -type f ) | while read -r f; do # DriverKit headers come from iig's output+ mkdir -p $HO/$(dirname $f); [ -e $HO/$f ] || cp $DVM/k27/iig/$f $HO/$f; done+ ( cd $DVM/out/x12377 && . $DVM/k27/x12377/env.sh && XNU_ARCH=arm64e XNU_ARM_DT_PLATFORM=1 XNU_ARMCPU=1 XNU_TREE=../k27/xnu KDK=kdk \+ XNU_OBJ=k27h XNU_BUILD_TARGET=installhdrs XNU_DEPLOYMENT_TARGET_FLAGS="-miphoneos-version-min=26.0 -DXNU_TARGET_OS_OSX" \+ bash $DVM/k27/x12377/build-kernel.sh > $W/installhdrs.log 2>&1 ) || { tail -20 $W/installhdrs.log; exit 1; }+fi++# the kexts (each step stops the build when a source fails)+( cd $S/corecrypto && $K $O/corecrypto --kext-view $(for c in */include; do echo -I $PWD/$c; done) -I $PWD/corecrypto_kext \+ --cflag=-Wno-nullability-completeness $(python3 - <<'PY'+import re+comps = "cc ccaes ccansikdf ccasn1 ccblowfish cccast ccchacha20poly1305 cccmac ccdes ccdigest ccdrbg cchkdf cchmac ccmd2 ccmd4 ccmd5 ccmode ccn ccnistkdf ccpad ccpbkdf2 ccrc2 ccrc4 ccripemd ccrng ccsha1 ccsha2 ccwrap cckprng ccpost ccrsa cczp".split()+for c in comps: # pd/corecrypto-pd.cmake's PD_CORECRYPTO_KERNEL_COMPONENTS+ s = open(f'cmake/components/{c}.cmake').read()+ print(' '.join(f'{c}/src/{f}' for f in re.search(r'set\(CORECRYPTO_%s_SOURCES(.*?)\)' % c, s, re.S).group(1).split()))+PY+) corecrypto_kext/main.c )+# PureDarwin's AMFI stub, with PureDarwin's CoreEntitlements headers (it declares their coreentitlements_t itself) and+# TrustCache headers (after this kernel's own)+mkdir -p $W/ce-inc; ln -sfn $S/pd/src/Kernel/xnu/EXTERNAL_HEADERS/CoreEntitlements $W/ce-inc/CoreEntitlements+( cd $E/amfi && $K $O/amfi --kext-view -I $F/compat/include -I $W/ce-inc \+ --after $S/pd/src/Kernel/xnu/EXTERNAL_HEADERS -D XNU_KERNEL_PRIVATE -D MACH_KERNEL_PRIVATE -D PRIVATE=1 \+ --cflag=-Wno-int-conversion --cflag=-Wno-implicit-function-declaration amfi_kext_main.c amfi_entitlements.cpp )+( cd $E/pthread && $K $O/pthread --kext-view -I $E/pthread/compat -I $E/pthread -I $S/pd/src/Libraries/libSystem/pthread/include \+ -I $S/pd/src/Libraries/libSystem/pthread/private -D __PTHREAD_EXPOSE_INTERNALS__ -D PRIVATE=1 -D XNU_KERNEL_PRIVATE \+ -D MACH_KERNEL_PRIVATE -D PD_FORCE_LOCAL_STDATOMIC --cflag=-Wno-int-conversion --cflag=-Wno-implicit-function-declaration \+ --cflag=-Wno-incompatible-library-redeclaration --cflag=-include$S/pd/src/Kernel/xnu/EXTERNAL_HEADERS/stdatomic.h \+ --cflag=-include$S/pd/src/Kernel/xnu/EXTERNAL_HEADERS/pd_pthread_sched.h kern_init.c kern_support.c kern_synch.c )+( cd $E/IOStorageFamily && $K $O/IOStorageFamily -I $E/IOStorageFamily/include --after $NETINC \+ --cflag=-include$DVM/out/k27/xnu/libkern/libkern/OSMalloc.h --cflag=-include$F/compat/devfs-ready.h *.cpp )+( cd $E/HFSEncodings && $K $O/HFSEncodings -I $E/HFSEncodings -I $E/hfs/core --after $NETINC *.c *.cpp )+# hfs's kext-config.h: its two compatibility declarations clash with this kernel's own headers, and the iOS target the+# kernel builds for would select HFS's iOS configuration (content protection) where the kexts are macOS's+sed -e '/^extern int tsleep(void \*chan/d; /^extern int proc_is_forcing_hfs_case_sensitivity/d' \+ -e 's|^#if (TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR) // iOS (real hardware)|#if 0 // xnulinux: macOS settings|' \+ $E/hfs/core/kext-config.h > $W/hfs-kext-config.h+( cd $E/hfs && $K $O/hfs --kext-view --drop-def CONFIG_PROTECT -I $E/hfs/shim -I $E/hfs/core -I $E/hfs/hfs_encodings \+ -I $E/IOStorageFamily/include -I $NETINC --cflag=-include$W/hfs-kext-config.h core/*.c core/*.cpp )+for c in kmod-start osmalloc loadtag kalloc-type; do ( cd $F/compat && $K $O/compat/$c --kext-view $c.c ); done+python3 $POC/scripts/free-kc/genspec.py $S $O $O/specs corecrypto amfi pthread IOStorageFamily HFSEncodings hfs++N="$O/specs/corecrypto.json $O/specs/amfi.json $O/specs/pthread.json $O/specs/IOStorageFamily.json $O/specs/HFSEncodings.json $O/specs/hfs.json"+for k in XnuCPU XnuDisk XnuDrm; do N="$N $POC/kexts/$k/$k.json"; done+# the collection is linked into an empty one made from layout numbers and XNU's own pseudo-extensions (mk-template.py):+# nothing of Apple's kernelcache is read+python3 $POC/scripts/free-kc/mk-template.py $POC/scripts/free-kc/layout.json $DVM/out/k27/xnu \+ $(strings $DVM/out/k27/kernel-k27.macho | sed -n 's/^Darwin Kernel Version \([0-9.]*\):.*/\1/p' | head -1) $W/kc-template.bin+# the link (scripts/kclink, as vm-xnu-rebuild.sh links; the specs' object lists of xnulinux's kexts are relative to $DVM)+( cd $DVM && python3 $POC/scripts/kclink/kclink.py $W/kc-template.bin out/k27/kernel-k27.macho $W/kc-free.bin --native $N \+ > $W/kclink.log 2>&1 ) || { tail -5 $W/kclink.log; exit 1; }+grep -E "^wrote" $W/kclink.log+sudo cp $W/kc-free.bin $OUT && echo "kernel collection without Apple's kexts: $OUT"diff --git a/scripts/free-kc/genspec.py b/scripts/free-kc/genspec.pynew file mode 100644index 0000000..03f330f--- /dev/null+++ b/scripts/free-kc/genspec.py@@ -0,0 +1,43 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: GPL-2.0-only+"""Native kext descriptions (scripts/kclink/kclink.py --native) for the free kexts that kcc.py built: bundle, version, libraries and+personalities from the kext's own Info.plist, its objects plus the compat objects it needs, and its kmod start/stop.++ genspec.py SRC OBJDIR SPECDIR NAME...++The collection they are linked into (mk-template.py) has no kexts, so none stands in for another. The com.apple.kec.*+ones are marked AppleKernelExternalComponent, which is what makes KLDBootstrap start them before IOKit+(corecrypto must register before IOPlatformExpertDevice hashes the platform UUID).+"""+import json, plistlib, sys+from pathlib import Path++SRC, O, OUT = Path(sys.argv[1]), Path(sys.argv[2]), Path(sys.argv[3])+OUT.mkdir(parents=True, exist_ok=True)+KEXTS = { # name: (Info.plist below SRC, bundle id when the plist leaves it to the build, start, stop, compat objects)+ 'corecrypto': ('corecrypto/corecrypto_kext/Info.plist', 'com.apple.kec.corecrypto', '_corecrypto_start', '_corecrypto_stop', []),+ 'amfi': ('pd/src/Kernel/Extensions/amfi/Info.plist', None, '_amfi_kext_start', '_amfi_kext_stop', ['kalloc-type']),+ 'pthread': ('pd/src/Kernel/Extensions/pthread/pthread-Info.plist', None, '_pthread_start', '_pthread_stop', ['kalloc-type']),+ 'IOStorageFamily': ('pd/src/Kernel/Extensions/IOStorageFamily/Info.plist', None, None, None, ['osmalloc']),+ 'HFSEncodings': ('pd/src/Kernel/Extensions/HFSEncodings/Info.plist', None, None, None, []),+ 'hfs': ('pd/src/Kernel/Extensions/hfs/Info.plist', None, None, None, ['loadtag']),+}+for name in sys.argv[4:]:+ plist, bundle, start, stop, compat = KEXTS[name]+ info = plistlib.load(open(SRC / plist, 'rb'))+ info.setdefault('CFBundleIdentifier', bundle)+ objects = json.loads((O / name / 'objects.json').read_text())+ for c in compat:+ objects += json.loads((O / 'compat' / c / 'objects.json').read_text())+ if not start: # no kmod start routine of its own: the shared one (kexts/free/compat/kmod-start.c)+ objects += json.loads((O / 'compat' / 'kmod-start' / 'objects.json').read_text())+ start, stop = '_native_kext_start', '_native_kext_stop'+ (O / name / 'objects-kc.json').write_text(json.dumps(objects, indent=1) + '\n')+ spec = {'name': name, 'bundle': info['CFBundleIdentifier'],+ # kclink gives a native kext OSBundleCompatibleVersion 1.0.0, which must not exceed its version (pthread's 1.0.0d1)+ 'version': str(info.get('CFBundleVersion', '1.0')).split('d')[0],+ 'objects': str(O / name / 'objects-kc.json'), 'start': start, 'stop': stop,+ 'libraries': info.get('OSBundleLibraries', {}), 'personalities': info.get('IOKitPersonalities', {}),+ 'plist': {'AppleKernelExternalComponent': True} if info['CFBundleIdentifier'].startswith('com.apple.kec.') else {}}+ (OUT / f'{name}.json').write_text(json.dumps(spec, indent=1, default=str) + '\n')+ print(f'{name}: {spec["bundle"]}, {len(objects)} objects, {len(spec["personalities"])} personalities')diff --git a/scripts/free-kc/kcc.py b/scripts/free-kc/kcc.pynew file mode 100644index 0000000..1c56d44--- /dev/null+++ b/scripts/free-kc/kcc.py@@ -0,0 +1,77 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: GPL-2.0-only+"""Compile a kext's sources as relocatable arm64e objects with the hosted kernel's own compile flags (its compile records+in the k27 object tree), as macOS-DroidVM's build-native-kext.py does for xnulinux's own kexts, but for third-party kext+sources: no -Werror, per-kext includes, defines and flags, and two views of the kernel headers:++ default the kernel's own (its include paths and XNU_KERNEL_PRIVATE), for sources written against xnu's tree+ --kext-view what a kext sees: this kernel's Kernel.framework (Headers, PrivateHeaders; scripts/free-kc/build.sh makes+ it with xnu's installhdrs) instead of the kernel's include paths and kernel-internal macros++--macos builds for macOS (TARGET_OS_OSX) instead of the kernel's iOS target: the free kexts' sources pick their macOS+configuration from it (HFS, IOStorageFamily's virtual methods); the code is the same arm64e kernel ABI.++ kcc.py OUTDIR [--kext-view] [--macos] [-I DIR] [-D X] [--after DIR] [--cflag F] [--drop-def NAME] SOURCE...++Objects (named after their path below the current directory) and OUTDIR/objects.json, the list scripts/kclink/kclink.py+--native reads.+"""+import argparse, json, os, subprocess, sys+from pathlib import Path+from concurrent.futures import ThreadPoolExecutor+DVM = Path(os.environ.get('DVM', Path.home() / 'w/dvm'))+NETINC = Path(os.environ.get('NETINC', Path.home() / 'w/poc/build/netinc')) # TargetConditionals.h (vm-xnu-rebuild.sh)+KF = Path(os.environ.get('KERNEL_FRAMEWORK', DVM / 'out/x12377/build/xnu/k27h-dst/System/Library/Frameworks/Kernel.framework/Versions/A'))+tree = DVM / 'out/x12377/build/xnu/k27-obj/DEVELOPMENT_ARM64_BCM2837'+p = argparse.ArgumentParser()+p.add_argument('out'); p.add_argument('sources', nargs='+')+p.add_argument('-I', dest='inc', action='append', default=[]); p.add_argument('-D', dest='defs', action='append', default=[])+p.add_argument('--cflag', action='append', default=[]); p.add_argument('--macos', action='store_true', help='build for macOS (TARGET_OS_OSX), as the kexts expect; the kernel is the same arm64e ABI')+p.add_argument('--after', action='append', default=[], help='-idirafter DIR'); p.add_argument('--cxxflag', action='append', default=[])+p.add_argument('--c-recipe', default='bsd/DEVELOPMENT/bsd_init.o.json')+p.add_argument('--drop-def', action='append', default=[], help='a -D of the kernel recipe to leave out')+p.add_argument('--kext-view', action='store_true', help='drop the kernel-internal macros (XNU/MACH/BSD_KERNEL_PRIVATE...): headers as a kext sees them')+a = p.parse_args()+INTERNAL = {'XNU_KERNEL_PRIVATE', 'MACH_KERNEL_PRIVATE', 'BSD_KERNEL_PRIVATE', 'IOKIT_KERNEL_PRIVATE', 'LIBKERN_KERNEL_PRIVATE', 'XNU_KERN_EVENT_DATA_IS_VLA'}+rec = {k: json.JSONDecoder().raw_decode((tree / n).read_text())[0] for k, n in (('cpp', 'iokit/DEVELOPMENT/IOPlatformExpert.cpo.json'), ('c', a.c_recipe))}+out = Path(a.out).resolve(); out.mkdir(parents=True, exist_ok=True)+def one(src):+ src = Path(src).resolve(); kind = 'cpp' if src.suffix in ('.cpp', '.cc') else 'c'+ r = rec[kind]+ try:+ rel = src.relative_to(Path.cwd())+ except ValueError:+ rel = Path(src.parent.name) / src.name+ dst = out / (str(rel.with_suffix('')).replace('/', '_') + '.o'); cmd = []; args = r['arguments']; i = 0+ while i < len(args):+ v = args[i]+ if v == r['file']: cmd.append(str(src))+ elif v == '-o': cmd += ['-o', str(dst)]; i += 1+ elif v in ('-MF', '-MJ', '-MT', '-MQ'): i += 1+ elif v == '-Xclang' and args[i + 1].startswith('-W'): i += 1+ elif a.kext_view and v in ('-I', '-isystem', '-iquote', '-include', '-idirafter'): i += 1+ elif a.kext_view and (v.startswith(('-I', '-isystem', '-iquote', '-idirafter')) or (v.startswith('-include') and len(v) > 8)): pass+ elif v == '-D' and args[i + 1].split('=')[0] in a.drop_def: i += 1+ elif v.startswith('-D') and v[2:].split('=')[0] in a.drop_def: pass+ elif a.kext_view and v == '-D' and args[i + 1].split('=')[0] in INTERNAL: i += 1+ elif a.kext_view and v.startswith('-D') and v[2:].split('=')[0] in INTERNAL: pass+ elif a.macos and v.startswith('--target=') and '-ios' in v: cmd.append(v.replace('-ios', '-macos'))+ elif a.macos and v.startswith('-mios-version-min='): cmd.append('-mmacos-version-min=' + v.split('=')[1])+ elif v not in ('-MD', '-MMD', '-MP', '-g', '-Werror') and not v.startswith('-W'): cmd.append(v)+ i += 1+ # the kext's own headers first (they may shadow the kernel's copies of the same family headers)+ extra = [f'-I{d}' for d in a.inc] + [f'-D{d}' for d in a.defs] + a.cflag + (a.cxxflag if kind == 'cpp' else []) + ['-w'] + [x for d in a.after for x in ('-idirafter', d)]+ if a.kext_view: # the kernel's own include paths are gone: the headers a kext builds against (Kernel.framework of this kernel)+ extra += [f'-I{KF}/PrivateHeaders', f'-I{KF}/Headers', '-idirafter', str(DVM / 'out/k27/xnu/EXTERNAL_HEADERS'), '-idirafter', str(NETINC), '-D__startup_func=', '-DDRIVER_PRIVATE', '-DNeXT']+ cmd[1:1] = extra+ env = dict(os.environ, CCC_OVERRIDE_OPTIONS='+-Wno-error')+ res = subprocess.run(cmd, cwd=r['directory'], capture_output=True, text=True, env=env)+ return src, dst, res+objs, failed = [], 0+with ThreadPoolExecutor(6) as ex:+ for src, dst, res in ex.map(one, a.sources):+ if res.returncode:+ failed += 1; print(f'FAILED {src}\n' + '\n'.join((res.stdout + res.stderr).splitlines()[:25]))+ else: objs.append(str(dst))+(out / 'objects.json').write_text(json.dumps(objs, indent=1) + '\n')+print(f'{out.name}: {len(objs)} objects, {failed} failed'); sys.exit(1 if failed else 0)diff --git a/scripts/free-kc/layout.json b/scripts/free-kc/layout.jsonnew file mode 100644index 0000000..ba5e79b--- /dev/null+++ b/scripts/free-kc/layout.json@@ -0,0 +1,15 @@+{+ "comment": "Where kclink places things in a kernel collection, as offsets from its first byte: the top-level segments, the slot of the kernel's __LINKINFO and where the shared __LINKEDIT starts. The numbers are those of the layout k27/segaddrs.sh links the kernel for (macOS 27.2's kernelcache); mk-template.py builds a collection skeleton from them alone.",+ "segments": [+ ["__TEXT", "0x0", "0x4000", 1, null],+ ["__PRELINK_TEXT", "0x4000", "0x814000", 1, "__text"],+ ["__DATA_CONST", "0x818000", "0x77c000", 1, null],+ ["__TEXT_EXEC", "0xf94000", "0x28d0000", 5, null],+ ["__PRELINK_INFO", "0x3864000", "0x2fc000", 3, "__info"],+ ["__DATA", "0x3b60000", "0x2c0000", 3, null],+ ["__LINKEDIT", "0x3e20000", "0x9c000", 1, null]+ ],+ "kernel_header": "0x4000",+ "kernel_linkinfo": ["0x3e20000", "0x51000"],+ "kernel_linkedit": "0x3ebc000"+}diff --git a/scripts/free-kc/mk-template.py b/scripts/free-kc/mk-template.pynew file mode 100644index 0000000..e80ce87--- /dev/null+++ b/scripts/free-kc/mk-template.py@@ -0,0 +1,82 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: GPL-2.0-only+"""An empty MH_FILESET kernel collection to link into, made from numbers alone (layout.json) and the kernel's own+pseudo-extensions, so that nothing of a vendor's kernelcache goes into the collection scripts/free-kc/build.sh links.++ mk-template.py LAYOUT.json XNU_SOURCE KERNEL_VERSION OUTPUT++scripts/kclink/kclink.py links into a collection it is given: its top-level segments, the kernel's fileset entry (where+the kernel's header goes), the prelink info and the chained fixups. This writes a file with exactly that structure and+nothing in it: the segments are zero, the kernel entry has only its __LINKINFO slot and the shared __LINKEDIT, the fixups+have no chains, and the prelink info lists only the kernel's com.apple.kpi.* pseudo-extensions, from XNU's own+config/System.kext/PlugIns.+"""+import hashlib, json, plistlib, struct, sys+from pathlib import Path++LC_SEGMENT_64, LC_UUID, LC_BUILD_VERSION, LC_UNIXTHREAD = 0x19, 0x1b, 0x32, 0x5+LC_CHAINED_FIXUPS, LC_FILESET_ENTRY = 0x80000034, 0x80000035+BASE = 0xfffffff007004000 # VM_KERNEL_LINK_ADDRESS the kernel is linked for: the collection needs no move+KPI = {'BSDKernel': 'com.apple.kpi.bsd', 'MACFramework': 'com.apple.kpi.dsep', 'IOKit': 'com.apple.kpi.iokit',+ 'Libkern': 'com.apple.kpi.libkern', 'Mach': 'com.apple.kpi.mach', 'Private': 'com.apple.kpi.private',+ 'Unsupported': 'com.apple.kpi.unsupported'}++layout = json.loads(Path(sys.argv[1]).read_text())+xnu, version, output = Path(sys.argv[2]), sys.argv[3], Path(sys.argv[4])+num = lambda s: int(s, 16) # noqa: E731+segs = [(name, num(off), num(size), prot, sect) for name, off, size, prot, sect in layout['segments']]+linkinfo_off, linkinfo_size = map(num, layout['kernel_linkinfo'])+linkedit_off = num(layout['kernel_linkedit'])++# the prelink info: the kernel's pseudo-extensions, as a kernelcache builder lists them+entries = []+for bundle, ident in KPI.items():+ text = (xnu / 'config/System.kext/PlugIns' / f'{bundle}.kext/Info.plist').read_text()+ text = text.replace('###KERNEL_VERSION_LONG###', version).replace('###KERNEL_VERSION_SHORT###', '.'.join(version.split('.')[:2]))+ entry = plistlib.loads(text.encode())+ assert entry['CFBundleIdentifier'] == ident and entry.get('OSKernelResource'), bundle+ entry.update({'_PrelinkBundlePath': f'/System/Library/Extensions/System.kext/PlugIns/{bundle}.kext',+ '_PrelinkExecutableLoadAddr': 0x7fffffffffffffff, '_PrelinkExecutableSourceAddr': 0x7fffffffffffffff})+ entries.append(entry)+kcid = hashlib.sha256(b'xnulinux free kernel collection ' + version.encode()).digest()[:16]+info = plistlib.dumps({'_PrelinkInfoDictionary': entries, '_PrelinkKCID': kcid, 'OSPrelinkInfoContainsUUIDs': True,+ 'ManagerVersion': 1, 'KMBuildVersion': 'xnulinux-free-kc'}, fmt=plistlib.FMT_XML) + b'\0'+info_off, info_size = next((o, s) for n, o, s, _, _ in segs if n == '__PRELINK_INFO')+assert len(info) <= info_size++size = linkedit_off # the file ends where the kernel's own link-edit data would start: kclink appends after it+image = bytearray(size)+image[info_off:info_off + len(info)] = info++# chained fixups with no chains: a header and a starts table of zero segments+fixups = struct.pack('<7I', 0, 28, 32, 32, 0, 1, 0) + struct.pack('<I', 0)+fixups += bytes(-len(fixups) % 8)+fixups_off = linkinfo_off + linkinfo_size # after the kernel's __LINKINFO slot, before its __LINKEDIT+assert fixups_off + len(fixups) <= linkedit_off+image[fixups_off:fixups_off + len(fixups)] = fixups++# the kernel's fileset entry: a Mach-O header with its __LINKINFO slot and the shared __LINKEDIT; kclink writes the real+# kernel's header over it+kh = num(layout['kernel_header'])+kcmds = struct.pack('<II16s4Q4I', LC_SEGMENT_64, 72, b'__LINKINFO', BASE + linkinfo_off, linkinfo_size, linkinfo_off, linkinfo_size, 1, 1, 0, 0)+kcmds += struct.pack('<II16s4Q4I', LC_SEGMENT_64, 72, b'__LINKEDIT', BASE + linkedit_off, 0, linkedit_off, 0, 1, 1, 0, 0)+image[kh:kh + 32 + len(kcmds)] = struct.pack('<8I', 0xfeedfacf, 0x100000c, 0xc0000002, 2, 2, len(kcmds), 0x200001, 0) + kcmds++# the collection's header+cmds = [struct.pack('<II16s', LC_UUID, 24, hashlib.sha256(kcid).digest()[:16]),+ struct.pack('<6I', LC_BUILD_VERSION, 24, 1, 0x1b0000, 0x1b0000, 0), # macOS 27, no tools+ struct.pack('<II', LC_UNIXTHREAD, 288) + bytes(280), # kclink puts the kernel's+ struct.pack('<4I', LC_CHAINED_FIXUPS, 16, fixups_off, len(fixups))]+for name, off, size_, prot, sect in segs:+ nsect = 1 if sect else 0+ body = struct.pack('<II16s4Q4I', LC_SEGMENT_64, 72 + 80 * nsect, name.encode(), BASE + off, size_, off, size_, prot, prot, nsect, 0)+ if sect:+ body += struct.pack('<16s16s2Q8I', sect.encode(), name.encode(), BASE + off, size_, off, 0, 0, 0, 0, 0, 0, 0)+ cmds.append(body)+name = b'com.apple.kernel\0'+cmds.append(struct.pack('<IIQQII', LC_FILESET_ENTRY, 32 + len(name) + (-(32 + len(name)) % 8), BASE + kh, kh, 32, 0)+ + name + bytes(-(32 + len(name)) % 8))+blob = b''.join(cmds)+image[0:32 + len(blob)] = struct.pack('<8I', 0xfeedfacf, 0x100000c, 0xc0000002, 12, len(cmds), len(blob), 0, 0) + blob+output.write_bytes(image)+print(f'{output}: {len(image):#x} bytes, {len(entries)} pseudo-extensions')diff --git a/scripts/kclink/kccompare.py b/scripts/kclink/kccompare.pynew file mode 100755index 0000000..cfd38e0--- /dev/null+++ b/scripts/kclink/kccompare.py@@ -0,0 +1,94 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: GPL-2.0-only+"""Compares two kernel collections: their fixups (decoded), their fileset entries' segments and sections, the bytes of+each entry's segments with pointers taken out, and their prelink info. For checking kclink against another linker.++ kccompare.py A B"""+import plistlib+import struct+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))+from macho import Image, kc_read_fixups # noqa: E402+++def load(path):+ buf = open(path, 'rb').read()+ img = Image(buf)+ hdr = img.segments[0].vmaddr+ fx = kc_read_fixups(buf, hdr, None)+ ents = {n: Image(buf, fo) for n, va, fo in img.entries}+ pi = img.segment('__PRELINK_INFO')+ info = plistlib.loads(buf[pi.fileoff:pi.fileoff + pi.filesize].rstrip(b'\0'))+ return buf, img, hdr, fx, ents, info+++def main():+ a, b = sys.argv[1], sys.argv[2]+ A, B = load(a), load(b)+ bufa, imga, hdra, fxa, ea, ia = A+ bufb, imgb, hdrb, fxb, eb, ib = B+ print(f'header {hdra:#x} / {hdrb:#x}; {len(fxa)} / {len(fxb)} pointers; {len(ea)} / {len(eb)} entries')+ for sa, sb in zip(imga.segments, imgb.segments):+ if (sa.name, sa.vmaddr, sa.vmsize) != (sb.name, sb.vmaddr, sb.vmsize):+ print(f' segment {sa.name} {sa.vmaddr:#x}+{sa.vmsize:#x} / {sb.name} {sb.vmaddr:#x}+{sb.vmsize:#x}')+ only = set(ea) ^ set(eb)+ if only:+ print(' entries in one only:', sorted(only))+ problems = 0+ for name in sorted(set(ea) & set(eb)):+ xa, xb = ea[name], eb[name]+ segs_a = [(s.name, s.vmaddr, s.vmsize) for s in xa.segments if s.name != '__LINKEDIT']+ segs_b = [(s.name, s.vmaddr, s.vmsize) for s in xb.segments if s.name != '__LINKEDIT']+ if segs_a != segs_b:+ print(f'{name}: segments differ: {segs_a} / {segs_b}')+ problems += 1+ continue+ secs_a = [(s.segname, s.sectname, s.addr, s.size, s.flags) for s in xa.sections()]+ secs_b = [(s.segname, s.sectname, s.addr, s.size, s.flags) for s in xb.sections()]+ if secs_a != secs_b:+ print(f'{name}: sections differ: {set(secs_a) ^ set(secs_b)}')+ problems += 1+ for s in xa.segments:+ if s.name == '__LINKEDIT' or not s.filesize:+ continue+ o = s.vmaddr - hdra+ bad_ptr, bad_bytes = [], []+ ptr = set()+ for loc in range(o, o + s.filesize, 4):+ fa, fb = fxa.get(loc), fxb.get(loc)+ if fa or fb:+ ptr.add(loc)+ ptr.add(loc + 4)+ if not fa or not fb or (fa.target, fa.key, fa.div, fa.addr_div) != \+ (fb.target, fb.key, fb.div, fb.addr_div):+ bad_ptr.append((loc, fa, fb))+ skip_hdr = 0+ if s.name == '__TEXT': # load commands: compared above+ skip_hdr = 32 + struct.unpack_from('<I', bufa, o + 20)[0]+ for loc in range(o + skip_hdr, o + s.filesize, 4):+ if loc not in ptr and bufa[loc:loc + 4] != bufb[loc:loc + 4]:+ bad_bytes.append(loc)+ if bad_ptr or bad_bytes:+ problems += 1+ print(f'{name} {s.name}: {len(bad_ptr)} pointers and {len(bad_bytes)} words differ;'+ f' first pointers {[(hex(l), x, y) for l, x, y in bad_ptr[:3]]}'+ f' first words {[hex(l) for l in bad_bytes[:6]]}')+ da = {d['CFBundleIdentifier']: d for d in ia['_PrelinkInfoDictionary']}+ db = {d['CFBundleIdentifier']: d for d in ib['_PrelinkInfoDictionary']}+ if set(da) != set(db):+ print('prelink info: entries in one only:', sorted(set(da) ^ set(db)))+ for k in sorted(set(da) & set(db)):+ if da[k] != db[k]:+ keys = sorted(x for x in set(da[k]) | set(db[k]) if da[k].get(x) != db[k].get(x))+ print(f'prelink info {k}: {[(x, da[k].get(x), db[k].get(x)) for x in keys]}'[:400])+ problems += 1+ if {x: y for x, y in ia.items() if x != '_PrelinkInfoDictionary'} != \+ {x: y for x, y in ib.items() if x != '_PrelinkInfoDictionary'}:+ print('prelink info: top-level keys differ')+ print(f'{problems} differences')+++if __name__ == '__main__':+ main()diff --git a/scripts/kclink/kclink.py b/scripts/kclink/kclink.pynew file mode 100755index 0000000..7cacdaa--- /dev/null+++ b/scripts/kclink/kclink.py@@ -0,0 +1,550 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: GPL-2.0-only+"""Links a kernel collection (an MH_FILESET kernelcache) for xnu.ko: the hosted kernel, kexts linked from object files+(scripts/kclink/kextld.py), and kexts kept from another collection.++ kclink.py BASE KERNEL OUTPUT [--keep BUNDLE_ID...] [--native SPEC.json...] [--rebind ADDRESS=SYMBOL...]++BASE is the collection the output is laid out like: its segments (__PRELINK_TEXT, __DATA_CONST, __TEXT_EXEC,+__PRELINK_INFO, __DATA, __LINKEDIT), its kexts (those --keep names, with every kext they depend on, stay where they+are, byte for byte but for their pointers) and its prelink info. It is a macOS kernelcache (scripts/apple-kc/link.sh) or+an empty collection made from numbers (scripts/free-kc/mk-template.py).++KERNEL is the kernel, linked at the addresses of its slots in the collection (threaded rebases, __TEXT,__thread_starts).+The output's addresses are the kernel's: the collection's header sits as far below the kernel's __TEXT as in BASE.++Every pointer goes into the collection's chained fixups (DYLD_CHAINED_PTR_64_KERNEL_CACHE). A kept kext's pointers into+BASE's kernel go to the same symbol in KERNEL (BASE's kernel symbol table names them); --rebind sends the pointer at+ADDRESS (in BASE) to another of KERNEL's symbols.++A native kext's spec (JSON): name, bundle, version, objects (a JSON list of object files; relative paths are from the+directory kclink runs in), start, stop, libraries, personalities, plist (more Info.plist keys), patch_personalities+({bundle: {personality: {key: value}}}, merged into a kept kext's IOKitPersonalities). Its segments go into space no+kernel or kept kext uses, first fit. Its symbols, as linked, are written to OUTPUT with suffix .natives.json."""+import argparse+import json+import os+import plistlib+import struct+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))+from macho import (HEADER, LC_SEGMENT_64, LC_SYMTAB, LC_DYSYMTAB, LC_UNIXTHREAD, LC_UUID, LC_SEGMENT_SPLIT_INFO, # noqa+ LC_FUNCTION_STARTS, LC_DATA_IN_CODE, LC_DYLD_CHAINED_FIXUPS, LC_FILESET_ENTRY, MH_FILESET,+ N_STAB, N_TYPE, N_SECT, N_EXT, NLIST, KC_PAGE, Fixup, Image, Segment, align, kc_read_fixups,+ kc_write_fixups, threaded_rebases)+import kextld # noqa: E402++KERNEL_ID = 'com.apple.kernel'+MH_DYLIB_IN_CACHE = 0x80000000+# the collection's segment each of the kernel's goes into+KERNEL_REGION = {'__TEXT': '__PRELINK_TEXT', '__DATA_CONST': '__DATA_CONST', '__LASTDATA_CONST': '__DATA_CONST',+ '__TEXT_EXEC': '__TEXT_EXEC', '__KLD': '__TEXT_EXEC', '__LAST': '__TEXT_EXEC',+ '__KLDDATA': '__DATA', '__DATA': '__DATA', '__BOOTDATA': '__DATA', '__LINKINFO': '__LINKEDIT'}+KEXT_REGION = {'__TEXT': '__PRELINK_TEXT', '__TEXT_EXEC': '__TEXT_EXEC', '__DATA_CONST': '__DATA_CONST',+ '__DATA': '__DATA', '__LINKINFO': '__LINKEDIT'}+ADDRESS_KEYS = ('_PrelinkExecutableLoadAddr', '_PrelinkExecutableSourceAddr', '_PrelinkKmodInfo')+NO_ADDRESS = 0x7fffffffffffffff # a codeless kext's _PrelinkExecutableLoadAddr+KERNEL_DROPPED_CMDS = {LC_SEGMENT_SPLIT_INFO, LC_FUNCTION_STARTS, LC_DATA_IN_CODE, 0x1d} # 0x1d: LC_CODE_SIGNATURE+++def fail(msg):+ sys.exit(f'kclink: {msg}')+++def u64(v):+ return v & 0xffffffffffffffff+++def has_code(d):+ a = d.get('_PrelinkExecutableLoadAddr')+ return a is not None and a != NO_ADDRESS+++class Holes:+ """Free ranges of one segment of the collection (offsets), handed out first fit."""++ def __init__(self, start, end):+ self.free = [(start, end)]++ def take(self, start, end):+ out = []+ for a, b in self.free:+ if end <= a or b <= start:+ out.append((a, b))+ continue+ if a < start:+ out.append((a, start))+ if end < b:+ out.append((end, b))+ self.free = out++ def fit(self, size, al):+ for a, b in self.free:+ s = align(a, al)+ if s + size <= b:+ self.take(s, s + size)+ return s+ return None+++def main():+ ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])+ ap.add_argument('base')+ ap.add_argument('kernel')+ ap.add_argument('output')+ ap.add_argument('--keep', nargs='*', default=[])+ ap.add_argument('--native', nargs='*', default=[])+ ap.add_argument('--rebind', nargs='*', default=[], help='ADDRESS=SYMBOL: the pointer at ADDRESS (in BASE)')+ ap.add_argument('--reserve', nargs='*', default=[], help='SEGMENT:START-END: offsets no native kext goes to')+ args = ap.parse_args()++ bbuf = open(args.base, 'rb').read()+ base = Image(bbuf)+ if base.filetype != MH_FILESET:+ fail(f'{args.base}: not a kernel collection')+ old_hdr = base.segments[0].vmaddr+ regions = {} # name -> [start, end] (offsets from the header)+ for s in base.segments:+ if s.fileoff != s.vmaddr - old_hdr:+ fail(f'{args.base}: segment {s.name} not mapped at its file offset')+ regions[s.name] = [s.fileoff, s.fileoff + s.vmsize]+ old_entries = {n: Image(bbuf, fo) for n, va, fo in base.entries}+ if KERNEL_ID not in old_entries:+ fail(f'{args.base}: no {KERNEL_ID}')+ old_kernel = old_entries[KERNEL_ID]+ info_seg = base.segment('__PRELINK_INFO')+ info = plistlib.loads(bbuf[info_seg.fileoff:info_seg.fileoff + info_seg.filesize].rstrip(b'\0'))++ kbuf = open(args.kernel, 'rb').read()+ kernel = Image(kbuf)+ ktext = kernel.segment('__TEXT')+ hdr = ktext.vmaddr - next(fo for n, va, fo in base.entries if n == KERNEL_ID)+ slide = u64(hdr - old_hdr)++ # what is kept: the kexts named, every kext they depend on, and the codeless ones all of whose libraries are there+ infos = {d['CFBundleIdentifier']: d for d in info['_PrelinkInfoDictionary']}+ keep = set()+ todo = list(args.keep)+ while todo:+ k = todo.pop()+ if k in keep:+ continue+ if k not in infos:+ fail(f'{k}: not in {args.base}')+ keep.add(k)+ todo += list(infos[k].get('OSBundleLibraries', {}))+ changed = True+ while changed:+ changed = False+ for k, d in infos.items():+ if k not in keep and not has_code(d) and all(lib in keep or lib not in infos and lib == KERNEL_ID+ for lib in d.get('OSBundleLibraries', {})):+ keep.add(k)+ changed = True+ kept = [n for n, va, fo in base.entries if n in keep and n != KERNEL_ID]+ print(f'keeping {len(kept)} kexts: {kept}')++ # the output: the kernel's segments where it was linked, the kept kexts where they were, the native kexts in what+ # is left+ out = bytearray(align(len(bbuf), KC_PAGE))+ holes = {name: Holes(a, b) for name, (a, b) in regions.items()}+ members = {name: [] for name in regions}++ def claim(region, start, size, who):+ if region not in regions:+ fail(f'{who}: no segment {region} in {args.base}')+ members[region].append((start, start + size, who))+ holes[region].take(start, start + size)++ # the kernel: from its first segment to the end of its last in each of the collection's segments (what lies+ # between its own, e.g. __DATA_CONST and __LASTDATA_CONST, is its too)+ kspan = {}+ for s in kernel.segments:+ if s.name == '__LINKEDIT' or not s.vmsize:+ continue+ if s.name not in KERNEL_REGION:+ fail(f'kernel segment {s.name} has no place in the collection')+ a, b = kspan.get(KERNEL_REGION[s.name], (1 << 64, 0))+ kspan[KERNEL_REGION[s.name]] = (min(a, s.vmaddr - hdr), max(b, s.vmaddr - hdr + s.vmsize))+ for region, (a, b) in kspan.items():+ claim(region, a, b - a, f'kernel in {region}')+ # kexts' data starts at the kernel's (empty) __PRELINK_DATA segment, where the kernel takes it to start+ pd = kernel.segment('__PRELINK_DATA')+ if pd is not None and regions['__DATA'][0] <= pd.vmaddr - hdr <= regions['__DATA'][1]:+ holes['__DATA'].take(regions['__DATA'][0], pd.vmaddr - hdr)+ for r in args.reserve:+ region, rng = r.split(':')+ a, b = (int(x, 0) for x in rng.split('-'))+ holes[region].take(a, b)+ for n in kept:+ for s in old_entries[n].segments:+ if s.name != '__LINKEDIT' and s.vmsize:+ claim(KEXT_REGION.get(s.name, s.name), s.vmaddr - old_hdr, s.vmsize, f'{n} {s.name}')+ for region, ms in members.items():+ ms.sort()+ for (a1, b1, w1), (a2, b2, w2) in zip(ms, ms[1:]):+ if a2 < b1:+ fail(f'{w1} ({a1:#x}-{b1:#x}) and {w2} ({a2:#x}-{b2:#x}) overlap')++ # fixups: the kernel's, the kept kexts', the native kexts'+ fixups = {}+ for va, f in threaded_rebases(kernel).items():+ fixups[va - hdr] = f+ print(f'kernel: {len(fixups)} threaded pointers ({sum(f.key is not None for f in fixups.values())} signed)')++ old_ksyms = {}+ for n, t, sc, d, v in old_kernel.symbols():+ if not t & N_STAB and (t & N_TYPE) == N_SECT:+ old_ksyms.setdefault(v, []).append(n)+ ksyms, kexports = {}, {}+ for n, t, sc, d, v in kernel.symbols():+ if not t & N_STAB and (t & N_TYPE) == N_SECT:+ if t & N_EXT:+ kexports[n] = ksyms[n] = v+ else:+ ksyms.setdefault(n, v)++ def in_old_kernel(va):+ return any(s.contains(va) for s in old_kernel.segments if s.name != '__LINKEDIT')++ kept_ranges = sorted((s.vmaddr, s.vmaddr + s.vmsize, n) for n in kept for s in old_entries[n].segments+ if s.name != '__LINKEDIT' and s.vmsize)++ def kept_owner(va):+ lo, hi = 0, len(kept_ranges)+ while lo < hi:+ mid = (lo + hi) // 2+ if kept_ranges[mid][1] <= va:+ lo = mid + 1+ else:+ hi = mid+ if lo < len(kept_ranges) and kept_ranges[lo][0] <= va < kept_ranges[lo][1]:+ return kept_ranges[lo][2]+ return None++ rebinds = {}+ for r in args.rebind:+ a, sym = r.split('=', 1)+ if sym not in ksyms:+ fail(f'--rebind {r}: no {sym} in the kernel')+ rebinds[int(a, 0) - old_hdr] = ksyms[sym]+ old_fixups = kc_read_fixups(bbuf, old_hdr, None)+ unbound, n_kept, to_kernel = {}, 0, 0+ for loc, f in old_fixups.items():+ owner = kept_owner(old_hdr + loc)+ if owner is None:+ continue+ n_kept += 1+ if loc in rebinds:+ fixups[loc] = Fixup(rebinds.pop(loc), f.key, f.div, f.addr_div)+ continue+ if kept_owner(f.target):+ fixups[loc] = Fixup(u64(f.target + slide), f.key, f.div, f.addr_div)+ continue+ if in_old_kernel(f.target):+ names = old_ksyms.get(f.target, [])+ new = next((kexports[n] for n in names if n in kexports), None)+ if new is None:+ new = next((ksyms[n] for n in names if n in ksyms), None)+ if new is None:+ unbound.setdefault(owner, set()).add(f'{names[0] if names else "?"} ({f.target:#x})')+ continue+ to_kernel += 1+ fixups[loc] = Fixup(new, f.key, f.div, f.addr_div)+ continue+ unbound.setdefault(owner, set()).add(f'{f.target:#x}, in no kept kext')+ if rebinds:+ fail(f'--rebind: no pointer of a kept kext at {", ".join(hex(a + old_hdr) for a in rebinds)}')+ if unbound:+ for owner, what in sorted(unbound.items()):+ print(f'{owner}: pointers to nothing in the output: {", ".join(sorted(what)[:12])}'+ f'{" ..." if len(what) > 12 else ""}', file=sys.stderr)+ fail('kept kexts point at what is not kept')+ print(f'kept kexts: {n_kept} chained pointers ({to_kernel} into the kernel, by symbol)')++ # native kexts: laid out, placed, then linked against the kernel, the kept kexts and each other+ specs = []+ for path in args.native:+ spec = json.loads(Path(path).read_text())+ if spec['bundle'] in keep or spec['bundle'] in (s['bundle'] for s, _ in specs):+ fail(f'{path}: {spec["bundle"]} is in the collection already')+ objects = json.loads(Path(spec['objects']).read_text())+ specs.append((spec, kextld.Kext(spec, objects)))+ for spec, kx in specs:+ addrs = {}+ for seg, (size, al) in kx.layout().items():+ region = KEXT_REGION[seg]+ off = holes[region].fit(size, al)+ if off is None:+ fail(f'{spec["bundle"]}: no room for its {seg} ({size:#x} bytes) in {region}')+ members[region].append((off, off + size, f'{spec["bundle"]} {seg}'))+ addrs[seg] = hdr + off+ kx.place(addrs, hdr)+ kept_exports = {}+ for n in kept:+ for name, v in old_entries[n].exports().items():+ kept_exports.setdefault(name, u64(v + slide))+ native_exports = {}+ for spec, kx in specs:+ for name, where in kx.globals.items():+ native_exports.setdefault(name, kx.addr_of(where))++ def resolve(name):+ for table in (native_exports, kexports, kept_exports, ksyms): # ksyms: the kernel's private symbols too+ if name in table:+ return table[name]+ return None++ kept_syms = {}++ def base_vtable(spec):+ """The address of the spec's `vtable` superclass's vtable, in the kept kext that has it."""+ vt = spec['vtable']+ if vt['base_kext'] not in keep:+ fail(f'{spec["bundle"]}: vtable base kext {vt["base_kext"]} not kept')+ if vt['base_kext'] not in kept_syms:+ syms = {}+ for n, t, sc, d, v in old_entries[vt['base_kext']].symbols():+ if not t & N_STAB and (t & N_TYPE) == N_SECT:+ syms.setdefault(n, set()).add(u64(v + slide))+ kept_syms[vt['base_kext']] = syms+ name = f'__ZTV{len(vt["base"])}{vt["base"]}'+ found = kept_syms[vt['base_kext']].get(name, set())+ if len(found) != 1:+ fail(f'{spec["bundle"]}: {len(found)} vtables {name} in {vt["base_kext"]}')+ a = next(iter(found))+ # its end: the next symbol of the kext+ end = min((v for vs in kept_syms[vt['base_kext']].values() for v in vs if v > a), default=a)+ return a, (end - a - 16) // 8++ def slot(vtable, j):+ a, n = vtable+ if not 0 <= j < n:+ return None+ f = fixups.get(a + 16 + 8 * j - hdr)+ return f.target if f else None++ natives = {}+ linked = []+ for spec, kx in specs:+ inherited = None+ if spec.get('vtable'):+ bvt = base_vtable(spec)+ inherited = lambda j, bvt=bvt: slot(bvt, j) # noqa: E731+ try:+ r = kx.link(resolve, inherited)+ except kextld.LinkError as e:+ fail(str(e))+ if spec.get('vtable'):+ # the slots this kext does not override must be its superclass's: a header that does not match the+ # superclass the collection has shows here+ vt, nvt = spec['vtable'], kx.vtable()+ own = [(kx.segs[s]['addr'], kx.segs[s]['addr'] + kx.segs[s]['size']) for s in kx.segs if kx.segs[s]['size']]+ bad = []+ for j in range(vt['slots']):+ if j in vt.get('ignore_slots', []):+ continue+ f = r['fixups'].get(nvt + 16 + 8 * j)+ t = f.target if f else None+ if t is not None and any(a <= t < b for a, b in own):+ continue+ if t != slot(bvt, j):+ bad.append(j)+ print(f'vtable check {vt["class"]} vs {vt["base"]}: {len(bad)} problem slots')+ if bad:+ fail(f'{spec["bundle"]}: slots {bad[:20]} of {vt["class"]}\'s vtable are not {vt["base"]}\'s')+ for va, f in r['fixups'].items():+ fixups[va - hdr] = f+ natives.update(r['symbols'])+ linked.append((spec, kx, r))+ print(f'{spec["bundle"]}: linked, header at {kx.segs["__TEXT"]["addr"]:#x}, {len(r["fixups"])} pointers')++ # bytes: the kept kexts', the kernel's, the native kexts'+ for n in kept:+ for s in old_entries[n].segments:+ if s.name != '__LINKEDIT' and s.filesize:+ out[s.fileoff:s.fileoff + s.filesize] = bbuf[s.fileoff:s.fileoff + s.filesize]+ le = base.segment('__LINKEDIT')+ out[le.fileoff:len(bbuf)] = bbuf[le.fileoff:]+ for s in kernel.segments:+ if s.name != '__LINKEDIT' and s.filesize:+ off = s.vmaddr - hdr+ out[off:off + s.filesize] = kbuf[s.fileoff:s.fileoff + s.filesize]++ # the kept kexts' headers, symbols and kmod_info at the output's addresses+ for n in kept:+ img = Image(out, old_entries[n].off)+ p = img.off + HEADER.size+ for cmd, raw in img.cmds:+ if cmd == LC_SEGMENT_64:+ seg = Segment(raw)+ seg.vmaddr = u64(seg.vmaddr + slide)+ for sec in seg.sections:+ sec.addr = u64(sec.addr + slide)+ out[p:p + len(raw)] = seg.pack()+ p += len(raw)+ if img.symtab:+ symoff, nsyms = img.symtab[:2]+ for i in range(nsyms):+ o = symoff + NLIST.size * i+ typ, value = out[o + 4], struct.unpack_from('<Q', out, o + 8)[0]+ if not typ & N_STAB and (typ & N_TYPE) == N_SECT:+ struct.pack_into('<Q', out, o + 8, u64(value + slide))+ d = infos[n]+ kmod = d.get('_PrelinkKmodInfo')+ if kmod:+ o = u64(kmod) - old_hdr + kextld.KMOD_ADDRESS+ a = struct.unpack_from('<Q', out, o)[0]+ if a:+ struct.pack_into('<Q', out, o, u64(a + slide))++ # the kernel's symbols, after BASE's __LINKEDIT+ symoff, nsyms, stroff, strsize = kernel.symtab+ k_symoff = len(out)+ out += kbuf[symoff:symoff + NLIST.size * nsyms]+ k_stroff = len(out)+ out += kbuf[stroff:stroff + strsize]+ out += b'\0' * (align(len(out), 8) - len(out))+ k_le = (k_symoff, len(out) - k_symoff)++ # prelink info: the kept kexts' entries at the output's addresses, the native kexts'+ entries = []+ patches = {}+ for spec, kx, r in linked:+ for bundle, pers in spec.get('patch_personalities', {}).items():+ patches.setdefault(bundle, {}).update(pers)+ for d in info['_PrelinkInfoDictionary']:+ k = d['CFBundleIdentifier']+ if k not in keep:+ continue+ d = dict(d)+ if has_code(d):+ for key in ADDRESS_KEYS:+ if key in d:+ d[key] = kextld.signed(u64(d[key] + slide))+ for pers, keys in patches.pop(k, {}).items():+ d['IOKitPersonalities'] = dict(d.get('IOKitPersonalities', {}))+ if pers not in d['IOKitPersonalities']:+ fail(f'patch_personalities: {k} has no personality {pers}')+ d['IOKitPersonalities'][pers] = {**d['IOKitPersonalities'][pers], **keys}+ entries.append(d)+ if patches:+ fail(f'patch_personalities: {", ".join(patches)} not kept')+ for spec, kx, r in linked:+ entries.append(kx.plist(kx.out[('__DATA', '__data')].addr))+ info = dict(info)+ info['_PrelinkInfoDictionary'] = entries+ plist = plistlib.dumps(info)++ # the collection's segments: BASE's, grown to what is in them; __PRELINK_INFO as large as the prelink info+ pi = regions['__PRELINK_INFO']+ pi[1] = pi[0] + align(len(plist), KC_PAGE)+ for region, ms in members.items():+ if ms and region not in ('__LINKEDIT',):+ regions[region][0] = min(regions[region][0], min(a for a, b, w in ms))+ regions[region][1] = max(regions[region][1], align(max(b for a, b, w in ms), KC_PAGE))+ order = sorted(regions.items(), key=lambda kv: kv[1][0])+ for (n1, (a1, b1)), (n2, (a2, b2)) in zip(order, order[1:]):+ if a2 < b1:+ fail(f'segments {n1} ({a1:#x}-{b1:#x}) and {n2} ({a2:#x}-{b2:#x}) overlap')+ out[pi[0]:pi[0] + len(plist)] = plist+ top = [(s.name, regions[s.name][0], regions[s.name][1] - regions[s.name][0]) for s in base.segments]++ # the native kexts' bytes and headers+ for spec, kx, r in linked:+ for seg, b in r['segments'].items():+ off = kx.segs[seg]['addr'] - hdr+ out[off:off + len(b)] = b+ h = kx.header((hdr + k_le[0], k_le[0], k_le[1]))+ off = kx.segs['__TEXT']['addr'] - hdr+ out[off:off + len(h)] = h++ # the kernel's header: its segments at their file offsets in the collection, its symbols where they went+ cmds = []+ for cmd, raw in kernel.cmds:+ if cmd in KERNEL_DROPPED_CMDS:+ continue+ if cmd == LC_SEGMENT_64:+ seg = Segment(raw)+ if seg.name == '__LINKEDIT':+ seg.vmaddr, seg.fileoff = hdr + k_le[0], k_le[0]+ seg.vmsize = seg.filesize = k_le[1]+ else:+ seg.fileoff = seg.vmaddr - hdr+ for sec in seg.sections:+ sec.offset = 0 if sec.zerofill else sec.addr - hdr+ raw = seg.pack()+ elif cmd == LC_SYMTAB:+ raw = struct.pack('<IIIIII', LC_SYMTAB, 24, k_symoff, nsyms, k_stroff, strsize)+ elif cmd == LC_DYSYMTAB:+ f = list(struct.unpack_from('<18I', raw, 8))+ if any(f[i] for i in (7, 9, 11, 13, 15, 17)): # ntoc, nmodtab, nextrefsyms, nindirect, nextrel, nlocrel+ fail('the kernel has tables of its LC_DYSYMTAB besides symbols, not carried into the collection')+ raw = struct.pack('<II18I', LC_DYSYMTAB, 80, *f)+ cmds.append(raw)+ body = b''.join(cmds)+ koff = ktext.vmaddr - hdr+ magic, cpu, sub, ft, _, old_size, flags, res = HEADER.unpack_from(kbuf, 0)+ flags |= MH_DYLIB_IN_CACHE # XNU takes the kernel to be in a collection (its chained fixups, not __thread_starts)+ out[koff:koff + HEADER.size + old_size] = HEADER.pack(magic, cpu, sub, ft, len(cmds), len(body), flags, res) + \+ body + b'\0' * (old_size - len(body))++ # chained fixups, then the collection's header+ blob = kc_write_fixups(out, hdr, top, fixups)+ fix_off = len(out)+ out += blob+ out += b'\0' * (align(len(out), KC_PAGE) - len(out))+ regions['__LINKEDIT'][1] = len(out)+ # every entry's __LINKEDIT: the collection's link-edit data its symbol table is in, to the end of the file+ le_start = min([k_symoff] + [old_entries[n].segment('__LINKEDIT').fileoff for n in kept+ if old_entries[n].segment('__LINKEDIT')])+ for off in [koff] + [old_entries[n].off for n in kept] + [kx.segs['__TEXT']['addr'] - hdr for spec, kx, r in linked]:+ img = Image(out, off)+ p = off + HEADER.size+ for cmd, raw in img.cmds:+ if cmd == LC_SEGMENT_64 and Segment(raw).name == '__LINKEDIT':+ seg = Segment(raw)+ seg.vmaddr, seg.fileoff = hdr + le_start, le_start+ seg.vmsize = seg.filesize = len(out) - le_start+ out[p:p + len(raw)] = seg.pack()+ p += len(raw)+ top = [(s.name, regions[s.name][0], regions[s.name][1] - regions[s.name][0]) for s in base.segments]++ tcmds = []+ for cmd, raw in base.cmds:+ if cmd == LC_UNIXTHREAD:+ raw = kernel.cmd(LC_UNIXTHREAD)+ elif cmd == LC_DYLD_CHAINED_FIXUPS:+ raw = struct.pack('<IIII', LC_DYLD_CHAINED_FIXUPS, 16, fix_off, len(blob))+ elif cmd == LC_SEGMENT_64:+ s = Segment(raw)+ a, size = regions[s.name][0], regions[s.name][1] - regions[s.name][0]+ s.vmaddr, s.vmsize, s.fileoff, s.filesize = hdr + a, size, a, size+ for sec in s.sections: # __PRELINK_TEXT,__text and __PRELINK_INFO,__info span their segment+ sec.addr, sec.size, sec.offset = s.vmaddr, (len(plist) if s.name == '__PRELINK_INFO' else size), a+ raw = s.pack()+ elif cmd == LC_FILESET_ENTRY:+ continue+ tcmds.append(raw)+ fileset = [(KERNEL_ID, ktext.vmaddr)] + [(n, u64(old_entries[n].segment('__TEXT').vmaddr + slide)) for n in kept] \+ + [(spec['bundle'], kx.segs['__TEXT']['addr']) for spec, kx, r in linked]+ for name, va in fileset:+ nm = name.encode() + b'\0'+ size = align(32 + len(nm), 8)+ tcmds.append(struct.pack('<IIQQII', LC_FILESET_ENTRY, size, va, va - hdr, 32, 0) + nm.ljust(size - 32, b'\0'))+ body = b''.join(tcmds)+ if HEADER.size + len(body) > regions['__TEXT'][1]:+ fail(f'the collection\'s load commands ({len(body):#x} bytes) do not fit in its __TEXT')+ magic, cpu, sub, ft, _, _, flags, res = HEADER.unpack_from(bbuf, 0)+ out[0:regions['__TEXT'][1]] = (HEADER.pack(magic, cpu, sub, ft, len(tcmds), len(body), flags, res) + body).ljust(+ regions['__TEXT'][1], b'\0')++ Path(args.output).write_bytes(out)+ Path(args.output).with_suffix('.natives.json').write_text(json.dumps(natives))+ print(f'wrote {args.output}: {len(out):#x} bytes, base {hdr:#x}, {len(fixups)} chained pointers')+++if __name__ == '__main__':+ main()diff --git a/scripts/kclink/kextld.py b/scripts/kclink/kextld.pynew file mode 100644index 0000000..f3fd4d2--- /dev/null+++ b/scripts/kclink/kextld.py@@ -0,0 +1,424 @@+# SPDX-License-Identifier: GPL-2.0-only+"""Links a kext from arm64e object files for a kernel collection: its sections laid out into the segments a kext in a+collection has (__TEXT with the Mach-O header, __TEXT_EXEC, __DATA_CONST, __DATA), its kmod_info, a GOT for what the+code loads through one, every relocation resolved, and every pointer handed back as a chained fixup for the collection.++Placement is the caller's: `layout()` gives each segment's size and alignment, `place()` takes the address each one+goes to, `link()` resolves and returns the bytes of each segment, its load commands and its pointers."""+import struct+import uuid++from macho import (HEADER, MH_MAGIC_64, MH_OBJECT, MH_KEXT_BUNDLE, CPU_TYPE_ARM64, LC_SEGMENT_64, LC_SYMTAB, LC_UUID,+ N_STAB, N_PEXT, N_TYPE, N_EXT, N_UNDF, N_ABS, N_SECT, NLIST, Fixup, Image, Section, Segment,+ align, name16)++# where each section of an object goes in the kext: (segment, section)+PLACEMENT = {+ ('__TEXT', '__text'): ('__TEXT_EXEC', '__text'),+ ('__TEXT', '__cstring'): ('__TEXT', '__cstring'),+ ('__TEXT', '__const'): ('__TEXT', '__const'),+ ('__TEXT', '__literal4'): ('__TEXT', '__literal4'),+ ('__TEXT', '__literal8'): ('__TEXT', '__literal8'),+ ('__TEXT', '__literal16'): ('__TEXT', '__literal16'),+ ('__TEXT', '__os_log'): ('__TEXT', '__os_log'),+ ('__TEXT', '__ustring'): ('__TEXT', '__ustring'),+ ('__DATA', '__const'): ('__DATA_CONST', '__const'),+ ('__DATA_CONST', '__const'): ('__DATA_CONST', '__const'),+ ('__DATA', '__kalloc_type'): ('__DATA_CONST', '__kalloc_type'),+ ('__DATA_CONST', '__kalloc_type'): ('__DATA_CONST', '__kalloc_type'),+ ('__DATA', '__kalloc_var'): ('__DATA_CONST', '__kalloc_var'),+ ('__DATA_CONST', '__kalloc_var'): ('__DATA_CONST', '__kalloc_var'),+ ('__DATA_CONST', '__assert'): ('__DATA_CONST', '__assert'),+ ('__DATA', '__mod_init_func'): ('__DATA_CONST', '__mod_init_func'),+ ('__DATA', '__mod_term_func'): ('__DATA_CONST', '__mod_term_func'),+ ('__DATA', '__data'): ('__DATA', '__data'),+ ('__DATA', '__bss'): ('__DATA', '__bss'),+ ('__DATA', '__common'): ('__DATA', '__common'),+}+# sections that carry nothing into the kext+DROPPED = {('__LD', '__compact_unwind'), ('__TEXT', '__eh_frame'), ('__LLVM', '__bitcode'), ('__LLVM', '__cmdline')}+SEGMENTS = ['__TEXT', '__TEXT_EXEC', '__DATA_CONST', '__DATA'] # their order in the kext+PROT = {'__TEXT': 1, '__TEXT_EXEC': 5, '__DATA_CONST': 3, '__DATA': 3}+SECT_FLAGS = {'__text': 0x80000400, '__cstring': 0x2, '__literal4': 0x3, '__literal8': 0x4, '__literal16': 0xe,+ '__mod_init_func': 0x9, '__mod_term_func': 0xa, '__got': 0x6, '__bss': 0x1, '__common': 0x1}+ZEROFILL = {'__bss', '__common'}++# arm64 relocation types+UNSIGNED, SUBTRACTOR, BRANCH26, PAGE21, PAGEOFF12, GOT_LOAD_PAGE21, GOT_LOAD_PAGEOFF12, POINTER_TO_GOT = range(8)+ADDEND, AUTHENTICATED_POINTER = 10, 11++# kmod_info_t (<mach/kmod.h>, 4-byte packed): next, info_version, id, name[64], version[64], reference_count,+# reference_list, address, size, hdr_size, start, stop+KMOD_INFO_SIZE = 196+KMOD_ADDRESS, KMOD_SIZE, KMOD_START, KMOD_STOP = 156, 164, 180, 188+# kmod_info's start and stop are signed with the IA key and the type discriminator of kmod_start_func_t, as XNU calls+# them (the value Apple's own kexts carry in their kmod_info)+KMOD_FUNC_DIV = 0xe4fe+MH_FLAGS = 0x80000085 # MH_NOUNDEFS | MH_DYLDLINK | MH_TWOLEVEL | MH_DYLIB_IN_CACHE+HEADER_RESERVE = 0x1000 # room for the header in __TEXT+++class LinkError(Exception):+ pass+++class OutSection:+ def __init__(self, seg, name):+ self.seg, self.name = seg, name+ self.size, self.align = 0, 0 # align: log2+ self.pieces = [] # (object index, input section index, offset in this section)+ self.data = None+ self.addr = 0+++class Obj:+ def __init__(self, path):+ self.path = path+ self.buf = open(path, 'rb').read()+ self.img = Image(self.buf)+ if self.img.filetype != MH_OBJECT or self.img.cputype != CPU_TYPE_ARM64:+ raise LinkError(f'{path}: not an arm64 object')+ self.sects = self.img.sections() # input sections, 1-based in nlist n_sect+ self.syms = self.img.symbols()+ self.where = {} # input section index -> (OutSection, offset)+++class Kext:+ """One kext from its spec (scripts/kexts' NAME.json: name, bundle, version, start, stop, objects...)."""++ def __init__(self, spec, objects):+ self.spec = spec+ self.objs = [Obj(p) for p in objects]+ self.out = {} # (seg, sect) -> OutSection, in creation order+ self.globals = {} # name -> (OutSection, offset) of defined external symbols+ self.got = {} # symbol name -> index in __got+ self.segs = {} # seg name -> {'size', 'align', 'addr'}+ self.symbols = {} # every named symbol's address once linked, for symbolizing++ def section(self, seg, name):+ key = (seg, name)+ if key not in self.out:+ self.out[key] = OutSection(seg, name)+ return self.out[key]++ def layout(self):+ """Lays out the sections into segments; returns {segment: (size, alignment in bytes)}."""+ # kmod_info first in __DATA,__data (what _PrelinkKmodInfo points at)+ kmod = self.section('__DATA', '__data')+ kmod.size, kmod.align = KMOD_INFO_SIZE, 3+ for oi, o in enumerate(self.objs):+ for si, s in enumerate(o.sects):+ key = (s.segname, s.sectname)+ if key in DROPPED or s.sectname.startswith('__debug') or s.segname == '__DWARF':+ continue+ if key not in PLACEMENT:+ raise LinkError(f'{o.path}: section {s.segname},{s.sectname} has no place in a kext')+ out = self.section(*PLACEMENT[key])+ off = align(out.size, 1 << s.align)+ out.pieces.append((oi, si, off))+ out.size, out.align = off + s.size, max(out.align, s.align)+ o.where[si] = (out, off)+ # common symbols: zero-filled storage in __DATA,__common+ common = {}+ for o in self.objs:+ for n, t, sc, d, v in o.syms:+ if not t & N_STAB and (t & N_TYPE) == N_UNDF and t & N_EXT and v:+ size, al = common.get(n, (0, 0))+ common[n] = (max(size, v), max(al, (d >> 8) & 0xf))+ if common:+ out = self.section('__DATA', '__common')+ for n, (size, al) in common.items():+ off = align(out.size, 1 << al)+ out.size, out.align = off + size, max(out.align, al)+ self.globals[n] = (out, off)+ # defined external symbols (private externs too: one kext is one linkage unit)+ for oi, o in enumerate(self.objs):+ for n, t, sc, d, v in o.syms:+ if t & N_STAB or not t & (N_EXT | N_PEXT) or (t & N_TYPE) != N_SECT:+ continue+ where = self.place_of(o, sc, v)+ if n in self.globals and self.globals[n] != where:+ if not d & 0x80: # N_WEAK_DEF: the first definition stays+ prev = self.globals[n]+ raise LinkError(f'{n} defined twice (in {o.path} and at {prev[0].seg},{prev[0].name})')+ continue+ self.globals.setdefault(n, where)+ # a GOT entry for every symbol the code loads through one+ for o in self.objs:+ for s in o.sects:+ for r in self.relocs(o, s):+ if r[1] in (GOT_LOAD_PAGE21, GOT_LOAD_PAGEOFF12, POINTER_TO_GOT):+ if not r[3]:+ raise LinkError(f'{o.path}: GOT load of a section, not a symbol')+ name = o.syms[r[2]][0]+ self.got.setdefault(name, len(self.got))+ if self.got:+ g = self.section('__DATA_CONST', '__got')+ g.size, g.align = 8 * len(self.got), 3+ # segments: their sections in order, zero-fill last in __DATA+ for seg in SEGMENTS:+ size = HEADER_RESERVE if seg == '__TEXT' else 0+ al = 4+ sects = [s for s in self.out.values() if s.seg == seg]+ sects.sort(key=lambda s: s.name in ZEROFILL)+ for s in sects:+ s.segoff = align(size, 1 << s.align)+ size = s.segoff + s.size+ al = max(al, s.align)+ size = align(size, 16)+ self.segs[seg] = {'size': size, 'align': 1 << al, 'addr': None, 'sects': sects}+ return {seg: (v['size'], v['align']) for seg, v in self.segs.items() if v['size']}++ def place_of(self, o, sect, value):+ s = o.sects[sect - 1]+ if sect - 1 not in o.where:+ raise LinkError(f'{o.path}: a symbol in dropped section {s.segname},{s.sectname}')+ out, off = o.where[sect - 1]+ return out, off + value - s.addr++ def place(self, addrs, base):+ """Takes each segment's address ({segment: address}); `base`: the collection's header address (a collection's+ file offsets are its addresses less that)."""+ for seg, v in self.segs.items():+ v['addr'] = addrs.get(seg, 0)+ v['fileoff'] = v['addr'] - base+ for s in v['sects']:+ s.addr = v['addr'] + s.segoff++ @staticmethod+ def relocs(o, s):+ out = []+ for i in range(s.nreloc):+ addr, info = struct.unpack_from('<iI', o.buf, s.reloff + 8 * i)+ out.append((addr, info >> 28, info & 0xffffff, (info >> 27) & 1, (info >> 25) & 3, (info >> 24) & 1))+ return out++ def addr_of(self, where):+ out, off = where+ return out.addr + off++ def vtable(self):+ """The address of the vtable of the spec's `vtable` class (the C++ class of this kext whose superclass is in+ another kext), or None."""+ vt = self.spec.get('vtable')+ if not vt:+ return None+ name = f'__ZTV{len(vt["class"])}{vt["class"]}'+ if name not in self.globals:+ raise LinkError(f'{self.spec["bundle"]}: no vtable {name}')+ return self.addr_of(self.globals[name])++ def link(self, resolve, inherited=None):+ """Resolves every relocation (`resolve(name)`: the address of a symbol outside this kext, or None) and returns+ {'segments': {seg: bytes}, 'fixups': {address: Fixup}, 'symbols': {name: address}}.+ A slot of the spec's `vtable` class that names a method no kext exports (a superclass's private override) gets+ what the superclass's vtable has in that slot: `inherited(slot)`, slots counted from the vtable's address+ point."""+ sp = self.spec+ unresolved = set()+ pending = [] # (address, symbol, Fixup, addend) of pointers to unresolved symbols+ fixups = {}++ def sym_addr(o, idx):+ n, t, sc, d, v = o.syms[idx]+ typ = t & N_TYPE+ if typ == N_SECT:+ return self.addr_of(self.place_of(o, sc, v))+ if typ == N_ABS:+ return v+ if n in self.globals:+ return self.addr_of(self.globals[n])+ return resolve(n)++ def ext_addr(name):+ if name in self.globals:+ return self.addr_of(self.globals[name])+ a = resolve(name)+ if a is None:+ unresolved.add(name)+ return 0+ return a++ for s in self.out.values():+ s.data = bytearray(0 if s.name in ZEROFILL else s.size)+ for oi, o in enumerate(self.objs):+ for si, s in enumerate(o.sects):+ if si not in o.where:+ continue+ out, off = o.where[si]+ if not s.zerofill:+ out.data[off:off + s.size] = o.buf[s.offset:s.offset + s.size]+ addend = 0+ for raddr, typ, num, ext, length, pcrel in self.relocs(o, s):+ if typ == ADDEND:+ addend = num - (1 << 24) if num & (1 << 23) else num+ continue+ pos = off + raddr+ place = out.addr + pos+ if ext:+ name = o.syms[num][0]+ target = sym_addr(o, num)+ if target is None and typ not in (UNSIGNED, AUTHENTICATED_POINTER, GOT_LOAD_PAGE21,+ GOT_LOAD_PAGEOFF12):+ unresolved.add(name)+ addend = 0+ continue+ else: # a section-relative reference: its address is in the content+ target, name = None, None+ if typ in (UNSIGNED, AUTHENTICATED_POINTER):+ if length != 3:+ raise LinkError(f'{o.path}: {length * 8}-bit pointer at {s.sectname}+{raddr:#x}')+ raw = struct.unpack_from('<Q', out.data, pos)[0]+ if typ == AUTHENTICATED_POINTER:+ add = raw & 0xffffffff+ add = add - (1 << 32) if add & (1 << 31) else add+ f = Fixup(0, (raw >> 49) & 3, (raw >> 32) & 0xffff, (raw >> 48) & 1)+ else:+ add, f = raw, Fixup(0)+ if ext and target is None:+ pending.append((place, name, f, add))+ struct.pack_into('<Q', out.data, pos, 0)+ addend = 0+ continue+ if target is None: # section index num, the content an address in the object+ ts = o.sects[num - 1]+ tout, toff = o.where[num - 1]+ target, add = tout.addr + toff + (add - ts.addr), 0+ f.target = (target + add) & 0xffffffffffffffff+ struct.pack_into('<Q', out.data, pos, 0)+ fixups[place] = f+ elif typ == BRANCH26:+ delta = target + addend - place+ if not -(1 << 27) <= delta < (1 << 27) or delta & 3:+ raise LinkError(f'{o.path}: branch to {name} out of range ({delta:#x})')+ insn = struct.unpack_from('<I', out.data, pos)[0]+ struct.pack_into('<I', out.data, pos, (insn & 0xfc000000) | ((delta >> 2) & 0x3ffffff))+ elif typ in (PAGE21, GOT_LOAD_PAGE21):+ t = self.got_addr(name) if typ == GOT_LOAD_PAGE21 else target + addend+ pages = (t >> 12) - (place >> 12)+ if not -(1 << 20) <= pages < (1 << 20):+ raise LinkError(f'{o.path}: adrp to {name} out of range')+ insn = struct.unpack_from('<I', out.data, pos)[0]+ insn = (insn & 0x9f00001f) | ((pages & 3) << 29) | (((pages >> 2) & 0x7ffff) << 5)+ struct.pack_into('<I', out.data, pos, insn)+ elif typ in (PAGEOFF12, GOT_LOAD_PAGEOFF12):+ t = self.got_addr(name) if typ == GOT_LOAD_PAGEOFF12 else target + addend+ insn = struct.unpack_from('<I', out.data, pos)[0]+ struct.pack_into('<I', out.data, pos, pageoff12(insn, t & 0xfff, o.path, name))+ else:+ raise LinkError(f'{o.path}: relocation type {typ} at {s.sectname}+{raddr:#x}')+ addend = 0+ if pending:+ vt = self.vtable()+ for place, name, f, add in pending:+ j = (place - vt - 16) // 8 if vt is not None else -1+ t = inherited(j) if j >= 0 and (place - vt) % 8 == 0 and inherited else None+ if t is None:+ unresolved.add(name)+ continue+ f.target = (t + add) & 0xffffffffffffffff+ fixups[place] = f+ # the GOT+ if self.got:+ g = self.out[('__DATA_CONST', '__got')]+ for name, i in self.got.items():+ fixups[g.addr + 8 * i] = Fixup(ext_addr(name))+ # kmod_info+ text, data = self.segs['__TEXT'], self.out[('__DATA', '__data')]+ k = data.data+ struct.pack_into('<QIi64s64si', k, 0, 0, 1, -1, sp['bundle'].encode(), sp['version'].encode(), -1)+ struct.pack_into('<QQQQ', k, KMOD_ADDRESS, text['addr'], text['size'], 0, 0)+ fixups[data.addr + KMOD_START] = Fixup(ext_addr(sp['start']), 0, KMOD_FUNC_DIV, 0)+ fixups[data.addr + KMOD_STOP] = Fixup(ext_addr(sp['stop']), 0, KMOD_FUNC_DIV, 0)+ if unresolved:+ raise LinkError(f'{sp["bundle"]}: unresolved symbols: {" ".join(sorted(unresolved))}')+ # every named symbol, for symbolizing+ for o in self.objs:+ for n, t, sc, d, v in o.syms:+ if n and not t & N_STAB and (t & N_TYPE) == N_SECT and sc - 1 in o.where:+ self.symbols.setdefault(n, self.addr_of(self.place_of(o, sc, v)))+ for n, where in self.globals.items():+ self.symbols[n] = self.addr_of(where)+ segments = {}+ for seg, v in self.segs.items():+ if not v['size']:+ continue+ b = bytearray(v['size'])+ for s in v['sects']:+ if s.name not in ZEROFILL:+ b[s.segoff:s.segoff + s.size] = s.data+ segments[seg] = b+ return {'segments': segments, 'fixups': fixups, 'symbols': dict(self.symbols)}++ def got_addr(self, name):+ return self.out[('__DATA_CONST', '__got')].addr + 8 * self.got[name]++ def uuid(self):+ return uuid.uuid5(uuid.NAMESPACE_URL, self.spec['bundle']).bytes++ def header(self, linkedit):+ """The kext's Mach-O header and load commands (written at the start of its __TEXT); `linkedit`: the+ collection's (vmaddr, fileoff, size) of the __LINKEDIT the kext's empty symbol table points into."""+ cmds = []+ order = ['__TEXT', '__TEXT_EXEC', '__DATA', '__DATA_CONST']+ for seg in order:+ v = self.segs[seg]+ if not v['size']:+ continue+ sg = Segment(name=seg, vmaddr=v['addr'], vmsize=v['size'], fileoff=v['fileoff'], filesize=v['size'],+ prot=PROT[seg])+ for s in v['sects']:+ sec = Section(b'\0' * 80)+ sec.sectname, sec.segname = s.name, seg+ sec.addr, sec.size, sec.align = s.addr, s.size, s.align+ sec.offset = 0 if s.name in ZEROFILL else v['fileoff'] + s.segoff+ sec.flags = SECT_FLAGS.get(s.name, 0)+ if s.name == '__kalloc_type' or s.name == '__kalloc_var':+ sec.flags = 0x8000000+ sg.sections.append(sec)+ cmds.append(sg.pack())+ le_va, le_off, le_size = linkedit+ cmds.append(Segment(name='__LINKEDIT', vmaddr=le_va, vmsize=le_size, fileoff=le_off, filesize=le_size).pack())+ cmds.append(struct.pack('<IIIIII', LC_SYMTAB, 24, le_off, 0, le_off, 0))+ cmds.append(struct.pack('<II', LC_UUID, 24) + self.uuid())+ body = b''.join(cmds)+ hdr = HEADER.pack(MH_MAGIC_64, CPU_TYPE_ARM64, 0xc0000002, MH_KEXT_BUNDLE, len(cmds), len(body), MH_FLAGS, 0)+ if len(hdr) + len(body) > HEADER_RESERVE:+ raise LinkError(f'{self.spec["bundle"]}: load commands do not fit in {HEADER_RESERVE:#x} bytes')+ return hdr + body++ def plist(self, data_va):+ sp = self.spec+ text = self.segs['__TEXT']+ d = {+ 'CFBundleExecutable': sp['name'], 'CFBundleIdentifier': sp['bundle'],+ 'CFBundleInfoDictionaryVersion': '6.0', 'CFBundleName': sp['name'], 'CFBundlePackageType': 'KEXT',+ 'CFBundleShortVersionString': sp['version'], 'CFBundleVersion': sp['version'],+ 'OSBundleCompatibleVersion': sp.get('compatible_version', '1.0.0'),+ 'OSBundleLibraries': sp.get('libraries', {}), 'IOKitPersonalities': sp.get('personalities', {}),+ 'OSBundleRequired': 'Root', 'OSBundleUUID': self.uuid(),+ '_PrelinkBundlePath': f'/System/Library/Extensions/{sp["name"]}.kext',+ '_PrelinkExecutableRelativePath': f'Contents/MacOS/{sp["name"]}',+ '_PrelinkExecutableLoadAddr': signed(text['addr']), '_PrelinkExecutableSourceAddr': signed(text['addr']),+ '_PrelinkExecutableSize': text['size'], '_PrelinkKmodInfo': signed(data_va),+ }+ d.update(sp.get('plist', {}))+ return d+++def signed(v):+ return v - (1 << 64) if v >= 1 << 63 else v+++def pageoff12(insn, lo, path, name):+ """The low 12 bits of an address into an add (immediate) or a load/store (unsigned offset, scaled)."""+ if (insn & 0x7f000000) == 0x11000000: # add/adds (immediate), 32 or 64-bit+ return (insn & ~(0xfff << 10)) | (lo << 10)+ if (insn & 0x3b000000) == 0x39000000: # ldr/str (unsigned immediate), integer or SIMD&FP+ scale = insn >> 30+ if insn & (1 << 26) and scale == 0 and insn & (1 << 23):+ scale = 4 # 128-bit q register+ if lo & ((1 << scale) - 1):+ raise LinkError(f'{path}: {name}: offset {lo:#x} not aligned for a {1 << scale}-byte access')+ return (insn & ~(0xfff << 10)) | ((lo >> scale) << 10)+ raise LinkError(f'{path}: {name}: page offset into instruction {insn:#010x}')diff --git a/scripts/kclink/macho.py b/scripts/kclink/macho.pynew file mode 100644index 0000000..17d691f--- /dev/null+++ b/scripts/kclink/macho.py@@ -0,0 +1,307 @@+# SPDX-License-Identifier: GPL-2.0-only+"""Mach-O reading and writing for kclink: images inside a buffer (a kernel, a kernel collection's fileset entries, kext+objects), their load commands, segments, sections and symbols, and the chained fixups of a kernel collection+(DYLD_CHAINED_PTR_64_KERNEL_CACHE) and of a kernel linked with threaded rebases (__TEXT,__thread_starts).++Formats as <mach-o/loader.h>, <mach-o/nlist.h>, <mach-o/fixup-chains.h> and <mach-o/arm64/reloc.h> define them."""+import struct++MH_MAGIC_64 = 0xfeedfacf+MH_OBJECT, MH_EXECUTE, MH_KEXT_BUNDLE, MH_FILESET = 0x1, 0x2, 0xb, 0xc+CPU_TYPE_ARM64 = 0x0100000c+LC_SYMTAB, LC_UNIXTHREAD, LC_DYSYMTAB, LC_SEGMENT_64, LC_UUID = 0x2, 0x5, 0xb, 0x19, 0x1b+LC_SEGMENT_SPLIT_INFO, LC_FUNCTION_STARTS, LC_DATA_IN_CODE = 0x1e, 0x26, 0x29+LC_DYLD_CHAINED_FIXUPS, LC_FILESET_ENTRY = 0x80000034, 0x80000035+S_ZEROFILL, S_GB_ZEROFILL, S_THREAD_LOCAL_ZEROFILL = 0x1, 0xc, 0x12+N_STAB, N_PEXT, N_TYPE, N_EXT = 0xe0, 0x10, 0x0e, 0x01+N_UNDF, N_ABS, N_SECT, N_INDR = 0x0, 0x2, 0xe, 0xa++HEADER = struct.Struct('<IIIIIIII')+SEGMENT = struct.Struct('<II16sQQQQiiII')+SECTION = struct.Struct('<16s16sQQIIIIIIII')+NLIST = struct.Struct('<IBBHQ')+++def cstr(b):+ return b.split(b'\0', 1)[0].decode()+++def name16(s):+ return s.encode().ljust(16, b'\0')+++def align(v, a):+ return (v + a - 1) & ~(a - 1)+++class Section:+ def __init__(self, raw):+ (sn, sg, self.addr, self.size, self.offset, self.align, self.reloff, self.nreloc, self.flags,+ self.reserved1, self.reserved2, self.reserved3) = SECTION.unpack(raw)+ self.sectname, self.segname = cstr(sn), cstr(sg)++ @property+ def zerofill(self):+ return (self.flags & 0xff) in (S_ZEROFILL, S_GB_ZEROFILL, S_THREAD_LOCAL_ZEROFILL)++ def pack(self):+ return SECTION.pack(name16(self.sectname), name16(self.segname), self.addr, self.size, self.offset, self.align,+ self.reloff, self.nreloc, self.flags, self.reserved1, self.reserved2, self.reserved3)+++class Segment:+ def __init__(self, raw=None, name='', vmaddr=0, vmsize=0, fileoff=0, filesize=0, prot=1, flags=0):+ self.sections = []+ if raw is None:+ self.name, self.vmaddr, self.vmsize, self.fileoff, self.filesize = name, vmaddr, vmsize, fileoff, filesize+ self.maxprot = self.initprot = prot+ self.flags = flags+ return+ (_, _, n, self.vmaddr, self.vmsize, self.fileoff, self.filesize, self.maxprot, self.initprot, nsects,+ self.flags) = SEGMENT.unpack_from(raw)+ self.name = cstr(n)+ self.sections = [Section(raw[SEGMENT.size + SECTION.size * i:SEGMENT.size + SECTION.size * (i + 1)])+ for i in range(nsects)]++ def pack(self):+ return SEGMENT.pack(LC_SEGMENT_64, SEGMENT.size + SECTION.size * len(self.sections), name16(self.name),+ self.vmaddr, self.vmsize, self.fileoff, self.filesize, self.maxprot, self.initprot,+ len(self.sections), self.flags) + b''.join(s.pack() for s in self.sections)++ def contains(self, va):+ return self.vmaddr <= va < self.vmaddr + self.vmsize+++class Image:+ """A Mach-O image whose header is at offset `off` of `buf`; file offsets in it are relative to `base`+ (0 for a file of its own, also 0 for a kernel collection's fileset entries, whose offsets are the collection's)."""++ def __init__(self, buf, off=0, base=0):+ self.buf, self.off, self.base = buf, off, base+ magic, self.cputype, self.cpusubtype, self.filetype, ncmds, self.sizeofcmds, self.flags, _ = \+ HEADER.unpack_from(buf, off)+ if magic != MH_MAGIC_64:+ raise ValueError(f'not a 64-bit Mach-O at {off:#x}')+ self.cmds = [] # (cmd, raw bytes), in order+ self.segments = []+ self.symtab = self.dysymtab = None+ self.entries = [] # MH_FILESET: (name, vmaddr, fileoff)+ p = off + HEADER.size+ for _ in range(ncmds):+ cmd, size = struct.unpack_from('<II', buf, p)+ raw = bytes(buf[p:p + size])+ self.cmds.append((cmd, raw))+ if cmd == LC_SEGMENT_64:+ self.segments.append(Segment(raw))+ elif cmd == LC_SYMTAB:+ self.symtab = struct.unpack_from('<IIII', raw, 8)+ elif cmd == LC_DYSYMTAB:+ self.dysymtab = struct.unpack_from('<18I', raw, 8)+ elif cmd == LC_FILESET_ENTRY:+ va, fo, noff = struct.unpack_from('<QQI', raw, 8)+ self.entries.append((cstr(raw[noff:]), va, fo))+ p += size++ def cmd(self, which):+ for c, raw in self.cmds:+ if c == which:+ return raw+ return None++ def segment(self, name):+ for s in self.segments:+ if s.name == name:+ return s+ return None++ def sections(self):+ return [s for seg in self.segments for s in seg.sections]++ def section(self, seg, sect):+ for s in self.sections():+ if s.segname == seg and s.sectname == sect:+ return s+ return None++ def va_to_off(self, va):+ """The file offset (in buf) of a virtual address, or None."""+ for s in self.segments:+ if s.vmaddr <= va < s.vmaddr + s.filesize:+ return self.base + s.fileoff + (va - s.vmaddr)+ return None++ def symbols(self):+ """[(name, type, sect, desc, value)] of the image's LC_SYMTAB."""+ if not self.symtab:+ return []+ symoff, nsyms, stroff, strsize = self.symtab+ b, out = self.buf, []+ for i in range(nsyms):+ strx, typ, sect, desc, value = NLIST.unpack_from(b, self.base + symoff + NLIST.size * i)+ end = b.index(b'\0', self.base + stroff + strx)+ out.append((bytes(b[self.base + stroff + strx:end]).decode(errors='replace'), typ, sect, desc, value))+ return out++ def exports(self):+ """{name: address} of the image's external defined symbols."""+ return {n: v for n, t, s, d, v in self.symbols()+ if not t & N_STAB and t & N_EXT and (t & N_TYPE) in (N_SECT, N_ABS)}+++# Chained fixups of a kernel collection: DYLD_CHAINED_PTR_64_KERNEL_CACHE, 4-byte stride+# target:30 (offset from the collection's header) cacheLevel:2 diversity:16 addrDiv:1 key:2 next:12 isAuth:1+PTR_64_KERNEL_CACHE = 8+KC_PAGE = 0x4000+++class Fixup:+ """A pointer the collection's loader writes: the address it points to, and how it is signed (key None: plain)."""+ __slots__ = ('target', 'key', 'div', 'addr_div')++ def __init__(self, target, key=None, div=0, addr_div=0):+ self.target, self.key, self.div, self.addr_div = target, key, div, addr_div++ def __repr__(self):+ return f'Fixup({self.target:#x}' + ('' if self.key is None else f', key {self.key} div {self.div:#x}'+ f'{" addr" if self.addr_div else ""}') + ')'+++def kc_decode(raw):+ """A DYLD_CHAINED_PTR_64_KERNEL_CACHE value: (target offset, cacheLevel, key or None, diversity, addrDiv, next)."""+ target, level = raw & 0x3fffffff, (raw >> 30) & 3+ nxt, auth = (raw >> 51) & 0xfff, raw >> 63+ if auth:+ return target, level, (raw >> 49) & 3, (raw >> 32) & 0xffff, (raw >> 48) & 1, nxt+ return target, level, None, 0, 0, nxt+++def kc_encode(target, key, div, addr_div, nxt):+ if not 0 <= target < 1 << 30:+ raise ValueError(f'fixup target offset {target:#x} out of range')+ v = target | nxt << 51+ if key is not None:+ v |= div << 32 | addr_div << 48 | key << 49 | 1 << 63+ return v+++def kc_read_fixups(buf, header_va, top_segments):+ """{offset from the collection's header: Fixup(target address)} of a collection's LC_DYLD_CHAINED_FIXUPS (only its+ own pointers, cacheLevel 0)."""+ img = Image(buf)+ raw = img.cmd(LC_DYLD_CHAINED_FIXUPS)+ out = {}+ if raw is None:+ return out+ dataoff, _ = struct.unpack_from('<II', raw, 8)+ _, starts_off, _, _, imports_count, _, _ = struct.unpack_from('<7I', buf, dataoff)+ if imports_count:+ raise ValueError('a kernel collection with chained imports')+ s = dataoff + starts_off+ seg_count = struct.unpack_from('<I', buf, s)[0]+ for i in range(seg_count):+ so = struct.unpack_from('<I', buf, s + 4 + 4 * i)[0]+ if not so:+ continue+ _, page_size, fmt, seg_off, _, page_count = struct.unpack_from('<IHHQIH', buf, s + so)+ if fmt != PTR_64_KERNEL_CACHE:+ raise ValueError(f'chained pointer format {fmt} (expected {PTR_64_KERNEL_CACHE})')+ for p in range(page_count):+ start = struct.unpack_from('<H', buf, s + so + 22 + 2 * p)[0]+ if start == 0xffff:+ continue+ if start & 0x8000:+ raise ValueError('multiple chain starts in a page')+ loc = seg_off + p * page_size + start+ while True:+ target, level, key, div, addr_div, nxt = kc_decode(struct.unpack_from('<Q', buf, loc)[0])+ if level:+ raise ValueError(f'pointer at {loc:#x} into another collection (level {level})')+ out[loc] = Fixup(header_va + target, key, div, addr_div)+ if not nxt:+ break+ loc += nxt * 4+ return out+++def kc_write_fixups(out, header_va, top_segments, fixups):+ """Writes every pointer of `fixups` ({offset: Fixup}) into `out` (the collection's bytes, file offset == offset from+ the header) as DYLD_CHAINED_PTR_64_KERNEL_CACHE chains, and returns the LC_DYLD_CHAINED_FIXUPS payload.+ `top_segments`: the collection's segments in load-command order, [(name, offset, size)]."""+ per_seg = [[] for _ in top_segments]+ locs = sorted(fixups)+ si = 0+ for loc in locs:+ if loc & 3:+ raise ValueError(f'misaligned pointer at {loc:#x}')+ while si < len(top_segments) and loc >= top_segments[si][1] + top_segments[si][2]:+ si += 1+ if si == len(top_segments) or loc < top_segments[si][1]:+ raise ValueError(f'pointer at {loc:#x} outside the collection\'s segments')+ per_seg[si].append(loc)+ seg_infos = []+ for (name, seg_off, seg_size), seglocs in zip(top_segments, per_seg):+ if not seglocs:+ seg_infos.append(None)+ continue+ page_count = (seg_size + KC_PAGE - 1) // KC_PAGE+ starts = [0xffff] * page_count+ for j, loc in enumerate(seglocs):+ page = (loc - seg_off) // KC_PAGE+ if starts[page] == 0xffff:+ starts[page] = (loc - seg_off) % KC_PAGE+ nxt = 0+ if j + 1 < len(seglocs) and (seglocs[j + 1] - seg_off) // KC_PAGE == page:+ nxt = (seglocs[j + 1] - loc) // 4+ f = fixups[loc]+ struct.pack_into('<Q', out, loc, kc_encode(f.target - header_va, f.key, f.div, f.addr_div, nxt))+ seg_infos.append(struct.pack('<IHHQIH', 22 + 2 * page_count, KC_PAGE, PTR_64_KERNEL_CACHE, seg_off, 0,+ page_count) + struct.pack(f'<{page_count}H', *starts))+ # dyld_chained_fixups_header, dyld_chained_starts_in_image, dyld_chained_starts_in_segment (8-byte aligned)+ image = bytearray(struct.pack('<I', len(top_segments)) + b'\0' * 4 * len(top_segments))+ pos = align(len(image), 8)+ image += b'\0' * (pos - len(image))+ for i, info in enumerate(seg_infos):+ if info is None:+ continue+ struct.pack_into('<I', image, 4 + 4 * i, len(image))+ image += info+ image += b'\0' * (align(len(image), 8) - len(image))+ starts_off = 32+ blob = struct.pack('<7I', 0, starts_off, starts_off + len(image), starts_off + len(image), 0, 1, 0)+ blob += b'\0' * (starts_off - len(blob)) + image+ return bytes(blob)+++def threaded_rebases(img):+ """{address: Fixup} of a kernel linked with threaded rebases: the chains listed in __TEXT,__thread_starts (as XNU's+ rebase_threaded_starts walks them). Signed pointers hold a 32-bit offset from the header; plain ones the address,+ sign-extended from 51 bits with the top byte kept apart."""+ sect = img.section('__TEXT', '__thread_starts')+ out = {}+ if sect is None or not sect.size:+ return out+ text = img.segment('__TEXT')+ words = struct.unpack_from(f'<{sect.size // 4}I', img.buf, img.base + sect.offset)+ stride = 8 if words[0] & 1 else 4+ for start in words[1:]:+ if start == 0xffffffff:+ break+ va = text.vmaddr + start+ while True:+ off = img.va_to_off(va)+ v = struct.unpack_from('<Q', img.buf, off)[0]+ if (v >> 62) & 1:+ raise ValueError(f'a threaded bind at {va:#x} in the kernel')+ if v >> 63:+ out[va] = Fixup(text.vmaddr + (v & 0xffffffff), (v >> 49) & 3, (v >> 32) & 0xffff, (v >> 48) & 1)+ else:+ top8 = (v & 0x0007f80000000000) << 13+ low = v & 0x000007ffffffffff+ if low & (1 << 42):+ low |= ~0x000007ffffffffff & 0xffffffffffffffff+ out[va] = Fixup(top8 | (low & 0x00ffffffffffffff))+ delta = (v >> 51) & 0x7ff+ if not delta:+ break+ va += delta * stride+ return outdiff --git a/scripts/mk-puredarwin-disk.sh b/scripts/mk-puredarwin-disk.shnew file mode 100755index 0000000..67d03ef--- /dev/null+++ b/scripts/mk-puredarwin-disk.sh@@ -0,0 +1,31 @@+#!/bin/bash+# SPDX-License-Identifier: GPL-2.0-only+# On the Mac: PureDarwin's root file system (scripts/puredarwin-root.sh) as the hosted system's disk, a GUID partition table+# with one journaled HFS+ volume (hfs.kext, Apple's or the free collection's, mounts it), and the ROOT_UUID xnu.ko boots it by.+# The kernel mounts the root read-only; PureDarwin's own images use ext4, whose kext clears that, and its mount(8) has no+# -uw for launchctl's remount, so /sbin/fsck (which launchctl runs first, on a read-only root) remounts it read-write as+# PureDarwin's HFS images do. The disk is checked on the Linux side before each boot (fsck.hfsplus), not here.+# mk-puredarwin-disk.sh ROOT.tar.gz OUT.img [SIZE (1g)] prints the disk's configuration for xnulinux-boot.sh (MAC_CONF):+# ROOT_UUID and BOOT_UUID, the partition's GUID+set -euo pipefail+ROOT=$1 OUT=$2 SIZE=${3:-1g}+M=$(mktemp -d); D="$OUT.dmg"+rm -f "$D"+hdiutil create -quiet -size "$SIZE" -fs "Journaled HFS+" -volname PureDarwin -layout GPTSPUD "$D"+hdiutil attach -quiet -owners on -nobrowse -mountpoint "$M" "$D"+trap 'hdiutil detach -quiet "$M" 2>/dev/null || true' EXIT+sudo tar -xzf "$ROOT" -C "$M"+sudo rm -rf "$M/.fseventsd" "$M/.Spotlight-V100"+F=$(mktemp)+cat > "$F" <<'FSCK'+#!/bin/zsh+# xnulinux: the disk was checked on the Linux host before boot (fsck.hfsplus); remount the HFS+ root read-write+dev=$(/bin/df / | /bin/awk 'NR==2 {print $1}')+/sbin/mount -t hfs -o update,rw "$dev" / && echo "xnulinux: root $dev remounted read-write"+exit 0+FSCK+sudo install -m 755 -o 0 -g 0 "$F" "$M/sbin/fsck"; rm -f "$F"+P=$(mktemp); diskutil info -plist "$M" > "$P"; uuid=$(plutil -extract DiskUUID raw "$P"); rm -f "$P"+sync; hdiutil detach -quiet "$M"; trap - EXIT; rmdir "$M"+mv "$D" "$OUT"+printf 'ROOT_UUID=%s\nBOOT_UUID=%s\n' "$uuid" "$uuid"diff --git a/scripts/puredarwin-root.sh b/scripts/puredarwin-root.shnew file mode 100755index 0000000..833a6ae--- /dev/null+++ b/scripts/puredarwin-root.sh@@ -0,0 +1,25 @@+#!/bin/bash+# SPDX-License-Identifier: GPL-2.0-only+# On a Linux host: PureDarwin's arm64 root file system as a tarball, from one of its disk images (Nix: .#image-arm64-virt-minimal,+# or the release puredarwin-arm64-virt-minimal-*.img.zst from hydra.lab004.dev). The image's root is the GPT partition+# "Darwin ext4 Root"; owners and modes are kept.+# puredarwin-root.sh IMAGE OUT.tar.gz+set -euo pipefail+IMG=$1 OUT=$2+start=$(python3 - "$IMG" <<'PY'+import struct, sys+f = open(sys.argv[1], 'rb'); f.seek(512)+h = f.read(92); lba, n, size = struct.unpack('<QIi', h[72:88])+f.seek(lba * 512)+for _ in range(n):+ e = f.read(size)+ if e[56:128].decode('utf-16le').rstrip('\0') == 'Darwin ext4 Root':+ print(struct.unpack('<Q', e[32:40])[0]); break+else:+ sys.exit('no "Darwin ext4 Root" partition')+PY+)+M=$(mktemp -d); trap 'sudo umount "$M" 2>/dev/null; rmdir "$M"' EXIT+sudo mount -o ro,loop,offset=$((start * 512)) "$IMG" "$M"+sudo tar -C "$M" --numeric-owner -czf "$OUT" .+echo "$OUT: $(du -h "$OUT" | cut -f1)"diff --git a/scripts/vm-xnu-rebuild.sh b/scripts/vm-xnu-rebuild.shindex bc090e1..e7d21cb 100755--- a/scripts/vm-xnu-rebuild.sh+++ b/scripts/vm-xnu-rebuild.sh@@ -24,8 +24,6 @@ mkdir -p $T/EXTERNAL_HEADERS/linux64for h in $P/include/*.h; do cmp -s $h $T/EXTERNAL_HEADERS/linux64/$(basename $h) || cp $h $T/EXTERNAL_HEADERS/linux64/; donet=$SECONDS; JOBS=12 bash k27/build-kernel27.sh 2>&1 | tail -15; echo "kernel: $((SECONDS - t)) s"if [ -e out/kc/kc27.bin ]; then- # the hosted system's extra Apple kexts (in kc27, not kept by default): IOSurface for actool, CoreImage and friends- for id in $(grep -v '^#' ~/w/poc/xnu-patches/kc-keep-extra.txt); do grep -qx "$id" configs/kc-keep.txt || echo "$id" >> configs/kc-keep.txt; donecp k27/segaddrs.sh /tmp/segaddrs.beforepython3 k27/kc27-layout.py out/kc/kc27.bin out/k27/kernel-k27.macho --write k27/segaddrs.sh | tail -2if ! cmp -s /tmp/segaddrs.before k27/segaddrs.sh; then@@ -54,8 +52,15 @@ if [ -e out/kc/kc27.bin ]; thenpython3 scripts/build-native-kext.py $n $(dirname $j)/$n.cpp -I $NETINC --obj ${KEXT_OBJ:-k27-obj} || { echo "kext $n failed to build: left out"; continue; }NATIVE="$NATIVE $j"done- t=$SECONDS; K27_NO_BOOT=1 NATIVE="$NATIVE" bash k27/try.sh 0 2>&1 | tail -3; echo "collection: $((SECONDS - t)) s"- grep -iE 'error|unresolved|XnuCpuMetal' out/k27/kc-build.log | tail -8 || true+ printf '%s\n' $NATIVE > out/k27/natives.txt # the kexts of ours in this collection, for scripts/apple-kc/package.sh+ # the collection (scripts/kclink): the kernel, xnulinux's kexts, and the Apple kexts of scripts/apple-kc/keep.txt from+ # macOS 27.2's kernelcache+ t=$SECONDS+ python3 ~/w/poc/scripts/kclink/kclink.py out/kc/kc27.bin out/k27/kernel-k27.macho out/k27/kc-k27.bin \+ --keep $(grep -v '^#' ~/w/poc/scripts/apple-kc/keep.txt) --native $NATIVE \+ --rebind $(grep -v '^#' ~/w/poc/scripts/apple-kc/rebind.txt) > out/k27/kclink.log 2>&1 ||+ { tail -5 out/k27/kclink.log; echo "kclink failed: out/k27/kclink.log"; exit 1; }+ grep -E '^wrote|vtable check' out/k27/kclink.log; echo "collection: $((SECONDS - t)) s"# AMFI of the collection's macOS expects the code-signature platform version of that build; the system disk's binaries# carry their own (macOS 27.0.1: 26 where 27.2's AMFI expects 27)python3 ~/w/poc/scripts/kc-amfi-platform.py out/k27/kc-k27.bin ${AMFI_PLATFORM:-26}diff --git a/scripts/xnulinux-boot.sh b/scripts/xnulinux-boot.shindex e9848e7..f1edb34 100755--- a/scripts/xnulinux-boot.sh+++ b/scripts/xnulinux-boot.sh@@ -10,10 +10,10 @@# kernel log goes to /var/log/xnulinux/, the exit status says how it ended# xnulinux-boot.sh stop end it (the disk synced first)#-# Configuration: /etc/xnulinux.conf, then /var/tmp/mac.conf (written by mk-macvm-disk.sh: ROOT_UUID, BOOT_UUID), then the+# Configuration: /etc/xnulinux.conf, then $MAC_CONF (/var/tmp/mac.conf, written by mk-macvm-disk.sh: ROOT_UUID, BOOT_UUID), then the# environment:# DISK (/var/tmp/mac.img) RAM_MB (7900) BOOTARGS CONSOLE_IN (/var/tmp/console-in) INPUT_IN (/var/tmp/xnu-input)-# FB_DUMP (/var/tmp/xnu-fb.raw) KEYSTORE (/var/tmp/xnu-keystore.bin) TRUSTCACHE (xnu/trustcache-mac.bin)+# FB_DUMP (/var/tmp/xnu-fb.raw) KEYSTORE (/var/tmp/xnu-keystore.bin) TRUSTCACHE (xnu/trustcache-mac.bin; empty: none)# IMAGE (xnu/kc.bin: the kernel collection under /lib/firmware) GPU (auto|off) CPUS (1: the hosted system's CPUs) XNU_ARGS (more xnu.ko parameters)set -euo pipefailcd "$(dirname "$0")/.."@@ -33,10 +33,11 @@ if [ "${1:-}" = stop ]; then # end the running hosted system (its disk synced fifiWAIT=0; [ "${1:-}" = --wait ] && WAIT=1[ -f /etc/xnulinux.conf ] && . /etc/xnulinux.conf-[ -f /var/tmp/mac.conf ] && . /var/tmp/mac.conf+MAC_CONF=${MAC_CONF:-/var/tmp/mac.conf} # the disk's UUIDs: mk-macvm-disk.sh's, or mk-puredarwin-disk.sh's output+[ -f "$MAC_CONF" ] && . "$MAC_CONF"DISK=${DISK:-/var/tmp/mac.img}; RAM_MB=${RAM_MB:-7900}; GPU=${GPU:-auto}; CPUS=${CPUS:-1}CONSOLE_IN=${CONSOLE_IN:-/var/tmp/console-in}; INPUT_IN=${INPUT_IN:-/var/tmp/xnu-input}; FB_DUMP=${FB_DUMP:-/var/tmp/xnu-fb.raw}-KEYSTORE=${KEYSTORE:-/var/tmp/xnu-keystore.bin}; TRUSTCACHE=${TRUSTCACHE:-xnu/trustcache-mac.bin}; IMAGE=${IMAGE:-xnu/kc.bin}+KEYSTORE=${KEYSTORE:-/var/tmp/xnu-keystore.bin}; TRUSTCACHE=${TRUSTCACHE-xnu/trustcache-mac.bin}; IMAGE=${IMAGE:-xnu/kc.bin}BOOTARGS=${BOOTARGS:-amfi_get_out_of_my_way=1 lp-sip0=2050}: "${ROOT_UUID:?no ROOT_UUID (/var/tmp/mac.conf from mk-macvm-disk.sh)}" "${BOOT_UUID:?no BOOT_UUID}"lsmod | grep -q '^xnu ' && { echo "xnu.ko is loaded: a hosted system is running (sudo rmmod xnu first)" >&2; exit 1; }@@ -109,7 +110,7 @@ for try in 1 2 3 4 5 6 7 8 9; dosync; echo 3 | sudo tee /proc/sys/vm/drop_caches >/dev/null; echo 1 | sudo tee /proc/sys/vm/compact_memory >/dev/nullsudo dmesg -Csudo setsid nohup insmod xnu-ko/xnu.ko mode=3 cpus="$CPUS" ram_mb="$RAM_MB" image="$IMAGE" \- trustcache="$TRUSTCACHE" disk="$DISK" root_uuid="$ROOT_UUID" boot_uuid="$BOOT_UUID" preboot_uuid="$BOOT_UUID" \+ ${TRUSTCACHE:+trustcache="$TRUSTCACHE"} disk="$DISK" root_uuid="$ROOT_UUID" boot_uuid="$BOOT_UUID" preboot_uuid="$BOOT_UUID" \console_in="$CONSOLE_IN" input_in="$INPUT_IN" fb_dump="$FB_DUMP" keystore="$KEYSTORE" bootargs="\"$BOOTARGS\"" ${XNU_ARGS:-} \> /var/tmp/xnu-insmod.log 2>&1 < /dev/null &sleep 5diff --git a/xnu-patches/0001-linux64-machine-layer.patch b/xnu-patches/0001-linux64-machine-layer.patchindex b405d4f..0ea0287 100644--- a/xnu-patches/0001-linux64-machine-layer.patch+++ b/xnu-patches/0001-linux64-machine-layer.patch@@ -2066,7 +2066,7 @@ diff --git a/osfmk/kern/link_compat.c b/osfmk/kern/link_compat.cindex e494eab..fc40514 100644--- a/osfmk/kern/link_compat.c+++ b/osfmk/kern/link_compat.c-@@ -65,3 +65,21 @@ native_verified_block_manifest_sha384(unsigned int device, const char *uuid, uin+@@ -65,3 +65,40 @@ native_verified_block_manifest_sha384(unsigned int device, const char *uuid, uin}#endif@@ -2088,6 +2088,25 @@ index e494eab..fc40514 100644+{+ return 0;+}++++/*++ * LINUX64 (xnulinux): the two functions of compiler-rt's profile runtime that OSKext's kext PGO collection calls. Without++ * them the link takes the runtime's objects from the toolchain's libclang_rt.cc_kext archive, Apple's binary. No kext++ * here is built with profiling; one that is gets size 0 and EIO.++ */++uint64_t __llvm_profile_get_size_for_buffer_internal(void);++uint64_t++__llvm_profile_get_size_for_buffer_internal(void)++{++ return 0;++}++++int __llvm_profile_write_buffer_internal(void);++int++__llvm_profile_write_buffer_internal(void)++{++ return -1;++}diff --git a/osfmk/kern/printf.c b/osfmk/kern/printf.cindex 2fc6931..d581670 100644--- a/osfmk/kern/printf.cdiff --git a/xnu-patches/kc-keep-extra.txt b/xnu-patches/kc-keep-extra.txtdeleted file mode 100644index 2ec3e7f..0000000--- a/xnu-patches/kc-keep-extra.txt+++ /dev/null@@ -1,11 +0,0 @@-# Apple kexts the hosted macOS needs beyond configs/kc-keep.txt (bundle IDs, one per line)-com.apple.iokit.IOSurface-com.apple.iokit.IOGraphicsFamily-com.apple.filesystems.lifs-com.apple.iokit.IOMobileGraphicsFamily-com.apple.iokit.IOAVFamily-# the keystore of Apple's virtual platform (VirtualMac): AppleKeyStore and AppleCredentialManager in software, no SEP-# hardware; AppleVirtualPlatform is their library-com.apple.driver.AppleVirtualPlatform-com.apple.driver.AppleVPCredentialManager-com.apple.driver.AppleVPKeyStore