XNU as a loadable kernel module inside Linux (macOS personality for arm64 Linux)
C
Prepare for open source: per-module licenses, SPDX headers, README
Heyang Zhoud9fb700841c3
diff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..cc1fff0--- /dev/null+++ b/LICENSE@@ -0,0 +1,14 @@+xnulinux is made of parts under different licenses, kept apart along the line between the Linux kernel and XNU.+Each source file names its license in an SPDX-License-Identifier line; the full texts are in LICENSES/:++ GPL-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/+ 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)+ 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)++Files without a comment syntax (JSON manifests, property lists, patches) are under the license of the directory they are in.++Copyright (c) 2026 Heyang Zhou and contributors.diff --git a/LICENSES/APSL-2.0.txt b/LICENSES/APSL-2.0.txtnew file mode 100644index 0000000..2d2d2cf--- /dev/null+++ b/LICENSES/APSL-2.0.txt@@ -0,0 +1,102 @@+APPLE PUBLIC SOURCE LICENSE+Version 2.0 - August 6, 2003++Please read this License carefully before downloading this software. By downloading or using this software, you are agreeing to be bound by the terms of this License. If you do not or cannot agree to the terms of this License, please do not download or use the software.++Apple Note: In January 2007, Apple changed its corporate name from "Apple Computer, Inc." to "Apple Inc." This change has been reflected below and copyright years updated, but no other changes have been made to the APSL 2.0.++1. General; Definitions. This License applies to any program or other work which Apple Inc. ("Apple") makes publicly available and which contains a notice placed by Apple identifying such program or work as "Original Code" and stating that it is subject to the terms of this Apple Public Source License version 2.0 ("License"). As used in this License:++ 1.1 "Applicable Patent Rights" mean: (a) in the case where Apple is the grantor of rights, (i) claims of patents that are now or hereafter acquired, owned by or assigned to Apple and (ii) that cover subject matter contained in the Original Code, but only to the extent necessary to use, reproduce and/or distribute the Original Code without infringement; and (b) in the case where You are the grantor of rights, (i) claims of patents that are now or hereafter acquired, owned by or assigned to You and (ii) that cover subject matter in Your Modifications, taken alone or in combination with Original Code.++ 1.2 "Contributor" means any person or entity that creates or contributes to the creation of Modifications.++ 1.3 "Covered Code" means the Original Code, Modifications, the combination of Original Code and any Modifications, and/or any respective portions thereof.++ 1.4 "Externally Deploy" means: (a) to sublicense, distribute or otherwise make Covered Code available, directly or indirectly, to anyone other than You; and/or (b) to use Covered Code, alone or as part of a Larger Work, in any way to provide a service, including but not limited to delivery of content, through electronic communication with a client other than You.++ 1.5 "Larger Work" means a work which combines Covered Code or portions thereof with code not governed by the terms of this License.++ 1.6 "Modifications" mean any addition to, deletion from, and/or change to, the substance and/or structure of the Original Code, any previous Modifications, the combination of Original Code and any previous Modifications, and/or any respective portions thereof. When code is released as a series of files, a Modification is: (a) any addition to or deletion from the contents of a file containing Covered Code; and/or (b) any new file or other representation of computer program statements that contains any part of Covered Code.++ 1.7 "Original Code" means (a) the Source Code of a program or other work as originally made available by Apple under this License, including the Source Code of any updates or upgrades to such programs or works made available by Apple under this License, and that has been expressly identified by Apple as such in the header file(s) of such work; and (b) the object code compiled from such Source Code and originally made available by Apple under this License++ 1.8 "Source Code" means the human readable form of a program or other work that is suitable for making modifications to it, including all modules it contains, plus any associated interface definition files, scripts used to control compilation and installation of an executable (object code).++ 1.9 "You" or "Your" means an individual or a legal entity exercising rights under this License. For legal entities, "You" or "Your" includes any entity which controls, is controlled by, or is under common control with, You, where "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 fifty percent (50%) or more of the outstanding shares or beneficial ownership of such entity.++2. Permitted Uses; Conditions & Restrictions. Subject to the terms and conditions of this License, Apple hereby grants You, effective on the date You accept this License and download the Original Code, a world-wide, royalty-free, non-exclusive license, to the extent of Apple's Applicable Patent Rights and copyrights covering the Original Code, to do the following:++ 2.1 Unmodified Code. You may use, reproduce, display, perform, internally distribute within Your organization, and Externally Deploy verbatim, unmodified copies of the Original Code, for commercial or non-commercial purposes, provided that in each instance:++ (a) You must retain and reproduce in all copies of Original Code the copyright and other proprietary notices and disclaimers of Apple as they appear in the Original Code, and keep intact all notices in the Original Code that refer to this License; and++ (b) You must include a copy of this License with every copy of Source Code of Covered Code and documentation You distribute or Externally Deploy, and You may not offer or impose any terms on such Source Code that alter or restrict this License or the recipients' rights hereunder, except as permitted under Section 6.++ 2.2 Modified Code. You may modify Covered Code and use, reproduce, display, perform, internally distribute within Your organization, and Externally Deploy Your Modifications and Covered Code, for commercial or non-commercial purposes, provided that in each instance You also meet all of these conditions:++ (a) You must satisfy all the conditions of Section 2.1 with respect to the Source Code of the Covered Code;++ (b) You must duplicate, to the extent it does not already exist, the notice in Exhibit A in each file of the Source Code of all Your Modifications, and cause the modified files to carry prominent notices stating that You changed the files and the date of any change; and++ (c) If You Externally Deploy Your Modifications, You must make Source Code of all Your Externally Deployed Modifications either available to those to whom You have Externally Deployed Your Modifications, or publicly available. Source Code of Your Externally Deployed Modifications must be released under the terms set forth in this License, including the license grants set forth in Section 3 below, for as long as you Externally Deploy the Covered Code or twelve (12) months from the date of initial External Deployment, whichever is longer. You should preferably distribute the Source Code of Your Externally Deployed Modifications electronically (e.g. download from a web site).++ 2.3 Distribution of Executable Versions. In addition, if You Externally Deploy Covered Code (Original Code and/or Modifications) in object code, executable form only, You must include a prominent notice, in the code itself as well as in related documentation, stating that Source Code of the Covered Code is available under the terms of this License with information on how and where to obtain such Source Code.++ 2.4 Third Party Rights. You expressly acknowledge and agree that although Apple and each Contributor grants the licenses to their respective portions of the Covered Code set forth herein, no assurances are provided by Apple or any Contributor that the Covered Code does not infringe the patent or other intellectual property rights of any other entity. Apple and each Contributor disclaim any liability to You for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, You hereby assume sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow You to distribute the Covered Code, it is Your responsibility to acquire that license before distributing the Covered Code.++3. Your Grants. In consideration of, and as a condition to, the licenses granted to You under this License, You hereby grant to any person or entity receiving or distributing Covered Code under this License a non-exclusive, royalty-free, perpetual, irrevocable license, under Your Applicable Patent Rights and other intellectual property rights (other than patent) owned or controlled by You, to use, reproduce, display, perform, modify, sublicense, distribute and Externally Deploy Your Modifications of the same scope and extent as Apple's licenses under Sections 2.1 and 2.2 above.++4. Larger Works. You may create a Larger Work by combining Covered Code with other code not governed by the terms of this License and distribute the Larger Work as a single product. In each such instance, You must make sure the requirements of this License are fulfilled for the Covered Code or any portion thereof.++5. Limitations on Patent License. Except as expressly stated in Section 2, no other patent rights, express or implied, are granted by Apple herein. Modifications and/or Larger Works may require additional patent licenses from Apple which Apple may grant in its sole discretion.++6. Additional Terms. You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations and/or other rights consistent with the scope of the license granted herein ("Additional Terms") to one or more recipients of Covered Code. However, You may do so only on Your own behalf and as Your sole responsibility, and not on behalf of Apple or any Contributor. You must obtain the recipient's agreement that any such Additional Terms are offered by You alone, and You hereby agree to indemnify, defend and hold Apple and every Contributor harmless for any liability incurred by or claims asserted against Apple or such Contributor by reason of any such Additional Terms.++7. Versions of the License. Apple may publish revised and/or new versions of this License from time to time. Each version will be given a distinguishing version number. Once Original Code has been published under a particular version of this License, You may continue to use it under the terms of that version. You may also choose to use such Original Code under the terms of any subsequent version of this License published by Apple. No one other than Apple has the right to modify the terms applicable to Covered Code created under this License.++8. NO WARRANTY OR SUPPORT. The Covered Code may contain in whole or in part pre-release, untested, or not fully tested works. The Covered Code may contain errors that could cause failures or loss of data, and may be incomplete or contain inaccuracies. You expressly acknowledge and agree that use of the Covered Code, or any portion thereof, is at Your sole and entire risk. THE COVERED CODE IS PROVIDED "AS IS" AND WITHOUT WARRANTY, UPGRADES OR SUPPORT OF ANY KIND AND APPLE AND APPLE'S LICENSOR(S) (COLLECTIVELY REFERRED TO AS "APPLE" FOR THE PURPOSES OF SECTIONS 8 AND 9) AND ALL CONTRIBUTORS EXPRESSLY DISCLAIM ALL WARRANTIES AND/OR CONDITIONS, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES AND/OR CONDITIONS OF MERCHANTABILITY, OF SATISFACTORY QUALITY, OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY, OF QUIET ENJOYMENT, AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. APPLE AND EACH CONTRIBUTOR DOES NOT WARRANT AGAINST INTERFERENCE WITH YOUR ENJOYMENT OF THE COVERED CODE, THAT THE FUNCTIONS CONTAINED IN THE COVERED CODE WILL MEET YOUR REQUIREMENTS, THAT THE OPERATION OF THE COVERED CODE WILL BE UNINTERRUPTED OR ERROR-FREE, OR THAT DEFECTS IN THE COVERED CODE WILL BE CORRECTED. NO ORAL OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE, AN APPLE AUTHORIZED REPRESENTATIVE OR ANY CONTRIBUTOR SHALL CREATE A WARRANTY. You acknowledge that the Covered Code is not intended for use in the operation of nuclear facilities, aircraft navigation, communication systems, or air traffic control machines in which case the failure of the Covered Code could lead to death, personal injury, or severe physical or environmental damage.++9. LIMITATION OF LIABILITY. TO THE EXTENT NOT PROHIBITED BY LAW, IN NO EVENT SHALL APPLE OR ANY CONTRIBUTOR BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES ARISING OUT OF OR RELATING TO THIS LICENSE OR YOUR USE OR INABILITY TO USE THE COVERED CODE, OR ANY PORTION THEREOF, WHETHER UNDER A THEORY OF CONTRACT, WARRANTY, TORT (INCLUDING NEGLIGENCE), PRODUCTS LIABILITY OR OTHERWISE, EVEN IF APPLE OR SUCH CONTRIBUTOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES AND NOTWITHSTANDING THE FAILURE OF ESSENTIAL PURPOSE OF ANY REMEDY. SOME JURISDICTIONS DO NOT ALLOW THE LIMITATION OF LIABILITY OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS LIMITATION MAY NOT APPLY TO YOU. In no event shall Apple's total liability to You for all damages (other than as may be required by applicable law) under this License exceed the amount of fifty dollars ($50.00).++10. Trademarks. This License does not grant any rights to use the trademarks or trade names "Apple", "Mac", "Mac OS", "QuickTime", "QuickTime Streaming Server" or any other trademarks, service marks, logos or trade names belonging to Apple (collectively "Apple Marks") or to any trademark, service mark, logo or trade name belonging to any Contributor. You agree not to use any Apple Marks in or as part of the name of products derived from the Original Code or to endorse or promote products derived from the Original Code other than as expressly permitted by and in strict compliance at all times with Apple's third party trademark usage guidelines which are posted at http://www.apple.com/legal/guidelinesfor3rdparties.html.++11. Ownership. Subject to the licenses granted under this License, each Contributor retains all rights, title and interest in and to any Modifications made by such Contributor. Apple retains all rights, title and interest in and to the Original Code and any Modifications made by or on behalf of Apple ("Apple Modifications"), and such Apple Modifications will not be automatically subject to this License. Apple may, at its sole discretion, choose to license such Apple Modifications under this License, or on different terms from those contained in this License or may choose not to license them at all.++12. Termination.++ 12.1 Termination. This License and the rights granted hereunder will terminate:++ (a) automatically without notice from Apple if You fail to comply with any term(s) of this License and fail to cure such breach within 30 days of becoming aware of such breach;++ (b) immediately in the event of the circumstances described in Section 13.5(b); or++ (c) automatically without notice from Apple if You, at any time during the term of this License, commence an action for patent infringement against Apple; provided that Apple did not first commence an action for patent infringement against You in that instance.++ 12.2 Effect of Termination. Upon termination, You agree to immediately stop any further use, reproduction, modification, sublicensing and distribution of the Covered Code. All sublicenses to the Covered Code which have been properly granted prior to termination shall survive any termination of this License. Provisions which, by their nature, should remain in effect beyond the termination of this License shall survive, including but not limited to Sections 3, 5, 8, 9, 10, 11, 12.2 and 13. No party will be liable to any other for compensation, indemnity or damages of any sort solely as a result of terminating this License in accordance with its terms, and termination of this License will be without prejudice to any other right or remedy of any party.++13. Miscellaneous.++ 13.1 Government End Users. The Covered Code is a "commercial item" as defined in FAR 2.101. Government software and technical data rights in the Covered Code include only those rights customarily provided to the public as defined in this License. This customary commercial license in technical data and software is provided in accordance with FAR 12.211 (Technical Data) and 12.212 (Computer Software) and, for Department of Defense purchases, DFAR 252.227-7015 (Technical Data -- Commercial Items) and 227.7202-3 (Rights in Commercial Computer Software or Computer Software Documentation). Accordingly, all U.S. Government End Users acquire Covered Code with only those rights set forth herein.++ 13.2 Relationship of Parties. This License will not be construed as creating an agency, partnership, joint venture or any other form of legal association between or among You, Apple or any Contributor, and You will not represent to the contrary, whether expressly, by implication, appearance or otherwise.++ 13.3 Independent Development. Nothing in this License will impair Apple's right to acquire, license, develop, have others develop for it, market and/or distribute technology or products that perform the same or similar functions as, or otherwise compete with, Modifications, Larger Works, technology or products that You may develop, produce, market or distribute.++ 13.4 Waiver; Construction. Failure by Apple or any Contributor to enforce any provision of this License will not be deemed a waiver of future enforcement of that or any other provision. Any law or regulation which provides that the language of a contract shall be construed against the drafter will not apply to this License.++ 13.5 Severability. (a) If for any reason a court of competent jurisdiction finds any provision of this License, or portion thereof, to be unenforceable, that provision of the License will be enforced to the maximum extent permissible so as to effect the economic benefits and intent of the parties, and the remainder of this License will continue in full force and effect. (b) Notwithstanding the foregoing, if applicable law prohibits or restricts You from fully and/or specifically complying with Sections 2 and/or 3 or prevents the enforceability of either of those Sections, this License will immediately terminate and You must immediately discontinue any use of the Covered Code and destroy all copies of it that are in your possession or control.++ 13.6 Dispute Resolution. Any litigation or other dispute resolution between You and Apple relating to this License shall take place in the Northern District of California, and You and Apple hereby consent to the personal jurisdiction of, and venue in, the state and federal courts within that District with respect to this License. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded.++ 13.7 Entire Agreement; Governing Law. This License constitutes the entire agreement between the parties with respect to the subject matter hereof. This License shall be governed by the laws of the United States and the State of California, except that body of California law concerning conflicts of law.++ Where You are located in the province of Quebec, Canada, the following clause applies: The parties hereby confirm that they have requested that this License and all related documents be drafted in English. Les parties ont exigé que le présent contrat et tous les documents connexes soient rédigés en anglais.++EXHIBIT A.++"Portions Copyright (c) 1999-2007 Apple Inc. All Rights Reserved.++This file contains Original Code and/or Modifications of Original Code as defined in and that are subject to the Apple Public Source License Version 2.0 (the 'License'). You may not use this file except in compliance with the License. Please obtain a copy of the License at http://www.opensource.apple.com/apsl/ and read it before using this file.++The Original Code and all software distributed under the License are distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the specific language governing rights and limitations under the License."diff --git a/LICENSES/BSD-2-Clause-Patent.txt b/LICENSES/BSD-2-Clause-Patent.txtnew file mode 100644index 0000000..31de6e4--- /dev/null+++ b/LICENSES/BSD-2-Clause-Patent.txt@@ -0,0 +1,19 @@+Copyright (c) <YEAR> <COPYRIGHT HOLDERS>++Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:++1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.++2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.++Subject to the terms and conditions of this license, each copyright holder and contributor hereby grants to those receiving rights under this license a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except for failure to satisfy the conditions of this license) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer this software, where such license applies only to those patent claims, already acquired or hereafter acquired, licensable by such copyright holder or contributor that are necessarily infringed by:++(a) their Contribution(s) (the licensed copyrights of copyright holders and non-copyrightable additions of contributors, in source or binary form) alone; or++(b) combination of their Contribution(s) with the work of authorship to which such Contribution(s) was added by such copyright holder or contributor, if, at the time the Contribution is added, such addition causes such combination to be necessarily infringed. The patent license shall not apply to any other combinations which include the Contribution.++Except as expressly stated above, no rights or licenses from any copyright holder or contributor is granted under this license, whether expressly, by implication, estoppel or otherwise.++DISCLAIMER++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.diff --git a/LICENSES/GPL-2.0-only.txt b/LICENSES/GPL-2.0-only.txtnew file mode 100644index 0000000..17cb286--- /dev/null+++ b/LICENSES/GPL-2.0-only.txt@@ -0,0 +1,117 @@+GNU GENERAL PUBLIC LICENSE+Version 2, June 1991++Copyright (C) 1989, 1991 Free Software Foundation, Inc.+51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA++Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.++Preamble++The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too.++When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.++To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.++For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.++We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.++Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.++Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.++The precise terms and conditions for copying, distribution and modification follow.++TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION++0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".++Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.++1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.++You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.++2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:++ a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.++ b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.++ c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)++These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.++Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.++In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.++3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:++ a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,++ b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,++ c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)++The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.++If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.++4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.++5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.++6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.++7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.++If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.++It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.++This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.++8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.++9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.++Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.++10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.++NO WARRANTY++11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.++12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.++END OF TERMS AND CONDITIONS++How to Apply These Terms to Your New Programs++If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.++To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.++ one line to give the program's name and an idea of what it does. Copyright (C) yyyy name of author++ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.++ This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.++ You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Also add information on how to contact you by electronic and paper mail.++If the program is interactive, make it output a short notice like this when it starts in an interactive mode:++ Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.++The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program.++You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names:++ Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker.++signature of Ty Coon, 1 April 1989 Ty Coon, President of Vicediff --git a/LICENSES/GPL-2.0-or-later.txt b/LICENSES/GPL-2.0-or-later.txtnew file mode 100644index 0000000..17cb286--- /dev/null+++ b/LICENSES/GPL-2.0-or-later.txt@@ -0,0 +1,117 @@+GNU GENERAL PUBLIC LICENSE+Version 2, June 1991++Copyright (C) 1989, 1991 Free Software Foundation, Inc.+51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA++Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.++Preamble++The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too.++When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.++To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.++For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.++We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.++Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.++Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.++The precise terms and conditions for copying, distribution and modification follow.++TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION++0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".++Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.++1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.++You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.++2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:++ a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.++ b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.++ c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)++These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.++Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.++In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.++3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:++ a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,++ b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,++ c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)++The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.++If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.++4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.++5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.++6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.++7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.++If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.++It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.++This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.++8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.++9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.++Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.++10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.++NO WARRANTY++11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.++12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.++END OF TERMS AND CONDITIONS++How to Apply These Terms to Your New Programs++If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.++To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.++ one line to give the program's name and an idea of what it does. Copyright (C) yyyy name of author++ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.++ This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.++ You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Also add information on how to contact you by electronic and paper mail.++If the program is interactive, make it output a short notice like this when it starts in an interactive mode:++ Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.++The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program.++You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names:++ Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker.++signature of Ty Coon, 1 April 1989 Ty Coon, President of Vicediff --git a/LICENSES/MIT.txt b/LICENSES/MIT.txtnew file mode 100644index 0000000..d817195--- /dev/null+++ b/LICENSES/MIT.txt@@ -0,0 +1,18 @@+MIT License++Copyright (c) <year> <copyright holders>++Permission is hereby granted, free of charge, to any person obtaining a copy of this software and+associated documentation files (the "Software"), to deal in the Software without restriction, including+without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the+following conditions:++The above copyright notice and this permission notice shall be included in all copies or substantial+portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT+LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO+EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE+USE OR OTHER DEALINGS IN THE SOFTWARE.diff --git a/README.md b/README.mdindex a6432c2..5dcdf6b 100644--- a/README.md+++ b/README.md@@ -1,58 +1,110 @@# xnulinux-XNU, built from source, running as a loadable kernel module inside an arm64 Linux kernel, to give Linux a macOS personality.+Run macOS userspace on Linux by loading the macOS kernel into it.-## Layout and licenses+xnulinux builds XNU, the open-source kernel of macOS, from Apple's published sources and runs it as a loadable kernel+module (`xnu.ko`) inside an unmodified arm64 Linux kernel. The hosted XNU drives the CPU and MMU directly, so macOS+processes run natively next to Linux processes on the same CPUs, with no hypervisor between them. Linux lends XNU its+memory, timers, files, network and GPU through a small interface module (`fki.ko`).-The two sides are kept apart by license and only meet at the FKI (foreign kernel interface, `include/linux/fki.h`):+With a stock Ubuntu kernel, `insmod xnu.ko` boots a macOS 27 system disk made by Apple's own installer to the+desktop: loginwindow, WindowServer, Dock, Finder, Safari and Chrome.++## How it works++```+ macOS processes (launchd, WindowServer, Safari...) Linux processes (systemd, sshd, xnudrmd...)+ ────────────────────────────────────────────────── ────────────────────────────────────────────+ XNU (source-built, LINUX64 machine layer, kexts) │+ ↕ linux64 host calls (xnu-patches/include/linux64_abi.h)+ xnu.ko (APSL side: loads and runs the kernel collection)+ ↕ FKI, the foreign kernel interface (fki_*)+ fki.ko (GPL side: CPUs, memory, faults, IPIs, files, network, host calls)+ Linux kernel (stock distro kernel, 4K pages, PAC)+```++- **CPUs**: each hosted CPU is a Linux kernel thread pinned to a Linux CPU. XNU runs on it until it calls the host+ (idle, I/O, a timer); Linux keeps its own exception vectors, and `fki.ko` forwards the faults and user exceptions of+ XNU code to XNU's handlers.+- **Memory**: XNU gets one physically contiguous block from Linux (CMA) and manages it with its own pmap; XNU and Linux+ share the user half of the address space layout (4K pages).+- **Devices**: kexts in `kexts/` give macOS a disk (a file on the Linux side), a display (a framebuffer Linux reads), a+ keyboard and pointer, an Ethernet link (a Linux network interface), a keystore and a GPU bridge.+- **GPU**: Metal in the hosted macOS runs on `gpu/xnu-cpu-metal` (metal2vulkan over Vulkan). Vulkan reaches the Linux+ host's GPU through the DRM bridge (`kexts/XnuDrm` → host call → `gpu/xnu-drm/xnudrmd` → the Linux render node), using+ Mesa's Venus driver; without a GPU it falls back to Mesa lavapipe on the CPU.++## Status++Working, on an Apple Silicon Mac running an arm64 Linux VM (krunkit) with 1 to 6 hosted CPUs:++- macOS 27.2.1 boots to the desktop with auto-login in 31–48 s (an Apple Virtualization macOS VM on the same Mac: 49 s).+- Apps open and quit, Spotlight and the file system work; a 30-minute stress run (40 rounds of Safari, Notes,+ Calculator, TextEdit, System Settings, Spotlight and a disk walk) finishes with no panic and no crash report.+- Runs as a systemd service: started at boot, stopped cleanly with the VM, restarted after a hosted-kernel panic, each+ run's log kept in `/var/log/xnulinux/`.+- The GPU bridge gives hosted apps the host GPU (`Virtio-GPU Venus (Apple M5 Max)`); it is off by default+ (`GPU=off`) while an occasional hang of the whole VM with it on is investigated.++What is still a stopgap is listed in [`docs/production.md`](docs/production.md). Notably: the OS cryptex is merged into+the system volume, AMFI is patched and SIP relaxed, and memory access is slower than a native VM (4K pages vs 16K).++## Requirements++- An arm64 Linux host with PAC (Apple Silicon M1 or later in a VM: krunkit for GPU access, or tart), 4K pages, ~24 GB of+ RAM (8 GB of it reserved for the hosted kernel).+- A Mac with Xcode to make the system disk and build the GPU parts.+- A macOS 27 installation (an Apple Virtualization VM disk) of your own. **No Apple binaries are in this repository or+ distributed by it**: the kexts Apple ships, the macOS system disk and its trust cache come from your own installation.++## Building and running++1. `scripts/vm-xnu-build.sh` (in the Linux VM, 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.+3. `scripts/mk-macvm-disk.sh` (on the Mac): turns a macOS VM disk made by Apple's installer into the hosted system's disk+ and copies it into the Linux VM.+4. `scripts/xnulinux-boot.sh` (in the Linux VM): builds `fki.ko` and `xnu.ko` against the running kernel, brings up the+ network (and the GPU bridge when there is a render node) and boots the hosted system. Its console is+ `scripts/xnu-console.sh`, its screen `tools/hosted/fb2png.py`, input `tools/hosted/xnu-input.py`.+5. `scripts/install-service.sh` (in the Linux VM): runs it as `xnulinux.service`, configured in `/etc/xnulinux.conf`+ (CPUs, memory, disk, GPU). On the Mac, `scripts/install-krun-agent.sh` keeps the VM itself running.+6. GPU (optional, on the Mac): `gpu/venus/build-darwin.sh` builds the hosted Vulkan driver, `gpu/xnu-cpu-metal/` the+ Metal plugin (see its README).++## Repository layout and licenses++The Linux side and the XNU side are kept apart by license and meet only at FKI. Every source file carries an+`SPDX-License-Identifier`; the license texts are in [`LICENSES/`](LICENSES).| Path | License | What ||---|---|---|-| `linux/` | GPL-2.0 | In-tree FKI patch for Linux (`drivers/fki`, `include/linux/fki.h`) |-| `fki-ko/` | GPL-2.0 | The same FKI v0 as an out-of-tree module, for stock distro kernels |-| `xnu-ko/` | APSL-2.0 side | `xnu.ko`: loads the XNU kernel collection and calls into it; uses only FKI |-| `xnu-patches/` | APSL-2.0 | The LINUX64 machine layer and hosted-kernel changes, applied to XNU's sources; `include/linux64_abi.h` is the interface xnu.ko and XNU share |-| `kexts/` | BSD-2-Clause | Our kexts in the kernel collection: disk, display, input, Ethernet, keystore stand-ins, Metal accelerator, DRM bridge |-| `gpu/` | per directory | Metal plugin (`xnu-cpu-metal`), the DRM bridge's user-space ends (`xnu-drm`), Mesa Venus patches (`venus`) |-| `scripts/`, `tools/` | | Build, disk, boot and test tools |--`xnu.ko` must not include Linux headers beyond the module ABI, call Linux functions other than `fki_*`, or carry Linux code.-Upstream code (Mesa, metal2vulkan, the Vulkan loader, Apple's open source) is fetched at pinned revisions and patched at+| `fki-ko/`, `linux/` | GPL-2.0-only | FKI: the out-of-tree module for stock kernels, and the same as an in-tree driver |+| `xnu-ko/` | APSL-2.0 | `xnu.ko`: loads XNU's kernel collection and runs it; calls Linux only through `fki_*` |+| `xnu-patches/` | APSL-2.0 | The LINUX64 machine layer and the other changes to XNU's sources, and their shared headers |+| `kexts/` | APSL-2.0 | The hosted system's kexts (CPU, disk, keystore, Metal accelerator, DRM bridge) |+| `kexts/XnuDisplay/`, `kexts/XnuEthernet/`, `kexts/XnuInput/` | BSD-2-Clause-Patent | Derived from [macOS-DroidVM](https://github.com/Droid-VM/macOS-DroidVM)'s kexts |+| `gpu/xnu-cpu-metal/` | GPL-2.0-or-later | The Metal plugin over metal2vulkan (GPL-2.0-or-later); `XnuCpuMetalShim.h` is BSD-2-Clause-Patent (from [AdrenoMetal](https://github.com/UniXNU/AdrenoMetal)) |+| `gpu/xnu-drm/` | GPL-2.0-only, MIT | `xnudrmd` (the Linux end of the DRM bridge) is GPL; the protocol header and `darwin/` (built into Mesa) are MIT |+| `gpu/venus/` | GPL-2.0-only; patches MIT | Build scripts and tests; the patches to Mesa and virglrenderer are under their upstream license (MIT) |+| `gpu/xnu-cpu-metal/patches/` | upstream's | Patches to Mesa (MIT) and metal2vulkan (GPL-2.0-or-later) |+| `scripts/`, `tools/`, `tests/`, `docs/` | GPL-2.0-only | Build, disk, boot, debugging and test tools; documentation |++`xnu.ko` is on the XNU side of the line: it runs XNU's code in its own address space, so it is APSL-2.0 like XNU, and+Linux reports it as a non-GPL module (`MODULE_LICENSE("Proprietary")`, which taints the kernel as ZFS does). It must not+include Linux headers beyond the module ABI, call Linux functions other than `fki_*`, or carry Linux code. Upstream code+(XNU, macOS-DroidVM's toolchain, Mesa, metal2vulkan, the Vulkan loader, LLVM) is fetched at pinned revisions and patched atbuild time; it is never committed.-## Status (2026-11-22)--- A stock Ubuntu kernel (`7.0.0-43-generic`, 4K pages, PAC) loads `xnu.ko`, which boots a source-built XNU- (`xnu-12377.121.6` with the LINUX64 machine layer) inside it, with a kernel collection of our kernel and Apple's macOS- 27.2 kexts. XNU uses the host CPU and MMU directly; Linux gives it memory (CMA), timers, files, a network link and a- message channel through FKI.-- The system disk is one Apple's own installer made (APFS, sealed system volume, Preboot, Data; `scripts/mk-macvm-disk.sh`)- with a simulated SEP (AppleVPKeyStore over `kexts/XnuEAN`). macOS 27.2.1 boots to the desktop with auto-login: Dock,- Finder, Safari and Chrome load web pages.-- Rendering: `gpu/xnu-cpu-metal` is a Metal device (metal2vulkan) over Mesa lavapipe on the CPU. The DRM bridge- (`fki-ko/fki_hostcall.c`, `kexts/XnuDrm`, `gpu/xnu-drm`) gives hosted processes the Linux host's GPU through Mesa Venus:- on an Apple Silicon host the Linux VM runs under krunkit (`scripts/krun-vm.sh`) and Vulkan in the hosted macOS runs on the- host's GPU (`Virtio-GPU Venus (Apple M5 Max)`): the Metal plugin takes it when the bridge is there, and WindowServer- composites the desktop on the host GPU.-- From PoC to production: [`docs/production.md`](docs/production.md).--## Running--The host is an arm64 Linux VM with PAC on an Apple Silicon Mac (`scripts/krun-vm.sh`; tart works without the GPU), 24 GB:-`scripts/vm-install-fki-service.sh` gives Linux 15 GB (`mem=15G`) and the 8 GB above to the hosted kernel (fki's carve-out).--1. `scripts/vm-xnu-build.sh` (once) sets up the macOS-DroidVM Linux toolchain and builds XNU natively on arm64.-2. `scripts/vm-xnu-rebuild.sh` applies `xnu-patches/`, rebuilds the kernel, builds `kexts/` and links the kernel collection.-3. `scripts/mk-macvm-disk.sh` (on the Mac) makes the system disk with Apple's installer and puts it in the VM.-4. `scripts/xnulinux-boot.sh` (in the VM) builds `fki.ko` and `xnu.ko`, brings up the network and, with a render node, the- GPU bridge (`xnudrmd`), and boots the hosted system from the disk and its `/var/tmp/mac.conf`; its console is- `scripts/xnu-console.sh`, its screen `tools/hosted/fb2png.py`.-5. `gpu/venus/build-darwin.sh` (on the Mac) builds the hosted Vulkan driver that the Metal plugin uses on a real GPU.-6. `scripts/install-service.sh` (in the VM, once) runs it as a service: `xnulinux.service` starts it at boot, stops it- cleanly (the disk synced) when the VM shuts down and starts it again after a panic; settings in `/etc/xnulinux.conf`- (CPUs, memory, disk, GPU, xnu.ko parameters), each run's kernel log in `/var/log/xnulinux/`.- On the Mac, `scripts/install-krun-agent.sh` keeps the VM itself running (launchd: started again after the guest- reboots or powers off, and at login); `scripts/install-krun-agent.sh remove` shuts the guest down and removes it.--Debugging: the VM console is captured on the host (`scripts/serial-pty.py`), a monitor thread on another CPU prints XNU's-counters every 2 s, and XNU dumps its threads with their saved frames after 20000 idle rounds.+## Acknowledgements++- [macOS-DroidVM](https://github.com/Droid-VM/macOS-DroidVM) and [UniXNU](https://github.com/UniXNU): the 4K-page XNU+ base, the Linux-hosted XNU toolchain, and the display, Ethernet and input kexts these are derived from.+- [metal2vulkan](https://github.com/steelbrain/metal2vulkan), [Mesa](https://mesa3d.org) (Venus, lavapipe),+ [virglrenderer](https://gitlab.freedesktop.org/virgl/virglrenderer) and [krunkit](https://github.com/containers/krunkit).+- Apple's open-source XNU.++macOS, Metal and XNU are trademarks of Apple Inc. This project is not affiliated with or endorsed by Apple.++Copyright © 2026 Heyang Zhou and contributors.diff --git a/docs/production.md b/docs/production.mdindex 9461791..c8f89f0 100644--- a/docs/production.md+++ b/docs/production.md@@ -33,7 +33,7 @@ What the PoC did to get each step running, and what replaces it. Ordered by what| Now | Replace with ||---|---|-| ~30 scripts; the boot runs from `xnulinux-boot.sh` (builds, checks, retries, GPU bridge; the bisecting `vm-m2-kbisect.sh` is gone); several have session paths (`/Users/admin/...`), tty names, fixed `sleep`s | One driver (`xnulinux` CLI): `build`, `disk`, `boot`, `console`, `screenshot`, `test`; configuration in one file |+| ~30 scripts; the boot runs from `xnulinux-boot.sh` (builds, checks, retries, GPU bridge; the bisecting `vm-m2-kbisect.sh` is gone); several have fixed `sleep`s and host-specific defaults | One driver (`xnulinux` CLI): `build`, `disk`, `boot`, `console`, `screenshot`, `test`; configuration in one file || HFS+ route scripts (`mk-fulldisk.sh`, `vm-sysdisk-*`, `vm-mk-sysdisk.sh`, `vm-m2-*`, `run-poc.sh`) | Removed (done: APFS route only) || `tools/hosted/tests/t*.sh`, `af*.sh`: one-off probes (removed) | A test suite with expected results: boot to desktop, Safari/Chrome page load (screenshot compare), `xcodebuild` of a pinned project, Metal unit tests || No CI | CI: fki.ko/xnu.ko build against a pinned kernel, XNU + collection build (x86_64 Linux works with the DroidVM toolchain), GPU plugin host tests on macOS |diff --git a/fki-ko/Makefile b/fki-ko/Makefileindex f47a81b..99fb500 100644--- a/fki-ko/Makefile+++ b/fki-ko/Makefile@@ -1,2 +1,3 @@+# SPDX-License-Identifier: GPL-2.0-onlyobj-m += fki.ofki-y := fki_mod.o fki_hostcall.odiff --git a/fki-ko/fki_hostcall.c b/fki-ko/fki_hostcall.cindex 0f1ff43..6266a3b 100644--- a/fki-ko/fki_hostcall.c+++ b/fki-ko/fki_hostcall.c@@ -1,4 +1,4 @@-// SPDX-License-Identifier: GPL-2.0+// SPDX-License-Identifier: GPL-2.0-only/** Host calls: a message channel from the foreign kernel to a Linux user process (a host service such as the DRM bridge,* gpu/xnu-drm/xnudrmd). The foreign kernel calls fki_hostcall() with a request; the service reads it fromdiff --git a/fki-ko/fki_internal.h b/fki-ko/fki_internal.hindex 4a4b196..6410aba 100644--- a/fki-ko/fki_internal.h+++ b/fki-ko/fki_internal.h@@ -1,4 +1,4 @@-/* SPDX-License-Identifier: GPL-2.0 */+/* SPDX-License-Identifier: GPL-2.0-only *//* Shared between fki's own files (not part of the interface in fki.h). */#ifndef FKI_INTERNAL_H#define FKI_INTERNAL_Hdiff --git a/gpu/venus/build-darwin.sh b/gpu/venus/build-darwin.shindex f138016..ae36185 100755--- a/gpu/venus/build-darwin.sh+++ b/gpu/venus/build-darwin.sh@@ -1,4 +1,5 @@#!/bin/bash+# SPDX-License-Identifier: GPL-2.0-only# On a Mac: build Mesa's Venus Vulkan driver for the hosted macOS, its renderer talking to the Linux host's GPU over the# DRM bridge (gpu/xnu-drm: libxnudrm in the driver, kexts/XnuDrm in the hosted kernel, xnudrmd on Linux). Patches as for# the Linux guest (patches/), plus libxnudrm copied into the tree. Also builds test/compute.c against it.diff --git a/gpu/venus/build-linux.sh b/gpu/venus/build-linux.shindex de9cc47..d555a70 100755--- a/gpu/venus/build-linux.sh+++ b/gpu/venus/build-linux.sh@@ -1,4 +1,5 @@#!/bin/bash+# SPDX-License-Identifier: GPL-2.0-only# In the Linux guest: build Mesa's Venus Vulkan driver with our patches (patches/), then check it on the GPU behind# virtio-gpu: list the device and run test/compute.c (a compute dispatch over 16 MB of host-visible memory, read back and# compared). Output: $OUT/lib/libvulkan_virtio.so and $OUT/share/vulkan/icd.d/virtio_icd.*.json.diff --git a/gpu/venus/test/compute.c b/gpu/venus/test/compute.cindex 91102de..5e7c944 100644--- a/gpu/venus/test/compute.c+++ b/gpu/venus/test/compute.c@@ -1,3 +1,4 @@+// SPDX-License-Identifier: GPL-2.0-only#define VK_NO_PROTOTYPES#include <vulkan/vulkan.h>#include <dlfcn.h>diff --git a/gpu/venus/test/compute.comp b/gpu/venus/test/compute.compindex 1d6d744..a52821d 100644--- a/gpu/venus/test/compute.comp+++ b/gpu/venus/test/compute.comp@@ -1,3 +1,4 @@+// SPDX-License-Identifier: GPL-2.0-only#version 450layout(local_size_x=64) in;layout(std430, binding=0) buffer B { uint d[]; };diff --git a/gpu/xnu-cpu-metal/.gitignore b/gpu/xnu-cpu-metal/.gitignoreindex d35d09c..4457bf6 100644--- a/gpu/xnu-cpu-metal/.gitignore+++ b/gpu/xnu-cpu-metal/.gitignore@@ -1,3 +1,4 @@+# SPDX-License-Identifier: GPL-2.0-or-latersrc/metal2vulkan/src/Vulkan-Loader/src/llvm-project/diff --git a/gpu/xnu-cpu-metal/README.md b/gpu/xnu-cpu-metal/README.mdindex 5ccea1c..3068644 100644--- a/gpu/xnu-cpu-metal/README.md+++ b/gpu/xnu-cpu-metal/README.md@@ -26,4 +26,3 @@ Install: `scripts/mk-macvm-disk.sh` (repo root) puts the bundle on the system di- `/Library/GPUBundles` is trusted only with `CSR_ALLOW_UNRESTRICTED_FS` (boot-arg `lp-sip0=2` in the hosted kernel).- The device class must conform to `MTLDeviceSPI` (`MTLAddDevice` asserts it).- `targetDeviceArchitecture` must be an `MTLTargetDeviceArchitecture` (the AIR type here), or binary archives assert.-`REPORT.md` is the development log (host-side reproduction and pixel comparisons against an M5 Max GPU).diff --git a/gpu/xnu-cpu-metal/REPORT.md b/gpu/xnu-cpu-metal/REPORT.mddeleted file mode 100644index fb5b9e0..0000000--- a/gpu/xnu-cpu-metal/REPORT.md+++ /dev/null@@ -1,672 +0,0 @@-# xnulinux 纯 CPU Metal 设备用户态构建报告--构建机:`tokyo-mac-studio-0`(macOS 27.0.1 / Build 26A434,Apple M5 Max 18 核 64 GB,Xcode 27.0,Rust 1.100.0)-工作目录:`/Users/admin/.stillfail/sessions/chat/c-73ef26e7b6/workspace`-------## 1. 产物路径清单--| 组件 | 路径 | 大小 | 架构 | 外部运行时依赖 |-|---|---|---|---|---|-| Mesa lavapipe ICD | `dist/lavapipe/lib/libvulkan_lvp.dylib` | 125 MB | `arm64` | 仅 Apple 系统库(`libSystem.B`、`libz.1`、`libc++.1`);LLVM 22.1.8 与 `libzstd.a` 已静态链入 |-| Khronos Vulkan Loader | `dist/lavapipe/lib/libvulkan.1.dylib` | 663 KB | `arm64` | 仅 Apple 系统库(`libSystem.B`、`CoreFoundation`) |-| Vulkan ICD 描述 | `dist/lavapipe/share/vulkan/icd.d/lvp_icd.aarch64.json` | 247 B | — | 指向 `libvulkan_lvp.dylib` |-| metal2vulkan C ABI 动态库 | `dist/m2v/lib/libxnu_m2v.dylib` | 32 MB | `arm64` | 仅 Apple 系统库(`libiconv.2`、`libSystem.B`);基于上游 `steelbrain/metal2vulkan` 0.2.0 零补丁构建 |-| metal2vulkan C 头文件 | `dist/m2v/include/xnu_m2v.h` | 12 KB | — | — |-| **Metal 插件 Bundle(自包含可重定位)** | **`dist/XnuCpuMetal.bundle`** | ~158 MB | `arm64` | 仅 Apple 系统框架(`Foundation`、`Metal`、`IOKit`、`IOSurface`、`IOGPU`、`CoreFoundation`、`libobjc`、`libc++`、`libSystem`)及内置 `@loader_path/../Frameworks/libxnu_m2v.dylib` |--`dist/XnuCpuMetal.bundle` 内部布局(可直接拷贝到托管 macOS 的 `/Library/GPUBundles/XnuCpuMetal.bundle`,无硬编码宿主机路径):-```-dist/XnuCpuMetal.bundle/- Contents/- Info.plist (NSPrincipalClass = XnuCpuMetalDevice)- MacOS/XnuCpuMetal (MH_BUNDLE, arm64)- Frameworks/- libxnu_m2v.dylib- libvulkan.1.dylib- libvulkan_lvp.dylib- Resources/- lvp_icd.aarch64.json (library_path = "../Frameworks/libvulkan_lvp.dylib")-```-------## 2. 可复现构建与验证脚本--所有脚本均在工作目录 `scripts/` 下,按顺序执行即可复现全部 3 步产物与验证:--1. **第 1 步(Mesa lavapipe)**:- - 构建:`bash scripts/build-lavapipe.sh`- - 验证:`bash scripts/test-lavapipe.sh`- - 实测结果:`Vulkan device: llvmpipe (LLVM 22.1.8, 128 bits) (type=4, api=1.4.363, driver=0x6803001)`,`Compute vecadd N=1024: bad=0`-2. **第 2 步(metal2vulkan + AIR→SPIR-V)**:- - 构建:`bash scripts/build-m2v.sh`- - 验证:`bash scripts/test-m2v.sh`(使用 `xcrun -sdk macosx metal` + `metallib` 编译 `test/vecadd.metal`)- - 实测结果:`m2v device: llvmpipe (LLVM 22.1.8, 128 bits) (maxBufferLength=2147483648)`,`pipeline: maxThreads=1024, simdWidth=32`,`Metal->metal2vulkan->lavapipe vecadd N=1024: status=4, bad=0`-3. **第 3 步(`XnuCpuMetal.bundle`)**:- - 构建:`bash scripts/build-bundle.sh`- - 验证:`bash scripts/test-bundle.sh`(通过 `NSBundle` 加载 `XnuCpuMetal.bundle`,检查 `principalClass == XnuCpuMetalDevice` 且为 `IOGPUMetalDevice` 子类,调用 `initWithAcceleratorPort:0` 并走标准 ObjC `MTLDevice` API 执行 `vecadd.metallib`)- - 实测结果:`Bundle loaded: principalClass=XnuCpuMetalDevice, isSubclassOf(IOGPUMetalDevice)=YES`,`Bundle ObjC MTLDevice vecadd N=1024: status=4, completedHandler=1, bad=0`(进程干净退出,退出码 0)-------## 3. 插件 Metal API 接入与空实现清单--### 已接入(经 `libxnu_m2v.dylib` 到达 `metal2vulkan-runtime` → `lavapipe`)-- **插件注册与 IOGPU 兼容层**(`XnuCpuMetalDevice` + `XnuCpuMetalShim.h`):- - `XnuCpuMetalDevice : IOGPUMetalDevice`、`initWithAcceleratorPort:`(保留自身避免 `-[IOGPUMetalDevice dealloc]` 破坏未初始化状态,返回动态创建的 `_MTLDevice` 子类 `XcmBackendDevice`)- - IOGPU 必需 selector:`_setAcceleratorService:`、`acceleratorPort`、`_setDeviceWrapper:`、`_deviceWrapper`、`isBuiltIn`、`recommendedMaxWorkingSetSize`、`sharedMemorySize`、`gpuCoreCount`、`cmdBufArgsSize`、`featureProfile`、queue GPU priorities、`userDictionary`、`bitCodeHash` 及全部 `MTL*` 协议声明-- **MTLDevice**:`name`、`registryID`、`isLowPower`、`isHeadless`、`isRemovable`、`hasUnifiedMemory`、`maxBufferLength`、`maxThreadsPerThreadgroup`、`supportsFamily:`、`newCommandQueue`、`newCommandQueueWithMaxCommandBufferCount:`、`newBufferWithLength:options:`、`newBufferWithBytes:length:options:`、`newBufferWithBytesNoCopy:length:options:deallocator:`(失败自动回退拷贝)、`newTextureWithDescriptor:`、`newLibraryWithData:error:`、`newLibraryWithURL:error:`、`newLibraryWithFile:error:`、`newComputePipelineStateWithFunction:error:`(含 options/descriptor/completionHandler 重载)、`newRenderPipelineStateWithDescriptor:error:`(含 options 重载)、`newSamplerStateWithDescriptor:`、`newDepthStencilStateWithDescriptor:`、`newEvent`、`newFence`;并从 `_MTLDevice` 继承 `newDefaultLibrary` / `newLibraryWithSource:options:error:` 等上层框架入口-- **MTLBuffer**:`contents`、`length`、`gpuAddress`、`didModifyRange:`、storage/cache/hazard/options/allocatedSize 属性-- **MTLTexture**:基本元数据属性、`replaceRegion:...`、`getBytes:...`、`newTextureViewWithPixelFormat:...`(含 level/slice 重载)-- **MTLLibrary / MTLFunction**:`functionNames`、`newFunctionWithName:`、`functionType`、`name`-- **MTLComputePipelineState / MTLRenderPipelineState / MTLSamplerState / MTLDepthStencilState / MTLEvent / MTLFence**:创建、销毁与 compute 线程组查询属性-- **MTLCommandQueue / MTLCommandBuffer**:`commandBuffer`、`status`、`error`、`commit`、`waitUntilScheduled`、`waitUntilCompleted`、`addScheduledHandler:`、`addCompletedHandler:`、`computeCommandEncoder`、`renderCommandEncoderWithDescriptor:`、`blitCommandEncoder`、`encodeSignalEvent:value:`、`encodeWaitForEvent:value:`-- **MTLComputeCommandEncoder**:`setComputePipelineState:`、`setBuffer/setBuffers/setBufferOffset`、`setBytes`、`setTexture/setTextures`、`setSamplerState/setSamplerStates`、`setThreadgroupMemoryLength:atIndex:`、`dispatchThreadgroups:`、`dispatchThreads:`、`endEncoding`-- **MTLRenderCommandEncoder**:`setRenderPipelineState:`、`setDepthStencilState:`、`setViewport:`、`setScissorRect:`、`setCullMode:`、`setFrontFacingWinding:`、vertex/fragment buffer/bytes/texture/sampler 绑定、`drawPrimitives:...`、`drawIndexedPrimitives:...`、`endEncoding`-- **MTLBlitCommandEncoder**:buffer↔buffer、buffer↔texture、texture↔buffer、texture↔texture 拷贝、`fillBuffer:range:value:`、`generateMipmapsForTexture:`、`synchronizeResource:`、`endEncoding`--### 尚未实现 / 桩实现(Stub)-- **IOSurface 零拷贝导入**:`newTextureWithDescriptor:iosurface:plane:` 目前仅创建普通后端纹理并保存 `IOSurfaceRef` 引用,未将 IOSurface 内存直接映射/回写到纹理(CoreImage 若经 IOSurface 交付结果需要补齐锁面读写或 no-copy 导入)-- **Function Constants 特化**:`newFunctionWithName:constantValues:error:` 目前忽略 `constantValues`,直接按函数名查找(`metal2vulkan-runtime` 自身支持 `new_function_with_name_constant_values`,后续若 `ictool`/CoreImage 触发可直接补接线)-- **高级 Metal 对象**:`MTLHeap`、`MTLSharedEvent`、`MTLBinaryArchive`、`MTLIndirectCommandBuffer`、`MTLArgumentEncoder`、`MTLCounterSampleBuffer`、`MTLAccelerationStructure`、stitched library / dynamic library、render pipeline `vertexDescriptor`(目前 `Xm2vRenderPipelineDesc` 未传递 `MTLVertexDescriptor`)、`MTLComputePipelineReflection` / `MTLRenderPipelineReflection`(目前返回 `nil`)-- **Purgeable 内存真实回收**:`setPurgeableState:` 仅记录状态,不触发后端释放-- **兜底机制**:任何未覆盖的 `IOGPUMetal*` selector 由 `resolveInstanceMethod:` 拦截,打印一次 `XnuCpuMetal: <prog>: stubbed <class> <sel>` 到 stderr 并返回 0,便于托管系统联调时定位实际缺口-------## 4. `arm64` vs `arm64e` 确认结论--1. **宿主与目标进程架构实测**:- - Xcode 工具链进程(本次首要目标)均为 **`arm64`**(非 `arm64e`):- - `/Applications/Xcode_27.app/Contents/Developer/usr/bin/ictool` → `Mach-O 64-bit executable arm64`- - `/Applications/Xcode_27.app/Contents/Developer/usr/bin/actool` → `Mach-O 64-bit executable arm64`- - `/Applications/Xcode_27.app/Contents/Developer/usr/bin/xcodebuild` → `Mach-O 64-bit executable arm64`- - macOS 系统工具与守护进程为 **`arm64e`**(例如 `/usr/bin/sips`、`WindowServer`、`iconservicesagent`)。- - dyld shared cache 中的 `Metal.framework` 是 `arm64e`,但 **arm64 进程加载 dyld shared cache 中的 `arm64e` 系统框架时,dyld 要求进程内动态加载的 bundle 匹配进程自身架构(即 `arm64`)**——这已在本机 `test_bundle`(arm64 进程链接系统 `Metal.framework`)加载 `arm64` `XnuCpuMetal.bundle` 中实测通过。-2. **`arm64e` 进程的限制(已实测确认)**:- - `arm64e` 进程无法 `dlopen` 仅含 `arm64` 切片的 `XnuCpuMetal.bundle`(dyld 拒绝:`incompatible architecture (have 'arm64', need 'arm64e')`)。- - 若后续需要同时服务 `arm64`(`ictool`/`xcodebuild`)和 `arm64e`(`sips`/系统守护进程),需将整条链编成 **universal fat(`arm64` + `arm64e`)**:- - `XnuCpuMetal`(ObjC++):Xcode 27 `clang++ -arch arm64e` 已实测直接支持。- - `libxnu_m2v.dylib`(Rust):`rustc 1.100.0` 含 tier-3 目标 `arm64e-apple-darwin`(需 nightly `-Zbuild-std`,且需像 `AdrenoMetal/bridge/RustPacBoundary.c` 那样处理 Rust↔C 的 PAC 指针签名边界)。- - `libvulkan_lvp.dylib` + `libvulkan.1.dylib`:Homebrew 预编译的 `llvm@22`、`zstd`、`vulkan-loader` 均为 `arm64`-only,编 `arm64e` 切片需从源码用 `-arch arm64e` 交叉/原生编译 LLVM、Vulkan-Loader 和 Mesa。-3. **建议**:当前阶段为了尽快在托管 XNU 里打通 `ictool`(本身是 `arm64` 进程)和 CoreImage 探针,**先用这份自包含的 `arm64` `XnuCpuMetal.bundle` 接入内核 stub kext 联调**;若联调发现 `ictool` 会经 XPC 调到某个 `arm64e` 守护进程或需要支持 `arm64e` 进程,再补 `arm64e` 切片做成 fat bundle。-------## 5. 已知缺口与联调注意事项--- **CoreImage / `ictool` 常见需求**:CoreImage 常使用 `newLibraryWithSource:options:error:`(由 `_MTLDevice` 走 `MTLCompilerService` 产出 AIR/metallib 后回调 `newLibraryWithData:error:`)、`MTLVertexDescriptor`、Function Constants 以及 `IOSurface` 纹理。若联调日志中出现 `XnuCpuMetal: <prog>: stubbed ...` 或 `newTextureWithDescriptor:iosurface:plane:` 数据为空,优先补齐对应项。-- **lavapipe 精度降级提示**:`metal2vulkan` 在 stderr 会打印 2–4 条 `PrecisionNote` / `DegradeNotice`(llvmpipe 无 `VK_KHR_pipeline_binary`、denormals、NaN encoding、float tininess);按 `metal2vulkan` 规则均为非致命提示。-- **许可证**:`src/mesa`、`src/metal2vulkan` 仅用于本机构建,未提交或推送至任何仓库。-------## 6. 第二轮成果:整链 Universal(`arm64 + arm64e`)与 Render / CoreImage 冒烟测试--### 6.1 Universal (`arm64 + arm64e`) 产物与构建脚本-`dist/XnuCpuMetal.bundle` 现已全部合成为 **`arm64 + arm64e` universal fat**(`lipo -info` 全部确认为 `arm64 arm64e`,无任何 Homebrew 运行时依赖):-- `dist/XnuCpuMetal.bundle/Contents/MacOS/XnuCpuMetal`(323 KB,`arm64 arm64e`)-- `dist/XnuCpuMetal.bundle/Contents/Frameworks/libxnu_m2v.dylib`(71 MB,`arm64 arm64e`)-- `dist/XnuCpuMetal.bundle/Contents/Frameworks/libvulkan.1.dylib`(1.4 MB,`arm64 arm64e`)-- `dist/XnuCpuMetal.bundle/Contents/Frameworks/libvulkan_lvp.dylib`(196 MB,`arm64 arm64e`)--新增可复现构建脚本:-1. `scripts/build-llvm-arm64e.sh`:从 `llvmorg-22.1.8`(sparse 仅 `llvm`/`cmake`/`third-party`)编译 `arm64e` AArch64 静态库与 `llvm-config`(关闭 zstd/libxml2/terminfo/tests)。-2. `scripts/build-vkloader-arm64e.sh`:从 Khronos `Vulkan-Loader` `vulkan-sdk-1.4.363.0` 编译 `arm64e` `libvulkan.1.dylib`。-3. `scripts/build-lavapipe-arm64e.sh`:基于 `arm64e` LLVM 22 编译 `arm64e` Mesa 26.3.1 lavapipe。- - **关键 PAC 修复**(`src/mesa/src/gallium/auxiliary/gallivm/lp_bld_init.c` 与 `lp_bld_init_orc.cpp` 中的 `gallivm_jit_function`):LLVM MCJIT/ORCJIT 返回未签名代码指针,`arm64e` 下 C 侧经 `blraaz` 调用 JIT shader 会触发 `SIGBUS`(多线程下表现为 `VkQueue` 超时 20.2s)。在 `gallivm_jit_function` 返回前用 `__builtin_ptrauth_sign_unauthenticated(__builtin_ptrauth_strip(code, 0), 0, 0)` 签名后,单线程与多线程 `arm64e` lavapipe 均一次通过。-4. `scripts/build-m2v-arm64e.sh` + `scripts/rust-pac-rewrite.py`:用 `nightly-aarch64-apple-darwin`(`rustc 1.102.0-nightly`)+ `-Zbuild-std=std,panic_unwind --target arm64e-apple-darwin` 编译 `libxnu_m2v.a`;实测 nightly 仍输出无 PAC 的 `blr`/`br`,因此按 `AdrenoMetal/bridge/RustPacBoundary.c` 方案:- - 用 `llvm-objcopy --redefine-sym` 将 Rust 目标文件中 7 个接收 C 回调的导入(`_pthread_create`、`__tlv_atexit`、`_atexit`、`___cxa_atexit`、`__dyld_register_func_for_add_image`、`__Unwind_Backtrace`、`_dlsym`)重定向到 `nmb_pac_*` 包装器;- - 链接 `RustPacBoundary.o` 后,由 `scripts/rust-pac-rewrite.py` 将 Rust `__TEXT,__text` 中的 `9528` 条 `blr` 与 `2734` 条 `br` 重写为 `bl`/`b _nmb_pac_call_xN`(跳过 40 个 PAC 边界函数),再 ad-hoc 签名。-5. `scripts/build-bundle-universal.sh`:编译 `arm64` + `arm64e` 两份 `XnuCpuMetal` 并用 `lipo -create` 合成全部 4 个 universal 二进制。--### 6.2 双架构验收实测结果-- **`arm64` 进程**(`bash scripts/test-bundle.sh arm64`):- `Bundle ObjC MTLDevice vecadd N=1024: status=4, completedHandler=1, bad=0 (c[0]=256.00, c[10]=283.50, c[1023]=3069.25)`,退出码 0。-- **`arm64e` 进程**(`bash scripts/test-bundle.sh arm64e`):- `Bundle ObjC MTLDevice vecadd N=1024: status=4, completedHandler=1, bad=0 (c[0]=256.00, c[10]=283.50, c[1023]=3069.25)`,退出码 0。--### 6.3 Render Pass + CoreImage `CIGaussianBlur` 冒烟测试(`bash scripts/test-render-ci.sh arm64|arm64e`)-1. **Render Pass(清蓝屏 + 画橙红三角形到 64×64 `RGBA8Unorm` 纹理 + Blit 读回校验)**:- - `arm64` 与 `arm64e` **均 PASS**:- `Render pass status=4: center=(255,51,0,255) corner=(0,0,255,255) triPx=1352 bluePx=2744 otherPx=0`-2. **CoreImage `CIContext(mtlDevice:)` + `CIGaussianBlur`**:- - 进展:`CIContext` 成功创建并加载 CoreImage 预编译 metallib,通过 DAG 图优化(`CIBlurProcessor-4.000`),进入 Apple `Metal.framework` 的 stitched function graph 编译器(`MTLCompilerStitchingRequest::serializedRequest`)。- - **本次过程中先补掉的 2 个阻塞点**:`XcmLibrary externFunctionNames`/`type`/`installName`,以及 `_MTLDevice` 基础限制(`recommendedMaxWorkingSetSize` 强制覆盖 + `maxTextureWidth2D`/`maxTextureHeight2D`/`maxThreadgroupMemoryLength`/`minimumLinearTextureAlignmentForPixelFormat:` 等,原默认返回 0 导致 CoreImage 报 `memory requirement of -1 too big`)。- - **落到 `stubbed` 的完整调用清单(下一步待补清单)**:- 1. `XcmQueue setBackgroundGPUPriority:`(低优先级,可沿用 `XnuCpuMetalShim.h` 里的 `kBackgroundPriorityKey` 存值)- 2. `XcmTexture isDrawable`(返回 `NO` 即可)- 3. `XcmBackendDevice newHeapWithDescriptor:`(MPS 探测时调用,目前返回 `nil` 使 CoreImage 跳过 MPS 走自有 shader;如需 MPS 支持需接入 `metal2vulkan_runtime::Heap`)- 4. `XcmCommandBuffer protectionOptions`(返回 `0` 即可)- 5. **`XcmFunction libraryData` / `bitCodeOffset` / `bitCodeFileSize`**(**当前阻断点**:`MTLCompilerStitchingRequest::serializedRequest` 读取这 3 个私有属性构造 stitched library XPC 请求,`libraryData` 返回 NULL 导致崩溃;需参考 `AdrenoMetal/NativeBridgeMetalFrontend.mm:4804` 覆盖 `newLibraryWithStitchedDescriptor:error:`,同时在 `libxnu_m2v` 暴露 `extern_function_names()` + `new_extern_function_with_name()` 供 CoreImage 链接 `ci_stdlib` extern 函数)- 6. **`newTextureWithDescriptor:iosurface:plane:`**(CoreImage 的 `imageWithBitmapData:` / `render:toBitmap:` 路径依赖 IOSurface 纹理读写,后续需补 IOSurface 映射/同步)--## 7. Round 3:CoreImage `CIGaussianBlur` 端到端打通(`arm64` + `arm64e`)--### 7.1 实现改动-1. **Stitched library + `libxnu_m2v` extern/specialized function 接口**:- - `src/xnu-m2v-bridge/include/xnu_m2v.h` 与 `src/xnu-m2v-bridge/src/lib.rs`:新增 `xm2v_library_extern_function_count`、`xm2v_library_extern_function_name_at`、`xm2v_library_new_extern_function`、`xm2v_library_new_function_specialized`,并重编 `arm64` + `arm64e` 双架构 `libxnu_m2v.dylib`。- - `src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm`:实现 `newLibraryWithStitchedDescriptor:error:`(及 archive/async 重载),通过 `MTLCompiler.framework` 的 request 14(在 16 MiB 栈独立 pthread 上执行 `xcmCodeGenRequest`)把 CoreImage stitch graph 编译为 metallib,并实现 `externFunctionNames`、`newFunctionWithName:constantValues:error:`、`newFunctionWithDescriptor:error:` 与 `xcmExtractFunctionBitcode` / `xcmLookupCIKernelFunction`。-2. **IOSurface 纹理双向同步**:- - `newTextureWithDescriptor:iosurface:plane:`(及 `slice:`):内部强制 `MTLStorageModeShared` 创建纹理,`syncFromIOSurfaceIfNeeded` 按 `IOSurfaceGetSeed` 懒同步 CPU/IOSurface 写入到纹理;`XcmCommandBuffer` 记录 `_dirtyIOSurfaceTextures`,在命令提交完成后调用 `syncToIOSurface` 回写 IOSurface 内存。- - 补齐 `_MTLDevice` 的内部 `limits` 结构体填充(`fillBaseLimits`)与 `iosurfaceTextureAlignmentBytes` / `linearTextureAlignmentBytes` / `readWriteTextureSupport` / `supportsSharedStorageTextures`。-3. **消除剩余桩调用**:- - `XcmHeap`(`newHeapWithDescriptor:`,实现 `<MTLHeap>` 并代理分配到设备)- - `setBackgroundGPUPriority:`、`isDrawable`、`protectionOptions`(command buffer 与 heap)、`GPUStartTime` / `GPUEndTime`、`globalTraceObjectID`。-4. **Mesa 26.3.1 `arm64e` gallivm JIT→C PAC 边界修复**:- - Round 2 修复了 C→JIT 方向(`gallivm_jit_function` 对返回指针签名);Round 3 跑 CoreImage 时发现 JIT→C 与 JIT→JIT 间接调用方向仍存在 PAC 签名未剥离问题(LLVM MCJIT 生成无 PAC 的 `blr`,跳转至 `arm64e` 签名指针触发 `SIGSEGV`,首次落点 `lp_texture_handle.c` 的 `get_size_function`)。- - 修复(均受 `#if defined(__has_feature) && __has_feature(ptrauth_calls)` 保护,不影响 `arm64`):- - `src/gallium/drivers/llvmpipe/lp_texture_handle.c`:`compile_function` 返回的 JIT 纹理/图像采样函数表指针以及 `matrix->compile_{sample,fetch,size}_function` 均剥离 PAC。- - `src/gallium/auxiliary/gallivm/lp_bld_const.c`(`lp_build_const_func_pointer_from_type`)、`lp_bld_format_aos.c`(`fetch_rgba_8unorm`)、`lp_bld_conv.c`(`_mesa_float_to_half`)、`lp_bld_init.c` & `lp_bld_init_orc.cpp`(`gallivm_add_global_mapping`)对传入 JIT 的 C 函数指针剥离 PAC。--### 7.2 验收实测结果(`arm64` + `arm64e`)-- `bash scripts/test-bundle.sh arm64`:`bad=0`,退出码 0。-- `bash scripts/test-bundle.sh arm64e`:`bad=0`,退出码 0。-- `bash scripts/test-render-ci.sh arm64`:- - `Render pass status=4: center=(255,51,0,255) corner=(0,0,255,255) triPx=1352 bluePx=2744 otherPx=0`(PASS)- - `CPU Metal (XnuCpuMetal (llvmpipe (LLVM 22.1.8, 128 bits))): center=(243,243,243,255) edge_2px_out=(148,148,148,255) corner=(0,0,0,120)`- - `Native GPU (Apple M5 Max): center=(244,244,244,255) edge_2px_out=(157,157,157,255) corner=(0,0,0,137)`- - `Pixel diff (64x64x4=16384 channels): maxErr=17, meanErr=2.4154, nonZeroDiff=6749`(PASS)- - stderr `stubbed` 计数:**0**(除 `metal2vulkan` 精度说明外无任何其他输出)。-- `bash scripts/test-render-ci.sh arm64e`:- - `Render pass status=4: center=(255,51,0,255) corner=(0,0,255,255) triPx=1352 bluePx=2744 otherPx=0`(PASS)- - `CPU Metal (XnuCpuMetal (llvmpipe (LLVM 22.1.8, 128 bits))): center=(243,243,243,255) edge_2px_out=(148,148,148,255) corner=(0,0,0,120)`- - `Native GPU (Apple M5 Max): center=(244,244,244,255) edge_2px_out=(157,157,157,255) corner=(0,0,0,137)`- - `Pixel diff (64x64x4=16384 channels): maxErr=17, meanErr=2.4154, nonZeroDiff=6749`(PASS)- - stderr `stubbed` 计数:**0**(除 `metal2vulkan` 精度说明外无任何其他输出)。--## 8. Round 4:macOS 27 设备发现机制静态分析与内核侧需求清单--### 8.1 macOS 27 `MTLCreateSystemDefaultDevice()` / `MTLCopyAllDevices()` 完整调用链(实机静态分析)-通过对宿主 macOS 27.0.1(26A434)的 `Metal.framework`、`IOGPU.framework`、`libsystem_sandbox.dylib` 反汇编与符号解析,确认设备发现完整路径如下:-1. **IORegistry 匹配**:`-[MTLIOAccelServiceGlobalContext init]` 调用 `IOServiceAddMatchingNotification(notifyPort, "IOServicePublish", IOServiceMatching("IOAccelerator"), ...)`,按 **IOKit 类名 `IOAccelerator`** 匹配(不是 `IOAcceleratorES`,后者为 iOS 专用)。-2. **读取的 IORegistry 属性**:- - `getMetalPluginClassForService`(`Metal.framework`)与 `+[IOGPUMetalDevice registerAcceleratorService:]`(`IOGPU.framework`)均只读 2 个核心属性:- - `MetalPluginName`(`CFString`,必填;若内部构建且设置了 `MTL_INTERNAL_BUNDLE`,会尝试 `%sInternal`)- - `MetalPluginClassName`(`CFString`,可选;若缺失或未找到类,自动回退到 bundle 的 `NSPrincipalClass`)- - `-[MTLIOAccelService initWithAcceleratorPort:deviceClass:]` 额外检查:- - `IOObjectConformsTo(port, "IOServiceCompatibility")` — **必须为 false**(若为 true 直接丢弃返回 `nil`)- - `IORegistryEntryGetRegistryEntryID(port, &rid)` + `IOServiceAddInterestNotification(notifyPort, port, "IOGeneralInterest", ...)`(普通 `IOService` 自带)- - `"Removable"`(若 `_mtlAvoidRemovable()` 为真且属性为 true 则跳过)与 `"SafeEjectRequested"`- - **`MetalStatisticsName`、`IOGLBundleName`、`IOGLESBundleName` 在 `MTLCreateSystemDefaultDevice()` / `MTLCopyAllDevices()` 路径中完全不读取**。-3. **Bundle 搜索目录与信任检查**(`libsystem_sandbox.dylib` `gpu_bundle_find_trusted`):- - 按顺序搜索 3 个目录(格式化为 `%s/%s.bundle`,须为目录 `S_IFDIR`):- 1. `/Library/GPUBundles/<MetalPluginName>.bundle`(所有图形沙箱如 `system.sb` 均放行只读,推荐放此处)- 2. `/System/Library/Extensions/<MetalPluginName>.bundle`- 3. `/AppleInternal/Library/Extensions/<MetalPluginName>.bundle`(仅 internal build 允许非受信任路径)- - 信任检查:`gpu_bundle_is_path_trusted(path)` 调用 `rootless_check_trusted_class(path, "KernelExtensionManagement")`,若返回 1 再回退 `_dyld_shared_cache_contains_path(path)`。托管环境关闭 SIP(`CSR_ALLOW_UNRESTRICTED_FS`)时 `rootless_check_trusted_class` 直接返回 0(受信任)。-4. **类校验与实例化**:- - `Metal.framework` `getMetalPluginClassForService` 要求类 `[cls isSubclassOfClass:[_MTLDevice class]]`。- - `IOGPU.framework` `+[IOGPUMetalDevice registerAcceleratorService:]` 要求类 `[cls isSubclassOfClass:[IOGPUMetalDevice class]]`(`IOGPUMetalDevice` 本身继承 `_MTLDevice`,我们的 `XnuCpuMetalDevice` 继承 `IOGPUMetalDevice`,两边同时满足)。- - `-[MTLIOAccelService initWithAcceleratorPort:deviceClass:]` 调用 `[[cls alloc] initWithAcceleratorPort:port]` -> `[dev _setAcceleratorService:self]` -> `MTLAddDevice(dev)`。-5. **`IOServiceOpen` / User Client**:- - `MTLCopyAllDevices` / `MTLIOAccelService` / `getMetalPluginClassForService` **全程不调用 `IOServiceOpen`**。- - `IOServiceOpen(service, mach_task_self(), 5 | (options << 16), &connect)` 以及 `IOConnectCallStructMethod`(selector `2` 输出 536 字节、selector `0` 输出 64 字节)仅在 `IOGPU.framework` 的 `IOGPUDeviceCreateWithOptions` 中调用(由 `-[IOGPUMetalDevice initWithAcceleratorPort:options:]` 触发)。--### 8.2 插件无 User Client 验证-- `XnuCpuMetalDevice` 覆盖了 `-initWithAcceleratorPort:` 与 `-initWithAcceleratorPort:options:`,不调用 `super`,内部全部由进程内 Mesa lavapipe 完成;`port == 0` 时仅跳过 `IORegistryEntryGetRegistryEntryID` 使用默认 `registryID`。-- `nm -u dist/XnuCpuMetal.bundle/Contents/MacOS/XnuCpuMetal` 确认 **0 个 `IOServiceOpen` / `IOConnect*` / `IOGPUDevice*` 符号引用**;`test-bundle.sh arm64e` 以 `port=0` 实测 `bad=0`。--### 8.3 内核侧需求清单与最小 kext 草稿-- **父类与依赖 kext**:继承 `IOAccelerator`,来自 **`com.apple.iokit.IOGraphicsFamily`**(macOS 27.0.1 宿主 `kextstat` 已确认内置于 boot kernel collection,版本 `600`,`IOGPUFamily` 本身即依赖它;Apple Silicon 上未加载 `IOAcceleratorFamily2.kext`)。-- **必须发布的属性**:`MetalPluginName = "XnuCpuMetal"`、`MetalPluginClassName = "XnuCpuMetalDevice"`、`IOMatchCategory = "IOAccelerator"`(可选 `model`、`gpu-core-count`)。**绝不可**发布 `Removable` 或 `SafeEjectRequested`(哪怕设为 `false`,`-[MTLIOAccelService initWithAcceleratorPort:deviceClass:]` 仅检查属性存在即跳过设备),且不可继承 `IOServiceCompatibility`。-- **User Client**:**不需要**(默认 `IOService::newUserClient` 返回 `kIOReturnUnsupported` 即可)。-- **最小 kext 源码草稿**(全新编写,不依赖 PCI/DT 硬件节点,挂在 `IOResources` 上):- - `src/xnu-cpu-metal-kext/XnuCpuMetalAccelerator.hpp`- - `src/xnu-cpu-metal-kext/XnuCpuMetalAccelerator.cpp`- - `src/xnu-cpu-metal-kext/Info.plist`--## 9. Round 5:`ictool Stats.icon` 端到端出图打通(RenderBox + QuartzCore)--基于宿主 `gpub/src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm` 新基线,定位并修复了阻断 `ictool` → `icrtool`(RenderBox + QuartzCore)的全部问题:--### 9.1 根因与修复清单-1. **函数常量 UAF 与 `std::vector` 重分配悬垂指针(解决 `FunctionConstantType { index: 0 }` 与 `ColorAttachment { index: 1/2 }` / `VertexAttribute { attribute: 4 }`)**:- - 原 `newFunctionWithName:constantValues:error:` 中 `std::vector<std::string> nameStorage` 在 `push_back` 时可能扩容导致已存入的 `c.name` 悬垂(60 个命名常量下触发 `FunctionConstantType { index: 0 }`);且提取函数返回后 ARC 释放 `[constantValues copy]` 与 `named`/`indexed` 数组导致 `c.bytes` 成为 UAF 脏内存,使 QuartzCore 的 `fc_has_attachment_1/2 = false` 被读成 `true`。- - 修复:改用 `std::deque<std::string>` + `std::deque<std::vector<uint8_t>>` 持久化拷贝常量名与字节,同时补齐 `xm2v_library_new_function_specialized_zero_rest`(`zeroRest` 重试)与缺失 `VertexAttribute`/`ColorAttachment` 的安全回退。修复后 `Stats.icon` 全部 11 条 RenderPSO 一次编译通过(0 次重试)。-2. **Linked Functions + 默认库/源码库覆盖(解决 `NeedsInput(LinkedFunction { symbol: "custom_fn" })`)**:- - 补齐 `newDefaultLibrary`、`newDefaultLibraryWithBundle:error:`、`newLibraryWithSource:options:error:`(经 `MTLCompiler.framework` request 13)及异步重载(均加 `NS_RETURNS_RETAINED`),防止 `_MTLDevice` 默认实现返回 `_MTLFunctionInternal`。- - `libxnu_m2v` 新增 `xm2v_library_new_function_with_descriptor`(传递 `specializedName`、`constantValues`、`options`)、`xm2v_compute_pipeline_new_with_linked` 以及 `Xm2vRenderPipelineDesc` 的 `vertex/fragment` public+private linked functions。-3. **VertexDescriptor、DepthStencil(前/背面 Stencil)、StencilRef 与 BlendColor**:- - `Xm2vRenderPipelineDesc` 新增 `vertex_attributes` / `vertex_layouts` 透传到 `metal2vulkan::pipeline::VertexDescriptor`。- - `Xm2vDepthStencilDesc` 新增 `front_face_stencil` / `back_face_stencil`,`XcmRenderEncoder` 接入 `xm2v_render_encoder_set_stencil_reference_values` 与 `xm2v_render_encoder_set_blend_color`。-4. **无有效 Pipeline 时安全空操作 + 异步 `commit` + 跨 `XcmTexture` 的 IOSurface 写后读同步**:- - `XcmRenderEncoder` 跟踪 `_hasPipeline`,无有效 pipeline 时 `drawPrimitives*` / `drawIndexedPrimitives*` 安全空操作,不再崩溃。- - `XcmCommandBuffer commit` 改为异步等待完成并触发 handlers 与 `syncToIOSurface`(消除多命令缓冲区事件等待 5s 死锁),并记录 `IOSurfaceID -> lastWriter`,在 `syncFromIOSurfaceIfNeeded` 中先等待已提交的写命令缓冲区完成再读 IOSurface(解决 RenderBox 跨 pass 复用同一 `IOSurface` 读到空白的问题)。-5. **消除剩余 stubbed 调用**:- - 补齐 `XcmTexture` `protectionOptions` / `allocatedSize`、`XcmRenderEncoder` `memoryBarrierWithScope:afterStages:beforeStages:` / `memoryBarrierWithResources:...`、`XcmQueue` `setSubmissionQueue:` / `setCompletionQueue:`、`XcmCommandBuffer` `setProtectionOptions:` / `commitAndWaitUntilSubmitted`。--### 9.2 宿主复现与全量回归验收-- **宿主 `ictool Stats.icon` 复现**(`DYLD_INSERT_LIBRARIES=build/ic-repro/libforce_xcm.dylib` 强制走 `dist/XnuCpuMetal.bundle`,执行 `ictool Stats.icon --export-image --output-file build/ic-repro/test.png --platform macOS --rendition Default --width 16 --height 16 --scale 2`):- - 退出码 **`0`**,stderr 除 `metal2vulkan` 精度说明外 **0 行错误、0 行 `stubbed`**。- - 与真 Mac 原生 GPU(Apple M5 Max)导出图 `build/stats_native.png` 逐像素比对(`32×32×4 = 4096` 通道):- - 原生 GPU:`nonZero=3944/4096, max=255, center=(64,144,255,255)`- - CPU Metal:`nonZero=3944/4096, max=255, center=(50,123,237,255)`- - 误差:**`meanErr=3.7783, maxErr=51`**(轮廓与红/蓝波形条完全一致)。-- **双架构回归全通过**:- - `bash scripts/test-bundle.sh arm64` / `arm64e`:`bad=0`,退出码 0。- - `bash scripts/test-render-ci.sh arm64` / `arm64e`:Render Pass PASS,CoreImage `CIGaussianBlur` 误差随常量 UAF 修复进一步降至 **`maxErr=1, meanErr=0.0161`**(`nonZeroDiff=264/16384`)!-------## Round 6: `MTLArgumentEncoder` + `useResource(s):`(Stats `MenuBarIcon.icon` scale 1 & 2)--### 根因-- Stats 的 "Generate menu bar icon" 阶段将 `Stats.icon` 的 `fill` 改为线性渐变并把 `grid.svg` 替换为 `#D8D8D8` 后,分别以 `--scale 1` 和 `--scale 2` 调用 `ictool`。-- `--scale 2` 在 `ImageIO` 的 `-[HDRImageConverter_Metal encodeInputImage:transform:toBuffer:offset:withArgumentEncoder:computeEncoder:index:textures:]` 路径中调用 `-[XcmFunction newArgumentEncoderWithBufferIndex:]`;此前该函数被 `XnuCpuMetalShim.h` stub 返回 `nil`,导致 `[argEnc constantDataAtIndex:]` 返回 `NULL` 并在 `offset 0x20` 处 `SIGSEGV`(exit 139)。--### 修复-1. **Rust C ABI 桥(`src/xnu-m2v-bridge/include/xnu_m2v.h`、`src/xnu-m2v-bridge/src/lib.rs`)**:- - 暴露 `metal2vulkan_runtime::ArgumentEncoder`:`xm2v_function_new_argument_encoder`、`xm2v_argument_encoder_release` / `encoded_length` / `alignment` / `set_argument_buffer` / `set_argument_buffer_array_element` / `set_buffer` / `set_texture` / `set_sampler` / `set_compute_pipeline` / `set_render_pipeline` / `constant_data` / `new_nested`。- - 暴露 `xm2v_texture_gpu_resource_id`、`xm2v_sampler_gpu_resource_id`。- - 暴露真实资源驻留接口:`xm2v_compute_encoder_use_buffer` / `xm2v_compute_encoder_use_texture` 与 `xm2v_render_encoder_use_buffer` / `xm2v_render_encoder_use_texture`(直连 `ComputeCommandEncoder::use_resource` 与 `RenderCommandEncoder::use_resource`)。-2. **ObjC 插件(`src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm`、`XnuCpuMetalShim.h`)**:- - 新增 `XcmArgumentEncoder` 实现 `<MTLArgumentEncoder>`(并在 `XnuCpuMetalShim.h` 注册协议与参考类 `_MTLArgumentEncoder`),写入 texture 时自动触发 `syncFromIOSurfaceIfNeeded`。- - `XcmFunction` 实现 `newArgumentEncoderWithBufferIndex:` 与 `newArgumentEncoderWithBufferIndex:reflection:`。- - `XcmComputeEncoder` 与 `XcmRenderEncoder` 的 `useResource:` / `useResources:` 接入真实 `xm2v_*_use_buffer` / `use_texture`,并同步处理 IOSurface 读写(读前 `syncFromIOSurfaceIfNeeded`,写后 `markDirtyIOSurfaceTexture:`)。- - `XcmTexture` / `XcmSampler` 暴露 `gpuResourceID`;`XcmBackendDevice` 暴露 `argumentBuffersSupport`(`MTLArgumentBuffersTier2`)。--### 验证结果(通用 `arm64 + arm64e` `dist/XnuCpuMetal.bundle`)-- **Modified `MenuBarIcon.icon`(`build/ic-repro/MenuBarIcon.icon`)**:- - `--scale 1`:`EXIT=0`,无任何 `stubbed` / 错误日志;`16×16` `nonZero=1008/1024`,对比原生 GPU `MenuBarIcon1_native.png`:`maxErr=42, meanErr=7.8740`。- - `--scale 2`:`EXIT=0`,无任何 `stubbed` / 错误日志;`32×32` `nonZero=3968/4096`,对比原生 GPU `MenuBarIcon2_native.png`:`maxErr=38, meanErr=4.3428`。-- **全量回归**:- - `bash scripts/test-bundle.sh arm64` / `arm64e`:`vecadd N=1024, status=4, completedHandler=1, bad=0`。- - `bash scripts/test-render-ci.sh arm64` / `arm64e`:Render Pass PASS,CoreImage `CIGaussianBlur` PASS(`maxErr=1, meanErr=0.0161, nonZeroDiff=264/16384`)。- - Plain `Stats.icon` `--scale 2`:`EXIT=0`,无 `stubbed` 日志;`32×32` `nonZero=3944/4096`,对比 `build/stats_native.png`:`maxErr=51, meanErr=3.7783`。-------## Round 7: 性能、资源占用与多项目 macOS CI 用例基线/优化--### 约束与测量方式-- 宿主机 Apple M5 Max(macOS 27.0.1),使用 `taskpolicy -c utility` + `RAYON_NUM_THREADS=1` + `LP_NUM_THREADS=1`(优化前)/ `LP_NUM_THREADS=0`(优化后,单核内联执行、无额外 worker 线程)模拟单核托管 VM 与多 VM 并发 CI 环境。-- 所有改动均基于 `xnulinux` commit `04d3386`(`gpu/xnu-cpu-metal/`),未修改任何 GPL/LGPL 上游源码。--### 性能剖析排序(`icrtool` WARM,200Hz `SIGPROF` PC 采样,3,600 samples)-1. **Mesa `llvmpipe` LLVM JIT 编译(~97%)**:`59.4%` LLVM (`SpillPlacement`, `ScheduleDAGSDNodes`, `RAGreedy`, `InterferenceCache`) + `13.5%` `memmove`/`memset` + `13.0%` `madvise` + `11.1%` `malloc`(根因:`build-lavapipe*.sh` 此前传了 `-Dshader-cache=disabled`,每次进程启动都从零重编译所有 LLVM JIT 着色器,并产生 500–700 MB 临时峰值 RSS)。-2. `lavapipe` 其余 + `dyld`:`2.7%`-3. `metal2vulkan` AIR→SPIR-V 翻译:`0.1%`(热运行已命中磁盘缓存;冷运行约占 ~14s)-4. `llvmpipe` JIT 光栅化/计算执行:`< 0.1%`-5. IOSurface 同步拷贝 / `XnuCpuMetal` 插件 / command buffer 等待:`< 0.1%`--### 实施的优化(4 文件,+91/-20 行)-1. **启用 Mesa `llvmpipe` 持久化 LLVM JIT 磁盘缓存**:`scripts/build-lavapipe.sh` 与 `scripts/build-lavapipe-arm64e.sh` 改为 `-Dshader-cache=enabled -Dshader-cache-max-size=256M`(arm64 与 arm64e 均生效,ORC JIT `LPObjectCacheORC` 直接复用 `gallivm_jit_function` PAC 签名)。-2. **Root/CI 安全的缓存目录与多 VM 并发默认上限**(`XnuCpuMetalPlugin.mm`、`lib.rs`):- - 缓存目录按 `XNU_CPU_METAL_CACHE_DIR` → `_CS_DARWIN_USER_CACHE_DIR` → `/var/tmp/xnu-cpu-metal-<uid>` → `/tmp/xnu-cpu-metal-<uid>` 回退并校验可写(适配 root 托管环境)。- - 默认设置 `MESA_SHADER_CACHE_DIR=<cacheDir>/mesa`、`MESA_SHADER_CACHE_MAX_SIZE=256M`(均可由环境变量覆盖)。- - `metal2vulkan` 缓存上限从默认 `25 GiB` 磁盘 / `256 MiB` 内存收紧为 `512 MiB` 磁盘 / `32 MiB` 内存(可通过 `XNU_CPU_METAL_CACHE_MAX_MB`、`XNU_CPU_METAL_MEM_CACHE_MB` 覆盖)。- - `LP_NUM_THREADS` 默认值:`hw.ncpu <= 1` 时为 `0`(内联执行、零额外 worker 线程),多核时上限为 `2`(多 VM 友好,可由 `LP_NUM_THREADS` 覆盖)。-3. **修复 `VK_ICD_FILENAMES` / `VK_DRIVER_FILES` 环境变量污染**(`lib.rs`):`xm2v_device_open` 打开设备后恢复原环境变量,避免同进程内 Chromium SwANGLE 被劫持到无 `VK_EXT_metal_surface` 的 lavapipe ICD。-4. **修复 `XcmCommandBuffer _fireHandlersOnce` 竞态**(`XnuCpuMetalPlugin.mm`):在 `@synchronized(self)` 内执行 `completedHandler`,防止缓存加速后 `waitUntilCompleted` 早于后台回调返回。--### 优化前后对比(单核约束,含多项目 CI 简化用例)-| 用例 | 来源 CI | 兼容性(vs 原生 GPU) | 优化前 Wall / User / Peak RSS | 优化后 Wall / User / Peak RSS | 提升 |-|---|---|---|---|---|---|-| `ictool Stats.icon --scale 2` (COLD) | Stats / Cue / AFFiNE | PASS (`maxErr=51, meanErr=3.7783`) | 61.72s / 24.30s / 893 MB | 33.75s / 24.86s / 1158 MB | Wall **1.83x** |-| `ictool Stats.icon --scale 2` (WARM1 → WARM2 → 稳态) | Stats / Cue / AFFiNE | PASS (`maxErr=51, meanErr=3.7783`) | 47.69s / 25.79s / 918 MB | 11.19s → 5.04s → **1.21s** / **1.09s** / 781–980 MB | Wall **4.3x → 39.4x**,CPU **23.7x** |-| `ictool MenuBarIcon.icon --scale 1` (WARM) | Stats | PASS (`maxErr=42, meanErr=7.8740`) | — | **1.22s** / 1.15s / 983 MB | 零 `stubbed` |-| `ictool MenuBarIcon.icon --scale 2` (WARM) | Stats | PASS (`maxErr=38, meanErr=4.3428`) | — | **2.35s** / 2.15s / **534 MB** | 零 `stubbed` |-| `CIGaussianBlur` 64×64 (WARM) | CoreImage | PASS (`maxErr=1, meanErr=0.0161`) | 0.45s (render 250.3ms) / 0.36s / 276 MB | **0.32s (render 108.6ms)** / 0.22s / **257 MB** | render **2.30x**,RSS -19 MB |-| `vecadd` 1M floats (WARM) | Compute | PASS (`bad=0`) | 0.16s (exec 9.5ms) / 0.14s / 179 MB | 0.22s / 0.15s / **160 MB** | RSS **-19 MB** |-| `mbui_offscreen` 800×600×5f (WARM) | `AFK-surf/monoid` (`mbui`) | PASS (`maxErr=2, meanErr=0.0784`) | 0.31s (render 65.7ms) / 0.25s / 195 MB | **0.23s (render 28.4ms)** / 0.17s / **186 MB** | render **2.31x**,RSS -9 MB |-| `gpui_offscreen` 800×600×5f (WARM) | `longbridge/gpui-component` | PASS (`maxErr=1, meanErr=0.0001`) | 0.25s (render 57.3ms) / 0.21s / 196 MB | **0.20s (render 24.0ms)** / 0.16s / **180 MB** | render **2.39x**,RSS -16 MB |-| `actool` minimal `.xcassets` | Cue / AFFiNE / monoid | PASS (21,720 B 完全一致) | 0.31s / 0.00s / 2.5 MB | 0.31s / 0.00s / 2.5 MB | 无回归 |-| Playwright Chromium headless Metal (`400×300`) | Cue / AFFiNE | PASS (`maxErr=2, meanErr=0.2256`) | SwANGLE 因 `VK_ICD_FILENAMES` 污染报错 | **零 SwANGLE/Vulkan 报错**,12.07s / 2.00s / 298 MB | 兼容性修复 |-| 空闲占用 (`idle_probe`, 3s idle) | 多 VM 并发 | 0.0% 空闲 CPU | RSS 160.5 MB / phys 98.9 MB / 14 线程 / 0.000s CPU | RSS **157.5 MB** / phys 101.7 MB / **13 线程** / **0.000s CPU** | 零空闲线程耗电 |--### 明确不做项及原因-- **不默认开启 `GALLIVM_PERF=no_opt`**:实测虽可降冷编译 ~40%,但使热渲染慢 **2.9x–3.1x**(`CIGaussianBlur` 108.6→316.0ms、`mbui` 28.4→87.6ms、`gpui` 24.0→73.5ms);配合磁盘缓存一次编译 `-O2` 复用显著更优。-- **不做零拷贝 IOSurface Vulkan 导入**:剖析显示 IOSurface 同步耗时 `< 0.1%`,800×600×5 帧 `gpui` 含 IOSurface 仅 24ms(4.8ms/帧);lavapipe 导入 IOSurface 需要线性布局与 `VK_EXT_external_memory_host`,与 `metal2vulkan-runtime` 的 tiled/shadowed 纹理模型冲突且收益微弱。-- **不改 `metal2vulkan-runtime` 64 MiB 内存 slab(`BLOCK_BYTES`)**:`metal2vulkan` 属 GPL/LGPL 上游(构建时拉取、不入库);我们在自研桥接层收紧了 `ShaderCacheOptions` 内存/磁盘上限。-- **不做 commit 去阻塞 / 无管线 draw 跳过**:插件此前已异步 `commit` 且已跳过 `!_hasPipeline` 的 draw。-------## Round 8: WindowServer / SkyLight Metal 设备筛选分析与合成器适配--### SkyLight 静态反汇编证据(macOS 27.0.1 dyld cache `SkyLight.framework`)-1. **`__WSSystemCanCompositeWithMetal_block_invoke` (`SkyLight @ 0x19365f508`)**:- - `+0x088`: `BL MTLCopyAllDevicesWithObserver(&observer, handler)`(observer block 在 `+0x1e0` 检查 `MTLDeviceWasAddedNotification`)。- - `+0x090`: `BL objc_msgSend("count")`;`+0x094`: `cbz x0, +0x0a4`。- - **此处本身没有任何设备属性过滤**——只要 `[devices count] == 0`,就记录 `"Metal device initially absent."`(`+0x0c8`),在 `dispatch_semaphore_wait` 上等 30 秒,超时后记录 `"No suitable Metal devices present after %llu seconds."`(`+0x168`)并 `abort()`。- - **托管系统 WindowServer 触发该错误的直接根因**:commit `04d3386` 的插件在 `confstr(_CS_DARWIN_USER_CACHE_DIR)` 失败时回退到共享路径 `/tmp/xnu-cpu-metal-m2v`;先前以 `root` (uid=0) 运行时 `metal2vulkan` `ShaderCache` 以 `0700` 创建了该目录,随后 `WindowServer` 以 `_windowserver` (uid=88) 启动时 `ShaderCache::open` 报 `PermissionDenied` → `xm2v_device_open` 返回 `NULL` → `initWithAcceleratorPort:` 返回 `nil` → `MTLCopyAllDevicesWithObserver` 返回空数组 (`count == 0`)。-2. **通过 `WSSystemCanCompositeWithMetal` 后 SkyLight 紧接着检查的接口**:- - `__WSGetDefaultMetalAccelerator_block_invoke` (`0x19366a14c`):`MTLCopyAllDevices` → `firstObject` → `acceleratorPort`(必须非 0)。- - `CompositorMetal::new_compositor` (`0x193663944`):`acceleratorPort`、`isRemovable` (`NO`)、`supportPriorityBand` (`NO`)、`MPSSupportsMTLDevice` (`YES`)、`registryID`、`compilerPropagatesThreadPriority:`、队列 `setCompletionQueue:` / `setSubmissionQueue:` / `setGPUPriority:`。- - `SLSCreateDefaultMetalDevice` (`0x19387fc08`):`acceleratorPort`、`isLowPower`。--### 插件修改(`XnuCpuMetalPlugin.mm`、`XnuCpuMetalShim.h`)-1. **Per-UID 真实可写探测的缓存目录回退**:按 `XNU_CPU_METAL_CACHE_DIR` → `_CS_DARWIN_USER_CACHE_DIR` → `_CS_DARWIN_USER_TEMP_DIR` → `NSTemporaryDirectory()` → `/var/tmp/xnu-cpu-metal-<uid>` → `/tmp/xnu-cpu-metal-<uid>` 逐级用实际 `open(O_CREAT|O_WRONLY)` 探测可写性,杜绝 uid=0 与 uid=88 (`_windowserver`) 互锁;打开失败时同步写入 `os_log_error`。-2. **对齐 DroidVM WindowServer 设备属性与 IOSurface 策略**:- - `isHeadless = NO`、`isLowPower = NO`(原为 `YES`/`YES`),保持 `isRemovable = NO`、`hasUnifiedMemory = YES`、`isBuiltIn = YES`。- - 启动时设置 `CFPreferencesSetAppValue(CFSTR("CAEnableIOSurfaceCompression"), kCFBooleanFalse, kCFPreferencesCurrentApplication)`,确保 QuartzCore/WindowServer 分配线性未压缩 IOSurface。-3. **补齐 WindowServer 合成器接口**:- - `XnuCpuMetalShim.h` 新增设备 `compilerPropagatesThreadPriority:` 与队列 `setCompletionQueue:` / `setSubmissionQueue:`(消除 `CompositorMetal::new_compositor` 的 stub 警告)。- - `XcmTexture` 多平面 IOSurface 同步增加 `plane < planeCount` 越界保护,并将 `_iosurface` / `_iosurfacePlane` 传递到 `newTextureViewWithPixelFormat:` 视图纹理(支持对 IOSurface 的 sRGB/格式视图渲染回写)。--### 宿主机验证结果(通用 `arm64 + arm64e` `XnuCpuMetal.bundle`)-- `test_ws_full`:`isHeadless=0, isLowPower=0, isRemovable=0, hasUnified=1, MPSSupportsMTLDevice=1`;2-plane YCbCr `420v` IOSurface (`R8Unorm` + `RG8Unorm`) 读写 PASS;`MPSImageGaussianBlur` + `setCompletionQueue:`/`setSubmissionQueue:` PASS(`status=4, center=(229,229,229,229)`)。-- 全量回归全部 PASS:`test-bundle.sh arm64/arm64e` (`bad=0, completedHandler=1`)、`test-render-ci.sh arm64/arm64e` (`CIGaussianBlur maxErr=1, meanErr=0.0161`)、`ictool Stats.icon` (`maxErr=51`)、`MenuBarIcon.icon` scale 1 & 2 (`maxErr=42/38`)、`mbui_offscreen` (`maxErr=2`)、`gpui_offscreen` (`maxErr=1`),全部零 `stubbed`。-------## Round 9: Vulkan-Loader secure-mode ICD 自包含加载 + `&BGA`/`&RhA`/`&b3a` 压缩 IOSurface 线性处理--### 修改内容-1. **彻底消除 `VK_ICD_FILENAMES` 环境变量依赖与构建目录 `sysconfdir` 硬编码**:- - `scripts/build-vkloader-arm64e.sh` 改为同时构建 `arm64` 与 `arm64e` 两个 slice,并传入 `-DSYSCONFDIR=/Library/GPUBundles/XnuCpuMetal.bundle/Contents/Resources`。- - `scripts/build-bundle-universal.sh` 将双架构 `libvulkan.1.dylib` 合并进 bundle,并在 bundle 内放入 `Contents/Resources/vulkan/icd.d/lvp_icd.aarch64.json`(`library_path: "../../../Frameworks/libvulkan_lvp.dylib"`)。在 `WindowServer` 等高权限/secure 模式下,Vulkan-Loader 自动搜索 `<SYSCONFDIR>/vulkan/icd.d` 并加载 bundle 内的 lavapipe,无需环境变量也无需在 `/usr/local/share/vulkan/icd.d` 写外部清单。- - `strings` 验证 `libvulkan.1.dylib` 中零 `/Users/admin` 硬编码路径,仅含 `/Library/GPUBundles/XnuCpuMetal.bundle/Contents/Resources`。-2. **`&BGA` / `&RhA` / `&b3a` / `b3a8` 压缩 IOSurface 格式的线性处理**(`XnuCpuMetalPlugin.mm`):- - 新增 `xcmPixelFormatBpp`(含 `BGRA10_XR` 8 Bpp)与 `xcmIOSurfacePlaneLayout`,在 `syncFromIOSurfaceIfNeeded` / `syncToIOSurface` 中统一将 `&` 开头的无损压缩 IOSurface 按线性未压缩行读取/回写;针对 `b3a8`/`&b3a` 双平面 `IOSurfaceGetBytesPerRowOfPlane == 0` 情形按 64B 对齐自动计算双平面偏移与 stride(并做 `allocSize` 越界保护)。- - `XcmTexture` 的 `replaceRegion:` 与 `getBytes:` 同步补齐 IOSurface 双向同步。--### 验证结果-- 端到端 `&BGA` (1280×720, `bpr=5120`)、`&RhA` (`RGBA16Float`)、`&b3a` (`BGR10_XR`) 渲染 + 采样 + Blit + IOSurface 线性回读测试 (`test_compressed_full`):**全部 PASS**(线性 BGRA 精确匹配 `(204,153,51,255)`)。-- 全量 `arm64` + `arm64e` 回归(`test-bundle.sh`、`test-render-ci.sh`):**全部 PASS**(`vecadd bad=0, completedHandler=1`;Render Pass PASS;CoreImage `CIGaussianBlur maxErr=1, meanErr=0.0161`)。-------## Round 10: Buffer-Backed Linear Textures + `MTLSharedEvent`/`MTLFence` + 内存态 `CAEnableIOSurfaceCompression`--### 根因分析(QuartzCore macOS 27.0.1 dyld cache 静态反汇编)-1. **`nil linear texture from buffer`**:`CA::OGL::MetalContext::copy_image_to_texture` 将客户端共享内存 backing store 通过 `newBufferWithBytesNoCopy:length:options:deallocator:` 包装为 `MTLBuffer` 后,调用 SPI `-[MTLBuffer newLinearTextureWithDescriptor:offset:bytesPerRow:bytesPerImage:]`。此前 `XcmBuffer` 未实现该 SPI(被 `resolveStub` 桩返回 `0`),且 `newTextureWithDescriptor:offset:bytesPerRow:` 忽略 `offset`/`bytesPerRow` 新建了独立纹理。-2. **`timed out fence` + `Command buffer failed (Error code = 0x1)`**:`XcmBackendDevice` 缺失 `newSharedEvent` / `newSharedEventWithOptions:` / `newSharedEventWithHandle:`,`XcmCommandBuffer` 的 `encodeSignalEvent:`/`encodeWaitForEvent:` 仅处理 `XcmEvent` 未处理 `MTLSharedEvent`,三类 Encoder 缺失 `updateFence:`/`waitForFence:`,且 `XcmCommandBuffer.error` 硬编码 `"Command buffer failed"` 未透出底层 `metal2vulkan` 失败原因。-3. **非持久化 `CAEnableIOSurfaceCompression`**:`CFPreferencesSetAppValue` 会把偏好落盘到各 App 的 plist。反汇编 `__CADeviceUseCompression_block_invoke` 确认 QuartzCore 调用 `CFPreferencesGetAppBooleanValue`,改用 `[[NSUserDefaults standardUserDefaults] registerDefaults:@{@"CAEnableIOSurfaceCompression": @NO}]` 仅在内存 `NSRegistrationDomain` 生效,绝不落盘。--### 修改内容-- **`src/xnu-m2v-bridge/include/xnu_m2v.h` & `src/lib.rs`**:- - 导出 `xm2v_buffer_new_no_copy_dealloc`(支持 `Deallocator` 回调)、`xm2v_buffer_new_texture`、`xm2v_buffer_new_linear_texture`(直接对接 `metal2vulkan_runtime::Buffer::new_texture` / `new_linear_texture`,原生别名共享内存并在需要时自动走 `shadowed-texture` 双向同步)。- - 导出完整 `Xm2vSharedEvent` / `Xm2vSharedEventHandle` C ABI(`new`、`new_with_handle`、`signaled_value`、`set_signaled_value`、`wait_until`、`notify`、`new_handle`)及 `xm2v_command_buffer_encode_{signal,signal_scheduled,wait}_shared_event`。- - 导出 Compute/Render/Blit Encoder 的 `update_fence` / `wait_fence` 与 `xm2v_command_buffer_error`(透出 `cb.error()` / `cb.refusal()` / `cb.error_description()`)。-- **`src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm` & `XnuCpuMetalShim.h`**:- - 实现 `-[XcmBuffer newTextureWithDescriptor:offset:bytesPerRow:]` 与 `-[XcmBuffer newLinearTextureWithDescriptor:offset:bytesPerRow:bytesPerImage:]`,在 `XcmTexture` 上维护并透传 `buffer` / `bufferOffset` / `bufferBytesPerRow`;`newBufferWithBytesNoCopy:` 完整透传 `deallocator`。- - 新增 `XcmSharedEvent`(声明遵循 `MTLSharedEvent`/`MTLEvent`,参考类 `IOGPUMetalSharedEvent`)与 `XcmSharedEventHandle`,支持 `MTLSharedEventListener` 在其 `dispatchQueue` 异步回调;补齐 `XcmCommandBuffer` 事件编码与 `os_log_error` 详细错误日志、三类 Encoder 的 `MTLFence` 编码。- - 将 `CFPreferencesSetAppValue` 替换为纯内存 `NSUserDefaults registerDefaults:`。--### 宿主机验证结果(通用 `arm64 + arm64e` `XnuCpuMetal.bundle`)-- **`test_round10`(`arm64` & `arm64e` 双架构全部 PASS)**:- - `CAEnableIOSurfaceCompression` 通过 `CFPreferencesGetAppBooleanValue` 读到 `valid=1, val=0` 且无任何 plist 落盘。- - WindowServer 日志全部 4 种线性纹理规格(`84x103 bpr=192 o=0`、`234x18 bpr=960 o=0x100`、`256x1 bpr=2048 o=0`、`1x1 bpr=64 o=0x100 bpi=4`)均成功创建并校验 `buffer`/`bufferOffset`/`bufferBytesPerRow` 与 `deallocator` 调用;CPU 原地覆写共享内存(`0xff112233` → `0xff44cc88`)不重建纹理,GPU Shader 连续两帧渲染结果精确一致。- - `MTLSharedEvent` GPU signal → `MTLSharedEventListener` 回调及时触发、CPU `setSignaledValue:` 解除 GPU `encodeWaitForEvent:` 阻塞、`newSharedEventHandle`/`newSharedEventWithHandle:` 别名与 `MTLFence` 均 PASS。-- **全量回归(`arm64` & `arm64e`)**:`test-bundle.sh`、`test-render-ci.sh`(Render Pass + `CIGaussianBlur maxErr=1, meanErr=0.0161`)、`test_compressed_full`(`&BGA`/`&RhA`/`&b3a`)全部 PASS。-------## Round 11: 修复 QuartzCore `VfxXg/Xgc` 合成全黑(`minConstantBufferAlignmentBytes` 环缓冲归零 + `isFramebufferReadSupported`)--### 根因定位(宿主机 `CARenderer rendererWithMTLTexture:options:` 复现 + `QuartzCore` 反汇编)-用 `CARenderer` 对比本插件与 Apple M5 Max 原生 Metal,在 `rounded_only` 与 `rounded_shadow` 场景中稳定复现全黑/大面积 `(0,0,0,0)`,并定位到两个耦合的设备能力缺口:-1. **`minConstantBufferAlignmentBytes` 返回 `0` 导致 `MetalBufferPool` 环缓冲偏移归零覆写**:- - 反汇编 `CA::OGL::MetalBufferPool::encode_vertex_arg`(`+0x3c..+0x58`)确认其用 `align = max(req_align, pool->min_alignment)` 计算对齐偏移 `aligned = (cur + align - 1) & (-align)`。- - 当 `VfxXg/Xgc` 编码 0 字节占位参数(`req_align = 0`)且 `_MTLDevice` limits 中 `minConstantBufferAlignmentBytes == 0` 时,`align = 0`,`aligned = (cur - 1) & 0 = 0`,导致 `pool->current_offset` 在同一个 RenderPass 中被重置为 `0`,后续 draw 直接从偏移 `0` 覆写同一个 256 KiB 缓冲,摧毁前面所有 draw 的顶点、索引和颜色常量。-2. **`isFramebufferReadSupported` 返回 `NO` 导致 `VfxXg/Xgc` 混合输出 `(0,0,0,0)`**:- - `VfxXg/Xgc`(`fixed_vert_lph_gen` + `fixed_frag_lph_cpf`)是 QuartzCore 的通用 uber-shader,其管线固定为 `blend=0` 并依赖 `[[color(0)]]` 可编程混合(`fc_framebuffer_fetch = Bool 01`)。此前插件未返回 `isFramebufferReadSupported = YES`,导致 QuartzCore 以 `fc_framebuffer_fetch = Bool 00` 且 `blend=0` 编译 `Xgc`,所有半透明/圆角/阴影/窗口合成 draw 均输出 `(0,0,0,0)`。开启后 `metal2vulkan-runtime` 通过 lavapipe 的 `rasterizationOrderColorAttachmentAccess` 精确执行 framebuffer fetch。--### 修改内容(`src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm`)-- 在 `fillBaseLimits` 补齐缺失的对齐字段:`minConstantBufferAlignmentBytes = 4`、`minBufferNoCopyAlignmentBytes = 4096`、`linearTextureArrayAlignmentBytes = 16`、`linearTextureArrayAlignmentSlice = 128`、`maxComputeThreadgroupMemoryAlignmentBytes = 16`、`linearTextureAlignmentBytes = 64`。-- 在 `XcmBackendDevice` 补齐 `isFramebufferReadSupported = YES`、`supportsProgrammableBlending = YES`、`supportsUnalignedVertexFetch = YES`,并在 `supportsFamily:` 放行 `Apple1..2` / `Mac1..2` / `Common1..3`。-- 在 `XNU_CPU_METAL_TRACE=1` 下新增每次 `renderCommandEncoderWithDescriptor:`(`c0`、load/store/clear、depth/stencil)、`newRenderPSO`(`blend` 参数与 `writeMask`)、`drawPrimitives`/`drawIndexedPrimitives`(图元类型、顶点数、绑定的 `vb`/`fb`/`ft`/`fs` 掩码、`fbytes`、`viewport`、`scissor`)及 `cb-done` 状态日志。--### 宿主机验证结果(通用 `arm64 + arm64e` `XnuCpuMetal.bundle`)-- **`CARenderer` 对比 Apple M5 Max(`build/test_carenderer.mm`,`arm64` & `arm64e` 双架构全部 PASS,覆盖 `VfxXg/Xgc` 路径)**:- - `color`(纯红 backgroundColor):`maxErr=0, meanErr=0.000`- - `image`(四象限 CGImage):`maxErr=0, meanErr=0.000`- - `two_layers`(双层叠加):`maxErr=0, meanErr=0.000`- - `rounded_only`(圆角 layer,触发 `VfxXg/Xgc`):`maxErr=1, meanErr=0.000`- - `rounded_shadow`(圆角 + 阴影,多 pass 模糊 + `VfxXg/Xgc`):`maxErr=3, meanErr=0.092`-- **全量回归(`arm64` & `arm64e`)**:`test_round10`、`test-bundle.sh`、`test-render-ci.sh`、`test_compressed_full` 全部 PASS。-------## Round 12: `XcmCommandBuffer` / Encoder 并发资源生命周期与线程安全加固(`iconservicesagent` 崩溃排查)--### 审计发现与修复(`src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm`)-1. **Encoder 资源过早释放(违反 `retainedReferences = YES`)**:- - 此前 `XcmRenderEncoder`、`XcmComputeEncoder`、`XcmBlitEncoder` 在 `endEncoding` 时立刻清空 `_retained`,且 `renderCommandEncoderWithDescriptor:` 未强引用非 IOSurface 的 color/depth/stencil attachment 纹理,导致调用方在 `endEncoding` + `commit` 后立即释放 `XcmBuffer`(含 `_fallbackDeallocator`)或 `XcmTexture` 时,对象可能在 GPU(`llvmpipe` 光栅化线程)仍在执行期间提前 `dealloc`。- - 修复:在 `XcmCommandBuffer` 新增 `_retainedResources` 与 `retainResource:`(`@synchronized(self)` 保护),将三类 Encoder 绑定资源、RenderPass attachment 纹理与 Event 全部挂到 `XcmCommandBuffer`,仅在 `wait_until_completed` + IOSurface 同步 + handlers 完成后于锁外 `_releaseRetainedResourcesOnce` 释放。-2. **`XcmCommandBuffer` 并发竞争与 Handler 顺序保证**:- - `addScheduledHandler:`、`addCompletedHandler:`、`markDirtyIOSurfaceTexture:`、`commit`(`_committed` 防重入)全部加 `@synchronized(self)` 保护。- - `_fireHandlersOnce` 在锁内快照清空回调列表,**锁外**执行用户回调避免死锁,同时用 `dispatch_group_t`(带同线程重入检测)保证任意并发调用 `waitUntilCompleted` 的线程在所有 completed handler 执行完之前绝不提前返回。-3. **`XcmTexture` IOSurface 并发同步与类型校验**:- - `syncFromIOSurfaceIfNeeded`(先 `xcmFlushIOSurfaceWriter` 再取 `@synchronized(self)`,保持严格锁序 `XcmCommandBuffer -> XcmTexture`)与 `syncToIOSurface` 加 `@synchronized(self)` 保护;`gIOSurfaceLastWriter` 超过 256 项时自动清理失效 `__weak` 项。- - 三类 Encoder 对 buffer/texture/sampler/depthStencil/pipeline 参数补齐 `isKindOfClass:` 校验,避免非法对象强转解引用 `_handle`。--### 验证结果(通用 `arm64 + arm64e` `dist/XnuCpuMetal.bundle`)-- **新增多线程并发压测**(`build/test_stress_mt.mm`,`arm64` & `arm64e`,`LP_NUM_THREADS=2` 与 `LP_NUM_THREADS=0`):- - Phase 1(8 线程 × 60 = 480 次并发 `commit` + IOSurface + `addCompletedHandler:` + 交替 `waitUntilCompleted` + 立即释放):`submitted=480 handlers=480 failures=0`- - Phase 2(4 线程 × 15 = 60 次并发 `CARenderer` 含圆角阴影):`caDone=60 failures=0`- - Phase 3(4 线程 × 40 = 160 次 `newBufferWithBytesNoCopy:` + `munmap` deallocator + `commit` 后立即释放):`noCopyDone=160 deallocCount=160 failures=0`- - Phase 4(40 轮双线程并发 `waitUntilCompleted` 与 `completedHandler` 完成顺序及单次触发校验):`failures=0`- - 4 进程并发 `ictool MenuBarIcon.icon`:全部退出 0 且输出一致(`114801` 字节)。-- **全量回归(`arm64` & `arm64e`)**:- - `test_carenderer`(5 项对比 Apple M5 Max)、`test_round10`(4/4 PASS)、`test-bundle.sh`(`bad=0`)、`test-render-ci.sh`(`CIGaussianBlur maxErr=1, meanErr=0.0161`)全部 PASS。-------## Round 13: Safari 打开时 `WindowServer` `GpuHang` → `AccessRevoked` → `llvmpipe_draw_vbo` UAF `SIGSEGV` 与 0 长度 NoCopy 修复--### 根因-1. **CPU 设备套用了 20.2s 硬件 GPU watchdog**:`metal2vulkan-runtime/src/command_buffer/stall.rs` 对所有设备硬编码 `WATCHDOG = 20.2s`、`STALL = 10s`。Safari 启动时 CPU 光栅化 + LLVM JIT 负载骤增,单批超过 20.2s 即被判 `GpuHang` 并 park `VkDevice`;累计 2 次后触发 `revocation.rs`(`REVOKING = 2`)永久吊销队列,后续提交全部 `AccessRevoked`。-2. **Parked 设备仍执行 host memory deallocator 导致 `llvmpipe_draw_vbo` 顶点 fetch UAF**:`VkDevice` 被 park 后 `release::object` 跳过 `vkFreeMemory`,但 `metal2vulkan-runtime/src/buffer.rs` 的 `Imported::drop` 与 `HostPages::drop` 仍会执行调用方的 `deallocator`(`munmap`),且 `XcmCommandBuffer` 仍释放 `_retainedResources`,导致 `lavapipe` 后台线程执行 `llvmpipe_draw_vbo` 读取已取消映射的页边界(`0x...c000`)而 `SIGSEGV`。同时 `XcmCommandBuffer` 的 `wait_until_completed` 存在 60s 硬超时。-3. **`newBufferWithBytesNoCopy(ptr=0, len=0)` 语义偏差**:实测宿主机 Apple M5 Max 上 `newBufferWithBytesNoCopy(NULL, 0)`、`newBufferWithLength(0)`、`newBufferWithBytes(NULL, 0)` 均直接返回 `nil` 且不调用 `deallocator`;原插件会报错并回退到 `xm2v_buffer_new(..., 0, ...)`。--### 修复-1. `src/metal2vulkan/crates/metal2vulkan-runtime/src/command_buffer/stall.rs`:对 `DeviceKind::Cpu` 将 `watchdog_after` 与 `stall_after` 放宽至 `3600s`(支持 `XNU_CPU_METAL_WATCHDOG_MS` 覆盖用于测试)。-2. `src/metal2vulkan/crates/metal2vulkan-runtime/src/buffer.rs`:`Imported::drop` 与 `HostPages::drop` 在 `release::parked(vk_device)` 时跳过 deallocator / keep_alive 释放(与 `vkFreeMemory` 一致地保持映射),彻底杜绝 parked 设备的 `munmap` UAF。-3. `src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm`:- - `XcmCommandBuffer` `wait_until_completed` 改为无限等待(`timeout_ms = 0`);若遇到 `GpuHang`/`DeviceLost` 则将 `_retainedResources` 存入静态 park 列表不提前释放。- - `xcmDev_newBufferNoCopy`、`xcmDev_newBufferLen`、`xcmDev_newBufferBytes` 对 `ptr == nullptr || length == 0` 直接返回 `nil` 且不触发 `deallocator`。--### 验证(通用 `arm64 + arm64e` `dist/XnuCpuMetal.bundle`)-- `build/test_round13.mm`(`arm64` & `arm64e`,`LP_NUM_THREADS=0`):- - `PASS [1]`:`newBufferWithBytesNoCopy(NULL, 0)` / `newBufferWithLength(0)` / `newBufferWithBytes(NULL, 0)` 全返回 `nil` 且 `dealloc=0`。- - `PASS [2]`:单 CB 26 次重负载 draw 连续运行 **25.02s**(超过原 20.2s watchdog)正常完成,`0 GpuHang / 0 AccessRevoked`,`dealloced=1/1`;3 连重负载 CB(9.75s)全过。- - `PASS [hang_uaf]`(`XNU_CPU_METAL_WATCHDOG_MS=1000` 强制触发 `GpuHang` 并 park 设备):`arm64` 与 `arm64e` 均在 `llvmpipe_draw_vbo` 继续读 `mmap` 顶点缓冲期间零 `SIGSEGV`(`dealloced=0`)。-- 全量回归:`test_carenderer_arm64e`、`test_round10_arm64e`、`test_stress_mt_arm64e`(Phase 1-4 `failures=0`)、`test-bundle.sh arm64e` 全部 PASS。-------## Round 14: 锁屏 `loginwindow` → `AvatarKit` / `VFX` `MTLDevice` Selector 差集补齐--### 根因与审计-- 锁屏时 `loginwindow` 的 `AVTView` 进入 `VFX`,调用 `-[XcmBackendDevice isDepth24Stencil8PixelFormatSupported]` 抛出 `NSInvalidArgumentException` 导致 `loginwindow` 退出、会话重启。-- 对照宿主机 macOS 27 `AGXG17CDevice`(Apple M5 Max)全量扫描 `@protocol(MTLDevice)`、`@protocol(MTLDeviceSPI)` 以及 7 个框架(`VFX`、`AvatarKit`、`SceneKit`、`CoreRE`、`QuartzCore`、`RenderBox`、`CoreImage`)共 **25,589 条 `__objc_selrefs`**,发现:- - `@protocol(MTLDevice)` 缺失 3 项:`isDepth24Stencil8PixelFormatSupported`、`sparseTileSizeWithTextureType:pixelFormat:sampleCount:`、`sparseTileSizeWithTextureType:pixelFormat:sampleCount:sparsePageSize:`(3 项均被 `VFX` / `SceneKit` 引用)。- - `@protocol(MTLDeviceSPI)` 缺失 23 项(含 `newBufferWithDescriptor:`、`newVisibleFunctionTableWithDescriptor:`、`newTextureWithBytesNoCopy:length:descriptor:deallocator:`、`supportsSampleCount:`、`singleFPConfig`/`doubleFPConfig`/`halfFPConfig`、`metalAssertionsEnabled`/`setMetalAssertionsEnabled:`、`tileSizeWithSparsePageSize:...`、`newRenderPipelineStateWithTileDescriptor:*` 等)。- - 另发现 VFX 初始化查询 `maxViewportCount` 返回了 `0`(应为 `16`),`maxArgumentBufferSamplerCount` 为 `0`(应为 `16`)。--### 修复(`src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm`)-- 在 `XcmBackendDevice` 补齐上述全部 26 个 `MTLDevice` + `MTLDeviceSPI` 方法(`isDepth24Stencil8PixelFormatSupported` 按 Apple Silicon 实测返回 `NO`;`newBufferWithDescriptor:` 标 `NS_RETURNS_RETAINED` 并完整转发至 `newBuffer*`),并补齐 `maxViewportCount = 16`、`maxArgumentBufferSamplerCount = 16`、`supportsBaseVertexInstanceDrawing` / `supportsDepthClipMode` / `supportsTextureCubeArray` / `supportsNonUniformThreadgroupSize = YES`。--### 验证(通用 `arm64 + arm64e` `dist/XnuCpuMetal.bundle`)-- 新增 `build/test_round14_vfx.mm`(`arm64` & `arm64e` 均 6/6 PASS):- 1. `isDepth24Stencil8PixelFormatSupported == NO`- 2. `@protocol(MTLDevice)` + `@protocol(MTLDeviceSPI)` 对照 Apple M5 Max **0 缺失**- 3. `Depth32Float_Stencil8` 纹理创建 + 深度/模板 RenderPass 完成- 4. `SCNRenderer rendererWithDevice:dev options:nil` 正常初始化- 5. `VFXRenderer rendererWithDevice:dev options:nil` 与 `AVTView initWithFrame:options:` 正常初始化(0 `unrecognized selector`)- 6. 7 个框架(`VFX`/`AvatarKit`/`SceneKit`/`CoreRE`/`QuartzCore`/`RenderBox`/`CoreImage`)25,589 条 `__objc_selrefs` **0 缺失**-- 全量回归:`test_carenderer_arm64e`、`test_round10_arm64e`、`test_round13_arm64e`、`test-bundle.sh arm64e` 全部 PASS。-------## Round 16: 双后端 Bundle(Venus 真 GPU + lavapipe 回退)与 MoltenVK 预演--### 改动内容-1. **双 ICD 打包(`scripts/build-bundle-universal.sh`)**:- - 将宿主机编译好的 universal (`arm64 + arm64e`) `libvulkan_virtio.dylib`(默认 `/Users/admin/w/venus-darwin/out/lib/libvulkan_virtio.dylib`,可通过 `VENUS_DYLIB` 覆盖)打入 `XnuCpuMetal.bundle/Contents/Frameworks/libvulkan_virtio.dylib`,修正 `install_name` 为 `@rpath/libvulkan_virtio.dylib` 并 ad-hoc 重签。- - 同时生成 `Contents/Resources/virtio_icd.aarch64.json` 与 `Contents/Resources/vulkan/icd.d/virtio_icd.aarch64.json`(后者供 `WindowServer` 等 secure-mode 进程在忽略 `VK_ICD_FILENAMES` 时由 Vulkan-Loader 自动扫描;`metal2vulkan` 内部按 `Discrete < Integrated < Virtual < Cpu` 优先级自动优先选 Venus、无 Venus 设备时回退 lavapipe)。- - 确认 bundle 内全部 5 个 Mach-O 二进制(`XnuCpuMetal`、`libxnu_m2v.dylib`、`libvulkan.1.dylib`、`libvulkan_lvp.dylib`、`libvulkan_virtio.dylib`)均为 `arm64 + arm64e` universal fat。-2. **启动自动探测与环境变量覆盖(`src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm`)**:- - 后端选择优先级:`XNU_CPU_METAL_ICD`(指定任意自定义 ICD JSON,便于宿主机用 MoltenVK 测试)> `XNU_CPU_METAL_BACKEND=venus|lavapipe` > 自动探测 `IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("XnuDrm"))`(存在则选 Venus,否则选 lavapipe)。- - 选择 Venus 或自定义 ICD 时**跳过**所有 lavapipe 专用设置(`MESA_SHADER_CACHE_DIR`、`MESA_SHADER_CACHE_MAX_SIZE`、`LP_NUM_THREADS`);`metal2vulkan-runtime` 的 3600s CPU watchdog 补丁本就仅对 `DeviceKind::Cpu` 生效,Venus 自动保持标准 GPU watchdog(20.2s)。- - 自动探测选中 Venus 但打开失败时自动回退 lavapipe;若通过 `XNU_CPU_METAL_BACKEND=venus` 强制指定则不回退并返回 `nil`。-3. **设备名与型号(`XnuCpuMetalPlugin.mm`)**:- - `name` 直接返回 Vulkan physical device 的 `deviceName`(如 Venus 下的 `"Virtio-GPU Venus (Apple M5 Max)"`、MoltenVK 下的 `"Apple M5 Max"`、lavapipe 下的 `"llvmpipe (LLVM 22.1.8, 128 bits)"`),不再包装 `"XnuCpuMetal (...)"` 前缀。- - 同步在 `XcmBackendDevice` 上注册 `model` 与 `productName`(均返回真实 Vulkan `deviceName`)。--### 宿主机 MoltenVK(`1.4.2`, Apple M5 Max)全套测试与缺口审计-通过 `XNU_CPU_METAL_ICD=/Users/admin/.local/krunkit/Cellar/molten-vk/1.4.2/etc/vulkan/icd.d/MoltenVK_icd.json`(注:krunkit 的 `libMoltenVK.dylib` 为 `arm64`-only,而我们打包的 `libvulkan_virtio.dylib` 为 `arm64 + arm64e`)对完整测试套件进行预演,同时对比 `lavapipe`(`arm64e`):--| 测试项 | lavapipe (`arm64e`) | MoltenVK (`arm64`, Apple M5 Max) | 说明 |-|---|---|---|---|-| `test-bundle.sh` (`vecadd N=1024`) | PASS (`bad=0`) | PASS (`bad=0`) | `name` / `model` 均正确反映真实后端 |-| `test-render-ci.sh` (Render Pass) | PASS | PASS | 64×64 RGBA8 三角形完全匹配 |-| `test-render-ci.sh` (`CIGaussianBlur`) | PASS (`maxErr=1, meanErr=0.0161`) | **PASS (`maxErr=0, meanErr=0.0000, nonZeroDiff=0`)** | 与原生 Apple M5 Max 逐字节完全一致 |-| `test_round10` (Linear Tex + SharedEvent + Fence) | PASS (4/4) | PASS (4/4) | 4 种 WindowServer 线性纹理 + CPU 原地覆写全过 |-| `test_carenderer` (5 项含 `VfxXg/Xgc`) | PASS (`rounded_only=1`, `rounded_shadow=3 / 0.092`) | **PASS (`rounded_only=0`, `rounded_shadow=3 / 0.018`)** | 全部 5 项通过 |-| `test_round13` (0-len NoCopy + 2 heavy CBs) | PASS (`1.93s`, `dealloced=2/2`) | **PASS (`0.34s`, `dealloced=2/2`)** | 耗时快 5.7× |-| `test_round14_vfx` (VFX/AvatarKit/25,589 selrefs) | PASS (6/6) | PASS (6/6) | 0 missing selectors |-| `test_stress_mt` (4 阶段并发压测) | PASS (Phase 1–4 `failures=0`) | PASS (Phase 1–4 `failures=0`) | 8 线程并发 commit / CARenderer / NoCopy |-| `XNU_CPU_METAL_BACKEND=lavapipe` / `venus` | `lavapipe` PASS;宿主机无 `XnuDrm` 强选 `venus` 干净返回 `nil` (`VkResult(-3)`) | — | 环境变量覆盖与无回退语义已验证 |--**MoltenVK 非阻塞降级提示与 Venus 预期注意事项**(无功能性失败):-- `metal2vulkan-driver-pipeline-cache-kept`:驱动未暴露 `VK_KHR_pipeline_binary`(使用驱动自身管线缓存,功能等价)。-- `metal2vulkan-degrade-shadowed-texture`:宿主指针导入(`VK_EXT_external_memory_host`)的线性纹理在行距不匹配或无 `VK_EXT_image_drm_format_modifier` 时采用 shadow-image 拷贝;若托管 Venus 不暴露 `VK_EXT_external_memory_host`,`metal2vulkan` 会自动退回到 host-visible staging/copy 路径(`test_round10` 已覆盖)。-- `metal2vulkan-degrade-render-pass-split`:可编程混合(`[[color(0)]]` framebuffer fetch)在无原生 raster-order color attachment 时拆分为子 RenderPass(功能正常,仅多一次 tile flush)。-- `metal2vulkan-degrade-dont-care-store`:`Depth32Float_Stencil8` 的 `DontCare` storeOp 降级为 `STORE`(功能正常)。--### IOSurface 帧拷贝开销实测(`test/test_iosurface_bench.mm`)-在 `XcmTexture` 当前基于 `IOSurfaceLock` + `replaceRegion`/`getBytes` 的双向同步路径下,测量不同分辨率(`BGRA8Unorm`,10 轮取平均):--| 分辨率 (单帧大小) | lavapipe (`arm64e`) RenderPass+`syncToIOSurface` | lavapipe `upload+download` | MoltenVK (`Apple M5 Max`) RenderPass+`syncToIOSurface` | MoltenVK `upload+download` |-|---|---|---|---|---|-| `512×512` (1.00 MB) | `0.29 ms` (3476 MB/s) | `0.23 ms` | `0.65 ms` (1542 MB/s) | `0.37 ms` |-| `1920×1080` (7.91 MB) | `0.76 ms` (10436 MB/s) | `0.47 ms` | `1.59 ms` (4969 MB/s) | `2.37 ms` (est upload `0.78 ms`) |-| `2560×1440` (14.06 MB) | `1.12 ms` (12530 MB/s) | `0.66 ms` | `2.77 ms` (5078 MB/s) | `4.26 ms` (est upload `1.49 ms`) |--结论:在真 GPU(MoltenVK)上,1080p 单帧 `syncToIOSurface` 约 `1.59 ms`、双向约 `2.37 ms`;1440p 单帧回写约 `2.77 ms`、双向约 `4.26 ms`。托管 VM 中经 Venus(virtio-gpu 共享内存)预计在 `2–5 ms/帧` 量级,首版接入可直接复用现有 IOSurface 同步路径满足 60fps 交互基线,后续如出现高分辨率合成瓶颈再评估基于共享内存 / `VK_EXT_external_memory_host` 的零拷贝优化。-------## Round 17: 通过 `VK_LUNARG_direct_driver_loading` (`EXCLUSIVE`) 实现无环境变量、确定性单 ICD 加载(解决 `WindowServer` secure-mode 回落 lavapipe)--### 根因核实-- 核实 `metal2vulkan-runtime` 源码:`DeviceKind::preference()` 确实按 `Discrete (0) < Integrated (1) < Virtual (2) < Cpu (3) < Other (4)` 排序;但 `Device::system_default_with` 在循环尝试 `ranked()` 设备时,若首位设备失败会静默尝试下一个设备并成功返回 lavapipe,不向上层报错。-- 在 `WindowServer`(secure mode,Vulkan-Loader 忽略 `VK_ICD_FILENAMES` / `VK_DRIVER_FILES`)下,此前 `ListedExtensions::of(&entry)` 调用 `vkEnumerateInstanceExtensionProperties(NULL)` 以及 `keeper.rs` 创建 `bare_instance` 时,Loader 仍会扫描 `Resources/vulkan/icd.d/*.json` 并同时 `dlopen` `libvulkan_virtio.dylib` 与 `libvulkan_lvp.dylib`(额外占 ~196 MB 内存并初始化 llvmpipe)。--### 修复方案(`VK_LUNARG_direct_driver_loading` `EXCLUSIVE` 模式)-1. **`patches/metal2vulkan/0003-direct-driver-loading.patch`**(改 `device/{adopt,create,keeper,mod}.rs`):- - `DeviceOptions` 新增 `direct_driver_pfn: Option<usize>`(以 `usize` 透传 ObjC++ 侧 `dlsym` 获得的 `PFN_vkGetInstanceProcAddr`,完整保留 `arm64e` PAC 签名且不经 Rust 侧解引用)。- - 启用 `direct_driver_pfn` 时:`instance_of` 跳过 `ListedExtensions::of(&entry)`(不再触发 `icd.d` 扫描),直接启用 Loader 内置扩展 `VK_KHR_portability_enumeration`、`VK_EXT_debug_utils`、`VK_LUNARG_direct_driver_loading`,并将 `VkDirectDriverLoadingListLUNARG { mode: EXCLUSIVE }` 链入 `VkInstanceCreateInfo.pNext`;`keeper.rs` 在 `direct_driver == true` 时跳过额外 `bare_instance`(驱动由插件 `dlopen` 常驻,同时省去每进程多开一个 Venus DRM 上下文)。-2. **`src/xnu-m2v-bridge/`(`include/xnu_m2v.h`、`src/lib.rs`)**:- - 新增 `xm2v_device_open_direct(loader_path, direct_driver_pfn, icd_json_path, cache_dir)`,当 `direct_driver_pfn != NULL` 时完全不读写 `VK_ICD_FILENAMES` / `VK_DRIVER_FILES`。-3. **`src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm`**:- - 新增 `xcmLoadDirectDriver`:在 Clang `arm64`/`arm64e` 侧 `dlopen(..., RTLD_NOW | RTLD_LOCAL)` 并先调用 `vk_icdNegotiateLoaderICDInterfaceVersion` 校验接口版本 `>= 7`(Mesa Venus 与 lavapipe 均支持 v7;旧版如 MoltenVK 1.4.2 报 v5 自动退回 manifest 路径),再 `dlsym("vk_icdGetInstanceProcAddr")` 传给 `xm2v_device_open_direct`。- - 选 Venus 时完全不 `dlopen` `libvulkan_lvp.dylib`;若 Venus 打开失败,先通过 `os_log_error` 打出具体 `xm2v_last_error()`,仅在非强制模式下再显式打开 `libvulkan_lvp.dylib` 回退。- - 新增 `XNU_CPU_METAL_DRIVER` 支持直接指定驱动 dylib;重新打包基于 `main` `4e908b8` 的新版 universal `libvulkan_virtio.dylib`。--### 宿主机验证结果(`test/test_round17_direct_driver.mm` + 全套回归)-- **`VK_LOADER_DEBUG=all` 实测(`arm64e`)**:`libvulkan_virtio.dylib` 与 `libvulkan_lvp.dylib` 均以 PAC 签名函数指针走 `VK_DIRECT_DRIVER_LOADING_MODE_EXCLUSIVE_LUNARG`,Loader 明确日志 `skipping system and environment variable driver search mechanisms`。-- **双 ICD / 恶意环境变量 / secure-mode 模拟(6 项全 PASS)**:- 1. 设恶意 `VK_ICD_FILENAMES=lvp` + `XNU_CPU_METAL_ICD=MoltenVK` → 选中 `Apple M5 Max`,`libvulkan_lvp` 未加载(`_dyld_image_count` 校验 `loaded=0`),blit fill PASS。- 2. 双 ICD 同时可见 `lvp:MoltenVK` 与 `MoltenVK:lvp` 两种顺序 → 均选中 `Apple M5 Max`,blit fill PASS。- 3. 设恶意 `VK_ICD_FILENAMES=MoltenVK` 下默认 lavapipe(`arm64` + `arm64e`)→ 走 `EXCLUSIVE` 选中 `llvmpipe`,`libvulkan_virtio` 与 `libMoltenVK` 均 `loaded=0`,blit fill PASS。- 4. 设恶意 `VK_ICD_FILENAMES=lvp` + `XNU_CPU_METAL_BACKEND=venus`(宿主机无 `XnuDrm`)→ 干净返回 `nil` (`VkResult(-3)`),`libvulkan_lvp` `loaded=0`。- 5. 模拟 secure-mode 双 ICD bundle(`Resources/vulkan/icd.d/` 同时放 `lvp` + `MoltenVK` 且 `unset VK_ICD_FILENAMES VK_DRIVER_FILES`)→ 默认选中 `llvmpipe`(`libMoltenVK` `loaded=0`),强选 `venus` 返回 `nil`(`libvulkan_lvp` `loaded=0`)。-- **全套回归全通过**:`lavapipe (arm64e)` 与 `MoltenVK (arm64)` 的 `test-bundle.sh`、`test-render-ci.sh`、`test_round10`、`test_carenderer`、`test_round13`、`test_round14_vfx` 全部 PASS。-------## Round 18: 修复 `WindowServer` 在 Venus 下黑屏(无 `VK_EXT_external_memory_host` 时的 `newBufferWithBytesNoCopy` 回退同步)--### 根因定位(托管 macOS `WindowServer` 实时排查)-1. 在托管 macOS 中运行独立 `test_carenderer`(`Virtio-GPU Venus (Apple M5 Max)`),`color`/`image`/`two_layers`/`rounded_only`/`rounded_shadow` 5 项全部像素精确匹配原生 Apple M5 Max;12 种常见像素格式 × 3 种 usage 在 Venus 上全部创建成功。-2. 在 `WindowServer` 中增加 `newTexture` / `newRenderPSO` / `newComputePSO` / `syncToIOSurface` 诊断日志,确认:- - 0 个 `newTexture` / `newRenderPSO` / `newComputePSO` 失败;- - `syncToIOSurface` 回写 `1280×800 &BGA` (`0x26424741`) 与 `1280×30 BGRA` 全部 `ok=1`,但内容全为 `BGRA(0,0,0,255)`(`nz=1,024,000/4,096,000` 与 `38,400/153,600`);- - 唯一错误日志是 `newBufferWithBytesNoCopy` 在 Venus 上因缺少 `VK_EXT_external_memory_host` 触发拷贝回退(`Unsupported(HostMemory, needs: ExtExternalMemoryHost)`,涵盖 4 KB – 98 KB 的图元/文字/图层缓冲及 33 MB 壁纸缓冲)。-3. **直接根因**:`xcmDev_newBufferNoCopy` 回退到 `xm2v_buffer_new` 拷贝路径时,此前只在有 `deallocator` 时记录 `_fallbackPtr`(仅用于 `dealloc` 释放),**从未在后续提交 GPU 前将调用方写入 `_fallbackPtr` 的新数据同步回 Vulkan 缓冲**,导致 `WindowServer` / `QuartzCore` 通过 `newBufferWithBytesNoCopy:` + 后续写入宿主指针或 `newLinearTextureWithDescriptor:` 提交的所有画面内容均为全零/旧数据。--### 修复内容(`src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm`)-- `XcmBuffer` 在 `newBufferWithBytesNoCopy:` 回退时始终保存 `_fallbackPtr` 与 `_fallbackLen`(无论是否传 `deallocator`),并跟踪 `_contentsAccessed` 避免覆盖通过 `.contents` 写入的数据。-- 新增 `-[XcmBuffer syncFromFallbackHostMemory]`:当 `!_contentsAccessed` 时将 `_fallbackPtr` 同步到 `xm2v_buffer_contents(_handle)`(`MTLStorageModeManaged` 时同步调 `didModifyRange:`)。-- 在 `-[XcmCommandBuffer commit]` 提交前遍历 `_retainedResources` 同步所有回退 `XcmBuffer`(含 `XcmTexture->_buffer`),并在 `newTextureWithDescriptor:offset:bytesPerRow:`、`newLinearTextureWithDescriptor:...` 与 `didModifyRange:` 中同步调用。-- 保留 `newTexture` / `newTextureIOSurface` / `newRenderPSO` / `newComputePSO` / `syncToIOSurface` 的限流失败 `os_log_error`;将 `newBufferWithBytesNoCopy` 回退提示降级为每进程仅记一次 `os_log_info`。--### 验证结果-- **托管 macOS `WindowServer` on Venus**:替换新 bundle 并重启 `WindowServer` 后,`vmmap` 确认仅加载 `libvulkan_virtio.dylib`(无 `libvulkan_lvp.dylib`),帧缓冲 `/var/tmp/xnu-fb.raw` 点亮 **`1,023,982 / 1,024,000`** 像素,完整渲染出 macOS 27 登录界面(金门大桥日落壁纸、`Sun 22 Nov`、`xnu` 头像、`Enter Password` 输入框、右上角 Wi-Fi 图标)。-- **宿主机全套回归**:`lavapipe (arm64e)` 与 `MoltenVK (arm64)` 的 `test_round17_direct_driver`、`test-bundle.sh`、`test-render-ci.sh`、`test_round10`、`test_carenderer`、`test_round13`、`test_round14_vfx` 全部 PASS。-------## Round 19 (clean): YCbCr 2-plane 壁纸、`setFragmentTexture:samplerState:` SPI 与 16 字节对齐修复--### 修复内容-1. **2-plane 10-bit YCbCr IOSurface 桌面壁纸(`MTLPixelFormatYCBCR10_420_2P = 505` / `RGB10_420_2P = 543` over `'x420'`)**:- - `xnu-m2v-bridge` 新增 `xm2v_pixel_format_is_ycbcr` 与 `xm2v_buffer_new_texture_with_iosurface_ycbcr`(封装 `metal2vulkan-runtime` 的 `Buffer::new_texture_with_iosurface_plane` + `IoSurfaceYCbCr` + `IOSurfaceYCbCrMatrix`)。- - `XcmTexture` 支持 YCbCr 2-plane IOSurface 拷贝进 Shared `Xm2vBuffer` 并按 `IOSurfaceGetSeed` 刷新。- - `XcmRenderEncoder` 补齐 `CoreAnimation` 采样 YCbCr 纹理所需的合并绑定 SPI:`setFragmentTexture:atTextureIndex:samplerState:atSamplerIndex:`(含 `lodMinClamp:lodMaxClamp:` 及 vertex 变体)。-2. **线性 / IOSurface 纹理对齐修正(`64 -> 16`,匹配 Apple Silicon)**:- - `xcmDev_minLinearAlign`、`xcmDev_minTileAlign` 与 `xcmDev_align16`(用于 `iosurfaceTextureAlignmentBytes` / `linearTextureAlignmentBytes` / `deviceLinearTextureAlignmentBytes` 等)统一由 `64` 改为 **`16`**,解决 `CoreImage` 拒收 16 字节对齐中间 IOSurface 导致 `iconservicesagent` 在 `CIBlurProcessor` → `MPSImageGaussianBlur` 持续 `SIGABRT` 的问题(托管 macOS 实测崩溃数由累计 134 次降至 0 次新增;Dock 剩余 8 个 `NaturalStack` 空白格定位为 Venus 下 `VK_EXT_fragment_shader_interlock` `vkCreateGraphicsPipelines` 返回 `-3`,`newBufferWithBytesNoCopy:` 真零拷贝别名留待 Round 20)。--### 验证结果-- 新增 `test/test_round19.mm`(3/3 PASS):16 字节对齐查询、`'x420'` `YCBCR10_420_2P (505)` 采样得 `(1.000, 1.000, 1.000, 1.000)`、`CIGaussianBlur` 18 组非 64 字节对齐宽度/半径组合全部 PASS。-- 宿主机 `lavapipe (arm64e)` 与 `MoltenVK 1.4.2 (arm64)` 全套回归全部 PASS。-------## Round 20: `newBufferWithBytesNoCopy:` 真物理页零拷贝别名(`mach_vm_remap`)、`lodMinClamp:lodMaxClamp:` 透传与 IOSurface 零拷贝边界--### 设计与修改-1. **以 `mach_vm_remap` 真物理页别名取代拷贝回退补丁(零拷贝、无阻塞、无死锁)**:- - `xnu-m2v-bridge`(`include/xnu_m2v.h`、`src/lib.rs`)新增 `xm2v_buffer_new_page_aligned`:通过独立 `HeapType::Placement` 堆并在偏移 `0` 处 `new_buffer_at_offset` 分配(回退 `dev.new_buffer`),确保任意页对齐尺寸(4 KB、16 KB、128 KB、33 MB 等)的 Venus/Vulkan blob 宿主映射地址均严格按 `vm_page_size` 对齐,无需修改 `metal2vulkan`。- - `XnuCpuMetalPlugin.mm` 的 `xcmDev_newBufferNoCopy` 在无 `VK_EXT_external_memory_host` 时:分配页对齐 GPU 缓冲并一次性拷入初始内容后,校验 `pointer` / `length` / `gpuPtr` 均为 `vm_page_size` 对齐且调用方整段可写(`xcmRangeIsFullyWritable` 排除 `PROT_READ` 只读映射),调用 `mach_vm_remap(mach_task_self(), &target, length, 0, VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE, mach_task_self(), (mach_vm_address_t)gpuPtr, FALSE, &curProt, &maxProt, VM_INHERIT_NONE)` 建立真物理页别名(`_fallbackAliased = YES`)。- - 彻底移除 Round 19 中引起争议的临时补丁:`-[XcmBuffer contents]` 绝不阻塞等待 `waitUntilCompleted`(别名缓冲直接返回 `_fallbackPtr`),无 compute 4 MB 快照/逐字节比对回写循环,无每缓冲 `vm_region_64` 绕过逻辑;`syncFromFallbackHostMemory` 对 `_fallbackAliased` 为 0 拷贝空操作。- - **安全解绑(兼容 `XnuDrm::doUnmap` 立即释页)**:`-[XcmBuffer dealloc]` 在调用 `xm2v_buffer_release(_handle)` 之前先将 `_fallbackPtr` 从 Venus/GPU 页解绑——有 `_fallbackDeallocator` 时若仍可写则以 `mach_vm_allocate(VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE)` 替换为零开销惰性匿名页后再释放 GPU 缓冲并调 deallocator;无 deallocator 时用 `mach_vm_read_overwrite` 拷入临时匿名页再 `mach_vm_remap(VM_FLAGS_OVERWRITE)` 覆盖回原地址,既为调用方保留最终 GPU 写入字节,又能在调用方早于 autorelease 池释放前已 `munmap` 时安全退出不崩溃。- - 对非页对齐指针/长度或 `PROT_READ` 只读映射,干净退回原有单向初始拷贝/只读路径并记录限流 `os_log_info` 与原子统计(`-[XcmBackendDevice xcmNoCopyStats]`)。- - **已知限制**:非页对齐回退路径沿用旧 `_contentsAccessed` 语义——一旦调用方读取过 `contents`,后续不再从 `_fallbackPtr` 同步回 GPU(该路径上之后写进原始指针的数据会丢),后续可通过 `fallbackUnaligned` 计数观察实际命中频率。-2. **`lodMinClamp:lodMaxClamp:` SPI 完整接入 `metal2vulkan`**:- - `xnu-m2v-bridge` 新增 `xm2v_render_encoder_set_vertex_sampler_lod` 与 `xm2v_render_encoder_set_fragment_sampler_lod`,调用 `metal2vulkan` 的 `set_{vertex,fragment}_sampler_states(&[s], Some((&[lod_min], &[lod_max])), index)`,不再静默丢弃 LOD 夹取范围。-3. **IOSurface 零拷贝边界说明(同进程 vs 跨进程)**:- - `mach_vm_remap(VM_FLAGS_OVERWRITE)` 仅修改当前进程任务内的虚拟地址映射。对于**跨进程** `IOSurface`(如 `VTDecoderXPCService` 写入 → `WindowServer` 采样的 4K 壁纸、`WebContent` 写入 → `WindowServer` 合成的页面),消费端若用 `VM_FLAGS_OVERWRITE` 覆写 `IOSurfaceGetBaseAddress` 会断开与内核共享 IOSurface 物理页的连接,导致生产端后续写入对消费端不可见。- - 因此跨进程 `IOSurface` 保持当前基于 `IOSurfaceGetSeed` 变更触发的同步路径(仅在 seed 变化时刷新);零拷贝页别名仅用于同进程、可证明安全且满足页对齐与可写前提的 `newBufferWithBytesNoCopy:` 缓冲。--### 验证结果(`test/test_round20.mm` 7/7 全通过)-- **宿主机 `lavapipe (arm64e)`**(`XNU_CPU_METAL_FORCE_NOCOPY_FALLBACK=1`):`test_round20` **7/7 PASS**,`test_round10` / `test_carenderer` PASS。-- **宿主机 `MoltenVK 1.4.2 (arm64)`**(`XNU_CPU_METAL_FORCE_NOCOPY_FALLBACK=1`):`test_round20` **7/7 PASS**,`WKWebView`(`800×600 darkPx=6285`)与 `Maps.app` `NaturalStack`(`256×256 nz=164186`)PASS。-- **托管 macOS 实机 Venus(`Virtio-GPU Venus (Apple M5 Max)`, `vm_page_size=4096`)**:- - `test_round20_arm64e default` **7/7 PASS(`EXIT=0`)**:- - `[1/7]` 16 字节对齐查询 PASS- - `[2/7]` `'x420'` 2-plane YCbCr 采样 PASS- - `[3/7]` `CIGaussianBlur` 18 组非 64B 对齐 PASS- - `[4/7]` `mach_vm_remap` 别名(2 次)、`PROT_READ` 回退(1 次)、非页对齐回退(1 次)、0 次提交拷贝、`dealloc`(有/无 deallocator)生命周期 PASS- - `[5/7]` 8-slice 环形缓冲并发 CPU 写(slice N+1)+ GPU compute(slice N)PASS- - `[6/7]` `-[XcmBuffer contents]` 在 commit 前及 `completedHandler` 内调用均不阻塞、不死锁 PASS- - `[7/7]` 33 MB 壁纸缓冲成功别名(1 次),10 次 commit 累计 `commitSyncCopies=0, commitSyncBytes=0` PASS- - `Safari` 加载 `https://example.com` 实机渲染清晰完整(6 语种正文、工具栏、4K 金门大桥壁纸、右上角时钟、Liquid Glass Dock 均正常)。-------## Round 21:Venus+MoltenVK 底层驱动识别(`underlying_driver_id`)、全量 Dock `.icon` 渲染修复与 virglrenderer/Venus 异步管线加固--### 问题根因-1. **Dock `.icon` 全部变灰占位符(`vkCreateGraphicsPipelines` 返回 `-3`)**:- - 在托管 macOS Venus(`virglrenderer 0.10.4e` → 宿主 `MoltenVK 1.4.2`)下,物理设备上报 `driverID = VK_DRIVER_ID_MESA_VENUS (22)`、`vendorID = 0x106b`、`VK_EXT_fragment_shader_interlock = v1`。- - `metal2vulkan` 与 `metal2vulkan-runtime` 仅在 `driver_id == DriverId::MOLTENVK` 时启用 MoltenVK 编译器/运行时规避;Venus 下这些规避全部旁路,导致含 `VK_EXT_fragment_shader_interlock` 的片段着色器走 `VK_KHR_push_descriptor` 推送 set 0,触发 MoltenVK 1.4.2 SPIRV-Cross 生成 `[[texture(2), raster_order_group(0)]]`,macOS 27 `MTLCompilerService` 直接 XPC 断开并返回 `VK_ERROR_INITIALIZATION_FAILED (-3)`。-2. **启用 `PushedBufferSizesUnset` 后触发 Venus ring FATAL 与 `krunkit` 段错误**:- - 开启 `PushedBufferSizesUnset` 后 set 0 改走普通 descriptor set,首次触发 `takes_multi_variable_dynamic()`(`pipeline/objects.rs`)自检探针 `multi_variable_dynamic_creates()`,其故意编译一个 MoltenVK 1.4.2 已知会拒掉(`-3`)的多变量 `STORAGE_BUFFER_DYNAMIC` compute pipeline。- - Mesa Venus 默认在 primary ring 走异步管线创建(`vn_async_vkCreateComputePipelines`),客体直接收到假 `VK_SUCCESS` 与未注册的 handle;宿主 `virglrenderer` 因 MoltenVK 返回 `-3` 未写入 `ctx->object_table`,客体紧接着 `vkDestroyPipeline` 即触发 `[vkr] failed to look up object` → `vkDestroyPipeline resulted in CS error` → ring `VK_RING_STATUS_FATAL_BIT_MESA` → 强拆活跃 context 导致 guest `vn_relax -> abort()` 与宿主 `krunkit` 段错误。--### 设计与修改-1. **`metal2vulkan` 补丁 `patches/metal2vulkan/0004-venus-moltenvk-driver-identity.patch`**:- - 新增 `DeviceDescription::underlying_driver_id(&self) -> Option<vk::DriverId>`:保持 `driver_id` 仍为 `MESA_VENUS`(不污染日志、缓存与 Venus 专属逻辑),当 `driver_id == MESA_VENUS && vendor_id == 0x106b && extensions.contains(ExtFragmentShaderInterlock)` 时返回 `Some(DriverId::MOLTENVK)`;9 处 MoltenVK 编译器/运行时规避改查 `underlying_driver_id()`,并附 3 场景单元测试 `venus_underlying_driver_distinguishes_moltenvk_honeykrisp_and_native`(Venus+MoltenVK / Venus+Honeykrisp / 原生 MoltenVK)。- - 在 `takes_multi_variable_dynamic()` 中对 `driver_id == Some(DriverId::MESA_VENUS)` 直接返回 `false`,避免在 Venus 上运行故意失败的自检管线。-2. **宿主 `virglrenderer` 与客体 Mesa Venus 双层加固(`gpu/venus/`)**:- - `gpu/venus/virglrenderer-patches/0001-vkr-tombstone-failed-pipelines.patch`:`vkCreate{Graphics,Compute}Pipelines` 失败(整批或单项)时为失败的 client object ID 注册 `VK_NULL_HANDLE` tombstone;后续 `vkDestroyPipeline` / `vkCmdBindPipeline` 命中 tombstone 时记日志忽略,`vkr_device_object_destroy` 跳过空 handle,彻底阻断 `failed to look up object` → ring FATAL → `krunkit` 崩溃链。(已知遗留:若异步客户端忽略创建失败后仍对 tombstone 发起 `vkCmdBindPipeline` + draw,draw 会在无绑定管线状态下到达 MoltenVK;配合下方 `0003` 同步创建可使客户端拿到真实 `-3` 而不发起无效 draw。)- - `gpu/venus/patches/0003-venus-sync-pipeline-create.patch`:在 `#ifdef __APPLE__`(该 Darwin 构建的 Venus 只服务托管 macOS,宿主渲染端为 MoltenVK)下将 `vn_Create{Graphics,Compute}Pipelines` 设为同步(`want_sync = true`),确保调用方拿到宿主 MoltenVK 返回的真实 `VkResult`。--### 验证结果-- **单测**:`cargo test -p metal2vulkan venus_underlying_driver` PASS。-- **宿主本地 `virgl_test_server`(`virglrenderer 0.10.4e` + `MoltenVK 1.4.2`)对抗验证**:- - 不带 r21 跳过补丁 + 仅宿主 virglrenderer 加固 + 旧异步客户端:`CLI_RC=0`,日志记录 tombstone 与忽略 destroy,ring 未 FATAL、进程不崩。- - 不带 r21 跳过补丁 + 宿主 virglrenderer 加固 + `0003` 同步 Venus 客户端:`CLI_RC=0`,探针拿到 `-3` 走回退路径,`Maps.app` 正常渲染 `CGImage 256x256 nz=164566/262144 center=(0,132,248,255)`。- - 带完整 r21 补丁:`repro_maps_r21_arm64e` PASS、`test_all_dock_icons` 16/16 与原生 M5 Max Metal 逐项一致、`test_round20_arm64e` 7/7 PASS。-- **托管 macOS 实机 Venus(单核 + 加固版 `libvirglrenderer`)**:- - Step 1(`/tmp` + `DYLD_INSERT_LIBRARIES`,未改 `/Library/GPUBundles`):`repro_maps_r21_arm64e` `EXIT=0`(`center=(0,132,248,255)`)、`test_round20_arm64e` **7/7 PASS**、`test_all_dock_icons` **16/16 PASS**。- - Step 2(清图标缓存 + 重启 `iconservices*`/`Dock` 抓取同尺寸 1280×800 前后对照图,测完立即恢复 `/Library/GPUBundles` 为 clean r20 `952f34e9...`):**改前 r20 Dock 19/19 应用图标全灰占位符 → 改后 r21 Dock 19/19 应用图标全部清晰完整渲染**(Finder、Apps、Safari、Messages、Mail、Maps、Photos、FaceTime、Phone、Calendar、Contacts、Reminders、Notes、Apple TV、Music、Games、App Store、iPhone Mirroring、System Settings + Liquid Glass 栏)。- - 整个实机测试期间宿主 `krunkit.log` **0 条新增行**(0 tombstone、0 `vkr` CS 错误、0 崩溃)。diff --git a/gpu/xnu-cpu-metal/scripts/build-bundle-universal.sh b/gpu/xnu-cpu-metal/scripts/build-bundle-universal.shindex b364c52..0e5d51c 100755--- a/gpu/xnu-cpu-metal/scripts/build-bundle-universal.sh+++ b/gpu/xnu-cpu-metal/scripts/build-bundle-universal.sh@@ -1,4 +1,5 @@#!/usr/bin/env bash+# SPDX-License-Identifier: GPL-2.0-or-laterset -euo pipefailROOT="$(cd "$(dirname "$0")/.." && pwd)"@@ -27,7 +28,7 @@ lipo -create \"$ROOT/dist/lavapipe-arm64e/lib/libvulkan_lvp.dylib" \-output "$BUNDLE/Contents/Frameworks/libvulkan_lvp.dylib"-VENUS_DYLIB="${VENUS_DYLIB:-/Users/admin/w/venus-darwin/out/lib/libvulkan_virtio.dylib}"+VENUS_DYLIB="${VENUS_DYLIB:-$HOME/w/venus-darwin/out/lib/libvulkan_virtio.dylib}" # gpu/venus/build-darwin.sh outputHAS_VENUS=0if [ -f "$VENUS_DYLIB" ]; thencp -f "$VENUS_DYLIB" "$BUNDLE/Contents/Frameworks/libvulkan_virtio.dylib"diff --git a/gpu/xnu-cpu-metal/scripts/build-bundle.sh b/gpu/xnu-cpu-metal/scripts/build-bundle.shindex ca7c22b..78641dd 100755--- a/gpu/xnu-cpu-metal/scripts/build-bundle.sh+++ b/gpu/xnu-cpu-metal/scripts/build-bundle.sh@@ -1,4 +1,5 @@#!/usr/bin/env bash+# SPDX-License-Identifier: GPL-2.0-or-laterset -euo pipefailROOT="$(cd "$(dirname "$0")/.." && pwd)"diff --git a/gpu/xnu-cpu-metal/scripts/build-lavapipe-arm64e.sh b/gpu/xnu-cpu-metal/scripts/build-lavapipe-arm64e.shindex 6086777..e0595b7 100755--- a/gpu/xnu-cpu-metal/scripts/build-lavapipe-arm64e.sh+++ b/gpu/xnu-cpu-metal/scripts/build-lavapipe-arm64e.sh@@ -1,4 +1,5 @@#!/usr/bin/env bash+# SPDX-License-Identifier: GPL-2.0-or-laterset -euo pipefailROOT="$(cd "$(dirname "$0")/.." && pwd)"diff --git a/gpu/xnu-cpu-metal/scripts/build-lavapipe.sh b/gpu/xnu-cpu-metal/scripts/build-lavapipe.shindex 571a23d..c1b2285 100755--- a/gpu/xnu-cpu-metal/scripts/build-lavapipe.sh+++ b/gpu/xnu-cpu-metal/scripts/build-lavapipe.sh@@ -1,4 +1,5 @@#!/usr/bin/env bash+# SPDX-License-Identifier: GPL-2.0-or-laterset -euo pipefailROOT="$(cd "$(dirname "$0")/.." && pwd)"diff --git a/gpu/xnu-cpu-metal/scripts/build-llvm-arm64e.sh b/gpu/xnu-cpu-metal/scripts/build-llvm-arm64e.shindex c0ac9d0..49f309a 100755--- a/gpu/xnu-cpu-metal/scripts/build-llvm-arm64e.sh+++ b/gpu/xnu-cpu-metal/scripts/build-llvm-arm64e.sh@@ -1,4 +1,5 @@#!/usr/bin/env bash+# SPDX-License-Identifier: GPL-2.0-or-laterset -euo pipefailROOT="$(cd "$(dirname "$0")/.." && pwd)"diff --git a/gpu/xnu-cpu-metal/scripts/build-m2v-arm64e.sh b/gpu/xnu-cpu-metal/scripts/build-m2v-arm64e.shindex c3e87a6..34ef851 100755--- a/gpu/xnu-cpu-metal/scripts/build-m2v-arm64e.sh+++ b/gpu/xnu-cpu-metal/scripts/build-m2v-arm64e.sh@@ -1,4 +1,5 @@#!/usr/bin/env bash+# SPDX-License-Identifier: GPL-2.0-or-laterset -euo pipefailROOT="$(cd "$(dirname "$0")/.." && pwd)"diff --git a/gpu/xnu-cpu-metal/scripts/build-m2v.sh b/gpu/xnu-cpu-metal/scripts/build-m2v.shindex 50d4b2f..d25d7ec 100755--- a/gpu/xnu-cpu-metal/scripts/build-m2v.sh+++ b/gpu/xnu-cpu-metal/scripts/build-m2v.sh@@ -1,4 +1,5 @@#!/usr/bin/env bash+# SPDX-License-Identifier: GPL-2.0-or-laterset -euo pipefailROOT="$(cd "$(dirname "$0")/.." && pwd)"diff --git a/gpu/xnu-cpu-metal/scripts/build-vkloader-arm64e.sh b/gpu/xnu-cpu-metal/scripts/build-vkloader-arm64e.shindex 5e6332b..a70de8a 100755--- a/gpu/xnu-cpu-metal/scripts/build-vkloader-arm64e.sh+++ b/gpu/xnu-cpu-metal/scripts/build-vkloader-arm64e.sh@@ -1,4 +1,5 @@#!/usr/bin/env bash+# SPDX-License-Identifier: GPL-2.0-or-laterset -euo pipefailROOT="$(cd "$(dirname "$0")/.." && pwd)"diff --git a/gpu/xnu-cpu-metal/scripts/fetch-sources.sh b/gpu/xnu-cpu-metal/scripts/fetch-sources.shindex 8582ffd..49095b0 100755--- a/gpu/xnu-cpu-metal/scripts/fetch-sources.sh+++ b/gpu/xnu-cpu-metal/scripts/fetch-sources.sh@@ -1,4 +1,5 @@#!/usr/bin/env bash+# SPDX-License-Identifier: GPL-2.0-or-later# Fetch the upstream sources the plugin builds against into src/ (never committed: see ../README.md),# then apply our local patches from patches/<project>/*.patch idempotently.set -euo pipefaildiff --git a/gpu/xnu-cpu-metal/scripts/mesa-arm64e-jit-pac.note b/gpu/xnu-cpu-metal/scripts/mesa-arm64e-jit-pac.noteindex 0fccbd6..3a95941 100644--- a/gpu/xnu-cpu-metal/scripts/mesa-arm64e-jit-pac.note+++ b/gpu/xnu-cpu-metal/scripts/mesa-arm64e-jit-pac.note@@ -1,3 +1,4 @@+# SPDX-License-Identifier: GPL-2.0-or-later# Patches applied to Mesa 26.3.1 for arm64e macOS PAC compatibility in gallivm JIT:## 1. C -> JIT indirect calls (sign unsigned JIT code pointer for arm64e blraaz):diff --git a/gpu/xnu-cpu-metal/scripts/rust-pac-rewrite.py b/gpu/xnu-cpu-metal/scripts/rust-pac-rewrite.pyindex 5d34cab..d88328a 100755--- a/gpu/xnu-cpu-metal/scripts/rust-pac-rewrite.py+++ b/gpu/xnu-cpu-metal/scripts/rust-pac-rewrite.py@@ -1,4 +1,5 @@#!/usr/bin/env python3+# SPDX-License-Identifier: GPL-2.0-or-later"""Rewrite plain ARM64 `blr Xn` / `br Xn` (n=0..29) in a linked arm64e Rust Mach-O dylibinto `bl _nmb_pac_call_xN` / `b _nmb_pac_call_xN` trampolines (from RustPacBoundary.c),skipping the trampolines themselves and RustPacBoundary's own C functions."""diff --git a/gpu/xnu-cpu-metal/scripts/test-bundle.sh b/gpu/xnu-cpu-metal/scripts/test-bundle.shindex 1efb420..af91ea1 100755--- a/gpu/xnu-cpu-metal/scripts/test-bundle.sh+++ b/gpu/xnu-cpu-metal/scripts/test-bundle.sh@@ -1,4 +1,5 @@#!/usr/bin/env bash+# SPDX-License-Identifier: GPL-2.0-or-laterset -euo pipefailROOT="$(cd "$(dirname "$0")/.." && pwd)"diff --git a/gpu/xnu-cpu-metal/scripts/test-lavapipe.sh b/gpu/xnu-cpu-metal/scripts/test-lavapipe.shindex 3e5a2fa..8f4eb4f 100755--- a/gpu/xnu-cpu-metal/scripts/test-lavapipe.sh+++ b/gpu/xnu-cpu-metal/scripts/test-lavapipe.sh@@ -1,4 +1,5 @@#!/usr/bin/env bash+# SPDX-License-Identifier: GPL-2.0-or-laterset -euo pipefailROOT="$(cd "$(dirname "$0")/.." && pwd)"diff --git a/gpu/xnu-cpu-metal/scripts/test-m2v.sh b/gpu/xnu-cpu-metal/scripts/test-m2v.shindex 1fb1bcc..bdbc222 100755--- a/gpu/xnu-cpu-metal/scripts/test-m2v.sh+++ b/gpu/xnu-cpu-metal/scripts/test-m2v.sh@@ -1,4 +1,5 @@#!/usr/bin/env bash+# SPDX-License-Identifier: GPL-2.0-or-laterset -euo pipefailROOT="$(cd "$(dirname "$0")/.." && pwd)"diff --git a/gpu/xnu-cpu-metal/scripts/test-render-ci.sh b/gpu/xnu-cpu-metal/scripts/test-render-ci.shindex 0781040..f5f7ebf 100755--- a/gpu/xnu-cpu-metal/scripts/test-render-ci.sh+++ b/gpu/xnu-cpu-metal/scripts/test-render-ci.sh@@ -1,4 +1,5 @@#!/usr/bin/env bash+# SPDX-License-Identifier: GPL-2.0-or-laterset -euo pipefailROOT="$(cd "$(dirname "$0")/.." && pwd)"diff --git a/gpu/xnu-cpu-metal/src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm b/gpu/xnu-cpu-metal/src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mmindex 9cc68e5..6bb3650 100644--- a/gpu/xnu-cpu-metal/src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm+++ b/gpu/xnu-cpu-metal/src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm@@ -1,3 +1,4 @@+// SPDX-License-Identifier: GPL-2.0-or-later#include <objc/message.h>// XnuCpuMetal.bundle — Pure-CPU Metal plugin for xnulinux (macOS 27).// Principal class: XnuCpuMetalDevice (subclass of IOGPUMetalDevice).diff --git a/gpu/xnu-cpu-metal/src/xnu-cpu-metal-bundle/XnuCpuMetalShim.h b/gpu/xnu-cpu-metal/src/xnu-cpu-metal-bundle/XnuCpuMetalShim.hindex 03432a2..b83b8b0 100644--- a/gpu/xnu-cpu-metal/src/xnu-cpu-metal-bundle/XnuCpuMetalShim.h+++ b/gpu/xnu-cpu-metal/src/xnu-cpu-metal-bundle/XnuCpuMetalShim.h@@ -1,3 +1,4 @@+// SPDX-License-Identifier: BSD-2-Clause-Patent// Adapted from UniXNU/AdrenoMetal's IOGPUMetalDeviceShim.h (BSD-2-Clause-Patent).// Installs macOS IOGPUMetalDevice compatibility selectors and Metal protocol conformances// on the dynamically created _MTLDevice subclass and Xcm* frontend classes.diff --git a/gpu/xnu-cpu-metal/src/xnu-m2v-bridge/Cargo.toml b/gpu/xnu-cpu-metal/src/xnu-m2v-bridge/Cargo.tomlindex 5eb2127..92ef0fa 100644--- a/gpu/xnu-cpu-metal/src/xnu-m2v-bridge/Cargo.toml+++ b/gpu/xnu-cpu-metal/src/xnu-m2v-bridge/Cargo.toml@@ -1,3 +1,4 @@+# SPDX-License-Identifier: GPL-2.0-or-later[package]name = "xnu-m2v-bridge"version = "0.1.0"diff --git a/gpu/xnu-cpu-metal/src/xnu-m2v-bridge/include/xnu_m2v.h b/gpu/xnu-cpu-metal/src/xnu-m2v-bridge/include/xnu_m2v.hindex c1f13b5..c777466 100644--- a/gpu/xnu-cpu-metal/src/xnu-m2v-bridge/include/xnu_m2v.h+++ b/gpu/xnu-cpu-metal/src/xnu-m2v-bridge/include/xnu_m2v.h@@ -1,3 +1,4 @@+// SPDX-License-Identifier: GPL-2.0-or-later#ifndef XNU_M2V_H#define XNU_M2V_Hdiff --git a/gpu/xnu-cpu-metal/src/xnu-m2v-bridge/src/lib.rs b/gpu/xnu-cpu-metal/src/xnu-m2v-bridge/src/lib.rsindex 9e6c3d9..defb88e 100644--- a/gpu/xnu-cpu-metal/src/xnu-m2v-bridge/src/lib.rs+++ b/gpu/xnu-cpu-metal/src/xnu-m2v-bridge/src/lib.rs@@ -1,3 +1,4 @@+// SPDX-License-Identifier: GPL-2.0-or-later//! C ABI bridge over `metal2vulkan` and `metal2vulkan-runtime` for xnulinux CPU Metal.use metal2vulkan::bind::SamplerDescriptor;diff --git a/gpu/xnu-cpu-metal/test/test_bundle.mm b/gpu/xnu-cpu-metal/test/test_bundle.mmindex befa543..b3bf9ad 100644--- a/gpu/xnu-cpu-metal/test/test_bundle.mm+++ b/gpu/xnu-cpu-metal/test/test_bundle.mm@@ -1,3 +1,4 @@+// SPDX-License-Identifier: GPL-2.0-or-later#import <Foundation/Foundation.h>#import <Metal/Metal.h>#import <objc/runtime.h>diff --git a/gpu/xnu-cpu-metal/test/test_carenderer.mm b/gpu/xnu-cpu-metal/test/test_carenderer.mmindex 6e9eb4e..f73cd6e 100644--- a/gpu/xnu-cpu-metal/test/test_carenderer.mm+++ b/gpu/xnu-cpu-metal/test/test_carenderer.mm@@ -1,3 +1,4 @@+// SPDX-License-Identifier: GPL-2.0-or-later#import <Foundation/Foundation.h>#import <Metal/Metal.h>#import <QuartzCore/QuartzCore.h>diff --git a/gpu/xnu-cpu-metal/test/test_iosurface_bench.mm b/gpu/xnu-cpu-metal/test/test_iosurface_bench.mmindex ad99716..6f53bf6 100644--- a/gpu/xnu-cpu-metal/test/test_iosurface_bench.mm+++ b/gpu/xnu-cpu-metal/test/test_iosurface_bench.mm@@ -1,3 +1,4 @@+// SPDX-License-Identifier: GPL-2.0-or-later#import <Foundation/Foundation.h>#import <Metal/Metal.h>#import <IOSurface/IOSurface.h>diff --git a/gpu/xnu-cpu-metal/test/test_render_ci.mm b/gpu/xnu-cpu-metal/test/test_render_ci.mmindex 6490211..5574983 100644--- a/gpu/xnu-cpu-metal/test/test_render_ci.mm+++ b/gpu/xnu-cpu-metal/test/test_render_ci.mm@@ -1,3 +1,4 @@+// SPDX-License-Identifier: GPL-2.0-or-later#import <Foundation/Foundation.h>#import <Metal/Metal.h>#import <CoreImage/CoreImage.h>diff --git a/gpu/xnu-cpu-metal/test/test_round10.mm b/gpu/xnu-cpu-metal/test/test_round10.mmindex e1314f2..53ec023 100644--- a/gpu/xnu-cpu-metal/test/test_round10.mm+++ b/gpu/xnu-cpu-metal/test/test_round10.mm@@ -1,3 +1,4 @@+// SPDX-License-Identifier: GPL-2.0-or-later#import <Foundation/Foundation.h>#import <Metal/Metal.h>#import <IOSurface/IOSurface.h>diff --git a/gpu/xnu-cpu-metal/test/test_round13.mm b/gpu/xnu-cpu-metal/test/test_round13.mmindex bcfe28b..5fdc7f1 100644--- a/gpu/xnu-cpu-metal/test/test_round13.mm+++ b/gpu/xnu-cpu-metal/test/test_round13.mm@@ -1,3 +1,4 @@+// SPDX-License-Identifier: GPL-2.0-or-later#import <Foundation/Foundation.h>#import <Metal/Metal.h>#include <atomic>diff --git a/gpu/xnu-cpu-metal/test/test_round14_vfx.mm b/gpu/xnu-cpu-metal/test/test_round14_vfx.mmindex ec6c53c..8c24c9a 100644--- a/gpu/xnu-cpu-metal/test/test_round14_vfx.mm+++ b/gpu/xnu-cpu-metal/test/test_round14_vfx.mm@@ -1,3 +1,4 @@+// SPDX-License-Identifier: GPL-2.0-or-later#import <Foundation/Foundation.h>#import <Metal/Metal.h>#import <IOKit/IOKitLib.h>diff --git a/gpu/xnu-cpu-metal/test/test_round17_direct_driver.mm b/gpu/xnu-cpu-metal/test/test_round17_direct_driver.mmindex 64b47d9..dd77b1a 100644--- a/gpu/xnu-cpu-metal/test/test_round17_direct_driver.mm+++ b/gpu/xnu-cpu-metal/test/test_round17_direct_driver.mm@@ -1,3 +1,4 @@+// SPDX-License-Identifier: GPL-2.0-or-later// Round 17 verification: deterministic direct driver loading (VK_LUNARG_direct_driver_loading)// Verifies:// 1. Selected backend loads ONLY its own driver dylib (unused ICDs in icd.d are never dlopen'd).diff --git a/gpu/xnu-cpu-metal/test/test_round19.mm b/gpu/xnu-cpu-metal/test/test_round19.mmindex 9c68a3d..76a1179 100644--- a/gpu/xnu-cpu-metal/test/test_round19.mm+++ b/gpu/xnu-cpu-metal/test/test_round19.mm@@ -1,3 +1,4 @@+// SPDX-License-Identifier: GPL-2.0-or-later// Round 19 regression test (non-fallback fixes):// 1. MTLDevice linear/IOSurface texture alignment queries return 16 (matching Apple Silicon).// 2. 2-plane 10-bit YCbCr IOSurface ('x420') -> MTLPixelFormatYCBCR10_420_2P (505) texture creation + shader sampling.diff --git a/gpu/xnu-cpu-metal/test/test_round20.mm b/gpu/xnu-cpu-metal/test/test_round20.mmindex eda576b..8f7e767 100644--- a/gpu/xnu-cpu-metal/test/test_round20.mm+++ b/gpu/xnu-cpu-metal/test/test_round20.mm@@ -1,3 +1,4 @@+// SPDX-License-Identifier: GPL-2.0-or-later// Round 20 regression test:// Preserves all Round 19 assertions (1-3) + verifies true mach_vm_remap physical-page aliasing (4-7):// 1. 16-byte linear/IOSurface texture alignment queries.diff --git a/gpu/xnu-cpu-metal/test/test_stress_mt.mm b/gpu/xnu-cpu-metal/test/test_stress_mt.mmindex d0ee2d6..ff20172 100644--- a/gpu/xnu-cpu-metal/test/test_stress_mt.mm+++ b/gpu/xnu-cpu-metal/test/test_stress_mt.mm@@ -1,3 +1,4 @@+// SPDX-License-Identifier: GPL-2.0-or-later#import <Foundation/Foundation.h>#import <Metal/Metal.h>#import <IOSurface/IOSurface.h>diff --git a/gpu/xnu-cpu-metal/test/tri.metal b/gpu/xnu-cpu-metal/test/tri.metalindex 1e3036e..3f71b19 100644--- a/gpu/xnu-cpu-metal/test/tri.metal+++ b/gpu/xnu-cpu-metal/test/tri.metal@@ -1,3 +1,4 @@+// SPDX-License-Identifier: GPL-2.0-or-later#include <metal_stdlib>using namespace metal;diff --git a/gpu/xnu-cpu-metal/test/vecadd.metal b/gpu/xnu-cpu-metal/test/vecadd.metalindex caab01d..43f0727 100644--- a/gpu/xnu-cpu-metal/test/vecadd.metal+++ b/gpu/xnu-cpu-metal/test/vecadd.metal@@ -1,3 +1,4 @@+// SPDX-License-Identifier: GPL-2.0-or-later#include <metal_stdlib>using namespace metal;diff --git a/gpu/xnu-drm/Makefile b/gpu/xnu-drm/Makefileindex 0784ca8..437a021 100644--- a/gpu/xnu-drm/Makefile+++ b/gpu/xnu-drm/Makefile@@ -1,3 +1,4 @@+# SPDX-License-Identifier: GPL-2.0-only# The Linux end (xnudrmd); the macOS ends are kexts/XnuDrm and darwin/ (libxnudrm, built with Mesa).CFLAGS ?= -O2 -Wall -Wextra -Wno-unused-parameterxnudrmd: xnudrmd.c xnudrm_proto.hdiff --git a/gpu/xnu-drm/xnudrmd.c b/gpu/xnu-drm/xnudrmd.cindex 8c52cee..97772c1 100644--- a/gpu/xnu-drm/xnudrmd.c+++ b/gpu/xnu-drm/xnudrmd.c@@ -1,4 +1,4 @@-// SPDX-License-Identifier: MIT+// SPDX-License-Identifier: GPL-2.0-only/** xnudrmd: the Linux end of the DRM bridge. It serves the hosted macOS's GPU clients (kexts/XnuDrm, libxnudrm) from* Linux's virtio-gpu render node: each request comes as a host call on /dev/xnu-hostcall (fki), is carried out with andiff --git a/kexts/XnuCPU/XnuCPU.cpp b/kexts/XnuCPU/XnuCPU.cppindex 6c2245e..3999f36 100644--- a/kexts/XnuCPU/XnuCPU.cpp+++ b/kexts/XnuCPU/XnuCPU.cpp@@ -1,4 +1,4 @@-// SPDX-License-Identifier: BSD-2-Clause+// SPDX-License-Identifier: APSL-2.0// XnuCPU: the hosted system's CPUs, one IOCPU per /cpus/cpuN node xnu.ko describes (compatible "xnulinux,cpu").//// On a Mac the platform's CPU driver registers each CPU with the kernel (ml_processor_register) and starts and signalsdiff --git a/kexts/XnuCpuMetal/XnuCpuMetal.cpp b/kexts/XnuCpuMetal/XnuCpuMetal.cppindex a1cdc4c..2b5ac4a 100644--- a/kexts/XnuCpuMetal/XnuCpuMetal.cpp+++ b/kexts/XnuCpuMetal/XnuCpuMetal.cpp@@ -1,4 +1,4 @@-// SPDX-License-Identifier: BSD-2-Clause+// SPDX-License-Identifier: APSL-2.0// XnuCpuMetal: the hosted macOS's Metal device, as a kext of the kernel collection (written for xnulinux, clean room).// Metal.framework finds GPUs by watching IOServiceMatching("IOAccelerator") and loads the plugin bundle named by the service's// MetalPluginName from /Library/GPUBundles, taking MetalPluginClassName (an IOGPUMetalDevice subclass) as the device class.diff --git a/kexts/XnuDisk/XnuDisk.cpp b/kexts/XnuDisk/XnuDisk.cppindex 8fe36fb..d9d1c62 100644--- a/kexts/XnuDisk/XnuDisk.cpp+++ b/kexts/XnuDisk/XnuDisk.cpp@@ -1,3 +1,4 @@+// SPDX-License-Identifier: APSL-2.0// XnuDisk: the hosted macOS's internal disk, a block storage device whose blocks are a file on the Linux side.//// The file is a whole disk as macOS makes one: a GUID partition table and an APFS container (System and Data volumes),diff --git a/kexts/XnuDisplay/IOMobileFramebufferABI.h b/kexts/XnuDisplay/IOMobileFramebufferABI.hindex 435da35..d2b7756 100644--- a/kexts/XnuDisplay/IOMobileFramebufferABI.h+++ b/kexts/XnuDisplay/IOMobileFramebufferABI.h@@ -1,4 +1,5 @@-// Generated by scripts/gen-iomfb-abi.py from the IOMobileFramebuffer classes of the macOS 26.5 kernelcache (vma2). Do not edit.+// SPDX-License-Identifier: BSD-2-Clause-Patent+// From macOS-DroidVM (overlay/kext/DroidVMDisplay), generated there by its scripts/gen-iomfb-abi.py from the IOMobileFramebuffer classes of the macOS 26.5 kernelcache (vma2). Do not edit.// Slot numbers and PAC diversities are the kernelcache's; return types are IOReturn where the mangled name says nothing.#pragma once#include <IOKit/IOService.h>diff --git a/kexts/XnuDrm/XnuDrm.cpp b/kexts/XnuDrm/XnuDrm.cppindex 4c8a08f..21cdb97 100644--- a/kexts/XnuDrm/XnuDrm.cpp+++ b/kexts/XnuDrm/XnuDrm.cpp@@ -1,4 +1,4 @@-// SPDX-License-Identifier: BSD-2-Clause+// SPDX-License-Identifier: APSL-2.0// XnuDrm: the hosted macOS's door to the Linux host's GPU (the DRM bridge, gpu/xnu-drm). A process opens a user client// (libxnudrm, inside Mesa's Venus driver); each of its requests is one host call (linux64_hostcall: LINUX64_CALL_HOSTCALL, xnu.ko,// fki) answered by xnudrmd, the Linux service that owns the DRM render node. Buffer mappings come back as the physicaldiff --git a/kexts/XnuEAN/XnuEAN.cpp b/kexts/XnuEAN/XnuEAN.cppindex f02b053..d034df7 100644--- a/kexts/XnuEAN/XnuEAN.cpp+++ b/kexts/XnuEAN/XnuEAN.cpp@@ -1,3 +1,4 @@+// SPDX-License-Identifier: APSL-2.0// XnuEAN: the EAN of the hosted macOS, the small keyed store the Secure Enclave's replacement on Apple's virtual platform keeps// its xART in.//diff --git a/scripts/build-host.sh b/scripts/build-host.shindex 6c32f35..2faaf98 100755--- a/scripts/build-host.sh+++ b/scripts/build-host.sh@@ -1,7 +1,8 @@#!/bin/bash+# SPDX-License-Identifier: GPL-2.0-only# Build the arm64 host Linux (4K pages like the UniXNU 4K XNU machine layer, 48-bit VA, user PAC) with the FKI patch, plus a busybox initramfs.set -euo pipefail-P=$(cd "$(dirname "$0")/.." && pwd); W=${W:-/data/station/remote/sessions/bb931bdb925f109d18e36b92ae3422802e35c0a46561ce911a41789790c989b6/work}; L=$W/src/linux; O=$W/out/linux; mkdir -p $O+P=$(cd "$(dirname "$0")/.." && pwd); W=${W:?W: a work directory holding src/linux (a Linux tree); the build goes to $W/out/linux}; L=$W/src/linux; O=$W/out/linux; mkdir -p $Ocd $Lgit checkout -q -- drivers/Kconfig drivers/Makefilersync -a $P/linux/ ./diff --git a/scripts/console-send-file.sh b/scripts/console-send-file.shindex a41f1a0..85d3a6c 100755--- a/scripts/console-send-file.sh+++ b/scripts/console-send-file.sh@@ -1,4 +1,5 @@#!/bin/bash+# SPDX-License-Identifier: GPL-2.0-only# console-send-file.sh LOCAL REMOTE: types LOCAL into the hosted macOS console shell as short base64 lines (one every# 0.3 s, so the tty input queue never overflows: one long typed line gets mangled by the line editor), decoded to REMOTE.cd "$(dirname "$0")/.."diff --git a/scripts/extract-trustcache.py b/scripts/extract-trustcache.pyindex d8a40fb..6b652ff 100755--- a/scripts/extract-trustcache.py+++ b/scripts/extract-trustcache.py@@ -1,4 +1,5 @@#!/usr/bin/env python3+# SPDX-License-Identifier: GPL-2.0-only"""Write the raw static trust cache module of this Mac's OS (the payload of StaticTrustCache.img4) to OUT.extract-trustcache.py OUT [PREBOOT]diff --git a/scripts/install-krun-agent.sh b/scripts/install-krun-agent.shindex ac314ec..905accb 100755--- a/scripts/install-krun-agent.sh+++ b/scripts/install-krun-agent.sh@@ -1,4 +1,5 @@#!/bin/bash+# SPDX-License-Identifier: GPL-2.0-only# On the Mac host: keep the Linux VM running under krunkit as a launchd agent of this user. krunkit exits when the guest# reboots or powers off; launchd starts it again (KeepAlive), and at login (RunAtLoad). With the hosted macOS as a service# in the VM (scripts/install-service.sh) a reboot of either comes back by itself.diff --git a/scripts/install-service.sh b/scripts/install-service.shindex aa2e54a..7c0dc73 100755--- a/scripts/install-service.sh+++ b/scripts/install-service.sh@@ -1,4 +1,5 @@#!/bin/bash+# SPDX-License-Identifier: GPL-2.0-only# In the VM (once, after scripts/vm-install-fki-service.sh and with the disk from scripts/mk-macvm-disk.sh): run the hosted# macOS as a system service. It starts at boot, is stopped cleanly (its disk synced) when the VM shuts down, and is# started again after a panic or a run that ended by itself; each run's kernel log is in /var/log/xnulinux/.diff --git a/scripts/kc-amfi-platform.py b/scripts/kc-amfi-platform.pyindex 1945df7..42b6c93 100644--- a/scripts/kc-amfi-platform.py+++ b/scripts/kc-amfi-platform.py@@ -1,4 +1,5 @@#!/usr/bin/env python3+# SPDX-License-Identifier: GPL-2.0-only"""Set the lowest code-signature platform version AMFI accepts in a built kernel collection (in place).The hosted kernel links Apple's kexts from one macOS build (the collection) while the system disk can be another: AMFIdiff --git a/scripts/krun-vm.sh b/scripts/krun-vm.shindex 4dba34b..3bede5e 100644--- a/scripts/krun-vm.sh+++ b/scripts/krun-vm.sh@@ -1,4 +1,5 @@#!/bin/bash+# SPDX-License-Identifier: GPL-2.0-only# On the Mac host: run the xnupoc Linux VM under krunkit (libkrun on Hypervisor.framework) instead of tart, for a GPU the# guest can use: krunkit gives Linux a virtio-gpu with Venus (Vulkan commands forwarded to virglrenderer, then MoltenVK and# Metal on the host GPU). The VM's disk is tart's own (stop tart first; both never run at once). Networking is gvproxydiff --git a/scripts/mk-macvm-disk.sh b/scripts/mk-macvm-disk.shindex bc3930d..1865054 100755--- a/scripts/mk-macvm-disk.sh+++ b/scripts/mk-macvm-disk.sh@@ -1,5 +1,6 @@#!/bin/bash-# On the macOS host (tokyo): the hosted system's disk from a macOS VM disk installed by Apple's own installer, then sent to+# SPDX-License-Identifier: GPL-2.0-only+# On the macOS host: the hosted system's disk from a macOS VM disk installed by Apple's own installer, then sent to# the xnupoc VM as /var/tmp/mac.img (xnu.ko disk=, kexts/XnuDisk; boot-arg rd=<its system volume>).## `tart create NAME --from-ipsw latest` installs macOS with Virtualization.framework, as Apple's own VMs are installed: the@@ -15,7 +16,7 @@ set -euo pipefailcd "$(dirname "$0")/.."V="bash scripts/vm.sh"SRC=${SRC:-$HOME/.tart/vms/xnumac/disk.img}; W=${W:-$PWD/../macvm}; IMG=$W/mac.img-GPU=${GPU:-/Users/admin/.stillfail/sessions/chat/c-73ef26e7b6/workspace/src/xnulinux/gpu/xnu-cpu-metal/dist/XnuCpuMetal.bundle}+GPU=${GPU:-$PWD/gpu/xnu-cpu-metal/dist/XnuCpuMetal.bundle}DISABLE="com.apple.watchdogd com.apple.iomfb_bics_daemon com.apple.audiomxd com.apple.audio.coreaudiod com.apple.PerfPowerServicescom.apple.PerfPowerServicesExtended com.apple.oahd com.apple.oahd-root-helper ${DISABLE:-}"# images of ours left attached by an earlier rundiff --git a/scripts/serial-pty.py b/scripts/serial-pty.pyindex 8041171..7919a22 100644--- a/scripts/serial-pty.py+++ b/scripts/serial-pty.py@@ -1,4 +1,5 @@#!/usr/bin/env python3+# SPDX-License-Identifier: GPL-2.0-only# On the Mac host: create a pty for `tart run --serial-path`, write its name to argv[1] and append# everything the guest writes to its console to argv[2]. Output survives a guest hang.import os, sys, ttydiff --git a/scripts/vm-dmesg-shell.sh b/scripts/vm-dmesg-shell.shindex 20f9693..20819a0 100755--- a/scripts/vm-dmesg-shell.sh+++ b/scripts/vm-dmesg-shell.sh@@ -1,5 +1,6 @@#!/bin/bash-# On tokyo: talk to the hosted macOS shell through the VM. XNU's output is read from the kernel ring buffer (dmesg,+# SPDX-License-Identifier: GPL-2.0-only+# On the macOS host: talk to the hosted macOS shell through the VM. XNU's output is read from the kernel ring buffer (dmesg,# log_buf_len=128M) instead of the serial console: a flood of console lines through a 115200-baud console stalled# printk with interrupts off on XNU's CPU (RCU stall). The ring buffer is read through journald (`journalctl -k`): after a# few minutes of XNU's output `dmesg` (util-linux, /dev/kmsg) stopped showing new records while journald kept them.diff --git a/scripts/vm-install-fki-service.sh b/scripts/vm-install-fki-service.shindex 5ec2d0c..29506ed 100755--- a/scripts/vm-install-fki-service.sh+++ b/scripts/vm-install-fki-service.sh@@ -1,4 +1,5 @@#!/bin/bash+# SPDX-License-Identifier: GPL-2.0-only# In the VM (once): the hosted kernel's DRAM as RAM Linux never manages, and fki.ko loaded with it early in every boot.# The VM has 24 GB; Linux's command line says mem=15G (RAM from 0x40000000 to 0x400000000), and the 8 GB above, below# the firmware's holes near the top, are fki's carve-out (carve_base/carve_mb). A CMA area was not enough: one page Linuxdiff --git a/scripts/vm-net-up.sh b/scripts/vm-net-up.shindex e945e8a..86952a9 100755--- a/scripts/vm-net-up.sh+++ b/scripts/vm-net-up.sh@@ -1,4 +1,5 @@#!/bin/bash+# SPDX-License-Identifier: GPL-2.0-only# In the VM, after fki.ko is loaded: the host side of the hosted macOS's en0. fki.ko's netdev xnu0 carries en0's# frames; Linux routes and NATs 192.168.77.0/24 out of its own uplink, and dnsmasq (when installed) answers DHCP and# DNS on xnu0. The hosted system: en0 192.168.77.2/24, router and DNS 192.168.77.1.diff --git a/scripts/vm-run-serial.sh b/scripts/vm-run-serial.shindex c38603e..d3508d8 100644--- a/scripts/vm-run-serial.sh+++ b/scripts/vm-run-serial.sh@@ -1,4 +1,5 @@#!/bin/bash+# SPDX-License-Identifier: GPL-2.0-only# On the Mac host: run the xnupoc VM with its console (hvc0) captured to ../serial-cap.log.cd "$(dirname "$0")/.."rm -f ../serial-namediff --git a/scripts/vm-xnu-build.sh b/scripts/vm-xnu-build.shindex 2c034ba..eac28fc 100755--- a/scripts/vm-xnu-build.sh+++ b/scripts/vm-xnu-build.sh@@ -1,4 +1,5 @@#!/bin/bash+# SPDX-License-Identifier: GPL-2.0-only# Inside the arm64 Ubuntu VM: the DroidVM Linux toolchain (native compile, no Darling: the kernel build does not need it)# and the xnu-12377 kernel from source.set -exdiff --git a/scripts/vm-xnu-rebuild.sh b/scripts/vm-xnu-rebuild.shindex 0024580..bc090e1 100755--- a/scripts/vm-xnu-rebuild.sh+++ b/scripts/vm-xnu-rebuild.sh@@ -1,4 +1,5 @@#!/bin/bash+# SPDX-License-Identifier: GPL-2.0-only# Inside the VM: apply xnulinux's XNU patches to the k27 tree, rebuild the kernel incrementally, and (when the macOS 27.2# kernelcache is there) relink the kernel collection with Apple's kexts. The kernel's segment slots inside the collection# (k27/segaddrs.sh) follow the kernel's size: when kc27-layout.py moves them, the kernel is linked again.diff --git a/scripts/vm.sh b/scripts/vm.shindex 9e5a33e..c4b9df9 100755--- a/scripts/vm.sh+++ b/scripts/vm.sh@@ -1,5 +1,6 @@#!/bin/bash-# On tokyo: run a command (or a script with -s FILE) in the xnupoc VM.+# SPDX-License-Identifier: GPL-2.0-only+# On the macOS host: run a command (or a script with -s FILE) in the xnupoc VM.W="$(cd "$(dirname "$0")/../.." && pwd)" # the session work dir (vmkey, vm.ip)ip=$(cat $W/vm.ip); port=$(cat $W/vm.port 2>/dev/null || echo 22) # vm.port: 2223 when the VM runs under krunkit (gvproxy)O="-o Port=$port -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=10 -o ServerAliveInterval=30 -o LogLevel=ERROR -i $W/vmkey"diff --git a/scripts/xnu-console.sh b/scripts/xnu-console.shindex 5323e25..1977798 100755--- a/scripts/xnu-console.sh+++ b/scripts/xnu-console.sh@@ -1,4 +1,5 @@#!/bin/bash+# SPDX-License-Identifier: GPL-2.0-only# On the Mac host, with the VM running and XNU loaded with CONSOLE_IN=/var/tmp/console-in: an interactive terminal on# XNU's /dev/console. Output: the "darwin console:" lines of the captured serial log; input: each line typed here is# appended to the console input file in the VM.diff --git a/scripts/xnulinux-boot.sh b/scripts/xnulinux-boot.shindex c5ce335..2e5ed88 100755--- a/scripts/xnulinux-boot.sh+++ b/scripts/xnulinux-boot.sh@@ -1,4 +1,5 @@#!/bin/bash+# SPDX-License-Identifier: GPL-2.0-only# In the VM: boot the hosted macOS. Builds fki.ko and xnu.ko against the running kernel (stops on a compile error, never# boots stale modules), brings up the hosted system's network (xnu0) and GPU bridge (xnudrmd, when there is a render node),# and loads xnu.ko on the disk mk-macvm-disk.sh made. Returns once XNU is running; xnu.ko stays loaded until the hosteddiff --git a/tests/host/fpcheck.c b/tests/host/fpcheck.cindex fb768a9..d6be984 100644--- a/tests/host/fpcheck.c+++ b/tests/host/fpcheck.c@@ -1,3 +1,4 @@+// SPDX-License-Identifier: GPL-2.0-only/* Keep known values in the FP/SIMD registers v8..v15 on one CPU while sleeping in a loop (so the task is switched out* and back in), and count the times they came back changed: a probe for a foreign kernel using SIMD on that CPU* behind Linux's back (Linux skips reloading a task's FP state when it believes the registers still hold it).diff --git a/tests/host/memcheck.c b/tests/host/memcheck.cindex f74a022..0c8313b 100644--- a/tests/host/memcheck.c+++ b/tests/host/memcheck.c@@ -1,3 +1,4 @@+// SPDX-License-Identifier: GPL-2.0-only/* Fill GBs of memory with a pattern derived from each word's address, re-verify it in a loop and report every word* that changed: its virtual and physical address (/proc/self/pagemap, root) and the value found. A probe for a foreign* writer (the hosted kernel, a device) scribbling over Linux's memory. Usage: memcheck GB SECONDS */diff --git a/tests/host/run.sh b/tests/host/run.shindex bde996f..d662696 100755--- a/tests/host/run.sh+++ b/tests/host/run.sh@@ -1,4 +1,5 @@#!/bin/bash+# SPDX-License-Identifier: GPL-2.0-only# In the VM, with a hosted system running: checks that the hosted kernel leaves Linux alone. 1 min.# fpcheck: a task on the hosted kernel's CPU (0) keeps its FP/SIMD registers across being switched out# memcheck: 4 GB of Linux memory keep their contents (nothing writes over Linux's pages)diff --git a/tools/dev/kcblraa.py b/tools/dev/kcblraa.pyindex 8af34fd..0b92c74 100644--- a/tools/dev/kcblraa.py+++ b/tools/dev/kcblraa.py@@ -1,4 +1,5 @@#!/usr/bin/env python3+# SPDX-License-Identifier: GPL-2.0-only# In [lo, hi) of a fileset KC: "ldr xA, [xB, #off]" followed within 4 instructions by "mov x17, #imm" and# "blraa xA, x17" (a call through a type-discriminated function pointer field). Prints off, imm, base reg, address.import struct, sys, collectionsdiff --git a/tools/dev/kcdis.py b/tools/dev/kcdis.pyindex c2a1c31..a417192 100644--- a/tools/dev/kcdis.py+++ b/tools/dev/kcdis.py@@ -1,4 +1,5 @@#!/usr/bin/env python3+# SPDX-License-Identifier: GPL-2.0-only# Disassemble [va, va+len) of a fileset kernel collection (top-level LC_SEGMENT_64s) with llvm-mc. Debugging aid.import struct, subprocess, syspath, va, n = sys.argv[1], int(sys.argv[2], 16), int(sys.argv[3], 0)diff --git a/tools/dev/kcstrs.py b/tools/dev/kcstrs.pyindex 414179a..1bdc51f 100644--- a/tools/dev/kcstrs.py+++ b/tools/dev/kcstrs.py@@ -1,4 +1,5 @@#!/usr/bin/env python3+# SPDX-License-Identifier: GPL-2.0-only# For adrp+add pairs in [va, va+len) of a fileset KC: the target address and the C string there (debugging aid).import struct, syspath, va0, n = sys.argv[1], int(sys.argv[2], 16), int(sys.argv[3], 0)diff --git a/tools/dev/kcxref.py b/tools/dev/kcxref.pyindex 43bc9df..2502a35 100644--- a/tools/dev/kcxref.py+++ b/tools/dev/kcxref.py@@ -1,4 +1,5 @@#!/usr/bin/env python3+# SPDX-License-Identifier: GPL-2.0-only# Find BL callers of a target in [lo, hi) of a fileset KC and print the instruction words after each (debugging aid).import struct, syspath, lo, hi, target = sys.argv[1], int(sys.argv[2], 16), int(sys.argv[3], 16), int(sys.argv[4], 16)diff --git a/tools/hosted/fb2png.py b/tools/hosted/fb2png.pyindex ad261a7..e55e24a 100644--- a/tools/hosted/fb2png.py+++ b/tools/hosted/fb2png.py@@ -1,4 +1,5 @@#!/usr/bin/env python3+# SPDX-License-Identifier: GPL-2.0-only"""Convert the hosted macOS's framebuffer dump (xnu.ko fb_dump: raw 32-bit BGRA rows) to a PNG.fb2png.py DUMP WIDTH HEIGHT OUT.pngdiff --git a/tools/hosted/gui-user.py b/tools/hosted/gui-user.pyindex 649171b..8faac72 100644--- a/tools/hosted/gui-user.py+++ b/tools/hosted/gui-user.py@@ -1,4 +1,5 @@#!/usr/bin/env python3+# SPDX-License-Identifier: GPL-2.0-only"""Make the hosted macOS's local user and automatic login, in a mounted system tree (run as root).gui-user.py ROOT TEMPLATE [NAME PASSWORD UID]diff --git a/tools/hosted/net-up.sh b/tools/hosted/net-up.shindex 0e59626..ee29600 100644--- a/tools/hosted/net-up.sh+++ b/tools/hosted/net-up.sh@@ -1,4 +1,5 @@#!/bin/sh+# SPDX-License-Identifier: GPL-2.0-only# In the hosted macOS, at boot (launchd job xnulinux.network): en0 is XNU's link to the host's xnu0 (bsd/net/if_linux64.c).# Without an IOKit interface behind it configd's IPConfiguration does not manage it, so configure it here: address, default# route, and the DNS/IPv4 state mDNSResponder resolves through (it does not read /etc/resolv.conf).diff --git a/tools/hosted/probe-window.m b/tools/hosted/probe-window.mindex c19fd0f..776dfaa 100644--- a/tools/hosted/probe-window.m+++ b/tools/hosted/probe-window.m@@ -1,3 +1,4 @@+// SPDX-License-Identifier: GPL-2.0-only// A rendering probe for the hosted macOS: one borderless window above everything (screen-saver level), for SECONDS seconds.// MODE picks who renders its content, to tell the client's rendering from WindowServer's compositing apart:// draw AppKit drawRect: four colour quadrants and a label (the client renders its layer tree)diff --git a/tools/hosted/tests/upd.sh b/tools/hosted/tests/upd.shdeleted file mode 100644index 2f5f72b..0000000--- a/tools/hosted/tests/upd.sh+++ /dev/null@@ -1,2 +0,0 @@-# In the hosted macOS: fetch the Metal plugin bundle from the Linux side and replace /Library/GPUBundles/XnuCpuMetal.bundle-cd /tmp && curl -sS -o XnuCpuMetal.bundle.tgz http://192.168.77.1:8765/XnuCpuMetal.bundle.tgz && rm -rf /Library/GPUBundles/XnuCpuMetal.bundle && tar -C /Library/GPUBundles -xzf XnuCpuMetal.bundle.tgz && echo "bundle updated: $(du -sh /Library/GPUBundles/XnuCpuMetal.bundle | cut -f1)"diff --git a/tools/hosted/xnu-input.py b/tools/hosted/xnu-input.pyindex e64cc0c..d7a4b66 100644--- a/tools/hosted/xnu-input.py+++ b/tools/hosted/xnu-input.py@@ -1,4 +1,5 @@#!/usr/bin/env python3+# SPDX-License-Identifier: GPL-2.0-only"""Send keyboard and pointer input to the hosted macOS (XnuInput): Linux evdev records appended to xnu.ko's input_in.xnu-input.py [--file /var/tmp/xnu-input] [--screen 1280x800] COMMAND ...diff --git a/tools/init/hello.s b/tools/init/hello.sindex 3264c57..1960750 100644--- a/tools/init/hello.s+++ b/tools/init/hello.s@@ -1,3 +1,4 @@+// SPDX-License-Identifier: GPL-2.0-only// /sbin/hello for the test root: write a line to /dev/console (fd 0 is not set up: open it) and exit 7..text.globl _startdiff --git a/tools/init/start.s b/tools/init/start.sindex 43a05ba..dfa78ac 100644--- a/tools/init/start.s+++ b/tools/init/start.s@@ -1,3 +1,4 @@+// SPDX-License-Identifier: GPL-2.0-only// A minimal static arm64 Mach-O for /sbin/launchd on a test root, BSD syscalls through svc #0x80 only:// open("/dev/console", O_WRONLY), write a line, fork; the child writes its own line and exits 7,// the child then execve()s /sbin/hello (which writes its line and exits 7); the parent wait4()s for it, writes a closing line and exits 42.diff --git a/tools/init/vm-install.sh b/tools/init/vm-install.shindex 8a6bb16..6c46ece 100755--- a/tools/init/vm-install.sh+++ b/tools/init/vm-install.sh@@ -1,4 +1,5 @@#!/bin/bash+# SPDX-License-Identifier: GPL-2.0-only# In the VM: build tools/init with the DroidVM k27 toolchain and put it at /sbin/launchd in /lib/firmware/xnu/root.img.set -euo pipefailcd "$(dirname "$0")"; TC=~/w/dvm/toolchains/linux/bin26diff --git a/xnu-ko/Makefile b/xnu-ko/Makefileindex f521bc6..34b9155 100644--- a/xnu-ko/Makefile+++ b/xnu-ko/Makefile@@ -1,3 +1,4 @@+# SPDX-License-Identifier: APSL-2.0# xnu.ko: the APSL side. Out-of-tree, non-GPL module that only uses fki.h.obj-m += xnu.oxnu-y := xnu_main.o macho.o adt.o world.odiff --git a/xnu-ko/adt.c b/xnu-ko/adt.cindex 08d0bd7..0c1c79e 100644--- a/xnu-ko/adt.c+++ b/xnu-ko/adt.c@@ -1,3 +1,4 @@+// SPDX-License-Identifier: APSL-2.0// ADT: node = {u32 nProperties, u32 nChildren}, then properties// {char name[32]; u32 length; value padded to 4}, then children.#include "xrt.h"diff --git a/xnu-ko/adt.h b/xnu-ko/adt.hindex f878c9e..9163b46 100644--- a/xnu-ko/adt.h+++ b/xnu-ko/adt.h@@ -1,3 +1,4 @@+// SPDX-License-Identifier: APSL-2.0/* Apple device tree (ADT) writer, written from the documented flattened format. */#pragma oncestruct adt { unsigned char *buf, *p, *end; int err; };diff --git a/xnu-ko/macho.c b/xnu-ko/macho.cindex 64afd39..64618db 100644--- a/xnu-ko/macho.c+++ b/xnu-ko/macho.c@@ -1,3 +1,4 @@+// SPDX-License-Identifier: APSL-2.0// Mach-O loading and threaded-rebase for the XNU image (APSL side).#include "xrt.h"#define ENOEXEC 8diff --git a/xnu-ko/macho.h b/xnu-ko/macho.hindex 6ddfcca..086e818 100644--- a/xnu-ko/macho.h+++ b/xnu-ko/macho.h@@ -1,3 +1,4 @@+// SPDX-License-Identifier: APSL-2.0/* Minimal Mach-O definitions (written from the public format, no Apple headers). */#pragma once#include "../fki-ko/fki.h"diff --git a/xnu-ko/world.S b/xnu-ko/world.Sindex d5a9a2c..8986d33 100644--- a/xnu-ko/world.S+++ b/xnu-ko/world.S@@ -1,3 +1,4 @@+// SPDX-License-Identifier: APSL-2.0/* World switch, see world.h. No PAC instructions here: keys change under our feet.* x18 is Linux's shadow call stack pointer (CONFIG_SHADOW_CALL_STACK), which belongs to the Linux task that entered the* world on this CPU. XNU does not use it or save it per thread, so it stays this CPU's while XNU runs (Linux code XNUdiff --git a/xnu-ko/world.h b/xnu-ko/world.hindex bd168ec..2506bb3 100644--- a/xnu-ko/world.h+++ b/xnu-ko/world.h@@ -1,3 +1,4 @@+// SPDX-License-Identifier: APSL-2.0/* World switch between Linux and the hosted XNU (see world.S for the layout). */#pragma once#include "../fki-ko/fki.h"diff --git a/xnu-ko/xrt.h b/xnu-ko/xrt.hindex e4536f8..9745720 100644--- a/xnu-ko/xrt.h+++ b/xnu-ko/xrt.h@@ -1,3 +1,4 @@+// SPDX-License-Identifier: APSL-2.0/* Tiny freestanding helpers so xnu.ko needs nothing from Linux beyond <linux/fki.h>. */#pragma oncestatic inline void *x_memcpy(void *d, const void *s, unsigned long n) { char *a = d; const char *b = s; while (n--) *a++ = *b++; return d; }diff --git a/xnu-patches/include/linux64.h b/xnu-patches/include/linux64.hindex f9b66fd..aeb3087 100644--- a/xnu-patches/include/linux64.h+++ b/xnu-patches/include/linux64.h@@ -1,3 +1,4 @@+// SPDX-License-Identifier: APSL-2.0/** Copyright (c) 2026 xnulinux contributors. All rights reserved.*diff --git a/xnu-patches/include/linux64_abi.h b/xnu-patches/include/linux64_abi.hindex 3c1b684..72dbdd2 100644--- a/xnu-patches/include/linux64_abi.h+++ b/xnu-patches/include/linux64_abi.h@@ -1,3 +1,4 @@+// SPDX-License-Identifier: APSL-2.0/** Copyright (c) 2026 xnulinux contributors. All rights reserved.*