Skip to content

Free fork of NotProton: Windows Steam games in Mac Steam, on CodeWeavers' Wine and Apple's Game Porting Toolkit

Public release/1.0

NotProtonNot69a96d75ea77
diff --git a/.github/workflows/app.yml b/.github/workflows/app.yml
new file mode 100644
index 0000000..4638579
--- /dev/null
+++ b/.github/workflows/app.yml
@@ -0,0 +1,115 @@
+name: app
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+ workflow_dispatch:
+ workflow_call:
+
+permissions:
+ contents: read
+
+env:
+ DOBBY_COMMIT: "5dfc8546954ce3b3198132ab13fddb89ee92cdd7"
+
+jobs:
+ build:
+ name: full app build
+ runs-on: xcode-27
+ timeout-minutes: 30
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Record the toolchain
+ run: |
+ sudo xcode-select -s /Applications/Xcode_27.0.app
+ xcodebuild -version
+ swift --version
+ echo "macOS SDK $(xcrun --sdk macosx --show-sdk-version)"
+
+ - name: Install cross compilers
+ run: brew install mingw-w64 bison flex
+
+ - name: Clone Dobby at the pinned commit
+ run: |
+ git clone --no-checkout https://github.com/jmpews/Dobby.git vendor/dobby
+ git -C vendor/dobby checkout $DOBBY_COMMIT
+
+ - name: Restore Dobby build cache
+ id: dobby-cache
+ uses: actions/cache@v4
+ with:
+ path: build/dobby
+ key: dobby-xcode-27-${{ env.DOBBY_COMMIT }}-${{ runner.arch }}
+
+ - name: Build Dobby
+ if: steps.dobby-cache.outputs.cache-hit != 'true'
+ run: make dobby
+
+ - name: Restore the Wine trees
+ id: wine-cache
+ uses: actions/cache/restore@v4
+ with:
+ path: |
+ scratch/wine
+ scratch/wine-build-dual
+ scratch/wine-build-arm64
+ key: wine-xcode-27-${{ hashFiles('bridge/setup-wine-tree.sh', 'bridge/register-components.diff') }}
+
+ - name: Restore Proton tarball cache
+ uses: actions/cache@v4
+ with:
+ path: scratch/proton-lsc
+ key: proton-tarball-${{ hashFiles('lsteamclient/fetch.sh') }}
+
+ - name: Build the dylib
+ run: make all
+
+ - name: Build the overlay shim
+ run: make overlay-shim
+
+ - name: Build helpers
+ run: make iconmaker appinfo
+
+ - name: Build the bridge
+ run: make bridge
+
+ - name: Save the Wine trees
+ if: steps.wine-cache.outputs.cache-hit != 'true'
+ uses: actions/cache/save@v4
+ with:
+ path: |
+ scratch/wine
+ scratch/wine-build-dual
+ scratch/wine-build-arm64
+ key: wine-xcode-27-${{ hashFiles('bridge/setup-wine-tree.sh', 'bridge/register-components.diff') }}
+
+ - name: Stage the app payload
+ run: make app-payload
+
+ - name: Build the app
+ run: make app
+
+ - name: Run the hermetic C suites
+ run: |
+ make -s sigcheck
+ make -s webpatch-fixtures
+ make -s panel-behavior
+ make -s spawn-env
+ make -s compatcheck
+ make -s compatsvc-check
+
+ - name: Run the Swift tests
+ run: make -s app-tests
+
+ - name: Package the app bundle
+ run: |
+ mkdir -p out/artifact
+ ditto -c -k --keepParent out/NotProton.app out/artifact/NotProton.zip
+
+ - name: Upload the app bundle
+ uses: actions/upload-artifact@v4
+ with:
+ name: NotProton
+ path: out/artifact
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
new file mode 100644
index 0000000..6881f50
--- /dev/null
+++ b/.github/workflows/lint.yml
@@ -0,0 +1,46 @@
+name: lint
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+env:
+ SHELLCHECK_VERSION: "0.11.0"
+
+jobs:
+ scripts:
+ name: shell scripts
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ # scriptcheck resolves its file list through git ls-files
+ - name: Confirm a git checkout
+ run: git rev-parse --is-inside-work-tree
+
+ # The runner image ships 0.9.0 and a working copy may have anything else.
+ # Versions disagree on which checks fire, so an unpinned tool makes the
+ # gate a property of the image rather than of the scripts.
+ - name: Install the pinned shellcheck
+ run: |
+ url=https://github.com/koalaman/shellcheck/releases/download/v$SHELLCHECK_VERSION/shellcheck-v$SHELLCHECK_VERSION.linux.x86_64.tar.xz
+ curl -fsSL "$url" | tar xJ -C "$RUNNER_TEMP"
+ sudo install "$RUNNER_TEMP/shellcheck-v$SHELLCHECK_VERSION/shellcheck" /usr/local/bin/shellcheck
+
+ # Both lint targets skip when shellcheck is missing, which would report
+ # success having read nothing
+ - name: Confirm the pinned version is the one on PATH
+ run: |
+ shellcheck --version
+ shellcheck --version | grep -qx "version: $SHELLCHECK_VERSION"
+
+ - name: Lint the build scripts
+ run: make scriptcheck
+
+ - name: Lint the embedded run script
+ run: make runcheck
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
new file mode 100644
index 0000000..f914c38
--- /dev/null
+++ b/.github/workflows/release.yml
@@ -0,0 +1,74 @@
+name: release
+
+on:
+ workflow_dispatch:
+ inputs:
+ version:
+ description: Version to release
+ required: true
+ type: string
+ release_notes:
+ description: Release notes
+ required: true
+ type: string
+
+permissions:
+ contents: write
+
+jobs:
+ build:
+ uses: ./.github/workflows/app.yml
+
+ release:
+ name: publish release
+ needs: build
+ runs-on: xcode-27
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/download-artifact@v4
+ with:
+ name: NotProton
+ path: release
+
+ - name: Verify the archive
+ env:
+ VERSION: ${{ inputs.version }}
+ run: |
+ ditto -x -k release/NotProton.zip release/extracted
+ codesign --verify --strict release/extracted/NotProton.app
+ actual=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' release/extracted/NotProton.app/Contents/Info.plist)
+ test "$actual" = "$VERSION"
+
+ - name: Resolve Sparkle tools
+ run: swift package resolve --package-path app
+
+ - name: Generate the appcast
+ env:
+ RELEASE_NOTES: ${{ inputs.release_notes }}
+ SPARKLE_PRIVATE_KEY: ${{ secrets.SPARKLE_PRIVATE_KEY }}
+ VERSION: ${{ inputs.version }}
+ run: |
+ printf '%s\n' "$RELEASE_NOTES" > release/NotProton.txt
+ printf '%s' "$SPARKLE_PRIVATE_KEY" | app/.build/artifacts/sparkle/Sparkle/bin/generate_appcast \
+ --ed-key-file - \
+ --download-url-prefix "https://github.com/$GITHUB_REPOSITORY/releases/download/v$VERSION/" \
+ --embed-release-notes \
+ release
+
+ - name: Publish the release
+ env:
+ GH_TOKEN: ${{ github.token }}
+ RELEASE_NOTES: ${{ inputs.release_notes }}
+ VERSION: ${{ inputs.version }}
+ run: |
+ git config user.name NotProtonNot
+ git config user.email [email protected]
+ git tag -f -a "v$VERSION" -m "Public release/$VERSION"
+ git push --force origin "v$VERSION"
+ gh release delete "v$VERSION" --yes || true
+ gh release create "v$VERSION" \
+ release/NotProton.zip \
+ release/appcast.xml \
+ --title "$VERSION" \
+ --notes "$RELEASE_NOTES"
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..6339ee1
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,25 @@
+build/
+.build/
+out/
+*.o
+*.a
+*.dylib
+.DS_Store
+
+vendor/dobby/
+vendor/sparkle/
+
+scratch/
+.scratch/
+
+steam-shim/proton-headers/
+
+cmake-build-*/
+.idea/
+.vscode/
+xcuserdata/
+*.xcuserstate
+DerivedData/
+
+app/Sources/NotProtonApp/Resources/payload/
+__pycache__/
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..f288702
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. 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
+them 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 prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. 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.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey 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;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If 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 convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU 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 that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ 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.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+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.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ 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
+state 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 a brief idea of what it does.>
+ Copyright (C) <year> <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 3 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, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ <program> Copyright (C) <year> <name of author>
+ This program 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, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<https://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<https://www.gnu.org/licenses/why-not-lgpl.html>.
diff --git a/LICENSE.lsteamclient b/LICENSE.lsteamclient
new file mode 100644
index 0000000..1638160
--- /dev/null
+++ b/LICENSE.lsteamclient
@@ -0,0 +1,149 @@
+================ STEAMWORKS SDK license ===================
+VALVE, Corp.
+SDK LICENSE
+
+This SDK License (the "Agreement") is made by and between you (the "Licensee")
+and Valve Corporation, a Washington corporation,(“Valve”) with offices located
+at 10400 NE 4th Street, Suite 1400, Bellevue, WA 98004, USA.
+
+THIS DOCUMENT DESCRIBES A CONTRACT BETWEEN YOU AND VALVE. PLEASE READ IT BEFORE
+DOWNLOADING OR USING THE STEAMWORKS SOFTWARE DEVELOPMENT KIT (THE “SDK”). BY
+DOWNLOADING AND/OR USING THE SDK YOU INDICATE YOUR ACCEPTANCE OF THIS
+AGREEMENT. IF YOU DO NOT AGREE, DO NOT DOWNLOAD AND/OR USE THE SDK.
+
+Whereas, Valve is the developer of an online platform titled "Steam" that
+provides online distribution services as well as a number of additional online
+services designed to be embedded in computer games and application software,
+including, but not limited to, user authentication, in-app purchasing and
+trading, leaderboards, matchmaking, stats and achievements (the “Steamworks
+Services”) and the SDK;
+
+Whereas, Licensee wishes to develop a game or application software designed to
+take advantage of the Steamworks Services (the "Licensee Software"); and
+
+Whereas, Licensee wishes to receive, and Valve wishes to disclose to Licensee,
+the SDK, and other information as deemed appropriate by Valve, all on the
+terms set forth herein;
+
+Now, therefore, in consideration of the mutual promises made herein, the
+parties agree as follows:
+
+1. License.
+
+1.1 License Grant. Valve hereby grants Licensee a nonexclusive, royalty-free,
+terminable, worldwide, nontransferable license to:
+
+(a) use and locally reproduce the SDK in source code form, solely to develop
+the Licensee Software; and
+
+(b) reproduce and distribute the part of the SDK provided inside the folder
+named redistributable_bin (the "SDK Redistributables") along with the Licensee
+Software in object code form.
+
+1.2 Updates. Valve may from time to time, in its sole discretion, provide
+updates, error corrections, and future versions of the SDK to Licensee. Upon
+delivery, such updates, error corrections and future versions shall be deemed
+part of the SDK, as applicable, under this Agreement.
+
+1.3 Reservation of Rights. Valve reserves all rights not explicitly granted
+herein.
+
+2. Ancillary Obligations.
+
+2.1 No obligation to provide services. Nothing herein shall be construed as
+establishing an obligation to Valve to provide Steamworks Services or accept
+Licensee Software for distribution via Steam.
+
+2.2 Indemnity. Licensee hereby agrees that it is solely responsible for any
+and all Licensee Software and Licensee's creation, distribution, and promotion
+thereof. Licensee shall defend, indemnify, and hold harmless Valve, its
+officers, directors, employees and agents against any and all claims, damages
+(including reasonable attorneys’ fees and costs), losses, or liabilities
+whatsoever arising out of Licensee's creation, distribution, or promotion of
+the Licensee Software.
+
+2.3 Trademarks. Licensee acknowledges and agrees that this Agreement does not
+grant Licensee any right to use any trademarks or trade names of Valve or its
+licensors. All such marks shall remain the property of the respective owner.
+Licensee will refrain from any action or communication that can be incorrectly
+interpreted as a cooperation or partnership between Valve and Licensee.
+
+2.4 No reverse engineering. Licensee will not take any steps to reverse
+engineer the functionality of the SDK or develop software to replace the SDK's
+functionality. If Licensee develops software to interact with the Steamworks
+Services, such software shall not communicate with the Steamworks Services
+directly but always through the application programming interface (API)
+provided by the SDK Redistributables.
+
+3. Term.
+
+3.1 Term. This Agreement shall become effective as of the date Licensee
+downloads or installs the SDK. It will continue to apply until terminated by
+either Valve or Licensee as set out below.
+
+3.2 Termination. Valve may terminate this Agreement immediately upon written
+(including email) notice to Licensee. Licensee may terminate this Agreement at
+any time by ceasing Licensees use of the SDK and ending Licensee's
+distribution of Licensee Software created using the SDK. Furthermore, the
+Agreement will terminate automatically upon Licensee's breach of any term of
+this Agreement.
+
+3.3 Survival. Sections 1.3, 2, 3.2, 3.3, and 4-6 shall survive any expiration
+or termination of this Agreement.
+
+4. Disclaimer of Warranties; Limitation of Liability
+
+4.1 NO WARRANTIES. THE SDK AND ANY OTHER MATERIAL DOWNLOADED BY LICENSEE IS
+PROVIDED “AS IS”. VALVE AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES WITH RESPECT
+TO THE SDK, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, IMPLIED
+WARRANTIES OF MERCHANTABILITY, NON-INFRINGEMENT, TITLE AND FITNESS FOR A
+PARTICULAR PURPOSE.
+
+4.2 LIMITATION OF LIABILITY. IN NO EVENT SHALL VALVE OR ITS SUPPLIERS BE
+LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES
+WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS
+PROFITS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY OTHER
+PECUNIARY LOSS) ARISING OUT OF THE USE OF OR INABILITY TO USE THE ENGINE
+AND/OR THE SDK, EVEN IF VALVE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+5. No Exclusivity.
+
+Neither this Agreement nor the disclosure or receipt of Information shall
+constitute or imply any promise to or intention to make any purchase of
+products or services by either party or its affiliated companies or any
+commitment by either party or its affiliated companies with respect to the
+present or future marketing of any product or service or any commitment to
+enter into any other business relationship. Except for the license and use
+restrictions expressly set forth herein, each party will be free (1) to
+pursue, negotiate, and enter into similar relationships with third parties and
+(2) to develop, market, and make available similar products and services.
+Neither party will be obligated to enter into any other agreement with the
+other party by virtue of this Agreement.
+
+6. General.
+
+6.1 Modification. No amendment or modification of this Agreement shall be
+valid or binding on the parties unless made in writing and signed on behalf of
+both of the parties by their respective duly authorized officers or
+representatives.
+
+6.2 Assignment. Licensee may not assign this agreement without the prior
+written consent of Valve. Subject to the limitations set forth in this
+Agreement, this Agreement will inure to the benefit of and be binding upon the
+parties, their successors and assigns.
+
+6.3 Severability. If any provision of this Agreement shall be held by a court
+of competent jurisdiction to be illegal, invalid or unenforceable, the
+remaining provisions shall remain in full force and effect.
+
+6.4 Governing Law, Jurisdiction and Venue. This Agreement shall be governed by
+the laws of the State of Washington. For any claims of any kind arising out of
+this Agreement or use of the SDK, each of the parties hereto submits to
+exclusive jurisdiction and venue in the state and federal courts sitting in
+King County, Washington.
+
+6.5 Entire Agreement. This Agreement constitutes the entire understanding
+between the parties hereto and supersedes all previous communications,
+representations and understandings, oral or written, between the parties, with
+respect to the subject matter of this Agreement.
diff --git a/LICENSE.steam-shim b/LICENSE.steam-shim
new file mode 100644
index 0000000..d7531fc
--- /dev/null
+++ b/LICENSE.steam-shim
@@ -0,0 +1,27 @@
+Copyright (c) 2015, 2019, 2020, 2021, 2022 Valve Corporation
+All rights reserved.
+
+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.
+
+3. Neither the name of the copyright holder nor the names of its contributors
+may be used to endorse or promote products derived from this software without
+specific prior written permission.
+
+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 HOLDER 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/Makefile b/Makefile
new file mode 100644
index 0000000..eee4b76
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,517 @@
+CC := clang
+ARCH := arm64
+MIN_VER := 15.0
+
+CFLAGS := -arch $(ARCH) -mmacosx-version-min=$(MIN_VER) \
+ -std=c17 -O2 -Wall -Wextra -Wno-unused-parameter \
+ -fPIC -MMD -MP \
+ -Idylib -Ivendor -Ivendor/dobby/include
+LDFLAGS := -arch $(ARCH) -mmacosx-version-min=$(MIN_VER) \
+ -dynamiclib -install_name @rpath/notproton.dylib
+
+FRAMEWORKS := -framework CoreFoundation
+
+DOBBY_DIR := build/dobby
+DOBBY_LIBS := $(DOBBY_DIR)/libdobby.a \
+ $(DOBBY_DIR)/builtin-plugin/SymbolResolver/libdobby_symbol_resolver.a \
+ $(DOBBY_DIR)/builtin-plugin/SymbolResolver/libmacho_ctx_kit.a \
+ $(DOBBY_DIR)/builtin-plugin/SymbolResolver/libshared_cache_ctx_kit.a \
+ $(DOBBY_DIR)/external/osbase/libosbase.a \
+ $(DOBBY_DIR)/external/logging/liblogging.a
+
+SRCS := \
+ dylib/core/loader.c \
+ dylib/core/macho.c \
+ dylib/resolver/anchor.c \
+ dylib/resolver/resolver.c \
+ dylib/resolver/sigdb.c \
+ dylib/util/log.c \
+ dylib/util/file.c \
+ dylib/hooks/hooks.c \
+ dylib/hooks/hook_compat.c \
+ dylib/hooks/hook_webui.c \
+ dylib/hooks/hook_webpatch.c \
+ dylib/hooks/hook_spawn.c \
+ dylib/feats/compat.c \
+ dylib/feats/webui.c \
+ dylib/feats/compatsvc.c \
+ dylib/feats/webpatch.c \
+ vendor/cJSON.c
+
+OUT_DIR := out
+
+GENERATED_DIR := $(OUT_DIR)/generated
+RUN_SCRIPT_H := $(GENERATED_DIR)/compat_run.h
+CFLAGS += -I$(GENERATED_DIR)
+
+ARM64_DYLIB := $(OUT_DIR)/notproton.arm64.dylib
+X86_STUB := $(OUT_DIR)/notproton.x86_64.dylib
+TARGET := $(OUT_DIR)/notproton.dylib
+
+OBJS := $(patsubst %.c,$(OUT_DIR)/%.o,$(SRCS))
+DEPS := $(OBJS:.o=.d)
+
+.PHONY: all clean rebuild dobby deploy dylib-install sigcheck app-payload app app-zip \
+ anchorcheck sigdb-fixtures webpatch-fixtures panel-behavior app-tests \
+ tests-list overlay-shim overlay-shim-install overlay-shim-tests \
+ overlay-shim-bench iconmaker icon \
+ appinfo helpers-install ntdll-resolve bridge runcheck compatcheck \
+ compatsvc-check scriptcheck
+
+APP_PAYLOAD := app/Sources/NotProtonApp/Resources/payload
+
+all: $(TARGET) $(APP_PAYLOAD)
+
+# SwiftPM's `.copy("Resources/payload")` in Package.swift needs this directory
+# to exist
+$(APP_PAYLOAD):
+ @mkdir -p $(APP_PAYLOAD)
+
+TEST_PATHS := dylib/tests overlay-shim/tests app/Tests
+
+tests-list:
+ @for p in $(TEST_PATHS); do echo $$p; done
+
+# A check with no inputs left is reported
+SKIP = echo "==> $(1): $(2) not present, skipped"
+
+runcheck:
+ @if ! command -v shellcheck >/dev/null 2>&1; then \
+ $(call SKIP,runcheck,shellcheck); exit 0; fi; \
+ shellcheck dylib/feats/compat_run.sh && sh -n dylib/feats/compat_run.sh && \
+ echo "==> runcheck: the run script lints and parses clean"
+
+# runcheck owns compat_run.sh, whose warnings wait for a change that can move
+# the embedded __text baseline
+SCRIPTS := $(shell git ls-files '*.sh' 2>/dev/null | grep -v '^dylib/feats/compat_run\.sh$$')
+
+scriptcheck:
+ @if ! command -v shellcheck >/dev/null 2>&1; then \
+ $(call SKIP,scriptcheck,shellcheck); exit 0; fi; \
+ if [ -z "$(strip $(SCRIPTS))" ]; then $(call SKIP,scriptcheck,a git checkout); exit 0; fi; \
+ for s in $(SCRIPTS); do \
+ shellcheck "$$s" || exit 1; \
+ sh -n "$$s" || exit 1; \
+ done; \
+ echo "==> scriptcheck: $(words $(SCRIPTS)) scripts lint and parse clean"
+
+COMPATCHECK := $(OUT_DIR)/compatcheck
+
+compatcheck: $(RUN_SCRIPT_H)
+ @if [ ! -f dylib/tests/compatcheck.c ]; then $(call SKIP,compatcheck,dylib/tests/compatcheck.c); exit 0; fi; \
+ mkdir -p $(OUT_DIR) && \
+ $(CC) -arch $(ARCH) -mmacosx-version-min=$(MIN_VER) -std=c17 -g \
+ -Wall -Wextra -Wno-unused-parameter -Idylib -I$(GENERATED_DIR) \
+ -o $(COMPATCHECK) dylib/tests/compatcheck.c && \
+ $(COMPATCHECK)
+
+COMPATSVC_CHECK := $(OUT_DIR)/compatsvc-check
+
+compatsvc-check:
+ @if [ ! -f dylib/tests/compatsvc-check.c ]; then $(call SKIP,compatsvc-check,dylib/tests/compatsvc-check.c); exit 0; fi; \
+ mkdir -p $(OUT_DIR) && \
+ $(CC) -arch $(ARCH) -mmacosx-version-min=$(MIN_VER) -std=c17 -g \
+ -Wall -Wextra -Wno-unused-parameter -Idylib \
+ -o $(COMPATSVC_CHECK) dylib/tests/compatsvc-check.c && \
+ $(COMPATSVC_CHECK)
+
+sigcheck:
+ @if [ ! -f dylib/tests/sigcheck.py ]; then $(call SKIP,sigcheck,dylib/tests/sigcheck.py); exit 0; fi; \
+ python3 dylib/tests/sigcheck.py
+
+# Validates anchors against a real dlopen'd steamclient.dylib
+ANCHORCHECK := $(OUT_DIR)/anchorcheck
+ANCHORCHECK_SRCS := dylib/tests/anchorcheck.c \
+ dylib/core/macho.c dylib/resolver/aob.c dylib/resolver/anchor.c \
+ dylib/resolver/resolver.c dylib/resolver/sigdb.c \
+ dylib/util/log.c dylib/util/file.c vendor/cJSON.c
+
+$(ANCHORCHECK): $(ANCHORCHECK_SRCS)
+ @mkdir -p $(dir $@)
+ $(CC) -arch $(ARCH) -mmacosx-version-min=$(MIN_VER) -std=c17 -g -O1 \
+ -Wall -Wextra -Wno-unused-parameter -Idylib -Ivendor \
+ -o $@ $(ANCHORCHECK_SRCS)
+
+anchorcheck:
+ @if [ ! -f dylib/tests/anchorcheck.c ]; then $(call SKIP,anchorcheck,dylib/tests/anchorcheck.c); exit 0; fi; \
+ $(MAKE) -s $(ANCHORCHECK) && $(ANCHORCHECK)
+
+SIGDB_FIXTURES := dylib/tests/sigdb-fixtures
+
+sigdb-fixtures:
+ @if [ ! -d $(SIGDB_FIXTURES) ] || [ ! -f dylib/tests/anchorcheck.c ]; then \
+ $(call SKIP,sigdb-fixtures,$(SIGDB_FIXTURES)); exit 0; fi; \
+ $(MAKE) -s $(ANCHORCHECK) || exit 1; \
+ fail=0; n=0; \
+ for f in $(SIGDB_FIXTURES)/*.json; do \
+ n=$$((n+1)); \
+ want=$$(awk -v name="$${f##*/}" '$$2 == name { print $$1 }' $(SIGDB_FIXTURES)/EXPECTED); \
+ out=$$($(ANCHORCHECK) "$$f" 2>&1); rc=$$?; \
+ if [ $$rc -ge 128 ]; then echo "crashed (rc=$$rc): $$f"; fail=1; continue; fi; \
+ if [ $$rc -eq 3 ]; then \
+ echo "anchorcheck cannot run here, so none of these fixtures were checked:"; \
+ echo "$$out" | tail -1; fail=1; break; fi; \
+ if [ -z "$$want" ]; then \
+ echo "no expected status in $(SIGDB_FIXTURES)/EXPECTED: $$f"; fail=1; continue; fi; \
+ if [ "$$rc" != "$$want" ]; then \
+ echo "expected $$want, got $$rc: $$f"; fail=1; fi; \
+ done; \
+ if [ $$fail -ne 0 ]; then exit 1; fi; \
+ echo "==> $$n sigdb fixtures: none crashed, each exited as $(SIGDB_FIXTURES)/EXPECTED records"
+
+GATECHECK := $(OUT_DIR)/gatecheck
+WEBPATCH_FIXTURES := dylib/tests/webpatch-fixtures
+
+$(GATECHECK): dylib/tests/gatecheck.c dylib/feats/webpatch.c dylib/feats/webpatch.h
+ @mkdir -p $(dir $@)
+ $(CC) -arch $(ARCH) -mmacosx-version-min=$(MIN_VER) -std=c17 -g -O1 \
+ -Wall -Wextra -Wno-unused-parameter -Idylib -o $@ dylib/tests/gatecheck.c
+
+webpatch-fixtures:
+ @if [ ! -d $(WEBPATCH_FIXTURES) ] || [ ! -f dylib/tests/gatecheck.c ]; then \
+ $(call SKIP,webpatch-fixtures,$(WEBPATCH_FIXTURES)); exit 0; fi; \
+ $(MAKE) -s $(GATECHECK) || exit 1; \
+ $(GATECHECK) || exit 1; \
+ fail=0; tmp=$$(mktemp -d); n=0; \
+ for good in $(WEBPATCH_FIXTURES)/gates.*.js; do \
+ n=$$(( $$n + 1 )); base=$$(basename $$good .js); \
+ cat $$good $$good > $$tmp/$$base.doubled.js; \
+ head -c $$(( $$(stat -f %z $$good) / 2 )) $$good > $$tmp/$$base.truncated.js; \
+ for spec in "$$good:APPLIED" "$$tmp/$$base.doubled.js:REJECTED" \
+ "$$tmp/$$base.truncated.js:REJECTED"; do \
+ f=$${spec%:*}; want=$${spec##*:}; \
+ out=$$($(GATECHECK) "$$f" 2>&1); rc=$$?; \
+ case "$$out" in *WRONG*) echo "$$out"; fail=1 ;; esac; \
+ case "$$out" in *$$want*) ;; *) echo "expected $$want: $$out"; fail=1 ;; esac; \
+ if [ $$rc -ne 0 ]; then fail=1; fi; \
+ done; \
+ done; \
+ rm -rf $$tmp; \
+ if [ $$fail -ne 0 ]; then exit 1; fi; \
+ echo "==> gate table and $$n webpatch fixtures: anchors intact, drift refused"
+
+SPAWN_ENV := $(OUT_DIR)/spawn-env
+
+spawn-env:
+ @if [ ! -f dylib/tests/spawn-env.c ]; then $(call SKIP,spawn-env,dylib/tests/spawn-env.c); exit 0; fi; \
+ mkdir -p $(OUT_DIR) && \
+ $(CC) -arch $(ARCH) -mmacosx-version-min=$(MIN_VER) -std=c17 -g -O1 \
+ -Wall -Wextra -Wno-unused-parameter -Idylib -o $(SPAWN_ENV) dylib/tests/spawn-env.c && \
+ $(SPAWN_ENV)
+
+SPAWN_LIVE := dylib/tests/spawn-live
+
+spawn-live: $(TARGET)
+ @if [ ! -d $(SPAWN_LIVE) ]; then $(call SKIP,spawn-live,$(SPAWN_LIVE)); exit 0; fi; \
+ tmp=$$(mktemp -d); trap 'rm -rf $$tmp' EXIT; mkdir -p $$tmp/sub; \
+ $(CC) -arch $(ARCH) -mmacosx-version-min=$(MIN_VER) -std=c17 -O1 -Wall -Wextra \
+ -o $$tmp/child $(SPAWN_LIVE)/child.c || exit 1; \
+ $(CC) -arch $(ARCH) -mmacosx-version-min=$(MIN_VER) -std=c17 -O1 -Wall -Wextra \
+ -o $$tmp/steam_osx $(SPAWN_LIVE)/driver.c || exit 1; \
+ cp $$tmp/steam_osx $$tmp/inert; cp $$tmp/child $$tmp/steam_osx_child; \
+ cp $$tmp/child $$tmp/sub/steam_osx; \
+ fail=0; \
+ for spec in "inert:child:1" "steam_osx:child:0" \
+ "steam_osx:steam_osx_child:0" "steam_osx:sub/steam_osx:1"; do \
+ drv=$${spec%%:*}; rest=$${spec#*:}; kid=$${rest%:*}; want=$${rest##*:}; \
+ got=$$(DYLD_INSERT_LIBRARIES=$$PWD/$(TARGET) $$tmp/$$drv $$tmp/$$kid 2>/dev/null \
+ | grep -c "^DYLD_INSERT_LIBRARIES=") || true; \
+ if [ "$$got" != "$$want" ]; then \
+ echo "$$drv -> $$kid: insert present $$got, wanted $$want"; fail=1; fi; \
+ done; \
+ if [ $$fail -ne 0 ]; then exit 1; fi; \
+ echo "==> spawn live: the hook lands, steam_osx keeps the insert, other children do not"
+
+APP_TESTS := app/Tests
+
+app-tests:
+ @if [ ! -d $(APP_TESTS) ]; then $(call SKIP,app-tests,$(APP_TESTS)); exit 0; fi; \
+ touch app/Package.swift; cd app && swift test
+
+PANEL_TESTS := dylib/tests/panel-behavior
+
+panel-behavior:
+ @if [ ! -d $(PANEL_TESTS) ]; then $(call SKIP,panel-behavior,$(PANEL_TESTS)); exit 0; fi; \
+ if ! command -v node >/dev/null 2>&1; then \
+ echo "==> panel-behavior: node not found, skipped"; exit 0; fi; \
+ mkdir -p $(OUT_DIR) && \
+ $(CC) -arch $(ARCH) -mmacosx-version-min=$(MIN_VER) -std=c17 -g -O1 \
+ -Wall -Wextra -Wno-unused-parameter -Idylib -o $(OUT_DIR)/panel-emit \
+ $(PANEL_TESTS)/emit.c && \
+ node $(PANEL_TESTS)/behavior.js $(OUT_DIR)/panel-emit && \
+ node $(PANEL_TESTS)/switching.js $(OUT_DIR)/panel-emit && \
+ echo "==> panel behavior: renders as expected, no stale arguments"
+
+CX_ROOT ?= /Applications/CrossOver Preview.app
+
+ntdll-resolve:
+ @if [ ! -f ntdll-patch/resolve.py ]; then \
+ $(call SKIP,ntdll-resolve,ntdll-patch/resolve.py); exit 0; fi; \
+ if ! python3 -c 'import capstone' >/dev/null 2>&1; then \
+ echo "==> ntdll-resolve: capstone not found, skipped (pip3 install capstone)"; exit 0; fi; \
+ if [ ! -d "$(CX_ROOT)" ]; then \
+ echo "==> ntdll-resolve: $(CX_ROOT) not present, skipped (set CX_ROOT)"; exit 0; fi; \
+ python3 ntdll-patch/resolve.py "$(CX_ROOT)"
+
+$(ARM64_DYLIB): $(OBJS)
+ @mkdir -p $(dir $@)
+ $(CC) $(LDFLAGS) -o $@ $^ $(DOBBY_LIBS) $(FRAMEWORKS) -lc++
+
+$(X86_STUB): dylib/stub_x86_64.c
+ @mkdir -p $(dir $@)
+ $(CC) -arch x86_64 -mmacosx-version-min=$(MIN_VER) \
+ -dynamiclib -install_name @rpath/notproton.dylib \
+ -o $@ $<
+
+$(TARGET): $(ARM64_DYLIB) $(X86_STUB)
+ lipo -create $^ -output $@
+ codesign -fs - $@
+ @echo "==> Built: $@"
+
+$(OUT_DIR)/%.o: %.c
+ @mkdir -p $(dir $@)
+ $(CC) $(CFLAGS) -c $< -o $@
+
+$(RUN_SCRIPT_H): dylib/feats/compat_run.sh dylib/embed_script.py
+ @mkdir -p $(GENERATED_DIR)
+ python3 dylib/embed_script.py $< $@ RUN_SCRIPT
+
+$(OUT_DIR)/dylib/feats/compat.o: $(RUN_SCRIPT_H)
+
+SUPPORT_DIR := $(HOME)/Library/Application Support/notproton
+OVERLAY_SHIM_SRC := overlay-shim/overlay_shim.m
+OVERLAY_SHIM_ARM := $(OUT_DIR)/overlay-shim.arm64.dylib
+OVERLAY_SHIM_X86 := $(OUT_DIR)/overlay-shim.x86_64.dylib
+OVERLAY_SHIM := $(OUT_DIR)/overlay-shim.dylib
+OVERLAY_SHIM_FLAGS := -mmacosx-version-min=$(MIN_VER) -dynamiclib -O2 -Wall -Wextra \
+ -install_name @rpath/overlay-shim.dylib \
+ -framework Metal -framework QuartzCore \
+ -framework CoreGraphics -framework CoreFoundation
+OVERLAY_SHIM_TESTS := overlay-shim/tests
+OVERLAY_SHIM_TEST_FLAGS := -mmacosx-version-min=$(MIN_VER) -O2 -Wall -Wextra \
+ -framework Metal -framework Foundation -framework QuartzCore
+
+overlay-shim: $(OVERLAY_SHIM)
+
+$(OVERLAY_SHIM): $(OVERLAY_SHIM_SRC)
+ @mkdir -p $(OUT_DIR)
+ $(CC) -arch arm64 $(OVERLAY_SHIM_FLAGS) -o $(OVERLAY_SHIM_ARM) $<
+ $(CC) -arch x86_64 $(OVERLAY_SHIM_FLAGS) -o $(OVERLAY_SHIM_X86) $<
+ lipo -create $(OVERLAY_SHIM_ARM) $(OVERLAY_SHIM_X86) -output $@
+ codesign -fs - $@
+ @lipo -info $@
+
+define install_atomically
+ @mkdir -p "$$(dirname "$(2)")"
+ cp -f "$(1)" "$(2).new"
+ mv -f "$(2).new" "$(2)"
+endef
+
+overlay-shim-install: $(OVERLAY_SHIM)
+ $(call install_atomically,$(OVERLAY_SHIM),$(SUPPORT_DIR)/overlay-shim.dylib)
+ @echo "==> Installed: $(SUPPORT_DIR)/overlay-shim.dylib"
+
+overlay-shim-tests: $(OVERLAY_SHIM)
+ @if [ ! -d $(OVERLAY_SHIM_TESTS) ]; then \
+ $(call SKIP,overlay-shim-tests,$(OVERLAY_SHIM_TESTS)); exit 0; fi; \
+ mkdir -p $(OUT_DIR); \
+ fail=0; ran=0; skipped=0; \
+ for t in device bridge delivery; do \
+ for a in arm64 x86_64; do \
+ $(CC) -arch $$a $(OVERLAY_SHIM_TEST_FLAGS) -o $(OUT_DIR)/$$t.$$a \
+ $(OVERLAY_SHIM_TESTS)/$$t.m || exit 1; \
+ out=$$(NOTPROTON_OVERLAY_SHIM=$(OVERLAY_SHIM) $(OUT_DIR)/$$t.$$a 2>&1); rc=$$?; \
+ case "$$rc" in \
+ 0) ran=$$((ran+1)); echo "$$out" | sed "s/^/ $$t.$$a /" ;; \
+ 3|126) skipped=$$((skipped+1)); \
+ echo " $$t.$$a skipped: $$(echo "$$out" | tail -1)" ;; \
+ *) echo " $$t.$$a exited $$rc:"; echo "$$out" | sed "s/^/ /"; fail=1 ;; \
+ esac; \
+ done; \
+ done; \
+ if [ $$fail -ne 0 ]; then exit 1; fi; \
+ if [ $$ran -eq 0 ]; then \
+ echo "overlay shim tests: all $$skipped skipped, so nothing was checked"; exit 1; fi; \
+ echo "==> overlay shim tests: $$ran passed, $$skipped skipped"
+
+overlay-shim-bench:
+ @if [ ! -f $(OVERLAY_SHIM_TESTS)/passbench.m ]; then \
+ $(call SKIP,overlay-shim-bench,$(OVERLAY_SHIM_TESTS)/passbench.m); exit 0; fi; \
+ mkdir -p $(OUT_DIR); \
+ for a in arm64 x86_64; do \
+ $(CC) -arch $$a $(OVERLAY_SHIM_TEST_FLAGS) -o $(OUT_DIR)/passbench.$$a \
+ $(OVERLAY_SHIM_TESTS)/passbench.m || exit 1; \
+ printf ' %-8s ' "$$a"; $(OUT_DIR)/passbench.$$a || exit 1; \
+ done
+
+ICONMAKER := $(OUT_DIR)/iconmaker
+
+iconmaker: $(ICONMAKER)
+
+$(ICONMAKER): helpers/iconmaker.swift
+ @mkdir -p $(OUT_DIR)
+ swiftc -O -framework AppKit -o $@ $<
+ @echo "==> Built $@"
+
+APPINFO := $(OUT_DIR)/appinfo
+
+appinfo: $(APPINFO)
+
+$(APPINFO): helpers/appinfo.swift
+ @mkdir -p $(OUT_DIR)
+ swiftc -O -o $@ $<
+ @echo "==> Built $@"
+
+helpers-install: $(ICONMAKER) $(APPINFO)
+ $(call install_atomically,$(ICONMAKER),$(SUPPORT_DIR)/iconmaker)
+ $(call install_atomically,$(APPINFO),$(SUPPORT_DIR)/appinfo)
+ @echo "==> Installed: $(SUPPORT_DIR)/{iconmaker,appinfo}"
+
+dobby:
+ @mkdir -p $(DOBBY_DIR)
+ cd $(DOBBY_DIR) && cmake $(CURDIR)/vendor/dobby \
+ -DCMAKE_OSX_ARCHITECTURES=arm64 \
+ -DCMAKE_OSX_DEPLOYMENT_TARGET=$(MIN_VER) \
+ -DDOBBY_DEBUG=OFF \
+ -DDOBBY_GENERATE_SHARED=OFF \
+ -G "Unix Makefiles"
+ $(MAKE) -C $(DOBBY_DIR) -j$(shell sysctl -n hw.ncpu)
+
+STEAM_APP := /Applications/Steam.app
+DEPLOY_DST := $(STEAM_APP)/Contents/MacOS/notproton.dylib
+INSTALL_DST := $(SUPPORT_DIR)/notproton.dylib
+
+dylib-install: $(TARGET)
+ $(call install_atomically,$(TARGET),$(INSTALL_DST))
+ @echo "==> Installed: $(INSTALL_DST)"
+
+sigdb-install:
+ @mkdir -p "$(SUPPORT_DIR)/signatures/macos.arm64"
+ cp -f signatures/macos.arm64/*.json "$(SUPPORT_DIR)/signatures/macos.arm64/"
+ @echo "==> Installed: $(SUPPORT_DIR)/signatures/macos.arm64"
+
+LAUNCHABLE_BUNDLES := $(HOME)/Desktop/NotProton.app /Applications/NotProton.app
+
+deploy: $(TARGET) dylib-install sigdb-install helpers-install
+ @if [ ! -d "$(STEAM_APP)" ]; then \
+ echo "==> deploy: $(STEAM_APP) not found"; exit 1; fi
+ $(call install_atomically,$(TARGET),$(DEPLOY_DST))
+ @echo "==> Deployed: $(DEPLOY_DST) (restart Steam to load)"
+ @for b in $(LAUNCHABLE_BUNDLES); do \
+ p=$$(find "$$b" -name notproton.dylib -type f 2>/dev/null | head -1); \
+ [ -n "$$p" ] || continue; \
+ cmp -s "$$p" "$(DEPLOY_DST)" && continue; \
+ echo "==> warning: $$b carries a different notproton.dylib"; \
+ echo "==> warning: launching it reverts this deploy, so rebuild it with 'make app'"; \
+ done
+
+WINE_BUILD := scratch/wine-build-dual
+
+WINE_BUILD_ARM64 := scratch/wine-build-arm64
+
+BRIDGE_FILES := \
+ $(WINE_BUILD)/programs/steam.exe/x86_64-windows/steam.exe:steam.exe \
+ $(WINE_BUILD)/dlls/lsteamclient/x86_64-windows/lsteamclient.dll:x86_64-windows-lsteamclient.dll \
+ $(WINE_BUILD)/dlls/lsteamclient/lsteamclient.so:x86_64-unix-lsteamclient.so \
+ $(WINE_BUILD_ARM64)/dlls/lsteamclient/lsteamclient.so:aarch64-unix-lsteamclient.so \
+ $(WINE_BUILD)/dlls/lsteamclient/i386-windows/lsteamclient.dll:i386-windows-lsteamclient.dll
+
+bridge:
+ bridge/setup-wine-tree.sh
+ WINE_BUILD="$(CURDIR)/$(WINE_BUILD_ARM64)" HOST=aarch64-apple-darwin \
+ HOST_CC="clang -arch arm64" HOST_CXX="clang++ -arch arm64" bridge/setup-wine-tree.sh
+ lsteamclient/build.sh
+ UNIX_ARCH=arm64 WINE_BUILD="$(CURDIR)/$(WINE_BUILD_ARM64)" lsteamclient/build.sh --unix
+ steam-shim/build.sh
+ @echo "==> Built the bridge, now run: $(MAKE) app-payload"
+
+app-payload: $(TARGET) $(OVERLAY_SHIM) $(ICONMAKER) $(APPINFO)
+ @mkdir -p "$(APP_PAYLOAD)/signatures/macos.arm64"
+ @mkdir -p "$(APP_PAYLOAD)/bridge"
+ cp -f $(TARGET) "$(APP_PAYLOAD)/notproton.dylib"
+ cp -f $(OVERLAY_SHIM) "$(APP_PAYLOAD)/overlay-shim.dylib"
+ cp -f $(ICONMAKER) "$(APP_PAYLOAD)/iconmaker"
+ cp -f $(APPINFO) "$(APP_PAYLOAD)/appinfo"
+ cp -f signatures/macos.arm64/*.json "$(APP_PAYLOAD)/signatures/macos.arm64/"
+ @set -e; for spec in $(BRIDGE_FILES); do \
+ src="$${spec%%:*}"; dst="$(APP_PAYLOAD)/bridge/$${spec##*:}"; \
+ if [ -f "$$src" ]; then cp -f "$$src" "$$dst"; \
+ elif [ -f "$$dst" ]; then echo "==> keeping staged $${spec##*:}"; \
+ else echo "$$src is missing and nothing is staged at $$dst, run: $(MAKE) bridge" >&2; exit 1; fi; \
+ done
+ @echo "==> Staged app payload in $(APP_PAYLOAD)"
+
+APP_BUNDLE := $(OUT_DIR)/NotProton.app
+APP_BUNDLE_PAYLOAD := $(APP_BUNDLE)/Contents/Resources/NotProtonApp_NotProtonApp.bundle/Contents/Resources/payload
+APP_ZIP := $(OUT_DIR)/NotProton.zip
+APP_VERSION := $(shell sed -n 's/^\#define NOTPROTON_VERSION "\(.*\)"/\1/p' dylib/version.h)
+
+APP_SIGN_ID ?= -
+
+ICONGEN := $(OUT_DIR)/icongen
+ICON_DOC := $(OUT_DIR)/NotProton.icon
+ICON_DIR := $(OUT_DIR)/icon
+ICON_CAR := $(ICON_DIR)/Assets.car
+
+icon: $(ICON_CAR)
+
+$(ICONGEN): helpers/icon.swift
+ @mkdir -p $(OUT_DIR)
+ swiftc -O -o $@ $<
+ @echo "==> Built $@"
+
+$(ICON_CAR): $(ICONGEN)
+ rm -rf "$(ICON_DOC)" "$(ICON_DIR)"
+ $(ICONGEN) "$(ICON_DOC)"
+ @mkdir -p "$(ICON_DIR)"
+ xcrun actool "$(ICON_DOC)" --compile "$(ICON_DIR)" --platform macosx \
+ --minimum-deployment-target 26.0 --app-icon NotProton \
+ --output-partial-info-plist "$(ICON_DIR)/partial.plist" >/dev/null
+ @echo "==> Built $@"
+
+app: app-payload $(ICON_CAR)
+ swift build --package-path app -c release
+ rm -rf "$(APP_BUNDLE)"
+ @mkdir -p "$(APP_BUNDLE)/Contents/MacOS" "$(APP_BUNDLE)/Contents/Resources"
+ cp app/Info.plist "$(APP_BUNDLE)/Contents/Info.plist"
+ /usr/libexec/PlistBuddy -c \
+ "Set :CFBundleShortVersionString $(APP_VERSION)" -c \
+ "Set :CFBundleVersion $(APP_VERSION)" \
+ "$(APP_BUNDLE)/Contents/Info.plist"
+ cp "$$(swift build --package-path app -c release --show-bin-path)/NotProtonApp" \
+ "$(APP_BUNDLE)/Contents/MacOS/NotProtonApp"
+ @mkdir -p "$(APP_BUNDLE)/Contents/Frameworks"
+ ditto "$$(swift build --package-path app -c release --show-bin-path)/Sparkle.framework" \
+ "$(APP_BUNDLE)/Contents/Frameworks/Sparkle.framework"
+ install_name_tool -add_rpath @executable_path/../Frameworks \
+ "$(APP_BUNDLE)/Contents/MacOS/NotProtonApp"
+ cp -R "$$(swift build --package-path app -c release --show-bin-path)/NotProtonApp_NotProtonApp.bundle" \
+ "$(APP_BUNDLE)/Contents/Resources/"
+ cp "$(ICON_DIR)/Assets.car" "$(ICON_DIR)/NotProton.icns" \
+ "$(APP_BUNDLE)/Contents/Resources/"
+ @missing=$$(cd "$(APP_PAYLOAD)" && find . -type f ! -name '.DS_Store' | sed 's|^\./||' \
+ | while read -r rel; do \
+ [ -s "$(CURDIR)/$(APP_BUNDLE_PAYLOAD)/$$rel" ] || echo "$$rel"; \
+ done); \
+ if [ -n "$$missing" ]; then \
+ echo "==> the bundle is missing staged payload, so the app would ship without it:" >&2; \
+ echo "$$missing" | sed 's/^/ /' >&2; \
+ echo "==> rm -rf app/.build/out and build again" >&2; \
+ exit 1; \
+ fi
+ @echo "==> Payload complete in the bundle"
+ codesign -f -s "$(APP_SIGN_ID)" "$(APP_BUNDLE)"
+ codesign --verify --strict "$(APP_BUNDLE)"
+ @echo "==> Built $(APP_BUNDLE) ($(APP_VERSION))"
+
+app-zip: app
+ rm -f "$(APP_ZIP)"
+ ditto -c -k --keepParent "$(APP_BUNDLE)" "$(APP_ZIP)"
+ @echo "==> Wrote $(APP_ZIP)"
+
+clean:
+ rm -rf $(OUT_DIR)
+
+rebuild: clean all
+
+-include $(DEPS)
diff --git a/NOTICE b/NOTICE
new file mode 100644
index 0000000..9c8bb03
--- /dev/null
+++ b/NOTICE
@@ -0,0 +1,32 @@
+NotProton licensing
+===================
+
+NotProton has a complex licensing situation. The bulk of the project is licensed
+under GPLV3.
+
+The parts that are modifications of Valve code are licensed under the license
+that Valve released them under.
+
+lsteamclient is licensed under the Steamworks SDK License, see
+https://github.com/ValveSoftware/Proton/blob/proton_11.0/lsteamclient/LICENSE
+
+steam-shim is a port of steam_helper from Proton 9.0, which Valve released under
+BSD-3-Clause.
+
+Steam-shim compiles against Steamworks SDK headers. Those headers are licensed
+under the Steamworks SDK license whenever they are used.
+
+It also compiles against OpenVR and Wine headers, which are BSD-3-Clause and
+LGPL-V2, respectively.
+
+The app bundle embeds Sparkle, which checks for and installs updates. Sparkle is
+MIT licensed, see
+https://github.com/sparkle-project/Sparkle/blob/2.10.0/LICENSE
+
+These third party files carry their original notices from the project authors:
+
+ steam-shim/jsoncpp.cpp JsonCpp, public domain / MIT (header)
+ steam-shim/json/json.h JsonCpp, public domain / MIT (header)
+ steam-shim/json/json-forwards.h JsonCpp, public domain / MIT (header)
+ vendor/cJSON.c cJSON, MIT (header)
+ vendor/cJSON.h cJSON, MIT (header)
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..6ebf732
--- /dev/null
+++ b/README.md
@@ -0,0 +1,25 @@
+# NotProton
+
+NotProton enables the Steam Play experience from Linux Steam in the macOS Steam client.
+
+This is done by forcibly enabling the Steam Play functionality in macOS Steam (which is
+present and inert) as well as by porting some components of Valve's Proton to macOS.
+
+This tool is intended to be used with Steam Client 1788652215 or 1790121765 and **CrossOver Preview
+2026082**. Both the FEX build and the Rosetta build are supported. The Rosetta build is
+the recommended version, as the FEX one has generally worse compatibility with games.
+It's early, that's all.
+
+The macOS app itself is located in the ```app``` folder. The core logic is in ```dylib```.
+```lsteamclient``` is a macOS port of Valve's lsteamclient. ```steam-shim```is a port of Valve's
+steam-helper from Proton 9. ntdll-patch patches the copy of CrossOver that the app
+makes/places in the ```~/Library/Application Support/notproton/runners/``` folder so that
+lsteamclient is loaded.
+
+This release is coming several days past when I wanted to release it, so the
+documentation is quite sparse. Sorry about that, I'll improve it over the next day or
+two.
+
+Please read NOTICE for license information.
+
+Please open issue reports with any issues.
diff --git a/app/Info.plist b/app/Info.plist
new file mode 100644
index 0000000..8929c98
--- /dev/null
+++ b/app/Info.plist
@@ -0,0 +1,38 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleDevelopmentRegion</key>
+ <string>en</string>
+ <key>CFBundleExecutable</key>
+ <string>NotProtonApp</string>
+ <key>CFBundleIconFile</key>
+ <string>NotProton</string>
+ <key>CFBundleIconName</key>
+ <string>NotProton</string>
+ <key>CFBundleIdentifier</key>
+ <string>com.notproton.NotProton</string>
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+ <key>CFBundleName</key>
+ <string>NotProton</string>
+ <key>CFBundlePackageType</key>
+ <string>APPL</string>
+ <key>CFBundleShortVersionString</key>
+ <string>0.0.0</string>
+ <key>CFBundleVersion</key>
+ <string>0.0.0</string>
+ <key>LSApplicationCategoryType</key>
+ <string>public.app-category.utilities</string>
+ <key>LSMinimumSystemVersion</key>
+ <string>26.0</string>
+ <key>NSHighResolutionCapable</key>
+ <true/>
+ <key>NSPrincipalClass</key>
+ <string>NSApplication</string>
+ <key>SUFeedURL</key>
+ <string>https://github.com/NotProtonNot/NotProton/releases/latest/download/appcast.xml</string>
+ <key>SUPublicEDKey</key>
+ <string>rDOXzJ+vt12aWeu9hATgvz6q46MlRcgR4gbTfj5YuWQ=</string>
+</dict>
+</plist>
diff --git a/app/Package.resolved b/app/Package.resolved
new file mode 100644
index 0000000..6b2a6cb
--- /dev/null
+++ b/app/Package.resolved
@@ -0,0 +1,15 @@
+{
+ "originHash" : "808975bc467a500b60b730fbebe797a562a102ee2818509f91e59ebfb710b7e8",
+ "pins" : [
+ {
+ "identity" : "sparkle",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/sparkle-project/Sparkle",
+ "state" : {
+ "revision" : "eef1a539a373c1f1a320624b1130fc5de7b2e100",
+ "version" : "2.10.0"
+ }
+ }
+ ],
+ "version" : 3
+}
diff --git a/app/Package.swift b/app/Package.swift
new file mode 100644
index 0000000..ba0b564
--- /dev/null
+++ b/app/Package.swift
@@ -0,0 +1,43 @@
+// swift-tools-version: 6.2
+import Foundation
+import PackageDescription
+let testsPath = "Tests/NotProtonAppTests"
+let payloadPath = "Sources/NotProtonApp/Resources/payload"
+let packageRoot = URL(fileURLWithPath: #filePath).deletingLastPathComponent()
+let hasTests = FileManager.default.fileExists(
+ atPath: packageRoot.appendingPathComponent(testsPath).path)
+
+// make app-payload stages the payload, so a checkout that has not been built does
+// not have it. A declared resource that is missing is a build error, while an app
+// missing the payload is a condition InstallPayload already reports.
+let hasPayload = FileManager.default.fileExists(
+ atPath: packageRoot.appendingPathComponent(payloadPath).path)
+let package = Package(
+ name: "NotProtonApp",
+ platforms: [.macOS("26.0")],
+ dependencies: [
+ .package(url: "https://github.com/sparkle-project/Sparkle", exact: "2.10.0"),
+ ],
+ targets: [
+ .executableTarget(
+ name: "NotProtonApp",
+ dependencies: [.product(name: "Sparkle", package: "Sparkle")],
+ path: "Sources/NotProtonApp",
+ resources: (hasPayload ? [.copy("Resources/payload")] : []) + [
+ .copy("Resources/payload.manifest"),
+ .copy("Resources/valve-packages.manifest"),
+ .copy("Resources/detour2.bin"),
+ .copy("Resources/detour32.bin"),
+ .copy("Resources/detour32-fex.bin"),
+ .copy("Resources/detour64-fex.bin"),
+ ],
+ swiftSettings: [.swiftLanguageMode(.v6)]
+ ),
+ ] + (hasTests ? [
+ .testTarget(
+ name: "NotProtonAppTests",
+ dependencies: ["NotProtonApp"],
+ path: testsPath
+ ),
+ ] : [])
+)
diff --git a/app/Sources/NotProtonApp/App.swift b/app/Sources/NotProtonApp/App.swift
new file mode 100644
index 0000000..a8f16ce
--- /dev/null
+++ b/app/Sources/NotProtonApp/App.swift
@@ -0,0 +1,157 @@
+// Self-explanatory
+
+import SwiftUI
+
+@main
+struct NotProtonApp: App {
+
+ @State private var status = SystemStatus()
+ @State private var prefixes = PrefixesModel()
+ @State private var pane: Pane = .status
+ private let updater = AppUpdater()
+
+ init() {
+ AppLog.start()
+ }
+
+ var body: some Scene {
+ Window("NotProton", id: "main") {
+ RootView(pane: $pane)
+ .environment(status)
+ .environment(prefixes)
+ .frame(minWidth: 720, minHeight: 460)
+ .onChange(of: pane) { prefixes.forgetOutcome() }
+ }
+ .defaultSize(width: 900, height: 760)
+ .commands { menus }
+ }
+
+ @CommandsBuilder
+ private var menus: some Commands {
+ CommandGroup(replacing: .newItem) {}
+
+ CommandGroup(after: .appInfo) {
+ Button("Check for Updates…") { updater.check() }
+ }
+
+ CommandGroup(after: .sidebar) {
+ Button("Status") { pane = .status }
+ .keyboardShortcut("1", modifiers: .command)
+ Button("Prefixes") { pane = .prefixes }
+ .keyboardShortcut("2", modifiers: .command)
+ Button("Prefix Backups") { pane = .backups }
+ .keyboardShortcut("3", modifiers: .command)
+
+ Divider()
+
+ Button("Refresh") {
+ Task {
+ switch pane {
+ case .status: await status.refresh()
+ case .prefixes, .backups: await prefixes.load()
+ }
+ }
+ }
+ .keyboardShortcut("r", modifiers: .command)
+ .disabled(pane == .status ? !status.isIdle : prefixes.isLoading)
+
+ Divider()
+ }
+
+ CommandMenu("Setup") {
+ Button("Install") { Task { await status.requestInstall() } }
+ .keyboardShortcut("i", modifiers: .command)
+ .disabled(!status.isIdle)
+
+ Button("Set Up Compatibility Tool") { Task { await status.requestCompatibilityTool() } }
+ .disabled(!status.isIdle || status.usableCrossOver == nil)
+
+ Button("Fetch Valve Binaries") { Task { await status.fetchValveBinaries() } }
+ .disabled(!status.isIdle)
+
+ Divider()
+
+ updateBlockCommand
+
+ Button("Repair Steam") { status.pendingConfirmation = .replaceSteam }
+ .disabled(!status.isIdle)
+
+ Divider()
+
+ Button("Reveal Log in Finder") {
+ NSWorkspace.shared.activateFileViewerSelecting([AppLog.file])
+ }
+ }
+
+ prefixMenu
+ }
+
+ @CommandsBuilder
+ private var prefixMenu: some Commands {
+ CommandMenu("Prefix") {
+ Button("Run Program…") {
+ if let prefix = prefixTarget { prefixes.chooseExecutable(for: prefix) }
+ }
+ .disabled(prefixTarget == nil)
+
+ Divider()
+
+ ForEach(WineTool.allCases, id: \.self) { tool in
+ Button(tool.label) {
+ if let prefix = prefixes.selectedPrefix { prefixes.open(tool, for: prefix) }
+ }
+ .disabled(prefixTarget == nil)
+ }
+
+ Divider()
+
+ Button("Reveal in Finder") {
+ if let prefix = prefixes.selectedPrefix { prefixes.reveal(prefix) }
+ }
+ .keyboardShortcut("r", modifiers: [.command, .shift])
+ .disabled(prefixes.selectedPrefix == nil)
+
+ Divider()
+
+ Button(PrefixPrompt.backUpButton(selectionTargets)) {
+ if !selectionTargets.isEmpty {
+ prefixes.pendingConfirmation = .backUp(selectionTargets)
+ }
+ }
+ .disabled(selectionTargets.isEmpty)
+
+ Button(PrefixPrompt.rebuildButton(selectionTargets)) {
+ if !selectionTargets.isEmpty {
+ prefixes.pendingConfirmation = .rebuild(selectionTargets)
+ }
+ }
+ .disabled(selectionTargets.isEmpty)
+
+ Button(PrefixPrompt.deleteButton(selectionTargets)) {
+ if !selectionTargets.isEmpty {
+ prefixes.pendingConfirmation = .delete(selectionTargets)
+ }
+ }
+ .disabled(selectionTargets.isEmpty)
+ }
+ }
+
+ private var prefixTarget: WinePrefix? {
+ prefixes.isBusy ? nil : prefixes.selectedPrefix
+ }
+
+ private var selectionTargets: [WinePrefix] {
+ prefixes.isBusy ? [] : prefixes.selectedPrefixes
+ }
+
+ @ViewBuilder
+ private var updateBlockCommand: some View {
+ if status.snapshot?.updateBlocked == true {
+ Button("Allow Client Updates") { Task { await status.setUpdateBlock(false) } }
+ .disabled(!status.isIdle)
+ } else {
+ Button("Block Client Updates") { status.pendingConfirmation = .blockUpdates }
+ .disabled(!status.isIdle || status.snapshot == nil)
+ }
+ }
+}
diff --git a/app/Sources/NotProtonApp/Model/BridgePayload.swift b/app/Sources/NotProtonApp/Model/BridgePayload.swift
new file mode 100644
index 0000000..b8c25e0
--- /dev/null
+++ b/app/Sources/NotProtonApp/Model/BridgePayload.swift
@@ -0,0 +1,118 @@
+// The Bridge Payload consists of the components Proton uses to 'bridge'
+// communication between the game running under Proton and the native
+// Steam client. This component of the app deploys them.
+
+import Foundation
+
+enum BridgePayload {
+ static let step = "Copy the built bridge files"
+
+ struct Entry: Sendable {
+ // Two different lsteamclient binaries, one 32 bit and one 64 bit.
+ let resource: String
+ let bridgePaths: [String]
+ }
+
+ static let entries: [Entry] = [
+ Entry(resource: "steam.exe", bridgePaths: [
+ "steam.exe",
+ ]),
+ Entry(resource: "x86_64-windows-lsteamclient.dll", bridgePaths: [
+ "lsteamclient.dll",
+ "x86_64-windows/lsteamclient.dll",
+ ]),
+ Entry(resource: "aarch64-unix-lsteamclient.so", bridgePaths: [
+ "aarch64-unix/lsteamclient.so",
+ ]),
+ Entry(resource: "x86_64-unix-lsteamclient.so", bridgePaths: [
+ "lsteamclient.so",
+ "x86_64-unix/lsteamclient.so",
+ ]),
+ Entry(resource: "i386-windows-lsteamclient.dll", bridgePaths: [
+ "i386-windows/lsteamclient.dll",
+ ]),
+ ]
+
+ struct Located: Sendable {
+ let sources: [(source: URL, bridgePaths: [String])]
+ }
+
+ static func locate(root: URL? = nil) throws -> Located {
+ let base: URL
+ if let root {
+ base = root
+ } else {
+ guard let payloadRoot = try? InstallPayload.root() else {
+ throw StepFailure(
+ step: step,
+ detail: "NotProton carries no components."
+ )
+ }
+ base = payloadRoot.appending(path: "bridge")
+ }
+
+ let files = FileManager.default
+ var missing: [String] = []
+ var sources: [(source: URL, bridgePaths: [String])] = []
+
+ for entry in entries {
+ let url = base.appending(path: entry.resource)
+ if files.fileExists(atPath: url.path(percentEncoded: false)) {
+ sources.append((source: url, bridgePaths: entry.bridgePaths))
+ } else {
+ missing.append(entry.resource)
+ }
+ }
+
+ guard missing.isEmpty else {
+ throw StepFailure(
+ step: step,
+ detail: "Missing components: \(missing.joined(separator: ", ")). "
+ + "Run make app-payload and build the app again."
+ )
+ }
+
+ return Located(sources: sources)
+ }
+
+ struct Outcome: Sendable {
+ let staged: [String]
+ let unchanged: [String]
+ }
+
+ static func stage(
+ located: Located,
+ bridge: URL = SupportPaths.bridge
+ ) throws -> Outcome {
+ let files = FileManager.default
+ var staged: [String] = []
+ var unchanged: [String] = []
+
+ for entry in located.sources {
+ let sourceSize = try fileSize(entry.source)
+ for bridgePath in entry.bridgePaths {
+ let destination = bridge.appending(path: bridgePath)
+ if let existing = try? fileSize(destination), existing == sourceSize {
+ unchanged.append(bridgePath)
+ continue
+ }
+
+ try files.createDirectory(
+ at: destination.deletingLastPathComponent(), withIntermediateDirectories: true
+ )
+ try? files.removeItem(at: destination)
+ try files.copyItem(at: entry.source, to: destination)
+ staged.append(bridgePath)
+ }
+ }
+
+ return Outcome(staged: staged, unchanged: unchanged)
+ }
+
+ private static func fileSize(_ url: URL) throws -> Int {
+ let attrs = try FileManager.default.attributesOfItem(
+ atPath: url.path(percentEncoded: false)
+ )
+ return (attrs[.size] as? Int) ?? 0
+ }
+}
diff --git a/app/Sources/NotProtonApp/Model/CrossOverLicense.swift b/app/Sources/NotProtonApp/Model/CrossOverLicense.swift
new file mode 100644
index 0000000..07155f1
--- /dev/null
+++ b/app/Sources/NotProtonApp/Model/CrossOverLicense.swift
@@ -0,0 +1,143 @@
+// Checks whether the user's CrossOver install is licensed.
+// CodeWeavers, I hope this doesn't bother you. You don't validate
+// license when the Wine binary itself is invoked, so I wanted to
+// do something to prevent skids from doing really trivial piracy.
+
+import Foundation
+
+enum CrossOverLicense {
+
+ struct Status: Sendable {
+ let licensed: Bool
+ let detail: String
+ // The real reason, for the log.
+ let diagnostic: String
+ }
+
+ static let defaultSearchDirs: [URL] = {
+ let home = URL(filePath: NSHomeDirectory())
+ return [
+ home.appending(path: "Library/Preferences"),
+ URL(filePath: "/Library/Preferences"),
+ ]
+ }()
+
+ private static let licenseBase = "com.codeweavers.CrossOver"
+
+ static let notActivatedTitle = "CrossOver does not appear to be activated."
+ static let notActivatedAdvice = "Please run CrossOver and try again."
+ static var notActivated: String { "\(notActivatedTitle) \(notActivatedAdvice)" }
+
+ static let defaultOpenssl = "/usr/bin/openssl"
+
+ static func check(
+ crossOverRoot: URL,
+ searchDirs: [URL] = defaultSearchDirs,
+ openssl: String = defaultOpenssl
+ ) -> Status {
+ let status = evaluate(
+ crossOverRoot: crossOverRoot, searchDirs: searchDirs, openssl: openssl
+ )
+ AppLog.note("license: \(status.diagnostic)")
+ return status
+ }
+
+ private static func evaluate(
+ crossOverRoot: URL,
+ searchDirs: [URL],
+ openssl: String
+ ) -> Status {
+ let keyFile = crossOverRoot.appending(
+ path: "share/crossover/data/tie.pub"
+ ).path(percentEncoded: false)
+
+ guard FileManager.default.fileExists(atPath: keyFile) else {
+ return Status(
+ licensed: false,
+ detail: notActivated,
+ diagnostic: "no verification key in the CrossOver bundle"
+ )
+ }
+
+ var rejection: String?
+
+ for dir in searchDirs {
+ let label = dir.path(percentEncoded: false)
+ let license = dir.appending(path: "\(licenseBase).license")
+ .path(percentEncoded: false)
+
+ guard FileManager.default.fileExists(atPath: license) else { continue }
+
+ let signatures = sidecars(in: dir)
+ guard !signatures.isEmpty else {
+ rejection = "the license in \(label) has no signature beside it"
+ continue
+ }
+
+ var unchecked: String?
+
+ for signature in signatures {
+ let result: CommandResult
+ do {
+ result = try Shell.run(openssl, [
+ "dgst", signature.digest, "-verify", keyFile,
+ "-signature", signature.path, license,
+ ])
+ } catch {
+ return Status(
+ licensed: false,
+ detail: notActivated,
+ diagnostic: "could not run \(openssl) to verify the license"
+ )
+ }
+
+ if result.succeeded {
+ return Status(
+ licensed: true,
+ detail: "CrossOver is activated.",
+ diagnostic: "valid license in \(label)"
+ )
+ }
+
+ let trouble = result.stderr.trimmingCharacters(in: .whitespacesAndNewlines)
+ if !trouble.isEmpty {
+ if trouble.localizedCaseInsensitiveContains("unable to load key") {
+ return Status(
+ licensed: false,
+ detail: notActivated,
+ diagnostic: "the verification key in the CrossOver bundle could not be read"
+ )
+ }
+ unchecked = "the license in \(label) could not be checked"
+ }
+ }
+
+ rejection = unchecked
+ ?? "no signature beside the license in \(label) verified against this bundle"
+ }
+
+ return Status(
+ licensed: false,
+ detail: notActivated,
+ diagnostic: rejection ?? "no CrossOver license file found"
+ )
+ }
+
+ static func requireValid(for install: CrossOverInstall) throws {
+ let status = check(crossOverRoot: install.crossOverRoot)
+ guard status.licensed else {
+ throw StepFailure(
+ step: "Verify CrossOver license",
+ detail: status.detail
+ )
+ }
+ }
+
+ private static func sidecars(in dir: URL) -> [(path: String, digest: String)] {
+ let candidates: [(path: String, digest: String)] = [
+ (dir.appending(path: "\(licenseBase).sha256").path(percentEncoded: false), "-sha256"),
+ (dir.appending(path: "\(licenseBase).sig").path(percentEncoded: false), "-sha1"),
+ ]
+ return candidates.filter { FileManager.default.fileExists(atPath: $0.path) }
+ }
+}
diff --git a/app/Sources/NotProtonApp/Model/CrossOverSource.swift b/app/Sources/NotProtonApp/Model/CrossOverSource.swift
new file mode 100644
index 0000000..ade792d
--- /dev/null
+++ b/app/Sources/NotProtonApp/Model/CrossOverSource.swift
@@ -0,0 +1,150 @@
+// Finds CrossOver installs on disk and checks for support
+
+import Foundation
+
+enum CrossOverSupport: Sendable, Equatable {
+ case supported(RunnerBuild)
+ case unsupportedBuild(String)
+ case unreadable
+}
+
+struct CrossOverInstall: Sendable, Identifiable {
+ let bundle: URL
+ let releaseVersion: String?
+ let support: CrossOverSupport
+
+ // Selected by the user rather than found on disk by tool.
+ var isManual = false
+
+ var id: String { bundle.path(percentEncoded: false) }
+ var name: String { bundle.deletingPathExtension().lastPathComponent }
+ var crossOverRoot: URL { SupportPaths.crossOverRoot(inBundle: bundle) }
+
+ var isPreview: Bool { name.localizedCaseInsensitiveContains("Preview") }
+
+ var isUsable: Bool {
+ if case .supported = support { return true }
+ return false
+ }
+}
+
+enum CrossOverSource {
+
+ static let searchRoots: [URL] = [
+ URL(filePath: "/Applications", directoryHint: .isDirectory),
+ SupportPaths.home.appending(path: "Applications", directoryHint: .isDirectory),
+ ]
+
+ private static let manualKey = "manualCrossOverPath"
+
+ static var manualBundle: URL? {
+ get {
+ guard let path = UserDefaults.standard.string(forKey: manualKey), !path.isEmpty else { return nil }
+ return URL(filePath: path, directoryHint: .isDirectory)
+ }
+ set { UserDefaults.standard.set(newValue?.path(percentEncoded: false), forKey: manualKey) }
+ }
+
+ // A CrossOver bundle without this directory is bad!
+ static func looksLikeCrossOver(_ bundle: URL) -> Bool {
+ let root = SupportPaths.crossOverRoot(inBundle: bundle)
+ return FileManager.default.fileExists(
+ atPath: root.appending(path: "lib/wine").path(percentEncoded: false)
+ )
+ }
+
+ static func discover() -> [CrossOverInstall] {
+ let fm = FileManager.default
+ var found: [CrossOverInstall] = []
+ var seen: Set<String> = []
+
+ func consider(_ bundle: URL, isManual: Bool) {
+ let key = bundle.standardizedFileURL.path(percentEncoded: false)
+ guard !seen.contains(key), looksLikeCrossOver(bundle) else { return }
+ seen.insert(key)
+ found.append(inspect(bundle: bundle, isManual: isManual))
+ }
+
+ if let manual = manualBundle { consider(manual, isManual: true) }
+
+ for root in searchRoots {
+ let entries = (try? fm.contentsOfDirectory(at: root, includingPropertiesForKeys: nil)) ?? []
+ for entry in entries where entry.pathExtension == "app" {
+ guard entry.deletingPathExtension().lastPathComponent.hasPrefix("CrossOver") else { continue }
+ consider(entry, isManual: false)
+ }
+ }
+
+ return found.sorted(by: preferred)
+ }
+
+ static func preferred(_ a: CrossOverInstall, _ b: CrossOverInstall) -> Bool {
+ if a.isManual != b.isManual { return a.isManual }
+ if a.isUsable != b.isUsable { return a.isUsable }
+ if a.isPreview != b.isPreview { return a.isPreview }
+ if a.name != b.name { return a.name < b.name }
+ return a.id < b.id
+ }
+
+ static func inspect(bundle: URL, isManual: Bool = false) -> CrossOverInstall {
+ guard let version = releaseVersion(of: bundle) else {
+ return CrossOverInstall(bundle: bundle, releaseVersion: nil, support: .unreadable, isManual: isManual)
+ }
+ guard let hash = Digest.sha256IfPresent(unixLoader(inBundle: bundle)) else {
+ return CrossOverInstall(
+ bundle: bundle, releaseVersion: version, support: .unreadable, isManual: isManual
+ )
+ }
+
+ guard let build = SupportedRunners.build(loaderSHA256: hash) else {
+ return CrossOverInstall(
+ bundle: bundle, releaseVersion: version,
+ support: .unsupportedBuild(version), isManual: isManual
+ )
+ }
+
+ return CrossOverInstall(
+ bundle: bundle, releaseVersion: version, support: .supported(build), isManual: isManual
+ )
+ }
+
+ // CrossOver puts the build date here and the version number in
+ // CFBundleVersion, so this is the string its download page shows.
+ static func releaseVersion(of bundle: URL) -> String? {
+ let plist = bundle.appending(path: "Contents/Info.plist")
+ guard let data = try? Data(contentsOf: plist),
+ let object = try? PropertyListSerialization.propertyList(from: data, format: nil),
+ let dict = object as? [String: Any]
+ else { return nil }
+ return dict["CFBundleShortVersionString"] as? String
+ }
+
+ static func unixLoader(inBundle bundle: URL) -> URL {
+ unixLoader(inRoot: SupportPaths.crossOverRoot(inBundle: bundle))
+ }
+
+ static func unixLoader(inRoot root: URL) -> URL {
+ root.appending(path: "lib/wine/x86_64-unix/wine")
+ }
+
+ static func verifyPatchInputs(root: URL, build: RunnerBuild) throws {
+ for arch in WineArch.allCases {
+ guard let expected = build.cleanNtdll[arch] else { continue }
+ let ntdll = NtdllPatcher.cleanSource(inRoot: root, arch: arch)
+ guard let actual = Digest.sha256IfPresent(ntdll) else {
+ throw StepFailure(
+ step: "Verify CrossOver",
+ detail: "\(arch.rawValue)/ntdll.dll is missing from \(root.path(percentEncoded: false))."
+ )
+ }
+ guard actual == expected else {
+ throw StepFailure(
+ step: "Verify CrossOver",
+ detail: "\(arch.rawValue)/\(ntdll.lastPathComponent) is not the build "
+ + "\(build.bundleVersion) copy. Expected \(expected.prefix(16)), "
+ + "found \(actual.prefix(16))."
+ )
+ }
+ }
+ }
+}
diff --git a/app/Sources/NotProtonApp/Model/InstallPayload.swift b/app/Sources/NotProtonApp/Model/InstallPayload.swift
new file mode 100644
index 0000000..e095af3
--- /dev/null
+++ b/app/Sources/NotProtonApp/Model/InstallPayload.swift
@@ -0,0 +1,73 @@
+// Deploys core NotProton components into the copy of CrossOver that NotProton deploys to the Steam location
+
+import Foundation
+
+enum InstallPayload {
+ static let step = "Find NotProton's components"
+
+ struct Located: Sendable {
+ let dylib: URL
+ let overlayShim: URL
+ let iconmaker: URL
+ let appinfo: URL
+
+ let signatures: [URL]
+ }
+
+ static func root(in bundle: Bundle = .module) throws -> URL {
+ guard let url = bundle.url(forResource: "payload", withExtension: nil) else {
+ throw StepFailure(
+ step: step,
+ detail: "This build of NotProton carries no components at all."
+ )
+ }
+ return url
+ }
+
+ static func locate(in bundle: Bundle = .module) throws -> Located {
+ try locate(root: try root(in: bundle))
+ }
+
+ static func locate(root: URL) throws -> Located {
+ let files = FileManager.default
+
+ let dylib = root.appending(path: SupportPaths.dylibName)
+ let shim = root.appending(path: "overlay-shim.dylib")
+ let iconmaker = root.appending(path: "iconmaker")
+ let appinfo = root.appending(path: "appinfo")
+
+ var missing: [String] = []
+ if !files.fileExists(atPath: dylib.path(percentEncoded: false)) {
+ missing.append(SupportPaths.dylibName)
+ }
+ if !files.fileExists(atPath: shim.path(percentEncoded: false)) {
+ missing.append("overlay-shim.dylib")
+ }
+ if !files.fileExists(atPath: iconmaker.path(percentEncoded: false)) {
+ missing.append("iconmaker")
+ }
+ if !files.fileExists(atPath: appinfo.path(percentEncoded: false)) {
+ missing.append("appinfo")
+ }
+
+ let signatureDir = root.appending(path: "signatures/macos.arm64")
+ let signatures = ((try? files.contentsOfDirectory(
+ at: signatureDir, includingPropertiesForKeys: nil
+ )) ?? []).filter { $0.pathExtension == "json" }.sorted { $0.lastPathComponent < $1.lastPathComponent }
+
+ if signatures.isEmpty { missing.append("signatures/macos.arm64/*.json") }
+
+ guard missing.isEmpty else {
+ throw StepFailure(
+ step: step,
+ detail: "These components are missing: \(missing.joined(separator: ", ")). "
+ + "Run make app-payload and build the app again."
+ )
+ }
+
+ return Located(
+ dylib: dylib, overlayShim: shim, iconmaker: iconmaker,
+ appinfo: appinfo, signatures: signatures
+ )
+ }
+}
diff --git a/app/Sources/NotProtonApp/Model/NtdllPatcher.swift b/app/Sources/NotProtonApp/Model/NtdllPatcher.swift
new file mode 100644
index 0000000..0fffcdf
--- /dev/null
+++ b/app/Sources/NotProtonApp/Model/NtdllPatcher.swift
@@ -0,0 +1,459 @@
+// Patches CrossOver's ntdll.dll so that lsteamclient is loaded.
+
+import Foundation
+
+// jump site
+struct NtdllHook: Sendable {
+ let rva: Int
+
+ // The bytes that are supposed to be at `rva`.
+ let stolen: [UInt8]
+}
+
+struct NtdllPatch: Sendable {
+ let arch: WineArch
+
+ let payloadResource: String
+ let payloadSHA256: String
+
+ // cave
+ let caveRVA: Int
+ let payloadRVA: Int
+
+ let hooks: [NtdllHook]
+
+
+ let caveSize: Int
+ let cavePad: UInt8
+
+ let machine: UInt16
+ let magic: UInt16
+ let imageBase: UInt64
+}
+
+enum NtdllPatcher {
+
+ static let step = "Patch ntdll"
+
+ private static let magicPE32Plus: UInt16 = 0x20b
+ private static let machineARM64: UInt16 = 0xaa64
+
+
+ static let byBuild: [String: [NtdllPatch]] = [
+ "27.0.0.40921": [
+ NtdllPatch(
+ arch: .x86_64Windows,
+ payloadResource: "detour2",
+ payloadSHA256: "4ce2ddc11c433fe15f78633fc5c1fda8b27fa642426cb26378f7d7d7b54a79f8",
+ caveRVA: 0x80be0,
+ payloadRVA: 0x80be0,
+ hooks: [
+ NtdllHook(rva: 0x51f15,
+ stolen: [0x48, 0x83, 0xbc, 0x24, 0xf0, 0x00, 0x00, 0x00, 0x00]),
+ ],
+ caveSize: 1056,
+ cavePad: 0x00,
+ machine: 0x8664,
+ magic: 0x20b,
+ imageBase: 0x1_7000_0000
+ ),
+ NtdllPatch(
+ arch: .i386Windows,
+ payloadResource: "detour32",
+ payloadSHA256: "2758d4f6783c853c460187f83f4fb9b1105380d194126ef83fc85e2596d3036a",
+ caveRVA: 0x7c830,
+ payloadRVA: 0x7c830,
+ hooks: [
+ NtdllHook(rva: 0x4d828, stolen: [0xf6, 0x45, 0xbc, 0x02, 0x75, 0x26]),
+ ],
+ caveSize: 2000,
+ cavePad: 0x00,
+ machine: 0x14c,
+ magic: 0x10b,
+ imageBase: 0x7bc0_0000
+ ),
+ ],
+ // FEX patches
+ "27.0.0.40921-fex": [
+ NtdllPatch(
+ arch: .i386Windows,
+ payloadResource: "detour32-fex",
+ payloadSHA256: "b4c697ba396ecb59125c505666ad3465d1208b8a1e3e53a0c457657b341376b9",
+ caveRVA: 0x6b2fe,
+ payloadRVA: 0x6b300,
+ hooks: [
+ NtdllHook(rva: 0x2ee12, stolen: [0x8b, 0x45, 0x14, 0xa8, 0x02]),
+ ],
+ caveSize: 3330,
+ cavePad: 0xcc,
+ machine: 0x14c,
+ magic: 0x10b,
+ imageBase: 0x7bc0_0000
+ ),
+ NtdllPatch(
+ arch: .aarch64Windows,
+ payloadResource: "detour64-fex",
+ payloadSHA256: "bee4ee13c235bd5de3cb6ce840b9695effd5623132f6dc0d137496d6a5330f5e",
+ caveRVA: 0xf1185,
+ payloadRVA: 0xf1190,
+ hooks: [
+ NtdllHook(rva: 0x48004, stolen: [0x1f, 0x20, 0x03, 0xd5]),
+ NtdllHook(rva: 0xa71bc, stolen: [0x1f, 0x20, 0x03, 0xd5]),
+ ],
+ caveSize: 61051,
+ cavePad: 0xcc,
+ machine: 0xaa64,
+ magic: 0x20b,
+ imageBase: 0x1_8000_0000
+ ),
+ ],
+ ]
+
+ static func patches(for build: RunnerBuild) -> [NtdllPatch] {
+ byBuild[build.id] ?? []
+ }
+
+ static func patch(for arch: WineArch, in build: RunnerBuild) -> NtdllPatch? {
+ patches(for: build).first { $0.arch == arch }
+ }
+
+ // Patch
+ static func apply(_ patch: NtdllPatch, to image: Data, payload: Data) throws -> Data {
+ var bytes = [UInt8](image)
+ try validateHeaders(patch, bytes)
+
+ let caveOffset = try fileOffset(of: patch.caveRVA, in: bytes, describing: "cave", patch: patch)
+ let payloadOffset = try fileOffset(of: patch.payloadRVA, in: bytes, describing: "payload", patch: patch)
+
+ let intoCave = patch.payloadRVA - patch.caveRVA
+ guard intoCave >= 0 else {
+ throw StepFailure(
+ step: step,
+ detail: "The \(patch.arch.rawValue) detour goes to \(hex(patch.payloadRVA)), below its "
+ + "cave at \(hex(patch.caveRVA)), so writing it would land in live code."
+ )
+ }
+
+ let room = patch.caveSize - intoCave
+ if payload.count > room {
+ throw StepFailure(
+ step: step,
+ detail: "The \(patch.arch.rawValue) detour is \(payload.count) bytes and the cave holds "
+ + "\(room), so writing it would overrun into live code."
+ )
+ }
+
+ try requireRange(caveOffset, patch.caveSize, in: bytes, describing: "The cave")
+ guard bytes[caveOffset ..< caveOffset + patch.caveSize].allSatisfy({ $0 == patch.cavePad }) else {
+ throw StepFailure(
+ step: step,
+ detail: "The \(patch.arch.rawValue) cave at \(hex(patch.caveRVA)) is not empty. "
+ + "This ntdll is either already patched or not the build its hash claimed."
+ )
+ }
+
+ // check files
+ var branches: [(offset: Int, code: [UInt8])] = []
+ for hook in patch.hooks {
+ let offset = try fileOffset(of: hook.rva, in: bytes, describing: "hook site", patch: patch)
+ try requireRange(offset, hook.stolen.count, in: bytes, describing: "The hook site")
+ let present = Array(bytes[offset ..< offset + hook.stolen.count])
+ guard present == hook.stolen else {
+ throw StepFailure(
+ step: step,
+ detail: "The \(patch.arch.rawValue) hook site at \(hex(hook.rva)) holds \(hex(present)) "
+ + "instead of \(hex(hook.stolen)), so the offsets do not belong to this ntdll."
+ )
+ }
+ branches.append(
+ (offset, try branch(patch, from: hook.rva, filling: hook.stolen.count))
+ )
+ }
+
+ bytes.replaceSubrange(payloadOffset ..< payloadOffset + payload.count, with: payload)
+ for branch in branches {
+ bytes.replaceSubrange(branch.offset ..< branch.offset + branch.code.count, with: branch.code)
+ }
+
+ return Data(bytes)
+ }
+
+ private static func branch(_ patch: NtdllPatch, from hookRVA: Int, filling width: Int) throws -> [UInt8] {
+ patch.machine == machineARM64
+ ? try branchLink(from: hookRVA, to: patch.payloadRVA, filling: width)
+ : try relativeJump(from: hookRVA, to: patch.payloadRVA, filling: width)
+ }
+
+ private static func branchLink(from hookRVA: Int, to payloadRVA: Int, filling width: Int) throws -> [UInt8] {
+ guard width == 4 else {
+ throw StepFailure(
+ step: step, detail: "A hook site of \(width) bytes cannot hold a branch and link."
+ )
+ }
+
+ let delta = payloadRVA - hookRVA
+ guard delta % 4 == 0, (-0x800_0000 ..< 0x800_0000).contains(delta) else {
+ throw StepFailure(
+ step: step,
+ detail: "The detour is \(delta) bytes from the hook site, which a branch and link "
+ + "cannot reach."
+ )
+ }
+
+ let encoded = UInt32(0x9400_0000) | (UInt32(bitPattern: Int32(delta) >> 2) & 0x03ff_ffff)
+ return withUnsafeBytes(of: encoded.littleEndian, Array.init)
+ }
+
+
+ private static func relativeJump(from hookRVA: Int, to caveRVA: Int, filling width: Int) throws -> [UInt8] {
+ guard width >= 5 else {
+ throw StepFailure(
+ step: step, detail: "A hook site of \(width) bytes cannot hold a relative jump."
+ )
+ }
+
+ let delta = caveRVA - (hookRVA + 5)
+ guard let displacement = Int32(exactly: delta) else {
+ throw StepFailure(
+ step: step,
+ detail: "The cave is \(delta) bytes from the hook site, which a relative jump cannot reach."
+ )
+ }
+
+ var jump: [UInt8] = [0xe9]
+ withUnsafeBytes(of: displacement.littleEndian) { jump.append(contentsOf: $0) }
+ jump.append(contentsOf: repeatElement(0xcc, count: width - 5))
+ return jump
+ }
+
+
+ private static func validateHeaders(_ patch: NtdllPatch, _ bytes: [UInt8]) throws {
+ let pe = Int(try u32(bytes, 0x3c))
+ guard try u32(bytes, pe) == 0x0000_4550 else {
+ throw StepFailure(
+ step: step, detail: "The \(patch.arch.rawValue) ntdll has no PE header where its DOS stub points."
+ )
+ }
+
+ let machine = try u16(bytes, pe + 4)
+ guard machine == patch.machine else {
+ throw StepFailure(
+ step: step,
+ detail: "The \(patch.arch.rawValue) ntdll is machine \(hex(Int(machine))), "
+ + "expected \(hex(Int(patch.machine)))."
+ )
+ }
+
+ let magic = try u16(bytes, pe + 24)
+ guard magic == patch.magic else {
+ throw StepFailure(
+ step: step,
+ detail: "The \(patch.arch.rawValue) ntdll optional header is \(hex(Int(magic))), "
+ + "expected \(hex(Int(patch.magic)))."
+ )
+ }
+
+ let imageBase = magic == magicPE32Plus
+ ? try u64(bytes, pe + 24 + 24)
+ : UInt64(try u32(bytes, pe + 24 + 28))
+ guard imageBase == patch.imageBase else {
+ throw StepFailure(
+ step: step,
+ detail: "The \(patch.arch.rawValue) ntdll is based at \(hex(imageBase)), "
+ + "and the detour was linked against \(hex(patch.imageBase))."
+ )
+ }
+ }
+
+ private static func fileOffset(
+ of rva: Int, in bytes: [UInt8], describing what: String, patch: NtdllPatch
+ ) throws -> Int {
+ let pe = Int(try u32(bytes, 0x3c))
+ let sections = Int(try u16(bytes, pe + 6))
+ let optionalSize = Int(try u16(bytes, pe + 20))
+ let table = pe + 24 + optionalSize
+
+ for index in 0 ..< sections {
+ let entry = table + index * 40
+ let virtualSize = Int(try u32(bytes, entry + 8))
+ let virtualAddress = Int(try u32(bytes, entry + 12))
+ let rawSize = Int(try u32(bytes, entry + 16))
+ let rawOffset = Int(try u32(bytes, entry + 20))
+
+ if rawSize == 0 || rawOffset == 0 { continue }
+
+ let span = max(virtualSize, rawSize)
+ guard rva >= virtualAddress, rva < virtualAddress + span else { continue }
+
+ let offset = rawOffset + (rva - virtualAddress)
+ try requireRange(offset, 1, in: bytes, describing: "The \(what)")
+ return offset
+ }
+
+ throw StepFailure(
+ step: step,
+ detail: "RVA \(hex(rva)) falls in no mapped section of the \(patch.arch.rawValue) ntdll, "
+ + "so the \(what) cannot be located."
+ )
+ }
+
+ private static func requireRange(
+ _ offset: Int, _ length: Int, in bytes: [UInt8], describing what: String
+ ) throws {
+ guard offset >= 0, length >= 0, offset <= bytes.count - length else {
+ throw StepFailure(
+ step: step,
+ detail: "\(what) at \(hex(offset)) spans \(length) bytes, past the end of a "
+ + "\(bytes.count) byte file."
+ )
+ }
+ }
+
+ private static func u16(_ bytes: [UInt8], _ offset: Int) throws -> UInt16 {
+ try requireRange(offset, 2, in: bytes, describing: "A header field")
+ return UInt16(bytes[offset]) | UInt16(bytes[offset + 1]) << 8
+ }
+
+ private static func u32(_ bytes: [UInt8], _ offset: Int) throws -> UInt32 {
+ try requireRange(offset, 4, in: bytes, describing: "A header field")
+ var value: UInt32 = 0
+ for index in (0 ..< 4).reversed() { value = value << 8 | UInt32(bytes[offset + index]) }
+ return value
+ }
+
+ private static func u64(_ bytes: [UInt8], _ offset: Int) throws -> UInt64 {
+ try requireRange(offset, 8, in: bytes, describing: "A header field")
+ var value: UInt64 = 0
+ for index in (0 ..< 8).reversed() { value = value << 8 | UInt64(bytes[offset + index]) }
+ return value
+ }
+
+ private static func hex(_ value: Int) -> String { "0x" + String(value, radix: 16) }
+ private static func hex(_ value: UInt64) -> String { "0x" + String(value, radix: 16) }
+ private static func hex(_ bytes: [UInt8]) -> String {
+ bytes.map { String(format: "%02x", $0) }.joined()
+ }
+
+ // Resources
+
+ static func payload(for patch: NtdllPatch) throws -> Data {
+ guard let url = Bundle.module.url(forResource: patch.payloadResource, withExtension: "bin") else {
+ throw StepFailure(
+ step: step,
+ detail: "\(patch.payloadResource).bin is missing from the app's resources."
+ )
+ }
+
+ let data: Data
+ do {
+ data = try Data(contentsOf: url)
+ } catch {
+ throw StepFailure(
+ step: step,
+ detail: "\(patch.payloadResource).bin could not be read. \(error.localizedDescription)"
+ )
+ }
+
+ let hash = Digest.sha256(of: data)
+ guard hash == patch.payloadSHA256 else {
+ throw StepFailure(
+ step: step,
+ detail: "\(patch.payloadResource).bin hashes \(hash.prefix(16)) and should hash "
+ + "\(patch.payloadSHA256.prefix(16)), so the shipped detour is not the one that was built."
+ )
+ }
+ return data
+ }
+
+ static func cleanSource(inRoot root: URL, arch: WineArch) -> URL {
+ Clean.copy(of: root.appending(path: "lib/wine/\(arch.rawValue)/ntdll.dll"))
+ }
+
+ @discardableResult
+ static func write(
+ _ patch: NtdllPatch, build: RunnerBuild, from source: URL, to destination: URL
+ ) throws -> String {
+ guard let expectedInput = build.cleanNtdll[patch.arch],
+ let expectedOutput = build.patchedNtdll[patch.arch]
+ else {
+ throw StepFailure(
+ step: step,
+ detail: "Build \(build.bundleVersion) records no \(patch.arch.rawValue) ntdll hashes."
+ )
+ }
+
+ guard let inputHash = Digest.sha256IfPresent(source) else {
+ throw StepFailure(
+ step: step, detail: "There is no ntdll to patch at \(source.path(percentEncoded: false))."
+ )
+ }
+ guard inputHash == expectedInput else {
+ throw StepFailure(
+ step: step,
+ detail: "The \(patch.arch.rawValue) ntdll at \(source.path(percentEncoded: false)) hashes "
+ + "\(inputHash.prefix(16)) and build \(build.bundleVersion) expects "
+ + "\(expectedInput.prefix(16)). It is already patched, or from another CrossOver build."
+ )
+ }
+
+ let image: Data
+ do {
+ image = try Data(contentsOf: source)
+ } catch {
+ throw StepFailure(
+ step: step,
+ detail: "\(source.path(percentEncoded: false)) could not be read. \(error.localizedDescription)"
+ )
+ }
+
+ let patched = try apply(patch, to: image, payload: try payload(for: patch))
+
+ let outputHash = Digest.sha256(of: patched)
+ guard outputHash == expectedOutput else {
+ throw StepFailure(
+ step: step,
+ detail: "The patched \(patch.arch.rawValue) ntdll hashes \(outputHash.prefix(16)) and build "
+ + "\(build.bundleVersion) expects \(expectedOutput.prefix(16)). Nothing was written."
+ )
+ }
+
+ try atomicReplace(destination, with: patched, step: step)
+ return outputHash
+ }
+
+ @discardableResult
+ static func stage(
+ build: RunnerBuild, runnerRoot: URL, bridge: URL = SupportPaths.bridge
+ ) throws -> [WineArch] {
+ var written: [WineArch] = []
+
+ for patch in patches(for: build) {
+ let destination = bridge.appending(path: "wine/\(patch.arch.rawValue)/ntdll.dll")
+
+ if Digest.sha256IfPresent(destination) == build.patchedNtdll[patch.arch] { continue }
+
+ try write(patch, build: build, from: cleanSource(inRoot: runnerRoot, arch: patch.arch),
+ to: destination)
+ written.append(patch.arch)
+ }
+
+ prune(keeping: patches(for: build).map(\.arch), in: bridge)
+
+ return written
+ }
+
+ private static func prune(keeping arches: [WineArch], in bridge: URL) {
+ let fm = FileManager.default
+
+ for arch in WineArch.allCases where !arches.contains(arch) {
+ let directory = bridge.appending(path: "wine/\(arch.rawValue)")
+ try? fm.removeItem(at: directory.appending(path: "ntdll.dll"))
+
+ let path = directory.path(percentEncoded: false)
+ if let left = try? fm.contentsOfDirectory(atPath: path), left.isEmpty {
+ try? fm.removeItem(at: directory)
+ }
+ }
+ }
+
+}
diff --git a/app/Sources/NotProtonApp/Model/PayloadManifest.swift b/app/Sources/NotProtonApp/Model/PayloadManifest.swift
new file mode 100644
index 0000000..1492b3c
--- /dev/null
+++ b/app/Sources/NotProtonApp/Model/PayloadManifest.swift
@@ -0,0 +1,95 @@
+// NotProton payload manifest stuff
+
+import Foundation
+
+enum PayloadOrigin: String, Sendable, CaseIterable {
+ case built, patched, valve
+
+
+ var isFetchable: Bool { self == .valve }
+}
+
+struct PayloadEntry: Sendable, Equatable, Identifiable {
+ let origin: PayloadOrigin
+ let path: String
+
+ var id: String { path }
+}
+
+struct PayloadManifest: Sendable {
+ let entries: [PayloadEntry]
+
+ func paths(origin: PayloadOrigin) -> [String] {
+ entries.filter { $0.origin == origin }.map(\.path)
+ }
+
+ static let resourceName = "payload"
+ static let resourceExtension = "manifest"
+
+ static func bundled() throws -> PayloadManifest {
+ guard let url = Bundle.module.url(
+ forResource: resourceName, withExtension: resourceExtension
+ ) else {
+ throw StepFailure(
+ step: "Read the component list",
+ detail: "\(resourceName).\(resourceExtension) is missing from the app's resources."
+ )
+ }
+ return try load(from: url)
+ }
+
+ static func load(from url: URL) throws -> PayloadManifest {
+ let data: Data
+ do {
+ data = try Data(contentsOf: url)
+ } catch {
+ throw StepFailure(
+ step: "Read the component list",
+ detail: "\(url.path(percentEncoded: false)) could not be read. \(error.localizedDescription)"
+ )
+ }
+ return try parse(String(decoding: data, as: UTF8.self))
+ }
+
+ static func parse(_ text: String) throws -> PayloadManifest {
+ var entries: [PayloadEntry] = []
+ var seen = Set<String>()
+
+ for (index, rawLine) in text.split(separator: "\n", omittingEmptySubsequences: false).enumerated() {
+ let line = rawLine.trimmingCharacters(in: .whitespaces)
+ if line.isEmpty || line.hasPrefix("#") { continue }
+
+ let fields = line.split(separator: " ", omittingEmptySubsequences: true)
+ let number = index + 1
+ guard fields.count == 2 else {
+ throw StepFailure(
+ step: "Read the component list",
+ detail: "Line \(number) is not an origin and a path: \(line)"
+ )
+ }
+ guard let origin = PayloadOrigin(rawValue: String(fields[0])) else {
+ throw StepFailure(
+ step: "Read the component list",
+ detail: "Line \(number) has an unknown origin \(fields[0]). "
+ + "Known: \(PayloadOrigin.allCases.map(\.rawValue).joined(separator: ", "))."
+ )
+ }
+
+ let path = String(fields[1])
+ guard seen.insert(path).inserted else {
+ throw StepFailure(
+ step: "Read the component list",
+ detail: "Line \(number) repeats \(path)."
+ )
+ }
+
+ entries.append(PayloadEntry(origin: origin, path: path))
+ }
+
+ guard !entries.isEmpty else {
+ throw StepFailure(step: "Read the component list", detail: "The component list has no entries.")
+ }
+
+ return PayloadManifest(entries: entries)
+ }
+}
diff --git a/app/Sources/NotProtonApp/Model/PayloadState.swift b/app/Sources/NotProtonApp/Model/PayloadState.swift
new file mode 100644
index 0000000..e66c30e
--- /dev/null
+++ b/app/Sources/NotProtonApp/Model/PayloadState.swift
@@ -0,0 +1,100 @@
+// Checks files on disk versus the manifest, presents state to user
+
+import Foundation
+
+struct PayloadState: Sendable {
+ var expected: Int
+ var present: Int
+ var missing: [PayloadEntry]
+ var overlayShimPresent: Bool
+ var iconmakerPresent: Bool
+ var appinfoPresent: Bool
+ var signatureDatabase: String?
+ var legacyCompatPresent: Int
+ var legacyCompatExpected: Int
+ var manifestProblem: String?
+
+ var isComplete: Bool {
+ manifestProblem == nil && missing.isEmpty && overlayShimPresent && iconmakerPresent
+ && appinfoPresent && signatureDatabase != nil
+ }
+
+ var isEmpty: Bool {
+ present == 0 && !overlayShimPresent && !iconmakerPresent && !appinfoPresent
+ && signatureDatabase == nil
+ }
+
+ func missing(origin: PayloadOrigin) -> [PayloadEntry] {
+ missing.filter { $0.origin == origin }
+ }
+}
+
+enum PayloadInspector {
+
+ static func inspect(bridge: URL = SupportPaths.bridge, build: RunnerBuild? = nil) -> PayloadState {
+ let fm = FileManager.default
+
+ var expected = 0
+ var missing: [PayloadEntry] = []
+ var problem: String?
+
+ do {
+ let manifest = try PayloadManifest.bundled()
+ let entries = manifest.entries.filter { applies($0, to: build) }
+ expected = entries.count
+ missing = entries.filter {
+ !fm.fileExists(atPath: bridge.appending(path: $0.path).path(percentEncoded: false))
+ }
+ } catch {
+ problem = error.localizedDescription
+ }
+
+ let legacyNames = ((try? ValvePackageManifest.bundled())?.files ?? [])
+ .filter { $0.bridgePath.hasPrefix("legacycompat/") }
+ .map { URL(filePath: $0.bridgePath).lastPathComponent }
+ let legacyPresent = legacyNames.filter {
+ fm.fileExists(
+ atPath: SupportPaths.Steam.legacyCompat
+ .appending(path: $0).path(percentEncoded: false)
+ )
+ }.count
+
+ return PayloadState(
+ expected: expected,
+ present: expected - missing.count,
+ missing: missing,
+ overlayShimPresent: fm.fileExists(atPath: SupportPaths.overlayShim.path(percentEncoded: false)),
+ iconmakerPresent: fm.fileExists(atPath: SupportPaths.iconmaker.path(percentEncoded: false)),
+ appinfoPresent: fm.fileExists(atPath: SupportPaths.appinfo.path(percentEncoded: false)),
+ signatureDatabase: newestSignatureDatabase(),
+ legacyCompatPresent: legacyPresent,
+ legacyCompatExpected: legacyNames.count,
+ manifestProblem: problem
+ )
+ }
+
+ private static func applies(_ entry: PayloadEntry, to build: RunnerBuild?) -> Bool {
+ guard entry.origin == .patched, let build,
+ let arch = WineArch.allCases.first(where: {
+ entry.path == "wine/\($0.rawValue)/ntdll.dll"
+ })
+ else { return true }
+ return build.patchedNtdll[arch] != nil
+ }
+
+ static func newestSignatureDatabase(in directory: URL = SupportPaths.signatures) -> String? {
+ let entries = (try? FileManager.default.contentsOfDirectory(
+ at: directory, includingPropertiesForKeys: nil
+ )) ?? []
+ return entries
+ .map(\.lastPathComponent)
+ .compactMap { name -> (name: String, build: UInt64)? in
+ guard name.hasSuffix(".json"),
+ let build = UInt64(name.dropLast(5)), build > 0
+ else { return nil }
+ return (name, build)
+ }
+ .max { $0.build < $1.build }?
+ .name
+ }
+}
diff --git a/app/Sources/NotProtonApp/Model/PrefixPrompt.swift b/app/Sources/NotProtonApp/Model/PrefixPrompt.swift
new file mode 100644
index 0000000..115785a
--- /dev/null
+++ b/app/Sources/NotProtonApp/Model/PrefixPrompt.swift
@@ -0,0 +1,114 @@
+// Strings for the delete/recreate confirmation prompts. Kept out of the view so
+// they can be tested. Dumb development artifact, basically.
+
+import Foundation
+
+enum PrefixPrompt {
+
+ static func deleteTitle(_ targets: [WinePrefix]) -> String {
+ switch targets.count {
+ case 0: "Delete prefix?"
+ case 1: "Delete the prefix for \(targets[0].title)?"
+ default: "Delete \(targets.count) prefixes?"
+ }
+ }
+
+ static func deleteButton(_ targets: [WinePrefix]) -> String {
+ targets.count > 1 ? "Delete \(targets.count) Prefixes" : "Delete Prefix"
+ }
+
+ static func deleteMessage(_ targets: [WinePrefix]) -> String {
+ guard targets.count > 1 else {
+ return sentences([
+ "This will DELETE the game's prefix.",
+ "The game SAVE DATA inside the prefix WILL BE LOST.",
+ "Are you sure you want to do this?",
+ ])
+ }
+ return sentences([
+ "This will DELETE the prefixes for \(targets.count) games.",
+ "The game SAVE DATA inside them WILL BE LOST.",
+ "Are you sure you want to do this?",
+ ])
+ }
+
+ static func rebuildTitle(_ targets: [WinePrefix]) -> String {
+ switch targets.count {
+ case 0: "Rebuild prefix?"
+ case 1: "Rebuild the prefix for \(targets[0].title)?"
+ default: "Rebuild \(targets.count) prefixes?"
+ }
+ }
+
+ static func rebuildButton(_ targets: [WinePrefix]) -> String {
+ targets.count > 1 ? "Rebuild \(targets.count) Prefixes" : "Rebuild Prefix"
+ }
+
+ static func rebuildWithBackupButton(_ targets: [WinePrefix]) -> String {
+ targets.count > 1
+ ? "Back Up and Rebuild \(targets.count) Prefixes" : "Back Up and Rebuild"
+ }
+
+ static func rebuildWithoutBackupButton(_ targets: [WinePrefix]) -> String {
+ targets.count > 1
+ ? "Rebuild \(targets.count) Prefixes Without Backing Up"
+ : "Rebuild Without Backing Up"
+ }
+
+ static func backUpTitle(_ targets: [WinePrefix]) -> String {
+ switch targets.count {
+ case 0: "Back up prefix?"
+ case 1: "Back up the prefix for \(targets[0].title)?"
+ default: "Back up \(targets.count) prefixes?"
+ }
+ }
+
+ static func backUpButton(_ targets: [WinePrefix]) -> String {
+ targets.count > 1 ? "Back Up \(targets.count) Prefixes" : "Back Up Prefix"
+ }
+
+ static func backUpMessage(_ targets: [WinePrefix] = []) -> String {
+ targets.count > 1
+ ? "Are you sure you want to back up these prefixes?"
+ : "Are you sure you want to back up this prefix?"
+ }
+
+ static func rebuildMessage() -> String {
+ sentences([
+ "This tool is intended to repair a prefix after switching between Rosetta/FEX CrossOver.",
+ "It will replace the DLLs used by CrossOver with ones that match your compatibility tool.",
+ "This can also fix issues where a game previously started/worked and does not work now, "
+ + "even if you did not switch CrossOver types.",
+ "You will not lose saves by using this tool.",
+ ])
+ }
+
+ static func deleteBackupsTitle(_ targets: [PrefixBackup]) -> String {
+ switch targets.count {
+ case 0: "Delete backup?"
+ case 1: "Delete the backup for \(targets[0].title)?"
+ default: "Delete \(targets.count) backups?"
+ }
+ }
+
+ static func deleteBackupsButton(_ targets: [PrefixBackup]) -> String {
+ targets.count > 1 ? "Delete \(targets.count) Backups" : "Delete Backup"
+ }
+
+ static func deleteBackupsMessage(_ targets: [PrefixBackup] = []) -> String {
+ guard targets.count > 1 else {
+ return sentences([
+ "Are you sure you want to delete this backup?",
+ "Any data in it will be lost.",
+ ])
+ }
+ return sentences([
+ "Are you sure you want to delete these \(targets.count) backups?",
+ "Any data in them will be lost.",
+ ])
+ }
+
+ private static func sentences(_ parts: [String]) -> String {
+ parts.joined(separator: " ")
+ }
+}
diff --git a/app/Sources/NotProtonApp/Model/PrefixRebuild.swift b/app/Sources/NotProtonApp/Model/PrefixRebuild.swift
new file mode 100644
index 0000000..4efde42
--- /dev/null
+++ b/app/Sources/NotProtonApp/Model/PrefixRebuild.swift
@@ -0,0 +1,338 @@
+// Prefix rebuild feature, experimental, blah blah.
+
+import Foundation
+
+extension PrefixTools {
+ @discardableResult
+ static func recreate(
+ _ prefix: WinePrefix,
+ runner: URL = SupportPaths.currentRunner,
+ now: Date = .now,
+ keepBackup: Bool = true
+ ) throws -> URL? {
+ guard !PrefixStore.isInUse(prefix) else {
+ throw StepFailure(
+ step: "Recreate prefix",
+ detail: "\(prefix.title) is running. Quit the game first."
+ )
+ }
+
+ if let held = PrefixStore.backups(of: prefix).last,
+ !FileManager.default.fileExists(
+ atPath: prefix.pfx.appending(path: "user.reg").path(percentEncoded: false))
+ {
+ throw StepFailure(
+ step: "Recreate prefix",
+ detail: "\(held.path(percentEncoded: false)) is left from a rebuild that did not "
+ + "finish and may hold the only copy of the saves. Move it somewhere safe, "
+ + "then try again."
+ )
+ }
+
+ let loader = loader(runner: runner)
+ guard FileManager.default.isExecutableFile(atPath: loader.path(percentEncoded: false)) else {
+ throw StepFailure(
+ step: "Recreate prefix",
+ detail: "No compatibility tool at \(loader.path(percentEncoded: false)). "
+ + "Use Set Up Compatibility Tool first."
+ )
+ }
+
+ let fm = FileManager.default
+ let fresh = prefix.root.appending(path: "pfx.rebuild")
+ if fm.fileExists(atPath: fresh.path(percentEncoded: false)) {
+ try fm.removeItem(at: fresh)
+ }
+ defer { try? fm.removeItem(at: fresh) }
+ try fm.createDirectory(at: fresh, withIntermediateDirectories: true)
+
+ var environment = environment(prefix: prefix, runner: runner)
+ environment["WINEPREFIX"] = fresh.path(percentEncoded: false)
+ layOutProfile(in: fresh)
+ _ = try Shell.check(loader.path(percentEncoded: false), ["wineboot", "--init"], environment: environment)
+
+ let carry = Carry(from: prefix.pfx, to: fresh)
+ carry.userData()
+ carry.strayFolders()
+
+ if let first = carry.lost.first {
+ AppLog.note("rebuild \(prefix.appID) refused, did not carry: \(carry.lost.joined(separator: ", "))")
+ throw StepFailure(
+ step: "Recreate prefix",
+ detail: "\(first) could not be copied out of the prefix. The prefix has been "
+ + "left as it was and nothing has been lost. Check free space and "
+ + "permissions, then try again."
+ )
+ }
+
+ let parked = fm.fileExists(atPath: prefix.pfx.path(percentEncoded: false))
+ let previous = backupSlot(in: prefix.root, at: now)
+ if parked {
+ try fm.moveItem(at: prefix.pfx, to: previous)
+ }
+ do {
+ try fm.moveItem(at: fresh, to: prefix.pfx)
+ } catch {
+ if parked { try? fm.moveItem(at: previous, to: prefix.pfx) }
+ throw error
+ }
+ guard parked else { return nil }
+ guard keepBackup else {
+ try? fm.removeItem(at: previous)
+ return nil
+ }
+ return previous
+ }
+
+ @discardableResult
+ static func backUp(_ prefix: WinePrefix, now: Date = .now) throws -> URL {
+ guard !PrefixStore.isInUse(prefix) else {
+ throw StepFailure(
+ step: "Back up prefix",
+ detail: "\(prefix.title) is running. Quit the game first."
+ )
+ }
+
+ let fm = FileManager.default
+ guard fm.fileExists(atPath: prefix.pfx.path(percentEncoded: false)) else {
+ throw StepFailure(
+ step: "Back up prefix",
+ detail: "\(prefix.title) does not appear to have a prefix to back up."
+ )
+ }
+
+ let slot = backupSlot(in: prefix.root, at: now)
+ do {
+ try fm.copyItem(at: prefix.pfx, to: slot)
+ } catch {
+ try? fm.removeItem(at: slot)
+ throw error
+ }
+ return slot
+ }
+
+ private static func backupSlot(in root: URL, at now: Date) -> URL {
+ let stamp = PrefixStore.backupClock().string(from: now)
+
+ let fm = FileManager.default
+ var slot = root.appending(path: "\(PrefixStore.backupPrefix)-\(stamp)")
+ var next = 2
+ while fm.fileExists(atPath: slot.path(percentEncoded: false)) {
+ slot = root.appending(path: "\(PrefixStore.backupPrefix)-\(stamp)-\(next)")
+ next += 1
+ }
+ return slot
+ }
+
+ private static func layOutProfile(in fresh: URL) {
+ let fm = FileManager.default
+ let users = fresh.appending(path: "drive_c/users")
+ let profile = users.appending(path: "steamuser")
+ try? fm.createDirectory(at: profile, withIntermediateDirectories: true)
+
+ for folder in [
+ "Documents", "Desktop", "Downloads", "Music", "Pictures", "Videos", "Templates",
+ "AppData/Local", "AppData/Roaming",
+ ] {
+ try? fm.createDirectory(
+ at: profile.appending(path: folder), withIntermediateDirectories: true)
+ }
+
+ for (legacy, target) in [
+ ("Local Settings/Application Data", "../AppData/Local"),
+ ("Application Data", "./AppData/Roaming"),
+ ("My Documents", "./Documents"),
+ ] {
+ let link = profile.appending(path: legacy)
+ try? fm.createDirectory(
+ at: link.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try? fm.createSymbolicLink(
+ atPath: link.path(percentEncoded: false), withDestinationPath: target)
+ }
+ try? fm.createSymbolicLink(
+ atPath: users.appending(path: "crossover").path(percentEncoded: false),
+ withDestinationPath: "steamuser")
+ }
+}
+
+private final class Carry {
+ private let old: URL
+ private let fresh: URL
+ private let fm = FileManager.default
+
+ private(set) var lost: [String] = []
+
+ private var carried: Set<String> = []
+
+ private var pendingLinks: [(from: URL, to: URL)] = []
+
+ init(from old: URL, to fresh: URL) {
+ self.old = old
+ self.fresh = fresh
+ }
+
+ func userData() {
+ let source = old.appending(path: "drive_c/users")
+ let destination = fresh.appending(path: "drive_c/users")
+
+ let profiles = realEntries(in: source).filter(directoryExists)
+ for profile in profiles {
+ merge(profile, into: landing(forProfile: profile, under: destination))
+ }
+ for link in pendingLinks { carryLinks(from: link.from, to: link.to) }
+ carryLinks(from: source, to: destination)
+
+ let registry = old.appending(path: "user.reg")
+ guard fm.fileExists(atPath: registry.path(percentEncoded: false)) else { return }
+ let landing = fresh.appending(path: "user.reg")
+ try? fm.removeItem(at: landing)
+ attempt(registry) { try fm.copyItem(at: registry, to: landing) }
+ }
+
+ func strayFolders() {
+ let source = old.appending(path: "drive_c")
+ let destination = fresh.appending(path: "drive_c")
+ guard directoryExists(source) else { return }
+ let template = Set(
+ (try? fm.contentsOfDirectory(atPath: destination.path(percentEncoded: false))) ?? [])
+ var names: [String] = []
+ attempt(source) {
+ names = try fm.contentsOfDirectory(atPath: source.path(percentEncoded: false))
+ }
+ for name in names where !template.contains(name) {
+ let stray = source.appending(path: name)
+ attempt(stray) {
+ try fm.copyItem(at: stray, to: destination.appending(path: name))
+ }
+ }
+ }
+
+ private func attempt(_ source: URL, _ work: () throws -> Void) {
+ do { try work() } catch { lost.append(source.path(percentEncoded: false)) }
+ }
+
+ private func landing(forProfile profile: URL, under users: URL) -> URL {
+ let name = profile.lastPathComponent
+ let shared = name == "crossover" || name == "steamuser"
+ return users.appending(path: shared ? "steamuser" : name)
+ }
+
+ private func merge(_ source: URL, into landing: URL) {
+ if isBrokenLink(landing) { try? fm.removeItem(at: landing) }
+ guard !escapes(landing) else {
+ park(source, beside: landing)
+ return
+ }
+ var landingIsDirectory: ObjCBool = false
+ let occupied = fm.fileExists(
+ atPath: landing.path(percentEncoded: false), isDirectory: &landingIsDirectory)
+
+ guard directoryExists(source) else {
+ if occupied {
+ guard !landingIsDirectory.boolValue else {
+ park(source, beside: landing)
+ return
+ }
+ guard carried.insert(identity(of: landing)).inserted else {
+ park(source, beside: landing)
+ return
+ }
+ try? fm.removeItem(at: landing)
+ } else {
+ carried.insert(identity(of: landing))
+ }
+ attempt(source) { try fm.copyItem(at: source, to: landing) }
+ return
+ }
+ if !occupied {
+ attempt(source) {
+ try fm.createDirectory(at: landing, withIntermediateDirectories: true)
+ }
+ carried.insert(identity(of: landing))
+ } else if !landingIsDirectory.boolValue {
+ park(source, beside: landing)
+ return
+ } else if carried.contains(identity(of: landing)) {
+ park(source, beside: landing)
+ return
+ }
+ for entry in realEntries(in: source) {
+ merge(entry, into: landing.appending(path: entry.lastPathComponent))
+ }
+ pendingLinks.append((from: source, to: landing))
+ }
+
+ private func park(_ source: URL, beside landing: URL) {
+ let parent = landing.deletingLastPathComponent()
+ var name = landing.lastPathComponent + " BACKUP"
+ var next = 2
+ while fm.fileExists(atPath: parent.appending(path: name).path(percentEncoded: false)) {
+ name = landing.lastPathComponent + " BACKUP \(next)"
+ next += 1
+ }
+ attempt(source) { try fm.copyItem(at: source, to: parent.appending(path: name)) }
+ }
+
+ private func identity(of landing: URL) -> String {
+ landing.deletingLastPathComponent().resolvingSymlinksInPath()
+ .appending(path: landing.lastPathComponent).path(percentEncoded: false)
+ }
+
+ private func isBrokenLink(_ url: URL) -> Bool {
+ let values = try? url.resourceValues(forKeys: [.isSymbolicLinkKey])
+ guard values?.isSymbolicLink == true else { return false }
+ return !fm.fileExists(atPath: url.path(percentEncoded: false))
+ }
+
+ private func escapes(_ landing: URL) -> Bool {
+ let values = try? landing.resourceValues(forKeys: [.isSymbolicLinkKey])
+ guard values?.isSymbolicLink == true else { return false }
+ let inside = fresh.resolvingSymlinksInPath().path(percentEncoded: false)
+ return !landing.resolvingSymlinksInPath().path(percentEncoded: false).hasPrefix(inside)
+ }
+
+ private func directoryExists(_ url: URL) -> Bool {
+ var isDirectory: ObjCBool = false
+ let found = fm.fileExists(
+ atPath: url.path(percentEncoded: false), isDirectory: &isDirectory)
+ return found && isDirectory.boolValue
+ }
+
+ private func realEntries(in url: URL) -> [URL] {
+ guard directoryExists(url) else { return [] }
+ var found: [URL] = []
+ attempt(url) {
+ found = try fm.contentsOfDirectory(
+ at: url,
+ includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey],
+ options: []
+ )
+ }
+ return found
+ .filter { entry in
+ (try? entry.resourceValues(forKeys: [.isSymbolicLinkKey]))?.isSymbolicLink != true
+ }
+ .sorted { $0.lastPathComponent < $1.lastPathComponent }
+ }
+
+ private func carryLinks(from old: URL, to fresh: URL) {
+ guard directoryExists(old) else { return }
+ var entries: [URL] = []
+ attempt(old) {
+ entries = try fm.contentsOfDirectory(
+ at: old, includingPropertiesForKeys: [.isSymbolicLinkKey], options: [])
+ }
+ for entry in entries {
+ let values = try? entry.resourceValues(forKeys: [.isSymbolicLinkKey])
+ guard values?.isSymbolicLink == true else { continue }
+ let landing = fresh.appending(path: entry.lastPathComponent)
+ guard !fm.fileExists(atPath: landing.path(percentEncoded: false)) else { continue }
+ guard let points = try? fm.destinationOfSymbolicLink(
+ atPath: entry.path(percentEncoded: false)) else { continue }
+ attempt(entry) {
+ try fm.createSymbolicLink(atPath: landing.path(percentEncoded: false),
+ withDestinationPath: points)
+ }
+ }
+ }
+}
diff --git a/app/Sources/NotProtonApp/Model/PrefixStore.swift b/app/Sources/NotProtonApp/Model/PrefixStore.swift
new file mode 100644
index 0000000..06d9e52
--- /dev/null
+++ b/app/Sources/NotProtonApp/Model/PrefixStore.swift
@@ -0,0 +1,276 @@
+// Logic for Prefix menu, not great, could use some improvements
+
+import Foundation
+
+struct SteamLibrary: Sendable, Hashable {
+ let root: URL
+
+ var volume: String?
+
+ var steamapps: URL { root.appending(path: "steamapps") }
+ var compatdata: URL { steamapps.appending(path: "compatdata") }
+
+ var displayName: String {
+ guard let volume else { return root.lastPathComponent }
+ return volume
+ }
+}
+
+enum PrefixArch: Sendable, Equatable {
+ case arm64
+ case x86_64
+ case i386
+
+ init?(machine: UInt16) {
+ switch machine {
+ case 0xaa64: self = .arm64
+ case 0x8664: self = .x86_64
+ case 0x014c: self = .i386
+ default: return nil
+ }
+ }
+}
+
+struct WinePrefix: Sendable, Hashable, Identifiable {
+ let appID: String
+ let name: String?
+ let library: SteamLibrary
+ let lastUsed: Date?
+
+ var root: URL { library.compatdata.appending(path: appID) }
+ var pfx: URL { root.appending(path: "pfx") }
+
+ var id: String { "\(library.root.path(percentEncoded: false))#\(appID)" }
+
+ var title: String { name ?? "App \(appID)" }
+}
+
+struct PrefixUsage: Sendable {
+ let bytes: Int64
+ let profileFiles: Int
+}
+
+struct PrefixBackup: Sendable, Hashable, Identifiable {
+ let prefix: WinePrefix
+ let url: URL
+ let taken: Date?
+ let bytes: Int64
+
+ var id: String { url.path(percentEncoded: false) }
+ var title: String { prefix.title }
+}
+
+enum PrefixStore {
+
+ static func libraries(vdf: URL = SupportPaths.Steam.libraryFoldersVDF) -> [SteamLibrary] {
+ guard let text = try? String(contentsOf: vdf, encoding: .utf8) else {
+ return [library(at: SupportPaths.Steam.userData)]
+ }
+
+ var roots: [URL] = []
+ for line in text.split(separator: "\n") {
+ let fields = line.split(separator: "\"").map(String.init)
+ .filter { !$0.trimmingCharacters(in: .whitespaces).isEmpty }
+ guard fields.count >= 2, fields[0] == "path" else { continue }
+ roots.append(URL(filePath: fields[1]))
+ }
+
+ if roots.isEmpty { roots = [SupportPaths.Steam.userData] }
+
+ var seen: Set<String> = []
+ return roots.compactMap { root in
+ guard seen.insert(root.path(percentEncoded: false)).inserted else { return nil }
+ return library(at: root)
+ }
+ }
+
+ static func library(at root: URL) -> SteamLibrary {
+ SteamLibrary(root: root, volume: volumeName(of: root))
+ }
+
+ static func volumeName(of root: URL) -> String? {
+ guard
+ let values = try? root.resourceValues(forKeys: [.volumeNameKey, .volumeIsRootFileSystemKey]),
+ values.volumeIsRootFileSystem != true,
+ let name = values.volumeName
+ else { return nil }
+ return name
+ }
+
+ // Every appid under compatdata that actually has a prefix.
+ static func all(libraries: [SteamLibrary] = PrefixStore.libraries()) -> [WinePrefix] {
+ var found: [WinePrefix] = []
+ for library in libraries {
+ let entries = (try? FileManager.default.contentsOfDirectory(
+ at: library.compatdata,
+ includingPropertiesForKeys: [.contentModificationDateKey],
+ options: [.skipsHiddenFiles]
+ )) ?? []
+
+ for entry in entries {
+ let appID = entry.lastPathComponent
+ let pfx = entry.appending(path: "pfx")
+ var isDirectory: ObjCBool = false
+ guard FileManager.default.fileExists(atPath: pfx.path(percentEncoded: false), isDirectory: &isDirectory),
+ isDirectory.boolValue
+ else { continue }
+
+ found.append(
+ WinePrefix(
+ appID: appID,
+ name: appName(appID: appID, in: library),
+ library: library,
+ lastUsed: (try? pfx.resourceValues(forKeys: [.contentModificationDateKey]))?
+ .contentModificationDate
+ )
+ )
+ }
+ }
+
+ return found.sorted {
+ ($0.lastUsed ?? .distantPast, $0.appID) > ($1.lastUsed ?? .distantPast, $1.appID)
+ }
+ }
+
+ static func appName(appID: String, in library: SteamLibrary) -> String? {
+ manifestValue("name", appID: appID, in: library)
+ }
+
+ static func installDirectory(of prefix: WinePrefix) -> URL? {
+ guard let folder = manifestValue("installdir", appID: prefix.appID, in: prefix.library)
+ else { return nil }
+ let url = prefix.library.steamapps.appending(path: "common").appending(path: folder)
+ return FileManager.default.fileExists(atPath: url.path(percentEncoded: false)) ? url : nil
+ }
+
+ private static func manifestValue(_ key: String, appID: String, in library: SteamLibrary) -> String? {
+ let manifest = library.steamapps.appending(path: "appmanifest_\(appID).acf")
+ guard let text = try? String(contentsOf: manifest, encoding: .utf8) else { return nil }
+ for line in text.split(separator: "\n") {
+ let fields = line.split(separator: "\"").map(String.init)
+ .filter { !$0.trimmingCharacters(in: .whitespaces).isEmpty }
+ if fields.count >= 2, fields[0] == key { return fields[1] }
+ }
+ return nil
+ }
+
+ static let backupPrefix = "pfx.previous"
+
+ static func backupClock() -> DateFormatter {
+ let clock = DateFormatter()
+ clock.locale = Locale(identifier: "en_US_POSIX")
+ clock.dateFormat = "yyyyMMdd-HHmmss"
+ return clock
+ }
+
+ static func backupDate(of backup: URL) -> Date? {
+ let name = backup.lastPathComponent
+ guard name.hasPrefix("\(backupPrefix)-") else { return nil }
+ let stamp = name.dropFirst(backupPrefix.count + 1).prefix(15)
+ return backupClock().date(from: String(stamp))
+ }
+
+ static func backupDetails(of prefix: WinePrefix) -> [PrefixBackup] {
+ backups(of: prefix).map { url in
+ PrefixBackup(
+ prefix: prefix,
+ url: url,
+ taken: backupDate(of: url),
+ bytes: directoryBytes(url)
+ )
+ }
+ }
+
+ static func backups(of prefix: WinePrefix) -> [URL] {
+ let fm = FileManager.default
+ let entries = (try? fm.contentsOfDirectory(
+ at: prefix.root,
+ includingPropertiesForKeys: [.isDirectoryKey],
+ options: [.skipsHiddenFiles]
+ )) ?? []
+
+ return entries
+ .filter { $0.lastPathComponent.hasPrefix(backupPrefix) }
+ .filter { entry in
+ var isDirectory: ObjCBool = false
+ let found = fm.fileExists(
+ atPath: entry.path(percentEncoded: false), isDirectory: &isDirectory)
+ return found && isDirectory.boolValue
+ }
+ .sorted { $0.lastPathComponent < $1.lastPathComponent }
+ }
+
+ static func usage(of prefix: WinePrefix) -> PrefixUsage {
+ let bytes = directoryBytes(prefix.pfx)
+
+ var files = 0
+ let users = prefix.pfx.appending(path: "drive_c/users").path(percentEncoded: false)
+ if let out = try? Shell.check("/usr/bin/find", [users, "-type", "f"]) {
+ files = out.split(separator: "\n").filter { !$0.isEmpty }.count
+ }
+
+ return PrefixUsage(bytes: bytes, profileFiles: files)
+ }
+
+ static func directoryBytes(_ url: URL) -> Int64 {
+ guard let out = try? Shell.check("/usr/bin/du", ["-sk", url.path(percentEncoded: false)]),
+ let kb = Int64(out.split(separator: "\t").first?.trimmingCharacters(in: .whitespaces) ?? "")
+ else { return 0 }
+ return kb * 1024
+ }
+
+
+ static func arch(of prefix: WinePrefix) -> PrefixArch? {
+ let dll = prefix.pfx.appending(path: "drive_c/windows/system32/ntdll.dll")
+ guard let handle = try? FileHandle(forReadingFrom: dll) else { return nil }
+ defer { try? handle.close() }
+
+ guard let dos = try? handle.read(upToCount: 0x40), dos.count == 0x40 else { return nil }
+ let lfanew = dos.withUnsafeBytes {
+ UInt32(littleEndian: $0.loadUnaligned(fromByteOffset: 0x3c, as: UInt32.self))
+ }
+ do { try handle.seek(toOffset: UInt64(lfanew)) } catch { return nil }
+
+ guard let head = try? handle.read(upToCount: 6), head.count == 6,
+ Array(head.prefix(4)) == [0x50, 0x45, 0x00, 0x00]
+ else { return nil }
+
+ return PrefixArch(
+ machine: head.withUnsafeBytes {
+ UInt16(littleEndian: $0.loadUnaligned(fromByteOffset: 4, as: UInt16.self))
+ }
+ )
+ }
+
+ static var serverRoot: URL { URL(filePath: "/tmp/.wine-\(getuid())") }
+
+ static func serverDirectory(of prefix: WinePrefix, root: URL = serverRoot) -> URL? {
+ guard
+ let attributes = try? FileManager.default.attributesOfItem(
+ atPath: prefix.pfx.path(percentEncoded: false)
+ ),
+ let device = attributes[.systemNumber] as? Int,
+ let inode = attributes[.systemFileNumber] as? Int
+ else { return nil }
+
+ return root.appending(
+ path: "server-\(String(device, radix: 16))-\(String(inode, radix: 16))")
+ }
+
+ static func isInUse(
+ _ prefix: WinePrefix, root: URL = serverRoot, lsof: String = "/usr/sbin/lsof",
+ drainTimeout: DispatchTimeInterval = .seconds(2)
+ ) -> Bool {
+ guard let dir = serverDirectory(of: prefix, root: root),
+ FileManager.default.fileExists(atPath: dir.path(percentEncoded: false))
+ else { return false }
+
+ guard let result = try? Shell.run(
+ lsof, ["-t", "+D", dir.path(percentEncoded: false)], drainTimeout: drainTimeout)
+ else { return true }
+
+ if !result.stdout.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { return true }
+
+ return result.outputLost || !result.stderr.isEmpty
+ }
+}
diff --git a/app/Sources/NotProtonApp/Model/PrefixTools.swift b/app/Sources/NotProtonApp/Model/PrefixTools.swift
new file mode 100644
index 0000000..13d4a2f
--- /dev/null
+++ b/app/Sources/NotProtonApp/Model/PrefixTools.swift
@@ -0,0 +1,181 @@
+// Shortcuts to launch the Wine tools (winecfg/regedit/task manager) against
+// a selected prefix, opens prefix directory in finder, etc.
+
+import AppKit
+import Foundation
+import UniformTypeIdentifiers
+
+enum WineTool: String, CaseIterable, Sendable {
+ case winecfg
+ case regedit
+ case taskmgr
+
+ var label: String {
+ switch self {
+ case .winecfg: "Wine Configuration"
+ case .regedit: "Registry Editor"
+ case .taskmgr: "Task Manager"
+ }
+ }
+}
+
+enum PrefixTools {
+
+ static func syncBackend(prefix: WinePrefix) -> String {
+ let marker = prefix.root.appending(path: "notproton-msync")
+ let recorded = try? String(contentsOf: marker, encoding: .utf8)
+ return recorded?.trimmingCharacters(in: .whitespacesAndNewlines) == "1" ? "1" : "0"
+ }
+
+ static func environment(prefix: WinePrefix, runner: URL = SupportPaths.currentRunner) -> [String: String] {
+ let root = runner.path(percentEncoded: false)
+ var environment = ProcessInfo.processInfo.environment
+ environment["CX_ROOT"] = root
+ environment["CX_HOME"] = SupportPaths.applicationSupport
+ .appending(path: "CrossOver").path(percentEncoded: false)
+ let wine = layout(runner: runner)
+ environment["WINELOADER"] = wine.loader.path(percentEncoded: false)
+ environment["WINESERVER"] = wine.server.path(percentEncoded: false)
+ environment["WINEDLLPATH"] = "\(root)/lib/wine/x86_64-windows:"
+ + wine.unixDir.path(percentEncoded: false)
+ environment["WINEPREFIX"] = prefix.pfx.path(percentEncoded: false)
+ environment["WINEMSYNC"] = syncBackend(prefix: prefix)
+ environment["PATH"] = "\(root)/bin:" + (environment["PATH"] ?? "/usr/bin:/bin")
+ return environment
+ }
+
+ static func loader(runner: URL = SupportPaths.currentRunner) -> URL {
+ layout(runner: runner).loader
+ }
+
+ struct WineLayout {
+ let loader: URL
+ let server: URL
+ let unixDir: URL
+ }
+
+ static func layout(runner: URL = SupportPaths.currentRunner) -> WineLayout {
+ let fm = FileManager.default
+ let hosted = runner.appending(path: "CrossOver-Hosted Application")
+ func executable(_ url: URL) -> Bool {
+ fm.isExecutableFile(atPath: url.path(percentEncoded: false))
+ }
+
+ let arm = runner.appending(path: "lib/wine/aarch64-unix")
+ let armLoader = arm.appending(path: "wine.app/Contents/MacOS/wine")
+ let armServer = hosted.appending(path: "wineserver-arm64")
+ if executable(armLoader), executable(armServer) {
+ return WineLayout(loader: armLoader, server: armServer, unixDir: arm)
+ }
+
+ let unix = runner.appending(path: "lib/wine/x86_64-unix")
+ let server = hosted.appending(path: "wineserver")
+ return WineLayout(
+ loader: unix.appending(path: "wine"),
+ server: executable(server) ? server : hosted.appending(path: "wineserver-x86"),
+ unixDir: unix
+ )
+ }
+
+ private static func readyLoader(step: String, prefix: WinePrefix, runner: URL) throws -> URL {
+ let loader = loader(runner: runner)
+ guard FileManager.default.isExecutableFile(atPath: loader.path(percentEncoded: false)) else {
+ throw StepFailure(
+ step: step,
+ detail: "No compatibility tool at \(loader.path(percentEncoded: false)). "
+ + "Use Set Up Compatibility Tool first."
+ )
+ }
+ guard FileManager.default.fileExists(atPath: prefix.pfx.path(percentEncoded: false)) else {
+ throw StepFailure(
+ step: step,
+ detail: "\(prefix.title) has no prefix at \(prefix.pfx.path(percentEncoded: false))."
+ )
+ }
+ return loader
+ }
+
+ static func launch(_ tool: WineTool, in prefix: WinePrefix, runner: URL = SupportPaths.currentRunner) throws {
+ let loader = try readyLoader(step: "Open \(tool.label)", prefix: prefix, runner: runner)
+ try Shell.detach(
+ loader.path(percentEncoded: false),
+ [tool.rawValue],
+ environment: environment(prefix: prefix, runner: runner)
+ )
+ }
+
+ static func run(
+ _ executable: URL,
+ in prefix: WinePrefix,
+ runner: URL = SupportPaths.currentRunner
+ ) throws {
+ let step = "Run \(executable.lastPathComponent)"
+ let loader = try readyLoader(step: step, prefix: prefix, runner: runner)
+ guard FileManager.default.fileExists(atPath: executable.path(percentEncoded: false)) else {
+ throw StepFailure(step: step, detail: "No file at \(executable.path(percentEncoded: false)).")
+ }
+ guard let arguments = arguments(for: executable) else {
+ throw StepFailure(
+ step: step,
+ detail: "\(executable.lastPathComponent) is not a Windows program. "
+ + "Pick an exe, msi, bat or cmd file."
+ )
+ }
+
+ try Shell.detach(
+ loader.path(percentEncoded: false),
+ arguments,
+ environment: environment(prefix: prefix, runner: runner),
+ currentDirectory: executable.deletingLastPathComponent()
+ )
+ }
+
+ static func arguments(for executable: URL) -> [String]? {
+ let path = executable.path(percentEncoded: false)
+ switch executable.pathExtension.lowercased() {
+ case "exe", "bat", "cmd": return [path]
+ case "msi": return ["msiexec", "/i", path]
+ default: return nil
+ }
+ }
+
+ static var runnableTypes: [UTType] {
+ ["exe", "msi", "bat", "cmd"].compactMap { UTType(filenameExtension: $0) }
+ }
+
+ static func reveal(_ prefix: WinePrefix) {
+ NSWorkspace.shared.selectFile(
+ prefix.pfx.path(percentEncoded: false),
+ inFileViewerRootedAtPath: prefix.root.path(percentEncoded: false)
+ )
+ }
+
+ static func reveal(at url: URL) {
+ NSWorkspace.shared.selectFile(
+ url.path(percentEncoded: false),
+ inFileViewerRootedAtPath: url.deletingLastPathComponent().path(percentEncoded: false)
+ )
+ }
+
+ static func deleteBackup(_ backup: URL) throws {
+ try WriteRefused.catching(backup.path(percentEncoded: false)) {
+ try FileManager.default.removeItem(at: backup)
+ }
+ }
+
+ static func delete(_ prefix: WinePrefix) throws {
+ guard !PrefixStore.isInUse(prefix) else {
+ throw StepFailure(
+ step: "Delete prefix",
+ detail: "\(prefix.title) is running. Quit the game first."
+ )
+ }
+ try WriteRefused.catching(prefix.root) {
+ try FileManager.default.removeItem(at: prefix.root)
+ }
+ }
+
+ static func prefixArch(runner: URL = SupportPaths.currentRunner) -> PrefixArch {
+ layout(runner: runner).unixDir.lastPathComponent == "aarch64-unix" ? .arm64 : .x86_64
+ }
+}
diff --git a/app/Sources/NotProtonApp/Model/RunnerInstaller.swift b/app/Sources/NotProtonApp/Model/RunnerInstaller.swift
new file mode 100644
index 0000000..d39b2df
--- /dev/null
+++ b/app/Sources/NotProtonApp/Model/RunnerInstaller.swift
@@ -0,0 +1,116 @@
+// Clones CrossOver's Wine runtime into ~/Library/Application Support/notproton/runners
+
+import Foundation
+
+enum RunnerInstaller {
+
+ static let step = "Clone CrossOver"
+
+ static func clone(
+ from install: CrossOverInstall,
+ replacingExisting: Bool = false,
+ runners: URL = SupportPaths.runners
+ ) throws -> RunnerBuild {
+ guard case .supported(let build) = install.support else {
+ throw StepFailure(
+ step: step,
+ detail: "\(install.name) is not a supported build. Supported: \(SupportedRunners.versionList)."
+ )
+ }
+
+ let fm = FileManager.default
+ let target = SupportPaths.runnerRoot(forBuild: build.id, runners: runners)
+
+ let existing = hasClone(forBuild: build.id, runners: runners)
+ let occupied = fm.fileExists(atPath: target.path(percentEncoded: false))
+
+ if !existing || replacingExisting {
+ let staging = target.deletingLastPathComponent()
+ .appending(path: ".\(target.lastPathComponent).new")
+ try? fm.removeItem(at: staging)
+ try copyPayload(from: install.crossOverRoot, to: staging)
+ if occupied {
+ try fm.removeItem(at: target)
+ }
+ try fm.moveItem(at: staging, to: target)
+ }
+
+ let cloned = SupportPaths.clonedRoot(forBuild: build.id, runners: runners)
+ try verifyClone(build: build, root: cloned)
+ try pointCurrent(atBuild: build.id, runners: runners)
+
+ return build
+ }
+
+ static func hasClone(forBuild build: String, runners: URL = SupportPaths.runners) -> Bool {
+ let root = SupportPaths.clonedRoot(forBuild: build, runners: runners)
+ return FileManager.default.fileExists(
+ atPath: root.appending(path: "lib/wine").path(percentEncoded: false)
+ )
+ }
+
+ static func copyPayload(from payload: URL, to target: URL) throws {
+ let fm = FileManager.default
+ try fm.createDirectory(at: target, withIntermediateDirectories: true)
+
+ let source = payload.path(percentEncoded: false)
+ let landing = target.appending(path: "CrossOver")
+ let destination = landing.path(percentEncoded: false)
+
+ let cloned = try Shell.run("/bin/cp", ["-c", "-R", source, destination])
+ if cloned.status == 0 {
+ scrubDownloadMarkers(at: landing)
+ return
+ }
+
+ try? fm.removeItem(at: landing)
+ let copied = try Shell.run("/bin/cp", ["-R", source, destination])
+ guard copied.status == 0 else {
+ throw StepFailure(
+ step: step,
+ detail: "Copying \(source) failed. \(copied.stderr.trimmingCharacters(in: .whitespacesAndNewlines))"
+ )
+ }
+ scrubDownloadMarkers(at: landing)
+ }
+
+ static func scrubDownloadMarkers(at payload: URL) {
+ for marker in ["com.apple.quarantine", "com.apple.provenance"] {
+ _ = try? Shell.run("/usr/bin/xattr", ["-r", "-d", marker, payload.path(percentEncoded: false)])
+ }
+ }
+
+ private static func verifyClone(build: RunnerBuild, root: URL) throws {
+ let loader = Clean.copy(of: CrossOverSource.unixLoader(inRoot: root))
+ guard let hash = Digest.sha256IfPresent(loader) else {
+ throw StepFailure(step: step, detail: "The clone has no Wine loader at \(loader.lastPathComponent).")
+ }
+ guard hash == build.loaderSHA256 else {
+ throw StepFailure(
+ step: step,
+ detail: "The cloned Wine loader at \(loader.lastPathComponent) does not match build "
+ + "\(build.id). Expected \(build.loaderSHA256.prefix(16)), found \(hash.prefix(16))."
+ )
+ }
+
+ try CrossOverSource.verifyPatchInputs(root: root, build: build)
+ }
+
+ static func pointCurrent(atBuild build: String, runners: URL = SupportPaths.runners) throws {
+ let fm = FileManager.default
+ let relative = "crossover-\(build)/CrossOver"
+ let staging = runners.appending(path: ".current.new")
+
+ try? fm.removeItem(at: staging)
+ try fm.createSymbolicLink(
+ atPath: staging.path(percentEncoded: false), withDestinationPath: relative
+ )
+
+ let current = runners.appending(path: "current").path(percentEncoded: false)
+ if rename(staging.path(percentEncoded: false), current) != 0 {
+ let reason = String(cString: strerror(errno))
+ try? fm.removeItem(at: staging)
+ throw StepFailure(step: step, detail: "Could not point the compatibility tool at \(relative). \(reason)")
+ }
+ }
+}
diff --git a/app/Sources/NotProtonApp/Model/RunnerPatcher.swift b/app/Sources/NotProtonApp/Model/RunnerPatcher.swift
new file mode 100644
index 0000000..988c526
--- /dev/null
+++ b/app/Sources/NotProtonApp/Model/RunnerPatcher.swift
@@ -0,0 +1,274 @@
+// Patcher logic
+
+import Foundation
+
+enum RunnerPatcher {
+
+ static let step = "Patch the compatibility tool"
+
+ private static let dyldEntitlement = "com.apple.security.cs.allow-dyld-environment-variables"
+
+ static let windowsBuiltins = [
+ (arch: "i386-windows", name: "lsteamclient.dll"),
+ (arch: "x86_64-windows", name: "lsteamclient.dll"),
+ ]
+
+ static func builtins(in root: URL) -> [(arch: String, name: String)] {
+ windowsBuiltins + [(arch: unixArch(in: root), name: "lsteamclient.so")]
+ }
+
+ static func unixArch(in root: URL) -> String {
+ let arches = unixLoaders(in: root).compactMap { loader in
+ loader.pathComponents.last { $0.hasSuffix("-unix") }
+ }
+ return arches.contains("aarch64-unix") ? "aarch64-unix" : "x86_64-unix"
+ }
+
+ struct Outcome: Sendable {
+ var ntdll: [WineArch] = []
+ var builtins: [String] = []
+ var loaders: [String] = []
+
+ var wroteNothing: Bool { ntdll.isEmpty && builtins.isEmpty && loaders.isEmpty }
+ }
+
+ static func install(
+ build: RunnerBuild, root: URL, bridge: URL = SupportPaths.bridge
+ ) throws -> Outcome {
+ var outcome = Outcome()
+ outcome.ntdll = try installNtdll(build: build, root: root, bridge: bridge)
+ outcome.builtins = try installBuiltins(root: root, bridge: bridge)
+ outcome.loaders = try grantLoaderEntitlement(root: root)
+ return outcome
+ }
+
+ static func verify(
+ build: RunnerBuild, root: URL, bridge: URL = SupportPaths.bridge
+ ) -> [String] {
+ var wrong: [String] = []
+ for arch in WineArch.allCases {
+ guard let expected = build.patchedNtdll[arch] else { continue }
+ let live = root.appending(path: "lib/wine/\(arch.rawValue)/ntdll.dll")
+ guard let actual = Digest.sha256IfPresent(live) else {
+ wrong.append("\(arch.rawValue)/ntdll.dll is missing")
+ continue
+ }
+ if actual != expected {
+ wrong.append("\(arch.rawValue)/ntdll.dll is not the patched copy")
+ }
+ }
+ for builtin in builtins(in: root) {
+ let installed = Digest.sha256IfPresent(
+ root.appending(path: "lib/wine/\(builtin.arch)/\(builtin.name)"))
+ guard let installed else {
+ wrong.append("\(builtin.arch)/\(builtin.name) is missing")
+ continue
+ }
+
+ let staged = Digest.sha256IfPresent(
+ bridge.appending(path: "\(builtin.arch)/\(builtin.name)"))
+ if let staged, staged != installed {
+ wrong.append("\(builtin.arch)/\(builtin.name) is out of date")
+ }
+ }
+
+ for loader in unixLoaders(in: root) {
+ let granted = entitlements(of: loader)
+ if granted?.contains(restrictedEntitlement) == true {
+ if !signatureIsValid(signingTarget(for: loader)) {
+ wrong.append("\(name(of: loader)) has a broken signature")
+ }
+ } else if granted?.contains(dyldEntitlement) != true {
+ wrong.append("\(name(of: loader)) is missing the dyld entitlement")
+ }
+ }
+
+ return wrong
+ }
+
+ private static func installNtdll(
+ build: RunnerBuild, root: URL, bridge: URL
+ ) throws -> [WineArch] {
+ var installed: [WineArch] = []
+
+ for arch in WineArch.allCases {
+ guard let expected = build.patchedNtdll[arch] else { continue }
+ let staged = bridge.appending(path: "wine/\(arch.rawValue)/ntdll.dll")
+
+ guard Digest.sha256IfPresent(staged) == expected else {
+ throw StepFailure(
+ step: step,
+ detail: "The patched \(arch.rawValue) ntdll has not been copied into place."
+ )
+ }
+
+ let live = root.appending(path: "lib/wine/\(arch.rawValue)/ntdll.dll")
+ if Digest.sha256IfPresent(live) == expected { continue }
+
+ try keepClean(live)
+ try atomicReplace(live, with: Data(contentsOf: staged), step: step)
+ installed.append(arch)
+ }
+
+ return installed
+ }
+
+ private static func installBuiltins(root: URL, bridge: URL) throws -> [String] {
+ var installed: [String] = []
+
+ for builtin in builtins(in: root) {
+ let source = bridge.appending(path: "\(builtin.arch)/\(builtin.name)")
+ guard FileManager.default.fileExists(atPath: source.path(percentEncoded: false)) else {
+ throw StepFailure(
+ step: step,
+ detail: "\(builtin.arch)/\(builtin.name) is not in the bridge. "
+ + "Install NotProton first."
+ )
+ }
+
+ let destination = root.appending(path: "lib/wine/\(builtin.arch)/\(builtin.name)")
+ if Digest.sha256IfPresent(source) == Digest.sha256IfPresent(destination) { continue }
+
+ try atomicReplace(destination, with: Data(contentsOf: source), step: step)
+ installed.append("\(builtin.arch)/\(builtin.name)")
+ }
+
+ return installed
+ }
+
+ private static func grantLoaderEntitlement(root: URL) throws -> [String] {
+ var signed: [String] = []
+
+ for loader in unixLoaders(in: root) {
+ let existing = entitlements(of: loader)
+ if existing?.contains(restrictedEntitlement) == true { continue }
+ if existing?.contains(dyldEntitlement) == true,
+ signatureIsValid(signingTarget(for: loader)) { continue }
+
+ guard let existing, !existing.isEmpty else {
+ throw StepFailure(
+ step: step,
+ detail: "\(name(of: loader)) carries no entitlements to extend."
+ )
+ }
+
+ do {
+ try sign(loader, addingTo: existing)
+ } catch {
+ restoreClean(loader)
+ throw error
+ }
+ signed.append(name(of: loader))
+ }
+
+ return signed
+ }
+
+ static func unixLoaders(in root: URL) -> [URL] {
+ let fm = FileManager.default
+ let wine = root.appending(path: "lib/wine")
+ let entries = (try? fm.contentsOfDirectory(at: wine, includingPropertiesForKeys: nil)) ?? []
+
+ return entries
+ .filter { $0.lastPathComponent.hasSuffix("-unix") }
+ .flatMap { [$0.appending(path: "wine"), $0.appending(path: "wine.app/Contents/MacOS/wine")] }
+ .filter { fm.fileExists(atPath: $0.path(percentEncoded: false)) }
+ .sorted { $0.path < $1.path }
+ }
+
+ static func name(of loader: URL) -> String {
+ let parts = loader.pathComponents
+ guard let arch = parts.lastIndex(where: { $0.hasSuffix("-unix") }) else {
+ return loader.lastPathComponent
+ }
+ return parts[arch...].joined(separator: "/")
+ }
+
+ private static func entitlements(of loader: URL) -> String? {
+ guard let result = try? Shell.run(
+ "/usr/bin/codesign", ["-d", "--entitlements", ":-", loader.path(percentEncoded: false)]
+ ), result.status == 0 else { return nil }
+ return result.stdout
+ }
+
+ private static func sign(_ loader: URL, addingTo existing: String) throws {
+ let plist = FileManager.default.temporaryDirectory
+ .appending(path: "np-entitlements-\(UUID().uuidString).plist")
+ defer { try? FileManager.default.removeItem(at: plist) }
+
+ try Data(existing.utf8).write(to: plist)
+ _ = try Shell.run("/usr/libexec/PlistBuddy", [
+ "-c", "Add :\(dyldEntitlement) bool true", plist.path(percentEncoded: false),
+ ])
+
+ try keepClean(loader)
+ let target = signingTarget(for: loader)
+ let result = try Shell.run("/usr/bin/codesign", [
+ "-f", "-s", "-", "--options", "runtime",
+ "--entitlements", plist.path(percentEncoded: false),
+ target.path(percentEncoded: false),
+ ])
+ guard result.status == 0 else {
+ throw StepFailure(
+ step: step,
+ detail: result.stderr.trimmingCharacters(in: .whitespacesAndNewlines)
+ )
+ }
+
+
+ guard entitlements(of: loader)?.contains(dyldEntitlement) == true else {
+ throw StepFailure(
+ step: step,
+ detail: "\(name(of: loader)) was re-signed without the dyld entitlement."
+ )
+ }
+ }
+
+ private static func signingTarget(for loader: URL) -> URL {
+ enclosingBundle(of: loader) ?? loader
+ }
+
+ private static func enclosingBundle(of loader: URL) -> URL? {
+ var candidate = loader.deletingLastPathComponent()
+ while candidate.pathComponents.count > 1 {
+ if candidate.pathExtension == "app" { return candidate }
+ candidate = candidate.deletingLastPathComponent()
+ }
+ return nil
+ }
+
+ static let restrictedEntitlement = "com.apple.developer.cross-architecture-support"
+
+ private static func signatureIsValid(_ target: URL) -> Bool {
+ guard let result = try? Shell.run(
+ "/usr/bin/codesign", ["--verify", "--strict", target.path(percentEncoded: false)]
+ ) else { return false }
+ return result.status == 0
+ }
+
+ private static func keepClean(_ file: URL) throws {
+ let backup = Clean.copy(of: file)
+ guard backup == file else { return }
+
+ let destination = file.appendingPathExtension(Clean.backupSuffix)
+ let result = try Shell.run("/bin/cp", [
+ "-p", file.path(percentEncoded: false), destination.path(percentEncoded: false),
+ ])
+ guard result.status == 0 else {
+ throw StepFailure(
+ step: step,
+ detail: "Keeping the shipped \(file.lastPathComponent) failed. "
+ + result.stderr.trimmingCharacters(in: .whitespacesAndNewlines)
+ )
+ }
+ }
+
+ private static func restoreClean(_ file: URL) {
+ let backup = file.appendingPathExtension(Clean.backupSuffix)
+ guard FileManager.default.fileExists(atPath: backup.path(percentEncoded: false)) else { return }
+ _ = try? Shell.run("/bin/cp", [
+ "-p", backup.path(percentEncoded: false), file.path(percentEncoded: false),
+ ])
+ }
+
+}
diff --git a/app/Sources/NotProtonApp/Model/RunnerSetup.swift b/app/Sources/NotProtonApp/Model/RunnerSetup.swift
new file mode 100644
index 0000000..8a5ae9b
--- /dev/null
+++ b/app/Sources/NotProtonApp/Model/RunnerSetup.swift
@@ -0,0 +1,51 @@
+// Clones CrossOver, throws it in bridge, invokes ntdll patch,
+
+import Foundation
+
+enum RunnerSetup {
+
+ enum Phase: Sendable {
+ case cloning
+ case staging
+ case patching
+ case finished
+
+ var label: String {
+ switch self {
+ case .cloning: "Copying CrossOver"
+ case .staging: "Patching"
+ case .patching: "Installing compatibility tool"
+ case .finished: "Done"
+ }
+ }
+ }
+
+ struct Outcome: Sendable {
+ let build: RunnerBuild
+ let staged: [WineArch]
+ let installed: RunnerPatcher.Outcome
+
+ var stagedNothing: Bool { staged.isEmpty && installed.wroteNothing }
+ }
+
+ static func run(
+ from install: CrossOverInstall,
+ replacingExisting: Bool = false,
+ report: @Sendable (Phase) -> Void = { _ in }
+ ) throws -> Outcome {
+ try CrossOverLicense.requireValid(for: install)
+
+ report(.cloning)
+ let build = try RunnerInstaller.clone(from: install, replacingExisting: replacingExisting)
+
+ report(.staging)
+ let root = SupportPaths.clonedRoot(forBuild: build.id)
+ let staged = try NtdllPatcher.stage(build: build, runnerRoot: root)
+
+ report(.patching)
+ let installed = try RunnerPatcher.install(build: build, root: root)
+
+ report(.finished)
+ return Outcome(build: build, staged: staged, installed: installed)
+ }
+}
diff --git a/app/Sources/NotProtonApp/Model/RunnerStore.swift b/app/Sources/NotProtonApp/Model/RunnerStore.swift
new file mode 100644
index 0000000..e7b0649
--- /dev/null
+++ b/app/Sources/NotProtonApp/Model/RunnerStore.swift
@@ -0,0 +1,84 @@
+// Checks CrossOver state for status display
+
+import Foundation
+
+enum RunnerState: Sendable, Equatable {
+ case none
+ case cloned(build: String, supported: Bool)
+ case bundleShaped(build: String)
+ case unpatched(build: String, problems: [String])
+ case broken(detail: String)
+
+ var buildIdentifier: String? {
+ switch self {
+ case .cloned(let build, _), .bundleShaped(let build), .unpatched(let build, _): build
+ case .none, .broken: nil
+ }
+ }
+}
+
+enum RunnerStore {
+
+ static func state(
+ runners: URL = SupportPaths.runners,
+ verify: @Sendable (RunnerBuild, URL) -> [String] = {
+ RunnerPatcher.verify(build: $0, root: $1)
+ }
+ ) -> RunnerState {
+ let fm = FileManager.default
+ let current = runners.appending(path: "current")
+ let currentPath = current.path(percentEncoded: false)
+
+ guard let attributes = try? fm.attributesOfItem(atPath: currentPath),
+ attributes[.type] as? FileAttributeType == .typeSymbolicLink
+ else {
+ if fm.fileExists(atPath: currentPath) {
+ return .broken(detail: "runners/current is not a symlink.")
+ }
+ return .none
+ }
+
+ guard let target = try? fm.destinationOfSymbolicLink(atPath: currentPath) else {
+ return .broken(detail: "runners/current cannot be read.")
+ }
+
+ let resolved = current.deletingLastPathComponent().appending(path: target).standardizedFileURL
+ guard fm.fileExists(atPath: resolved.appending(path: "lib/wine").path(percentEncoded: false)) else {
+ return .broken(detail: "runners/current points at \(target), which has no lib/wine.")
+ }
+
+ guard let build = buildIdentifier(inPath: target) else {
+ return .broken(detail: "runners/current points at \(target), which has no recognisable build.")
+ }
+
+ if target.split(separator: "/").contains(where: { $0.hasSuffix(".app") }) {
+ return .bundleShaped(build: build)
+ }
+
+ guard let supported = SupportedRunners.build(id: build) else {
+ return .cloned(build: build, supported: false)
+ }
+
+ let problems = verify(supported, resolved)
+ guard problems.isEmpty else { return .unpatched(build: build, problems: problems) }
+
+ return .cloned(build: build, supported: true)
+ }
+
+ static func buildIdentifier(inPath path: String) -> String? {
+ for component in path.split(separator: "/") where component.hasPrefix("crossover-") {
+ return String(component.dropFirst("crossover-".count))
+ }
+ return nil
+ }
+
+ static func clonedBuilds(in runners: URL = SupportPaths.runners) -> [String] {
+ let fm = FileManager.default
+ let entries = (try? fm.contentsOfDirectory(at: runners, includingPropertiesForKeys: nil)) ?? []
+ return entries
+ .map(\.lastPathComponent)
+ .filter { $0.hasPrefix("crossover-") }
+ .map { String($0.dropFirst("crossover-".count)) }
+ .sorted()
+ }
+}
diff --git a/app/Sources/NotProtonApp/Model/SteamBundle.swift b/app/Sources/NotProtonApp/Model/SteamBundle.swift
new file mode 100644
index 0000000..320cb6f
--- /dev/null
+++ b/app/Sources/NotProtonApp/Model/SteamBundle.swift
@@ -0,0 +1,125 @@
+// Steam app bundle patching component
+
+import Foundation
+
+enum SteamDeployment: Sendable, Equatable {
+ case steamMissing
+ case notInstalled
+ case installed(version: String?)
+ case outdated(deployed: String, bundled: String)
+ // If the user has something else installed, maybe let's not deploy?
+ case foreign(insert: String)
+}
+
+// Reading and writing the injection
+enum SteamBundle {
+
+ static let insertKey = "DYLD_INSERT_LIBRARIES"
+
+ static let plistBackupName = "Info.plist.before-notproton"
+ static let environmentKey = "LSEnvironment"
+
+ static var isPresent: Bool {
+ FileManager.default.fileExists(atPath: SupportPaths.Steam.app.path(percentEncoded: false))
+ }
+
+ static var isRunning: Bool {
+
+ Shell.processIsRunning(named: "steam_osx")
+ }
+
+ static func deployment(
+ bundledVersion: String,
+ app: URL = SupportPaths.Steam.app,
+ versionFile: URL = SupportPaths.deployedVersion
+ ) -> SteamDeployment {
+ let files = FileManager.default
+ guard files.fileExists(atPath: app.path(percentEncoded: false)) else { return .steamMissing }
+
+ let plist = SupportPaths.Steam.infoPlist(inBundle: app)
+ guard let insert = currentInsert(at: plist), !insert.isEmpty else { return .notInstalled }
+
+ let deployedDylib = SupportPaths.Steam.deployedDylib(inBundle: app)
+ .path(percentEncoded: false)
+ let components = insert.split(separator: ":").map(String.init)
+ guard components.contains(deployedDylib) else { return .foreign(insert: insert) }
+
+ guard files.fileExists(atPath: deployedDylib) else { return .notInstalled }
+
+ guard let deployed = deployedVersion(at: versionFile) else { return .installed(version: nil) }
+ if deployed == bundledVersion { return .installed(version: deployed) }
+ return .outdated(deployed: deployed, bundled: bundledVersion)
+ }
+
+ static func currentInsert(at url: URL = SupportPaths.Steam.infoPlist) -> String? {
+ guard let dict = readInfoPlist(at: url),
+ let environment = dict[environmentKey] as? [String: Any]
+ else { return nil }
+ return environment[insertKey] as? String
+ }
+
+ static func deployedVersion(at url: URL = SupportPaths.deployedVersion) -> String? {
+ guard let data = try? Data(contentsOf: url) else { return nil }
+ let text = String(decoding: data, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)
+ return text.isEmpty ? nil : text
+ }
+
+ static func stopClient(
+ app: URL = SupportPaths.Steam.app,
+ helpers: [URL] = [SupportPaths.Steam.innerApp],
+ step: String,
+ onStopping: () -> Void = {}
+ ) throws -> Bool {
+ guard isRunning else { return false }
+ onStopping()
+
+ _ = try? Shell.run("/usr/bin/pkill", ["-x", "steam_osx"])
+ for _ in 0..<60 where isRunning {
+ Thread.sleep(forTimeInterval: 0.5)
+ }
+
+ if isRunning {
+ _ = try? Shell.run("/usr/bin/pkill", ["-9", "-x", "steam_osx"])
+ Thread.sleep(forTimeInterval: 1)
+ }
+
+ guard !isRunning else {
+ throw StepFailure(
+ step: step,
+ detail: "Steam is running, please close Steam."
+ )
+ }
+
+ for pattern in sweepPatterns(app: app, helpers: helpers) {
+ _ = try? Shell.run("/usr/bin/pkill", ["-f", pattern])
+ }
+ return true
+ }
+
+ static func sweepPatterns(app: URL, helpers: [URL]) -> [String] {
+ ([app] + helpers).map { $0.path(percentEncoded: false) + "/" }
+ }
+
+ static func register(_ app: URL = SupportPaths.Steam.app) {
+ let lsregister = "/System/Library/Frameworks/CoreServices.framework/Frameworks"
+ + "/LaunchServices.framework/Support/lsregister"
+ _ = try? Shell.run(lsregister, ["-f", app.path(percentEncoded: false)])
+ }
+
+ static func readInfoPlist(at url: URL = SupportPaths.Steam.infoPlist) -> [String: Any]? {
+ guard let data = try? Data(contentsOf: url),
+ let object = try? PropertyListSerialization.propertyList(from: data, format: nil)
+ else { return nil }
+ return object as? [String: Any]
+ }
+
+ static func writeInfoPlist(_ dict: [String: Any], at url: URL = SupportPaths.Steam.infoPlist) throws {
+ var format = PropertyListSerialization.PropertyListFormat.xml
+ if let data = try? Data(contentsOf: url) {
+ _ = try? PropertyListSerialization.propertyList(from: data, format: &format)
+ }
+
+ let data = try PropertyListSerialization.data(fromPropertyList: dict, format: format, options: 0)
+ try WriteRefused.catching(url) { try data.write(to: url, options: .atomic) }
+ }
+}
diff --git a/app/Sources/NotProtonApp/Model/SteamInstaller.swift b/app/Sources/NotProtonApp/Model/SteamInstaller.swift
new file mode 100644
index 0000000..0c40b56
--- /dev/null
+++ b/app/Sources/NotProtonApp/Model/SteamInstaller.swift
@@ -0,0 +1,275 @@
+// 'Install' logic for the Steam patch componen
+
+import Foundation
+
+enum InstallPhase: Sendable {
+ case checkingPayload
+ case stagingBridge
+ case preflight
+ case stoppingClient
+ case copyingDylib
+ case installingSignatures
+ case installingOverlayShim
+ case settingInsert
+ case signing
+ case registering
+ case finished
+
+ var label: String {
+ switch self {
+ case .checkingPayload: "Preparing"
+ case .stagingBridge: "Staging components"
+ case .preflight: "Checking Steam"
+ case .stoppingClient: "Stopping Steam"
+ case .copyingDylib: "Installing"
+ case .installingSignatures: "Installing signatures"
+ case .installingOverlayShim: "Installing components"
+ case .settingInsert: "Configuring Steam"
+ case .signing: "Signing"
+ case .registering: "Finishing up"
+ case .finished: "Done"
+ }
+ }
+}
+
+struct InstallOutcome: Sendable {
+ let stoppedClient: Bool
+ let version: String
+ let signatureDatabases: Int
+ let backedUpPlist: Bool
+ let bridgeStaged: Int
+}
+
+enum SteamInstaller {
+ static let step = "Install NotProton"
+
+ typealias ClientStopper = @Sendable (URL, () -> Void) throws -> Bool
+ typealias BundleRegistrar = @Sendable (URL) -> Void
+
+ static let stopTheClient: ClientStopper = { app, onStopping in
+ try SteamBundle.stopClient(app: app, step: step, onStopping: onStopping)
+ }
+
+ static func run(
+ payload suppliedPayload: InstallPayload.Located? = nil,
+ bridgePayload suppliedBridge: BridgePayload.Located? = nil,
+ version: String = AppVersion.bundled,
+ app: URL = SupportPaths.Steam.app,
+ bridge: URL = SupportPaths.bridge,
+ signatures: URL = SupportPaths.signatures,
+ overlayShim: URL = SupportPaths.overlayShim,
+ iconmaker: URL = SupportPaths.iconmaker,
+ appinfo: URL = SupportPaths.appinfo,
+ deployedVersion: URL = SupportPaths.deployedVersion,
+ backups: URL = SupportPaths.backups,
+ stopClient: ClientStopper = stopTheClient,
+ register: BundleRegistrar = { SteamBundle.register($0) },
+ report: @escaping @Sendable (InstallPhase) -> Void = { _ in }
+ ) throws -> InstallOutcome {
+ report(.checkingPayload)
+ let payload = try suppliedPayload ?? InstallPayload.locate()
+ let bridgeLocated = try suppliedBridge ?? BridgePayload.locate()
+
+ report(.stagingBridge)
+ let bridgeResult = try BridgePayload.stage(located: bridgeLocated, bridge: bridge)
+
+ report(.preflight)
+ let plist = app.appending(path: "Contents/Info.plist")
+ let dylib = app.appending(path: "Contents/MacOS/\(SupportPaths.dylibName)")
+ try assertBundleIsPresent(app)
+ try assertInsertIsDeployedOrAbsent(at: plist, dylib: dylib)
+ let patching = try needsPatching(plist: plist, dylib: dylib, shipping: payload.dylib, app: app)
+
+ var stopped = false
+ if patching {
+ stopped = try stopClient(app) { report(.stoppingClient) }
+
+ report(.copyingDylib)
+ try install(payload.dylib, at: dylib)
+ }
+ try write(version, to: deployedVersion)
+
+ report(.installingSignatures)
+ try FileManager.default.createDirectory(at: signatures, withIntermediateDirectories: true)
+ for database in payload.signatures {
+ try install(database, at: signatures.appending(path: database.lastPathComponent))
+ }
+
+ report(.installingOverlayShim)
+ try install(payload.overlayShim, at: overlayShim)
+ try install(payload.iconmaker, at: iconmaker)
+ try install(payload.appinfo, at: appinfo)
+
+ var backedUp = false
+ if patching {
+ report(.settingInsert)
+ backedUp = try backUpPlist(plist, into: backups)
+
+ let priorPlist = try? Data(contentsOf: plist)
+ do {
+ try setInsert(at: plist, to: dylib)
+
+ report(.signing)
+ try adHocSign(dylib)
+ try adHocSign(app.appending(path: "Contents/MacOS/steam_osx"))
+ try adHocSign(app)
+ } catch {
+ revertPlist(priorPlist, at: plist, app: app)
+ throw error
+ }
+ }
+
+ report(.registering)
+ register(app)
+
+ let landed = SteamBundle.currentInsert(at: plist)
+ guard landed == dylib.path(percentEncoded: false) else {
+ AppLog.note("install: bundle declares \(landed ?? "no insert")")
+ throw StepFailure(
+ step: step,
+ detail: "Steam is set up to inject a different dylib. Please repair Steam "
+ + "before installing NotProton."
+ )
+ }
+
+ report(.finished)
+ return InstallOutcome(
+ stoppedClient: stopped,
+ version: version,
+ signatureDatabases: payload.signatures.count,
+ backedUpPlist: backedUp,
+ bridgeStaged: bridgeResult.staged.count
+ )
+ }
+
+
+ static func assertBundleIsPresent(_ app: URL) throws {
+ guard FileManager.default.fileExists(atPath: app.path(percentEncoded: false)) else {
+ throw StepFailure(
+ step: step,
+ detail: "\(app.path(percentEncoded: false)) is not there, so there is nothing to install into."
+ )
+ }
+ }
+
+ static func assertInsertIsDeployedOrAbsent(at plist: URL, dylib: URL) throws {
+ guard let insert = SteamBundle.currentInsert(at: plist), !insert.isEmpty else { return }
+
+ let deployed = dylib.path(percentEncoded: false)
+ let foreign = insert.split(separator: ":").map(String.init).filter { $0 != deployed }
+ guard foreign.isEmpty else {
+ throw StepFailure(
+ step: step,
+ detail: "Another dylib is present. Repair your Steam install before "
+ + "installing NotProton."
+ )
+ }
+ }
+
+ static func needsPatching(plist: URL, dylib: URL, shipping: URL, app: URL) throws -> Bool {
+ let deployed = SteamBundle.currentInsert(at: plist) == dylib.path(percentEncoded: false)
+ if deployed, let installed = MachOBuild.identity(of: dylib),
+ let current = MachOBuild.identity(of: shipping), installed == current
+ {
+ AppLog.note("install: Steam already carries this dylib, installing for this account only")
+ return false
+ }
+
+ do {
+ try assertBundleIsWritable(app)
+ } catch let refusal as WriteRefused where refusal.remedy == .otherAccount {
+ throw StepFailure(
+ step: step,
+ detail: deployed ? Self.mismatchAcrossAccounts : Self.unpatchedAcrossAccounts
+ )
+ }
+ return true
+ }
+
+ private static let mismatchAcrossAccounts =
+ "Steam has a different copy of NotProton, installed by another account on this Mac. "
+ + "Update NotProton from that account, then try again."
+
+ private static let unpatchedAcrossAccounts =
+ "Steam has not been set up for NotProton, and this account cannot change it. "
+ + "Install from the account that owns Steam."
+
+ static func assertBundleIsWritable(_ app: URL) throws {
+ let directory = app.appending(path: "Contents/MacOS")
+ let probe = directory.appending(path: ".notproton-write-probe")
+ do {
+ try Data("probe".utf8).write(to: probe)
+ try FileManager.default.removeItem(at: probe)
+ } catch let error as NSError where error.code == NSFileWriteNoPermissionError {
+ throw WriteRefused(path: directory.path(percentEncoded: false))
+ } catch {
+ throw StepFailure(
+ step: step,
+ detail: "\(directory.path(percentEncoded: false)) could not be written. "
+ + error.localizedDescription
+ )
+ }
+ }
+
+ static func install(_ source: URL, at destination: URL) throws {
+ let files = FileManager.default
+ try WriteRefused.catching(destination) {
+ try files.createDirectory(
+ at: destination.deletingLastPathComponent(), withIntermediateDirectories: true
+ )
+ try? files.removeItem(at: destination)
+ try files.copyItem(at: source, to: destination)
+ }
+ }
+
+ static func write(_ version: String, to url: URL) throws {
+ try FileManager.default.createDirectory(
+ at: url.deletingLastPathComponent(), withIntermediateDirectories: true
+ )
+ try Data("\(version)\n".utf8).write(to: url)
+ }
+
+ static func backUpPlist(_ plist: URL, into backups: URL) throws -> Bool {
+ let destination = backups.appending(path: SteamBundle.plistBackupName)
+ let files = FileManager.default
+ guard !files.fileExists(atPath: destination.path(percentEncoded: false)) else { return false }
+ guard files.fileExists(atPath: plist.path(percentEncoded: false)) else { return false }
+
+ try files.createDirectory(at: backups, withIntermediateDirectories: true)
+ try files.copyItem(at: plist, to: destination)
+ return true
+ }
+
+ static func revertPlist(_ bytes: Data?, at plist: URL, app: URL) {
+ guard let bytes else { return }
+ try? bytes.write(to: plist)
+ try? adHocSign(app)
+ }
+
+ static func setInsert(at plist: URL, to dylib: URL) throws {
+ guard var dict = SteamBundle.readInfoPlist(at: plist) else {
+ throw StepFailure(
+ step: step,
+ detail: "\(plist.path(percentEncoded: false)) could not be read as a property list."
+ )
+ }
+
+ var environment = dict[SteamBundle.environmentKey] as? [String: Any] ?? [:]
+ environment[SteamBundle.insertKey] = dylib.path(percentEncoded: false)
+ dict[SteamBundle.environmentKey] = environment
+ try SteamBundle.writeInfoPlist(dict, at: plist)
+ }
+
+ static func adHocSign(_ url: URL, step: String = step) throws {
+ let path = url.path(percentEncoded: false)
+ let result = try Shell.run("/usr/bin/codesign", ["-f", "-s", "-", path])
+ guard result.succeeded else {
+ throw StepFailure(
+ step: step,
+ detail: "\(path) could not be signed. "
+ + result.stderr.trimmingCharacters(in: .whitespacesAndNewlines)
+ )
+ }
+ }
+
+}
diff --git a/app/Sources/NotProtonApp/Model/SteamRepair.swift b/app/Sources/NotProtonApp/Model/SteamRepair.swift
new file mode 100644
index 0000000..663b481
--- /dev/null
+++ b/app/Sources/NotProtonApp/Model/SteamRepair.swift
@@ -0,0 +1,216 @@
+// Logic for the Repair button
+
+import Foundation
+
+enum RepairPhase: Sendable {
+ case downloading(PinnedDownload.Progress)
+ case unpacking
+ case checking
+ case stoppingClient
+ case replacing
+ case clearingInsert
+ case removingUpdateBlock
+ case registering
+ case finished
+
+ var label: String {
+ switch self {
+ case .downloading(let progress): progress.label
+ case .unpacking: "Unpacking"
+ case .checking: "Verifying"
+ case .stoppingClient: "Stopping Steam"
+ case .replacing: "Restoring Steam"
+ case .clearingInsert: "Cleaning up"
+ case .removingUpdateBlock: "Cleaning up"
+ case .registering: "Finishing up"
+ case .finished: "Done"
+ }
+ }
+}
+
+struct RepairOutcome: Sendable {
+ let stoppedClient: Bool
+ let bundleVersion: String?
+ let clearedInnerInsert: Bool
+ let removedUpdateBlocks: [String]
+ let removedStaleBackup: Bool
+}
+
+enum SteamRepair {
+
+ static let valveTeam = "MXGJJ98X76"
+ static let valveIdentifier = "com.valvesoftware.steam"
+
+ private static let step = "Repair Steam"
+
+ static func run(
+ manifest suppliedManifest: ValvePackageManifest? = nil,
+ app: URL = SupportPaths.Steam.app,
+ innerPlist: URL = SupportPaths.Steam.innerInfoPlist,
+ updateBlocks: [URL] = UpdateBlock.paths,
+ backups: URL = SupportPaths.backups,
+ downloads: URL = SupportPaths.packageDownloads,
+ report: @Sendable (RepairPhase) -> Void = { _ in }
+ ) async throws -> RepairOutcome {
+ let manifest = try suppliedManifest ?? ValvePackageManifest.bundled()
+ guard let bundle = manifest.bundle else {
+ throw StepFailure(
+ step: step,
+ detail: "This copy of NotProton cannot repair Steam. Please reinstall NotProton."
+ )
+ }
+
+ let staged = try await stage(bundle, bases: manifest.bases, downloads: downloads, report: report)
+
+ report(.checking)
+ try verifyValveSignature(staged)
+
+ let stopped = try SteamBundle.stopClient(app: app, step: step) { report(.stoppingClient) }
+
+ report(.replacing)
+ try replace(app, with: staged)
+
+ report(.clearingInsert)
+ let clearedInner = try clearInsert(at: innerPlist)
+
+ report(.removingUpdateBlock)
+ let removed = try UpdateBlock.remove(from: updateBlocks)
+
+ report(.registering)
+ SteamBundle.register(app)
+
+ try verifyValveSignature(app)
+ let plist = app.appending(path: "Contents/Info.plist")
+ if let insert = SteamBundle.currentInsert(at: plist), !insert.isEmpty {
+ AppLog.note("repair: restored bundle still declares \(insert)")
+ throw StepFailure(
+ step: step,
+ detail: "Steam could not be fully restored. Please run Repair Steam again."
+ )
+ }
+
+ let removedBackup = try removeStaleBackup(from: backups)
+
+ report(.finished)
+ return RepairOutcome(
+ stoppedClient: stopped,
+ bundleVersion: version(of: app),
+ clearedInnerInsert: clearedInner,
+ removedUpdateBlocks: removed,
+ removedStaleBackup: removedBackup
+ )
+ }
+
+ static func stage(
+ _ bundle: ValveBundle,
+ bases: [URL],
+ downloads: URL,
+ work suppliedWork: URL? = nil,
+ report: @Sendable (RepairPhase) -> Void = { _ in }
+ ) async throws -> URL {
+ let files = FileManager.default
+ try files.createDirectory(at: downloads, withIntermediateDirectories: true)
+
+ let archive = try await PinnedDownload.obtain(
+ file: bundle.file, sha256: bundle.sha256, bases: bases, into: downloads, step: step
+ ) { report(.downloading($0)) }
+
+ report(.unpacking)
+
+ let work = suppliedWork ?? downloads.appending(path: "bundle")
+ try? files.removeItem(at: work)
+ try files.createDirectory(at: work, withIntermediateDirectories: true)
+
+ try Shell.check("/usr/bin/unzip", [
+ "-q", "-o", archive.path(percentEncoded: false), bundle.innerArchive,
+ "-d", work.path(percentEncoded: false),
+ ])
+ try Shell.check("/usr/bin/tar", [
+ "-xzf", work.appending(path: bundle.innerArchive).path(percentEncoded: false),
+ "-C", work.path(percentEncoded: false),
+ ])
+
+ let staged = work.appending(path: bundle.bundleName)
+ guard files.fileExists(atPath: staged.path(percentEncoded: false)) else {
+ throw StepFailure(
+ step: step,
+ detail: "\(bundle.innerArchive) did not contain \(bundle.bundleName)."
+ )
+ }
+ return staged
+ }
+
+ static func verifyValveSignature(_ url: URL) throws {
+ let path = url.path(percentEncoded: false)
+
+ let strict = try Shell.run("/usr/bin/codesign", ["--verify", "--strict", path])
+ guard strict.succeeded else {
+ throw StepFailure(
+ step: step,
+ detail: "\(path) does not verify against its own signature. "
+ + strict.stderr.trimmingCharacters(in: .whitespacesAndNewlines)
+ )
+ }
+
+ let described = try Shell.run("/usr/bin/codesign", ["-dvv", path])
+ let text = described.stdout + described.stderr
+
+ let fields = Set(
+ text.split(separator: "\n").map {
+ $0.trimmingCharacters(in: .whitespacesAndNewlines)
+ }
+ )
+
+ guard fields.contains("TeamIdentifier=\(valveTeam)") else {
+ throw StepFailure(
+ step: step,
+ detail: "\(path) is not signed by Valve. Expected TeamIdentifier=\(valveTeam)."
+ )
+ }
+ guard fields.contains("Identifier=\(valveIdentifier)") else {
+ throw StepFailure(
+ step: step,
+ detail: "\(path) is not the Steam bundle. Expected Identifier=\(valveIdentifier)."
+ )
+ }
+ }
+
+ static func replace(_ app: URL, with staged: URL) throws {
+ let files = FileManager.default
+ try WriteRefused.catching(app) {
+ guard files.fileExists(atPath: app.path(percentEncoded: false)) else {
+ try files.moveItem(at: staged, to: app)
+ return
+ }
+ _ = try files.replaceItemAt(app, withItemAt: staged)
+ }
+ }
+
+ static func clearInsert(at plist: URL) throws -> Bool {
+ guard var dict = SteamBundle.readInfoPlist(at: plist),
+ var environment = dict[SteamBundle.environmentKey] as? [String: Any],
+ environment[SteamBundle.insertKey] != nil
+ else { return false }
+
+ environment.removeValue(forKey: SteamBundle.insertKey)
+ dict[SteamBundle.environmentKey] = environment
+ try SteamBundle.writeInfoPlist(dict, at: plist)
+ return true
+ }
+
+ static func removeStaleBackup(from backups: URL) throws -> Bool {
+ let backup = backups.appending(path: SteamBundle.plistBackupName)
+ let path = backup.path(percentEncoded: false)
+ let files = FileManager.default
+ guard files.fileExists(atPath: path) else { return false }
+
+ try WriteRefused.catching(path) { try files.removeItem(at: backup) }
+ return true
+ }
+
+ static func version(of app: URL) -> String? {
+ guard let dict = SteamBundle.readInfoPlist(at: app.appending(path: "Contents/Info.plist"))
+ else { return nil }
+ return dict["CFBundleVersion"] as? String
+ }
+}
diff --git a/app/Sources/NotProtonApp/Model/SupportedRunner.swift b/app/Sources/NotProtonApp/Model/SupportedRunner.swift
new file mode 100644
index 0000000..16e8fb3
--- /dev/null
+++ b/app/Sources/NotProtonApp/Model/SupportedRunner.swift
@@ -0,0 +1,89 @@
+// Allow list of CrossOver builds the runner clones from. The ntdll hook sites
+// are hardcoded RVAs, so a build not pinned here would be patched at the wrong
+// offsets. New builds go in after running ntdll-patch/resolve.py and pinning
+// the hashes.
+
+import Foundation
+
+enum WineArch: String, Sendable, CaseIterable {
+ case x86_64Windows = "x86_64-windows"
+ case i386Windows = "i386-windows"
+ case aarch64Windows = "aarch64-windows"
+}
+
+struct RunnerBuild: Sendable, Equatable, Identifiable {
+ // CFBundleVersion, which also names the directory under runners/ and keys
+ // the ntdll hash tables. Changing it orphans an installed runner.
+ let bundleVersion: String
+
+ // CFBundleShortVersionString. CrossOver inverts the usual pair and sets this
+ // to the build date, so it is the string the download page shows. Display
+ // only, never identity.
+ let releaseVersion: String
+
+ let flavor: String?
+
+ let loaderSHA256: String
+
+ let cleanNtdll: [WineArch: String]
+ let patchedNtdll: [WineArch: String]
+
+ var id: String { flavor.map { "\(bundleVersion)-\($0)" } ?? bundleVersion }
+
+ var flavorName: String { flavor?.uppercased() ?? "Rosetta" }
+
+ var displayVersion: String { "\(releaseVersion) \(flavorName)" }
+}
+
+enum SupportedRunners {
+
+ static let all: [RunnerBuild] = [
+ RunnerBuild(
+ bundleVersion: "27.0.0.40921",
+ releaseVersion: "20260821",
+ flavor: nil,
+ loaderSHA256: "b59d5fdccb62d425230a4e4d157c50c25b63ff586832c60cc5b12b4d6053ab80",
+ cleanNtdll: [
+ .x86_64Windows: "04c7200b6645decb7c2d1ba6b0195abc9af83257072558d11aa72cc067ac3377",
+ .i386Windows: "94cc7c14c1e9dcf58ef501015c115f8405c73b2a65cefe31faa5d9e47f36e58b",
+ ],
+ patchedNtdll: [
+ .x86_64Windows: "b21f4bace5a7a0cfef0f74cef9b27561f6eb3ad38daf76f36b186ca0677c2b2c",
+ .i386Windows: "25bfde1f50ee96485763968ef10b9d9ad35e38214232f17ebdc009b098af44a0",
+ ]
+ ),
+ RunnerBuild(
+ bundleVersion: "27.0.0.40921",
+ releaseVersion: "20260821",
+ flavor: "fex",
+ loaderSHA256: "7a6ea337c9caf2217454bec9537371e5d8ca302406bbed40b65316c1a636c4ab",
+ cleanNtdll: [
+ .i386Windows: "09474795d6f306163cebab6429819999fcff50e07dbc4b067a90ec4f74a3a7d7",
+ .aarch64Windows: "7823d71fbce6c9947163bf8b96beb299eabb02878245bcaf6759f2a22e81f071",
+ ],
+ patchedNtdll: [
+ .i386Windows: "e799ea02418294588ee353a90b967358be316a3044ff9515b28aa1ce07e63981",
+ .aarch64Windows: "560939a0f6e58314fc9d79fe6f839dce2b181f829ae58dca195fa142fcf40f39",
+ ]
+ ),
+ ]
+
+ static func build(loaderSHA256 hash: String) -> RunnerBuild? {
+ all.first { $0.loaderSHA256 == hash }
+ }
+
+ static func build(id: String) -> RunnerBuild? {
+ all.first { $0.id == id }
+ }
+
+ static func displayVersion(forID id: String) -> String {
+ build(id: id)?.displayVersion ?? id
+ }
+
+ static var versionList: String {
+ var seen = Set<String>()
+ return all.map(\.releaseVersion)
+ .filter { seen.insert($0).inserted }
+ .joined(separator: ", ")
+ }
+}
diff --git a/app/Sources/NotProtonApp/Model/Uninstall.swift b/app/Sources/NotProtonApp/Model/Uninstall.swift
new file mode 100644
index 0000000..5272a4a
--- /dev/null
+++ b/app/Sources/NotProtonApp/Model/Uninstall.swift
@@ -0,0 +1,121 @@
+// Self-explanatory I think
+
+import Foundation
+
+enum UninstallPhase: Sendable {
+ case stoppingClient
+ case detaching
+ case restoring(RepairPhase)
+ case removing
+ case finished
+
+ var label: String {
+ switch self {
+ case .stoppingClient: "Stopping Steam"
+ case .detaching: "Detaching from Steam"
+ case .restoring(let phase): phase.label
+ case .removing: "Removing files"
+ case .finished: "Done"
+ }
+ }
+}
+
+struct UninstallOutcome: Sendable {
+ let stoppedClient: Bool
+ let detached: Bool
+ let restoredValveSignature: Bool
+ let removed: [String]
+}
+
+enum Uninstall {
+ static let step = "Remove NotProton"
+
+ typealias Repair = @Sendable (@escaping @Sendable (RepairPhase) -> Void) async throws -> Void
+
+ typealias Stop = @Sendable (@Sendable () -> Void) throws -> Bool
+
+ static func run(
+ app: URL = SupportPaths.Steam.app,
+ innerPlist: URL = SupportPaths.Steam.innerInfoPlist,
+ updateBlocks: [URL] = UpdateBlock.paths,
+ legacyCompat: URL = SupportPaths.Steam.legacyCompat,
+ compatTool: URL = SupportPaths.Steam.compatTool,
+ directories: [URL] = [
+ SupportPaths.support,
+ SupportPaths.packageDownloads.deletingLastPathComponent(),
+ ],
+ report: @escaping @Sendable (UninstallPhase) -> Void = { _ in },
+ repair: Repair = { report in _ = try await SteamRepair.run(report: report) },
+ stop: Stop = { onStopping in try SteamBundle.stopClient(step: step, onStopping: onStopping) }
+ ) async throws -> UninstallOutcome {
+ let stopped = try stop { report(.stoppingClient) }
+
+ report(.detaching)
+ let detached = try detach(from: app, innerPlist: innerPlist, updateBlocks: updateBlocks)
+
+ let restored: Bool
+ do {
+ try await repair { report(.restoring($0)) }
+ restored = true
+ } catch {
+ restored = false
+ }
+
+ report(.removing)
+ let removed = try remove(
+ legacyCompat: legacyCompat, compatTool: compatTool, directories: directories
+ )
+
+ report(.finished)
+ return UninstallOutcome(
+ stoppedClient: stopped,
+ detached: detached,
+ restoredValveSignature: restored,
+ removed: removed
+ )
+ }
+
+ static func detach(from app: URL, innerPlist: URL, updateBlocks: [URL]) throws -> Bool {
+ let files = FileManager.default
+ let plist = app.appending(path: "Contents/Info.plist")
+ let dylib = app.appending(path: "Contents/MacOS/\(SupportPaths.dylibName)")
+ let executable = app.appending(path: "Contents/MacOS/steam_osx")
+
+ _ = try SteamRepair.clearInsert(at: innerPlist)
+ _ = try UpdateBlock.remove(from: updateBlocks)
+
+ let cleared = try SteamRepair.clearInsert(at: plist)
+ var droppedDylib = false
+ do {
+ if files.fileExists(atPath: dylib.path(percentEncoded: false)) {
+ try files.removeItem(at: dylib)
+ droppedDylib = true
+ }
+
+ guard cleared || droppedDylib else { return false }
+
+ try SteamInstaller.adHocSign(executable, step: step)
+ try SteamInstaller.adHocSign(app, step: step)
+ } catch {
+ if cleared || droppedDylib {
+ try? SteamInstaller.adHocSign(executable, step: step)
+ try? SteamInstaller.adHocSign(app, step: step)
+ }
+ throw error
+ }
+ return true
+ }
+
+ static func remove(legacyCompat: URL, compatTool: URL, directories: [URL]) throws -> [String] {
+ let files = FileManager.default
+ var removed: [String] = []
+
+ for target in [legacyCompat, compatTool] + directories {
+ let path = target.path(percentEncoded: false)
+ guard files.fileExists(atPath: path) else { continue }
+ try WriteRefused.catching(path) { try files.removeItem(at: target) }
+ removed.append(target.lastPathComponent)
+ }
+ return removed
+ }
+}
diff --git a/app/Sources/NotProtonApp/Model/UpdateBlock.swift b/app/Sources/NotProtonApp/Model/UpdateBlock.swift
new file mode 100644
index 0000000..e21b4bc
--- /dev/null
+++ b/app/Sources/NotProtonApp/Model/UpdateBlock.swift
@@ -0,0 +1,112 @@
+// Simple logic to block updates in the Steam client, if
+// a user wants to.
+
+import Foundation
+
+enum UpdateBlock {
+ static let step = "Block client updates"
+
+ static let key = "BootStrapperInhibitUpdateOnLaunch"
+ static let contents = "\(key)=enable\n"
+
+ static var paths: [URL] {
+ [SupportPaths.Steam.configFile, SupportPaths.Steam.innerConfigFile]
+ }
+
+ static func isPresent(at urls: [URL] = paths) -> Bool {
+ guard let required = urls.first else { return false }
+ guard let text = try? String(contentsOf: required, encoding: .utf8) else { return false }
+ return setting(in: text) == "enable"
+ }
+
+ private static func setting(in text: String) -> String? {
+ text.split(separator: "\n", omittingEmptySubsequences: false).compactMap(value(of:)).last
+ }
+
+ private static func value(of line: Substring) -> String? {
+ let parts = line.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false)
+ guard parts.count == 2, parts[0].trimmingCharacters(in: .whitespaces) == key else { return nil }
+ return parts[1].trimmingCharacters(in: .whitespaces)
+ }
+
+ private static func blocked(_ text: String) -> String {
+ var seen = false
+ var out: [String] = []
+ for line in text.split(separator: "\n", omittingEmptySubsequences: false) {
+ guard value(of: line) != nil else {
+ out.append(String(line))
+ continue
+ }
+ if !seen {
+ out.append(contents.trimmingCharacters(in: .newlines))
+ seen = true
+ }
+ }
+ guard !seen else { return out.joined(separator: "\n") }
+ if out.last?.isEmpty == true { out.removeLast() }
+ out.append(contents.trimmingCharacters(in: .newlines))
+ out.append("")
+ return out.joined(separator: "\n")
+ }
+
+ private static func unblocked(_ text: String) -> String {
+ let out = text.split(separator: "\n", omittingEmptySubsequences: false)
+ .filter { value(of: $0) == nil }
+ return out.joined(separator: "\n")
+ }
+
+ @discardableResult
+ static func write(to urls: [URL] = paths) throws -> [String] {
+ guard let required = urls.first else { return [] }
+
+ func existing(at url: URL) -> String {
+ (try? String(contentsOf: url, encoding: .utf8)) ?? ""
+ }
+
+ do {
+ try FileManager.default.createDirectory(
+ at: required.deletingLastPathComponent(), withIntermediateDirectories: true
+ )
+ try Data(blocked(existing(at: required)).utf8).write(to: required)
+ } catch let error as NSError where error.code == NSFileWriteNoPermissionError {
+ throw WriteRefused(path: required.path(percentEncoded: false))
+ } catch {
+ throw StepFailure(
+ step: step,
+ detail: "\(required.path(percentEncoded: false)) could not be written. "
+ + error.localizedDescription
+ )
+ }
+
+ var written = [required.path(percentEncoded: false)]
+ for url in urls.dropFirst() {
+ let parent = url.deletingLastPathComponent()
+ guard FileManager.default.fileExists(atPath: parent.path(percentEncoded: false)) else { continue }
+ guard (try? Data(blocked(existing(at: url)).utf8).write(to: url)) != nil else { continue }
+ written.append(url.path(percentEncoded: false))
+ }
+ return written
+ }
+
+ @discardableResult
+ static func remove(from urls: [URL] = paths) throws -> [String] {
+ let files = FileManager.default
+ var removed: [String] = []
+ for url in urls {
+ let path = url.path(percentEncoded: false)
+ guard files.fileExists(atPath: path) else { continue }
+ let text = try? String(contentsOf: url, encoding: .utf8)
+ let kept = text.map(unblocked) ?? ""
+ guard text == nil || kept != text else { continue }
+ try WriteRefused.catching(path) {
+ if kept.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ try files.removeItem(at: url)
+ } else {
+ try Data(kept.utf8).write(to: url)
+ }
+ }
+ removed.append(path)
+ }
+ return removed
+ }
+}
diff --git a/app/Sources/NotProtonApp/Model/ValveFetcher.swift b/app/Sources/NotProtonApp/Model/ValveFetcher.swift
new file mode 100644
index 0000000..ca51b36
--- /dev/null
+++ b/app/Sources/NotProtonApp/Model/ValveFetcher.swift
@@ -0,0 +1,125 @@
+// Downloads needed components from Valve
+
+import Foundation
+
+enum ValveFetcher {
+
+ enum Phase: Sendable {
+ case downloading(PinnedDownload.Progress)
+ case extracting
+ case verifying
+ case installing
+ case finished
+
+ var label: String {
+ switch self {
+ case .downloading(let progress): progress.label
+ case .extracting: "Extracting"
+ case .verifying: "Verifying"
+ case .installing: "Installing"
+ case .finished: "Done"
+ }
+ }
+ }
+
+ struct Outcome: Sendable {
+ let installed: [String]
+ let unchanged: [String]
+
+ var wroteNothing: Bool { installed.isEmpty }
+ }
+
+ private static let step = "Fetch the Valve binaries"
+
+ static func run(
+ manifest suppliedManifest: ValvePackageManifest? = nil,
+ bridge: URL = SupportPaths.bridge,
+ downloads: URL = SupportPaths.packageDownloads,
+ report: @Sendable (Phase) -> Void = { _ in }
+ ) async throws -> Outcome {
+ let manifest = try suppliedManifest ?? ValvePackageManifest.bundled()
+ let files = FileManager.default
+ try files.createDirectory(at: downloads, withIntermediateDirectories: true)
+
+ let extracted = downloads.appending(path: "extract")
+ try? files.removeItem(at: extracted)
+ try files.createDirectory(at: extracted, withIntermediateDirectories: true)
+ defer { try? files.removeItem(at: extracted) }
+
+ for package in manifest.packages {
+ let archive = try await obtain(package, bases: manifest.bases, downloads: downloads, report: report)
+ report(.extracting)
+ try extract(manifest.innerPaths(package: package.id), from: archive, into: extracted)
+ }
+
+ report(.verifying)
+ let wrong = manifest.files.filter { Digest.sha256IfPresent(extracted.appending(path: $0.innerPath)) != $0.sha256 }
+ guard wrong.isEmpty else {
+ AppLog.note("valve fetch: \(wrong.count) of \(manifest.files.count) files missed their "
+ + "pinned hash: \(wrong.map(\.bridgePath).joined(separator: ", "))")
+ throw StepFailure(
+ step: step,
+ detail: "Something is wrong with the downloaded files. "
+ + "Please check for a NotProton update."
+ )
+ }
+
+ report(.installing)
+ let outcome = try install(manifest, from: extracted, into: bridge)
+
+ report(.finished)
+ return outcome
+ }
+
+ static func install(
+ _ manifest: ValvePackageManifest, from extracted: URL, into bridge: URL
+ ) throws -> Outcome {
+ let files = FileManager.default
+ var installed: [String] = []
+ var unchanged: [String] = []
+
+ for file in manifest.files {
+ let destination = bridge.appending(path: file.bridgePath)
+ if Digest.sha256IfPresent(destination) == file.sha256 {
+ unchanged.append(file.bridgePath)
+ continue
+ }
+ try files.createDirectory(
+ at: destination.deletingLastPathComponent(), withIntermediateDirectories: true
+ )
+
+ let pending = destination.appendingPathExtension("notproton-pending")
+ try? files.removeItem(at: pending)
+ try files.copyItem(at: extracted.appending(path: file.innerPath), to: pending)
+
+ if files.fileExists(atPath: destination.path(percentEncoded: false)) {
+ _ = try files.replaceItemAt(destination, withItemAt: pending)
+ } else {
+ try files.moveItem(at: pending, to: destination)
+ }
+ installed.append(file.bridgePath)
+ }
+
+ return Outcome(installed: installed, unchanged: unchanged)
+ }
+
+ private static func obtain(
+ _ package: ValvePackage,
+ bases: [URL],
+ downloads: URL,
+ report: @Sendable (Phase) -> Void
+ ) async throws -> URL {
+ try await PinnedDownload.obtain(
+ file: package.file, sha256: package.sha256, bases: bases, into: downloads, step: step
+ ) { report(.downloading($0)) }
+ }
+
+ private static func extract(_ inner: [String], from archive: URL, into destination: URL) throws {
+ try Shell.check(
+ "/usr/bin/unzip",
+ ["-q", "-o", archive.path(percentEncoded: false)]
+ + inner
+ + ["-d", destination.path(percentEncoded: false)]
+ )
+ }
+}
diff --git a/app/Sources/NotProtonApp/Model/ValvePackageManifest.swift b/app/Sources/NotProtonApp/Model/ValvePackageManifest.swift
new file mode 100644
index 0000000..81e4ad2
--- /dev/null
+++ b/app/Sources/NotProtonApp/Model/ValvePackageManifest.swift
@@ -0,0 +1,167 @@
+// Validation for downloaded Valve binaries
+
+import Foundation
+
+struct ValvePackage: Sendable, Equatable, Identifiable {
+ let id: String
+ let file: String
+ let sha256: String
+}
+
+struct ValveFile: Sendable, Equatable, Identifiable {
+ let bridgePath: String
+ let package: String
+ let innerPath: String
+ let sha256: String
+
+ var id: String { bridgePath }
+}
+
+struct ValveBundle: Sendable, Equatable {
+ let file: String
+ let sha256: String
+ let innerArchive: String
+ let bundleName: String
+}
+
+struct ValvePackageManifest: Sendable {
+ let bases: [URL]
+ let packages: [ValvePackage]
+ let files: [ValveFile]
+ let bundle: ValveBundle?
+
+ func package(id: String) -> ValvePackage? {
+ packages.first { $0.id == id }
+ }
+
+ func innerPaths(package id: String) -> [String] {
+ var seen = Set<String>()
+ return files.filter { $0.package == id }.compactMap { seen.insert($0.innerPath).inserted ? $0.innerPath : nil }
+ }
+
+ static let resourceName = "valve-packages"
+ static let resourceExtension = "manifest"
+
+ private static let step = "Read the Valve file list"
+
+ static func bundled() throws -> ValvePackageManifest {
+ guard let url = Bundle.module.url(
+ forResource: resourceName, withExtension: resourceExtension
+ ) else {
+ throw StepFailure(
+ step: step,
+ detail: "\(resourceName).\(resourceExtension) is missing from the app's resources."
+ )
+ }
+ return try load(from: url)
+ }
+
+ static func load(from url: URL) throws -> ValvePackageManifest {
+ let data: Data
+ do {
+ data = try Data(contentsOf: url)
+ } catch {
+ throw StepFailure(
+ step: step,
+ detail: "\(url.path(percentEncoded: false)) could not be read. \(error.localizedDescription)"
+ )
+ }
+ return try parse(String(decoding: data, as: UTF8.self))
+ }
+
+ static func parse(_ text: String) throws -> ValvePackageManifest {
+ var bases: [URL] = []
+ var packages: [ValvePackage] = []
+ var files: [ValveFile] = []
+ var bundle: ValveBundle?
+ var packageIDs = Set<String>()
+ var bridgePaths = Set<String>()
+
+ for (index, rawLine) in text.split(separator: "\n", omittingEmptySubsequences: false).enumerated() {
+ let line = rawLine.trimmingCharacters(in: .whitespaces)
+ if line.isEmpty || line.hasPrefix("#") { continue }
+
+ let fields = line.split(separator: " ", omittingEmptySubsequences: true).map(String.init)
+ let number = index + 1
+
+ switch fields[0] {
+ case "base":
+ try expect(fields.count == 2, number, "a base and one URL", line)
+ guard let url = URL(string: fields[1]), url.scheme == "https", url.host() != nil else {
+ throw fail(number, "does not hold an https URL: \(fields[1])")
+ }
+ bases.append(url)
+
+ case "package":
+ try expect(fields.count == 4, number, "a package, an id, a filename and a sha256", line)
+ try expectHash(fields[3], number)
+ guard packageIDs.insert(fields[1]).inserted else {
+ throw fail(number, "repeats the package id \(fields[1]).")
+ }
+ packages.append(ValvePackage(id: fields[1], file: fields[2], sha256: fields[3]))
+
+ case "file":
+ try expect(fields.count == 5, number, "a file, a bridge path, a package id, an inner path and a sha256", line)
+ try expectHash(fields[4], number)
+ guard bridgePaths.insert(fields[1]).inserted else {
+ throw fail(number, "repeats the bridge path \(fields[1]).")
+ }
+ files.append(ValveFile(bridgePath: fields[1], package: fields[2], innerPath: fields[3], sha256: fields[4]))
+
+ case "bundle":
+ try expect(fields.count == 5, number,
+ "a bundle, a filename, a sha256, an inner archive and a bundle name", line)
+ try expectHash(fields[2], number)
+ guard bundle == nil else {
+ throw fail(number, "declares a second bundle. One is the most that can be installed.")
+ }
+ bundle = ValveBundle(
+ file: fields[1], sha256: fields[2], innerArchive: fields[3], bundleName: fields[4]
+ )
+
+ default:
+ throw fail(number, "has an unknown row kind \(fields[0]). Known: base, package, file, bundle.")
+ }
+ }
+
+ guard !bases.isEmpty else { throw fail(nil, "names no CDN host to fetch from.") }
+ guard !packages.isEmpty else { throw fail(nil, "names no package.") }
+ guard !files.isEmpty else { throw fail(nil, "names no file.") }
+
+ for file in files where !packageIDs.contains(file.package) {
+ throw fail(nil, "\(file.bridgePath) names the package \(file.package), which is not declared. "
+ + "Declared: \(packages.map(\.id).joined(separator: ", ")).")
+ }
+
+ for package in packages where !files.contains(where: { $0.package == package.id }) {
+ throw fail(nil, "declares the package \(package.id), which no file row uses.")
+ }
+
+ var hashByInner: [String: (path: String, sha: String)] = [:]
+ for file in files {
+ let key = "\(file.package)/\(file.innerPath)"
+ if let first = hashByInner[key], first.sha != file.sha256 {
+ throw fail(nil, "\(first.path) and \(file.bridgePath) both come from \(key) "
+ + "but pin different hashes.")
+ }
+ hashByInner[key] = (file.bridgePath, file.sha256)
+ }
+
+ return ValvePackageManifest(bases: bases, packages: packages, files: files, bundle: bundle)
+ }
+
+ private static func expect(_ condition: Bool, _ line: Int, _ shape: String, _ text: String) throws {
+ guard condition else { throw fail(line, "is not \(shape): \(text)") }
+ }
+
+ private static func expectHash(_ value: String, _ line: Int) throws {
+ let hex = "0123456789abcdef"
+ guard value.count == 64, value.allSatisfy(hex.contains) else {
+ throw fail(line, "does not end in a lowercase 64 character sha256: \(value)")
+ }
+ }
+
+ private static func fail(_ line: Int?, _ detail: String) -> StepFailure {
+ StepFailure(step: step, detail: line.map { "Line \($0) \(detail)" } ?? "The Valve file list \(detail)")
+ }
+}
diff --git a/app/Sources/NotProtonApp/PrefixesModel.swift b/app/Sources/NotProtonApp/PrefixesModel.swift
new file mode 100644
index 0000000..2efd311
--- /dev/null
+++ b/app/Sources/NotProtonApp/PrefixesModel.swift
@@ -0,0 +1,277 @@
+// Prefix logic that drives the prefix view itself.
+
+import AppKit
+import Foundation
+import Observation
+
+@MainActor
+@Observable
+final class PrefixesModel {
+
+ private(set) var prefixes: [WinePrefix] = []
+ private(set) var usage: [String: PrefixUsage] = [:]
+ private(set) var isLoading = false
+ private(set) var arch: [String: PrefixArch] = [:]
+ private(set) var expectedArch: PrefixArch = .arm64
+
+ func isForeign(_ prefix: WinePrefix) -> Bool {
+ guard let built = arch[prefix.id] else { return false }
+ return built != expectedArch
+ }
+
+ private(set) var hasLoaded = false
+ private(set) var busy = Set<WinePrefix.ID>()
+
+ var isBusy: Bool { !busy.isEmpty }
+ var outcome: String?
+ private(set) var report: FailureReport?
+
+ var failure: String? { report?.message }
+
+ var selection = Set<WinePrefix.ID>()
+
+ var pendingConfirmation: Confirmation?
+
+ private(set) var backups: [PrefixBackup] = []
+
+ var backupBytes: Int64 { backups.reduce(into: Int64(0)) { $0 += $1.bytes } }
+
+ enum Confirmation: Equatable {
+ case delete([WinePrefix])
+ case rebuild([WinePrefix])
+ case backUp([WinePrefix])
+ case deleteBackups([PrefixBackup])
+ }
+
+ var selectedPrefix: WinePrefix? {
+ guard selection.count == 1, let id = selection.first else { return nil }
+ return prefixes.first { $0.id == id }
+ }
+
+ var selectedPrefixes: [WinePrefix] {
+ prefixes.filter { selection.contains($0.id) }
+ }
+
+ private let libraries: @Sendable () -> [SteamLibrary]
+ private let runnerArch: @Sendable () -> PrefixArch
+ private let rebuild: @Sendable (WinePrefix, Bool) throws -> URL?
+ private let makeBackup: @Sendable (WinePrefix) throws -> URL
+
+ init(
+ libraries: @escaping @Sendable () -> [SteamLibrary] = { PrefixStore.libraries() },
+ runnerArch: @escaping @Sendable () -> PrefixArch = { PrefixTools.prefixArch() },
+ rebuild: @escaping @Sendable (WinePrefix, Bool) throws -> URL? = {
+ try PrefixTools.recreate($0, keepBackup: $1)
+ },
+ makeBackup: @escaping @Sendable (WinePrefix) throws -> URL = {
+ try PrefixTools.backUp($0)
+ }
+ ) {
+ self.libraries = libraries
+ self.runnerArch = runnerArch
+ self.rebuild = rebuild
+ self.makeBackup = makeBackup
+ }
+
+ private var loadGeneration = 0
+ func load() async {
+ loadGeneration += 1
+ let run = loadGeneration
+ isLoading = true
+ defer { if run == loadGeneration { isLoading = false } }
+
+ let roots = libraries()
+ let found = await Task.detached { PrefixStore.all(libraries: roots) }.value
+ guard run == loadGeneration else { return }
+ prefixes = found
+ usage = [:]
+ expectedArch = runnerArch()
+ arch = await Task.detached {
+ found.reduce(into: [String: PrefixArch]()) { built, prefix in
+ if let found = PrefixStore.arch(of: prefix) { built[prefix.id] = found }
+ }
+ }.value
+ guard run == loadGeneration else { return }
+ selection = selection.filter { id in found.contains { $0.id == id } }
+
+ var kept: [PrefixBackup] = []
+ for prefix in found {
+ let details = await Task.detached { PrefixStore.backupDetails(of: prefix) }.value
+ guard run == loadGeneration else { return }
+ kept.append(contentsOf: details)
+ }
+ kept.sort { ($0.taken ?? .distantPast) > ($1.taken ?? .distantPast) }
+ backups = kept
+
+ for prefix in found {
+ let measured = await Task.detached { PrefixStore.usage(of: prefix) }.value
+ guard run == loadGeneration else { return }
+ usage[prefix.id] = measured
+ }
+
+ hasLoaded = true
+ }
+
+ func open(_ tool: WineTool, for prefix: WinePrefix) {
+ act(on: prefix) {
+ try PrefixTools.launch(tool, in: prefix)
+ return "Opened \(tool.label) in \(prefix.title)."
+ }
+ }
+
+ func reveal(_ prefix: WinePrefix) {
+ PrefixTools.reveal(prefix)
+ }
+
+ func delete(_ targets: [WinePrefix]) async {
+ await eachInTurn(targets, { try PrefixTools.delete($0) }) { deleted in
+ if deleted.count == 1 {
+ return "Deleted the prefix for \(deleted[0].prefix.title). Steam will make a new "
+ + "prefix if the game is launched again."
+ }
+ guard deleted.count > 1 else { return nil }
+ return "Deleted \(deleted.count) prefixes. Steam will make a new prefix if a game "
+ + "is launched again."
+ }
+ }
+
+ func backUp(_ targets: [WinePrefix]) async {
+ await eachInTurn(targets, makeBackup) { saved in
+ guard let first = saved.first else { return nil }
+ guard saved.count == 1 else { return "Backed up \(saved.count) prefixes." }
+ return "Backed up the prefix for \(first.prefix.title)."
+ }
+ }
+
+ func recreate(_ targets: [WinePrefix], keepBackup: Bool = true) async {
+ let make = rebuild
+ await eachInTurn(targets, { try make($0, keepBackup) }) { rebuilt in
+ let kept = rebuilt.compactMap(\.made)
+ if rebuilt.count == 1 {
+ let title = rebuilt[0].prefix.title
+ guard let backup = kept.first else { return "Rebuilt the prefix for \(title)." }
+ return "Rebuilt the prefix for \(title). The original is at "
+ + "\(backup.path(percentEncoded: false)). Check that your save is present in "
+ + "the game, then delete the backup to save space."
+ }
+ guard rebuilt.count > 1 else { return nil }
+ guard !kept.isEmpty else { return "Rebuilt \(rebuilt.count) prefixes." }
+ return "Rebuilt \(rebuilt.count) prefixes. Each original is kept beside the game's "
+ + "prefix. Check that your saves are present in the games, then delete the "
+ + "backups to save space."
+ }
+ }
+
+ func reveal(_ backup: PrefixBackup) {
+ PrefixTools.reveal(at: backup.url)
+ }
+
+ func forgetOutcome() {
+ report = nil
+ outcome = nil
+ }
+
+ func deleteBackups(_ targets: [PrefixBackup]) async {
+ guard !targets.isEmpty else { return }
+ forgetOutcome()
+ isLoading = true
+
+ var cleared: [PrefixBackup] = []
+ var refused: [Error] = []
+ for backup in targets {
+ do {
+ try await Task.detached { try PrefixTools.deleteBackup(backup.url) }.value
+ cleared.append(backup)
+ } catch {
+ refused.append(error)
+ }
+ }
+
+ outcome = clearedSentence(cleared)
+ report = FailureReport(refused)
+ let gone = Set(cleared.map(\.id))
+ backups.removeAll { gone.contains($0.id) }
+ isLoading = false
+ await load()
+ }
+
+ private func clearedSentence(_ cleared: [PrefixBackup]) -> String? {
+ guard !cleared.isEmpty else { return nil }
+ let games = Set(cleared.map(\.prefix.id)).count
+ if cleared.count == 1 {
+ return "Deleted the backup for \(cleared[0].title)."
+ }
+ if games == 1 {
+ return "Deleted \(cleared.count) backups for \(cleared[0].title)."
+ }
+ return "Deleted \(cleared.count) backups across \(games) prefixes."
+ }
+
+ private typealias Step<Made> = (prefix: WinePrefix, made: Made)
+
+ @discardableResult
+ private func eachInTurn<Made: Sendable>(
+ _ targets: [WinePrefix],
+ _ work: @escaping @Sendable (WinePrefix) throws -> Made,
+ saying sentence: ([Step<Made>]) -> String?
+ ) async -> [Step<Made>] {
+ guard !targets.isEmpty else { return [] }
+ forgetOutcome()
+ isLoading = true
+ busy = Set(targets.map(\.id))
+
+ var done: [Step<Made>] = []
+ var refused: [Error] = []
+ for prefix in targets {
+ do {
+ let made = try await Task.detached { try work(prefix) }.value
+ done.append((prefix: prefix, made: made))
+ } catch {
+ refused.append(error)
+ }
+ busy.remove(prefix.id)
+ }
+
+ outcome = sentence(done)
+ report = FailureReport(refused)
+
+ busy = []
+ isLoading = false
+ await load()
+ return done
+ }
+
+ func chooseExecutable(for prefix: WinePrefix) {
+ let panel = NSOpenPanel()
+ panel.canChooseFiles = true
+ panel.canChooseDirectories = false
+ panel.allowsMultipleSelection = false
+ let types = PrefixTools.runnableTypes
+ if !types.isEmpty { panel.allowedContentTypes = types }
+ panel.prompt = "Run"
+ panel.message = "Choose a Windows program to run in \(prefix.title)."
+ panel.directoryURL = PrefixStore.installDirectory(of: prefix)
+ ?? prefix.pfx.appending(path: "drive_c")
+
+ guard panel.runModal() == .OK, let picked = panel.url else { return }
+ run(picked, in: prefix)
+ }
+
+ func run(_ executable: URL, in prefix: WinePrefix) {
+ act(on: prefix) {
+ try PrefixTools.run(executable, in: prefix)
+ return "Started \(executable.lastPathComponent) in \(prefix.title)."
+ }
+ }
+
+ private func act(on prefix: WinePrefix, _ body: () throws -> String) {
+ forgetOutcome()
+ busy = [prefix.id]
+ defer { busy = [] }
+ do {
+ outcome = try body()
+ } catch {
+ report = FailureReport([error])
+ }
+ }
+}
diff --git a/app/Sources/NotProtonApp/Resources/detour2.bin b/app/Sources/NotProtonApp/Resources/detour2.bin
new file mode 100644
index 0000000..2ee1810
Binary files /dev/null and b/app/Sources/NotProtonApp/Resources/detour2.bin differ
diff --git a/app/Sources/NotProtonApp/Resources/detour32-fex.bin b/app/Sources/NotProtonApp/Resources/detour32-fex.bin
new file mode 100755
index 0000000..17dc6a4
Binary files /dev/null and b/app/Sources/NotProtonApp/Resources/detour32-fex.bin differ
diff --git a/app/Sources/NotProtonApp/Resources/detour32.bin b/app/Sources/NotProtonApp/Resources/detour32.bin
new file mode 100644
index 0000000..db38672
Binary files /dev/null and b/app/Sources/NotProtonApp/Resources/detour32.bin differ
diff --git a/app/Sources/NotProtonApp/Resources/detour64-fex.bin b/app/Sources/NotProtonApp/Resources/detour64-fex.bin
new file mode 100755
index 0000000..3edf831
Binary files /dev/null and b/app/Sources/NotProtonApp/Resources/detour64-fex.bin differ
diff --git a/app/Sources/NotProtonApp/Resources/payload.manifest b/app/Sources/NotProtonApp/Resources/payload.manifest
new file mode 100644
index 0000000..7121fb4
--- /dev/null
+++ b/app/Sources/NotProtonApp/Resources/payload.manifest
@@ -0,0 +1,19 @@
+built lsteamclient.dll
+built lsteamclient.so
+built steam.exe
+built i386-windows/lsteamclient.dll
+built x86_64-windows/lsteamclient.dll
+built x86_64-unix/lsteamclient.so
+built aarch64-unix/lsteamclient.so
+patched wine/i386-windows/ntdll.dll
+patched wine/x86_64-windows/ntdll.dll
+valve steamclient.dll
+valve steamclient64.dll
+valve tier0_s64.dll
+valve vstdlib_s64.dll
+valve legacycompat/GameOverlayRenderer64.dll
+valve legacycompat/Steam.dll
+valve legacycompat/SteamService.exe
+valve legacycompat/iscriptevaluator.exe
+valve legacycompat/steamclient.dll
+valve legacycompat/steamclient64.dll
diff --git a/app/Sources/NotProtonApp/Resources/valve-packages.manifest b/app/Sources/NotProtonApp/Resources/valve-packages.manifest
new file mode 100644
index 0000000..07c1335
--- /dev/null
+++ b/app/Sources/NotProtonApp/Resources/valve-packages.manifest
@@ -0,0 +1,19 @@
+base https://client-update.akamai.steamstatic.com
+base https://steamcdn-a.akamaihd.net/client
+base https://media.steampowered.com/client
+
+package linux bins_misc_ubuntu12.zip.3f92810725ee673827371a0470cd4f8c7ea8cfae 026b984726c728bbf81ae3ba16623bcd96e2bf837a859c235acf0ee279d940fd
+package win64 bins_win64.zip.36f5d9202e79ab2aa3e3c5902e84bbd799d31fc0 93f5b6bea0267fd85dc8cc823fdab5c5fb55d7f3a1deab0598acefef0e133bce
+
+bundle appdmg_osx.zip.984652b88a9737e3f4e77c656d9ffa67d5042c2c 8bf4ce8b4bcbc50f642988c955559f605e7a877372116e7a2b3fd1355004bedb SteamMacBootstrapper.tar.gz Steam.app
+
+file legacycompat/Steam.dll linux legacycompat/Steam.dll b2000e57123e99bbbe26aaec40cfaf09a4df93959c5148f0db571ed2e3401102
+file legacycompat/SteamService.exe linux legacycompat/SteamService.exe a12c6c9ed617bf7c804227cb494666487c9d185daf61940af498980f6937387e
+file legacycompat/iscriptevaluator.exe linux legacycompat/iscriptevaluator.exe bafaae73e3763522917d34681b77120c29bef7dd3801c34e8cc8d5e92a78eeeb
+file legacycompat/steamclient.dll linux legacycompat/steamclient.dll e9e961c914a418b6a3c597822bdc920bdea62c842ff42de23dc306331da563f8
+file legacycompat/steamclient64.dll linux steamclient64.dll caba4826aa3501039d095aee1843a6bfb270fb43a3ab4455b2d6733223579fee
+file legacycompat/GameOverlayRenderer64.dll linux GameOverlayRenderer64.dll 59057f983ae6f02b7eb2495bf65e0430129dd81dff8d9628c764bd1a07e23fee
+file steamclient.dll linux legacycompat/steamclient.dll e9e961c914a418b6a3c597822bdc920bdea62c842ff42de23dc306331da563f8
+file steamclient64.dll linux steamclient64.dll caba4826aa3501039d095aee1843a6bfb270fb43a3ab4455b2d6733223579fee
+file tier0_s64.dll win64 tier0_s64.dll 30f7bb8d9b86006852493c26124ba253bd9e7ffd40a8b3c7254f86a9032c3be3
+file vstdlib_s64.dll win64 vstdlib_s64.dll 99efb4c2ad47f90c803b5ee0bd6424916b28facb9fa2568845b1b1f58a36062a
diff --git a/app/Sources/NotProtonApp/Support/AppLog.swift b/app/Sources/NotProtonApp/Support/AppLog.swift
new file mode 100644
index 0000000..5a71a9a
--- /dev/null
+++ b/app/Sources/NotProtonApp/Support/AppLog.swift
@@ -0,0 +1,113 @@
+// I Love Logs
+
+import Foundation
+
+enum AppLog {
+
+ static var file: URL { SupportPaths.support.appending(path: "app.log") }
+
+ private static let sizeLimit = 512 * 1024
+
+ private static let queue = DispatchQueue(label: "notproton.applog")
+
+ private nonisolated(unsafe) static var isOn = false
+
+ static func start() {
+ queue.async {
+ isOn = true
+ append("--- NotProton \(AppVersion.bundled) started ---\n")
+ }
+ }
+
+ static func note(_ message: String) {
+ let line = "\(Date().ISO8601Format()) \(message)\n"
+ queue.async { append(line) }
+ }
+
+ static func note(_ snapshot: StatusSnapshot) {
+ var lines = [
+ "state steam=\(describe(snapshot.steam))",
+ "state steamRunning=\(snapshot.steamRunning) updatesBlocked=\(snapshot.updateBlocked)",
+ "state runner=\(describe(snapshot.runner))",
+ ]
+
+ if snapshot.crossOver.isEmpty {
+ lines.append("state crossOver=none found")
+ }
+ for install in snapshot.crossOver {
+ lines.append(
+ "state crossOver \(install.name) version=\(install.releaseVersion ?? "unreadable") "
+ + "support=\(describe(install.support))"
+ + (install.isManual ? " chosen" : "")
+ + " at=\(install.bundle.path(percentEncoded: false))"
+ )
+ }
+
+ let payload = snapshot.payload
+ lines.append(
+ "state payload staged=\(payload.present)/\(payload.expected) "
+ + "overlayShim=\(payload.overlayShimPresent) "
+ + "iconmaker=\(payload.iconmakerPresent) "
+ + "appinfo=\(payload.appinfoPresent) "
+ + "signatures=\(payload.signatureDatabase ?? "none") "
+ + "legacycompat=\(payload.legacyCompatPresent)/\(payload.legacyCompatExpected)"
+ )
+ for entry in payload.missing {
+ lines.append("state payload missing \(entry.origin) \(entry.path)")
+ }
+ if let problem = payload.manifestProblem {
+ lines.append("state payload manifest problem: \(problem)")
+ }
+
+ for line in lines { note(line) }
+ }
+
+ private static func describe(_ steam: SteamDeployment) -> String {
+ switch steam {
+ case .steamMissing: "no Steam.app"
+ case .notInstalled: "not installed"
+ case .installed(let version): "installed \(version ?? "version unknown")"
+ case .outdated(let deployed, let bundled): "outdated deployed=\(deployed) bundled=\(bundled)"
+ case .foreign(let insert): "foreign insert \(insert)"
+ }
+ }
+
+ private static func describe(_ runner: RunnerState) -> String {
+ switch runner {
+ case .none: "not set up"
+ case .cloned(let build, let supported): "cloned \(build) supported=\(supported)"
+ case .bundleShaped(let build): "cloned \(build) in an .app"
+ case .unpatched(let build, let problems):
+ "cloned \(build) unpatched: \(problems.joined(separator: ", "))"
+ case .broken(let detail): "broken: \(detail)"
+ }
+ }
+
+ private static func describe(_ support: CrossOverSupport) -> String {
+ switch support {
+ case .supported(let build): "supported \(build.id)"
+ case .unsupportedBuild(let version): "unsupported build \(version)"
+ case .unreadable: "unreadable"
+ }
+ }
+
+ private static func append(_ line: String) {
+ guard isOn else { return }
+ let fm = FileManager.default
+ try? fm.createDirectory(at: SupportPaths.support, withIntermediateDirectories: true)
+
+ let path = file.path(percentEncoded: false)
+ if let size = (try? fm.attributesOfItem(atPath: path))?[.size] as? Int, size > sizeLimit {
+ try? fm.removeItem(at: file)
+ }
+
+ guard let data = line.data(using: .utf8) else { return }
+ guard let handle = try? FileHandle(forWritingTo: file) else {
+ try? data.write(to: file)
+ return
+ }
+ defer { try? handle.close() }
+ _ = try? handle.seekToEnd()
+ try? handle.write(contentsOf: data)
+ }
+}
diff --git a/app/Sources/NotProtonApp/Support/AppUpdater.swift b/app/Sources/NotProtonApp/Support/AppUpdater.swift
new file mode 100644
index 0000000..0f1e87e
--- /dev/null
+++ b/app/Sources/NotProtonApp/Support/AppUpdater.swift
@@ -0,0 +1,26 @@
+import Sparkle
+
+@MainActor
+final class AppUpdater {
+
+ private let controller: SPUStandardUpdaterController
+
+ init() {
+ #if DEBUG
+ let scheduling = false
+ #else
+ let scheduling = true
+ #endif
+ controller = SPUStandardUpdaterController(
+ startingUpdater: scheduling,
+ updaterDelegate: nil,
+ userDriverDelegate: nil
+ )
+ }
+
+ func check() {
+ #if !DEBUG
+ controller.checkForUpdates(nil)
+ #endif
+ }
+}
diff --git a/app/Sources/NotProtonApp/Support/AtomicReplace.swift b/app/Sources/NotProtonApp/Support/AtomicReplace.swift
new file mode 100644
index 0000000..fd53625
--- /dev/null
+++ b/app/Sources/NotProtonApp/Support/AtomicReplace.swift
@@ -0,0 +1,33 @@
+// Simple logic
+
+import Foundation
+
+func atomicReplace(_ destination: URL, with data: Data, step: String) throws {
+ let fm = FileManager.default
+ let directory = destination.deletingLastPathComponent()
+ try fm.createDirectory(at: directory, withIntermediateDirectories: true)
+
+ let staging = directory.appending(path: ".\(destination.lastPathComponent).new")
+ try? fm.removeItem(at: staging)
+
+ do {
+ try data.write(to: staging)
+ } catch {
+ throw StepFailure(
+ step: step,
+ detail: "\(staging.path(percentEncoded: false)) could not be written. "
+ + error.localizedDescription
+ )
+ }
+
+ if rename(
+ staging.path(percentEncoded: false), destination.path(percentEncoded: false)
+ ) != 0 {
+ let reason = String(cString: strerror(errno))
+ try? fm.removeItem(at: staging)
+ throw StepFailure(
+ step: step,
+ detail: "Replacing \(destination.path(percentEncoded: false)) failed. \(reason)"
+ )
+ }
+}
diff --git a/app/Sources/NotProtonApp/Support/Clean.swift b/app/Sources/NotProtonApp/Support/Clean.swift
new file mode 100644
index 0000000..5610f88
--- /dev/null
+++ b/app/Sources/NotProtonApp/Support/Clean.swift
@@ -0,0 +1,12 @@
+import Foundation
+
+enum Clean {
+
+ static let backupSuffix = "notproton-orig"
+
+ static func copy(of file: URL) -> URL {
+ let backup = file.appendingPathExtension(backupSuffix)
+ if FileManager.default.fileExists(atPath: backup.path(percentEncoded: false)) { return backup }
+ return file
+ }
+}
diff --git a/app/Sources/NotProtonApp/Support/Digest.swift b/app/Sources/NotProtonApp/Support/Digest.swift
new file mode 100644
index 0000000..0ee0f87
--- /dev/null
+++ b/app/Sources/NotProtonApp/Support/Digest.swift
@@ -0,0 +1,30 @@
+// Hasssssh
+
+import CryptoKit
+import Foundation
+
+enum Digest {
+
+ private static let chunkSize = 1 << 20
+
+ static func sha256(of url: URL) throws -> String {
+ let handle = try FileHandle(forReadingFrom: url)
+ defer { try? handle.close() }
+
+ var hasher = SHA256()
+ while let chunk = try handle.read(upToCount: chunkSize), !chunk.isEmpty {
+ hasher.update(data: chunk)
+ }
+ return hasher.finalize().map { String(format: "%02x", $0) }.joined()
+ }
+
+ // ntdll specific
+ static func sha256(of data: Data) -> String {
+ SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()
+ }
+
+ static func sha256IfPresent(_ url: URL) -> String? {
+ guard FileManager.default.fileExists(atPath: url.path(percentEncoded: false)) else { return nil }
+ return try? sha256(of: url)
+ }
+}
diff --git a/app/Sources/NotProtonApp/Support/MachOBuild.swift b/app/Sources/NotProtonApp/Support/MachOBuild.swift
new file mode 100644
index 0000000..b333e6c
--- /dev/null
+++ b/app/Sources/NotProtonApp/Support/MachOBuild.swift
@@ -0,0 +1,77 @@
+// Which build is this binary? Signing rewrites the bytes, LC_UUID survives it
+
+import Foundation
+
+enum MachOBuild {
+ private static let fat32: UInt32 = 0xcafe_babe
+ private static let fat64: UInt32 = 0xcafe_babf
+ private static let thin64: UInt32 = 0xfeed_facf
+ private static let thin32: UInt32 = 0xfeed_face
+ private static let swapped64: UInt32 = 0xcffa_edfe
+ private static let swapped32: UInt32 = 0xcefa_edfe
+ private static let uuidCommand: UInt32 = 0x1b
+
+ static func identity(of url: URL) -> [String]? {
+ guard let bytes = try? Data(contentsOf: url, options: .mappedIfSafe) else { return nil }
+ var found: Set<String> = []
+ collect(bytes, at: 0, into: &found)
+ return found.isEmpty ? nil : found.sorted()
+ }
+
+ private static func collect(_ bytes: Data, at offset: Int, into found: inout Set<String>) {
+ guard let magic = read(bytes, at: offset, bigEndian: false) else { return }
+ let fat = magic.byteSwapped
+
+ if fat == fat32 || fat == fat64 {
+ guard let count = read(bytes, at: offset + 4, bigEndian: true) else { return }
+ let wide = fat == fat64
+ for index in 0..<Int(count) {
+ let entry = offset + 8 + index * (wide ? 32 : 20)
+ guard let slice = read(bytes, at: entry + (wide ? 12 : 8), bigEndian: true) else {
+ return
+ }
+ readCommands(bytes, at: Int(slice), into: &found)
+ }
+ return
+ }
+
+ readCommands(bytes, at: offset, into: &found)
+ }
+
+ private static func readCommands(_ bytes: Data, at offset: Int, into found: inout Set<String>) {
+ guard let magic = read(bytes, at: offset, bigEndian: false) else { return }
+ guard [thin64, thin32, swapped64, swapped32].contains(magic) else { return }
+
+ let flipped = magic == swapped64 || magic == swapped32
+ let wide = magic == thin64 || magic == swapped64
+ guard let count = read(bytes, at: offset + 16, bigEndian: flipped) else { return }
+
+ var cursor = offset + (wide ? 32 : 28)
+ for _ in 0..<Int(count) {
+ guard let command = read(bytes, at: cursor, bigEndian: flipped),
+ let size = read(bytes, at: cursor + 4, bigEndian: flipped), size >= 8
+ else { return }
+
+ if command == uuidCommand, let value = readUUID(bytes, at: cursor + 8) {
+ found.insert(value)
+ }
+ cursor += Int(size)
+ }
+ }
+
+ private static func read(_ bytes: Data, at offset: Int, bigEndian: Bool) -> UInt32? {
+ guard offset >= 0, offset + 4 <= bytes.count else { return nil }
+ let value = bytes.withUnsafeBytes { raw in
+ raw.loadUnaligned(fromByteOffset: offset, as: UInt32.self)
+ }
+ return bigEndian ? value.bigEndian : value.littleEndian
+ }
+
+ private static func readUUID(_ bytes: Data, at offset: Int) -> String? {
+ guard offset >= 0, offset + 16 <= bytes.count else { return nil }
+ let raw = bytes.withUnsafeBytes { buffer in
+ buffer.loadUnaligned(fromByteOffset: offset, as: uuid_t.self)
+ }
+ return UUID(uuid: raw).uuidString
+ }
+}
diff --git a/app/Sources/NotProtonApp/Support/PinnedDownload.swift b/app/Sources/NotProtonApp/Support/PinnedDownload.swift
new file mode 100644
index 0000000..02bb019
--- /dev/null
+++ b/app/Sources/NotProtonApp/Support/PinnedDownload.swift
@@ -0,0 +1,87 @@
+// Download one hash pinned file from a list of CDN hosts
+
+import Foundation
+
+enum PinnedDownload {
+
+ enum Progress: Sendable {
+ case reusing
+ case fetching(host: String)
+
+ var label: String {
+ switch self {
+ case .reusing: "Preparing"
+ case .fetching(let host): "Downloading from \(host)"
+ }
+ }
+ }
+
+ static func obtain(
+ file: String,
+ sha256: String,
+ bases: [URL],
+ into downloads: URL,
+ step: String,
+ report: @Sendable (Progress) -> Void = { _ in }
+ ) async throws -> URL {
+ let archive = downloads.appending(path: file)
+ if Digest.sha256IfPresent(archive) == sha256 {
+ report(.reusing)
+ return archive
+ }
+
+ var refusals: [String] = []
+ var kinds: Set<Refusal> = []
+ for base in bases {
+ let host = base.host() ?? base.absoluteString
+ report(.fetching(host: host))
+ do {
+ let (body, response) = try await URLSession.shared.download(from: base.appending(path: file))
+ defer { try? FileManager.default.removeItem(at: body) }
+
+ if let http = response as? HTTPURLResponse, http.statusCode != 200 {
+ refusals.append("\(host) answered \(http.statusCode)")
+ kinds.insert(.answered)
+ continue
+ }
+
+ let got = try Digest.sha256(of: body)
+ guard got == sha256 else {
+ refusals.append("\(host) served \(got.prefix(16)) rather than \(sha256.prefix(16))")
+ kinds.insert(.mismatch)
+ continue
+ }
+
+ try FileManager.default.createDirectory(
+ at: downloads, withIntermediateDirectories: true
+ )
+ try? FileManager.default.removeItem(at: archive)
+ try FileManager.default.moveItem(at: body, to: archive)
+ return archive
+ } catch {
+ refusals.append("\(host): \(error.localizedDescription)")
+ kinds.insert(.unreachable)
+ }
+ }
+
+ AppLog.note("\(file) refused by all \(bases.count) hosts: \(refusals.joined(separator: ". "))")
+ throw StepFailure(step: step, detail: reason(kinds))
+ }
+
+ private enum Refusal {
+ case unreachable
+ case mismatch
+ case answered
+ }
+
+ private static func reason(_ kinds: Set<Refusal>) -> String {
+ if kinds == [.mismatch] {
+ return "Something is wrong with the downloaded files. Please check for a NotProton update."
+ }
+ if kinds == [.unreachable] {
+ return "NotProton could not reach Valve's servers. Please check your internet "
+ + "connection and try again."
+ }
+ return "NotProton could not download the files it needs from Valve. Please try again later."
+ }
+}
diff --git a/app/Sources/NotProtonApp/Support/Shell.swift b/app/Sources/NotProtonApp/Support/Shell.swift
new file mode 100644
index 0000000..fd30585
--- /dev/null
+++ b/app/Sources/NotProtonApp/Support/Shell.swift
@@ -0,0 +1,135 @@
+// Install function needs to shell out, this handles it
+
+import Foundation
+
+struct CommandResult: Sendable {
+ let status: Int32
+ let stdout: String
+ let stderr: String
+ let outputLost: Bool
+
+ init(status: Int32, stdout: String, stderr: String, outputLost: Bool = false) {
+ self.status = status
+ self.stdout = stdout
+ self.stderr = stderr
+ self.outputLost = outputLost
+ }
+
+ var succeeded: Bool { status == 0 }
+}
+
+struct CommandFailure: LocalizedError {
+ let command: String
+ let status: Int32
+ let stderr: String
+
+ var errorDescription: String? {
+ let detail = stderr.trimmingCharacters(in: .whitespacesAndNewlines)
+ if detail.isEmpty { return "\(command) failed with status \(status)." }
+ return "\(command) failed with status \(status): \(detail)"
+ }
+}
+
+private final class DataBox: @unchecked Sendable {
+ var data = Data()
+}
+
+enum Shell {
+
+ private static let outputDrainTimeout: DispatchTimeInterval = .seconds(10)
+
+ static func run(
+ _ executable: String,
+ _ arguments: [String],
+ environment: [String: String]? = nil,
+ currentDirectory: URL? = nil,
+ drainTimeout: DispatchTimeInterval = outputDrainTimeout
+ ) throws -> CommandResult {
+ let process = Process()
+ process.executableURL = URL(filePath: executable)
+ process.arguments = arguments
+ if let environment { process.environment = environment }
+ if let currentDirectory { process.currentDirectoryURL = currentDirectory }
+
+ let out = Pipe(), err = Pipe()
+ process.standardOutput = out
+ process.standardError = err
+
+ try process.run()
+
+ let outBox = DataBox(), errBox = DataBox()
+ let group = DispatchGroup()
+
+ for (pipe, box) in [(out, outBox), (err, errBox)] {
+ group.enter()
+ DispatchQueue.global(qos: .userInitiated).async {
+ box.data = pipe.fileHandleForReading.readDataToEndOfFile()
+ group.leave()
+ }
+ }
+
+ process.waitUntilExit()
+
+ if group.wait(timeout: .now() + drainTimeout) == .timedOut {
+ AppLog.note("\(executable) exited but left its output open")
+ return CommandResult(
+ status: process.terminationStatus, stdout: "", stderr: "", outputLost: true)
+ }
+
+ return CommandResult(
+ status: process.terminationStatus,
+ stdout: String(decoding: outBox.data, as: UTF8.self),
+ stderr: String(decoding: errBox.data, as: UTF8.self)
+ )
+ }
+
+ @discardableResult
+ static func check(
+ _ executable: String,
+ _ arguments: [String],
+ environment: [String: String]? = nil,
+ currentDirectory: URL? = nil,
+ drainTimeout: DispatchTimeInterval = outputDrainTimeout
+ ) throws -> String {
+ let result = try run(
+ executable, arguments, environment: environment, currentDirectory: currentDirectory,
+ drainTimeout: drainTimeout)
+ guard result.succeeded else {
+ let reason = result.stderr.isEmpty ? result.stdout : result.stderr
+ throw CommandFailure(
+ command: (executable as NSString).lastPathComponent,
+ status: result.status,
+ stderr: reason.isEmpty && result.outputLost
+ ? "Its output was still open when it exited, so none was captured."
+ : reason
+ )
+ }
+ return result.stdout
+ }
+
+ // For the wine tools
+ static func detach(
+ _ executable: String,
+ _ arguments: [String],
+ environment: [String: String],
+ currentDirectory: URL? = nil
+ ) throws {
+ let process = Process()
+ process.executableURL = URL(filePath: executable)
+ process.arguments = arguments
+ process.environment = environment
+ if let currentDirectory { process.currentDirectoryURL = currentDirectory }
+ process.standardOutput = FileHandle.nullDevice
+ process.standardError = FileHandle.nullDevice
+ try process.run()
+ }
+
+ static func processIsRunning(
+ named name: String, pgrep: String = "/usr/bin/pgrep",
+ drainTimeout: DispatchTimeInterval = outputDrainTimeout
+ ) -> Bool {
+ guard let result = try? run(pgrep, ["-x", name], drainTimeout: drainTimeout)
+ else { return false }
+ return result.succeeded
+ }
+}
diff --git a/app/Sources/NotProtonApp/Support/StepFailure.swift b/app/Sources/NotProtonApp/Support/StepFailure.swift
new file mode 100644
index 0000000..38b971c
--- /dev/null
+++ b/app/Sources/NotProtonApp/Support/StepFailure.swift
@@ -0,0 +1,8 @@
+import Foundation
+
+struct StepFailure: LocalizedError {
+ let step: String
+ let detail: String
+
+ var errorDescription: String? { "\(step): \(detail)" }
+}
diff --git a/app/Sources/NotProtonApp/Support/SupportPaths.swift b/app/Sources/NotProtonApp/Support/SupportPaths.swift
new file mode 100644
index 0000000..d6adbc4
--- /dev/null
+++ b/app/Sources/NotProtonApp/Support/SupportPaths.swift
@@ -0,0 +1,90 @@
+// Path construction for the NotProton support directory and Steam
+
+import Foundation
+
+enum SupportPaths {
+
+ static let supportDirName = "notproton"
+ static let dylibName = "notproton.dylib"
+
+ static var home: URL {
+ URL(filePath: NSHomeDirectory())
+ }
+
+ static var applicationSupport: URL {
+ home.appending(path: "Library/Application Support")
+ }
+
+ // ~/Library/Application Support/notproton
+ static var support: URL {
+ applicationSupport.appending(path: supportDirName)
+ }
+
+ static var bridge: URL { support.appending(path: "bridge") }
+ static var runners: URL { support.appending(path: "runners") }
+ static var backups: URL { support.appending(path: "backups") }
+ static var launchers: URL { support.appending(path: "launchers") }
+
+ static var signatures: URL {
+ support.appending(path: "signatures/macos.arm64")
+ }
+
+ static var overlayShim: URL { support.appending(path: "overlay-shim.dylib") }
+ static var iconmaker: URL { support.appending(path: "iconmaker") }
+ static var appinfo: URL { support.appending(path: "appinfo") }
+
+ static var packageDownloads: URL {
+ home.appending(path: "Library/Caches/\(supportDirName)/valve-packages")
+ }
+
+ static var deployedVersion: URL { support.appending(path: "dylib.version") }
+
+ static var currentRunner: URL { runners.appending(path: "current") }
+
+ static func runnerRoot(forBuild build: String, runners: URL = SupportPaths.runners) -> URL {
+ runners.appending(path: "crossover-\(build)")
+ }
+
+ static func crossOverRoot(inBundle bundle: URL) -> URL {
+ bundle.appending(path: "Contents/SharedSupport/CrossOver")
+ }
+
+ static func clonedRoot(forBuild build: String, runners: URL = SupportPaths.runners) -> URL {
+ runnerRoot(forBuild: build, runners: runners).appending(path: "CrossOver")
+ }
+
+ enum Steam {
+ static var app: URL { URL(filePath: "/Applications/Steam.app") }
+ static var infoPlist: URL { infoPlist(inBundle: app) }
+ static var executable: URL { app.appending(path: "Contents/MacOS/steam_osx") }
+ static var deployedDylib: URL { deployedDylib(inBundle: app) }
+
+ static func infoPlist(inBundle bundle: URL) -> URL {
+ bundle.appending(path: "Contents/Info.plist")
+ }
+
+ static func deployedDylib(inBundle bundle: URL) -> URL {
+ bundle.appending(path: "Contents/MacOS/\(dylibName)")
+ }
+
+ static var userData: URL {
+ SupportPaths.applicationSupport.appending(path: "Steam")
+ }
+
+ static var configFile: URL { userData.appending(path: "steam.cfg") }
+
+ static var innerApp: URL { userData.appending(path: "Steam.AppBundle/Steam") }
+ static var innerInfoPlist: URL { innerApp.appending(path: "Contents/Info.plist") }
+
+ static var innerClient: URL { innerApp.appending(path: "Contents/MacOS") }
+
+ static var innerConfigFile: URL { innerClient.appending(path: "steam.cfg") }
+ static var legacyCompat: URL { innerClient.appending(path: "legacycompat") }
+
+ static var compatTool: URL {
+ userData.appending(path: "compatibilitytools.d/notproton")
+ }
+
+ static var libraryFoldersVDF: URL { userData.appending(path: "steamapps/libraryfolders.vdf") }
+ }
+}
diff --git a/app/Sources/NotProtonApp/Support/TextWidth.swift b/app/Sources/NotProtonApp/Support/TextWidth.swift
new file mode 100644
index 0000000..880762e
--- /dev/null
+++ b/app/Sources/NotProtonApp/Support/TextWidth.swift
@@ -0,0 +1,16 @@
+import AppKit
+
+enum TextWidth {
+
+ static let cellPadding: CGFloat = 24
+
+ static func of(_ text: String, size: CGFloat = NSFont.systemFontSize) -> CGFloat {
+ let font = NSFont.systemFont(ofSize: size)
+ return (text as NSString).size(withAttributes: [.font: font]).width.rounded(.up)
+ }
+
+ static func widest(_ texts: [String], padding: CGFloat = cellPadding) -> CGFloat? {
+ guard let widest = texts.map({ of($0) }).max() else { return nil }
+ return widest + padding
+ }
+}
diff --git a/app/Sources/NotProtonApp/Support/WriteRefused.swift b/app/Sources/NotProtonApp/Support/WriteRefused.swift
new file mode 100644
index 0000000..dab6526
--- /dev/null
+++ b/app/Sources/NotProtonApp/Support/WriteRefused.swift
@@ -0,0 +1,118 @@
+// We couldn't write? Logic for that
+
+import AppKit
+import Foundation
+
+struct WriteRefused: LocalizedError {
+ let path: String
+
+ var errorDescription: String? { "Could not write files." }
+}
+
+extension WriteRefused {
+ static func catching<T>(_ path: String, _ body: () throws -> T) throws -> T {
+ do {
+ return try body()
+ } catch let error as NSError where error.code == NSFileWriteNoPermissionError {
+ throw WriteRefused(path: path)
+ }
+ }
+
+ static func catching<T>(_ url: URL, _ body: () throws -> T) throws -> T {
+ try catching(url.path(percentEncoded: false), body)
+ }
+
+ var remedy: Remedy { Remedy(forPath: path) }
+}
+
+// A write failure generally equals App Management permission error
+// or bad folder ownership
+enum Remedy: Hashable {
+ case appManagement
+ case otherAccount
+ case ownership
+
+ var advice: String {
+ switch self {
+ case .appManagement: "NotProton needs the App Management permission."
+ case .otherAccount:
+ "Steam was installed by another account on this Mac. Only that account can modify it. "
+ + "Log in to macOS with that account to reinstall NotProton."
+ case .ownership: "Check permissions, make sure your user owns the folder."
+ }
+ }
+
+ static let settingsButton = "Open System Settings"
+
+ private static let appManagementPane =
+ "x-apple.systempreferences:com.apple.settings.PrivacySecurity.extension?Privacy_AppBundles"
+
+ var settingsPane: URL? {
+ switch self {
+ case .appManagement: URL(string: Self.appManagementPane)
+ case .otherAccount, .ownership: nil
+ }
+ }
+
+ @MainActor
+ static func openSettings(_ pane: URL) {
+ AppLog.note("opening App Management settings")
+ NSWorkspace.shared.open(pane)
+ }
+
+ static func owner(of path: String) -> uid_t? {
+ let files = FileManager.default
+ let url = URL(filePath: path)
+ for candidate in [url, url.deletingLastPathComponent()] {
+ guard
+ let attributes = try? files.attributesOfItem(
+ atPath: candidate.path(percentEncoded: false)
+ ),
+ let owner = attributes[.ownerAccountID] as? NSNumber
+ else { continue }
+ return uid_t(owner.uint32Value)
+ }
+ return nil
+ }
+
+ init(forPath path: String) {
+ if let owner = Self.owner(of: path), owner != getuid() {
+ self = .otherAccount
+ return
+ }
+
+ let files = FileManager.default
+ var directory = URL(filePath: path)
+ while directory.pathComponents.count > 1 {
+ let plist = directory.appending(path: "Contents/Info.plist")
+ if files.fileExists(atPath: plist.path(percentEncoded: false)) {
+ self = .appManagement
+ return
+ }
+ directory = directory.deletingLastPathComponent()
+ }
+ self = .ownership
+ }
+}
+
+struct FailureReport {
+ let message: String
+ let remedy: Remedy?
+
+ var settingsPane: URL? { remedy?.settingsPane }
+
+ init?(_ errors: [Error]) {
+ guard !errors.isEmpty else { return nil }
+
+ var seen = Set<String>()
+ let reasons = errors.map(\.localizedDescription).filter { seen.insert($0).inserted }
+
+ let refusals = errors.compactMap { $0 as? WriteRefused }
+ let wanted = Set(refusals.map(\.remedy))
+ remedy = refusals.count == errors.count && wanted.count == 1 ? wanted.first : nil
+
+ var parts = reasons
+ if let advice = remedy?.advice { parts.append(advice) }
+ message = parts.joined(separator: " ")
+ }
+}
diff --git a/app/Sources/NotProtonApp/SystemStatus.swift b/app/Sources/NotProtonApp/SystemStatus.swift
new file mode 100644
index 0000000..1da4e43
--- /dev/null
+++ b/app/Sources/NotProtonApp/SystemStatus.swift
@@ -0,0 +1,343 @@
+// Logic behind Status view
+
+import AppKit
+import Foundation
+import Observation
+import UniformTypeIdentifiers
+
+enum AppVersion {
+ static let fallback = "0.1.0-dev"
+
+ static var bundled: String {
+ Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? fallback
+ }
+}
+
+struct StatusSnapshot: Sendable {
+ var steam: SteamDeployment
+ var steamRunning: Bool
+ var updateBlocked: Bool
+ var crossOver: [CrossOverInstall]
+ var crossOverLicense: CrossOverLicense.Status?
+ var runner: RunnerState
+ var payload: PayloadState
+
+ static func capture(bundledVersion: String) -> StatusSnapshot {
+ let installs = CrossOverSource.discover()
+ let license = installs.first(where: \.isUsable).map {
+ CrossOverLicense.check(crossOverRoot: $0.crossOverRoot)
+ }
+
+ let runner = RunnerStore.state()
+
+ return StatusSnapshot(
+ steam: SteamBundle.deployment(bundledVersion: bundledVersion),
+ steamRunning: SteamBundle.isRunning,
+ updateBlocked: UpdateBlock.isPresent(),
+ crossOver: installs,
+ crossOverLicense: license,
+ runner: runner,
+ payload: PayloadInspector.inspect(
+ build: runner.buildIdentifier.flatMap(SupportedRunners.build(id:))
+ )
+ )
+ }
+}
+
+@MainActor
+@Observable
+final class SystemStatus {
+
+ var snapshot: StatusSnapshot?
+ var isRefreshing = false
+ var activity: String?
+ var outcome: String?
+ private(set) var failure: String?
+ private(set) var failureRemedy: Remedy?
+
+ var isBusy: Bool { activity != nil }
+ var isIdle: Bool { !isBusy && !isRefreshing }
+
+ enum Confirmation: Identifiable, Hashable {
+ case replaceSteam
+ case blockUpdates
+ case installUnlicensed
+ case toolUnlicensed
+ case removeEverything
+
+ var id: Self { self }
+ }
+
+ var pendingConfirmation: Confirmation?
+ var generation = 0
+
+ func beginRun(_ label: String) -> Int {
+ activity = label
+ AppLog.note("run begin: \(label)")
+ return generation
+ }
+
+ func report(_ run: Int, _ label: String) {
+ guard run == generation else { return }
+ activity = label
+ AppLog.note("run step: \(label)")
+ }
+
+ func endRun() {
+ generation += 1
+ activity = nil
+ AppLog.note("run end\(failure == nil ? "" : " (failed)")")
+ }
+
+ private func record(_ error: Error) {
+ setFailure(error)
+ if let refusal = error as? WriteRefused {
+ AppLog.note("run failed: cannot write \(refusal.path)")
+ } else {
+ AppLog.note("run failed: \(error.localizedDescription)")
+ }
+ }
+
+ func setFailure(_ message: String) {
+ failure = message
+ failureRemedy = nil
+ }
+
+ func setFailure(_ error: Error) {
+ let report = FailureReport([error])
+ failure = report?.message
+ failureRemedy = report?.remedy
+ }
+
+ func clearFailure() {
+ failure = nil
+ failureRemedy = nil
+ }
+
+ var usableCrossOver: CrossOverInstall? {
+ snapshot?.crossOver.first(where: \.isUsable)
+ }
+
+ func checkLicense() async -> CrossOverLicense.Status? {
+ guard let install = usableCrossOver else { return nil }
+ let status = await Task.detached(priority: .userInitiated) {
+ CrossOverLicense.check(crossOverRoot: install.crossOverRoot)
+ }.value
+ snapshot?.crossOverLicense = status
+ return status
+ }
+
+ enum Request {
+ case install
+ case compatibilityTool
+ }
+
+ nonisolated static func activationQuestion(
+ _ request: Request, licensed: Bool?, runner: RunnerState
+ ) -> Confirmation? {
+ guard licensed == false else { return nil }
+ switch request {
+ case .install: return runner == RunnerState.none ? .installUnlicensed : nil
+ case .compatibilityTool: return .toolUnlicensed
+ }
+ }
+
+ func requestInstall() async {
+ if let question = Self.activationQuestion(
+ .install,
+ licensed: await checkLicense()?.licensed,
+ runner: snapshot?.runner ?? RunnerState.none
+ ) {
+ pendingConfirmation = question
+ } else {
+ await installIntoSteam()
+ }
+ }
+
+ func requestCompatibilityTool(replacingExisting: Bool = false) async {
+ if let question = Self.activationQuestion(
+ .compatibilityTool,
+ licensed: await checkLicense()?.licensed,
+ runner: snapshot?.runner ?? RunnerState.none
+ ) {
+ pendingConfirmation = question
+ } else {
+ await setUpRunner(replacingExisting: replacingExisting)
+ }
+ }
+
+ var chosenCrossOver: URL? { CrossOverSource.manualBundle }
+
+ // Lets the user pick a copy of CrossOver the search did not find/auto-select
+ func chooseCrossOver() async {
+ let panel = NSOpenPanel()
+ panel.canChooseFiles = true
+ panel.canChooseDirectories = false
+ panel.allowsMultipleSelection = false
+ panel.allowedContentTypes = [.application]
+ panel.prompt = "Choose"
+ panel.message = "Select a copy of CrossOver."
+ panel.directoryURL = URL(filePath: "/Applications", directoryHint: .isDirectory)
+
+ guard panel.runModal() == .OK, let picked = panel.url else { return }
+
+ clearFailure()
+ outcome = nil
+
+ guard CrossOverSource.looksLikeCrossOver(picked) else {
+ setFailure("\(picked.lastPathComponent) is not a valid copy of CrossOver.")
+ AppLog.note("crossOver choice refused: \(picked.path(percentEncoded: false))")
+ return
+ }
+
+ CrossOverSource.manualBundle = picked
+ AppLog.note("crossOver choice: \(picked.path(percentEncoded: false))")
+ await refresh()
+ }
+
+ func clearCrossOverChoice() async {
+ clearFailure()
+ outcome = nil
+ CrossOverSource.manualBundle = nil
+ AppLog.note("crossOver choice cleared")
+ await refresh()
+ }
+
+ private func runnerOutcome(_ result: RunnerSetup.Outcome) -> String {
+ result.stagedNothing ? "Compatibility tool is already set up." : "Compatibility tool ready."
+ }
+
+ func perform(
+ from first: String,
+ _ body: (_ progress: @escaping @Sendable (String) -> Void) async throws -> String?
+ ) async {
+ clearFailure()
+ outcome = nil
+ let run = beginRun(first)
+ defer { endRun() }
+
+ do {
+ outcome = try await body { label in
+ Task { @MainActor in self.report(run, label) }
+ }
+ } catch {
+ record(error)
+ }
+
+ await refresh()
+ }
+
+ private func setUpRunner(replacingExisting: Bool = false) async {
+ guard let install = usableCrossOver else {
+ setFailure("No supported copy of CrossOver found.")
+ AppLog.note("run refused: no supported CrossOver")
+ outcome = nil
+ return
+ }
+
+ await perform(from: RunnerSetup.Phase.cloning.label) { progress in
+ let result = try await Task.detached(priority: .userInitiated) {
+ try RunnerSetup.run(from: install, replacingExisting: replacingExisting) {
+ progress($0.label)
+ }
+ }.value
+
+ return runnerOutcome(result)
+ }
+ }
+
+ func fetchValveBinaries() async {
+ await perform(from: ValveFetcher.Phase.verifying.label) { progress in
+ let result = try await ValveFetcher.run { progress($0.label) }
+ return result.wroteNothing ? nil : "Downloaded missing components."
+ }
+ }
+
+ private static let restartHint = "Steam was stopped, so start it again."
+
+ private static let toolNotActivated =
+ "The compatibility tool was not set up because CrossOver is not activated."
+
+ func installIntoSteam() async {
+ await perform(from: InstallPhase.checkingPayload.label) { progress in
+ let result = try await Task.detached(priority: .userInitiated) {
+ try SteamInstaller.run(report: { progress($0.label) })
+ }.value
+
+ var parts = ["NotProton successfully installed."]
+ if result.stoppedClient { parts.append(Self.restartHint) }
+ let install = usableCrossOver
+ let state = await Task.detached(priority: .userInitiated) {
+ (runner: RunnerStore.state(),
+ payload: PayloadInspector.inspect(),
+ license: install.map { CrossOverLicense.check(crossOverRoot: $0.crossOverRoot) })
+ }.value
+
+ if let install, state.license?.licensed == true, state.runner == .none {
+ progress("Setting up compatibility tool")
+ // A tool that came up is the expected case and goes unsaid. Failure
+ // throws, and an unactivated CrossOver is reported below.
+ _ = try await Task.detached(priority: .userInitiated) {
+ try RunnerSetup.run(from: install) { progress($0.label) }
+ }.value
+ } else if install != nil, state.license?.licensed == false, state.runner == .none {
+ // Not a failure, NotProton was installed but without a compatibility tool
+ parts.append(Self.toolNotActivated)
+ }
+
+ // Fetch binaries from Valve
+ if state.payload.missing.contains(where: { $0.origin.isFetchable }) {
+ progress("Downloading missing components")
+ _ = try await ValveFetcher.run { progress($0.label) }
+ }
+
+ return parts.joined(separator: " ")
+ }
+ }
+
+ func setUpdateBlock(_ blocked: Bool) async {
+ await perform(from: blocked ? "Blocking Steam client updates"
+ : "Allowing Steam client updates") { _ in
+ if blocked {
+ try UpdateBlock.write()
+ return "Steam client updates are blocked."
+ }
+
+ try UpdateBlock.remove()
+ return "Steam client updates are allowed."
+ }
+ }
+
+ func repairSteam() async {
+ await perform(from: RepairPhase.checking.label) { progress in
+ let result = try await SteamRepair.run { progress($0.label) }
+
+ var parts = ["Steam restored to its original state."]
+ if result.stoppedClient { parts.append(Self.restartHint) }
+ return parts.joined(separator: " ")
+ }
+ }
+
+ func removeEverything() async {
+ await perform(from: UninstallPhase.stoppingClient.label) { progress in
+ let result = try await Uninstall.run { progress($0.label) }
+
+ return result.restoredValveSignature
+ ? "NotProton has been removed."
+ : "NotProton has been removed. Steam needs to be redownloaded. "
+ + "Please run Repair Steam again once you are online."
+ }
+ }
+
+ func refresh() async {
+ isRefreshing = true
+ defer { isRefreshing = false }
+
+ let version = AppVersion.bundled
+ let captured = await Task.detached(priority: .userInitiated) {
+ StatusSnapshot.capture(bundledVersion: version)
+ }.value
+ snapshot = captured
+ AppLog.note(captured)
+ }
+}
diff --git a/app/Sources/NotProtonApp/Views/BackupsView.swift b/app/Sources/NotProtonApp/Views/BackupsView.swift
new file mode 100644
index 0000000..0e1f8b1
--- /dev/null
+++ b/app/Sources/NotProtonApp/Views/BackupsView.swift
@@ -0,0 +1,210 @@
+import SwiftUI
+
+struct BackupsView: View {
+
+ @Environment(PrefixesModel.self) private var model
+ @State private var selection = Set<PrefixBackup.ID>()
+
+ var body: some View {
+ Group {
+ if !model.hasLoaded {
+ ProgressView("Looking for backups")
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ } else if model.backups.isEmpty {
+ ContentUnavailableView(
+ "No Backups",
+ systemImage: "externaldrive.badge.timemachine"
+ )
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ } else {
+ table
+ }
+ }
+ .navigationTitle("Prefix Backups")
+ .navigationSubtitle(summary)
+ .safeAreaInset(edge: .bottom) {
+ if let failed = model.report {
+ report(
+ StatusRow(
+ title: "Failed",
+ value: failed.message,
+ tone: .bad,
+ action: failed.settingsPane.map { pane in
+ StatusAction(label: Remedy.settingsButton) { Remedy.openSettings(pane) }
+ }
+ )
+ )
+ } else if let outcome = model.outcome {
+ report(StatusRow(title: "Done", value: outcome, tone: .ok))
+ }
+ }
+ .toolbar {
+ if #available(macOS 26.1, *) {
+ ToolbarItemGroup(placement: .primaryAction) { strip }
+ .visibilityPriority(.high)
+ } else {
+ ToolbarItemGroup(placement: .primaryAction) { strip }
+ }
+ }
+ .task { if model.prefixes.isEmpty { await model.load() } }
+ .onChange(of: model.backups) { _, kept in
+ selection = selection.filter { id in kept.contains { $0.id == id } }
+ }
+ .confirmationDialog(
+ PrefixPrompt.deleteBackupsTitle(clearing),
+ isPresented: asking,
+ titleVisibility: .visible
+ ) {
+ Button(PrefixPrompt.deleteBackupsButton(clearing), role: .destructive) {
+ let targets = clearing
+ model.pendingConfirmation = nil
+ Task { await model.deleteBackups(targets) }
+ }
+ Button("Cancel", role: .cancel) { model.pendingConfirmation = nil }
+ .keyboardShortcut(.defaultAction)
+ } message: {
+ Text(PrefixPrompt.deleteBackupsMessage(clearing))
+ }
+ }
+
+ private var summary: String {
+ guard !model.backups.isEmpty else { return "" }
+ let size = model.backupBytes.formatted(.byteCount(style: .file))
+ let count = model.backups.count == 1 ? "1 backup" : "\(model.backups.count) backups"
+ return "\(count), \(size)"
+ }
+
+ private var selected: [PrefixBackup] {
+ model.backups.filter { selection.contains($0.id) }
+ }
+
+ private var clearing: [PrefixBackup] {
+ if case .deleteBackups(let targets) = model.pendingConfirmation { return targets }
+ return []
+ }
+
+ private var asking: Binding<Bool> {
+ Binding(
+ get: { isAsking },
+ set: { shown in
+ if !shown, isAsking { model.pendingConfirmation = nil }
+ }
+ )
+ }
+
+ private var isAsking: Bool {
+ if case .deleteBackups = model.pendingConfirmation { return true }
+ return false
+ }
+
+ @ViewBuilder
+ private var strip: some View {
+ Button("Reveal in Finder", systemImage: "folder") {
+ if let backup = selected.first, selected.count == 1 { model.reveal(backup) }
+ }
+ .disabled(selected.count != 1)
+ .help("Show the selected backup in the Finder.")
+
+ Button("Delete", systemImage: "trash") {
+ ask(selected)
+ }
+ .disabled(selected.isEmpty || model.isLoading)
+ .help("Delete the selected backups.")
+
+ Button("Delete All", systemImage: "externaldrive.badge.minus") {
+ ask(model.backups)
+ }
+ .disabled(model.backups.isEmpty || model.isLoading)
+ .help("Delete every backup that rebuilds have kept.")
+
+ Button("Refresh", systemImage: "arrow.clockwise") {
+ Task { await model.load() }
+ }
+ .disabled(model.isLoading)
+ .help("List the backups again and update their sizes.")
+ }
+
+ private var gameWidth: CGFloat {
+ TextWidth.widest(model.backups.map(\.title)) ?? 240
+ }
+
+ private var libraryWidth: CGFloat {
+ TextWidth.widest(model.backups.map(\.prefix.library.displayName)) ?? 120
+ }
+
+ private var takenWidth: CGFloat {
+ TextWidth.widest(model.backups.map(taken)) ?? 150
+ }
+
+ private var table: some View {
+ Table(model.backups, selection: $selection) {
+ TableColumn("Game") { backup in
+ Text(backup.title).help(backup.title)
+ }
+ .width(min: 60, ideal: gameWidth)
+
+ TableColumn("App ID") { backup in
+ Text(backup.prefix.appID).monospacedDigit().foregroundStyle(.secondary)
+ }
+ .width(min: 50, ideal: 80)
+
+ TableColumn("Library") { backup in
+ Text(backup.prefix.library.displayName)
+ .foregroundStyle(.secondary)
+ .help(backup.prefix.library.displayName)
+ }
+ .width(min: 44, ideal: libraryWidth)
+
+ TableColumn("Size") { backup in
+ Text(backup.bytes.formatted(.byteCount(style: .file)))
+ .monospacedDigit()
+ .foregroundStyle(.secondary)
+ }
+ .width(min: 56, ideal: 90)
+
+ TableColumn("Backed up") { backup in
+ Text(taken(backup))
+ .foregroundStyle(.secondary)
+ .help(taken(backup))
+ }
+ .width(min: 70, ideal: takenWidth)
+ }
+ .contextMenu(forSelectionType: PrefixBackup.ID.self) { ids in
+ actions(for: ids)
+ }
+ .onDeleteCommand {
+ ask(selected)
+ }
+ }
+
+ @ViewBuilder
+ private func actions(for ids: Set<PrefixBackup.ID>) -> some View {
+ let targets = model.backups.filter { ids.contains($0.id) }
+ Group {
+ if targets.count == 1, let backup = targets.first {
+ Button("Reveal in Finder") { model.reveal(backup) }
+ Divider()
+ }
+ if !targets.isEmpty {
+ Button(PrefixPrompt.deleteBackupsButton(targets), role: .destructive) {
+ ask(targets)
+ }
+ }
+ }
+ .disabled(model.isLoading)
+ }
+
+ private func taken(_ backup: PrefixBackup) -> String {
+ guard let taken = backup.taken else { return "Unknown" }
+ return taken.formatted(date: .abbreviated, time: .shortened)
+ }
+
+ private func ask(_ targets: [PrefixBackup]) {
+ guard !targets.isEmpty, !model.isLoading else { return }
+ model.pendingConfirmation = .deleteBackups(targets)
+ }
+
+ private func report(_ row: StatusRow) -> some View {
+ row.padding(10).frame(maxWidth: .infinity, alignment: .leading).background(.bar)
+ }
+}
diff --git a/app/Sources/NotProtonApp/Views/PrefixesView.swift b/app/Sources/NotProtonApp/Views/PrefixesView.swift
new file mode 100644
index 0000000..4867eed
--- /dev/null
+++ b/app/Sources/NotProtonApp/Views/PrefixesView.swift
@@ -0,0 +1,320 @@
+// Prefix management UI inside NotProton, also see PrefixesModel
+
+import SwiftUI
+
+struct PrefixesView: View {
+
+ @Environment(PrefixesModel.self) private var model
+ @Environment(\.colorSchemeContrast) private var contrast
+
+ var body: some View {
+ Group {
+ if !model.hasLoaded {
+ ProgressView("Looking for prefixes")
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ } else if model.prefixes.isEmpty {
+ ContentUnavailableView(
+ "No Prefixes",
+ systemImage: "externaldrive",
+ description: Text(
+ "A prefix appears here once a Windows game has been launched through NotProton."
+ )
+ )
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ } else {
+ table
+ }
+ }
+ .navigationTitle("Prefixes")
+ .safeAreaInset(edge: .bottom) {
+ if let failed = model.report {
+ report(
+ StatusRow(
+ title: "Failed",
+ value: failed.message,
+ tone: .bad,
+ action: failed.settingsPane.map { pane in
+ StatusAction(label: Remedy.settingsButton) { Remedy.openSettings(pane) }
+ }
+ )
+ )
+ } else if let outcome = model.outcome {
+ report(
+ StatusRow(
+ title: "Done",
+ value: outcome,
+ tone: .ok
+ )
+ )
+ }
+ }
+ .toolbar {
+ if #available(macOS 26.1, *) {
+ ToolbarItemGroup(placement: .primaryAction) { strip }
+ .visibilityPriority(.high)
+ } else {
+ ToolbarItemGroup(placement: .primaryAction) { strip }
+ }
+ }
+ .task { if model.prefixes.isEmpty { await model.load() } }
+ .confirmationDialog(
+ PrefixPrompt.deleteTitle(deleting),
+ isPresented: asking(.delete),
+ titleVisibility: .visible
+ ) {
+ Button(PrefixPrompt.deleteButton(deleting), role: .destructive) {
+ let targets = deleting
+ model.pendingConfirmation = nil
+ Task { await model.delete(targets) }
+ }
+ Button("Cancel", role: .cancel) { model.pendingConfirmation = nil }
+ .keyboardShortcut(.defaultAction)
+ } message: {
+ Text(PrefixPrompt.deleteMessage(deleting))
+ }
+ .confirmationDialog(
+ PrefixPrompt.rebuildTitle(rebuilding),
+ isPresented: asking(.rebuild),
+ titleVisibility: .visible
+ ) {
+ Button(PrefixPrompt.rebuildWithBackupButton(rebuilding)) {
+ let targets = rebuilding
+ model.pendingConfirmation = nil
+ Task { await model.recreate(targets) }
+ }
+ .keyboardShortcut(.defaultAction)
+ Button(PrefixPrompt.rebuildWithoutBackupButton(rebuilding)) {
+ let targets = rebuilding
+ model.pendingConfirmation = nil
+ Task { await model.recreate(targets, keepBackup: false) }
+ }
+ Button("Cancel", role: .cancel) { model.pendingConfirmation = nil }
+ } message: {
+ Text(PrefixPrompt.rebuildMessage())
+ }
+ .confirmationDialog(
+ PrefixPrompt.backUpTitle(backingUp),
+ isPresented: asking(.backUp),
+ titleVisibility: .visible
+ ) {
+ Button(PrefixPrompt.backUpButton(backingUp)) {
+ let targets = backingUp
+ model.pendingConfirmation = nil
+ Task { await model.backUp(targets) }
+ }
+ .keyboardShortcut(.defaultAction)
+ Button("Cancel", role: .cancel) { model.pendingConfirmation = nil }
+ } message: {
+ Text(PrefixPrompt.backUpMessage(backingUp))
+ }
+ }
+
+ private enum Question {
+ case delete, rebuild, backUp
+ }
+
+ private var deleting: [WinePrefix] {
+ if case .delete(let targets) = model.pendingConfirmation { return targets }
+ return []
+ }
+
+ private var rebuilding: [WinePrefix] {
+ if case .rebuild(let targets) = model.pendingConfirmation { return targets }
+ return []
+ }
+
+ private var backingUp: [WinePrefix] {
+ if case .backUp(let targets) = model.pendingConfirmation { return targets }
+ return []
+ }
+
+ private func isAsking(_ question: Question) -> Bool {
+ switch (question, model.pendingConfirmation) {
+ case (.delete, .delete): true
+ case (.rebuild, .rebuild): true
+ case (.backUp, .backUp): true
+ default: false
+ }
+ }
+
+ private func asking(_ question: Question) -> Binding<Bool> {
+ Binding(
+ get: { isAsking(question) },
+ set: { shown in
+ if !shown, isAsking(question) { model.pendingConfirmation = nil }
+ }
+ )
+ }
+
+ @ViewBuilder
+ private var strip: some View {
+ Menu {
+ toolButtons(for: model.selectedPrefix)
+ } label: {
+ Label("Tools", systemImage: "wrench.and.screwdriver")
+ }
+ .disabled(model.selectedPrefix == nil || model.isBusy)
+ .help("Run a program or open a Wine tool in the selected prefix.")
+
+ Button("Reveal in Finder", systemImage: "folder") {
+ if let prefix = model.selectedPrefix { model.reveal(prefix) }
+ }
+ .disabled(model.selectedPrefix == nil)
+ .help("Show the selected prefix in the Finder.")
+
+ Button("Refresh", systemImage: "arrow.clockwise") {
+ Task { await model.load() }
+ }
+ .disabled(model.isLoading)
+ .help("List the prefixes again and update their sizes.")
+ }
+
+ private func lastUsed(_ prefix: WinePrefix) -> String {
+ prefix.lastUsed?.formatted(date: .abbreviated, time: .omitted) ?? "Never"
+ }
+
+ private var libraryWidth: CGFloat {
+ TextWidth.widest(model.prefixes.map(\.library.displayName)) ?? 120
+ }
+
+ private var lastUsedWidth: CGFloat {
+ TextWidth.widest(model.prefixes.map(lastUsed)) ?? 110
+ }
+
+ private var gameWidth: CGFloat {
+ let widths = model.prefixes.map { prefix -> CGFloat in
+ var width = TextWidth.of(prefix.title)
+ if model.isForeign(prefix) { width += 22 }
+ if prefix.name == nil {
+ width += TextWidth.of("No longer installed", size: NSFont.smallSystemFontSize) + 6
+ }
+ return width
+ }
+ guard let widest = widths.max() else { return 240 }
+ return widest + TextWidth.cellPadding
+ }
+
+ private var table: some View {
+ @Bindable var model = model
+ return Table(model.prefixes, selection: $model.selection) {
+ TableColumn("Game") { prefix in
+ HStack(spacing: 6) {
+ if model.isForeign(prefix) {
+ Button {
+ model.pendingConfirmation = .rebuild([prefix])
+ } label: {
+ Image(systemName: "exclamationmark.circle.fill")
+ .foregroundStyle(.tint)
+ }
+ .buttonStyle(.borderless)
+ .disabled(model.isBusy)
+ .help(
+ "Built by a different compatibility tool, so the game cannot start. "
+ + "Click to rebuild the prefix."
+ )
+ .accessibilityLabel("Needs rebuilding")
+ }
+ Text(prefix.title).help(prefix.title)
+ if prefix.name == nil {
+ Text("No longer installed")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+ if model.busy.contains(prefix.id) {
+ ProgressView().controlSize(.small)
+ }
+ }
+ }
+ .width(min: 60, ideal: gameWidth)
+
+ TableColumn("App ID") { prefix in
+ Text(prefix.appID).monospacedDigit().foregroundStyle(.secondary)
+ }
+ .width(min: 50, ideal: 80)
+
+ TableColumn("Library") { prefix in
+ Text(prefix.library.displayName)
+ .foregroundStyle(.secondary)
+ .help(prefix.library.displayName)
+ }
+ .width(min: 44, ideal: libraryWidth)
+
+ TableColumn("Size") { prefix in
+ if let usage = model.usage[prefix.id] {
+ Text(usage.bytes.formatted(.byteCount(style: .file)))
+ .monospacedDigit()
+ .foregroundStyle(.secondary)
+ } else {
+ Text("Calculating…")
+ .foregroundStyle(contrast == .increased ? .secondary : .tertiary)
+ }
+ }
+ .width(min: 56, ideal: 90)
+
+ TableColumn("Last used") { prefix in
+ Text(lastUsed(prefix))
+ .foregroundStyle(.secondary)
+ .help(lastUsed(prefix))
+ }
+ .width(min: 60, ideal: lastUsedWidth)
+
+
+ }
+ .contextMenu(forSelectionType: WinePrefix.ID.self) { ids in
+ actions(for: ids)
+ }
+ .onDeleteCommand {
+ let targets = model.selectedPrefixes
+ if !model.isBusy, !targets.isEmpty {
+ model.pendingConfirmation = .delete(targets)
+ }
+ }
+ }
+
+ @ViewBuilder
+ private func actions(for ids: Set<WinePrefix.ID>) -> some View {
+ let targets = model.prefixes.filter { ids.contains($0.id) }
+ Group {
+ if let prefix = single(ids) {
+ toolButtons(for: prefix)
+ Divider()
+ Button("Reveal in Finder") { model.reveal(prefix) }
+ }
+ if !targets.isEmpty {
+ Divider()
+ Button(PrefixPrompt.backUpButton(targets)) {
+ model.pendingConfirmation = .backUp(targets)
+ }
+ Button(PrefixPrompt.rebuildButton(targets)) {
+ model.pendingConfirmation = .rebuild(targets)
+ }
+ Button(PrefixPrompt.deleteButton(targets), role: .destructive) {
+ model.pendingConfirmation = .delete(targets)
+ }
+ }
+ }
+ .disabled(model.isBusy)
+ }
+
+ @ViewBuilder
+ private func toolButtons(for prefix: WinePrefix?) -> some View {
+ Button("Run Program…") {
+ if let prefix { model.chooseExecutable(for: prefix) }
+ }
+ Divider()
+ ForEach(WineTool.allCases, id: \.self) { tool in
+ Button(tool.label) {
+ if let prefix { model.open(tool, for: prefix) }
+ }
+ }
+ }
+
+ private func single(_ ids: Set<WinePrefix.ID>) -> WinePrefix? {
+ guard ids.count == 1, let id = ids.first else { return nil }
+ return model.prefixes.first { $0.id == id }
+ }
+
+ private func report(_ row: StatusRow) -> some View {
+ row.padding(10).frame(maxWidth: .infinity, alignment: .leading).background(.bar)
+ }
+}
diff --git a/app/Sources/NotProtonApp/Views/RootView.swift b/app/Sources/NotProtonApp/Views/RootView.swift
new file mode 100644
index 0000000..51ef6d1
--- /dev/null
+++ b/app/Sources/NotProtonApp/Views/RootView.swift
@@ -0,0 +1,49 @@
+import SwiftUI
+
+enum Pane: String, CaseIterable, Identifiable, Hashable {
+ case status
+ case prefixes
+ case backups
+
+ var id: String { rawValue }
+
+ var label: String {
+ switch self {
+ case .status: "Status"
+ case .prefixes: "Prefixes"
+ case .backups: "Prefix Backups"
+ }
+ }
+
+ var symbol: String {
+ switch self {
+ case .status: "checklist"
+ case .prefixes: "externaldrive"
+ case .backups: "externaldrive.badge.timemachine"
+ }
+ }
+}
+
+struct RootView: View {
+
+ @Binding var pane: Pane
+
+ var body: some View {
+ NavigationSplitView {
+ List(selection: $pane) {
+ ForEach(Pane.allCases) { item in
+ Label(item.label, systemImage: item.symbol)
+ .tag(item)
+ }
+ }
+ .listStyle(.sidebar)
+ .navigationSplitViewColumnWidth(min: 180, ideal: 200, max: 260)
+ } detail: {
+ switch pane {
+ case .status: StatusView()
+ case .prefixes: PrefixesView()
+ case .backups: BackupsView()
+ }
+ }
+ }
+}
diff --git a/app/Sources/NotProtonApp/Views/StatusView.swift b/app/Sources/NotProtonApp/Views/StatusView.swift
new file mode 100644
index 0000000..07c4137
--- /dev/null
+++ b/app/Sources/NotProtonApp/Views/StatusView.swift
@@ -0,0 +1,528 @@
+// 'Status' view, see SystemStatus for actual logic
+
+import SwiftUI
+
+enum StatusTone: Sendable {
+ case ok, info, warning, bad, neutral
+
+ var symbol: String {
+ switch self {
+ case .ok: "circle.fill"
+ case .info: "circle"
+ case .warning: "circle.fill"
+ case .bad: "circle.fill"
+ case .neutral: "circle"
+ }
+ }
+
+ var color: Color {
+ switch self {
+ case .ok: .green
+ case .info: .secondary
+ case .warning: .orange
+ case .bad: .red
+ case .neutral: .secondary
+ }
+ }
+}
+
+struct StatusAction {
+ let label: String
+ var isProminent = false
+ var role: ButtonRole?
+ var help: String?
+ var isEnabled = true
+ let perform: () -> Void
+}
+
+enum StatusMetrics {
+ static let symbolWidth: CGFloat = 10
+ static let symbolSpacing: CGFloat = 8
+ static var textInset: CGFloat { symbolWidth + symbolSpacing }
+}
+
+struct StatusRow: View {
+
+ @Environment(\.colorSchemeContrast) private var contrast
+
+ let title: String
+ var value: String?
+
+ var tone: StatusTone?
+ var detail: String?
+ var action: StatusAction?
+
+ var body: some View {
+ HStack(alignment: .center, spacing: 0) {
+ HStack(alignment: .firstTextBaseline, spacing: StatusMetrics.symbolSpacing) {
+ if let tone {
+ Image(systemName: tone.symbol)
+ .font(.system(size: 8))
+ .foregroundStyle(tone.color)
+ .frame(width: StatusMetrics.symbolWidth)
+ .accessibilityHidden(true)
+ } else {
+ Color.clear.frame(width: StatusMetrics.symbolWidth, height: 1)
+ }
+
+ VStack(alignment: .leading, spacing: 2) {
+ Text(title)
+ .font(.headline)
+ if let value {
+ Text(value)
+ .foregroundStyle(.secondary)
+ }
+ if let detail {
+ Text(detail)
+ .font(.callout)
+ .foregroundStyle(contrast == .increased ? .secondary : .tertiary)
+ .textSelection(.enabled)
+ }
+ }
+ }
+
+ if let action {
+ Spacer(minLength: 12)
+ button(action)
+ .disabled(!action.isEnabled)
+ .help(action.help ?? "")
+ .accessibilityLabel("\(action.label), \(title)")
+ }
+ }
+ .accessibilityElement(children: .combine)
+ .padding(.vertical, 2)
+ }
+
+ @ViewBuilder
+ private func button(_ action: StatusAction) -> some View {
+ if action.isProminent {
+ Button(action.label, role: action.role, action: action.perform)
+ .buttonStyle(.borderedProminent)
+ } else {
+ Button(action.label, role: action.role, action: action.perform)
+ .buttonStyle(.bordered)
+ }
+ }
+}
+
+struct StatusView: View {
+ @Environment(SystemStatus.self) private var status
+
+ private static let updateBlockPrompt =
+ "Steam client updates may break NotProton. If you don't want to wait for "
+ + "NotProton to be updated to be compatible with future Steam versions at the "
+ + "cost of not getting updates to the Steam client, you can stop the Steam "
+ + "client from updating itself."
+
+ var body: some View {
+ Group {
+ if let snapshot = status.snapshot {
+ statusForm(snapshot)
+ } else {
+ ProgressView("Checking")
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ }
+ }
+ .navigationTitle("Status")
+ .toolbar {
+ if #available(macOS 26.1, *) {
+ ToolbarItem(placement: .primaryAction) { refreshButton }
+ .visibilityPriority(.high)
+ } else {
+ ToolbarItem(placement: .primaryAction) { refreshButton }
+ }
+ }
+ .confirmationDialog(
+ "Block Steam client updates?",
+ isPresented: asking(.blockUpdates),
+ titleVisibility: .visible
+ ) {
+ Button("Block Updates", role: .destructive) {
+ Task { await status.setUpdateBlock(true) }
+ }
+ Button("Cancel", role: .cancel) {}
+ } message: {
+ Text(Self.updateBlockPrompt)
+ }
+ .confirmationDialog(
+ "Replace Steam with Valve's bundle?",
+ isPresented: asking(.replaceSteam),
+ titleVisibility: .visible
+ ) {
+ Button("Replace Steam", role: .destructive) {
+ Task { await status.repairSteam() }
+ }
+ Button("Cancel", role: .cancel) {}
+ } message: {
+ Text(
+ "This will restore Steam itself to its original state but does not remove "
+ + "the support components used by NotProton."
+ )
+ }
+ .confirmationDialog(
+ "Remove everything NotProton has created?",
+ isPresented: asking(.removeEverything),
+ titleVisibility: .visible
+ ) {
+ Button("Remove Everything", role: .destructive) {
+ Task { await status.removeEverything() }
+ }
+ Button("Cancel", role: .cancel) {}
+ } message: {
+ Text(
+ "Steam is restored to its unmodified state and NotProton is removed, including "
+ + "the compatibility tool that lives inside the Steam folder. Windows games "
+ + "and Steam Play prefixes are not removed."
+ )
+ }
+ .confirmationDialog(
+ CrossOverLicense.notActivatedTitle,
+ isPresented: asking(.installUnlicensed),
+ titleVisibility: .visible
+ ) {
+ Button("Continue Anyway") {
+ Task { await status.installIntoSteam() }
+ }
+ Button("Cancel", role: .cancel) {}
+ } message: {
+ Text(
+ CrossOverLicense.notActivatedAdvice
+ + " NotProton can be deployed, but the CrossOver compatibility tool "
+ + "cannot be installed without a valid license."
+ )
+ }
+ .task { if status.snapshot == nil { await status.refresh() } }
+ .confirmationDialog(
+ CrossOverLicense.notActivatedTitle,
+ isPresented: asking(.toolUnlicensed),
+ titleVisibility: .visible
+ ) {
+ Button("OK", role: .cancel) {}
+ } message: {
+ Text(CrossOverLicense.notActivatedAdvice)
+ }
+ }
+
+ private func asking(_ confirmation: SystemStatus.Confirmation) -> Binding<Bool> {
+ Binding(
+ get: { status.pendingConfirmation == confirmation },
+ set: { shown in
+ if !shown, status.pendingConfirmation == confirmation {
+ status.pendingConfirmation = nil
+ }
+ }
+ )
+ }
+
+ private func statusForm(_ snapshot: StatusSnapshot) -> some View {
+ Form {
+ if let failure = status.failure {
+ StatusRow(
+ title: "Failed",
+ value: failure,
+ tone: .bad,
+ action: status.failureRemedy?.settingsPane.map { pane in
+ StatusAction(label: Remedy.settingsButton) {
+ Remedy.openSettings(pane)
+ }
+ }
+ )
+ } else if let outcome = status.outcome {
+ StatusRow(title: "Done", value: outcome, tone: .ok)
+ }
+
+ if let activity = status.activity {
+ HStack(spacing: 10) {
+ ProgressView()
+ .controlSize(.small)
+ Text(activity)
+ .foregroundStyle(.secondary)
+ }
+ }
+
+ Section("Steam") {
+ steamRow(snapshot.steam, payload: snapshot.payload)
+ if snapshot.steamRunning {
+ StatusRow(
+ title: "Steam is running",
+ value: "Close Steam before continuing.",
+ tone: .info
+ )
+ }
+ updateBlockRow(snapshot.updateBlocked)
+ }
+
+ Section("Compatibility Tool") {
+ crossOverRow(snapshot)
+ runnerRow(snapshot.runner, payload: snapshot.payload)
+ }
+
+ componentsSection(snapshot.payload)
+
+ dangerSection
+ }
+ .formStyle(.grouped)
+ .frame(maxWidth: 680)
+ .frame(maxWidth: .infinity)
+ }
+
+ private var dangerSection: some View {
+ Section {
+ StatusRow(
+ title: "Repair Steam",
+ value: "Restore Steam to its original state.",
+ action: StatusAction(
+ label: "Repair",
+ role: .destructive,
+ isEnabled: status.isIdle
+ ) { status.pendingConfirmation = .replaceSteam }
+ )
+ StatusRow(
+ title: "Remove Everything",
+ value: "Remove NotProton and restore Steam to its original state.",
+ action: StatusAction(
+ label: "Remove",
+ role: .destructive,
+ isEnabled: status.isIdle
+ ) { status.pendingConfirmation = .removeEverything }
+ )
+ }
+ }
+
+ private var refreshButton: some View {
+ Button("Refresh", systemImage: "arrow.clockwise") {
+ Task { await status.refresh() }
+ }
+ .disabled(!status.isIdle)
+ }
+
+ private func installAction(prominent: Bool) -> StatusAction {
+ StatusAction(
+ label: "Install",
+ isProminent: prominent,
+ help: "Install NotProton into Steam.",
+ isEnabled: status.isIdle
+ ) {
+ Task { await status.requestInstall() }
+ }
+ }
+
+ private func steamRow(_ deployment: SteamDeployment, payload: PayloadState) -> some View {
+ switch deployment {
+ case .steamMissing:
+ StatusRow(title: "NotProton", value: "Steam not found.", tone: .bad)
+ case .notInstalled:
+ StatusRow(
+ title: "NotProton",
+ value: "Not installed.",
+ tone: .neutral,
+ action: installAction(prominent: true)
+ )
+ case .installed(let version):
+ if payload.isComplete {
+ StatusRow(
+ title: "NotProton",
+ value: "Installed" + (version.map { " (\($0))" } ?? ""),
+ tone: .ok
+ )
+ } else {
+ StatusRow(
+ title: "NotProton",
+ value: "Installed, but not for this account.",
+ tone: .warning,
+ detail: "Steam is set up for NotProton, but this account is missing its "
+ + "components. Install to add them.",
+ action: installAction(prominent: true)
+ )
+ }
+ case .outdated(_, let bundled):
+ StatusRow(
+ title: "NotProton",
+ value: "Update available (\(bundled)).",
+ tone: .warning,
+ action: installAction(prominent: true)
+ )
+ case .foreign:
+ StatusRow(
+ title: "NotProton",
+ value: "Another dylib is present.",
+ tone: .warning,
+ detail: "Repair your Steam install before installing NotProton."
+ )
+ }
+ }
+
+ private func updateBlockRow(_ blocked: Bool) -> some View {
+ Toggle(isOn: blockUpdates) {
+ VStack(alignment: .leading, spacing: 2) {
+ Text("Block Steam client updates")
+ .font(.headline)
+ Text(
+ blocked
+ ? "The Steam client will not update itself."
+ : "A Steam client update may break NotProton."
+ )
+ .foregroundStyle(.secondary)
+ }
+ .padding(.leading, StatusMetrics.textInset)
+ }
+ .disabled(!status.isIdle)
+ .help("Steam client updates may break NotProton.")
+ }
+
+ private var blockUpdates: Binding<Bool> {
+ Binding(
+ get: { status.snapshot?.updateBlocked ?? false },
+ set: { wanted in
+ if wanted {
+ status.pendingConfirmation = .blockUpdates
+ } else {
+ Task { await status.setUpdateBlock(false) }
+ }
+ }
+ )
+ }
+
+ @ViewBuilder
+ private func crossOverRow(_ snapshot: StatusSnapshot) -> some View {
+ if let install = snapshot.crossOver.first(where: \.isUsable) {
+ if case .supported(let build) = install.support {
+ StatusRow(
+ title: install.name,
+ value: "Build \(build.displayVersion)",
+ tone: snapshot.crossOverLicense?.licensed == true ? .ok : .warning,
+ detail: install.bundle.path(percentEncoded: false),
+ action: crossOverAction()
+ )
+ }
+ } else {
+ StatusRow(
+ title: "CrossOver",
+ value: "Not found. Supported: \(SupportedRunners.versionList).",
+ tone: .bad,
+ action: crossOverAction()
+ )
+ }
+ }
+
+ private func crossOverAction() -> StatusAction {
+ if status.chosenCrossOver != nil {
+ return StatusAction(
+ label: "Use Search",
+ help: "Use the default CrossOver.",
+ isEnabled: status.isIdle
+ ) { Task { await status.clearCrossOverChoice() } }
+ }
+ return StatusAction(
+ label: "Choose\u{2026}",
+ help: "Pick a CrossOver install.",
+ isEnabled: status.isIdle
+ ) { Task { await status.chooseCrossOver() } }
+ }
+
+ private func runnerAction(
+ label: String = "Set Up", replacingExisting: Bool = false
+ ) -> StatusAction {
+ StatusAction(
+ label: label,
+ isProminent: true,
+ help: "Set up the compatibility tool from CrossOver.",
+ isEnabled: status.isIdle && status.usableCrossOver != nil
+ ) {
+ Task { await status.requestCompatibilityTool(replacingExisting: replacingExisting) }
+ }
+ }
+
+ private func runnerRow(_ state: RunnerState, payload: PayloadState) -> some View {
+ let patchedMissing = !payload.missing(origin: .patched).isEmpty
+
+ switch state {
+ case .none:
+ return StatusRow(
+ title: "Compatibility Tool",
+ value: "Not set up.",
+ tone: .neutral,
+ action: runnerAction()
+ )
+ case .cloned(let build, let supported):
+ let satisfied = supported && !patchedMissing
+ return StatusRow(
+ title: "Compatibility Tool",
+ value: "Build \(SupportedRunners.displayVersion(forID: build))"
+ + (supported ? "" : " (unsupported)"),
+ tone: satisfied ? .ok : .warning,
+ action: satisfied
+ ? runnerAction(label: "Copy Again", replacingExisting: true)
+ : runnerAction()
+ )
+ case .unpatched(let build, _):
+ return StatusRow(
+ title: "Compatibility Tool",
+ value: "Build \(SupportedRunners.displayVersion(forID: build)), not patched.",
+ tone: .warning,
+ action: runnerAction()
+ )
+ case .bundleShaped(let build):
+ return StatusRow(
+ title: "Compatibility Tool",
+ value: "Build \(SupportedRunners.displayVersion(forID: build)), needs re-setup.",
+ tone: .warning,
+ action: runnerAction()
+ )
+ case .broken:
+ return StatusRow(
+ title: "Compatibility Tool",
+ value: "Unusable.",
+ tone: .bad,
+ action: runnerAction()
+ )
+ }
+ }
+
+ private func fetchAction() -> StatusAction {
+ StatusAction(
+ label: "Fetch Valve Binaries",
+ isProminent: true,
+ help: "Download missing Valve binaries.",
+ isEnabled: status.isIdle
+ ) { Task { await status.fetchValveBinaries() } }
+ }
+
+ @ViewBuilder
+ private func componentsSection(_ payload: PayloadState) -> some View {
+ if let problem = payload.manifestProblem {
+ Section("NotProton Components") {
+ StatusRow(title: "Components", value: "Component list unreadable.", tone: .bad, detail: problem)
+ }
+ } else if payload.isComplete {
+ Section("NotProton Components") {
+ StatusRow(title: "Components", value: "Ready.", tone: .ok)
+ }
+ } else if payload.isEmpty {
+ Section("NotProton Components") {
+ StatusRow(title: "Components", value: "Not yet deployed.", tone: .neutral)
+ }
+ } else {
+ Section("NotProton Components") {
+ if !payload.missing.isEmpty {
+ let names = payload.missing.map {
+ URL(filePath: $0.path).lastPathComponent
+ }.joined(separator: ", ")
+ StatusRow(
+ title: "Missing",
+ value: names,
+ tone: .bad,
+ action: payload.missing.contains(where: { $0.origin.isFetchable })
+ ? fetchAction() : nil
+ )
+ }
+ if !payload.overlayShimPresent {
+ StatusRow(title: "Overlay shim", value: "Missing.", tone: .bad)
+ }
+ if payload.signatureDatabase == nil {
+ StatusRow(title: "Signature database", value: "Missing.", tone: .bad)
+ }
+ }
+ }
+ }
+}
diff --git a/app/Tests/NotProtonAppTests/AppInfoToolTests.swift b/app/Tests/NotProtonAppTests/AppInfoToolTests.swift
new file mode 100644
index 0000000..3a6d356
--- /dev/null
+++ b/app/Tests/NotProtonAppTests/AppInfoToolTests.swift
@@ -0,0 +1,154 @@
+import Foundation
+import Testing
+
+@testable import NotProtonApp
+
+// The launcher builds a game's bundle name and icon from what this tool prints, so a parse
+// that reads the wrong key mislabels a bundle. Caches are synthetic: the installed one is v29.
+@Suite("appinfo tool")
+struct AppInfoToolTests {
+
+ private struct Cache {
+ var bytes: [UInt8] = []
+
+ mutating func u32(_ v: UInt32) {
+ for i in 0..<4 { bytes.append(UInt8((v >> (8 * UInt32(i))) & 0xff)) }
+ }
+
+ mutating func u64(_ v: UInt64) {
+ for i in 0..<8 { bytes.append(UInt8((v >> (8 * UInt64(i))) & 0xff)) }
+ }
+
+ mutating func cstring(_ s: String) {
+ bytes.append(contentsOf: Array(s.utf8))
+ bytes.append(0)
+ }
+ }
+
+ private static let fields = [
+ ("name", "Dark Messiah of Might & Magic"),
+ ("icon", "5a08cd17d14ccb07a14f316dfa222b18a20960fd"),
+ ("clienticon", "0d652160dff1ab3d1352aa83c9cf14a20146519e"),
+ ]
+
+ // Key data is identical in both formats apart from how a key is named, so the
+ // caller decides that and the section nesting stays shared.
+ private static func keyData(_ key: (String) -> [UInt8]) -> [UInt8] {
+ var kv = Cache()
+ kv.bytes.append(0x00)
+ kv.bytes.append(contentsOf: key("appinfo"))
+ kv.bytes.append(0x00)
+ kv.bytes.append(contentsOf: key("common"))
+ for (name, value) in fields {
+ kv.bytes.append(0x01)
+ kv.bytes.append(contentsOf: key(name))
+ kv.cstring(value)
+ }
+ // One terminator closes common, one closes appinfo, and one closes the root
+ // section the tool starts reading at. A real entry ends 08 08 08 for that reason.
+ kv.bytes.append(contentsOf: [0x08, 0x08, 0x08])
+ return kv.bytes
+ }
+
+ private static func entry(appID: UInt32, keyData: [UInt8]) -> [UInt8] {
+ var e = Cache()
+ e.u32(appID)
+ // The size counts everything after itself, and the 60 byte header in between
+ // is what the tool has to skip to reach the keys.
+ e.u32(UInt32(60 + keyData.count))
+ e.bytes.append(contentsOf: [UInt8](repeating: 0, count: 60))
+ e.bytes.append(contentsOf: keyData)
+ return e.bytes
+ }
+
+ private static func v29(appID: UInt32) -> Data {
+ let table = ["appinfo", "common"] + fields.map(\.0)
+ let index = { (key: String) -> [UInt8] in
+ var c = Cache()
+ c.u32(UInt32(table.firstIndex(of: key)!))
+ return c.bytes
+ }
+ let body = entry(appID: appID, keyData: keyData(index))
+
+ var file = Cache()
+ file.u32(0x0756_4429)
+ file.u32(1)
+ // Header, entry and the zero appid that ends the list all precede the table.
+ file.u64(UInt64(16 + body.count + 4))
+ file.bytes.append(contentsOf: body)
+ file.u32(0)
+ file.u32(UInt32(table.count))
+ for s in table { file.cstring(s) }
+ return Data(file.bytes)
+ }
+
+ private static func v28(appID: UInt32) -> Data {
+ let inline = { (key: String) -> [UInt8] in
+ var c = Cache()
+ c.cstring(key)
+ return c.bytes
+ }
+ var file = Cache()
+ file.u32(0x0756_4428)
+ file.u32(1)
+ file.bytes.append(contentsOf: entry(appID: appID, keyData: keyData(inline)))
+ file.u32(0)
+ return Data(file.bytes)
+ }
+
+ private func read(_ cache: Data, _ appID: String) throws -> CommandResult {
+ let tool = try InstallPayload.locate().appinfo
+ let path = URL.temporaryDirectory.appending(path: "np-appinfo-\(UUID().uuidString).vdf")
+ try cache.write(to: path)
+ defer { try? FileManager.default.removeItem(at: path) }
+ return try Shell.run(tool.path(percentEncoded: false), [path.path(percentEncoded: false), appID])
+ }
+
+ private func values(_ result: CommandResult) -> [String: String] {
+ var out: [String: String] = [:]
+ for line in result.stdout.split(separator: "\n") {
+ guard let split = line.firstIndex(of: "=") else { continue }
+ out[String(line[line.startIndex..<split])] = String(line[line.index(after: split)...])
+ }
+ return out
+ }
+
+ @Test("A v29 cache resolves the client icon, which is not the icon we used to guess")
+ func readsStringTableFormat() throws {
+ let result = try read(Self.v29(appID: 2100), "2100")
+ let fields = values(result)
+
+ #expect(result.status == 0)
+ #expect(fields["clienticon"] == "0d652160dff1ab3d1352aa83c9cf14a20146519e")
+ #expect(fields["icon"] == "5a08cd17d14ccb07a14f316dfa222b18a20960fd")
+ // A name carrying an ampersand is what broke the generated plist before, so it
+ // has to survive the parse intact for the caller to escape it.
+ #expect(fields["name"] == "Dark Messiah of Might & Magic")
+ }
+
+ @Test("A v28 cache with inline keys resolves the same values")
+ func readsInlineKeyFormat() throws {
+ let result = try read(Self.v28(appID: 42700), "42700")
+ let fields = values(result)
+
+ #expect(result.status == 0)
+ #expect(fields["clienticon"] == "0d652160dff1ab3d1352aa83c9cf14a20146519e")
+ #expect(fields["name"] == "Dark Messiah of Might & Magic")
+ }
+
+ @Test("An app the cache does not carry prints nothing and fails")
+ func refusesUnknownApp() throws {
+ let result = try read(Self.v29(appID: 2100), "10180")
+
+ #expect(result.status != 0)
+ #expect(result.stdout.isEmpty, "a caller reading key=value lines must get none")
+ }
+
+ @Test("A cache that is not a cache fails instead of printing garbage")
+ func refusesUnparsableFile() throws {
+ let result = try read(Data(repeating: 0xab, count: 4096), "2100")
+
+ #expect(result.status != 0)
+ #expect(result.stdout.isEmpty)
+ }
+}
diff --git a/app/Tests/NotProtonAppTests/BridgePayloadTests.swift b/app/Tests/NotProtonAppTests/BridgePayloadTests.swift
new file mode 100644
index 0000000..42735f4
--- /dev/null
+++ b/app/Tests/NotProtonAppTests/BridgePayloadTests.swift
@@ -0,0 +1,115 @@
+import Foundation
+import Testing
+
+@testable import NotProtonApp
+
+@Suite("Bridge payload")
+struct BridgePayloadTests {
+
+ private func scratch() throws -> URL {
+ let url = URL.temporaryDirectory.appending(path: "np-bridge-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
+ return url
+ }
+
+ private func fakeResources(in work: URL) throws -> URL {
+ let root = work.appending(path: "bridge")
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+
+ for entry in BridgePayload.entries {
+ let data = Data(repeating: UInt8(entry.resource.count % 256), count: entry.resource.count * 100)
+ try data.write(to: root.appending(path: entry.resource))
+ }
+ return root
+ }
+
+ @Test("Locate finds all four resources when present")
+ func locateFindsAll() throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+
+ let root = try fakeResources(in: work)
+ let located = try BridgePayload.locate(root: root)
+ #expect(located.sources.count == BridgePayload.entries.count)
+ }
+
+ @Test("Locate reports missing resources rather than silently staging nothing")
+ func locateReportsMissing() throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+
+ let root = work.appending(path: "empty-bridge")
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+
+ #expect(throws: StepFailure.self) { try BridgePayload.locate(root: root) }
+ }
+
+ @Test("Stage writes all six bridge paths from four resources")
+ func stageWritesAll() throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+
+ let root = try fakeResources(in: work)
+ let located = try BridgePayload.locate(root: root)
+ let bridge = work.appending(path: "staged")
+ let result = try BridgePayload.stage(located: located, bridge: bridge)
+
+ let allPaths = BridgePayload.entries.flatMap(\.bridgePaths)
+ #expect(result.staged.count == allPaths.count)
+ #expect(result.unchanged.isEmpty)
+
+ for path in allPaths {
+ #expect(
+ FileManager.default.fileExists(atPath: bridge.appending(path: path).path(percentEncoded: false)),
+ "\(path) was not staged"
+ )
+ }
+ }
+
+ @Test("Files at the correct size are left alone on a second run")
+ func skipsMatchingSize() throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+
+ let root = try fakeResources(in: work)
+ let located = try BridgePayload.locate(root: root)
+ let bridge = work.appending(path: "staged")
+
+ let first = try BridgePayload.stage(located: located, bridge: bridge)
+ let second = try BridgePayload.stage(located: located, bridge: bridge)
+
+ #expect(!first.staged.isEmpty)
+ #expect(second.staged.isEmpty, "files were re-staged despite matching size")
+ let allPaths = BridgePayload.entries.flatMap(\.bridgePaths)
+ #expect(second.unchanged.count == allPaths.count)
+ }
+
+ @Test("Flat and arch copies are byte-identical")
+ func duplicatesMatch() throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+
+ let root = try fakeResources(in: work)
+ let located = try BridgePayload.locate(root: root)
+ let bridge = work.appending(path: "staged")
+ _ = try BridgePayload.stage(located: located, bridge: bridge)
+
+ // The x86_64 lsteamclient.dll is staged to both lsteamclient.dll and
+ // x86_64-windows/lsteamclient.dll, from the same source. Verify identity.
+ for entry in BridgePayload.entries where entry.bridgePaths.count > 1 {
+ let first = try Data(contentsOf: bridge.appending(path: entry.bridgePaths[0]))
+ for duplicate in entry.bridgePaths.dropFirst() {
+ let other = try Data(contentsOf: bridge.appending(path: duplicate))
+ #expect(first == other, "\(entry.bridgePaths[0]) and \(duplicate) differ")
+ }
+ }
+ }
+
+ @Test("The entry manifest covers every built path in payload.manifest")
+ func coversPayloadManifest() throws {
+ let manifest = try PayloadManifest.bundled()
+ let builtPaths = Set(manifest.paths(origin: .built))
+ let bridgePaths = Set(BridgePayload.entries.flatMap(\.bridgePaths))
+ #expect(builtPaths == bridgePaths, "BridgePayload entries do not match payload.manifest built paths")
+ }
+}
diff --git a/app/Tests/NotProtonAppTests/CrossOverLicenseTests.swift b/app/Tests/NotProtonAppTests/CrossOverLicenseTests.swift
new file mode 100644
index 0000000..ae5e7f0
--- /dev/null
+++ b/app/Tests/NotProtonAppTests/CrossOverLicenseTests.swift
@@ -0,0 +1,262 @@
+import Foundation
+import Testing
+
+@testable import NotProtonApp
+
+// The check gates whether a runner may be cloned, so a wrong unlicensed verdict strands a user
+// who holds a good license. Fixtures carry their own keypair, so it reads the same either way.
+@Suite("CrossOver license")
+struct CrossOverLicenseTests {
+
+ // The tree hangs off a bundle so the layout check() is handed directly and the one
+ // requireValid derives from a bundle are the same tree.
+ private struct Fixture {
+ let dir: URL
+ let bundle: URL
+ let local: URL
+ let system: URL
+ let key: URL
+
+ var root: URL { SupportPaths.crossOverRoot(inBundle: bundle) }
+ var publishedKey: URL { root.appending(path: "share/crossover/data/tie.pub") }
+ var searchDirs: [URL] { [local, system] }
+
+ func remove() { try? FileManager.default.removeItem(at: dir) }
+ }
+
+ private static let base = "com.codeweavers.CrossOver"
+
+ private static let body = """
+ [crossmac]
+ customer=Test
+ expires=2999/01/01
+ [license]
+ id=test
+
+ """
+
+ private static func fixture(withKey: Bool = true) throws -> Fixture {
+ let fm = FileManager.default
+ let dir = URL.temporaryDirectory.appending(path: "np-license-\(UUID().uuidString)")
+ let fix = Fixture(
+ dir: dir,
+ bundle: dir.appending(path: "CrossOver.app"),
+ local: dir.appending(path: "local"),
+ system: dir.appending(path: "system"),
+ key: dir.appending(path: "private.pem")
+ )
+
+ // The caller registers teardown on what it is handed, so a fixture that throws
+ // half built has to take its own tree with it.
+ do {
+ for made in [
+ fix.publishedKey.deletingLastPathComponent(), fix.local, fix.system,
+ ] {
+ try fm.createDirectory(at: made, withIntermediateDirectories: true)
+ }
+ try generate(key: fix.key, publishing: withKey ? fix.publishedKey : nil)
+ } catch {
+ fix.remove()
+ throw error
+ }
+ return fix
+ }
+
+ // check, not run: openssl failing here leaves the fixture without the file the test
+ // is about, and a test that then passes proves nothing.
+ private static func generate(key: URL, publishing pub: URL?) throws {
+ try Shell.check(
+ CrossOverLicense.defaultOpenssl,
+ ["genrsa", "-out", key.path(percentEncoded: false), "2048"]
+ )
+ guard let pub else { return }
+ try Shell.check(CrossOverLicense.defaultOpenssl, [
+ "rsa", "-in", key.path(percentEncoded: false),
+ "-pubout", "-out", pub.path(percentEncoded: false),
+ ])
+ }
+
+ @discardableResult
+ private static func writeLicense(in dir: URL) throws -> URL {
+ let license = dir.appending(path: "\(base).license")
+ try body.write(to: license, atomically: true, encoding: .utf8)
+ return license
+ }
+
+ private static func sign(
+ _ license: URL, with key: URL, digest: String, sidecar: String
+ ) throws {
+ try Shell.check(CrossOverLicense.defaultOpenssl, [
+ "dgst", digest, "-sign", key.path(percentEncoded: false),
+ "-out", license.deletingLastPathComponent()
+ .appending(path: "\(base).\(sidecar)").path(percentEncoded: false),
+ license.path(percentEncoded: false),
+ ])
+ }
+
+ @Test("A license signed by the bundle's key is accepted")
+ func validLicenseIsAccepted() throws {
+ let fix = try Self.fixture()
+ defer { fix.remove() }
+ let license = try Self.writeLicense(in: fix.local)
+ try Self.sign(license, with: fix.key, digest: "-sha256", sidecar: "sha256")
+
+ let status = CrossOverLicense.check(crossOverRoot: fix.root, searchDirs: fix.searchDirs)
+ #expect(status.licensed)
+ }
+
+ @Test("A bundle carrying no verification key is named in the diagnostic")
+ func missingKeyIsNamed() throws {
+ let fix = try Self.fixture(withKey: false)
+ defer { fix.remove() }
+ let license = try Self.writeLicense(in: fix.local)
+ try Self.sign(license, with: fix.key, digest: "-sha256", sidecar: "sha256")
+
+ let status = CrossOverLicense.check(crossOverRoot: fix.root, searchDirs: fix.searchDirs)
+ #expect(!status.licensed)
+ #expect(status.diagnostic == "no verification key in the CrossOver bundle")
+ #expect(status.detail == CrossOverLicense.notActivated)
+ }
+
+ // Both read the same to the user, so the log is the only thing left that can tell an
+ // install that never had a license from one whose license was refused.
+ @Test("No license file reads apart from a license that fails")
+ func absentLicenseReadsApartFromInvalid() throws {
+ let fix = try Self.fixture()
+ defer { fix.remove() }
+
+ let absent = CrossOverLicense.check(crossOverRoot: fix.root, searchDirs: fix.searchDirs)
+ #expect(!absent.licensed)
+ #expect(absent.diagnostic == "no CrossOver license file found")
+ #expect(absent.detail == CrossOverLicense.notActivated)
+
+ let license = try Self.writeLicense(in: fix.local)
+ let other = fix.local.appending(path: "other.pem")
+ try Self.generate(key: other, publishing: nil)
+ try Self.sign(license, with: other, digest: "-sha256", sidecar: "sha256")
+
+ let wrong = CrossOverLicense.check(crossOverRoot: fix.root, searchDirs: fix.searchDirs)
+ #expect(!wrong.licensed)
+ #expect(wrong.diagnostic.contains("verified against this bundle"))
+ #expect(wrong.diagnostic != absent.diagnostic)
+ #expect(wrong.detail == CrossOverLicense.notActivated)
+ }
+
+ @Test("A license with no signature beside it is named as such")
+ func unsignedLicenseIsNamed() throws {
+ let fix = try Self.fixture()
+ defer { fix.remove() }
+ try Self.writeLicense(in: fix.local)
+
+ let status = CrossOverLicense.check(crossOverRoot: fix.root, searchDirs: fix.searchDirs)
+ #expect(!status.licensed)
+ #expect(status.diagnostic.contains("has no signature beside it"))
+ #expect(status.detail == CrossOverLicense.notActivated)
+ }
+
+ // The sidecar that verifies is not always the first one present, and taking only
+ // the first turned a good license into an invalid one.
+ @Test("A stale .sha256 does not condemn a license the .sig verifies")
+ func staleSidecarDoesNotCondemnTheLicense() throws {
+ let fix = try Self.fixture()
+ defer { fix.remove() }
+ let license = try Self.writeLicense(in: fix.local)
+ try Self.sign(license, with: fix.key, digest: "-sha1", sidecar: "sig")
+ try Data(repeating: 0x41, count: 256).write(
+ to: fix.local.appending(path: "\(Self.base).sha256")
+ )
+
+ let status = CrossOverLicense.check(crossOverRoot: fix.root, searchDirs: fix.searchDirs)
+ #expect(status.licensed)
+ }
+
+ @Test("A license kept only in the system directory is found")
+ func systemDirectoryIsSearched() throws {
+ let fix = try Self.fixture()
+ defer { fix.remove() }
+ let license = try Self.writeLicense(in: fix.system)
+ try Self.sign(license, with: fix.key, digest: "-sha256", sidecar: "sha256")
+
+ let status = CrossOverLicense.check(crossOverRoot: fix.root, searchDirs: fix.searchDirs)
+ #expect(status.licensed)
+ #expect(status.diagnostic.contains(fix.system.path(percentEncoded: false)))
+ }
+
+ // Without the tool there is no verdict, and the user is told the same thing either way, so
+ // the log is the only place a missing openssl reads apart from a CrossOver never activated.
+ @Test("A missing openssl reads apart from an unactivated CrossOver in the log")
+ func missingToolIsNotReportedAsUnlicensed() throws {
+ let fix = try Self.fixture()
+ defer { fix.remove() }
+ let license = try Self.writeLicense(in: fix.local)
+ try Self.sign(license, with: fix.key, digest: "-sha256", sidecar: "sha256")
+
+ let status = CrossOverLicense.check(
+ crossOverRoot: fix.root,
+ searchDirs: fix.searchDirs,
+ openssl: "/usr/bin/notproton-no-such-openssl"
+ )
+ #expect(!status.licensed)
+ #expect(status.diagnostic.contains("could not run"))
+ #expect(status.diagnostic.contains("notproton-no-such-openssl"))
+ #expect(status.detail == CrossOverLicense.notActivated)
+ }
+
+ // The reason reaches the user only through the thrown failure. requireValid searches the
+ // machine's own directories, so only the two agreeing is fixed, not the text itself.
+ @Test("The refusal carries the reason the check found and nothing else")
+ func refusalCarriesTheReason() throws {
+ let fix = try Self.fixture()
+ defer { fix.remove() }
+ let install = CrossOverInstall(
+ bundle: fix.bundle, releaseVersion: nil, support: .unreadable
+ )
+
+ // A key generated for this fixture verifies no license on this machine, and a
+ // machine with no license has nothing to find either.
+ let expected = CrossOverLicense.check(crossOverRoot: install.crossOverRoot)
+ #expect(!expected.licensed)
+
+ do {
+ try CrossOverLicense.requireValid(for: install)
+ Issue.record("requireValid accepted a bundle whose key verifies nothing")
+ } catch let failure as StepFailure {
+ #expect(failure.detail == expected.detail)
+ }
+ }
+
+ // An unreadable key exits the same status as a signature that does not match, which
+ // leaves the log as the only place the two are told apart.
+ @Test("An unreadable verification key reads apart from a license that fails in the log")
+ func unreadableKeyReadsApartFromInvalid() throws {
+ let fix = try Self.fixture()
+ defer { fix.remove() }
+ let license = try Self.writeLicense(in: fix.local)
+ try Self.sign(license, with: fix.key, digest: "-sha256", sidecar: "sha256")
+ try Data("not a key".utf8).write(to: fix.publishedKey)
+
+ let status = CrossOverLicense.check(crossOverRoot: fix.root, searchDirs: fix.searchDirs)
+ #expect(!status.licensed)
+ #expect(status.diagnostic == "the verification key in the CrossOver bundle could not be read")
+ #expect(status.detail == CrossOverLicense.notActivated)
+ }
+
+ // Same exit status again, and the license here is the one thing known to be good.
+ @Test("A signature openssl cannot read is not called an invalid license")
+ func unreadableSidecarIsNotCalledInvalid() throws {
+ let fix = try Self.fixture()
+ defer { fix.remove() }
+ let license = try Self.writeLicense(in: fix.local)
+ try Self.sign(license, with: fix.key, digest: "-sha256", sidecar: "sha256")
+ try FileManager.default.setAttributes(
+ [.posixPermissions: 0],
+ ofItemAtPath: fix.local.appending(path: "\(Self.base).sha256")
+ .path(percentEncoded: false)
+ )
+
+ let status = CrossOverLicense.check(crossOverRoot: fix.root, searchDirs: fix.searchDirs)
+ #expect(!status.licensed)
+ #expect(status.diagnostic.contains("could not be checked"))
+ #expect(status.detail == CrossOverLicense.notActivated)
+ }
+}
diff --git a/app/Tests/NotProtonAppTests/CrossOverSourceTests.swift b/app/Tests/NotProtonAppTests/CrossOverSourceTests.swift
new file mode 100644
index 0000000..e576005
--- /dev/null
+++ b/app/Tests/NotProtonAppTests/CrossOverSourceTests.swift
@@ -0,0 +1,123 @@
+import Foundation
+import Testing
+
+@testable import NotProtonApp
+
+@Suite("Choosing between installed CrossOvers")
+struct CrossOverSourceTests {
+
+ private func install(
+ _ name: String, _ support: CrossOverSupport,
+ root: String = "/Applications", isManual: Bool = false
+ ) -> CrossOverInstall {
+ CrossOverInstall(
+ bundle: URL(filePath: "\(root)/\(name).app"),
+ releaseVersion: "20260821",
+ support: support,
+ isManual: isManual
+ )
+ }
+
+ private func sorted(_ installs: [CrossOverInstall]) -> [CrossOverInstall] {
+ installs.sorted(by: CrossOverSource.preferred)
+ }
+
+ private func picked(_ installs: [CrossOverInstall]) -> CrossOverInstall? {
+ sorted(installs).first(where: \.isUsable)
+ }
+
+ @Test("A usable Preview is chosen ahead of a usable stable CrossOver")
+ func prefersUsablePreview() {
+ let build = SupportedRunners.build(id: "27.0.0.40921")!
+ let stable = install("CrossOver", .supported(build))
+ let preview = install("CrossOver Preview", .supported(build))
+
+ // Order the input the way discovery would have on the machine that hit this:
+ // stable first because "CrossOver" sorts before "CrossOver Preview".
+ #expect(picked([stable, preview])?.name == "CrossOver Preview")
+ #expect(picked([preview, stable])?.name == "CrossOver Preview")
+ }
+
+ @Test("An incompatible stable is not chosen over a usable Preview")
+ func skipsIncompatibleStable() {
+ let build = SupportedRunners.build(id: "27.0.0.40921")!
+ let stable = install("CrossOver", .unsupportedBuild("30.0.0.0"))
+ let preview = install("CrossOver Preview", .supported(build))
+
+ // The stable install here is not clonable, so selection has to land on Preview
+ // even though stable sorts first by name.
+ #expect(picked([stable, preview])?.name == "CrossOver Preview")
+ }
+
+ @Test("An unreadable Preview does not shadow a usable stable")
+ func fallsBackToUsableStable() {
+ let build = SupportedRunners.build(id: "27.0.0.40921")!
+ // Preview is present but nothing in it can be read, so it is not usable.
+ let preview = install("CrossOver Preview", .unreadable)
+ let stable = install("CrossOver", .supported(build))
+
+ // Preference is only among usable installs, so an unusable Preview must not win
+ // over the one install that can actually be cloned.
+ #expect(picked([preview, stable])?.name == "CrossOver")
+ }
+
+ @Test("With no usable install, nothing is chosen")
+ func nonePickedWhenAllUnusable() {
+ let stable = install("CrossOver", .unsupportedBuild("30.0.0.0"))
+ let preview = install("CrossOver Preview", .unreadable)
+ #expect(picked([stable, preview]) == nil)
+ }
+
+ @Test("The same build in both Applications folders resolves to the same one every sort")
+ func breaksNameTieByPath() {
+ let build = SupportedRunners.build(id: "27.0.0.40921")!
+ let system = install("CrossOver Preview", .supported(build))
+ let home = install("CrossOver Preview", .supported(build), root: "/Users/someone/Applications")
+
+ // Every key but the path matches here, and sorted(by:) is unstable, so before the
+ // path tie-break the clone source could differ between two runs on one machine.
+ let system_path = "/Applications/CrossOver Preview.app"
+ #expect(picked([system, home])?.bundle.path(percentEncoded: false) == system_path)
+ #expect(picked([home, system])?.bundle.path(percentEncoded: false) == system_path)
+ }
+
+ @Test("A bundle whose loader is not a known build is refused, not called modified")
+ func unknownLoaderIsUnsupported() throws {
+ let fm = FileManager.default
+ let dir = URL(filePath: NSTemporaryDirectory()).appending(path: "notproton-cx-\(UUID().uuidString)")
+ let bundle = dir.appending(path: "CrossOver Preview.app")
+ let loader = bundle.appending(path: "Contents/SharedSupport/CrossOver/lib/wine/x86_64-unix/wine")
+ try fm.createDirectory(at: loader.deletingLastPathComponent(), withIntermediateDirectories: true)
+ defer { try? fm.removeItem(at: dir) }
+
+ let build = SupportedRunners.all[0]
+ let version = build.releaseVersion
+ let plist = try PropertyListSerialization.data(
+ fromPropertyList: [
+ "CFBundleVersion": build.bundleVersion,
+ "CFBundleShortVersionString": version,
+ ],
+ format: .xml, options: 0
+ )
+ try plist.write(to: bundle.appending(path: "Contents/Info.plist"))
+
+ #expect(CrossOverSource.inspect(bundle: bundle).support == .unreadable)
+
+ // A supported version carrying another flavor's bytes. Calling this modified told
+ // the user an untouched CodeWeavers download had been tampered with.
+ try Data("not the shipped loader".utf8).write(to: loader)
+ #expect(CrossOverSource.inspect(bundle: bundle).support == .unsupportedBuild(version))
+ }
+
+ @Test("A bundle the user named is taken over one the search found")
+ func prefersNamedBundle() {
+ let build = SupportedRunners.build(id: "27.0.0.40921")!
+ let found = install("CrossOver Preview", .supported(build))
+ let named = install("CrossOver", .supported(build), root: "/Volumes/Spare", isManual: true)
+
+ // Preview otherwise outranks stable, so this also covers the choice beating the
+ // heuristic it exists to overrule.
+ #expect(picked([found, named])?.isManual == true)
+ #expect(picked([named, found])?.isManual == true)
+ }
+}
diff --git a/app/Tests/NotProtonAppTests/DetectionTests.swift b/app/Tests/NotProtonAppTests/DetectionTests.swift
new file mode 100644
index 0000000..3ba8517
--- /dev/null
+++ b/app/Tests/NotProtonAppTests/DetectionTests.swift
@@ -0,0 +1,163 @@
+import Foundation
+import Testing
+
+@testable import NotProtonApp
+
+@Suite("Runner allow list")
+struct SupportedRunnerTests {
+
+ // The arches a build carries need both hashes: an input with no output leaves the patch
+ // unverified, and an output with no input patches a file nothing had checked.
+ @Test("Every row's pin hashes are complete for the arches it claims")
+ func rowsAreComplete() {
+ #expect(!SupportedRunners.all.isEmpty)
+
+ for build in SupportedRunners.all {
+ expectSHA256(build.loaderSHA256, "loader for \(build.id)")
+ #expect(!build.cleanNtdll.isEmpty, "\(build.id) patches nothing")
+ #expect(Set(build.cleanNtdll.keys) == Set(build.patchedNtdll.keys), "\(build.id) is lopsided")
+
+ for (arch, clean) in build.cleanNtdll {
+ let patched = build.patchedNtdll[arch]
+ expectSHA256(clean, "clean \(arch.rawValue)")
+ expectSHA256(patched ?? "", "patched \(arch.rawValue)")
+
+ // A patch that produced its own input would mean the patcher did
+ // nothing, and the launch path would silently run stock ntdll.
+ #expect(clean != patched)
+ }
+ }
+ }
+
+ @Test("Identities are unique so lookup is unambiguous")
+ func identitiesAreUnique() {
+ // Versions are deliberately not unique here: CodeWeavers ships flavors sharing one,
+ // which is why neither the lookup key nor the clone directory is the version.
+ let ids = SupportedRunners.all.map(\.id)
+ #expect(Set(ids).count == ids.count)
+
+ let loaders = SupportedRunners.all.map(\.loaderSHA256)
+ #expect(Set(loaders).count == loaders.count)
+ }
+
+ @Test("The first supported build keeps a bare version as its id")
+ func firstBuildKeepsBareVersionID() {
+ // Its clone is already on disk as crossover-<version>, and a machine whose CrossOver
+ // has since been replaced by another flavor could not produce that clone again.
+ let build = SupportedRunners.all[0]
+ #expect(build.flavor == nil)
+ #expect(build.id == build.bundleVersion)
+ }
+
+ // Picking the FEX CrossOver used to read "Build 27.0.0.40921", the same as the Rosetta one.
+ // Which had been picked only became visible once the clone directory carried the flavor.
+ @Test("A build is named by its flavor as well as its version")
+ func buildsAreNamedByFlavor() {
+ let rosetta = try! #require(SupportedRunners.build(id: "27.0.0.40921"))
+ let fex = try! #require(SupportedRunners.build(id: "27.0.0.40921-fex"))
+
+ #expect(rosetta.bundleVersion == fex.bundleVersion)
+ #expect(rosetta.releaseVersion == fex.releaseVersion)
+ #expect(rosetta.displayVersion == "20260821 Rosetta")
+ #expect(fex.displayVersion == "20260821 FEX")
+ #expect(rosetta.displayVersion != fex.displayVersion)
+ }
+
+ // The installed row has only the clone directory name, which is the id.
+ @Test("An installed build is named the same way the picked one is")
+ func installedBuildsReadBackTheSame() {
+ for build in SupportedRunners.all {
+ #expect(SupportedRunners.displayVersion(forID: build.id) == build.displayVersion)
+ #expect(!SupportedRunners.displayVersion(forID: build.id).contains("-fex"))
+ }
+
+ // A tree off the allow list still has to say something, and its directory name is
+ // all there is to say.
+ #expect(SupportedRunners.displayVersion(forID: "26.0.1.1234") == "26.0.1.1234")
+ }
+
+ @Test("Lookup matches on an exact loader hash only")
+ func lookupIsExact() {
+ let build = SupportedRunners.all[0]
+ #expect(SupportedRunners.build(loaderSHA256: build.loaderSHA256) != nil)
+ #expect(SupportedRunners.build(loaderSHA256: String(build.loaderSHA256.dropLast())) == nil)
+ #expect(SupportedRunners.build(loaderSHA256: build.loaderSHA256 + " ") == nil)
+ #expect(SupportedRunners.build(id: build.id) != nil)
+ #expect(SupportedRunners.build(id: build.id + " ") == nil)
+ }
+
+ private func expectSHA256(_ value: String, _ label: String) {
+ #expect(value.count == 64, "\(label) is not a sha256")
+ #expect(value.allSatisfy { $0.isHexDigit && !$0.isUppercase }, "\(label) is not lowercase hex")
+ }
+}
+
+@Suite("Runner store")
+struct RunnerStoreTests {
+
+ @Test("The build comes out of the crossover- path component")
+ func buildIdentifierParsing() {
+ #expect(RunnerStore.buildIdentifier(
+ inPath: "crossover-27.0.0.40921/CrossOver Preview.app/Contents/SharedSupport/CrossOver"
+ ) == "27.0.0.40921")
+
+ #expect(RunnerStore.buildIdentifier(
+ inPath: "../runners/crossover-1.2.3/CrossOver Preview.app/Contents/SharedSupport/CrossOver"
+ ) == "1.2.3")
+
+ #expect(RunnerStore.buildIdentifier(inPath: "CrossOver Preview.app/Contents") == nil)
+ #expect(RunnerStore.buildIdentifier(inPath: "") == nil)
+ }
+}
+
+@Suite("Signature database selection")
+struct SignatureSelectionTests {
+
+ @Test("The highest numbered database wins, not the first listed")
+ func picksHighestBuild() throws {
+ let directory = FileManager.default.temporaryDirectory
+ .appending(path: "np-signature-test-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: directory) }
+
+ for name in ["1788400362.json", "999999999.json", "1788400363.json", "notes.txt"] {
+ try Data().write(to: directory.appending(path: name))
+ }
+
+ #expect(PayloadInspector.newestSignatureDatabase(in: directory) == "1788400363.json")
+ }
+
+ @Test("An empty or absent directory reports nothing staged")
+ func handlesEmptyDirectory() throws {
+ let directory = FileManager.default.temporaryDirectory
+ .appending(path: "np-signature-empty-\(UUID().uuidString)")
+ #expect(PayloadInspector.newestSignatureDatabase(in: directory) == nil)
+
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: directory) }
+ #expect(PayloadInspector.newestSignatureDatabase(in: directory) == nil)
+ }
+}
+
+@Suite("Support paths")
+struct SupportPathTests {
+
+ // These strings are a contract with the dylib and RUN_SCRIPT rather than a
+ // preference, so they are pinned here to make a rename visible.
+ @Test("Paths match what the dylib and the run script use")
+ func pathsAreStable() {
+ let support = SupportPaths.support.path(percentEncoded: false)
+ #expect(support.hasSuffix("/Library/Application Support/notproton"))
+
+ #expect(SupportPaths.signatures.path(percentEncoded: false)
+ .hasSuffix("/notproton/signatures/macos.arm64"))
+ #expect(SupportPaths.overlayShim.path(percentEncoded: false)
+ .hasSuffix("/notproton/overlay-shim.dylib"))
+ #expect(SupportPaths.currentRunner.path(percentEncoded: false)
+ .hasSuffix("/notproton/runners/current"))
+ #expect(SupportPaths.Steam.deployedDylib.path(percentEncoded: false)
+ == "/Applications/Steam.app/Contents/MacOS/notproton.dylib")
+ #expect(SupportPaths.Steam.infoPlist.path(percentEncoded: false)
+ == "/Applications/Steam.app/Contents/Info.plist")
+ }
+}
diff --git a/app/Tests/NotProtonAppTests/InstallPayloadTests.swift b/app/Tests/NotProtonAppTests/InstallPayloadTests.swift
new file mode 100644
index 0000000..63267cd
--- /dev/null
+++ b/app/Tests/NotProtonAppTests/InstallPayloadTests.swift
@@ -0,0 +1,107 @@
+import Foundation
+import Testing
+
+@testable import NotProtonApp
+
+@Suite("Install payload")
+struct InstallPayloadTests {
+
+ private func scratch() throws -> URL {
+ let url = URL.temporaryDirectory.appending(path: "np-payload-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
+ return url
+ }
+
+ private func stage(_ root: URL, dylib: Bool = true, shim: Bool = true, iconmaker: Bool = true, appinfo: Bool = true, signatures: [String] = ["1788400362.json"]) throws {
+ let files = FileManager.default
+ let signatureDir = root.appending(path: "signatures/macos.arm64")
+ try files.createDirectory(at: signatureDir, withIntermediateDirectories: true)
+ if dylib { try Data("dylib".utf8).write(to: root.appending(path: SupportPaths.dylibName)) }
+ if shim { try Data("shim".utf8).write(to: root.appending(path: "overlay-shim.dylib")) }
+ if iconmaker { try Data("iconmaker".utf8).write(to: root.appending(path: "iconmaker")) }
+ if appinfo { try Data("appinfo".utf8).write(to: root.appending(path: "appinfo")) }
+ for name in signatures {
+ try Data("{}".utf8).write(to: signatureDir.appending(path: name))
+ }
+ }
+
+ @Test("The shipped app carries a payload staged by make")
+ func shippedPayloadIsStaged() throws {
+ let located = try InstallPayload.locate()
+
+ #expect(located.dylib.lastPathComponent == "notproton.dylib")
+ #expect(located.overlayShim.lastPathComponent == "overlay-shim.dylib")
+ #expect(located.appinfo.lastPathComponent == "appinfo")
+ #expect(!located.signatures.isEmpty)
+
+ // A real fat dylib, not a placeholder: an install that copied a stub would
+ // deploy something dyld refuses at launch.
+ let size = try FileManager.default.attributesOfItem(
+ atPath: located.dylib.path(percentEncoded: false)
+ )[.size] as? Int
+ #expect((size ?? 0) > 100_000, "the staged dylib is too small to be the built one")
+
+ let architectures = try Shell.run("/usr/bin/lipo", ["-info", located.dylib.path(percentEncoded: false)])
+ #expect(architectures.stdout.contains("arm64"))
+ #expect(architectures.stdout.contains("x86_64"))
+ }
+
+ @Test("Every signature database in the payload is found, in a stable order")
+ func findsAllSignatureDatabases() throws {
+ let root = try scratch()
+ defer { try? FileManager.default.removeItem(at: root) }
+ try stage(root, signatures: ["1788652215.json", "1788400362.json", "notes.txt"])
+
+ let located = try InstallPayload.locate(root: root)
+
+ #expect(located.signatures.map(\.lastPathComponent) == ["1788400362.json", "1788652215.json"])
+ }
+
+ @Test("A payload missing an artifact says which one and how to fix it")
+ func reportsMissingArtifacts() throws {
+ let root = try scratch()
+ defer { try? FileManager.default.removeItem(at: root) }
+ try stage(root, dylib: false)
+
+ do {
+ _ = try InstallPayload.locate(root: root)
+ Issue.record("a payload with no dylib was accepted")
+ } catch let failure as StepFailure {
+ #expect(failure.detail.contains("notproton.dylib"))
+ #expect(failure.detail.contains("make app-payload"))
+ #expect(!failure.detail.contains("overlay-shim.dylib"), "the shim was present and should not be named")
+ }
+ }
+
+ @Test("A payload with no signature database is refused")
+ func refusesPayloadWithoutSignatures() throws {
+ let root = try scratch()
+ defer { try? FileManager.default.removeItem(at: root) }
+ try stage(root, signatures: [])
+
+ do {
+ _ = try InstallPayload.locate(root: root)
+ Issue.record("a payload with no signature database was accepted")
+ } catch let failure as StepFailure {
+ #expect(failure.detail.contains("signatures/macos.arm64"))
+ }
+ }
+
+ @Test("An empty payload names every missing artifact")
+ func reportsEverythingMissing() throws {
+ let root = try scratch()
+ defer { try? FileManager.default.removeItem(at: root) }
+ try stage(root, dylib: false, shim: false, iconmaker: false, appinfo: false, signatures: [])
+
+ do {
+ _ = try InstallPayload.locate(root: root)
+ Issue.record("an empty payload was accepted")
+ } catch let failure as StepFailure {
+ #expect(failure.detail.contains("notproton.dylib"))
+ #expect(failure.detail.contains("overlay-shim.dylib"))
+ #expect(failure.detail.contains("iconmaker"))
+ #expect(failure.detail.contains("appinfo"))
+ #expect(failure.detail.contains("signatures/macos.arm64"))
+ }
+ }
+}
diff --git a/app/Tests/NotProtonAppTests/MachOBuildTests.swift b/app/Tests/NotProtonAppTests/MachOBuildTests.swift
new file mode 100644
index 0000000..72f0fcc
--- /dev/null
+++ b/app/Tests/NotProtonAppTests/MachOBuildTests.swift
@@ -0,0 +1,89 @@
+import Foundation
+import Testing
+
+@testable import NotProtonApp
+
+@Suite("Mach-O build identity")
+struct MachOBuildTests {
+
+ private func scratch() throws -> URL {
+ let url = URL.temporaryDirectory.appending(path: "np-macho-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
+ return url
+ }
+
+ private func dylib(_ body: String, in work: URL, named name: String) throws -> URL {
+ let source = work.appending(path: "\(name).c")
+ try Data(body.utf8).write(to: source)
+ let built = work.appending(path: "\(name).dylib")
+ try Shell.check("/usr/bin/clang", [
+ "-dynamiclib", "-o", built.path(percentEncoded: false),
+ source.path(percentEncoded: false),
+ ])
+ return built
+ }
+
+ @Test("Signing a binary does not change which build it is")
+ func signingPreservesIdentity() throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+
+ let built = try dylib("int np_probe(void) { return 1; }\n", in: work, named: "probe")
+ let before = try #require(MachOBuild.identity(of: built))
+
+ let copy = work.appending(path: "copy.dylib")
+ try FileManager.default.copyItem(at: built, to: copy)
+ try SteamInstaller.adHocSign(copy)
+
+ #expect(try Data(contentsOf: copy) != Data(contentsOf: built))
+ #expect(MachOBuild.identity(of: copy) == before)
+ }
+
+ @Test("Two different builds are told apart")
+ func differentBuildsDiffer() throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+
+ let one = try dylib("int np_probe(void) { return 1; }\n", in: work, named: "one")
+ let two = try dylib("int np_probe(void) { return 2; }\n", in: work, named: "two")
+
+ #expect(MachOBuild.identity(of: one) != MachOBuild.identity(of: two))
+ }
+
+ @Test("A universal binary is identified by every slice it carries")
+ func universalBinaryReportsBothSlices() throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+
+ let source = work.appending(path: "fat.c")
+ try Data("int np_probe(void) { return 1; }\n".utf8).write(to: source)
+ let built = work.appending(path: "fat.dylib")
+ try Shell.check("/usr/bin/clang", [
+ "-dynamiclib", "-arch", "arm64", "-arch", "x86_64",
+ "-o", built.path(percentEncoded: false), source.path(percentEncoded: false),
+ ])
+
+ let identity = try #require(MachOBuild.identity(of: built))
+ #expect(identity.count == 2)
+ #expect(identity == identity.sorted())
+
+ let thin = work.appending(path: "thin.dylib")
+ try Shell.check("/usr/bin/clang", [
+ "-dynamiclib", "-arch", "arm64",
+ "-o", thin.path(percentEncoded: false), source.path(percentEncoded: false),
+ ])
+ #expect(MachOBuild.identity(of: thin) != identity)
+ }
+
+ @Test("Something that is not a binary has no build identity")
+ func rubbishHasNoIdentity() throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+
+ let text = work.appending(path: "notes.txt")
+ try Data("not a binary".utf8).write(to: text)
+
+ #expect(MachOBuild.identity(of: text) == nil)
+ #expect(MachOBuild.identity(of: work.appending(path: "absent.dylib")) == nil)
+ }
+}
diff --git a/app/Tests/NotProtonAppTests/NtdllPatcherTests.swift b/app/Tests/NotProtonAppTests/NtdllPatcherTests.swift
new file mode 100644
index 0000000..a94edc5
--- /dev/null
+++ b/app/Tests/NotProtonAppTests/NtdllPatcherTests.swift
@@ -0,0 +1,468 @@
+import Foundation
+import Testing
+
+@testable import NotProtonApp
+
+// A stand-in PE with one file-backed section and one with nothing behind it, so the section
+// walk and every refusal run without CrossOver. Deliberately not an identity mapping.
+private struct StubPE {
+ static let peOffset = 0x80
+ static let sectionVirtualAddress = 0x1000
+ static let sectionRawOffset = 0x400
+ static let sectionSize = 0x4000
+
+ // A .bss style section placed before the real one, to prove it is skipped rather
+ // than matched.
+ static let bssVirtualAddress = 0x200
+ static let bssSize = 0x200
+
+ static func rva(forOffset offset: Int) -> Int {
+ sectionVirtualAddress + (offset - sectionRawOffset)
+ }
+
+ static func make(machine: UInt16, magic: UInt16, imageBase: UInt64) -> Data {
+ var bytes = [UInt8](repeating: 0, count: sectionRawOffset + sectionSize)
+
+ write(&bytes, 0x3c, UInt32(peOffset))
+ write(&bytes, peOffset, UInt32(0x0000_4550))
+ write(&bytes, peOffset + 4, machine)
+
+ let optionalSize: UInt16 = 0xf0
+ write(&bytes, peOffset + 6, UInt16(2))
+ write(&bytes, peOffset + 20, optionalSize)
+ write(&bytes, peOffset + 24, magic)
+
+ if magic == 0x20b {
+ write(&bytes, peOffset + 24 + 24, imageBase)
+ } else {
+ write(&bytes, peOffset + 24 + 28, UInt32(truncatingIfNeeded: imageBase))
+ }
+
+ let table = peOffset + 24 + Int(optionalSize)
+ write(&bytes, table + 8, UInt32(bssSize))
+ write(&bytes, table + 12, UInt32(bssVirtualAddress))
+ write(&bytes, table + 16, UInt32(0))
+ write(&bytes, table + 20, UInt32(0))
+
+ write(&bytes, table + 40 + 8, UInt32(sectionSize))
+ write(&bytes, table + 40 + 12, UInt32(sectionVirtualAddress))
+ write(&bytes, table + 40 + 16, UInt32(sectionSize))
+ write(&bytes, table + 40 + 20, UInt32(sectionRawOffset))
+
+ return Data(bytes)
+ }
+
+ private static func write<T: FixedWidthInteger>(_ bytes: inout [UInt8], _ offset: Int, _ value: T) {
+ withUnsafeBytes(of: value.littleEndian) { raw in
+ for (index, byte) in raw.enumerated() { bytes[offset + index] = byte }
+ }
+ }
+}
+
+@Suite("ntdll patcher")
+struct NtdllPatcherTests {
+
+ private let stolen: [UInt8] = [0x48, 0x83, 0xbc, 0x24, 0xf0, 0x00, 0x00, 0x00, 0x00]
+
+ private func stubPatch(caveSize: Int = 0x100, cavePad: UInt8 = 0) -> NtdllPatch {
+ NtdllPatch(
+ arch: .x86_64Windows,
+ payloadResource: "detour2",
+ payloadSHA256: "unused",
+ caveRVA: StubPE.rva(forOffset: StubPE.sectionRawOffset + 0x800),
+ payloadRVA: StubPE.rva(forOffset: StubPE.sectionRawOffset + 0x800),
+ hooks: [
+ NtdllHook(rva: StubPE.rva(forOffset: StubPE.sectionRawOffset + 0x100), stolen: stolen)
+ ],
+ caveSize: caveSize,
+ cavePad: cavePad,
+ machine: 0x8664,
+ magic: 0x20b,
+ imageBase: 0x1_7000_0000
+ )
+ }
+
+ private func stubImage() -> Data {
+ var bytes = [UInt8](StubPE.make(machine: 0x8664, magic: 0x20b, imageBase: 0x1_7000_0000))
+ let hookOffset = StubPE.sectionRawOffset + 0x100
+ for (index, byte) in stolen.enumerated() { bytes[hookOffset + index] = byte }
+ return Data(bytes)
+ }
+
+ // MARK: - The patch itself
+
+ @Test("A patch writes the detour into the cave and a reachable jump at the hook")
+ func patchWritesBothSites() throws {
+ let patch = stubPatch()
+ let payload = Data([0x90, 0x91, 0x92, 0x93])
+ let result = [UInt8](try NtdllPatcher.apply(patch, to: stubImage(), payload: payload))
+
+ let caveOffset = StubPE.sectionRawOffset + 0x800
+ #expect(Array(result[caveOffset ..< caveOffset + 4]) == [0x90, 0x91, 0x92, 0x93])
+
+ let hookOffset = StubPE.sectionRawOffset + 0x100
+ #expect(result[hookOffset] == 0xe9)
+
+ let displacement = result[(hookOffset + 1) ..< (hookOffset + 5)]
+ .reversed()
+ .reduce(Int32(0)) { $0 << 8 | Int32($1) }
+ #expect(Int(displacement) == patch.payloadRVA - (patch.hooks[0].rva + 5))
+
+ // The stolen bytes past the jump are int3, not left as the tail of the
+ // instruction that was overwritten.
+ #expect(Array(result[(hookOffset + 5) ..< (hookOffset + stolen.count)]) == [0xcc, 0xcc, 0xcc, 0xcc])
+ }
+
+ @Test("The file keeps its length, because a PE cannot absorb inserted bytes")
+ func patchDoesNotResize() throws {
+ let patch = stubPatch()
+ let image = stubImage()
+ let result = try NtdllPatcher.apply(patch, to: image, payload: Data(repeating: 0x90, count: 64))
+ #expect(result.count == image.count)
+ }
+
+ // MARK: - Refusals
+
+ @Test("A hook site holding something else is refused")
+ func wrongStolenBytesRefused() throws {
+ let patch = stubPatch()
+ var bytes = [UInt8](stubImage())
+ bytes[StubPE.sectionRawOffset + 0x100] = 0x90
+
+ #expect(throws: StepFailure.self) {
+ try NtdllPatcher.apply(patch, to: Data(bytes), payload: Data([0x90]))
+ }
+ }
+
+ @Test("A cave with anything in it is refused, so a second patch cannot stack")
+ func occupiedCaveRefused() throws {
+ let patch = stubPatch()
+ let payload = Data(repeating: 0x90, count: 32)
+ let once = try NtdllPatcher.apply(patch, to: stubImage(), payload: payload)
+
+ #expect(throws: StepFailure.self) {
+ try NtdllPatcher.apply(patch, to: once, payload: payload)
+ }
+ }
+
+ @Test("A detour larger than the cave is refused rather than overrunning it")
+ func oversizePayloadRefused() throws {
+ let patch = stubPatch(caveSize: 16)
+ #expect(throws: StepFailure.self) {
+ try NtdllPatcher.apply(patch, to: stubImage(), payload: Data(repeating: 0x90, count: 17))
+ }
+ }
+
+ @Test("A mismatched machine, optional header or image base is refused")
+ func headerMismatchRefused() throws {
+ let patch = stubPatch()
+ let payload = Data([0x90])
+
+ let wrongMachine = StubPE.make(machine: 0x14c, magic: 0x20b, imageBase: 0x1_7000_0000)
+ #expect(throws: StepFailure.self) { try NtdllPatcher.apply(patch, to: wrongMachine, payload: payload) }
+
+ let wrongMagic = StubPE.make(machine: 0x8664, magic: 0x10b, imageBase: 0x1_7000_0000)
+ #expect(throws: StepFailure.self) { try NtdllPatcher.apply(patch, to: wrongMagic, payload: payload) }
+
+ let wrongBase = StubPE.make(machine: 0x8664, magic: 0x20b, imageBase: 0x1_8000_0000)
+ #expect(throws: StepFailure.self) { try NtdllPatcher.apply(patch, to: wrongBase, payload: payload) }
+ }
+
+ @Test("A truncated file is refused instead of read past its end")
+ func truncatedFileRefused() throws {
+ let patch = stubPatch()
+ let image = stubImage().prefix(StubPE.sectionRawOffset)
+
+ #expect(throws: StepFailure.self) {
+ try NtdllPatcher.apply(patch, to: Data(image), payload: Data([0x90]))
+ }
+ }
+
+ // The size check on its own read an address below the cave as extra room rather than as
+ // being outside it, so the detour was written into the code in front of the cave.
+ @Test("A detour addressed below its cave is refused")
+ func detourBelowItsCaveRefused() throws {
+ let base = stubPatch()
+ let below = NtdllPatch(
+ arch: base.arch, payloadResource: base.payloadResource, payloadSHA256: base.payloadSHA256,
+ caveRVA: base.caveRVA, payloadRVA: base.caveRVA - 0x100, hooks: base.hooks,
+ caveSize: base.caveSize, cavePad: base.cavePad, machine: base.machine,
+ magic: base.magic, imageBase: base.imageBase
+ )
+
+ #expect(throws: StepFailure.self) {
+ try NtdllPatcher.apply(below, to: stubImage(), payload: Data(repeating: 0x90, count: 0x10))
+ }
+ }
+
+ @Test("An RVA in no mapped section is refused, including one inside an unbacked section")
+ func unmappedRVARefused() throws {
+ let base = stubPatch()
+ let payload = Data([0x90])
+
+ let beyond = NtdllPatch(
+ arch: base.arch, payloadResource: base.payloadResource, payloadSHA256: base.payloadSHA256,
+ caveRVA: 0x9000_0000, payloadRVA: 0x9000_0000, hooks: base.hooks, caveSize: base.caveSize,
+ cavePad: base.cavePad, machine: base.machine, magic: base.magic, imageBase: base.imageBase
+ )
+ #expect(throws: StepFailure.self) {
+ try NtdllPatcher.apply(beyond, to: stubImage(), payload: payload)
+ }
+
+ // Inside the .bss style section, which has no file offset to resolve to.
+ let unbacked = NtdllPatch(
+ arch: base.arch, payloadResource: base.payloadResource, payloadSHA256: base.payloadSHA256,
+ caveRVA: StubPE.bssVirtualAddress + 0x10, payloadRVA: StubPE.bssVirtualAddress + 0x10,
+ hooks: base.hooks,
+ caveSize: base.caveSize, cavePad: base.cavePad, machine: base.machine, magic: base.magic,
+ imageBase: base.imageBase
+ )
+ #expect(throws: StepFailure.self) {
+ try NtdllPatcher.apply(unbacked, to: stubImage(), payload: payload)
+ }
+ }
+
+ // MARK: - Shipped payloads
+
+ @Test("Both detour payloads ship and match the hashes they were built with")
+ func shippedPayloadsMatch() throws {
+ for build in SupportedRunners.all {
+ for patch in NtdllPatcher.patches(for: build) {
+ let payload = try NtdllPatcher.payload(for: patch)
+ #expect(!payload.isEmpty)
+ #expect(Digest.sha256(of: payload) == patch.payloadSHA256)
+ }
+ }
+ }
+
+ // A build is patched only where it has both a hash and offsets. A patch without a hash
+ // runs against an unverified input, a hash without a patch promises one that never runs.
+ @Test("Every build's patches line up with the arches it records hashes for")
+ func patchesMatchRecordedArches() {
+ for build in SupportedRunners.all {
+ let patched = Set(NtdllPatcher.patches(for: build).map(\.arch))
+ #expect(patched == Set(build.cleanNtdll.keys))
+ #expect(patched == Set(build.patchedNtdll.keys))
+ for arch in patched {
+ #expect(NtdllPatcher.patch(for: arch, in: build) != nil)
+ }
+ }
+ #expect(!NtdllPatcher.patches(for: SupportedRunners.all[0]).isEmpty)
+ }
+
+ // MARK: - Against the real thing
+
+ // The point of the port: the same input has to come out as the bytes apply.py and
+ // apply32.py produced, which SupportedRunners records. Needs an unpatched CrossOver.
+ @Test("Patching the unpatched ntdll reproduces the recorded hashes")
+ func realNtdllReproducesRecordedHashes() throws {
+ let root = URL(filePath: "/Applications/CrossOver Preview.app/Contents/SharedSupport/CrossOver")
+ guard FileManager.default.fileExists(atPath: root.path(percentEncoded: false)),
+ let installed = Digest.sha256IfPresent(CrossOverSource.unixLoader(inRoot: root)),
+ let build = SupportedRunners.build(loaderSHA256: installed)
+ else { return }
+
+ var reproduced: [WineArch] = []
+ for patch in NtdllPatcher.patches(for: build) {
+ let source = NtdllPatcher.cleanSource(inRoot: root, arch: patch.arch)
+ guard let hash = Digest.sha256IfPresent(source), hash == build.cleanNtdll[patch.arch] else {
+ continue
+ }
+
+ let patched = try NtdllPatcher.apply(
+ patch, to: try Data(contentsOf: source), payload: try NtdllPatcher.payload(for: patch)
+ )
+ #expect(Digest.sha256(of: patched) == build.patchedNtdll[patch.arch])
+ reproduced.append(patch.arch)
+ }
+
+ // The bundle was identified by its loader, so every arch with a clean hash is present
+ // and a run that reproduced fewer skipped rather than passed.
+ #expect(reproduced.count == build.cleanNtdll.count)
+ }
+
+ // Every supported build, not whichever is installed. Refusal runs on synthetic bytes, so
+ // a build's patches are checkable on a machine that could never run it.
+ @Test("An input that is not the pinned build is refused before anything is written")
+ func unpinnedInputRefused() throws {
+ let directory = URL(filePath: NSTemporaryDirectory()).appending(path: "notproton-patch-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: directory) }
+
+ let source = directory.appending(path: "ntdll.dll")
+ try Data(repeating: 0, count: 1024).write(to: source)
+
+ var checked = 0
+ for build in SupportedRunners.all {
+ for patch in NtdllPatcher.patches(for: build) {
+ let destination = directory.appending(path: "out-\(build.id)-\(patch.arch.rawValue).dll")
+ #expect(throws: StepFailure.self) {
+ try NtdllPatcher.write(patch, build: build, from: source, to: destination)
+ }
+ #expect(!FileManager.default.fileExists(atPath: destination.path(percentEncoded: false)))
+ checked += 1
+ }
+ }
+ #expect(checked > 0)
+ }
+
+ @Test("A missing input is refused by name")
+ func missingInputRefused() throws {
+ let source = URL(filePath: NSTemporaryDirectory()).appending(path: "notproton-absent-\(UUID().uuidString)")
+
+ var checked = 0
+ for build in SupportedRunners.all {
+ for patch in NtdllPatcher.patches(for: build) {
+ #expect(throws: StepFailure.self) {
+ try NtdllPatcher.write(patch, build: build, from: source, to: source)
+ }
+ checked += 1
+ }
+ }
+ #expect(checked > 0)
+ }
+
+ // The bridge here came out of apply.py and apply32.py, so staging from the same clone has
+ // to be byte identical. A clean ntdll cannot be a fixture, so no runner means skip.
+ private static func cleanRunnerRoot(for build: RunnerBuild) -> URL? {
+ let root = SupportPaths.currentRunner
+ guard FileManager.default.fileExists(
+ atPath: root.appending(path: "lib/wine").path(percentEncoded: false)
+ ) else { return nil }
+
+ for patch in NtdllPatcher.patches(for: build) {
+ let source = NtdllPatcher.cleanSource(inRoot: root, arch: patch.arch)
+ guard Digest.sha256IfPresent(source) == build.cleanNtdll[patch.arch] else {
+ return nil
+ }
+ }
+ return root
+ }
+
+ @Test("Staging reproduces the bridge the python patcher produced")
+ func stagingReproducesExistingBridge() throws {
+ for build in SupportedRunners.all {
+ guard let root = Self.cleanRunnerRoot(for: build) else { continue }
+ try Self.expectStagingReproducesBridge(build: build, root: root)
+ }
+ }
+
+ private static func expectStagingReproducesBridge(build: RunnerBuild, root: URL) throws {
+ let fm = FileManager.default
+
+ let scratch = URL(filePath: NSTemporaryDirectory()).appending(path: "notproton-stage-\(UUID().uuidString)")
+ defer { try? fm.removeItem(at: scratch) }
+
+ try NtdllPatcher.stage(build: build, runnerRoot: root, bridge: scratch)
+
+ var compared: [WineArch] = []
+ for patch in NtdllPatcher.patches(for: build) {
+ let relative = "wine/\(patch.arch.rawValue)/ntdll.dll"
+ let staged = scratch.appending(path: relative)
+ let existing = SupportPaths.bridge.appending(path: relative)
+
+ #expect(Digest.sha256IfPresent(staged) == build.patchedNtdll[patch.arch])
+ guard let live = Digest.sha256IfPresent(existing) else { continue }
+ #expect(Digest.sha256IfPresent(staged) == live)
+ compared.append(patch.arch)
+ }
+
+ // A staged bridge that matched nothing is a test that skipped. Asked per build rather
+ // than against a fixed arch, so a bridge of another flavor does not stand this down.
+ let bridgeHoldsThisBuild = build.patchedNtdll.keys.contains { arch in
+ Digest.sha256IfPresent(SupportPaths.bridge.appending(path: "wine/\(arch.rawValue)/ntdll.dll")) != nil
+ }
+ if bridgeHoldsThisBuild {
+ #expect(compared.count == build.patchedNtdll.count)
+ }
+ }
+
+ @Test("Staging a second time writes nothing, so it is safe on every install")
+ func stagingIsIdempotent() throws {
+ for build in SupportedRunners.all {
+ guard let root = Self.cleanRunnerRoot(for: build) else { continue }
+ let fm = FileManager.default
+
+ let scratch = URL(filePath: NSTemporaryDirectory()).appending(path: "notproton-stage-\(UUID().uuidString)")
+ defer { try? fm.removeItem(at: scratch) }
+
+ // One file per patch the build defines. A build pins the arches its loader can map,
+ // never all of WineArch: an x86_64 loader has no aarch64 guest.
+ let first = try NtdllPatcher.stage(build: build, runnerRoot: root, bridge: scratch)
+ #expect(first.count == NtdllPatcher.patches(for: build).count)
+
+ let second = try NtdllPatcher.stage(build: build, runnerRoot: root, bridge: scratch)
+ #expect(second.isEmpty)
+ }
+ }
+
+ @Test("The clean source prefers the one time backup over a live file")
+ func cleanSourcePrefersBackup() throws {
+ let root = URL(filePath: NSTemporaryDirectory()).appending(path: "notproton-root-\(UUID().uuidString)")
+ let directory = root.appending(path: "lib/wine/x86_64-windows")
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let live = directory.appending(path: "ntdll.dll")
+ try Data([0x00]).write(to: live)
+ #expect(NtdllPatcher.cleanSource(inRoot: root, arch: .x86_64Windows) == live)
+
+ let backup = directory.appending(path: "ntdll.dll.notproton-orig")
+ try Data([0x00]).write(to: backup)
+ #expect(NtdllPatcher.cleanSource(inRoot: root, arch: .x86_64Windows) == backup)
+ }
+}
+
+@Suite("ntdll staging")
+struct NtdllStagingTests {
+
+ // A build whose patched hashes are the files already in the bridge, so staging has nothing
+ // to write and the only thing under test is what it leaves behind.
+ private func stagedBridge() throws -> (bridge: URL, build: RunnerBuild) {
+ let bridge = FileManager.default.temporaryDirectory
+ .appending(path: "np-bridge-\(UUID().uuidString)")
+
+ var hashes: [WineArch: String] = [:]
+ for arch in WineArch.allCases {
+ let directory = bridge.appending(path: "wine/\(arch.rawValue)")
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ let file = directory.appending(path: "ntdll.dll")
+ try Data("staged \(arch.rawValue)".utf8).write(to: file)
+ hashes[arch] = try Digest.sha256(of: file)
+ }
+
+ // The FEX flavor, which patches i386 and aarch64 and leaves x86_64 alone.
+ let build = RunnerBuild(
+ bundleVersion: "27.0.0.40921",
+ releaseVersion: "20260821",
+ flavor: "fex",
+ loaderSHA256: "unused",
+ cleanNtdll: [:],
+ patchedNtdll: [
+ .i386Windows: hashes[.i386Windows]!,
+ .aarch64Windows: hashes[.aarch64Windows]!,
+ ]
+ )
+ return (bridge, build)
+ }
+
+ @Test("Staging drops an ntdll left in the bridge for an arch this build does not patch")
+ func stagingPrunesForeignArches() throws {
+ let (bridge, build) = try stagedBridge()
+ defer { try? FileManager.default.removeItem(at: bridge) }
+
+ let written = try NtdllPatcher.stage(
+ build: build, runnerRoot: bridge.appending(path: "unused"), bridge: bridge
+ )
+ #expect(written.isEmpty)
+
+ let fm = FileManager.default
+ for arch in [WineArch.i386Windows, .aarch64Windows] {
+ let kept = bridge.appending(path: "wine/\(arch.rawValue)/ntdll.dll")
+ #expect(fm.fileExists(atPath: kept.path(percentEncoded: false)))
+ }
+
+ let foreign = bridge.appending(path: "wine/x86_64-windows/ntdll.dll")
+ #expect(!fm.fileExists(atPath: foreign.path(percentEncoded: false)))
+ }
+}
diff --git a/app/Tests/NotProtonAppTests/PayloadManifestTests.swift b/app/Tests/NotProtonAppTests/PayloadManifestTests.swift
new file mode 100644
index 0000000..c7fcbbc
--- /dev/null
+++ b/app/Tests/NotProtonAppTests/PayloadManifestTests.swift
@@ -0,0 +1,103 @@
+import Foundation
+import Testing
+
+@testable import NotProtonApp
+
+@Suite("Payload manifest")
+struct PayloadManifestTests {
+
+ @Test("The shipped manifest is the payload a launch consumes")
+ func shippedManifestIsComplete() throws {
+ let manifest = try PayloadManifest.bundled()
+
+ // Nineteen files in the split a working install proved: seven built here, two
+ // patched on device, ten from pinned Valve client packages.
+ #expect(manifest.entries.count == 19)
+ #expect(manifest.paths(origin: .built).count == 7)
+ #expect(manifest.paths(origin: .patched).count == 2)
+ #expect(manifest.paths(origin: .valve).count == 10)
+
+ // Every payload file is fetchable from Valve or produced here, which is what dropping
+ // the steam_api pair bought. A fourth origin would mean a file with no way to get it.
+ #expect(PayloadOrigin.allCases.filter(\.isFetchable) == [.valve])
+ #expect(PayloadOrigin.allCases.count == 3)
+
+ // The patched entries are the two ntdlls and nothing else. Anything else
+ // marked patched would be staged from a file the app is not allowed to ship.
+ #expect(Set(manifest.paths(origin: .patched)) == [
+ "wine/i386-windows/ntdll.dll",
+ "wine/x86_64-windows/ntdll.dll",
+ ])
+ }
+
+ @Test("Every entry is a relative path inside the bridge")
+ func pathsAreRelative() throws {
+ for entry in try PayloadManifest.bundled().entries {
+ #expect(!entry.path.hasPrefix("/"), "\(entry.path) is absolute")
+ #expect(!entry.path.contains(".."), "\(entry.path) escapes the bridge")
+ #expect(!entry.path.contains(" "), "\(entry.path) has a space, which verify.sh splits on")
+ }
+ }
+
+ @Test("Comments and blank lines are ignored")
+ func ignoresCommentsAndBlanks() throws {
+ let manifest = try PayloadManifest.parse(
+ """
+ # a comment
+ # an indented comment
+
+ built steam.exe
+ valve steamclient.dll
+ """
+ )
+
+ #expect(manifest.entries == [
+ PayloadEntry(origin: .built, path: "steam.exe"),
+ PayloadEntry(origin: .valve, path: "steamclient.dll"),
+ ])
+ }
+
+ // A skipped line drops a file out of the payload and turns a typo into a launch
+ // that fails somewhere unrelated, so every one of these has to throw.
+ @Test("A malformed manifest is refused rather than partly read")
+ func refusesMalformed() {
+ #expect(throws: StepFailure.self) { try PayloadManifest.parse("nonsense steam.exe") }
+ #expect(throws: StepFailure.self) { try PayloadManifest.parse("built") }
+ #expect(throws: StepFailure.self) { try PayloadManifest.parse("built steam.exe extra") }
+ #expect(throws: StepFailure.self) { try PayloadManifest.parse("# only comments") }
+ #expect(throws: StepFailure.self) { try PayloadManifest.parse("") }
+ #expect(throws: StepFailure.self) {
+ try PayloadManifest.parse("built steam.exe\nvalve steam.exe")
+ }
+ }
+}
+
+@Suite("Payload inspection")
+struct PayloadInspectionTests {
+
+ @Test("A bridge missing files reports them by name and origin")
+ func reportsMissingByOrigin() throws {
+ let bridge = FileManager.default.temporaryDirectory
+ .appending(path: "np-bridge-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: bridge, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: bridge) }
+
+ let manifest = try PayloadManifest.bundled()
+ for path in manifest.paths(origin: .valve) {
+ let file = bridge.appending(path: path)
+ try FileManager.default.createDirectory(
+ at: file.deletingLastPathComponent(), withIntermediateDirectories: true
+ )
+ try Data().write(to: file)
+ }
+
+ let state = PayloadInspector.inspect(bridge: bridge)
+ #expect(state.manifestProblem == nil)
+ #expect(state.expected == 19)
+ #expect(state.present == 10)
+ #expect(state.missing(origin: .valve).isEmpty)
+ #expect(state.missing(origin: .built).count == 7)
+ #expect(state.missing(origin: .patched).count == 2)
+ #expect(!state.isComplete)
+ }
+}
diff --git a/app/Tests/NotProtonAppTests/PayloadStateTests.swift b/app/Tests/NotProtonAppTests/PayloadStateTests.swift
new file mode 100644
index 0000000..d985bf0
--- /dev/null
+++ b/app/Tests/NotProtonAppTests/PayloadStateTests.swift
@@ -0,0 +1,168 @@
+import Foundation
+import Testing
+
+@testable import NotProtonApp
+
+// The dylib picks the signature database itself, in newest_sigdb_in_dir. What the app reports
+// has to be the file the dylib will load, or the status describes a different install.
+@Suite("Signature database selection")
+struct SignatureDatabaseSelectionTests {
+
+ private func directory(_ names: [String]) throws -> URL {
+ let url = URL.temporaryDirectory.appending(path: "np-sigs-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
+ for name in names {
+ try Data("{}".utf8).write(to: url.appending(path: name))
+ }
+ return url
+ }
+
+ @Test("The highest numbered database wins, whatever order the directory lists")
+ func picksTheHighestNumber() throws {
+ let dir = try directory(["1788400362.json", "1700000000.json", "1788400361.json"])
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ #expect(PayloadInspector.newestSignatureDatabase(in: dir) == "1788400362.json")
+ }
+
+ @Test("Numbers are compared as numbers, not as text")
+ func comparesNumerically() throws {
+ // Lexically "9" sorts above "10", so a string comparison would pick the older one.
+ let dir = try directory(["9.json", "10.json"])
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ #expect(PayloadInspector.newestSignatureDatabase(in: dir) == "10.json")
+ }
+
+ @Test("A directory with no database reports none")
+ func reportsNoneWhenEmpty() throws {
+ let dir = try directory([])
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ #expect(PayloadInspector.newestSignatureDatabase(in: dir) == nil)
+ }
+
+ @Test("A directory that is not there reports none rather than throwing")
+ func reportsNoneWhenAbsent() {
+ let absent = URL.temporaryDirectory.appending(path: "np-sigs-absent-\(UUID().uuidString)")
+ #expect(PayloadInspector.newestSignatureDatabase(in: absent) == nil)
+ }
+
+ @Test("Files that are not databases are ignored")
+ func ignoresOtherFiles() throws {
+ let dir = try directory(["1788400362.json", "notes.txt", "README"])
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ #expect(PayloadInspector.newestSignatureDatabase(in: dir) == "1788400362.json")
+ }
+
+ // newest_sigdb_in_dir requires the whole stem to be digits, so strtoull has to consume every
+ // character before ".json". A name the dylib skips cannot be reported as the one it loads.
+ @Test("A name that is not all digits is not a database the dylib would load")
+ func refusesNonNumericNames() throws {
+ let dir = try directory(["notes.json"])
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ #expect(PayloadInspector.newestSignatureDatabase(in: dir) == nil)
+ }
+
+ @Test("Trailing text after the number is not a database either")
+ func refusesTrailingText() throws {
+ // What duplicating the file in Finder produces.
+ let dir = try directory(["1788400362 copy.json"])
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ #expect(PayloadInspector.newestSignatureDatabase(in: dir) == nil)
+ }
+
+ // The dylib treats a parsed value of zero as no database, so "0.json" is skipped.
+ @Test("Zero is not a client build")
+ func refusesZero() throws {
+ let dir = try directory(["0.json"])
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ #expect(PayloadInspector.newestSignatureDatabase(in: dir) == nil)
+ }
+
+ @Test("A real database is still found next to names the dylib skips")
+ func picksTheRealOneAmongstJunk() throws {
+ let dir = try directory(["notes.json", "0.json", "1788400362.json", "old copy.json"])
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ #expect(PayloadInspector.newestSignatureDatabase(in: dir) == "1788400362.json")
+ }
+}
+
+@Suite("Payload completeness")
+struct PayloadStateTests {
+
+ private func state(
+ missing: [PayloadEntry] = [],
+ overlay: Bool = true,
+ signatures: String? = "1788400362.json",
+ problem: String? = nil
+ ) -> PayloadState {
+ PayloadState(
+ expected: 18,
+ present: 18 - missing.count,
+ missing: missing,
+ overlayShimPresent: overlay,
+ iconmakerPresent: true,
+ appinfoPresent: true,
+ signatureDatabase: signatures,
+ legacyCompatPresent: 6,
+ legacyCompatExpected: 6,
+ manifestProblem: problem
+ )
+ }
+
+ @Test("Everything staged is complete")
+ func completeWhenNothingIsWrong() {
+ #expect(state().isComplete)
+ }
+
+ @Test("Each thing that can be wrong on its own makes the payload incomplete")
+ func incompleteForEachCause() {
+ let entry = PayloadEntry(origin: .valve, path: "steamclient64.dll")
+
+ #expect(!state(missing: [entry]).isComplete)
+ #expect(!state(overlay: false).isComplete)
+ #expect(!state(signatures: nil).isComplete)
+ #expect(!state(problem: "the manifest will not parse").isComplete)
+ }
+
+ // A manifest that will not parse leaves expected at zero and missing empty, which looks
+ // exactly like a complete install. Only the problem separates them, so it has to decide.
+ @Test("An unreadable manifest is not mistaken for a complete install")
+ func unreadableManifestIsNotComplete() {
+ let broken = PayloadState(
+ expected: 0, present: 0, missing: [],
+ overlayShimPresent: true,
+ iconmakerPresent: true,
+ appinfoPresent: true,
+ signatureDatabase: "1788400362.json",
+ legacyCompatPresent: 6,
+ legacyCompatExpected: 6,
+ manifestProblem: "payload.tsv is missing from the app's resources."
+ )
+ #expect(!broken.isComplete)
+ }
+
+ @Test("Missing entries are reported per origin")
+ func splitsMissingByOrigin() {
+ let built = PayloadEntry(origin: .built, path: "x86_64-unix/lsteamclient.so")
+ let valve = PayloadEntry(origin: .valve, path: "steamclient64.dll")
+ let patched = PayloadEntry(origin: .patched, path: "wine/i386-windows/ntdll.dll")
+ let payload = state(missing: [built, valve, patched])
+
+ #expect(payload.missing(origin: .built) == [built])
+ #expect(payload.missing(origin: .valve) == [valve])
+ #expect(payload.missing(origin: .patched) == [patched])
+ }
+
+ @Test("An origin with nothing missing reports nothing")
+ func emptyOriginIsEmpty() {
+ let payload = state(missing: [PayloadEntry(origin: .valve, path: "steamclient64.dll")])
+ #expect(payload.missing(origin: .built).isEmpty)
+ }
+}
diff --git a/app/Tests/NotProtonAppTests/PinnedDownloadTests.swift b/app/Tests/NotProtonAppTests/PinnedDownloadTests.swift
new file mode 100644
index 0000000..13beb9e
--- /dev/null
+++ b/app/Tests/NotProtonAppTests/PinnedDownloadTests.swift
@@ -0,0 +1,148 @@
+import Foundation
+import Testing
+
+@testable import NotProtonApp
+
+// The pin is the only thing between a substituted download and code that gets unpacked and
+// run, and it had no test of its own. Hosts are file URLs, so none of this needs the network.
+@Suite("Pinned download")
+struct PinnedDownloadTests {
+
+ // The progress closure is Sendable, so what it records has to be too.
+ private final class Reports: @unchecked Sendable {
+ private let lock = NSLock()
+ private var seen: [String] = []
+ func add(_ s: String) { lock.lock(); seen.append(s); lock.unlock() }
+ var all: [String] { lock.lock(); defer { lock.unlock() }; return seen }
+ }
+
+ private func scratch() throws -> URL {
+ let url = FileManager.default.temporaryDirectory
+ .appending(path: "notproton-pinned-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
+ return url
+ }
+
+ // A host directory holding one file under the name the download asks for.
+ private func host(_ root: URL, named: String, serving bytes: String) throws -> URL {
+ let dir = root.appending(path: "host-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ try Data(bytes.utf8).write(to: dir.appending(path: named))
+ return dir
+ }
+
+ private func obtain(
+ bases: [URL], into downloads: URL, sha256: String, file: String = "package.tar"
+ ) async throws -> URL {
+ try await PinnedDownload.obtain(
+ file: file, sha256: sha256, bases: bases, into: downloads, step: "test"
+ )
+ }
+
+ @Test("Bytes that match the pin are kept")
+ func keepsMatchingBytes() async throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+
+ let body = "the real package"
+ let serving = try host(work, named: "package.tar", serving: body)
+ let downloads = work.appending(path: "downloads")
+
+ let got = try await obtain(
+ bases: [serving], into: downloads, sha256: Digest.sha256(of: Data(body.utf8))
+ )
+
+ #expect(try String(contentsOf: got, encoding: .utf8) == body)
+ }
+
+ @Test("Bytes that do not match the pin are refused and nothing is left behind")
+ func refusesMismatchedBytes() async throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+
+ let serving = try host(work, named: "package.tar", serving: "a substituted package")
+ let downloads = work.appending(path: "downloads")
+ let wanted = Digest.sha256(of: Data("the real package".utf8))
+
+ await #expect(throws: StepFailure.self) {
+ _ = try await obtain(bases: [serving], into: downloads, sha256: wanted)
+ }
+
+ // The point is not only that it threw. Bytes left in the downloads directory
+ // would be picked up as cached and reused by the next run.
+ #expect(
+ FileManager.default.fileExists(
+ atPath: downloads.appending(path: "package.tar").path(percentEncoded: false)
+ ) == false,
+ "the rejected body was kept and would be reused as a cached download"
+ )
+ }
+
+ @Test("A host serving the wrong bytes is passed over for one that does not")
+ func fallsThroughToAHonestHost() async throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+
+ let body = "the real package"
+ let liar = try host(work, named: "package.tar", serving: "a substituted package")
+ let honest = try host(work, named: "package.tar", serving: body)
+ let downloads = work.appending(path: "downloads")
+
+ let got = try await obtain(
+ bases: [liar, honest], into: downloads, sha256: Digest.sha256(of: Data(body.utf8))
+ )
+
+ #expect(try String(contentsOf: got, encoding: .utf8) == body)
+ }
+
+ @Test("An archive already on disk that matches is not fetched again")
+ func reusesMatchingArchive() async throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+
+ let body = "the real package"
+ let downloads = work.appending(path: "downloads")
+ try FileManager.default.createDirectory(at: downloads, withIntermediateDirectories: true)
+ try Data(body.utf8).write(to: downloads.appending(path: "package.tar"))
+
+ // No hosts at all, so anything that reaches the network cannot succeed.
+ let reported = Reports()
+ let got = try await PinnedDownload.obtain(
+ file: "package.tar",
+ sha256: Digest.sha256(of: Data(body.utf8)),
+ bases: [],
+ into: downloads,
+ step: "test",
+ report: { reported.add($0.label) }
+ )
+
+ #expect(reported.all == ["Preparing"])
+ #expect(try String(contentsOf: got, encoding: .utf8) == body)
+ }
+
+ // Two phase enums show this wording, so one copy is what both depend on. The host has to
+ // survive into the label: a fallthrough to a second host is only visible through it.
+ @Test("A fetch reports the host the bytes came from")
+ func reportsTheHostFetchedFrom() async throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+
+ let body = "the real package"
+ let serving = try host(work, named: "package.tar", serving: body)
+ let reported = Reports()
+
+ _ = try await PinnedDownload.obtain(
+ file: "package.tar",
+ sha256: Digest.sha256(of: Data(body.utf8)),
+ bases: [serving],
+ into: work.appending(path: "downloads"),
+ step: "test",
+ report: { reported.add($0.label) }
+ )
+
+ let label = try #require(reported.all.first)
+ #expect(reported.all.count == 1)
+ #expect(label.hasPrefix("Downloading from "))
+ #expect(label.contains(serving.lastPathComponent))
+ }
+}
diff --git a/app/Tests/NotProtonAppTests/PrefixPromptTests.swift b/app/Tests/NotProtonAppTests/PrefixPromptTests.swift
new file mode 100644
index 0000000..dedc212
--- /dev/null
+++ b/app/Tests/NotProtonAppTests/PrefixPromptTests.swift
@@ -0,0 +1,149 @@
+import Foundation
+import Testing
+
+@testable import NotProtonApp
+
+@Suite("Asking before a prefix goes")
+struct PrefixPromptTests {
+
+ private func prefix(_ appID: String, _ name: String?) -> WinePrefix {
+ WinePrefix(
+ appID: appID,
+ name: name,
+ library: SteamLibrary(root: URL(filePath: "/Users/tester/Library/Application Support/Steam")),
+ lastUsed: nil)
+ }
+
+ private var agent: WinePrefix { prefix("1574480", "Agent 64: Spies Never Die") }
+ private var ikaruga: WinePrefix { prefix("253750", "IKARUGA") }
+ private var orphan: WinePrefix { prefix("1649240", nil) }
+
+ @Test("One prefix is asked about by name")
+ func singleDeleteNamesTheGame() {
+ #expect(PrefixPrompt.deleteTitle([agent]) == "Delete the prefix for Agent 64: Spies Never Die?")
+ #expect(PrefixPrompt.deleteButton([agent]) == "Delete Prefix")
+ // A prefix whose game is gone still has to be askable about.
+ #expect(PrefixPrompt.deleteTitle([orphan]) == "Delete the prefix for App 1649240?")
+ }
+
+ // The Prefix menu shows the delete item greyed out with nothing selected, and it shows
+ // it by name, so an empty selection has to read as an action rather than as a count.
+ @Test("With nothing selected the delete item still reads as an action")
+ func emptySelectionReadsAsTheAction() {
+ #expect(PrefixPrompt.deleteButton([]) == "Delete Prefix")
+ #expect(PrefixPrompt.deleteTitle([]) == "Delete prefix?")
+ }
+
+ // Naming one of them and deleting all of them is how the wrong prefix gets thrown
+ // away, so more than one is counted instead.
+ @Test("Several prefixes are counted, not named")
+ func multipleDeleteCountsThem() {
+ let targets = [agent, ikaruga, orphan]
+ #expect(PrefixPrompt.deleteTitle(targets) == "Delete 3 prefixes?")
+ #expect(PrefixPrompt.deleteButton(targets) == "Delete 3 Prefixes")
+ }
+
+ @Test("Delete says the save data goes and asks for confirmation")
+ func deleteSaysSavesAreLost() {
+ let one = PrefixPrompt.deleteMessage([agent])
+ #expect(one == "This will DELETE the game's prefix. The game SAVE DATA inside the"
+ + " prefix WILL BE LOST. Are you sure you want to do this?")
+
+ let both = PrefixPrompt.deleteMessage([agent, ikaruga])
+ #expect(both == "This will DELETE the prefixes for 2 games. The game SAVE DATA inside"
+ + " them WILL BE LOST. Are you sure you want to do this?")
+ #expect(!both.contains("Agent 64"))
+ }
+
+ // Rebuild inits the prefix itself before the dialog closes, so deferring to Steam
+ // would be describing something that does not happen.
+ @Test("Rebuild does not claim Steam makes the prefix again")
+ func rebuildDescribesItself() {
+ let message = PrefixPrompt.rebuildMessage()
+ #expect(PrefixPrompt.rebuildTitle([ikaruga]) == "Rebuild the prefix for IKARUGA?")
+ #expect(PrefixPrompt.rebuildButton([ikaruga]) == "Rebuild Prefix")
+ #expect(message.contains("switching between Rosetta/FEX CrossOver"))
+ #expect(message.contains("You will not lose saves by using this tool."))
+ #expect(!message.contains("Steam"))
+ #expect(!message.contains("Continue"))
+ }
+
+ // A queued rebuild asks once for the whole selection, so it counts too.
+ @Test("A rebuild of several prefixes counts them instead of naming one")
+ func rebuildCountsTheSelection() {
+ #expect(PrefixPrompt.rebuildTitle([agent, ikaruga]) == "Rebuild 2 prefixes?")
+ #expect(PrefixPrompt.rebuildButton([agent, ikaruga]) == "Rebuild 2 Prefixes")
+ #expect(!PrefixPrompt.rebuildTitle([agent, ikaruga]).contains("Agent 64"))
+
+ // The menu bar item keeps its label while greyed out with nothing selected.
+ #expect(PrefixPrompt.rebuildTitle([]) == "Rebuild prefix?")
+ #expect(PrefixPrompt.rebuildButton([]) == "Rebuild Prefix")
+ }
+ @Test("The backup prompt names the game for one and the count for many")
+ func deleteBackupsPromptCounts() {
+ let one = backup(of: ikaruga, stamp: "20260101-120000")
+ let two = backup(of: ikaruga, stamp: "20260102-133000")
+
+ #expect(PrefixPrompt.deleteBackupsTitle([]) == "Delete backup?")
+ #expect(PrefixPrompt.deleteBackupsTitle([one]) == "Delete the backup for IKARUGA?")
+ #expect(PrefixPrompt.deleteBackupsTitle([one, two]) == "Delete 2 backups?")
+ #expect(PrefixPrompt.deleteBackupsButton([one]) == "Delete Backup")
+ #expect(PrefixPrompt.deleteBackupsButton([one, two]) == "Delete 2 Backups")
+ }
+
+ @Test("The rebuild prompt offers the backup choice and counts both ways")
+ func rebuildOffersTheBackupChoice() {
+ let targets = [agent, ikaruga, orphan]
+
+ #expect(PrefixPrompt.rebuildWithBackupButton([agent]) == "Back Up and Rebuild")
+ #expect(
+ PrefixPrompt.rebuildWithoutBackupButton([agent]) == "Rebuild Without Backing Up")
+ #expect(
+ PrefixPrompt.rebuildWithBackupButton(targets) == "Back Up and Rebuild 3 Prefixes")
+ #expect(
+ PrefixPrompt.rebuildWithoutBackupButton(targets)
+ == "Rebuild 3 Prefixes Without Backing Up")
+
+ }
+
+ @Test("Backing up names the game for one and counts many")
+ func backUpPromptCounts() {
+ let targets = [agent, ikaruga, orphan]
+
+ #expect(PrefixPrompt.backUpTitle([]) == "Back up prefix?")
+ #expect(PrefixPrompt.backUpTitle([agent]) == "Back up the prefix for Agent 64: Spies Never Die?")
+ #expect(PrefixPrompt.backUpTitle(targets) == "Back up 3 prefixes?")
+
+ #expect(PrefixPrompt.backUpButton([agent]) == "Back Up Prefix")
+ #expect(PrefixPrompt.backUpButton(targets) == "Back Up 3 Prefixes")
+
+ #expect(
+ PrefixPrompt.backUpMessage([agent])
+ == "Are you sure you want to back up this prefix?")
+ #expect(
+ PrefixPrompt.backUpMessage(targets)
+ == "Are you sure you want to back up these prefixes?")
+ }
+
+ private func backup(of prefix: WinePrefix, stamp: String) -> PrefixBackup {
+ PrefixBackup(
+ prefix: prefix,
+ url: prefix.root.appending(path: "pfx.previous-\(stamp)"),
+ taken: PrefixStore.backupClock().date(from: stamp),
+ bytes: 1024
+ )
+ }
+
+ @Test("The backup prompt asks once and names what is lost")
+ func deleteBackupsPromptReassures() {
+ let one = backup(of: ikaruga, stamp: "20260101-120000")
+ let two = backup(of: ikaruga, stamp: "20260102-133000")
+
+ #expect(PrefixPrompt.deleteBackupsMessage([one])
+ == "Are you sure you want to delete this backup? Any data in it will be lost.")
+ #expect(PrefixPrompt.deleteBackupsMessage()
+ == "Are you sure you want to delete this backup? Any data in it will be lost.")
+ #expect(PrefixPrompt.deleteBackupsMessage([one, two])
+ == "Are you sure you want to delete these 2 backups? Any data in them will be lost.")
+ }
+}
diff --git a/app/Tests/NotProtonAppTests/PrefixStoreTests.swift b/app/Tests/NotProtonAppTests/PrefixStoreTests.swift
new file mode 100644
index 0000000..92d313e
--- /dev/null
+++ b/app/Tests/NotProtonAppTests/PrefixStoreTests.swift
@@ -0,0 +1,453 @@
+import Foundation
+import Testing
+
+@testable import NotProtonApp
+
+@Suite("Prefix store")
+struct PrefixStoreTests {
+
+ private func tempDirectory() throws -> URL {
+ let dir = FileManager.default.temporaryDirectory.appending(path: "np-pfx-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ return dir
+ }
+
+ private func write(_ text: String, to url: URL) throws {
+ try FileManager.default.createDirectory(
+ at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data(text.utf8).write(to: url)
+ }
+
+ @Test("Every library path in the file is found, in order, without duplicates")
+ func readsLibraryPaths() throws {
+ let dir = try tempDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ // Shaped like the real file: nested blocks, tab separated, an apps block whose
+ // keys are numbers, and a second library on another volume.
+ let vdf = dir.appending(path: "libraryfolders.vdf")
+ try write(
+ """
+ "libraryfolders"
+ {
+ \t"0"
+ \t{
+ \t\t"path"\t\t"/Users/tester/Library/Application Support/Steam"
+ \t\t"label"\t\t""
+ \t\t"apps"
+ \t\t{
+ \t\t\t"480"\t\t"1906055"
+ \t\t}
+ \t}
+ \t"1"
+ \t{
+ \t\t"path"\t\t"/Volumes/External Games SSD/SteamLibrary"
+ \t\t"label"\t\t""
+ \t}
+ }
+ """, to: vdf)
+
+ let libraries = PrefixStore.libraries(vdf: vdf)
+ #expect(libraries.count == 2)
+ #expect(libraries.first?.root.path(percentEncoded: false) == "/Users/tester/Library/Application Support/Steam")
+ #expect(libraries.last?.root.lastPathComponent == "SteamLibrary")
+ // A library path with a space in it has to survive, since the external one has two.
+ #expect(libraries.last?.root.path(percentEncoded: false) == "/Volumes/External Games SSD/SteamLibrary")
+ #expect(libraries.last?.compatdata.lastPathComponent == "compatdata")
+ }
+
+ @Test("A missing or empty file still yields the default library")
+ func fallsBackToTheDefaultLibrary() throws {
+ let dir = try tempDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ let missing = PrefixStore.libraries(vdf: dir.appending(path: "nothing.vdf"))
+ #expect(missing.count == 1)
+ #expect(missing.first?.root == SupportPaths.Steam.userData)
+
+ let empty = dir.appending(path: "empty.vdf")
+ try write("\"libraryfolders\"\n{\n}\n", to: empty)
+ #expect(PrefixStore.libraries(vdf: empty).first?.root == SupportPaths.Steam.userData)
+ }
+
+ @Test("An entry without a pfx is not a prefix")
+ func skipsEntriesWithoutAPrefix() throws {
+ let dir = try tempDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let library = SteamLibrary(root: dir)
+
+ // Steam keeps a compatdata/0 with no pfx inside it. Listing that as a prefix
+ // would offer a delete and a winecfg for something that does not exist.
+ try FileManager.default.createDirectory(
+ at: library.compatdata.appending(path: "0"), withIntermediateDirectories: true)
+ try FileManager.default.createDirectory(
+ at: library.compatdata.appending(path: "1574480/pfx"), withIntermediateDirectories: true)
+ // A file named like an appid is not a directory and must not be walked.
+ try write("", to: library.compatdata.appending(path: "9999"))
+
+ let prefixes = PrefixStore.all(libraries: [library])
+ #expect(prefixes.map(\.appID) == ["1574480"])
+ }
+
+ @Test("A name comes from the library's own appmanifest, and its absence is not a failure")
+ func readsTheAppName() throws {
+ let dir = try tempDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let library = SteamLibrary(root: dir)
+
+ try FileManager.default.createDirectory(
+ at: library.compatdata.appending(path: "1574480/pfx"), withIntermediateDirectories: true)
+ try FileManager.default.createDirectory(
+ at: library.compatdata.appending(path: "1649240/pfx"), withIntermediateDirectories: true)
+ try write(
+ """
+ "AppState"
+ {
+ \t"appid"\t\t"1574480"
+ \t"name"\t\t"Agent 64: Spies Never Die"
+ }
+ """, to: library.steamapps.appending(path: "appmanifest_1574480.acf"))
+
+ let prefixes = PrefixStore.all(libraries: [library])
+ let named = prefixes.first { $0.appID == "1574480" }
+ let orphan = prefixes.first { $0.appID == "1649240" }
+
+ #expect(named?.name == "Agent 64: Spies Never Die")
+ #expect(named?.title == "Agent 64: Spies Never Die")
+ // A prefix outliving the game it belongs to is the case worth listing, not
+ // hiding, so no name has to be survivable.
+ #expect(orphan?.name == nil)
+ #expect(orphan?.title == "App 1649240")
+ }
+
+ @Test("Sizing a prefix stops at a symlink instead of walking through it")
+ func doesNotFollowLinksOutOfThePrefix() throws {
+ let dir = try tempDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let library = SteamLibrary(root: dir)
+
+ // CrossOver's template points Documents at the real home. Sizing that would tell the user
+ // a prefix costs everything in their home folder, which makes the warning worthless.
+ let outside = dir.appending(path: "outside-the-prefix")
+ try write("host file one", to: outside.appending(path: "one.txt"))
+ try write("host file two", to: outside.appending(path: "two.txt"))
+
+ let profile = library.compatdata.appending(path: "1574480/pfx/drive_c/users/crossover")
+ try write("in prefix", to: profile.appending(path: "AppData/Roaming/game/save.dat"))
+ try FileManager.default.createSymbolicLink(
+ at: profile.appending(path: "Documents"), withDestinationURL: outside)
+
+ let prefix = try #require(PrefixStore.all(libraries: [library]).first)
+ let usage = PrefixStore.usage(of: prefix)
+
+ // The one real file under the profile, and neither file behind the link.
+ #expect(usage.profileFiles == 1)
+ #expect(usage.bytes > 0)
+ }
+
+ @Test("Only the parked prefixes count as backups")
+ func backupsIgnoreEverythingElseInTheEntry() throws {
+ let dir = try tempDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let library = SteamLibrary(root: dir)
+ let fm = FileManager.default
+
+ let entry = library.compatdata.appending(path: "1574480")
+ for folder in ["pfx", "pfx.rebuild", "notproton-msync",
+ "pfx.previous-20260101-120000", "pfx.previous-20260102-133000"] {
+ try fm.createDirectory(
+ at: entry.appending(path: folder), withIntermediateDirectories: true)
+ }
+ try write("not a prefix", to: entry.appending(path: "pfx.previous-note.txt"))
+
+ let prefix = try #require(PrefixStore.all(libraries: [library]).first)
+
+ #expect(PrefixStore.backups(of: prefix).map(\.lastPathComponent)
+ == ["pfx.previous-20260101-120000", "pfx.previous-20260102-133000"])
+ }
+
+ @Test("Backing up a prefix copies it into a listed slot and leaves the prefix alone")
+ func backUpCopiesTheLivePrefix() throws {
+ let dir = try tempDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let prefix = try prefix(in: dir)
+ try write("save", to: prefix.pfx.appending(path: "user.reg"))
+ let taken = try #require(PrefixStore.backupClock().date(from: "20260101-120000"))
+
+ let slot = try PrefixTools.backUp(prefix, now: taken)
+
+ #expect(slot.lastPathComponent == "pfx.previous-20260101-120000")
+ #expect(PrefixStore.backups(of: prefix).map(\.lastPathComponent)
+ == ["pfx.previous-20260101-120000"])
+ #expect(try String(contentsOf: slot.appending(path: "user.reg"), encoding: .utf8) == "save")
+ #expect(
+ try String(contentsOf: prefix.pfx.appending(path: "user.reg"), encoding: .utf8)
+ == "save")
+ }
+
+ @Test("Backing up refuses a game that has never made a prefix")
+ func backUpRefusesAMissingPrefix() throws {
+ let dir = try tempDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let prefix = try prefix(in: dir)
+ try FileManager.default.removeItem(at: prefix.pfx)
+
+ let refusal = try #require(throws: StepFailure.self) { try PrefixTools.backUp(prefix) }
+ #expect(refusal.detail.hasPrefix(prefix.title))
+ #expect(refusal.detail.hasSuffix("."))
+ #expect(PrefixStore.backups(of: prefix).isEmpty)
+ }
+
+ @Test("A backup carries the time in its name back out as a date")
+ func backupDetailsReadTheStamp() throws {
+ let dir = try tempDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let library = SteamLibrary(root: dir)
+
+ let entry = library.compatdata.appending(path: "1574480")
+ try write("live", to: entry.appending(path: "pfx/drive_c/users/crossover/save.dat"))
+ try write("older", to: entry.appending(path: "pfx.previous-20260101-120000/user.reg"))
+ try write("newer", to: entry.appending(path: "pfx.previous-20260102-133000-2/user.reg"))
+
+ let prefix = try #require(PrefixStore.all(libraries: [library]).first)
+ let details = PrefixStore.backupDetails(of: prefix)
+
+ #expect(details.count == 2)
+ #expect(details.allSatisfy { $0.bytes > 0 })
+ #expect(details.map(\.prefix) == [prefix, prefix])
+
+ let clock = PrefixStore.backupClock()
+ #expect(details[0].taken == clock.date(from: "20260101-120000"))
+ #expect(details[1].taken == clock.date(from: "20260102-133000"))
+ #expect(PrefixStore.usage(of: prefix).profileFiles == 1)
+ }
+
+ @Test("A parked prefix with no readable stamp still lists, without a date")
+ func backupWithoutAStampHasNoDate() throws {
+ let dir = try tempDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let library = SteamLibrary(root: dir)
+
+ let entry = library.compatdata.appending(path: "1574480")
+ try write("live", to: entry.appending(path: "pfx/user.reg"))
+ try write("old", to: entry.appending(path: "pfx.previous/user.reg"))
+
+ let prefix = try #require(PrefixStore.all(libraries: [library]).first)
+ let details = PrefixStore.backupDetails(of: prefix)
+
+ #expect(details.count == 1)
+ #expect(details[0].taken == nil)
+ #expect(PrefixStore.backupDate(of: details[0].url) == nil)
+ }
+
+ @Test("A library on the boot volume is named by its folder alone")
+ func bootVolumeLibraryIsNotQualified() throws {
+ let dir = try tempDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ let library = PrefixStore.library(at: dir)
+ #expect(library.volume == nil)
+ #expect(library.displayName == dir.lastPathComponent)
+ #expect(PrefixStore.volumeName(of: dir) == nil)
+ }
+
+ @Test("A library on another drive is named by the drive alone")
+ func externalLibraryNamesTheDrive() {
+ let root = URL(filePath: "/Volumes/External Games SSD/SteamLibrary")
+ let library = SteamLibrary(root: root, volume: "External Games SSD")
+
+ // Every library folder Steam makes is called SteamLibrary, so naming it beside the
+ // drive spends the column on a word that is the same for every row.
+ #expect(library.displayName == "External Games SSD")
+ #expect(SteamLibrary(root: root).displayName == "SteamLibrary")
+ }
+
+ @Test("A prefix points at the game's install folder while the game is installed")
+ func findsTheInstallDirectory() throws {
+ let dir = try tempDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let library = SteamLibrary(root: dir)
+
+ try FileManager.default.createDirectory(
+ at: library.compatdata.appending(path: "1574480/pfx"), withIntermediateDirectories: true)
+ try write(
+ """
+ "AppState"
+ {
+ \t"appid"\t\t"1574480"
+ \t"installdir"\t\t"Agent 64"
+ }
+ """, to: library.steamapps.appending(path: "appmanifest_1574480.acf"))
+
+ let prefix = try #require(PrefixStore.all(libraries: [library]).first)
+ #expect(PrefixStore.installDirectory(of: prefix) == nil)
+
+ // The manifest can name a folder that is not there, which is what an uninstalled
+ // game with a leftover prefix looks like.
+ let installed = library.steamapps.appending(path: "common/Agent 64")
+ try FileManager.default.createDirectory(at: installed, withIntermediateDirectories: true)
+ #expect(
+ PrefixStore.installDirectory(of: prefix)?.path(percentEncoded: false)
+ == installed.path(percentEncoded: false))
+ }
+
+ // A prefix's ntdll, cut down to the two fields the arch is read out of: e_lfanew at
+ // 0x3c, and the machine word four bytes past the signature it points at.
+ private func writeNtdll(machine: UInt16?, in pfx: URL, lfanew: UInt32 = 0x40) throws {
+ var bytes = [UInt8](repeating: 0, count: 0x40)
+ withUnsafeBytes(of: lfanew.littleEndian) { bytes.replaceSubrange(0x3c..<0x40, with: $0) }
+ if let machine {
+ bytes += [0x50, 0x45, 0x00, 0x00]
+ bytes += withUnsafeBytes(of: machine.littleEndian) { Array($0) }
+ }
+ let dll = pfx.appending(path: "drive_c/windows/system32/ntdll.dll")
+ try FileManager.default.createDirectory(
+ at: dll.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data(bytes).write(to: dll)
+ }
+
+ private func prefix(in dir: URL) throws -> WinePrefix {
+ let library = SteamLibrary(root: dir)
+ try FileManager.default.createDirectory(
+ at: library.compatdata.appending(path: "1574480/pfx"), withIntermediateDirectories: true)
+ return try #require(PrefixStore.all(libraries: [library]).first)
+ }
+
+ // The one signal on disk that separates the two tools. system.reg says #arch=win64 for both
+ // and carries no PROCESSOR_ARCHITECTURE, so the wrong flavor is invisible without a PE read.
+ @Test("A prefix names the compatibility tool that built it through its own ntdll")
+ func readsPrefixArch() throws {
+ let dir = try tempDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let prefix = try prefix(in: dir)
+
+ for (machine, expected) in [
+ (UInt16(0xaa64), PrefixArch.arm64),
+ (UInt16(0x8664), PrefixArch.x86_64),
+ (UInt16(0x014c), PrefixArch.i386),
+ ] {
+ try writeNtdll(machine: machine, in: prefix.pfx)
+ #expect(PrefixStore.arch(of: prefix) == expected)
+ }
+ }
+
+ // Every one of these is a prefix nothing can be said about, and a rebuild must not be
+ // demanded on the strength of a header that was never read.
+ @Test("An unreadable header is no arch rather than a wrong one")
+ func unreadableArchIsNil() throws {
+ let dir = try tempDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let prefix = try prefix(in: dir)
+
+ // Never booted, so wineboot has installed nothing.
+ #expect(PrefixStore.arch(of: prefix) == nil)
+
+ // A machine type wine does not build for.
+ try writeNtdll(machine: 0x1234, in: prefix.pfx)
+ #expect(PrefixStore.arch(of: prefix) == nil)
+
+ // e_lfanew pointing past the end of the file.
+ try writeNtdll(machine: 0xaa64, in: prefix.pfx, lfanew: 0x40000)
+ #expect(PrefixStore.arch(of: prefix) == nil)
+
+ // A DOS header with no PE header behind it.
+ try writeNtdll(machine: nil, in: prefix.pfx)
+ #expect(PrefixStore.arch(of: prefix) == nil)
+
+ // Not a PE at all.
+ let dll = prefix.pfx.appending(path: "drive_c/windows/system32/ntdll.dll")
+ try write("just text", to: dll)
+ #expect(PrefixStore.arch(of: prefix) == nil)
+
+ // Six readable bytes where the PE header should be. The length checks pass, so only the
+ // signature stands between a half written file and a word read out of whatever is there.
+ var stub = [UInt8](repeating: 0, count: 0x40)
+ withUnsafeBytes(of: UInt32(0x40).littleEndian) { stub.replaceSubrange(0x3c..<0x40, with: $0) }
+ stub += [0x4d, 0x5a, 0x00, 0x00, 0x64, 0x86]
+ try Data(stub).write(to: dll)
+ #expect(PrefixStore.arch(of: prefix) == nil)
+ }
+
+ @Test("An idle prefix is not reported as in use")
+ func idlePrefixIsNotInUse() throws {
+ let dir = try tempDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let library = SteamLibrary(root: dir)
+ try FileManager.default.createDirectory(
+ at: library.compatdata.appending(path: "1574480/pfx"), withIntermediateDirectories: true)
+
+ let prefix = try #require(PrefixStore.all(libraries: [library]).first)
+ // A freshly made directory has never had a wineserver, so the socket directory
+ // named after its device and inode cannot exist.
+ #expect(PrefixStore.serverDirectory(of: prefix) != nil)
+ #expect(PrefixStore.isInUse(prefix) == false)
+ }
+
+ // Everything below needs the socket directory to be there, since a prefix whose directory
+ // is absent is answered before lsof is reached at all.
+ private func prefixWithServerDirectory() throws -> (WinePrefix, URL, URL) {
+ let dir = try tempDirectory()
+ let library = SteamLibrary(root: dir)
+ try FileManager.default.createDirectory(
+ at: library.compatdata.appending(path: "1574480/pfx"), withIntermediateDirectories: true)
+ let prefix = try #require(PrefixStore.all(libraries: [library]).first)
+ let root = dir.appending(path: "wine-sockets")
+ let socket = try #require(PrefixStore.serverDirectory(of: prefix, root: root))
+ try FileManager.default.createDirectory(at: socket, withIntermediateDirectories: true)
+ return (prefix, root, dir)
+ }
+
+ private func stubLsof(in dir: URL, body: String) throws -> String {
+ let path = dir.appending(path: "lsof")
+ try Data("#!/bin/sh\n\(body)\n".utf8).write(to: path)
+ try FileManager.default.setAttributes(
+ [.posixPermissions: 0o755], ofItemAtPath: path.path(percentEncoded: false))
+ return path.path(percentEncoded: false)
+ }
+
+ @Test("A prefix whose socket directory is held open is reported as in use")
+ func heldPrefixIsInUse() throws {
+ let (prefix, root, dir) = try prefixWithServerDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let held = try #require(PrefixStore.serverDirectory(of: prefix, root: root))
+ .appending(path: "socket")
+ try Data("s".utf8).write(to: held)
+ let handle = try FileHandle(forReadingFrom: held)
+ defer { try? handle.close() }
+
+ #expect(PrefixStore.isInUse(prefix, root: root))
+ }
+
+ // Every one of these used to answer that the prefix was free, which is the answer that
+ // deletes a prefix out from under a running game.
+ @Test("lsof failing to answer is not read as the prefix being free")
+ func anUnusableLsofIsNotReadAsFree() throws {
+ let (prefix, root, dir) = try prefixWithServerDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ // Nothing to run at all.
+ #expect(PrefixStore.isInUse(
+ prefix, root: root, lsof: dir.appending(path: "absent").path(percentEncoded: false)))
+
+ // Ran, said nothing, complained.
+ #expect(PrefixStore.isInUse(
+ prefix, root: root,
+ lsof: try stubLsof(in: dir, body: "echo trouble >&2; exit 1")))
+
+ // Ran, exited as lsof does when it finds nothing, but left its output open.
+ #expect(PrefixStore.isInUse(
+ prefix, root: root,
+ lsof: try stubLsof(in: dir, body: "sleep 3 & exit 1"),
+ drainTimeout: .milliseconds(200)))
+ }
+
+ // The other half of the same decision: a real lsof reporting nothing has to stay a no, or
+ // no prefix could ever be rebuilt.
+ @Test("An idle socket directory is still reported as free")
+ func anIdleSocketDirectoryIsFree() throws {
+ let (prefix, root, dir) = try prefixWithServerDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ #expect(PrefixStore.isInUse(prefix, root: root) == false)
+ }
+}
diff --git a/app/Tests/NotProtonAppTests/PrefixToolsTests.swift b/app/Tests/NotProtonAppTests/PrefixToolsTests.swift
new file mode 100644
index 0000000..1cc8ac5
--- /dev/null
+++ b/app/Tests/NotProtonAppTests/PrefixToolsTests.swift
@@ -0,0 +1,1352 @@
+import Foundation
+import Testing
+
+@testable import NotProtonApp
+
+@Suite("Prefix tools")
+struct PrefixToolsTests {
+
+ // The launch path is shell and this is Swift, so the rules it carries are read back
+ // out of compat_run.sh rather than restated here.
+ private static func compatSource() throws -> String {
+ let repoRoot = URL(filePath: #filePath)
+ .deletingLastPathComponent() // NotProtonAppTests
+ .deletingLastPathComponent() // Tests
+ .deletingLastPathComponent() // app
+ .deletingLastPathComponent() // repo root
+ return try String(
+ contentsOf: repoRoot.appending(path: "dylib/feats/compat_run.sh"), encoding: .utf8)
+ }
+
+ private func samplePrefix() -> WinePrefix {
+ WinePrefix(
+ appID: "1574480",
+ name: "Agent 64: Spies Never Die",
+ library: SteamLibrary(root: URL(filePath: "/Users/tester/Library/Application Support/Steam")),
+ lastUsed: nil
+ )
+ }
+
+ @Test("The runner variables are the ones RUN_SCRIPT exports")
+ func matchesRunScript() throws {
+ // A tool under a stale copy of the runner layout writes registry keys the game side then
+ // reads under different rules, and nothing else would notice the drift.
+ let source = try Self.compatSource()
+
+ // Written in compat_run.sh as: export WINELOADER="$CX_ROOT/lib/wine/..."
+ func exported(_ name: String) throws -> String {
+ let pattern = #"export \#(name)="([^"]*)""#
+ let regex = try Regex(pattern)
+ let match = try #require(
+ source.firstMatch(of: regex), "compat_run.sh no longer exports \(name)")
+ return String(match[1].substring ?? "")
+ }
+
+ let home = try exported("CX_HOME").replacingOccurrences(
+ of: "$HOME", with: SupportPaths.home.path(percentEncoded: false))
+
+ // Both sides resolve the loader and wineserver from whichever unix directory the runner
+ // has, so the check is that they pick the same pair for the same tree.
+ let fm = FileManager.default
+ for (arch, loaderTail, serverName) in [
+ ("aarch64-unix", "wine.app/Contents/MacOS/wine", "wineserver-arm64"),
+ ("x86_64-unix", "wine", "wineserver-x86"),
+ ] {
+ let runner = URL(filePath: NSTemporaryDirectory())
+ .appending(path: "notproton-layout-\(UUID().uuidString)")
+ defer { try? fm.removeItem(at: runner) }
+
+ for path in ["lib/wine/\(arch)/\(loaderTail)", "CrossOver-Hosted Application/\(serverName)"] {
+ let file = runner.appending(path: path)
+ try fm.createDirectory(
+ at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data().write(to: file)
+ try fm.setAttributes(
+ [.posixPermissions: 0o755], ofItemAtPath: file.path(percentEncoded: false))
+ }
+
+ let layout = PrefixTools.layout(runner: runner)
+ #expect(layout.loader == runner.appending(path: "lib/wine/\(arch)/\(loaderTail)"))
+ #expect(layout.server == runner.appending(path: "CrossOver-Hosted Application/\(serverName)"))
+
+ // The shapes the script reaches for, which is what would drift independently.
+ #expect(source.contains("$wine_unix/\(loaderTail)"))
+ #expect(source.contains(serverName))
+
+ let environment = PrefixTools.environment(prefix: samplePrefix(), runner: runner)
+ let dllPath = try exported("WINEDLLPATH")
+ .replacingOccurrences(of: "$CX_ROOT", with: runner.path(percentEncoded: false))
+ .replacingOccurrences(of: "$wine_unix", with: layout.unixDir.path(percentEncoded: false))
+
+ #expect(environment["WINEDLLPATH"] == dllPath, "WINEDLLPATH drifted from RUN_SCRIPT")
+ #expect(environment["WINELOADER"] == layout.loader.path(percentEncoded: false))
+ #expect(environment["WINESERVER"] == layout.server.path(percentEncoded: false))
+ #expect(environment["CX_HOME"] == home)
+
+ // WINELOADER is what launch and recreate actually invoke, so the two have to
+ // agree with each other as well as with the script.
+ #expect(environment["WINELOADER"]
+ == PrefixTools.loader(runner: runner).path(percentEncoded: false))
+ }
+ }
+
+ @Test("The prefix and the sync backend are set, and the game only variables are not")
+ func setsPrefixAndBackend() {
+ let prefix = samplePrefix()
+ let environment = PrefixTools.environment(prefix: prefix)
+
+ #expect(environment["WINEPREFIX"] == prefix.pfx.path(percentEncoded: false))
+ #expect(environment["WINEPREFIX"]?.hasSuffix("/compatdata/1574480/pfx") == true)
+ #expect(environment["WINEMSYNC"] == PrefixTools.syncBackend(prefix: prefix))
+ // Derived rather than spelled out, because the support directory hangs off the
+ // running account's home and a literal here would only ever pass on one machine.
+ let runnerBin = SupportPaths.currentRunner.appending(path: "bin")
+ .path(percentEncoded: false)
+ #expect(environment["PATH"]?.hasPrefix(runnerBin + ":") == true)
+
+ // Redirecting steamclient to lsteamclient means something for a game, not for a
+ // configuration window, where it would apply game override rules to what it touches.
+ #expect(environment["WINEDLLOVERRIDES"] == nil)
+ }
+
+ @Test("The sync backend is whatever the last launch recorded")
+ func readsRecordedBackend() throws {
+ let root = URL(filePath: NSTemporaryDirectory())
+ .appending(path: "np-msync-\(UUID().uuidString)")
+ let library = SteamLibrary(root: root)
+ let prefix = WinePrefix(appID: "480", name: nil, library: library, lastUsed: nil)
+ try FileManager.default.createDirectory(at: prefix.root, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ #expect(PrefixTools.syncBackend(prefix: prefix) == "0")
+
+ let marker = prefix.root.appending(path: "notproton-msync")
+ for (recorded, expected) in [("1", "1"), ("0", "0"), ("1\n", "1"), ("", "0"), ("yes", "0")] {
+ try recorded.write(to: marker, atomically: true, encoding: .utf8)
+ #expect(
+ PrefixTools.syncBackend(prefix: prefix) == expected,
+ "recorded \(recorded.debugDescription)")
+ #expect(PrefixTools.environment(prefix: prefix)["WINEMSYNC"] == expected)
+ }
+ }
+
+ @Test("Every tool is offered under the name the loader resolves")
+ func toolNamesAreBare() {
+ #expect(WineTool.allCases.map(\.rawValue) == ["winecfg", "regedit", "taskmgr"])
+ for tool in WineTool.allCases {
+ #expect(!tool.rawValue.contains("/"), "\(tool) would not resolve as a builtin")
+ #expect(!tool.rawValue.hasSuffix(".exe"))
+ #expect(!tool.label.isEmpty)
+ }
+ }
+
+ @Test("Without a runner, opening a tool says so instead of failing at exec")
+ func refusesWithoutARunner() throws {
+ let dir = FileManager.default.temporaryDirectory.appending(path: "np-norunner-\(UUID().uuidString)")
+ defer { try? FileManager.default.removeItem(at: dir) }
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+
+ #expect(throws: StepFailure.self) {
+ try PrefixTools.launch(.winecfg, in: samplePrefix(), runner: dir)
+ }
+ #expect(throws: StepFailure.self) {
+ try PrefixTools.recreate(samplePrefix(), runner: dir)
+ }
+ }
+
+ // An msi is data for msiexec rather than a program, so the loader would start nothing.
+ // Refused here rather than inside wine, where the reason goes to a log nobody opens.
+ @Test("A picked file is run the way its kind has to be run")
+ func windowsProgramsAreInvokedByKind() {
+ #expect(PrefixTools.arguments(for: URL(filePath: "/games/Agent 64/game.exe")) == ["/games/Agent 64/game.exe"])
+ #expect(PrefixTools.arguments(for: URL(filePath: "/games/setup.EXE")) == ["/games/setup.EXE"])
+ #expect(PrefixTools.arguments(for: URL(filePath: "/games/patch.bat")) == ["/games/patch.bat"])
+ #expect(PrefixTools.arguments(for: URL(filePath: "/games/patch.cmd")) == ["/games/patch.cmd"])
+ #expect(PrefixTools.arguments(for: URL(filePath: "/games/vc.msi")) == ["msiexec", "/i", "/games/vc.msi"])
+
+ #expect(PrefixTools.arguments(for: URL(filePath: "/games/readme.txt")) == nil)
+ #expect(PrefixTools.arguments(for: URL(filePath: "/games/game.app")) == nil)
+ #expect(PrefixTools.arguments(for: URL(filePath: "/games/game")) == nil)
+ }
+
+ @Test("Running a picked program refuses before exec when it cannot work")
+ func runRefusesEarly() throws {
+ let dir = FileManager.default.temporaryDirectory.appending(path: "np-run-\(UUID().uuidString)")
+ defer { try? FileManager.default.removeItem(at: dir) }
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ let exe = dir.appending(path: "setup.exe")
+ try Data("MZ".utf8).write(to: exe)
+
+ // No runner, which is the same refusal opening a tool gets.
+ #expect(throws: StepFailure.self) {
+ try PrefixTools.run(exe, in: samplePrefix(), runner: dir)
+ }
+ #expect(throws: StepFailure.self) {
+ try PrefixTools.run(dir.appending(path: "gone.exe"), in: samplePrefix())
+ }
+ #expect(throws: StepFailure.self) {
+ try PrefixTools.run(URL(filePath: "/bin/ls"), in: samplePrefix())
+ }
+ }
+
+ @Test("Every kind offered by the file picker is a kind that can be run")
+ func pickerTypesMatchWhatRuns() {
+ let extensions = PrefixTools.runnableTypes.compactMap(\.preferredFilenameExtension)
+ #expect(!extensions.isEmpty)
+ for extension_ in extensions {
+ #expect(
+ PrefixTools.arguments(for: URL(filePath: "/games/thing.\(extension_)")) != nil,
+ "the picker offers \(extension_) but nothing runs it")
+ }
+ }
+
+ // The same rule is read once in shell and once here, so a word that drifted on one side
+ // leaves the pane calling a prefix fine that the launcher will not start, or the reverse.
+ @Test("The launcher and the pane read the prefix arch the same way")
+ func archRuleMatchesRunScript() throws {
+ let source = try Self.compatSource()
+
+ // Written in compat.c as: aarch64-unix) want=aa64 ;;
+ func wanted(_ pattern: String) throws -> PrefixArch? {
+ let match = try #require(
+ source.firstMatch(of: try Regex(pattern)), "compat.c no longer sets \(pattern)")
+ let word = try #require(UInt16(String(match[1].substring ?? ""), radix: 16))
+ return PrefixArch(machine: word)
+ }
+
+ #expect(try wanted(#"aarch64-unix\) want=(\w+)"#) == .arm64)
+ #expect(try wanted(#"\*\) want=(\w+)"#) == .x86_64)
+
+ // And both read it out of the same file.
+ #expect(source.contains(#"drive_c/windows/system32/ntdll.dll"#))
+ }
+
+ // Both names come off the same machine words the arch rule uses, so a wrong word or the
+ // two swapped tells the player to keep the build they have and rebuild for the other.
+ @Test("The dialog names the build that made the prefix and the one installed now")
+ func dialogNamesBothBuilds() throws {
+ let source = try Self.compatSource()
+
+ // Written in compat_run.sh as: aa64) printf 'the FEX build of CrossOver' ;;
+ func name(of word: String) throws -> String {
+ let match = try #require(
+ source.firstMatch(of: try Regex("\(word)\\) printf '([^']+)'")),
+ "compat_run.sh no longer names \(word)")
+ return String(match[1].substring ?? "")
+ }
+
+ // The machine word each loader wants, taken from the rule rather than restated.
+ func wanted(_ pattern: String) throws -> String {
+ let match = try #require(source.firstMatch(of: try Regex(pattern)))
+ return String(match[1].substring ?? "")
+ }
+
+ #expect(try name(of: wanted(#"aarch64-unix\) want=(\w+)"#)).contains("FEX"))
+ #expect(try name(of: wanted(#"\*\) want=(\w+)"#)).contains("Rosetta"))
+
+ // A prefix that reads as 32 bit is neither build, so it gets no build name.
+ let fallback = try #require(source.firstMatch(of: /\*\) printf '([^']+)'/))
+ let vague = String(fallback.1)
+ #expect(!vague.contains("FEX") && !vague.contains("Rosetta"))
+
+ // What made the prefix is named first and blamed, what is installed second.
+ let built = try #require(source.range(of: #"$(tool_name "$have")"#))
+ let installed = try #require(source.range(of: #"$(tool_name "$want")"#))
+ #expect(built.lowerBound < installed.lowerBound)
+ }
+
+ // A newline inside an AppleScript string literal is a syntax error, so osascript writes
+ // nothing and the launch still stops, with no dialog ever reaching the screen to say why.
+ @Test("The alert reaches osascript as one line")
+ func alertIsOneLine() throws {
+ let source = try Self.compatSource()
+ let opening = try #require(source.range(of: "display alert"))
+ let closing = try #require(source.range(of: #"" as critical"#))
+ #expect(!source[opening.lowerBound..<closing.lowerBound].contains("\n"))
+ }
+
+ // Steam runs the tool twice for one launch and both passes reach the refusal, so an
+ // ungated alert shows twice. Only the alert is gated; the evaluator pass still has to stop.
+ @Test("Only the pass that launches the game shows the alert")
+ func alertSkipsTheEvaluatorPass() throws {
+ let source = try Self.compatSource()
+ let gate = try #require(source.range(of: #"if [ "$verb" != run ]; then"#))
+ let alert = try #require(source.range(of: "display alert"))
+ let closing = try #require(
+ source.range(of: " fi\n", range: alert.upperBound..<source.endIndex))
+ let refusal = try #require(source.range(of: " exit 1\n"))
+
+ #expect(gate.upperBound < alert.lowerBound)
+ #expect(alert.upperBound < closing.lowerBound)
+ #expect(closing.upperBound <= refusal.lowerBound)
+ }
+
+ // Whichever unix tree the runner has decides the loader, and so decides the arch of
+ // every windows file wineboot then installs. The two have to be read by one rule.
+ @Test("The arch a runner builds prefixes for follows the loader it resolves")
+ func prefixArchFollowsTheLoader() throws {
+ let fm = FileManager.default
+ for (arch, loaderTail, serverName, expected) in [
+ ("aarch64-unix", "wine.app/Contents/MacOS/wine", "wineserver-arm64", PrefixArch.arm64),
+ ("x86_64-unix", "wine", "wineserver-x86", PrefixArch.x86_64),
+ ] {
+ let runner = FileManager.default.temporaryDirectory
+ .appending(path: "np-arch-\(UUID().uuidString)")
+ defer { try? fm.removeItem(at: runner) }
+ for path in ["lib/wine/\(arch)/\(loaderTail)", "CrossOver-Hosted Application/\(serverName)"] {
+ let file = runner.appending(path: path)
+ try fm.createDirectory(
+ at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data().write(to: file)
+ try fm.setAttributes([.posixPermissions: 0o755], ofItemAtPath: file.path(percentEncoded: false))
+ }
+ #expect(PrefixTools.prefixArch(runner: runner) == expected)
+ }
+ }
+
+ // Stands in for wineboot --init, the one part of a rebuild a test cannot run: the windows
+ // tree, empty profile stubs, the link out to the real home. lock makes the rename fail.
+ private func fakeRunner(
+ in dir: URL, home: URL, exit status: Int = 0, lock: Bool = false, extra: String = ":"
+ ) throws -> URL {
+ let runner = dir.appending(path: "runner")
+ let loader = runner.appending(path: "lib/wine/x86_64-unix/wine")
+ try FileManager.default.createDirectory(
+ at: loader.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data("""
+ #!/bin/sh
+ [ "$1" = wineboot ] || exit 64
+ mkdir -p "$WINEPREFIX/drive_c/windows/system32" \\
+ "$WINEPREFIX/drive_c/Program Files" \\
+ "$WINEPREFIX/drive_c/Program Files (x86)" \\
+ "$WINEPREFIX/drive_c/ProgramData" \\
+ "$WINEPREFIX/drive_c/users/crossover/AppData" \\
+ "$WINEPREFIX/drive_c/users/crossover/Desktop"
+ printf fresh > "$WINEPREFIX/drive_c/windows/system32/ntdll.dll"
+ printf template > "$WINEPREFIX/drive_c/users/crossover/AppData/wine.ini"
+ printf template > "$WINEPREFIX/drive_c/users/crossover/AppData/fresh.ini"
+ printf 'fresh user' > "$WINEPREFIX/user.reg"
+ printf 'fresh system' > "$WINEPREFIX/system.reg"
+ ln -s "\(home.path(percentEncoded: false))" "$WINEPREFIX/drive_c/users/crossover/Documents"
+ \(extra)
+ \(lock ? "chflags uchg \"$WINEPREFIX\"" : ":")
+ exit \(status)
+ """.utf8).write(to: loader)
+ try FileManager.default.setAttributes(
+ [.posixPermissions: 0o755], ofItemAtPath: loader.path(percentEncoded: false))
+ return runner
+ }
+
+ // A prefix as a game leaves it: saves under the profile, a link out to the home folder,
+ // and files the game's own installer put in windows and Program Files.
+ private func usedPrefix(in dir: URL, home: URL) throws -> WinePrefix {
+ let library = SteamLibrary(root: dir)
+ let pfx = library.compatdata.appending(path: "1574480/pfx")
+ let fm = FileManager.default
+ for path in ["drive_c/windows/system32", "drive_c/users/crossover/AppData/Roaming/game",
+ "drive_c/Program Files/redist"] {
+ try fm.createDirectory(at: pfx.appending(path: path), withIntermediateDirectories: true)
+ }
+ try Data("stale".utf8).write(to: pfx.appending(path: "drive_c/windows/system32/ntdll.dll"))
+ try Data("redist".utf8).write(to: pfx.appending(path: "drive_c/windows/vcruntime.dll"))
+ try Data("save".utf8)
+ .write(to: pfx.appending(path: "drive_c/users/crossover/AppData/Roaming/game/save.dat"))
+ try Data("installed".utf8).write(to: pfx.appending(path: "drive_c/Program Files/redist/thing.dll"))
+ try Data("mine".utf8).write(to: pfx.appending(path: "user.reg"))
+ try Data("stale system".utf8).write(to: pfx.appending(path: "system.reg"))
+ try fm.createSymbolicLink(
+ at: pfx.appending(path: "drive_c/users/crossover/Documents"), withDestinationURL: home)
+ try Data("0".utf8).write(to: library.compatdata.appending(path: "1574480/notproton-msync"))
+ return try #require(PrefixStore.all(libraries: [library]).first)
+ }
+
+ // Why a rebuild is offered instead of a delete: the arch specific half only arrives with
+ // the template, while the profile has nothing arch specific and is what a player misses.
+ @Test("A rebuild keeps the Windows user profile and replaces everything else")
+ func rebuildKeepsTheProfile() throws {
+ let fm = FileManager.default
+ let dir = fm.temporaryDirectory.appending(path: "np-rebuild-\(UUID().uuidString)")
+ defer { try? fm.removeItem(at: dir) }
+ let home = dir.appending(path: "home/Documents")
+ try fm.createDirectory(at: home, withIntermediateDirectories: true)
+ try Data("mine".utf8).write(to: home.appending(path: "letter.txt"))
+
+ let prefix = try usedPrefix(in: dir, home: home)
+ try PrefixTools.recreate(prefix, runner: try fakeRunner(in: dir, home: home))
+
+ func text(_ path: String) -> String? {
+ try? String(contentsOf: prefix.pfx.appending(path: path), encoding: .utf8)
+ }
+
+ // Kept. HKCU comes over with the profile it belongs to, because a game keeps its
+ // settings and sometimes its progress there.
+ #expect(text("drive_c/users/crossover/AppData/Roaming/game/save.dat") == "save")
+ #expect(text("user.reg") == "mine")
+
+ // HKLM does not, so the record of what is installed matches the files that are
+ // actually there and the next launch reinstalls what went with the old tree.
+ #expect(text("system.reg") == "fresh system")
+
+ // Replaced, both the file the arch is read from and what an installer left beside it.
+ #expect(text("drive_c/windows/system32/ntdll.dll") == "fresh")
+ #expect(text("drive_c/windows/vcruntime.dll") == nil)
+ #expect(text("drive_c/Program Files/redist/thing.dll") == nil)
+
+ // Inside the prefix, so the folder Steam syncs is the folder the game reads. The home
+ // folder the template used to point at keeps what is in it and is no longer reached.
+ let inside = prefix.pfx.resolvingSymlinksInPath().path(percentEncoded: false)
+ let documents = prefix.pfx.appending(path: "drive_c/users/steamuser/Documents")
+ #expect(documents.resolvingSymlinksInPath().path(percentEncoded: false).hasPrefix(inside))
+ #expect(text("drive_c/users/crossover/Documents/letter.txt") == nil)
+ #expect(fm.fileExists(atPath: home.appending(path: "letter.txt").path(percentEncoded: false)))
+
+ #expect(!fm.fileExists(
+ atPath: prefix.root.appending(path: "pfx.rebuild").path(percentEncoded: false)))
+ #expect(fm.fileExists(atPath: prefix.root.appending(path: "notproton-msync").path(percentEncoded: false)))
+
+ let kept = try #require(PrefixStore.backups(of: prefix).first)
+ #expect(PrefixStore.backups(of: prefix).count == 1)
+ #expect(try String(
+ contentsOf: kept.appending(path: "drive_c/users/crossover/AppData/Roaming/game/save.dat"),
+ encoding: .utf8) == "save")
+ }
+
+ // A prefix whose Documents is a real folder has the game's saves sitting in it. They come
+ // across into the profile rather than being left behind or pushed out to the home folder.
+ @Test("A real folder on the old side is carried into the prefix")
+ func linksSurviveARealFolder() throws {
+ let fm = FileManager.default
+ let dir = fm.temporaryDirectory.appending(path: "np-rebuild-link-\(UUID().uuidString)")
+ defer { try? fm.removeItem(at: dir) }
+ let home = dir.appending(path: "home/Documents")
+ try fm.createDirectory(at: home, withIntermediateDirectories: true)
+
+ let prefix = try usedPrefix(in: dir, home: home)
+ let documents = prefix.pfx.appending(path: "drive_c/users/crossover/Documents")
+ try fm.removeItem(at: documents)
+ try fm.createDirectory(at: documents, withIntermediateDirectories: true)
+ try Data("stale".utf8).write(to: documents.appending(path: "letter.txt"))
+
+ try PrefixTools.recreate(prefix, runner: try fakeRunner(in: dir, home: home))
+
+ let carried = prefix.pfx.appending(path: "drive_c/users/steamuser/Documents/letter.txt")
+ #expect(try String(contentsOf: carried, encoding: .utf8) == "stale")
+ #expect(!fm.fileExists(atPath: home.appending(path: "letter.txt").path(percentEncoded: false)))
+ }
+
+ // Two real profile directories with a save in each. Carrying them a name at a time emptied
+ // whichever the walk reached second, and which that was went by directory order.
+ @Test("A rebuild keeps both profiles of a prefix that has them side by side")
+ func rebuildKeepsBothProfiles() throws {
+ let fm = FileManager.default
+ let dir = URL(filePath: NSTemporaryDirectory()).appending(path: UUID().uuidString)
+ defer { try? fm.removeItem(at: dir) }
+ let home = dir.appending(path: "home")
+ try fm.createDirectory(at: home, withIntermediateDirectories: true)
+ let runner = try fakeRunner(in: dir, home: home)
+ let prefix = try usedPrefix(in: dir, home: home)
+
+ let beside = prefix.pfx.appending(path: "drive_c/users/steamuser/AppData/LocalLow/other")
+ try fm.createDirectory(at: beside, withIntermediateDirectories: true)
+ try Data("theirs".utf8).write(to: beside.appending(path: "save.txt"))
+
+ try PrefixTools.recreate(prefix, runner: runner)
+
+ let profile = prefix.pfx.appending(path: "drive_c/users/steamuser")
+ func text(_ path: String) -> String? {
+ try? String(contentsOf: profile.appending(path: path), encoding: .utf8)
+ }
+ #expect(text("AppData/Roaming/game/save.dat") == "save")
+ #expect(text("AppData/LocalLow/other/save.txt") == "theirs")
+ }
+
+ // The merge keeps whichever copy the walk reaches first, never the newer date: a cloud
+ // download is stamped when it arrives. crossover is the profile the game wrote under.
+ @Test("Which of two profiles' copies survives does not turn on its date")
+ func rebuildResolvesAProfileCollisionTheSameWayRoundEitherWay() throws {
+ let shared = "AppData/Roaming/game/save.dat"
+ for newest in ["crossover", "steamuser"] {
+ let fm = FileManager.default
+ let dir = URL(filePath: NSTemporaryDirectory()).appending(path: UUID().uuidString)
+ defer { try? fm.removeItem(at: dir) }
+ let home = dir.appending(path: "home")
+ try fm.createDirectory(at: home, withIntermediateDirectories: true)
+ let runner = try fakeRunner(in: dir, home: home)
+ let prefix = try usedPrefix(in: dir, home: home)
+ let users = prefix.pfx.appending(path: "drive_c/users")
+
+ let beside = users.appending(path: "steamuser/\(shared)")
+ try fm.createDirectory(
+ at: beside.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data("steamuser".utf8).write(to: beside)
+ try Data("crossover".utf8).write(to: users.appending(path: "crossover/\(shared)"))
+ // Stamped rather than written in order, because the copy carries the date with it
+ // and the walk decides nothing.
+ for name in ["crossover", "steamuser"] {
+ let when = Date(timeIntervalSince1970: name == newest ? 2_000_000 : 1_000_000)
+ try fm.setAttributes(
+ [.modificationDate: when],
+ ofItemAtPath: users.appending(path: "\(name)/\(shared)")
+ .path(percentEncoded: false))
+ }
+
+ try PrefixTools.recreate(prefix, runner: runner)
+
+ let carried = users.appending(path: "steamuser/\(shared)")
+ #expect(try String(contentsOf: carried, encoding: .utf8) == "crossover",
+ "the answer moved when \(newest) was made the newer copy")
+ }
+ }
+
+ // merge_user_dir in dylib/feats/compat_run.sh only copies into directories not already
+ // there, since one save directory holding two sessions may make no sense. Losers are parked.
+ @Test("A save directory reached more than once is carried from one place and parked from the rest")
+ func rebuildTakesOneInstanceOfASaveDirectory() throws {
+ let fm = FileManager.default
+ let dir = URL(filePath: NSTemporaryDirectory()).appending(path: UUID().uuidString)
+ defer { try? fm.removeItem(at: dir) }
+ let home = dir.appending(path: "home")
+ try fm.createDirectory(at: home, withIntermediateDirectories: true)
+ let runner = try fakeRunner(in: dir, home: home)
+ let prefix = try usedPrefix(in: dir, home: home)
+ let users = prefix.pfx.appending(path: "drive_c/users")
+
+ for (path, mark) in [
+ ("crossover/AppData/Roaming/Slot", "crossover"),
+ ("steamuser/AppData/Roaming/Slot", "steamuser"),
+ ("crossover/Application Data/Slot", "legacy"),
+ ] {
+ let folder = users.appending(path: path)
+ try fm.createDirectory(at: folder, withIntermediateDirectories: true)
+ try Data(mark.utf8).write(to: folder.appending(path: "\(mark).sav"))
+ // Loose in the container the template makes, which is merged through rather than
+ // taken whole, so the copies meet as files instead of as a directory.
+ try Data(mark.utf8).write(
+ to: folder.deletingLastPathComponent().appending(path: "note.txt"))
+ }
+
+ try PrefixTools.recreate(prefix, runner: runner)
+
+ let roaming = users.appending(path: "steamuser/AppData/Roaming")
+ func contents(_ name: String) -> [String] {
+ ((try? fm.contentsOfDirectory(
+ atPath: roaming.appending(path: name).path(percentEncoded: false))) ?? []).sorted()
+ }
+ // crossover sorts ahead of steamuser and AppData ahead of Application Data, so the
+ // instance that is kept is fixed rather than left to the order the filesystem lists in.
+ #expect(contents("Slot") == ["crossover.sav"], "the kept instance holds another session")
+ let parked = Set(contents("Slot BACKUP") + contents("Slot BACKUP 2"))
+ #expect(parked == ["legacy.sav", "steamuser.sav"], "an instance that lost was dropped")
+
+ func read(_ name: String) -> String? {
+ try? String(contentsOf: roaming.appending(path: name), encoding: .utf8)
+ }
+ #expect(read("note.txt") == "crossover")
+ #expect(Set([read("note.txt BACKUP"), read("note.txt BACKUP 2")].compactMap { $0 })
+ == ["legacy", "steamuser"], "a file that lost to another spelling was dropped")
+ }
+
+ // The template writes at wineboot, so its copy is always the newer one and the date says
+ // nothing. What the player has none of stays: a newer wine adds to the profile too.
+ @Test("A file the template just wrote gives way to the player's copy")
+ func rebuildPrefersThePlayersCopy() throws {
+ let fm = FileManager.default
+ let dir = URL(filePath: NSTemporaryDirectory()).appending(path: UUID().uuidString)
+ defer { try? fm.removeItem(at: dir) }
+ let home = dir.appending(path: "home")
+ try fm.createDirectory(at: home, withIntermediateDirectories: true)
+ let runner = try fakeRunner(in: dir, home: home)
+ let prefix = try usedPrefix(in: dir, home: home)
+
+ let settings = prefix.pfx.appending(path: "drive_c/users/crossover/AppData/wine.ini")
+ try fm.createDirectory(
+ at: settings.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data("mine".utf8).write(to: settings)
+
+ try PrefixTools.recreate(prefix, runner: runner)
+
+ let profile = prefix.pfx.appending(path: "drive_c/users/steamuser")
+ func text(_ path: String) -> String? {
+ try? String(contentsOf: profile.appending(path: path), encoding: .utf8)
+ }
+ #expect(text("AppData/wine.ini") == "mine")
+ #expect(text("AppData/fresh.ini") == "template")
+ }
+
+ // Both documents names can be real folders, the pre-Vista one from a cloud rule and the
+ // modern one from wine. Only one survives as the directory, so the other has to arrive.
+ @Test("Both documents names carry their files into the one directory")
+ func rebuildKeepsBothDocumentsNames() throws {
+ let fm = FileManager.default
+ let dir = URL(filePath: NSTemporaryDirectory()).appending(path: UUID().uuidString)
+ defer { try? fm.removeItem(at: dir) }
+ let home = dir.appending(path: "home")
+ try fm.createDirectory(at: home, withIntermediateDirectories: true)
+ let runner = try fakeRunner(in: dir, home: home)
+ let prefix = try usedPrefix(in: dir, home: home)
+
+ let users = prefix.pfx.appending(path: "drive_c/users")
+ let modern = users.appending(path: "crossover/Documents")
+ try fm.removeItem(at: modern)
+ try fm.createDirectory(at: modern, withIntermediateDirectories: true)
+ try Data("modern".utf8).write(to: modern.appending(path: "modern.txt"))
+ let preVista = users.appending(path: "crossover/My Documents")
+ try fm.createDirectory(at: preVista, withIntermediateDirectories: true)
+ try Data("legacy".utf8).write(to: preVista.appending(path: "legacy.txt"))
+
+ try PrefixTools.recreate(prefix, runner: runner)
+
+ let profile = users.appending(path: "steamuser")
+ for name in ["Documents", "My Documents"] {
+ for file in ["modern.txt", "legacy.txt"] {
+ let carried = profile.appending(path: "\(name)/\(file)")
+ #expect((try? String(contentsOf: carried, encoding: .utf8)) != nil,
+ "\(name)/\(file) did not come over")
+ }
+ }
+ }
+
+ // A prefix from before this layout has the profile the other way round, with steamuser
+ // the link. A rebuild turns it around so Steam and the game stop reading two folders.
+ @Test("A rebuild brings an older profile onto the steamuser layout")
+ func rebuildPutsBackLinksTheTemplateOmits() throws {
+ let dir = URL(filePath: NSTemporaryDirectory()).appending(path: UUID().uuidString)
+ let home = dir.appending(path: "home")
+ try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
+ let runner = try fakeRunner(in: dir, home: home)
+ let prefix = try usedPrefix(in: dir, home: home)
+ let fm = FileManager.default
+ let users = prefix.pfx.appending(path: "drive_c/users")
+
+ try fm.createSymbolicLink(
+ atPath: users.appending(path: "crossover/My Documents").path(percentEncoded: false),
+ withDestinationPath: "Documents")
+ try fm.createSymbolicLink(
+ atPath: users.appending(path: "steamuser").path(percentEncoded: false),
+ withDestinationPath: "crossover")
+
+ // The old side points Documents somewhere that is no longer where the home folder
+ // is, which is what a moved or renamed home leaves behind.
+ try fm.removeItem(at: users.appending(path: "crossover/Documents"))
+ try fm.createSymbolicLink(
+ atPath: users.appending(path: "crossover/Documents").path(percentEncoded: false),
+ withDestinationPath: "/somewhere/that/moved")
+
+ try PrefixTools.recreate(prefix, runner: runner)
+
+ func target(_ path: String) throws -> String {
+ try fm.destinationOfSymbolicLink(
+ atPath: users.appending(path: path).path(percentEncoded: false))
+ }
+ #expect(try target("crossover") == "steamuser")
+
+ // The save came over, and the folder holding it is in the prefix rather than the
+ // dangling place the old profile pointed Documents at.
+ let profile = users.appending(path: "steamuser")
+ let save = profile.appending(path: "AppData/Roaming/game/save.dat")
+ #expect(try String(contentsOf: save, encoding: .utf8) == "save")
+ let inside = prefix.pfx.resolvingSymlinksInPath().path(percentEncoded: false)
+ for name in ["Documents", "My Documents"] {
+ let resolved = profile.appending(path: name)
+ .resolvingSymlinksInPath().path(percentEncoded: false)
+ #expect(resolved.hasPrefix(inside), "\(name) resolves to \(resolved)")
+ }
+ }
+
+ // Only folders were carried, so a game that keeps its settings in a file beside them
+ // lost the file while its save folder came through.
+ @Test("A rebuild keeps a file sitting loose in a profile")
+ func rebuildKeepsALooseProfileFile() throws {
+ let dir = URL(filePath: NSTemporaryDirectory()).appending(path: UUID().uuidString)
+ let home = dir.appending(path: "home")
+ try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
+ let runner = try fakeRunner(in: dir, home: home)
+ let prefix = try usedPrefix(in: dir, home: home)
+ let loose = prefix.pfx.appending(path: "drive_c/users/crossover/settings.ini")
+ try Data("windowed=1".utf8).write(to: loose)
+
+ try PrefixTools.recreate(prefix, runner: runner)
+
+ #expect(try Data(contentsOf: loose) == Data("windowed=1".utf8))
+ }
+
+ // Every directory the merge lands is revisited for its links once all the real
+ // directories are in place, and a link inside a save directory is only reached that way.
+ @Test("A rebuild keeps a link sitting inside a save directory")
+ func rebuildKeepsALinkInsideAProfile() throws {
+ let dir = URL(filePath: NSTemporaryDirectory()).appending(path: UUID().uuidString)
+ let home = dir.appending(path: "home")
+ try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
+ let runner = try fakeRunner(in: dir, home: home)
+ let prefix = try usedPrefix(in: dir, home: home)
+ let game = prefix.pfx.appending(path: "drive_c/users/crossover/AppData/Roaming/game")
+ try FileManager.default.createSymbolicLink(
+ atPath: game.appending(path: "latest").path(percentEncoded: false),
+ withDestinationPath: "save.dat")
+
+ try PrefixTools.recreate(prefix, runner: runner)
+
+ let carried = prefix.pfx.appending(
+ path: "drive_c/users/steamuser/AppData/Roaming/game/latest")
+ #expect(try FileManager.default.destinationOfSymbolicLink(
+ atPath: carried.path(percentEncoded: false)) == "save.dat")
+ }
+
+ // A link carried across early holds the name a later profile has a real save directory on,
+ // and a landing link is what makes the merge give up on a name.
+ @Test("A link from one profile does not take the name another profile's saves land on")
+ func linksWaitForEveryRealDirectory() throws {
+ let dir = URL(filePath: NSTemporaryDirectory()).appending(path: UUID().uuidString)
+ let home = dir.appending(path: "home")
+ try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
+ let runner = try fakeRunner(in: dir, home: home)
+ let prefix = try usedPrefix(in: dir, home: home)
+ let fm = FileManager.default
+ let roaming = prefix.pfx.appending(path: "drive_c/users/crossover/AppData/Roaming")
+ try fm.createSymbolicLink(
+ atPath: roaming.appending(path: "other").path(percentEncoded: false),
+ withDestinationPath: "game")
+ let theirs = prefix.pfx.appending(path: "drive_c/users/steamuser/AppData/Roaming/other")
+ try fm.createDirectory(at: theirs, withIntermediateDirectories: true)
+ try Data("theirs".utf8).write(to: theirs.appending(path: "theirs.dat"))
+
+ try PrefixTools.recreate(prefix, runner: runner)
+
+ let landed = prefix.pfx.appending(path: "drive_c/users/steamuser/AppData/Roaming/other")
+ // Read through the link the other profile left, the save comes back either way, out of
+ // a directory holding a second game's files rather than its own.
+ #expect(
+ (try? landed.resourceValues(forKeys: [.isSymbolicLinkKey]))?.isSymbolicLink == false)
+ #expect(try Data(contentsOf: landed.appending(path: "theirs.dat")) == Data("theirs".utf8))
+ }
+
+ // A game installed by hand lives where the player put it, which the template knows
+ // nothing about, so the rebuild took it away along with the tree it sat beside.
+ @Test("A rebuild keeps what the template does not make")
+ func rebuildKeepsStrayTopLevelNames() throws {
+ let dir = URL(filePath: NSTemporaryDirectory()).appending(path: UUID().uuidString)
+ let home = dir.appending(path: "home")
+ try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
+ let runner = try fakeRunner(in: dir, home: home)
+ let prefix = try usedPrefix(in: dir, home: home)
+ let fm = FileManager.default
+ let driveC = prefix.pfx.appending(path: "drive_c")
+ try fm.createDirectory(at: driveC.appending(path: "Games/Quake"), withIntermediateDirectories: true)
+ try Data("exe".utf8).write(to: driveC.appending(path: "Games/Quake/quake.exe"))
+ try Data("notes".utf8).write(to: driveC.appending(path: "notes.txt"))
+
+ try PrefixTools.recreate(prefix, runner: runner)
+
+ #expect(try Data(contentsOf: driveC.appending(path: "Games/Quake/quake.exe")) == Data("exe".utf8))
+ #expect(try Data(contentsOf: driveC.appending(path: "notes.txt")) == Data("notes".utf8))
+
+ // A name the template does make is the template's, arch and all.
+ #expect(!fm.fileExists(
+ atPath: driveC.appending(path: "Program Files/redist/thing.dll").path(percentEncoded: false)))
+ }
+
+ // Emptying the prefix first meant a wineboot that failed left the game with nothing at
+ // all, and the next launch inherited the wreckage.
+ @Test("A rebuild that fails leaves the prefix as it was")
+ func failedRebuildKeepsTheOldPrefix() throws {
+ let fm = FileManager.default
+ let dir = fm.temporaryDirectory.appending(path: "np-rebuild-fail-\(UUID().uuidString)")
+ defer { try? fm.removeItem(at: dir) }
+ let home = dir.appending(path: "home/Documents")
+ try fm.createDirectory(at: home, withIntermediateDirectories: true)
+
+ let prefix = try usedPrefix(in: dir, home: home)
+ let runner = try fakeRunner(in: dir, home: home, exit: 1)
+ #expect(throws: (any Error).self) { try PrefixTools.recreate(prefix, runner: runner) }
+
+ func text(_ path: String) -> String? {
+ try? String(contentsOf: prefix.pfx.appending(path: path), encoding: .utf8)
+ }
+ #expect(text("drive_c/windows/system32/ntdll.dll") == "stale")
+ #expect(text("drive_c/users/crossover/AppData/Roaming/game/save.dat") == "save")
+ #expect(!fm.fileExists(atPath: prefix.root.appending(path: "pfx.rebuild").path(percentEncoded: false)))
+ }
+
+ // Every copy out of the old prefix was a try?, so a save that would not read left the fresh
+ // prefix short, the old one deleted anyway, and the client synced the gap over the cloud.
+ @Test("A save that cannot be copied stops the rebuild")
+ func rebuildRefusesWhenASaveCannotBeCarried() throws {
+ let fm = FileManager.default
+ let dir = fm.temporaryDirectory.appending(path: "np-carry-fail-\(UUID().uuidString)")
+ defer { try? fm.removeItem(at: dir) }
+ let home = dir.appending(path: "home/Documents")
+ try fm.createDirectory(at: home, withIntermediateDirectories: true)
+
+ let prefix = try usedPrefix(in: dir, home: home)
+ let runner = try fakeRunner(in: dir, home: home)
+ let save = prefix.pfx
+ .appending(path: "drive_c/users/crossover/AppData/Roaming/game/save.dat")
+ try fm.setAttributes(
+ [.posixPermissions: 0], ofItemAtPath: save.path(percentEncoded: false))
+
+ #expect(throws: (any Error).self) { try PrefixTools.recreate(prefix, runner: runner) }
+
+ try fm.setAttributes(
+ [.posixPermissions: 0o644], ofItemAtPath: save.path(percentEncoded: false))
+
+ func text(_ path: String) -> String? {
+ try? String(contentsOf: prefix.pfx.appending(path: path), encoding: .utf8)
+ }
+ // The prefix stays the one the game was using, so the client has nothing new to sync.
+ #expect(try String(contentsOf: save, encoding: .utf8) == "save")
+ #expect(text("drive_c/windows/system32/ntdll.dll") == "stale")
+ #expect(text("user.reg") == "mine")
+ #expect(!fm.fileExists(
+ atPath: prefix.root.appending(path: "pfx.rebuild").path(percentEncoded: false)))
+ #expect(PrefixStore.backups(of: prefix).isEmpty)
+ }
+
+ // Steam lays a prefix down in stages, so one caught early holds no profile. That is nothing
+ // to carry, not something lost, and refusing it blocks the prefix most likely to need it.
+ @Test("A prefix with no profile yet still rebuilds")
+ func rebuildAcceptsAPrefixWithNothingToCarry() throws {
+ let fm = FileManager.default
+ let dir = fm.temporaryDirectory.appending(path: "np-carry-none-\(UUID().uuidString)")
+ defer { try? fm.removeItem(at: dir) }
+ let home = dir.appending(path: "home/Documents")
+ try fm.createDirectory(at: home, withIntermediateDirectories: true)
+
+ let library = SteamLibrary(root: dir)
+ let pfx = library.compatdata.appending(path: "1574480/pfx")
+ try fm.createDirectory(
+ at: pfx.appending(path: "drive_c/windows"), withIntermediateDirectories: true)
+ let prefix = try #require(PrefixStore.all(libraries: [library]).first)
+
+ try PrefixTools.recreate(prefix, runner: try fakeRunner(in: dir, home: home))
+
+ #expect(fm.fileExists(
+ atPath: pfx.appending(path: "drive_c/users/steamuser").path(percentEncoded: false)))
+ #expect(PrefixStore.backups(of: prefix).count == 1)
+ }
+
+ // The rebuild used to delete pfx.previous on sight. A half finished swap leaves the saves
+ // there, the client lays a bare prefix down, and the entry looks ordinary: last copy gone.
+ @Test("A prefix left from an unfinished rebuild is not deleted")
+ func rebuildRefusesToDeleteAStrandedPrefix() throws {
+ let fm = FileManager.default
+ let dir = fm.temporaryDirectory.appending(path: "np-stranded-\(UUID().uuidString)")
+ defer { try? fm.removeItem(at: dir) }
+ let home = dir.appending(path: "home/Documents")
+ try fm.createDirectory(at: home, withIntermediateDirectories: true)
+
+ // What the client lays down before it boots the prefix: no registry yet.
+ let library = SteamLibrary(root: dir)
+ let entry = library.compatdata.appending(path: "1574480")
+ try fm.createDirectory(
+ at: entry.appending(path: "pfx/drive_c/windows"), withIntermediateDirectories: true)
+ let stranded = entry
+ .appending(path: "pfx.previous/drive_c/users/crossover/AppData/Roaming/game/save.dat")
+ try fm.createDirectory(
+ at: stranded.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data("save".utf8).write(to: stranded)
+ let prefix = try #require(PrefixStore.all(libraries: [library]).first)
+ let runner = try fakeRunner(in: dir, home: home)
+
+ #expect(throws: StepFailure.self) { try PrefixTools.recreate(prefix, runner: runner) }
+
+ #expect(try String(contentsOf: stranded, encoding: .utf8) == "save")
+ }
+
+ @Test("A prefix kept by an earlier rebuild is left alone by the next one")
+ func rebuildKeepsAnOlderBackup() throws {
+ let fm = FileManager.default
+ let dir = fm.temporaryDirectory.appending(path: "np-spent-\(UUID().uuidString)")
+ defer { try? fm.removeItem(at: dir) }
+ let home = dir.appending(path: "home/Documents")
+ try fm.createDirectory(at: home, withIntermediateDirectories: true)
+
+ let prefix = try usedPrefix(in: dir, home: home)
+ let previous = prefix.root.appending(path: "pfx.previous")
+ try fm.createDirectory(at: previous, withIntermediateDirectories: true)
+ try Data("spent".utf8).write(to: previous.appending(path: "user.reg"))
+
+ try PrefixTools.recreate(prefix, runner: try fakeRunner(in: dir, home: home))
+
+ #expect(try String(contentsOf: previous.appending(path: "user.reg"), encoding: .utf8)
+ == "spent")
+ #expect(PrefixStore.backups(of: prefix).count == 2)
+ #expect(try String(
+ contentsOf: prefix.pfx
+ .appending(path: "drive_c/users/steamuser/AppData/Roaming/game/save.dat"),
+ encoding: .utf8) == "save")
+ }
+
+ // The rename is the one call where the prefix is neither the old nor the new one. Failing
+ // there left nothing under pfx and the saves in pfx.previous, a name the list ignores.
+ @Test("A rebuild that cannot be swapped in puts the old prefix back")
+ func failedSwapRestoresTheOldPrefix() throws {
+ let fm = FileManager.default
+ let dir = fm.temporaryDirectory.appending(path: "np-swap-fail-\(UUID().uuidString)")
+ defer {
+ let clear = Process()
+ clear.executableURL = URL(filePath: "/usr/bin/chflags")
+ clear.arguments = ["-R", "nouchg", dir.path(percentEncoded: false)]
+ try? clear.run()
+ clear.waitUntilExit()
+ try? fm.removeItem(at: dir)
+ }
+ let home = dir.appending(path: "home/Documents")
+ try fm.createDirectory(at: home, withIntermediateDirectories: true)
+
+ // windows is in the template, so it is skipped whole and the rebuild reaches the swap
+ // with nothing recorded as lost.
+ let library = SteamLibrary(root: dir)
+ let pfx = library.compatdata.appending(path: "1574480/pfx")
+ try fm.createDirectory(
+ at: pfx.appending(path: "drive_c/windows"), withIntermediateDirectories: true)
+ let marker = pfx.appending(path: "drive_c/windows/marker")
+ try Data("old".utf8).write(to: marker)
+ let prefix = try #require(PrefixStore.all(libraries: [library]).first)
+ let runner = try fakeRunner(in: dir, home: home, lock: true)
+
+ var thrown: (any Error)?
+ do { try PrefixTools.recreate(prefix, runner: runner) } catch { thrown = error }
+
+ // Every refusal in the rebuild is a StepFailure, so a Cocoa error is the rename itself
+ // and not the run stopping somewhere earlier and looking the same afterwards.
+ #expect((thrown as? NSError)?.domain == NSCocoaErrorDomain)
+ #expect(try String(contentsOf: marker, encoding: .utf8) == "old")
+ #expect(PrefixStore.backups(of: prefix).isEmpty)
+ }
+
+ @Test("A second rebuild keeps the prefix the first one parked")
+ func rebuildKeepsEveryParkedPrefix() throws {
+ let fm = FileManager.default
+ let dir = fm.temporaryDirectory.appending(path: "np-keep-all-\(UUID().uuidString)")
+ defer { try? fm.removeItem(at: dir) }
+ let home = dir.appending(path: "home/Documents")
+ try fm.createDirectory(at: home, withIntermediateDirectories: true)
+
+ let prefix = try usedPrefix(in: dir, home: home)
+ let runner = try fakeRunner(in: dir, home: home)
+ let clock = DateFormatter()
+ clock.locale = Locale(identifier: "en_US_POSIX")
+ clock.dateFormat = "yyyyMMdd-HHmmss"
+
+ let first = try #require(try PrefixTools.recreate(
+ prefix, runner: runner, now: clock.date(from: "20260101-120000")!))
+ let second = try #require(try PrefixTools.recreate(
+ prefix, runner: runner, now: clock.date(from: "20260102-133000")!))
+
+ #expect(first.lastPathComponent == "pfx.previous-20260101-120000")
+ #expect(second.lastPathComponent == "pfx.previous-20260102-133000")
+ #expect(PrefixStore.backups(of: prefix).count == 2)
+ #expect(fm.fileExists(atPath: first.path(percentEncoded: false)))
+ }
+
+ @Test("Two rebuilds in the same second are kept under separate names")
+ func rebuildInTheSameSecondDoesNotCollide() throws {
+ let fm = FileManager.default
+ let dir = fm.temporaryDirectory.appending(path: "np-same-second-\(UUID().uuidString)")
+ defer { try? fm.removeItem(at: dir) }
+ let home = dir.appending(path: "home/Documents")
+ try fm.createDirectory(at: home, withIntermediateDirectories: true)
+
+ let prefix = try usedPrefix(in: dir, home: home)
+ let runner = try fakeRunner(in: dir, home: home)
+ let clock = DateFormatter()
+ clock.locale = Locale(identifier: "en_US_POSIX")
+ clock.dateFormat = "yyyyMMdd-HHmmss"
+ let instant = clock.date(from: "20260101-120000")!
+
+ let first = try #require(try PrefixTools.recreate(prefix, runner: runner, now: instant))
+ let second = try #require(try PrefixTools.recreate(prefix, runner: runner, now: instant))
+
+ #expect(first.lastPathComponent == "pfx.previous-20260101-120000")
+ #expect(second.lastPathComponent == "pfx.previous-20260101-120000-2")
+ #expect(PrefixStore.backups(of: prefix).count == 2)
+ }
+
+ @Test("A rebuild with no prefix to park reports no backup")
+ func rebuildWithNothingToParkReportsNoBackup() throws {
+ let fm = FileManager.default
+ let dir = fm.temporaryDirectory.appending(path: "np-nopark-\(UUID().uuidString)")
+ defer { try? fm.removeItem(at: dir) }
+ let home = dir.appending(path: "home/Documents")
+ try fm.createDirectory(at: home, withIntermediateDirectories: true)
+
+ let library = SteamLibrary(root: dir)
+ let pfx = library.compatdata.appending(path: "1574480/pfx")
+ try fm.createDirectory(at: pfx, withIntermediateDirectories: true)
+ let prefix = try #require(PrefixStore.all(libraries: [library]).first)
+ try fm.removeItem(at: pfx)
+
+ let parked = try PrefixTools.recreate(prefix, runner: try fakeRunner(in: dir, home: home))
+
+ #expect(parked == nil)
+ #expect(PrefixStore.backups(of: prefix).isEmpty)
+ }
+
+ @Test("Deleting a backup takes that one and leaves the live prefix")
+ func deleteBackupsClearsThemAll() throws {
+ let fm = FileManager.default
+ let dir = fm.temporaryDirectory.appending(path: "np-clear-\(UUID().uuidString)")
+ defer { try? fm.removeItem(at: dir) }
+ let home = dir.appending(path: "home/Documents")
+ try fm.createDirectory(at: home, withIntermediateDirectories: true)
+
+ let prefix = try usedPrefix(in: dir, home: home)
+ for stamp in ["20260101-120000", "20260102-133000"] {
+ try fm.createDirectory(
+ at: prefix.root.appending(path: "pfx.previous-\(stamp)"),
+ withIntermediateDirectories: true)
+ }
+
+ let kept = PrefixStore.backups(of: prefix)
+ #expect(kept.count == 2)
+
+ try PrefixTools.deleteBackup(kept[0])
+
+ #expect(PrefixStore.backups(of: prefix).map(\.lastPathComponent)
+ == ["pfx.previous-20260102-133000"])
+ #expect(fm.fileExists(atPath: prefix.pfx.path(percentEncoded: false)))
+
+ try PrefixTools.deleteBackup(kept[1])
+ #expect(PrefixStore.backups(of: prefix).isEmpty)
+ #expect(fm.fileExists(atPath: prefix.pfx.path(percentEncoded: false)))
+ }
+
+ @Test("Deleting takes the whole compatdata entry, not just the prefix inside it")
+ func deleteRemovesTheEntry() throws {
+ let dir = FileManager.default.temporaryDirectory.appending(path: "np-del-\(UUID().uuidString)")
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let library = SteamLibrary(root: dir)
+ let entry = library.compatdata.appending(path: "1574480")
+ try FileManager.default.createDirectory(
+ at: entry.appending(path: "pfx/drive_c"), withIntermediateDirectories: true)
+ try Data("log".utf8).write(to: entry.appending(path: "notproton-run.log"))
+
+ let prefix = try #require(PrefixStore.all(libraries: [library]).first)
+ try PrefixTools.delete(prefix)
+
+ #expect(!FileManager.default.fileExists(atPath: entry.path(percentEncoded: false)))
+ // The compatdata directory itself belongs to Steam and stays.
+ #expect(FileManager.default.fileExists(atPath: library.compatdata.path(percentEncoded: false)))
+ }
+
+ @Test("The proton profile is laid out before wineboot can redirect it")
+ func profileLayoutPrecedesWineboot() throws {
+ let source = try Self.compatSource()
+
+ let definition = try #require(source.range(of: "lay_out_proton_profile() {"))
+ let call = try #require(source.range(of: " lay_out_proton_profile\n"))
+ let wineboot = try #require(source.range(of: "wineboot --init"))
+
+ // sh reads a script top to bottom, so a call above the definition is only an
+ // unknown command.
+ #expect(definition.lowerBound < call.lowerBound)
+ // wineboot is what swaps the profile folders for links into the mac home, so
+ // they have to already exist when it runs.
+ #expect(call.lowerBound < wineboot.lowerBound)
+ }
+
+ @Test("The profile link points at steamuser, not out of the prefix")
+ func profileLinkPointsInward() throws {
+ let source = try Self.compatSource()
+
+ // CrossOver fixes the profile name, so crossover is the link and steamuser is
+ // the real directory holding the files Steam syncs.
+ #expect(source.contains(#"ln -s steamuser "$users/crossover""#))
+ // The reverse direction is what routed cloud saves out to the mac home.
+ #expect(!source.contains(#"ln -s "$profile" "$users/steamuser""#))
+ }
+
+ // Steam resolves WinAppDataLocal, WinAppDataRoaming and WinMyDocuments through the XP
+ // names, which reach the modern folders by junction. Without them an upload globs nothing.
+ @Test("A rebuilt prefix reaches every cloud root by its pre-Vista name")
+ func rebuildAliasesThePreVistaNames() throws {
+ let fm = FileManager.default
+ let dir = URL(filePath: NSTemporaryDirectory()).appending(path: UUID().uuidString)
+ defer { try? fm.removeItem(at: dir) }
+ let home = dir.appending(path: "home")
+ try fm.createDirectory(at: home, withIntermediateDirectories: true)
+ let runner = try fakeRunner(in: dir, home: home)
+ let prefix = try usedPrefix(in: dir, home: home)
+
+ try PrefixTools.recreate(prefix, runner: runner)
+
+ let profile = prefix.pfx.appending(path: "drive_c/users/steamuser")
+ // The targets are relative and spelled the way Proton spells them, so the link
+ // survives the prefix moving to another volume.
+ for (legacy, target) in [
+ ("Local Settings/Application Data", "../AppData/Local"),
+ ("Application Data", "./AppData/Roaming"),
+ ("My Documents", "./Documents"),
+ ] {
+ let link = profile.appending(path: legacy)
+ let points = try? fm.destinationOfSymbolicLink(
+ atPath: link.path(percentEncoded: false))
+ #expect(points == target, "\(legacy) points at \(points ?? "nothing")")
+
+ var isDirectory: ObjCBool = false
+ let found = fm.fileExists(
+ atPath: link.path(percentEncoded: false), isDirectory: &isDirectory)
+ #expect(found && isDirectory.boolValue, "\(legacy) does not reach a directory")
+ }
+ }
+
+ // Once the client syncs a cloud rule without the alias, its download sits under the
+ // pre-Vista name while the game reads the modern one. A rebuild has to bring them together.
+ @Test("A cloud save left under the old name lands where the game reads")
+ func rebuildCarriesACloudSaveOntoTheModernName() throws {
+ let fm = FileManager.default
+ let dir = URL(filePath: NSTemporaryDirectory()).appending(path: UUID().uuidString)
+ defer { try? fm.removeItem(at: dir) }
+ let home = dir.appending(path: "home")
+ try fm.createDirectory(at: home, withIntermediateDirectories: true)
+ let runner = try fakeRunner(in: dir, home: home)
+ let prefix = try usedPrefix(in: dir, home: home)
+
+ let stranded = prefix.pfx.appending(
+ path: "drive_c/users/crossover/Local Settings/Application Data/Ghost/Saves")
+ try fm.createDirectory(at: stranded, withIntermediateDirectories: true)
+ try Data("cloud".utf8).write(to: stranded.appending(path: "progress.sav"))
+
+ try PrefixTools.recreate(prefix, runner: runner)
+
+ let profile = prefix.pfx.appending(path: "drive_c/users/steamuser")
+ let landed = profile.appending(path: "AppData/Local/Ghost/Saves/progress.sav")
+ #expect((try? String(contentsOf: landed, encoding: .utf8)) == "cloud")
+ }
+
+ @Test("The launch path aliases every root the client resolves through an old name")
+ func launchPathAliasesEveryCloudRoot() throws {
+ let source = try Self.compatSource()
+
+ for pair in [
+ #""Local Settings/Application Data|AppData/Local|../AppData/Local""#,
+ #""Application Data|AppData/Roaming|./AppData/Roaming""#,
+ #""My Documents|Documents|./Documents""#,
+ ] {
+ #expect(source.contains(pair), "the launch path does not carry \(pair)")
+ }
+ }
+
+ // The client can drop cloud files under an old name between launches, so the aliases cannot
+ // be left to prefix creation. lay_out_proton_profile is what runs them every launch.
+ @Test("The aliases are made from inside the profile layout, not off on their own")
+ func migrationRunsEveryLaunch() throws {
+ let source = try Self.compatSource()
+
+ let definition = try #require(source.range(of: "migrate_user_paths() {"))
+ let call = try #require(source.range(of: " migrate_user_paths \"$profile\"\n"))
+ let layout = try #require(source.range(of: "lay_out_proton_profile() {"))
+
+ // sh reads a script top to bottom, so a call above the definition is only an
+ // unknown command.
+ #expect(definition.lowerBound < call.lowerBound)
+ // A call outside the one function that is known to run before wineboot would say
+ // nothing about when the aliases are made, so the call has to be within its body.
+ let body = try #require(source.range(of: "\n}\n", range: layout.upperBound..<source.endIndex))
+ #expect(layout.upperBound < call.lowerBound && call.upperBound < body.lowerBound)
+ }
+
+ // Steam stamps a download when it lands, so the legacy copy routinely looks newer. A
+ // rebuild has to settle that the way a launch does, or survival turns on what was run.
+ @Test("The modern name's copy outlives the legacy one on both paths")
+ func rebuildKeepsTheModernCopyOnACollision() throws {
+ let fm = FileManager.default
+ let dir = URL(filePath: NSTemporaryDirectory()).appending(path: UUID().uuidString)
+ defer { try? fm.removeItem(at: dir) }
+ let home = dir.appending(path: "home")
+ try fm.createDirectory(at: home, withIntermediateDirectories: true)
+ let runner = try fakeRunner(in: dir, home: home)
+ let prefix = try usedPrefix(in: dir, home: home)
+ let old = prefix.pfx.appending(path: "drive_c/users/crossover")
+ // The template points this out to the mac home, which is the escape a rebuild undoes.
+ // It has to be a real folder here to hold the game's copy of the save.
+ try fm.removeItem(at: old.appending(path: "Documents"))
+
+ for (legacy, modern) in [
+ ("Local Settings/Application Data", "AppData/Local"),
+ ("Application Data", "AppData/Roaming"),
+ ("My Documents", "Documents"),
+ ] {
+ for spelling in [legacy, modern] {
+ try? fm.createDirectory(
+ at: old.appending(path: "\(spelling)/Ghost"), withIntermediateDirectories: true)
+ }
+ let game = old.appending(path: "\(modern)/Ghost/save.dat")
+ let client = old.appending(path: "\(legacy)/Ghost/save.dat")
+ try Data("game".utf8).write(to: game)
+ try Data("client".utf8).write(to: client)
+ try fm.setAttributes(
+ [.modificationDate: Date(timeIntervalSince1970: 1_000)],
+ ofItemAtPath: game.path(percentEncoded: false))
+ try fm.setAttributes(
+ [.modificationDate: Date(timeIntervalSince1970: 9_000)],
+ ofItemAtPath: client.path(percentEncoded: false))
+ }
+
+ try PrefixTools.recreate(prefix, runner: runner)
+
+ let profile = prefix.pfx.appending(path: "drive_c/users/steamuser")
+ for (legacy, modern) in [
+ ("Local Settings/Application Data", "AppData/Local"),
+ ("Application Data", "AppData/Roaming"),
+ ("My Documents", "Documents"),
+ ] {
+ let landed = profile.appending(path: "\(modern)/Ghost/save.dat")
+ #expect((try? String(contentsOf: landed, encoding: .utf8)) == "game",
+ "\(modern) did not keep the game's copy")
+ // One directory under two names, so the alias has to read back the same file.
+ let alias = profile.appending(path: "\(legacy)/Ghost/save.dat")
+ #expect((try? String(contentsOf: alias, encoding: .utf8)) == "game",
+ "\(legacy) disagrees with \(modern)")
+ }
+ }
+
+ // A dangling link from the first profile holds the name the next profile's real folder lands
+ // on. The name tests free through it while mkdir and copy refuse, so saves went quietly.
+ @Test("A save survives a landing held by a link to nothing")
+ func rebuildReplacesABrokenLandingLink() throws {
+ let fm = FileManager.default
+ let dir = URL(filePath: NSTemporaryDirectory()).appending(path: UUID().uuidString)
+ defer { try? fm.removeItem(at: dir) }
+ let home = dir.appending(path: "home")
+ try fm.createDirectory(at: home, withIntermediateDirectories: true)
+ let runner = try fakeRunner(in: dir, home: home)
+ let prefix = try usedPrefix(in: dir, home: home)
+ let users = prefix.pfx.appending(path: "drive_c/users")
+
+ // crossover is walked first, so its link is already on the name by the time steamuser's
+ // folder of the same name is merged onto it.
+ try fm.createSymbolicLink(
+ at: users.appending(path: "crossover/AppData/Roaming/Ghost"),
+ withDestinationURL: dir.appending(path: "gone"))
+ let save = users.appending(path: "steamuser/AppData/Roaming/Ghost/slot1.sav")
+ try fm.createDirectory(
+ at: save.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data("precious".utf8).write(to: save)
+
+ try PrefixTools.recreate(prefix, runner: runner)
+
+ let landed = prefix.pfx
+ .appending(path: "drive_c/users/steamuser/AppData/Roaming/Ghost/slot1.sav")
+ #expect((try? String(contentsOf: landed, encoding: .utf8)) == "precious")
+ }
+
+ @Test("A save survives a link out of the prefix landing on its name")
+ func rebuildKeepsARealFolderOverACarriedLink() throws {
+ let fm = FileManager.default
+ let dir = URL(filePath: NSTemporaryDirectory()).appending(path: UUID().uuidString)
+ defer { try? fm.removeItem(at: dir) }
+ let home = dir.appending(path: "home")
+ try fm.createDirectory(at: home, withIntermediateDirectories: true)
+ let outside = dir.appending(path: "outside")
+ try fm.createDirectory(at: outside, withIntermediateDirectories: true)
+ let runner = try fakeRunner(in: dir, home: home)
+ let prefix = try usedPrefix(in: dir, home: home)
+ let users = prefix.pfx.appending(path: "drive_c/users")
+
+ // A mac home redirect below the profile root, the shape a real bottle has under Desktop.
+ // crossover walks first, so it took the name before steamuser's saves reached the merge.
+ try fm.createSymbolicLink(
+ at: users.appending(path: "crossover/AppData/Roaming/Ghost"),
+ withDestinationURL: outside)
+ let save = users.appending(path: "steamuser/AppData/Roaming/Ghost/slot1.sav")
+ try fm.createDirectory(
+ at: save.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data("precious".utf8).write(to: save)
+
+ try PrefixTools.recreate(prefix, runner: runner)
+
+ let landed = prefix.pfx
+ .appending(path: "drive_c/users/steamuser/AppData/Roaming/Ghost/slot1.sav")
+ #expect((try? String(contentsOf: landed, encoding: .utf8)) == "precious")
+ #expect(!fm.fileExists(atPath: outside.appending(path: "slot1.sav").path(percentEncoded: false)))
+ }
+
+ // The old name becomes a link, so the merge is never attempted again and anything that
+ // failed to copy is unreachable. Proton raises here, which would kill the launch instead.
+ @Test("The old name is only moved aside once the merge has succeeded")
+ func renameWaitsForTheMerge() throws {
+ let source = try Self.compatSource()
+
+ let gate = try #require(source.range(of: #"if ! merge_user_dir "$old" "$new"; then"#))
+ let rename = try #require(source.range(of: #"mv "$old" "$old BACKUP""#))
+ #expect(gate.lowerBound < rename.lowerBound)
+ // A bare call could not report anything: the walk reads from a pipe, so it runs in a
+ // subshell and only the group's status comes back.
+ #expect(!source.contains(" merge_user_dir \"$old\" \"$new\"\n"))
+ // And the gate is worth nothing unless the walk can come back unhappy.
+ #expect(source.contains(#"[ -z "$failed" ]"#))
+ // Nothing about either failure is visible in the prefix, so the log has to carry it.
+ #expect(source.contains("did not merge into $new_rel, left in place"))
+ #expect(source.contains("could not be moved aside, cloud saves stay split"))
+ }
+
+ // A modern name that is a link is a shape Proton never produces, and the rename the merge
+ // ends with would leave the link dangling and the files behind it unreachable.
+ @Test("A cloud root whose modern name is a link is left alone")
+ func migrationRefusesALinkedModernName() throws {
+ let source = try Self.compatSource()
+
+ let refusal = try #require(source.range(of: #"if [ -L "$new" ]; then"#))
+ let rename = try #require(source.range(of: #"mv "$old" "$old BACKUP""#))
+ #expect(refusal.lowerBound < rename.lowerBound)
+ }
+
+ // The three shapes a landing can take that no tree merges into. Each used to return,
+ // dropping everything under it, and nothing recorded as lost let the swap delete the prefix.
+ private func rebuild(
+ _ label: String, freshProfile: String, oldPath: String, contents: String
+ ) throws -> URL {
+ let fm = FileManager.default
+ let dir = fm.temporaryDirectory.appending(path: "np-\(label)-\(UUID().uuidString)")
+ let home = dir.appending(path: "home/Documents")
+ try fm.createDirectory(at: home, withIntermediateDirectories: true)
+
+ let prefix = try usedPrefix(in: dir, home: home)
+ let old = prefix.pfx.appending(path: "drive_c/users/crossover/\(oldPath)")
+ try fm.createDirectory(at: old.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data(contents.utf8).write(to: old)
+
+ let runner = try fakeRunner(
+ in: dir, home: home,
+ extra: "cd \"$WINEPREFIX/drive_c/users/steamuser\" && \(freshProfile)")
+ try PrefixTools.recreate(prefix, runner: runner)
+ return dir
+ }
+
+ @Test("A save under a landing link that leaves the prefix is kept inside it")
+ func escapingLandingKeepsTheSave() throws {
+ let dir = try rebuild(
+ "escape", freshProfile: "ln -s \"$HOME\" Saves",
+ oldPath: "Saves/game.sav", contents: "progress")
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ let pfx = SteamLibrary(root: dir).compatdata.appending(path: "1574480/pfx")
+ let parked = pfx.appending(path: "drive_c/users/steamuser/Saves BACKUP/game.sav")
+ #expect(try String(contentsOf: parked, encoding: .utf8) == "progress")
+ }
+
+ @Test("A save file is kept when a directory holds its name")
+ func fileUnderADirectoryLandingIsKept() throws {
+ let dir = try rebuild(
+ "filedir", freshProfile: "mkdir -p Notes",
+ oldPath: "Notes", contents: "progress")
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ let pfx = SteamLibrary(root: dir).compatdata.appending(path: "1574480/pfx")
+ let parked = pfx.appending(path: "drive_c/users/steamuser/Notes BACKUP")
+ #expect(try String(contentsOf: parked, encoding: .utf8) == "progress")
+ }
+
+ @Test("A save directory is kept when a file holds its name")
+ func directoryUnderAFileLandingIsKept() throws {
+ let dir = try rebuild(
+ "dirfile", freshProfile: "printf x > Logs",
+ oldPath: "Logs/game.sav", contents: "progress")
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ let pfx = SteamLibrary(root: dir).compatdata.appending(path: "1574480/pfx")
+ let parked = pfx.appending(path: "drive_c/users/steamuser/Logs BACKUP/game.sav")
+ #expect(try String(contentsOf: parked, encoding: .utf8) == "progress")
+ }
+}
diff --git a/app/Tests/NotProtonAppTests/PrefixesModelTests.swift b/app/Tests/NotProtonAppTests/PrefixesModelTests.swift
new file mode 100644
index 0000000..13c6ee6
--- /dev/null
+++ b/app/Tests/NotProtonAppTests/PrefixesModelTests.swift
@@ -0,0 +1,668 @@
+import Foundation
+import Testing
+
+@testable import NotProtonApp
+
+// Loading measures every prefix with du and find in turn, so it stays in flight long enough
+// for a second to start on top. The libraries closure runs off the main actor, hence a lock.
+private final class Libraries: @unchecked Sendable {
+ private let lock = NSLock()
+ private var value: [SteamLibrary]
+
+ init(_ value: [SteamLibrary]) { self.value = value }
+
+ var current: [SteamLibrary] {
+ get { lock.withLock { value } }
+ set { lock.withLock { value = newValue } }
+ }
+}
+
+// Stands in for the wineboot a real rebuild runs, which a test has no runner for. Records
+// the order the queue visits prefixes in and notices two ever being in flight at once.
+private final class Recorder: @unchecked Sendable {
+ private let lock = NSLock()
+ private var inFlight = 0
+ private var order: [String] = []
+ private var clashed = false
+ private let held: DispatchSemaphore?
+
+ // A held turn blocks inside the rebuild until the test lets it go, so what the model
+ // published stays readable instead of lasting only as long as a sleep.
+ init(holdingEachTurn: Bool = false) {
+ held = holdingEachTurn ? DispatchSemaphore(value: 0) : nil
+ }
+
+ struct Refused: LocalizedError {
+ let appID: String
+ var errorDescription: String? { "\(appID) refused" }
+ }
+
+ var visited: [String] { lock.withLock { order } }
+ var overlapped: Bool { lock.withLock { clashed } }
+
+ func releaseTurn() { held?.signal() }
+
+ static func backup(of prefix: WinePrefix) -> URL {
+ prefix.root.appending(path: "pfx.previous-20260101-120000")
+ }
+
+ @discardableResult
+ func enter(_ prefix: WinePrefix, failing: Bool = false) throws -> URL? {
+ lock.withLock {
+ order.append(prefix.title)
+ inFlight += 1
+ if inFlight > 1 { clashed = true }
+ }
+ defer { lock.withLock { inFlight -= 1 } }
+ if let held {
+ held.wait()
+ } else {
+ // Long enough that a queue running these concurrently would be caught holding
+ // two at once. Without it every call returns before the next begins either way.
+ Thread.sleep(forTimeInterval: 0.05)
+ }
+ if failing { throw Refused(appID: prefix.appID) }
+ return Self.backup(of: prefix)
+ }
+}
+
+@MainActor
+@Suite("Loading prefixes")
+struct PrefixesModelTests {
+
+ private func makeLibrary(appIDs: [String]) throws -> (URL, SteamLibrary) {
+ let dir = FileManager.default.temporaryDirectory.appending(path: "np-model-\(UUID().uuidString)")
+ let library = SteamLibrary(root: dir)
+ for appID in appIDs {
+ try FileManager.default.createDirectory(
+ at: library.compatdata.appending(path: "\(appID)/pfx/drive_c/users/crossover"),
+ withIntermediateDirectories: true)
+ }
+ return (dir, library)
+ }
+
+ private func write(_ text: String, to url: URL) throws {
+ try FileManager.default.createDirectory(
+ at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data(text.utf8).write(to: url)
+ }
+
+ // Enough of an ntdll for the arch to be read out of it: e_lfanew at 0x3c pointing at a
+ // PE signature and the machine word behind it.
+ private func writeNtdll(machine: UInt16, in pfx: URL) throws {
+ var bytes = [UInt8](repeating: 0, count: 0x40)
+ withUnsafeBytes(of: UInt32(0x40).littleEndian) { bytes.replaceSubrange(0x3c..<0x40, with: $0) }
+ bytes += [0x50, 0x45, 0x00, 0x00]
+ bytes += withUnsafeBytes(of: machine.littleEndian) { Array($0) }
+ let dll = pfx.appending(path: "drive_c/windows/system32/ntdll.dll")
+ try FileManager.default.createDirectory(
+ at: dll.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data(bytes).write(to: dll)
+ }
+
+ // The launcher refuses a prefix from the other compatibility tool, so the pane has to mark
+ // those rows or the refusal is the first anyone hears. Never booted means no arch yet.
+ @Test("A prefix built by the other compatibility tool is the only one flagged")
+ func flagsForeignPrefixes() async throws {
+ let (dir, library) = try makeLibrary(appIDs: ["1574480", "253750", "447700"])
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ let compatdata = library.compatdata
+ try writeNtdll(machine: 0xaa64, in: compatdata.appending(path: "1574480/pfx"))
+ try writeNtdll(machine: 0x8664, in: compatdata.appending(path: "253750/pfx"))
+
+ let model = PrefixesModel(libraries: { [library] }, runnerArch: { .arm64 })
+ await model.load()
+
+ func prefix(_ appID: String) throws -> WinePrefix {
+ try #require(model.prefixes.first { $0.appID == appID })
+ }
+ #expect(model.expectedArch == .arm64)
+ #expect(model.isForeign(try prefix("1574480")) == false)
+ #expect(model.isForeign(try prefix("253750")) == true)
+ #expect(model.isForeign(try prefix("447700")) == false)
+ }
+
+ @Test("A load lists the prefixes and measures each one")
+ func loadsAndMeasures() async throws {
+ let (dir, library) = try makeLibrary(appIDs: ["1574480", "1649240"])
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let model = PrefixesModel(libraries: { [library] })
+
+ await model.load()
+
+ #expect(model.prefixes.count == 2)
+ #expect(Set(model.usage.keys) == Set(model.prefixes.map(\.id)))
+ #expect(!model.isLoading)
+ }
+
+ // The regression: a superseded load kept writing into the dictionary the newer one had
+ // emptied, and the first to finish cleared isLoading while the other was still measuring.
+ @Test("A load that is superseded does not publish into the newer one")
+ func supersededLoadPublishesNothing() async throws {
+ let (oldDir, oldLibrary) = try makeLibrary(appIDs: ["1574480", "1649240", "3014330"])
+ defer { try? FileManager.default.removeItem(at: oldDir) }
+ let (newDir, newLibrary) = try makeLibrary(appIDs: ["4401430"])
+ defer { try? FileManager.default.removeItem(at: newDir) }
+
+ let libraries = Libraries([oldLibrary])
+ let model = PrefixesModel(libraries: { libraries.current })
+
+ let first = Task { await model.load() }
+ // Let the first load get past listing and into measuring.
+ await Task.yield()
+
+ // What deleting a prefix does: the library changes, then a load starts on top of
+ // the one still running.
+ libraries.current = [newLibrary]
+ let replacement = Task { await model.load() }
+
+ _ = await first.value
+ _ = await replacement.value
+
+ // Whatever interleaving happened, the sizes must describe the listed prefixes
+ // and nothing else, and nothing may still claim to be loading.
+ #expect(Set(model.usage.keys) == Set(model.prefixes.map(\.id)))
+ #expect(!model.isLoading)
+ }
+
+ @Test("Loading again from a changed library replaces the previous results")
+ func reloadReplacesResults() async throws {
+ let (oldDir, oldLibrary) = try makeLibrary(appIDs: ["1574480", "1649240"])
+ defer { try? FileManager.default.removeItem(at: oldDir) }
+ let (newDir, newLibrary) = try makeLibrary(appIDs: ["4401430"])
+ defer { try? FileManager.default.removeItem(at: newDir) }
+
+ // Swapped between loads, the way deleting a prefix changes what is there.
+ let libraries = Libraries([oldLibrary])
+ let model = PrefixesModel(libraries: { libraries.current })
+
+ await model.load()
+ #expect(model.prefixes.count == 2)
+
+ libraries.current = [newLibrary]
+ await model.load()
+
+ #expect(model.prefixes.map(\.appID) == ["4401430"])
+ #expect(Set(model.usage.keys) == Set(model.prefixes.map(\.id)))
+ #expect(!model.isLoading)
+ }
+
+ // The toolbar, context menu and Prefix menu all act on the selection, so one pointing at a
+ // prefix that is gone offers an action on nothing. Delete and rebuild both reload.
+ @Test("A load drops selected prefixes that are no longer there")
+ func loadPrunesStaleSelection() async throws {
+ let (dir, library) = try makeLibrary(appIDs: ["1574480", "1649240"])
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ let model = PrefixesModel(libraries: { [library] })
+ await model.load()
+
+ let survivor = try #require(model.prefixes.first { $0.appID == "1649240" })
+ let doomed = try #require(model.prefixes.first { $0.appID == "1574480" })
+ model.selection = [survivor.id, doomed.id]
+
+ // A delete takes one appid out of the library it was in. Swapping the library instead
+ // would move every prefix, since a prefix is keyed by library root as well as appid.
+ try FileManager.default.removeItem(at: library.compatdata.appending(path: "1574480"))
+ await model.load()
+
+ #expect(model.prefixes.count == 1)
+ #expect(!model.selection.contains(doomed.id))
+ // Still selected, because it is still there. A load that cleared the selection
+ // outright would pass the check above for the wrong reason.
+ #expect(model.selection.count == 1)
+ }
+
+ // The wine tools and Reveal drive one prefix each, so more than one selected row has
+ // to resolve to nothing rather than to one of them.
+ @Test("Only a single selected prefix is a target for the per-prefix actions")
+ func selectedPrefixIsSingleSelectionOnly() async throws {
+ let (dir, library) = try makeLibrary(appIDs: ["1574480", "1649240"])
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let model = PrefixesModel(libraries: { [library] })
+ await model.load()
+
+ #expect(model.selectedPrefix == nil)
+
+ let one = try #require(model.prefixes.first)
+ model.selection = [one.id]
+ #expect(model.selectedPrefix == one)
+
+ model.selection = Set(model.prefixes.map(\.id))
+ #expect(model.selection.count == 2)
+ #expect(model.selectedPrefix == nil)
+ }
+
+ // Selecting every prefix that needs rebuilding used to offer nothing, so they had to be
+ @Test("Declining the backup tells the rebuild not to keep one")
+ func rebuildForwardsTheBackupChoice() async throws {
+ let (dir, library) = try makeLibrary(appIDs: ["1574480"])
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ let model = PrefixesModel(
+ libraries: { [library] },
+ rebuild: { prefix, keep in keep ? Recorder.backup(of: prefix) : nil })
+ await model.load()
+ let targets = model.prefixes
+ let title = try #require(targets.first).title
+
+ await model.recreate(targets, keepBackup: false)
+ #expect(model.outcome == "Rebuilt the prefix for \(title).")
+
+ await model.recreate(targets)
+ #expect(model.outcome?.contains("The original is at") == true)
+ }
+
+ @Test("Backing up reports where the copy landed")
+ func backUpReportsTheSlot() async throws {
+ let (dir, library) = try makeLibrary(appIDs: ["1574480", "1649240"])
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ let model = PrefixesModel(
+ libraries: { [library] }, makeBackup: { Recorder.backup(of: $0) })
+ await model.load()
+ let targets = model.prefixes
+ let first = try #require(targets.first)
+
+ await model.backUp([first])
+ #expect(model.outcome == "Backed up the prefix for \(first.title).")
+ #expect(model.failure == nil)
+
+ await model.backUp(targets)
+ #expect(model.outcome == "Backed up 2 prefixes.")
+ }
+
+ // picked and confirmed one at a time.
+ @Test("Rebuilding takes every selected prefix, one after another")
+ func rebuildTakesTheWholeSelection() async throws {
+ let (dir, library) = try makeLibrary(appIDs: ["1574480", "1649240", "253750"])
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ // Records the order and asserts nothing overlaps: a second wineboot in the same
+ // runner while the first is still going is the failure this queue exists to avoid.
+ let log = Recorder()
+ let model = PrefixesModel(
+ libraries: { [library] }, rebuild: { prefix, _ in try log.enter(prefix) })
+ await model.load()
+ model.selection = Set(model.prefixes.map(\.id))
+
+ let targets = model.selectedPrefixes
+ #expect(targets.count == 3)
+ await model.recreate(targets)
+
+ #expect(log.visited == targets.map(\.title))
+ #expect(!log.overlapped)
+ #expect(model.outcome == "Rebuilt 3 prefixes. Each original is kept beside the game's "
+ + "prefix. Check that your saves are present in the games, then delete the backups "
+ + "to save space.")
+ #expect(model.failure == nil)
+ #expect(model.busy.isEmpty)
+ #expect(!model.isBusy)
+ }
+
+ // A prefix whose game is running refuses, and it used to be the only one attempted.
+ @Test("A prefix that refuses to rebuild does not stop the ones queued behind it")
+ func rebuildReportsAPartialRun() async throws {
+ let (dir, library) = try makeLibrary(appIDs: ["1574480", "1649240", "253750"])
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ let log = Recorder()
+ let model = PrefixesModel(
+ libraries: { [library] },
+ rebuild: { prefix, _ in try log.enter(prefix, failing: prefix.appID == "1649240") }
+ )
+ await model.load()
+ let targets = model.prefixes
+ await model.recreate(targets)
+
+ #expect(log.visited.count == 3)
+ #expect(model.outcome == "Rebuilt 2 prefixes. Each original is kept beside the game's "
+ + "prefix. Check that your saves are present in the games, then delete the backups "
+ + "to save space.")
+ #expect(model.failure == "1649240 refused")
+ #expect(model.busy.isEmpty)
+ }
+
+ // The pane used to keep the sentence and drop the error, so a refusal it could act on
+ // arrived as a string with no remedy left in it.
+ @Test("A refused rebuild reaches the pane with its remedy intact")
+ func rebuildCarriesTheRemedy() async throws {
+ let (dir, library) = try makeLibrary(appIDs: ["1574480", "1649240"])
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ let model = PrefixesModel(
+ libraries: { [library] },
+ rebuild: { prefix, _ in
+ throw WriteRefused(path: prefix.root.path(percentEncoded: false))
+ }
+ )
+ await model.load()
+ await model.recreate(model.prefixes)
+
+ let report = try #require(model.report)
+ #expect(report.remedy == .ownership, "a prefix the user owns was blamed on a permission")
+ #expect(report.settingsPane == nil)
+ // Two refusals, one sentence, because neither of them names its own path.
+ #expect(
+ report.message
+ == "Could not write files. Check permissions, make sure your user owns the folder.")
+ }
+
+ @Test("One rebuilt prefix reports where the old one was parked")
+ func rebuildOfOneReportsTheBackup() async throws {
+ let (dir, library) = try makeLibrary(appIDs: ["1574480"])
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ let log = Recorder()
+ let model = PrefixesModel(
+ libraries: { [library] }, rebuild: { prefix, _ in try log.enter(prefix) })
+ await model.load()
+ let target = try #require(model.prefixes.first)
+
+ await model.recreate([target])
+
+ let backup = Recorder.backup(of: target).path(percentEncoded: false)
+ #expect(model.outcome == "Rebuilt the prefix for \(target.title). The original is at "
+ + "\(backup). Check that your save is present in the game, then delete the backup "
+ + "to save space.")
+ #expect(model.failure == nil)
+ }
+
+ @Test("A rebuild that parked nothing says nothing about a backup")
+ func rebuildThatParkedNothingMentionsNoBackup() async throws {
+ let (dir, library) = try makeLibrary(appIDs: ["1574480"])
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ let model = PrefixesModel(libraries: { [library] }, rebuild: { _, _ in nil })
+ await model.load()
+ let target = try #require(model.prefixes.first)
+
+ await model.recreate([target])
+
+ #expect(model.outcome == "Rebuilt the prefix for \(target.title).")
+ }
+
+ @Test("Backups from every prefix are listed newest first")
+ func backupsAreListedNewestFirst() async throws {
+ let (dir, library) = try makeLibrary(appIDs: ["1574480", "1649240"])
+ defer { try? FileManager.default.removeItem(at: dir) }
+ try park(["1574480": ["20260101-120000"], "1649240": ["20260103-090000"]], in: library)
+
+ let model = PrefixesModel(libraries: { [library] })
+ await model.load()
+
+ #expect(model.backups.count == 2)
+ #expect(model.backups.map(\.prefix.appID) == ["1649240", "1574480"])
+ #expect(model.backupBytes == model.backups.reduce(into: Int64(0)) { $0 += $1.bytes })
+ }
+
+ @Test("Deleting backups counts them rather than the prefixes")
+ func deleteBackupsReportsTheCount() async throws {
+ let (dir, library) = try makeLibrary(appIDs: ["1574480", "1649240"])
+ defer { try? FileManager.default.removeItem(at: dir) }
+ try park(
+ [
+ "1574480": ["20260101-120000", "20260102-133000"],
+ "1649240": ["20260101-120000", "20260102-133000"],
+ ],
+ in: library)
+
+ let model = PrefixesModel(libraries: { [library] })
+ await model.load()
+ #expect(model.backups.count == 4)
+
+ await model.deleteBackups(model.backups)
+
+ #expect(model.outcome == "Deleted 4 backups across 2 prefixes.")
+ #expect(model.failure == nil)
+ #expect(model.backups.isEmpty)
+ #expect(model.prefixes.allSatisfy { PrefixStore.backups(of: $0).isEmpty })
+ }
+
+ @Test("Deleting the backups of one game names the game")
+ func deleteBackupsOfOneGameNamesIt() async throws {
+ let (dir, library) = try makeLibrary(appIDs: ["1574480", "1649240"])
+ defer { try? FileManager.default.removeItem(at: dir) }
+ try park(
+ ["1574480": ["20260101-120000", "20260102-133000"], "1649240": ["20260105-101500"]],
+ in: library)
+
+ let model = PrefixesModel(libraries: { [library] })
+ await model.load()
+ let mine = model.backups.filter { $0.prefix.appID == "1574480" }
+ #expect(mine.count == 2)
+
+ await model.deleteBackups(mine)
+
+ #expect(model.outcome == "Deleted 2 backups for \(mine[0].title).")
+ #expect(model.backups.map(\.prefix.appID) == ["1649240"])
+ }
+
+ @Test("Deleting a single backup names the game once")
+ func deleteOneBackupNamesTheGame() async throws {
+ let (dir, library) = try makeLibrary(appIDs: ["1574480"])
+ defer { try? FileManager.default.removeItem(at: dir) }
+ try park(["1574480": ["20260101-120000"]], in: library)
+
+ let model = PrefixesModel(libraries: { [library] })
+ await model.load()
+ let only = try #require(model.backups.first)
+
+ await model.deleteBackups([only])
+
+ #expect(model.outcome == "Deleted the backup for \(only.title).")
+ #expect(model.backups.isEmpty)
+ }
+
+ @Test("Deleting backups where there are none says nothing")
+ func deleteBackupsWithNoneIsQuiet() async throws {
+ let (dir, library) = try makeLibrary(appIDs: ["1574480"])
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ let model = PrefixesModel(libraries: { [library] })
+ await model.load()
+
+ await model.deleteBackups(model.backups)
+
+ #expect(model.backups.isEmpty)
+ #expect(model.outcome == nil)
+ #expect(model.failure == nil)
+ }
+
+ private func park(_ stamps: [String: [String]], in library: SteamLibrary) throws {
+ let fm = FileManager.default
+ for (appID, taken) in stamps {
+ for stamp in taken {
+ let backup = library.compatdata.appending(path: "\(appID)/pfx.previous-\(stamp)")
+ try fm.createDirectory(at: backup, withIntermediateDirectories: true)
+ try Data("parked".utf8).write(to: backup.appending(path: "user.reg"))
+ }
+ }
+ }
+
+ @Test("Rebuilding nothing asks nothing of the disk")
+ func rebuildOfAnEmptySelectionDoesNothing() async throws {
+ let log = Recorder()
+ let model = PrefixesModel(
+ libraries: { [] }, rebuild: { prefix, _ in try log.enter(prefix) })
+ model.outcome = "untouched"
+ await model.recreate([])
+
+ #expect(log.visited.isEmpty)
+ #expect(model.outcome == "untouched")
+ }
+
+ // The spinner on a row comes off this set. Every selected row spins from the moment the
+ // run starts, and a row stops as its own turn ends rather than when the queue does.
+ @Test("Every selected row is busy from the start and each stops as its turn ends")
+ func busyFollowsTheQueue() async throws {
+ let (dir, library) = try makeLibrary(appIDs: ["1574480", "1649240", "253750"])
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ let log = Recorder(holdingEachTurn: true)
+ let model = PrefixesModel(
+ libraries: { [library] }, rebuild: { prefix, _ in try log.enter(prefix) })
+ await model.load()
+ let targets = model.prefixes
+
+ let running = Task { await model.recreate(targets) }
+
+ // A prefix having started means the one before it is done and out of the set. The turn is
+ // held inside the rebuild, so the set cannot move between the wait and the read.
+ for (turn, remaining) in [(1, 3), (2, 2), (3, 1)] {
+ while log.visited.count < turn { await Task.yield() }
+ #expect(model.busy.count == remaining)
+ log.releaseTurn()
+ }
+ await running.value
+
+ #expect(model.busy.isEmpty)
+ }
+
+ // A rebuilt prefix has new sizes to measure and a deleted one must leave the list, so
+ // both runs end by reading the libraries again rather than keeping what was read before.
+ @Test("A finished rebuild reads the libraries again")
+ func rebuildReloadsTheList() async throws {
+ let (dir, library) = try makeLibrary(appIDs: ["1574480", "1649240"])
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ let box = Libraries([library])
+ let log = Recorder()
+ let model = PrefixesModel(
+ libraries: { box.current }, rebuild: { prefix, _ in try log.enter(prefix) })
+ await model.load()
+ let targets = model.prefixes
+ #expect(targets.count == 2)
+
+ // Taken away before the run finishes, so an empty list afterwards can only mean the
+ // run went back to the libraries for it.
+ box.current = []
+ await model.recreate(targets)
+
+ #expect(model.prefixes.isEmpty)
+ }
+
+ // Right-clicking four selected rows and deleting used to throw away one of them, which
+ // left the other three selected and looking untouched.
+ @Test("Deleting takes every selected prefix")
+ func deleteTakesTheWholeSelection() async throws {
+ let (dir, library) = try makeLibrary(appIDs: ["1574480", "1649240", "253750"])
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let model = PrefixesModel(libraries: { [library] })
+ await model.load()
+
+ let doomed = model.prefixes.filter { $0.appID != "253750" }
+ model.selection = Set(doomed.map(\.id))
+ #expect(model.selectedPrefixes.count == 2)
+
+ await model.delete(model.selectedPrefixes)
+
+ #expect(model.prefixes.map(\.appID) == ["253750"])
+ #expect(model.failure == nil)
+ #expect(
+ model.outcome
+ == "Deleted 2 prefixes. Steam will make a new prefix if a game is launched again.")
+ #expect(model.busy.isEmpty)
+ #expect(!model.isLoading)
+ }
+
+ @Test("Deleting one prefix says which one")
+ func deleteOfOneNamesIt() async throws {
+ let (dir, library) = try makeLibrary(appIDs: ["1574480"])
+ defer { try? FileManager.default.removeItem(at: dir) }
+ try write(
+ """
+ "AppState"
+ {
+ \t"name"\t\t"Agent 64: Spies Never Die"
+ }
+ """, to: library.steamapps.appending(path: "appmanifest_1574480.acf"))
+
+ let model = PrefixesModel(libraries: { [library] })
+ await model.load()
+ await model.delete(model.prefixes)
+
+ #expect(model.prefixes.isEmpty)
+ #expect(
+ model.outcome
+ == "Deleted the prefix for Agent 64: Spies Never Die. Steam will make a new prefix "
+ + "if the game is launched again.")
+ }
+
+ // A running game refuses, and it refuses in the middle of a list of them. Stopping
+ // there would leave the rest selected with no word about why nothing happened to them.
+ @Test("A prefix that refuses does not stop the others")
+ func refusalDoesNotStopTheRest() async throws {
+ let (dir, library) = try makeLibrary(appIDs: ["1574480", "253750"])
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ let model = PrefixesModel(libraries: { [library] })
+ await model.load()
+ #expect(model.prefixes.count == 2)
+
+ let busy = try #require(model.prefixes.first { $0.appID == "253750" })
+ let held = try hold(busy)
+ defer { held() }
+
+ await model.delete(model.prefixes)
+
+ // The refusal happens before anything is unlinked, so the whole prefix is still
+ // there and still listed.
+ #expect(model.prefixes.map(\.appID) == ["253750"])
+ #expect(model.outcome?.contains("Deleted the prefix for App 1574480.") == true)
+ #expect(model.failure?.contains("is running. Quit the game first.") == true)
+ #expect(model.busy.isEmpty)
+ }
+
+ // What a live wineserver looks like: a socket directory named after the prefix's
+ // device and inode, with something holding a file open inside it for lsof to find.
+ private func hold(_ prefix: WinePrefix) throws -> () -> Void {
+ let dir = try #require(PrefixStore.serverDirectory(of: prefix))
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ let socket = dir.appending(path: "socket")
+ try Data().write(to: socket)
+
+ let handle = try FileHandle(forReadingFrom: socket)
+ return {
+ try? handle.close()
+ try? FileManager.default.removeItem(at: dir)
+ }
+ }
+
+ @Test("Deleting nothing is not an operation")
+ func deletingNothingDoesNothing() async throws {
+ let (dir, library) = try makeLibrary(appIDs: ["1574480"])
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let model = PrefixesModel(libraries: { [library] })
+ await model.load()
+ model.outcome = "untouched"
+
+ await model.delete([])
+
+ #expect(model.prefixes.count == 1)
+ #expect(model.outcome == "untouched")
+ #expect(model.failure == nil)
+ #expect(!model.isLoading)
+ }
+
+ @Test("A library with no prefixes leaves nothing behind")
+ func emptyLibraryClearsResults() async throws {
+ let (dir, library) = try makeLibrary(appIDs: ["1574480"])
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let (emptyDir, emptyLibrary) = try makeLibrary(appIDs: [])
+ defer { try? FileManager.default.removeItem(at: emptyDir) }
+
+ let libraries = Libraries([library])
+ let model = PrefixesModel(libraries: { libraries.current })
+ await model.load()
+ #expect(!model.usage.isEmpty)
+
+ libraries.current = [emptyLibrary]
+ await model.load()
+
+ #expect(model.prefixes.isEmpty)
+ #expect(model.usage.isEmpty)
+ #expect(!model.isLoading)
+ }
+}
diff --git a/app/Tests/NotProtonAppTests/RealRebuildTests.swift b/app/Tests/NotProtonAppTests/RealRebuildTests.swift
new file mode 100644
index 0000000..9fdb90a
--- /dev/null
+++ b/app/Tests/NotProtonAppTests/RealRebuildTests.swift
@@ -0,0 +1,158 @@
+import Foundation
+import Testing
+
+@testable import NotProtonApp
+
+// The real rebuild against a clone of a real prefix, where every other test fakes wineboot.
+// Caught My Documents going missing. Skipped without a runner and a prefix to clone.
+enum RealPrefixes {
+ static var library: SteamLibrary {
+ SteamLibrary(root: URL(filePath: NSHomeDirectory())
+ .appending(path: "Library/Application Support/Steam"))
+ }
+
+ // One prefix per profile shape: steamuser real, steamuser linked, and both real, which is
+ // the shape a save was lost from. All three have to come out on the steamuser layout.
+ static var candidates: [WinePrefix] {
+ let loader = PrefixTools.layout(runner: SupportPaths.currentRunner).unixDir
+ guard FileManager.default.fileExists(
+ atPath: loader.path(percentEncoded: false)) else { return [] }
+ func realDirectory(_ url: URL) -> Bool {
+ let values = try? url.resourceValues(forKeys: [.isSymbolicLinkKey, .isDirectoryKey])
+ return values?.isSymbolicLink != true && values?.isDirectory == true
+ }
+ var real: WinePrefix?
+ var linked: WinePrefix?
+ var split: WinePrefix?
+ for prefix in PrefixStore.all(libraries: [library]) where !PrefixStore.isInUse(prefix) {
+ let users = prefix.pfx.appending(path: "drive_c/users")
+ let steamuser = users.appending(path: "steamuser")
+ // A prefix Steam has only just laid down holds the profile directory and none of
+ // the registry, and every test here reads the registry.
+ guard FileManager.default.fileExists(
+ atPath: prefix.pfx.appending(path: "user.reg").path(percentEncoded: false)
+ ) else { continue }
+ guard let values = try? steamuser.resourceValues(
+ forKeys: [.isSymbolicLinkKey, .isDirectoryKey]) else { continue }
+ if values.isSymbolicLink == true {
+ linked = linked ?? prefix
+ } else if values.isDirectory == true {
+ if realDirectory(users.appending(path: "crossover")) {
+ split = split ?? prefix
+ } else {
+ real = real ?? prefix
+ }
+ }
+ }
+ return [real, linked, split].compactMap { $0 }
+ }
+}
+
+@Suite("Real rebuild", .serialized, .enabled(if: !RealPrefixes.candidates.isEmpty))
+struct RealRebuildTests {
+ private func clone(_ prefix: WinePrefix) throws -> WinePrefix {
+ let dir = URL(filePath: NSTemporaryDirectory())
+ .appending(path: "realrebuild-\(prefix.appID)-\(UUID().uuidString)")
+ let library = SteamLibrary(root: dir)
+ try FileManager.default.createDirectory(
+ at: library.compatdata, withIntermediateDirectories: true)
+ try FileManager.default.copyItem(
+ at: prefix.root, to: library.compatdata.appending(path: prefix.appID))
+ return WinePrefix(appID: prefix.appID, name: prefix.name, library: library, lastUsed: nil)
+ }
+
+ private func inventory(_ pfx: URL) -> (files: [String], links: [String]) {
+ let fm = FileManager.default
+ let users = pfx.appending(path: "drive_c/users").resolvingSymlinksInPath()
+ let base = users.path(percentEncoded: false) + "/"
+ var files: [String] = []
+ var links: [String] = []
+ let walker = fm.enumerator(
+ at: users, includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey])
+ while let entry = walker?.nextObject() as? URL {
+ let full = entry.resolvingSymlinksInPath().path(percentEncoded: false)
+ let path = full.hasPrefix(base) ? String(full.dropFirst(base.count)) : full
+ let values = try? entry.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
+ if values?.isSymbolicLink == true {
+ links.append(path)
+ } else if values?.isDirectory != true {
+ files.append(path)
+ }
+ }
+ return (files.sorted(), links.sorted())
+ }
+
+ @Test("A real rebuild keeps every profile file and lands on the steamuser layout")
+ func realRebuildKeepsBothProfiles() throws {
+ for original in RealPrefixes.candidates {
+ let prefix = try clone(original)
+ defer { try? FileManager.default.removeItem(at: prefix.library.root) }
+
+ let before = inventory(prefix.pfx)
+ let registry = try Data(contentsOf: prefix.pfx.appending(path: "user.reg"))
+
+ // No prefix here has one, so a game installed by hand is planted to be found.
+ let stray = prefix.pfx.appending(path: "drive_c/Games/Quake/quake.exe")
+ try FileManager.default.createDirectory(
+ at: stray.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data("exe".utf8).write(to: stray)
+
+ try PrefixTools.recreate(prefix)
+ let after = inventory(prefix.pfx)
+
+ // Both profile names fold to one directory after a rebuild, as do the documents names
+ // and BACKUP, which parks shared saves. That also hides a BACKUP the player made.
+ func normalised(_ paths: [String]) -> Set<String> {
+ Set(paths.map { path in
+ var parts = path.split(separator: "/").map(String.init)
+ guard !parts.isEmpty else { return path }
+ parts = parts.map { $0.replacing(#/ BACKUP( \d+)?$/#, with: "") }
+ parts[0] = "profile"
+ if parts.count > 1, ["Documents", "My Documents"].contains(parts[1]) {
+ parts[1] = "documents"
+ }
+ return parts.joined(separator: "/")
+ })
+ }
+ #expect(normalised(after.files) == normalised(before.files),
+ "\(prefix.appID) lost profile files")
+ #expect(try Data(contentsOf: prefix.pfx.appending(path: "user.reg")) == registry)
+ #expect(try Data(contentsOf: stray) == Data("exe".utf8), "\(prefix.appID) lost C:\\Games")
+
+ // Steam resolves a cloud rule under steamuser and CrossOver reads the name it fixes
+ // on, so the one has to be the directory and the other the link to it.
+ let users = prefix.pfx.appending(path: "drive_c/users")
+ let crossover = users.appending(path: "crossover")
+ let steamuser = users.appending(path: "steamuser")
+ #expect(try FileManager.default.destinationOfSymbolicLink(
+ atPath: crossover.path(percentEncoded: false)) == "steamuser")
+ #expect((try? steamuser.resourceValues(forKeys: [.isSymbolicLinkKey]))?
+ .isSymbolicLink != true)
+
+ // Whichever name holds the files, a game asking for the other one has to arrive.
+ let documents = steamuser.appending(path: "Documents")
+ let preVista = steamuser.appending(path: "My Documents")
+ for name in [documents, preVista] {
+ var resolved = ObjCBool(false)
+ #expect(FileManager.default.fileExists(
+ atPath: name.path(percentEncoded: false), isDirectory: &resolved))
+ #expect(resolved.boolValue)
+ }
+
+ // Steam syncs saves from inside the prefix, so no redirected folder may resolve
+ // back out to the mac home. Known folders only, the bug was those leading out.
+ let inside = prefix.pfx.resolvingSymlinksInPath().path(percentEncoded: false)
+ for folder in ["Documents", "My Documents", "Downloads", "Music", "Pictures", "Videos"] {
+ let resolved = steamuser.appending(path: folder)
+ .resolvingSymlinksInPath().path(percentEncoded: false)
+ #expect(resolved.hasPrefix(inside),
+ "\(prefix.appID) resolves \(folder) to \(resolved)")
+ }
+
+ // The windows tree is the fresh one, for the arch the installed runner builds.
+ let ntdll = prefix.pfx.appending(path: "drive_c/windows/system32/ntdll.dll")
+ #expect(PrefixStore.arch(of: prefix) == PrefixTools.prefixArch())
+ #expect(FileManager.default.fileExists(atPath: ntdll.path(percentEncoded: false)))
+ }
+ }
+}
diff --git a/app/Tests/NotProtonAppTests/RunnerInstallerTests.swift b/app/Tests/NotProtonAppTests/RunnerInstallerTests.swift
new file mode 100644
index 0000000..f09442e
--- /dev/null
+++ b/app/Tests/NotProtonAppTests/RunnerInstallerTests.swift
@@ -0,0 +1,238 @@
+import Foundation
+import Testing
+
+@testable import NotProtonApp
+
+@Suite("Pointing the current runner")
+struct RunnerInstallerTests {
+
+ private func makeRunners() throws -> URL {
+ let runners = FileManager.default.temporaryDirectory
+ .appending(path: "np-point-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: runners, withIntermediateDirectories: true)
+ return runners
+ }
+
+ @Test("The link is relative and in the form the run script expects")
+ func writesRelativeTarget() throws {
+ let runners = try makeRunners()
+ defer { try? FileManager.default.removeItem(at: runners) }
+
+ try RunnerInstaller.pointCurrent(atBuild: "27.0.0.40921", runners: runners)
+
+ let target = try FileManager.default.destinationOfSymbolicLink(
+ atPath: runners.appending(path: "current").path(percentEncoded: false)
+ )
+ #expect(target == "crossover-27.0.0.40921/CrossOver")
+ }
+
+ // Switching builds happens over a link that already exists, and rename is what
+ // makes that a single step rather than an unlink the launch path could land in.
+ @Test("An existing link is replaced")
+ func replacesExistingLink() throws {
+ let runners = try makeRunners()
+ defer { try? FileManager.default.removeItem(at: runners) }
+
+ try RunnerInstaller.pointCurrent(atBuild: "1.0.0.1", runners: runners)
+ try RunnerInstaller.pointCurrent(atBuild: "2.0.0.2", runners: runners)
+
+ let target = try FileManager.default.destinationOfSymbolicLink(
+ atPath: runners.appending(path: "current").path(percentEncoded: false)
+ )
+ #expect(target.hasPrefix("crossover-2.0.0.2/"))
+
+ // No staging file left behind, or the next attempt starts from a dirty state.
+ #expect(!FileManager.default.fileExists(
+ atPath: runners.appending(path: ".current.new").path(percentEncoded: false)
+ ))
+ }
+
+ @Test("A directory in the way is reported instead of being worked around")
+ func refusesDirectoryInTheWay() throws {
+ let runners = try makeRunners()
+ defer { try? FileManager.default.removeItem(at: runners) }
+
+ try FileManager.default.createDirectory(
+ at: runners.appending(path: "current"), withIntermediateDirectories: true
+ )
+
+ #expect(throws: StepFailure.self) {
+ try RunnerInstaller.pointCurrent(atBuild: "1.0.0.1", runners: runners)
+ }
+ #expect(!FileManager.default.fileExists(
+ atPath: runners.appending(path: ".current.new").path(percentEncoded: false)
+ ))
+ }
+
+ // The clone is found afterwards at a fixed name inside the build directory, so the copy has
+ // to land as a child. cp keys that off the destination existing, and first time it does not.
+ @Test("The copy lands as a payload directory inside the build directory")
+ func copyLandsAsChildOfBuildDirectory() throws {
+ let runners = try makeRunners()
+ defer { try? FileManager.default.removeItem(at: runners) }
+
+ let source = runners.appending(path: "source/CrossOver Preview.app/Contents/SharedSupport/CrossOver")
+ try FileManager.default.createDirectory(
+ at: source.appending(path: "lib/wine"), withIntermediateDirectories: true
+ )
+
+ let version = "27.0.0.40921"
+ let target = SupportPaths.runnerRoot(forBuild: version, runners: runners)
+ try RunnerInstaller.copyPayload(from: source, to: target)
+
+ #expect(FileManager.default.fileExists(
+ atPath: target.appending(path: "CrossOver/lib/wine").path(percentEncoded: false)
+ ))
+
+ // The check the setup path runs next has to agree, because that is where a wrongly
+ // shaped copy was being reported.
+ #expect(RunnerInstaller.hasClone(forBuild: version, runners: runners))
+ }
+
+ // A CrossOver bundle holding only the files the clone path hashes, with the build describing
+ // those exact bytes, so verification passes without a real 1.2G install to copy.
+ private func makeSupportedInstall(in directory: URL) throws -> (CrossOverInstall, RunnerBuild) {
+ let bundle = directory.appending(path: "source/CrossOver Preview.app")
+ let wine = bundle.appending(path: "Contents/SharedSupport/CrossOver/lib/wine")
+
+ for arch in WineArch.allCases {
+ try FileManager.default.createDirectory(
+ at: wine.appending(path: arch.rawValue), withIntermediateDirectories: true
+ )
+ try Data("ntdll for \(arch.rawValue)".utf8)
+ .write(to: wine.appending(path: "\(arch.rawValue)/ntdll.dll"))
+ }
+ try FileManager.default.createDirectory(
+ at: wine.appending(path: "x86_64-unix"), withIntermediateDirectories: true
+ )
+ try Data("wine loader".utf8).write(to: wine.appending(path: "x86_64-unix/wine"))
+
+ func hash(_ url: URL) throws -> String {
+ try #require(Digest.sha256IfPresent(url))
+ }
+
+ var clean: [WineArch: String] = [:]
+ for arch in WineArch.allCases {
+ clean[arch] = try hash(wine.appending(path: "\(arch.rawValue)/ntdll.dll"))
+ }
+
+ let build = RunnerBuild(
+ bundleVersion: "27.0.0.40921",
+ releaseVersion: "20260821",
+ flavor: nil,
+ loaderSHA256: try hash(wine.appending(path: "x86_64-unix/wine")),
+ cleanNtdll: clean,
+ patchedNtdll: [:]
+ )
+ let install = CrossOverInstall(
+ bundle: bundle, releaseVersion: build.releaseVersion, support: .supported(build)
+ )
+ return (install, build)
+ }
+
+ // The first attempt left the build directory holding the payload's contents, not the payload.
+ // Setup read that as a finished clone, skipped the copy, then failed the lookup itself.
+ @Test("A build directory with no payload in it is cloned again rather than trusted")
+ func replacesACloneThatHasNoPayloadInIt() throws {
+ let runners = try makeRunners()
+ defer { try? FileManager.default.removeItem(at: runners) }
+
+ let (install, build) = try makeSupportedInstall(in: runners)
+
+ let target = SupportPaths.runnerRoot(forBuild: build.bundleVersion, runners: runners)
+ try FileManager.default.createDirectory(
+ at: target.appending(path: "Contents/SharedSupport/CrossOver"),
+ withIntermediateDirectories: true
+ )
+
+ _ = try RunnerInstaller.clone(from: install, runners: runners)
+
+ #expect(RunnerInstaller.hasClone(forBuild: build.bundleVersion, runners: runners))
+
+ // The leftover contents must be gone, not left beside the payload.
+ #expect(!FileManager.default.fileExists(
+ atPath: target.appending(path: "Contents").path(percentEncoded: false)
+ ))
+ }
+
+ // Keeping lib/wine is not the same as keeping the loader inside it, and the loader is what
+ // a game needs. Setup skips the copy for such a clone, so nothing else catches the loss.
+ @Test("A clone that kept its payload directory but lost its loader is refused")
+ func refusesCloneThatLostItsLoader() throws {
+ let runners = try makeRunners()
+ defer { try? FileManager.default.removeItem(at: runners) }
+
+ let (install, build) = try makeSupportedInstall(in: runners)
+ _ = try RunnerInstaller.clone(from: install, runners: runners)
+
+ let root = SupportPaths.clonedRoot(forBuild: build.bundleVersion, runners: runners)
+ try FileManager.default.removeItem(at: CrossOverSource.unixLoader(inRoot: root))
+
+ // Still counts as cloned, so the copy is skipped and the loader check is reached.
+ #expect(RunnerInstaller.hasClone(forBuild: build.bundleVersion, runners: runners))
+
+ let failure = try #require(throws: StepFailure.self) {
+ try RunnerInstaller.clone(from: install, runners: runners)
+ }
+ #expect(
+ failure.detail.contains("no Wine loader"),
+ "a clone with no loader in it was reported as something else"
+ )
+ }
+
+ // Replacing an intact clone used to remove it before the copy, so a failed copy took a
+ // working 1.2G tree with it and left runners/current dangling, with nothing in the UI.
+ @Test("A failed recopy leaves the working clone and the current link intact")
+ func keepsWorkingCloneWhenRecopyFails() throws {
+ let runners = try makeRunners()
+ defer { try? FileManager.default.removeItem(at: runners) }
+
+ let (install, build) = try makeSupportedInstall(in: runners)
+ _ = try RunnerInstaller.clone(from: install, runners: runners)
+
+ let payload = SupportPaths
+ .clonedRoot(forBuild: build.bundleVersion, runners: runners)
+ .appending(path: "lib/wine")
+ let current = runners.appending(path: "current")
+ let files = FileManager.default
+
+ // Asserted before the failure, or the checks afterwards pass on a clone that was
+ // never there to begin with.
+ #expect(files.fileExists(atPath: payload.path(percentEncoded: false)))
+ #expect(files.fileExists(atPath: current.path(percentEncoded: false)))
+
+ // Removing the source fails the copy the same way running out of room part way
+ // through does, which is the case that costs the user a working runner.
+ try files.removeItem(at: runners.appending(path: "source"))
+
+ #expect(throws: StepFailure.self) {
+ try RunnerInstaller.clone(from: install, replacingExisting: true, runners: runners)
+ }
+
+ #expect(
+ files.fileExists(atPath: payload.path(percentEncoded: false)),
+ "a recopy that failed destroyed the working clone"
+ )
+ // fileExists resolves the link, so a dangling current reads as absent here.
+ #expect(
+ files.fileExists(atPath: current.path(percentEncoded: false)),
+ "runners/current is dangling, so a launch resolves it to nothing"
+ )
+ }
+
+ @Test("The state reader agrees with what was just written")
+ func stateAgreesWithInstaller() throws {
+ let runners = try makeRunners()
+ defer { try? FileManager.default.removeItem(at: runners) }
+
+ let version = SupportedRunners.all[0].bundleVersion
+ try FileManager.default.createDirectory(
+ at: runners.appending(path: "crossover-\(version)/CrossOver/lib/wine"),
+ withIntermediateDirectories: true
+ )
+ try RunnerInstaller.pointCurrent(atBuild: version, runners: runners)
+
+ #expect(RunnerStore.state(runners: runners, verify: { _, _ in [] })
+ == .cloned(build: version, supported: true))
+ }
+}
diff --git a/app/Tests/NotProtonAppTests/RunnerPatcherTests.swift b/app/Tests/NotProtonAppTests/RunnerPatcherTests.swift
new file mode 100644
index 0000000..1e35a9d
--- /dev/null
+++ b/app/Tests/NotProtonAppTests/RunnerPatcherTests.swift
@@ -0,0 +1,177 @@
+import Foundation
+import Testing
+
+@testable import NotProtonApp
+
+@Suite("Runner patching")
+struct RunnerPatcherTests {
+
+ // Only real CrossOver bytes can answer whether a repair works, since no tree a test builds
+ // meets the pinned hashes. An APFS clone costs a second and leaves the real one alone.
+ private static func healthyClone() throws -> (root: URL, build: RunnerBuild)? {
+ // Resolved first, or cp copies runners/current itself and its relative target
+ // lands as a dangling link in the scratch directory.
+ let live = SupportPaths.currentRunner.resolvingSymlinksInPath()
+
+ // Which build is installed decides the hashes the tree is held to. Taking the first in
+ // the allow list calls a healthy tree of the other flavor broken, skipping the rest.
+ guard let id = RunnerStore.buildIdentifier(inPath: live.path(percentEncoded: false)),
+ let build = SupportedRunners.build(id: id),
+ RunnerPatcher.verify(build: build, root: live).isEmpty
+ else { return nil }
+
+ let scratch = URL(filePath: NSTemporaryDirectory())
+ .appending(path: "notproton-runner-\(UUID().uuidString)")
+ let copied = try Shell.run("/bin/cp", [
+ "-c", "-R", live.path(percentEncoded: false), scratch.path(percentEncoded: false),
+ ])
+
+ // Past the healthy check, a clone that cannot be read is this test breaking and
+ // not a machine that cannot answer, so it fails rather than skipping.
+ try #require(copied.status == 0)
+ try #require(RunnerPatcher.verify(build: build, root: scratch).isEmpty)
+
+ return (scratch, build)
+ }
+
+ // The launch path used to copy this on every run, so the button is now the only thing
+ // that closes the gap after an app update replaces the bridge copy.
+ @Test("A builtin the bridge has replaced is reported, then repaired by the install")
+ func repairsStaleBuiltin() throws {
+ guard let (root, build) = try Self.healthyClone() else { return }
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let arch = RunnerPatcher.unixArch(in: root)
+ let builtin = root.appending(path: "lib/wine/\(arch)/lsteamclient.so")
+ try Data("not the bridge copy".utf8).write(to: builtin)
+
+ #expect(RunnerPatcher.verify(build: build, root: root)
+ == ["\(arch)/lsteamclient.so is out of date"])
+
+ let outcome = try RunnerPatcher.install(build: build, root: root)
+ #expect(outcome.builtins == ["\(arch)/lsteamclient.so"])
+ #expect(RunnerPatcher.verify(build: build, root: root).isEmpty)
+ }
+
+ @Test("A builtin that was never installed is reported, then repaired by the install")
+ func repairsMissingBuiltin() throws {
+ guard let (root, build) = try Self.healthyClone() else { return }
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let builtin = root.appending(path: "lib/wine/i386-windows/lsteamclient.dll")
+ try FileManager.default.removeItem(at: builtin)
+
+ #expect(RunnerPatcher.verify(build: build, root: root)
+ == ["i386-windows/lsteamclient.dll is missing"])
+
+ _ = try RunnerPatcher.install(build: build, root: root)
+ #expect(RunnerPatcher.verify(build: build, root: root).isEmpty)
+ }
+
+ // A runner back on stock ntdll runs games that fail their ownership check, which is
+ // the failure this whole path exists to prevent.
+ @Test("A runner back on stock ntdll is reported, then repaired by the install")
+ func repairsStockNtdll() throws {
+ guard let (root, build) = try Self.healthyClone() else { return }
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let arch = WineArch.x86_64Windows
+ let live = root.appending(path: "lib/wine/\(arch.rawValue)/ntdll.dll")
+ let clean = NtdllPatcher.cleanSource(inRoot: root, arch: arch)
+ guard clean != live else { return }
+
+ try Data(contentsOf: clean).write(to: live)
+ #expect(RunnerPatcher.verify(build: build, root: root)
+ == ["\(arch.rawValue)/ntdll.dll is not the patched copy"])
+
+ let outcome = try RunnerPatcher.install(build: build, root: root)
+ #expect(outcome.ntdll == [arch])
+ #expect(Digest.sha256IfPresent(live) == build.patchedNtdll[arch])
+ #expect(RunnerPatcher.verify(build: build, root: root).isEmpty)
+ }
+
+ // Without the entitlement dyld drops the overlay insert and the game still runs, so
+ // nothing but this check reports it.
+ @Test("A loader signed without the dyld entitlement is reported, then repaired")
+ func repairsStrippedEntitlement() throws {
+ guard let (root, build) = try Self.healthyClone() else { return }
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let loader = root.appending(path: "lib/wine/x86_64-unix/wine")
+ let clean = Clean.copy(of: loader)
+ guard clean != loader else { return }
+
+ try #require(try Shell.run("/bin/cp", [
+ "-p", clean.path(percentEncoded: false), loader.path(percentEncoded: false),
+ ]).status == 0)
+
+ #expect(RunnerPatcher.verify(build: build, root: root)
+ == ["x86_64-unix/wine is missing the dyld entitlement"])
+
+ let outcome = try RunnerPatcher.install(build: build, root: root)
+ #expect(outcome.loaders == ["x86_64-unix/wine"])
+ #expect(RunnerPatcher.verify(build: build, root: root).isEmpty)
+ }
+
+ // Re-running has to be free, or the button cannot be the answer to every runner
+ // problem the UI reports.
+ @Test("Installing into a runner that is already right writes nothing")
+ func installIsIdempotent() throws {
+ guard let (root, build) = try Self.healthyClone() else { return }
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let outcome = try RunnerPatcher.install(build: build, root: root)
+ #expect(outcome.wroteNothing)
+ }
+
+ // The FEX flavor has only a wine.app in its arm64 directory, and a loader that is not found
+ // never gets the dyld entitlement. Silent at install, it shows up as a game with no dylib.
+ @Test("Loader discovery finds both the bare and the bundled layout")
+ func loaderDiscoveryCoversBothLayouts() throws {
+ let fm = FileManager.default
+ let root = URL(filePath: NSTemporaryDirectory()).appending(path: "notproton-loaders-\(UUID().uuidString)")
+ defer { try? fm.removeItem(at: root) }
+
+ let bundled = root.appending(path: "lib/wine/aarch64-unix/wine.app/Contents/MacOS/wine")
+ let bare = root.appending(path: "lib/wine/x86_64-unix/wine")
+ for file in [bundled, bare] {
+ try fm.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data().write(to: file)
+ }
+
+ // A windows directory alongside them must not be mistaken for a unix loader.
+ let windows = root.appending(path: "lib/wine/x86_64-windows/wine")
+ try fm.createDirectory(at: windows.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data().write(to: windows)
+
+ // Compared by name rather than by URL, since the temporary directory is reached
+ // through a symlink that only one of the two sides resolves.
+ let found = Set(RunnerPatcher.unixLoaders(in: root).map(RunnerPatcher.name(of:)))
+ #expect(found == ["aarch64-unix/wine.app/Contents/MacOS/wine", "x86_64-unix/wine"])
+ }
+
+ // The FEX flavor ships both unix directories and RUN_SCRIPT runs the arm64 loader, so
+ // the unix builtin installed anywhere else is one verify_runner reads as missing.
+ @Test("The unix builtin follows the loader RUN_SCRIPT picks")
+ func unixBuiltinFollowsTheLoader() throws {
+ let fm = FileManager.default
+ let root = URL(filePath: NSTemporaryDirectory()).appending(path: "notproton-unixarch-\(UUID().uuidString)")
+ defer { try? fm.removeItem(at: root) }
+
+ func write(_ path: String) throws {
+ let file = root.appending(path: path)
+ try fm.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try Data().write(to: file)
+ }
+
+ try write("lib/wine/x86_64-unix/wine")
+ #expect(RunnerPatcher.unixArch(in: root) == "x86_64-unix")
+
+ try write("lib/wine/aarch64-unix/wine.app/Contents/MacOS/wine")
+ #expect(RunnerPatcher.unixArch(in: root) == "aarch64-unix")
+
+ let arches = RunnerPatcher.builtins(in: root).map(\.arch)
+ #expect(arches == RunnerPatcher.windowsBuiltins.map(\.arch) + ["aarch64-unix"])
+ #expect(RunnerPatcher.builtins(in: root).allSatisfy { $0.name.hasPrefix("lsteamclient") })
+ }
+}
diff --git a/app/Tests/NotProtonAppTests/RunnerSetupTests.swift b/app/Tests/NotProtonAppTests/RunnerSetupTests.swift
new file mode 100644
index 0000000..128003a
--- /dev/null
+++ b/app/Tests/NotProtonAppTests/RunnerSetupTests.swift
@@ -0,0 +1,165 @@
+import Foundation
+import Testing
+
+@testable import NotProtonApp
+
+// Scratch directories rather than the live runner, so these say the same thing on a
+// machine that has never had a clone made on it.
+private func scratchDirectory() throws -> URL {
+ let url = FileManager.default.temporaryDirectory
+ .appending(path: "notproton-setup-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
+ return url
+}
+
+@Suite("Clean copy resolution")
+struct CleanTests {
+
+ @Test("The backup beside a file is preferred when it exists")
+ func backupWins() throws {
+ let dir = try scratchDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ let live = dir.appending(path: "ntdll.dll")
+ let backup = dir.appending(path: "ntdll.dll.notproton-orig")
+ try Data([1]).write(to: live)
+ try Data([2]).write(to: backup)
+
+ #expect(Clean.copy(of: live) == backup)
+ }
+
+ @Test("A file with no backup resolves to itself")
+ func noBackupResolvesToSelf() throws {
+ let dir = try scratchDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ let live = dir.appending(path: "wine")
+ try Data([1]).write(to: live)
+
+ #expect(Clean.copy(of: live) == live)
+ }
+
+ @Test("The suffix is appended, not substituted for the extension")
+ func suffixIsAppended() throws {
+ let dir = try scratchDirectory()
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ let live = dir.appending(path: "ntdll.dll")
+ let backup = dir.appending(path: "ntdll.dll.notproton-orig")
+ try Data([1]).write(to: live)
+ try Data([2]).write(to: backup)
+
+ // A rule built on deletingPathExtension would look for ntdll.notproton-orig
+ // and silently fall through to the patched file.
+ #expect(Clean.copy(of: live).lastPathComponent == "ntdll.dll.notproton-orig")
+ }
+}
+
+// The regression: verifyPatchInputs read lib/wine/<arch>/ntdll.dll directly, which holds the
+// patched file on any launched clone, so it reported a mismatch on a runner that was correct.
+@Suite("Patch input verification")
+struct PatchInputTests {
+
+ private static let cleanBytes = Data("clean ntdll".utf8)
+ private static let patchedBytes = Data("patched ntdll".utf8)
+
+ private static var build: RunnerBuild {
+ RunnerBuild(
+ bundleVersion: "test-build",
+ releaseVersion: "test-build",
+ flavor: nil,
+ loaderSHA256: "",
+ cleanNtdll: [.x86_64Windows: Digest.sha256(of: cleanBytes)],
+ patchedNtdll: [.x86_64Windows: Digest.sha256(of: patchedBytes)]
+ )
+ }
+
+ private func makeRoot(live: Data, backup: Data?) throws -> URL {
+ let root = try scratchDirectory()
+ let dir = root.appending(path: "lib/wine/x86_64-windows")
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ try live.write(to: dir.appending(path: "ntdll.dll"))
+ if let backup {
+ try backup.write(to: dir.appending(path: "ntdll.dll.notproton-orig"))
+ }
+ return root
+ }
+
+ @Test("A freshly cloned runner verifies")
+ func freshCloneVerifies() throws {
+ let root = try makeRoot(live: Self.cleanBytes, backup: nil)
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ try CrossOverSource.verifyPatchInputs(root: root, build: Self.build)
+ }
+
+ @Test("A runner that has been launched verifies through the backup")
+ func launchedCloneVerifies() throws {
+ let root = try makeRoot(live: Self.patchedBytes, backup: Self.cleanBytes)
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ try CrossOverSource.verifyPatchInputs(root: root, build: Self.build)
+ }
+
+ @Test("A patched file with no backup beside it is refused")
+ func patchedWithoutBackupIsRefused() throws {
+ let root = try makeRoot(live: Self.patchedBytes, backup: nil)
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ #expect(throws: StepFailure.self) {
+ try CrossOverSource.verifyPatchInputs(root: root, build: Self.build)
+ }
+ }
+
+ @Test("A missing ntdll is refused")
+ func missingIsRefused() throws {
+ let root = try scratchDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ #expect(throws: StepFailure.self) {
+ try CrossOverSource.verifyPatchInputs(root: root, build: Self.build)
+ }
+ }
+}
+
+@Suite("Cloned payload resolution")
+struct ClonedPayloadTests {
+
+ @Test("An intact clone is recognised by the payload inside it")
+ func findsPayload() throws {
+ let runners = try scratchDirectory()
+ defer { try? FileManager.default.removeItem(at: runners) }
+
+ let payload = SupportPaths.clonedRoot(forBuild: "1.2.3.4", runners: runners)
+ try FileManager.default.createDirectory(
+ at: payload.appending(path: "lib/wine"), withIntermediateDirectories: true
+ )
+
+ #expect(RunnerInstaller.hasClone(forBuild: "1.2.3.4", runners: runners))
+ }
+
+ @Test("A clone still shaped as an .app does not count as cloned")
+ func refusesBundleShapedClone() throws {
+ let runners = try scratchDirectory()
+ defer { try? FileManager.default.removeItem(at: runners) }
+
+ let clone = SupportPaths.runnerRoot(forBuild: "1.2.3.4", runners: runners)
+ try FileManager.default.createDirectory(
+ at: clone.appending(path: "CrossOver Preview.app/Contents/SharedSupport/CrossOver/lib/wine"),
+ withIntermediateDirectories: true
+ )
+
+ #expect(!RunnerInstaller.hasClone(forBuild: "1.2.3.4", runners: runners))
+ }
+
+ @Test("A clone with no payload in it does not count as cloned")
+ func refusesCloneWithoutPayload() throws {
+ let runners = try scratchDirectory()
+ defer { try? FileManager.default.removeItem(at: runners) }
+
+ let clone = SupportPaths.runnerRoot(forBuild: "1.2.3.4", runners: runners)
+ try FileManager.default.createDirectory(at: clone, withIntermediateDirectories: true)
+
+ #expect(!RunnerInstaller.hasClone(forBuild: "1.2.3.4", runners: runners))
+ }
+}
diff --git a/app/Tests/NotProtonAppTests/RunnerStateTests.swift b/app/Tests/NotProtonAppTests/RunnerStateTests.swift
new file mode 100644
index 0000000..0660d50
--- /dev/null
+++ b/app/Tests/NotProtonAppTests/RunnerStateTests.swift
@@ -0,0 +1,134 @@
+import Foundation
+import Testing
+
+@testable import NotProtonApp
+
+@Suite("Runner state detection")
+struct RunnerStateTests {
+
+ // A stand in for the runners directory, built the same way the installer builds
+ // the real one: a versioned directory plus a current symlink pointing into it.
+ struct Fixture: ~Copyable {
+ let runners: URL
+
+ init() throws {
+ runners = FileManager.default.temporaryDirectory
+ .appending(path: "np-runners-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: runners, withIntermediateDirectories: true)
+ }
+
+ func makeClone(build: String, withWine: Bool = true, inBundle: Bool = false) throws -> String {
+ let payload = inBundle ? "CrossOver Preview.app/Contents/SharedSupport/CrossOver" : "CrossOver"
+ let relative = "crossover-\(build)/\(payload)"
+ let root = runners.appending(path: relative)
+ let leaf = withWine ? root.appending(path: "lib/wine") : root
+ try FileManager.default.createDirectory(at: leaf, withIntermediateDirectories: true)
+ return relative
+ }
+
+ func linkCurrent(to relative: String) throws {
+ try FileManager.default.createSymbolicLink(
+ atPath: runners.appending(path: "current").path(percentEncoded: false),
+ withDestinationPath: relative
+ )
+ }
+
+ deinit { try? FileManager.default.removeItem(at: runners) }
+ }
+
+ @Test("No current link means nothing is set up")
+ func reportsNone() throws {
+ let fixture = try Fixture()
+ #expect(RunnerStore.state(runners: fixture.runners) == .none)
+ }
+
+ @Test("A supported clone is reported with its build")
+ func reportsSupportedClone() throws {
+ let fixture = try Fixture()
+ let version = SupportedRunners.all[0].bundleVersion
+ try fixture.linkCurrent(to: fixture.makeClone(build: version))
+
+ #expect(RunnerStore.state(runners: fixture.runners, verify: { _, _ in [] })
+ == .cloned(build: version, supported: true))
+ }
+
+ // The launch path only reads the runner, so a clone the app never finished patching
+ // has to be caught here rather than by a game failing its ownership check.
+ @Test("A clone missing a file the app installs is reported as unpatched")
+ func reportsUnpatchedClone() throws {
+ let fixture = try Fixture()
+ let version = SupportedRunners.all[0].bundleVersion
+ try fixture.linkCurrent(to: fixture.makeClone(build: version))
+
+ #expect(RunnerStore.state(runners: fixture.runners, verify: { _, _ in ["ntdll is stock"] })
+ == .unpatched(build: version, problems: ["ntdll is stock"]))
+ }
+
+ // A clone made by an older release of the app stays on disk and keeps working,
+ // so it is reported rather than treated as broken.
+ @Test("A clone outside the allow list is reported as unsupported")
+ func reportsUnsupportedClone() throws {
+ let fixture = try Fixture()
+ try fixture.linkCurrent(to: fixture.makeClone(build: "1.0.0.1"))
+
+ #expect(RunnerStore.state(runners: fixture.runners) == .cloned(build: "1.0.0.1", supported: false))
+ }
+
+ // Nothing about this clone is visibly wrong, and it runs, so only the shape says
+ // the launch path has no way to install the ntdll patch into it.
+ @Test("A clone still inside an .app is reported as the older layout")
+ func reportsBundleShapedClone() throws {
+ let fixture = try Fixture()
+ let version = SupportedRunners.all[0].bundleVersion
+ try fixture.linkCurrent(to: fixture.makeClone(build: version, inBundle: true))
+
+ #expect(RunnerStore.state(runners: fixture.runners) == .bundleShaped(build: version))
+ }
+
+ @Test("A link to a tree with no lib/wine is broken")
+ func detectsIncompleteTree() throws {
+ let fixture = try Fixture()
+ try fixture.linkCurrent(to: fixture.makeClone(build: "27.0.0.40921", withWine: false))
+
+ guard case .broken = RunnerStore.state(runners: fixture.runners) else {
+ Issue.record("expected broken, got \(RunnerStore.state(runners: fixture.runners))")
+ return
+ }
+ }
+
+ @Test("A dangling link is broken")
+ func detectsDanglingLink() throws {
+ let fixture = try Fixture()
+ try fixture.linkCurrent(to: "crossover-27.0.0.40921/nothing/here")
+
+ guard case .broken = RunnerStore.state(runners: fixture.runners) else {
+ Issue.record("expected broken for a dangling link")
+ return
+ }
+ }
+
+ // This is the case the trailing slash bug hid: with a directory URL, lstat
+ // resolves through the link and a real clone looks like a plain directory.
+ @Test("A directory in place of the link is broken, not mistaken for a clone")
+ func detectsDirectoryInsteadOfLink() throws {
+ let fixture = try Fixture()
+ try FileManager.default.createDirectory(
+ at: fixture.runners.appending(path: "current/lib/wine"), withIntermediateDirectories: true
+ )
+
+ guard case .broken(let detail) = RunnerStore.state(runners: fixture.runners) else {
+ Issue.record("expected broken for a directory in place of the link")
+ return
+ }
+ #expect(detail.contains("symlink"))
+ }
+
+ @Test("Clones are listed by version")
+ func listsClones() throws {
+ let fixture = try Fixture()
+ _ = try fixture.makeClone(build: "27.0.0.40921")
+ _ = try fixture.makeClone(build: "26.0.0.1")
+
+ #expect(RunnerStore.clonedBuilds(in: fixture.runners) == ["26.0.0.1", "27.0.0.40921"])
+ }
+}
diff --git a/app/Tests/NotProtonAppTests/ShellTests.swift b/app/Tests/NotProtonAppTests/ShellTests.swift
new file mode 100644
index 0000000..bb8bf6c
--- /dev/null
+++ b/app/Tests/NotProtonAppTests/ShellTests.swift
@@ -0,0 +1,123 @@
+import Foundation
+import Testing
+
+@testable import NotProtonApp
+
+@Suite("Shell")
+struct ShellTests {
+
+ private func absentPath() -> String {
+ URL.temporaryDirectory
+ .appending(path: "np-absent-\(UUID().uuidString)")
+ .path(percentEncoded: false)
+ }
+
+ @Test("Output bigger than the pipe buffer comes back whole")
+ func drainsMoreThanThePipeBufferHolds() throws {
+ let root = URL.temporaryDirectory.appending(path: "np-shell-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let file = root.appending(path: "big.txt")
+
+ // Several megabytes against a 64K pipe buffer. A child filling the pipe while the parent
+ // waits for it to exit cannot progress, so this hangs if the two reads stop overlapping.
+ let chunk = Data(String(repeating: "notproton ", count: 1024).utf8)
+ var payload = Data()
+ for _ in 0..<512 { payload.append(chunk) }
+ try payload.write(to: file)
+
+ let result = try Shell.run("/bin/cat", [file.path(percentEncoded: false)])
+
+ #expect(result.succeeded)
+ #expect(result.stdout.utf8.count == payload.count)
+ }
+
+ @Test("A command that fails is reported, not thrown")
+ func reportsANonZeroExit() throws {
+ let result = try Shell.run("/usr/bin/false", [])
+
+ #expect(!result.succeeded)
+ #expect(result.status == 1)
+ }
+
+ @Test("The two streams are kept apart")
+ func separatesStderrFromStdout() throws {
+ let result = try Shell.run("/bin/cat", [absentPath()])
+
+ #expect(!result.succeeded)
+ #expect(result.stdout.isEmpty)
+ #expect(result.stderr.contains("No such file"))
+ }
+
+ @Test("A checked command carries the command, status and stderr")
+ func checkReportsWhatFailed() throws {
+ let failure = #expect(throws: CommandFailure.self) {
+ try Shell.check("/bin/cat", [absentPath()])
+ }
+
+ #expect(failure?.command == "cat")
+ #expect(failure?.status != 0)
+ #expect(failure?.errorDescription?.contains("No such file") == true)
+ }
+
+ // A backgrounded grandchild holds both write ends open after the child is gone, as
+ // wineserver does. The drain gives up, and lost output must not read as empty output.
+ @Test("Output that could not be collected is reported as lost, not as empty")
+ func reportsOutputItCouldNotCollect() throws {
+ let result = try Shell.run(
+ "/bin/sh", ["-c", "printf hello; sleep 3 & exit 3"], drainTimeout: .milliseconds(200))
+
+ #expect(result.status == 3)
+ #expect(result.outputLost)
+ #expect(result.stdout.isEmpty)
+ }
+
+ @Test("Output that was collected is not reported as lost")
+ func doesNotReportCollectedOutputAsLost() throws {
+ let result = try Shell.run("/bin/echo", ["hello"], drainTimeout: .milliseconds(200))
+
+ #expect(result.succeeded)
+ #expect(!result.outputLost)
+ #expect(result.stdout == "hello\n")
+ }
+
+ @Test("A checked command says so when its output was lost")
+ func checkSaysWhenOutputWasLost() throws {
+ let failure = #expect(throws: CommandFailure.self) {
+ try Shell.check(
+ "/bin/sh", ["-c", "sleep 3 & exit 3"], drainTimeout: .milliseconds(200))
+ }
+
+ #expect(failure?.status == 3)
+ #expect(failure?.errorDescription?.contains("still open") == true)
+ }
+
+ private func stubPgrep(body: String) throws -> (String, URL) {
+ let dir = URL.temporaryDirectory.appending(path: "np-pgrep-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ let path = dir.appending(path: "pgrep")
+ try Data("#!/bin/sh\n\(body)\n".utf8).write(to: path)
+ try FileManager.default.setAttributes(
+ [.posixPermissions: 0o755], ofItemAtPath: path.path(percentEncoded: false))
+ return (path.path(percentEncoded: false), dir)
+ }
+
+ // A match whose pid list never arrived used to report nothing running.
+ @Test("A match still counts when its output is not collected")
+ func aMatchWithLostOutputStillCounts() throws {
+ let (pgrep, dir) = try stubPgrep(body: "echo 123; sleep 3 & exit 0")
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ #expect(Shell.processIsRunning(
+ named: "anything", pgrep: pgrep, drainTimeout: .milliseconds(200)))
+ }
+
+ @Test("Nothing matching reports nothing running")
+ func noMatchReportsNothingRunning() throws {
+ let (pgrep, dir) = try stubPgrep(body: "exit 1")
+ defer { try? FileManager.default.removeItem(at: dir) }
+
+ #expect(Shell.processIsRunning(named: "anything", pgrep: pgrep) == false)
+ #expect(Shell.processIsRunning(named: "anything", pgrep: absentPath()) == false)
+ }
+}
diff --git a/app/Tests/NotProtonAppTests/ShimAgreementTests.swift b/app/Tests/NotProtonAppTests/ShimAgreementTests.swift
new file mode 100644
index 0000000..5a460ba
--- /dev/null
+++ b/app/Tests/NotProtonAppTests/ShimAgreementTests.swift
@@ -0,0 +1,77 @@
+import Foundation
+import Testing
+
+@testable import NotProtonApp
+
+// The app writes the runner and RUN_SCRIPT reads it back, in two languages nothing at build
+// time holds together, so a file the shim never checks goes stale. Both lists are parsed out.
+@Suite("Shim agreement")
+struct ShimAgreementTests {
+
+ private static func runScript() throws -> String {
+ let repo = URL(filePath: #filePath)
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+ return try String(
+ contentsOf: repo.appending(path: "dylib/feats/compat_run.sh"), encoding: .utf8)
+ }
+
+ private static func verifyRunnerBlock() throws -> String {
+ let script = try runScript()
+ let start = try #require(script.range(of: "verify_runner() {"))
+ let rest = script[start.upperBound...]
+ let end = try #require(rest.range(of: "\n}\n"))
+ return String(rest[..<end.lowerBound])
+ }
+
+ // Each loop the shim runs over an arch list, in the order they appear.
+ private static func archLists(in block: String) -> [Set<String>] {
+ block.split(separator: "\n").compactMap { line in
+ guard let marker = line.range(of: "for arch in ") else { return nil }
+ let tail = line[marker.upperBound...]
+ guard let semicolon = tail.firstIndex(of: ";") else { return nil }
+ return Set(tail[..<semicolon].split(separator: " ").map(String.init))
+ }
+ }
+
+ @Test("The shim checks the ntdll arches the app patches")
+ func ntdllArchesAgree() throws {
+ let lists = Self.archLists(in: try Self.verifyRunnerBlock())
+ #expect(lists.count == 2)
+ #expect(lists.first == Set(WineArch.allCases.map(\.rawValue)))
+ }
+
+ @Test("The shim checks the builtins the app installs")
+ func builtinsAgree() throws {
+ let block = try Self.verifyRunnerBlock()
+ let lists = Self.archLists(in: block)
+
+ #expect(lists.count == 2)
+
+ // The windows halves are named literally. The unix one is whichever arch directory the
+ // loader turned up in, so both sides resolve that rather than naming a fixed arch.
+ let arches = try #require(lists.last)
+ let unix = "\"${wine_unix##*/}\""
+ #expect(arches.contains(unix))
+ #expect(arches.subtracting([unix]) == Set(RunnerPatcher.windowsBuiltins.map(\.arch)))
+
+ for builtin in RunnerPatcher.windowsBuiltins {
+ #expect(block.contains(builtin.name))
+ }
+ #expect(block.contains("lsteamclient.so"))
+ }
+
+ // A runner write left in the shim is the layout problem coming back: writing into the
+ // runner at launch is what failed silently when it needed a permission Steam lacks.
+ @Test("The shim no longer writes into the runner")
+ func shimOnlyReadsTheRunner() throws {
+ let script = try Self.runScript()
+ for line in script.split(separator: "\n") {
+ let writes = line.contains("cp -f") || line.contains("codesign ")
+ guard writes, line.contains("$CX_ROOT") else { continue }
+ Issue.record("RUN_SCRIPT writes into the runner: \(line.trimmingCharacters(in: .whitespaces))")
+ }
+ }
+}
diff --git a/app/Tests/NotProtonAppTests/SteamBundleTests.swift b/app/Tests/NotProtonAppTests/SteamBundleTests.swift
new file mode 100644
index 0000000..0607e24
--- /dev/null
+++ b/app/Tests/NotProtonAppTests/SteamBundleTests.swift
@@ -0,0 +1,162 @@
+import Foundation
+import Testing
+
+@testable import NotProtonApp
+
+@Suite("Steam bundle")
+struct SteamBundleTests {
+
+ // The bug this guards was live: the sweep covered only the bundle being replaced, and the
+ // helpers do not run from there, so an ipcserver survived a stop that reported success.
+ @Test("The process sweep covers the helpers as well as the bundle being modified")
+ func sweepCoversHelpers() {
+ let patterns = SteamBundle.sweepPatterns(
+ app: SupportPaths.Steam.app, helpers: [SupportPaths.Steam.innerApp]
+ )
+
+ #expect(patterns.count == 2)
+ #expect(patterns.contains("/Applications/Steam.app/"))
+ #expect(
+ patterns.contains { $0.hasSuffix("/Steam.AppBundle/Steam/") },
+ "the inner bundle, where ipcserver and the helpers actually run, is not swept"
+ )
+ }
+
+ // Without it, the pattern matches any process whose command line merely mentions the
+ // path, including this test runner.
+ @Test("Every pattern is directory-scoped")
+ func patternsAreDirectoryScoped() {
+ let patterns = SteamBundle.sweepPatterns(
+ app: URL(filePath: "/tmp/Some.app"), helpers: [URL(filePath: "/tmp/Inner")]
+ )
+
+ #expect(patterns.allSatisfy { $0.hasSuffix("/") })
+ #expect(patterns == ["/tmp/Some.app/", "/tmp/Inner/"])
+ }
+
+ @Test("Sweeping nothing is possible, so a test can stop short of killing helpers")
+ func helpersCanBeEmpty() {
+ let patterns = SteamBundle.sweepPatterns(app: URL(filePath: "/tmp/A.app"), helpers: [])
+ #expect(patterns == ["/tmp/A.app/"])
+ }
+
+ private enum Insert {
+ case absent
+ case own
+ case other(String)
+ }
+
+ private func stubBundle(insert: Insert, dylib: Bool) throws -> URL {
+ let app = URL.temporaryDirectory
+ .appending(path: "np-deploy-\(UUID().uuidString)")
+ .appending(path: "Steam.app")
+ let macOS = app.appending(path: "Contents/MacOS")
+ try FileManager.default.createDirectory(at: macOS, withIntermediateDirectories: true)
+
+ var plist: [String: Any] = ["CFBundleIdentifier": "com.valvesoftware.steam"]
+ switch insert {
+ case .absent:
+ break
+ case .own:
+ let own = SupportPaths.Steam.deployedDylib(inBundle: app)
+ plist[SteamBundle.environmentKey] = [
+ SteamBundle.insertKey: own.path(percentEncoded: false)
+ ]
+ case .other(let value):
+ plist[SteamBundle.environmentKey] = [SteamBundle.insertKey: value]
+ }
+ try PropertyListSerialization
+ .data(fromPropertyList: plist, format: .xml, options: 0)
+ .write(to: app.appending(path: "Contents/Info.plist"))
+
+ if dylib {
+ try Data("stand-in\n".utf8).write(to: macOS.appending(path: SupportPaths.dylibName))
+ }
+ return app
+ }
+
+ private func versionFile(_ version: String?) throws -> URL {
+ let root = URL.temporaryDirectory.appending(path: "np-version-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ let url = root.appending(path: "dylib.version")
+ if let version { try Data("\(version)\n".utf8).write(to: url) }
+ return url
+ }
+
+ @Test("A bundle patched for this account with a matching version reads as installed")
+ func installedForThisAccount() throws {
+ #expect(
+ SteamBundle.deployment(
+ bundledVersion: "0.2.0",
+ app: try stubBundle(insert: .own, dylib: true),
+ versionFile: try versionFile("0.2.0")
+ ) == .installed(version: "0.2.0")
+ )
+ }
+
+ @Test("A bundle patched by another account reports no version rather than a clean install")
+ func patchedByAnotherAccount() throws {
+ #expect(
+ SteamBundle.deployment(
+ bundledVersion: "0.2.0",
+ app: try stubBundle(insert: .own, dylib: true),
+ versionFile: try versionFile(nil)
+ ) == .installed(version: nil)
+ )
+ }
+
+ @Test("A plist naming a dylib that is not there reads as not installed")
+ func namedDylibMissing() throws {
+ #expect(
+ SteamBundle.deployment(
+ bundledVersion: "0.2.0",
+ app: try stubBundle(insert: .own, dylib: false),
+ versionFile: try versionFile("0.2.0")
+ ) == .notInstalled
+ )
+ }
+
+ @Test("An older recorded version reads as outdated")
+ func outdatedVersion() throws {
+ #expect(
+ SteamBundle.deployment(
+ bundledVersion: "0.2.0",
+ app: try stubBundle(insert: .own, dylib: true),
+ versionFile: try versionFile("0.1.0")
+ ) == .outdated(deployed: "0.1.0", bundled: "0.2.0")
+ )
+ }
+
+ @Test("Somebody else's insert is left alone")
+ func foreignInsert() throws {
+ #expect(
+ SteamBundle.deployment(
+ bundledVersion: "0.2.0",
+ app: try stubBundle(insert: .other("/opt/other/thing.dylib"), dylib: true),
+ versionFile: try versionFile(nil)
+ ) == .foreign(insert: "/opt/other/thing.dylib")
+ )
+ }
+
+ @Test("An unpatched bundle reads as not installed")
+ func unpatched() throws {
+ #expect(
+ SteamBundle.deployment(
+ bundledVersion: "0.2.0",
+ app: try stubBundle(insert: .absent, dylib: false),
+ versionFile: try versionFile(nil)
+ ) == .notInstalled
+ )
+ }
+
+ @Test("A missing bundle reads as Steam missing")
+ func steamMissing() throws {
+ #expect(
+ SteamBundle.deployment(
+ bundledVersion: "0.2.0",
+ app: URL.temporaryDirectory.appending(path: "np-absent-\(UUID().uuidString).app"),
+ versionFile: try versionFile("0.2.0")
+ ) == .steamMissing
+ )
+ }
+}
diff --git a/app/Tests/NotProtonAppTests/SteamInstallerTests.swift b/app/Tests/NotProtonAppTests/SteamInstallerTests.swift
new file mode 100644
index 0000000..db354f0
--- /dev/null
+++ b/app/Tests/NotProtonAppTests/SteamInstallerTests.swift
@@ -0,0 +1,437 @@
+import Foundation
+import Testing
+
+@testable import NotProtonApp
+
+// Run against a real pinned Valve bundle staged into scratch, not /Applications/Steam.app.
+// The chain seals a dylib inside a bundle inside another signature. Serialized, one cache.
+@Suite("Steam installer", .serialized)
+struct SteamInstallerTests {
+
+ private func scratch() throws -> URL {
+ let url = URL.temporaryDirectory.appending(path: "np-install-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
+ return url
+ }
+
+ private func stockBundle(into work: URL) async throws -> URL {
+ let manifest = try ValvePackageManifest.bundled()
+ let bundle = try #require(manifest.bundle)
+ return try await SteamRepair.stage(
+ bundle,
+ bases: manifest.bases,
+ downloads: SupportPaths.packageDownloads,
+ work: work.appending(path: "staging")
+ )
+ }
+
+ // A stand-in payload rather than the shipped one, so the tests do not depend on make
+ // having been run. The dylib has to be a real Mach-O because it gets signed.
+ private func payload(in work: URL) throws -> InstallPayload.Located {
+ let root = work.appending(path: "payload")
+ let signatureDir = root.appending(path: "signatures/macos.arm64")
+ try FileManager.default.createDirectory(at: signatureDir, withIntermediateDirectories: true)
+
+ let source = work.appending(path: "probe.c")
+ try Data("int np_probe(void) { return 1; }\n".utf8).write(to: source)
+
+ let dylib = root.appending(path: SupportPaths.dylibName)
+ try Shell.check("/usr/bin/clang", [
+ "-dynamiclib", "-o", dylib.path(percentEncoded: false), source.path(percentEncoded: false),
+ ])
+
+ let shim = root.appending(path: "overlay-shim.dylib")
+ try FileManager.default.copyItem(at: dylib, to: shim)
+
+ let iconmaker = root.appending(path: "iconmaker")
+ try FileManager.default.copyItem(at: dylib, to: iconmaker)
+
+ let appinfo = root.appending(path: "appinfo")
+ try FileManager.default.copyItem(at: dylib, to: appinfo)
+
+ try Data("{}".utf8).write(to: signatureDir.appending(path: "1788400362.json"))
+ try Data("{}".utf8).write(to: signatureDir.appending(path: "1788652215.json"))
+
+ return try InstallPayload.locate(root: root)
+ }
+
+ private struct Fixture {
+ let work: URL
+ let app: URL
+ let payload: InstallPayload.Located
+ let support: URL
+
+ var plist: URL { app.appending(path: "Contents/Info.plist") }
+ var deployedDylib: URL { app.appending(path: "Contents/MacOS/\(SupportPaths.dylibName)") }
+ var signatures: URL { support.appending(path: "signatures/macos.arm64") }
+ var overlayShim: URL { support.appending(path: "overlay-shim.dylib") }
+ var iconmaker: URL { support.appending(path: "iconmaker") }
+ var appinfo: URL { support.appending(path: "appinfo") }
+ var deployedVersion: URL { support.appending(path: "dylib.version") }
+ var backups: URL { support.appending(path: "backups") }
+ var bridge: URL { support.appending(path: "bridge") }
+ }
+
+ private func fixture(into work: URL) async throws -> Fixture {
+ Fixture(
+ work: work,
+ app: try await stockBundle(into: work),
+ payload: try payload(in: work),
+ support: work.appending(path: "support")
+ )
+ }
+
+ // The registrar and stopper a test uses: record the call, do nothing.
+ private final class Calls: @unchecked Sendable {
+ private let lock = NSLock()
+ private var registered: [URL] = []
+ func register(_ url: URL) { lock.lock(); registered.append(url); lock.unlock() }
+ var registrations: [URL] { lock.lock(); defer { lock.unlock() }; return registered }
+ }
+
+ private func install(
+ _ fixture: Fixture,
+ version: String = "9.9.9-test",
+ calls: Calls = Calls(),
+ stopped: Bool = false
+ ) throws -> InstallOutcome {
+ try SteamInstaller.run(
+ payload: fixture.payload,
+ version: version,
+ app: fixture.app,
+ bridge: fixture.bridge,
+ signatures: fixture.signatures,
+ overlayShim: fixture.overlayShim,
+ iconmaker: fixture.iconmaker,
+ appinfo: fixture.appinfo,
+ deployedVersion: fixture.deployedVersion,
+ backups: fixture.backups,
+ stopClient: { _, onStopping in if stopped { onStopping() }; return stopped },
+ register: { calls.register($0) }
+ )
+ }
+
+ @Test("A full install puts every artifact in place and declares the insert")
+ func installsEverything() async throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+ let fixture = try await self.fixture(into: work)
+ let calls = Calls()
+
+ let outcome = try install(fixture, calls: calls)
+
+ #expect(outcome.version == "9.9.9-test")
+ #expect(outcome.signatureDatabases == 2)
+ #expect(outcome.backedUpPlist)
+ #expect(!outcome.stoppedClient)
+
+ let files = FileManager.default
+ #expect(files.fileExists(atPath: fixture.deployedDylib.path(percentEncoded: false)))
+ #expect(files.fileExists(atPath: fixture.overlayShim.path(percentEncoded: false)))
+ #expect(files.fileExists(atPath: fixture.iconmaker.path(percentEncoded: false)))
+ #expect(files.fileExists(atPath: fixture.appinfo.path(percentEncoded: false)))
+ #expect(
+ try String(contentsOf: fixture.deployedVersion, encoding: .utf8)
+ .trimmingCharacters(in: .whitespacesAndNewlines) == "9.9.9-test"
+ )
+
+ // Both databases, and the arch component preserved: the dylib builds that path
+ // itself, so a database one level up resolves nothing.
+ let installed = try files.contentsOfDirectory(atPath: fixture.signatures.path(percentEncoded: false))
+ #expect(installed.sorted() == ["1788400362.json", "1788652215.json"])
+
+ #expect(
+ SteamBundle.currentInsert(at: fixture.plist)
+ == fixture.deployedDylib.path(percentEncoded: false)
+ )
+ #expect(calls.registrations == [fixture.app], "the bundle was not re-registered")
+ }
+
+ @Test("Setting the insert keeps the rest of Valve's environment")
+ func preservesValveEnvironment() async throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+ let fixture = try await self.fixture(into: work)
+
+ // What Valve actually ships, asserted before the install rather than assumed.
+ let before = try #require(SteamBundle.readInfoPlist(at: fixture.plist))
+ let stock = try #require(before[SteamBundle.environmentKey] as? [String: Any])
+ #expect(stock["LC_ALL"] as? String == "en_US.UTF-8")
+
+ _ = try install(fixture)
+
+ let after = try #require(SteamBundle.readInfoPlist(at: fixture.plist))
+ let environment = try #require(after[SteamBundle.environmentKey] as? [String: Any])
+ #expect(environment["LC_ALL"] as? String == "en_US.UTF-8", "LC_ALL is Valve's and has to survive")
+ #expect(environment.count == 2, "only the insert should have been added")
+ #expect(after["CFBundleVersion"] as? String == "6.1", "the rest of the plist was disturbed")
+ }
+
+ @Test("The bundle is signed inner to outer, so every seal verifies afterwards")
+ func signsInnerToOuter() async throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+ let fixture = try await self.fixture(into: work)
+
+ _ = try install(fixture)
+
+ // The outer seal covers the executable and the dylib is sealed in its own right, so
+ // signing outer first would leave the bundle describing files that changed afterwards.
+ for target in [fixture.deployedDylib, fixture.app.appending(path: "Contents/MacOS/steam_osx"), fixture.app] {
+ let result = try Shell.run("/usr/bin/codesign", ["--verify", "--strict", target.path(percentEncoded: false)])
+ #expect(result.succeeded, "\(target.lastPathComponent) does not verify: \(result.stderr)")
+ }
+
+ // Valve's authority is gone, which is the whole reason repair replaces the bundle
+ // rather than editing it back.
+ let described = try Shell.run("/usr/bin/codesign", ["-dvv", fixture.app.path(percentEncoded: false)])
+ #expect(!(described.stdout + described.stderr).contains("TeamIdentifier=MXGJJ98X76"))
+ }
+
+ @Test("An insert belonging to something else stops the install and is left alone")
+ func refusesForeignInsert() async throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+ let fixture = try await self.fixture(into: work)
+
+ let foreign = "/Applications/Steam.app/Contents/MacOS/somethingelse.dylib"
+ try SteamInstaller.setInsert(at: fixture.plist, to: URL(filePath: foreign))
+
+ do {
+ _ = try install(fixture)
+ Issue.record("an install over a foreign insert was allowed")
+ } catch let failure as StepFailure {
+ #expect(failure.detail.contains("Repair your Steam install"))
+ }
+
+ #expect(SteamBundle.currentInsert(at: fixture.plist) == foreign, "the foreign insert was modified")
+ #expect(
+ !FileManager.default.fileExists(atPath: fixture.deployedDylib.path(percentEncoded: false)),
+ "the dylib was copied in despite the refusal"
+ )
+ }
+
+ @Test("Installing over an existing install is allowed and refreshes it")
+ func reinstallIsAllowed() async throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+ let fixture = try await self.fixture(into: work)
+
+ _ = try install(fixture, version: "1.0.0")
+ let second = try install(fixture, version: "2.0.0")
+
+ #expect(second.version == "2.0.0")
+ #expect(
+ try String(contentsOf: fixture.deployedVersion, encoding: .utf8)
+ .trimmingCharacters(in: .whitespacesAndNewlines) == "2.0.0"
+ )
+ // Taken by the first install, and not retaken: a backup of what NotProton itself
+ // left behind is not a backup of the original.
+ #expect(second.backedUpPlist == false)
+ }
+
+ @Test("A failure while signing puts the plist back, so the bundle still starts")
+ func revertsInsertWhenSigningFails() async throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+ let fixture = try await self.fixture(into: work)
+
+ let before = try Data(contentsOf: fixture.plist)
+
+ // Signing walks inner to outer with the client executable second, so removing it fails
+ // between the insert and the signature. That window left a Steam its own seal misses.
+ try FileManager.default.removeItem(at: fixture.app.appending(path: "Contents/MacOS/steam_osx"))
+
+ let failure = try #require(throws: StepFailure.self) { try install(fixture) }
+
+ // Asserting where the failure came from, because a test that stopped earlier
+ // than the signing step would pass on a plist that was never touched.
+ #expect(
+ failure.detail.contains("could not be signed"),
+ "the install failed before the window this test is about: \(failure.detail)"
+ )
+ #expect(
+ try Data(contentsOf: fixture.plist) == before,
+ "the plist kept the insert, so the executable no longer matches its signature"
+ )
+ #expect(SteamBundle.currentInsert(at: fixture.plist) == nil)
+ }
+
+ @Test("The plist backup records the state before the first install only")
+ func backsUpOriginalPlistOnce() async throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+ let fixture = try await self.fixture(into: work)
+
+ _ = try install(fixture)
+
+ let backup = fixture.backups.appending(path: "Info.plist.before-notproton")
+ let saved = try #require(SteamBundle.readInfoPlist(at: backup))
+ let environment = try #require(saved[SteamBundle.environmentKey] as? [String: Any])
+ #expect(environment[SteamBundle.insertKey] == nil, "the backup already carries an insert")
+ #expect(environment["LC_ALL"] as? String == "en_US.UTF-8")
+ }
+
+ @Test("A missing Steam bundle is reported as its own condition")
+ func reportsMissingBundle() async throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+ var fixture = try await self.fixture(into: work)
+ fixture = Fixture(
+ work: work,
+ app: work.appending(path: "nothing-here/Steam.app"),
+ payload: fixture.payload,
+ support: fixture.support
+ )
+
+ do {
+ _ = try install(fixture)
+ Issue.record("an install into a bundle that is not there was allowed")
+ } catch let failure as StepFailure {
+ #expect(failure.detail.contains("is not there"))
+ }
+ }
+
+ // Straight at the probe, so neither of these needs a Valve bundle to be fetched first.
+ private func bundle(writable: Bool) throws -> URL {
+ let app = try scratch().appending(path: "Steam.app")
+ try FileManager.default.createDirectory(
+ at: app.appending(path: "Contents/MacOS"), withIntermediateDirectories: true
+ )
+ if !writable {
+ try FileManager.default.setAttributes(
+ [.posixPermissions: 0o500],
+ ofItemAtPath: app.appending(path: "Contents/MacOS").path(percentEncoded: false)
+ )
+ }
+ return app
+ }
+
+ @Test("A bundle that refuses the probe is reported as a refused write")
+ func probeRefusalIsARefusal() throws {
+ let app = try bundle(writable: false)
+ let inside = app.appending(path: "Contents/MacOS").path(percentEncoded: false)
+ defer {
+ try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: inside)
+ try? FileManager.default.removeItem(at: app.deletingLastPathComponent())
+ }
+
+ let refusal = try #require(throws: WriteRefused.self) {
+ try SteamInstaller.assertBundleIsWritable(app)
+ }
+
+ #expect(refusal.path == inside)
+ }
+
+ // The probe used to call every failure a refused write, so anything that stopped it sent
+ // the user to grant a permission that had nothing to do with it.
+ @Test("A probe that fails for another reason keeps that reason")
+ func probeFailureKeepsItsOwnReason() throws {
+ let app = try scratch().appending(path: "Steam.app")
+ defer { try? FileManager.default.removeItem(at: app.deletingLastPathComponent()) }
+
+ let failure = try #require(throws: StepFailure.self) {
+ try SteamInstaller.assertBundleIsWritable(app)
+ }
+
+ #expect(failure.detail.contains("could not be written"))
+ #expect(
+ failure.detail.contains("App Management") == false,
+ "a bundle that is not there was reported as a permission to grant"
+ )
+ }
+
+ @Test("A bundle that takes the probe is left exactly as it was")
+ func probeLeavesNothingBehind() throws {
+ let app = try bundle(writable: true)
+ defer { try? FileManager.default.removeItem(at: app.deletingLastPathComponent()) }
+
+ try SteamInstaller.assertBundleIsWritable(app)
+
+ let left = try FileManager.default.contentsOfDirectory(
+ atPath: app.appending(path: "Contents/MacOS").path(percentEncoded: false)
+ )
+ #expect(left.isEmpty, "the probe file was left in the bundle")
+ }
+
+ @Test("A second account installs its own components without touching a patched Steam")
+ func secondAccountLeavesTheBundleAlone() async throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+ let fixture = try await self.fixture(into: work)
+ let files = FileManager.default
+
+ _ = try install(fixture)
+
+ let pinned = Date(timeIntervalSince1970: 1_000_000)
+ try files.setAttributes(
+ [.modificationDate: pinned],
+ ofItemAtPath: fixture.deployedDylib.path(percentEncoded: false)
+ )
+ try files.removeItem(at: fixture.support)
+
+ let outcome = try install(fixture, stopped: true)
+
+ #expect(!outcome.stoppedClient, "Steam was stopped for an install that changed nothing")
+ #expect(!outcome.backedUpPlist)
+ #expect(outcome.signatureDatabases == 2)
+
+ let untouched = try files.attributesOfItem(
+ atPath: fixture.deployedDylib.path(percentEncoded: false)
+ )[.modificationDate] as? Date
+ #expect(untouched == pinned, "the deployed dylib was rewritten")
+
+ #expect(files.fileExists(atPath: fixture.overlayShim.path(percentEncoded: false)))
+ #expect(files.fileExists(atPath: fixture.iconmaker.path(percentEncoded: false)))
+ #expect(files.fileExists(atPath: fixture.appinfo.path(percentEncoded: false)))
+ #expect(
+ try files.contentsOfDirectory(atPath: fixture.signatures.path(percentEncoded: false))
+ .sorted() == ["1788400362.json", "1788652215.json"]
+ )
+ #expect(
+ try String(contentsOf: fixture.deployedVersion, encoding: .utf8)
+ .trimmingCharacters(in: .whitespacesAndNewlines) == "9.9.9-test"
+ )
+ }
+
+ @Test("A Steam carrying a different build of the dylib is patched again")
+ func differentBuildIsPatched() async throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+ let fixture = try await self.fixture(into: work)
+
+ _ = try install(fixture)
+ #expect(
+ try !SteamInstaller.needsPatching(
+ plist: fixture.plist,
+ dylib: fixture.deployedDylib,
+ shipping: fixture.payload.dylib,
+ app: fixture.app
+ )
+ )
+
+ try Data("a different build".utf8).write(to: fixture.deployedDylib)
+
+ #expect(
+ try SteamInstaller.needsPatching(
+ plist: fixture.plist,
+ dylib: fixture.deployedDylib,
+ shipping: fixture.payload.dylib,
+ app: fixture.app
+ )
+ )
+ }
+
+ @Test("A payload with nothing in it stops the install before anything is touched")
+ func refusesEmptyPayload() async throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+ let fixture = try await self.fixture(into: work)
+
+ let empty = work.appending(path: "empty-payload")
+ try FileManager.default.createDirectory(at: empty, withIntermediateDirectories: true)
+
+ #expect(throws: StepFailure.self) { try InstallPayload.locate(root: empty) }
+ #expect(SteamBundle.currentInsert(at: fixture.plist) == nil)
+ }
+}
diff --git a/app/Tests/NotProtonAppTests/SteamRepairTests.swift b/app/Tests/NotProtonAppTests/SteamRepairTests.swift
new file mode 100644
index 0000000..2dc6808
--- /dev/null
+++ b/app/Tests/NotProtonAppTests/SteamRepairTests.swift
@@ -0,0 +1,271 @@
+import Foundation
+import Testing
+
+@testable import NotProtonApp
+
+// Real package and real pin, like the Valve fetcher tests: whether the gate takes Valve's
+// actual bytes and refuses everything else is not a fixture question. Serialized, one cache.
+@Suite("Steam repair", .serialized)
+struct SteamRepairTests {
+
+ private func scratch() throws -> URL {
+ let url = URL.temporaryDirectory.appending(path: "np-repair-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
+ return url
+ }
+
+ private func stagedStockBundle(into work: URL) async throws -> URL {
+ let manifest = try ValvePackageManifest.bundled()
+ let bundle = try #require(manifest.bundle)
+ return try await SteamRepair.stage(
+ bundle,
+ bases: manifest.bases,
+ downloads: SupportPaths.packageDownloads,
+ work: work.appending(path: "staging")
+ )
+ }
+
+ @Test("The pinned package unpacks to a bundle that is signed by Valve")
+ func stagesAValveSignedBundle() async throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+ let staged = try await stagedStockBundle(into: work)
+
+ #expect(staged.lastPathComponent == "Steam.app")
+ #expect(throws: Never.self) { try SteamRepair.verifyValveSignature(staged) }
+ #expect(SteamRepair.version(of: staged) == "6.1")
+
+ // The bundle Valve ships declares LC_ALL and no insert. Everything repair does to
+ // the inner plist is measured against this, so it is asserted rather than assumed.
+ let plist = try #require(SteamBundle.readInfoPlist(at: staged.appending(path: "Contents/Info.plist")))
+ let environment = try #require(plist[SteamBundle.environmentKey] as? [String: Any])
+ #expect(environment[SteamBundle.insertKey] == nil)
+ #expect(environment["LC_ALL"] as? String == "en_US.UTF-8")
+ #expect(environment.count == 1)
+ }
+
+ // The case that actually occurs: an injected bundle is ad-hoc signed and an ad-hoc signature
+ // verifies strictly, so only the authority check catches it. Repair checks both.
+ @Test("An ad-hoc signed bundle is refused even though it verifies strictly")
+ func refusesAdHocSignedBundle() async throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+ let staged = try await stagedStockBundle(into: work)
+
+ let copy = work.appending(path: "copy/Steam.app")
+ try FileManager.default.createDirectory(at: copy.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try FileManager.default.copyItem(at: staged, to: copy)
+ try Shell.check("/usr/bin/codesign", ["-f", "-s", "-", copy.path(percentEncoded: false)])
+
+ // Strict verification passes, which is precisely the trap.
+ let strict = try Shell.run("/usr/bin/codesign", ["--verify", "--strict", copy.path(percentEncoded: false)])
+ #expect(strict.succeeded, "an ad-hoc signature was expected to verify against itself")
+
+ #expect(throws: StepFailure.self) { try SteamRepair.verifyValveSignature(copy) }
+ }
+
+ // codesign echoes the path it was given into the description it prints, so a bundle under
+ // directories named after the fields repair looks for used to answer for them.
+ @Test("A path named after the expected fields cannot answer for them")
+ func refusesFieldsSuppliedByThePath() throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+
+ let nested = work
+ .appending(path: "TeamIdentifier=\(SteamRepair.valveTeam)")
+ .appending(path: "Identifier=\(SteamRepair.valveIdentifier)")
+ let app = nested.appending(path: "Steam.app")
+ try FileManager.default.createDirectory(
+ at: app.appending(path: "Contents/MacOS"), withIntermediateDirectories: true
+ )
+ try FileManager.default.copyItem(
+ at: URL(filePath: "/bin/echo"), to: app.appending(path: "Contents/MacOS/Steam")
+ )
+ try Data(
+ """
+ <?xml version="1.0" encoding="UTF-8"?>
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" \
+ "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+ <plist version="1.0"><dict>
+ <key>CFBundleExecutable</key><string>Steam</string>
+ <key>CFBundleIdentifier</key><string>com.attacker.evil</string>
+ </dict></plist>
+ """.utf8
+ ).write(to: app.appending(path: "Contents/Info.plist"))
+
+ let path = app.path(percentEncoded: false)
+ try Shell.check("/usr/bin/codesign", ["-f", "-s", "-", path])
+
+ // The same trap as above: this verifies against itself, so only the authority
+ // check stands between it and being installed as stock.
+ let strict = try Shell.run("/usr/bin/codesign", ["--verify", "--strict", path])
+ #expect(strict.succeeded, "the ad-hoc signature was expected to verify against itself")
+
+ // And it is genuinely not Valve's, so the refusal below is the fields being
+ // matched whole rather than anything about this bundle's own signature.
+ let described = try Shell.run("/usr/bin/codesign", ["-dvv", path])
+ let text = described.stdout + described.stderr
+ #expect(text.contains("Signature=adhoc"))
+ #expect(text.contains("TeamIdentifier=not set"))
+
+ #expect(throws: StepFailure.self) { try SteamRepair.verifyValveSignature(app) }
+ }
+
+ @Test("A bundle with an added file no longer matches its signature and is refused")
+ func refusesTamperedBundle() async throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+ let staged = try await stagedStockBundle(into: work)
+
+ let copy = work.appending(path: "copy/Steam.app")
+ try FileManager.default.createDirectory(at: copy.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try FileManager.default.copyItem(at: staged, to: copy)
+ #expect(throws: Never.self) { try SteamRepair.verifyValveSignature(copy) }
+
+ // The injection this whole project performs, which is what repair exists to undo.
+ try Data("not a dylib".utf8).write(to: copy.appending(path: "Contents/MacOS/notproton.dylib"))
+
+ #expect(throws: StepFailure.self) { try SteamRepair.verifyValveSignature(copy) }
+ }
+
+ @Test("A manifest with no bundle row cannot repair")
+ func refusesManifestWithoutBundle() async throws {
+ let real = try ValvePackageManifest.bundled()
+ let without = ValvePackageManifest(
+ bases: real.bases, packages: real.packages, files: real.files, bundle: nil
+ )
+
+ await #expect(throws: StepFailure.self) {
+ try await SteamRepair.run(manifest: without)
+ }
+ }
+
+ // MARK: - The inner plist
+
+ @Test("Clearing the insert removes that key and nothing else")
+ func clearsOnlyTheInsert() throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+
+ let plist = work.appending(path: "Info.plist")
+ let stock: [String: Any] = [
+ "CFBundleVersion": "6.1",
+ SteamBundle.environmentKey: ["LC_ALL": "en_US.UTF-8"],
+ ]
+ var tampered = stock
+ tampered[SteamBundle.environmentKey] = [
+ "LC_ALL": "en_US.UTF-8",
+ SteamBundle.insertKey: "/Applications/Steam.app/Contents/MacOS/notproton.dylib",
+ ]
+ try SteamBundle.writeInfoPlist(tampered, at: plist)
+
+ #expect(try SteamRepair.clearInsert(at: plist))
+
+ let after = try #require(SteamBundle.readInfoPlist(at: plist))
+ let environment = try #require(after[SteamBundle.environmentKey] as? [String: Any])
+ #expect(environment[SteamBundle.insertKey] == nil)
+ #expect(environment["LC_ALL"] as? String == "en_US.UTF-8", "LC_ALL is Valve's and has to survive")
+ #expect(environment.count == 1, "the environment dict is kept rather than emptied")
+ #expect(after["CFBundleVersion"] as? String == "6.1")
+
+ // Running twice is not an error, and the second run reports it changed nothing.
+ #expect(try SteamRepair.clearInsert(at: plist) == false)
+ }
+
+ @Test("Clearing the insert reports nothing done when there is no plist or no insert")
+ func clearInsertIsQuietWhenThereIsNothingToDo() throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+
+ #expect(try SteamRepair.clearInsert(at: work.appending(path: "absent.plist")) == false)
+
+ let bare = work.appending(path: "bare.plist")
+ try SteamBundle.writeInfoPlist(["CFBundleVersion": "6.1"], at: bare)
+ #expect(try SteamRepair.clearInsert(at: bare) == false)
+ }
+
+ // MARK: - The invalidated backup
+
+ // What matters is that both sides agree on the name, so this drives one with the other. A
+ // test that hardcoded the name would still pass if the two diverged.
+ @Test("Repair removes the backup the installer wrote")
+ func removesTheBackupTheInstallerWrote() throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+
+ let plist = work.appending(path: "Info.plist")
+ let backups = work.appending(path: "backups")
+ try SteamBundle.writeInfoPlist(["CFBundleVersion": "6.1"], at: plist)
+
+ #expect(try SteamInstaller.backUpPlist(plist, into: backups))
+ #expect(try SteamRepair.removeStaleBackup(from: backups))
+
+ let leftovers = try FileManager.default.contentsOfDirectory(
+ atPath: backups.path(percentEncoded: false)
+ )
+ #expect(leftovers.isEmpty, "left behind: \(leftovers)")
+ }
+
+ @Test("Removing a backup that is not there is not a failure")
+ func absentBackupIsNotAFailure() throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+
+ #expect(try SteamRepair.removeStaleBackup(from: work.appending(path: "backups")) == false)
+ }
+
+ // MARK: - The swap
+
+ @Test("Replacing a bundle leaves Valve's signature intact at the destination")
+ func replaceInstallsAVerifiableBundle() async throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+ let staged = try await stagedStockBundle(into: work)
+
+ // Stand in for the tampered bundle being replaced, so this exercises the
+ // replaceItemAt path rather than the install-into-nothing one.
+ let destination = work.appending(path: "dest/Steam.app")
+ try FileManager.default.createDirectory(
+ at: destination.appending(path: "Contents/MacOS"), withIntermediateDirectories: true
+ )
+ try Data("stale".utf8).write(to: destination.appending(path: "Contents/MacOS/notproton.dylib"))
+
+ try SteamRepair.replace(destination, with: staged)
+
+ #expect(throws: Never.self) { try SteamRepair.verifyValveSignature(destination) }
+ #expect(SteamRepair.version(of: destination) == "6.1")
+ #expect(SteamBundle.currentInsert(at: destination.appending(path: "Contents/Info.plist")) == nil)
+ #expect(
+ !FileManager.default.fileExists(
+ atPath: destination.appending(path: "Contents/MacOS/notproton.dylib").path(percentEncoded: false)
+ ),
+ "the injected dylib survived the replacement"
+ )
+ }
+
+ @Test("A bundle that is not installed at all is installed rather than refused")
+ func replaceInstallsWhenNothingIsThere() async throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+ let staged = try await stagedStockBundle(into: work)
+
+ let destination = work.appending(path: "dest/Steam.app")
+ try FileManager.default.createDirectory(
+ at: destination.deletingLastPathComponent(), withIntermediateDirectories: true
+ )
+ try SteamRepair.replace(destination, with: staged)
+
+ #expect(throws: Never.self) { try SteamRepair.verifyValveSignature(destination) }
+ }
+
+ // The wording is defined once on PinnedDownload.Progress so repair and the fetcher
+ // cannot drift apart on it. This case is the only thing carrying it out of repair.
+ @Test("The download phase shows the download's own wording")
+ func downloadPhaseDelegatesItsLabel() {
+ #expect(RepairPhase.downloading(.reusing).label
+ == PinnedDownload.Progress.reusing.label)
+ #expect(RepairPhase.downloading(.fetching(host: "cdn.example")).label
+ == "Downloading from cdn.example")
+ }
+
+}
diff --git a/app/Tests/NotProtonAppTests/SystemStatusTests.swift b/app/Tests/NotProtonAppTests/SystemStatusTests.swift
new file mode 100644
index 0000000..42dae6e
--- /dev/null
+++ b/app/Tests/NotProtonAppTests/SystemStatusTests.swift
@@ -0,0 +1,542 @@
+import Foundation
+import Testing
+
+@testable import NotProtonApp
+
+// Progress reports reach the main actor as separate tasks, so one can arrive after the run
+// that issued it has finished. If it takes effect the app looks permanently busy.
+@MainActor
+@Suite("Run activity")
+struct RunActivityTests {
+
+ @Test("A run reports its progress")
+ func reportsProgress() {
+ let status = SystemStatus()
+ let run = status.beginRun("cloning")
+
+ status.report(run, "staging")
+
+ #expect(status.activity == "staging")
+ #expect(status.isBusy)
+ }
+
+ // isIdle is the single condition every button and every menu item consults, so a
+ // refresh that did not count as work would let a second action start on top of it.
+ @Test("Nothing may start while a refresh or a run is in flight")
+ func idleCoversBothKindsOfWork() {
+ let status = SystemStatus()
+ #expect(status.isIdle)
+
+ status.isRefreshing = true
+ #expect(!status.isIdle)
+
+ status.isRefreshing = false
+ let run = status.beginRun("cloning")
+ #expect(!status.isIdle)
+
+ status.report(run, "staging")
+ #expect(!status.isIdle)
+
+ status.endRun()
+ #expect(status.isIdle)
+ }
+
+ @Test("A confirmation is remembered until it is answered")
+ func pendingConfirmationSurvivesUntilCleared() {
+ let status = SystemStatus()
+ #expect(status.pendingConfirmation == nil)
+
+ status.pendingConfirmation = .blockUpdates
+ #expect(status.pendingConfirmation == .blockUpdates)
+
+ // A second ask replaces the first rather than queueing behind it, so the dialog
+ // on screen is always the one that will run if it is confirmed.
+ status.pendingConfirmation = .replaceSteam
+ #expect(status.pendingConfirmation == .replaceSteam)
+
+ status.pendingConfirmation = nil
+ #expect(status.pendingConfirmation == nil)
+ }
+
+ @Test("A finished run is not busy")
+ func finishedRunIsIdle() {
+ let status = SystemStatus()
+ _ = status.beginRun("cloning")
+
+ status.endRun()
+
+ #expect(status.activity == nil)
+ #expect(!status.isBusy)
+ }
+
+ // The bug this guards: a report queued before the run ended landed afterwards and set
+ // activity again, leaving isBusy true with nothing running and every button disabled.
+ @Test("A report that arrives after its run finished is ignored")
+ func lateReportCannotResurrectActivity() {
+ let status = SystemStatus()
+ let run = status.beginRun("cloning")
+
+ status.endRun()
+ status.report(run, "finished")
+
+ #expect(status.activity == nil)
+ #expect(!status.isBusy)
+ }
+
+ @Test("A report from an earlier run cannot disturb the run after it")
+ func staleReportDoesNotDisturbTheNextRun() {
+ let status = SystemStatus()
+ let first = status.beginRun("cloning")
+ status.endRun()
+
+ let second = status.beginRun("checking")
+ status.report(first, "staging")
+
+ #expect(status.activity == "checking")
+
+ status.report(second, "downloading")
+ #expect(status.activity == "downloading")
+ }
+
+ @Test("Every report of a run still counts, not just the first")
+ func acceptsRepeatedReports() {
+ let status = SystemStatus()
+ let run = status.beginRun("cloning")
+
+ for label in ["staging", "patching", "finished"] {
+ status.report(run, label)
+ }
+
+ #expect(status.activity == "finished")
+ }
+}
+
+@Suite("App version")
+struct AppVersionTests {
+
+ // Nothing sets CFBundleShortVersionString yet, so the fallback is what gets recorded as the
+ // deployed version. A release shipping without the real version would go unnoticed.
+ @Test("The version is never empty")
+ func versionIsNeverEmpty() {
+ #expect(!AppVersion.bundled.isEmpty)
+ #expect(!AppVersion.fallback.isEmpty)
+ }
+}
+
+// Fixture trees rather than the machine's own /Applications, so the answer does not turn
+// on whether the developer happens to have the client installed.
+@MainActor
+@Suite("Failure remedies")
+struct FailureRemedyTests {
+
+ // No .app on it, matching the client's inner bundle, which is the case that made
+ // testing the extension the wrong test.
+ private func bundle(named name: String = "Inner") throws -> URL {
+ let root = URL.temporaryDirectory.appending(path: "np-remedy-\(UUID().uuidString)")
+ let app = root.appending(path: name)
+ try FileManager.default.createDirectory(
+ at: app.appending(path: "Contents"), withIntermediateDirectories: true
+ )
+ try Data().write(to: app.appending(path: "Contents/Info.plist"))
+ return app
+ }
+
+ private func plainDirectory() throws -> URL {
+ let root = URL.temporaryDirectory.appending(path: "np-remedy-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(
+ at: root.appending(path: "compatdata/1649240"), withIntermediateDirectories: true
+ )
+ return root.appending(path: "compatdata/1649240")
+ }
+
+ @Test("A refusal inside a bundle offers the settings pane")
+ func insideABundleOffersThePane() throws {
+ let target = try bundle().appending(path: "Contents/MacOS/notproton.dylib")
+ let status = SystemStatus()
+
+ status.setFailure(WriteRefused(path: target.path(percentEncoded: false)))
+
+ #expect(status.failureRemedy == .appManagement)
+ #expect(status.failure?.contains("App Management") == true)
+ }
+
+ // The bundle root itself is refused by the repair step, so the walk has to consider the
+ // path it was given and not only the directories above it.
+ @Test("A refusal of a bundle itself offers the settings pane")
+ func theBundleItselfOffersThePane() throws {
+ let status = SystemStatus()
+
+ status.setFailure(WriteRefused(path: try bundle().path(percentEncoded: false)))
+
+ #expect(status.failureRemedy == .appManagement)
+ }
+
+ @Test("A refusal outside a bundle asks about ownership instead")
+ func outsideABundleAsksAboutOwnership() throws {
+ let target = try plainDirectory()
+ let status = SystemStatus()
+
+ status.setFailure(WriteRefused(path: target.path(percentEncoded: false)))
+
+ #expect(
+ status.failureRemedy == .ownership,
+ "a prefix the user owns was sent to a permission that cannot write it"
+ )
+ #expect(status.failureRemedy?.settingsPane == nil)
+ #expect(status.failure?.contains("App Management") == false)
+ }
+
+ @Test("A plain message does not offer the settings pane")
+ func plainFailureOffersNothing() throws {
+ let status = SystemStatus()
+ status.setFailure(WriteRefused(path: try bundle().path(percentEncoded: false)))
+
+ status.setFailure("No supported copy of CrossOver found.")
+
+ #expect(
+ status.failureRemedy == nil,
+ "the button outlived the permission failure it belonged to"
+ )
+ }
+
+ @Test("Clearing a failure clears its remedy")
+ func clearingDropsTheRemedy() throws {
+ let status = SystemStatus()
+ status.setFailure(WriteRefused(path: try bundle().path(percentEncoded: false)))
+
+ status.clearFailure()
+
+ #expect(status.failure == nil)
+ #expect(status.failureRemedy == nil)
+ }
+
+ // A typo makes URL(string:) return nil and the button do nothing at all, which looks
+ // like the app ignoring the click.
+ @Test("The settings pane is a URL that names the App Management list")
+ func settingsPaneParses() throws {
+ let pane = try #require(Remedy.appManagement.settingsPane)
+
+ #expect(pane.scheme == "x-apple.systempreferences")
+ #expect(pane.query == "Privacy_AppBundles")
+ }
+}
+
+// One row for a whole batch, so what it offers has to hold for everything in it.
+@Suite("Failure reports")
+struct FailureReportTests {
+
+ private func bundlePath() throws -> String {
+ let app = URL.temporaryDirectory.appending(path: "np-report-\(UUID().uuidString)/Steam.app")
+ try FileManager.default.createDirectory(
+ at: app.appending(path: "Contents"), withIntermediateDirectories: true
+ )
+ try Data().write(to: app.appending(path: "Contents/Info.plist"))
+ return app.path(percentEncoded: false)
+ }
+
+ @Test("Nothing refused is no report at all")
+ func emptyIsNil() {
+ #expect(FailureReport([]) == nil)
+ }
+
+ @Test("Refusals that agree offer the remedy they agree on")
+ func agreementOffersTheRemedy() throws {
+ let report = try #require(
+ FailureReport([
+ WriteRefused(path: try bundlePath()),
+ WriteRefused(path: try bundlePath()),
+ ])
+ )
+
+ #expect(report.remedy == .appManagement)
+ }
+
+ // Sending the user to App Management for a batch it fixes half of leaves the other half
+ // failing with the pane already open.
+ @Test("Refusals that disagree offer no remedy")
+ func disagreementOffersNothing() throws {
+ let report = try #require(
+ FailureReport([
+ WriteRefused(path: try bundlePath()),
+ WriteRefused(path: "/Users/nobody/compatdata/1649240"),
+ ])
+ )
+
+ #expect(report.remedy == nil)
+ #expect(report.settingsPane == nil)
+ }
+
+ @Test("One failure that is not a refusal withdraws the remedy")
+ func anUnrelatedFailureWithdrawsIt() throws {
+ let report = try #require(
+ FailureReport([
+ WriteRefused(path: try bundlePath()),
+ StepFailure(step: "Delete prefix", detail: "Portal is running. Quit the game first."),
+ ])
+ )
+
+ #expect(report.remedy == nil)
+ }
+
+ // Every refusal says the same sentence, since none of them names its path.
+ @Test("Repeated reasons are said once")
+ func repeatedReasonsCollapse() throws {
+ let report = try #require(
+ FailureReport((1...3).map { _ in WriteRefused(path: "/Users/nobody/prefix") })
+ )
+
+ #expect(
+ report.message == "Could not write files. Check permissions, make sure your user owns the folder."
+ )
+ }
+
+ @Test("A path owned by another account is not blamed on App Management")
+ func otherAccountBeatsAppManagement() throws {
+ #expect(Remedy(forPath: "/usr/bin") == .otherAccount)
+ #expect(Remedy(forPath: "/usr/bin").settingsPane == nil)
+ }
+
+ @Test("A bundle this account owns still asks for App Management")
+ func ownedBundleAsksForAppManagement() throws {
+ let root = URL.temporaryDirectory.appending(path: "np-remedy-\(UUID().uuidString)")
+ let app = root.appending(path: "Steam.app")
+ let inside = app.appending(path: "Contents/MacOS")
+ try FileManager.default.createDirectory(at: inside, withIntermediateDirectories: true)
+ try Data("{}".utf8).write(to: app.appending(path: "Contents/Info.plist"))
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ #expect(Remedy(forPath: inside.path(percentEncoded: false)) == .appManagement)
+ }
+
+ @Test("Distinct reasons are all kept")
+ func distinctReasonsSurvive() throws {
+ let report = try #require(
+ FailureReport([
+ StepFailure(step: "Delete prefix", detail: "Portal is running."),
+ StepFailure(step: "Delete prefix", detail: "Half-Life is running."),
+ ])
+ )
+
+ #expect(report.message.contains("Portal is running."))
+ #expect(report.message.contains("Half-Life is running."))
+ }
+}
+
+// A user who activates CrossOver after a refresh, then presses the button that was turned
+// down, gets the same refusal from a verdict that is no longer true.
+@MainActor
+@Suite("License freshness")
+struct LicenseFreshnessTests {
+
+ private func scratch() -> URL {
+ let dir = URL(filePath: NSTemporaryDirectory())
+ .appending(path: "np-license-\(UUID().uuidString)")
+ try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ return dir
+ }
+
+ // A bundle with no tie.pub in it, which the check turns down without reading any
+ // license file, so the verdict does not depend on what this machine is activated for.
+ private func snapshot(
+ install: CrossOverInstall?, license: CrossOverLicense.Status?, bridge: URL
+ ) -> StatusSnapshot {
+ StatusSnapshot(
+ steam: .steamMissing,
+ steamRunning: false,
+ updateBlocked: false,
+ crossOver: install.map { [$0] } ?? [],
+ crossOverLicense: license,
+ runner: .none,
+ payload: PayloadInspector.inspect(bridge: bridge)
+ )
+ }
+
+ @Test("A stale verdict is not what the next action reads")
+ func staleVerdictIsReplaced() async throws {
+ let root = scratch()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let install = CrossOverInstall(
+ bundle: root.appending(path: "CrossOver.app"),
+ releaseVersion: "20260821",
+ support: .supported(SupportedRunners.all[0])
+ )
+ let status = SystemStatus()
+ status.snapshot = snapshot(
+ install: install,
+ license: CrossOverLicense.Status(
+ licensed: true, detail: "CrossOver is activated.",
+ diagnostic: "valid license in nowhere"
+ ),
+ bridge: root
+ )
+
+ let fresh = try #require(await status.checkLicense())
+
+ #expect(!fresh.licensed, "the cached verdict was handed back instead of a new one")
+ #expect(
+ status.snapshot?.crossOverLicense?.licensed == false,
+ "the dialog would still report the verdict the check replaced"
+ )
+ }
+
+ // The gates read == false, so an install that cannot be checked at all has to stay nil
+ // rather than come back as a refusal and block the button.
+ @Test("No usable install leaves nothing to check")
+ func nothingToCheck() async {
+ let root = scratch()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let status = SystemStatus()
+ status.snapshot = snapshot(
+ install: CrossOverInstall(
+ bundle: root.appending(path: "CrossOver.app"),
+ releaseVersion: nil,
+ support: .unreadable
+ ),
+ license: nil,
+ bridge: root
+ )
+
+ #expect(await status.checkLicense() == nil)
+ }
+}
+
+// Four entry points share one answer here. The menu items used to skip it: Install dropped
+// the tool without saying so, and Set Up hit the refusal inside RunnerSetup as a failed step.
+@Suite("Activation questions")
+struct ActivationQuestionTests {
+
+ @Test("An install that would build a tool asks before going ahead unactivated")
+ func unactivatedInstallAsks() {
+ #expect(
+ SystemStatus.activationQuestion(.install, licensed: false, runner: .none)
+ == .installUnlicensed
+ )
+ }
+
+ // The dialog warns that the tool cannot be installed. With one already set up none
+ // would have been built, so the warning described something that could not happen.
+ @Test("An install asks nothing when the tool it would skip is already set up")
+ func installWithToolAsksNothing() {
+ #expect(
+ SystemStatus.activationQuestion(
+ .install, licensed: false, runner: .cloned(build: "27.0.0.40921", supported: true)
+ ) == nil
+ )
+ }
+
+ @Test("An activated install goes straight ahead")
+ func activatedInstallProceeds() {
+ #expect(SystemStatus.activationQuestion(.install, licensed: true, runner: .none) == nil)
+ }
+
+ // Unlike an install there is no reduced version to go ahead with, so this one asks
+ // whatever is already set up.
+ @Test("Setting up the tool asks whenever CrossOver is unactivated")
+ func unactivatedToolAsks() {
+ for runner in [RunnerState.none, .cloned(build: "27.0.0.40921", supported: true)] {
+ #expect(
+ SystemStatus.activationQuestion(.compatibilityTool, licensed: false, runner: runner)
+ == .toolUnlicensed
+ )
+ }
+ }
+
+ @Test("Setting up the tool goes straight ahead when CrossOver is activated")
+ func activatedToolProceeds() {
+ #expect(
+ SystemStatus.activationQuestion(.compatibilityTool, licensed: true, runner: .none)
+ == nil
+ )
+ }
+
+ // A check that could not run is not a refusal. Reading it as one would turn away every
+ // user whose CrossOver the app cannot inspect.
+ @Test("An install that could not be checked is not treated as a refusal")
+ func uncheckedProceeds() {
+ #expect(SystemStatus.activationQuestion(.install, licensed: nil, runner: .none) == nil)
+ #expect(
+ SystemStatus.activationQuestion(.compatibilityTool, licensed: nil, runner: .none) == nil
+ )
+ }
+}
+
+@MainActor
+@Suite("Run bookkeeping")
+struct PerformTests {
+
+ @Test("A run ends carrying what its body said")
+ func outcomeComesFromTheBody() async {
+ let status = SystemStatus()
+
+ await status.perform(from: "Working") { _ in "Done." }
+
+ #expect(status.outcome == "Done.")
+ #expect(status.failure == nil)
+ }
+
+ @Test("A run with nothing to say leaves no outcome behind")
+ func nothingToSayLeavesNoOutcome() async {
+ let status = SystemStatus()
+
+ await status.perform(from: "Working") { _ in "Done." }
+ await status.perform(from: "Working") { _ in nil }
+
+ #expect(status.outcome == nil)
+ }
+
+ @Test("A run drops the failure the one before it left")
+ func aRunClearsTheEarlierFailure() async {
+ let status = SystemStatus()
+ status.setFailure("Old news.")
+
+ await status.perform(from: "Working") { _ in "Done." }
+
+ #expect(status.failure == nil)
+ #expect(status.outcome == "Done.")
+ }
+
+ @Test("A body that throws ends the run as a failure and not as an outcome")
+ func aThrownErrorIsRecorded() async {
+ let status = SystemStatus()
+ // Left by an earlier run, so a failure has something to clear. Without it the
+ // outcome is already nil and the run never has to drop anything.
+ await status.perform(from: "Working") { _ in "Done." }
+
+ await status.perform(from: "Working") { _ in
+ throw StepFailure(step: "Staging", detail: "disk full")
+ }
+
+ #expect(status.failure?.contains("disk full") == true)
+ #expect(status.outcome == nil)
+ }
+
+ @Test("The opening label is on screen before the body starts")
+ func theOpeningLabelIsUpFirst() async {
+ let status = SystemStatus()
+ var seen: String?
+
+ await status.perform(from: "Cloning") { _ in
+ seen = status.activity
+ return "Done."
+ }
+
+ #expect(seen == "Cloning")
+ }
+
+ @Test("A run counts as busy until it is over")
+ func busyForTheWholeRun() async {
+ let status = SystemStatus()
+ var busyMidRun = false
+
+ await status.perform(from: "Working") { progress in
+ progress("Halfway")
+ busyMidRun = status.isBusy
+ return "Done."
+ }
+
+ #expect(busyMidRun)
+ #expect(!status.isBusy)
+ }
+}
diff --git a/app/Tests/NotProtonAppTests/ToggleAgreementTests.swift b/app/Tests/NotProtonAppTests/ToggleAgreementTests.swift
new file mode 100644
index 0000000..002186a
--- /dev/null
+++ b/app/Tests/NotProtonAppTests/ToggleAgreementTests.swift
@@ -0,0 +1,58 @@
+import Darwin
+import Foundation
+import Testing
+
+@testable import NotProtonApp
+
+// webpatch.c writes the Compatibility page toggles and compat_run.sh decides which tokens are
+// environment rather than game arguments. Nothing at build time holds the two together.
+@Suite("Toggle agreement")
+struct ToggleAgreementTests {
+
+ private static func source(_ path: String) throws -> String {
+ let repo = URL(filePath: #filePath)
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+ return try String(contentsOf: repo.appending(path: path), encoding: .utf8)
+ }
+
+ // The three shapes a setting name appears in: read, toggle, and write.
+ static func toggleNames(in webpatch: String) throws -> Set<String> {
+ var names: Set<String> = []
+ for pattern in [
+ #"g\(\\"([A-Z0-9_]+)\\"\)"#,
+ #"T\(\[\\"([A-Z0-9_]+)\\""#,
+ #"\[\\"([A-Z0-9_]+)\\","#,
+ ] {
+ for match in webpatch.matches(of: try Regex(pattern)) {
+ names.insert(String(match[1].substring ?? ""))
+ }
+ }
+ return names
+ }
+
+ static func allowedPatterns(in compat: String) throws -> [String] {
+ let line = try #require(
+ compat.split(separator: "\n").first { $0.contains("*=*|") },
+ "compat_run.sh no longer has a launch option allowlist")
+ return line.matches(of: try Regex(#"([A-Z0-9_]+\*?=\*)"#))
+ .map { String($0[1].substring ?? "") }
+ }
+
+ @Test("Every Compatibility page toggle is exported rather than passed to the game")
+ func togglesAreNamespaced() throws {
+ let names = try Self.toggleNames(in: try Self.source("dylib/feats/webpatch.c"))
+ let patterns = try Self.allowedPatterns(in: try Self.source("dylib/feats/compat_run.sh"))
+
+ #expect(names.count >= 8, "found \(names.count) toggles, the parse looks wrong")
+ #expect(!patterns.isEmpty)
+
+ for name in names.sorted() {
+ let token = "\(name)=1"
+ let covered = patterns.contains { fnmatch($0, token, 0) == 0 }
+ #expect(covered, "\(name) matches no allowlist pattern in compat_run.sh, so it reads as unset")
+ }
+ }
+}
diff --git a/app/Tests/NotProtonAppTests/UninstallTests.swift b/app/Tests/NotProtonAppTests/UninstallTests.swift
new file mode 100644
index 0000000..dad906b
--- /dev/null
+++ b/app/Tests/NotProtonAppTests/UninstallTests.swift
@@ -0,0 +1,283 @@
+import Foundation
+import Testing
+
+@testable import NotProtonApp
+
+// Every path is passed explicitly. The defaults are /Applications/Steam.app, the real
+// steam.cfg and the real caches directory, so leaning on them would uninstall this machine.
+@Suite("Uninstall")
+struct UninstallTests {
+
+ // The report closure is Sendable, so what it records has to be too.
+ private final class PhaseLog: @unchecked Sendable {
+ private let lock = NSLock()
+ private var seen: [UninstallPhase] = []
+ func add(_ phase: UninstallPhase) { lock.lock(); seen.append(phase); lock.unlock() }
+ var all: [UninstallPhase] { lock.lock(); defer { lock.unlock() }; return seen }
+ }
+
+ private struct Layout: Sendable {
+ let root: URL
+ let app: URL
+ let innerPlist: URL
+ let updateBlock: URL
+ let legacyCompat: URL
+ let compatTool: URL
+ let support: URL
+ let caches: URL
+
+ var outerPlist: URL { app.appending(path: "Contents/Info.plist") }
+ var dylib: URL { app.appending(path: "Contents/MacOS/\(SupportPaths.dylibName)") }
+ }
+
+ private func layout(signable: Bool = false) throws -> Layout {
+ let files = FileManager.default
+ let root = URL.temporaryDirectory.appending(path: "np-uninstall-\(UUID().uuidString)")
+ let app = root.appending(path: "Steam.app")
+ let macOS = app.appending(path: "Contents/MacOS")
+ let inner = root.appending(path: "inner")
+ let legacyCompat = inner.appending(path: "legacycompat")
+ let compatTool = root.appending(path: "compatibilitytools.d/notproton")
+ let support = root.appending(path: "notproton")
+ let caches = root.appending(path: "valve-packages")
+
+ for dir in [macOS, inner, legacyCompat, compatTool, support, caches] {
+ try files.createDirectory(at: dir, withIntermediateDirectories: true)
+ }
+
+ let updateBlock = root.appending(path: "steam.cfg")
+ // A client config holding a setting of Valve's beside the one NotProton adds, which is
+ // the shape that shows the removal taking out only its own line.
+ try Data("BootStrapperInhibitAll=enable\nBootStrapperInhibitUpdateOnLaunch=enable\n".utf8)
+ .write(to: updateBlock)
+ try Data("1\n".utf8).write(to: support.appending(path: "dylib.version"))
+ try Data("archive\n".utf8).write(to: caches.appending(path: "steam_client_osx.zip"))
+ try Data("\"run\"\n".utf8).write(to: compatTool.appending(path: "toolmanifest.vdf"))
+
+ let result = Layout(
+ root: root,
+ app: app,
+ innerPlist: inner.appending(path: "Info.plist"),
+ updateBlock: updateBlock,
+ legacyCompat: legacyCompat,
+ compatTool: compatTool,
+ support: support,
+ caches: caches
+ )
+
+ guard signable else { return result }
+
+ // Signed for real rather than stubbed, because the thing worth checking is that a
+ // plist edit inside a sealed bundle is followed by a signature that still verifies.
+ let source = root.appending(path: "main.c")
+ try Data("int main(void) { return 0; }\n".utf8).write(to: source)
+ try Shell.check("/usr/bin/clang", [
+ "-o", macOS.appending(path: "steam_osx").path(percentEncoded: false),
+ source.path(percentEncoded: false),
+ ])
+ try Shell.check("/usr/bin/clang", [
+ "-dynamiclib",
+ "-o", result.dylib.path(percentEncoded: false),
+ source.path(percentEncoded: false),
+ ])
+
+ let injected: [String: Any] = [
+ "CFBundleExecutable": "steam_osx",
+ "CFBundleIdentifier": "com.valvesoftware.steam",
+ SteamBundle.environmentKey: [
+ "LC_ALL": "C",
+ SteamBundle.insertKey: result.dylib.path(percentEncoded: false),
+ ],
+ ]
+ try SteamBundle.writeInfoPlist(injected, at: result.outerPlist)
+ try SteamBundle.writeInfoPlist(injected, at: result.innerPlist)
+ try SteamInstaller.adHocSign(app)
+
+ return result
+ }
+
+ @Test("Detaching leaves a Steam that loads nothing of ours")
+ func takesEverythingOfOursOutOfTheBundle() throws {
+ let layout = try layout(signable: true)
+ defer { try? FileManager.default.removeItem(at: layout.root) }
+ let files = FileManager.default
+
+ let detached = try Uninstall.detach(
+ from: layout.app,
+ innerPlist: layout.innerPlist,
+ updateBlocks: [layout.updateBlock]
+ )
+
+ #expect(detached)
+ #expect(SteamBundle.currentInsert(at: layout.outerPlist) == nil)
+ #expect(SteamBundle.currentInsert(at: layout.innerPlist) == nil)
+ #expect(!files.fileExists(atPath: layout.dylib.path(percentEncoded: false)))
+ #expect(unpinnedWithoutLosingTheRest(layout.updateBlock))
+
+ // LC_ALL is stock and has to survive, or the detach has swapped one difference
+ // from Valve's bundle for another.
+ let environment = SteamBundle.readInfoPlist(at: layout.outerPlist)?[
+ SteamBundle.environmentKey
+ ] as? [String: Any]
+ #expect(environment?["LC_ALL"] as? String == "C")
+
+ let verified = try Shell.run("/usr/bin/codesign", [
+ "--verify", "--deep", layout.app.path(percentEncoded: false),
+ ])
+ #expect(verified.succeeded)
+ }
+
+ // The client is no longer pinned and the setting that was not NotProton's is still there.
+ private func unpinnedWithoutLosingTheRest(_ cfg: URL) -> Bool {
+ guard let text = try? String(contentsOf: cfg, encoding: .utf8) else { return false }
+ return !UpdateBlock.isPresent(at: [cfg]) && text.contains("BootStrapperInhibitAll=enable")
+ }
+
+ private func verifies(_ app: URL) throws -> Bool {
+ try Shell.run("/usr/bin/codesign", [
+ "--verify", "--deep", app.path(percentEncoded: false),
+ ]).succeeded
+ }
+
+ // These hold no signature but used to be cleared after the bundle's own plist, so a throw
+ // returned with the bundle edited and unsigned, which is a Steam only a redownload fixes.
+ @Test("A removal that fails outside the bundle leaves the bundle alone")
+ func failureOutsideTheBundleLeavesItSigned() throws {
+ let files = FileManager.default
+ let layout = try layout(signable: true)
+ defer { try? FileManager.default.removeItem(at: layout.root) }
+ // The block is taken out by rewriting steam.cfg without that line, since the file holds
+ // settings of Valve's too, so it is the file that has to refuse the write.
+ try files.setAttributes(
+ [.posixPermissions: 0o444],
+ ofItemAtPath: layout.updateBlock.path(percentEncoded: false))
+ defer {
+ try? files.setAttributes(
+ [.posixPermissions: 0o644],
+ ofItemAtPath: layout.updateBlock.path(percentEncoded: false))
+ }
+
+ // Pinned to the refused write rather than to any throw at all, so the test cannot pass
+ // on a failure from somewhere else in the removal.
+ #expect(throws: WriteRefused.self) {
+ try Uninstall.detach(
+ from: layout.app, innerPlist: layout.innerPlist, updateBlocks: [layout.updateBlock])
+ }
+
+ #expect(SteamBundle.currentInsert(at: layout.outerPlist) != nil)
+ #expect(try verifies(layout.app))
+ }
+
+ // Once the plist is cleared the executable will not validate until it is signed again, so a
+ // throw between the two signs anyway. Forward, not back: the client starts carrying nothing.
+ @Test("A removal that fails inside the bundle still signs it")
+ func failureInsideTheBundleStillSignsIt() throws {
+ let layout = try layout(signable: true)
+ defer { try? FileManager.default.removeItem(at: layout.root) }
+ let dylib = layout.dylib.path(percentEncoded: false)
+ try Shell.check("/usr/bin/chflags", ["uchg", dylib])
+ defer { _ = try? Shell.check("/usr/bin/chflags", ["nouchg", dylib]) }
+
+ #expect(throws: (any Error).self) {
+ try Uninstall.detach(
+ from: layout.app, innerPlist: layout.innerPlist, updateBlocks: [layout.updateBlock])
+ }
+
+ #expect(SteamBundle.currentInsert(at: layout.outerPlist) == nil)
+ #expect(try verifies(layout.app))
+ }
+
+ @Test("A restore that fails does not cancel the removal")
+ func removesEverythingWhenSteamCannotBeRestored() async throws {
+ let layout = try layout()
+ defer { try? FileManager.default.removeItem(at: layout.root) }
+ struct Offline: Error {}
+
+ let outcome = try await Uninstall.run(
+ app: layout.app,
+ innerPlist: layout.innerPlist,
+ updateBlocks: [layout.updateBlock],
+ legacyCompat: layout.legacyCompat,
+ compatTool: layout.compatTool,
+ directories: [layout.support, layout.caches],
+ repair: { _ in throw Offline() },
+ stop: { _ in false }
+ )
+
+ #expect(outcome.restoredValveSignature == false)
+
+ let files = FileManager.default
+ #expect(!files.fileExists(atPath: layout.support.path(percentEncoded: false)))
+ #expect(!files.fileExists(atPath: layout.caches.path(percentEncoded: false)))
+ #expect(!files.fileExists(atPath: layout.legacyCompat.path(percentEncoded: false)))
+ #expect(
+ !files.fileExists(atPath: layout.compatTool.path(percentEncoded: false)),
+ "Steam would still list the tool in its dropdown after a removal"
+ )
+ #expect(unpinnedWithoutLosingTheRest(layout.updateBlock))
+ }
+
+ @Test("The copy the restore downloads is removed with everything else")
+ func removesWhatTheRestoreLeavesBehind() async throws {
+ let layout = try layout()
+ defer { try? FileManager.default.removeItem(at: layout.root) }
+ let caches = layout.caches
+ try FileManager.default.removeItem(at: caches)
+
+ let outcome = try await Uninstall.run(
+ app: layout.app,
+ innerPlist: layout.innerPlist,
+ updateBlocks: [layout.updateBlock],
+ legacyCompat: layout.legacyCompat,
+ compatTool: layout.compatTool,
+ directories: [layout.support, caches],
+ repair: { _ in
+ let staged = caches.appending(path: "bundle")
+ try FileManager.default.createDirectory(at: staged, withIntermediateDirectories: true)
+ try Data("2.6G of Steam".utf8).write(to: staged.appending(path: "Steam.app"))
+ },
+ stop: { _ in false }
+ )
+
+ #expect(outcome.restoredValveSignature)
+ #expect(!FileManager.default.fileExists(atPath: caches.path(percentEncoded: false)))
+ }
+
+ // Restoring forwards whatever phase repair reached. Carrying the phase rather than its
+ // rendering lets this assert on the phase and keeps the wording in one place.
+ @Test("A removal reports the repair's own phases while it restores")
+ func reportsTheRepairPhases() async throws {
+ let layout = try layout()
+ defer { try? FileManager.default.removeItem(at: layout.root) }
+
+ let log = PhaseLog()
+ _ = try await Uninstall.run(
+ app: layout.app,
+ innerPlist: layout.innerPlist,
+ updateBlocks: [layout.updateBlock],
+ legacyCompat: layout.legacyCompat,
+ compatTool: layout.compatTool,
+ directories: [layout.support, layout.caches],
+ report: { log.add($0) },
+ repair: { report in
+ report(.checking)
+ report(.replacing)
+ },
+ stop: { _ in false }
+ )
+
+ let restoring = log.all.compactMap { phase -> RepairPhase? in
+ if case .restoring(let inner) = phase { inner } else { nil }
+ }
+ #expect(restoring.count == 2)
+ #expect(restoring.contains { if case .checking = $0 { true } else { false } })
+ #expect(restoring.contains { if case .replacing = $0 { true } else { false } })
+
+ // Read from the outer phase, which is what the window shows: the wording has to come
+ // from RepairPhase rather than being restated here.
+ let labels = log.all.map(\.label)
+ #expect(labels.contains(RepairPhase.checking.label))
+ #expect(labels.contains(RepairPhase.replacing.label))
+ }
+
+}
diff --git a/app/Tests/NotProtonAppTests/UpdateBlockTests.swift b/app/Tests/NotProtonAppTests/UpdateBlockTests.swift
new file mode 100644
index 0000000..ddceb43
--- /dev/null
+++ b/app/Tests/NotProtonAppTests/UpdateBlockTests.swift
@@ -0,0 +1,190 @@
+import Foundation
+import Testing
+
+@testable import NotProtonApp
+
+@Suite("Update block")
+struct UpdateBlockTests {
+
+ private func scratch() throws -> URL {
+ let url = URL.temporaryDirectory.appending(path: "np-cfg-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
+ return url
+ }
+
+ @Test("Writing the block writes the required copy and the best-effort one")
+ func writesBothCopies() throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+
+ let required = work.appending(path: "Steam/steam.cfg")
+ let inner = work.appending(path: "Steam/Steam.AppBundle/Steam/Contents/MacOS/steam.cfg")
+ try FileManager.default.createDirectory(
+ at: inner.deletingLastPathComponent(), withIntermediateDirectories: true
+ )
+
+ let written = try UpdateBlock.write(to: [required, inner])
+
+ #expect(written.count == 2)
+ for url in [required, inner] {
+ let text = try String(contentsOf: url, encoding: .utf8)
+ #expect(text == "BootStrapperInhibitUpdateOnLaunch=enable\n")
+ }
+ }
+
+ // The client owns that directory. Creating it would leave a config file somewhere the
+ // client is not installed, which is worse than not writing the best-effort copy.
+ @Test("The best-effort copy is skipped when the client directory is not there")
+ func skipsBestEffortWhenDirectoryAbsent() throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+
+ let required = work.appending(path: "Steam/steam.cfg")
+ let inner = work.appending(path: "no-client-here/steam.cfg")
+
+ let written = try UpdateBlock.write(to: [required, inner])
+
+ #expect(written == [required.path(percentEncoded: false)])
+ #expect(!FileManager.default.fileExists(atPath: inner.path(percentEncoded: false)))
+ #expect(!FileManager.default.fileExists(
+ atPath: inner.deletingLastPathComponent().path(percentEncoded: false)
+ ), "a directory was created where the client is not installed")
+ }
+
+ @Test("Presence is decided by the required copy only")
+ func presenceFollowsRequiredCopy() throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+
+ let required = work.appending(path: "steam.cfg")
+ let inner = work.appending(path: "inner/steam.cfg")
+ #expect(UpdateBlock.isPresent(at: [required, inner]) == false)
+
+ try UpdateBlock.write(to: [required])
+ #expect(UpdateBlock.isPresent(at: [required, inner]))
+
+ // A file that exists but says something else is not the block.
+ try Data("SomethingElse=1\n".utf8).write(to: required)
+ #expect(UpdateBlock.isPresent(at: [required, inner]) == false)
+ }
+
+ @Test("Removing the block takes every copy it finds and ignores the rest")
+ func removesEveryCopy() throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+
+ let present = work.appending(path: "steam.cfg")
+ let absent = work.appending(path: "inner/steam.cfg")
+ try UpdateBlock.write(to: [present])
+
+ let removed = try UpdateBlock.remove(from: [present, absent])
+
+ #expect(removed == [present.path(percentEncoded: false)])
+ #expect(!FileManager.default.fileExists(atPath: present.path(percentEncoded: false)))
+ #expect(try UpdateBlock.remove(from: [present, absent]).isEmpty)
+ }
+
+ @Test("Writing over an existing block leaves one block, not two")
+ func writeIsIdempotent() throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+
+ let required = work.appending(path: "steam.cfg")
+ try UpdateBlock.write(to: [required])
+ try UpdateBlock.write(to: [required])
+
+ let text = try String(contentsOf: required, encoding: .utf8)
+ #expect(text == "BootStrapperInhibitUpdateOnLaunch=enable\n")
+ }
+
+ // The block being present used to mean the key appearing anywhere in the file, so a
+ // config that turns it off read as one that turns it on.
+ @Test("The key set to anything but enable is not a block")
+ func disabledKeyIsNotABlock() throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+ let cfg = work.appending(path: "steam.cfg")
+
+ try Data("BootStrapperInhibitUpdateOnLaunch=disable\n".utf8).write(to: cfg)
+ #expect(UpdateBlock.isPresent(at: [cfg]) == false)
+
+ // A later line is the one that takes effect.
+ try Data("BootStrapperInhibitUpdateOnLaunch=enable\nBootStrapperInhibitUpdateOnLaunch=disable\n".utf8)
+ .write(to: cfg)
+ #expect(UpdateBlock.isPresent(at: [cfg]) == false)
+
+ try Data("BootStrapperInhibitUpdateOnLaunch=enable\n".utf8).write(to: cfg)
+ #expect(UpdateBlock.isPresent(at: [cfg]))
+ }
+
+ // steam.cfg is the client's file. Writing the block replaced it outright and removing the
+ // block deleted it, either of which threw away settings nothing to do with NotProton.
+ @Test("Blocking and unblocking leave the rest of the file alone")
+ func otherSettingsSurvive() throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+ let cfg = work.appending(path: "steam.cfg")
+ try Data("BootStrapperInhibitAll=enable\nSomethingElse=1\n".utf8).write(to: cfg)
+
+ try UpdateBlock.write(to: [cfg])
+ var text = try String(contentsOf: cfg, encoding: .utf8)
+ #expect(text == "BootStrapperInhibitAll=enable\nSomethingElse=1\nBootStrapperInhibitUpdateOnLaunch=enable\n")
+ #expect(UpdateBlock.isPresent(at: [cfg]))
+
+ try UpdateBlock.remove(from: [cfg])
+ text = try String(contentsOf: cfg, encoding: .utf8)
+ #expect(text == "BootStrapperInhibitAll=enable\nSomethingElse=1\n")
+ #expect(FileManager.default.fileExists(atPath: cfg.path(percentEncoded: false)))
+ }
+
+ // Turning the block on where it is turned off changes that line rather than adding a
+ // second one under it, since the last line is the one that counts.
+ @Test("Blocking replaces a line that turned the block off")
+ func blockingReplacesADisabledLine() throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+ let cfg = work.appending(path: "steam.cfg")
+ try Data("BootStrapperInhibitUpdateOnLaunch=disable\nOther=2\n".utf8).write(to: cfg)
+
+ try UpdateBlock.write(to: [cfg])
+
+ #expect(try String(contentsOf: cfg, encoding: .utf8)
+ == "BootStrapperInhibitUpdateOnLaunch=enable\nOther=2\n")
+ }
+
+ @Test("A file holding nothing but the block is removed with it")
+ func aFileOfOnlyTheBlockGoes() throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+ let cfg = work.appending(path: "steam.cfg")
+
+ try UpdateBlock.write(to: [cfg])
+ let removed = try UpdateBlock.remove(from: [cfg])
+
+ #expect(removed == [cfg.path(percentEncoded: false)])
+ #expect(!FileManager.default.fileExists(atPath: cfg.path(percentEncoded: false)))
+ }
+
+ // A file the block was never in is not a file this changed, so repair does not report it.
+ @Test("A file without the block is left as it is")
+ func aFileWithoutTheBlockIsUntouched() throws {
+ let work = try scratch()
+ defer { try? FileManager.default.removeItem(at: work) }
+ let cfg = work.appending(path: "steam.cfg")
+ try Data("Other=2\n".utf8).write(to: cfg)
+
+ #expect(try UpdateBlock.remove(from: [cfg]).isEmpty)
+ #expect(try String(contentsOf: cfg, encoding: .utf8) == "Other=2\n")
+ }
+
+ @Test("The shipped paths are the two the client actually reads")
+ func shippedPathsAreTheClientPaths() {
+ let paths = UpdateBlock.paths.map { $0.path(percentEncoded: false) }
+
+ #expect(paths.count == 2)
+ #expect(paths[0].hasSuffix("/Application Support/Steam/steam.cfg"))
+ // Next to the client executable, not beside its bundle: that is where the
+ // bootstrapper looks, and it was checked against the live install.
+ #expect(paths[1].hasSuffix("/Steam.AppBundle/Steam/Contents/MacOS/steam.cfg"))
+ }
+}
diff --git a/app/Tests/NotProtonAppTests/ValveFetcherTests.swift b/app/Tests/NotProtonAppTests/ValveFetcherTests.swift
new file mode 100644
index 0000000..59e825f
--- /dev/null
+++ b/app/Tests/NotProtonAppTests/ValveFetcherTests.swift
@@ -0,0 +1,227 @@
+import Foundation
+import Testing
+
+@testable import NotProtonApp
+
+// Real packages and real pins into a throwaway bridge. A fixture would only prove the test
+// agrees with itself, so this pays for Valve's 97M once per machine and caches it.
+
+// Swift 6 refuses a captured var mutated inside the report closure, so a box is written by
+// one closure and read after run returns, as Shell does for pipe buffers.
+private final class PhaseLog: @unchecked Sendable {
+ var labels: [String] = []
+}
+
+@Suite("Valve fetcher", .serialized)
+struct ValveFetcherTests {
+
+ private func scratchBridge() throws -> URL {
+ let bridge = FileManager.default.temporaryDirectory
+ .appending(path: "np-valve-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: bridge, withIntermediateDirectories: true)
+ return bridge
+ }
+
+ @Test("An empty bridge gets all ten files, each matching its pin")
+ func fillsAnEmptyBridge() async throws {
+ let bridge = try scratchBridge()
+ defer { try? FileManager.default.removeItem(at: bridge) }
+
+ let manifest = try ValvePackageManifest.bundled()
+ let log = PhaseLog()
+ let outcome = try await ValveFetcher.run(manifest: manifest, bridge: bridge) { phase in
+ log.labels.append(phase.label)
+ }
+ let phases = log.labels
+
+ #expect(outcome.installed.count == 10)
+ #expect(outcome.unchanged.isEmpty)
+ #expect(!outcome.wroteNothing)
+
+ // The pins are checked inside run, so this is the independent read back: the
+ // bytes that actually landed in the bridge, hashed again from disk.
+ for file in manifest.files {
+ let landed = Digest.sha256IfPresent(bridge.appending(path: file.bridgePath))
+ #expect(landed == file.sha256, "\(file.bridgePath) landed as \(landed ?? "nothing")")
+ }
+
+ // Both packages were handled and the run reached the end, so an early return
+ // cannot be what made the assertions above pass.
+ #expect(phases.contains(ValveFetcher.Phase.verifying.label))
+ #expect(phases.contains(ValveFetcher.Phase.installing.label))
+ #expect(phases.last == ValveFetcher.Phase.finished.label)
+ #expect(phases.filter { $0 == "Extracting" }.count == manifest.packages.count)
+ }
+
+ // The wording is defined once on PinnedDownload.Progress so the fetcher and repair
+ // cannot drift apart on it. This case is the only thing carrying it out of the fetcher.
+ @Test("The download phase shows the download's own wording")
+ func downloadPhaseDelegatesItsLabel() {
+ #expect(ValveFetcher.Phase.downloading(.reusing).label
+ == PinnedDownload.Progress.reusing.label)
+ #expect(ValveFetcher.Phase.downloading(.fetching(host: "cdn.example")).label
+ == "Downloading from cdn.example")
+ }
+
+ @Test("A bridge that is already correct is left alone")
+ func secondRunWritesNothing() async throws {
+ let bridge = try scratchBridge()
+ defer { try? FileManager.default.removeItem(at: bridge) }
+
+ let manifest = try ValvePackageManifest.bundled()
+ _ = try await ValveFetcher.run(manifest: manifest, bridge: bridge)
+ let again = try await ValveFetcher.run(manifest: manifest, bridge: bridge)
+
+ #expect(again.installed.isEmpty)
+ #expect(again.unchanged.count == 10)
+ #expect(again.wroteNothing)
+ }
+
+ @Test("A file that is missing or wrong is replaced, and the rest are not touched")
+ func repairsOnlyWhatIsWrong() async throws {
+ let bridge = try scratchBridge()
+ defer { try? FileManager.default.removeItem(at: bridge) }
+
+ let manifest = try ValvePackageManifest.bundled()
+ _ = try await ValveFetcher.run(manifest: manifest, bridge: bridge)
+
+ // One deleted and one corrupted, including a file the bridge stages twice from a single
+ // archive entry, which is where a shared inner path could go wrong.
+ let deleted = "tier0_s64.dll"
+ let corrupted = "legacycompat/steamclient64.dll"
+ try FileManager.default.removeItem(at: bridge.appending(path: deleted))
+ try Data("not a PE".utf8).write(to: bridge.appending(path: corrupted))
+
+ let repair = try await ValveFetcher.run(manifest: manifest, bridge: bridge)
+
+ #expect(Set(repair.installed) == [deleted, corrupted])
+ #expect(repair.unchanged.count == 8)
+ for path in [deleted, corrupted] {
+ let want = manifest.files.first { $0.bridgePath == path }?.sha256
+ #expect(Digest.sha256IfPresent(bridge.appending(path: path)) == want)
+ }
+ }
+
+ @Test("A file whose extracted bytes do not match its pin stops the whole install")
+ func refusesAFileThatFailsItsPin() async throws {
+ let bridge = try scratchBridge()
+ defer { try? FileManager.default.removeItem(at: bridge) }
+
+ // The package still matches its own pin, so this is the second gate, on the extracted
+ // bytes. Nine files fine and one wrong leaves the bridge alone, not nine tenths updated.
+ let real = try ValvePackageManifest.bundled()
+ let tampered = ValvePackageManifest(
+ bases: real.bases,
+ packages: real.packages,
+ files: real.files.map { file in
+ file.bridgePath == "tier0_s64.dll"
+ ? ValveFile(
+ bridgePath: file.bridgePath, package: file.package,
+ innerPath: file.innerPath, sha256: String(repeating: "0", count: 64)
+ )
+ : file
+ },
+ bundle: real.bundle
+ )
+
+ await #expect(throws: StepFailure.self) {
+ try await ValveFetcher.run(manifest: tampered, bridge: bridge)
+ }
+
+ let landed = try FileManager.default.contentsOfDirectory(atPath: bridge.path(percentEncoded: false))
+ #expect(landed.isEmpty, "the bridge got \(landed) from a run that failed verification")
+ }
+
+ // The gate above guarantees every extracted file is present and pinned, so the only way to
+ // a part-way failure is an extract short a file. Out of disk is the real-world shape.
+ @Test("A copy that fails part way leaves the previous binary in place")
+ func keepsPreviousBinaryWhenACopyFails() throws {
+ let bridge = try scratchBridge()
+ let extracted = try scratchBridge()
+ defer {
+ try? FileManager.default.removeItem(at: bridge)
+ try? FileManager.default.removeItem(at: extracted)
+ }
+
+ let files = FileManager.default
+ try Data("new first".utf8).write(to: extracted.appending(path: "first.dll"))
+ try Data("new second".utf8).write(to: extracted.appending(path: "second.dll"))
+
+ func pin(_ name: String) throws -> String {
+ try #require(Digest.sha256IfPresent(extracted.appending(path: name)))
+ }
+
+ let manifest = ValvePackageManifest(
+ bases: [URL(string: "https://example.com")!],
+ packages: [
+ ValvePackage(id: "bins", file: "bins.zip", sha256: String(repeating: "a", count: 64))
+ ],
+ files: [
+ ValveFile(
+ bridgePath: "first.dll", package: "bins",
+ innerPath: "first.dll", sha256: try pin("first.dll")
+ ),
+ ValveFile(
+ bridgePath: "second.dll", package: "bins",
+ innerPath: "second.dll", sha256: try pin("second.dll")
+ ),
+ ],
+ bundle: nil
+ )
+
+ // A bridge from an earlier run, which is the state a failed update must not leave
+ // worse than it found.
+ try Data("old first".utf8).write(to: bridge.appending(path: "first.dll"))
+ try Data("old second".utf8).write(to: bridge.appending(path: "second.dll"))
+
+ try files.removeItem(at: extracted.appending(path: "second.dll"))
+
+ #expect(throws: (any Error).self) {
+ try ValveFetcher.install(manifest, from: extracted, into: bridge)
+ }
+
+ // The first file proves the loop reached the copies, so the check below cannot pass
+ // on a run that gave up before touching the bridge.
+ let first = try? String(contentsOf: bridge.appending(path: "first.dll"), encoding: .utf8)
+ #expect(first == "new first", "the loop never got as far as the first copy")
+
+ let second = try? String(contentsOf: bridge.appending(path: "second.dll"), encoding: .utf8)
+ #expect(
+ second == "old second",
+ "a copy that failed removed the previous binary, leaving \(second ?? "nothing")"
+ )
+
+ let landed = try files.contentsOfDirectory(atPath: bridge.path(percentEncoded: false))
+ #expect(
+ !landed.contains { $0.contains("notproton-pending") },
+ "a staging file was left in the bridge: \(landed)"
+ )
+ }
+
+ @Test("A package whose bytes do not match its pin is refused, and nothing is installed")
+ func refusesAPackageThatFailsItsPin() async throws {
+ let bridge = try scratchBridge()
+ let downloads = try scratchBridge()
+ defer {
+ try? FileManager.default.removeItem(at: bridge)
+ try? FileManager.default.removeItem(at: downloads)
+ }
+
+ // A host that answers, over https, with something that is not the package. The
+ // pin is the only thing standing between that and the bridge.
+ let real = try ValvePackageManifest.bundled()
+ let decoy = ValvePackageManifest(
+ bases: [URL(string: "https://example.com")!],
+ packages: real.packages,
+ files: real.files,
+ bundle: real.bundle
+ )
+
+ await #expect(throws: StepFailure.self) {
+ try await ValveFetcher.run(manifest: decoy, bridge: bridge, downloads: downloads)
+ }
+
+ let landed = try FileManager.default.contentsOfDirectory(atPath: bridge.path(percentEncoded: false))
+ #expect(landed.isEmpty, "the bridge got \(landed) from a package that failed its pin")
+ }
+}
diff --git a/app/Tests/NotProtonAppTests/ValvePackageManifestTests.swift b/app/Tests/NotProtonAppTests/ValvePackageManifestTests.swift
new file mode 100644
index 0000000..126825d
--- /dev/null
+++ b/app/Tests/NotProtonAppTests/ValvePackageManifestTests.swift
@@ -0,0 +1,186 @@
+import Foundation
+import Testing
+
+@testable import NotProtonApp
+
+@Suite("Valve package manifest")
+struct ValvePackageManifestTests {
+
+ @Test("The shipped manifest pins every Valve file to a package")
+ func shippedManifestIsComplete() throws {
+ let manifest = try ValvePackageManifest.bundled()
+
+ // Ten files out of two packages, over three hosts that serve identical bytes.
+ #expect(manifest.files.count == 10)
+ #expect(manifest.packages.count == 2)
+ #expect(manifest.bases.count == 3)
+
+ // Akamai first. The order is the order they are tried in, so it is not
+ // incidental: the fallbacks exist for when the first host is unreachable.
+ #expect(manifest.bases.first?.host() == "client-update.akamai.steamstatic.com")
+
+ // Both packages are named for their own sha1, which is the pin that stops a
+ // client update from moving the contents underneath a fixed name.
+ for package in manifest.packages {
+ let sha1 = package.file.split(separator: ".").last.map(String.init) ?? ""
+ #expect(sha1.count == 40, "\(package.file) does not end in a package sha1")
+ }
+
+ // The bundle is pinned the same way but is not a bridge input, so it is absent
+ // from the counts above. It comes wrapped twice, as a tar.gz inside the zip.
+ let bundle = try #require(manifest.bundle)
+ #expect(bundle.file == "appdmg_osx.zip.984652b88a9737e3f4e77c656d9ffa67d5042c2c")
+ #expect(bundle.sha256 == "8bf4ce8b4bcbc50f642988c955559f605e7a877372116e7a2b3fd1355004bedb")
+ #expect(bundle.innerArchive == "SteamMacBootstrapper.tar.gz")
+ #expect(bundle.bundleName == "Steam.app")
+
+ let bundleSHA1 = bundle.file.split(separator: ".").last.map(String.init) ?? ""
+ #expect(bundleSHA1.count == 40, "\(bundle.file) does not end in a package sha1")
+ }
+
+ // Optional because only repair reads it. A manifest without one has to parse, or
+ // every consumer would be made to carry a row none of them touch.
+ @Test("A manifest with no bundle row parses, and repair is what reports it missing")
+ func bundleRowIsOptional() throws {
+ let hash = String(repeating: "a", count: 64)
+ let manifest = try ValvePackageManifest.parse(
+ """
+ base https://example.invalid/client
+ package win64 bins_win64.zip.aa \(hash)
+ file tier0_s64.dll win64 tier0_s64.dll \(hash)
+ """
+ )
+
+ #expect(manifest.bundle == nil)
+ }
+
+ // Both manifests are written by hand and read by different consumers, so only a test stops
+ // them drifting. No row means unfetchable, and no entry means a file nothing consumes.
+ @Test("Every valve payload entry has exactly one package row, and the reverse")
+ func agreesWithThePayloadManifest() throws {
+ let payload = try PayloadManifest.bundled()
+ let packages = try ValvePackageManifest.bundled()
+
+ let fromPayload = Set(payload.paths(origin: .valve))
+ let fromPackages = Set(packages.files.map(\.bridgePath))
+
+ #expect(fromPayload == fromPackages)
+ #expect(fromPackages.count == packages.files.count, "a bridge path is listed twice")
+ }
+
+ @Test("A package is opened once per archive entry, not once per bridge path")
+ func innerPathsAreDeduplicated() throws {
+ let manifest = try ValvePackageManifest.bundled()
+
+ // Six of the ten come from the Linux package under legacycompat, and two are also staged
+ // at the bridge root, so eight bridge paths resolve to six entries in that archive.
+ let linux = manifest.files.filter { $0.package == "linux" }
+ #expect(linux.count == 8)
+ #expect(manifest.innerPaths(package: "linux").count == 6)
+ #expect(manifest.innerPaths(package: "win64").count == 2)
+ }
+
+ @Test("Row kinds parse into their own collections")
+ func parsesEachRowKind() throws {
+ let manifest = try ValvePackageManifest.parse(
+ """
+ # a comment
+ # an indented comment
+
+ base https://example.invalid/client
+ package win64 bins_win64.zip.aa \(String(repeating: "a", count: 64))
+ file tier0_s64.dll win64 tier0_s64.dll \(String(repeating: "b", count: 64))
+ bundle appdmg_osx.zip.cc \(String(repeating: "c", count: 64)) SteamMacBootstrapper.tar.gz Steam.app
+ """
+ )
+
+ #expect(manifest.bases.map(\.absoluteString) == ["https://example.invalid/client"])
+ #expect(manifest.packages == [
+ ValvePackage(id: "win64", file: "bins_win64.zip.aa", sha256: String(repeating: "a", count: 64)),
+ ])
+ #expect(manifest.files == [
+ ValveFile(
+ bridgePath: "tier0_s64.dll", package: "win64",
+ innerPath: "tier0_s64.dll", sha256: String(repeating: "b", count: 64)
+ ),
+ ])
+ #expect(manifest.bundle == ValveBundle(
+ file: "appdmg_osx.zip.cc", sha256: String(repeating: "c", count: 64),
+ innerArchive: "SteamMacBootstrapper.tar.gz", bundleName: "Steam.app"
+ ))
+ }
+
+ // Every one of these has to throw. A skipped row means a file that is silently not
+ // fetched, and the failure then surfaces as a launch that breaks for another reason.
+ @Test("A malformed manifest is refused rather than partly read")
+ func refusesMalformed() {
+ let hash = String(repeating: "a", count: 64)
+ let good = """
+ base https://example.invalid/client
+ package win64 bins_win64.zip.aa \(hash)
+ file tier0_s64.dll win64 tier0_s64.dll \(hash)
+ """
+
+ func parse(_ text: String) throws { _ = try ValvePackageManifest.parse(text) }
+
+ #expect(throws: StepFailure.self) { try parse("nonsense one two") }
+ #expect(throws: StepFailure.self) { try parse("") }
+ #expect(throws: StepFailure.self) { try parse("# only comments") }
+
+ // A base that is not https, and one that is not a URL at all.
+ #expect(throws: StepFailure.self) { try parse(good.replacingOccurrences(of: "https://", with: "http://")) }
+ #expect(throws: StepFailure.self) { try parse("base not-a-url\n" + good) }
+
+ // Missing and extra fields, per row kind.
+ #expect(throws: StepFailure.self) { try parse("base") }
+ #expect(throws: StepFailure.self) { try parse("package win64 bins_win64.zip.aa") }
+ #expect(throws: StepFailure.self) { try parse("file tier0_s64.dll win64 tier0_s64.dll") }
+ #expect(throws: StepFailure.self) { try parse(good + " extra") }
+
+ // A hash that is short, uppercase, or not hex.
+ #expect(throws: StepFailure.self) { try parse(good.replacingOccurrences(of: hash, with: "aa")) }
+ #expect(throws: StepFailure.self) { try parse(good.replacingOccurrences(of: hash, with: hash.uppercased())) }
+ #expect(throws: StepFailure.self) {
+ try parse(good.replacingOccurrences(of: hash, with: String(repeating: "z", count: 64)))
+ }
+
+ // A manifest with no host, no package, or no file.
+ #expect(throws: StepFailure.self) { try parse(good.replacingOccurrences(of: "base https://example.invalid/client\n", with: "")) }
+ #expect(throws: StepFailure.self) { try parse("base https://example.invalid/client") }
+ #expect(throws: StepFailure.self) {
+ try parse("base https://example.invalid/client\npackage win64 bins_win64.zip.aa \(hash)")
+ }
+
+ // A file naming a package that was never declared.
+ #expect(throws: StepFailure.self) { try parse(good.replacingOccurrences(of: "file tier0_s64.dll win64", with: "file tier0_s64.dll win66")) }
+
+ // The same bridge path or package id twice.
+ #expect(throws: StepFailure.self) { try parse(good + "\nfile tier0_s64.dll win64 other.dll \(hash)") }
+ #expect(throws: StepFailure.self) { try parse(good + "\npackage win64 other.zip.bb \(hash)") }
+
+ // A declared package that no file row uses would be downloaded for nothing.
+ #expect(throws: StepFailure.self) {
+ try parse(good + "\npackage linux bins_misc_ubuntu12.zip.bb \(hash)")
+ }
+
+ // Two bridge paths sharing one archive entry but disagreeing on its hash. This
+ // is allowed to share, and not allowed to contradict.
+ let shared = good + "\nfile copy.dll win64 tier0_s64.dll \(String(repeating: "b", count: 64))"
+ #expect(throws: StepFailure.self) { try parse(shared) }
+ #expect(throws: Never.self) {
+ try parse(good + "\nfile copy.dll win64 tier0_s64.dll \(hash)")
+ }
+
+ // A bundle row short a field, with a bad hash, and declared twice. Only one
+ // bundle can be installed, so a second row is a mistake rather than a choice.
+ let bundleRow = "bundle appdmg_osx.zip.cc \(hash) SteamMacBootstrapper.tar.gz Steam.app"
+ #expect(throws: StepFailure.self) {
+ try parse(good + "\nbundle appdmg_osx.zip.cc \(hash) SteamMacBootstrapper.tar.gz")
+ }
+ #expect(throws: StepFailure.self) {
+ try parse(good + "\n" + bundleRow.replacingOccurrences(of: hash, with: "aa"))
+ }
+ #expect(throws: StepFailure.self) { try parse(good + "\n" + bundleRow + "\n" + bundleRow) }
+ #expect(throws: Never.self) { try parse(good + "\n" + bundleRow) }
+ }
+}
diff --git a/bridge/fetch-valve.sh b/bridge/fetch-valve.sh
new file mode 100755
index 0000000..cf222d3
--- /dev/null
+++ b/bridge/fetch-valve.sh
@@ -0,0 +1,117 @@
+#!/bin/sh
+# Fetch the Valve binaries the bridge stages, from Valve's client packages.
+#
+# ./fetch.sh download, verify every hash, report
+# ./fetch.sh --install also copy them into the bridge
+#
+# The ten Valve files in the bridge come from two pinned Steam client packages. The
+# pins, the CDN hosts and every file hash live in the manifest this reads, which the
+# app reads as a bundled resource too, so there is one definition rather than one per
+# consumer. That file also records where the package names come from, and why two of
+# the paths inside the packages look misplaced.
+#
+# The shim once linked steam_api.dll and steam_api64.dll, which are in no client
+# package and could not be fetched. That dependency is gone: steam.cpp loads
+# steamclient64.dll and calls its CreateInterface instead, so every payload file is
+# either built here or fetchable.
+set -eu
+
+here="$(cd "$(dirname "$0")" && pwd)"
+repo="$(cd "$here/.." && pwd)"
+BRIDGE_DIR="${BRIDGE_DIR:-$HOME/Library/Application Support/notproton/bridge}"
+WORK="${WORK:-$repo/scratch/valve-fetch}"
+MANIFEST="${MANIFEST:-$repo/app/Sources/NotProtonApp/Resources/valve-packages.manifest}"
+[ -f "$MANIFEST" ] || { echo "==> no package manifest at $MANIFEST" >&2; exit 1; }
+
+# Akamai is listed first and the rest are fallbacks. All three serve identical bytes.
+BASES="${BASES:-$(awk '$1 == "base" { printf "%s ", $2 }' "$MANIFEST")}"
+
+install=0
+[ "${1:-}" = "--install" ] && install=1
+
+# id | CDN filename | sha256
+PACKAGES="$(awk '$1 == "package" { print $2 "|" $3 "|" $4 }' "$MANIFEST")"
+
+# bridge path | package id | path inside the package | sha256
+FILES="$(awk '$1 == "file" { print $2 "|" $3 "|" $4 "|" $5 }' "$MANIFEST")"
+
+sha() { shasum -a 256 "$1" | cut -d' ' -f1; }
+
+# Downloads once and keeps the package, so a second run verifies without refetching.
+get_pkg() {
+ name="$1"
+ want="$2"
+ out="$WORK/$name"
+ if [ -f "$out" ] && [ "$(sha "$out")" = "$want" ]; then
+ echo "==> have $name"
+ return 0
+ fi
+ for base in $BASES; do
+ echo "==> fetching $name from $base"
+ if curl -fsS -o "$out.part" "$base/$name"; then
+ got="$(sha "$out.part")"
+ if [ "$got" = "$want" ]; then
+ mv "$out.part" "$out"
+ return 0
+ fi
+ echo " sha256 mismatch: got $got" >&2
+ echo " wanted $want" >&2
+ rm -f "$out.part"
+ fi
+ done
+ rm -f "$out.part"
+ echo "==> could not fetch $name from any base" >&2
+ return 1
+}
+
+mkdir -p "$WORK"
+for spec in $PACKAGES; do
+ get_pkg "$(echo "$spec" | cut -d'|' -f2)" "$(echo "$spec" | cut -d'|' -f3)"
+done
+
+# Extracted fresh every run so a stale extract cannot pass the hash check by luck.
+EX="$WORK/extract"
+rm -rf "$EX"
+mkdir -p "$EX"
+for spec in $FILES; do
+ inner="$(echo "$spec" | cut -d'|' -f3)"
+ id="$(echo "$spec" | cut -d'|' -f2)"
+ pkg="$(echo "$PACKAGES" | awk -F'|' -v id="$id" '$1 == id { print $2 }')"
+ [ -n "$pkg" ] || { echo "==> file row names unknown package $id" >&2; exit 1; }
+ [ -f "$EX/$inner" ] || unzip -q -o "$WORK/$pkg" "$inner" -d "$EX"
+done
+
+echo "==> verifying"
+bad=0
+for spec in $FILES; do
+ rel="$(echo "$spec" | cut -d'|' -f1)"
+ inner="$(echo "$spec" | cut -d'|' -f3)"
+ want="$(echo "$spec" | cut -d'|' -f4)"
+ got="$(sha "$EX/$inner" 2>/dev/null || echo missing)"
+ if [ "$got" = "$want" ]; then
+ printf ' %-40s ok\n' "$rel"
+ else
+ printf ' %-40s BAD got %s\n' "$rel" "$got"
+ bad=$((bad + 1))
+ fi
+done
+
+[ "$bad" -eq 0 ] || { echo "==> $bad file(s) failed, not installing" >&2; exit 1; }
+
+if [ "$install" -eq 0 ]; then
+ echo "==> verified, pass --install to copy into the bridge"
+ exit 0
+fi
+
+for spec in $FILES; do
+ rel="$(echo "$spec" | cut -d'|' -f1)"
+ inner="$(echo "$spec" | cut -d'|' -f3)"
+ mkdir -p "$BRIDGE_DIR/$(dirname "$rel")"
+ if cmp -s "$EX/$inner" "$BRIDGE_DIR/$rel"; then
+ printf ' %-40s unchanged\n' "$rel"
+ else
+ cp -f "$EX/$inner" "$BRIDGE_DIR/$rel"
+ printf ' %-40s installed\n' "$rel"
+ fi
+done
+echo "==> done. RUN_SCRIPT stages these on the next launch."
diff --git a/bridge/pe-info.py b/bridge/pe-info.py
new file mode 100755
index 0000000..17b820c
--- /dev/null
+++ b/bridge/pe-info.py
@@ -0,0 +1,28 @@
+#!/usr/bin/env python3
+# Print "<arch> <hash>" for a PE file
+
+import hashlib
+import struct
+import sys
+
+MACHINE = {0x014C: "i386", 0x8664: "x86_64"}
+
+
+def main():
+ if len(sys.argv) != 2:
+ sys.exit("usage: pe-info.py <pe-file>")
+
+ data = bytearray(open(sys.argv[1], "rb").read())
+ pe = struct.unpack_from("<I", data, 0x3C)[0]
+ if data[pe:pe + 4] != b"PE\0\0":
+ sys.exit(f"{sys.argv[1]}: not a PE file")
+
+ machine = struct.unpack_from("<H", data, pe + 4)[0]
+ for off in (pe + 8, pe + 24 + 64):
+ data[off:off + 4] = b"\0\0\0\0"
+
+ print(MACHINE.get(machine, hex(machine)), hashlib.sha256(data).hexdigest()[:16])
+
+
+if __name__ == "__main__":
+ main()
diff --git a/bridge/register-components.diff b/bridge/register-components.diff
new file mode 100644
index 0000000..d6e340b
--- /dev/null
+++ b/bridge/register-components.diff
@@ -0,0 +1,81 @@
+Register dlls/lsteamclient and programs/steam.exe with Wine's build system.
+
+Wine's configure enumerates the makefiles it will generate, so a component has to be
+declared before configure runs. Undeclared, it gets no makefile and its build target
+silently does nothing.
+
+WINE_EXTERNAL(programs/steam.exe) is what stops makedep reading the internal includes
+inside jsoncpp's amalgamation. Those sit behind JSON_IS_AMALGAMATION and never compile,
+but the scanner follows them regardless of the #if.
+
+Tracked as a patch rather than regenerated with autoconf. It is +8/-1 mechanical lines
+across the two files, where a local autoconf against stock 11.15 would rewrite the whole
+of configure with whatever version happens to be installed.
+
+diff --git a/configure b/configure
+index aa3c65e..2df611f 100755
+--- a/configure
++++ b/configure
+@@ -1244,6 +1244,7 @@ enable_l3codecx_ax
+ enable_loadperf
+ enable_localspl
+ enable_localui
++enable_lsteamclient
+ enable_lz32
+ enable_magnification
+ enable_mapi32
+@@ -1789,6 +1790,7 @@ enable_shutdown
+ enable_sort
+ enable_spoolsv
+ enable_start
++enable_steam_exe
+ enable_subst
+ enable_svchost
+ enable_systeminfo
+@@ -22569,6 +22571,7 @@ wine_fn_config_makefile dlls/localspl enable_localspl
+ wine_fn_config_makefile dlls/localspl/tests enable_tests
+ wine_fn_config_makefile dlls/localui enable_localui
+ wine_fn_config_makefile dlls/localui/tests enable_tests
++wine_fn_config_makefile dlls/lsteamclient enable_lsteamclient
+ wine_fn_config_makefile dlls/lz32 enable_lz32
+ wine_fn_config_makefile dlls/lz32/tests enable_tests
+ wine_fn_config_makefile dlls/lzexpand.dll16 enable_win16
+@@ -23367,6 +23370,8 @@ wine_fn_config_makefile programs/shutdown enable_shutdown
+ wine_fn_config_makefile programs/sort enable_sort
+ wine_fn_config_makefile programs/spoolsv enable_spoolsv
+ wine_fn_config_makefile programs/start enable_start
++wine_fn_config_makefile programs/steam.exe enable_steam_exe
++
+ wine_fn_config_makefile programs/subst enable_subst
+ wine_fn_config_makefile programs/svchost enable_svchost
+ wine_fn_config_makefile programs/systeminfo enable_systeminfo
+@@ -23493,7 +23498,7 @@ dlls/wineandroid.drv/wine-debug.apk: dlls/wineandroid.drv/build.gradle ${wine_sr
+ mv dlls/wineandroid.drv/build/outputs/apk/debug/wine-debug.apk \$@"
+
+
+-EXTERNAL_SUBDIRS="libs/capstone libs/c++ libs/c++abi libs/faudio libs/ffmpeg libs/fluidsynth libs/gsm libs/icucommon libs/icui18n libs/jpeg libs/jxr libs/lcms2 libs/ldap libs/mpg123 libs/musl libs/png libs/sqlite3 libs/symcrypt libs/tiff libs/unwind libs/vkd3d libs/xml2 libs/xslt libs/zlib libs/compiler-rt"
++EXTERNAL_SUBDIRS="libs/capstone libs/c++ libs/c++abi libs/faudio libs/ffmpeg libs/fluidsynth libs/gsm libs/icucommon libs/icui18n libs/jpeg libs/jxr libs/lcms2 libs/ldap libs/mpg123 libs/musl libs/png libs/sqlite3 libs/symcrypt libs/tiff libs/unwind libs/vkd3d libs/xml2 libs/xslt libs/zlib programs/steam.exe libs/compiler-rt"
+
+ TAGSFLAGS="--langmap='c:+.idl.l.rh,make:(Make*.in)'"
+
+diff --git a/configure.ac b/configure.ac
+index ee0b1c4..29a174a 100644
+--- a/configure.ac
++++ b/configure.ac
+@@ -2862,6 +2862,7 @@ WINE_CONFIG_MAKEFILE(dlls/localspl)
+ WINE_CONFIG_MAKEFILE(dlls/localspl/tests)
+ WINE_CONFIG_MAKEFILE(dlls/localui)
+ WINE_CONFIG_MAKEFILE(dlls/localui/tests)
++WINE_CONFIG_MAKEFILE(dlls/lsteamclient)
+ WINE_CONFIG_MAKEFILE(dlls/lz32)
+ WINE_CONFIG_MAKEFILE(dlls/lz32/tests)
+ WINE_CONFIG_MAKEFILE(dlls/lzexpand.dll16)
+@@ -3660,6 +3661,8 @@ WINE_CONFIG_MAKEFILE(programs/shutdown)
+ WINE_CONFIG_MAKEFILE(programs/sort)
+ WINE_CONFIG_MAKEFILE(programs/spoolsv)
+ WINE_CONFIG_MAKEFILE(programs/start)
++WINE_CONFIG_MAKEFILE(programs/steam.exe)
++WINE_EXTERNAL(programs/steam.exe)
+ WINE_CONFIG_MAKEFILE(programs/subst)
+ WINE_CONFIG_MAKEFILE(programs/svchost)
+ WINE_CONFIG_MAKEFILE(programs/systeminfo)
diff --git a/bridge/setup-wine-tree.sh b/bridge/setup-wine-tree.sh
new file mode 100755
index 0000000..06c86a4
--- /dev/null
+++ b/bridge/setup-wine-tree.sh
@@ -0,0 +1,117 @@
+#!/bin/sh
+# Create and configure the wine tree that the component builds need.
+#
+# ./setup-wine-tree.sh create and configure, skipping whatever is already done
+#
+# CrossOver ships a runtime-only Wine with no winegcc or winebuild, so lsteamclient
+# and the steam.exe shim are built in a wine source tree and staged into the bridge
+# unsigned.
+#
+# The base is stock Wine 11.15, the version the CrossOver runtime is built from
+# (wine-11.15-8895-g32f409fef6a). ntdll from a different vintage speaks a different
+# server protocol and the shipped loader refuses to boot it.
+#
+# A unix half loads into the wine loader's own process and has to match its arch. The
+# rosetta loader is x86_64, which on an Apple Silicon host needs the cross configure
+# that HOST and the two compilers below provide. The FEX loader is arm64 and wants a
+# native tree, so each gets its own build directory. The PE halves come from mingw.
+set -eu
+
+here="$(cd "$(dirname "$0")" && pwd)"
+repo="$(cd "$here/.." && pwd)"
+
+WINE_URL="${WINE_URL:-https://gitlab.winehq.org/wine/wine.git}"
+WINE_TAG="${WINE_TAG:-wine-11.15}"
+# A shallow clone of a mutable tag records nothing about what it resolved to, so a
+# tag moved upstream would change what gets built here with no signal.
+WINE_COMMIT="${WINE_COMMIT:-2df1ee28039cf84776eb1421ed90bd154cebb65f}"
+WINE_SRC="${WINE_SRC:-$repo/scratch/wine}"
+WINE_BUILD="${WINE_BUILD:-$repo/scratch/wine-build-dual}"
+# i386 is built because a 32 bit game needs the i386 PE halves. freetype and X are
+# off because nothing built here uses either.
+CONFIGURE_OPTS="${CONFIGURE_OPTS:---enable-archs=i386,x86_64 --without-freetype --without-x}"
+HOST="${HOST:-x86_64-apple-darwin}"
+# Taken from HOST rather than spelled out twice, since configure normalises it.
+HOST_CPU="${HOST%%-*}"
+HOST_CC="${HOST_CC:-clang -arch x86_64}"
+HOST_CXX="${HOST_CXX:-clang++ -arch x86_64}"
+
+# The bison and autoconf macOS ships are too old for wine's configure.
+PATH="/opt/homebrew/bin:/opt/homebrew/opt/bison/bin:/opt/homebrew/opt/autoconf/bin:$PATH"
+export PATH
+
+missing=""
+for tool in git make bison flex i686-w64-mingw32-gcc x86_64-w64-mingw32-gcc; do
+ command -v "$tool" >/dev/null 2>&1 || missing="$missing $tool"
+done
+if [ -n "$missing" ]; then
+ echo "==> missing tools:$missing" >&2
+ echo " brew install mingw-w64 bison flex" >&2
+ exit 1
+fi
+
+if [ ! -d "$WINE_SRC/.git" ]; then
+ echo "==> cloning $WINE_TAG into $WINE_SRC"
+ git clone --depth 1 --branch "$WINE_TAG" "$WINE_URL" "$WINE_SRC"
+else
+ echo "==> source tree present, leaving it alone: $WINE_SRC"
+fi
+
+head="$(git -C "$WINE_SRC" rev-parse HEAD)"
+if [ "$head" != "$WINE_COMMIT" ]; then
+ echo "==> $WINE_SRC is at $head, not the pinned $WINE_COMMIT" >&2
+ echo " Either $WINE_TAG has moved upstream or this tree came from elsewhere." >&2
+ echo " Set WINE_COMMIT to adopt it, once the loader is known to boot its ntdll." >&2
+ exit 1
+fi
+echo "==> source tree at pinned $WINE_COMMIT"
+
+if grep -q 'WINE_CONFIG_MAKEFILE(dlls/lsteamclient)' "$WINE_SRC/configure.ac"; then
+ echo "==> components already registered with configure"
+else
+ echo "==> registering dlls/lsteamclient and programs/steam.exe with configure"
+ ( cd "$WINE_SRC" && git apply "$here/register-components.diff" )
+fi
+
+"$repo/lsteamclient/fetch.sh"
+"$repo/steam-shim/fetch-headers.sh"
+
+# Whole trees, not just the two Makefile.in files: makedep reads the SOURCES each one
+# lists and fails the entire configure if any of those files is absent.
+mkdir -p "$WINE_SRC/dlls/lsteamclient" "$WINE_SRC/programs/steam.exe"
+rsync -a "$repo/build/lsteamclient/" "$WINE_SRC/dlls/lsteamclient/"
+rsync -a --exclude build.sh --exclude gen-implib.sh --exclude fetch-headers.sh \
+ "$repo/steam-shim/" "$WINE_SRC/programs/steam.exe/"
+echo "==> placed sources for dlls/lsteamclient and programs/steam.exe"
+
+# A configure that dies in config.status still leaves config.status behind, so that
+# is not the thing to test for. The Makefile is what has to exist.
+if [ -f "$WINE_BUILD/Makefile" ]; then
+ echo "==> build tree already configured, leaving it alone: $WINE_BUILD"
+else
+ echo "==> configuring $WINE_BUILD"
+ mkdir -p "$WINE_BUILD"
+ # Unquoted on purpose so the options split. CC and CXX are each a command plus flag.
+ # shellcheck disable=SC2086
+ ( cd "$WINE_BUILD" && "$WINE_SRC/configure" $CONFIGURE_OPTS \
+ --host="$HOST" CC="$HOST_CC" CXX="$HOST_CXX" )
+fi
+
+# A cross configure that quietly falls back to the host compiler produces arm64 unix
+# objects that only fail much later, at the link, so check it here instead.
+if ! grep -q "^host_cpu = $HOST_CPU" "$WINE_BUILD/config.status"; then
+ echo "==> configure did not take the $HOST_CPU host, unix halves would be the wrong arch" >&2
+ exit 1
+fi
+
+# lsteamclient's unix half links against wine's ntdll.so. It is wine's artifact rather
+# than a component's, so it is built here and before the component scripts run.
+if [ -f "$WINE_BUILD/dlls/ntdll/ntdll.so" ]; then
+ echo "==> dlls/ntdll/ntdll.so already built"
+else
+ echo "==> building dlls/ntdll/ntdll.so"
+ ( cd "$WINE_BUILD" && make dlls/ntdll/ntdll.so )
+fi
+
+echo "==> ready, now run: ../lsteamclient/build.sh --install"
+echo " ../steam-shim/build.sh --install"
diff --git a/bridge/verify.sh b/bridge/verify.sh
new file mode 100755
index 0000000..5559185
--- /dev/null
+++ b/bridge/verify.sh
@@ -0,0 +1,222 @@
+#!/bin/sh
+# Check the bridge holds exactly what a launch consumes, and nothing else.
+#
+# ./verify.sh report what is missing, unexpected, or present
+# ./verify.sh --prune also move anything unexpected out to scratch/bridge-attic
+#
+# The bridge is the staging area RUN_SCRIPT installs from on every launch, so what
+# sits in it ends up in the CrossOver tree, the wine prefix, and the Steam client
+# directory. Stray files there are not harmless:
+#
+# - legacycompat is copied by glob, so anything dropped in it is installed into the
+# Steam client directory verbatim.
+# - a stale lsteamclient.so or steamclient64.so beside a PE of the same name makes
+# wine bind that builtin to the old unix half instead of loading the dll.
+# - a wrong-arch PE on WINEDLLPATH aborts builtin lookup outright with c000007b.
+#
+# Backups belong outside the bridge for the same reason, which is why --prune moves
+# rather than deletes: the attic is in scratch, which is disposable.
+#
+# Every file here is reproducible. The built ones come from make lsteamclient,
+# make steam-shim and make ntdll-patch. The Valve ones come from the Steam client
+# packages, fetched by fetch-valve.sh beside this script.
+set -eu
+
+here="$(cd "$(dirname "$0")" && pwd)"
+repo="$(cd "$here/.." && pwd)"
+BRIDGE_DIR="${BRIDGE_DIR:-$HOME/Library/Application Support/notproton/bridge}"
+ATTIC="${ATTIC:-$repo/scratch/bridge-attic}"
+# Stale whole-bridge copies get made next to it rather than inside it, where a
+# check that only walks the bridge cannot see them.
+SUPPORT_DIR="${SUPPORT_DIR:-$(dirname "$BRIDGE_DIR")}"
+BRIDGE_NAME="$(basename "$BRIDGE_DIR")"
+
+prune=0
+[ "${1:-}" = "--prune" ] && prune=1
+
+# What RUN_SCRIPT reads, taken from the manifest the companion app also ships, so
+# this list and the one the installer stages from cannot drift apart. The manifest
+# sits in the app's resource directory because that is the only place Swift Package
+# Manager will package a file from.
+MANIFEST="${MANIFEST:-$repo/app/Sources/NotProtonApp/Resources/payload.manifest}"
+if [ ! -f "$MANIFEST" ]; then
+ echo "==> no payload manifest at $MANIFEST" >&2
+ exit 1
+fi
+
+# Three origins collapse to the two sections this check has always printed. The
+# manifest separates built from patched because the installer treats them
+# differently, the patched ntdlls being made from the user's own CrossOver. That
+# distinction does not matter here.
+origin() {
+ awk -v want="$1" '$1 == want { print $2 }' "$MANIFEST"
+}
+
+built="$(origin built; origin patched)"
+valve="$(origin valve)"
+
+if [ -z "$built" ] || [ -z "$valve" ]; then
+ echo "==> payload manifest has no usable entries: $MANIFEST" >&2
+ exit 1
+fi
+
+if [ ! -d "$BRIDGE_DIR" ]; then
+ echo "==> no bridge at $BRIDGE_DIR" >&2
+ exit 1
+fi
+
+expected="$(printf '%s\n%s\n' "$built" "$valve" | sed '/^$/d')"
+missing=0
+unexpected=0
+
+report() {
+ label="$1"
+ list="$2"
+ echo "==> $label"
+ for rel in $list; do
+ f="$BRIDGE_DIR/$rel"
+ if [ -f "$f" ]; then
+ printf ' %-42s %10s %s\n' "$rel" "$(wc -c < "$f" | tr -d ' ')" \
+ "$(shasum -a 256 "$f" | cut -c1-16)"
+ else
+ printf ' %-42s %s\n' "$rel" "MISSING"
+ missing=$((missing + 1))
+ fi
+ done
+}
+
+report "built here" "$built"
+report "from Valve" "$valve"
+
+# Listed relative to the bridge so the paths stay printable and the directory name
+# containing spaces never has to be stripped by pattern. grep does the comparison
+# because a case statement inside a command substitution does not parse in the sh
+# macOS ships. Every line of $expected is one fixed whole-line pattern, and grep
+# exits nonzero when nothing is left over, which is the ordinary result.
+strays="$(cd "$BRIDGE_DIR" && { find . -mindepth 1 -type f | sed 's|^\./||' \
+ | grep -Fxv "$expected" || true; })"
+
+unexpected=0
+[ -n "$strays" ] && unexpected="$(printf '%s\n' "$strays" | wc -l | tr -d ' ')"
+
+echo "==> unexpected"
+if [ "$unexpected" -eq 0 ]; then
+ echo " none"
+else
+ printf '%s\n' "$strays" | while read -r rel; do
+ if [ "$prune" -eq 1 ]; then
+ mkdir -p "$ATTIC/$(dirname "$rel")"
+ mv "$BRIDGE_DIR/$rel" "$ATTIC/$rel"
+ printf ' moved to attic: %s\n' "$rel"
+ else
+ printf ' %s\n' "$rel"
+ fi
+ done
+fi
+
+if [ "$prune" -eq 1 ] && [ "$unexpected" -gt 0 ]; then
+ # Moving files leaves the directories that held them behind.
+ ( cd "$BRIDGE_DIR" && find . -mindepth 1 -type d -empty -delete )
+ unexpected=0
+fi
+
+# A whole copy of the bridge parked beside it is the other way this directory
+# accumulates. Each one is a few hundred megabytes of binaries that no launch reads
+# and that no build target maintains, so they only go stale.
+copies="$(find "$SUPPORT_DIR" -maxdepth 1 -mindepth 1 -type d -name "$BRIDGE_NAME.*" \
+ | sed "s|^$SUPPORT_DIR/||" | sort)"
+stale=0
+[ -n "$copies" ] && stale="$(printf '%s\n' "$copies" | wc -l | tr -d ' ')"
+
+echo "==> stale bridge copies"
+if [ "$stale" -eq 0 ]; then
+ echo " none"
+else
+ printf '%s\n' "$copies" | while read -r c; do
+ sz="$(du -sh "$SUPPORT_DIR/$c" | awk '{print $1}')"
+ if [ "$prune" -eq 1 ]; then
+ mkdir -p "$ATTIC"
+ rm -rf "${ATTIC:?}/${c:?}"
+ mv "$SUPPORT_DIR/$c" "$ATTIC/$c"
+ printf ' moved to attic: %-42s %s\n' "$c" "$sz"
+ else
+ printf ' %-42s %s\n' "$c" "$sz"
+ fi
+ done
+ [ "$prune" -eq 1 ] && stale=0
+fi
+
+
+# RUN_SCRIPT rewrites the flat bridge files in each prefix's Steam directory and the one
+# i386 lsteamclient.dll trigger in syswow64 on every launch, so a stale copy in either
+# place heals itself and is only worth reporting. Anywhere else in a prefix is different:
+# nothing rewrites it and nothing prunes it, so it keeps whatever build put it there.
+# system32 is the case that matters. install_lsteamclient deliberately puts nothing there
+# so that a 64 bit load never finds a trigger it did not stage, and a correct-arch PE
+# appearing there defeats that on its own.
+PREFIX_ROOT="${PREFIX_ROOT:-$HOME/Library/Application Support/Steam/steamapps/compatdata}"
+
+prefix_strays=""
+prefixes=0
+prefix_stale=0
+if [ -d "$PREFIX_ROOT" ]; then
+ for pfx in "$PREFIX_ROOT"/*/pfx; do
+ [ -d "$pfx" ] || continue
+ prefixes=$((prefixes + 1))
+ appid="$(basename "$(dirname "$pfx")")"
+
+ staged="$pfx/drive_c/Program Files (x86)/Steam/lsteamclient.dll"
+ trigger="$pfx/drive_c/windows/syswow64/lsteamclient.dll"
+ for pair in "$staged:$BRIDGE_DIR/lsteamclient.dll" \
+ "$trigger:$BRIDGE_DIR/i386-windows/lsteamclient.dll"; do
+ have="${pair%:*}"
+ want="${pair##*:}"
+ [ -f "$have" ] || continue
+ cmp -s "$have" "$want" || prefix_stale=$((prefix_stale + 1))
+ done
+
+ while IFS= read -r f; do
+ [ -n "$f" ] || continue
+ rel="${f#"$pfx"/}"
+ case "$rel" in
+ "drive_c/Program Files (x86)/Steam/"*) continue ;;
+ "drive_c/windows/syswow64/lsteamclient.dll") continue ;;
+ esac
+ prefix_strays="$prefix_strays$appid/$rel
+"
+ done <<STRAYS
+$(find "$pfx" -type f \
+ \( -name lsteamclient.dll -o -name lsteamclient.so \
+ -o -name steamclient.dll -o -name steamclient64.dll \
+ -o -name tier0_s64.dll -o -name vstdlib_s64.dll \
+ -o -name steam.exe \) 2>/dev/null)
+STRAYS
+ done
+fi
+
+prefix_strays="$(printf '%s' "$prefix_strays" | sed '/^$/d')"
+stray_count=0
+[ -n "$prefix_strays" ] && stray_count="$(printf '%s\n' "$prefix_strays" | wc -l | tr -d ' ')"
+
+echo "==> prefix strays ($prefixes prefixes, $prefix_stale staged copies stale, heal next launch)"
+if [ "$stray_count" -eq 0 ]; then
+ echo " none"
+else
+ printf '%s\n' "$prefix_strays" | while read -r rel; do
+ appid="${rel%%/*}"
+ sub="${rel#*/}"
+ src="$PREFIX_ROOT/$appid/pfx/$sub"
+ if [ "$prune" -eq 1 ]; then
+ mkdir -p "$ATTIC/prefix-strays/$appid/$(dirname "$sub")"
+ mv "$src" "$ATTIC/prefix-strays/$appid/$sub"
+ printf ' moved to attic: %s\n' "$rel"
+ else
+ printf ' %s\n' "$rel"
+ fi
+ done
+ [ "$prune" -eq 1 ] && stray_count=0
+fi
+
+[ "$prune" -eq 1 ] && echo "==> attic: $ATTIC"
+echo "==> $missing missing, $unexpected unexpected, $stale stale copies, $stray_count prefix strays"
+[ "$missing" -eq 0 ] && [ "$unexpected" -eq 0 ] && [ "$stale" -eq 0 ] && [ "$stray_count" -eq 0 ]
diff --git a/dylib/core/loader.c b/dylib/core/loader.c
new file mode 100644
index 0000000..369451e
--- /dev/null
+++ b/dylib/core/loader.c
@@ -0,0 +1,242 @@
+// Dylib entry point into steamclient.dylib
+#include "../version.h"
+#include "../util/log.h"
+#include "../util/file.h"
+#include "../resolver/resolver.h"
+#include "../resolver/sigdb.h"
+#include "../core/macho.h"
+#include "../hooks/hooks.h"
+#include "../feats/compat.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <pthread.h>
+#include <stdint.h>
+#include <dirent.h>
+#include <mach-o/dyld.h>
+#include <libgen.h>
+
+#define STEAMCLIENT_DYLIB "steamclient.dylib"
+
+// The bootstrapper can take a while before the real client dylib appears...
+#define WAIT_TIMEOUT_MS 60000
+
+static void drop_marker_file(const char *dir, const char *name) {
+ char path[1024];
+ int len = snprintf(path, sizeof(path), "%s/%s", dir, name);
+ if (len < 0 || len >= (int)sizeof(path))
+ return;
+ if (unlink(path) == 0)
+ NP_LOG("removed marker %s", path);
+}
+
+// A leftover 'marker' makes the client redownload and rewrite Info.plist, which is bad.
+static void clear_relaunch_markers(void) {
+ char exe[1024];
+ uint32_t cap = sizeof(exe);
+ if (_NSGetExecutablePath(exe, &cap) != 0) {
+ NP_WARN("could not read own executable path");
+ return;
+ }
+
+ char scratch[1024];
+ snprintf(scratch, sizeof(scratch), "%s", exe);
+ const char *dir = dirname(scratch);
+
+ drop_marker_file(dir, ".crash");
+ drop_marker_file(dir, ".forceupdate");
+}
+
+static int pick_latest_sigdb(const char *dir, char *buf, size_t buf_size) {
+ DIR *dh = opendir(dir);
+ if (!dh)
+ return -1;
+
+ uint64_t top = 0;
+ int found = 0;
+ struct dirent *e;
+ while ((e = readdir(dh)) != NULL) {
+ size_t len = strlen(e->d_name);
+ if (len < 6 || strcmp(e->d_name + len - 5, ".json") != 0)
+ continue;
+
+ char *stop = NULL;
+ uint64_t build = strtoull(e->d_name, &stop, 10);
+ if (build == 0 || stop != e->d_name + len - 5)
+ continue;
+
+ if (!found || build >= top) {
+ top = build;
+ found = 1;
+ snprintf(buf, buf_size, "%s/%s", dir, e->d_name);
+ }
+ }
+ closedir(dh);
+
+ return found ? 0 : -1;
+}
+
+static void sigdb_path_for(char *buf, size_t buf_size) {
+ const char *env = getenv("NOTPROTON_SIG");
+ if (env && env[0]) {
+ snprintf(buf, buf_size, "%s", env);
+ return;
+ }
+
+ const char *home = np_home_dir();
+ if (!home) {
+ snprintf(buf, buf_size, "<no-home>/<none>.json");
+ return;
+ }
+
+ char dir[512];
+ np_support_path(dir, sizeof(dir), home, "signatures/macos.arm64");
+
+ if (pick_latest_sigdb(dir, buf, buf_size) == 0)
+ return;
+
+ snprintf(buf, buf_size, "%s/<none>.json", dir);
+}
+
+static pthread_t g_install;
+static int g_install_started;
+static int g_active;
+
+static void *install_thread(void *unused) {
+ (void)unused;
+
+ NP_LOG("install_thread: waiting for %s", STEAMCLIENT_DYLIB);
+
+ const struct mach_header_64 *mh = NULL;
+ intptr_t slide = 0;
+
+ if (np_await_image(STEAMCLIENT_DYLIB, WAIT_TIMEOUT_MS, &mh, &slide,
+ NULL, 0) != 0) {
+ // The Steam bootstraper does this
+ NP_LOG("install_thread: %s absent after %d ms, hooks will install in the "
+ "relaunched client", STEAMCLIENT_DYLIB, WAIT_TIMEOUT_MS);
+ return NULL;
+ }
+
+ uintptr_t text_base = 0;
+ size_t text_size = 0;
+
+ if (np_find_segment(mh, slide, "__TEXT", &text_base, &text_size) != 0) {
+ NP_ERR("install_thread: no __TEXT segment in %s", STEAMCLIENT_DYLIB);
+ return NULL;
+ }
+
+ NP_LOG("install_thread: %s __TEXT @ 0x%lx (%zu bytes) slide=0x%lx",
+ STEAMCLIENT_DYLIB, (unsigned long)text_base, text_size,
+ (unsigned long)slide);
+
+ np_sigdb_t sigdb = {0};
+
+ char sig_path[512];
+ sigdb_path_for(sig_path, sizeof(sig_path));
+
+ if (np_load_profile(sig_path, &sigdb) != 0) {
+ NP_ERR("install_thread: cannot load signature database from %s", sig_path);
+ return NULL;
+ }
+
+ np_resolve_result_t resolved = {0};
+
+ int resolved_count = np_resolve_signatures(mh, slide, &sigdb, &resolved);
+ NP_LOG("install_thread: signatures %d/%d resolved", resolved_count, sigdb.sig_count);
+
+ int required = 0;
+ for (int i = 0; i < sigdb.sig_count; i++)
+ if (!sigdb.signatures[i].deprecated) required++;
+
+ // Safety feature :)
+ if (resolved_count < required) {
+ NP_ERR("install_thread: %d/%d signatures resolved, installing nothing; "
+ "the signature database is out of date for this Steam build",
+ resolved_count, required);
+ np_free_resolution(&resolved);
+ np_free_profile(&sigdb);
+ return NULL;
+ }
+
+ // Registers compatibility tool.
+ np_compat_ensure_tool_manifest();
+
+ int total = 0;
+ int installed = np_hooks_install_all(mh, slide, &resolved, &total);
+
+ NP_LOG("install_thread: ready, %d/%d hooks installed", installed, total);
+
+ if (installed == 0)
+ NP_WARN("install_thread: no hooks installed, check the signature database");
+ else if (installed < total)
+ NP_WARN("install_thread: only %d of %d hooks installed, compat support is "
+ "incomplete for this client build", installed, total);
+
+ np_free_resolution(&resolved);
+ np_free_profile(&sigdb);
+
+ return NULL;
+}
+
+static void np_log_platform_overrides(void) {
+ static const char *const vars[] = {
+ "SteamOverridePlatform",
+ "SteamPlatform",
+ "STEAM_FORCE_OS",
+ "STEAMOS",
+ "SteamOS",
+ "SteamOverrideOSType",
+ "STEAM_COMPAT_FORCE_PLATFORM",
+ };
+
+ int found = 0;
+ for (size_t i = 0; i < sizeof(vars) / sizeof(vars[0]); i++) {
+ const char *val = getenv(vars[i]);
+ if (val) {
+ NP_LOG("np_init: platform override present %s=%s", vars[i], val);
+ found = 1;
+ }
+ }
+ if (!found)
+ NP_LOG("np_init: no platform override env set, client reports as macOS");
+}
+
+__attribute__((constructor))
+static void np_init(void) {
+ const char *pn = getprogname();
+ if (!pn || strcmp(pn, "steam_osx") != 0)
+ return;
+
+ np_log_init();
+ g_active = 1;
+
+ clear_relaunch_markers();
+
+ NP_LOG("np_init: loaded into %s (pid %d) version %s",
+ pn, getpid(), NOTPROTON_VERSION);
+
+ np_log_platform_overrides();
+ np_compat_export_tools_path();
+ np_hooks_spawn_install();
+
+ if (pthread_create(&g_install, NULL, install_thread, NULL) == 0)
+ g_install_started = 1;
+ else
+ NP_ERR("np_init: cannot create loader thread");
+}
+
+__attribute__((destructor))
+static void np_fini(void) {
+ if (!g_active)
+ return;
+
+ if (g_install_started) {
+ np_await_stop();
+ pthread_join(g_install, NULL);
+ }
+
+ NP_LOG("np_fini: unloading, hooks left in place for the OS to reclaim");
+}
diff --git a/dylib/core/macho.c b/dylib/core/macho.c
new file mode 100644
index 0000000..680fa73
--- /dev/null
+++ b/dylib/core/macho.c
@@ -0,0 +1,103 @@
+#include "macho.h"
+#include <mach-o/dyld.h>
+#include <signal.h>
+#include <string.h>
+#include <unistd.h>
+
+static volatile sig_atomic_t g_await_stop;
+
+void np_await_stop(void) {
+ g_await_stop = 1;
+}
+
+static int image_index_by_name(const char *needle) {
+ uint32_t n = _dyld_image_count();
+ for (uint32_t idx = 0; idx < n; idx++) {
+ const char *path = _dyld_get_image_name(idx);
+ if (path && strstr(path, needle))
+ return (int)idx;
+ }
+ return -1;
+}
+
+int np_await_image(const char *name, int timeout_ms,
+ const struct mach_header_64 **out_mh, intptr_t *out_slide,
+ char *out_path, size_t path_size) {
+ for (int waited = 0; waited < timeout_ms; waited += 100) {
+ if (g_await_stop) return -1;
+
+ int idx = image_index_by_name(name);
+ if (idx >= 0) {
+ *out_mh = (const struct mach_header_64 *)_dyld_get_image_header((uint32_t)idx);
+ *out_slide = _dyld_get_image_vmaddr_slide((uint32_t)idx);
+ if (out_path && path_size) {
+ const char *p = _dyld_get_image_name((uint32_t)idx);
+ size_t len = strlen(p);
+ if (len >= path_size) len = path_size - 1;
+ memcpy(out_path, p, len);
+ out_path[len] = '\0';
+ }
+ return 0;
+ }
+ usleep(100000);
+ }
+ return -1;
+}
+
+int np_find_segment(const struct mach_header_64 *mh, intptr_t slide,
+ const char *segname, uintptr_t *out_base, size_t *out_size) {
+ if (!mh || !segname) return -1;
+
+ const uint8_t *cursor = (const uint8_t *)(mh + 1);
+ uint32_t remaining = mh->ncmds;
+
+ while (remaining--) {
+ const struct load_command *lc = (const struct load_command *)cursor;
+ if (lc->cmdsize < sizeof(*lc))
+ return -1; // corrupt or truncated
+ if (lc->cmd == LC_SEGMENT_64) {
+ const struct segment_command_64 *sc = (const struct segment_command_64 *)cursor;
+ if (strncmp(sc->segname, segname, sizeof(sc->segname)) == 0) {
+ *out_base = (uintptr_t)sc->vmaddr + (uintptr_t)slide;
+ *out_size = (size_t)sc->vmsize;
+ return 0;
+ }
+ }
+ cursor += lc->cmdsize;
+ }
+ return -1;
+}
+
+int np_get_section_containing(const struct mach_header_64 *mh, intptr_t slide,
+ uintptr_t addr, uintptr_t *out_base,
+ size_t *out_size) {
+ if (!mh || !out_base || !out_size) return -1;
+
+ const uint8_t *cursor = (const uint8_t *)(mh + 1);
+ uint32_t remaining = mh->ncmds;
+
+ while (remaining--) {
+ const struct load_command *lc = (const struct load_command *)cursor;
+ if (lc->cmdsize < sizeof(*lc))
+ return -1; // corrupt or truncated
+ if (lc->cmd == LC_SEGMENT_64) {
+ const struct segment_command_64 *sc =
+ (const struct segment_command_64 *)cursor;
+
+ if (lc->cmdsize < sizeof(*sc) + sc->nsects * sizeof(struct section_64))
+ return -1;
+
+ const struct section_64 *sect = (const struct section_64 *)(sc + 1);
+ for (uint32_t i = 0; i < sc->nsects; i++) {
+ uintptr_t base = (uintptr_t)sect[i].addr + (uintptr_t)slide;
+ if (addr < base || addr >= base + (uintptr_t)sect[i].size)
+ continue;
+ *out_base = base;
+ *out_size = (size_t)sect[i].size;
+ return 0;
+ }
+ }
+ cursor += lc->cmdsize;
+ }
+ return -1;
+}
diff --git a/dylib/core/macho.h b/dylib/core/macho.h
new file mode 100644
index 0000000..460be98
--- /dev/null
+++ b/dylib/core/macho.h
@@ -0,0 +1,21 @@
+#ifndef NOTPROTON_CORE_MACHO_H
+#define NOTPROTON_CORE_MACHO_H
+
+#include <stdint.h>
+#include <stddef.h>
+#include <mach-o/loader.h>
+
+int np_await_image(const char *name, int timeout_ms,
+ const struct mach_header_64 **out_mh, intptr_t *out_slide,
+ char *out_path, size_t path_size);
+
+void np_await_stop(void);
+
+int np_find_segment(const struct mach_header_64 *mh, intptr_t slide,
+ const char *segname, uintptr_t *out_base, size_t *out_size);
+
+int np_get_section_containing(const struct mach_header_64 *mh, intptr_t slide,
+ uintptr_t addr, uintptr_t *out_base,
+ size_t *out_size);
+
+#endif // NOTPROTON_CORE_MACHO_H
diff --git a/dylib/embed_script.py b/dylib/embed_script.py
new file mode 100644
index 0000000..7f3d148
--- /dev/null
+++ b/dylib/embed_script.py
@@ -0,0 +1,42 @@
+#!/usr/bin/env python3
+# Turns a shell script into a C string literal.
+import sys
+from pathlib import Path
+
+
+def literal(text: str) -> str:
+ lines = text.split("\n")
+ if lines and lines[-1] == "":
+ lines.pop()
+ out = []
+ for line in lines:
+ body = line.replace("\\", "\\\\").replace('"', '\\"')
+ out.append(f' "{body}\\n"')
+ return "\n".join(out)
+
+
+def main() -> int:
+ if len(sys.argv) != 4:
+ sys.stderr.write("usage: embed_script.py <input.sh> <output.h> <symbol>\n")
+ return 2
+ src, dst, symbol = Path(sys.argv[1]), Path(sys.argv[2]), sys.argv[3]
+
+ text = src.read_text(encoding="ascii")
+ guard = f"NOTPROTON_GENERATED_{symbol.upper()}_H"
+ header = (
+ f"// Generated from {src.as_posix()} by dylib/embed_script.py. Edit that file.\n"
+ f"#ifndef {guard}\n"
+ f"#define {guard}\n"
+ f"\n"
+ f"static const char {symbol}[] =\n"
+ f"{literal(text)};\n"
+ f"\n"
+ f"#endif // {guard}\n"
+ )
+ dst.parent.mkdir(parents=True, exist_ok=True)
+ dst.write_text(header, encoding="ascii")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/dylib/feats/compat.c b/dylib/feats/compat.c
new file mode 100644
index 0000000..163d066
--- /dev/null
+++ b/dylib/feats/compat.c
@@ -0,0 +1,568 @@
+// Compatibility tool support
+#include "compat.h"
+#include "../util/log.h"
+#include "../util/file.h"
+
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+// The client maps Cloud's Windows path roots into the compat prefix only when
+// the tool's name contains "proton" so without a match every AutoCloud rule silently
+// skips the app.
+#define TOOL_DIR_NAME "notproton"
+#define TOOL_DISPLAY_NAME "CrossOver Preview"
+
+#define COMPAT_MANAGER_ENABLED_OFF 0x7B0
+#define COMPAT_TOOL_STRIDE 0x130
+#define COMPAT_TOOL_FLAGS_OFF 0x28 // bit 0: tool needs no downloaded app
+#define COMPAT_TOOL_FLAG_NO_APP 0x1
+#define COMPAT_TOOL_FROM_OSLIST_OFF 0x70
+#define COMPAT_TOOL_TO_OSLIST_OFF 0x78
+
+#define COMPAT_MAPPING_PRIORITY_GLOBAL 75
+#define COMPAT_MAPPING_PRIORITY_APP 250
+
+static const char TOOL_MANIFEST[] =
+ "\"manifest\"\n"
+ "{\n"
+ " \"version\" \"2\"\n"
+ " \"commandline\" \"/run %verb%\"\n"
+ "}\n";
+
+// Steam's compatibilitytools.d scanner registers a tool when this file is present
+// in the tool subdirectory. install_path is "." because the manifest lives inside
+// the tool directory. to_oslist is macos
+static const char TOOL_DECLARATION[] =
+ "\"compatibilitytools\"\n"
+ "{\n"
+ " \"compat_tools\"\n"
+ " {\n"
+ " \"" TOOL_DIR_NAME "\"\n"
+ " {\n"
+ " \"install_path\" \".\"\n"
+ " \"display_name\" \"" TOOL_DISPLAY_NAME "\"\n"
+ " \"from_oslist\" \"windows\"\n"
+ " \"to_oslist\" \"macos\"\n"
+ " }\n"
+ " }\n"
+ "}\n";
+
+#include "compat_run.h" // RUN_SCRIPT, generated from compat_run.sh
+
+static int write_file(const char *path, const char *content, int executable) {
+ FILE *f = fopen(path, "w");
+ if (!f) return -1;
+ fputs(content, f);
+ int err = fclose(f);
+ if (executable)
+ chmod(path, 0755);
+ return err ? -1 : 0;
+}
+
+static int ensure_dir(const char *path) {
+ struct stat st;
+ if (stat(path, &st) == 0)
+ return S_ISDIR(st.st_mode) ? 0 : -1;
+ return mkdir(path, 0755);
+}
+
+static int32_t g_tool_shift;
+
+// LDR Wt,[X0,#imm]. Writes the byte offset and destination register.
+static int ldr32_from_x0(uint32_t w, uint32_t *off, uint32_t *rt) {
+ if ((w & 0xFFC003E0u) != 0xB9400000u) return 0;
+ *rt = w & 0x1Fu;
+ *off = ((w >> 10) & 0xFFFu) * 4u;
+ return 1;
+}
+
+// LDR Xt,[Xn,#imm] for a named base register.
+static int ldr64_from(uint32_t w, uint32_t base, uint32_t *off) {
+ if ((w & 0xFFC00000u) != 0xF9400000u) return 0;
+ if (((w >> 5) & 0x1Fu) != base) return 0;
+ *off = ((w >> 10) & 0xFFFu) * 8u;
+ return 1;
+}
+
+static int ldr64_from_x0(uint32_t w, uint32_t *off) {
+ return ldr64_from(w, 0, off);
+}
+
+// LDRB Wt,[Xn,#imm] for a named base register.
+static int ldrb_from(uint32_t w, uint32_t base, uint32_t *off) {
+ if ((w & 0xFFC00000u) != 0x39400000u) return 0;
+ if (((w >> 5) & 0x1Fu) != base) return 0;
+ *off = (w >> 10) & 0xFFFu;
+ return 1;
+}
+
+// MOV Xd,X0, which assembles as ORR Xd,XZR,X0. Writes the destination register.
+static int mov_from_x0(uint32_t w, uint32_t *rd) {
+ if ((w & 0xFFFFFFE0u) != 0xAA0003E0u) return 0;
+ *rd = w & 0x1Fu;
+ return 1;
+}
+
+// CBZ Wt. Writes the branch target.
+static int cbz32(uintptr_t pc, uint32_t w, uint32_t rt, uintptr_t *target) {
+ if ((w & 0xFF000000u) != 0x34000000u) return 0;
+ if ((w & 0x1Fu) != rt) return 0;
+ int32_t imm = (int32_t)((w >> 5) & 0x7FFFFu);
+ imm = (imm << 13) >> 13;
+ *target = pc + (uintptr_t)(imm * 4);
+ return 1;
+}
+
+// The oslist gate compares both oslist strings, so its two loads sit at the far
+// end of the struct and corroborate a shift derived at the near end. The base
+// register is whatever the compiler picked, so a build that stops using the one
+// seen here yields nothing and the shift stands on the near-end pair alone.
+// Returns the number of offsets written.
+static int probe_oslist_offsets(uintptr_t oslist_gate, uint32_t base,
+ uint32_t *from_off, uint32_t *to_off) {
+ if (!oslist_gate) return 0;
+
+ uint32_t seen[2];
+ int n = 0;
+ for (uintptr_t pc = oslist_gate - 0x40; pc <= oslist_gate + 0x20; pc += 4) {
+ uint32_t off;
+ if (!ldr64_from(*(const uint32_t *)pc, base, &off)) continue;
+ if (n > 0 && seen[0] == off) continue;
+ if (n > 1 && seen[1] == off) continue;
+ if (n == 2) return 0;
+ seen[n++] = off;
+ }
+ if (n != 2) return 0;
+
+ // to_oslist sits above from_oslist in the struct, whichever order the
+ // comparison happens to load them in.
+ *to_off = seen[0] > seen[1] ? seen[0] : seen[1];
+ *from_off = seen[0] > seen[1] ? seen[1] : seen[0];
+ return 2;
+}
+
+int np_compat_probe_tool_layout(uintptr_t appid_gate, uintptr_t oslist_gate) {
+ if (!appid_gate) return 0;
+
+ uint32_t appid_off, rt;
+ if (!ldr32_from_x0(*(const uint32_t *)appid_gate, &appid_off, &rt)) {
+ NP_WARN("np_compat_probe_tool_layout: 0x%lx is not the appid load",
+ (unsigned long)appid_gate);
+ return 0;
+ }
+
+ uintptr_t local_path;
+ if (!cbz32(appid_gate + 4, *(const uint32_t *)(appid_gate + 4), rt, &local_path)) {
+ NP_WARN("np_compat_probe_tool_layout: no appid branch after 0x%lx",
+ (unsigned long)appid_gate);
+ return 0;
+ }
+
+ // The install field is the first thing the local path wants, within a few
+ // instructions of the branch landing.
+ uint32_t install_off = 0;
+ for (uintptr_t pc = local_path; pc < local_path + 0x20; pc += 4) {
+ if (ldr64_from_x0(*(const uint32_t *)pc, &install_off)) break;
+ }
+ if (!install_off) {
+ NP_WARN("np_compat_probe_tool_layout: no install load at 0x%lx",
+ (unsigned long)local_path);
+ return 0;
+ }
+
+ int32_t by_appid = (int32_t)appid_off - COMPAT_TOOL_APPID_OFF;
+ int32_t by_install = (int32_t)install_off - COMPAT_TOOL_INSTALL_OFF;
+ if (by_appid != by_install) {
+ NP_ERR("np_compat_probe_tool_layout: appid moved %+d but install moved %+d; "
+ "the tool layout no longer shifts as one block",
+ by_appid, by_install);
+ return 0;
+ }
+
+ // COMPAT_TOOL_TO_OSLIST_OFF is the highest field written into a registration,
+ // so agreement there means the shift holds across every field in use rather
+ // than only the two it was read from.
+ uint32_t from_off = 0, to_off = 0;
+ if (probe_oslist_offsets(oslist_gate, 21, &from_off, &to_off) == 2) {
+ int32_t by_from = (int32_t)from_off - COMPAT_TOOL_FROM_OSLIST_OFF;
+ int32_t by_to = (int32_t)to_off - COMPAT_TOOL_TO_OSLIST_OFF;
+ if (by_from != by_appid || by_to != by_appid) {
+ NP_ERR("np_compat_probe_tool_layout: near fields moved %+d but oslist "
+ "moved %+d/%+d; the tool layout no longer shifts as one block",
+ by_appid, by_from, by_to);
+ return 0;
+ }
+ NP_DBG("np_compat_probe_tool_layout: oslist offsets 0x%x/0x%x agree on %+d",
+ from_off, to_off, by_appid);
+ }
+
+ g_tool_shift = by_appid;
+ if (g_tool_shift)
+ NP_LOG("np_compat_probe_tool_layout: tool fields from install onward are "
+ "%+d from the baseline (appid 0x%x, install 0x%x)",
+ g_tool_shift, appid_off, install_off);
+ return 1;
+}
+
+// The manager is a much larger object than a tool entry and grows in the middle,
+// so a single distance does not describe it the way one does for the tool tail:
+// the tool array and its count sit below the growth and do not move, while the
+// enabled flag sits above it and does. Reading the flag's own offset back keeps
+// the two independent.
+static uint32_t g_enabled_off = COMPAT_MANAGER_ENABLED_OFF;
+
+int np_compat_probe_enabled_off(uintptr_t bis_enabled) {
+ if (!bis_enabled) return 0;
+
+ // this arrives in X0 and is parked in a callee-saved register before the
+ // profiling call clobbers it, so the flag is read through that register.
+ uint32_t base = 0;
+ int have_base = 0;
+ for (uintptr_t pc = bis_enabled; pc < bis_enabled + 0x40; pc += 4) {
+ if (mov_from_x0(*(const uint32_t *)pc, &base)) { have_base = 1; break; }
+ }
+ if (!have_base) {
+ NP_WARN("np_compat_probe_enabled_off: this is never parked in a register "
+ "at 0x%lx", (unsigned long)bis_enabled);
+ return 0;
+ }
+
+ // The flag is the first thing the body tests, ahead of any other byte read
+ // through that register.
+ uint32_t off = 0;
+ int found = 0;
+ for (uintptr_t pc = bis_enabled; pc < bis_enabled + 0x80; pc += 4) {
+ if (ldrb_from(*(const uint32_t *)pc, base, &off)) { found = 1; break; }
+ }
+ if (!found) {
+ NP_WARN("np_compat_probe_enabled_off: no flag load through x%u at 0x%lx",
+ base, (unsigned long)bis_enabled);
+ return 0;
+ }
+
+ // A tiny offset would mean the match landed on some unrelated early byte
+ // read rather than on the flag, which sits far into the object.
+ if (off < 0x100) {
+ NP_ERR("np_compat_probe_enabled_off: 0x%x is too low to be the enabled "
+ "flag; refusing to write it", off);
+ return 0;
+ }
+
+ if (off != g_enabled_off)
+ NP_LOG("np_compat_probe_enabled_off: enabled flag at 0x%x, %+d from the "
+ "baseline", off, (int32_t)off - COMPAT_MANAGER_ENABLED_OFF);
+ g_enabled_off = off;
+ return 1;
+}
+
+uint32_t np_compat_enabled_off(void) {
+ return g_enabled_off;
+}
+
+uint32_t np_compat_tool_off(uint32_t reference_off) {
+ if (reference_off < COMPAT_TOOL_INSTALL_OFF) return reference_off;
+ return (uint32_t)((int32_t)reference_off + g_tool_shift);
+}
+
+size_t np_compat_tool_stride(void) {
+ return (size_t)((int32_t)COMPAT_TOOL_STRIDE + g_tool_shift);
+}
+
+// The compatibility tool needs to go in the folder Steam normally (on Linux)
+// scans for compatibility tools. So the tool is shoved into
+// ~/Library/Application Support/Steam/compatibilitytools.d and
+// STEAM_EXTRA_COMPAT_TOOLS_PATHS points there.
+void np_compat_export_tools_path(void) {
+ const char *home = np_home_dir();
+ if (!home) return;
+ if (getenv("STEAM_EXTRA_COMPAT_TOOLS_PATHS")) return;
+
+ char tools_dir[512];
+ snprintf(tools_dir, sizeof(tools_dir),
+ "%s/Library/Application Support/Steam/compatibilitytools.d", home);
+
+ setenv("STEAM_EXTRA_COMPAT_TOOLS_PATHS", tools_dir, 1);
+ NP_LOG("np_compat_export_tools_path: set STEAM_EXTRA_COMPAT_TOOLS_PATHS=%s",
+ tools_dir);
+}
+
+int np_compat_ensure_tool_manifest(void) {
+ const char *home = np_home_dir();
+ if (!home) return -1;
+
+ char tools_dir[512];
+ snprintf(tools_dir, sizeof(tools_dir),
+ "%s/Library/Application Support/Steam/compatibilitytools.d", home);
+
+ if (ensure_dir(tools_dir) != 0) {
+ NP_WARN("np_compat_ensure_tool_manifest: cannot create %s", tools_dir);
+ return -1;
+ }
+
+ char tool_dir[512];
+ snprintf(tool_dir, sizeof(tool_dir), "%s/%s", tools_dir, TOOL_DIR_NAME);
+
+ if (ensure_dir(tool_dir) != 0) {
+ NP_WARN("np_compat_ensure_tool_manifest: cannot create %s", tool_dir);
+ return -1;
+ }
+
+ char path[512];
+ int wrote = 0;
+
+ // Rewritten every launch so field changes take effect. A rescan replaces it in
+ // place rather than adding a second copy.
+ snprintf(path, sizeof(path), "%s/compatibilitytool.vdf", tool_dir);
+ if (write_file(path, TOOL_DECLARATION, 0) == 0) wrote++;
+ else NP_WARN("np_compat_ensure_tool_manifest: failed to write %s", path);
+
+ snprintf(path, sizeof(path), "%s/toolmanifest.vdf", tool_dir);
+ if (access(path, F_OK) != 0) {
+ if (write_file(path, TOOL_MANIFEST, 0) == 0) wrote++;
+ else NP_WARN("np_compat_ensure_tool_manifest: failed to write %s", path);
+ }
+
+ // The run script is the shim this project owns and updates, so rewrite it
+ // every launch rather than leaving a stale copy behind.
+ snprintf(path, sizeof(path), "%s/run", tool_dir);
+ if (write_file(path, RUN_SCRIPT, 1) == 0) wrote++;
+ else NP_WARN("np_compat_ensure_tool_manifest: failed to write %s", path);
+
+ if (wrote > 0)
+ NP_LOG("np_compat_ensure_tool_manifest: wrote %d file(s) to %s", wrote, tool_dir);
+
+ return 0;
+}
+
+const char *np_compat_tool_dir(void) {
+ static char dir[512];
+ static int resolved = 0;
+
+ if (resolved)
+ return dir[0] ? dir : NULL;
+
+ resolved = 1;
+
+ const char *home = np_home_dir();
+ if (!home) {
+ dir[0] = '\0';
+ return NULL;
+ }
+
+ snprintf(dir, sizeof(dir),
+ "%s/Library/Application Support/Steam/compatibilitytools.d/%s",
+ home, TOOL_DIR_NAME);
+ return dir;
+}
+
+const char *np_compat_tool_commandline(void) {
+ return "/run %verb%";
+}
+
+void np_compat_force_enable(void *compat_mgr) {
+ if (!compat_mgr) return;
+
+ uint8_t *base = (uint8_t *)compat_mgr;
+ uint32_t off = np_compat_enabled_off();
+ uint8_t prev = base[off];
+ base[off] = 1;
+
+ // Steam polls compat state frequently. Only log the one transition.
+ if (!prev)
+ NP_LOG("np_compat_force_enable: compat layer force-enabled (this+0x%X: 0 -> 1)",
+ off);
+}
+
+typedef uint32_t (*fn_GetValidPlatforms)(void *compat_mgr, uint32_t appid);
+static fn_GetValidPlatforms g_get_valid_platforms;
+
+void np_compat_set_valid_platforms_fn(uintptr_t get_valid_platforms) {
+ g_get_valid_platforms = (fn_GetValidPlatforms)get_valid_platforms;
+}
+
+uint32_t np_compat_valid_platforms(void *compat_mgr, uint32_t appid) {
+ if (!g_get_valid_platforms || !compat_mgr)
+ return 0;
+ return g_get_valid_platforms(compat_mgr, appid);
+}
+
+typedef void *(*fn_FindToolForTargetApp)(void *compat_mgr, uint32_t appid);
+static fn_FindToolForTargetApp g_find_tool_for_app;
+
+void np_compat_set_find_tool_fn(uintptr_t find_tool_for_target_app) {
+ g_find_tool_for_app = (fn_FindToolForTargetApp)find_tool_for_target_app;
+}
+
+void *np_compat_tool_for_app(void *compat_mgr, uint32_t appid) {
+ if (!g_find_tool_for_app || !compat_mgr)
+ return NULL;
+ return g_find_tool_for_app(compat_mgr, appid);
+}
+
+// The config argument is a tool-specific string the dropdown has no way to set, and
+// the client passes it empty from its own handler.
+static fn_FindToolForTargetApp g_chosen_tool;
+
+void np_compat_set_chosen_tool_fn(uintptr_t find_tool_for_target_app) {
+ g_chosen_tool = (fn_FindToolForTargetApp)find_tool_for_target_app;
+}
+
+void *np_compat_chosen_tool(void *compat_mgr, uint32_t appid) {
+ if (!g_chosen_tool || !compat_mgr)
+ return NULL;
+ return g_chosen_tool(compat_mgr, appid);
+}
+
+bool np_compat_would_force(void *compat_mgr, uint32_t appid) {
+ if (!compat_mgr || !appid)
+ return false;
+ uint32_t platforms = np_compat_valid_platforms(compat_mgr, appid);
+ return (platforms & COMPAT_PLATFORM_WINDOWS) && !(platforms & COMPAT_PLATFORM_MACOS);
+}
+
+typedef void *(*fn_FindMapping)(void *compat_mgr, uint32_t appid);
+static fn_FindMapping g_find_mapping;
+
+void np_compat_set_app_mapping_fn(uintptr_t find_mapping) {
+ g_find_mapping = (fn_FindMapping)find_mapping;
+}
+
+// { const char *name; const char *config; int32_t priority }, owned by the client.
+static const char *mapping_name(const void *mapping) {
+ const char *const *entry = (const char *const *)mapping;
+ if (!entry || !entry[0] || !entry[0][0])
+ return NULL;
+ return entry[0];
+}
+
+const char *np_compat_app_mapping(void *compat_mgr, uint32_t appid) {
+ if (!g_find_mapping || !compat_mgr || !appid)
+ return NULL;
+ return mapping_name(g_find_mapping(compat_mgr, appid));
+}
+
+static fn_FindMapping g_get_wildcard;
+
+void np_compat_set_wildcard_fn(uintptr_t get_wildcard_mapping) {
+ g_get_wildcard = (fn_FindMapping)get_wildcard_mapping;
+}
+
+const char *np_compat_wildcard_mapping(void *compat_mgr, uint32_t appid) {
+ if (!g_get_wildcard || !compat_mgr || !appid)
+ return NULL;
+ return mapping_name(g_get_wildcard(compat_mgr, appid));
+}
+
+typedef void (*fn_SetCompatToolMapping)(void *compat_mgr, uint32_t appid,
+ const char *tool_name, const char *config,
+ uint32_t priority);
+static fn_SetCompatToolMapping g_set_mapping;
+
+void np_compat_set_mapping_fn(uintptr_t set_compat_tool_mapping) {
+ g_set_mapping = (fn_SetCompatToolMapping)set_compat_tool_mapping;
+}
+
+void np_compat_map_tool(void *compat_mgr, uint32_t appid, const char *tool_name) {
+ if (!g_set_mapping || !compat_mgr || !tool_name) {
+ NP_ERR("np_compat_map_tool: app %u cannot be mapped to %s", appid,
+ tool_name ? tool_name : "no tool");
+ return;
+ }
+ g_set_mapping(compat_mgr, appid, tool_name, "",
+ appid ? COMPAT_MAPPING_PRIORITY_APP
+ : COMPAT_MAPPING_PRIORITY_GLOBAL);
+}
+
+typedef void (*fn_YldRegisterTool)(void *compat_mgr, void *tool);
+static fn_YldRegisterTool g_yld_register_tool;
+
+void np_compat_set_register_fn(uintptr_t yld_register_tool) {
+ g_yld_register_tool = (fn_YldRegisterTool)yld_register_tool;
+}
+
+static void *g_manager;
+
+void *np_compat_manager(void) {
+ return g_manager;
+}
+
+void np_compat_register_crossover(void *compat_mgr) {
+ static int registered = 0;
+
+ // Every compat query arrives on the instance the properties page reads, which is
+ // the one the tool list has to be enumerated from.
+ if (compat_mgr)
+ g_manager = compat_mgr;
+
+ if (registered || !compat_mgr || !g_yld_register_tool)
+ return;
+
+ // The compatibilitytools.d scan registers this tool from disk at client startup,
+ // so any session that found the manifest there already holds an entry and a
+ // second one is a duplicate under the same name. Only the first session after an
+ // install, when the manifest did not exist to be scanned, has nothing to find.
+ if (np_compat_registered_tool(compat_mgr)) {
+ registered = 1;
+ NP_LOG("np_compat_register_crossover: %s already registered from disk, "
+ "skipping the runtime entry", TOOL_DIR_NAME);
+ return;
+ }
+
+ // YldRegisterTool copies a whole entry out of this buffer and keeps the string
+ // pointers as-is, which is why the strings are static and why the buffer carries
+ // headroom for a client that inserted a field. to_oslist=macos passes the
+ // registration gate, from_oslist=windows intersects the app mask so the dropdown
+ // keeps it, and appid 0 marks a manager-local tool the resolver routes to the
+ // local run script.
+ static uint8_t tool[COMPAT_TOOL_STRIDE + 64];
+ memset(tool, 0, sizeof(tool));
+
+ static const char name[] = TOOL_DIR_NAME;
+ static const char display[] = TOOL_DISPLAY_NAME;
+ static const char from_oslist[] = "windows";
+ static const char to_oslist[] = "macos";
+
+ *(uint32_t *)(tool + COMPAT_TOOL_FLAGS_OFF) = COMPAT_TOOL_FLAG_NO_APP;
+ *(const char **)(tool + COMPAT_TOOL_NAME_OFF) = name;
+ *(const char **)(tool + COMPAT_TOOL_DISPLAY_OFF) = display;
+ *(const char **)(tool + np_compat_tool_off(COMPAT_TOOL_INSTALL_OFF)) =
+ np_compat_tool_dir();
+ *(uint32_t *)(tool + np_compat_tool_off(COMPAT_TOOL_APPID_OFF)) = 0;
+ *(const char **)(tool + np_compat_tool_off(COMPAT_TOOL_FROM_OSLIST_OFF)) = from_oslist;
+ *(const char **)(tool + np_compat_tool_off(COMPAT_TOOL_TO_OSLIST_OFF)) = to_oslist;
+
+ registered = 1;
+ g_yld_register_tool(compat_mgr, tool);
+ NP_LOG("np_compat_register_crossover: registered %s into manager 0x%llx",
+ name, (unsigned long long)(uintptr_t)compat_mgr);
+}
+
+void *np_compat_registered_tool(void *compat_mgr) {
+ if (!compat_mgr)
+ return NULL;
+
+ uint8_t *base = (uint8_t *)compat_mgr;
+ uint8_t *array = *(uint8_t **)(base + COMPAT_MANAGER_TOOL_ARRAY_OFF);
+ uint32_t count = *(uint32_t *)(base + COMPAT_MANAGER_TOOL_COUNT_OFF);
+ if (!array || count > COMPAT_MANAGER_TOOLS_MAX) {
+ // Once, because Steam walks this for every windows-only app as the library
+ // redraws and a count this wrong does not correct itself.
+ static const char once = 0;
+ if (np_log_first_hit(&once, 0))
+ NP_ERR("np_compat_registered_tool: the manager reports %u tool(s) at %p, "
+ "which is not a list this reads", count, (const void *)array);
+ return NULL;
+ }
+
+ for (uint32_t i = 0; i < count; i++) {
+ uint8_t *entry = array + (size_t)i * np_compat_tool_stride();
+ const char *name = *(const char **)(entry + COMPAT_TOOL_NAME_OFF);
+ if (name && strcmp(name, TOOL_DIR_NAME) == 0)
+ return entry;
+ }
+ return NULL;
+}
diff --git a/dylib/feats/compat.h b/dylib/feats/compat.h
new file mode 100644
index 0000000..d49b131
--- /dev/null
+++ b/dylib/feats/compat.h
@@ -0,0 +1,123 @@
+// Compatibility tool support
+#ifndef NOTPROTON_FEATS_COMPAT_H
+#define NOTPROTON_FEATS_COMPAT_H
+
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+
+// Manager tool array: base pointer at TOOL_ARRAY_OFF, count at TOOL_COUNT_OFF,
+// fixed per-entry stride from np_compat_tool_stride.
+#define COMPAT_MANAGER_TOOL_ARRAY_OFF 0x320
+#define COMPAT_MANAGER_TOOL_COUNT_OFF 0x330
+#define COMPAT_TOOL_NAME_OFF 0x40
+
+// Sanity cap: the client ships one tool on macOS, so a count above this means
+// the offset moved and the array walk would read past the end.
+#define COMPAT_MANAGER_TOOLS_MAX 32
+
+// Platform bits GetValidPlatforms reports.
+#define COMPAT_PLATFORM_WINDOWS 0x1
+#define COMPAT_PLATFORM_MACOS 0x2
+
+// Tool entry fields ahead of the insertion point. These never move.
+#define COMPAT_TOOL_GATE_FLAGS_OFF 0x24
+#define COMPAT_TOOL_GATE_HIDDEN 0x1
+#define COMPAT_TOOL_PRIORITY_OFF 0x38
+#define COMPAT_TOOL_DISPLAY_OFF 0x50
+
+// Tool entry fields at or past the insertion point. These are the baseline the
+// probed shift is measured against. Read live values through np_compat_tool_off.
+#define COMPAT_TOOL_INSTALL_OFF 0x58
+#define COMPAT_TOOL_APPID_OFF 0x60
+#define COMPAT_TOOL_PLATFORM_OFF 0x80
+
+// Reads live field offsets from the appid and install-dir gates. Returns 0 when
+// the two disagree about how far the struct shifted. The oslist gate is optional
+// and corroborates the result at the far end.
+int np_compat_probe_tool_layout(uintptr_t appid_gate, uintptr_t oslist_gate);
+
+// Reads the enabled-flag offset from BIsCompatibilityToolEnabled. Returns 0
+// when the flag cannot be located, leaving the baseline in place.
+int np_compat_probe_enabled_off(uintptr_t bis_enabled);
+uint32_t np_compat_enabled_off(void);
+
+// Live position of a field by its reference offset. Fields ahead of the
+// insertion point come back unchanged.
+uint32_t np_compat_tool_off(uint32_t reference_off);
+
+// Live stride of the manager's tool array.
+size_t np_compat_tool_stride(void);
+
+// Exports STEAM_EXTRA_COMPAT_TOOLS_PATHS. Must run before any thread but the
+// initial one exists (setenv can free the environ the client is reading).
+void np_compat_export_tools_path(void);
+
+int np_compat_ensure_tool_manifest(void);
+void np_compat_force_enable(void *compat_mgr);
+
+// Platform bitmask for an app. Reports 0 when the function was not resolved,
+// which reads as "cannot say" rather than as every platform at once.
+void np_compat_set_valid_platforms_fn(uintptr_t get_valid_platforms);
+uint32_t np_compat_valid_platforms(void *compat_mgr, uint32_t appid);
+
+// The tool an app will run under: user mapping if present, CrossOver default
+// otherwise. Goes through the same function the launch path uses.
+void np_compat_set_find_tool_fn(uintptr_t find_tool_for_target_app);
+void *np_compat_tool_for_app(void *compat_mgr, uint32_t appid);
+
+// The tool from the client's own mapping alone, without the CrossOver default.
+// The properties page needs the two apart to show absence vs. choice.
+void np_compat_set_chosen_tool_fn(uintptr_t find_tool_for_target_app);
+void *np_compat_chosen_tool(void *compat_mgr, uint32_t appid);
+
+// Whether an app gets the CrossOver default: windows-only with no macOS.
+//
+// Deliberately blind to whether a macOS build can actually run. A 32-bit macOS
+// build cannot run on a current system, but moving it onto a tool means fetching
+// the windows build in full -- a choice to be offered, not taken.
+bool np_compat_would_force(void *compat_mgr, uint32_t appid);
+
+// The wildcard (global default) mapping as it applies to one app, or NULL. Asked
+// rather than reconstructed because the client scopes it by architecture as well
+// as platform, which diverges from the default on a 32-bit macOS build.
+void np_compat_set_wildcard_fn(uintptr_t get_wildcard_mapping);
+const char *np_compat_wildcard_mapping(void *compat_mgr, uint32_t appid);
+
+// The app's own mapping entry, or NULL. A live pointer into the client's mapping
+// table (not a copy). This is what the user chose, not what the client resolved:
+// the two diverge when the named tool is not installed, which resolves to nothing
+// and is how an app is taken off tools. Refuses appid zero.
+void np_compat_set_app_mapping_fn(uintptr_t find_mapping);
+const char *np_compat_app_mapping(void *compat_mgr, uint32_t appid);
+
+// Maps an app to a tool (what the dropdown does). Empty `tool_name` clears back
+// to the client default. Appid zero sets the global default at lower priority.
+void np_compat_set_mapping_fn(uintptr_t set_compat_tool_mapping);
+void np_compat_map_tool(void *compat_mgr, uint32_t appid, const char *tool_name);
+
+// CCompatManager::YldRegisterTool, resolved at install time.
+void np_compat_set_register_fn(uintptr_t yld_register_tool);
+
+// Registers CrossOver into the given manager once. The local
+// compatibilitytools.d scan uses a different instance than the dropdown reads
+// and does not run on every launch, so this registers into the right one.
+void np_compat_register_crossover(void *compat_mgr);
+
+// The manager the properties page enumerates, or NULL before the first compat
+// query. Captured at registration, not construction (the compatibilitytools.d
+// scan builds a different instance).
+void *np_compat_manager(void);
+
+// The registered CrossOver tool entry in the manager array, or NULL.
+// Manager-owned. Callers read fields without taking ownership.
+void *np_compat_registered_tool(void *compat_mgr);
+
+// Absolute path to the local CrossOver tool directory, or NULL. Resolved once
+// and cached.
+const char *np_compat_tool_dir(void);
+
+// Command line template for the tool's toolmanifest.vdf commandline value.
+const char *np_compat_tool_commandline(void);
+
+#endif // NOTPROTON_FEATS_COMPAT_H
diff --git a/dylib/feats/compat_run.sh b/dylib/feats/compat_run.sh
new file mode 100755
index 0000000..a2b0dec
--- /dev/null
+++ b/dylib/feats/compat_run.sh
@@ -0,0 +1,717 @@
+#!/bin/sh
+# notproton CrossOver compatibility tool shim
+set -e
+
+verb="$1"
+shift || true
+
+# Options set from the Compatibility page are passed along as
+# launch options.
+launch_env=""
+argc=$#
+argi=0
+while [ "$argi" -lt "$argc" ]; do
+ arg="$1"
+ shift
+ case "$arg" in
+ CX_GRAPHICS*=*|D3DM_*=*|DXMT_*=*|DXVK_*=*|MTL_*=*|NOTPROTON_*=*|ROSETTA_*=*|WINE*=*)
+ # shellcheck disable=SC2163 # arg is a NAME=VALUE pair, which export takes as an assignment
+ export "$arg"
+ launch_env="$launch_env $arg"
+ ;;
+ *) set -- "$@" "$arg" ;;
+ esac
+ argi=$((argi+1))
+done
+
+case "$verb" in
+ getcompatpath)
+ printf '%s\n' "$STEAM_COMPAT_DATA_PATH"
+ exit 0
+ ;;
+esac
+
+CX_ROOT="$HOME/Library/Application Support/notproton/runners/current"
+export CX_ROOT
+# cxcompatdb resolves its database through CX_HOME and logs an error for
+# every module loaded without it :(
+export CX_HOME="$HOME/Library/Application Support/CrossOver"
+wine_unix="$CX_ROOT/lib/wine/aarch64-unix"
+WINELOADER="$wine_unix/wine.app/Contents/MacOS/wine"
+WINESERVER="$CX_ROOT/CrossOver-Hosted Application/wineserver-arm64"
+if [ ! -x "$WINELOADER" ] || [ ! -x "$WINESERVER" ]; then
+ wine_unix="$CX_ROOT/lib/wine/x86_64-unix"
+ WINELOADER="$wine_unix/wine"
+ WINESERVER="$CX_ROOT/CrossOver-Hosted Application/wineserver"
+ [ -x "$WINESERVER" ] || WINESERVER="$CX_ROOT/CrossOver-Hosted Application/wineserver-x86"
+fi
+export WINELOADER WINESERVER
+export WINEDLLPATH="$CX_ROOT/lib/wine/x86_64-windows:$wine_unix"
+export PATH="$CX_ROOT/bin:$PATH"
+
+if [ -n "$STEAM_COMPAT_DATA_PATH" ]; then
+ log="$STEAM_COMPAT_DATA_PATH/notproton-run.log"
+else
+ log=/dev/null
+fi
+[ "$(stat -f %z "$log" 2>/dev/null || echo 0)" -gt 262144 ] \
+ && : > "$log" || true
+{
+ echo "=== notproton run $(date) ==="
+ echo "verb=$verb"
+ echo "args:"; for a in "$@"; do echo " [$a]"; done
+ echo "cwd=$(pwd)"
+ echo "STEAM_COMPAT_DATA_PATH=$STEAM_COMPAT_DATA_PATH"
+ echo "STEAM_COMPAT_INSTALL_PATH=$STEAM_COMPAT_INSTALL_PATH"
+ echo "STEAM_COMPAT_APP_ID=$STEAM_COMPAT_APP_ID"
+ echo "-- steam env passed through --"
+ env | grep -iE '^(Steam|SDL_)' | sort
+} >> "$log" 2>&1 || true
+
+stage_step="startup"
+# shellcheck disable=SC2329 # the trap below invokes this
+report_early_exit() {
+ status=$?
+ [ "$status" = 0 ] && return 0
+ echo "=== aborted during $stage_step (exit $status) before launch ===" \
+ >> "$log" 2>&1 || true
+}
+trap report_early_exit EXIT
+
+if [ -n "$STEAM_COMPAT_APP_ID" ]; then
+ export SteamAppId="$STEAM_COMPAT_APP_ID"
+ export SteamGameId="$STEAM_COMPAT_APP_ID"
+fi
+
+prefix_machine() {
+ dll="$WINEPREFIX/drive_c/windows/system32/ntdll.dll"
+ [ -f "$dll" ] || return 1
+ off=$(od -A n -t u4 -j 60 -N 4 "$dll" 2>/dev/null | tr -d ' ')
+ case "$off" in ''|*[!0-9]*) return 1 ;; esac
+ sig=$(od -A n -t x1 -j "$off" -N 4 "$dll" 2>/dev/null | tr -d ' \n')
+ [ "$sig" = 50450000 ] || return 1
+ od -A n -t x2 -j "$((off + 4))" -N 2 "$dll" 2>/dev/null | tr -d ' \n'
+}
+
+tool_name() {
+ case "$1" in
+ aa64) printf 'the FEX build of CrossOver' ;;
+ 8664) printf 'the Rosetta build of CrossOver' ;;
+ *) printf 'an older 32-bit setup' ;;
+ esac
+}
+
+refuse_foreign_prefix() {
+ case "${wine_unix##*/}" in
+ aarch64-unix) want=aa64 ;;
+ *) want=8664 ;;
+ esac
+ have=$(prefix_machine) || return 0
+ [ "$have" = "$want" ] && return 0
+ echo "=== prefix ntdll is $have and this compatibility tool wants $want, rebuild the prefix in NotProton ===" >> "$log" 2>&1 || true
+
+ if [ "$verb" != run ]; then
+ osascript >/dev/null 2>&1 <<APPLESCRIPT || true
+display alert "This game needs its prefix rebuilt" message "This game originally ran under $(tool_name "$have"), but $(tool_name "$want") is present now. The prefix needs to be rebuilt in NotProton in order to run the game. You will not lose game saves by rebuilding the prefix." as critical
+APPLESCRIPT
+ fi
+ exit 1
+}
+# Steam cloud related
+merge_user_dir() {
+ src=$1
+ dst=$2
+ failed=
+ set -- ""
+ while [ "$#" -gt 0 ]; do
+ rest=$1
+ shift
+ src_dir="$src$rest"
+ dst_dir="$dst$rest"
+ if [ ! -r "$src_dir" ] || [ ! -x "$src_dir" ]; then failed=1; continue; fi
+ if [ -L "$dst_dir" ] && [ ! -e "$dst_dir" ]; then
+ rm -f "$dst_dir" 2>/dev/null || true
+ fi
+ probe=$dst_dir
+ through=
+ while [ -n "$probe" ] && [ "$probe" != "$dst" ]; do
+ if [ -L "$probe" ]; then through=1; break; fi
+ probe=${probe%/*}
+ done
+ if [ -n "$through" ]; then
+ echo "=== $rest is held by a link, merge refused ===" >> "$log" 2>&1 || true
+ failed=1
+ continue
+ fi
+ if [ -n "$rest" ] && [ -e "$dst_dir" ]; then continue; fi
+ if ! mkdir -p "$dst_dir" 2>/dev/null; then failed=1; continue; fi
+ for entry in "$src_dir"/* "$src_dir"/.[!.]* "$src_dir"/..?*; do
+ [ -e "$entry" ] || [ -L "$entry" ] || continue
+ name=${entry##*/}
+ if [ -d "$entry" ] && [ ! -L "$entry" ]; then
+ set -- "$@" "$rest/$name"
+ continue
+ fi
+ landing="$dst_dir/$name"
+ if [ -e "$landing" ]; then continue; fi
+ if [ -L "$landing" ]; then rm -f "$landing" 2>/dev/null || true; fi
+ if [ -L "$entry" ]; then
+ if ! cp -Pp "$entry" "$landing" 2>/dev/null; then
+ rm -f "$landing" 2>/dev/null || true
+ failed=1
+ fi
+ else
+ if ! cp -p "$entry" "$landing" 2>/dev/null; then
+ rm -f "$landing" 2>/dev/null || true
+ failed=1
+ fi
+ chmod u+w "$landing" 2>/dev/null || true
+ fi
+ done
+ done
+ [ -z "$failed" ]
+}
+
+# Steam Cloud stuff
+migrate_user_paths() {
+ profile=$1
+ for pair in \
+ "Local Settings/Application Data|AppData/Local|../AppData/Local" \
+ "Application Data|AppData/Roaming|./AppData/Roaming" \
+ "My Documents|Documents|./Documents"; do
+ old_rel=${pair%%|*}
+ rest=${pair#*|}
+ new_rel=${rest%%|*}
+ link=${rest#*|}
+ old="$profile/$old_rel"
+ new="$profile/$new_rel"
+ case "$(readlink "$new" 2>/dev/null || true)" in
+ *"drive_c/users/steamuser/$old_rel") rm -f "$new" 2>/dev/null || true ;;
+ esac
+ if [ -L "$new" ]; then
+ echo "=== $new_rel is a link, rebuild the prefix for cloud saves ===" \
+ >> "$log" 2>&1 || true
+ continue
+ fi
+ held=
+ for rel in "$old_rel" "$new_rel"; do
+ probe=$rel
+ while [ "$probe" != "${probe%/*}" ]; do
+ probe=${probe%/*}
+ if [ -L "$profile/$probe" ]; then held=$probe; break; fi
+ done
+ if [ -n "$held" ]; then break; fi
+ done
+ if [ -n "$held" ]; then
+ echo "=== $held is a link, rebuild the prefix for cloud saves ===" \
+ >> "$log" 2>&1 || true
+ continue
+ fi
+ if [ -e "$old" ] && [ ! -L "$old" ]; then
+ if ! merge_user_dir "$old" "$new"; then
+ echo "=== $old_rel did not merge into $new_rel, left in place ===" \
+ >> "$log" 2>&1 || true
+ continue
+ fi
+ rmdir "$old BACKUP" 2>/dev/null || true
+ if [ -e "$old BACKUP" ] || [ -L "$old BACKUP" ] \
+ || ! mv "$old" "$old BACKUP" 2>> "$log"; then
+ echo "=== $old_rel could not be moved aside, cloud saves stay split ===" \
+ >> "$log" 2>&1 || true
+ continue
+ fi
+ fi
+ if [ ! -e "$old" ] && [ ! -L "$old" ]; then
+ mkdir -p "${old%/*}" 2>/dev/null || true
+ ln -s "$link" "$old" 2>/dev/null \
+ || echo "=== $old_rel could not be aliased onto $new_rel ===" >> "$log" 2>&1 \
+ || true
+ elif [ -L "$old" ] && [ "$(readlink "$old")" != "$link" ]; then
+ rm -f "$old" 2>/dev/null || true
+ ln -s "$link" "$old" 2>/dev/null \
+ || echo "=== $old_rel could not be aliased onto $new_rel ===" >> "$log" 2>&1 \
+ || true
+ fi
+ done
+}
+
+lay_out_proton_profile() {
+ users="$WINEPREFIX/drive_c/users"
+ if [ -d "$users/crossover" ] && [ ! -L "$users/crossover" ]; then
+ echo "=== prefix predates the steamuser layout, rebuild it for cloud saves ===" \
+ >> "$log" 2>&1 || true
+ return 0
+ fi
+ profile="$users/steamuser"
+ if [ -L "$profile" ]; then
+ echo "=== the profile is a link, rebuild the prefix for cloud saves ===" \
+ >> "$log" 2>&1 || true
+ return 0
+ fi
+ mkdir -p "$profile" 2>/dev/null || return 0
+ for folder in Documents Desktop Downloads Music Pictures Videos Templates \
+ AppData/Local AppData/Roaming; do
+ mkdir -p "$profile/$folder" 2>/dev/null || true
+ done
+ migrate_user_paths "$profile"
+ if [ -L "$users/crossover" ] && [ ! -e "$users/crossover" ]; then
+ rm -f "$users/crossover" 2>/dev/null || true
+ fi
+ if [ ! -e "$users/crossover" ] \
+ && ln -s steamuser "$users/crossover" 2>/dev/null; then
+ echo "=== pointed crossover at steamuser ===" >> "$log" 2>&1 || true
+ fi
+}
+
+if [ -n "$STEAM_COMPAT_DATA_PATH" ]; then
+ export WINEPREFIX="$STEAM_COMPAT_DATA_PATH/pfx"
+ mkdir -p "$WINEPREFIX"
+ msync_from=launch-options
+ if [ -z "$WINEMSYNC" ] && [ -r "$STEAM_COMPAT_DATA_PATH/notproton-msync" ]; then
+ WINEMSYNC=$(tr -d ' \t\n' \
+ < "$STEAM_COMPAT_DATA_PATH/notproton-msync" 2>/dev/null || true)
+ msync_from=carried-over
+ fi
+ [ -n "$WINEMSYNC" ] || msync_from=default
+ export WINEMSYNC="${WINEMSYNC:-0}"
+ printf '%s' "$WINEMSYNC" \
+ > "$STEAM_COMPAT_DATA_PATH/notproton-msync" 2>/dev/null || true
+ stage_step="prefix arch check"
+ refuse_foreign_prefix
+ echo "sync: WINEMSYNC=$WINEMSYNC from $msync_from" >> "$log" 2>&1 || true
+ "$WINESERVER" -k >> "$log" 2>&1 || true
+ stage_step="profile layout"
+ lay_out_proton_profile
+ "$WINELOADER" wineboot --init >> "$log" 2>&1 || true
+ "$WINELOADER" reg add 'HKLM\Software\Microsoft\Windows NT\CurrentVersion\AeDebug' /v Auto /t REG_SZ /d 0 /f >> "$log" 2>&1 || true
+ "$WINELOADER" reg add 'HKLM\Software\Wow6432Node\Microsoft\Windows NT\CurrentVersion\AeDebug' /v Auto /t REG_SZ /d 0 /f >> "$log" 2>&1 || true
+ "$WINELOADER" reg add 'HKCU\Software\Wine\WineDbg' /v ShowCrashDialog /t REG_DWORD /d 0 /f >> "$log" 2>&1 || true
+
+ echo "video: RetinaMode=${NOTPROTON_RETINA:-0}" >> "$log" 2>&1 || true
+ if [ "$NOTPROTON_RETINA" = "1" ]; then
+ "$WINELOADER" reg add 'HKCU\Software\Wine\Mac Driver' /v RetinaMode /t REG_SZ /d y /f >> "$log" 2>&1 || true
+ else
+ "$WINELOADER" reg delete 'HKCU\Software\Wine\Mac Driver' /v RetinaMode /f >> "$log" 2>&1 || true
+ fi
+
+ "$WINELOADER" reg add 'HKLM\Software\Classes\steam' /v 'URL Protocol' /t REG_SZ /d '' /f >> "$log" 2>&1 || true
+ "$WINELOADER" reg add 'HKLM\Software\Classes\steam\shell\open\command' /ve /t REG_SZ /d '"C:\Program Files (x86)\Steam\steam.exe" "%1"' /f >> "$log" 2>&1 || true
+fi
+
+bridge_src="$HOME/Library/Application Support/notproton/bridge"
+prefix_steam="$WINEPREFIX/drive_c/Program Files (x86)/Steam"
+verify_runner() {
+ if [ ! -d "$bridge_src/wine" ]; then
+ echo "=== no patched ntdll in the bridge, run NotProton ===" >> "$log" 2>&1 || true
+ return
+ fi
+ for arch in x86_64-windows i386-windows aarch64-windows; do
+ staged="$bridge_src/wine/$arch/ntdll.dll"
+ live="$CX_ROOT/lib/wine/$arch/ntdll.dll"
+ [ -f "$staged" ] || continue
+ if [ ! -f "$live" ]; then
+ echo "=== runner has no $arch ntdll, set up the runner in NotProton ===" >> "$log" 2>&1 || true
+ elif ! cmp -s "$staged" "$live"; then
+ echo "=== runner $arch ntdll is not the patched copy, set up the runner in NotProton ===" >> "$log" 2>&1 || true
+ fi
+ done
+ for arch in i386-windows x86_64-windows "${wine_unix##*/}"; do
+ case "$arch" in
+ *-unix) name="lsteamclient.so" ;;
+ *) name="lsteamclient.dll" ;;
+ esac
+ [ -f "$CX_ROOT/lib/wine/$arch/$name" ] && continue
+ echo "=== runner is missing $arch/$name, set up the runner in NotProton ===" >> "$log" 2>&1 || true
+ done
+}
+install_lsteamclient_trigger() {
+ src="$bridge_src/i386-windows/lsteamclient.dll"
+ dst="$WINEPREFIX/drive_c/windows/syswow64/lsteamclient.dll"
+ [ -f "$src" ] && [ -d "$WINEPREFIX/drive_c/windows/syswow64" ] || return 0
+ cmp -s "$src" "$dst" && return 0
+ if cp -f "$src" "$dst"; then
+ echo "=== installed syswow64 lsteamclient trigger ===" >> "$log" 2>&1 || true
+ else
+ echo "=== could not install the syswow64 lsteamclient trigger ===" >> "$log" 2>&1 || true
+ fi
+}
+
+# Steam runs a Windows game's installscript.vdf by invoking the standalone
+# evaluator through the compat tool, the same way the linux client does, but
+# the binaries are missing on macOS, so...
+install_legacycompat() {
+ src="$bridge_src/legacycompat"
+ dst="$STEAM_COMPAT_CLIENT_INSTALL_PATH/legacycompat"
+ [ -d "$src" ] && [ -n "$STEAM_COMPAT_CLIENT_INSTALL_PATH" ] || return 0
+ mkdir -p "$dst" || return 0
+ for f in "$src"/*; do
+ [ -f "$f" ] || continue
+ b=$(basename "$f")
+ cmp -s "$f" "$dst/$b" && continue
+ cp -f "$f" "$dst/$b" && \
+ echo "=== installed legacycompat/$b ===" >> "$log" 2>&1
+ done
+}
+
+link_legacy_steam_dll() {
+ src="$STEAM_COMPAT_CLIENT_INSTALL_PATH/legacycompat/Steam.dll"
+ [ -n "$STEAM_COMPAT_INSTALL_PATH" ] && [ -f "$src" ] || return 0
+ dst="$(dirname "$STEAM_COMPAT_INSTALL_PATH")/Steam.dll"
+ [ -L "$dst" ] || [ ! -e "$dst" ] || return 0
+ [ "$(readlink "$dst" 2>/dev/null)" = "$src" ] && return 0
+ ln -sfn "$src" "$dst" && \
+ echo "=== linked legacy Steam.dll ===" >> "$log" 2>&1
+}
+
+bridge_files="steamclient64.dll steamclient.dll tier0_s64.dll vstdlib_s64.dll"
+bridge_files="$bridge_files lsteamclient.dll lsteamclient.so steam.exe"
+if [ -d "$bridge_src" ] && [ -n "$WINEPREFIX" ]; then
+ stage_step="bridge staging"
+ mkdir -p "$prefix_steam"
+ for f in $bridge_files; do
+ src="$bridge_src/$f"
+ if [ "$f" = lsteamclient.so ]; then
+ src="$bridge_src/${wine_unix##*/}/$f"
+ fi
+ if [ ! -f "$src" ]; then
+ echo "=== bridge missing $f ===" >> "$log" 2>&1 || true
+ continue
+ fi
+ cp -f "$src" "$prefix_steam/$f" || \
+ echo "=== failed to stage $f ===" >> "$log" 2>&1
+ done
+ for f in "$prefix_steam"/*.dll "$prefix_steam"/*.so "$prefix_steam"/*.exe; do
+ [ -f "$f" ] || continue
+ case " $bridge_files " in
+ *" $(basename "$f") "*) ;;
+ *) rm -f "$f" && echo "=== pruned stale $(basename "$f") ===" >> "$log" 2>&1 ;;
+ esac
+ done
+ verify_runner
+ install_lsteamclient_trigger
+ export WINEDLLPATH="$prefix_steam:$WINEDLLPATH"
+ export WINEDLLOVERRIDES="steamclient=n;steamclient64=n;lsteamclient=b"
+ native_client="$STEAM_COMPAT_CLIENT_INSTALL_PATH"
+ if [ -z "$native_client" ]; then
+ native_client="$HOME/Library/Application Support/Steam/Steam.AppBundle/Steam/Contents/MacOS"
+ export STEAM_COMPAT_CLIENT_INSTALL_PATH="$native_client"
+ fi
+ install_legacycompat
+ link_legacy_steam_dll
+ echo "=== bridge staged into $prefix_steam ===" >> "$log" 2>&1 || true
+ echo "WINEDLLPATH=$WINEDLLPATH" >> "$log" 2>&1 || true
+ echo "STEAM_COMPAT_CLIENT_INSTALL_PATH=$STEAM_COMPAT_CLIENT_INSTALL_PATH" >> "$log" 2>&1 || true
+fi
+
+export WINEDEBUG="${WINEDEBUG:-err+all,fixme-all}"
+trap - EXIT
+echo "launch_env=$launch_env" >> "$log" 2>&1 || true
+echo "=== launching ($verb): $WINELOADER $* ===" >> "$log" 2>&1 || true
+
+target="$1"
+case "$target" in
+ "$STEAM_COMPAT_INSTALL_PATH"/*) foreground=1 ;;
+ *) foreground=0 ;;
+esac
+
+if [ "$foreground" = 0 ]; then
+ echo "=== running helper on raw loader: $* ===" >> "$log" 2>&1 || true
+ "$WINELOADER" "$@" >> "$log" 2>&1
+ status=$?
+ echo "=== helper exited status=$status ===" >> "$log" 2>&1 || true
+ exit $status
+fi
+
+# Fixes CrossOver window focus issues
+steam_root="$(dirname "$(dirname "$(dirname "$STEAM_COMPAT_DATA_PATH")")")"
+manifest="$steam_root/steamapps/appmanifest_$STEAM_COMPAT_APP_ID.acf"
+client_root="$STEAM_COMPAT_CLIENT_INSTALL_PATH"
+while [ -n "$client_root" ] && [ "$client_root" != "/" ] && [ ! -d "$client_root/appcache" ]; do
+ client_root=$(dirname "$client_root")
+done
+# Icon stuff
+appinfo_tool="$HOME/Library/Application Support/notproton/appinfo"
+appinfo_vdf="$client_root/appcache/appinfo.vdf"
+meta_name=""
+meta_icon=""
+meta_clienticon=""
+if [ -x "$appinfo_tool" ] && [ -f "$appinfo_vdf" ]; then
+ meta=$("$appinfo_tool" "$appinfo_vdf" "$STEAM_COMPAT_APP_ID" 2>> "$log") || meta=""
+ meta_name=$(printf '%s\n' "$meta" | sed -n 's/^name=//p')
+ meta_icon=$(printf '%s\n' "$meta" | sed -n 's/^icon=//p')
+ meta_clienticon=$(printf '%s\n' "$meta" | sed -n 's/^clienticon=//p')
+fi
+game_name="$meta_name"
+if [ -z "$game_name" ] && [ -f "$manifest" ]; then
+ game_name=$(sed -n 's/.*"name"[[:space:]]*"\(.*\)".*/\1/p' "$manifest" | head -1)
+fi
+[ -z "$game_name" ] && game_name=$(basename "$STEAM_COMPAT_INSTALL_PATH")
+[ -z "$game_name" ] && game_name="Steam Game"
+# shellcheck disable=SC1003 # the pair deletes a literal backslash, not a quote
+bundle_name=$(printf '%s' "$game_name" | tr -d '/:"`$\\')
+game_name_xml=$(printf '%s' "$game_name" | sed -e 's/&/\&amp;/g' -e 's/</\&lt;/g' -e 's/>/\&gt;/g')
+loader_root="$HOME/Library/Application Support/notproton/launchers/$STEAM_COMPAT_APP_ID"
+mkdir -p "$loader_root"
+loader_app="$loader_root/$bundle_name.app"
+rm -rf "$loader_root"/*.app
+loader_contents="$loader_app/Contents"
+loader_macos="$loader_contents/MacOS"
+loader_res="$loader_contents/Resources"
+mkdir -p "$loader_macos" "$loader_res"
+
+icon_arg=""
+resolve_icon() {
+ set +e
+ iconmaker="$HOME/Library/Application Support/notproton/iconmaker"
+ art_dir="$client_root/appcache/librarycache/$STEAM_COMPAT_APP_ID"
+ art=""
+ if [ -n "$meta_clienticon" ]; then
+ ico="$loader_root/clienticon-$meta_clienticon.ico"
+ absent="$loader_root/clienticon-$meta_clienticon.absent"
+ find "$loader_root" -maxdepth 1 -name 'clienticon-*' ! -name "clienticon-$meta_clienticon.*" -delete 2>/dev/null || true
+ find "$absent" -mtime +14 -delete 2>/dev/null || true
+ if [ ! -s "$ico" ] && [ ! -f "$absent" ]; then
+ url="https://shared.fastly.steamstatic.com/community_assets/images/apps/$STEAM_COMPAT_APP_ID/$meta_clienticon.ico"
+ code=$(curl -fsL --connect-timeout 5 --max-time 20 -w '%{http_code}' -o "$ico.new" "$url" 2>>"$log")
+ magic=$(od -An -tx1 -N4 "$ico.new" 2>/dev/null | tr -d ' \n')
+ if [ "$magic" = "00000100" ]; then
+ mv -f "$ico.new" "$ico"
+ echo "fetched client icon $meta_clienticon" >> "$log" 2>&1 || true
+ else
+ rm -f "$ico.new"
+ if [ "$code" = "404" ]; then
+ : > "$absent"
+ echo "no client icon published for $meta_clienticon" >> "$log" 2>&1 || true
+ else
+ echo "client icon fetch for $meta_clienticon failed (http ${code:-none}), will retry" >> "$log" 2>&1 || true
+ fi
+ fi
+ fi
+ [ -s "$ico" ] && art="$ico"
+ fi
+ if [ -z "$art" ] && [ -n "$meta_icon" ] && [ -f "$art_dir/$meta_icon.jpg" ]; then
+ art="$art_dir/$meta_icon.jpg"
+ fi
+ if [ -z "$art" ]; then
+ art=$(find "$art_dir" -maxdepth 1 -type f -name '*.jpg' 2>/dev/null | grep -E '/[0-9a-f]{40}\.jpg$' | head -1)
+ fi
+ # Capsule art (horrible) fallback if no icon at all exists...
+ if [ -z "$art" ]; then
+ for name in library_600x900.jpg header.jpg; do
+ found=$(find "$art_dir" -name "$name" 2>/dev/null | head -1)
+ [ -n "$found" ] && { art="$found"; break; }
+ done
+ fi
+ icon_source=""
+ if [ -n "$art" ]; then
+ icon_source="$art $(stat -f %m "$art" 2>/dev/null || echo 0)"
+ fi
+ icon_cache="$loader_root/game.icns"
+ if [ -n "$art" ] && [ -s "$icon_cache" ] && [ "$(cat "$loader_root/notproton-icon.source" 2>/dev/null)" = "$icon_source" ] && cp -f "$icon_cache" "$loader_res/game.icns"; then
+ icon_arg=" <key>CFBundleIconFile</key><string>game</string>"
+ echo "icon reused from $art" >> "$log" 2>&1 || true
+ elif [ -n "$art" ] && [ -x "$iconmaker" ]; then
+ if "$iconmaker" "$art" "$icon_cache" >> "$log" 2>&1 && cp -f "$icon_cache" "$loader_res/game.icns"; then
+ icon_arg=" <key>CFBundleIconFile</key><string>game</string>"
+ printf '%s\n' "$icon_source" > "$loader_root/notproton-icon.source"
+ echo "icon built from $art" >> "$log" 2>&1 || true
+ elif [ "$art" = "$ico" ]; then
+ # A cached .ico that iconmaker rejects is corrupt and passes the size
+ # guard on every launch, so drop it to force a clean fetch next time.
+ rm -f "$ico"
+ echo "discarded unreadable client icon $meta_clienticon" >> "$log" 2>&1 || true
+ fi
+ fi
+ set -e
+ return 0
+}
+resolve_icon || true
+[ -n "$icon_arg" ] || echo "no icon resolved, launching without one" >> "$log" 2>&1 || true
+
+uielement_arg=""
+if [ "${NOTPROTON_HIDE_LAUNCHER_TILE:-0}" = "1" ]; then
+ uielement_arg=" <key>LSUIElement</key><true/>"
+ echo "launcher tile hidden by NOTPROTON_HIDE_LAUNCHER_TILE" >> "$log" 2>&1 || true
+fi
+cat > "$loader_contents/Info.plist" <<PLIST
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleName</key><string>$game_name_xml</string>
+ <key>CFBundleDisplayName</key><string>$game_name_xml</string>
+ <key>CFBundleIdentifier</key><string>com.notproton.launcher.$STEAM_COMPAT_APP_ID</string>
+ <key>CFBundleExecutable</key><string>launcher</string>
+ <key>CFBundlePackageType</key><string>APPL</string>
+ <key>CFBundleInfoDictionaryVersion</key><string>6.0</string>
+ <key>LSApplicationCategoryType</key><string>public.app-category.games</string>
+ <key>NSHighResolutionCapable</key><true/>
+ <key>NSPrincipalClass</key><string>NSApplication</string>
+$uielement_arg
+$icon_arg
+</dict>
+</plist>
+PLIST
+
+# Invokes macOS Game Mode
+for f in "$wine_unix"/*; do
+ [ -e "$f" ] || continue
+ base=${f##*/}
+ case "$base" in
+ wine|wine.app) continue ;;
+ esac
+ ln -sfn "$f" "$loader_macos/$base"
+done
+ln "$WINELOADER" "$loader_macos/wine" 2>/dev/null || cp "$WINELOADER" "$loader_macos/wine"
+if [ -x "$loader_macos/wine" ]; then
+ WINELOADER="$loader_macos/wine"
+ echo "loader staged in bundle for game mode" >> "$log" 2>&1 || true
+else
+ echo "loader staging failed, game mode unavailable" >> "$log" 2>&1 || true
+fi
+
+cat > "$loader_macos/launcher" <<LAUNCHER
+#!/bin/sh
+export WINELOADER="$WINELOADER"
+wine_log="$loader_root/notproton-wine.log"
+exec > "\$wine_log" 2>&1
+shim="$HOME/Library/Application Support/notproton/overlay-shim.dylib"
+if [ -n "\$STEAM_DYLD_INSERT_LIBRARIES" ]; then
+ if [ -f "\$shim" ]; then
+ export DYLD_INSERT_LIBRARIES="\$shim:\$STEAM_DYLD_INSERT_LIBRARIES"
+ export NOTPROTON_OVERLAY_SHIM="\$shim"
+ else
+ export DYLD_INSERT_LIBRARIES="\$STEAM_DYLD_INSERT_LIBRARIES"
+ fi
+fi
+[ -n "\$NOTPROTON_GAME_CWD" ] && cd "\$NOTPROTON_GAME_CWD"
+"$WINELOADER" "\$@"
+exit \$?
+LAUNCHER
+chmod +x "$loader_macos/launcher"
+
+wine_helpers='winedevice\.exe|services\.exe|plugplay\.exe|svchost\.exe'
+wine_helpers="$wine_helpers|rpcss\.exe|explorer\.exe|steam\.exe"
+wine_helpers="$wine_helpers|winemenubuilder\.exe|conhost\.exe|start\.exe"
+wine_helpers="$wine_helpers|wineboot\.exe|rundll32\.exe|tabtip\.exe"
+wine_helpers="$wine_helpers|vc_redist|vcredist|dxsetup\.exe|msiexec\.exe"
+wine_helpers="$wine_helpers|installinf|iscriptevaluator\.exe|regsvr32\.exe"
+wine_helpers="$wine_helpers|winedbg\.exe|unitycrashhandler"
+prefix_server_dir() {
+ [ -n "$WINEPREFIX" ] || return 1
+ ids=$(stat -f '%d-%i' "$WINEPREFIX" 2>/dev/null) || return 1
+ [ -n "$ids" ] || return 1
+ printf '/tmp/.wine-%s/server-%s' "$(id -u)" \
+ "$(printf '%s' "$ids" | awk -F- '{printf "%x-%x", $1, $2}')"
+}
+
+prefix_game_running() {
+ command -v lsof >/dev/null 2>&1 || return 1
+ dir=$(prefix_server_dir) || return 1
+ [ -d "$dir" ] || return 1
+ pids=$(lsof -t +D "$dir" 2>/dev/null | sort -u | tr '\n' ',')
+ pids=${pids%,}
+ [ -n "$pids" ] || return 1
+ # shellcheck disable=SC1003 # the pair matches the backslash in a drive path
+ ps -p "$pids" -o args= 2>/dev/null | grep -E '^[A-Za-z]:\\' | grep -viE "$wine_helpers" | grep -q .
+}
+
+wait_prefix_idle() {
+ idle=0
+ tick=0
+ while [ "$idle" -lt 10 ] && [ "$tick" -lt 300 ]; do
+ tick=$((tick + 1))
+ if prefix_game_running; then idle=0; else idle=$((idle + 1)); fi
+ sleep 1
+ done
+ echo "wait_prefix_idle done after tick=$tick idle=$idle" >> "$log" 2>&1 || true
+}
+
+kill_wine_prefix() {
+ "$WINESERVER" -k >> "$log" 2>&1 || true
+ "$WINESERVER" -w >> "$log" 2>&1 || true
+ if command -v lsof >/dev/null 2>&1 && server_dir=$(prefix_server_dir); then
+ if [ -d "$server_dir" ]; then
+ survivors=$(lsof -t +D "$server_dir" 2>/dev/null | sort -u)
+ if [ -n "$survivors" ]; then
+ echo "=== sweeping prefix stragglers: $survivors ===" >> "$log" 2>&1 || true
+ # shellcheck disable=SC2086 # survivors is a list of pids and has to split
+ kill -9 $survivors 2>/dev/null || true
+ fi
+ fi
+ fi
+}
+
+# Steam's "Exit Game" and the client shutting the game down both send a
+# termination signal to this run script, this handles it
+# shellcheck disable=SC2329 # the trap below invokes this
+terminate() {
+ echo "=== termination signal received, killing wine prefix ===" >> "$log" 2>&1 || true
+ kill_wine_prefix
+ [ -n "$open_pid" ] && kill "$open_pid" 2>/dev/null || true
+}
+trap terminate TERM INT HUP
+
+shim_exe="C:\\Program Files (x86)\\Steam\\steam.exe"
+
+game_cwd="$(pwd)"
+if [ -n "$STEAM_DYLD_INSERT_LIBRARIES" ]; then
+ echo "=== overlay injected from $STEAM_DYLD_INSERT_LIBRARIES ===" >> "$log" 2>&1 || true
+else
+ echo "=== client staged no overlay renderer, overlay disabled ===" >> "$log" 2>&1 || true
+fi
+set -- --args "$shim_exe" "$@"
+for name in $(env | sed -nE 's/^(Steam[A-Za-z0-9]*|(CX_GRAPHICS|D3DM_|DXMT_|DXVK_|MTL_|ROSETTA_)[A-Z0-9_]*)=.*/\1/p'); do
+ eval "value=\$$name"
+ # shellcheck disable=SC2154 # eval assigns value on the line above
+ set -- --env "$name=$value" "$@"
+done
+set -- \
+ --env CX_ROOT="$CX_ROOT" \
+ --env CX_HOME="$CX_HOME" \
+ --env WINESERVER="$WINESERVER" \
+ --env WINEDLLPATH="$WINEDLLPATH" \
+ --env WINEDLLOVERRIDES="$WINEDLLOVERRIDES" \
+ --env WINEMSYNC="$WINEMSYNC" \
+ --env WINEPREFIX="$WINEPREFIX" \
+ --env WINEDEBUG="$WINEDEBUG" \
+ --env PATH="$PATH" \
+ --env STEAM_COMPAT_DATA_PATH="$STEAM_COMPAT_DATA_PATH" \
+ --env STEAM_COMPAT_INSTALL_PATH="$STEAM_COMPAT_INSTALL_PATH" \
+ --env STEAM_COMPAT_CLIENT_INSTALL_PATH="$STEAM_COMPAT_CLIENT_INSTALL_PATH" \
+ --env STEAM_COMPAT_APP_ID="$STEAM_COMPAT_APP_ID" \
+ --env STEAM_DYLD_INSERT_LIBRARIES="$STEAM_DYLD_INSERT_LIBRARIES" \
+ --env NOTPROTON_GAME_CWD="$game_cwd" "$@"
+lsregister="/System/Library/Frameworks/CoreServices.framework/Versions/A"
+lsregister="$lsregister/Frameworks/LaunchServices.framework/Support/lsregister"
+[ -x "$lsregister" ] && "$lsregister" -f "$loader_app" >> "$log" 2>&1 || true
+open -n -W -a "$loader_app" "$@" >> "$log" 2>&1 &
+open_pid=$!
+status=0
+seen=0
+idle=0
+while :; do
+ if prefix_game_running; then
+ seen=1
+ idle=0
+ else
+ idle=$((idle + 1))
+ fi
+ if ! kill -0 "$open_pid" 2>/dev/null; then
+ wait "$open_pid" || status=$?
+ echo "=== bundle exited status=$status ===" >> "$log" 2>&1 || true
+ if [ "$status" -le 128 ]; then
+ wait_prefix_idle
+ fi
+ break
+ fi
+ if [ "$seen" -eq 1 ] && [ "$idle" -ge 10 ]; then
+ echo "=== game tree gone, ending session ===" >> "$log" 2>&1 || true
+ break
+ fi
+ sleep 1
+done
+echo "=== game exited status=$status, killing wine prefix ===" >> "$log" 2>&1 || true
+kill_wine_prefix
+echo "=== wine prefix killed, session ending ===" >> "$log" 2>&1 || true
+exit $status
diff --git a/dylib/feats/compatsvc.c b/dylib/feats/compatsvc.c
new file mode 100644
index 0000000..954ba18
--- /dev/null
+++ b/dylib/feats/compatsvc.c
@@ -0,0 +1,338 @@
+// CompatManager WebUI service.
+#include <string.h>
+
+#include "compatsvc.h"
+#include "compat.h"
+#include "webui.h"
+#include "../resolver/anchor.h"
+#include "../util/log.h"
+
+// Route names carry the interface version the page asks for.
+#define ROUTE_GET_COMPAT_TOOLS "CompatManager.GetCompatTools#1"
+#define ROUTE_SPECIFY_COMPAT_TOOL "CompatManager.SpecifyCompatTool#1"
+#define ROUTE_NOTIFY_STATE_CHANGED "CompatManager.NotifyStateChanged#1"
+
+// Mangled RTTI names of the message types. A client that builds the CompatManager
+// page compiles these without registering the service, so the vtables are there to
+// be found. A client whose page specifies the tool directly carries none of them.
+#define TYPE_GET_REQUEST "37CCompatManager_GetCompatTools_Request"
+#define TYPE_GET_RESPONSE "38CCompatManager_GetCompatTools_Response"
+#define TYPE_SPECIFY_REQUEST "40CCompatManager_SpecifyCompatTool_Request"
+#define TYPE_SPECIFY_RESPONSE "41CCompatManager_SpecifyCompatTool_Response"
+#define TYPE_STATE_CHANGED "40CCompatManager_StateChanged_Notification"
+
+// CCompatManager_GetCompatTools_Request.
+#define REQ_HAS_BITS_OFF 16
+#define REQ_APPID_OFF 24
+#define REQ_HAS_APPID 1
+
+// CCompatManager_SpecifyCompatTool_Request. An unset name field points at the
+// shared empty string, which clears the mapping back to its default.
+#define SPECIFY_TOOL_NAME_OFF 24
+#define SPECIFY_APPID_OFF 32
+#define SPECIFY_HAS_APPID 2
+
+// Result the page reads as success, and the one it reads as failure.
+#define RESULT_OK 1
+#define RESULT_FAIL 2
+
+// Field numbers of the two messages, from the interface the page is built against.
+#define TOOL_NAME 1
+#define TOOL_DISPLAY_NAME 2
+#define TOOL_IS_DEFAULT 3
+#define TOOL_IS_ACTIVE 4
+#define TOOL_IS_LEGACY 5
+#define TOOL_IS_INCOMPATIBLE 6
+
+#define RESP_TOOLS 1
+#define RESP_SELECTED 3
+#define RESP_DEFAULT 4
+
+// Wire types this writes.
+#define WIRE_VARINT 0
+#define WIRE_BYTES 2
+
+// Per-tool and per-reply size caps, for safety.
+#define TOOL_MAX 512
+#define BODY_MAX (TOOL_MAX * 8)
+
+// No appid equals the global Steam Play setting, answered with windows.
+#define PLATFORMS_UNSCOPED COMPAT_PLATFORM_WINDOWS
+
+// A tool's own appid gets this result instead of a list.
+#define RESULT_IS_A_TOOL 128
+
+// Display label for the "no tool" entry.
+#define TOOL_NONE_LABEL "No Compatibility Tool"
+
+// Protobuf writer.
+typedef struct {
+ uint8_t *buf;
+ size_t cap;
+ size_t len;
+ int ok;
+} np_pb_t;
+
+static void pb_byte(np_pb_t *w, uint8_t b) {
+ if (w->len >= w->cap) { w->ok = 0; return; }
+ w->buf[w->len++] = b;
+}
+
+static void pb_varint(np_pb_t *w, uint64_t v) {
+ do {
+ uint8_t b = (uint8_t)(v & 0x7f);
+ v >>= 7;
+ pb_byte(w, v ? (uint8_t)(b | 0x80) : b);
+ } while (v && w->ok);
+}
+
+static void pb_tag(np_pb_t *w, uint32_t field, uint32_t wire) {
+ pb_varint(w, ((uint64_t)field << 3) | wire);
+}
+
+static void pb_blob(np_pb_t *w, uint32_t field, const uint8_t *bytes, size_t len) {
+ pb_tag(w, field, WIRE_BYTES);
+ pb_varint(w, len);
+ for (size_t i = 0; i < len && w->ok; i++)
+ pb_byte(w, bytes[i]);
+}
+
+static void pb_string(np_pb_t *w, uint32_t field, const char *str) {
+ if (!str) return;
+ pb_blob(w, field, (const uint8_t *)str, strlen(str));
+}
+
+static void pb_bool(np_pb_t *w, uint32_t field, int set) {
+ pb_tag(w, field, WIRE_VARINT);
+ pb_varint(w, set ? 1 : 0);
+}
+
+static void pb_tool(np_pb_t *w, uint32_t resp_field,
+ const char *name, const char *display,
+ int is_active, int is_incompatible) {
+ uint8_t item[TOOL_MAX];
+ np_pb_t t = { item, sizeof item, 0, 1 };
+ pb_string(&t, TOOL_NAME, name);
+ pb_string(&t, TOOL_DISPLAY_NAME, display);
+ pb_bool(&t, TOOL_IS_DEFAULT, 0);
+ pb_bool(&t, TOOL_IS_ACTIVE, is_active);
+ pb_bool(&t, TOOL_IS_LEGACY, 0);
+ pb_bool(&t, TOOL_IS_INCOMPATIBLE, is_incompatible);
+ if (t.ok)
+ pb_blob(w, resp_field, item, t.len);
+ else
+ w->ok = 0;
+}
+
+static int offered(const uint8_t *tool, uint32_t platforms, int bypass) {
+ uint32_t converts_from =
+ *(const uint32_t *)(tool + np_compat_tool_off(COMPAT_TOOL_PLATFORM_OFF));
+ uint32_t gate = *(const uint32_t *)(tool + COMPAT_TOOL_GATE_FLAGS_OFF);
+
+ if (!(platforms & converts_from)) return 0;
+ if ((gate & COMPAT_TOOL_GATE_HIDDEN) && !bypass) return 0;
+ return 1;
+}
+
+static const char *tool_name(const void *tool) {
+ if (!tool) return NULL;
+ return *(const char *const *)((const uint8_t *)tool + COMPAT_TOOL_NAME_OFF);
+}
+
+static int get_compat_tools(uintptr_t request, uintptr_t response) {
+ uint32_t has_bits = *(const uint32_t *)(request + REQ_HAS_BITS_OFF);
+ uint32_t appid = (has_bits & REQ_HAS_APPID)
+ ? *(const uint32_t *)(request + REQ_APPID_OFF) : 0;
+
+ uint8_t *mgr = (uint8_t *)np_compat_manager();
+ if (!mgr) {
+ // An empty list is a valid answer, and the page renders it as no dropdown
+ // rather than as an error.
+ NP_WARN("compatsvc: app %u asked for tools before any manager was seen, so "
+ "the page gets an empty list", appid);
+ return RESULT_OK;
+ }
+
+ const uint8_t *array = *(const uint8_t **)(mgr + COMPAT_MANAGER_TOOL_ARRAY_OFF);
+ uint32_t count = *(const uint32_t *)(mgr + COMPAT_MANAGER_TOOL_COUNT_OFF);
+ if (!array || count > COMPAT_MANAGER_TOOLS_MAX) {
+ NP_ERR("compatsvc: the manager reports %u tool(s) at %p, which is not a list "
+ "this reads", count, (const void *)array);
+ return RESULT_FAIL;
+ }
+
+ int bypass = mgr[np_compat_enabled_off() + 2] != 0;
+ if (appid && !bypass) {
+ for (uint32_t i = 0; i < count; i++) {
+ const uint8_t *tool = array + (size_t)i * np_compat_tool_stride();
+ if (*(const uint32_t *)(tool + np_compat_tool_off(COMPAT_TOOL_APPID_OFF)) != appid)
+ continue;
+ NP_LOG("compatsvc: app %u is itself a compatibility tool, so it is "
+ "offered none", appid);
+ return RESULT_IS_A_TOOL;
+ }
+ }
+
+ uint32_t platforms = appid ? np_compat_valid_platforms(mgr, appid)
+ : PLATFORMS_UNSCOPED;
+ // The resolved tool and the raw mapping.
+ const char *active = tool_name(np_compat_tool_for_app(mgr, appid));
+ // Raw mapping, including names that resolve to no installed tool.
+ const char *chosen = appid ? np_compat_app_mapping(mgr, appid)
+ : tool_name(np_compat_chosen_tool(mgr, 0));
+ const bool holds_none = chosen && strcmp(chosen, NP_COMPAT_TOOL_NONE) == 0;
+ // The fallback tool for when no choice is made. The wildcard covers apps the
+ // client will not run natively (Windows stuff). Left unset where nothing carries the app,
+ // so the "Default" entry shows no name.
+ const char *fallback = np_compat_wildcard_mapping(mgr, appid);
+ if (!fallback && (appid == 0 || np_compat_would_force(mgr, appid)))
+ fallback = tool_name(np_compat_registered_tool(mgr));
+
+ int32_t best = 0;
+ for (uint32_t i = 0; i < count; i++) {
+ int32_t prio = *(const int32_t *)(array + (size_t)i * np_compat_tool_stride()
+ + COMPAT_TOOL_PRIORITY_OFF);
+ if (prio > best) best = prio;
+ }
+
+ uint8_t body[BODY_MAX];
+ np_pb_t w = { body, sizeof body, 0, 1 };
+ uint32_t listed = 0;
+
+ for (uint32_t i = 0; i < count; i++) {
+ const uint8_t *tool = array + (size_t)i * np_compat_tool_stride();
+ if (!offered(tool, platforms, bypass)) continue;
+
+ const char *name = tool_name(tool);
+ if (!name) continue;
+
+ int32_t prio = *(const int32_t *)(tool + COMPAT_TOOL_PRIORITY_OFF);
+ pb_tool(&w, RESP_TOOLS, name,
+ *(const char *const *)(tool + COMPAT_TOOL_DISPLAY_OFF),
+ active && strcmp(active, name) == 0,
+ best != 0 && prio != best && prio > 0);
+ if (!w.ok) {
+ NP_ERR("compatsvc: tool %s does not fit the reply", name);
+ return RESULT_FAIL;
+ }
+ listed++;
+ }
+
+ // "No tool" entry.
+ if (appid && (fallback || holds_none)) {
+ pb_tool(&w, RESP_TOOLS, NP_COMPAT_TOOL_NONE, TOOL_NONE_LABEL,
+ holds_none, 0);
+ if (!w.ok) {
+ NP_ERR("compatsvc: the entry for using no tool does not fit the reply");
+ return RESULT_FAIL;
+ }
+ listed++;
+ }
+
+ pb_string(&w, RESP_SELECTED, chosen ? chosen : "");
+
+ // The page renders this as "Default".
+ if (fallback)
+ pb_string(&w, RESP_DEFAULT, fallback);
+
+ if (!w.ok) {
+ NP_ERR("compatsvc: %u tool(s) do not fit the reply to app %u", listed, appid);
+ return RESULT_FAIL;
+ }
+ if (!np_webui_parse_into(response, body, (uint32_t)w.len)) {
+ NP_ERR("compatsvc: the client rejected the %zu byte reply built for app %u",
+ w.len, appid);
+ return RESULT_FAIL;
+ }
+
+ NP_LOG("compatsvc: app %u is offered %u entr(ies) from %u tool(s) on platforms "
+ "0x%x, mapped to %s, running under %s, defaulting to %s", appid, listed,
+ count, platforms, chosen ? chosen : "no tool",
+ active ? active : "no tool", fallback ? fallback : "no tool");
+ return RESULT_OK;
+}
+
+// Reads a protobuf string field.
+static const char *string_field(uintptr_t field) {
+ uintptr_t str = *(const uintptr_t *)field & ~(uintptr_t)1;
+ if (!str) return "";
+
+ const int8_t *bytes = (const int8_t *)str;
+ return bytes[23] < 0 ? *(const char *const *)str : (const char *)str;
+}
+
+// The page takes the result code as the answer and refetches the tool list.
+static int specify_compat_tool(uintptr_t request, uintptr_t response) {
+ uint32_t has_bits = *(const uint32_t *)(request + REQ_HAS_BITS_OFF);
+ uint32_t appid = (has_bits & SPECIFY_HAS_APPID)
+ ? *(const uint32_t *)(request + SPECIFY_APPID_OFF) : 0;
+ const char *tool = string_field(request + SPECIFY_TOOL_NAME_OFF);
+ (void)response;
+
+ uint8_t *mgr = (uint8_t *)np_compat_manager();
+ if (!mgr) {
+ NP_ERR("compatsvc: app %u cannot be mapped to %s before any manager was seen",
+ appid, *tool ? tool : "its default");
+ return RESULT_FAIL;
+ }
+
+ np_compat_map_tool(mgr, appid, tool);
+ NP_LOG("compatsvc: app %u now maps to %s", appid, *tool ? tool : "its default");
+ return RESULT_OK;
+}
+
+static uintptr_t g_state_changed;
+static int g_routes = NP_COMPATSVC_UNTRIED;
+
+void np_compatsvc_state_changed(void) {
+ if (!g_state_changed) return;
+ np_webui_notify(ROUTE_NOTIFY_STATE_CHANGED, g_state_changed);
+}
+
+void np_compatsvc_register(const struct mach_header_64 *mh, intptr_t slide,
+ uintptr_t text_base, size_t text_size) {
+ // Every path below settles g_routes, so it doubles as the once-only guard. A registry
+ // that is not up yet leaves it untried, which is what brings the next lookup back.
+ if (g_routes != NP_COMPATSVC_UNTRIED || !np_webui_registry()) return;
+
+ uintptr_t request = np_rtti_vptr(mh, slide, text_base, text_size, TYPE_GET_REQUEST);
+ uintptr_t response = np_rtti_vptr(mh, slide, text_base, text_size, TYPE_GET_RESPONSE);
+ if (!request || !response) {
+ // A fact about the build, not a fault: every client whose page specifies the tool
+ // directly lands here. hook_webpatch owns the error, where the cost is known.
+ g_routes = NP_COMPATSVC_ABSENT;
+ NP_LOG("compatsvc: the client has no message types for %s",
+ ROUTE_GET_COMPAT_TOOLS);
+ return;
+ }
+
+ np_webui_register_route(ROUTE_GET_COMPAT_TOOLS, request, response, get_compat_tools);
+
+ uintptr_t specify_request = np_rtti_vptr(mh, slide, text_base, text_size,
+ TYPE_SPECIFY_REQUEST);
+ uintptr_t specify_response = np_rtti_vptr(mh, slide, text_base, text_size,
+ TYPE_SPECIFY_RESPONSE);
+ if (!specify_request || !specify_response) {
+ // Half a CompatManager. Unlike the case above this is not a shape any client
+ // ships: the list can be read and nothing can be set from it.
+ g_routes = NP_COMPATSVC_ABSENT;
+ NP_ERR("compatsvc: the client answers %s but has no message types for %s",
+ ROUTE_GET_COMPAT_TOOLS, ROUTE_SPECIFY_COMPAT_TOOL);
+ return;
+ }
+
+ np_webui_register_route(ROUTE_SPECIFY_COMPAT_TOOL, specify_request,
+ specify_response, specify_compat_tool);
+
+ g_routes = NP_COMPATSVC_READY;
+
+ uintptr_t notification = np_rtti_vptr(mh, slide, text_base, text_size,
+ TYPE_STATE_CHANGED);
+ g_state_changed = notification ? np_webui_new_message(notification) : 0;
+ if (!g_state_changed)
+ NP_WARN("compatsvc: the page will show a stale tool until it is reopened");
+}
+
+int np_compatsvc_routes(void) {
+ return g_routes;
+}
diff --git a/dylib/feats/compatsvc.h b/dylib/feats/compatsvc.h
new file mode 100644
index 0000000..0a23c98
--- /dev/null
+++ b/dylib/feats/compatsvc.h
@@ -0,0 +1,29 @@
+// CompatManager WebUI service.
+#ifndef NOTPROTON_FEATS_COMPATSVC_H
+#define NOTPROTON_FEATS_COMPATSVC_H
+
+#include <stdint.h>
+#include <stddef.h>
+#include <mach-o/loader.h>
+
+// Registers on first route lookup rather than at install time
+void np_compatsvc_register(const struct mach_header_64 *mh, intptr_t slide,
+ uintptr_t text_base, size_t text_size);
+
+// Whether the CompatManager routes are answering. UNTRIED is a route lookup that has
+// not happened yet, which is not the same as a client that cannot serve them: the
+// compat chunk can be served before anything asks the transport for a route.
+enum {
+ NP_COMPATSVC_UNTRIED = 0,
+ NP_COMPATSVC_READY,
+ NP_COMPATSVC_ABSENT,
+};
+int np_compatsvc_routes(void);
+
+// Sentinel name for "no tool".
+#define NP_COMPAT_TOOL_NONE "notproton.none"
+
+// Tells the page the mapping changed.
+void np_compatsvc_state_changed(void);
+
+#endif // NOTPROTON_FEATS_COMPATSVC_H
diff --git a/dylib/feats/webpatch.c b/dylib/feats/webpatch.c
new file mode 100644
index 0000000..37fcc9f
--- /dev/null
+++ b/dylib/feats/webpatch.c
@@ -0,0 +1,331 @@
+// Enables Steam Play in the UI/enables the Compatibility tab in game properties
+#include "webpatch.h"
+#include "../util/log.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+#define NP_C1 "\001"
+#define NP_C2 "\002"
+#define NP_C3 "\003"
+#define NP_C4 "\004"
+#define NP_C5 "\005"
+#define NP_C6 "\006"
+#define NP_C7 "\007"
+#define NP_C8 "\010"
+#define NP_CAP_MAX 8
+
+typedef struct {
+ const char *find;
+ const char *replace;
+ int expect; // exact occurrence count, else abort
+} np_gate_t;
+
+typedef struct { const char *at; size_t len; } np_cap_t;
+
+static int is_ident_char(unsigned char c) {
+ return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
+ (c >= '0' && c <= '9') || c == '_' || c == '$';
+}
+
+static int cap_index(unsigned char c) {
+ return (c >= 1 && c <= NP_CAP_MAX) ? c - 1 : -1;
+}
+
+static size_t match_at(const char *src, size_t len, size_t pos,
+ const char *find, np_cap_t *caps) {
+ for (int i = 0; i < NP_CAP_MAX; i++) { caps[i].at = NULL; caps[i].len = 0; }
+
+ size_t s = pos;
+ for (const char *f = find; *f; f++) {
+ int ci = cap_index((unsigned char)*f);
+ if (ci < 0) {
+ if (s >= len || src[s] != *f) return 0;
+ s++;
+ continue;
+ }
+
+ size_t run = 0;
+ while (s + run < len && is_ident_char((unsigned char)src[s + run])) run++;
+ if (run == 0) return 0;
+
+ if (caps[ci].at) {
+ if (run != caps[ci].len || memcmp(src + s, caps[ci].at, run) != 0)
+ return 0;
+ } else {
+ caps[ci].at = src + s;
+ caps[ci].len = run;
+ }
+ s += run;
+ }
+ return s - pos;
+}
+
+static size_t count_matches(const char *src, size_t len, const char *find) {
+ np_cap_t caps[NP_CAP_MAX];
+ size_t n = 0;
+ for (size_t i = 0; i < len; ) {
+ size_t used = match_at(src, len, i, find, caps);
+ if (used) { n++; i += used; } else i++;
+ }
+ return n;
+}
+
+typedef struct { char *buf; size_t len, cap; } np_out_t;
+
+static int out_reserve(np_out_t *o, size_t extra) {
+ if (o->len + extra + 1 <= o->cap) return 1;
+ size_t want = o->cap ? o->cap : 1024;
+ while (want < o->len + extra + 1) want *= 2;
+ char *grown = realloc(o->buf, want);
+ if (!grown) return 0;
+ o->buf = grown;
+ o->cap = want;
+ return 1;
+}
+
+static int out_put(np_out_t *o, const char *p, size_t n) {
+ if (!out_reserve(o, n)) return 0;
+ memcpy(o->buf + o->len, p, n);
+ o->len += n;
+ return 1;
+}
+
+static int out_expand(np_out_t *o, const char *replace, const np_cap_t *caps) {
+ for (const char *r = replace; *r; r++) {
+ int ci = cap_index((unsigned char)*r);
+ if (ci < 0) {
+ if (!out_put(o, r, 1)) return 0;
+ } else {
+ if (!caps[ci].at) return 0;
+ if (!out_put(o, caps[ci].at, caps[ci].len)) return 0;
+ }
+ }
+ return 1;
+}
+
+// CrossOver options panel. Not in great shape, but it'll do
+#define NP_CX_OPTIONS_CSS \
+ "\".MSCXPanel{margin-top:10px}" \
+ ".MSCXPanel .MSCXRow{display:flex;flex-direction:row;padding:9px;margin:0;" \
+ "color:#dfe3e6;background:rgba(59,63,72,.5);border-radius:3px}" \
+ ".MSCXPanel .MSCXRow:hover{box-shadow:0 6px 8px 0 rgba(0,0,0,.16)}" \
+ ".MSCXNoBottomGap{margin-bottom:0}\""
+
+#define NP_CX_OPTIONS_BODY(ARG, RT, BARREL) \
+ ARG "=>{" \
+ "const t=" ARG ".details,o=t.strLaunchOptions||\"\"," \
+ "g=k=>{const p=o.split(\" \").find(x=>x.indexOf(k+\"=\")===0);return p?p.slice(k.length+1):\"\"}," \
+ "s=ps=>{const a=o.split(\" \").filter(x=>x&&!ps.some(p=>x.indexOf(p[0]+\"=\")===0));" \
+ "ps.forEach(p=>{if(p[1])a.unshift(p[0]+\"=\"+p[1])});" \
+ "SteamClient.Apps.SetAppLaunchOptions(t.unAppID,a.join(\" \"))}," \
+ "T=(ks,l,on,off)=>(0," RT ".jsx)(" BARREL ".Yh,{className:\"MSCXRow\",label:l," \
+ "checked:g(ks[0])===on," \
+ "onChange:v=>s(ks.map(k=>[k,v?on:(off||\"\")]))},ks[0])," \
+ "b=g(\"CX_GRAPHICS_BACKEND\")," \
+ "dm=\"\"===b||\"d3dmetal\"===b," \
+ "dx=\"\"===b||\"dxmt\"===b," \
+ "sw=\"1\"===g(\"DXMT_METALFX_SPATIAL_SWAPCHAIN\")," \
+ "F=\"d3d11.metalSpatialUpscaleFactor=\"," \
+ "cf=g(\"DXMT_CONFIG\")," \
+ "U=[{data:\"\",label:\"Off\"}," \
+ "{data:\"1.5\",label:\"1.5x\"}," \
+ "{data:\"1.72\",label:\"1.72x\"}," \
+ "{data:\"2.0\",label:\"2x\"}," \
+ "{data:\"3.0\",label:\"3x\"}]," \
+ "B=[{data:\"\",label:\"Automatic\"}," \
+ "{data:\"d3dmetal\",label:\"D3DMetal\"}," \
+ "{data:\"dxmt\",label:\"DXMT\"}," \
+ "{data:\"dxvk\",label:\"DXVK\"}," \
+ "{data:\"wined3d\",label:\"WineD3D\"}];" \
+ "if((t.vecPlatforms||[]).indexOf(\"osx\")>=0&&!t.strCompatToolName)return null;" \
+ "return(0," RT ".jsx)(\"div\",{className:\"MSCXPanel\",children:(0," RT ".jsxs)(" RT ".Fragment,{children:[" \
+ "(0," RT ".jsx)(\"style\",{children:" NP_CX_OPTIONS_CSS "})," \
+ "(0," RT ".jsxs)(" BARREL ".XY,{label:\"Graphics\",children:[" \
+ "(0," RT ".jsx)(" BARREL ".m,{rgOptions:B,selectedOption:b," \
+ "onChange:v=>s([[\"CX_GRAPHICS_BACKEND\",v.data]]" \
+ ".concat(\"\"===v.data||\"d3dmetal\"===v.data?[]:[[\"D3DM_ENABLE_METALFX\",\"\"]])" \
+ ".concat(\"\"===v.data||\"dxmt\"===v.data?[]:" \
+ "[[\"DXMT_METALFX_SPATIAL_SWAPCHAIN\",\"\"],[\"DXMT_CONFIG\",\"\"]])" \
+ ".concat(\"dxmt\"===v.data?[]:[[\"DXMT_ENABLE_NVEXT\",\"\"]]))})," \
+ "T([\"MTL_HUD_ENABLED\"],\"Metal HUD\",\"1\")," \
+ "dm&&T([\"D3DM_ENABLE_METALFX\"],\"DLSS\",\"1\")," \
+ "\"dxmt\"===b&&T([\"DXMT_ENABLE_NVEXT\"],\"DLSS\",\"1\")," \
+ "T([\"ROSETTA_ADVERTISE_AVX\"],\"Advertise AVX2 to Rosetta\",\"1\",\"0\")," \
+ "T([\"WINEMSYNC\"],\"MSync\",\"1\",\"0\")," \
+ "T([\"NOTPROTON_RETINA\"],\"High Resolution\",\"1\",\"0\")" \
+ "]},\"gfx\")," \
+ "dx&&(0," RT ".jsx)(" BARREL ".XY," \
+ "{label:\"MetalFX Upscaling (Samples from the resolution the game is set to)\"," \
+ "children:(0," RT ".jsx)(" BARREL ".m,{rgOptions:U," \
+ "selectedOption:sw?(0===cf.indexOf(F)?cf.slice(F.length):\"2.0\"):\"\"," \
+ "onChange:v=>s(v.data?[[\"DXMT_METALFX_SPATIAL_SWAPCHAIN\",\"1\"],[\"DXMT_CONFIG\",F+v.data]]" \
+ ":[[\"DXMT_METALFX_SPATIAL_SWAPCHAIN\",\"\"],[\"DXMT_CONFIG\",\"\"]])})},\"usf\")" \
+ "]})})}"
+
+#define NP_CX_OPTIONS_COMPONENT \
+ "MSCXOpts=" NP_CX_OPTIONS_BODY("e", "i", "c") ","
+
+// Valve is testing a new compatibility page UI, this logic relates to supporting that
+#define NP_CX_OPTIONS_STATEMENT \
+ "var MSCXOpts=" NP_CX_OPTIONS_BODY("np", NP_C3, NP_C4) ";"
+
+static const np_gate_t g_gates_forcetool[] = {
+ // SteamPlay settings section
+ { "function ue(e){return(0,T.CI)()?",
+ "function ue(e){return true?", 1 },
+ // AppProperties Compatibility tab (app and non-Steam-shortcut variants)
+ { "(0,f.CI)()&&o.push({title:(0,A.we)(\"#AppProperties_CompatibilityPage\")",
+ "true&&o.push({title:(0,A.we)(\"#AppProperties_CompatibilityPage\")", 2 },
+ // Settings page Compatibility entry, keeping the SteamOS exclusion (!rf())
+ { "Compatibility:{visible:t&&(0,f.CI)()&&!(0,f.rf)()",
+ "Compatibility:{visible:t&&true&&!(0,f.rf)()", 1 },
+ { "return(0,i.jsxs)(i.Fragment,{children:[0!=a.length&&(0,i.jsx)(_r,{label:(0,A.we)"
+ "(\"#AppProperties_CompatilibityForceTool\"),checked:g,onChange:C,disabled:!r||0===a.length}),"
+ "g&&a.length>0&&(0,i.jsx)(c.m,{strClassName:K().TopGap,rgOptions:d,"
+ "selectedOption:t.strCompatToolName,onChange:e=>SteamClient.Apps.SpecifyCompatTool"
+ "(t.unAppID,e.data)})]})",
+ "return(0,i.jsxs)(i.Fragment,{children:[0!=a.length&&(0,i.jsx)(_r,{label:(0,A.we)"
+ "(\"#AppProperties_CompatilibityForceTool\"),checked:g,onChange:C,disabled:!r||0===a.length}),"
+ "g&&a.length>0&&(0,i.jsx)(c.m,{strClassName:K().TopGap+\" MSCXNoBottomGap\",rgOptions:d,"
+ "selectedOption:t.strCompatToolName,onChange:e=>SteamClient.Apps.SpecifyCompatTool"
+ "(t.unAppID,e.data)})]})", 1 },
+ // Compatibility page container
+ { "Rt=(0,a.PA)(e=>(0,i.jsxs)(c.nB,{children:[(0,i.jsx)(\"div\",{className:K().HiddenIfNotLast,"
+ "children:(0,A.we)(\"#AppProperties_CompatibilityNoOptions\")}),(0,i.jsx)(It,{...e}),"
+ "(0,i.jsx)(xt,{...e})]}));",
+ NP_CX_OPTIONS_COMPONENT
+ "Rt=(0,a.PA)(e=>(0,i.jsxs)(c.nB,{children:[(0,i.jsx)(\"div\",{className:K().HiddenIfNotLast,"
+ "children:(0,A.we)(\"#AppProperties_CompatibilityNoOptions\")}),(0,i.jsx)(It,{...e}),"
+ "(0,i.jsx)(xt,{...e}),(0,i.jsx)(MSCXOpts,{...e})]}));", 1 },
+ { "get is_invalid_os_type(){return this.most_available_per_client_data.is_invalid_os_type}",
+ "get is_invalid_os_type(){return false}", 1 },
+ // Reminder banner for 32 bit Mac games
+ { "s.is_invalid_os_type&&(0,n.jsx)(U,{})",
+ "!s.local_per_client_data?.installed&&"
+ "s.most_available_per_client_data?.is_invalid_os_type&&(0,n.jsx)(U,{})", 1 },
+ { "(0,h.we)(\"#GameList_Entry_Invalid_OSType2\")",
+ "\"Enable CrossOver under Properties > Compatibility to install and run "
+ "the Windows version.\"", 1 },
+};
+
+// Support for new compatibility tab UI in the Steam beta
+static const np_gate_t g_gates_selecttool[] = {
+ // AppProperties Compatibility tab
+ { "(0," NP_C1 ".CI)()&&" NP_C2 ".push({title:(0," NP_C3 ".we)"
+ "(\"#AppProperties_CompatibilityPage\")",
+ "true&&" NP_C2 ".push({title:(0," NP_C3 ".we)"
+ "(\"#AppProperties_CompatibilityPage\")", 2 },
+ // Settings page Compatibility entry.
+ { "Compatibility:{visible:" NP_C1 "&&(0," NP_C2 ".CI)(),title:",
+ "Compatibility:{visible:" NP_C1 "&&true,title:", 1 },
+ { "function " NP_C1 "(" NP_C2 "){return(0," NP_C3 ".jsxs)(" NP_C4 ".XY,{label:(0," NP_C5 ".we)"
+ "(\"#Settings_SteamPlay_SteamPlay\"),children:[(0," NP_C3 ".jsx)(" NP_C6 ",{details:" NP_C2 ".details}),"
+ "(0," NP_C3 ".jsx)(" NP_C7 ".G,{setting:\"compat_show_all_tools\",label:(0," NP_C5 ".we)"
+ "(\"#Settings_SteamPlay_ShowAll\"),feature:" NP_C8 ".OK})]})}",
+ NP_CX_OPTIONS_STATEMENT
+ "function " NP_C1 "(" NP_C2 "){return(0," NP_C3 ".jsxs)(" NP_C3 ".Fragment,{children:["
+ "(0," NP_C3 ".jsxs)(" NP_C4 ".XY,{label:(0," NP_C5 ".we)"
+ "(\"#Settings_SteamPlay_SteamPlay\"),children:[(0," NP_C3 ".jsx)(" NP_C6 ",{details:" NP_C2 ".details}),"
+ "(0," NP_C3 ".jsx)(" NP_C7 ".G,{setting:\"compat_show_all_tools\",label:(0," NP_C5 ".we)"
+ "(\"#Settings_SteamPlay_ShowAll\"),feature:" NP_C8 ".OK})]}),"
+ "(0," NP_C3 ".jsx)(MSCXOpts,{details:" NP_C2 ".details})]})}", 1 },
+ { "get is_invalid_os_type(){return this.most_available_per_client_data.is_invalid_os_type}",
+ "get is_invalid_os_type(){return false}", 1 },
+ // Reminder banner for 32 bit Mac games
+ { NP_C1 ".is_invalid_os_type&&(0," NP_C2 ".jsx)(" NP_C3 ",{})",
+ "!" NP_C1 ".local_per_client_data?.installed&&"
+ NP_C1 ".most_available_per_client_data?.is_invalid_os_type&&"
+ "(0," NP_C2 ".jsx)(" NP_C3 ",{})", 1 },
+ { "(0," NP_C1 ".we)(\"#GameList_Entry_Invalid_OSType2\")",
+ "\"Enable CrossOver under Properties > Compatibility to install and run "
+ "the Windows version.\"", 1 },
+};
+
+typedef struct {
+ const char *name;
+ const char *probe;
+ const np_gate_t *gates;
+ size_t count;
+} np_ui_shape_t;
+
+static const np_ui_shape_t g_shapes[] = {
+ { NP_SHAPE_FORCETOOL, "#AppProperties_CompatilibityForceTool",
+ g_gates_forcetool, sizeof(g_gates_forcetool) / sizeof(g_gates_forcetool[0]) },
+ { NP_SHAPE_SELECTTOOL, "#AppProperties_Compat_SelectTool",
+ g_gates_selecttool, sizeof(g_gates_selecttool) / sizeof(g_gates_selecttool[0]) },
+};
+#define NP_SHAPE_COUNT (sizeof(g_shapes) / sizeof(g_shapes[0]))
+
+static int has_suffix(const char *s, const char *suf) {
+ size_t ls = strlen(s), lf = strlen(suf);
+ return ls >= lf && memcmp(s + ls - lf, suf, lf) == 0;
+}
+
+int np_webpatch_should_patch(const char *path) {
+ return path
+ && strstr(path, "steamui") != NULL
+ && strstr(path, "/chunk~") != NULL
+ && has_suffix(path, ".js");
+}
+
+char *np_webpatch_transform(const uint8_t *src, size_t src_len, size_t *out_len,
+ const char **out_shape) {
+ const char *s = (const char *)src;
+
+ if (out_shape)
+ *out_shape = NULL;
+
+ const np_ui_shape_t *shape = NULL;
+ for (size_t i = 0; i < NP_SHAPE_COUNT; i++) {
+ if (count_matches(s, src_len, g_shapes[i].probe) == 0)
+ continue;
+ if (shape) {
+ NP_WARN("webpatch: chunk carries both the '%s' and '%s' compat UI, "
+ "refusing to guess which one renders", shape->name, g_shapes[i].name);
+ return NULL;
+ }
+ shape = &g_shapes[i];
+ }
+ if (!shape)
+ return NULL; // Not the part carrying the compat UI.
+
+ if (out_shape)
+ *out_shape = shape->name;
+
+ int drifted = 0;
+ for (size_t g = 0; g < shape->count; g++) {
+ size_t n = count_matches(s, src_len, shape->gates[g].find);
+ if (n != (size_t)shape->gates[g].expect) {
+ NP_WARN("webpatch: [%s] gate %zu expected %d occurrence(s), found %zu",
+ shape->name, g, shape->gates[g].expect, n);
+ drifted = 1;
+ }
+ }
+ if (drifted) {
+ NP_ERR("webpatch: [%s] compat UI left unpatched, a Steam update moved the "
+ "anchors", shape->name);
+ return NULL;
+ }
+
+ np_out_t out = {0};
+ np_cap_t caps[NP_CAP_MAX];
+ for (size_t i = 0; i < src_len; ) {
+ const np_gate_t *hit = NULL;
+ size_t used = 0;
+ for (size_t g = 0; g < shape->count; g++) {
+ used = match_at(s, src_len, i, shape->gates[g].find, caps);
+ if (used) { hit = &shape->gates[g]; break; }
+ }
+ int ok = hit ? out_expand(&out, hit->replace, caps)
+ : out_put(&out, s + i, 1);
+ if (!ok) { free(out.buf); return NULL; }
+ i += hit ? used : 1;
+ }
+
+ if (!out_reserve(&out, 0)) { free(out.buf); return NULL; }
+ out.buf[out.len] = '\0';
+ *out_len = out.len;
+ NP_LOG("webpatch: [%s] %zu gates applied", shape->name, shape->count);
+ return out.buf;
+}
diff --git a/dylib/feats/webpatch.h b/dylib/feats/webpatch.h
new file mode 100644
index 0000000..b97f9f4
--- /dev/null
+++ b/dylib/feats/webpatch.h
@@ -0,0 +1,22 @@
+// Enables Steam Play in the UI/enables the Compatibility tab in game properties
+#ifndef NOTPROTON_FEATS_WEBPATCH_H
+#define NOTPROTON_FEATS_WEBPATCH_H
+
+#include <stddef.h>
+#include <stdint.h>
+
+int np_webpatch_should_patch(const char *path);
+
+// The compat UIs, named so a caller can compare against the table rather than a literal
+// of its own that a rename would leave behind. forcetool calls SpecifyCompatTool straight
+// out; selecttool reads its list from the CompatManager routes.
+#define NP_SHAPE_FORCETOOL "forcetool"
+#define NP_SHAPE_SELECTTOOL "selecttool"
+
+// `out_shape` is optional and names the compat UI the chunk carried, so a caller can tell
+// which page it just served without probing the bytes a second time. It is set whenever a
+// shape is identified, including the drifted case that returns NULL.
+char *np_webpatch_transform(const uint8_t *src, size_t src_len, size_t *out_len,
+ const char **out_shape);
+
+#endif // NOTPROTON_FEATS_WEBPATCH_H
diff --git a/dylib/feats/webui.c b/dylib/feats/webui.c
new file mode 100644
index 0000000..0b64b35
--- /dev/null
+++ b/dylib/feats/webui.c
@@ -0,0 +1,593 @@
+// WebUI route registration for routes the macOS client does not serve.
+// Specific to the Steam beta client, which has a new UI.
+#include "webui.h"
+#include "../core/macho.h"
+#include "../util/log.h"
+#include "../util/ptr.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+static inline int32_t sign_extend(uint32_t val, int bits) {
+ if (val & (1u << (bits - 1))) val -= (1u << bits);
+ return (int32_t)val;
+}
+
+#define ACCESSOR_LOOKBACK 12
+
+#define MIN_SITES 4
+
+#define FN_SPAN_MAX 0x400
+
+#define VT_SLOTS 24
+
+#define VT_RUN_MIN 8
+
+#define MAX_ROUTES 4
+
+#define REGISTRY_MAP_OFF 96
+#define MAP_ELEMENTS_OFF 48
+#define MAP_BOUND_OFF 72
+#define ROUTE_STRIDE 48
+
+#define REGISTRY_BROADCASTER_OFF 24
+#define BROADCAST_TASK_NAME "ThreadedBroadcastNotification"
+
+#define MSG_NEW_OFF 24
+
+#define ELEM_DESCRIPTOR_OFF 8
+#define ELEM_FLAGS_OFF 16
+
+#define DESC_NAME 0
+#define DESC_CONSTANT 1
+#define DESC_FACTORY 2
+#define DESC_QWORDS 7
+
+#define DESC_CONSTANT_VALUE 0xFFFFFFFD00000000ULL
+
+#define RESULT_FAIL 2
+
+typedef uintptr_t (*np_registry_accessor_fn)(void);
+typedef uintptr_t (*np_msg_new_fn)(void);
+typedef int (*np_notify_fn)(uintptr_t transport, const char *name, uintptr_t message);
+typedef int (*np_parse_fn)(uintptr_t message, const void *bytes, uint32_t len);
+typedef uintptr_t (*np_job_factory_fn)(uintptr_t dispatcher, uintptr_t arg);
+typedef void (*np_send_response_fn)(uintptr_t job, uintptr_t ctx);
+typedef int (*np_register_fn)(uintptr_t registry, void *record);
+
+typedef struct {
+ uintptr_t descriptor[DESC_QWORDS];
+ uintptr_t request_vptr;
+ np_webui_handler_fn handler;
+} np_route_t;
+
+static uintptr_t g_registry;
+static uintptr_t g_register_fn;
+static uintptr_t g_send_response;
+static uintptr_t g_parse;
+static uintptr_t g_text_base, g_text_end;
+static uintptr_t g_const_base, g_const_end;
+static uintptr_t g_text_seg_base;
+static size_t g_text_seg_size;
+
+// A slot of 0 is a real slot
+static int g_notify_slot = -1;
+
+static np_route_t g_routes[MAX_ROUTES];
+static int g_route_count;
+
+static uintptr_t g_stock_factory;
+static uintptr_t g_clone[2 + VT_SLOTS];
+static uintptr_t g_clone_vptr;
+static uintptr_t g_route_flags;
+
+static int bl_target(uint32_t insn, uintptr_t pc, uintptr_t *out) {
+ if ((insn & 0xFC000000) != 0x94000000) return 0;
+ int32_t imm = sign_extend(insn & 0x03FFFFFF, 26);
+ *out = pc + 4 * (intptr_t)imm;
+ return 1;
+}
+
+static int in_text(uintptr_t va) {
+ return g_text_base && va >= g_text_base && va < g_text_end && (va & 3) == 0;
+}
+
+static uintptr_t adrp_add_target(uintptr_t pc, uint32_t first, uint32_t second) {
+ if ((first & 0x9F000000) != 0x90000000) return 0;
+
+ int reg = (int)(first & 0x1F);
+ int32_t imm = sign_extend(((first >> 5) & 0x7FFFF) << 2 | ((first >> 29) & 3), 21);
+ uintptr_t page = (pc & ~(uintptr_t)0xFFF) + ((intptr_t)imm << 12);
+
+ if ((second & 0xFF800000) != 0x91000000) return 0;
+ if ((int)(second & 0x1F) != reg || (int)((second >> 5) & 0x1F) != reg) return 0;
+
+ return page + ((second >> 10) & 0xFFF);
+}
+
+static uintptr_t find_accessor(uintptr_t register_fn, uintptr_t text_base,
+ size_t text_size, int *out_sites) {
+ uintptr_t end = text_base + text_size;
+ uintptr_t winner = 0;
+ int agree = 0, disagree = 0, silent = 0;
+
+ for (uintptr_t pc = text_base; pc + 4 <= end; pc += 4) {
+ uintptr_t called;
+ if (!bl_target(*(const uint32_t *)pc, pc, &called) || called != register_fn)
+ continue;
+
+ uintptr_t accessor = 0;
+ for (int back = 1; back <= ACCESSOR_LOOKBACK; back++) {
+ uintptr_t at = pc - 4 * back;
+ if (at < text_base) break;
+ if (bl_target(*(const uint32_t *)at, at, &accessor)) break;
+ }
+ if (!accessor) { silent++; continue; }
+
+ if (!winner) { winner = accessor; agree = 1; }
+ else if (accessor == winner) { agree++; }
+ else { disagree++; }
+ }
+
+ if (disagree) {
+ NP_ERR("webui: %d registration sites reach the registry through 0x%lx but %d "
+ "use something else, so none of them can be trusted",
+ agree, (unsigned long)winner, disagree);
+ return 0;
+ }
+ if (agree < MIN_SITES) {
+ NP_WARN("webui: %d registration site(s) name an accessor, %d name none; "
+ "need %d that agree", agree, silent, MIN_SITES);
+ return 0;
+ }
+ if (winner < text_base || winner >= end) {
+ NP_ERR("webui: accessor 0x%lx sits outside the code it was read from",
+ (unsigned long)winner);
+ return 0;
+ }
+
+ if (silent)
+ NP_DBG("webui: %d registration site(s) set up the registry outside the "
+ "instructions this reads", silent);
+ if (out_sites) *out_sites = agree;
+ return winner;
+}
+
+// request-body parse
+static uintptr_t find_parse(uintptr_t dispatch_fn) {
+ uintptr_t found = 0;
+ int hits = 0;
+
+ for (uintptr_t pc = dispatch_fn; pc + 8 <= dispatch_fn + FN_SPAN_MAX; pc += 4) {
+ uintptr_t called = 0;
+ if (!bl_target(*(const uint32_t *)pc, pc, &called)) continue;
+ // TBZ W0, #0, <label>
+ if ((*(const uint32_t *)(pc + 4) & 0xFFF8001F) != 0x36000000) continue;
+ found = called;
+ hits++;
+ }
+
+ if (hits != 1) {
+ NP_ERR("webui: the dispatcher tests %d of its calls a bit at a time, so "
+ "none of them is certainly the parse", hits);
+ return 0;
+ }
+ return found;
+}
+
+int np_webui_init(const struct mach_header_64 *mh, intptr_t slide,
+ uintptr_t register_fn, uintptr_t dispatch_fn,
+ uintptr_t send_response) {
+ if (!mh || !register_fn || !dispatch_fn || !send_response) return 0;
+
+ size_t text_size = 0;
+ if (np_get_section_containing(mh, slide, register_fn, &g_text_base, &text_size) != 0) {
+ NP_ERR("webui: the register function at 0x%lx belongs to no section",
+ (unsigned long)register_fn);
+ return 0;
+ }
+ g_text_end = g_text_base + text_size;
+
+ uintptr_t const_base = 0;
+ size_t const_size = 0;
+ if (np_find_segment(mh, slide, "__DATA_CONST", &const_base, &const_size) != 0) {
+ NP_ERR("webui: the image has no __DATA_CONST, so no vtable can be trusted");
+ return 0;
+ }
+ g_const_base = const_base;
+ g_const_end = const_base + const_size;
+
+ // String literals are in in __TEXT
+ if (np_find_segment(mh, slide, "__TEXT", &g_text_seg_base, &g_text_seg_size) != 0)
+ NP_WARN("webui: the image has no __TEXT, so nothing can be told when the "
+ "answer to a route stops holding");
+
+ int sites = 0;
+ uintptr_t accessor = find_accessor(register_fn, g_text_base, text_size, &sites);
+ if (!accessor) return 0;
+
+ uintptr_t registry = ((np_registry_accessor_fn)accessor)();
+ if (!np_plausible_ptr(registry)) {
+ NP_ERR("webui: accessor 0x%lx returned 0x%lx, which is no registry",
+ (unsigned long)accessor, (unsigned long)registry);
+ return 0;
+ }
+
+ g_registry = registry;
+ g_register_fn = register_fn;
+ g_send_response = send_response;
+ g_parse = find_parse(dispatch_fn);
+ NP_LOG("webui: registry 0x%lx via accessor 0x%lx, agreed by %d of the client's "
+ "own route registrations", (unsigned long)registry,
+ (unsigned long)accessor, sites);
+ return 1;
+}
+
+uintptr_t np_webui_registry(void) {
+ return g_registry;
+}
+
+int np_webui_parse_into(uintptr_t message, const void *bytes, uint32_t len) {
+ if (!g_parse || !message || !bytes) return 0;
+ return (((np_parse_fn)g_parse)(message, bytes, len) & 1) ? 1 : 0;
+}
+
+uintptr_t np_webui_lookup_site(uintptr_t register_fn, uintptr_t dispatch_fn) {
+ if (!register_fn || !dispatch_fn) return 0;
+
+ uintptr_t lookup = 0;
+ for (uintptr_t pc = register_fn; pc < register_fn + FN_SPAN_MAX; pc += 4)
+ if (bl_target(*(const uint32_t *)pc, pc, &lookup)) break;
+
+ if (!lookup) {
+ NP_ERR("webui: the register function at 0x%lx calls nothing, so the route "
+ "lookup has no name", (unsigned long)register_fn);
+ return 0;
+ }
+
+ uintptr_t site = 0;
+ int hits = 0;
+ for (uintptr_t pc = dispatch_fn; pc < dispatch_fn + FN_SPAN_MAX; pc += 4) {
+ uintptr_t called;
+ if (bl_target(*(const uint32_t *)pc, pc, &called) && called == lookup) {
+ site = pc;
+ hits++;
+ }
+ }
+
+ if (hits != 1) {
+ NP_ERR("webui: the dispatcher at 0x%lx reaches the route lookup 0x%lx %d "
+ "times, where one call is the whole basis for trusting it",
+ (unsigned long)dispatch_fn, (unsigned long)lookup, hits);
+ return 0;
+ }
+
+ NP_DBG("webui: route lookup 0x%lx called from 0x%lx",
+ (unsigned long)lookup, (unsigned long)site);
+ return site;
+}
+
+static const char *route_at(uintptr_t elements, int index) {
+ uintptr_t slot = elements + (uintptr_t)index * ROUTE_STRIDE;
+ uint64_t name = *(const uint64_t *)slot;
+ if (name < 0x100000000ULL || name >= 0x800000000000ULL) return NULL;
+
+ const char *s = (const char *)(uintptr_t)name;
+ for (int i = 0; i < 128; i++) {
+ if (s[i] == '\0') return i ? s : NULL;
+ if (s[i] < 0x20 || s[i] > 0x7e) return NULL;
+ }
+ return NULL;
+}
+
+static int walk_routes(uintptr_t *elements_out, int *bound_out) {
+ if (!g_registry) return 0;
+
+ uintptr_t map = g_registry + REGISTRY_MAP_OFF;
+ uintptr_t elements = *(const uintptr_t *)(map + MAP_ELEMENTS_OFF);
+ int bound = *(const int32_t *)(map + MAP_BOUND_OFF);
+ if (!np_plausible_ptr(elements) || bound <= 0 || bound > 4096) {
+ NP_WARN("webui: route table at 0x%lx bound %d is not walkable",
+ (unsigned long)elements, bound);
+ return 0;
+ }
+ *elements_out = elements;
+ *bound_out = bound;
+ return 1;
+}
+
+void np_webui_dump_routes(void) {
+ uintptr_t elements;
+ int bound;
+ if (!getenv("NOTPROTON_WEBUI_ROUTES") || !walk_routes(&elements, &bound)) return;
+
+ int named = 0;
+ for (int i = 0; i < bound; i++) {
+ const char *name = route_at(elements, i);
+ if (!name) continue;
+ named++;
+ NP_LOG("webui: route[%d] %s", i, name);
+ }
+ NP_LOG("webui: %d of %d route slots named", named, bound);
+}
+
+// The target of a branch, with `cond` set when the branch is conditional
+static uintptr_t branch_target(uint32_t insn, uintptr_t pc, int *cond) {
+ int32_t imm;
+ *cond = 0;
+
+ if ((insn & 0xFC000000) == 0x14000000) { // B
+ imm = sign_extend(insn & 0x03FFFFFF, 26);
+ } else if ((insn & 0xFF000010) == 0x54000000 || // B.cond
+ (insn & 0x7F000000) == 0x34000000) { // CBZ, CBNZ
+ *cond = 1;
+ imm = sign_extend((insn >> 5) & 0x7FFFF, 19);
+ } else if ((insn & 0x7F000000) == 0x36000000) { // TBZ, TBNZ
+ *cond = 1;
+ imm = sign_extend((insn >> 5) & 0x3FFF, 14);
+ } else {
+ return 0;
+ }
+
+ return pc + 4 * (intptr_t)imm;
+}
+
+// This was painful, WIP, don't change unless you are me
+static int fn_calls(uintptr_t fn, uintptr_t target) {
+ uintptr_t furthest = fn;
+
+ for (uintptr_t pc = fn; pc < fn + FN_SPAN_MAX; pc += 4) {
+ uint32_t insn = *(const uint32_t *)pc;
+
+ uintptr_t called;
+ if (bl_target(insn, pc, &called) && called == target) return 1;
+
+ int cond = 0;
+ uintptr_t branch = branch_target(insn, pc, &cond);
+ if (branch) {
+ if (!cond && pc >= furthest) break;
+ if (branch > furthest) furthest = branch;
+ continue;
+ }
+
+ int returns = insn == 0xD65F03C0 || // RET
+ (insn & 0xFFFFFC1F) == 0xD61F0000; // BR
+ if (returns && pc >= furthest) break;
+ }
+ return 0;
+}
+
+static int vtable_run(uintptr_t vptr) {
+ int n = 0;
+ while (n < VT_SLOTS && in_text(*(const uintptr_t *)(vptr + 8 * (uintptr_t)n)))
+ n++;
+ return n;
+}
+
+// The handler slot of a job vtable
+static int handler_slot(uintptr_t vptr, int run) {
+ int found = -1;
+ for (int i = 0; i < run; i++) {
+ uintptr_t fn = *(const uintptr_t *)(vptr + 8 * (uintptr_t)i);
+ if (!fn_calls(fn, g_send_response)) continue;
+ if (found >= 0) {
+ NP_DBG("webui: job vtable 0x%lx sends a response from both slot %d and "
+ "slot %d, so neither can be claimed",
+ (unsigned long)vptr, found, i);
+ return -1;
+ }
+ found = i;
+ }
+ return found;
+}
+
+// The job vtable a factory installs
+static uintptr_t vtable_from_factory(uintptr_t factory, int *slot_out, int *run_out) {
+ uintptr_t ctor = 0;
+ for (uintptr_t pc = factory; pc < factory + FN_SPAN_MAX; pc += 4)
+ if (bl_target(*(const uint32_t *)pc, pc, &ctor)) break;
+
+ if (!in_text(ctor)) {
+ NP_DBG("webui: job factory 0x%lx calls nothing that could build the job",
+ (unsigned long)factory);
+ return 0;
+ }
+
+ for (uintptr_t pc = ctor; pc + 8 <= ctor + FN_SPAN_MAX; pc += 4) {
+ uintptr_t cand = adrp_add_target(pc, *(const uint32_t *)pc,
+ *(const uint32_t *)(pc + 4));
+ if (!cand || cand < g_const_base + 16) continue;
+ if (cand + 8 * VT_SLOTS >= g_const_end) continue;
+
+ int run = vtable_run(cand);
+ if (run < VT_RUN_MIN) continue;
+
+ int slot = handler_slot(cand, run);
+ if (slot < 0) continue;
+
+ *slot_out = slot;
+ *run_out = run;
+ return cand;
+ }
+
+ NP_DBG("webui: nothing in the job builder at 0x%lx reads as a job class built on "
+ "a single base", (unsigned long)ctor);
+ return 0;
+}
+
+// Every route shares one job class, so one handler serves them all
+static int64_t job_handler(uintptr_t job, uintptr_t ctx) {
+ uintptr_t request = *(const uintptr_t *)(ctx + 8);
+ uintptr_t response = *(const uintptr_t *)(ctx + 16);
+ uintptr_t vptr = np_plausible_ptr(request) ? *(const uintptr_t *)request : 0;
+
+ int result = RESULT_FAIL;
+ for (int i = 0; i < g_route_count; i++) {
+ if (g_routes[i].request_vptr != vptr) continue;
+ result = g_routes[i].handler(request, response);
+ break;
+ }
+
+ *(uint32_t *)ctx = (uint32_t)result;
+ ((np_send_response_fn)g_send_response)(job, ctx);
+ return 1;
+}
+
+// A route the client already serves, borrowed for its job factory and its flags.
+static int borrow_from_served_route(void) {
+ uintptr_t elements;
+ int bound;
+ if (!walk_routes(&elements, &bound)) return 0;
+
+ for (int i = 0; i < bound; i++) {
+ if (!route_at(elements, i)) continue;
+
+ uintptr_t elem = elements + (uintptr_t)i * ROUTE_STRIDE;
+ uintptr_t desc = *(const uintptr_t *)(elem + ELEM_DESCRIPTOR_OFF);
+ if (!np_plausible_ptr(desc)) continue;
+
+ uintptr_t factory = *(const uintptr_t *)(desc + 8 * DESC_FACTORY);
+ if (!in_text(factory)) continue;
+
+ int slot = -1, run = 0;
+ uintptr_t vptr = vtable_from_factory(factory, &slot, &run);
+ if (!vptr) continue;
+
+ // Two entries sit ahead of slot 0, the offset to top and the type
+ // information, and code that asks a job what it is reads them.
+ memcpy(g_clone, (const void *)(vptr - 16), 16 + 8 * (size_t)run);
+ g_clone[2 + slot] = (uintptr_t)job_handler;
+ g_clone_vptr = (uintptr_t)&g_clone[2];
+ g_stock_factory = factory;
+ g_route_flags = *(const uintptr_t *)(elem + ELEM_FLAGS_OFF);
+
+ NP_LOG("webui: job built like the client's own %s, vtable 0x%lx cloned over "
+ "%d virtuals with the handler in slot %d", route_at(elements, i),
+ (unsigned long)vptr, run, slot);
+ return 1;
+ }
+
+ NP_ERR("webui: none of the %d routes the client serves gives up a job factory",
+ bound);
+ return 0;
+}
+
+static uintptr_t job_factory(uintptr_t dispatcher, uintptr_t arg) {
+ uintptr_t job = ((np_job_factory_fn)g_stock_factory)(dispatcher, arg);
+ if (job && g_clone_vptr)
+ *(uintptr_t *)job = g_clone_vptr;
+ return job;
+}
+
+int np_webui_register_route(const char *name, uintptr_t request_vptr,
+ uintptr_t response_vptr, np_webui_handler_fn handler) {
+ if (!g_registry || !g_register_fn || !name || !handler) return 0;
+ if (!np_plausible_ptr(request_vptr) || !np_plausible_ptr(response_vptr)) {
+ NP_ERR("webui: %s has no message types, so it cannot be served", name);
+ return 0;
+ }
+ if (g_route_count >= MAX_ROUTES) {
+ NP_ERR("webui: no room left to serve %s", name);
+ return 0;
+ }
+
+ if (!g_clone_vptr && !borrow_from_served_route())
+ return 0;
+
+ uintptr_t request_new = *(const uintptr_t *)(request_vptr + MSG_NEW_OFF);
+ uintptr_t response_new = *(const uintptr_t *)(response_vptr + MSG_NEW_OFF);
+ if (!in_text(request_new) || !in_text(response_new)) {
+ NP_ERR("webui: the message types for %s do not build their own messages", name);
+ return 0;
+ }
+
+ np_route_t *route = &g_routes[g_route_count];
+ route->descriptor[DESC_NAME] = (uintptr_t)name;
+ route->descriptor[DESC_CONSTANT] = DESC_CONSTANT_VALUE;
+ route->descriptor[DESC_FACTORY] = (uintptr_t)job_factory;
+ route->request_vptr = request_vptr;
+ route->handler = handler;
+
+ uintptr_t record[4] = {
+ (uintptr_t)route->descriptor,
+ g_route_flags,
+ request_new,
+ response_new,
+ };
+
+ int rc = ((np_register_fn)g_register_fn)(g_registry, record);
+ if (rc != 1) {
+ NP_ERR("webui: the client refused to serve %s (rc=%d)", name, rc);
+ return 0;
+ }
+
+ g_route_count++;
+ NP_LOG("webui: serving %s", name);
+ return 1;
+}
+
+static uintptr_t find_literal(const char *s) {
+ if (!g_text_seg_base) return 0;
+ return (uintptr_t)memmem((const void *)g_text_seg_base, g_text_seg_size,
+ s, strlen(s) + 1);
+}
+
+static int notify_slot(uintptr_t vtable, uintptr_t task_name) {
+ for (int slot = 0; slot < VT_SLOTS; slot++) {
+ uintptr_t fn = *(const uintptr_t *)(vtable + 8 * (uintptr_t)slot);
+ if (!in_text(fn)) continue;
+
+ for (uintptr_t pc = fn; pc + 8 <= fn + FN_SPAN_MAX; pc += 4) {
+ uint32_t insn = *(const uint32_t *)pc;
+ if (insn == 0xD65F03C0) break; // RET
+ if (adrp_add_target(pc, insn, *(const uint32_t *)(pc + 4)) == task_name)
+ return slot;
+ }
+ }
+ return -1;
+}
+
+uintptr_t np_webui_new_message(uintptr_t vptr) {
+ if (!np_plausible_ptr(vptr)) return 0;
+
+ uintptr_t new_fn = *(const uintptr_t *)(vptr + MSG_NEW_OFF);
+ if (!in_text(new_fn)) {
+ NP_ERR("webui: the message type at 0x%lx does not build its own messages",
+ (unsigned long)vptr);
+ return 0;
+ }
+ return ((np_msg_new_fn)new_fn)();
+}
+
+int np_webui_notify(const char *name, uintptr_t message) {
+ static int worked_out;
+
+ if (!g_registry || !name || !np_plausible_ptr(message)) return 0;
+
+ uintptr_t transport = *(const uintptr_t *)(g_registry + REGISTRY_BROADCASTER_OFF);
+ uintptr_t vtable = np_plausible_ptr(transport) ? *(const uintptr_t *)transport : 0;
+ if (!np_plausible_ptr(vtable)) {
+ NP_DBG("webui: no transport is up, so %s reaches nobody", name);
+ return 0;
+ }
+
+ if (g_notify_slot < 0) {
+ if (worked_out) return 0;
+ worked_out = 1;
+
+ uintptr_t task = find_literal(BROADCAST_TASK_NAME);
+ g_notify_slot = task ? notify_slot(vtable, task) : -1;
+ if (g_notify_slot < 0) {
+ NP_ERR("webui: the transport at 0x%lx sends nothing through a task, so "
+ "the page will not hear %s", (unsigned long)transport, name);
+ return 0;
+ }
+ NP_LOG("webui: notifications go out through slot %d of the transport at 0x%lx",
+ g_notify_slot, (unsigned long)transport);
+ }
+
+ uintptr_t send = *(const uintptr_t *)(vtable + 8 * (uintptr_t)g_notify_slot);
+ if (!in_text(send)) return 0;
+
+ return ((np_notify_fn)send)(transport, name, message) == 1;
+}
diff --git a/dylib/feats/webui.h b/dylib/feats/webui.h
new file mode 100644
index 0000000..8e271a5
--- /dev/null
+++ b/dylib/feats/webui.h
@@ -0,0 +1,45 @@
+// WebUI route registration for routes the macOS client does not serve.
+// Specific to the Steam beta client, which has a new UI.
+#ifndef NOTPROTON_FEATS_WEBUI_H
+#define NOTPROTON_FEATS_WEBUI_H
+
+#include <stdint.h>
+#include <stddef.h>
+#include <mach-o/loader.h>
+
+// The Compatibility page on beta Steam needs GetCompatTools and SpecifyCompatTool,
+// neither of which are served on the macOS client, rudely.
+int np_webui_init(const struct mach_header_64 *mh, intptr_t slide,
+ uintptr_t register_fn, uintptr_t dispatch_fn,
+ uintptr_t send_response);
+
+uintptr_t np_webui_registry(void);
+
+// Logs every route the client serves. Runs with NOTPROTON_WEBUI_ROUTES set.
+void np_webui_dump_routes(void);
+
+// The instruction where the dispatcher looks up a route, or 0.
+uintptr_t np_webui_lookup_site(uintptr_t register_fn, uintptr_t dispatch_fn);
+
+// Fills `message` from protobuf bytes through the client's own parser,
+// returns 1 on success.
+int np_webui_parse_into(uintptr_t message, const void *bytes, uint32_t len);
+
+// Builds a message of the type `vptr` names. Only the client's own message
+// classes produce objects it will accept.
+uintptr_t np_webui_new_message(uintptr_t vptr);
+
+// Invalidates a route so the page refetches rather than showing stale data.
+int np_webui_notify(const char *name, uintptr_t message);
+
+// Fills `response` from `request`. The return value is the result the page sees,
+// where 1 is success.
+typedef int (*np_webui_handler_fn)(uintptr_t request, uintptr_t response);
+
+// Serves `name` from `handler`. The vptrs name the client's constructors
+// (vtable slot 3 is no-argument New). `request_vptr` also identifies which route
+// a request belongs to. Returns 1 once the route is live.
+int np_webui_register_route(const char *name, uintptr_t request_vptr,
+ uintptr_t response_vptr, np_webui_handler_fn handler);
+
+#endif // NOTPROTON_FEATS_WEBUI_H
diff --git a/dylib/hooks/hook_compat.c b/dylib/hooks/hook_compat.c
new file mode 100644
index 0000000..1dcfa3e
--- /dev/null
+++ b/dylib/hooks/hook_compat.c
@@ -0,0 +1,247 @@
+// Compat tool hooks
+#include "hooks.h"
+#include "../feats/compat.h"
+#include "../feats/compatsvc.h"
+#include "../util/ptr.h"
+#include "../util/log.h"
+#include <stdint.h>
+#include <stdbool.h>
+#include <signal.h>
+#include <string.h>
+
+static void *orig_CCompatManager_Init = NULL;
+typedef void *(*fn_CCompatManager_Init)(void *self, void *arg1);
+
+// A failed DobbyHook leaves the target patched with no original. Every hook
+// below gives up its feature on NULL rather than fault, for safety.
+static void *hook_CCompatManager_Init(void *self, void *arg1) {
+ fn_CCompatManager_Init orig = (fn_CCompatManager_Init)orig_CCompatManager_Init;
+ if (!orig) {
+ NP_ERR("hook_CCompatManager_Init: no original, cannot initialize the manager");
+ return NULL;
+ }
+ void *ret = orig(self, arg1);
+
+ np_compat_force_enable(self);
+
+ return ret;
+}
+
+static void *orig_CCompatManager_BIsEnabled = NULL;
+typedef bool (*fn_CCompatManager_BIsEnabled)(void *self, uint32_t appid);
+
+// Runs on every compat query, forcing the global switch on. Native Mac
+// apps are not routed through a compatibility tool.
+static bool hook_CCompatManager_BIsEnabled(void *self, uint32_t appid) {
+ fn_CCompatManager_BIsEnabled orig = (fn_CCompatManager_BIsEnabled)orig_CCompatManager_BIsEnabled;
+ if (!orig) {
+ NP_ERR("hook_CCompatManager_BIsEnabled: no original, reporting compat disabled");
+ return false;
+ }
+ np_compat_force_enable(self);
+ np_compat_register_crossover(self);
+ return orig(self, appid);
+}
+
+void np_hooks_compat_set_helpers(uintptr_t yld_register_tool,
+ uintptr_t get_valid_platforms,
+ uintptr_t find_tool_for_target_app,
+ uintptr_t set_compat_tool_mapping,
+ uintptr_t find_mapping,
+ uintptr_t get_wildcard_mapping) {
+ np_compat_set_register_fn(yld_register_tool);
+ np_compat_set_valid_platforms_fn(get_valid_platforms);
+ np_compat_set_find_tool_fn(find_tool_for_target_app);
+ np_compat_set_mapping_fn(set_compat_tool_mapping);
+ np_compat_set_app_mapping_fn(find_mapping);
+ np_compat_set_wildcard_fn(get_wildcard_mapping);
+}
+
+static void *orig_FindToolForTargetApp = NULL;
+typedef void *(*fn_FindToolForTargetApp)(void *self, uint32_t appid);
+
+// An unmapped windows-only app resolves to no tool ("Install on Windows").
+// Those are defaulted to CrossOver for quality UX.
+static void *hook_FindToolForTargetApp(void *self, uint32_t appid) {
+ fn_FindToolForTargetApp orig = (fn_FindToolForTargetApp)orig_FindToolForTargetApp;
+ if (!orig) {
+ NP_ERR("hook_FindToolForTargetApp: no original, resolving no tool for appID %u",
+ appid);
+ return NULL;
+ }
+ void *tool = orig(self, appid);
+
+ if (tool || appid == 0)
+ return tool;
+
+ // The NP_COMPAT_TOOL_NONE sentinel is honored as an explicit refusal.
+ const char *mapping = np_compat_app_mapping(self, appid);
+ if (mapping && strcmp(mapping, NP_COMPAT_TOOL_NONE) == 0)
+ return NULL;
+
+ if (!np_compat_would_force(self, appid))
+ return NULL;
+
+ void *crossover = np_compat_registered_tool(self);
+ if (crossover)
+ NP_DBG("hook_FindToolForTargetApp: appID %u is windows-only, defaulting to CrossOver tool",
+ appid);
+ return crossover;
+}
+
+static void *orig_InternalSpecifyCompatTool = NULL;
+typedef uint64_t (*fn_InternalSpecifyCompatTool)(void *self, uint64_t appid,
+ const char *name, void *config,
+ int priority);
+
+// Every mapping change arrives here (global default/per-app), so this is
+// where the page is notified.
+static uint64_t hook_InternalSpecifyCompatTool(void *self, uint64_t appid,
+ const char *name, void *config,
+ int priority) {
+ fn_InternalSpecifyCompatTool orig =
+ (fn_InternalSpecifyCompatTool)orig_InternalSpecifyCompatTool;
+ if (!orig) {
+ NP_ERR("hook_InternalSpecifyCompatTool: no original, so appID %u keeps the "
+ "mapping it had", (uint32_t)appid);
+ return 0;
+ }
+
+ uint64_t result = orig(self, appid, name, config, priority);
+ np_compatsvc_state_changed();
+ return result;
+}
+
+// The trampoline is the client's own resolution without the CrossOver default.
+void np_hooks_compat_publish_originals(void) {
+ np_compat_set_chosen_tool_fn((uintptr_t)orig_FindToolForTargetApp);
+}
+
+// Proton converts is only for Linux, so the oslist match fails on macOS and the
+// app shows "Install on Windows". Forcing x0 non-zero takes the from_oslist
+// write path.
+static void instrument_oslist_override_gate(void *address, void *ctx_) {
+ (void)address;
+ np_arm64_ctx_t *ctx = (np_arm64_ctx_t *)ctx_;
+ if (ctx->general.x[0] != 0)
+ return;
+ ctx->general.x[0] = 1;
+ uint64_t tool = ctx->general.x[21];
+ uint32_t appid = (tool && np_plausible_ptr(tool))
+ ? *(uint32_t *)(tool + np_compat_tool_off(COMPAT_TOOL_APPID_OFF)) : 0;
+ NP_LOG("instrument_oslist_override_gate: appid=%u install platform forced to tool from_oslist", appid);
+}
+
+//
+#define TOOL_VERSION_OFF 0x04
+#define TOOL_COMMANDLINE_OFF 0x18
+#define TOOL_DEPENDENCY_OFF 0x20
+
+// Proton targets linux with no macOS depot, so the depot lookup fails. Rewriting
+// the tool to appid zero points the launch builder at the local CrossOver
+// directory.
+static void instrument_resolver_local_redirect(void *address, void *ctx_) {
+ (void)address;
+ np_arm64_ctx_t *ctx = (np_arm64_ctx_t *)ctx_;
+
+ uint64_t tool = ctx->general.x[0];
+ if (!tool || !np_plausible_ptr(tool))
+ return;
+
+ uint32_t tool_appid = *(uint32_t *)(tool + np_compat_tool_off(COMPAT_TOOL_APPID_OFF));
+ if (tool_appid == 0)
+ return;
+
+ const char *tool_dir = np_compat_tool_dir();
+ if (!tool_dir)
+ return;
+
+ *(uint32_t *)(tool + TOOL_VERSION_OFF) = 2;
+ *(uint32_t *)(tool + TOOL_DEPENDENCY_OFF) = 0;
+ *(uint32_t *)(tool + np_compat_tool_off(COMPAT_TOOL_APPID_OFF)) = 0;
+ *(const char **)(tool + np_compat_tool_off(COMPAT_TOOL_INSTALL_OFF)) = tool_dir;
+ *(const char **)(tool + TOOL_COMMANDLINE_OFF) = np_compat_tool_commandline();
+
+ NP_LOG("instrument_resolver_local_redirect: tool %u routed to local CrossOver tool at %s",
+ tool_appid, tool_dir);
+}
+
+static void *orig_TerminateProcessByPid = NULL;
+typedef int (*fn_TerminateProcessByPid)(int pid);
+
+static int hook_TerminateProcessByPid(int pid) {
+ fn_TerminateProcessByPid orig = (fn_TerminateProcessByPid)orig_TerminateProcessByPid;
+ int ret = orig ? orig(pid) : 0;
+ if (!orig)
+ NP_ERR("hook_TerminateProcessByPid: no original, signalling pid %d directly", pid);
+ if (ret == 0 && pid > 0) {
+ if (kill(pid, SIGTERM) == 0) {
+ NP_LOG("hook_TerminateProcessByPid: pid %d has no running application, "
+ "sent SIGTERM to run script for prefix teardown", pid);
+ return 1;
+ }
+ }
+ return ret;
+}
+
+static np_patch_entry_t g_hooks[] = {
+ {
+ .label = "CCompatManager::Init",
+ .signature = "CCompatManager::Init",
+ .entry = (void *)hook_CCompatManager_Init,
+ .trampoline = &orig_CCompatManager_Init,
+ .tolerate_missing = 1,
+ },
+ {
+ .label = "CCompatManager::BIsCompatibilityToolEnabled",
+ .signature = "CCompatManager::BIsCompatibilityToolEnabled",
+ .entry = (void *)hook_CCompatManager_BIsEnabled,
+ .trampoline = &orig_CCompatManager_BIsEnabled,
+ .tolerate_missing = 1,
+ },
+ {
+ .label = "CCompatManager::FindToolForTargetApp",
+ .signature = "CCompatManager::FindToolForTargetApp",
+ .entry = (void *)hook_FindToolForTargetApp,
+ .trampoline = &orig_FindToolForTargetApp,
+ .tolerate_missing = 1,
+ },
+ {
+ .label = "CCompatManager::InternalSpecifyCompatTool",
+ .signature = "CCompatManager::InternalSpecifyCompatTool",
+ .entry = (void *)hook_InternalSpecifyCompatTool,
+ .trampoline = &orig_InternalSpecifyCompatTool,
+ .tolerate_missing = 1,
+ },
+ {
+ .label = "CCompatManager::GetOSListOverrideForApp.oslist_gate",
+ .signature = "CCompatManager::GetOSListOverrideForApp.oslist_gate",
+ .entry = (void *)instrument_oslist_override_gate,
+ .trampoline = NULL,
+ .tolerate_missing = 1,
+ .mode = NP_PATCH_PREHOOK,
+ },
+ {
+ .label = "CCompatManager::ResolveCompatToolForApp.local_redirect",
+ .signature = "CCompatManager::ResolveCompatToolForApp.local_redirect",
+ .entry = (void *)instrument_resolver_local_redirect,
+ .trampoline = NULL,
+ .tolerate_missing = 1,
+ .mode = NP_PATCH_PREHOOK,
+ },
+ {
+ .label = "CAppManager::TerminateProcessByPid",
+ .signature = "CAppManager::TerminateProcessByPid",
+ .entry = (void *)hook_TerminateProcessByPid,
+ .trampoline = &orig_TerminateProcessByPid,
+ .tolerate_missing = 1,
+ },
+};
+
+int np_hooks_compat_count(void) {
+ return (int)(sizeof(g_hooks) / sizeof(g_hooks[0]));
+}
+
+np_patch_entry_t *np_hooks_compat_defs(void) {
+ return g_hooks;
+}
diff --git a/dylib/hooks/hook_spawn.c b/dylib/hooks/hook_spawn.c
new file mode 100644
index 0000000..a8d486b
--- /dev/null
+++ b/dylib/hooks/hook_spawn.c
@@ -0,0 +1,140 @@
+// Strips DYLD_INSERT_LIBRARIES from child processes
+#include "hooks.h"
+#include "../util/log.h"
+
+#include <spawn.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+extern int DobbyHook(void *address, void *replace_call, void **origin_call);
+extern void *DobbySymbolResolver(const char *image_name, const char *symbol_name);
+
+typedef int (*fn_execve)(const char *path, char *const argv[], char *const envp[]);
+typedef int (*fn_posix_spawn)(pid_t *pid, const char *path,
+ const posix_spawn_file_actions_t *fa,
+ const posix_spawnattr_t *attr,
+ char *const argv[], char *const envp[]);
+
+static fn_execve orig_execve;
+static fn_posix_spawn orig_posix_spawn;
+static fn_posix_spawn orig_posix_spawnp;
+
+#define NP_INSERT_KEY "DYLD_INSERT_LIBRARIES="
+#define NP_INSERT_KEY_LEN (sizeof(NP_INSERT_KEY) - 1)
+
+// steam_osx re-execs itself and needs the insert for hooks. Steam Helper runs
+// CEF and needs it for the webpatch fopen interpose, strips elsewhere
+static int np_target_keeps_insert(const char *path) {
+ if (!path)
+ return 1;
+ const char *base = strrchr(path, '/');
+ base = base ? base + 1 : path;
+ return strcmp(base, "steam_osx") == 0
+ || strcmp(base, "Steam Helper") == 0;
+}
+
+static char **np_without_insert(char *const envp[]) {
+ if (!envp)
+ return NULL;
+
+ int count = 0;
+ int found = 0;
+ for (int i = 0; envp[i]; i++) {
+ if (strncmp(envp[i], NP_INSERT_KEY, NP_INSERT_KEY_LEN) == 0)
+ found = 1;
+ count++;
+ }
+ if (!found)
+ return NULL;
+
+ char **clean = malloc(sizeof(char *) * (size_t)(count + 1));
+ if (!clean) {
+ NP_WARN("[spawn] cannot allocate a stripped environment, insert passed through");
+ return NULL;
+ }
+
+ int j = 0;
+ for (int i = 0; envp[i]; i++) {
+ if (strncmp(envp[i], NP_INSERT_KEY, NP_INSERT_KEY_LEN) != 0)
+ clean[j++] = envp[i];
+ }
+ clean[j] = NULL;
+ return clean;
+}
+
+static int np_hook_execve(const char *path, char *const argv[], char *const envp[]) {
+ if (np_target_keeps_insert(path))
+ return orig_execve(path, argv, envp);
+
+ char **clean = np_without_insert(envp);
+ if (!clean)
+ return orig_execve(path, argv, envp);
+
+ NP_DBG("[spawn] execve '%s' without the insert", path);
+ int rc = orig_execve(path, argv, (char *const *)clean);
+ // Only reached when the exec failed, since a successful one replaced this image.
+ free(clean);
+ return rc;
+}
+
+static int np_spawn_without_insert(fn_posix_spawn orig, const char *api,
+ pid_t *pid, const char *path,
+ const posix_spawn_file_actions_t *fa,
+ const posix_spawnattr_t *attr,
+ char *const argv[], char *const envp[]) {
+ if (np_target_keeps_insert(path))
+ return orig(pid, path, fa, attr, argv, envp);
+
+ char **clean = np_without_insert(envp);
+ if (!clean)
+ return orig(pid, path, fa, attr, argv, envp);
+
+ NP_DBG("[spawn] %s '%s' without the insert", api, path);
+ int rc = orig(pid, path, fa, attr, argv, (char *const *)clean);
+ free(clean);
+ return rc;
+}
+
+static int np_hook_posix_spawn(pid_t *pid, const char *path,
+ const posix_spawn_file_actions_t *fa,
+ const posix_spawnattr_t *attr,
+ char *const argv[], char *const envp[]) {
+ return np_spawn_without_insert(orig_posix_spawn, "posix_spawn",
+ pid, path, fa, attr, argv, envp);
+}
+
+static int np_hook_posix_spawnp(pid_t *pid, const char *path,
+ const posix_spawn_file_actions_t *fa,
+ const posix_spawnattr_t *attr,
+ char *const argv[], char *const envp[]) {
+ return np_spawn_without_insert(orig_posix_spawnp, "posix_spawnp",
+ pid, path, fa, attr, argv, envp);
+}
+
+static void np_hook_symbol(const char *sym, void *repl, void **orig) {
+ void *addr = DobbySymbolResolver("libsystem_kernel.dylib", sym);
+ if (!addr)
+ addr = DobbySymbolResolver(NULL, sym);
+ if (!addr) {
+ NP_WARN("[spawn] %s: unresolved, children keep the insert", sym);
+ return;
+ }
+
+ int rc = DobbyHook(addr, repl, orig);
+ if (rc == 0)
+ NP_LOG("[spawn] %s: hooked @ %p", sym, addr);
+ else
+ NP_WARN("[spawn] %s: DobbyHook failed rc=%d, children keep the insert", sym, rc);
+}
+
+void np_hooks_spawn_install(void) {
+ if (np_hooks_env_lists_label("NOTPROTON_DISABLE", "spawn")) {
+ NP_WARN("[spawn] DISABLED via NOTPROTON_DISABLE, children keep the insert");
+ return;
+ }
+
+ np_hook_symbol("execve", (void *)np_hook_execve, (void **)&orig_execve);
+ np_hook_symbol("posix_spawn", (void *)np_hook_posix_spawn, (void **)&orig_posix_spawn);
+ np_hook_symbol("posix_spawnp", (void *)np_hook_posix_spawnp, (void **)&orig_posix_spawnp);
+}
diff --git a/dylib/hooks/hook_webpatch.c b/dylib/hooks/hook_webpatch.c
new file mode 100644
index 0000000..692a0a4
--- /dev/null
+++ b/dylib/hooks/hook_webpatch.c
@@ -0,0 +1,228 @@
+// Feeds a compat-gate-patched SteamUI chunk to the loopback reader. The bytes are
+// rewritten in memory and handed back as an anonymous fd, so the on-disk file is
+// not modified, to keep the Steam bootstrap happy.
+
+#include "../feats/webpatch.h"
+#include "../feats/compatsvc.h"
+#include "../util/file.h"
+#include "../util/log.h"
+
+#include <stdarg.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/stat.h>
+#include <sys/syscall.h>
+#include <stdio.h>
+#include <errno.h>
+
+#define DYLD_INTERPOSE(_replacement, _replacee) \
+ __attribute__((used)) static struct { \
+ const void *replacement; \
+ const void *replacee; \
+ } _interpose_##_replacee __attribute__((section("__DATA,__interpose"))) = { \
+ (const void *)(uintptr_t)&_replacement, \
+ (const void *)(uintptr_t)&_replacee \
+ }
+
+
+_Pragma("clang diagnostic push")
+_Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"")
+static int sys_open(const char *path, int oflag, mode_t mode) {
+ return (int)syscall(SYS_open, path, oflag, mode);
+}
+static int sys_openat(int dirfd, const char *path, int oflag, mode_t mode) {
+ return (int)syscall(SYS_openat, dirfd, path, oflag, mode);
+}
+_Pragma("clang diagnostic pop")
+
+#define WEBPATCH_MAX_CHUNK (32 * 1024 * 1024)
+
+static char *drain_fd(int fd, size_t *out_len) {
+ struct stat st;
+ if (fstat(fd, &st) != 0)
+ return NULL;
+ if (st.st_size <= 0 || st.st_size > WEBPATCH_MAX_CHUNK)
+ return NULL;
+
+ size_t total = (size_t)st.st_size;
+ char *buf = malloc(total);
+ if (!buf)
+ return NULL;
+
+ for (size_t done = 0; done < total; ) {
+ ssize_t n = read(fd, buf + done, total - done);
+ if (n <= 0) {
+ free(buf);
+ return NULL;
+ }
+ done += (size_t)n;
+ }
+ *out_len = total;
+ return buf;
+}
+
+static int spill_to_temp(const char *bytes, size_t len) {
+ const char *home = np_home_dir();
+ if (!home)
+ return -1;
+
+ char dir[1024];
+ np_support_path(dir, sizeof(dir), home, NULL);
+ mkdir(dir, 0755);
+
+ char tmpl[1100];
+ snprintf(tmpl, sizeof(tmpl), "%s/webpatch.XXXXXX", dir);
+ int fd = mkstemp(tmpl);
+ if (fd < 0)
+ return -1;
+ unlink(tmpl);
+
+ for (size_t done = 0; done < len; ) {
+ ssize_t n = write(fd, bytes + done, len - done);
+ if (n <= 0) {
+ close(fd);
+ return -1;
+ }
+ done += (size_t)n;
+ }
+
+ if (lseek(fd, 0, SEEK_SET) != 0) {
+ close(fd);
+ return -1;
+ }
+ return fd;
+}
+
+// Read `path`, apply the compat gates, and return a rewound anonymous fd holding
+// the patched bytes. -1 falls the caller through to the real file, which happens
+// when the read fails or the gates are absent/missing. Safety.
+static int open_patched(const char *path) {
+ int in = sys_open(path, O_RDONLY, 0);
+ if (in < 0)
+ return -1;
+
+ size_t raw_len = 0;
+ char *raw = drain_fd(in, &raw_len);
+ close(in);
+ if (!raw)
+ return -1;
+
+ size_t patched_len = 0;
+ const char *shape = NULL;
+ char *patched = np_webpatch_transform((const uint8_t *)raw, raw_len, &patched_len,
+ &shape);
+ free(raw);
+ if (!patched)
+ return -1;
+
+ // Only this page pays for an unregistered service, and only here is it known that the
+ // page arrived. UNTRIED is not a miss: the chunk can precede the first route lookup.
+ if (shape && strcmp(shape, NP_SHAPE_SELECTTOOL) == 0 &&
+ np_compatsvc_routes() == NP_COMPATSVC_ABSENT)
+ NP_ERR("webpatch: the compat page sources its tools from CompatManager and this "
+ "client cannot answer, so the list will be empty");
+
+ int fd = spill_to_temp(patched, patched_len);
+ free(patched);
+ if (fd < 0)
+ return -1;
+
+ NP_LOG_FIRST("webpatch: served patched compat chunk (%s)", path);
+ return fd;
+}
+
+static const int WRITE_INTENT = O_WRONLY | O_RDWR | O_CREAT | O_TRUNC | O_APPEND;
+
+static int try_serve(const char *path, int oflag) {
+ if (oflag & WRITE_INTENT)
+ return -1;
+ if (!np_webpatch_should_patch(path))
+ return -1;
+ return open_patched(path);
+}
+
+static mode_t creat_mode(int oflag, va_list ap) {
+ if (oflag & O_CREAT)
+ return (mode_t)va_arg(ap, int);
+ return 0;
+}
+
+static int np_open(const char *path, int oflag, ...) {
+ va_list ap; va_start(ap, oflag);
+ mode_t mode = creat_mode(oflag, ap);
+ va_end(ap);
+
+ int served = try_serve(path, oflag);
+ if (served >= 0)
+ return served;
+ return sys_open(path, oflag, mode);
+}
+
+static int np_openat(int dirfd, const char *path, int oflag, ...) {
+ va_list ap; va_start(ap, oflag);
+ mode_t mode = creat_mode(oflag, ap);
+ va_end(ap);
+
+ if (path && path[0] == '/') {
+ int served = try_serve(path, oflag);
+ if (served >= 0)
+ return served;
+ }
+ return sys_openat(dirfd, path, oflag, mode);
+}
+
+static int mode_string_flags(const char *mode) {
+ if (!mode || !mode[0])
+ return -1;
+
+ int oflag;
+ switch (mode[0]) {
+ case 'r': oflag = O_RDONLY; break;
+ case 'w': oflag = O_WRONLY | O_CREAT | O_TRUNC; break;
+ case 'a': oflag = O_WRONLY | O_CREAT | O_APPEND; break;
+ default: return -1;
+ }
+ for (const char *p = mode + 1; *p; p++) {
+ switch (*p) {
+ case '+': oflag = (oflag & ~(O_RDONLY | O_WRONLY)) | O_RDWR; break;
+ case 'x': oflag |= O_EXCL; break;
+ case 'e': oflag |= O_CLOEXEC; break;
+ default: break;
+ }
+ }
+ return oflag;
+}
+
+static FILE *np_fopen(const char *path, const char *mode) {
+ int oflag = mode_string_flags(mode);
+ if (!path || oflag < 0) {
+ errno = EINVAL;
+ return NULL;
+ }
+
+ int served = try_serve(path, oflag);
+ if (served >= 0) {
+ FILE *fp = fdopen(served, mode);
+ if (fp)
+ return fp;
+ close(served);
+ }
+
+ int fd = sys_open(path, oflag, 0666);
+ if (fd < 0)
+ return NULL;
+ FILE *fp = fdopen(fd, mode);
+ if (!fp) {
+ int e = errno;
+ close(fd);
+ errno = e;
+ }
+ return fp;
+}
+
+DYLD_INTERPOSE(np_open, open);
+DYLD_INTERPOSE(np_openat, openat);
+DYLD_INTERPOSE(np_fopen, fopen);
diff --git a/dylib/hooks/hook_webui.c b/dylib/hooks/hook_webui.c
new file mode 100644
index 0000000..f28be14
--- /dev/null
+++ b/dylib/hooks/hook_webui.c
@@ -0,0 +1,58 @@
+// Registers the CompatManager routes on the thread that looks routes up. See
+// compatsvc.c/h
+#include "hooks.h"
+#include "../core/macho.h"
+#include "../feats/compatsvc.h"
+#include "../feats/webui.h"
+#include "../util/log.h"
+#include <stdint.h>
+#include <string.h>
+
+#define LOOKUP_LABEL "CWebUITransport::RouteLookup"
+
+static const struct mach_header_64 *g_mh;
+static intptr_t g_slide;
+static uintptr_t g_text_base;
+static size_t g_text_size;
+
+static void register_routes(void *address, void *ctx) {
+ (void)address;
+ (void)ctx;
+ np_compatsvc_register(g_mh, g_slide, g_text_base, g_text_size);
+}
+
+// An unresolved site here leaves the CompatManager routes unregistered, and the panel
+// then shows a service that answers nothing, so the miss is worth a warning where the
+// optional hooks settle for a debug line.
+static np_patch_entry_t g_hooks[] = {
+ {
+ .label = LOOKUP_LABEL,
+ .entry = (void *)register_routes,
+ .trampoline = NULL,
+ .tolerate_missing = 0,
+ .mode = NP_PATCH_PREHOOK,
+ },
+};
+
+void np_hooks_webui_bind(const struct mach_header_64 *mh, intptr_t slide,
+ uintptr_t register_fn, uintptr_t dispatch_fn) {
+ if (!mh || !dispatch_fn) return;
+ if (np_get_section_containing(mh, slide, dispatch_fn, &g_text_base, &g_text_size) != 0)
+ return;
+
+ g_mh = mh;
+ g_slide = slide;
+
+ uintptr_t site = np_webui_lookup_site(register_fn, dispatch_fn);
+ for (size_t i = 0; i < sizeof(g_hooks) / sizeof(g_hooks[0]); i++)
+ if (strcmp(g_hooks[i].label, LOOKUP_LABEL) == 0)
+ g_hooks[i].address = site;
+}
+
+int np_hooks_webui_count(void) {
+ return (int)(sizeof(g_hooks) / sizeof(g_hooks[0]));
+}
+
+np_patch_entry_t *np_hooks_webui_defs(void) {
+ return g_hooks;
+}
diff --git a/dylib/hooks/hooks.c b/dylib/hooks/hooks.c
new file mode 100644
index 0000000..006b4cd
--- /dev/null
+++ b/dylib/hooks/hooks.c
@@ -0,0 +1,124 @@
+// Hook registration and Dobby installation.
+
+#include "hooks.h"
+#include "../core/macho.h"
+#include "../feats/webui.h"
+#include "../feats/compat.h"
+#include "../util/log.h"
+#include <stdlib.h>
+#include <string.h>
+
+extern int DobbyHook(void *address, void *replace_call, void **origin_call);
+typedef void (*np_prehook_fn)(void *address, void *ctx);
+extern int DobbyInstrument(void *address, np_prehook_fn pre_handler);
+
+int np_hooks_env_lists_label(const char *var, const char *label) {
+ const char *list = getenv(var);
+ if (!list || !list[0] || !label)
+ return 0;
+
+ size_t label_len = strlen(label);
+ while (*list) {
+ const char *comma = strchr(list, ',');
+ size_t field_len = comma ? (size_t)(comma - list) : strlen(list);
+ if (field_len == label_len && memcmp(list, label, label_len) == 0)
+ return 1;
+ if (!comma)
+ break;
+ list = comma + 1;
+ }
+ return 0;
+}
+
+typedef struct {
+ const char *group;
+ int (*count)(void);
+ np_patch_entry_t *(*entries)(void);
+} np_hook_group_t;
+
+// webpatch reaches the client through a dyld interpose table, not a resolved
+// address, so it has no row here.
+static const np_hook_group_t np_groups[] = {
+ { "compat", np_hooks_compat_count, np_hooks_compat_defs },
+ { "webui", np_hooks_webui_count, np_hooks_webui_defs },
+};
+
+// Installs one entry. Returns 1 when the patch lands, 0 when it is skipped or fails.
+static int np_apply_entry(np_resolve_result_t *resolved, const char *group,
+ np_patch_entry_t *e) {
+ if (np_hooks_env_lists_label("NOTPROTON_DISABLE", e->label)) {
+ NP_WARN("[%s] %s: DISABLED via NOTPROTON_DISABLE", group, e->label);
+ return 0;
+ }
+
+ uintptr_t addr = e->address ? e->address
+ : e->signature ? np_lookup_address(resolved, e->signature) : 0;
+ if (!addr) {
+ if (e->tolerate_missing)
+ NP_DBG("[%s] %s: unresolved (optional)", group, e->label);
+ else
+ NP_WARN("[%s] %s: unresolved, cannot install", group, e->label);
+ return 0;
+ }
+
+ int prehook = (e->mode == NP_PATCH_PREHOOK);
+ int rc = prehook ? DobbyInstrument((void *)addr, (np_prehook_fn)e->entry)
+ : DobbyHook((void *)addr, e->entry, e->trampoline);
+ if (rc == 0) {
+ NP_LOG("[%s] %s: %s @ %p", group, e->label,
+ prehook ? "instrumented" : "hooked", (void *)addr);
+ return 1;
+ }
+
+ // Dobby patches the target before reporting the error and never registers the
+ // entry, so the patch cannot be lifted.
+ NP_ERR("[%s] %s: %s failed (ret=%d) @ %p, target may stay patched with no original; "
+ "the hook degrades instead of calling it",
+ group, e->label, prehook ? "DobbyInstrument" : "DobbyHook", rc, (void *)addr);
+ return 0;
+}
+
+int np_hooks_install_all(const struct mach_header_64 *mh, intptr_t slide,
+ np_resolve_result_t *resolved, int *total_out) {
+ np_hooks_compat_set_helpers(
+ np_lookup_address(resolved, "CCompatManager::YldRegisterTool"),
+ np_lookup_address(resolved, "CCompatManager::GetValidPlatforms"),
+ np_lookup_address(resolved, "CCompatManager::FindToolForTargetApp"),
+ np_lookup_address(resolved, "CCompatManager::SetCompatToolMapping"),
+ np_lookup_address(resolved, "CCompatManager::FindMapping"),
+ np_lookup_address(resolved, "CCompatManager::GetWildcardMapping"));
+
+ np_compat_probe_tool_layout(
+ np_lookup_address(resolved, "CCompatManager::ResolveCompatToolForApp.local_redirect"),
+ np_lookup_address(resolved, "CCompatManager::GetOSListOverrideForApp.oslist_gate"));
+ np_compat_probe_enabled_off(
+ np_lookup_address(resolved, "CCompatManager::BIsCompatibilityToolEnabled"));
+
+ uintptr_t register_fn = np_lookup_address(resolved,
+ "CWebUIJobDispatcher::RegisterHandler");
+ uintptr_t dispatch_fn = np_lookup_address(resolved, "CWebUITransport::DispatchJob");
+
+ np_webui_init(mh, slide, register_fn, dispatch_fn,
+ np_lookup_address(resolved, "CWebUIMsgJob::SendResponse"));
+ np_webui_dump_routes();
+ np_hooks_webui_bind(mh, slide, register_fn, dispatch_fn);
+
+ int total = 0;
+ int landed = 0;
+ for (size_t g = 0; g < sizeof(np_groups) / sizeof(np_groups[0]); g++) {
+ const np_hook_group_t *group = &np_groups[g];
+ np_patch_entry_t *entries = group->entries();
+ int n = group->count();
+ for (int i = 0; i < n; i++) {
+ total++;
+ landed += np_apply_entry(resolved, group->group, &entries[i]);
+ }
+ }
+
+ np_hooks_compat_publish_originals();
+
+ if (total_out)
+ *total_out = total;
+ NP_LOG("hooks: %d/%d installed", landed, total);
+ return landed;
+}
diff --git a/dylib/hooks/hooks.h b/dylib/hooks/hooks.h
new file mode 100644
index 0000000..027eae6
--- /dev/null
+++ b/dylib/hooks/hooks.h
@@ -0,0 +1,58 @@
+// Hook definitions, Dobby installation, and shared hook infrastructure.
+#ifndef NOTPROTON_HOOKS_HOOKS_H
+#define NOTPROTON_HOOKS_HOOKS_H
+
+#include <stdint.h>
+#include <stddef.h>
+#include "../resolver/resolver.h"
+
+typedef enum {
+ NP_PATCH_REPLACE = 0, // swap in a replacement, keep the original callable
+ NP_PATCH_PREHOOK = 1, // run before the target, may rewrite registers
+} np_patch_mode_t;
+
+// Register state a prehook is handed, in Dobby's layout.
+typedef struct { uint64_t _d0, sp, _d1; struct { uint64_t x[29]; } general; } np_arm64_ctx_t;
+
+typedef struct {
+ const char *label;
+ const char *signature;
+ // Target for a hook that lands somewhere a signature cannot name, such as an
+ // instruction inside a function.
+ uintptr_t address;
+ void *entry;
+ void **trampoline;
+ np_patch_mode_t mode;
+ int tolerate_missing; // when set, an unresolved signature only logs at debug
+} np_patch_entry_t;
+
+int np_hooks_compat_count(void);
+np_patch_entry_t *np_hooks_compat_defs(void);
+
+void np_hooks_compat_publish_originals(void);
+
+void np_hooks_compat_set_helpers(uintptr_t yld_register_tool,
+ uintptr_t get_valid_platforms,
+ uintptr_t find_tool_for_target_app,
+ uintptr_t set_compat_tool_mapping,
+ uintptr_t find_mapping,
+ uintptr_t get_wildcard_mapping);
+
+int np_hooks_webui_count(void);
+np_patch_entry_t *np_hooks_webui_defs(void);
+
+void np_hooks_webui_bind(const struct mach_header_64 *mh, intptr_t slide,
+ uintptr_t register_fn, uintptr_t dispatch_fn);
+
+int np_hooks_install_all(const struct mach_header_64 *mh, intptr_t slide,
+ np_resolve_result_t *resolved, int *total_out);
+
+// True when `label` is one entry of the comma-separated value of env var `var`.
+// NOTPROTON_DISABLE uses this to skip named hooks.
+int np_hooks_env_lists_label(const char *var, const char *label);
+
+// Resolved from libc rather than the signature database, and installed before the client
+// can spawn anything, so this one does not wait for steamclient the way the rest do.
+void np_hooks_spawn_install(void);
+
+#endif // NOTPROTON_HOOKS_HOOKS_H
diff --git a/dylib/resolver/anchor.c b/dylib/resolver/anchor.c
new file mode 100644
index 0000000..8ebdcd2
--- /dev/null
+++ b/dylib/resolver/anchor.c
@@ -0,0 +1,435 @@
+// Anchor-based function resolution
+
+#include "anchor.h"
+#include "resolver.h" // np_looks_like_prologue
+#include "../core/macho.h" // np_find_segment, np_get_section_containing
+#include "../util/log.h"
+
+#include <dlfcn.h>
+#include <string.h>
+
+// Default opcode filter: BLR Xn
+#define DEFAULT_INSN 0xD63F0000u
+#define DEFAULT_INSN_MASK 0xFFFFFC1Fu
+
+static const char *const data_segs[] = {"__DATA_CONST", "__DATA"};
+#define N_DATA_SEGS ((int)(sizeof(data_segs) / sizeof(data_segs[0])))
+
+// AArch64 instruction helpers
+// Decode ADRP: 1 00 10000 immhi(19) Rd(5) with immlo in bits [30:29].
+// Returns the target page address and writes the destination register to *reg.
+static uintptr_t adrp_target(uintptr_t pc, uint32_t w, int *reg) {
+ if ((w & 0x9F000000u) != 0x90000000u) return 0;
+ *reg = (int)(w & 0x1Fu);
+ uint32_t lo = (w >> 29) & 3u;
+ uint32_t hi = (w >> 5) & 0x7FFFFu;
+ int64_t imm = (int64_t)((hi << 2) | lo);
+ imm = (imm << 43) >> 43;
+ return (pc & ~(uintptr_t)0xFFF) + (uintptr_t)(imm << 12);
+}
+
+// Decode ADD (immediate) with shift=0 whose Rn matches `expected_rn`.
+// Returns the full target address (page + offset) or 0.
+static uintptr_t add_imm_target(uint32_t w, int expected_rn, uintptr_t page) {
+ if ((w & 0x7F800000u) != 0x11000000u) return 0;
+ if ((int)((w >> 5) & 0x1Fu) != expected_rn) return 0;
+ uint32_t imm = (w >> 10) & 0xFFFu;
+ if ((w >> 22) & 1u) imm <<= 12;
+ return page + imm;
+}
+
+// Decode LDR (unsigned offset, 64-bit) whose Rn matches `expected_rn`.
+// Returns the address of the loaded slot.
+static uintptr_t ldr_slot_addr(uint32_t w, int expected_rn, uintptr_t page) {
+ if ((w & 0xFFC00000u) != 0xF9400000u) return 0;
+ if ((int)((w >> 5) & 0x1Fu) != expected_rn) return 0;
+ uint32_t imm12 = (w >> 10) & 0xFFFu;
+ return page + (uintptr_t)imm12 * 8u;
+}
+
+static uintptr_t branch26_target(uintptr_t pc, uint32_t w, uint32_t opcode) {
+ if ((w & 0xFC000000u) != opcode) return 0;
+ int64_t imm = (int64_t)(w & 0x03FFFFFFu);
+ imm = (imm << 38) >> 38;
+ return pc + (uintptr_t)(imm * 4);
+}
+
+static uintptr_t bl_target(uintptr_t pc, uint32_t w) {
+ return branch26_target(pc, w, 0x94000000u);
+}
+
+static uintptr_t b_target(uintptr_t pc, uint32_t w) {
+ return branch26_target(pc, w, 0x14000000u);
+}
+
+// Instructions that can legitimately begin a function
+static const struct { uint32_t mask, val; } entry_forms[] = {
+ { 0xFF0003FF, 0xD10003FF }, // SUB SP, SP, #imm
+ { 0xFFC003E0, 0xA98003E0 }, // STP Xt, Xt2, [SP, #-imm]! (pre-indexed)
+ { 0xFFFFFFFF, 0xD503237F }, // PACIBSP (sign LR)
+};
+
+static int is_entry_insn(uintptr_t pc) {
+ uint32_t w = *(const uint32_t *)pc;
+ for (size_t i = 0; i < sizeof(entry_forms) / sizeof(entry_forms[0]); i++) {
+ if ((w & entry_forms[i].mask) == entry_forms[i].val) return 1;
+ }
+ return 0;
+}
+
+// Searching for a C-string VA across segments
+static uintptr_t cstring_va(const struct mach_header_64 *mh, intptr_t slide,
+ const char *needle) {
+ static const char *candidates[] = {"__TEXT", "__DATA_CONST", "__DATA"};
+ size_t needle_len = strlen(needle);
+
+ for (int s = 0; s < (int)(sizeof(candidates) / sizeof(candidates[0])); s++) {
+ uintptr_t seg_base;
+ size_t seg_size;
+ if (np_find_segment(mh, slide, candidates[s], &seg_base, &seg_size) != 0)
+ continue;
+ if (seg_size <= needle_len) continue;
+
+ const char *region = (const char *)seg_base;
+ uintptr_t result = 0;
+ for (size_t off = 0; off + needle_len < seg_size; off++) {
+ if (region[off] != needle[0]) continue;
+ if (memcmp(region + off, needle, needle_len) != 0) continue;
+ if (region[off + needle_len] != '\0') continue;
+ if (result) return 0; // more than one hit, give up
+ result = seg_base + off;
+ off += needle_len; // skip past this match
+ }
+ if (result) return result;
+ }
+ return 0;
+}
+
+// Finds the code that references `target`. `nth` selects among references in
+// ascending address order, or requires a unique one when 0.
+static uintptr_t xref_to_va(uintptr_t text, size_t text_sz, uintptr_t target,
+ int nth, int indirect) {
+ size_t words = text_sz / 4;
+ if (words < 2) return 0;
+
+ const uint32_t *code = (const uint32_t *)text;
+ uintptr_t first = 0;
+ int seen = 0;
+
+ for (size_t i = 0; i + 1 < words; i++) {
+ int reg = -1;
+ uintptr_t page = adrp_target(text + i * 4, code[i], &reg);
+ if (!page) continue;
+
+ uintptr_t addr = indirect ? ldr_slot_addr(code[i + 1], reg, page)
+ : add_imm_target(code[i + 1], reg, page);
+ if (!addr || addr != target) continue;
+
+ seen++;
+ if (nth > 0) {
+ if (seen == nth) return text + i * 4;
+ continue;
+ }
+ if (first) return 0; // ambiguous and no ordinal given
+ first = text + i * 4;
+ }
+ return nth > 0 ? 0 : first;
+}
+
+// The pointer-sized slot in `seg` holding `a` or, if non-zero, `b`.
+// 0 when absent or ambiguous.
+static uintptr_t slot_holding(uintptr_t seg, size_t seg_sz,
+ uintptr_t a, uintptr_t b) {
+ if (seg_sz < sizeof(uintptr_t)) return 0;
+ const uintptr_t *p = (const uintptr_t *)seg;
+ size_t n = seg_sz / sizeof(uintptr_t);
+ uintptr_t found = 0;
+ for (size_t i = 0; i < n; i++) {
+ if (p[i] != a && !(b && p[i] == b)) continue;
+ if (found) return 0; // second candidate, not unique
+ found = seg + i * sizeof(uintptr_t);
+ }
+ return found;
+}
+
+// Pointer slots are not guaranteed to still hold the address of the string this
+// image shipped.
+static uintptr_t uniqued_selector(const char *name) {
+ static void *(*sel_get_uid)(const char *);
+ static int looked_up;
+ if (!looked_up) {
+ looked_up = 1;
+ sel_get_uid = (void *(*)(const char *))dlsym(RTLD_DEFAULT, "sel_getUid");
+ }
+ return sel_get_uid ? (uintptr_t)sel_get_uid(name) : 0;
+}
+
+
+// Backward scan from a reference to the start of its function
+// Stops at the start of the section holding `pc` rather than the start of
+// __TEXT.
+static uintptr_t enclosing_fn(const struct mach_header_64 *mh, intptr_t slide,
+ uintptr_t text, uintptr_t pc) {
+ uintptr_t floor = text;
+ uintptr_t sect_base;
+ size_t sect_size;
+ if (np_get_section_containing(mh, slide, pc, &sect_base, &sect_size) == 0)
+ floor = sect_base;
+
+ while (pc >= floor) {
+ if (is_entry_insn(pc)) return pc;
+ if (pc == floor) break;
+ pc -= 4;
+ }
+ return 0;
+}
+
+// Follow the single branch that targets `callee`
+static uintptr_t sole_caller(const struct mach_header_64 *mh, intptr_t slide,
+ uintptr_t text, size_t text_sz, uintptr_t callee,
+ int tail) {
+ size_t words = text_sz / 4;
+ const uint32_t *code = (const uint32_t *)text;
+ uintptr_t found = 0;
+ for (size_t i = 0; i < words; i++) {
+ uintptr_t pc = text + i * 4;
+ uintptr_t t = tail ? b_target(pc, code[i]) : bl_target(pc, code[i]);
+ if (t != callee) continue;
+ // B also encodes intra-function jumps, so a loop back to a function's own
+ // entry would otherwise make that function its own tail caller.
+ if (tail && enclosing_fn(mh, slide, text, pc) == callee) continue;
+ if (found) return 0; // more than one caller
+ found = pc;
+ }
+ return found ? enclosing_fn(mh, slide, text, found) : 0;
+}
+
+
+#define MAX_CALLER_HOPS 4
+
+static uintptr_t hop_to_caller(const struct mach_header_64 *mh, intptr_t slide,
+ uintptr_t text, size_t text_sz, uintptr_t from,
+ int hops, int tail) {
+ if (hops > MAX_CALLER_HOPS) {
+ NP_WARN("anchor: caller_hops=%d exceeds the %d supported", hops,
+ MAX_CALLER_HOPS);
+ return 0;
+ }
+ for (int i = 0; i < hops; i++) {
+ from = sole_caller(mh, slide, text, text_sz, from, tail);
+ if (!from) return 0;
+ }
+ return from;
+}
+
+// Nth matching instruction after `start`
+static uintptr_t scan_for_insn(uintptr_t text, size_t text_sz,
+ uintptr_t start,
+ uint32_t opcode, uint32_t opmask, int nth) {
+ uintptr_t bound = text + text_sz;
+ int count = 0;
+ for (uintptr_t pc = start; pc + 4 <= bound; pc += 4) {
+ uint32_t w = *(const uint32_t *)pc;
+ if ((w & opmask) == opcode) {
+ if (++count == nth) return pc + 4;
+ }
+ }
+ return 0;
+}
+
+// The sole matching instruction pair inside one function body
+static uintptr_t body_end(uintptr_t fn, uintptr_t text, size_t text_sz) {
+ uintptr_t cap = fn + NP_FN_SPAN_MAX;
+ uintptr_t bound = text + text_sz;
+ if (cap > bound) cap = bound;
+ for (uintptr_t pc = fn + 4; pc + 4 <= cap; pc += 4) {
+ if (is_entry_insn(pc)) return pc;
+ }
+ return cap;
+}
+
+static uintptr_t sole_insn_pair(uintptr_t fn, uintptr_t text, size_t text_sz,
+ const np_insn_pair_t *p) {
+ uintptr_t end = body_end(fn, text, text_sz);
+ uintptr_t found = 0;
+
+ for (uintptr_t pc = fn; pc + 8 <= end; pc += 4) {
+ uint32_t a = *(const uint32_t *)pc;
+ uint32_t b = *(const uint32_t *)(pc + 4);
+ if ((a & p->first_mask) != p->first) continue;
+ if ((b & p->second_mask) != p->second) continue;
+ if (p->tie_mask && (a & p->tie_mask) != (b & p->tie_mask)) continue;
+ if (found) return 0;
+ found = p->land_on_second ? pc + 4 : pc;
+ }
+ return found;
+}
+
+// Public entry point
+uintptr_t np_locate_anchor(const struct mach_header_64 *mh, intptr_t slide,
+ uintptr_t text_base, size_t text_size,
+ const np_anchor_t *anchor) {
+ if (!mh || !anchor || !text_base || !text_size) return 0;
+
+ if (anchor->kind == NP_MATCH_VTABLE_SLOT) {
+ if (!anchor->va) return 0;
+
+ uintptr_t sect_base = 0;
+ size_t sect_size = 0;
+ uintptr_t slot = anchor->va + (uintptr_t)slide;
+ if (np_get_section_containing(mh, slide, slot, &sect_base, &sect_size) != 0)
+ return 0;
+ if (sect_size < sizeof(uintptr_t)) return 0;
+ if (slot - sect_base > sect_size - sizeof(uintptr_t)) return 0;
+
+ uintptr_t fn = *(const uintptr_t *)slot;
+ if (fn < text_base || fn > text_base + text_size - sizeof(uint32_t)) return 0;
+ return np_looks_like_prologue(fn) ? fn : 0;
+ }
+
+ // Both STRING and INSN_AFTER_STRING start with a string xref.
+ uintptr_t str = cstring_va(mh, slide, anchor->str);
+ if (!str) return 0;
+
+ // An indirect anchor names the string but the code only ever sees the
+ // pointer slot that holds it, so redirect the search to that slot.
+ uintptr_t target = str;
+ if (anchor->indirect) {
+ uintptr_t uniqued = uniqued_selector(anchor->str);
+ uintptr_t slot = 0;
+ for (int s = 0; s < N_DATA_SEGS && !slot; s++) {
+ uintptr_t base;
+ size_t size;
+ if (np_find_segment(mh, slide, data_segs[s], &base, &size) != 0) continue;
+ slot = slot_holding(base, size, str, uniqued);
+ }
+ if (!slot) return 0;
+ target = slot;
+ }
+
+ uintptr_t ref = xref_to_va(text_base, text_size, target,
+ anchor->nth_xref, anchor->indirect);
+ if (!ref) return 0;
+
+ if (anchor->kind == NP_MATCH_INSN_AFTER_STRING) {
+ uint32_t opcode = anchor->insn ? anchor->insn : DEFAULT_INSN;
+ uint32_t opmask = anchor->insn_mask ? anchor->insn_mask : DEFAULT_INSN_MASK;
+ int n = anchor->nth > 0 ? anchor->nth : 1;
+ return scan_for_insn(text_base, text_size, ref, opcode, opmask, n);
+ }
+
+ if (anchor->kind != NP_MATCH_STRING &&
+ anchor->kind != NP_MATCH_INSN_PAIR_IN_FN) return 0;
+
+ uintptr_t fn;
+ if (anchor->caller_hops > 0) {
+ fn = hop_to_caller(mh, slide, text_base, text_size, ref,
+ anchor->caller_hops, anchor->caller_tail);
+ if (!fn) {
+ uintptr_t body = enclosing_fn(mh, slide, text_base, ref);
+ if (body) fn = hop_to_caller(mh, slide, text_base, text_size, body,
+ anchor->caller_hops, anchor->caller_tail);
+ }
+ } else {
+ fn = enclosing_fn(mh, slide, text_base, ref);
+ }
+ if (!fn) return 0;
+
+ if (anchor->kind == NP_MATCH_INSN_PAIR_IN_FN)
+ return sole_insn_pair(fn, text_base, text_size, &anchor->pair);
+ return fn;
+}
+
+// RTTI pass: mangled type name to typeinfo to vtable
+static uintptr_t type_name_va(const struct mach_header_64 *mh, intptr_t slide,
+ const char *name) {
+ uintptr_t base;
+ size_t size;
+ if (np_find_segment(mh, slide, "__TEXT", &base, &size) != 0) return 0;
+
+ size_t len = strlen(name);
+ if (size <= len + 1) return 0;
+
+ const char *region = (const char *)base;
+ uintptr_t found = 0;
+ for (size_t off = 1; off + len < size; off++) {
+ if (region[off] != name[0]) continue;
+ if (region[off - 1] != '\0') continue;
+ if (memcmp(region + off, name, len) != 0) continue;
+ if (region[off + len] != '\0') continue;
+ if (found) return 0; // more than one hit, give up
+ found = base + off;
+ off += len;
+ }
+ return found;
+}
+
+// Subclass typeinfos point at their base, so referrers are not unique: a vtable
+// is told apart by shape. The slot below the typeinfo holds offset-to-top,
+// which is zero only for a primary vtable, and the slot above holds the first
+// virtual, which lands in code (slot 0 is often a thunk or one-instruction
+// getter). The zero check also rejects the base-class field of a derived
+// typeinfo, which sits above the name pointer.
+static uintptr_t vptr_from_typeinfo(const struct mach_header_64 *mh, intptr_t slide,
+ uintptr_t text, size_t text_sz, uintptr_t ti) {
+ uintptr_t found = 0;
+
+ for (int s = 0; s < N_DATA_SEGS; s++) {
+ uintptr_t base;
+ size_t size;
+ if (np_find_segment(mh, slide, data_segs[s], &base, &size) != 0) continue;
+ if (size < 3 * sizeof(uintptr_t)) continue;
+
+ const uintptr_t *p = (const uintptr_t *)base;
+ size_t n = size / sizeof(uintptr_t);
+ for (size_t i = 1; i + 1 < n; i++) {
+ if (p[i] != ti) continue;
+ if (p[i - 1] != 0) continue;
+ uintptr_t fn = p[i + 1];
+ if (fn < text || fn >= text + text_sz) continue;
+ if (fn & 3) continue;
+ if (found) return 0; // more than one primary vtable, give up
+ found = base + (i + 1) * sizeof(uintptr_t);
+ }
+ }
+ return found;
+}
+
+uintptr_t np_rtti_vptr(const struct mach_header_64 *mh, intptr_t slide,
+ uintptr_t text_base, size_t text_size,
+ const char *type_name) {
+ if (!mh || !type_name || !*type_name || !text_base || !text_size) return 0;
+
+ uintptr_t name = type_name_va(mh, slide, type_name);
+ if (!name) {
+ NP_WARN("rtti: no unique type name '%s'", type_name);
+ return 0;
+ }
+
+ uintptr_t found = 0;
+
+ for (int s = 0; s < N_DATA_SEGS; s++) {
+ uintptr_t base;
+ size_t size;
+ if (np_find_segment(mh, slide, data_segs[s], &base, &size) != 0) continue;
+ if (size < 2 * sizeof(uintptr_t)) continue;
+
+ const uintptr_t *p = (const uintptr_t *)base;
+ size_t n = size / sizeof(uintptr_t);
+ for (size_t i = 1; i < n; i++) {
+ if (p[i] != name) continue;
+ // The name sits at typeinfo+8, so the object starts a slot earlier.
+ uintptr_t vptr = vptr_from_typeinfo(mh, slide, text_base, text_size,
+ base + (i - 1) * sizeof(uintptr_t));
+ if (!vptr) continue;
+ if (found && found != vptr) {
+ NP_WARN("rtti: '%s' reaches more than one vtable", type_name);
+ return 0;
+ }
+ found = vptr;
+ }
+ }
+
+ if (!found) NP_WARN("rtti: no vtable for type name '%s'", type_name);
+ return found;
+}
diff --git a/dylib/resolver/anchor.h b/dylib/resolver/anchor.h
new file mode 100644
index 0000000..faa8155
--- /dev/null
+++ b/dylib/resolver/anchor.h
@@ -0,0 +1,59 @@
+// Anchor-based function resolution
+#ifndef NOTPROTON_RESOLVER_ANCHOR_H
+#define NOTPROTON_RESOLVER_ANCHOR_H
+
+#include <stdint.h>
+#include <stddef.h>
+#include <mach-o/loader.h>
+
+typedef enum {
+ NP_MATCH_NONE = 0,
+ NP_MATCH_STRING, // entry point that loads one unique C string
+ NP_MATCH_VTABLE_SLOT, // pointer parked at a fixed data address
+ NP_MATCH_INSN_AFTER_STRING, // the instruction one past the Nth chosen opcode,
+ // counting from a string load
+ NP_MATCH_INSN_PAIR_IN_FN, // the sole adjacent opcode pair inside the function
+ // a string reference identifies
+} np_match_kind_t;
+
+typedef struct {
+ uint32_t first, first_mask;
+ uint32_t second, second_mask;
+ uint32_t tie_mask;
+ int land_on_second;
+} np_insn_pair_t;
+
+typedef struct {
+ np_match_kind_t kind;
+ char str[256]; // the referenced string, for the two string kinds
+ uintptr_t va; // unslid data address of the vtable slot
+ uint32_t insn; // opcode bits to match against (0 selects BLR)
+ uint32_t insn_mask; // which opcode bits are significant (0 selects BLR)
+ int nth; // 1-based index of the wanted opcode match
+
+ int nth_xref;
+
+ np_insn_pair_t pair; // for NP_MATCH_INSN_PAIR_IN_FN
+
+ // Some functions reach their string through a pointer slot (ADRP+LDR)
+ // instead of materialising its address (ADRP+ADD). ObjC selector stubs
+ // are the most common example.
+ int indirect;
+
+ int caller_hops;
+ int caller_tail;
+} np_anchor_t;
+
+// Upper bound on a function body when scanning for a pair.
+#define NP_FN_SPAN_MAX 0x400
+
+// Resolve an anchor to a runtime address (slide applied), or 0.
+uintptr_t np_locate_anchor(const struct mach_header_64 *mh, intptr_t slide,
+ uintptr_t text_base, size_t text_size,
+ const np_anchor_t *anchor);
+
+uintptr_t np_rtti_vptr(const struct mach_header_64 *mh, intptr_t slide,
+ uintptr_t text_base, size_t text_size,
+ const char *type_name);
+
+#endif // NOTPROTON_RESOLVER_ANCHOR_H
diff --git a/dylib/resolver/aob.c b/dylib/resolver/aob.c
new file mode 100644
index 0000000..257c3db
--- /dev/null
+++ b/dylib/resolver/aob.c
@@ -0,0 +1,107 @@
+// Pattern scanner for the offline checkers. Anchorcheck uses this to cross-check what
+// the anchors resolved to.
+
+#include "aob.h"
+#include "../util/log.h"
+#include "../util/hex.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+// Pattern compilation
+
+int np_compile_pattern(const char *hex_str, np_byte_pattern_t *out) {
+ if (!hex_str || !out) return -1;
+ memset(out, 0, sizeof(*out));
+
+ size_t max_len = strlen(hex_str) / 2 + 1;
+ uint8_t *b = calloc(max_len, 1);
+ uint8_t *m = calloc(max_len, 1);
+ if (!b || !m) { free(b); free(m); return -1; }
+
+ int n = 0;
+ const char *c = hex_str;
+ while (*c) {
+ if (*c == ' ') { c++; continue; }
+ if (c[0] == '?' && c[1] == '?') {
+ b[n] = 0x00;
+ m[n] = 0x00;
+ n++; c += 2;
+ } else {
+ int hi = np_hex_val(c[0]);
+ int lo = np_hex_val(c[1]);
+ if (hi < 0 || lo < 0) { free(b); free(m); return -1; }
+ b[n] = (uint8_t)((hi << 4) | lo);
+ m[n] = 0xFF;
+ n++; c += 2;
+ }
+ }
+ if (n == 0) { free(b); free(m); return -1; }
+
+ out->bytes = b;
+ out->mask = m;
+ out->length = n;
+ return 0;
+}
+
+void np_release_pattern(np_byte_pattern_t *pat) {
+ if (!pat) return;
+ free(pat->bytes); pat->bytes = NULL;
+ free(pat->mask); pat->mask = NULL;
+ pat->length = 0;
+}
+
+// In-memory scan
+static int concrete_byte(const np_byte_pattern_t *pat, uint8_t *val) {
+ for (int k = 0; k < pat->length; k++) {
+ if (pat->mask[k] == 0xFF) {
+ *val = pat->bytes[k];
+ return k;
+ }
+ }
+ return -1;
+}
+
+static int matches_at(const uint8_t *mem, const np_byte_pattern_t *pat) {
+ const uint8_t *pb = pat->bytes, *pm = pat->mask;
+ int rem = pat->length;
+ int k = 0;
+
+ while (rem >= 4) {
+ uint32_t d, e, f;
+ memcpy(&d, mem + k, 4);
+ memcpy(&f, pm + k, 4);
+ memcpy(&e, pb + k, 4);
+ if ((d & f) != e) return 0;
+ k += 4; rem -= 4;
+ }
+ while (rem-- > 0) {
+ if ((mem[k] & pm[k]) != pb[k]) return 0;
+ k++;
+ }
+ return 1;
+}
+
+uintptr_t np_scan_sole_match(uintptr_t base, size_t size,
+ const np_byte_pattern_t *pat) {
+ if (!pat || pat->length <= 0 || (size_t)pat->length > size)
+ return 0;
+
+ uint8_t anchor;
+ int anchor_off = concrete_byte(pat, &anchor);
+ if (anchor_off < 0) return 0;
+
+ const uint8_t *region = (const uint8_t *)base;
+ size_t limit = size - (size_t)pat->length;
+ uintptr_t found = 0;
+ int hits = 0;
+
+ // Step by 4 (ARM64).
+ for (size_t pos = 0; pos <= limit; pos += 4) {
+ if (region[pos + anchor_off] != anchor) continue;
+ if (!matches_at(region + pos, pat)) continue;
+ if (++hits > 1) return 0;
+ found = base + pos;
+ }
+ return found;
+}
diff --git a/dylib/resolver/aob.h b/dylib/resolver/aob.h
new file mode 100644
index 0000000..5a1c4f5
--- /dev/null
+++ b/dylib/resolver/aob.h
@@ -0,0 +1,24 @@
+// AOB pattern scanner
+#ifndef NOTPROTON_RESOLVER_AOB_H
+#define NOTPROTON_RESOLVER_AOB_H
+
+#include <stdint.h>
+#include <stddef.h>
+
+// A compiled byte pattern with per-byte mask (0xFF = match, 0x00 = wildcard).
+typedef struct {
+ uint8_t *bytes;
+ uint8_t *mask;
+ int length;
+} np_byte_pattern_t;
+
+// Hex string like "AB ?? CD 01" into a compiled pattern.
+int np_compile_pattern(const char *hex_str, np_byte_pattern_t *out);
+
+void np_release_pattern(np_byte_pattern_t *pat);
+
+// The sole match of `pat` in `size` bytes at `base`, or 0 when zero or
+// multiple matches exist.
+uintptr_t np_scan_sole_match(uintptr_t base, size_t size, const np_byte_pattern_t *pat);
+
+#endif // NOTPROTON_RESOLVER_AOB_H
diff --git a/dylib/resolver/resolver.c b/dylib/resolver/resolver.c
new file mode 100644
index 0000000..0fe0ba7
--- /dev/null
+++ b/dylib/resolver/resolver.c
@@ -0,0 +1,128 @@
+// Signature resolver
+
+#include "resolver.h"
+#include "anchor.h"
+#include "../core/macho.h"
+#include "../util/log.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+// Prologue detection
+static const struct { uint32_t mask, val; } prologue_forms[] = {
+ { 0xFF0003FF, 0xD10003FF }, // SUB SP, SP, #imm
+ { 0xFFC07FFF, 0xA9007BFD }, // STP x29, x30, [SP, #off]
+ { 0xFFC07FFF, 0xA9807BFD }, // STP x29, x30, [SP, #off]!
+ { 0xFFFFFFFF, 0xD503237F }, // PACIBSP (sign LR)
+ { 0xFFFFFFFF, 0x910003FD }, // MOV x29, SP
+ { 0xFFC003E0, 0xA98003E0 }, // STP Xt, Xt2, [SP, #off]!
+ { 0xFFC003E0, 0xA90003E0 }, // STP Xt, Xt2, [SP, #off]
+};
+
+int np_looks_like_prologue(uintptr_t addr) {
+ if (!addr) return 0;
+ uint32_t w = *(const uint32_t *)addr;
+ for (int i = 0; i < (int)(sizeof(prologue_forms) / sizeof(prologue_forms[0])); i++) {
+ if ((w & prologue_forms[i].mask) == prologue_forms[i].val)
+ return 1;
+ }
+ return 0;
+}
+
+// Result accumulator
+static void push(np_resolve_result_t *r, const char *name, uintptr_t addr) {
+ if (r->used == r->cap) {
+ int grown = r->cap ? r->cap * 2 : 32;
+ np_resolved_t *buf = realloc(r->items, (size_t)grown * sizeof(*buf));
+ if (!buf) return;
+ r->items = buf;
+ r->cap = grown;
+ }
+ r->items[r->used++] = (np_resolved_t){ .name = name, .site = addr };
+}
+
+// Single-signature resolution
+static uintptr_t try_anchor(np_sig_entry_t *sig,
+ const struct mach_header_64 *mh, intptr_t slide,
+ uintptr_t text, size_t text_sz) {
+ if (sig->anchor.kind == NP_MATCH_NONE) return 0;
+ uintptr_t addr = np_locate_anchor(mh, slide, text, text_sz, &sig->anchor);
+ if (!addr) return 0;
+
+ NP_LOG("resolver: '%s' -> 0x%lx [anchor]", sig->name, (unsigned long)addr);
+ return addr;
+}
+
+// arm64 instructions are 4-byte aligned, so a misaligned or out-of-__TEXT
+// address cannot be a hook site.
+static int usable_code_address(const char *name, uintptr_t addr,
+ uintptr_t text, size_t text_sz) {
+ if (addr & 3u) {
+ NP_WARN("resolver: '%s' resolved to 0x%lx, not a 4-byte aligned "
+ "instruction address; rejecting", name, (unsigned long)addr);
+ return 0;
+ }
+ if (addr < text || addr > text + text_sz - sizeof(uint32_t)) {
+ NP_WARN("resolver: '%s' resolved to 0x%lx, outside __TEXT "
+ "0x%lx..0x%lx; rejecting", name, (unsigned long)addr,
+ (unsigned long)text, (unsigned long)(text + text_sz));
+ return 0;
+ }
+ return 1;
+}
+
+// Public API
+int np_resolve_signatures(const struct mach_header_64 *mh, intptr_t slide,
+ np_sigdb_t *sigdb, np_resolve_result_t *out) {
+ if (!mh || !sigdb || !out) return 0;
+ memset(out, 0, sizeof(*out));
+
+ uintptr_t text;
+ size_t text_sz;
+ if (np_find_segment(mh, slide, "__TEXT", &text, &text_sz) != 0) {
+ NP_ERR("resolver: __TEXT segment not found, cannot scan");
+ return 0;
+ }
+
+ NP_LOG("resolver: scanning __TEXT @ 0x%lx (%zu bytes) for %d signatures",
+ text, text_sz, sigdb->sig_count);
+
+ int resolved = 0;
+
+ for (int i = 0; i < sigdb->sig_count; i++) {
+ np_sig_entry_t *sig = &sigdb->signatures[i];
+
+ if (sig->deprecated) {
+ push(out, sig->name, 0);
+ continue;
+ }
+
+ uintptr_t addr = try_anchor(sig, mh, slide, text, text_sz);
+
+ if (addr && !usable_code_address(sig->name, addr, text, text_sz))
+ addr = 0;
+
+ if (addr)
+ resolved++;
+
+ push(out, sig->name, addr);
+ }
+
+ NP_LOG("resolver: %d/%d signatures resolved", resolved, sigdb->sig_count);
+ return resolved;
+}
+
+uintptr_t np_lookup_address(const np_resolve_result_t *result, const char *name) {
+ if (!result || !name) return 0;
+ for (int i = 0; i < result->used; i++) {
+ if (result->items[i].name && strcmp(result->items[i].name, name) == 0)
+ return result->items[i].site;
+ }
+ return 0;
+}
+
+void np_free_resolution(np_resolve_result_t *result) {
+ if (!result) return;
+ free(result->items);
+ memset(result, 0, sizeof(*result));
+}
diff --git a/dylib/resolver/resolver.h b/dylib/resolver/resolver.h
new file mode 100644
index 0000000..24654bf
--- /dev/null
+++ b/dylib/resolver/resolver.h
@@ -0,0 +1,31 @@
+// Signature resolver
+#ifndef NOTPROTON_RESOLVER_RESOLVER_H
+#define NOTPROTON_RESOLVER_RESOLVER_H
+
+#include <stdint.h>
+#include <stddef.h>
+#include <mach-o/loader.h>
+#include "sigdb.h"
+
+typedef struct {
+ const char *name;
+ uintptr_t site;
+} np_resolved_t;
+
+typedef struct {
+ np_resolved_t *items;
+ int used;
+ int cap;
+} np_resolve_result_t;
+
+// True when the 32-bit value at `addr` looks like a common AArch64 prologue.
+int np_looks_like_prologue(uintptr_t addr);
+
+// Resolve every signature in `sigdb` against the live image at `mh`+`slide`.
+int np_resolve_signatures(const struct mach_header_64 *mh, intptr_t slide,
+ np_sigdb_t *sigdb, np_resolve_result_t *out);
+
+uintptr_t np_lookup_address(const np_resolve_result_t *result, const char *name);
+void np_free_resolution(np_resolve_result_t *result);
+
+#endif // NOTPROTON_RESOLVER_RESOLVER_H
diff --git a/dylib/resolver/sigdb.c b/dylib/resolver/sigdb.c
new file mode 100644
index 0000000..e36fb1c
--- /dev/null
+++ b/dylib/resolver/sigdb.c
@@ -0,0 +1,199 @@
+// Signature database loader
+
+#include "sigdb.h"
+#include "../util/log.h"
+#include "../util/file.h"
+#include "../../vendor/cJSON.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+// JSON helpers
+static cJSON *read_json_file(const char *path) {
+ size_t n = 0;
+ uint8_t *raw = np_read_whole_file(path, &n);
+ if (!raw) return NULL;
+ // cJSON_ParseWithLength needs a contiguous buffer, so guarantee NUL.
+ uint8_t *buf = realloc(raw, n + 1);
+ if (!buf) { free(raw); return NULL; }
+ buf[n] = '\0';
+ cJSON *j = cJSON_Parse((char *)buf);
+ free(buf);
+ return j;
+}
+
+static void str_field(cJSON *parent, const char *key, char *dst, size_t cap) {
+ cJSON *v = cJSON_GetObjectItem(parent, key);
+ if (!v || !cJSON_IsString(v) || !v->valuestring || cap == 0) return;
+ size_t n = strlen(v->valuestring);
+ if (n >= cap) n = cap - 1;
+ memcpy(dst, v->valuestring, n);
+ dst[n] = '\0';
+}
+
+static uintptr_t hex_field(cJSON *parent, const char *key) {
+ cJSON *v = cJSON_GetObjectItem(parent, key);
+ if (!v || !cJSON_IsString(v) || !v->valuestring) return 0;
+ const char *s = v->valuestring;
+ if (s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) s += 2;
+ return (uintptr_t)strtoull(s, NULL, 16);
+}
+
+// Build IDs are uint64 but fit in a JSON double
+static uint64_t build_field(cJSON *parent, const char *key) {
+ cJSON *v = cJSON_GetObjectItem(parent, key);
+ if (!v) return 0;
+ if (cJSON_IsString(v) && v->valuestring)
+ return strtoull(v->valuestring, NULL, 10);
+ if (cJSON_IsNumber(v))
+ return (uint64_t)v->valuedouble;
+ return 0;
+}
+
+// Anchor sub-object
+static int int_field(cJSON *parent, const char *key, int fallback) {
+ cJSON *v = cJSON_GetObjectItem(parent, key);
+ return (v && cJSON_IsNumber(v)) ? v->valueint : fallback;
+}
+
+// Empty masks match every instruction, so both are required.
+static int load_insn_pair(cJSON *anchor_obj, np_insn_pair_t *p) {
+ cJSON *obj = cJSON_GetObjectItem(anchor_obj, "pair");
+ if (!obj || !cJSON_IsObject(obj)) return -1;
+
+ p->first = (uint32_t)hex_field(obj, "first");
+ p->first_mask = (uint32_t)hex_field(obj, "first_mask");
+ p->second = (uint32_t)hex_field(obj, "second");
+ p->second_mask = (uint32_t)hex_field(obj, "second_mask");
+ p->tie_mask = (uint32_t)hex_field(obj, "tie_mask");
+
+ cJSON *land = cJSON_GetObjectItem(obj, "land");
+ p->land_on_second = (land && cJSON_IsString(land) && land->valuestring &&
+ strcmp(land->valuestring, "second") == 0) ? 1 : 0;
+
+ if (!p->first_mask || !p->second_mask) return -1;
+ return 0;
+}
+
+static void load_anchor(cJSON *sig_obj, np_anchor_t *a) {
+ cJSON *obj = cJSON_GetObjectItem(sig_obj, "anchor");
+ if (!obj || !cJSON_IsObject(obj)) return;
+
+ cJSON *kind = cJSON_GetObjectItem(obj, "kind");
+ if (!kind || !cJSON_IsString(kind) || !kind->valuestring) return;
+
+ const char *ks = kind->valuestring;
+ if (strcmp(ks, "string") == 0) {
+ a->kind = NP_MATCH_STRING;
+ str_field(obj, "value", a->str, sizeof(a->str));
+ } else if (strcmp(ks, "insn_after_string") == 0) {
+ a->kind = NP_MATCH_INSN_AFTER_STRING;
+ str_field(obj, "value", a->str, sizeof(a->str));
+ a->nth = int_field(obj, "n", 1);
+ } else if (strcmp(ks, "insn_pair_in_fn") == 0) {
+ a->kind = NP_MATCH_INSN_PAIR_IN_FN;
+ str_field(obj, "value", a->str, sizeof(a->str));
+ if (load_insn_pair(obj, &a->pair) != 0) {
+ NP_WARN("sigdb: anchor '%s' has no usable pair; ignoring it", a->str);
+ a->kind = NP_MATCH_NONE;
+ return;
+ }
+ } else if (strcmp(ks, "vtable_slot") == 0) {
+ a->va = hex_field(obj, "va");
+ // A missing or unparseable va reads as zero
+ if (!a->va) {
+ NP_WARN("sigdb: vtable_slot anchor has no usable va; ignoring it");
+ a->kind = NP_MATCH_NONE;
+ return;
+ }
+ a->kind = NP_MATCH_VTABLE_SLOT;
+ return; // refinements below are string-only
+ } else {
+ return;
+ }
+
+ // A negative count silently resolves by a different route
+ int nth_xref = int_field(obj, "nth_xref", 0);
+ int caller_hops = int_field(obj, "caller_hops", 0);
+ if (nth_xref < 0 || caller_hops < 0) {
+ NP_WARN("sigdb: anchor '%s' has a negative nth_xref/caller_hops; ignoring it",
+ a->str);
+ a->kind = NP_MATCH_NONE;
+ return;
+ }
+
+ a->nth_xref = nth_xref;
+ a->caller_hops = caller_hops;
+
+ cJSON *tail = cJSON_GetObjectItem(obj, "caller_tail");
+ a->caller_tail = (tail && cJSON_IsTrue(tail)) ? 1 : 0;
+
+ // caller_tail without hops is nonsensical
+ if (a->caller_tail && !caller_hops) {
+ NP_WARN("sigdb: anchor '%s' sets caller_tail without caller_hops; ignoring it",
+ a->str);
+ a->kind = NP_MATCH_NONE;
+ return;
+ }
+
+ cJSON *ind = cJSON_GetObjectItem(obj, "indirect");
+ a->indirect = (ind && cJSON_IsTrue(ind)) ? 1 : 0;
+}
+
+// Public API
+int np_load_profile(const char *path, np_sigdb_t *out) {
+ if (!path || !out) return -1;
+ memset(out, 0, sizeof(*out));
+
+ cJSON *root = read_json_file(path);
+ if (!root) { NP_ERR("sigdb: cannot read or parse '%s'", path); return -1; }
+
+ cJSON *v;
+ if ((v = cJSON_GetObjectItem(root, "schema_version")))
+ out->schema_version = v->valueint;
+ if ((v = cJSON_GetObjectItem(root, "profile_version")))
+ out->sigdb_version = v->valueint;
+ out->steam_build = build_field(root, "steam_build");
+ str_field(root, "steam_build_date", out->steam_build_date, sizeof(out->steam_build_date));
+
+ cJSON *arr = cJSON_GetObjectItem(root, "signatures");
+ int total = (arr && cJSON_IsArray(arr)) ? cJSON_GetArraySize(arr) : 0;
+
+ if (total > 0) {
+ out->signatures = calloc((size_t)total, sizeof(np_sig_entry_t));
+ if (!out->signatures) { cJSON_Delete(root); return -1; }
+ out->sig_count = total;
+
+ cJSON *elem = NULL;
+ int i = 0;
+ cJSON_ArrayForEach(elem, arr) {
+ if (i >= total) break;
+ np_sig_entry_t *e = &out->signatures[i++];
+
+ str_field(elem, "name", e->name, sizeof(e->name));
+ str_field(elem, "aob_hex", e->aob_hex, sizeof(e->aob_hex));
+ e->func_addr_this_build = hex_field(elem, "func_addr_this_build");
+
+ if ((v = cJSON_GetObjectItem(elem, "deprecated")))
+ e->deprecated = cJSON_IsTrue(v);
+ if ((v = cJSON_GetObjectItem(elem, "match_offset")))
+ e->match_offset = (int32_t)v->valueint;
+
+ load_anchor(elem, &e->anchor);
+ }
+ }
+
+ cJSON_Delete(root);
+ NP_LOG("sigdb: loaded %d signatures from '%s' (schema=%d, profile=%d, steam_build=%llu %s)",
+ out->sig_count, path, out->schema_version, out->sigdb_version,
+ (unsigned long long)out->steam_build,
+ out->steam_build_date[0] ? out->steam_build_date : "");
+ return 0;
+}
+
+void np_free_profile(np_sigdb_t *p) {
+ if (!p) return;
+ free(p->signatures);
+ p->signatures = NULL;
+ p->sig_count = 0;
+}
diff --git a/dylib/resolver/sigdb.h b/dylib/resolver/sigdb.h
new file mode 100644
index 0000000..4958930
--- /dev/null
+++ b/dylib/resolver/sigdb.h
@@ -0,0 +1,31 @@
+// Signature database loader
+#ifndef NOTPROTON_RESOLVER_SIGDB_H
+#define NOTPROTON_RESOLVER_SIGDB_H
+
+#include <stdint.h>
+#include <stddef.h>
+#include "anchor.h"
+
+typedef struct {
+ char name[128];
+ char aob_hex[4096];
+ uintptr_t func_addr_this_build;
+ int deprecated;
+ int32_t match_offset; // signed delta from the pattern hit to the entry point
+ np_anchor_t anchor;
+} np_sig_entry_t;
+
+// A loaded signature database targeting a specific Steam client build.
+typedef struct {
+ np_sig_entry_t *signatures;
+ int sig_count;
+ int schema_version;
+ int sigdb_version;
+ uint64_t steam_build;
+ char steam_build_date[32];
+} np_sigdb_t;
+
+int np_load_profile(const char *path, np_sigdb_t *out);
+void np_free_profile(np_sigdb_t *p);
+
+#endif // NOTPROTON_RESOLVER_SIGDB_H
diff --git a/dylib/stub_x86_64.c b/dylib/stub_x86_64.c
new file mode 100644
index 0000000..6e30c6f
--- /dev/null
+++ b/dylib/stub_x86_64.c
@@ -0,0 +1 @@
+// Empty x86_64 half of the fat dylib. The Intel Steam stub maps it and finds nothing to run.
diff --git a/dylib/tests/anchorcheck.c b/dylib/tests/anchorcheck.c
new file mode 100644
index 0000000..9187084
--- /dev/null
+++ b/dylib/tests/anchorcheck.c
@@ -0,0 +1,358 @@
+// Anchor validation. Resolves every sig in every database against the loaded
+// steamclient.dylib by the same path the dylib uses, then checks each against the address
+// and bytes recorded when the database was cut. Loaded rather than on disk because dyld
+// rebases and ObjC rewrites selector slots. Other builds must land on the live addresses.
+// Usage: out/anchorcheck [path-to-sigdb.json ...]
+
+#include "../resolver/sigdb.h"
+#include "../resolver/resolver.h"
+#include "../resolver/anchor.h"
+#include "../resolver/aob.h"
+#include "../core/macho.h"
+
+#include <dirent.h>
+#include <dlfcn.h>
+#include <mach-o/dyld.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#define STEAMCLIENT \
+ "/Library/Application Support/Steam/Steam.AppBundle/Steam/Contents/MacOS/steamclient.dylib"
+#define SIGDB_DIR "signatures/macos.arm64"
+#define MAX_DBS 16
+
+// Locate the loaded image whose name ends with `suffix`.
+static const struct mach_header_64 *find_image(const char *suffix,
+ intptr_t *slide_out,
+ const char **path_out) {
+ size_t want = strlen(suffix);
+ uint32_t n = _dyld_image_count();
+ for (uint32_t i = 0; i < n; i++) {
+ const char *name = _dyld_get_image_name(i);
+ if (!name) continue;
+ size_t len = strlen(name);
+ if (len < want) continue;
+ if (strcmp(name + len - want, suffix) != 0) continue;
+ *slide_out = _dyld_get_image_vmaddr_slide(i);
+ *path_out = name;
+ return (const struct mach_header_64 *)_dyld_get_image_header(i);
+ }
+ return NULL;
+}
+
+// An independent read on the anchor result, meaningful only against the build the
+// pattern was recorded from.
+static uintptr_t resolve_by_aob(np_sig_entry_t *sig,
+ uintptr_t text, size_t text_sz) {
+ if (!sig->aob_hex[0]) return 0;
+
+ np_byte_pattern_t pat;
+ if (np_compile_pattern(sig->aob_hex, &pat) != 0) return 0;
+ uintptr_t addr = np_scan_sole_match(text, text_sz, &pat);
+ np_release_pattern(&pat);
+ if (!addr) return 0;
+
+ if (sig->match_offset) {
+ uintptr_t adj = addr - (uintptr_t)sig->match_offset;
+ if (adj < text || adj >= text + text_sz) return 0;
+ addr = adj;
+ }
+ return addr;
+}
+
+static const char *kind_name(np_match_kind_t k) {
+ switch (k) {
+ case NP_MATCH_STRING: return "string";
+ case NP_MATCH_VTABLE_SLOT: return "vtable_slot";
+ case NP_MATCH_INSN_AFTER_STRING: return "insn_after_string";
+ case NP_MATCH_INSN_PAIR_IN_FN: return "insn_pair";
+ default: return "none";
+ }
+}
+
+// Addresses are reported unslid throughout, so they can be pasted into a
+// disassembler.
+typedef struct {
+ const char *name;
+ np_match_kind_t kind;
+ uintptr_t anchor;
+ uintptr_t recorded;
+ uintptr_t aob;
+ int has_pattern;
+} row_t;
+
+typedef struct {
+ char path[512];
+ uint64_t build;
+ np_sigdb_t sigdb;
+ row_t *rows;
+ int count;
+ int unresolved;
+ int recorded_match;
+ int recorded_total;
+} dbcheck_t;
+
+// Class vptrs per client build, read off the disassembly. These address data rather than
+// code, so they are not signatures and get checked separately. The CompatManager message
+// classes arrived with 1789086785, so the older build has only the one row.
+static const struct { uint64_t build; const char *type_name; uintptr_t vptr; } expected_vptr[] = {
+ {1788400362, "14CCompatManager", 0x1715a00},
+
+ {1789086785, "14CCompatManager", 0x1743ed0},
+ {1789086785, "21CMsgCompatManagerTool", 0x16ad000},
+ {1789086785, "22CMsgCompatManagerAlias", 0x16ad0b0},
+ {1789086785, "37CCompatManager_GetCompatTools_Request", 0x16ad160},
+ {1789086785, "38CCompatManager_GetCompatTools_Response", 0x16ad210},
+ {1789086785, "40CCompatManager_SpecifyCompatTool_Request", 0x16ad2c0},
+ {1789086785, "41CCompatManager_SpecifyCompatTool_Response", 0x16ad370},
+ {1789086785, "40CCompatManager_StateChanged_Notification", 0x16ad420},
+};
+
+static int run_rtti(const struct mach_header_64 *mh, intptr_t slide,
+ uintptr_t text, size_t text_sz, uint64_t build) {
+ int ok = 0, bad = 0, checked = 0;
+
+ for (size_t i = 0; i < sizeof(expected_vptr) / sizeof(expected_vptr[0]); i++) {
+ if (expected_vptr[i].build != build) continue;
+ checked++;
+
+ const char *name = expected_vptr[i].type_name;
+ uintptr_t got = np_rtti_vptr(mh, slide, text, text_sz, name);
+ unsigned long got_u = got ? (unsigned long)(got - (uintptr_t)slide) : 0;
+ unsigned long want = (unsigned long)expected_vptr[i].vptr;
+
+ const char *verdict = !got ? "UNRESOLVED" : (got_u == want ? "OK" : "WRONG");
+ if (got && got_u == want) ok++; else bad++;
+
+ printf("%-48s vptr=0x%-9lx want=0x%-9lx %s\n", name, got_u, want, verdict);
+ }
+
+ if (!checked) {
+ printf("no vptr expectations recorded for build %llu\n", (unsigned long long)build);
+ return 0;
+ }
+ printf("\n%d vptr correct, %d incorrect (of %d)\n", ok, bad, checked);
+ return bad ? 1 : 0;
+}
+
+static int ends_with_json(const char *name) {
+ size_t n = strlen(name);
+ return n > 5 && strcmp(name + n - 5, ".json") == 0;
+}
+
+// Every database in the signature directory, sorted by name so the output runs
+// oldest build first.
+static int collect_dbs(char paths[][512], int max) {
+ DIR *dh = opendir(SIGDB_DIR);
+ if (!dh) return 0;
+
+ int n = 0;
+ struct dirent *e;
+ while ((e = readdir(dh)) != NULL && n < max) {
+ if (e->d_name[0] == '.' || !ends_with_json(e->d_name)) continue;
+ snprintf(paths[n], 512, "%s/%s", SIGDB_DIR, e->d_name);
+ n++;
+ }
+ closedir(dh);
+
+ for (int i = 1; i < n; i++) {
+ char tmp[512];
+ snprintf(tmp, sizeof(tmp), "%s", paths[i]);
+ int j = i - 1;
+ while (j >= 0 && strcmp(paths[j], tmp) > 0) {
+ snprintf(paths[j + 1], 512, "%s", paths[j]);
+ j--;
+ }
+ snprintf(paths[j + 1], 512, "%s", tmp);
+ }
+ return n;
+}
+
+// One database against the live image: what its anchors found, and what its
+// recorded evidence claims.
+static int check_db(dbcheck_t *db, const struct mach_header_64 *mh, intptr_t slide,
+ uintptr_t text, size_t text_sz) {
+ if (np_load_profile(db->path, &db->sigdb) != 0) {
+ fprintf(stderr, "cannot load sigdb '%s'\n", db->path);
+ return -1;
+ }
+ db->build = db->sigdb.steam_build;
+ db->count = db->sigdb.sig_count;
+ db->rows = calloc((size_t)db->count, sizeof(row_t));
+ if (!db->rows) { fprintf(stderr, "out of memory\n"); return -1; }
+
+ for (int i = 0; i < db->count; i++) {
+ np_sig_entry_t *sig = &db->sigdb.signatures[i];
+ row_t *r = &db->rows[i];
+
+ r->name = sig->name;
+ r->kind = sig->anchor.kind;
+ r->recorded = sig->func_addr_this_build;
+ r->has_pattern = sig->aob_hex[0] != '\0';
+
+ uintptr_t anc = (sig->anchor.kind == NP_MATCH_NONE)
+ ? 0
+ : np_locate_anchor(mh, slide, text, text_sz, &sig->anchor);
+ uintptr_t aob = resolve_by_aob(sig, text, text_sz);
+
+ r->anchor = anc ? anc - (uintptr_t)slide : 0;
+ r->aob = aob ? aob - (uintptr_t)slide : 0;
+
+ if (!r->anchor) db->unresolved++;
+ if (r->recorded) {
+ db->recorded_total++;
+ if (r->anchor == r->recorded) db->recorded_match++;
+ }
+ }
+ return 0;
+}
+
+// The database whose recorded addresses the anchors actually landed on describes
+// the running client. Nothing in the app bundle reports the client build, so it
+// has to be recognised rather than read.
+static int pick_live(const dbcheck_t *dbs, int n) {
+ int best = -1, best_hits = 0;
+ for (int i = 0; i < n; i++) {
+ if (dbs[i].recorded_match > best_hits) {
+ best_hits = dbs[i].recorded_match;
+ best = i;
+ }
+ }
+ return best_hits ? best : -1;
+}
+
+static int report_db(const dbcheck_t *db, int is_live) {
+ int bad = 0;
+
+ printf("%s build %llu%s\n", db->path, (unsigned long long)db->build,
+ is_live ? " [live client]" : "");
+
+ for (int i = 0; i < db->count; i++) {
+ const row_t *r = &db->rows[i];
+ const char *verdict;
+
+ if (r->kind == NP_MATCH_NONE) { verdict = "NO ANCHOR"; bad++; }
+ else if (!r->anchor) { verdict = "ANCHOR FAILED"; bad++; }
+ // A pattern from another build landing somewhere else is the hazard that
+ // keeps patterns out of the resolver, so it is worth seeing. Not a failure:
+ // nothing resolves from it.
+ else if (!is_live) { verdict = (r->has_pattern && r->aob && r->aob != r->anchor)
+ ? "stale pattern hit elsewhere"
+ : "resolved"; }
+ else if (r->recorded && r->anchor != r->recorded) {
+ verdict = "WRONG"; bad++; }
+ else if (!r->recorded) { verdict = "no recorded address"; }
+ else if (r->has_pattern && r->aob != r->anchor) {
+ verdict = "AOB DISAGREES"; bad++; }
+ else { verdict = "OK"; }
+
+ printf(" %-56s %-13s anchor=0x%-8lx recorded=0x%-8lx aob=0x%-8lx %s\n",
+ r->name, kind_name(r->kind), (unsigned long)r->anchor,
+ (unsigned long)r->recorded, (unsigned long)r->aob, verdict);
+ }
+
+ printf(" %d anchors resolved, %d unresolved", db->count - db->unresolved, db->unresolved);
+ if (is_live)
+ printf("; %d of %d recorded addresses matched\n", db->recorded_match, db->recorded_total);
+ else
+ printf("; recorded addresses and patterns describe another build\n");
+ printf("\n");
+ return bad;
+}
+
+// An anchor that finds a different function depending on which database it was
+// read from would make the resolution order matter, and the dylib loads only one.
+static int report_cross_db(const dbcheck_t *dbs, int n) {
+ int bad = 0;
+ for (int i = 0; i < n; i++) {
+ for (int r = 0; r < dbs[i].count; r++) {
+ const row_t *a = &dbs[i].rows[r];
+ if (!a->anchor) continue;
+
+ for (int j = i + 1; j < n; j++) {
+ for (int s = 0; s < dbs[j].count; s++) {
+ const row_t *b = &dbs[j].rows[s];
+ if (strcmp(a->name, b->name) != 0 || !b->anchor) continue;
+ if (a->anchor == b->anchor) continue;
+
+ printf("CROSS-DB DISAGREEMENT %-40s %llu=0x%lx %llu=0x%lx\n",
+ a->name, (unsigned long long)dbs[i].build,
+ (unsigned long)a->anchor,
+ (unsigned long long)dbs[j].build,
+ (unsigned long)b->anchor);
+ bad++;
+ }
+ }
+ }
+ }
+ if (bad) printf("\n");
+ return bad;
+}
+
+// Exit 1 is a database with problems, 2 one that could not be read, 3 this machine being
+// unable to answer. Callers feeding deliberately broken databases need those apart: a
+// rejected database is a result, an unloadable client image means nothing was checked.
+int main(int argc, char **argv) {
+ const char *home = getenv("HOME");
+ if (!home) { fprintf(stderr, "HOME unset\n"); return 3; }
+
+ char dylib[1024];
+ snprintf(dylib, sizeof(dylib), "%s%s", home, STEAMCLIENT);
+
+ void *handle = dlopen(dylib, RTLD_LAZY | RTLD_LOCAL);
+ if (!handle) {
+ fprintf(stderr, "dlopen failed: %s\n", dlerror());
+ return 3;
+ }
+
+ intptr_t slide = 0;
+ const char *loaded_path = NULL;
+ const struct mach_header_64 *mh =
+ find_image("/steamclient.dylib", &slide, &loaded_path);
+ if (!mh) { fprintf(stderr, "steamclient image not found after dlopen\n"); return 3; }
+
+ uintptr_t text;
+ size_t text_sz;
+ if (np_find_segment(mh, slide, "__TEXT", &text, &text_sz) != 0) {
+ fprintf(stderr, "__TEXT not found\n");
+ return 3;
+ }
+
+ printf("image : %s\n", loaded_path);
+ printf("slide : 0x%lx\n", (unsigned long)slide);
+ printf("__TEXT : 0x%lx (%zu bytes)\n\n", text, text_sz);
+
+ char paths[MAX_DBS][512];
+ int n = 0;
+ for (int i = 1; i < argc && n < MAX_DBS; i++)
+ snprintf(paths[n++], 512, "%s", argv[i]);
+ if (!n) n = collect_dbs(paths, MAX_DBS);
+ if (!n) { fprintf(stderr, "no signature databases in %s\n", SIGDB_DIR); return 3; }
+
+ dbcheck_t dbs[MAX_DBS] = {0};
+ for (int i = 0; i < n; i++) {
+ snprintf(dbs[i].path, sizeof(dbs[i].path), "%s", paths[i]);
+ if (check_db(&dbs[i], mh, slide, text, text_sz) != 0) return 2;
+ }
+
+ int live = pick_live(dbs, n);
+
+ int bad = 0;
+ for (int i = 0; i < n; i++) bad += report_db(&dbs[i], i == live);
+ bad += report_cross_db(dbs, n);
+
+ if (live < 0) {
+ printf("no database describes the running client, so only the anchors were "
+ "checked. Anchors are what the dylib resolves from, so this is not a "
+ "failure.\n");
+ } else {
+ bad += run_rtti(mh, slide, text, text_sz, dbs[live].build);
+ }
+
+ for (int i = 0; i < n; i++) {
+ free(dbs[i].rows);
+ np_free_profile(&dbs[i].sigdb);
+ }
+ return bad ? 1 : 0;
+}
diff --git a/dylib/tests/compatcheck.c b/dylib/tests/compatcheck.c
new file mode 100644
index 0000000..c44427e
--- /dev/null
+++ b/dylib/tests/compatcheck.c
@@ -0,0 +1,284 @@
+// The layout probes read instruction words straight out of the client, and everything else
+// reaches it through a function pointer an installer sets. Including the unit rather than
+// linking points the probes at synthesised instructions and the pointers at stubs. No Steam.
+#include "../feats/compat.c"
+
+#include <stdio.h>
+
+// Silent, because half of these checks drive paths whose whole job is to refuse and log.
+int np_log_level = -1;
+FILE *np_log_file = NULL;
+
+int np_log_first_hit(const void *anchor, unsigned long tag) {
+ (void)anchor; (void)tag;
+ return 1;
+}
+
+const char *np_home_dir(void) {
+ return "/nonexistent";
+}
+
+static int failures;
+
+static void check(int ok, const char *what) {
+ if (!ok) {
+ printf("FAIL %s\n", what);
+ failures++;
+ }
+}
+
+// A64 encodings the probes look for.
+#define NOP 0xD503201Fu
+static uint32_t ldr32_x0(uint32_t off, uint32_t rt) { return 0xB9400000u | ((off / 4u) << 10) | rt; }
+static uint32_t ldr64(uint32_t base, uint32_t off, uint32_t rt) {
+ return 0xF9400000u | ((off / 8u) << 10) | (base << 5) | rt;
+}
+static uint32_t ldrb(uint32_t base, uint32_t off, uint32_t rt) {
+ return 0x39400000u | (off << 10) | (base << 5) | rt;
+}
+static uint32_t mov_x0(uint32_t rd) { return 0xAA0003E0u | rd; }
+static uint32_t cbz(int32_t words, uint32_t rt) {
+ return 0x34000000u | (((uint32_t)words & 0x7FFFFu) << 5) | rt;
+}
+
+// The gate the probe is handed: the appid load, a branch past it, and the install load
+// the branch lands near. Laid out in a fresh buffer so one case cannot feed the next.
+#define CODE_WORDS 64
+#define GATE_IDX 32
+static uint32_t code[CODE_WORDS];
+
+static uintptr_t build_gate(uint32_t appid_off, uint32_t install_off) {
+ for (int i = 0; i < CODE_WORDS; i++) code[i] = NOP;
+ code[GATE_IDX] = ldr32_x0(appid_off, 3);
+ code[GATE_IDX + 1] = cbz(4, 3); // lands on GATE_IDX + 5
+ code[GATE_IDX + 5] = ldr64(0, install_off, 4);
+ return (uintptr_t)&code[GATE_IDX];
+}
+
+// The far-end corroboration: two loads through x21 inside the window the probe scans.
+static uint32_t oslist_code[CODE_WORDS];
+
+static uintptr_t build_oslist(uint32_t from_off, uint32_t to_off) {
+ for (int i = 0; i < CODE_WORDS; i++) oslist_code[i] = NOP;
+ oslist_code[GATE_IDX] = ldr64(21, from_off, 1);
+ oslist_code[GATE_IDX + 1] = ldr64(21, to_off, 2);
+ return (uintptr_t)&oslist_code[GATE_IDX];
+}
+
+static void probe_cases(void) {
+ g_tool_shift = 0;
+ check(np_compat_probe_tool_layout(build_gate(0x60, 0x58), 0) == 1,
+ "the reference layout probes clean");
+ check(g_tool_shift == 0, "the reference layout reports no shift");
+ check(np_compat_tool_stride() == COMPAT_TOOL_STRIDE, "an unshifted entry keeps its stride");
+
+ g_tool_shift = 0;
+ check(np_compat_probe_tool_layout(build_gate(0x68, 0x60), 0) == 1,
+ "a client that grew the entry by 8 probes clean");
+ check(np_compat_tool_off(COMPAT_TOOL_APPID_OFF) == 0x68, "appid follows the shift");
+ check(np_compat_tool_off(COMPAT_TOOL_INSTALL_OFF) == 0x60, "install follows the shift");
+ check(np_compat_tool_off(COMPAT_TOOL_GATE_FLAGS_OFF) == COMPAT_TOOL_GATE_FLAGS_OFF,
+ "a field ahead of the insertion point does not follow the shift");
+ check(np_compat_tool_stride() == COMPAT_TOOL_STRIDE + 8, "the entry widens by what it moved");
+
+ // A shift already established has to survive a probe that cannot agree with itself,
+ // because a half-written layout is worse than the one being replaced.
+ g_tool_shift = 8;
+ check(np_compat_probe_tool_layout(build_gate(0x68, 0x58), 0) == 0,
+ "appid and install disagreeing about the shift is refused");
+ check(g_tool_shift == 8, "a refused probe leaves the shift alone");
+
+ g_tool_shift = 0;
+ check(np_compat_probe_tool_layout(0, 0) == 0, "no gate is refused");
+
+ for (int i = 0; i < CODE_WORDS; i++) code[i] = NOP;
+ check(np_compat_probe_tool_layout((uintptr_t)&code[GATE_IDX], 0) == 0,
+ "a gate that is not the appid load is refused");
+
+ uintptr_t gate = build_gate(0x60, 0x58);
+ code[GATE_IDX + 1] = NOP;
+ check(np_compat_probe_tool_layout(gate, 0) == 0, "an appid load with no branch after it is refused");
+
+ gate = build_gate(0x60, 0x58);
+ code[GATE_IDX + 5] = NOP;
+ check(np_compat_probe_tool_layout(gate, 0) == 0, "a branch landing on no install load is refused");
+}
+
+static void oslist_cases(void) {
+ g_tool_shift = 0;
+ check(np_compat_probe_tool_layout(build_gate(0x68, 0x60), build_oslist(0x78, 0x80)) == 1,
+ "the far end agreeing on the shift probes clean");
+ check(g_tool_shift == 8, "agreement at both ends keeps the shift");
+
+ g_tool_shift = 0;
+ check(np_compat_probe_tool_layout(build_gate(0x68, 0x60), build_oslist(0x70, 0x78)) == 0,
+ "the near fields moving and the oslist not is refused");
+ check(g_tool_shift == 0, "a far-end disagreement writes no shift");
+
+ // Whichever order the comparison loads them in, the higher offset is to_oslist.
+ g_tool_shift = 0;
+ check(np_compat_probe_tool_layout(build_gate(0x68, 0x60), build_oslist(0x80, 0x78)) == 1,
+ "the oslist pair is read by offset rather than by load order");
+}
+
+static void enabled_cases(void) {
+ g_enabled_off = COMPAT_MANAGER_ENABLED_OFF;
+
+ for (int i = 0; i < CODE_WORDS; i++) code[i] = NOP;
+ code[0] = mov_x0(21);
+ code[1] = ldrb(21, 0x7C0, 8);
+ check(np_compat_probe_enabled_off((uintptr_t)code) == 1, "the enabled flag probes clean");
+ check(np_compat_enabled_off() == 0x7C0, "the probed flag offset is what gets reported");
+
+ g_enabled_off = COMPAT_MANAGER_ENABLED_OFF;
+ for (int i = 0; i < CODE_WORDS; i++) code[i] = NOP;
+ code[0] = mov_x0(21);
+ code[1] = ldrb(21, 0x20, 8);
+ check(np_compat_probe_enabled_off((uintptr_t)code) == 0,
+ "a byte read too early in the object is not taken for the flag");
+ check(np_compat_enabled_off() == COMPAT_MANAGER_ENABLED_OFF,
+ "a refused flag probe leaves the baseline in place");
+
+ for (int i = 0; i < CODE_WORDS; i++) code[i] = NOP;
+ code[0] = ldrb(21, 0x7C0, 8);
+ check(np_compat_probe_enabled_off((uintptr_t)code) == 0,
+ "a body that never parks this in a register is refused");
+
+ check(np_compat_probe_enabled_off(0) == 0, "no function is refused");
+}
+
+// A manager holding `count` entries, the one at `named_slot` carrying the tool name.
+static uint8_t manager[0x400];
+static uint8_t entries[8 * (COMPAT_TOOL_STRIDE + 64)];
+
+static void *build_manager(uint32_t count, int named_slot) {
+ memset(manager, 0, sizeof manager);
+ memset(entries, 0, sizeof entries);
+ *(uint8_t **)(manager + COMPAT_MANAGER_TOOL_ARRAY_OFF) = entries;
+ *(uint32_t *)(manager + COMPAT_MANAGER_TOOL_COUNT_OFF) = count;
+ if (named_slot >= 0) {
+ uint8_t *entry = entries + (size_t)named_slot * np_compat_tool_stride();
+ *(const char **)(entry + COMPAT_TOOL_NAME_OFF) = TOOL_DIR_NAME;
+ }
+ return manager;
+}
+
+static void manager_cases(void) {
+ g_tool_shift = 0;
+
+ void *mgr = build_manager(3, 1);
+ void *want = entries + np_compat_tool_stride();
+ check(np_compat_registered_tool(mgr) == want, "the entry registered under the tool name is found");
+
+ check(np_compat_registered_tool(build_manager(3, -1)) == NULL,
+ "a manager holding no entry of ours reports none");
+ check(np_compat_registered_tool(NULL) == NULL, "no manager reports no entry");
+
+ // A count this large means the offset it was read from moved, so the array it
+ // describes is not one to walk.
+ check(np_compat_registered_tool(build_manager(COMPAT_MANAGER_TOOLS_MAX + 1, 1)) == NULL,
+ "a count past the cap is refused rather than walked");
+ check(np_compat_registered_tool(build_manager(COMPAT_MANAGER_TOOLS_MAX, -1)) == NULL,
+ "a count at the cap is still walked");
+
+ mgr = build_manager(3, 1);
+ *(uint8_t **)((uint8_t *)mgr + COMPAT_MANAGER_TOOL_ARRAY_OFF) = NULL;
+ check(np_compat_registered_tool(mgr) == NULL, "a manager with no array is refused");
+
+ // The walk steps by the live stride, so an entry that grew is still found.
+ g_tool_shift = 8;
+ mgr = build_manager(3, 2);
+ check(np_compat_registered_tool(mgr) == entries + 2 * np_compat_tool_stride(),
+ "the walk steps by the live stride rather than the baseline");
+ g_tool_shift = 0;
+}
+
+static uint32_t stub_platforms_value;
+static uint32_t stub_platforms(void *mgr, uint32_t appid) {
+ (void)mgr; (void)appid;
+ return stub_platforms_value;
+}
+
+static const char *stub_mapping_entry[3];
+static void *stub_find_mapping(void *mgr, uint32_t appid) {
+ (void)mgr; (void)appid;
+ return stub_mapping_entry;
+}
+
+static uint32_t last_priority;
+static uint32_t last_appid;
+static void stub_set_mapping(void *mgr, uint32_t appid, const char *tool_name,
+ const char *config, uint32_t priority) {
+ (void)mgr; (void)tool_name; (void)config;
+ last_appid = appid;
+ last_priority = priority;
+}
+
+static void installed_fn_cases(void) {
+ // Nothing installed is the state before the client has given the function up, and
+ // every one of these reads as "cannot say" rather than as an answer.
+ g_get_valid_platforms = NULL;
+ g_find_mapping = NULL;
+ check(np_compat_valid_platforms(manager, 7) == 0, "no platforms function reports no platform");
+ check(np_compat_would_force(manager, 7) == false, "no platforms function forces nothing");
+ check(np_compat_app_mapping(manager, 7) == NULL, "no mapping function reports no mapping");
+
+ np_compat_set_valid_platforms_fn((uintptr_t)stub_platforms);
+ stub_platforms_value = COMPAT_PLATFORM_WINDOWS;
+ check(np_compat_would_force(manager, 7), "a windows-only app takes the default");
+
+ stub_platforms_value = COMPAT_PLATFORM_WINDOWS | COMPAT_PLATFORM_MACOS;
+ check(!np_compat_would_force(manager, 7), "an app with a macOS build is left alone");
+
+ stub_platforms_value = COMPAT_PLATFORM_MACOS;
+ check(!np_compat_would_force(manager, 7), "a macOS-only app is left alone");
+
+ stub_platforms_value = COMPAT_PLATFORM_WINDOWS;
+ check(!np_compat_would_force(manager, 0), "appid zero is not an app to force");
+ check(np_compat_valid_platforms(NULL, 7) == 0, "no manager reports no platform");
+
+ np_compat_set_app_mapping_fn((uintptr_t)stub_find_mapping);
+ stub_mapping_entry[0] = "notproton";
+ check(np_compat_app_mapping(manager, 7) != NULL, "a mapped app reports its entry");
+ check(strcmp(np_compat_app_mapping(manager, 7), "notproton") == 0,
+ "the name in the entry is what comes back");
+ check(np_compat_app_mapping(manager, 0) == NULL,
+ "appid zero is refused rather than reaching the global entry");
+
+ // An entry naming nothing is how the client holds an app that was taken off tools.
+ stub_mapping_entry[0] = "";
+ check(np_compat_app_mapping(manager, 7) == NULL, "an empty name reports no mapping");
+ stub_mapping_entry[0] = NULL;
+ check(np_compat_app_mapping(manager, 7) == NULL, "an entry naming nothing reports no mapping");
+
+ np_compat_set_mapping_fn((uintptr_t)stub_set_mapping);
+ last_priority = 0;
+ np_compat_map_tool(manager, 7, "notproton");
+ check(last_appid == 7 && last_priority == COMPAT_MAPPING_PRIORITY_APP,
+ "an app mapping outranks the global one");
+
+ last_priority = 0;
+ np_compat_map_tool(manager, 0, "notproton");
+ check(last_appid == 0 && last_priority == COMPAT_MAPPING_PRIORITY_GLOBAL,
+ "the global mapping stays under the threshold that skips the platform check");
+
+ last_priority = 0;
+ np_compat_map_tool(manager, 7, NULL);
+ check(last_priority == 0, "mapping an app to no tool at all reaches the client as nothing");
+}
+
+int main(void) {
+ probe_cases();
+ oslist_cases();
+ enabled_cases();
+ manager_cases();
+ installed_fn_cases();
+
+ if (failures) {
+ printf("==> compat: %d check(s) failed\n", failures);
+ return 1;
+ }
+ printf("==> compat: layout probes hold, the tool array walk is bounded, "
+ "installed functions answer\n");
+ return 0;
+}
diff --git a/dylib/tests/compatsvc-check.c b/dylib/tests/compatsvc-check.c
new file mode 100644
index 0000000..4090e68
--- /dev/null
+++ b/dylib/tests/compatsvc-check.c
@@ -0,0 +1,725 @@
+// The compat service builds the protobuf replies the page draws its dropdown from.
+// Including the unit reaches the two static handlers, and stubbing the compat layer below
+// them sets up manager state without a live client. The reply bytes are decoded back here.
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <stdbool.h>
+#include <mach-o/loader.h>
+
+// Stubs for the compat layer, set by each test before calling a handler. The check owns
+// both sides, so what the handler includes and labels is under test, not the compat answers.
+
+static uint8_t fake_manager[0x800];
+static uint8_t fake_entries[8 * 0x200];
+static int32_t stub_tool_shift;
+static uint32_t stub_enabled_off_val;
+static uint32_t stub_platforms_val;
+static int stub_would_force_val;
+static const char *stub_tool_for_app_name;
+static const char *stub_chosen_tool_name;
+static const char *stub_app_mapping_val;
+static const char *stub_wildcard_val;
+static void *stub_registered_tool_val;
+static uint32_t last_map_appid;
+static const char *last_map_tool;
+
+void *np_compat_manager(void) { return fake_manager; }
+
+uint32_t np_compat_tool_off(uint32_t ref) {
+ if (ref < 0x58) return ref;
+ return (uint32_t)((int32_t)ref + stub_tool_shift);
+}
+
+size_t np_compat_tool_stride(void) { return 0x130 + stub_tool_shift; }
+
+uint32_t np_compat_enabled_off(void) { return stub_enabled_off_val; }
+
+uint32_t np_compat_valid_platforms(void *mgr, uint32_t appid) {
+ (void)mgr; (void)appid;
+ return stub_platforms_val;
+}
+
+bool np_compat_would_force(void *mgr, uint32_t appid) {
+ (void)mgr; (void)appid;
+ return stub_would_force_val;
+}
+
+static uint8_t stub_tool_for_app_entry[0x200];
+void *np_compat_tool_for_app(void *mgr, uint32_t appid) {
+ (void)mgr; (void)appid;
+ if (!stub_tool_for_app_name) return NULL;
+ memset(stub_tool_for_app_entry, 0, sizeof stub_tool_for_app_entry);
+ *(const char **)(stub_tool_for_app_entry + 0x40) = stub_tool_for_app_name;
+ return stub_tool_for_app_entry;
+}
+
+static uint8_t stub_chosen_entry[0x200];
+void *np_compat_chosen_tool(void *mgr, uint32_t appid) {
+ (void)mgr; (void)appid;
+ if (!stub_chosen_tool_name) return NULL;
+ memset(stub_chosen_entry, 0, sizeof stub_chosen_entry);
+ *(const char **)(stub_chosen_entry + 0x40) = stub_chosen_tool_name;
+ return stub_chosen_entry;
+}
+
+const char *np_compat_app_mapping(void *mgr, uint32_t appid) {
+ (void)mgr; (void)appid;
+ return stub_app_mapping_val;
+}
+
+const char *np_compat_wildcard_mapping(void *mgr, uint32_t appid) {
+ (void)mgr; (void)appid;
+ return stub_wildcard_val;
+}
+
+void *np_compat_registered_tool(void *mgr) {
+ (void)mgr;
+ return stub_registered_tool_val;
+}
+
+void np_compat_map_tool(void *mgr, uint32_t appid, const char *name) {
+ (void)mgr;
+ last_map_appid = appid;
+ last_map_tool = name;
+}
+
+void np_compat_force_enable(void *mgr) { (void)mgr; }
+
+const char *np_compat_tool_dir(void) { return "/fake/tool"; }
+const char *np_compat_tool_commandline(void) { return "/fake/run %verb%"; }
+
+// Stubs for the webui layer. np_webui_parse_into captures the protobuf bytes so the
+// test can decode them.
+static uint8_t captured_pb[8192];
+static uint32_t captured_pb_len;
+static int parse_into_ok = 1;
+
+int np_webui_parse_into(uintptr_t message, const void *bytes, uint32_t len) {
+ (void)message;
+ if (len <= sizeof captured_pb) {
+ memcpy(captured_pb, bytes, len);
+ captured_pb_len = len;
+ }
+ return parse_into_ok;
+}
+
+uintptr_t np_webui_registry(void) { return 1; }
+
+int np_webui_register_route(const char *name, uintptr_t req, uintptr_t resp,
+ int (*handler)(uintptr_t, uintptr_t)) {
+ (void)name; (void)req; (void)resp; (void)handler;
+ return 1;
+}
+
+int np_webui_notify(const char *name, uintptr_t message) {
+ (void)name; (void)message;
+ return 1;
+}
+
+uintptr_t np_webui_new_message(uintptr_t vptr) {
+ (void)vptr;
+ return 1;
+}
+
+// A client that does not carry a message type reads as a vptr of 0. Naming a substring
+// here is how a test spells "this build has no such type".
+static const char *stub_absent_type;
+
+uintptr_t np_rtti_vptr(const struct mach_header_64 *mh, intptr_t slide,
+ uintptr_t text_base, size_t text_size, const char *name) {
+ (void)mh; (void)slide; (void)text_base; (void)text_size;
+ if (stub_absent_type && strstr(name, stub_absent_type))
+ return 0;
+ return 1;
+}
+
+// Log stubs.
+int np_log_level = -1;
+FILE *np_log_file = NULL;
+
+int np_log_first_hit(const void *anchor, unsigned long tag) {
+ (void)anchor; (void)tag;
+ return 1;
+}
+
+#include "../feats/compatsvc.c"
+
+// Minimal protobuf decoder for the captured reply. Enough to find field values.
+typedef struct {
+ const uint8_t *p;
+ const uint8_t *end;
+} pb_reader_t;
+
+static uint64_t pb_read_varint(pb_reader_t *r) {
+ uint64_t val = 0;
+ int shift = 0;
+ while (r->p < r->end) {
+ uint8_t b = *r->p++;
+ val |= (uint64_t)(b & 0x7f) << shift;
+ if (!(b & 0x80)) break;
+ shift += 7;
+ }
+ return val;
+}
+
+typedef struct {
+ uint32_t field;
+ uint32_t wire;
+ const uint8_t *bytes;
+ size_t len;
+ uint64_t varint;
+} pb_field_t;
+
+static int pb_next(pb_reader_t *r, pb_field_t *f) {
+ if (r->p >= r->end) return 0;
+ uint64_t tag = pb_read_varint(r);
+ f->field = (uint32_t)(tag >> 3);
+ f->wire = (uint32_t)(tag & 7);
+ f->bytes = NULL;
+ f->len = 0;
+ f->varint = 0;
+ if (f->wire == 0) {
+ f->varint = pb_read_varint(r);
+ } else if (f->wire == 2) {
+ f->len = (size_t)pb_read_varint(r);
+ f->bytes = r->p;
+ r->p += f->len;
+ }
+ return 1;
+}
+
+// Copy a string field into `dst` of size `dsz`, null-terminated. Returns 1 if found.
+static int pb_copy_string(const uint8_t *buf, size_t len, uint32_t field_num,
+ char *dst, size_t dsz) {
+ pb_reader_t r = { buf, buf + len };
+ pb_field_t f;
+ while (pb_next(&r, &f)) {
+ if (f.field == field_num && f.wire == 2) {
+ size_t n = f.len < dsz - 1 ? f.len : dsz - 1;
+ memcpy(dst, f.bytes, n);
+ dst[n] = '\0';
+ return 1;
+ }
+ }
+ return 0;
+}
+
+static int pb_find_bool(const uint8_t *buf, size_t len, uint32_t field_num) {
+ pb_reader_t r = { buf, buf + len };
+ pb_field_t f;
+ while (pb_next(&r, &f)) {
+ if (f.field == field_num && f.wire == 0)
+ return (int)f.varint;
+ }
+ return -1;
+}
+
+// Count tools in the reply, and collect their names / flags.
+#define MAX_TOOLS 16
+typedef struct {
+ char name[64];
+ char display[64];
+ int is_active;
+ int is_incompatible;
+} reply_tool_t;
+
+typedef struct {
+ int count;
+ reply_tool_t tools[MAX_TOOLS];
+ char selected[64];
+ char fallback[64];
+} reply_t;
+
+static void decode_reply(reply_t *out) {
+ memset(out, 0, sizeof *out);
+ pb_reader_t r = { captured_pb, captured_pb + captured_pb_len };
+ pb_field_t f;
+ while (pb_next(&r, &f)) {
+ if (f.field == RESP_TOOLS && f.wire == 2 && out->count < MAX_TOOLS) {
+ reply_tool_t *t = &out->tools[out->count];
+ pb_copy_string(f.bytes, f.len, TOOL_NAME, t->name, sizeof t->name);
+ pb_copy_string(f.bytes, f.len, TOOL_DISPLAY_NAME, t->display, sizeof t->display);
+ t->is_active = pb_find_bool(f.bytes, f.len, TOOL_IS_ACTIVE);
+ t->is_incompatible = pb_find_bool(f.bytes, f.len, TOOL_IS_INCOMPATIBLE);
+ out->count++;
+ } else if (f.field == RESP_SELECTED && f.wire == 2) {
+ size_t l = f.len; if (l >= sizeof out->selected) l = sizeof out->selected - 1;
+ memcpy(out->selected, f.bytes, l);
+ out->selected[l] = '\0';
+ } else if (f.field == RESP_DEFAULT && f.wire == 2) {
+ size_t l = f.len; if (l >= sizeof out->fallback) l = sizeof out->fallback - 1;
+ memcpy(out->fallback, f.bytes, l);
+ out->fallback[l] = '\0';
+ }
+ }
+}
+
+static int failures;
+
+static void check(int ok, const char *what) {
+ if (!ok) {
+ printf("FAIL %s\n", what);
+ failures++;
+ }
+}
+
+// Reset all stubs to a clean state.
+static void reset(void) {
+ memset(fake_manager, 0, sizeof fake_manager);
+ memset(fake_entries, 0, sizeof fake_entries);
+ stub_tool_shift = 0;
+ stub_enabled_off_val = 0x7B0;
+ stub_platforms_val = COMPAT_PLATFORM_WINDOWS;
+ stub_would_force_val = 1;
+ stub_tool_for_app_name = NULL;
+ stub_chosen_tool_name = NULL;
+ stub_app_mapping_val = NULL;
+ stub_wildcard_val = NULL;
+ stub_registered_tool_val = NULL;
+ last_map_appid = 0;
+ last_map_tool = NULL;
+ parse_into_ok = 1;
+ captured_pb_len = 0;
+ memset(captured_pb, 0, sizeof captured_pb);
+}
+
+// Build a fake manager with `count` tools, each carrying platform, priority, name, display
+// and gate flags at the matching COMPAT_TOOL_*_OFF offsets.
+typedef struct {
+ const char *name;
+ const char *display;
+ uint32_t platform;
+ int32_t priority;
+ uint32_t gate_flags;
+ uint32_t appid;
+} tool_spec_t;
+
+static void build_tools(const tool_spec_t *specs, int count) {
+ size_t stride = np_compat_tool_stride();
+ *(uint8_t **)(fake_manager + COMPAT_MANAGER_TOOL_ARRAY_OFF) = fake_entries;
+ *(uint32_t *)(fake_manager + COMPAT_MANAGER_TOOL_COUNT_OFF) = (uint32_t)count;
+ memset(fake_entries, 0, sizeof fake_entries);
+ for (int i = 0; i < count; i++) {
+ uint8_t *e = fake_entries + (size_t)i * stride;
+ *(const char **)(e + COMPAT_TOOL_NAME_OFF) = specs[i].name;
+ *(const char **)(e + COMPAT_TOOL_DISPLAY_OFF) = specs[i].display;
+ *(uint32_t *)(e + np_compat_tool_off(COMPAT_TOOL_PLATFORM_OFF)) = specs[i].platform;
+ *(int32_t *)(e + COMPAT_TOOL_PRIORITY_OFF) = specs[i].priority;
+ *(uint32_t *)(e + COMPAT_TOOL_GATE_FLAGS_OFF) = specs[i].gate_flags;
+ *(uint32_t *)(e + np_compat_tool_off(COMPAT_TOOL_APPID_OFF)) = specs[i].appid;
+ }
+}
+
+// Build a request buffer with the given has-bits and appid.
+static uint8_t request_buf[128];
+
+static uintptr_t build_request(uint32_t has_bits, uint32_t appid) {
+ memset(request_buf, 0, sizeof request_buf);
+ *(uint32_t *)(request_buf + REQ_HAS_BITS_OFF) = has_bits;
+ *(uint32_t *)(request_buf + REQ_APPID_OFF) = appid;
+ return (uintptr_t)request_buf;
+}
+
+// string_field reads a pointer at `field`, clears the arena tag, then inspects byte 23 of
+// the struct it reaches: negative means long form (first qword is a char *), non-negative
+// means short form (the bytes are the characters). Long form here, tool names are allocated.
+static uint8_t specify_string_struct[24];
+
+static uintptr_t build_specify_request(uint32_t has_bits, uint32_t appid,
+ const char *tool_name) {
+ memset(request_buf, 0, sizeof request_buf);
+ *(uint32_t *)(request_buf + REQ_HAS_BITS_OFF) = has_bits;
+ *(uint32_t *)(request_buf + SPECIFY_APPID_OFF) = appid;
+ memset(specify_string_struct, 0, sizeof specify_string_struct);
+ *(const char **)specify_string_struct = tool_name ? tool_name : "";
+ specify_string_struct[23] = 0xFF;
+ *(uintptr_t *)(request_buf + SPECIFY_TOOL_NAME_OFF) = (uintptr_t)specify_string_struct;
+ return (uintptr_t)request_buf;
+}
+
+// The response is not read by the handler, only passed to np_webui_parse_into.
+static uint8_t response_buf[64];
+
+static void offered_cases(void) {
+ reset();
+ tool_spec_t tools[] = {
+ { "crossover", "CrossOver", COMPAT_PLATFORM_WINDOWS, 100, 0, 0 },
+ };
+ build_tools(tools, 1);
+ stub_platforms_val = COMPAT_PLATFORM_WINDOWS;
+
+ int rc = get_compat_tools(build_request(REQ_HAS_APPID, 7), (uintptr_t)response_buf);
+ check(rc == RESULT_OK, "a windows-only app is answered");
+ reply_t r;
+ decode_reply(&r);
+ check(r.count == 1, "one tool that converts from windows is offered");
+ check(strcmp(r.tools[0].name, "crossover") == 0, "the offered tool is the one that converts from windows");
+
+ // A tool that converts from linux is not offered to a windows-only app.
+ reset();
+ tool_spec_t linux_tool[] = {
+ { "proton", "Proton", 0x10, 100, 0, 0 },
+ };
+ build_tools(linux_tool, 1);
+ stub_platforms_val = COMPAT_PLATFORM_WINDOWS;
+ rc = get_compat_tools(build_request(REQ_HAS_APPID, 7), (uintptr_t)response_buf);
+ check(rc == RESULT_OK, "a tool for the wrong platform is answered without error");
+ decode_reply(&r);
+ check(r.count == 0, "a tool converting from a platform the app does not ship for is not offered");
+}
+
+static void hidden_cases(void) {
+ reset();
+ tool_spec_t tools[] = {
+ { "crossover", "CrossOver", COMPAT_PLATFORM_WINDOWS, 100, COMPAT_TOOL_GATE_HIDDEN, 0 },
+ };
+ build_tools(tools, 1);
+ stub_platforms_val = COMPAT_PLATFORM_WINDOWS;
+
+ // The bypass byte sits at enabled_off + 2 in the manager.
+ fake_manager[stub_enabled_off_val + 2] = 0;
+
+ int rc = get_compat_tools(build_request(REQ_HAS_APPID, 7), (uintptr_t)response_buf);
+ reply_t r;
+ decode_reply(&r);
+ check(r.count == 0, "a hidden tool is not offered when the bypass is off");
+
+ fake_manager[stub_enabled_off_val + 2] = 1;
+ rc = get_compat_tools(build_request(REQ_HAS_APPID, 7), (uintptr_t)response_buf);
+ (void)rc;
+ decode_reply(&r);
+ check(r.count == 1, "a hidden tool is offered when the bypass is on");
+}
+
+static void is_a_tool_cases(void) {
+ reset();
+ tool_spec_t tools[] = {
+ { "crossover", "CrossOver", COMPAT_PLATFORM_WINDOWS, 100, 0, 730 },
+ };
+ build_tools(tools, 1);
+ stub_platforms_val = COMPAT_PLATFORM_WINDOWS;
+ fake_manager[stub_enabled_off_val + 2] = 0;
+
+ int rc = get_compat_tools(build_request(REQ_HAS_APPID, 730), (uintptr_t)response_buf);
+ check(rc == RESULT_IS_A_TOOL, "a tool asked about its own appid is refused rather than listed");
+
+ // The is-a-tool check is bypassed when compatibility is switched off.
+ fake_manager[stub_enabled_off_val + 2] = 1;
+ rc = get_compat_tools(build_request(REQ_HAS_APPID, 730), (uintptr_t)response_buf);
+ check(rc == RESULT_OK, "the is-a-tool check is skipped when the bypass is on");
+}
+
+static void none_entry_cases(void) {
+ reset();
+ tool_spec_t tools[] = {
+ { "crossover", "CrossOver", COMPAT_PLATFORM_WINDOWS, 100, 0, 0 },
+ };
+ build_tools(tools, 1);
+ stub_platforms_val = COMPAT_PLATFORM_WINDOWS;
+
+ // No fallback, no existing "none" mapping: the none entry does not appear.
+ stub_wildcard_val = NULL;
+ stub_would_force_val = 0;
+ stub_registered_tool_val = NULL;
+ stub_app_mapping_val = NULL;
+
+ int rc = get_compat_tools(build_request(REQ_HAS_APPID, 7), (uintptr_t)response_buf);
+ (void)rc;
+ reply_t r;
+ decode_reply(&r);
+ int has_none = 0;
+ for (int i = 0; i < r.count; i++)
+ if (strcmp(r.tools[i].name, NP_COMPAT_TOOL_NONE) == 0) has_none = 1;
+ check(!has_none, "the none entry is absent when neither fallback nor mapping names it");
+
+ // A wildcard mapping creates a fallback, so the none entry appears.
+ stub_wildcard_val = "crossover";
+ rc = get_compat_tools(build_request(REQ_HAS_APPID, 7), (uintptr_t)response_buf);
+ decode_reply(&r);
+ has_none = 0;
+ for (int i = 0; i < r.count; i++)
+ if (strcmp(r.tools[i].name, NP_COMPAT_TOOL_NONE) == 0) has_none = 1;
+ check(has_none, "the none entry appears when a wildcard mapping creates a fallback");
+
+ // An app already holding the none name keeps the entry.
+ stub_wildcard_val = NULL;
+ stub_app_mapping_val = NP_COMPAT_TOOL_NONE;
+ rc = get_compat_tools(build_request(REQ_HAS_APPID, 7), (uintptr_t)response_buf);
+ decode_reply(&r);
+ has_none = 0;
+ for (int i = 0; i < r.count; i++)
+ if (strcmp(r.tools[i].name, NP_COMPAT_TOOL_NONE) == 0) has_none = 1;
+ check(has_none, "the none entry appears when the app already holds it");
+
+ // The none entry never appears for the global scope (appid 0).
+ stub_wildcard_val = "crossover";
+ rc = get_compat_tools(build_request(0, 0), (uintptr_t)response_buf);
+ decode_reply(&r);
+ has_none = 0;
+ for (int i = 0; i < r.count; i++)
+ if (strcmp(r.tools[i].name, NP_COMPAT_TOOL_NONE) == 0) has_none = 1;
+ check(!has_none, "the none entry is absent for the global setting");
+}
+
+static void priority_cases(void) {
+ reset();
+ tool_spec_t tools[] = {
+ { "proton8", "Proton 8", COMPAT_PLATFORM_WINDOWS, 200, 0, 0 },
+ { "proton7", "Proton 7", COMPAT_PLATFORM_WINDOWS, 150, 0, 0 },
+ { "custom", "Custom", COMPAT_PLATFORM_WINDOWS, 0, 0, 0 },
+ };
+ build_tools(tools, 3);
+ stub_platforms_val = COMPAT_PLATFORM_WINDOWS;
+
+ int rc = get_compat_tools(build_request(REQ_HAS_APPID, 7), (uintptr_t)response_buf);
+ (void)rc;
+ reply_t r;
+ decode_reply(&r);
+ check(r.count == 3, "all three platform-matching tools are listed");
+
+ // The best priority is 200. proton7 at 150 should be incompatible, custom at 0 should not.
+ int p8_incompat = -1, p7_incompat = -1, custom_incompat = -1;
+ for (int i = 0; i < r.count; i++) {
+ if (strcmp(r.tools[i].name, "proton8") == 0) p8_incompat = r.tools[i].is_incompatible;
+ if (strcmp(r.tools[i].name, "proton7") == 0) p7_incompat = r.tools[i].is_incompatible;
+ if (strcmp(r.tools[i].name, "custom") == 0) custom_incompat = r.tools[i].is_incompatible;
+ }
+ check(p8_incompat == 0, "the tool with the best priority is not incompatible");
+ check(p7_incompat == 1, "a tool below the best priority is incompatible");
+ check(custom_incompat == 0, "a tool with priority zero opts out of ranking");
+}
+
+static void selected_cases(void) {
+ reset();
+ tool_spec_t tools[] = {
+ { "crossover", "CrossOver", COMPAT_PLATFORM_WINDOWS, 100, 0, 0 },
+ };
+ build_tools(tools, 1);
+ stub_platforms_val = COMPAT_PLATFORM_WINDOWS;
+
+ // A per-app query with a mapping reports the mapping as the selection.
+ stub_app_mapping_val = "crossover";
+ stub_tool_for_app_name = "crossover";
+ int rc = get_compat_tools(build_request(REQ_HAS_APPID, 7), (uintptr_t)response_buf);
+ (void)rc;
+ reply_t r;
+ decode_reply(&r);
+ check(strcmp(r.selected, "crossover") == 0, "a mapped app reports its mapping as the selection");
+
+ // No mapping reports the empty string, which is the "no choice" state.
+ stub_app_mapping_val = NULL;
+ stub_tool_for_app_name = "crossover";
+ rc = get_compat_tools(build_request(REQ_HAS_APPID, 7), (uintptr_t)response_buf);
+ decode_reply(&r);
+ check(strcmp(r.selected, "") == 0, "an unmapped app reports the empty string as the selection");
+
+ // The global query reads the chosen tool rather than the mapping.
+ stub_chosen_tool_name = "crossover";
+ rc = get_compat_tools(build_request(0, 0), (uintptr_t)response_buf);
+ decode_reply(&r);
+ check(strcmp(r.selected, "crossover") == 0, "the global setting reports the chosen tool");
+}
+
+static void fallback_cases(void) {
+ reset();
+ tool_spec_t tools[] = {
+ { "crossover", "CrossOver", COMPAT_PLATFORM_WINDOWS, 100, 0, 0 },
+ };
+ build_tools(tools, 1);
+ stub_platforms_val = COMPAT_PLATFORM_WINDOWS;
+
+ // The wildcard names a fallback directly.
+ stub_wildcard_val = "crossover";
+ int rc = get_compat_tools(build_request(REQ_HAS_APPID, 7), (uintptr_t)response_buf);
+ (void)rc;
+ reply_t r;
+ decode_reply(&r);
+ check(strcmp(r.fallback, "crossover") == 0, "the wildcard mapping names the fallback");
+
+ // No wildcard, but would_force + registered tool fills it in.
+ stub_wildcard_val = NULL;
+ stub_would_force_val = 1;
+ stub_registered_tool_val = fake_entries;
+ rc = get_compat_tools(build_request(REQ_HAS_APPID, 7), (uintptr_t)response_buf);
+ decode_reply(&r);
+ check(strcmp(r.fallback, "crossover") == 0,
+ "a forced app with no wildcard falls back to the registered tool");
+
+ // Global (appid 0) with no wildcard still falls back to the registered tool.
+ stub_wildcard_val = NULL;
+ stub_would_force_val = 0;
+ stub_registered_tool_val = fake_entries;
+ rc = get_compat_tools(build_request(0, 0), (uintptr_t)response_buf);
+ decode_reply(&r);
+ check(strcmp(r.fallback, "crossover") == 0,
+ "the global setting with no wildcard falls back to the registered tool");
+
+ // An app that would not be forced and has no wildcard gets no fallback.
+ stub_wildcard_val = NULL;
+ stub_would_force_val = 0;
+ stub_registered_tool_val = fake_entries;
+ rc = get_compat_tools(build_request(REQ_HAS_APPID, 7), (uintptr_t)response_buf);
+ decode_reply(&r);
+ check(r.fallback[0] == '\0', "an unforced app with no wildcard gets no fallback");
+}
+
+static void active_flag_cases(void) {
+ reset();
+ tool_spec_t tools[] = {
+ { "crossover", "CrossOver", COMPAT_PLATFORM_WINDOWS, 100, 0, 0 },
+ { "proton", "Proton", COMPAT_PLATFORM_WINDOWS, 200, 0, 0 },
+ };
+ build_tools(tools, 2);
+ stub_platforms_val = COMPAT_PLATFORM_WINDOWS;
+ stub_tool_for_app_name = "crossover";
+
+ int rc = get_compat_tools(build_request(REQ_HAS_APPID, 7), (uintptr_t)response_buf);
+ (void)rc;
+ reply_t r;
+ decode_reply(&r);
+ int cx_active = -1, pt_active = -1;
+ for (int i = 0; i < r.count; i++) {
+ if (strcmp(r.tools[i].name, "crossover") == 0) cx_active = r.tools[i].is_active;
+ if (strcmp(r.tools[i].name, "proton") == 0) pt_active = r.tools[i].is_active;
+ }
+ check(cx_active == 1, "the tool the app runs under is flagged active");
+ check(pt_active == 0, "a tool the app does not run under is not active");
+}
+
+static void specify_cases(void) {
+ reset();
+
+ // A request with appid and tool name maps the tool.
+ last_map_appid = 0;
+ last_map_tool = NULL;
+ int rc = specify_compat_tool(
+ build_specify_request(SPECIFY_HAS_APPID, 42, "crossover"),
+ (uintptr_t)response_buf);
+ check(rc == RESULT_OK, "a specify with a tool name succeeds");
+ check(last_map_appid == 42, "the appid from the request reaches the mapping");
+ check(last_map_tool && strcmp(last_map_tool, "crossover") == 0,
+ "the tool name from the request reaches the mapping");
+
+ // A request with no appid has-bit maps as appid zero (the global).
+ last_map_appid = 99;
+ rc = specify_compat_tool(
+ build_specify_request(0, 42, "crossover"),
+ (uintptr_t)response_buf);
+ check(rc == RESULT_OK, "a specify with no appid has-bit succeeds");
+ check(last_map_appid == 0, "a request with no appid has-bit reads as appid zero");
+}
+
+static void no_manager_cases(void) {
+ // When np_compat_manager returns NULL the handlers must cope.
+ reset();
+ parse_into_ok = 0;
+ tool_spec_t tools[] = {
+ { "crossover", "CrossOver", COMPAT_PLATFORM_WINDOWS, 100, 0, 0 },
+ };
+ build_tools(tools, 1);
+ stub_platforms_val = COMPAT_PLATFORM_WINDOWS;
+ int rc = get_compat_tools(build_request(REQ_HAS_APPID, 7), (uintptr_t)response_buf);
+ check(rc == RESULT_FAIL, "a rejected parse_into fails the whole reply");
+ parse_into_ok = 1;
+}
+
+// hook_webpatch reads these to decide whether an absent service matters, so untried has to
+// stay apart from absent: folding them puts an error on a launch where nothing is wrong.
+static void routes_state_cases(void) {
+ g_routes = NP_COMPATSVC_UNTRIED;
+ stub_absent_type = NULL;
+ check(np_compatsvc_routes() == NP_COMPATSVC_UNTRIED,
+ "no route lookup yet reads as untried rather than absent");
+
+ np_compatsvc_register(NULL, 0, 0, 0);
+ check(np_compatsvc_routes() == NP_COMPATSVC_READY,
+ "a client carrying every message type registers and reads as ready");
+
+ // The stable client: the page specifies the tool directly and the build carries no
+ // CompatManager types at all.
+ g_routes = NP_COMPATSVC_UNTRIED;
+ stub_absent_type = "CCompatManager_GetCompatTools";
+ np_compatsvc_register(NULL, 0, 0, 0);
+ check(np_compatsvc_routes() == NP_COMPATSVC_ABSENT,
+ "a client with no GetCompatTools types reads as absent");
+
+ // Half a CompatManager, which is the shape that stays an error.
+ g_routes = NP_COMPATSVC_UNTRIED;
+ stub_absent_type = "CCompatManager_SpecifyCompatTool";
+ np_compatsvc_register(NULL, 0, 0, 0);
+ check(np_compatsvc_routes() == NP_COMPATSVC_ABSENT,
+ "a client that can list but not specify reads as absent");
+
+ // Settled state is also the once-only guard, so a second lookup is not a second
+ // registration that could overwrite what the first one found.
+ stub_absent_type = NULL;
+ np_compatsvc_register(NULL, 0, 0, 0);
+ check(np_compatsvc_routes() == NP_COMPATSVC_ABSENT,
+ "a later route lookup does not re-register over a settled answer");
+
+ g_routes = NP_COMPATSVC_UNTRIED;
+ stub_absent_type = NULL;
+}
+
+static void string_field_cases(void) {
+ // string_field reads an arena-tagged pointer. Low bit set = arena, cleared before
+ // deref. A long string (byte[23] < 0) dereferences the first qword as a pointer to
+ // the characters. A short string (byte[23] >= 0) reads the characters inline.
+ static uint8_t short_str[24];
+ memcpy(short_str, "hello world", 11);
+ short_str[23] = 11;
+ uintptr_t ptr = (uintptr_t)short_str;
+
+ // Build a request whose tool name field points at this.
+ memset(request_buf, 0, sizeof request_buf);
+ *(uintptr_t *)(request_buf + SPECIFY_TOOL_NAME_OFF) = ptr;
+ const char *result = string_field((uintptr_t)(request_buf + SPECIFY_TOOL_NAME_OFF));
+ check(result != NULL, "a short string is read");
+ check(result == (const char *)short_str, "a short string reads inline from the struct");
+
+ // A long string: byte[23] negative, first qword is a pointer.
+ static char long_chars[] = "this is a longer string value";
+ static uint8_t long_str[24];
+ *(const char **)long_str = long_chars;
+ long_str[23] = (uint8_t)0xFF;
+ ptr = (uintptr_t)long_str;
+ *(uintptr_t *)(request_buf + SPECIFY_TOOL_NAME_OFF) = ptr;
+ result = string_field((uintptr_t)(request_buf + SPECIFY_TOOL_NAME_OFF));
+ check(result != NULL && strcmp(result, long_chars) == 0,
+ "a long string dereferences the first qword as the character pointer");
+
+ // Arena-tagged pointer (low bit set).
+ *(uintptr_t *)(request_buf + SPECIFY_TOOL_NAME_OFF) = ptr | 1;
+ result = string_field((uintptr_t)(request_buf + SPECIFY_TOOL_NAME_OFF));
+ check(result != NULL && strcmp(result, long_chars) == 0,
+ "the arena tag in the low bit is cleared before the deref");
+
+ // NULL string returns empty.
+ *(uintptr_t *)(request_buf + SPECIFY_TOOL_NAME_OFF) = 0;
+ result = string_field((uintptr_t)(request_buf + SPECIFY_TOOL_NAME_OFF));
+ check(result != NULL && result[0] == '\0', "a null string field returns empty");
+}
+
+int main(void) {
+ offered_cases();
+ hidden_cases();
+ is_a_tool_cases();
+ none_entry_cases();
+ priority_cases();
+ selected_cases();
+ fallback_cases();
+ active_flag_cases();
+ specify_cases();
+ no_manager_cases();
+ routes_state_cases();
+ string_field_cases();
+
+ if (failures) {
+ printf("==> compatsvc: %d check(s) failed\n", failures);
+ return 1;
+ }
+ printf("==> compatsvc: the tool list, the none entry, the priorities, the specify "
+ "handler, and the route states all answer\n");
+ return 0;
+}
diff --git a/dylib/tests/gatecheck.c b/dylib/tests/gatecheck.c
new file mode 100644
index 0000000..8c91845
--- /dev/null
+++ b/dylib/tests/gatecheck.c
@@ -0,0 +1,181 @@
+// The gate table is static, so the unit under test is included rather than
+// linked.
+#include "../feats/webpatch.c"
+
+#include <stdarg.h>
+#include <stdio.h>
+
+// Satisfies the log macros without pulling in log.c, which reaches for the
+// support directory this tool has no use for. Drift reasons land on stderr.
+int np_log_level = NP_LVL_INFO;
+FILE *np_log_file;
+
+static int g_wrong;
+
+static void wrong(const char *fmt, ...) {
+ va_list ap;
+ va_start(ap, fmt);
+ fputs("WRONG: ", stdout);
+ vprintf(fmt, ap);
+ fputc('\n', stdout);
+ va_end(ap);
+ g_wrong = 1;
+}
+
+// Invariants the transform relies on but cannot check at run time. A replacement still
+// holding its own anchor would be found again next pass, and an anchor inside another
+// anchor would make the result depend on table order rather than on the chunk.
+static void selfcheck(void) {
+ size_t total = 0;
+ for (size_t sh = 0; sh < NP_SHAPE_COUNT; sh++) {
+ const np_ui_shape_t *S = &g_shapes[sh];
+ const char *nm = S->name;
+ if (!S->probe || !*S->probe) wrong("[%s] has no probe", nm);
+ for (size_t o = 0; o < NP_SHAPE_COUNT; o++) {
+ if (o == sh) continue;
+ if (strcmp(S->probe, g_shapes[o].probe) == 0)
+ wrong("[%s] and [%s] share a probe", nm, g_shapes[o].name);
+ }
+ for (size_t i = 0; i < S->count; i++) {
+ const np_gate_t *a = &S->gates[i];
+ if (!a->find || !*a->find) wrong("[%s] gate %zu has no anchor", nm, i);
+ if (!a->replace || !*a->replace) wrong("[%s] gate %zu has no replacement", nm, i);
+ if (a->expect < 1) wrong("[%s] gate %zu expects %d hits", nm, i, a->expect);
+ if (a->find && a->replace && strcmp(a->find, a->replace) == 0)
+ wrong("[%s] gate %zu replaces its anchor with itself", nm, i);
+ if (a->find && a->replace && *a->find && strstr(a->replace, a->find))
+ wrong("[%s] gate %zu replacement still contains its own anchor", nm, i);
+ // A capture the replacement reads but the anchor never binds would
+ // expand to nothing, so the transform would refuse at run time.
+ for (const char *r = a->replace; r && *r; r++) {
+ int ci = cap_index((unsigned char)*r);
+ if (ci >= 0 && !strchr(a->find, *r))
+ wrong("[%s] gate %zu replacement reads capture %d, anchor never binds it",
+ nm, i, ci + 1);
+ }
+ for (size_t j = 0; j < S->count; j++) {
+ if (i == j || !a->find || !S->gates[j].find || !*S->gates[j].find) continue;
+ if (strstr(a->find, S->gates[j].find))
+ wrong("[%s] gate %zu anchor contains gate %zu anchor", nm, i, j);
+ }
+ }
+ total += S->count;
+ }
+ printf("%zu shapes, %zu gates checked\n", NP_SHAPE_COUNT, total);
+}
+
+static uint8_t *slurp(const char *path, size_t *len) {
+ FILE *f = fopen(path, "rb");
+ if (!f) return NULL;
+ fseek(f, 0, SEEK_END);
+ long n = ftell(f);
+ fseek(f, 0, SEEK_SET);
+ if (n < 0) { fclose(f); return NULL; }
+ uint8_t *buf = malloc((size_t)n + 1);
+ if (!buf) { fclose(f); return NULL; }
+ size_t got = fread(buf, 1, (size_t)n, f);
+ fclose(f);
+ buf[got] = 0;
+ *len = got;
+ return buf;
+}
+
+// A patched chunk has to carry every replacement, keep none of the anchors, and
+// be refused if it is fed back in, which is what stops a second read of the same
+// file from patching it twice.
+static const np_ui_shape_t *shape_of(const char *buf, size_t len) {
+ for (size_t i = 0; i < NP_SHAPE_COUNT; i++)
+ if (count_matches(buf, len, g_shapes[i].probe) > 0) return &g_shapes[i];
+ return NULL;
+}
+
+static void check_output(const char *out, size_t out_len) {
+ const np_ui_shape_t *S = shape_of(out, out_len);
+ if (!S) { wrong("the patched chunk no longer matches any known compat UI"); return; }
+ for (size_t g = 0; g < S->count; g++) {
+ if (count_matches(out, out_len, S->gates[g].find) != 0)
+ wrong("[%s] gate %zu anchor survived the patch", S->name, g);
+ if (count_matches(out, out_len, S->gates[g].replace)
+ < (size_t)S->gates[g].expect)
+ wrong("[%s] gate %zu replacement is missing from the patch", S->name, g);
+ }
+ // This pass is meant to be refused, so its drift report is not a finding.
+ size_t again_len = 0;
+ int saved = np_log_level;
+ np_log_level = -1;
+ char *again = np_webpatch_transform((const uint8_t *)out, out_len, &again_len, NULL);
+ np_log_level = saved;
+ if (again) { wrong("a patched chunk was patched a second time"); free(again); }
+}
+
+// Cuts a window around every anchor occurrence in a real chunk and joins them
+// into a fixture, so the committed bytes are Steam's rather than a restatement of
+// the table above. Run by hand when the fixture is first made or refreshed.
+static int extract(const char *chunk, const char *out_path) {
+ size_t len = 0;
+ uint8_t *buf = slurp(chunk, &len);
+ if (!buf) { fprintf(stderr, "cannot read %s\n", chunk); return 1; }
+
+ FILE *o = fopen(out_path, "wb");
+ if (!o) { fprintf(stderr, "cannot write %s\n", out_path); free(buf); return 1; }
+
+ const np_ui_shape_t *S = shape_of((const char *)buf, len);
+ if (!S) {
+ fprintf(stderr, "%s carries no known compat UI\n", chunk);
+ fclose(o); free(buf);
+ return 1;
+ }
+ // The probe goes in first so the fixture selects the same shape the chunk did.
+ fprintf(o, "%s\n", S->probe);
+
+ const size_t pad = 160;
+ np_cap_t caps[NP_CAP_MAX];
+ for (size_t g = 0; g < S->count; g++) {
+ size_t hits = 0;
+ for (size_t i = 0; i < len; ) {
+ size_t used = match_at((const char *)buf, len, i, S->gates[g].find, caps);
+ if (!used) { i++; continue; }
+ size_t from = i > pad ? i - pad : 0;
+ size_t to = i + used + pad < len ? i + used + pad : len;
+ fwrite(buf + from, 1, to - from, o);
+ fputs("\n", o);
+ hits++;
+ i += used;
+ }
+ if (hits != (size_t)S->gates[g].expect) {
+ fprintf(stderr, "[%s] gate %zu found %zu times in %s, table expects %d\n",
+ S->name, g, hits, chunk, S->gates[g].expect);
+ fclose(o); free(buf);
+ return 1;
+ }
+ }
+ fclose(o);
+ free(buf);
+ printf("extracted fixture to %s\n", out_path);
+ return 0;
+}
+
+int main(int argc, char **argv) {
+ if (argc == 4 && strcmp(argv[1], "--extract") == 0)
+ return extract(argv[2], argv[3]);
+
+ if (argc < 2) { selfcheck(); return g_wrong; }
+
+ for (int i = 1; i < argc; i++) {
+ size_t len = 0;
+ uint8_t *buf = slurp(argv[i], &len);
+ if (!buf) { wrong("cannot read %s", argv[i]); continue; }
+
+ size_t out_len = 0;
+ char *out = np_webpatch_transform(buf, len, &out_len, NULL);
+ if (out) {
+ check_output(out, out_len);
+ printf("APPLIED %s\n", argv[i]);
+ free(out);
+ } else {
+ printf("REJECTED %s\n", argv[i]);
+ }
+ free(buf);
+ }
+ return g_wrong;
+}
diff --git a/dylib/tests/panel-behavior/behavior.js b/dylib/tests/panel-behavior/behavior.js
new file mode 100644
index 0000000..53d9973
--- /dev/null
+++ b/dylib/tests/panel-behavior/behavior.js
@@ -0,0 +1,87 @@
+// What the panel renders, checked against both forms of the one payload.
+'use strict';
+const { panel, walk, details, runner, FORMS } = require('./harness');
+
+const emit = process.argv[2];
+if (!emit) { console.error('usage: behavior.js <emit>'); process.exit(2); }
+
+let failed = 0;
+for (const form of Object.keys(FORMS)) {
+ const { render: P, written } = panel(emit, form);
+ const t = runner(form);
+ const nodes = opts => walk(P({ details: details(opts) }));
+ const toggles = ns => ns.filter(x => x.type === 'Toggle').map(x => x.props.label);
+ const sections = ns => ns.filter(x => x.type === 'Section').map(x => x.props.label.split(' ')[0]);
+ const last = () => (written.length ? written[written.length - 1].opts : '');
+
+ t.ok(P({ details: details('', { vecPlatforms: ['osx'], strCompatToolName: '' }) }) === null,
+ 'a mac build with nothing pinned renders no panel');
+
+ let r = nodes('');
+ t.ok(toggles(r).length === 5 && sections(r).length === 2, 'automatic shows five toggles in two sections');
+ t.ok(r.filter(x => x.type === 'Dropdown').length === 2, 'two dropdowns');
+ t.ok(!('label' in r.find(x => x.type === 'Dropdown').props), 'the backend dropdown carries no label column');
+
+ r = nodes('CX_GRAPHICS_BACKEND=dxmt');
+ t.ok(toggles(r).filter(l => l === 'DLSS').length === 1 && sections(r).includes('MetalFX'),
+ 'dxmt keeps one DLSS and keeps MetalFX');
+ r = nodes('CX_GRAPHICS_BACKEND=d3dmetal');
+ t.ok(toggles(r).filter(l => l === 'DLSS').length === 1 && !sections(r).includes('MetalFX'),
+ 'd3dmetal keeps one DLSS and hides MetalFX');
+ // Both flags are labeled DLSS, so a backend showing its own and its neighbor's
+ // would put the same word on two rows.
+ for (const b of ['', 'd3dmetal', 'dxmt', 'dxvk', 'wined3d']) {
+ const ls = toggles(nodes(b ? 'CX_GRAPHICS_BACKEND=' + b : ''));
+ t.ok(ls.filter(l => l === 'DLSS').length === (b === 'dxvk' || b === 'wined3d' ? 0 : 1),
+ `${b || 'automatic'} shows DLSS at most once (${ls.join(',')})`);
+ }
+ // The row that writes the flag the chosen backend actually reads.
+ const dlss = (b, key) => {
+ written.length = 0;
+ nodes('CX_GRAPHICS_BACKEND=' + b).find(x => x.props.label === 'DLSS').props.onChange(true);
+ t.ok(last().includes(key + '=1'), `${b} DLSS writes ${key} (${last()})`);
+ };
+ dlss('d3dmetal', 'D3DM_ENABLE_METALFX');
+ dlss('dxmt', 'DXMT_ENABLE_NVEXT');
+ t.ok(nodes('CX_GRAPHICS_BACKEND=dxmt DXMT_ENABLE_NVEXT=1')
+ .find(x => x.props.label === 'DLSS').props.checked === true,
+ 'the dxmt DLSS toggle reads as on from its argument');
+
+ t.ok(nodes('CX_GRAPHICS_BACKEND=dxmt').find(x => x.type === 'Dropdown').props.selectedOption === 'dxmt',
+ 'the backend dropdown reflects the current value');
+ t.ok(nodes('MTL_HUD_ENABLED=1').find(x => x.props.label === 'Metal HUD').props.checked === true,
+ 'a toggle reads as on from its argument');
+
+ nodes('CX_GRAPHICS_BACKEND=dxmt').filter(x => x.type === 'Dropdown')[1].props.onChange({ data: '2.0' });
+ t.ok(last().includes('metalSpatialUpscaleFactor=2.0'), 'the upscaler writes its factor');
+
+ // The section names the factor, so a label promising a resolution to go and set in
+ // the game is the wording this replaced.
+ const upscaler = nodes('CX_GRAPHICS_BACKEND=dxmt').find(x => x.type === 'Section' &&
+ x.props.label.indexOf('MetalFX') === 0);
+ t.ok(/Samples from the resolution the game is set to/.test(upscaler.props.label),
+ 'the upscaler section says where it samples from');
+ const factors = nodes('CX_GRAPHICS_BACKEND=dxmt').filter(x => x.type === 'Dropdown')[1]
+ .props.rgOptions.map(o => o.label);
+ t.ok(factors.join(',') === 'Off,1.5x,1.72x,2x,3x', `the factors name themselves (${factors.join(',')})`);
+
+ // The value is the name wine gives the library, which is lower case, and the label is
+ // the name in a list of four the reader picks from.
+ const backends = nodes('').find(x => x.type === 'Dropdown').props.rgOptions;
+ t.ok(backends.map(o => o.label).join(',') === 'Automatic,D3DMetal,DXMT,DXVK,WineD3D',
+ `the backends name themselves (${backends.map(o => o.label).join(',')})`);
+ t.ok(backends.map(o => o.data).join(',') === ',d3dmetal,dxmt,dxvk,wined3d',
+ 'the backend values stay as the tool reads them');
+
+ const root = P({ details: details('') });
+ t.ok(root.props.className === 'MSCXPanel', 'the panel root carries its own class');
+ const classes = nodes('').filter(x => x.type === 'Toggle').map(x => x.props.className);
+ t.ok(classes.length === 5 && classes.every(c => c === 'MSCXRow'), 'every checkbox carries the row class');
+ const css = nodes('').filter(x => x.type === 'style');
+ t.ok(css.length === 1 && css[0].props.children.includes('.MSCXPanel .MSCXRow{'),
+ 'the panel carries one stylesheet defining the row rule');
+
+ failed += t.failed;
+}
+console.log(failed ? `\n${failed} failure(s)` : '\nboth shapes pass');
+process.exit(failed ? 1 : 0);
diff --git a/dylib/tests/panel-behavior/emit.c b/dylib/tests/panel-behavior/emit.c
new file mode 100644
index 0000000..9872a1f
--- /dev/null
+++ b/dylib/tests/panel-behavior/emit.c
@@ -0,0 +1,23 @@
+// The payload is a macro, so the unit under test is included rather than linked.
+// Both forms come from one body, which is what makes the checks that run against
+// this output speak for both page shapes at once.
+#include "../../feats/webpatch.c"
+
+#include <stdio.h>
+#include <string.h>
+
+int np_log_level = 0;
+FILE *np_log_file = NULL;
+
+int main(int argc, char **argv) {
+ if (argc == 2 && strcmp(argv[1], "component") == 0) {
+ fputs(NP_CX_OPTIONS_COMPONENT, stdout);
+ return 0;
+ }
+ if (argc == 2 && strcmp(argv[1], "statement") == 0) {
+ fputs(NP_CX_OPTIONS_STATEMENT, stdout);
+ return 0;
+ }
+ fputs("usage: emit component|statement\n", stderr);
+ return 2;
+}
diff --git a/dylib/tests/panel-behavior/harness.js b/dylib/tests/panel-behavior/harness.js
new file mode 100644
index 0000000..add1a0d
--- /dev/null
+++ b/dylib/tests/panel-behavior/harness.js
@@ -0,0 +1,73 @@
+// Runs the injected panel as a component, with the barrel and react stubbed, so the
+// checks exercise the payload the gates actually write rather than a copy of it.
+//
+// Capture bytes stand in for names the page assigns, and expanding them to names no
+// Steam build would pick keeps a check from passing only for the letters one build
+// happened to use.
+'use strict';
+const fs = require('fs');
+const { execFileSync } = require('child_process');
+
+const CAPS = { '\u0003': 'R0', '\u0004': 'B0' };
+const expand = s => s.replace(/[\u0001-\u0008]/g, c => {
+ if (!(c in CAPS)) throw new Error('payload uses unbound capture ' + c.charCodeAt(0));
+ return CAPS[c];
+});
+
+const mk = (type, props) => ({ type, props });
+const react = { jsx: mk, jsxs: mk, Fragment: 'Fragment' };
+const barrel = { XY: 'Section', m: 'Dropdown', Yh: 'Toggle' };
+
+// The two shapes take the payload in different forms and bind different names, which
+// is the whole of the difference between them.
+const FORMS = {
+ component: { arg: 'component', react: 'i', barrel: 'c' },
+ statement: { arg: 'statement', react: 'R0', barrel: 'B0' },
+};
+
+function panel(emit, form) {
+ const raw = execFileSync(emit, [form], { encoding: 'utf8' }).trim();
+ const src = form === 'component'
+ ? 'var ' + raw.replace(/,$/, '')
+ : expand(raw).replace(/;$/, '');
+ const f = FORMS[form];
+ const written = [];
+ const SteamClient = {
+ Apps: { SetAppLaunchOptions: (appid, opts) => written.push({ appid, opts }) },
+ };
+ const build = new Function(f.react, f.barrel, 'SteamClient', src + '\nreturn MSCXOpts;');
+ return { render: build(react, barrel, SteamClient), written };
+}
+
+// Function components are resolved rather than recorded, so a check sees the nodes the
+// page ends up with and not the wrappers on the way there.
+function walk(node, out = []) {
+ if (!node || typeof node !== 'object') return out;
+ if (Array.isArray(node)) { node.forEach(c => walk(c, out)); return out; }
+ if (typeof node.type === 'function') return walk(node.type(node.props), out);
+ if (node.type) out.push(node);
+ if (node.props && node.props.children) walk(node.props.children, out);
+ return out;
+}
+
+function details(launchOptions, over) {
+ return Object.assign({
+ unAppID: 287700,
+ vecPlatforms: ['windows'],
+ strCompatToolName: 'notproton',
+ strLaunchOptions: launchOptions,
+ }, over || {});
+}
+
+function runner(name) {
+ let failed = 0;
+ return {
+ ok(cond, what) {
+ if (!cond) failed++;
+ console.log(` ${cond ? 'PASS' : 'FAIL'} [${name}] ${what}`);
+ },
+ get failed() { return failed; },
+ };
+}
+
+module.exports = { panel, walk, details, runner, expand, FORMS };
diff --git a/dylib/tests/panel-behavior/switching.js b/dylib/tests/panel-behavior/switching.js
new file mode 100644
index 0000000..f2c1ce7
--- /dev/null
+++ b/dylib/tests/panel-behavior/switching.js
@@ -0,0 +1,74 @@
+// An option belongs to the backend that reads it, and the control for it goes away
+// with that backend. An argument left behind is one the page can no longer switch
+// off, so changing the backend has to take it along.
+'use strict';
+const { panel, walk, details, runner, FORMS } = require('./harness');
+
+const emit = process.argv[2];
+if (!emit) { console.error('usage: switching.js <emit>'); process.exit(2); }
+
+const DXMT = ['DXMT_METALFX_SPATIAL_SWAPCHAIN', 'DXMT_CONFIG'];
+const D3DM = ['D3DM_ENABLE_METALFX'];
+const NVEXT = ['DXMT_ENABLE_NVEXT'];
+const DLSS_ON = 'CX_GRAPHICS_BACKEND=dxmt DXMT_ENABLE_NVEXT=1';
+const UPSCALED = 'CX_GRAPHICS_BACKEND=dxmt DXMT_METALFX_SPATIAL_SWAPCHAIN=1'
+ + ' DXMT_CONFIG=d3d11.metalSpatialUpscaleFactor=2.0';
+
+// Whichever backend is chosen, the arguments the others own have to be gone and the
+// arguments no backend owns have to survive.
+const CASES = [
+ { to: 'd3dmetal', from: UPSCALED, gone: DXMT, kept: [] },
+ { to: 'dxvk', from: UPSCALED, gone: DXMT, kept: [] },
+ { to: 'wined3d', from: UPSCALED, gone: DXMT, kept: [] },
+ { to: 'dxmt', from: 'CX_GRAPHICS_BACKEND=d3dmetal D3DM_ENABLE_METALFX=1', gone: D3DM, kept: [] },
+ { to: 'dxvk', from: 'CX_GRAPHICS_BACKEND=d3dmetal D3DM_ENABLE_METALFX=1', gone: D3DM, kept: [] },
+ // Automatic resolves to either backend, so neither one's arguments are stale.
+ { to: '', from: UPSCALED, gone: [], kept: DXMT },
+ { to: '', from: 'CX_GRAPHICS_BACKEND=d3dmetal D3DM_ENABLE_METALFX=1', gone: [], kept: D3DM },
+ // The dxmt DLSS row is the exception: it shows under dxmt alone, so automatic has
+ // nowhere to switch the flag off and has to take it along.
+ { to: '', from: DLSS_ON, gone: NVEXT, kept: [] },
+ { to: 'd3dmetal', from: DLSS_ON, gone: NVEXT, kept: [] },
+ { to: 'dxvk', from: DLSS_ON, gone: NVEXT, kept: [] },
+ { to: 'wined3d', from: DLSS_ON, gone: NVEXT, kept: [] },
+ { to: 'dxmt', from: DLSS_ON, gone: [], kept: NVEXT },
+ // Switching into dxmt drops the other backend's DLSS rather than leaving both set.
+ { to: 'dxmt',
+ from: 'CX_GRAPHICS_BACKEND=d3dmetal D3DM_ENABLE_METALFX=1 DXMT_ENABLE_NVEXT=1',
+ gone: D3DM, kept: NVEXT },
+ // Stripping arguments by name is the kind of thing that takes neighbours with it.
+ { to: 'dxvk',
+ from: '-novid MTL_HUD_ENABLED=1 WINEMSYNC=1 NOTPROTON_RETINA=1 ' + UPSCALED + ' %command%',
+ gone: DXMT,
+ kept: ['-novid', 'MTL_HUD_ENABLED=1', 'WINEMSYNC=1', 'NOTPROTON_RETINA=1', '%command%'] },
+];
+
+let failed = 0;
+for (const form of Object.keys(FORMS)) {
+ const { render: P, written } = panel(emit, form);
+ const t = runner(form);
+ for (const c of CASES) {
+ written.length = 0;
+ const nodes = walk(P({ details: details(c.from) }));
+ const backend = nodes.find(x => x.type === 'Dropdown' &&
+ (x.props.rgOptions || []).some(o => o.data === 'dxmt'));
+ backend.props.onChange({ data: c.to });
+ const opts = written.length ? written[written.length - 1].opts : '';
+ const stale = c.gone.filter(k => opts.indexOf(k + '=') >= 0);
+ const lost = c.kept.filter(k => opts.indexOf(k) < 0);
+ const to = c.to || 'automatic';
+ t.ok(stale.length === 0 && lost.length === 0,
+ `switching to ${to} drops ${c.gone.length} and keeps ${c.kept.length}`
+ + (stale.length ? ` [stale: ${stale}]` : '') + (lost.length ? ` [lost: ${lost}]` : ''));
+ }
+ // %command% has to stay last or Steam runs the game before the arguments.
+ written.length = 0;
+ const nodes = walk(P({ details: details(UPSCALED + ' %command%') }));
+ nodes.find(x => x.type === 'Dropdown' &&
+ (x.props.rgOptions || []).some(o => o.data === 'dxmt')).props.onChange({ data: 'dxvk' });
+ const opts = written[written.length - 1].opts;
+ t.ok(opts.trim().endsWith('%command%'), `%command% stays last (${opts})`);
+ failed += t.failed;
+}
+console.log(failed ? `\n${failed} failure(s)` : '\nno stale arguments, nothing lost');
+process.exit(failed ? 1 : 0);
diff --git a/dylib/tests/sigcheck.py b/dylib/tests/sigcheck.py
new file mode 100644
index 0000000..004a57a
--- /dev/null
+++ b/dylib/tests/sigcheck.py
@@ -0,0 +1,43 @@
+#!/usr/bin/env python3
+# Validates signature names in the dylib sources against the signature db
+import json
+import pathlib
+import re
+import sys
+
+root = pathlib.Path(__file__).resolve().parents[2]
+
+wanted = {}
+for path in sorted((root / "dylib").rglob("*.c")):
+ text = path.read_text()
+ for pattern in (r'\.signature\s*=\s*"([^"]+)"',
+ r'np_resolve_find\s*\(\s*\w+\s*,\s*"([^"]+)"',
+ r'np_lookup_address\s*\(\s*\w+\s*,\s*\n?\s*"([^"]+)"'):
+ for name in re.findall(pattern, text):
+ wanted.setdefault(name, path.relative_to(root))
+
+if not wanted:
+ sys.exit("sigcheck: no signature names found in dylib/, the patterns are stale")
+
+dbs = sorted((root / "signatures").rglob("*.json"))
+if not dbs:
+ sys.exit("sigcheck: no signature database under signatures/")
+
+status = 0
+for db in dbs:
+ have = {s["name"] for s in json.load(db.open())["signatures"]}
+ rel = db.relative_to(root)
+
+ missing = {n: src for n, src in wanted.items() if n not in have}
+ for name in sorted(missing):
+ print("%s: MISSING %s (wanted by %s)" % (rel, name, missing[name]))
+ status = 1
+
+ for name in sorted(have - set(wanted)):
+ print("%s: unused %s" % (rel, name))
+ status = 1
+
+ if not missing and have == set(wanted):
+ print("%s: %d signatures, all referenced" % (rel, len(have)))
+
+sys.exit(status)
diff --git a/dylib/tests/sigdb-fixtures/EXPECTED b/dylib/tests/sigdb-fixtures/EXPECTED
new file mode 100644
index 0000000..dfecdf3
--- /dev/null
+++ b/dylib/tests/sigdb-fixtures/EXPECTED
@@ -0,0 +1,37 @@
+# Exit status each fixture has to produce, so that a database built to be wrong
+# passing quietly counts as a failure rather than a success. 2 is a database
+# rejected before it could be read, 1 is one read and reported as broken, 0 is
+# one read with nothing worth reporting.
+#
+# The fixtures that claim the build of the client installed on the machine are
+# judged against that client, so a client update can move them. The failure
+# names the fixture and both statuses when that happens.
+
+1 all_deprecated.json
+0 array_root.json
+1 deep_nest.json
+2 empty_file.json
+0 empty_sigs.json
+1 empty_string.json
+1 hops_huge.json
+1 hops_negative.json
+1 indirect_on_all.json
+1 long_string.json
+0 no_signatures_key.json
+2 not_json.json
+1 nthxref_huge.json
+1 nthxref_negative.json
+1 pair_impossible.json
+1 pair_missing.json
+1 pair_no_masks.json
+1 tail_no_hops.json
+1 tail_on_all.json
+2 truncated.json
+1 vtable_no_va.json
+1 vtable_va_cstring.json
+1 vtable_va_garbage.json
+1 vtable_va_max.json
+0 vtable_va_real.json
+1 vtable_va_wild.json
+1 vtable_va_zero.json
+1 wrong_kind.json
diff --git a/dylib/tests/sigdb-fixtures/all_deprecated.json b/dylib/tests/sigdb-fixtures/all_deprecated.json
new file mode 100644
index 0000000..34aac9e
--- /dev/null
+++ b/dylib/tests/sigdb-fixtures/all_deprecated.json
@@ -0,0 +1,98 @@
+{
+ "schema_version": 3,
+ "profile_version": 1,
+ "arch": "arm64",
+ "platform": "macos",
+ "steam_build": 0,
+ "steam_build_date": "",
+ "signatures": [
+ {
+ "name": "CCompatManager::Init",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x690f6c",
+ "anchor": {
+ "kind": "string",
+ "value": "STEAM_COMPAT_TOOL_MAPPINGS"
+ },
+ "deprecated": true
+ },
+ {
+ "name": "CCompatManager::BIsCompatibilityToolEnabled",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x6962f0",
+ "anchor": {
+ "kind": "string",
+ "value": "CCompatManager::BIsCompatibilityToolEnabled"
+ },
+ "deprecated": true
+ },
+ {
+ "name": "CCompatManager::YldRegisterTool",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x699f00",
+ "match_offset": 168,
+ "anchor": {
+ "kind": "string",
+ "value": "CCompatManager::YldRegisterTool"
+ },
+ "deprecated": true
+ },
+ {
+ "name": "CCompatManager::GetOSListOverrideForApp.oslist_gate",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695ed0",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "pTool != nullptr",
+ "nth_xref": 1,
+ "fn_offset": 196
+ },
+ "deprecated": true
+ },
+ {
+ "name": "CCompatManager::ResolveCompatToolForApp.local_redirect",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695fc4",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "GetAppInstallDir failed for tool %u \"%s\"",
+ "fn_offset": 116
+ },
+ "deprecated": true
+ },
+ {
+ "name": "CAppManager::TerminateProcessByPid",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0xd6f28",
+ "anchor": {
+ "kind": "string",
+ "value": "terminate",
+ "indirect": true,
+ "caller_hops": 1
+ },
+ "deprecated": true
+ },
+ {
+ "name": "CCompatManager::FindToolForTargetApp",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x69577c",
+ "anchor": {
+ "kind": "string",
+ "value": "FindToolForTargetApp matched with itself - ignoring: %u %s"
+ },
+ "deprecated": true
+ },
+ {
+ "name": "CCompatManager::GetValidPlatforms",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x69457c",
+ "anchor": {
+ "kind": "string",
+ "value": "AppID %u does not advertise linux as a supported platform, but a linux specific depot is present.\n"
+ },
+ "deprecated": true
+ }
+ ]
+}
\ No newline at end of file
diff --git a/dylib/tests/sigdb-fixtures/array_root.json b/dylib/tests/sigdb-fixtures/array_root.json
new file mode 100644
index 0000000..3a26a2e
--- /dev/null
+++ b/dylib/tests/sigdb-fixtures/array_root.json
@@ -0,0 +1 @@
+[1,2,3]
\ No newline at end of file
diff --git a/dylib/tests/sigdb-fixtures/deep_nest.json b/dylib/tests/sigdb-fixtures/deep_nest.json
new file mode 100644
index 0000000..0265f47
--- /dev/null
+++ b/dylib/tests/sigdb-fixtures/deep_nest.json
@@ -0,0 +1 @@
+{"signatures":[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]}
\ No newline at end of file
diff --git a/dylib/tests/sigdb-fixtures/empty_file.json b/dylib/tests/sigdb-fixtures/empty_file.json
new file mode 100644
index 0000000..e69de29
diff --git a/dylib/tests/sigdb-fixtures/empty_sigs.json b/dylib/tests/sigdb-fixtures/empty_sigs.json
new file mode 100644
index 0000000..3c43074
--- /dev/null
+++ b/dylib/tests/sigdb-fixtures/empty_sigs.json
@@ -0,0 +1,6 @@
+{
+ "schema_version": 3,
+ "arch": "arm64",
+ "platform": "macos",
+ "signatures": []
+}
\ No newline at end of file
diff --git a/dylib/tests/sigdb-fixtures/empty_string.json b/dylib/tests/sigdb-fixtures/empty_string.json
new file mode 100644
index 0000000..467c202
--- /dev/null
+++ b/dylib/tests/sigdb-fixtures/empty_string.json
@@ -0,0 +1,90 @@
+{
+ "schema_version": 3,
+ "profile_version": 1,
+ "arch": "arm64",
+ "platform": "macos",
+ "steam_build": 0,
+ "steam_build_date": "",
+ "signatures": [
+ {
+ "name": "CCompatManager::Init",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x690f6c",
+ "anchor": {
+ "kind": "string",
+ "value": ""
+ }
+ },
+ {
+ "name": "CCompatManager::BIsCompatibilityToolEnabled",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x6962f0",
+ "anchor": {
+ "kind": "string",
+ "value": ""
+ }
+ },
+ {
+ "name": "CCompatManager::YldRegisterTool",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x699f00",
+ "match_offset": 168,
+ "anchor": {
+ "kind": "string",
+ "value": ""
+ }
+ },
+ {
+ "name": "CCompatManager::GetOSListOverrideForApp.oslist_gate",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695ed0",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "",
+ "nth_xref": 1,
+ "fn_offset": 196
+ }
+ },
+ {
+ "name": "CCompatManager::ResolveCompatToolForApp.local_redirect",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695fc4",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "",
+ "fn_offset": 116
+ }
+ },
+ {
+ "name": "CAppManager::TerminateProcessByPid",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0xd6f28",
+ "anchor": {
+ "kind": "string",
+ "value": "",
+ "indirect": true,
+ "caller_hops": 1
+ }
+ },
+ {
+ "name": "CCompatManager::FindToolForTargetApp",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x69577c",
+ "anchor": {
+ "kind": "string",
+ "value": ""
+ }
+ },
+ {
+ "name": "CCompatManager::GetValidPlatforms",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x69457c",
+ "anchor": {
+ "kind": "string",
+ "value": ""
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/dylib/tests/sigdb-fixtures/hops_huge.json b/dylib/tests/sigdb-fixtures/hops_huge.json
new file mode 100644
index 0000000..33de9b0
--- /dev/null
+++ b/dylib/tests/sigdb-fixtures/hops_huge.json
@@ -0,0 +1,97 @@
+{
+ "schema_version": 3,
+ "profile_version": 1,
+ "arch": "arm64",
+ "platform": "macos",
+ "steam_build": 0,
+ "steam_build_date": "",
+ "signatures": [
+ {
+ "name": "CCompatManager::Init",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x690f6c",
+ "anchor": {
+ "kind": "string",
+ "value": "STEAM_COMPAT_TOOL_MAPPINGS",
+ "caller_hops": 100000
+ }
+ },
+ {
+ "name": "CCompatManager::BIsCompatibilityToolEnabled",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x6962f0",
+ "anchor": {
+ "kind": "string",
+ "value": "CCompatManager::BIsCompatibilityToolEnabled",
+ "caller_hops": 100000
+ }
+ },
+ {
+ "name": "CCompatManager::YldRegisterTool",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x699f00",
+ "match_offset": 168,
+ "anchor": {
+ "kind": "string",
+ "value": "CCompatManager::YldRegisterTool",
+ "caller_hops": 100000
+ }
+ },
+ {
+ "name": "CCompatManager::GetOSListOverrideForApp.oslist_gate",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695ed0",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "pTool != nullptr",
+ "nth_xref": 1,
+ "fn_offset": 196,
+ "caller_hops": 100000
+ }
+ },
+ {
+ "name": "CCompatManager::ResolveCompatToolForApp.local_redirect",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695fc4",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "GetAppInstallDir failed for tool %u \"%s\"",
+ "fn_offset": 116,
+ "caller_hops": 100000
+ }
+ },
+ {
+ "name": "CAppManager::TerminateProcessByPid",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0xd6f28",
+ "anchor": {
+ "kind": "string",
+ "value": "terminate",
+ "indirect": true,
+ "caller_hops": 100000
+ }
+ },
+ {
+ "name": "CCompatManager::FindToolForTargetApp",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x69577c",
+ "anchor": {
+ "kind": "string",
+ "value": "FindToolForTargetApp matched with itself - ignoring: %u %s",
+ "caller_hops": 100000
+ }
+ },
+ {
+ "name": "CCompatManager::GetValidPlatforms",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x69457c",
+ "anchor": {
+ "kind": "string",
+ "value": "AppID %u does not advertise linux as a supported platform, but a linux specific depot is present.\n",
+ "caller_hops": 100000
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/dylib/tests/sigdb-fixtures/hops_negative.json b/dylib/tests/sigdb-fixtures/hops_negative.json
new file mode 100644
index 0000000..a70a354
--- /dev/null
+++ b/dylib/tests/sigdb-fixtures/hops_negative.json
@@ -0,0 +1,97 @@
+{
+ "schema_version": 3,
+ "profile_version": 1,
+ "arch": "arm64",
+ "platform": "macos",
+ "steam_build": 0,
+ "steam_build_date": "",
+ "signatures": [
+ {
+ "name": "CCompatManager::Init",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x690f6c",
+ "anchor": {
+ "kind": "string",
+ "value": "STEAM_COMPAT_TOOL_MAPPINGS",
+ "caller_hops": -5
+ }
+ },
+ {
+ "name": "CCompatManager::BIsCompatibilityToolEnabled",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x6962f0",
+ "anchor": {
+ "kind": "string",
+ "value": "CCompatManager::BIsCompatibilityToolEnabled",
+ "caller_hops": -5
+ }
+ },
+ {
+ "name": "CCompatManager::YldRegisterTool",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x699f00",
+ "match_offset": 168,
+ "anchor": {
+ "kind": "string",
+ "value": "CCompatManager::YldRegisterTool",
+ "caller_hops": -5
+ }
+ },
+ {
+ "name": "CCompatManager::GetOSListOverrideForApp.oslist_gate",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695ed0",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "pTool != nullptr",
+ "nth_xref": 1,
+ "fn_offset": 196,
+ "caller_hops": -5
+ }
+ },
+ {
+ "name": "CCompatManager::ResolveCompatToolForApp.local_redirect",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695fc4",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "GetAppInstallDir failed for tool %u \"%s\"",
+ "fn_offset": 116,
+ "caller_hops": -5
+ }
+ },
+ {
+ "name": "CAppManager::TerminateProcessByPid",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0xd6f28",
+ "anchor": {
+ "kind": "string",
+ "value": "terminate",
+ "indirect": true,
+ "caller_hops": -5
+ }
+ },
+ {
+ "name": "CCompatManager::FindToolForTargetApp",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x69577c",
+ "anchor": {
+ "kind": "string",
+ "value": "FindToolForTargetApp matched with itself - ignoring: %u %s",
+ "caller_hops": -5
+ }
+ },
+ {
+ "name": "CCompatManager::GetValidPlatforms",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x69457c",
+ "anchor": {
+ "kind": "string",
+ "value": "AppID %u does not advertise linux as a supported platform, but a linux specific depot is present.\n",
+ "caller_hops": -5
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/dylib/tests/sigdb-fixtures/indirect_on_all.json b/dylib/tests/sigdb-fixtures/indirect_on_all.json
new file mode 100644
index 0000000..6e15f8f
--- /dev/null
+++ b/dylib/tests/sigdb-fixtures/indirect_on_all.json
@@ -0,0 +1,97 @@
+{
+ "schema_version": 3,
+ "profile_version": 1,
+ "arch": "arm64",
+ "platform": "macos",
+ "steam_build": 0,
+ "steam_build_date": "",
+ "signatures": [
+ {
+ "name": "CCompatManager::Init",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x690f6c",
+ "anchor": {
+ "kind": "string",
+ "value": "STEAM_COMPAT_TOOL_MAPPINGS",
+ "indirect": true
+ }
+ },
+ {
+ "name": "CCompatManager::BIsCompatibilityToolEnabled",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x6962f0",
+ "anchor": {
+ "kind": "string",
+ "value": "CCompatManager::BIsCompatibilityToolEnabled",
+ "indirect": true
+ }
+ },
+ {
+ "name": "CCompatManager::YldRegisterTool",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x699f00",
+ "match_offset": 168,
+ "anchor": {
+ "kind": "string",
+ "value": "CCompatManager::YldRegisterTool",
+ "indirect": true
+ }
+ },
+ {
+ "name": "CCompatManager::GetOSListOverrideForApp.oslist_gate",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695ed0",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "pTool != nullptr",
+ "nth_xref": 1,
+ "fn_offset": 196,
+ "indirect": true
+ }
+ },
+ {
+ "name": "CCompatManager::ResolveCompatToolForApp.local_redirect",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695fc4",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "GetAppInstallDir failed for tool %u \"%s\"",
+ "fn_offset": 116,
+ "indirect": true
+ }
+ },
+ {
+ "name": "CAppManager::TerminateProcessByPid",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0xd6f28",
+ "anchor": {
+ "kind": "string",
+ "value": "terminate",
+ "indirect": true,
+ "caller_hops": 1
+ }
+ },
+ {
+ "name": "CCompatManager::FindToolForTargetApp",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x69577c",
+ "anchor": {
+ "kind": "string",
+ "value": "FindToolForTargetApp matched with itself - ignoring: %u %s",
+ "indirect": true
+ }
+ },
+ {
+ "name": "CCompatManager::GetValidPlatforms",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x69457c",
+ "anchor": {
+ "kind": "string",
+ "value": "AppID %u does not advertise linux as a supported platform, but a linux specific depot is present.\n",
+ "indirect": true
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/dylib/tests/sigdb-fixtures/long_string.json b/dylib/tests/sigdb-fixtures/long_string.json
new file mode 100644
index 0000000..2ca43f1
--- /dev/null
+++ b/dylib/tests/sigdb-fixtures/long_string.json
@@ -0,0 +1,90 @@
+{
+ "schema_version": 3,
+ "profile_version": 1,
+ "arch": "arm64",
+ "platform": "macos",
+ "steam_build": 0,
+ "steam_build_date": "",
+ "signatures": [
+ {
+ "name": "CCompatManager::Init",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x690f6c",
+ "anchor": {
+ "kind": "string",
+ "value": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+ }
+ },
+ {
+ "name": "CCompatManager::BIsCompatibilityToolEnabled",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x6962f0",
+ "anchor": {
+ "kind": "string",
+ "value": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+ }
+ },
+ {
+ "name": "CCompatManager::YldRegisterTool",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x699f00",
+ "match_offset": 168,
+ "anchor": {
+ "kind": "string",
+ "value": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+ }
+ },
+ {
+ "name": "CCompatManager::GetOSListOverrideForApp.oslist_gate",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695ed0",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
+ "nth_xref": 1,
+ "fn_offset": 196
+ }
+ },
+ {
+ "name": "CCompatManager::ResolveCompatToolForApp.local_redirect",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695fc4",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
+ "fn_offset": 116
+ }
+ },
+ {
+ "name": "CAppManager::TerminateProcessByPid",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0xd6f28",
+ "anchor": {
+ "kind": "string",
+ "value": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
+ "indirect": true,
+ "caller_hops": 1
+ }
+ },
+ {
+ "name": "CCompatManager::FindToolForTargetApp",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x69577c",
+ "anchor": {
+ "kind": "string",
+ "value": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+ }
+ },
+ {
+ "name": "CCompatManager::GetValidPlatforms",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x69457c",
+ "anchor": {
+ "kind": "string",
+ "value": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/dylib/tests/sigdb-fixtures/no_signatures_key.json b/dylib/tests/sigdb-fixtures/no_signatures_key.json
new file mode 100644
index 0000000..ade1b80
--- /dev/null
+++ b/dylib/tests/sigdb-fixtures/no_signatures_key.json
@@ -0,0 +1,5 @@
+{
+ "schema_version": 3,
+ "arch": "arm64",
+ "platform": "macos"
+}
\ No newline at end of file
diff --git a/dylib/tests/sigdb-fixtures/not_json.json b/dylib/tests/sigdb-fixtures/not_json.json
new file mode 100644
index 0000000..eb55c99
Binary files /dev/null and b/dylib/tests/sigdb-fixtures/not_json.json differ
diff --git a/dylib/tests/sigdb-fixtures/nthxref_huge.json b/dylib/tests/sigdb-fixtures/nthxref_huge.json
new file mode 100644
index 0000000..0bfae2d
--- /dev/null
+++ b/dylib/tests/sigdb-fixtures/nthxref_huge.json
@@ -0,0 +1,97 @@
+{
+ "schema_version": 3,
+ "profile_version": 1,
+ "arch": "arm64",
+ "platform": "macos",
+ "steam_build": 0,
+ "steam_build_date": "",
+ "signatures": [
+ {
+ "name": "CCompatManager::Init",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x690f6c",
+ "anchor": {
+ "kind": "string",
+ "value": "STEAM_COMPAT_TOOL_MAPPINGS",
+ "nth_xref": 999999
+ }
+ },
+ {
+ "name": "CCompatManager::BIsCompatibilityToolEnabled",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x6962f0",
+ "anchor": {
+ "kind": "string",
+ "value": "CCompatManager::BIsCompatibilityToolEnabled",
+ "nth_xref": 999999
+ }
+ },
+ {
+ "name": "CCompatManager::YldRegisterTool",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x699f00",
+ "match_offset": 168,
+ "anchor": {
+ "kind": "string",
+ "value": "CCompatManager::YldRegisterTool",
+ "nth_xref": 999999
+ }
+ },
+ {
+ "name": "CCompatManager::GetOSListOverrideForApp.oslist_gate",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695ed0",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "pTool != nullptr",
+ "nth_xref": 999999,
+ "fn_offset": 196
+ }
+ },
+ {
+ "name": "CCompatManager::ResolveCompatToolForApp.local_redirect",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695fc4",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "GetAppInstallDir failed for tool %u \"%s\"",
+ "fn_offset": 116,
+ "nth_xref": 999999
+ }
+ },
+ {
+ "name": "CAppManager::TerminateProcessByPid",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0xd6f28",
+ "anchor": {
+ "kind": "string",
+ "value": "terminate",
+ "indirect": true,
+ "caller_hops": 1,
+ "nth_xref": 999999
+ }
+ },
+ {
+ "name": "CCompatManager::FindToolForTargetApp",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x69577c",
+ "anchor": {
+ "kind": "string",
+ "value": "FindToolForTargetApp matched with itself - ignoring: %u %s",
+ "nth_xref": 999999
+ }
+ },
+ {
+ "name": "CCompatManager::GetValidPlatforms",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x69457c",
+ "anchor": {
+ "kind": "string",
+ "value": "AppID %u does not advertise linux as a supported platform, but a linux specific depot is present.\n",
+ "nth_xref": 999999
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/dylib/tests/sigdb-fixtures/nthxref_negative.json b/dylib/tests/sigdb-fixtures/nthxref_negative.json
new file mode 100644
index 0000000..d4f8008
--- /dev/null
+++ b/dylib/tests/sigdb-fixtures/nthxref_negative.json
@@ -0,0 +1,97 @@
+{
+ "schema_version": 3,
+ "profile_version": 1,
+ "arch": "arm64",
+ "platform": "macos",
+ "steam_build": 0,
+ "steam_build_date": "",
+ "signatures": [
+ {
+ "name": "CCompatManager::Init",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x690f6c",
+ "anchor": {
+ "kind": "string",
+ "value": "STEAM_COMPAT_TOOL_MAPPINGS",
+ "nth_xref": -3
+ }
+ },
+ {
+ "name": "CCompatManager::BIsCompatibilityToolEnabled",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x6962f0",
+ "anchor": {
+ "kind": "string",
+ "value": "CCompatManager::BIsCompatibilityToolEnabled",
+ "nth_xref": -3
+ }
+ },
+ {
+ "name": "CCompatManager::YldRegisterTool",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x699f00",
+ "match_offset": 168,
+ "anchor": {
+ "kind": "string",
+ "value": "CCompatManager::YldRegisterTool",
+ "nth_xref": -3
+ }
+ },
+ {
+ "name": "CCompatManager::GetOSListOverrideForApp.oslist_gate",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695ed0",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "pTool != nullptr",
+ "nth_xref": -3,
+ "fn_offset": 196
+ }
+ },
+ {
+ "name": "CCompatManager::ResolveCompatToolForApp.local_redirect",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695fc4",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "GetAppInstallDir failed for tool %u \"%s\"",
+ "fn_offset": 116,
+ "nth_xref": -3
+ }
+ },
+ {
+ "name": "CAppManager::TerminateProcessByPid",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0xd6f28",
+ "anchor": {
+ "kind": "string",
+ "value": "terminate",
+ "indirect": true,
+ "caller_hops": 1,
+ "nth_xref": -3
+ }
+ },
+ {
+ "name": "CCompatManager::FindToolForTargetApp",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x69577c",
+ "anchor": {
+ "kind": "string",
+ "value": "FindToolForTargetApp matched with itself - ignoring: %u %s",
+ "nth_xref": -3
+ }
+ },
+ {
+ "name": "CCompatManager::GetValidPlatforms",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x69457c",
+ "anchor": {
+ "kind": "string",
+ "value": "AppID %u does not advertise linux as a supported platform, but a linux specific depot is present.\n",
+ "nth_xref": -3
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/dylib/tests/sigdb-fixtures/pair_impossible.json b/dylib/tests/sigdb-fixtures/pair_impossible.json
new file mode 100644
index 0000000..1ab85c3
--- /dev/null
+++ b/dylib/tests/sigdb-fixtures/pair_impossible.json
@@ -0,0 +1,101 @@
+{
+ "schema_version": 3,
+ "profile_version": 1,
+ "arch": "arm64",
+ "platform": "macos",
+ "steam_build": 0,
+ "steam_build_date": "",
+ "signatures": [
+ {
+ "name": "CCompatManager::Init",
+ "func_addr_this_build": "0x6a3bd0",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "STEAM_COMPAT_TOOL_MAPPINGS"
+ }
+ },
+ {
+ "name": "CCompatManager::BIsCompatibilityToolEnabled",
+ "func_addr_this_build": "0x6a8424",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "CCompatManager::BIsCompatibilityToolEnabled"
+ }
+ },
+ {
+ "name": "CCompatManager::YldRegisterTool",
+ "func_addr_this_build": "0x6ac470",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "CCompatManager::YldRegisterTool"
+ }
+ },
+ {
+ "name": "CCompatManager::GetOSListOverrideForApp.oslist_gate",
+ "func_addr_this_build": "0x6a8070",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "insn_pair_in_fn",
+ "value": "pTool != nullptr",
+ "nth_xref": 1,
+ "pair": {
+ "first": "0xFFFFFFFF",
+ "first_mask": "0xFFFFFFFF",
+ "second": "0xFFFFFFFF",
+ "second_mask": "0xFFFFFFFF",
+ "tie_mask": "0x0",
+ "land": "second"
+ }
+ }
+ },
+ {
+ "name": "CCompatManager::ResolveCompatToolForApp.local_redirect",
+ "func_addr_this_build": "0x6a8130",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "insn_pair_in_fn",
+ "value": "GetAppInstallDir failed for tool %u \"%s\"",
+ "pair": {
+ "first": "0xFFFFFFFF",
+ "first_mask": "0xFFFFFFFF",
+ "second": "0xFFFFFFFF",
+ "second_mask": "0xFFFFFFFF",
+ "tie_mask": "0x1F",
+ "land": "first"
+ }
+ }
+ },
+ {
+ "name": "CAppManager::TerminateProcessByPid",
+ "func_addr_this_build": "0xdd0cc",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "terminate",
+ "indirect": true,
+ "caller_hops": 1
+ }
+ },
+ {
+ "name": "CCompatManager::FindToolForTargetApp",
+ "func_addr_this_build": "0x6a7b64",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "FindToolForTargetApp matched with itself - ignoring: %u %s"
+ }
+ },
+ {
+ "name": "CCompatManager::GetValidPlatforms",
+ "func_addr_this_build": "0x6a65d0",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "AppID %u does not advertise linux as a supported platform, but a linux specific depot is present.\n"
+ }
+ }
+ ]
+}
diff --git a/dylib/tests/sigdb-fixtures/pair_missing.json b/dylib/tests/sigdb-fixtures/pair_missing.json
new file mode 100644
index 0000000..1083440
--- /dev/null
+++ b/dylib/tests/sigdb-fixtures/pair_missing.json
@@ -0,0 +1,85 @@
+{
+ "schema_version": 3,
+ "profile_version": 1,
+ "arch": "arm64",
+ "platform": "macos",
+ "steam_build": 0,
+ "steam_build_date": "",
+ "signatures": [
+ {
+ "name": "CCompatManager::Init",
+ "func_addr_this_build": "0x6a3bd0",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "STEAM_COMPAT_TOOL_MAPPINGS"
+ }
+ },
+ {
+ "name": "CCompatManager::BIsCompatibilityToolEnabled",
+ "func_addr_this_build": "0x6a8424",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "CCompatManager::BIsCompatibilityToolEnabled"
+ }
+ },
+ {
+ "name": "CCompatManager::YldRegisterTool",
+ "func_addr_this_build": "0x6ac470",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "CCompatManager::YldRegisterTool"
+ }
+ },
+ {
+ "name": "CCompatManager::GetOSListOverrideForApp.oslist_gate",
+ "func_addr_this_build": "0x6a8070",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "insn_pair_in_fn",
+ "value": "pTool != nullptr",
+ "nth_xref": 1
+ }
+ },
+ {
+ "name": "CCompatManager::ResolveCompatToolForApp.local_redirect",
+ "func_addr_this_build": "0x6a8130",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "insn_pair_in_fn",
+ "value": "GetAppInstallDir failed for tool %u \"%s\""
+ }
+ },
+ {
+ "name": "CAppManager::TerminateProcessByPid",
+ "func_addr_this_build": "0xdd0cc",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "terminate",
+ "indirect": true,
+ "caller_hops": 1
+ }
+ },
+ {
+ "name": "CCompatManager::FindToolForTargetApp",
+ "func_addr_this_build": "0x6a7b64",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "FindToolForTargetApp matched with itself - ignoring: %u %s"
+ }
+ },
+ {
+ "name": "CCompatManager::GetValidPlatforms",
+ "func_addr_this_build": "0x6a65d0",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "AppID %u does not advertise linux as a supported platform, but a linux specific depot is present.\n"
+ }
+ }
+ ]
+}
diff --git a/dylib/tests/sigdb-fixtures/pair_no_masks.json b/dylib/tests/sigdb-fixtures/pair_no_masks.json
new file mode 100644
index 0000000..da2a0b4
--- /dev/null
+++ b/dylib/tests/sigdb-fixtures/pair_no_masks.json
@@ -0,0 +1,101 @@
+{
+ "schema_version": 3,
+ "profile_version": 1,
+ "arch": "arm64",
+ "platform": "macos",
+ "steam_build": 0,
+ "steam_build_date": "",
+ "signatures": [
+ {
+ "name": "CCompatManager::Init",
+ "func_addr_this_build": "0x6a3bd0",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "STEAM_COMPAT_TOOL_MAPPINGS"
+ }
+ },
+ {
+ "name": "CCompatManager::BIsCompatibilityToolEnabled",
+ "func_addr_this_build": "0x6a8424",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "CCompatManager::BIsCompatibilityToolEnabled"
+ }
+ },
+ {
+ "name": "CCompatManager::YldRegisterTool",
+ "func_addr_this_build": "0x6ac470",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "CCompatManager::YldRegisterTool"
+ }
+ },
+ {
+ "name": "CCompatManager::GetOSListOverrideForApp.oslist_gate",
+ "func_addr_this_build": "0x6a8070",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "insn_pair_in_fn",
+ "value": "pTool != nullptr",
+ "nth_xref": 1,
+ "pair": {
+ "first": "0x94000000",
+ "first_mask": "0x0",
+ "second": "0xB4000000",
+ "second_mask": "0x0",
+ "tie_mask": "0x0",
+ "land": "second"
+ }
+ }
+ },
+ {
+ "name": "CCompatManager::ResolveCompatToolForApp.local_redirect",
+ "func_addr_this_build": "0x6a8130",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "insn_pair_in_fn",
+ "value": "GetAppInstallDir failed for tool %u \"%s\"",
+ "pair": {
+ "first": "0xB9400000",
+ "first_mask": "0x0",
+ "second": "0x34000000",
+ "second_mask": "0x0",
+ "tie_mask": "0x1F",
+ "land": "first"
+ }
+ }
+ },
+ {
+ "name": "CAppManager::TerminateProcessByPid",
+ "func_addr_this_build": "0xdd0cc",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "terminate",
+ "indirect": true,
+ "caller_hops": 1
+ }
+ },
+ {
+ "name": "CCompatManager::FindToolForTargetApp",
+ "func_addr_this_build": "0x6a7b64",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "FindToolForTargetApp matched with itself - ignoring: %u %s"
+ }
+ },
+ {
+ "name": "CCompatManager::GetValidPlatforms",
+ "func_addr_this_build": "0x6a65d0",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "AppID %u does not advertise linux as a supported platform, but a linux specific depot is present.\n"
+ }
+ }
+ ]
+}
diff --git a/dylib/tests/sigdb-fixtures/tail_no_hops.json b/dylib/tests/sigdb-fixtures/tail_no_hops.json
new file mode 100644
index 0000000..2732e69
--- /dev/null
+++ b/dylib/tests/sigdb-fixtures/tail_no_hops.json
@@ -0,0 +1,96 @@
+{
+ "schema_version": 3,
+ "profile_version": 1,
+ "arch": "arm64",
+ "platform": "macos",
+ "steam_build": 0,
+ "steam_build_date": "",
+ "signatures": [
+ {
+ "name": "CCompatManager::Init",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x690f6c",
+ "anchor": {
+ "kind": "string",
+ "value": "STEAM_COMPAT_TOOL_MAPPINGS",
+ "caller_tail": true
+ }
+ },
+ {
+ "name": "CCompatManager::BIsCompatibilityToolEnabled",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x6962f0",
+ "anchor": {
+ "kind": "string",
+ "value": "CCompatManager::BIsCompatibilityToolEnabled",
+ "caller_tail": true
+ }
+ },
+ {
+ "name": "CCompatManager::YldRegisterTool",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x699f00",
+ "match_offset": 168,
+ "anchor": {
+ "kind": "string",
+ "value": "CCompatManager::YldRegisterTool",
+ "caller_tail": true
+ }
+ },
+ {
+ "name": "CCompatManager::GetOSListOverrideForApp.oslist_gate",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695ed0",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "pTool != nullptr",
+ "nth_xref": 1,
+ "fn_offset": 196,
+ "caller_tail": true
+ }
+ },
+ {
+ "name": "CCompatManager::ResolveCompatToolForApp.local_redirect",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695fc4",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "GetAppInstallDir failed for tool %u \"%s\"",
+ "fn_offset": 116,
+ "caller_tail": true
+ }
+ },
+ {
+ "name": "CAppManager::TerminateProcessByPid",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0xd6f28",
+ "anchor": {
+ "kind": "string",
+ "value": "terminate",
+ "caller_tail": true
+ }
+ },
+ {
+ "name": "CCompatManager::FindToolForTargetApp",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x69577c",
+ "anchor": {
+ "kind": "string",
+ "value": "FindToolForTargetApp matched with itself - ignoring: %u %s",
+ "caller_tail": true
+ }
+ },
+ {
+ "name": "CCompatManager::GetValidPlatforms",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x69457c",
+ "anchor": {
+ "kind": "string",
+ "value": "AppID %u does not advertise linux as a supported platform, but a linux specific depot is present.\n",
+ "caller_tail": true
+ }
+ }
+ ]
+}
diff --git a/dylib/tests/sigdb-fixtures/tail_on_all.json b/dylib/tests/sigdb-fixtures/tail_on_all.json
new file mode 100644
index 0000000..3a70c42
--- /dev/null
+++ b/dylib/tests/sigdb-fixtures/tail_on_all.json
@@ -0,0 +1,104 @@
+{
+ "schema_version": 3,
+ "profile_version": 1,
+ "arch": "arm64",
+ "platform": "macos",
+ "steam_build": 0,
+ "steam_build_date": "",
+ "signatures": [
+ {
+ "name": "CCompatManager::Init",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x690f6c",
+ "anchor": {
+ "kind": "string",
+ "value": "STEAM_COMPAT_TOOL_MAPPINGS",
+ "caller_tail": true,
+ "caller_hops": 1
+ }
+ },
+ {
+ "name": "CCompatManager::BIsCompatibilityToolEnabled",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x6962f0",
+ "anchor": {
+ "kind": "string",
+ "value": "CCompatManager::BIsCompatibilityToolEnabled",
+ "caller_tail": true,
+ "caller_hops": 1
+ }
+ },
+ {
+ "name": "CCompatManager::YldRegisterTool",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x699f00",
+ "match_offset": 168,
+ "anchor": {
+ "kind": "string",
+ "value": "CCompatManager::YldRegisterTool",
+ "caller_tail": true,
+ "caller_hops": 1
+ }
+ },
+ {
+ "name": "CCompatManager::GetOSListOverrideForApp.oslist_gate",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695ed0",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "pTool != nullptr",
+ "nth_xref": 1,
+ "fn_offset": 196,
+ "caller_tail": true,
+ "caller_hops": 1
+ }
+ },
+ {
+ "name": "CCompatManager::ResolveCompatToolForApp.local_redirect",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695fc4",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "string",
+ "value": "GetAppInstallDir failed for tool %u \"%s\"",
+ "fn_offset": 116,
+ "caller_tail": true,
+ "caller_hops": 1
+ }
+ },
+ {
+ "name": "CAppManager::TerminateProcessByPid",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0xd6f28",
+ "anchor": {
+ "kind": "string",
+ "value": "terminate",
+ "caller_hops": 1,
+ "caller_tail": true
+ }
+ },
+ {
+ "name": "CCompatManager::FindToolForTargetApp",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x69577c",
+ "anchor": {
+ "kind": "string",
+ "value": "FindToolForTargetApp matched with itself - ignoring: %u %s",
+ "caller_tail": true,
+ "caller_hops": 1
+ }
+ },
+ {
+ "name": "CCompatManager::GetValidPlatforms",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x69457c",
+ "anchor": {
+ "kind": "string",
+ "value": "AppID %u does not advertise linux as a supported platform, but a linux specific depot is present.\n",
+ "caller_tail": true,
+ "caller_hops": 1
+ }
+ }
+ ]
+}
diff --git a/dylib/tests/sigdb-fixtures/truncated.json b/dylib/tests/sigdb-fixtures/truncated.json
new file mode 100644
index 0000000..35a23e5
--- /dev/null
+++ b/dylib/tests/sigdb-fixtures/truncated.json
@@ -0,0 +1 @@
+{"schema_version":3,"signatures":[{"name":"x",
\ No newline at end of file
diff --git a/dylib/tests/sigdb-fixtures/vtable_no_va.json b/dylib/tests/sigdb-fixtures/vtable_no_va.json
new file mode 100644
index 0000000..128f7df
--- /dev/null
+++ b/dylib/tests/sigdb-fixtures/vtable_no_va.json
@@ -0,0 +1,77 @@
+{
+ "schema_version": 3,
+ "profile_version": 1,
+ "arch": "arm64",
+ "platform": "macos",
+ "steam_build": 0,
+ "steam_build_date": "",
+ "signatures": [
+ {
+ "name": "CCompatManager::Init",
+ "aob_hex": "?? ?? ?? D1 FC 6F 0B A9 FA 67 0C A9 F8 5F 0D A9 F6 57 0E A9 F4 4F 0F A9 FD 7B 10 A9 FD 03 04 91 F4 03 01 AA F3 03 00 AA ?? ?? ?? ?? 08 A9 40 F9 08 01 40 F9 ?? ?? ?? ?? 29 01 28 91 A8 03 1A F8 09 00 00 F9 F9 03 00 AA 3F 8F 00 F8 1F 08 00 F9",
+ "func_addr_this_build": "0x690f6c",
+ "anchor": {
+ "kind": "vtable_slot"
+ }
+ },
+ {
+ "name": "CCompatManager::BIsCompatibilityToolEnabled",
+ "aob_hex": "FF 03 01 D1 F4 4F 02 A9 FD 7B 03 A9 ?? ?? ?? ?? F4 03 01 AA F3 03 00 AA E1 17 00 B9 ?? ?? ?? ?? 08 0D 40 F9 08 01 40 B9 E8 00 00 34 ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? 81 00 80 52 ?? ?? ?? ??",
+ "func_addr_this_build": "0x6962f0",
+ "anchor": {
+ "kind": "vtable_slot"
+ }
+ },
+ {
+ "name": "CCompatManager::YldRegisterTool",
+ "aob_hex": "88 3E 40 F9 1F 01 00 F1 56 03 88 9A E0 03 16 AA ?? ?? ?? 94 E8 03 00 AA 89 22 40 F9 3F 01 00 F1 40 03 89 9A 88 00 00 34",
+ "func_addr_this_build": "0x699f00",
+ "match_offset": 168,
+ "anchor": {
+ "kind": "vtable_slot"
+ }
+ },
+ {
+ "name": "CCompatManager::GetOSListOverrideForApp.oslist_gate",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695ed0",
+ "aob_hex": "E0 03 14 AA ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? A8 3A 40 F9 1F 01 00 F1 C8 02 88 9A 68 02 00 F9 33 00 80 52",
+ "anchor": {
+ "kind": "vtable_slot"
+ }
+ },
+ {
+ "name": "CCompatManager::ResolveCompatToolForApp.local_redirect",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695fc4",
+ "aob_hex": "80 02 40 F9 ?? ?? ?? ?? 01 60 40 B9 ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? 08 01 40 F9 09 30 82 52 00 01 09 8B 02 00 80 52 ?? ?? ?? ??",
+ "anchor": {
+ "kind": "vtable_slot"
+ }
+ },
+ {
+ "name": "CAppManager::TerminateProcessByPid",
+ "aob_hex": "F4 4F BE A9 FD 7B 01 A9 FD 43 00 91 F3 03 00 AA ?? ?? ?? ?? F4 03 00 AA ?? ?? ?? ?? 00 F9 45 F9 E2 03 13 AA ?? ?? ?? ?? ?? ?? ?? ?? F3 03 00 AA",
+ "func_addr_this_build": "0xd6f28",
+ "anchor": {
+ "kind": "vtable_slot"
+ }
+ },
+ {
+ "name": "CCompatManager::FindToolForTargetApp",
+ "aob_hex": "FF 83 01 D1 F6 57 03 A9 F4 4F 04 A9 FD 7B 05 A9 FD 43 01 91 A1 C3 1D B8 08 C0 5E 39 1F 05 00 71 ?? ?? ?? ?? F4 03 01 AA F3 03 00 AA ?? ?? ?? ?? 08 21 38 91 15 01 40 F9 16 07 82 52 A0 02 16 8B ?? ?? ?? ?? A0 02 16 8B E1 03 14 AA ?? ?? ?? ??",
+ "func_addr_this_build": "0x69577c",
+ "anchor": {
+ "kind": "vtable_slot"
+ }
+ },
+ {
+ "name": "CCompatManager::GetValidPlatforms",
+ "aob_hex": "FF 03 01 D1 F6 57 01 A9 F4 4F 02 A9 FD 7B 03 A9 FD C3 00 91 F4 03 01 AA F6 03 00 AA ?? ?? ?? ?? 08 21 38 91 13 01 40 F9 15 07 82 52 60 02 15 8B ?? ?? ?? ?? 60 02 15 8B E1 03 14 AA 22 00 80 52 ?? ?? ?? ?? ?? ?? ?? ?? F5 03 00 AA ?? ?? ?? ??",
+ "func_addr_this_build": "0x69457c",
+ "anchor": {
+ "kind": "vtable_slot"
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/dylib/tests/sigdb-fixtures/vtable_va_cstring.json b/dylib/tests/sigdb-fixtures/vtable_va_cstring.json
new file mode 100644
index 0000000..faa8ef7
--- /dev/null
+++ b/dylib/tests/sigdb-fixtures/vtable_va_cstring.json
@@ -0,0 +1,85 @@
+{
+ "schema_version": 3,
+ "profile_version": 1,
+ "arch": "arm64",
+ "platform": "macos",
+ "steam_build": 0,
+ "steam_build_date": "",
+ "signatures": [
+ {
+ "name": "CCompatManager::Init",
+ "aob_hex": "?? ?? ?? D1 FC 6F 0B A9 FA 67 0C A9 F8 5F 0D A9 F6 57 0E A9 F4 4F 0F A9 FD 7B 10 A9 FD 03 04 91 F4 03 01 AA F3 03 00 AA ?? ?? ?? ?? 08 A9 40 F9 08 01 40 F9 ?? ?? ?? ?? 29 01 28 91 A8 03 1A F8 09 00 00 F9 F9 03 00 AA 3F 8F 00 F8 1F 08 00 F9",
+ "func_addr_this_build": "0x690f6c",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "0x1534540"
+ }
+ },
+ {
+ "name": "CCompatManager::BIsCompatibilityToolEnabled",
+ "aob_hex": "FF 03 01 D1 F4 4F 02 A9 FD 7B 03 A9 ?? ?? ?? ?? F4 03 01 AA F3 03 00 AA E1 17 00 B9 ?? ?? ?? ?? 08 0D 40 F9 08 01 40 B9 E8 00 00 34 ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? 81 00 80 52 ?? ?? ?? ??",
+ "func_addr_this_build": "0x6962f0",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "0x1534540"
+ }
+ },
+ {
+ "name": "CCompatManager::YldRegisterTool",
+ "aob_hex": "88 3E 40 F9 1F 01 00 F1 56 03 88 9A E0 03 16 AA ?? ?? ?? 94 E8 03 00 AA 89 22 40 F9 3F 01 00 F1 40 03 89 9A 88 00 00 34",
+ "func_addr_this_build": "0x699f00",
+ "match_offset": 168,
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "0x1534540"
+ }
+ },
+ {
+ "name": "CCompatManager::GetOSListOverrideForApp.oslist_gate",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695ed0",
+ "aob_hex": "E0 03 14 AA ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? A8 3A 40 F9 1F 01 00 F1 C8 02 88 9A 68 02 00 F9 33 00 80 52",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "0x1534540"
+ }
+ },
+ {
+ "name": "CCompatManager::ResolveCompatToolForApp.local_redirect",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695fc4",
+ "aob_hex": "80 02 40 F9 ?? ?? ?? ?? 01 60 40 B9 ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? 08 01 40 F9 09 30 82 52 00 01 09 8B 02 00 80 52 ?? ?? ?? ??",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "0x1534540"
+ }
+ },
+ {
+ "name": "CAppManager::TerminateProcessByPid",
+ "aob_hex": "F4 4F BE A9 FD 7B 01 A9 FD 43 00 91 F3 03 00 AA ?? ?? ?? ?? F4 03 00 AA ?? ?? ?? ?? 00 F9 45 F9 E2 03 13 AA ?? ?? ?? ?? ?? ?? ?? ?? F3 03 00 AA",
+ "func_addr_this_build": "0xd6f28",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "0x1534540"
+ }
+ },
+ {
+ "name": "CCompatManager::FindToolForTargetApp",
+ "aob_hex": "FF 83 01 D1 F6 57 03 A9 F4 4F 04 A9 FD 7B 05 A9 FD 43 01 91 A1 C3 1D B8 08 C0 5E 39 1F 05 00 71 ?? ?? ?? ?? F4 03 01 AA F3 03 00 AA ?? ?? ?? ?? 08 21 38 91 15 01 40 F9 16 07 82 52 A0 02 16 8B ?? ?? ?? ?? A0 02 16 8B E1 03 14 AA ?? ?? ?? ??",
+ "func_addr_this_build": "0x69577c",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "0x1534540"
+ }
+ },
+ {
+ "name": "CCompatManager::GetValidPlatforms",
+ "aob_hex": "FF 03 01 D1 F6 57 01 A9 F4 4F 02 A9 FD 7B 03 A9 FD C3 00 91 F4 03 01 AA F6 03 00 AA ?? ?? ?? ?? 08 21 38 91 13 01 40 F9 15 07 82 52 60 02 15 8B ?? ?? ?? ?? 60 02 15 8B E1 03 14 AA 22 00 80 52 ?? ?? ?? ?? ?? ?? ?? ?? F5 03 00 AA ?? ?? ?? ??",
+ "func_addr_this_build": "0x69457c",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "0x1534540"
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/dylib/tests/sigdb-fixtures/vtable_va_garbage.json b/dylib/tests/sigdb-fixtures/vtable_va_garbage.json
new file mode 100644
index 0000000..6793b59
--- /dev/null
+++ b/dylib/tests/sigdb-fixtures/vtable_va_garbage.json
@@ -0,0 +1,85 @@
+{
+ "schema_version": 3,
+ "profile_version": 1,
+ "arch": "arm64",
+ "platform": "macos",
+ "steam_build": 0,
+ "steam_build_date": "",
+ "signatures": [
+ {
+ "name": "CCompatManager::Init",
+ "aob_hex": "?? ?? ?? D1 FC 6F 0B A9 FA 67 0C A9 F8 5F 0D A9 F6 57 0E A9 F4 4F 0F A9 FD 7B 10 A9 FD 03 04 91 F4 03 01 AA F3 03 00 AA ?? ?? ?? ?? 08 A9 40 F9 08 01 40 F9 ?? ?? ?? ?? 29 01 28 91 A8 03 1A F8 09 00 00 F9 F9 03 00 AA 3F 8F 00 F8 1F 08 00 F9",
+ "func_addr_this_build": "0x690f6c",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "not-a-number"
+ }
+ },
+ {
+ "name": "CCompatManager::BIsCompatibilityToolEnabled",
+ "aob_hex": "FF 03 01 D1 F4 4F 02 A9 FD 7B 03 A9 ?? ?? ?? ?? F4 03 01 AA F3 03 00 AA E1 17 00 B9 ?? ?? ?? ?? 08 0D 40 F9 08 01 40 B9 E8 00 00 34 ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? 81 00 80 52 ?? ?? ?? ??",
+ "func_addr_this_build": "0x6962f0",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "not-a-number"
+ }
+ },
+ {
+ "name": "CCompatManager::YldRegisterTool",
+ "aob_hex": "88 3E 40 F9 1F 01 00 F1 56 03 88 9A E0 03 16 AA ?? ?? ?? 94 E8 03 00 AA 89 22 40 F9 3F 01 00 F1 40 03 89 9A 88 00 00 34",
+ "func_addr_this_build": "0x699f00",
+ "match_offset": 168,
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "not-a-number"
+ }
+ },
+ {
+ "name": "CCompatManager::GetOSListOverrideForApp.oslist_gate",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695ed0",
+ "aob_hex": "E0 03 14 AA ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? A8 3A 40 F9 1F 01 00 F1 C8 02 88 9A 68 02 00 F9 33 00 80 52",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "not-a-number"
+ }
+ },
+ {
+ "name": "CCompatManager::ResolveCompatToolForApp.local_redirect",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695fc4",
+ "aob_hex": "80 02 40 F9 ?? ?? ?? ?? 01 60 40 B9 ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? 08 01 40 F9 09 30 82 52 00 01 09 8B 02 00 80 52 ?? ?? ?? ??",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "not-a-number"
+ }
+ },
+ {
+ "name": "CAppManager::TerminateProcessByPid",
+ "aob_hex": "F4 4F BE A9 FD 7B 01 A9 FD 43 00 91 F3 03 00 AA ?? ?? ?? ?? F4 03 00 AA ?? ?? ?? ?? 00 F9 45 F9 E2 03 13 AA ?? ?? ?? ?? ?? ?? ?? ?? F3 03 00 AA",
+ "func_addr_this_build": "0xd6f28",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "not-a-number"
+ }
+ },
+ {
+ "name": "CCompatManager::FindToolForTargetApp",
+ "aob_hex": "FF 83 01 D1 F6 57 03 A9 F4 4F 04 A9 FD 7B 05 A9 FD 43 01 91 A1 C3 1D B8 08 C0 5E 39 1F 05 00 71 ?? ?? ?? ?? F4 03 01 AA F3 03 00 AA ?? ?? ?? ?? 08 21 38 91 15 01 40 F9 16 07 82 52 A0 02 16 8B ?? ?? ?? ?? A0 02 16 8B E1 03 14 AA ?? ?? ?? ??",
+ "func_addr_this_build": "0x69577c",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "not-a-number"
+ }
+ },
+ {
+ "name": "CCompatManager::GetValidPlatforms",
+ "aob_hex": "FF 03 01 D1 F6 57 01 A9 F4 4F 02 A9 FD 7B 03 A9 FD C3 00 91 F4 03 01 AA F6 03 00 AA ?? ?? ?? ?? 08 21 38 91 13 01 40 F9 15 07 82 52 60 02 15 8B ?? ?? ?? ?? 60 02 15 8B E1 03 14 AA 22 00 80 52 ?? ?? ?? ?? ?? ?? ?? ?? F5 03 00 AA ?? ?? ?? ??",
+ "func_addr_this_build": "0x69457c",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "not-a-number"
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/dylib/tests/sigdb-fixtures/vtable_va_max.json b/dylib/tests/sigdb-fixtures/vtable_va_max.json
new file mode 100644
index 0000000..728eaff
--- /dev/null
+++ b/dylib/tests/sigdb-fixtures/vtable_va_max.json
@@ -0,0 +1,85 @@
+{
+ "schema_version": 3,
+ "profile_version": 1,
+ "arch": "arm64",
+ "platform": "macos",
+ "steam_build": 0,
+ "steam_build_date": "",
+ "signatures": [
+ {
+ "name": "CCompatManager::Init",
+ "aob_hex": "?? ?? ?? D1 FC 6F 0B A9 FA 67 0C A9 F8 5F 0D A9 F6 57 0E A9 F4 4F 0F A9 FD 7B 10 A9 FD 03 04 91 F4 03 01 AA F3 03 00 AA ?? ?? ?? ?? 08 A9 40 F9 08 01 40 F9 ?? ?? ?? ?? 29 01 28 91 A8 03 1A F8 09 00 00 F9 F9 03 00 AA 3F 8F 00 F8 1F 08 00 F9",
+ "func_addr_this_build": "0x690f6c",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "0xffffffffffffffff"
+ }
+ },
+ {
+ "name": "CCompatManager::BIsCompatibilityToolEnabled",
+ "aob_hex": "FF 03 01 D1 F4 4F 02 A9 FD 7B 03 A9 ?? ?? ?? ?? F4 03 01 AA F3 03 00 AA E1 17 00 B9 ?? ?? ?? ?? 08 0D 40 F9 08 01 40 B9 E8 00 00 34 ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? 81 00 80 52 ?? ?? ?? ??",
+ "func_addr_this_build": "0x6962f0",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "0xffffffffffffffff"
+ }
+ },
+ {
+ "name": "CCompatManager::YldRegisterTool",
+ "aob_hex": "88 3E 40 F9 1F 01 00 F1 56 03 88 9A E0 03 16 AA ?? ?? ?? 94 E8 03 00 AA 89 22 40 F9 3F 01 00 F1 40 03 89 9A 88 00 00 34",
+ "func_addr_this_build": "0x699f00",
+ "match_offset": 168,
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "0xffffffffffffffff"
+ }
+ },
+ {
+ "name": "CCompatManager::GetOSListOverrideForApp.oslist_gate",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695ed0",
+ "aob_hex": "E0 03 14 AA ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? A8 3A 40 F9 1F 01 00 F1 C8 02 88 9A 68 02 00 F9 33 00 80 52",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "0xffffffffffffffff"
+ }
+ },
+ {
+ "name": "CCompatManager::ResolveCompatToolForApp.local_redirect",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695fc4",
+ "aob_hex": "80 02 40 F9 ?? ?? ?? ?? 01 60 40 B9 ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? 08 01 40 F9 09 30 82 52 00 01 09 8B 02 00 80 52 ?? ?? ?? ??",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "0xffffffffffffffff"
+ }
+ },
+ {
+ "name": "CAppManager::TerminateProcessByPid",
+ "aob_hex": "F4 4F BE A9 FD 7B 01 A9 FD 43 00 91 F3 03 00 AA ?? ?? ?? ?? F4 03 00 AA ?? ?? ?? ?? 00 F9 45 F9 E2 03 13 AA ?? ?? ?? ?? ?? ?? ?? ?? F3 03 00 AA",
+ "func_addr_this_build": "0xd6f28",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "0xffffffffffffffff"
+ }
+ },
+ {
+ "name": "CCompatManager::FindToolForTargetApp",
+ "aob_hex": "FF 83 01 D1 F6 57 03 A9 F4 4F 04 A9 FD 7B 05 A9 FD 43 01 91 A1 C3 1D B8 08 C0 5E 39 1F 05 00 71 ?? ?? ?? ?? F4 03 01 AA F3 03 00 AA ?? ?? ?? ?? 08 21 38 91 15 01 40 F9 16 07 82 52 A0 02 16 8B ?? ?? ?? ?? A0 02 16 8B E1 03 14 AA ?? ?? ?? ??",
+ "func_addr_this_build": "0x69577c",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "0xffffffffffffffff"
+ }
+ },
+ {
+ "name": "CCompatManager::GetValidPlatforms",
+ "aob_hex": "FF 03 01 D1 F6 57 01 A9 F4 4F 02 A9 FD 7B 03 A9 FD C3 00 91 F4 03 01 AA F6 03 00 AA ?? ?? ?? ?? 08 21 38 91 13 01 40 F9 15 07 82 52 60 02 15 8B ?? ?? ?? ?? 60 02 15 8B E1 03 14 AA 22 00 80 52 ?? ?? ?? ?? ?? ?? ?? ?? F5 03 00 AA ?? ?? ?? ??",
+ "func_addr_this_build": "0x69457c",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "0xffffffffffffffff"
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/dylib/tests/sigdb-fixtures/vtable_va_real.json b/dylib/tests/sigdb-fixtures/vtable_va_real.json
new file mode 100644
index 0000000..09649a4
--- /dev/null
+++ b/dylib/tests/sigdb-fixtures/vtable_va_real.json
@@ -0,0 +1,19 @@
+{
+ "schema_version": 3,
+ "profile_version": 1,
+ "arch": "arm64",
+ "platform": "macos",
+ "steam_build": 0,
+ "steam_build_date": "",
+ "signatures": [
+ {
+ "name": "CCompatManager::Init",
+ "aob_hex": "?? ?? ?? D1 FC 6F 0B A9 FA 67 0C A9 F8 5F 0D A9 F6 57 0E A9 F4 4F 0F A9 FD 7B 10 A9 FD 03 04 91 F4 03 01 AA F3 03 00 AA ?? ?? ?? ?? 08 A9 40 F9 08 01 40 F9 ?? ?? ?? ?? 29 01 28 91 A8 03 1A F8 09 00 00 F9 F9 03 00 AA 3F 8F 00 F8 1F 08 00 F9",
+ "func_addr_this_build": "0x690f6c",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "0x167c2b8"
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/dylib/tests/sigdb-fixtures/vtable_va_wild.json b/dylib/tests/sigdb-fixtures/vtable_va_wild.json
new file mode 100644
index 0000000..554bb2d
--- /dev/null
+++ b/dylib/tests/sigdb-fixtures/vtable_va_wild.json
@@ -0,0 +1,85 @@
+{
+ "schema_version": 3,
+ "profile_version": 1,
+ "arch": "arm64",
+ "platform": "macos",
+ "steam_build": 0,
+ "steam_build_date": "",
+ "signatures": [
+ {
+ "name": "CCompatManager::Init",
+ "aob_hex": "?? ?? ?? D1 FC 6F 0B A9 FA 67 0C A9 F8 5F 0D A9 F6 57 0E A9 F4 4F 0F A9 FD 7B 10 A9 FD 03 04 91 F4 03 01 AA F3 03 00 AA ?? ?? ?? ?? 08 A9 40 F9 08 01 40 F9 ?? ?? ?? ?? 29 01 28 91 A8 03 1A F8 09 00 00 F9 F9 03 00 AA 3F 8F 00 F8 1F 08 00 F9",
+ "func_addr_this_build": "0x690f6c",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "0xdeadbeef000"
+ }
+ },
+ {
+ "name": "CCompatManager::BIsCompatibilityToolEnabled",
+ "aob_hex": "FF 03 01 D1 F4 4F 02 A9 FD 7B 03 A9 ?? ?? ?? ?? F4 03 01 AA F3 03 00 AA E1 17 00 B9 ?? ?? ?? ?? 08 0D 40 F9 08 01 40 B9 E8 00 00 34 ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? 81 00 80 52 ?? ?? ?? ??",
+ "func_addr_this_build": "0x6962f0",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "0xdeadbeef000"
+ }
+ },
+ {
+ "name": "CCompatManager::YldRegisterTool",
+ "aob_hex": "88 3E 40 F9 1F 01 00 F1 56 03 88 9A E0 03 16 AA ?? ?? ?? 94 E8 03 00 AA 89 22 40 F9 3F 01 00 F1 40 03 89 9A 88 00 00 34",
+ "func_addr_this_build": "0x699f00",
+ "match_offset": 168,
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "0xdeadbeef000"
+ }
+ },
+ {
+ "name": "CCompatManager::GetOSListOverrideForApp.oslist_gate",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695ed0",
+ "aob_hex": "E0 03 14 AA ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? A8 3A 40 F9 1F 01 00 F1 C8 02 88 9A 68 02 00 F9 33 00 80 52",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "0xdeadbeef000"
+ }
+ },
+ {
+ "name": "CCompatManager::ResolveCompatToolForApp.local_redirect",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695fc4",
+ "aob_hex": "80 02 40 F9 ?? ?? ?? ?? 01 60 40 B9 ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? 08 01 40 F9 09 30 82 52 00 01 09 8B 02 00 80 52 ?? ?? ?? ??",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "0xdeadbeef000"
+ }
+ },
+ {
+ "name": "CAppManager::TerminateProcessByPid",
+ "aob_hex": "F4 4F BE A9 FD 7B 01 A9 FD 43 00 91 F3 03 00 AA ?? ?? ?? ?? F4 03 00 AA ?? ?? ?? ?? 00 F9 45 F9 E2 03 13 AA ?? ?? ?? ?? ?? ?? ?? ?? F3 03 00 AA",
+ "func_addr_this_build": "0xd6f28",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "0xdeadbeef000"
+ }
+ },
+ {
+ "name": "CCompatManager::FindToolForTargetApp",
+ "aob_hex": "FF 83 01 D1 F6 57 03 A9 F4 4F 04 A9 FD 7B 05 A9 FD 43 01 91 A1 C3 1D B8 08 C0 5E 39 1F 05 00 71 ?? ?? ?? ?? F4 03 01 AA F3 03 00 AA ?? ?? ?? ?? 08 21 38 91 15 01 40 F9 16 07 82 52 A0 02 16 8B ?? ?? ?? ?? A0 02 16 8B E1 03 14 AA ?? ?? ?? ??",
+ "func_addr_this_build": "0x69577c",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "0xdeadbeef000"
+ }
+ },
+ {
+ "name": "CCompatManager::GetValidPlatforms",
+ "aob_hex": "FF 03 01 D1 F6 57 01 A9 F4 4F 02 A9 FD 7B 03 A9 FD C3 00 91 F4 03 01 AA F6 03 00 AA ?? ?? ?? ?? 08 21 38 91 13 01 40 F9 15 07 82 52 60 02 15 8B ?? ?? ?? ?? 60 02 15 8B E1 03 14 AA 22 00 80 52 ?? ?? ?? ?? ?? ?? ?? ?? F5 03 00 AA ?? ?? ?? ??",
+ "func_addr_this_build": "0x69457c",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "0xdeadbeef000"
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/dylib/tests/sigdb-fixtures/vtable_va_zero.json b/dylib/tests/sigdb-fixtures/vtable_va_zero.json
new file mode 100644
index 0000000..681d588
--- /dev/null
+++ b/dylib/tests/sigdb-fixtures/vtable_va_zero.json
@@ -0,0 +1,85 @@
+{
+ "schema_version": 3,
+ "profile_version": 1,
+ "arch": "arm64",
+ "platform": "macos",
+ "steam_build": 0,
+ "steam_build_date": "",
+ "signatures": [
+ {
+ "name": "CCompatManager::Init",
+ "aob_hex": "?? ?? ?? D1 FC 6F 0B A9 FA 67 0C A9 F8 5F 0D A9 F6 57 0E A9 F4 4F 0F A9 FD 7B 10 A9 FD 03 04 91 F4 03 01 AA F3 03 00 AA ?? ?? ?? ?? 08 A9 40 F9 08 01 40 F9 ?? ?? ?? ?? 29 01 28 91 A8 03 1A F8 09 00 00 F9 F9 03 00 AA 3F 8F 00 F8 1F 08 00 F9",
+ "func_addr_this_build": "0x690f6c",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "0x0"
+ }
+ },
+ {
+ "name": "CCompatManager::BIsCompatibilityToolEnabled",
+ "aob_hex": "FF 03 01 D1 F4 4F 02 A9 FD 7B 03 A9 ?? ?? ?? ?? F4 03 01 AA F3 03 00 AA E1 17 00 B9 ?? ?? ?? ?? 08 0D 40 F9 08 01 40 B9 E8 00 00 34 ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? 81 00 80 52 ?? ?? ?? ??",
+ "func_addr_this_build": "0x6962f0",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "0x0"
+ }
+ },
+ {
+ "name": "CCompatManager::YldRegisterTool",
+ "aob_hex": "88 3E 40 F9 1F 01 00 F1 56 03 88 9A E0 03 16 AA ?? ?? ?? 94 E8 03 00 AA 89 22 40 F9 3F 01 00 F1 40 03 89 9A 88 00 00 34",
+ "func_addr_this_build": "0x699f00",
+ "match_offset": 168,
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "0x0"
+ }
+ },
+ {
+ "name": "CCompatManager::GetOSListOverrideForApp.oslist_gate",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695ed0",
+ "aob_hex": "E0 03 14 AA ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? A8 3A 40 F9 1F 01 00 F1 C8 02 88 9A 68 02 00 F9 33 00 80 52",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "0x0"
+ }
+ },
+ {
+ "name": "CCompatManager::ResolveCompatToolForApp.local_redirect",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695fc4",
+ "aob_hex": "80 02 40 F9 ?? ?? ?? ?? 01 60 40 B9 ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? 08 01 40 F9 09 30 82 52 00 01 09 8B 02 00 80 52 ?? ?? ?? ??",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "0x0"
+ }
+ },
+ {
+ "name": "CAppManager::TerminateProcessByPid",
+ "aob_hex": "F4 4F BE A9 FD 7B 01 A9 FD 43 00 91 F3 03 00 AA ?? ?? ?? ?? F4 03 00 AA ?? ?? ?? ?? 00 F9 45 F9 E2 03 13 AA ?? ?? ?? ?? ?? ?? ?? ?? F3 03 00 AA",
+ "func_addr_this_build": "0xd6f28",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "0x0"
+ }
+ },
+ {
+ "name": "CCompatManager::FindToolForTargetApp",
+ "aob_hex": "FF 83 01 D1 F6 57 03 A9 F4 4F 04 A9 FD 7B 05 A9 FD 43 01 91 A1 C3 1D B8 08 C0 5E 39 1F 05 00 71 ?? ?? ?? ?? F4 03 01 AA F3 03 00 AA ?? ?? ?? ?? 08 21 38 91 15 01 40 F9 16 07 82 52 A0 02 16 8B ?? ?? ?? ?? A0 02 16 8B E1 03 14 AA ?? ?? ?? ??",
+ "func_addr_this_build": "0x69577c",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "0x0"
+ }
+ },
+ {
+ "name": "CCompatManager::GetValidPlatforms",
+ "aob_hex": "FF 03 01 D1 F6 57 01 A9 F4 4F 02 A9 FD 7B 03 A9 FD C3 00 91 F4 03 01 AA F6 03 00 AA ?? ?? ?? ?? 08 21 38 91 13 01 40 F9 15 07 82 52 60 02 15 8B ?? ?? ?? ?? 60 02 15 8B E1 03 14 AA 22 00 80 52 ?? ?? ?? ?? ?? ?? ?? ?? F5 03 00 AA ?? ?? ?? ??",
+ "func_addr_this_build": "0x69457c",
+ "anchor": {
+ "kind": "vtable_slot",
+ "va": "0x0"
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/dylib/tests/sigdb-fixtures/wrong_kind.json b/dylib/tests/sigdb-fixtures/wrong_kind.json
new file mode 100644
index 0000000..c62c6b6
--- /dev/null
+++ b/dylib/tests/sigdb-fixtures/wrong_kind.json
@@ -0,0 +1,90 @@
+{
+ "schema_version": 3,
+ "profile_version": 1,
+ "arch": "arm64",
+ "platform": "macos",
+ "steam_build": 0,
+ "steam_build_date": "",
+ "signatures": [
+ {
+ "name": "CCompatManager::Init",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x690f6c",
+ "anchor": {
+ "kind": "not_a_real_kind",
+ "value": "STEAM_COMPAT_TOOL_MAPPINGS"
+ }
+ },
+ {
+ "name": "CCompatManager::BIsCompatibilityToolEnabled",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x6962f0",
+ "anchor": {
+ "kind": "not_a_real_kind",
+ "value": "CCompatManager::BIsCompatibilityToolEnabled"
+ }
+ },
+ {
+ "name": "CCompatManager::YldRegisterTool",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x699f00",
+ "match_offset": 168,
+ "anchor": {
+ "kind": "not_a_real_kind",
+ "value": "CCompatManager::YldRegisterTool"
+ }
+ },
+ {
+ "name": "CCompatManager::GetOSListOverrideForApp.oslist_gate",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695ed0",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "not_a_real_kind",
+ "value": "pTool != nullptr",
+ "nth_xref": 1,
+ "fn_offset": 196
+ }
+ },
+ {
+ "name": "CCompatManager::ResolveCompatToolForApp.local_redirect",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695fc4",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "anchor": {
+ "kind": "not_a_real_kind",
+ "value": "GetAppInstallDir failed for tool %u \"%s\"",
+ "fn_offset": 116
+ }
+ },
+ {
+ "name": "CAppManager::TerminateProcessByPid",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0xd6f28",
+ "anchor": {
+ "kind": "not_a_real_kind",
+ "value": "terminate",
+ "indirect": true,
+ "caller_hops": 1
+ }
+ },
+ {
+ "name": "CCompatManager::FindToolForTargetApp",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x69577c",
+ "anchor": {
+ "kind": "not_a_real_kind",
+ "value": "FindToolForTargetApp matched with itself - ignoring: %u %s"
+ }
+ },
+ {
+ "name": "CCompatManager::GetValidPlatforms",
+ "aob_hex": "EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE",
+ "func_addr_this_build": "0x69457c",
+ "anchor": {
+ "kind": "not_a_real_kind",
+ "value": "AppID %u does not advertise linux as a supported platform, but a linux specific depot is present.\n"
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/dylib/tests/spawn-env.c b/dylib/tests/spawn-env.c
new file mode 100644
index 0000000..873135c
--- /dev/null
+++ b/dylib/tests/spawn-env.c
@@ -0,0 +1,117 @@
+// The decision is in two static functions, so the unit under test is included rather
+// than linked. What matters is which child keeps the insert and which entries survive
+// the strip, neither of which needs Dobby or a live client.
+#include "../hooks/hook_spawn.c"
+
+#include <stdio.h>
+
+int np_log_level = 0;
+FILE *np_log_file = NULL;
+
+int DobbyHook(void *address, void *replace_call, void **origin_call) {
+ (void)address; (void)replace_call; (void)origin_call;
+ return -1;
+}
+
+void *DobbySymbolResolver(const char *image_name, const char *symbol_name) {
+ (void)image_name; (void)symbol_name;
+ return NULL;
+}
+
+int np_hooks_env_lists_label(const char *var, const char *label) {
+ (void)var; (void)label;
+ return 0;
+}
+
+static int failures;
+
+static void check(int ok, const char *what) {
+ if (!ok) {
+ printf("FAIL %s\n", what);
+ failures++;
+ }
+}
+
+static void keeps(const char *path, int want, const char *what) {
+ check(np_target_keeps_insert(path) == want, what);
+}
+
+// Entries of `got`, in order, against a NULL-terminated expectation.
+static void survives(char *const envp[], const char *const want[], const char *what) {
+ char **got = np_without_insert(envp);
+ if (!want) {
+ check(got == NULL, what);
+ free(got);
+ return;
+ }
+ if (!got) {
+ check(0, what);
+ return;
+ }
+ int i = 0;
+ for (; want[i] && got[i]; i++) {
+ if (strcmp(want[i], got[i]) != 0)
+ break;
+ }
+ check(want[i] == NULL && got[i] == NULL, what);
+ free(got);
+}
+
+int main(void) {
+ // The client's own re-exec is the one child that has to keep the insert, because the
+ // hooks install in that process and an exec does not get LSEnvironment.
+ keeps("/Applications/Steam.app/Contents/MacOS/steam_osx", 1, "an absolute steam_osx keeps it");
+ keeps("/Users/x/Library/Application Support/Steam/Steam.AppBundle/Steam/Contents/MacOS/steam_osx",
+ 1, "the AppBundle copy of steam_osx keeps it");
+ keeps("steam_osx", 1, "a bare steam_osx keeps it");
+ keeps(NULL, 1, "an unnamed target keeps it");
+
+ // Everything else is what dyld was killing.
+ keeps("/bin/sh", 0, "sh loses it");
+ keeps("/bin/bash", 0, "bash loses it");
+ keeps("/usr/sbin/lsof", 0, "lsof loses it");
+ keeps("/bin/launchctl", 0, "launchctl loses it");
+ keeps("/Applications/Steam.app/Contents/MacOS/Steam Helper", 1,
+ "the helper keeps it for the webpatch interpose");
+ // A prefix match on the directory would hand the insert to every one of these.
+ keeps("/Applications/Steam.app/Contents/MacOS/steam_osx_helper", 0,
+ "a name starting with steam_osx loses it");
+
+ survives(NULL, NULL, "a null environment is left alone");
+
+ char *plain[] = { (char *)"PATH=/bin", (char *)"HOME=/Users/x", NULL };
+ survives(plain, NULL, "an environment without the insert is not copied");
+
+ char *with[] = { (char *)"PATH=/bin",
+ (char *)"DYLD_INSERT_LIBRARIES=/Applications/Steam.app/Contents/MacOS/notproton.dylib",
+ (char *)"HOME=/Users/x", NULL };
+ const char *without[] = { "PATH=/bin", "HOME=/Users/x", NULL };
+ survives(with, without, "the insert is taken out and the rest kept in order");
+
+ char *only[] = { (char *)"DYLD_INSERT_LIBRARIES=/x.dylib", NULL };
+ const char *empty[] = { NULL };
+ survives(only, empty, "an environment of nothing but the insert comes back empty");
+
+ // The compat tool's run script reads STEAM_DYLD_INSERT_LIBRARIES to build the overlay's
+ // insert. A match that was not anchored at the start would eat it and take the overlay
+ // out of every game launch.
+ char *shim[] = { (char *)"STEAM_DYLD_INSERT_LIBRARIES=/overlay.dylib", NULL };
+ survives(shim, NULL, "the overlay's own variable is not the insert");
+
+ // The key has to carry its '=' or a longer name sharing the prefix goes too.
+ char *longer[] = { (char *)"DYLD_INSERT_LIBRARIES_EXTRA=/x.dylib", NULL };
+ survives(longer, NULL, "a longer name sharing the prefix is not the insert");
+
+ char *twice[] = { (char *)"DYLD_INSERT_LIBRARIES=/a.dylib",
+ (char *)"PATH=/bin",
+ (char *)"DYLD_INSERT_LIBRARIES=/b.dylib", NULL };
+ const char *once[] = { "PATH=/bin", NULL };
+ survives(twice, once, "every copy of the insert is taken out");
+
+ if (failures) {
+ printf("==> spawn env: %d check(s) failed\n", failures);
+ return 1;
+ }
+ printf("==> spawn env: steam_osx and Steam Helper keep the insert, every other child loses it\n");
+ return 0;
+}
diff --git a/dylib/tests/spawn-live/child.c b/dylib/tests/spawn-live/child.c
new file mode 100644
index 0000000..522b891
--- /dev/null
+++ b/dylib/tests/spawn-live/child.c
@@ -0,0 +1,4 @@
+// Prints its own environment so the caller can see whether the insert reached it.
+#include <stdio.h>
+extern char **environ;
+int main(void) { for (int i = 0; environ[i]; i++) puts(environ[i]); return 0; }
diff --git a/dylib/tests/spawn-live/driver.c b/dylib/tests/spawn-live/driver.c
new file mode 100644
index 0000000..5586670
--- /dev/null
+++ b/dylib/tests/spawn-live/driver.c
@@ -0,0 +1,14 @@
+// Spawns argv[1] the way the client spawns its port check, through posix_spawn with its
+// own environment. Named steam_osx by the make target so the dylib installs its hooks.
+#include <spawn.h>
+#include <sys/wait.h>
+extern char **environ;
+int main(int argc, char **argv) {
+ if (argc != 2) return 2;
+ char *a[] = { argv[1], NULL };
+ pid_t pid;
+ int st = 0;
+ if (posix_spawn(&pid, argv[1], NULL, NULL, a, environ) != 0) return 111;
+ waitpid(pid, &st, 0);
+ return 0;
+}
diff --git a/dylib/tests/webpatch-fixtures/gates.forcetool.js b/dylib/tests/webpatch-fixtures/gates.forcetool.js
new file mode 100644
index 0000000..931b039
--- /dev/null
+++ b/dylib/tests/webpatch-fixtures/gates.forcetool.js
@@ -0,0 +1,9 @@
+Developer_HDRCompatTesting"),description:(0,c.we)("#Settings_Developer_HDRCompatTesting_Desc")}),(0,i.jsx)(N.M3,{}),(0,i.jsx)(L.Y6,{showWhenUnavailable:!0})]})}function ue(e){return(0,T.CI)()?(0,i.jsxs)(s.XY,{label:(0,c.we)("#Settings_SteamPlay_SteamPlay"),children:[(0,i.jsx)("div",{children:(0,c.we)("#Settings_SteamPlay_IsWildcardEnabled")}),(0,i.js
+title:(0,A.we)("#AppProperties_ShortcutPage"),route:F.BV.AppProperties.Shortcut(),link:F.BV.AppProperties.Shortcut(t),content:(0,i.jsx)(gr,{appId:r.unAppID})}),(0,f.CI)()&&o.push({title:(0,A.we)("#AppProperties_CompatibilityPage"),route:F.BV.AppProperties.Compatibility(),link:F.BV.AppProperties.Compatibility(t),content:(0,i.jsx)(Rt,{details:r})}),o.push({title:(0,A.we)("#AppProperties_Co
+(o.push({title:(0,A.we)("#AppProperties_GeneralPage"),route:F.BV.AppProperties.General(),link:F.BV.AppProperties.General(t),content:(0,i.jsx)(At,{details:r})}),(0,f.CI)()&&o.push({title:(0,A.we)("#AppProperties_CompatibilityPage"),route:F.BV.AppProperties.Compatibility(),link:F.BV.AppProperties.Compatibility(t),content:(0,i.jsx)(Rt,{details:r})}),o.push({title:(0,A.we)("#AppProperties_Up
+:(0,i.jsx)(ls,{})},InGame:{visible:t,title:(0,A.we)("#Settings_Page_InGame"),icon:(0,i.jsx)(m.InGame,{}),route:s.BV.Settings.InGame(),content:(0,i.jsx)(ks,{})},Compatibility:{visible:t&&(0,f.CI)()&&!(0,f.rf)(),title:(0,A.we)("#Settings_Page_Compatibility"),icon:(0,i.jsx)(m.SteamLogo,{}),route:s.BV.Settings.Compatibility(),content:(0,i.jsx)(Ia.Y,{})},Interface:{visibl
+e(!1),g=o||m,C=n.useCallback(e=>{p(e),e?SteamClient.Apps.SpecifyCompatTool(t.unAppID,o?"":l):SteamClient.Apps.SpecifyCompatTool(t.unAppID,"")},[t.unAppID,l,o]);return(0,i.jsxs)(i.Fragment,{children:[0!=a.length&&(0,i.jsx)(_r,{label:(0,A.we)("#AppProperties_CompatilibityForceTool"),checked:g,onChange:C,disabled:!r||0===a.length}),g&&a.length>0&&(0,i.jsx)(c.m,{strClassName:K().TopGap,rgOptions:d,selectedOption:t.strCompatToolName,onChange:e=>SteamClient.Apps.SpecifyCompatTool(t.unAppID,e.data)})]})}),xt=(0,a.PA)(e=>{const{details:t}=e,r=(0,st.GY)();if(!f.TS.ON_FRAME||!r)return null;const a={ThunksDB_GL:0,ThunksDB_Vulkan:0,Multiblock:1},o=(0,s.q3)(()=>u.rV
+ibity_OverrideArmTranslationOptions"),checked:g,onChange:h,disabled:!o},"fexgroup"),g&&(0,i.jsx)("div",{className:K().CompatExperimentOptions,children:_})]})}),Rt=(0,a.PA)(e=>(0,i.jsxs)(c.nB,{children:[(0,i.jsx)("div",{className:K().HiddenIfNotLast,children:(0,A.we)("#AppProperties_CompatibilityNoOptions")}),(0,i.jsx)(It,{...e}),(0,i.jsx)(xt,{...e})]}));function Tt(e){const{details:t}=e,[r]=(0,u.e_)("b24HourClock");return(0,i.jsxs)(c.nB,{children:[(0,i.jsx)(Nt,{details:t}),(0,i.jsx)(Ot,{details:t}),(0,i.jsxs)("
+r_client_data.active_beta}get is_available_on_current_platform(){return this.local_per_client_data&&this.local_per_client_data.is_available_on_current_platform}get is_invalid_os_type(){return this.most_available_per_client_data.is_invalid_os_type}get selected_per_client_data(){let e=this.per_client_data.find(e=>e.clientid==this.selected_clientid);return e||(e=this.most_available_per_client_data),e}get mo
+ie().HidePlayBar,bInPage:!0,details:a,overview:s,stickyheader:p,onGameInfoToggle:o,onSeek:t.SeekToSection,bShowInfoExpanded:h,bShowingLaunchDetails:_},s.appid),s.is_invalid_os_type&&(0,n.jsx)(U,{}),r.has("info")&&(0,n.jsx)(x.b,{concise:i,overview:s,details:a,expand:h,suppressTransition:C}),(0,n.jsx)(k.Qd,{overview:s,details:a,workshopVisible:f,marketPrese
+,{})}),(0,h.we)("#GameList_Entry_Invalid_OSType")]}),(0,n.jsx)("div",{className:z().WarningText,children:(0,n.jsxs)("div",{className:z().WarningText2,children:[(0,h.we)("#GameList_Entry_Invalid_OSType2"),(0,n.jsx)("a",{href:"https://help.steampowered.com/faqs/view/5E0D-522A-4E62-B6EF",className:z().WarningText3,children:(0,h.we)("#GameList_Entry_Invalid_OSType3
diff --git a/dylib/tests/webpatch-fixtures/gates.selecttool-rebuilt.js b/dylib/tests/webpatch-fixtures/gates.selecttool-rebuilt.js
new file mode 100644
index 0000000..41f7e7b
--- /dev/null
+++ b/dylib/tests/webpatch-fixtures/gates.selecttool-rebuilt.js
@@ -0,0 +1,8 @@
+#AppProperties_Compat_SelectTool
+tle:(0,d.we)("#AppProperties_ShortcutPage"),route:G.BV.AppProperties.Shortcut(),link:G.BV.AppProperties.Shortcut(Ur),content:(0,e.jsx)(Ji,{appId:Xr.unAppID})}),(0,y.CI)()&&Nr.push({title:(0,d.we)("#AppProperties_CompatibilityPage"),route:G.BV.AppProperties.Compatibility(),link:G.BV.AppProperties.Compatibility(Ur),content:(0,e.jsx)(pe,{details:Xr})}),Nr.push({title:(0,d.we)("#AppProperties
+.push({title:(0,d.we)("#AppProperties_GeneralPage"),route:G.BV.AppProperties.General(),link:G.BV.AppProperties.General(Ur),content:(0,e.jsx)(et,{details:Xr})}),(0,y.CI)()&&Nr.push({title:(0,d.we)("#AppProperties_CompatibilityPage"),route:G.BV.AppProperties.Compatibility(),link:G.BV.AppProperties.Compatibility(Ur),content:(0,e.jsx)(pe,{details:Xr})}),Nr.push({title:(0,d.we)("#AppProperties
+(0,e.jsx)(K1,{})},InGame:{visible:Dr,title:(0,d.we)("#Settings_Page_InGame"),icon:(0,e.jsx)(c.InGame,{}),route:r.BV.Settings.InGame(),content:(0,e.jsx)(sl,{})},Compatibility:{visible:Dr&&(0,y.CI)(),title:(0,d.we)("#Settings_Page_Compatibility"),icon:(0,e.jsx)(c.SteamLogo,{}),route:r.BV.Settings.Compatibility(),content:(0,e.jsx)(x1.YW,{})},Interface:{visible:Dr,t
+r_client_data.active_beta}get is_available_on_current_platform(){return this.local_per_client_data&&this.local_per_client_data.is_available_on_current_platform}get is_invalid_os_type(){return this.most_available_per_client_data.is_invalid_os_type}get selected_per_client_data(){let H=this.per_client_data.find($=>$.clientid==this.selected_clientid);return H||(H=this.most_available_per_client_data),H}get mo
+ePlayBar,bInPage:!0,details:le,overview:We,stickyheader:Re,onGameInfoToggle:xe,onSeek:Xe.SeekToSection,bShowInfoExpanded:vt,bShowingLaunchDetails:zt},We.appid),We.is_invalid_os_type&&(0,e.jsx)(U,{}),Me.has("info")&&(0,e.jsx)(S.b,{concise:fe,overview:We,details:le,expand:vt,suppressTransition:At}),(0,e.jsx)(x.Qd,{overview:We,details:le,workshopVisible:St,ma
+,{})}),(0,h.we)("#GameList_Entry_Invalid_OSType")]}),(0,e.jsx)("div",{className:Q().WarningText,children:(0,e.jsxs)("div",{className:Q().WarningText2,children:[(0,h.we)("#GameList_Entry_Invalid_OSType2"),(0,e.jsx)("a",{href:"https://help.steampowered.com/faqs/view/5E0D-522A-4E62-B6EF",className:Q().WarningText3,children:(0,h.we)("#GameList_Entry_Invalid_OSType3
+function Ae(Rj){return(0,Zq.jsxs)(Vt.XY,{label:(0,Nb.we)("#Settings_SteamPlay_SteamPlay"),children:[(0,Zq.jsx)(Ug,{}),(0,Zq.jsx)(Kx.G,{setting:"compat_show_all_tools",label:(0,Nb.we)("#Settings_SteamPlay_ShowAll"),feature:Ld.OK})]})}function Yc(Rj){return(0,Zq.jsx)(Bf.sh,{children:(0,Zq.jsx)(Ae,{})})}function Pm(Rj){return(0,Zq.jsxs)(Vt.XY,{label:(0,Nb.we)("#Settings_SteamPlay_SteamPlay"),children:[(0,Zq.jsx)(Hw,{details:Rj.details}),(0,Zq.jsx)(Kx.G,{setting:"compat_show_all_tools",label:(0,Nb.we)("#Settings_SteamPlay_ShowAll"),feature:Ld.OK})]})}})
diff --git a/dylib/tests/webpatch-fixtures/gates.selecttool.js b/dylib/tests/webpatch-fixtures/gates.selecttool.js
new file mode 100644
index 0000000..6fd47d1
--- /dev/null
+++ b/dylib/tests/webpatch-fixtures/gates.selecttool.js
@@ -0,0 +1,8 @@
+#AppProperties_Compat_SelectTool
+tle:(0,d.we)("#AppProperties_ShortcutPage"),route:G.BV.AppProperties.Shortcut(),link:G.BV.AppProperties.Shortcut(Ur),content:(0,e.jsx)(Ji,{appId:Xr.unAppID})}),(0,y.CI)()&&Nr.push({title:(0,d.we)("#AppProperties_CompatibilityPage"),route:G.BV.AppProperties.Compatibility(),link:G.BV.AppProperties.Compatibility(Ur),content:(0,e.jsx)(pe,{details:Xr})}),Nr.push({title:(0,d.we)("#AppProperties
+.push({title:(0,d.we)("#AppProperties_GeneralPage"),route:G.BV.AppProperties.General(),link:G.BV.AppProperties.General(Ur),content:(0,e.jsx)(et,{details:Xr})}),(0,y.CI)()&&Nr.push({title:(0,d.we)("#AppProperties_CompatibilityPage"),route:G.BV.AppProperties.Compatibility(),link:G.BV.AppProperties.Compatibility(Ur),content:(0,e.jsx)(pe,{details:Xr})}),Nr.push({title:(0,d.we)("#AppProperties
+(0,e.jsx)(K1,{})},InGame:{visible:Dr,title:(0,d.we)("#Settings_Page_InGame"),icon:(0,e.jsx)(c.InGame,{}),route:r.BV.Settings.InGame(),content:(0,e.jsx)(sl,{})},Compatibility:{visible:Dr&&(0,y.CI)(),title:(0,d.we)("#Settings_Page_Compatibility"),icon:(0,e.jsx)(c.SteamLogo,{}),route:r.BV.Settings.Compatibility(),content:(0,e.jsx)(x1.YW,{})},Interface:{visible:Dr,t
+r_client_data.active_beta}get is_available_on_current_platform(){return this.local_per_client_data&&this.local_per_client_data.is_available_on_current_platform}get is_invalid_os_type(){return this.most_available_per_client_data.is_invalid_os_type}get selected_per_client_data(){let H=this.per_client_data.find($=>$.clientid==this.selected_clientid);return H||(H=this.most_available_per_client_data),H}get mo
+ePlayBar,bInPage:!0,details:le,overview:We,stickyheader:Re,onGameInfoToggle:xe,onSeek:Xe.SeekToSection,bShowInfoExpanded:vt,bShowingLaunchDetails:zt},We.appid),We.is_invalid_os_type&&(0,e.jsx)(U,{}),Me.has("info")&&(0,e.jsx)(S.b,{concise:fe,overview:We,details:le,expand:vt,suppressTransition:At}),(0,e.jsx)(x.Qd,{overview:We,details:le,workshopVisible:St,ma
+,{})}),(0,h.we)("#GameList_Entry_Invalid_OSType")]}),(0,e.jsx)("div",{className:Q().WarningText,children:(0,e.jsxs)("div",{className:Q().WarningText2,children:[(0,h.we)("#GameList_Entry_Invalid_OSType2"),(0,e.jsx)("a",{href:"https://help.steampowered.com/faqs/view/5E0D-522A-4E62-B6EF",className:Q().WarningText3,children:(0,h.we)("#GameList_Entry_Invalid_OSType3
+function I(f){return(0,e.jsxs)(a.XY,{label:(0,i.we)("#Settings_SteamPlay_SteamPlay"),children:[(0,e.jsx)(P,{}),(0,e.jsx)(c.G,{setting:"compat_show_all_tools",label:(0,i.we)("#Settings_SteamPlay_ShowAll"),feature:o.OK})]})}function W(f){return(0,e.jsx)(u.sh,{children:(0,e.jsx)(I,{})})}function C(f){return(0,e.jsxs)(a.XY,{label:(0,i.we)("#Settings_SteamPlay_SteamPlay"),children:[(0,e.jsx)(y,{details:f.details}),(0,e.jsx)(c.G,{setting:"compat_show_all_tools",label:(0,i.we)("#Settings_SteamPlay_ShowAll"),feature:o.OK})]})}})
diff --git a/dylib/util/file.c b/dylib/util/file.c
new file mode 100644
index 0000000..541964f
--- /dev/null
+++ b/dylib/util/file.c
@@ -0,0 +1,65 @@
+// File/Path Helpers.
+#include "file.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <pwd.h>
+#include <sys/stat.h>
+
+#define NP_READ_CEILING (16u * 1024u * 1024u)
+
+uint8_t *np_read_whole_file(const char *path, size_t *out_len) {
+ int fd = open(path, O_RDONLY);
+ if (fd < 0)
+ return NULL;
+
+ struct stat meta;
+ if (fstat(fd, &meta) != 0 || !S_ISREG(meta.st_mode) ||
+ meta.st_size <= 0 || (uintmax_t)meta.st_size > NP_READ_CEILING) {
+ close(fd);
+ return NULL;
+ }
+
+ size_t total = (size_t)meta.st_size;
+ uint8_t *data = (uint8_t *)malloc(total);
+ if (!data) {
+ close(fd);
+ return NULL;
+ }
+
+ size_t got = 0;
+ while (got < total) {
+ ssize_t n = read(fd, data + got, total - got);
+ if (n <= 0) {
+ free(data);
+ close(fd);
+ return NULL;
+ }
+ got += (size_t)n;
+ }
+
+ close(fd);
+ *out_len = total;
+ return data;
+}
+
+const char *np_home_dir(void) {
+ const char *env = getenv("HOME");
+ if (env && env[0])
+ return env;
+
+ struct passwd *pw = getpwuid(getuid());
+ if (pw && pw->pw_dir && pw->pw_dir[0])
+ return pw->pw_dir;
+ return NULL;
+}
+
+void np_support_path(char *buf, size_t bufsz, const char *home, const char *rel) {
+ static const char base[] = "/Library/Application Support/notproton";
+ if (rel && rel[0])
+ snprintf(buf, bufsz, "%s%s/%s", home, base, rel);
+ else
+ snprintf(buf, bufsz, "%s%s", home, base);
+}
diff --git a/dylib/util/file.h b/dylib/util/file.h
new file mode 100644
index 0000000..48d2872
--- /dev/null
+++ b/dylib/util/file.h
@@ -0,0 +1,15 @@
+// File/Path Helpers.
+#ifndef NOTPROTON_UTIL_FILE_H
+#define NOTPROTON_UTIL_FILE_H
+
+#include <stdint.h>
+#include <stddef.h>
+
+// Caller owns the returned buffer. Refuses anything over 16 MB.
+uint8_t *np_read_whole_file(const char *path, size_t *out_len);
+
+const char *np_home_dir(void);
+
+void np_support_path(char *buf, size_t bufsz, const char *home, const char *rel);
+
+#endif // NOTPROTON_UTIL_FILE_H
diff --git a/dylib/util/hex.h b/dylib/util/hex.h
new file mode 100644
index 0000000..6799266
--- /dev/null
+++ b/dylib/util/hex.h
@@ -0,0 +1,14 @@
+// Hex helpers
+#ifndef NOTPROTON_UTIL_HEX_H
+#define NOTPROTON_UTIL_HEX_H
+
+static inline int np_hex_val(int ch) {
+ if (ch >= '0' && ch <= '9')
+ return ch - '0';
+ ch |= 0x20; // fold A-F onto a-f
+ if (ch >= 'a' && ch <= 'f')
+ return ch - 'a' + 10;
+ return -1;
+}
+
+#endif // NOTPROTON_UTIL_HEX_H
diff --git a/dylib/util/log.c b/dylib/util/log.c
new file mode 100644
index 0000000..ed327ae
--- /dev/null
+++ b/dylib/util/log.c
@@ -0,0 +1,83 @@
+// Logs
+#include "log.h"
+#include "file.h"
+#include <stdlib.h>
+#include <stdint.h>
+#include <sys/stat.h>
+
+int np_log_level = NP_LVL_INFO;
+FILE *np_log_file = NULL;
+
+#define NP_LOG_MAX_BYTES (16 * 1024 * 1024)
+
+#define NP_SEEN_SLOTS 8192
+
+struct np_seen_slot {
+ const void *anchor;
+ unsigned long tag;
+ unsigned char filled;
+};
+
+static struct np_seen_slot np_seen[NP_SEEN_SLOTS];
+static int np_seen_overflow;
+
+static unsigned long np_seen_fold(const void *anchor, unsigned long tag) {
+ unsigned long acc = 1469598103934665603UL; // FNV offset basis
+ unsigned long bits = (unsigned long)(uintptr_t)anchor ^ (tag << 1);
+ for (int b = 0; b < (int)sizeof(bits); b++) {
+ acc ^= (bits & 0xFF);
+ acc *= 1099511628211UL; // FNV prime
+ bits >>= 8;
+ }
+ return acc;
+}
+
+int np_log_first_hit(const void *anchor, unsigned long tag) {
+ unsigned long start = np_seen_fold(anchor, tag) % NP_SEEN_SLOTS;
+ for (unsigned long step = 0; step < NP_SEEN_SLOTS; step++) {
+ struct np_seen_slot *slot = &np_seen[(start + step) % NP_SEEN_SLOTS];
+ if (slot->filled) {
+ if (slot->anchor == anchor && slot->tag == tag)
+ return 0; // seen before
+ continue;
+ }
+ slot->anchor = anchor;
+ slot->tag = tag;
+ slot->filled = 1;
+ return 1; // first time
+ }
+ if (!np_seen_overflow) {
+ np_seen_overflow = 1;
+ NP_ERR("log dedupe table exhausted at %d entries; repeat lines now dropped",
+ NP_SEEN_SLOTS);
+ }
+ return 0;
+}
+
+void np_log_init(void) {
+ const char *want = getenv("NOTPROTON_LOG_LEVEL");
+ if (want && want[0]) {
+ int parsed = atoi(want);
+ if (parsed >= NP_LVL_ERR && parsed <= NP_LVL_DBG)
+ np_log_level = parsed;
+ }
+
+ if (np_log_file)
+ return;
+
+ const char *home = np_home_dir();
+ if (!home)
+ home = "/tmp";
+
+ char folder[512];
+ char logpath[512];
+ np_support_path(folder, sizeof(folder), home, NULL);
+ mkdir(folder, 0755);
+ snprintf(logpath, sizeof(logpath), "%s/notproton.log", folder);
+
+ struct stat info;
+ int oversize = (stat(logpath, &info) == 0 && info.st_size > NP_LOG_MAX_BYTES);
+ np_log_file = fopen(logpath, oversize ? "w" : "a");
+ if (np_log_file)
+ setlinebuf(np_log_file);
+}
diff --git a/dylib/util/log.h b/dylib/util/log.h
new file mode 100644
index 0000000..ad2c57e
--- /dev/null
+++ b/dylib/util/log.h
@@ -0,0 +1,51 @@
+// Logs
+#ifndef NOTPROTON_UTIL_LOG_H
+#define NOTPROTON_UTIL_LOG_H
+
+#include <stdio.h>
+#include <time.h>
+
+extern int np_log_level;
+extern FILE *np_log_file;
+void np_log_init(void);
+
+enum {
+ NP_LVL_ERR = 0,
+ NP_LVL_WARN,
+ NP_LVL_INFO,
+ NP_LVL_DBG,
+};
+
+#define NP_LOG_PREFIX "[notproton]"
+
+#define NP_EMIT(level, tag, fmt, ...) do { \
+ if (np_log_level >= (level)) { \
+ time_t _now = time(NULL); \
+ struct tm _cal; localtime_r(&_now, &_cal); \
+ char _ts[24]; \
+ strftime(_ts, sizeof(_ts), "%Y-%m-%d %H:%M:%S", &_cal); \
+ FILE *_sinks[2] = { stderr, np_log_file }; \
+ for (int _s = 0; _s < 2; _s++) { \
+ if (_sinks[_s]) \
+ fprintf(_sinks[_s], "%s " NP_LOG_PREFIX " %s " fmt "\n", \
+ _ts, tag, ##__VA_ARGS__); \
+ } \
+ } \
+} while(0)
+
+#define NP_ERR(fmt, ...) NP_EMIT(NP_LVL_ERR, "error", fmt, ##__VA_ARGS__)
+#define NP_WARN(fmt, ...) NP_EMIT(NP_LVL_WARN, "warn", fmt, ##__VA_ARGS__)
+#define NP_LOG(fmt, ...) NP_EMIT(NP_LVL_INFO, "info", fmt, ##__VA_ARGS__)
+#define NP_DBG(fmt, ...) NP_EMIT(NP_LVL_DBG, "debug", fmt, ##__VA_ARGS__)
+
+int np_log_first_hit(const void *anchor, unsigned long tag);
+
+#define NP_LOG_FIRST_KEY(key, fmt, ...) do { \
+ static const char np_here = 0; \
+ if (np_log_level >= NP_LVL_DBG || np_log_first_hit(&np_here, (unsigned long)(key))) \
+ NP_LOG(fmt, ##__VA_ARGS__); \
+} while(0)
+
+#define NP_LOG_FIRST(fmt, ...) NP_LOG_FIRST_KEY(0, fmt, ##__VA_ARGS__)
+
+#endif // NOTPROTON_UTIL_LOG_H
diff --git a/dylib/util/ptr.h b/dylib/util/ptr.h
new file mode 100644
index 0000000..96962b4
--- /dev/null
+++ b/dylib/util/ptr.h
@@ -0,0 +1,14 @@
+// Pointer validation helpers
+#ifndef NOTPROTON_UTIL_PTR_H
+#define NOTPROTON_UTIL_PTR_H
+
+#include <stdint.h>
+
+static inline int np_plausible_ptr(uint64_t v) {
+ if (v < 0x100000000ULL) return 0; // below 4 GB (image/stack guard)
+ if (v >= 0x800000000000ULL) return 0; // kernel space
+ if (v & 0x7) return 0; // not 8-byte aligned
+ return 1;
+}
+
+#endif // NOTPROTON_UTIL_PTR_H
diff --git a/dylib/version.h b/dylib/version.h
new file mode 100644
index 0000000..55c9ba0
--- /dev/null
+++ b/dylib/version.h
@@ -0,0 +1,7 @@
+// Build version string
+#ifndef NOTPROTON_VERSION_H
+#define NOTPROTON_VERSION_H
+
+#define NOTPROTON_VERSION "1.0.0"
+
+#endif // NOTPROTON_VERSION_H
diff --git a/helpers/appinfo.swift b/helpers/appinfo.swift
new file mode 100644
index 0000000..8f71286
--- /dev/null
+++ b/helpers/appinfo.swift
@@ -0,0 +1,198 @@
+// Reads Steam's appinfo.vdf cache and prints key=value metadata for one app on
+// stdout. Usage: appinfo <appinfo.vdf> <appid>.
+//
+// common/icon is a 32x32 thumbnail. common/clienticon is the real multi-res
+// icon, and the two hashes differ for most apps, so the icon cannot be
+// inferred from the filesystem. Exits non-zero without printing on read
+// failure.
+
+import Foundation
+
+let args = CommandLine.arguments
+guard args.count == 3, let wantAppID = UInt32(args[2]) else {
+ fputs("usage: appinfo <appinfo.vdf> <appid>\n", stderr)
+ exit(2)
+}
+
+guard let file = FileManager.default.contents(atPath: args[1]) else {
+ fputs("appinfo: cannot read \(args[1])\n", stderr)
+ exit(1)
+}
+let bytes = [UInt8](file)
+
+enum VDFError: Error {
+ case truncated
+ case unknownType(UInt8)
+ case unknownMagic(UInt32)
+ case badStringIndex(UInt32)
+}
+
+indirect enum Value {
+ case string(String)
+ case number(Int64)
+ case section([String: Value])
+}
+
+struct Cursor {
+ let b: [UInt8]
+ var p: Int
+
+ mutating func u8() throws -> UInt8 {
+ guard p < b.count else { throw VDFError.truncated }
+ defer { p += 1 }
+ return b[p]
+ }
+
+ mutating func u32() throws -> UInt32 {
+ guard p + 4 <= b.count else { throw VDFError.truncated }
+ defer { p += 4 }
+ return UInt32(b[p]) | UInt32(b[p + 1]) << 8
+ | UInt32(b[p + 2]) << 16 | UInt32(b[p + 3]) << 24
+ }
+
+ mutating func u64() throws -> UInt64 {
+ var v: UInt64 = 0
+ for i in 0..<8 {
+ guard p + i < b.count else { throw VDFError.truncated }
+ v |= UInt64(b[p + i]) << (8 * UInt64(i))
+ }
+ p += 8
+ return v
+ }
+
+ // Values and, before the string table existed, keys are NUL terminated.
+ mutating func cstring() throws -> String {
+ var end = p
+ while end < b.count && b[end] != 0 { end += 1 }
+ guard end < b.count else { throw VDFError.truncated }
+ let s = String(decoding: b[p..<end], as: UTF8.self)
+ p = end + 1
+ return s
+ }
+
+ // A wide string ends at a NUL pair, not a single NUL.
+ mutating func wcstring() throws -> String {
+ var end = p
+ while end + 1 < b.count && !(b[end] == 0 && b[end + 1] == 0) { end += 2 }
+ guard end + 1 < b.count else { throw VDFError.truncated }
+ var units: [UInt16] = []
+ var i = p
+ while i < end {
+ units.append(UInt16(b[i]) | UInt16(b[i + 1]) << 8)
+ i += 2
+ }
+ p = end + 2
+ return String(decoding: units, as: UTF16.self)
+ }
+
+ mutating func skip(_ n: Int) throws {
+ guard p + n <= b.count else { throw VDFError.truncated }
+ p += n
+ }
+}
+
+// v29 moved every key into one table at the end of the file and left an index
+// in its place, so the table has to be read before any app can be parsed.
+func readStringTable(_ b: [UInt8], at offset: Int) throws -> [String] {
+ var c = Cursor(b: b, p: offset)
+ let count = try c.u32()
+ var out: [String] = []
+ out.reserveCapacity(Int(count))
+ for _ in 0..<count { out.append(try c.cstring()) }
+ return out
+}
+
+func readSection(_ c: inout Cursor, _ table: [String]?) throws -> [String: Value] {
+ var out: [String: Value] = [:]
+ while true {
+ let type = try c.u8()
+ // 0x0b is the alternate section terminator the format also allows.
+ if type == 0x08 || type == 0x0b { return out }
+ let key: String
+ if let table = table {
+ let i = try c.u32()
+ guard Int(i) < table.count else { throw VDFError.badStringIndex(i) }
+ key = table[Int(i)]
+ } else {
+ key = try c.cstring()
+ }
+ switch type {
+ // Handles every type the format defines. An unused-but-legal type inside
+ // an app entry would otherwise drop the whole entry and its name.
+ case 0x00: out[key] = .section(try readSection(&c, table))
+ case 0x01: out[key] = .string(try c.cstring())
+ case 0x02: out[key] = .number(Int64(Int32(bitPattern: try c.u32())))
+ case 0x03: try c.skip(4)
+ case 0x04: try c.skip(4)
+ case 0x05: out[key] = .string(try c.wcstring())
+ case 0x06: try c.skip(4)
+ case 0x07: out[key] = .number(Int64(bitPattern: try c.u64()))
+ case 0x0a: out[key] = .number(Int64(bitPattern: try c.u64()))
+ default: throw VDFError.unknownType(type)
+ }
+ }
+}
+
+func findApp(_ b: [UInt8], _ appID: UInt32) throws -> [String: Value]? {
+ var head = Cursor(b: b, p: 0)
+ let magic = try head.u32()
+ _ = try head.u32()
+
+ var table: [String]? = nil
+ var pos: Int
+ // The sha1 of the entry's own binary vdf arrived in v28, which moves the
+ // start of the key data 20 bytes further into every app entry.
+ var entryHeader = 60
+ switch magic {
+ case 0x0756_4429:
+ let offset = try head.u64()
+ guard offset < UInt64(b.count) else { throw VDFError.truncated }
+ table = try readStringTable(b, at: Int(offset))
+ pos = 16
+ case 0x0756_4428:
+ pos = 8
+ case 0x0756_4427:
+ pos = 8
+ entryHeader = 40
+ default:
+ throw VDFError.unknownMagic(magic)
+ }
+
+ while pos + 8 <= b.count {
+ var e = Cursor(b: b, p: pos)
+ let id = try e.u32()
+ if id == 0 { return nil }
+ let size = Int(try e.u32())
+ if id == appID {
+ var kv = Cursor(b: b, p: pos + 8 + entryHeader)
+ let root = try readSection(&kv, table)
+ // Each entry wraps its keys in one "appinfo" section.
+ if case .section(let inner)? = root["appinfo"] { return inner }
+ return root
+ }
+ guard size > 0 else { throw VDFError.truncated }
+ pos = pos + 8 + size
+ }
+ return nil
+}
+
+do {
+ guard let app = try findApp(bytes, wantAppID) else {
+ fputs("appinfo: no entry for appid \(wantAppID)\n", stderr)
+ exit(1)
+ }
+ guard case .section(let common)? = app["common"] else {
+ fputs("appinfo: appid \(wantAppID) has no common section\n", stderr)
+ exit(1)
+ }
+ // A newline in a value would break the key=value framing the caller reads.
+ for key in ["name", "icon", "clienticon", "logo"] {
+ guard case .string(let v)? = common[key], !v.isEmpty else { continue }
+ let flat = v.replacingOccurrences(of: "\n", with: " ")
+ .replacingOccurrences(of: "\r", with: " ")
+ print("\(key)=\(flat)")
+ }
+} catch {
+ fputs("appinfo: cannot parse \(args[1]): \(error)\n", stderr)
+ exit(1)
+}
diff --git a/helpers/icon.swift b/helpers/icon.swift
new file mode 100644
index 0000000..f66967f
--- /dev/null
+++ b/helpers/icon.swift
@@ -0,0 +1,265 @@
+import CoreGraphics
+import Foundation
+import ImageIO
+import UniformTypeIdentifiers
+
+let canvas: CGFloat = 1024
+let center = CGPoint(x: canvas / 2, y: canvas / 2)
+let space = CGColorSpace(name: CGColorSpace.sRGB)!
+let white = CGColor(red: 1, green: 1, blue: 1, alpha: 1)
+let coverage: CGFloat = 0.90
+
+let orbitRadiusX: CGFloat = 492
+let orbitRadiusY: CGFloat = 95
+let strokeWidth: CGFloat = 38
+let knockoutGap: CGFloat = 22
+let ringOuterRadius: CGFloat = 219
+let ringBand: CGFloat = 48
+let coreRadius: CGFloat = 137
+let orbitAngle: CGFloat = -21
+let orbitShiftY: CGFloat = -44
+
+enum Element: String, CaseIterable {
+ case orbitBack = "Orbit Back"
+ case sphereRing = "Sphere Ring"
+ case sphereCore = "Sphere Core"
+ case orbitFront = "Orbit Front"
+
+ var fileName: String {
+ rawValue.lowercased().replacingOccurrences(of: " ", with: "-") + ".png"
+ }
+
+ var depth: Double {
+ switch self {
+ case .orbitBack: 0.40
+ case .sphereRing: 0.70
+ case .sphereCore: 0.90
+ case .orbitFront: 1.00
+ }
+ }
+
+ var translucency: Double {
+ switch self {
+ case .orbitBack: 0.30
+ case .sphereRing: 0.35
+ case .sphereCore: 0.50
+ case .orbitFront: 0.30
+ }
+ }
+}
+
+func makeContext(size: CGFloat) -> CGContext {
+ let context = CGContext(
+ data: nil,
+ width: Int(size),
+ height: Int(size),
+ bitsPerComponent: 8,
+ bytesPerRow: 0,
+ space: space,
+ bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
+ )!
+ context.setAllowsAntialiasing(true)
+ context.interpolationQuality = .high
+ return context
+}
+
+func circle(_ radius: CGFloat) -> CGRect {
+ CGRect(
+ x: center.x - radius,
+ y: center.y - radius,
+ width: radius * 2,
+ height: radius * 2
+ )
+}
+
+func orbitFrame() -> CGAffineTransform {
+ CGAffineTransform(translationX: center.x, y: center.y + orbitShiftY)
+ .rotated(by: orbitAngle * .pi / 180)
+}
+
+func orbitPath() -> CGPath {
+ var transform = orbitFrame()
+ let box = CGRect(
+ x: -orbitRadiusX,
+ y: -orbitRadiusY,
+ width: orbitRadiusX * 2,
+ height: orbitRadiusY * 2
+ )
+ return CGPath(ellipseIn: box, transform: &transform)
+}
+
+func halfPlane(front: Bool) -> CGPath {
+ let big = canvas * 2
+ let overlap: CGFloat = 6
+ let rect = front
+ ? CGRect(x: -big, y: -big, width: big * 2, height: big + overlap)
+ : CGRect(x: -big, y: -overlap, width: big * 2, height: big + overlap)
+ var transform = orbitFrame()
+ return CGPath(rect: rect, transform: &transform)
+}
+
+func strokeHalf(front: Bool, into context: CGContext) {
+ context.saveGState()
+ context.addPath(halfPlane(front: front))
+ context.clip()
+ context.setLineWidth(strokeWidth)
+ context.addPath(orbitPath())
+ context.strokePath()
+ context.restoreGState()
+}
+
+func cutNearHalf(from context: CGContext) {
+ context.saveGState()
+ context.addPath(halfPlane(front: true))
+ context.clip()
+ context.setBlendMode(.clear)
+ context.setLineWidth(strokeWidth + knockoutGap * 2)
+ context.addPath(orbitPath())
+ context.strokePath()
+ context.restoreGState()
+}
+
+func draw(_ element: Element, into context: CGContext) {
+ context.setStrokeColor(white)
+ context.setFillColor(white)
+
+ switch element {
+ case .orbitBack:
+ strokeHalf(front: false, into: context)
+ context.setBlendMode(.clear)
+ context.fillEllipse(in: circle(ringOuterRadius + knockoutGap))
+ context.setBlendMode(.normal)
+
+ case .sphereRing:
+ context.setLineWidth(ringBand)
+ context.strokeEllipse(in: circle(ringOuterRadius - ringBand / 2))
+ cutNearHalf(from: context)
+
+ case .sphereCore:
+ context.fillEllipse(in: circle(coreRadius))
+ cutNearHalf(from: context)
+
+ case .orbitFront:
+ strokeHalf(front: true, into: context)
+ }
+}
+
+func render(_ elements: [Element]) -> CGImage {
+ let context = makeContext(size: canvas)
+ for element in elements {
+ draw(element, into: context)
+ }
+ return context.makeImage()!
+}
+
+func inkBounds(_ image: CGImage) -> CGRect {
+ let width = image.width
+ let height = image.height
+ var pixels = [UInt8](repeating: 0, count: width * height * 4)
+ pixels.withUnsafeMutableBytes { buffer in
+ let scan = CGContext(
+ data: buffer.baseAddress,
+ width: width,
+ height: height,
+ bitsPerComponent: 8,
+ bytesPerRow: width * 4,
+ space: space,
+ bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
+ )!
+ scan.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))
+ }
+ var minX = width, minY = height, maxX = -1, maxY = -1
+ for y in 0..<height {
+ for x in 0..<width where pixels[(y * width + x) * 4 + 3] > 8 {
+ if x < minX { minX = x }
+ if x > maxX { maxX = x }
+ if y < minY { minY = y }
+ if y > maxY { maxY = y }
+ }
+ }
+ guard maxX >= minX, maxY >= minY else {
+ return CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height))
+ }
+ return CGRect(
+ x: CGFloat(minX),
+ y: CGFloat(minY),
+ width: CGFloat(maxX - minX + 1),
+ height: CGFloat(maxY - minY + 1)
+ )
+}
+
+func normalized(_ image: CGImage, sharedInk ink: CGRect) -> CGImage {
+ let scale = canvas * coverage / max(ink.width, ink.height)
+ let context = makeContext(size: canvas)
+ context.translateBy(x: canvas / 2, y: canvas / 2)
+ context.scaleBy(x: scale, y: scale)
+ context.translateBy(x: -ink.midX, y: -ink.midY)
+ context.draw(image, in: CGRect(x: 0, y: 0, width: canvas, height: canvas))
+ return context.makeImage()!
+}
+
+func write(_ image: CGImage, to url: URL) throws {
+ guard
+ let destination = CGImageDestinationCreateWithURL(
+ url as CFURL,
+ UTType.png.identifier as CFString,
+ 1,
+ nil
+ )
+ else {
+ throw CocoaError(.fileWriteUnknown)
+ }
+ CGImageDestinationAddImage(destination, image, nil)
+ guard CGImageDestinationFinalize(destination) else {
+ throw CocoaError(.fileWriteUnknown)
+ }
+}
+
+func group(for element: Element) -> [String: Any] {
+ [
+ "blur-material": NSNull(),
+ "layers": [
+ [
+ "fill": ["solid": "srgb:1.00000,1.00000,1.00000,1.00000"],
+ "image-name": element.fileName,
+ "name": element.rawValue,
+ ]
+ ],
+ "opacity": 1,
+ "refractivity": ["depth": element.depth, "enabled": true, "strength": 0.005],
+ "shadow": ["kind": "neutral", "opacity": 0.5],
+ "specular": "inside",
+ "translucency": ["enabled": true, "value": element.translucency],
+ ]
+}
+
+guard CommandLine.arguments.count == 2 else {
+ FileHandle.standardError.write("usage: icon <output.icon>\n".data(using: .utf8)!)
+ exit(2)
+}
+
+let root = URL(fileURLWithPath: CommandLine.arguments[1], isDirectory: true)
+let assets = root.appendingPathComponent("Assets", isDirectory: true)
+try? FileManager.default.removeItem(at: root)
+try FileManager.default.createDirectory(at: assets, withIntermediateDirectories: true)
+
+let sharedInk = inkBounds(render(Element.allCases))
+for element in Element.allCases {
+ let layer = normalized(render([element]), sharedInk: sharedInk)
+ try write(layer, to: assets.appendingPathComponent(element.fileName))
+}
+
+let document: [String: Any] = [
+ "features": ["refractivity", "specular-location"],
+ "fill": [
+ "linear-gradient": [
+ "srgb:0.25882,0.25882,0.26667,1.00000",
+ "srgb:0.12549,0.12549,0.13333,1.00000",
+ ]
+ ],
+ "groups": Element.allCases.map(group(for:)),
+ "supported-platforms": ["circles": ["watchOS"], "squares": "shared"],
+]
+try JSONSerialization
+ .data(withJSONObject: document, options: [.prettyPrinted, .sortedKeys])
+ .write(to: root.appendingPathComponent("icon.json"))
diff --git a/helpers/iconmaker.swift b/helpers/iconmaker.swift
new file mode 100644
index 0000000..d22043a
--- /dev/null
+++ b/helpers/iconmaker.swift
@@ -0,0 +1,112 @@
+// Reads an image and produces a macOS .icns masked to the continuous rounded
+// rect (squircle) that native app icons use. Input is scaled to fill 1024x1024
+// and clipped. Output covers 16x16 through 512x512@2x.
+// Usage: iconmaker <input-image> <output.icns>
+
+import AppKit
+import Foundation
+
+guard CommandLine.arguments.count == 3 else {
+ fputs("usage: iconmaker <input-image> <output.icns>\n", stderr)
+ exit(1)
+}
+
+let inputPath = CommandLine.arguments[1]
+let outputPath = CommandLine.arguments[2]
+
+guard let srcImage = NSImage(contentsOfFile: inputPath) else {
+ fputs("iconmaker: cannot read \(inputPath)\n", stderr)
+ exit(1)
+}
+
+// The Apple icon grid puts the squircle corner radius at ~22.37% of the
+// icon side. NSBezierPath.init(roundedRect:xRadius:yRadius:) draws a
+// continuous rounded rect on macOS 14+, which is the shape Finder uses.
+let maskRadius: CGFloat = 0.2237
+
+let sizes: [(side: Int, scale: Int, name: String)] = [
+ (16, 1, "icon_16x16.png"),
+ (16, 2, "[email protected]"),
+ (32, 1, "icon_32x32.png"),
+ (32, 2, "[email protected]"),
+ (128, 1, "icon_128x128.png"),
+ (128, 2, "[email protected]"),
+ (256, 1, "icon_256x256.png"),
+ (256, 2, "[email protected]"),
+ (512, 1, "icon_512x512.png"),
+ (512, 2, "[email protected]"),
+]
+
+let fm = FileManager.default
+let iconsetURL: URL
+if #available(macOS 13.0, *) {
+ iconsetURL = URL(filePath: outputPath + ".iconset")
+} else {
+ iconsetURL = URL(fileURLWithPath: outputPath + ".iconset")
+}
+try? fm.removeItem(at: iconsetURL)
+try fm.createDirectory(at: iconsetURL, withIntermediateDirectories: true)
+
+for entry in sizes {
+ let px = entry.side * entry.scale
+ let s = CGFloat(px)
+ let r = s * maskRadius
+
+ let rep = NSBitmapImageRep(
+ bitmapDataPlanes: nil, pixelsWide: px, pixelsHigh: px,
+ bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true,
+ isPlanar: false, colorSpaceName: .deviceRGB,
+ bytesPerRow: 0, bitsPerPixel: 0
+ )!
+
+ let ctx = NSGraphicsContext(bitmapImageRep: rep)!
+ NSGraphicsContext.current = ctx
+
+ // Clip to the squircle, then draw the source image scaled to fill.
+ let rect = NSRect(x: 0, y: 0, width: s, height: s)
+ let path = NSBezierPath(roundedRect: rect, xRadius: r, yRadius: r)
+ path.addClip()
+
+ // Scale-to-fill: pick the scale that covers the canvas on both axes,
+ // then center the overflow.
+ let srcSize = srcImage.size
+ let scale = max(s / srcSize.width, s / srcSize.height)
+ let drawW = srcSize.width * scale
+ let drawH = srcSize.height * scale
+ let drawRect = NSRect(
+ x: (s - drawW) / 2, y: (s - drawH) / 2,
+ width: drawW, height: drawH
+ )
+ srcImage.draw(in: drawRect)
+
+ ctx.flushGraphics()
+ NSGraphicsContext.current = nil
+
+ guard let png = rep.representation(using: .png, properties: [:]) else {
+ fputs("iconmaker: failed to render \(entry.name)\n", stderr)
+ exit(1)
+ }
+
+ let fileURL: URL
+ if #available(macOS 13.0, *) {
+ fileURL = iconsetURL.appending(path: entry.name)
+ } else {
+ fileURL = iconsetURL.appendingPathComponent(entry.name)
+ }
+ try png.write(to: fileURL)
+}
+
+// iconutil produces the .icns from the populated iconset directory.
+let proc = Process()
+proc.executableURL = URL(fileURLWithPath: "/usr/bin/iconutil")
+proc.arguments = ["-c", "icns", iconsetURL.path, "-o", outputPath]
+try proc.run()
+proc.waitUntilExit()
+
+// Clean up the intermediate iconset.
+try? fm.removeItem(at: iconsetURL)
+
+if proc.terminationStatus != 0 {
+ fputs("iconmaker: iconutil failed with status \(proc.terminationStatus)\n", stderr)
+ exit(1)
+}
diff --git a/lsteamclient/LICENSE b/lsteamclient/LICENSE
new file mode 100644
index 0000000..1638160
--- /dev/null
+++ b/lsteamclient/LICENSE
@@ -0,0 +1,149 @@
+================ STEAMWORKS SDK license ===================
+VALVE, Corp.
+SDK LICENSE
+
+This SDK License (the "Agreement") is made by and between you (the "Licensee")
+and Valve Corporation, a Washington corporation,(“Valve”) with offices located
+at 10400 NE 4th Street, Suite 1400, Bellevue, WA 98004, USA.
+
+THIS DOCUMENT DESCRIBES A CONTRACT BETWEEN YOU AND VALVE. PLEASE READ IT BEFORE
+DOWNLOADING OR USING THE STEAMWORKS SOFTWARE DEVELOPMENT KIT (THE “SDK”). BY
+DOWNLOADING AND/OR USING THE SDK YOU INDICATE YOUR ACCEPTANCE OF THIS
+AGREEMENT. IF YOU DO NOT AGREE, DO NOT DOWNLOAD AND/OR USE THE SDK.
+
+Whereas, Valve is the developer of an online platform titled "Steam" that
+provides online distribution services as well as a number of additional online
+services designed to be embedded in computer games and application software,
+including, but not limited to, user authentication, in-app purchasing and
+trading, leaderboards, matchmaking, stats and achievements (the “Steamworks
+Services”) and the SDK;
+
+Whereas, Licensee wishes to develop a game or application software designed to
+take advantage of the Steamworks Services (the "Licensee Software"); and
+
+Whereas, Licensee wishes to receive, and Valve wishes to disclose to Licensee,
+the SDK, and other information as deemed appropriate by Valve, all on the
+terms set forth herein;
+
+Now, therefore, in consideration of the mutual promises made herein, the
+parties agree as follows:
+
+1. License.
+
+1.1 License Grant. Valve hereby grants Licensee a nonexclusive, royalty-free,
+terminable, worldwide, nontransferable license to:
+
+(a) use and locally reproduce the SDK in source code form, solely to develop
+the Licensee Software; and
+
+(b) reproduce and distribute the part of the SDK provided inside the folder
+named redistributable_bin (the "SDK Redistributables") along with the Licensee
+Software in object code form.
+
+1.2 Updates. Valve may from time to time, in its sole discretion, provide
+updates, error corrections, and future versions of the SDK to Licensee. Upon
+delivery, such updates, error corrections and future versions shall be deemed
+part of the SDK, as applicable, under this Agreement.
+
+1.3 Reservation of Rights. Valve reserves all rights not explicitly granted
+herein.
+
+2. Ancillary Obligations.
+
+2.1 No obligation to provide services. Nothing herein shall be construed as
+establishing an obligation to Valve to provide Steamworks Services or accept
+Licensee Software for distribution via Steam.
+
+2.2 Indemnity. Licensee hereby agrees that it is solely responsible for any
+and all Licensee Software and Licensee's creation, distribution, and promotion
+thereof. Licensee shall defend, indemnify, and hold harmless Valve, its
+officers, directors, employees and agents against any and all claims, damages
+(including reasonable attorneys’ fees and costs), losses, or liabilities
+whatsoever arising out of Licensee's creation, distribution, or promotion of
+the Licensee Software.
+
+2.3 Trademarks. Licensee acknowledges and agrees that this Agreement does not
+grant Licensee any right to use any trademarks or trade names of Valve or its
+licensors. All such marks shall remain the property of the respective owner.
+Licensee will refrain from any action or communication that can be incorrectly
+interpreted as a cooperation or partnership between Valve and Licensee.
+
+2.4 No reverse engineering. Licensee will not take any steps to reverse
+engineer the functionality of the SDK or develop software to replace the SDK's
+functionality. If Licensee develops software to interact with the Steamworks
+Services, such software shall not communicate with the Steamworks Services
+directly but always through the application programming interface (API)
+provided by the SDK Redistributables.
+
+3. Term.
+
+3.1 Term. This Agreement shall become effective as of the date Licensee
+downloads or installs the SDK. It will continue to apply until terminated by
+either Valve or Licensee as set out below.
+
+3.2 Termination. Valve may terminate this Agreement immediately upon written
+(including email) notice to Licensee. Licensee may terminate this Agreement at
+any time by ceasing Licensees use of the SDK and ending Licensee's
+distribution of Licensee Software created using the SDK. Furthermore, the
+Agreement will terminate automatically upon Licensee's breach of any term of
+this Agreement.
+
+3.3 Survival. Sections 1.3, 2, 3.2, 3.3, and 4-6 shall survive any expiration
+or termination of this Agreement.
+
+4. Disclaimer of Warranties; Limitation of Liability
+
+4.1 NO WARRANTIES. THE SDK AND ANY OTHER MATERIAL DOWNLOADED BY LICENSEE IS
+PROVIDED “AS IS”. VALVE AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES WITH RESPECT
+TO THE SDK, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, IMPLIED
+WARRANTIES OF MERCHANTABILITY, NON-INFRINGEMENT, TITLE AND FITNESS FOR A
+PARTICULAR PURPOSE.
+
+4.2 LIMITATION OF LIABILITY. IN NO EVENT SHALL VALVE OR ITS SUPPLIERS BE
+LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES
+WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS
+PROFITS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY OTHER
+PECUNIARY LOSS) ARISING OUT OF THE USE OF OR INABILITY TO USE THE ENGINE
+AND/OR THE SDK, EVEN IF VALVE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+5. No Exclusivity.
+
+Neither this Agreement nor the disclosure or receipt of Information shall
+constitute or imply any promise to or intention to make any purchase of
+products or services by either party or its affiliated companies or any
+commitment by either party or its affiliated companies with respect to the
+present or future marketing of any product or service or any commitment to
+enter into any other business relationship. Except for the license and use
+restrictions expressly set forth herein, each party will be free (1) to
+pursue, negotiate, and enter into similar relationships with third parties and
+(2) to develop, market, and make available similar products and services.
+Neither party will be obligated to enter into any other agreement with the
+other party by virtue of this Agreement.
+
+6. General.
+
+6.1 Modification. No amendment or modification of this Agreement shall be
+valid or binding on the parties unless made in writing and signed on behalf of
+both of the parties by their respective duly authorized officers or
+representatives.
+
+6.2 Assignment. Licensee may not assign this agreement without the prior
+written consent of Valve. Subject to the limitations set forth in this
+Agreement, this Agreement will inure to the benefit of and be binding upon the
+parties, their successors and assigns.
+
+6.3 Severability. If any provision of this Agreement shall be held by a court
+of competent jurisdiction to be illegal, invalid or unenforceable, the
+remaining provisions shall remain in full force and effect.
+
+6.4 Governing Law, Jurisdiction and Venue. This Agreement shall be governed by
+the laws of the State of Washington. For any claims of any kind arising out of
+this Agreement or use of the SDK, each of the parties hereto submits to
+exclusive jurisdiction and venue in the state and federal courts sitting in
+King County, Washington.
+
+6.5 Entire Agreement. This Agreement constitutes the entire understanding
+between the parties hereto and supersedes all previous communications,
+representations and understandings, oral or written, between the parties, with
+respect to the subject matter of this Agreement.
diff --git a/lsteamclient/build.sh b/lsteamclient/build.sh
new file mode 100755
index 0000000..d47ac42
--- /dev/null
+++ b/lsteamclient/build.sh
@@ -0,0 +1,264 @@
+#!/bin/bash
+# Build lsteamclient from the tree fetch.sh assembles, which is Valve's sources with
+# the files authored here laid over them. This directory holds only the authored ones.
+# The module has two halves and both come from the same SOURCES list in Makefile.in:
+# the .cpp entries are the unix half (lsteamclient.so), the .c entries are the PE side
+# (lsteamclient.dll, one per Windows arch).
+#
+# The PE halves build with the wine build tree's own make. The unix half cannot,
+# and that is why the second half of this script exists: make links for the machine
+# rather than for the tree's host, silently ignores every object of the other arch,
+# and drops a ~104 KB stub that loads but exports nothing. Every compile and link
+# below therefore names its arch explicitly.
+#
+# A unix half runs inside the wine loader's own process, so UNIX_ARCH is whichever
+# arch that loader is: x86_64 for the rosetta CrossOver build, arm64 for the FEX one.
+# It has to match the tree WINE_BUILD points at, because the ntdll.so it links
+# against comes from there.
+#
+# SOURCES order is the link order and affects the output bytes, so never sort it.
+#
+# An x86_64 unix half must be unsigned, because wine builtins fail to load once
+# codesigned. arm64 is the other way round: the platform will not map an unsigned
+# arm64 image at all, so the linker signs its output as it produces it and that
+# signature has to survive. CrossOver's own arm64 builtins are signed for the same
+# reason. PE files carry no Mach-O signature, so none of this applies to them.
+#
+# Reproducibility differs between the halves. A PE rebuild from unchanged source
+# is byte-identical except for two header fields, TimeDateStamp and the optional
+# header CheckSum, so this script reports a hash with those zeroed and that value
+# can be compared across builds. The unix half has no such property: -g makes the
+# linker stamp every object's mtime into the Mach-O debug map, which also changes
+# LC_UUID, so two builds of identical source never hash the same. Compare code
+# and symbols instead:
+# otool -s __TEXT __text <so> | tail -n +2 | shasum
+# nm -U <so> | awk '{print $2, $3}' | sort
+#
+# Usage:
+# ./build.sh build and verify both halves
+# ./build.sh --pe PE halves only
+# ./build.sh --unix unix half only
+# ./build.sh --install also install to the CrossOver tree and bridge
+#
+# Overridable: WINE_BUILD, WINE_SRC_REL, CX_ROOT, BRIDGE_DIR, UNIX_ARCH
+
+set -eu
+
+here=$(cd "$(dirname "$0")" && pwd)
+repo=$(cd "$here/.." && pwd)
+
+WINE_BUILD=${WINE_BUILD:-$repo/scratch/wine-build-dual}
+# Mach-O spells the arm64 arch arm64 and wine spells its directory aarch64-unix, so
+# both names are kept rather than derived from each other at every use.
+UNIX_ARCH=${UNIX_ARCH:-x86_64}
+case "$UNIX_ARCH" in
+ x86_64) unix_dir=x86_64-unix ;;
+ arm64) unix_dir=aarch64-unix ;;
+ *) echo "==> UNIX_ARCH is $UNIX_ARCH, expected x86_64 or arm64" >&2; exit 1 ;;
+esac
+# Relative because it lands in the debug info. Keep the default sibling layout so
+# a rebuild stays comparable to the shipped binary.
+WINE_SRC_REL=${WINE_SRC_REL:-../wine}
+# The complete tree, unlike $here, which holds only the authored files.
+TREE=${TREE:-$repo/build/lsteamclient}
+# The cloned runner, not the user's installed CrossOver. --install writes into this
+# tree, and the installed app has to stay stock: it is the only clean copy on the
+# machine and it is what the clone and the ntdll patcher are both taken from.
+CX_ROOT=${CX_ROOT:-$HOME/Library/Application Support/notproton/runners/current}
+BRIDGE_DIR=${BRIDGE_DIR:-$HOME/Library/Application Support/notproton/bridge}
+
+install=0
+do_pe=1
+do_unix=1
+for arg in "$@"; do
+ case "$arg" in
+ --install) install=1 ;;
+ --pe) do_unix=0 ;;
+ --unix) do_pe=0 ;;
+ *) echo "==> unknown argument $arg"; exit 1 ;;
+ esac
+done
+
+"$here/fetch.sh"
+
+dll=dlls/lsteamclient
+out=$dll/lsteamclient.so
+
+if [ ! -d "$WINE_BUILD/$dll" ]; then
+ echo "==> no wine build tree at $WINE_BUILD/$dll"
+ echo " the tree is a configured CrossOver 11.0 source drop, see ALIGNMENT.md"
+ exit 1
+fi
+
+cd "$WINE_BUILD"
+
+src=$WINE_SRC_REL/$dll
+[ -d "$src" ] || { echo "==> no wine source tree at $WINE_BUILD/$src"; exit 1; }
+
+echo "==> syncing the assembled tree into $WINE_SRC_REL/$dll"
+# --delete so the build cannot see anything but the assembled sources. Dropping
+# steamclient.spec and steamclient64.spec is safe: the generated Makefile names only
+# lsteamclient.spec, because MODULE is lsteamclient.dll.
+# Unchanged files keep their mtime so the staleness checks below do not rebuild the
+# world.
+rsync -a --delete "$TREE/" "$src/"
+
+pe_info=$here/../bridge/pe-info.py
+
+pe_i386=$dll/i386-windows/lsteamclient.dll
+pe_x86_64=$dll/x86_64-windows/lsteamclient.dll
+
+if [ "$do_pe" -eq 1 ]; then
+ for cc in i686-w64-mingw32-gcc x86_64-w64-mingw32-gcc; do
+ command -v "$cc" >/dev/null || { echo "==> missing $cc, install mingw-w64"; exit 1; }
+ done
+
+ for target in "$pe_i386" "$pe_x86_64"; do
+ echo "==> building $target"
+ make "$target" >/dev/null
+ done
+
+ for target in "$pe_i386" "$pe_x86_64"; do
+ want=${target#"$dll/"}
+ want=${want%%-windows/*}
+ size=$(stat -f %z "$target")
+ # shellcheck disable=SC2046
+ set -- $("$pe_info" "$target")
+ [ "$1" = "$want" ] || { echo "==> $target is $1, expected $want"; exit 1; }
+ # A PE half that lost its objects would be orders of magnitude smaller than
+ # the ~30 MB the real thing weighs.
+ [ "$size" -gt 1000000 ] || { echo "==> $target is only $size bytes, the link dropped objects"; exit 1; }
+ echo "==> built $target $1 $size bytes $2 (timestamp and checksum zeroed)"
+ done
+fi
+
+if [ "$do_unix" -eq 1 ]; then
+ # ntdll.so supplies the Nt*, ntdll_*, and wine_dbg_* symbols at link time.
+ [ -f dlls/ntdll/ntdll.so ] || { echo "==> missing dlls/ntdll/ntdll.so, build ntdll first"; exit 1; }
+ if [ "$(lipo -archs dlls/ntdll/ntdll.so)" != "$UNIX_ARCH" ]; then
+ echo "==> dlls/ntdll/ntdll.so is not $UNIX_ARCH, the tree was built for the wrong arch"
+ exit 1
+ fi
+
+ objs=$(sed -n 's/^[[:space:]]*\([A-Za-z0-9_]*\.cpp\)[[:space:]]*\\*[[:space:]]*$/\1/p' "$TREE/Makefile.in")
+ count=$(echo "$objs" | wc -l | tr -d ' ')
+ echo "==> unix half: $count sources from Makefile.in SOURCES"
+
+ CXXFLAGS="-arch $UNIX_ARCH -I$dll -I$src -Iinclude -I$WINE_SRC_REL/include \
+-D__WINESRC__ -DSTEAM_API_EXPORTS -Dprivate=public -Dprotected=public -DWINE_UNIX_LIB \
+-fPIC -fasynchronous-unwind-tables -g -O2"
+
+ built=0
+ for cpp in $objs; do
+ o=$dll/${cpp%.cpp}.o
+ if [ ! -f "$o" ] || [ "$src/$cpp" -nt "$o" ]; then
+ echo " CXX $cpp"
+ # shellcheck disable=SC2086
+ g++ $CXXFLAGS -c -o "$o" "$src/$cpp"
+ built=$((built + 1))
+ fi
+ done
+ echo "==> compiled $built object(s), $((count - built)) already current"
+
+ link_objs=""
+ for cpp in $objs; do
+ o=$dll/${cpp%.cpp}.o
+ [ -f "$o" ] || { echo "==> missing object $o"; exit 1; }
+ link_objs="$link_objs $o"
+ done
+
+ echo "==> linking $out"
+ # shellcheck disable=SC2086
+ gcc -std=gnu23 -arch "$UNIX_ARCH" -o "$out" -dynamiclib \
+ -install_name @rpath/lsteamclient.so -Wl,-rpath,@loader_path/ \
+ $link_objs dlls/ntdll/ntdll.so -lc++ -Wl,-undefined,dynamic_lookup
+
+ # A real unix half is ~3.3 MB, so a size floor catches a link that dropped its
+ # objects and left the stub.
+ size=$(stat -f %z "$out")
+ arch=$(lipo -archs "$out")
+ [ "$arch" = "$UNIX_ARCH" ] || { echo "==> built $arch, expected $UNIX_ARCH"; exit 1; }
+ [ "$size" -gt 1000000 ] || { echo "==> only $size bytes, the link dropped objects"; exit 1; }
+ # codesign exits non-zero for an object that is not signed at all, which is the
+ # state x86_64 has to be in, so the text is what gets checked and not the status.
+ signing=$(codesign -dv "$out" 2>&1 || true)
+ if [ "$UNIX_ARCH" = x86_64 ]; then
+ if ! echo "$signing" | grep -q "not signed at all"; then
+ echo "==> output is signed, wine will refuse to load it"
+ exit 1
+ fi
+ state=unsigned
+ else
+ if ! echo "$signing" | grep -q "linker-signed"; then
+ echo "==> output is not linker-signed, the platform will refuse to map it"
+ exit 1
+ fi
+ state=linker-signed
+ fi
+ echo "==> built $out $arch $size bytes $(shasum -a 256 "$out" | cut -c1-16) $state"
+fi
+
+[ "$install" -eq 1 ] || { echo "==> not installing, pass --install to deploy"; exit 0; }
+
+[ -d "$CX_ROOT/lib/wine" ] || { echo "==> no CrossOver tree at $CX_ROOT"; exit 1; }
+
+# Refuse to write into an installed CrossOver, whatever CX_ROOT says. That copy is
+# the source the runner clone and the ntdll patcher are both taken from, and
+# CrossOver ships no lsteamclient, so anything added there is a modification of the
+# user's application that nothing would ever clean up.
+case "$CX_ROOT" in
+ /Applications/*)
+ echo "==> refusing to install into $CX_ROOT" >&2
+ echo " that is an installed CrossOver and it has to stay stock." >&2
+ echo " point CX_ROOT at the runner clone under the support directory." >&2
+ exit 1
+ ;;
+esac
+
+# Each half goes to three places.
+#
+# The bridge arch directories are what RUN_SCRIPT's install_lsteamclient copies
+# into the CrossOver tree on every launch, so they are the real source of truth.
+# Writing the CrossOver tree here as well only makes the current build testable
+# without launching a game first; the next launch overwrites it from the bridge
+# either way, which means skipping the bridge copy silently reverts the install.
+#
+# The flat bridge copies are separate consumers, not duplicates: RUN_SCRIPT
+# stages them into the prefix Steam directory as the load trigger for the 64 bit
+# side, alongside the 32 bit trigger it puts in syswow64. Wrong-arch flat PEs
+# abort builtin lookup outright, so the flat copy is the x86_64 one.
+install_one() {
+ from=$1
+ shift
+ for dst in "$@"; do
+ mkdir -p "$(dirname "$dst")"
+ cp -f "$from" "$dst"
+ case "$dst" in
+ *.so)
+ if [ "$UNIX_ARCH" = x86_64 ]; then
+ codesign --remove-signature "$dst" 2>/dev/null || true
+ fi
+ ;;
+ esac
+ cmp -s "$from" "$dst" || { echo "==> install verify failed: $dst differs from $from"; exit 1; }
+ echo "==> installed $dst"
+ done
+}
+
+if [ "$do_pe" -eq 1 ]; then
+ install_one "$pe_i386" \
+ "$BRIDGE_DIR/i386-windows/lsteamclient.dll" \
+ "$CX_ROOT/lib/wine/i386-windows/lsteamclient.dll"
+ install_one "$pe_x86_64" \
+ "$BRIDGE_DIR/x86_64-windows/lsteamclient.dll" \
+ "$BRIDGE_DIR/lsteamclient.dll" \
+ "$CX_ROOT/lib/wine/x86_64-windows/lsteamclient.dll"
+fi
+
+if [ "$do_unix" -eq 1 ]; then
+ install_one "$out" \
+ "$BRIDGE_DIR/$unix_dir/lsteamclient.so" \
+ "$CX_ROOT/lib/wine/$unix_dir/lsteamclient.so"
+fi
+
+echo "==> done. prefixes refresh their copy from the bridge on next launch."
diff --git a/lsteamclient/fetch.sh b/lsteamclient/fetch.sh
new file mode 100755
index 0000000..b69cf72
--- /dev/null
+++ b/lsteamclient/fetch.sh
@@ -0,0 +1,95 @@
+#!/bin/sh
+# Assemble a complete lsteamclient source tree: Valve's, at the pinned commit, with
+# the files authored here laid over the top.
+#
+# Only the authored files are tracked in this repo. Valve's 3,133 are fetched, so
+# their Steamworks SDK licensed sources and the LGPL cxx.h are never redistributed
+# here.
+#
+# Usage:
+# ./fetch.sh assemble if needed
+# ./fetch.sh --refetch discard the cached tarball and assembled tree first
+#
+# Overridable: PROTON_COMMIT, BASELINE_DIGEST, WORK, TREE
+
+set -eu
+
+here=$(cd "$(dirname "$0")" && pwd)
+repo=$(cd "$here/.." && pwd)
+
+PROTON_COMMIT=${PROTON_COMMIT:-164e0ccd2ea2b1ec2e5d08dc97f65b184c2539ca}
+
+# sha256 over the extracted tree: for each path in sorted order, the sha256 of the
+# path then the sha256 of the contents. This pins content, not the archive, because
+# codeload regenerates the tarball and the gzip framing moves. It also means a
+# force-push that orphans the commit is caught as a mismatch instead of silently
+# building against whatever the branch holds now.
+BASELINE_DIGEST=${BASELINE_DIGEST:-b286df1df46a70d9e2cc674676afcc6e08b1a56ce472e5add0932b86940657bf}
+
+WORK=${WORK:-$repo/scratch/proton-lsc}
+TREE=${TREE:-$repo/build/lsteamclient}
+
+# Laid over Valve's tree, in this order, by the loop at the end.
+authored="steamclient_main.c
+unix_steam_input_manual.cpp
+unixlib.cpp"
+
+if [ "${1:-}" = "--refetch" ]; then
+ rm -rf "$WORK" "$TREE"
+elif [ $# -ne 0 ]; then
+ echo "==> unknown argument $1" >&2
+ exit 1
+fi
+
+tarball=$WORK/proton-$PROTON_COMMIT.tar.gz
+base=$WORK/lsteamclient
+
+if [ ! -d "$base" ]; then
+ mkdir -p "$WORK"
+ if [ ! -f "$tarball" ]; then
+ echo "==> fetching Proton $PROTON_COMMIT"
+ curl -fsSL -o "$tarball.part" \
+ "https://codeload.github.com/ValveSoftware/Proton/tar.gz/$PROTON_COMMIT"
+ mv "$tarball.part" "$tarball"
+ fi
+ echo "==> extracting lsteamclient"
+ mkdir -p "$base.part"
+ tar xzf "$tarball" -C "$base.part" --strip-components=2 "*/lsteamclient/"
+ mv "$base.part" "$base"
+fi
+
+got=$(cd "$base" && python3 -c '
+import hashlib, pathlib
+root = pathlib.Path(".")
+h = hashlib.sha256()
+for p in sorted(q for q in root.rglob("*") if q.is_file()):
+ h.update(hashlib.sha256(str(p.relative_to(root)).encode()).digest())
+ h.update(hashlib.sha256(p.read_bytes()).digest())
+print(h.hexdigest())
+')
+
+if [ "$got" != "$BASELINE_DIGEST" ]; then
+ echo "==> baseline digest mismatch for Proton $PROTON_COMMIT" >&2
+ echo " expected $BASELINE_DIGEST" >&2
+ echo " got $got" >&2
+ echo " the cached tree is not the pinned commit. ./fetch.sh --refetch to discard it." >&2
+ exit 1
+fi
+
+count=$(find "$base" -type f | wc -l | tr -d ' ')
+echo "==> baseline verified: Proton $PROTON_COMMIT, $count files"
+
+# Rebuilt from the baseline each time so a removed authored file cannot leave a stale
+# copy behind, and so the overlay below is always the only divergence.
+rm -rf "$TREE"
+mkdir -p "$(dirname "$TREE")"
+cp -c -R "$base" "$TREE" 2>/dev/null || cp -R "$base" "$TREE"
+
+echo "$authored" | while IFS= read -r f; do
+ [ -n "$f" ] || continue
+ [ -f "$here/$f" ] || { echo "==> authored file missing: $f" >&2; exit 1; }
+ [ -f "$TREE/$f" ] || { echo "==> $f is not in Valve's tree, so it is not an overlay" >&2; exit 1; }
+ cp -f "$here/$f" "$TREE/$f"
+done
+
+echo "==> assembled $TREE with $(echo "$authored" | LC_ALL=C grep -c .) authored files over it"
diff --git a/lsteamclient/steamclient_main.c b/lsteamclient/steamclient_main.c
new file mode 100644
index 0000000..86db794
--- /dev/null
+++ b/lsteamclient/steamclient_main.c
@@ -0,0 +1,641 @@
+/* Proton's lsteamclient, now for macOS! */
+#include <stdarg.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <limits.h>
+#include <stdint.h>
+#include <assert.h>
+
+#include "windef.h"
+#include "winbase.h"
+#include "winnls.h"
+#include "winuser.h"
+#include "winternl.h"
+#include "winsock2.h"
+
+#include "steamclient_private.h"
+
+WINE_DEFAULT_DEBUG_CHANNEL(steamclient);
+
+CREATE_TYPE_INFO_VTABLE;
+
+#ifdef __ASM_USE_THISCALL_WRAPPER
+
+#define DEFINE_VTBL_WRAPPER(off) \
+ __ASM_GLOBAL_FUNC(vtbl_wrapper_ ## off, \
+ "popl %eax\n\t" \
+ "popl %ecx\n\t" \
+ "pushl %eax\n\t" \
+ "movl 0(%ecx), %eax\n\t" \
+ "jmp *" #off "(%eax)\n\t")
+
+DEFINE_VTBL_WRAPPER(0);
+DEFINE_VTBL_WRAPPER(4);
+DEFINE_VTBL_WRAPPER(8);
+DEFINE_VTBL_WRAPPER(12);
+DEFINE_VTBL_WRAPPER(16);
+DEFINE_VTBL_WRAPPER(20);
+DEFINE_VTBL_WRAPPER(24);
+DEFINE_VTBL_WRAPPER(28);
+DEFINE_VTBL_WRAPPER(32);
+DEFINE_VTBL_WRAPPER(36);
+DEFINE_VTBL_WRAPPER(40);
+DEFINE_VTBL_WRAPPER(44);
+DEFINE_VTBL_WRAPPER(48);
+DEFINE_VTBL_WRAPPER(52);
+DEFINE_VTBL_WRAPPER(56);
+
+#endif
+
+static char temp_path_buffer[TEMP_PATH_BUFFER_LENGTH];
+
+static CRITICAL_SECTION steamclient_cs = { NULL, -1, 0, 0, 0, 0 };
+static HANDLE steam_overlay_event;
+static BOOL wsa_initialized;
+
+BOOL WINAPI DllMain(HINSTANCE instance, DWORD reason, void *reserved)
+{
+ TRACE("(%p, %lu, %p)\n", instance, reason, reserved);
+
+ switch (reason)
+ {
+ case DLL_PROCESS_ATTACH:
+ DisableThreadLibraryCalls(instance);
+ steam_overlay_event = CreateEventA(NULL, TRUE, FALSE, "__wine_steamclient_GameOverlayActivated");
+#if defined(__x86_64__) || defined(__aarch64__)
+ init_type_info_rtti( (char *)instance );
+ init_rtti( (char *)instance );
+#endif
+ __wine_init_unix_call();
+ break;
+ case DLL_PROCESS_DETACH:
+ CloseHandle(steam_overlay_event);
+ if (wsa_initialized)
+ {
+ WSACleanup();
+ wsa_initialized = FALSE;
+ }
+ break;
+ }
+
+ return TRUE;
+}
+
+NTSTATUS steamclient_call( unsigned int code, void *args, const char *name )
+{
+ NTSTATUS status = WINE_UNIX_CALL( code, args );
+
+ if (status == STATUS_ACCESS_VIOLATION)
+ {
+ ERR( "Access violation in %s.\n", name );
+ *(volatile int *)0xbeef |= 0;
+ }
+ if (status) WARN( "%s failed, status %#x\n", name, (UINT)status );
+ return status;
+}
+
+static BYTE *alloc_start, *alloc_end;
+
+static int8_t allocated_from_steamclient_dll( void *ptr )
+{
+ return (BYTE *)ptr >= alloc_start && (BYTE *)ptr < alloc_end;
+}
+
+
+static void *get_mem_from_steamclient_dll(size_t size, unsigned int version, void *vtbl)
+{
+ static BYTE * const error_ptr = (BYTE *)~(ULONG_PTR)0;
+ static const unsigned int magic = 0x53ba947a;
+ static struct
+ {
+ unsigned int version;
+ void *vtbl;
+ size_t size;
+ void *ptr;
+ }
+ allocated[256];
+ static unsigned int allocated_count;
+ static BYTE *alloc_base;
+ unsigned int i;
+
+ if (alloc_base == error_ptr)
+ {
+ /* Previously failed to locate the section. */
+ return NULL;
+ }
+
+ if (alloc_base && (IsBadReadPtr(alloc_start, sizeof(magic)) || *(unsigned int *)alloc_start != magic))
+ {
+ TRACE("steamclient.dll reloaded.\n");
+ alloc_base = alloc_start = alloc_end = NULL;
+ allocated_count = 0;
+ }
+
+ for (i = 0; i < allocated_count; ++i)
+ {
+ if ((vtbl && allocated[i].vtbl == vtbl) || (!vtbl && allocated[i].version == version))
+ {
+ if (allocated[i].size != size)
+ {
+ FIXME("Size does not match.\n");
+ return NULL;
+ }
+ return allocated[i].ptr;
+ }
+ }
+
+ if (allocated_count == ARRAY_SIZE(allocated))
+ {
+ FIXME("Too many interface versions.\n");
+ return NULL;
+ }
+
+ if (!alloc_base)
+ {
+ static const WCHAR steamclient64W[] = {'s','t','e','a','m','c','l','i','e','n','t','6','4','.','d','l','l',0};
+ static const WCHAR steamclientW[] = {'s','t','e','a','m','c','l','i','e','n','t','.','d','l','l',0};
+ const IMAGE_SECTION_HEADER *sec;
+ const IMAGE_NT_HEADERS *nt;
+ HMODULE mod;
+
+ /* A 64 bit game loads steamclient64.dll, a 32 bit one steamclient.dll. */
+ if (!(mod = GetModuleHandleW(steamclient64W)) && !(mod = GetModuleHandleW(steamclientW)))
+ {
+ WARN("Module not found, err %lu.\n", GetLastError());
+ alloc_base = error_ptr;
+ return NULL;
+ }
+ if (!(nt = RtlImageNtHeader(mod)))
+ {
+ FIXME("Got NULL NT image headers.\n");
+ alloc_base = error_ptr;
+ return NULL;
+ }
+ sec = (const IMAGE_SECTION_HEADER *)((const BYTE *)&nt->OptionalHeader + nt->FileHeader.SizeOfOptionalHeader);
+ for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
+ {
+ if (!memcmp(sec[i].Name, ".data", 5))
+ {
+ alloc_start = alloc_base = (BYTE *)mod + sec[i].VirtualAddress;
+ alloc_end = alloc_base + sec[i].SizeOfRawData;
+ if (alloc_end - alloc_start < sizeof(magic))
+ {
+ ERR(".data section is too small.\n");
+ alloc_base = error_ptr;
+ return NULL;
+ }
+ TRACE("Found .data section, start %p, end %p.\n", alloc_base, alloc_end);
+ *(unsigned int *)alloc_base = magic;
+ alloc_base += sizeof(unsigned int);
+ break;
+ }
+ }
+ if (i == nt->FileHeader.NumberOfSections)
+ {
+ FIXME(".data section not found.\n");
+ alloc_base = error_ptr;
+ return NULL;
+ }
+ }
+
+ if (alloc_end - alloc_base < size)
+ {
+ FIXME("Not enough section size left.\n");
+ return NULL;
+ }
+ allocated[allocated_count].version = version;
+ allocated[allocated_count].vtbl = vtbl;
+ allocated[allocated_count].size = size;
+ allocated[allocated_count].ptr = alloc_base;
+ alloc_base += size;
+
+ return allocated[allocated_count++].ptr;
+}
+
+void *alloc_mem_for_iface(size_t size, const char *iface_version)
+{
+ const char steamclient_iface_name[] = "SteamClient";
+ unsigned int version;
+ void *ret;
+
+ /* Mafia II depends on SteamClient interface pointer to point inside
+ * native Windows steamclient.dll. */
+ if (strncmp(iface_version, steamclient_iface_name, ARRAY_SIZE(steamclient_iface_name) - 1))
+ goto fallback;
+
+ version = atoi(iface_version + ARRAY_SIZE(steamclient_iface_name) - 1);
+ if (!version)
+ {
+ FIXME("Could not get iface version from %s.\n", iface_version);
+ goto fallback;
+ }
+
+ if ((ret = get_mem_from_steamclient_dll(size, version, NULL)))
+ return ret;
+
+fallback:
+ return HeapAlloc(GetProcessHeap(), 0, size);
+}
+
+void *alloc_vtable(void *vtable, unsigned int method_count, const char *iface_version)
+{
+#if defined(__x86_64__) || defined(__aarch64__)
+ return vtable;
+#else
+ static const char *iface_names[] =
+ {
+ "SteamUser",
+ "SteamFriends",
+ "SteamUtils",
+ "STEAMUSERSTATS",
+ "STEAMAPPS",
+ "SteamNetworking",
+ "SteamClient",
+ };
+ unsigned int i;
+ char *ret;
+
+ for (i = 0; i < ARRAY_SIZE(iface_names); ++i)
+ if (!strncmp(iface_version, iface_names[i], strlen(iface_names[i]) - 1))
+ break;
+
+ if (i == ARRAY_SIZE(iface_names))
+ return vtable;
+
+ if (!(ret = get_mem_from_steamclient_dll(method_count * sizeof(void *), 0, vtable)))
+ return vtable;
+
+ TRACE("iface %s, method_count %d, allocating from module.\n", iface_version, method_count);
+
+ memcpy(ret, vtable, method_count * sizeof(void *));
+ return ret;
+#endif
+}
+
+struct steamclient_interface
+{
+ struct list entry;
+ const char *name;
+ struct u_iface u_iface;
+ struct w_iface *w_iface;
+};
+
+static struct list steamclient_interfaces = LIST_INIT(steamclient_interfaces);
+
+struct w_iface *create_win_interface( const char *name, struct u_iface u_iface )
+{
+ struct steamclient_interface *e;
+ struct w_iface *ret = NULL;
+ iface_constructor constructor;
+
+ TRACE("trying to create %s\n", name);
+
+ if (!u_iface.handle)
+ return NULL;
+
+ EnterCriticalSection(&steamclient_cs);
+
+ LIST_FOR_EACH_ENTRY(e, &steamclient_interfaces, struct steamclient_interface, entry)
+ {
+ if (e->u_iface.handle == u_iface.handle && !strcmp(e->name, name))
+ {
+ ret = e->w_iface;
+ TRACE("-> %p\n", ret);
+ goto done;
+ }
+ }
+
+ if ((constructor = find_iface_constructor( name )))
+ {
+ ret = constructor( u_iface );
+ if (allocated_from_steamclient_dll( ret ) || allocated_from_steamclient_dll( ret->vtable ))
+ {
+ /* Don't cache interfaces allocated from steamclient.dll space.
+ * steamclient may get reloaded by the app, miss the previous
+ * data and potentially have different load address. */
+ goto done;
+ }
+
+ e = HeapAlloc( GetProcessHeap(), 0, sizeof(*e) );
+ e->name = strdup( name );
+ e->u_iface = u_iface;
+ e->w_iface = ret;
+ list_add_tail( &steamclient_interfaces, &e->entry );
+
+ goto done;
+ }
+
+done:
+ LeaveCriticalSection(&steamclient_cs);
+ if (!ret) ERR("Don't recognize interface name: %s\n", name);
+ SetLastError(0);
+ return ret;
+}
+
+void *get_unix_buffer( struct u_buffer buf )
+{
+ struct steamclient_get_unix_buffer_params params = {.buf = buf};
+ void *ret;
+
+ if ((UINT_PTR)buf.ptr == buf.ptr && (UINT_PTR)(buf.ptr + buf.len) == (buf.ptr + buf.len))
+ return (void *)(UINT_PTR)buf.ptr;
+
+ if (!(params.ptr = ret = HeapAlloc( GetProcessHeap(), 0, buf.len ))) return NULL;
+ if (STEAMCLIENT_CALL( steamclient_get_unix_buffer, &params ) || (ret != params.ptr))
+ {
+ HeapFree( GetProcessHeap(), 0, ret );
+ ret = params.ptr;
+ }
+
+ return ret;
+}
+
+static BOOL get_env_win(const WCHAR *name, char *value, unsigned int size)
+{
+ DWORD i, env_size;
+
+ if (!(env_size = GetEnvironmentVariableW(name, (WCHAR *)value, size / sizeof(WCHAR))) || env_size >= size / sizeof(WCHAR))
+ return FALSE;
+
+ for (i = 0; i <= env_size; ++i)
+ value[i] = ((WCHAR *)value)[i];
+
+ return TRUE;
+}
+
+static int load_steamclient(void)
+{
+ char steam_app_id[4096], ignore_child_processes[4096];
+ struct steamclient_init_params params = {.g_tmppath = temp_path_buffer};
+ DWORD saved_err = GetLastError();
+
+ if (!get_env_win(u"SteamAppId", steam_app_id, sizeof(steam_app_id)))
+ params.steam_app_id_unset = TRUE;
+ else
+ params.steam_app_id = steam_app_id;
+
+ if (!get_env_win(u"IgnoreChildProcesses", ignore_child_processes, sizeof(ignore_child_processes)))
+ params.ignore_child_processes_unset = TRUE;
+ else
+ params.ignore_child_processes = ignore_child_processes;
+
+ if (STEAMCLIENT_CALL( steamclient_init, &params )) return 0;
+ if (!wsa_initialized)
+ {
+ /* Some games depend on winsocks being initialized after initializing Steam API. */
+ WSADATA data;
+
+ WSAStartup(0x202, &data);
+ wsa_initialized = TRUE;
+ }
+ SetLastError(saved_err);
+ return 1;
+}
+
+void *CDECL CreateInterface(const char *name, int *return_code)
+{
+ struct steamclient_CreateInterface_params params = {.name = name, .return_code = return_code};
+
+ TRACE("name: %s, return_code: %p\n", name, return_code);
+ if (!load_steamclient()) return NULL;
+ if (STEAMCLIENT_CALL( steamclient_CreateInterface, &params )) return NULL;
+ return create_win_interface( name, params._ret );
+}
+
+void execute_pending_callbacks(void)
+{
+ struct steamclient_next_callback_params params = {0};
+
+ while (!STEAMCLIENT_CALL( steamclient_next_callback, &params ) && params._ret)
+ {
+ if (!params.callback || params.size > params.callback->size)
+ params.callback = realloc( params.callback, params.size );
+ else switch (params.callback->type)
+ {
+ case SOCKETS_DEBUG_OUTPUT:
+ TRACE( "SOCKETS_DEBUG_OUTPUT func %p, type %u, msg %s.\n", params.callback->sockets_debug_output.pfnFunc,
+ params.callback->sockets_debug_output.type, debugstr_a( params.callback->sockets_debug_output.msg ) );
+ params.callback->sockets_debug_output.pfnFunc( params.callback->sockets_debug_output.type, params.callback->sockets_debug_output.msg );
+ break;
+ case WARNING_MESSAGE_HOOK:
+ TRACE( "WARNING_MESSAGE_HOOK func %p, severity %d, msg %s.\n", params.callback->warning_message_hook.pFunction,
+ params.callback->warning_message_hook.severity, debugstr_a( params.callback->warning_message_hook.msg ) );
+ params.callback->warning_message_hook.pFunction( params.callback->warning_message_hook.severity, params.callback->warning_message_hook.msg );
+ break;
+ case CALL_CDECL_FUNC_DATA:
+ TRACE( "CALL_CDECL_FUNC_DATA func %p, data %p.\n", params.callback->call_cdecl_func_data.pFunc, params.callback->call_cdecl_func_data.data );
+ params.callback->call_cdecl_func_data.pFunc( params.callback->call_cdecl_func_data.data );
+ break;
+#define CALL_VTABLE_CASES(method) \
+ case CALL_IFACE_VTABLE_ ## method ## _0: \
+ TRACE( "CALL_IFACE_VTABLE_" #method "_0 iface %p.\n", params.callback->call_iface_vtable.iface ); \
+ CALL_VTBL_FUNC( params.callback->call_iface_vtable.iface, method * 4, void, (void *), (params.callback->call_iface_vtable.iface) ); \
+ break; \
+ case CALL_IFACE_VTABLE_ ## method ## _1: \
+ TRACE( "CALL_IFACE_VTABLE_" #method "_1 iface %p, arg0 %#I64x.\n", params.callback->call_iface_vtable.iface, \
+ params.callback->call_iface_vtable.arg0 ); \
+ CALL_VTBL_FUNC( params.callback->call_iface_vtable.iface, method * 4, void, (void *, intptr_t), (params.callback->call_iface_vtable.iface, \
+ params.callback->call_iface_vtable.arg0) ); \
+ break; \
+ case CALL_IFACE_VTABLE_ ## method ## _2: \
+ TRACE( "CALL_IFACE_VTABLE_" #method "_2 iface %p, arg0 %#I64x, arg1 %#I64x.\n", params.callback->call_iface_vtable.iface, \
+ params.callback->call_iface_vtable.arg0, params.callback->call_iface_vtable.arg1 ); \
+ CALL_VTBL_FUNC( params.callback->call_iface_vtable.iface, method * 4, void, (void *, intptr_t, intptr_t), (params.callback->call_iface_vtable.iface, \
+ params.callback->call_iface_vtable.arg0, params.callback->call_iface_vtable.arg1) ); \
+ break
+
+ CALL_VTABLE_CASES(0);
+ CALL_VTABLE_CASES(1);
+ CALL_VTABLE_CASES(2);
+#undef CALL_VTABLE_CASES
+ case CALL_IFACE_VTABLE_0_SERVER_RESPONDED:
+ TRACE( "CALL_IFACE_VTABLE_0_SERVER_RESPONDED iface %p, server %p.\n", params.callback->server_responded.iface,
+ params.callback->server_responded.server );
+ CALL_VTBL_FUNC( params.callback->server_responded.iface, 0, void, (void *, gameserveritem_t_165 *), (params.callback->server_responded.iface,
+ params.callback->server_responded.server) );
+ break;
+ case CALL_IFACE_VTABLE_0_ADD_PLAYER_TO_LIST:
+ TRACE( "CALL_IFACE_VTABLE_0_ADD_PLAYER_TO_LIST iface %p, name %s, score %u, time_played %f.\n", params.callback->add_player_to_list.iface,
+ debugstr_a( params.callback->add_player_to_list.name ), params.callback->add_player_to_list.score, params.callback->add_player_to_list.time_played );
+ CALL_VTBL_FUNC( params.callback->add_player_to_list.iface, 0, void, (void *, const char *, int32_t, float), (params.callback->add_player_to_list.iface,
+ params.callback->add_player_to_list.name, params.callback->add_player_to_list.score, params.callback->add_player_to_list.time_played) );
+ break;
+ case CALL_IFACE_VTABLE_0_RULES_RESPONDED:
+ {
+ const char *value = params.callback->rules_responded.rule_and_value + strlen( params.callback->rules_responded.rule_and_value ) + 1;
+ TRACE( "CALL_IFACE_VTABLE_0_RULES_RESPONDED iface %p, rule %s, value %s.\n", params.callback->rules_responded.iface,
+ debugstr_a( params.callback->rules_responded.rule_and_value ), debugstr_a( value ) );
+ CALL_VTBL_FUNC( params.callback->rules_responded.iface, 0, void, (void *, const char *, const char *), (params.callback->rules_responded.iface,
+ params.callback->rules_responded.rule_and_value, value) );
+ break;
+ }
+ case CALL_IFACE_VTABLE_0_FRIENDS_RESPONDED:
+ {
+ TRACE( "CALL_IFACE_VTABLE_0_FRIENDS_RESPONDED iface %p, steam_id %#I64x, name %s, connected %d.\n", params.callback->friends_responded.iface,
+ *(int64_t *)&params.callback->friends_responded.steamid,
+ debugstr_a( params.callback->friends_responded.name ), (int)params.callback->friends_responded.connected );
+ CALL_VTBL_FUNC( params.callback->friends_responded.iface, 0, void, (void *, CSteamID, const char *, int8_t), (params.callback->friends_responded.iface,
+ params.callback->friends_responded.steamid, params.callback->friends_responded.name, params.callback->friends_responded.connected) );
+ break;
+ }
+ }
+ }
+
+ free( params.callback );
+}
+
+static void *last_callback_data;
+
+int8_t CDECL Steam_FreeLastCallback( int32_t pipe )
+{
+ struct steamclient_Steam_FreeLastCallback_params params = {.pipe = pipe};
+ TRACE( "%u\n", pipe );
+
+ if (!load_steamclient()) return 0;
+
+ HeapFree( GetProcessHeap(), 0, last_callback_data );
+ last_callback_data = NULL;
+
+ STEAMCLIENT_CALL( steamclient_Steam_FreeLastCallback, &params );
+ return params._ret;
+}
+
+int8_t CDECL Steam_BGetCallback( int32_t pipe, w_CallbackMsg_t *win_msg, int32_t *ignored )
+{
+ struct steamclient_Steam_BGetCallback_params params =
+ {
+ .pipe = pipe,
+ .w_msg = win_msg,
+ .ignored = ignored,
+ };
+ struct steamclient_callback_message_receive_params receive_params =
+ {
+ .w_msg = win_msg,
+ };
+
+ TRACE("%u, %p, %p\n", pipe, win_msg, ignored);
+
+ if (!load_steamclient()) return 0;
+
+ execute_pending_callbacks();
+
+next_event:
+ STEAMCLIENT_CALL( steamclient_Steam_BGetCallback, &params );
+ if (!params._ret)
+ {
+ SetLastError(0);
+ return FALSE;
+ }
+ receive_params.cookie = params.cookie;
+
+ if (!(win_msg->m_pubParam = HeapAlloc( GetProcessHeap(), 0, win_msg->m_cubParam ))) return FALSE;
+ last_callback_data = win_msg->m_pubParam;
+ STEAMCLIENT_CALL( steamclient_callback_message_receive, &receive_params );
+
+ if (win_msg->m_iCallback == 0x14b) /* GameOverlayActivated_t::k_iCallback */
+ {
+ uint8_t activated = *(uint8_t *)win_msg->m_pubParam;
+ FIXME( "HACK: Steam overlay %sactivated, %sabling all input events.\n",
+ activated ? "" : "de", activated ? "dis" : "en" );
+ if (activated)
+ {
+ SetEvent( steam_overlay_event );
+ keybd_event( VK_LSHIFT, 0x2a /* lshift scancode */, KEYEVENTF_KEYUP, 0 );
+ keybd_event( VK_RSHIFT, 0x36 /* rshift scancode */, KEYEVENTF_KEYUP, 0 );
+ keybd_event( VK_TAB, 0x0f /* tab scancode */, KEYEVENTF_KEYUP, 0 );
+ }
+ else
+ {
+ if (WaitForSingleObject( steam_overlay_event, 0 ) == WAIT_TIMEOUT)
+ {
+ FIXME( "Spurious steam overlay deactivate event, skipping.\n" );
+ Steam_FreeLastCallback( pipe );
+ goto next_event;
+ }
+ ResetEvent( steam_overlay_event );
+ }
+ }
+
+ execute_pending_callbacks();
+ return params._ret;
+}
+
+int8_t CDECL Steam_GetAPICallResult( int32_t pipe, uint64_t call, void *w_callback,
+ int w_callback_len, int id, int8_t *failed )
+{
+ struct steamclient_Steam_GetAPICallResult_params params =
+ {
+ .pipe = pipe,
+ .call = call,
+ .w_callback = w_callback,
+ .w_callback_len = w_callback_len,
+ .id = id,
+ .failed = failed,
+ };
+
+ TRACE( "%u, x, %p, %u, %u, %p\n", pipe, w_callback, w_callback_len, id, failed );
+
+ if (!load_steamclient()) return FALSE;
+ STEAMCLIENT_CALL( steamclient_Steam_GetAPICallResult, &params );
+ return params._ret;
+}
+
+void CDECL Steam_ReleaseThreadLocalMemory(int bThreadExit)
+{
+ struct steamclient_Steam_ReleaseThreadLocalMemory_params params = {.thread_exit = bThreadExit};
+ TRACE("%d\n", bThreadExit);
+
+ if (!load_steamclient()) return;
+
+ STEAMCLIENT_CALL( steamclient_Steam_ReleaseThreadLocalMemory, &params );
+}
+
+void CDECL Breakpad_SteamMiniDumpInit( uint32_t a, const char *b, const char *c )
+{
+ TRACE("\n");
+}
+
+void CDECL Breakpad_SteamSetAppID( uint32_t appid )
+{
+ TRACE("\n");
+}
+
+int CDECL Breakpad_SteamSetSteamID( uint64_t steamid )
+{
+ TRACE("\n");
+ return 1;
+}
+
+int CDECL Breakpad_SteamWriteMiniDumpSetComment(const char *comment)
+{
+ TRACE("\n");
+ return 1;
+}
+
+void CDECL Breakpad_SteamWriteMiniDumpUsingExceptionInfoWithBuildId(int a, int b)
+{
+ TRACE("\n");
+}
+
+int8_t CDECL Steam_IsKnownInterface( const char *pchVersion )
+{
+ struct steamclient_Steam_IsKnownInterface_params params = {.version = pchVersion};
+ TRACE("%s\n", pchVersion);
+ load_steamclient();
+ STEAMCLIENT_CALL( steamclient_Steam_IsKnownInterface, &params );
+ return params._ret;
+}
+
+void CDECL Steam_NotifyMissingInterface( int32_t hSteamPipe, const char *pchVersion )
+{
+ struct steamclient_Steam_NotifyMissingInterface_params params = {.pipe = hSteamPipe, .version = pchVersion};
+ TRACE("%u %s\n", hSteamPipe, pchVersion);
+ load_steamclient();
+ STEAMCLIENT_CALL( steamclient_Steam_NotifyMissingInterface, &params );
+}
+
+void steamclient_init_registry(void)
+{
+ load_steamclient();
+ STEAMCLIENT_CALL( steamclient_init_registry, NULL );
+}
diff --git a/lsteamclient/unix_steam_input_manual.cpp b/lsteamclient/unix_steam_input_manual.cpp
new file mode 100644
index 0000000..97886a4
--- /dev/null
+++ b/lsteamclient/unix_steam_input_manual.cpp
@@ -0,0 +1,325 @@
+#include "unix_private.h"
+
+#if 0
+#pragma makedep unix
+#endif
+
+#include <unordered_map>
+
+#ifdef __linux__
+#include <X11/keysym.h>
+#endif
+
+#ifdef __linux__
+static const uint32_t vk_to_xkeysym[0xFF] =
+{
+ 0, /* 0x0 Undefined */
+ 0, /* VK_LBUTTON */
+ 0, /* VK_RBUTTON */
+ XK_Cancel, /* VK_CANCEL */
+ 0, /* VK_MBUTTON */
+ 0, /* VK_XBUTTON1 */
+ 0, /* VK_XBUTTON2 */
+ 0, /* 0x07 Undefined */
+ XK_BackSpace, /* VK_BACK */
+ XK_Tab, /* VK_TAB */
+ 0, /* 0x0A-0x0B Undefined */
+ 0,
+ XK_Clear, /* VK_CLEAR */
+ XK_Return, /* VK_RETURN */
+ 0, /* 0x0E-0x0F Undefined */
+ 0,
+ XK_Shift_L, /* VK_SHIFT */
+ XK_Control_L, /* VK_CONTROL */
+ XK_Alt_L, /* VK_MENU */
+ XK_Pause, /* VK_PAUSE */
+ XK_Caps_Lock, /* VK_CAPITAL */
+ 0, /* VK_KANA */
+ 0, /* 0x16 Undefined */
+ 0, /* VK_JUNJA */
+ 0, /* VK_FINAL */
+ 0, /* VK_HANJA */
+ 0, /* 0x1A Undefined */
+ XK_Escape, /* VK_ESCAPE */
+ XK_Henkan_Mode, /* VK_CONVERT */
+ XK_Muhenkan, /* VK_NONCONVERT */
+ 0, /* VK_ACCEPT */
+ 0, /* VK_MODECHANGE */
+ ' ', /* VK_SPACE */
+ XK_Prior, /* VK_PRIOR */
+ XK_Next, /* VK_NEXT */
+ XK_End, /* VK_END */
+ XK_Home, /* VK_HOME */
+ XK_Left, /* VK_LEFT */
+ XK_Up, /* VK_UP */
+ XK_Right, /* VK_RIGHT */
+ XK_Down, /* VK_DOWN */
+ XK_Select, /* VK_SELECT */
+ XK_Print, /* VK_PRINT */
+ XK_Execute, /* VK_EXECUTE */
+ XK_Print, /* VK_SNAPSHOT */
+ XK_Insert, /* VK_INSERT */
+ XK_Delete, /* VK_DELETE */
+ XK_Help, /* VK_HELP */
+
+ '0',
+ '1',
+ '2',
+ '3',
+ '4',
+ '5',
+ '6',
+ '7',
+ '8',
+ '9',
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0, /* 0x3A-0x40 Undefined */
+ 'A',
+ 'B',
+ 'C',
+ 'D',
+ 'E',
+ 'F',
+ 'G',
+ 'H',
+ 'I',
+ 'J',
+ 'K',
+ 'L',
+ 'M',
+ 'N',
+ 'O',
+ 'P',
+ 'Q',
+ 'R',
+ 'S',
+ 'T',
+ 'U',
+ 'V',
+ 'W',
+ 'X',
+ 'Y',
+ 'Z',
+
+ XK_Super_L, /* VK_LWIN */
+ XK_Super_R, /* VK_RWIN */
+ XK_Menu, /* VK_APPS */
+ 0, /* 0x5E Unassigned */
+ 0, /* VK_SLEEP */
+ XK_KP_0, /* VK_NUMPAD0 */
+ XK_KP_1, /* VK_NUMPAD1 */
+ XK_KP_2, /* VK_NUMPAD2 */
+ XK_KP_3, /* VK_NUMPAD3 */
+ XK_KP_4, /* VK_NUMPAD4 */
+ XK_KP_5, /* VK_NUMPAD5 */
+ XK_KP_6, /* VK_NUMPAD6 */
+ XK_KP_7, /* VK_NUMPAD7 */
+ XK_KP_8, /* VK_NUMPAD8 */
+ XK_KP_9, /* VK_NUMPAD9 */
+ XK_KP_Multiply, /* VK_MULTIPLY */
+ XK_KP_Add, /* VK_ADD */
+ XK_KP_Separator, /* VK_SEPARATOR */
+ XK_KP_Subtract, /* VK_SUBTRACT */
+ XK_KP_Decimal, /* VK_DECIMAL */
+ XK_KP_Divide, /* VK_DIVIDE */
+ XK_F1, /* VK_F1 */
+ XK_F2, /* VK_F2 */
+ XK_F3, /* VK_F3 */
+ XK_F4, /* VK_F4 */
+ XK_F5, /* VK_F5 */
+ XK_F6, /* VK_F6 */
+ XK_F7, /* VK_F7 */
+ XK_F8, /* VK_F8 */
+ XK_F9, /* VK_F9 */
+ XK_F10, /* VK_F10 */
+ XK_F11, /* VK_F11 */
+ XK_F12, /* VK_F12 */
+ XK_F13, /* VK_F13 */
+ XK_F14, /* VK_F14 */
+ XK_F15, /* VK_F15 */
+ XK_F16, /* VK_F16 */
+ XK_F17, /* VK_F17 */
+ XK_F18, /* VK_F18 */
+ XK_F19, /* VK_F19 */
+ XK_F20, /* VK_F20 */
+ XK_F21, /* VK_F21 */
+ XK_F22, /* VK_F22 */
+ XK_F23, /* VK_F23 */
+ XK_F24, /* VK_F24 */
+ 0, /* VK_NAVIGATION_VIEW */
+ 0, /* VK_NAVIGATION_MENU */
+ 0, /* VK_NAVIGATION_UP */
+ 0, /* VK_NAVIGATION_DOWN */
+ 0, /* VK_NAVIGATION_LEFT */
+ 0, /* VK_NAVIGATION_RIGHT */
+ 0, /* VK_NAVIGATION_ACCEPT */
+ 0, /* VK_NAVIGATION_CANCEL */
+ XK_Num_Lock, /* VK_NUMLOCK */
+ XK_Scroll_Lock, /* VK_SCROLL */
+ XK_KP_Equal, /* VK_OEM_NEC_EQUAL */
+ 0, /* VK_OEM_FJ_JISHO */
+ 0, /* VK_OEM_FJ_MASSHOU */
+ 0, /* VK_OEM_FJ_TOUROKU */
+ 0, /* VK_OEM_FJ_LOYA */
+ 0, /* VK_OEM_FJ_ROYA */
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0, /* 0x97-0x9F Unassigned */
+ XK_Shift_L, /* VK_LSHIFT */
+ XK_Shift_R, /* VK_RSHIFT */
+ XK_Control_L, /* VK_LCONTROL */
+ XK_Control_R, /* VK_RCONTROL */
+ XK_Alt_L, /* VK_LMENU */
+ XK_Alt_R, /* VK_RMENU */
+
+ /* below are OEM, browser keys, etc */
+};
+
+uint32_t manual_convert_nNativeKeyCode( uint32_t win_vk )
+{
+ if(win_vk < sizeof(vk_to_xkeysym) / sizeof(*vk_to_xkeysym))
+ return vk_to_xkeysym[win_vk];
+ return 0;
+}
+#elif defined(__APPLE__)
+/* No X11 on macOS, so Valve's keysym table has nothing to map onto. */
+uint32_t manual_convert_nNativeKeyCode( uint32_t win_vk )
+{
+ return 0;
+}
+#else
+#error You must implement VK<->Native keysym conversion for this platform.
+#endif
+
+typedef std::unordered_map< uint64_t, char * > glyph_cache;
+static glyph_cache input_cache, input_cache_svg, input_cache_png, xbox_cache, controller_cache;
+
+static const char *glyph_cache_lookup( glyph_cache &cache, const char *str, uint16_t origin,
+ uint32_t flags, uint16_t size )
+{
+ uint64_t key = (uint64_t)flags << 32 | (uint64_t)size << 16 | origin;
+
+ if (cache.find( key ) == cache.end())
+ {
+ char *dos_path = (char *)malloc( PATH_MAX );
+ steamclient_unix_path_to_dos_path( 1, str, dos_path, PATH_MAX, 0 );
+ cache[key] = dos_path;
+ }
+
+ return cache[key];
+}
+
+template< typename Iface, typename Params >
+static NTSTATUS ISteamController_GetGlyphForActionOrigin( Iface *iface, Params *params, bool wow64 )
+{
+ if (!(params->_ret = iface->GetGlyphForActionOrigin( params->eOrigin ))) return 0;
+ params->_ret = glyph_cache_lookup( controller_cache, params->_ret, params->eOrigin, 0, 0 );
+ return 0;
+}
+
+template< typename Iface, typename Params >
+static NTSTATUS ISteamController_GetGlyphForXboxOrigin( Iface *iface, Params *params, bool wow64 )
+{
+ if (!(params->_ret = iface->GetGlyphForXboxOrigin( params->eOrigin ))) return 0;
+ params->_ret = glyph_cache_lookup( xbox_cache, params->_ret, params->eOrigin, 0, 0 );
+ return 0;
+}
+
+template< typename Iface, typename Params >
+static NTSTATUS ISteamInput_GetGlyphForActionOrigin( Iface *iface, Params *params, bool wow64 )
+{
+ if (!(params->_ret = iface->GetGlyphForActionOrigin( params->eOrigin ))) return 0;
+ params->_ret = glyph_cache_lookup( input_cache, params->_ret, params->eOrigin, 0, 0 );
+ return 0;
+}
+
+template< typename Iface, typename Params >
+static NTSTATUS ISteamInput_GetGlyphForXboxOrigin( Iface *iface, Params *params, bool wow64 )
+{
+ if (!(params->_ret = iface->GetGlyphForXboxOrigin( params->eOrigin ))) return 0;
+ params->_ret = glyph_cache_lookup( xbox_cache, params->_ret, params->eOrigin, 0, 0 );
+ return 0;
+}
+
+static void (W_CDECL *w_EnableActionEventCallbacks_152)( SteamInputActionEvent_t * );
+static void U_CDECL u_SteamInputActionEventCallbackPointer_152( SteamInputActionEvent_t *dat )
+{
+ if (w_EnableActionEventCallbacks_152) queue_cdecl_func_callback( (w_cdecl_func)w_EnableActionEventCallbacks_152, dat, sizeof(*dat) );
+}
+
+template< typename Iface, typename Params >
+NTSTATUS ISteamInput_EnableActionEventCallbacks( Iface *iface, Params *params, bool wow64 )
+{
+ w_EnableActionEventCallbacks_152 = params->pCallback;
+ iface->EnableActionEventCallbacks( params->pCallback ? &u_SteamInputActionEventCallbackPointer_152 : NULL );
+ return 0;
+}
+
+template< typename Iface, typename Params >
+static NTSTATUS ISteamInput_GetGlyphPNGForActionOrigin( Iface *iface, Params *params, bool wow64 )
+{
+ if (!(params->_ret = iface->GetGlyphPNGForActionOrigin( params->eOrigin, params->eSize, params->unFlags ))) return 0;
+ params->_ret = glyph_cache_lookup( input_cache_png, params->_ret, params->eOrigin, params->unFlags, params->eSize );
+ return 0;
+}
+
+template< typename Iface, typename Params >
+static NTSTATUS ISteamInput_GetGlyphSVGForActionOrigin( Iface *iface, Params *params, bool wow64 )
+{
+ if (!(params->_ret = iface->GetGlyphSVGForActionOrigin( params->eOrigin, params->unFlags ))) return 0;
+ params->_ret = glyph_cache_lookup( input_cache_svg, params->_ret, params->eOrigin, params->unFlags, 0 );
+ return 0;
+}
+
+template< typename Iface, typename Params >
+static NTSTATUS ISteamInput_GetGlyphForActionOrigin_Legacy( Iface *iface, Params *params, bool wow64 )
+{
+ if (!(params->_ret = iface->GetGlyphForActionOrigin_Legacy( params->eOrigin ))) return 0;
+ params->_ret = glyph_cache_lookup( input_cache, params->_ret, params->eOrigin, 0, 0 );
+ return 0;
+}
+
+LSTEAMCLIENT_UNIX_IMPL( ISteamController, SteamController005, GetGlyphForActionOrigin );
+
+LSTEAMCLIENT_UNIX_IMPL( ISteamController, SteamController006, GetGlyphForActionOrigin );
+
+LSTEAMCLIENT_UNIX_IMPL( ISteamController, SteamController007, GetGlyphForActionOrigin );
+LSTEAMCLIENT_UNIX_IMPL( ISteamController, SteamController007, GetGlyphForXboxOrigin );
+
+LSTEAMCLIENT_UNIX_IMPL( ISteamController, SteamController008, GetGlyphForActionOrigin );
+LSTEAMCLIENT_UNIX_IMPL( ISteamController, SteamController008, GetGlyphForXboxOrigin );
+
+LSTEAMCLIENT_UNIX_IMPL( ISteamInput, SteamInput001, GetGlyphForActionOrigin );
+LSTEAMCLIENT_UNIX_IMPL( ISteamInput, SteamInput001, GetGlyphForXboxOrigin );
+
+LSTEAMCLIENT_UNIX_IMPL( ISteamInput, SteamInput002, GetGlyphForActionOrigin );
+LSTEAMCLIENT_UNIX_IMPL( ISteamInput, SteamInput002, GetGlyphForXboxOrigin );
+
+LSTEAMCLIENT_UNIX_IMPL( ISteamInput, SteamInput005, EnableActionEventCallbacks );
+LSTEAMCLIENT_UNIX_IMPL( ISteamInput, SteamInput005, GetGlyphPNGForActionOrigin );
+LSTEAMCLIENT_UNIX_IMPL( ISteamInput, SteamInput005, GetGlyphSVGForActionOrigin );
+LSTEAMCLIENT_UNIX_IMPL( ISteamInput, SteamInput005, GetGlyphForActionOrigin_Legacy );
+LSTEAMCLIENT_UNIX_IMPL( ISteamInput, SteamInput005, GetGlyphForXboxOrigin );
+
+LSTEAMCLIENT_UNIX_IMPL( ISteamInput, SteamInput006, EnableActionEventCallbacks );
+LSTEAMCLIENT_UNIX_IMPL( ISteamInput, SteamInput006, GetGlyphPNGForActionOrigin );
+LSTEAMCLIENT_UNIX_IMPL( ISteamInput, SteamInput006, GetGlyphSVGForActionOrigin );
+LSTEAMCLIENT_UNIX_IMPL( ISteamInput, SteamInput006, GetGlyphForActionOrigin_Legacy );
+LSTEAMCLIENT_UNIX_IMPL( ISteamInput, SteamInput006, GetGlyphForXboxOrigin );
+
+LSTEAMCLIENT_UNIX_IMPL( ISteamInput, SteamInput007, EnableActionEventCallbacks );
+LSTEAMCLIENT_UNIX_IMPL( ISteamInput, SteamInput007, GetGlyphPNGForActionOrigin );
+LSTEAMCLIENT_UNIX_IMPL( ISteamInput, SteamInput007, GetGlyphSVGForActionOrigin );
+LSTEAMCLIENT_UNIX_IMPL( ISteamInput, SteamInput007, GetGlyphForActionOrigin_Legacy );
+LSTEAMCLIENT_UNIX_IMPL( ISteamInput, SteamInput007, GetGlyphForXboxOrigin );
diff --git a/lsteamclient/unixlib.cpp b/lsteamclient/unixlib.cpp
new file mode 100644
index 0000000..944ee88
--- /dev/null
+++ b/lsteamclient/unixlib.cpp
@@ -0,0 +1,1666 @@
+/* Stock Wine 11.15 windef.h defines max/min as macros unless NOMINMAX is set, */
+/* which breaks the std::max in collapse_path. */
+#define NOMINMAX
+#include "ntstatus.h"
+#define WIN32_NO_STATUS
+#include "unix_private.h"
+
+#include <winnls.h>
+#include <pthread.h>
+#include <stdlib.h>
+#include <dlfcn.h>
+#include <unordered_map>
+#include <vector>
+
+#if 0
+#pragma makedep unix
+#endif
+
+WINE_DEFAULT_DEBUG_CHANNEL(steamclient);
+
+char *g_tmppath;
+
+struct callback_entry
+{
+ struct list entry;
+ struct callback callback;
+};
+
+static struct list callbacks = LIST_INIT( callbacks );
+static pthread_mutex_t callbacks_lock = PTHREAD_MUTEX_INITIALIZER;
+
+static const struct callback_def *find_first_callback_def_by_id( int id, bool wow64 );
+
+static int callback_len_utow( int cb_id, int u_len, bool wow64 )
+{
+ const struct callback_def *c, *end;
+
+ if (!(c = find_first_callback_def_by_id( cb_id, wow64 ))) return u_len;
+
+ if (wow64) end = wow64_callback_data + wow64_callback_data_size;
+ else end = callback_data + callback_data_size;
+
+ while (c != end && c->id == cb_id)
+ {
+ if (c->u_callback_len == u_len) return c->w_callback_len;
+ ++c;
+ }
+ ERR( "Unix len %d not found for callback %d.\n", u_len, cb_id );
+ return find_first_callback_def_by_id( cb_id, wow64 )->w_callback_len;
+}
+
+void queue_vtable_callback( struct w_iface *w_iface, enum callback_type type, uint64_t arg0, uint64_t arg1 )
+{
+ struct callback_entry *entry;
+ uint32_t size = 0;
+
+ size += sizeof(struct callback_entry);
+ if (!(entry = (struct callback_entry *)calloc( 1, size ))) return;
+
+ entry->callback.type = type;
+ size -= offsetof( struct callback_entry, callback );
+ entry->callback.size = size;
+
+ entry->callback.call_iface_vtable.iface = w_iface;
+ entry->callback.call_iface_vtable.arg0 = arg0;
+ entry->callback.call_iface_vtable.arg1 = arg1;
+
+ pthread_mutex_lock( &callbacks_lock );
+ list_add_tail( &callbacks, &entry->entry );
+ pthread_mutex_unlock( &callbacks_lock );
+}
+
+void queue_vtable_callback_0_server_responded( struct w_iface *w_iface, gameserveritem_t_165 *server )
+{
+ uint32_t size = sizeof(*server);
+ struct callback_entry *entry;
+
+ size += sizeof(struct callback_entry);
+ if (!(entry = (struct callback_entry *)calloc( 1, size ))) return;
+
+ entry->callback.type = CALL_IFACE_VTABLE_0_SERVER_RESPONDED;
+ size -= offsetof( struct callback_entry, callback );
+ entry->callback.size = size;
+
+ entry->callback.server_responded.iface = w_iface;
+ entry->callback.server_responded.server[0] = *server;
+
+ pthread_mutex_lock( &callbacks_lock );
+ list_add_tail( &callbacks, &entry->entry );
+ pthread_mutex_unlock( &callbacks_lock );
+}
+
+void queue_vtable_callback_0_add_player_to_list( struct w_iface *w_iface, const char *pchName, int nScore, float flTimePlayed )
+{
+ uint32_t name_size = strlen( pchName ) + 1, size = name_size;
+ struct callback_entry *entry;
+
+ size += sizeof(struct callback_entry);
+ if (!(entry = (struct callback_entry *)calloc( 1, size ))) return;
+
+ entry->callback.type = CALL_IFACE_VTABLE_0_ADD_PLAYER_TO_LIST;
+ size -= offsetof( struct callback_entry, callback );
+ entry->callback.size = size;
+
+ entry->callback.add_player_to_list.iface = w_iface;
+ entry->callback.add_player_to_list.score = nScore;
+ entry->callback.add_player_to_list.time_played = flTimePlayed;
+ memcpy( (char *)entry->callback.add_player_to_list.name, pchName, name_size );
+
+ pthread_mutex_lock( &callbacks_lock );
+ list_add_tail( &callbacks, &entry->entry );
+ pthread_mutex_unlock( &callbacks_lock );
+}
+
+void queue_vtable_callback_0_rules_responded( struct w_iface *w_iface, const char *pchRule, const char *pchValue )
+{
+ uint32_t rule_size = strlen( pchRule ) + 1, value_size = strlen( pchValue ) + 1, size = rule_size + value_size;
+ struct callback_entry *entry;
+
+ size += sizeof(struct callback_entry);
+ if (!(entry = (struct callback_entry *)calloc( 1, size ))) return;
+
+ entry->callback.type = CALL_IFACE_VTABLE_0_RULES_RESPONDED;
+ size -= offsetof( struct callback_entry, callback );
+ entry->callback.size = size;
+
+ entry->callback.rules_responded.iface = w_iface;
+ memcpy( (char *)entry->callback.rules_responded.rule_and_value, pchRule, rule_size );
+ memcpy( (char *)entry->callback.rules_responded.rule_and_value + rule_size, pchValue, value_size );
+
+ pthread_mutex_lock( &callbacks_lock );
+ list_add_tail( &callbacks, &entry->entry );
+ pthread_mutex_unlock( &callbacks_lock );
+}
+
+void queue_vtable_callback_0_friends_responded( struct w_iface *w_iface, CSteamID steamID, const char *pchName, int8_t bCurrentlyConnected )
+{
+ uint32_t name_size = strlen( pchName ) + 1, size = name_size;
+ struct callback_entry *entry;
+
+ size += sizeof(struct callback_entry);
+ if (!(entry = (struct callback_entry *)calloc( 1, size ))) return;
+
+ entry->callback.type = CALL_IFACE_VTABLE_0_FRIENDS_RESPONDED;
+ size -= offsetof( struct callback_entry, callback );
+ entry->callback.size = size;
+
+ entry->callback.friends_responded.iface = w_iface;
+ entry->callback.friends_responded.steamid = steamID;
+ entry->callback.friends_responded.connected = bCurrentlyConnected;
+ memcpy( (char *)entry->callback.friends_responded.name, pchName, name_size );
+
+ pthread_mutex_lock( &callbacks_lock );
+ list_add_tail( &callbacks, &entry->entry );
+ pthread_mutex_unlock( &callbacks_lock );
+}
+
+static w_FSteamNetworkingSocketsDebugOutput w_steam_networking_socket_debug_output;
+static void u_steam_networking_socket_debug_output( uint32_t nType, const char *pszMsg )
+{
+ uint32_t msg_size = strlen( pszMsg ) + 1, size = msg_size;
+ struct callback_entry *entry;
+
+ size += sizeof(struct callback_entry);
+ if (!(entry = (struct callback_entry *)calloc( 1, size ))) return;
+
+ entry->callback.type = SOCKETS_DEBUG_OUTPUT;
+ size -= offsetof( struct callback_entry, callback );
+ entry->callback.size = size;
+
+ entry->callback.sockets_debug_output.pfnFunc = w_steam_networking_socket_debug_output;
+ entry->callback.sockets_debug_output.type = nType;
+ memcpy( (char *)entry->callback.sockets_debug_output.msg, pszMsg, msg_size );
+
+ pthread_mutex_lock( &callbacks_lock );
+ list_add_tail( &callbacks, &entry->entry );
+ pthread_mutex_unlock( &callbacks_lock );
+}
+
+void queue_cdecl_func_callback( w_cdecl_func func, void *data, uint32_t data_size )
+{
+ uint32_t size = data_size;
+ struct callback_entry *entry;
+
+ size += sizeof(struct callback_entry);
+ if (!(entry = (struct callback_entry *)calloc( 1, size ))) return;
+
+ entry->callback.type = CALL_CDECL_FUNC_DATA;
+ size -= offsetof( struct callback_entry, callback );
+ entry->callback.size = size;
+
+ entry->callback.call_cdecl_func_data.pFunc = func;
+ memcpy( (char *)entry->callback.call_cdecl_func_data.data, data, data_size );
+
+ pthread_mutex_lock( &callbacks_lock );
+ list_add_tail( &callbacks, &entry->entry );
+ pthread_mutex_unlock( &callbacks_lock );
+}
+
+u_FSteamNetworkingSocketsDebugOutput manual_convert_SetDebugOutputFunction_pfnFunc( w_FSteamNetworkingSocketsDebugOutput w_func )
+{
+ w_steam_networking_socket_debug_output = w_func;
+ return &u_steam_networking_socket_debug_output;
+}
+
+static w_SteamAPIWarningMessageHook_t w_steam_api_warning_message_hook;
+static void u_steam_api_warning_message_hook( int severity, const char *msg )
+{
+ uint32_t msg_size = strlen( msg ) + 1, size = msg_size;
+ struct callback_entry *entry;
+
+ size += sizeof(struct callback_entry);
+ if (!(entry = (struct callback_entry *)calloc( 1, size ))) return;
+
+ entry->callback.type = WARNING_MESSAGE_HOOK;
+ size -= offsetof( struct callback_entry, callback );
+ entry->callback.size = size;
+
+ entry->callback.warning_message_hook.pFunction = w_steam_api_warning_message_hook;
+ entry->callback.warning_message_hook.severity = severity;
+ memcpy( (char *)entry->callback.warning_message_hook.msg, msg, msg_size );
+
+ pthread_mutex_lock( &callbacks_lock );
+ list_add_tail( &callbacks, &entry->entry );
+ pthread_mutex_unlock( &callbacks_lock );
+}
+
+u_SteamAPIWarningMessageHook_t manual_convert_SetWarningMessageHook_pFunction( w_SteamAPIWarningMessageHook_t w_func )
+{
+ w_steam_api_warning_message_hook = w_func;
+ return &u_steam_api_warning_message_hook;
+}
+
+static uint32_t U_CDECL u_steam_api_check_callback_registered( int32_t v )
+{
+ return 1;
+}
+
+u_SteamAPI_CheckCallbackRegistered_t manual_convert_Set_SteamAPI_CCheckCallbackRegisteredInProcess_func( w_SteamAPI_CheckCallbackRegistered_t w_func )
+{
+ FIXME("not implemented!\n");
+ return &u_steam_api_check_callback_registered;
+}
+
+static uint32_t U_CDECL u_steam_api_check_callback_registered_156( int32_t v )
+{
+ return 1;
+}
+
+u_SteamAPI_CheckCallbackRegistered_t_156 manual_convert_Set_SteamAPI_CCheckCallbackRegisteredInProcess_func_156( w_SteamAPI_CheckCallbackRegistered_t_156 w_func )
+{
+ FIXME("not implemented!\n");
+ return &u_steam_api_check_callback_registered_156;
+}
+
+static void U_CDECL u_steam_api_post_api_result_in_process( uint64_t a, void *b, uint32_t c, int d )
+{
+}
+
+u_SteamAPI_PostAPIResultInProcess_t manual_convert_Set_SteamAPI_CPostAPIResultInProcess_func( w_SteamAPI_PostAPIResultInProcess_t w_func )
+{
+ FIXME("not implemented!\n");
+ return &u_steam_api_post_api_result_in_process;
+}
+
+u_SteamAPI_PostAPIResultInProcess_t manual_convert_Remove_SteamAPI_CPostAPIResultInProcess_func( w_SteamAPI_PostAPIResultInProcess_t w_func )
+{
+ FIXME("not implemented!\n");
+ return &u_steam_api_post_api_result_in_process;
+}
+
+static void U_CDECL u_void_steam_api_post_api_result_in_process(void)
+{
+}
+
+u_void_SteamAPI_PostAPIResultInProcess_t manual_convert_DEPRECATED_Set_SteamAPI_CPostAPIResultInProcess__a( w_void_SteamAPI_PostAPIResultInProcess_t w_func )
+{
+ FIXME("not implemented!\n");
+ return &u_void_steam_api_post_api_result_in_process;
+}
+
+u_void_SteamAPI_PostAPIResultInProcess_t manual_convert_DEPRECATED_Remove_SteamAPI_CPostAPIResultInProcess__a( w_void_SteamAPI_PostAPIResultInProcess_t w_func )
+{
+ FIXME("not implemented!\n");
+ return &u_void_steam_api_post_api_result_in_process;
+}
+
+template< typename Iface, typename Params >
+static NTSTATUS ISteamClient_Set_SteamAPI_CCheckCallbackRegisteredInProcess( Iface *iface, Params *params, bool wow64 )
+{
+ uint32_t (*U_CDECL lin_func)(int32_t) = manual_convert_Set_SteamAPI_CCheckCallbackRegisteredInProcess_func_156( params->func );
+ iface->Set_SteamAPI_CCheckCallbackRegisteredInProcess( lin_func );
+ return 0;
+}
+
+LSTEAMCLIENT_UNIX_IMPL( ISteamClient, SteamClient020, Set_SteamAPI_CCheckCallbackRegisteredInProcess );
+LSTEAMCLIENT_UNIX_IMPL( ISteamClient, SteamClient021, Set_SteamAPI_CCheckCallbackRegisteredInProcess );
+LSTEAMCLIENT_UNIX_IMPL( ISteamClient, SteamClient023, Set_SteamAPI_CCheckCallbackRegisteredInProcess );
+
+template< typename Params >
+static NTSTATUS steamclient_next_callback( Params *params, bool wow64 )
+{
+ uint32_t capacity = params->size;
+ struct list *ptr;
+
+ pthread_mutex_lock( &callbacks_lock );
+ if ((ptr = list_head( &callbacks )))
+ {
+ struct callback_entry *entry = LIST_ENTRY( ptr, struct callback_entry, entry );
+
+ params->size = entry->callback.size;
+ if (params->size <= capacity)
+ {
+ memcpy( params->callback, &entry->callback, params->size );
+ list_remove( &entry->entry );
+ free( entry );
+ }
+ }
+ pthread_mutex_unlock( &callbacks_lock );
+
+ params->_ret = !!ptr;
+ return 0;
+}
+
+static void *(*p_CreateInterface)( const char *name, int *return_code );
+static int8_t (*p_Steam_BGetCallback)( int32_t a, u_CallbackMsg_t *b, int32_t *c );
+static int8_t (*p_Steam_GetAPICallResult)( int32_t, uint64_t, void *, int, int, int8_t * );
+static int8_t (*p_Steam_FreeLastCallback)( int32_t );
+static void (*p_Steam_ReleaseThreadLocalMemory)( int );
+static bool (*p_Steam_IsKnownInterface)( const char * );
+static void (*p_Steam_NotifyMissingInterface)( int32_t, const char * );
+
+template< typename Params >
+static NTSTATUS steamclient_Steam_BGetCallback( Params *params, bool wow64 )
+{
+ u_CallbackMsg_t *u_msg, u_msg_tmp;
+ auto *w_msg = &*params->w_msg;
+
+ if (!p_Steam_BGetCallback( params->pipe, &u_msg_tmp, params->ignored ))
+ params->_ret = false;
+ else
+ {
+ u_msg = new u_CallbackMsg_t(u_msg_tmp);
+ TRACE( "id %d, u_size %d.\n", u_msg->m_iCallback, u_msg->m_cubParam );
+ w_msg->m_hSteamUser = u_msg->m_hSteamUser;
+ w_msg->m_iCallback = u_msg->m_iCallback;
+ w_msg->m_cubParam = callback_len_utow( u_msg->m_iCallback, u_msg->m_cubParam, false );
+ params->cookie = (UINT_PTR)u_msg;
+ params->_ret = true;
+ }
+
+ return 0;
+}
+
+template< typename Params >
+static NTSTATUS steamclient_callback_message_receive( Params *params, bool wow64 )
+{
+ u_CallbackMsg_t *u_msg = (u_CallbackMsg_t *)(UINT_PTR)params->cookie;
+ auto *w_msg = &*params->w_msg;
+
+ if (!u_msg) return 0;
+
+ convert_callback_utow( u_msg->m_iCallback, (void *)u_msg->m_pubParam,
+ u_msg->m_cubParam, (void *)w_msg->m_pubParam,
+ w_msg->m_cubParam, false );
+ if (w_msg->m_iCallback == 703 /* SteamAPICallCompleted_t::k_iCallback */)
+ {
+ SteamAPICallCompleted_t_137 *c = (SteamAPICallCompleted_t_137 *)u_msg->m_pubParam;
+ SteamAPICallCompleted_t_137 *w = (SteamAPICallCompleted_t_137 *)(uint8_t *)w_msg->m_pubParam;
+
+ if (sizeof(SteamAPICallCompleted_t_137) == w_msg->m_cubParam)
+ {
+ int len;
+
+ len = callback_len_utow( c->m_iCallback, c->m_cubParam, false );
+ TRACE( "SteamAPICallCompleted_t id %d, size %d -> %d.\n", c->m_iCallback, c->m_cubParam, len );
+ w->m_cubParam = len;
+ }
+ else
+ {
+ WARN( "Unexpected SteamAPICallCompleted_t callback size %d, not doing API callback size conversion.", w_msg->m_cubParam );
+ }
+ }
+
+ delete u_msg;
+ return 0;
+}
+
+template< typename Params >
+static NTSTATUS steamclient_Steam_FreeLastCallback( Params *params, bool wow64 )
+{
+ params->_ret = p_Steam_FreeLastCallback( params->pipe );
+ return 0;
+}
+
+template< typename Params >
+static NTSTATUS steamclient_Steam_GetAPICallResult( Params *params, bool wow64 )
+{
+ int u_callback_len = params->w_callback_len;
+ void *u_callback;
+
+ if (!(u_callback = alloc_callback_wtou( params->id, params->w_callback, &u_callback_len, false ))) return false;
+
+ params->_ret = p_Steam_GetAPICallResult( params->pipe, params->call, u_callback, u_callback_len,
+ params->id, params->failed );
+
+ if (params->_ret && u_callback != params->w_callback)
+ {
+ convert_callback_utow( params->id, u_callback, u_callback_len, params->w_callback, params->w_callback_len, false );
+ free( u_callback );
+ }
+
+ return 0;
+}
+
+static UINT asciiz_to_unicode( WCHAR *dst, const char *src )
+{
+ WCHAR *p = dst;
+ while ((*p++ = *src++));
+ return (p - dst) * sizeof(WCHAR);
+}
+
+static BOOL set_reg_value( HANDLE hkey, const WCHAR *name, UINT type, const void *value, DWORD count )
+{
+ unsigned short name_size = name ? lstrlenW( name ) * sizeof(WCHAR) : 0;
+ UNICODE_STRING nameW = { name_size, name_size, (WCHAR *)name };
+ return !NtSetValueKey( hkey, &nameW, 0, type, value, count );
+}
+
+static void set_reg_ascii_dword( HANDLE hkey, const char *name, DWORD value )
+{
+ WCHAR nameW[64], valueW[128];
+ asciiz_to_unicode( nameW, name );
+ set_reg_value( hkey, nameW, REG_DWORD, &value, sizeof(value) );
+}
+
+static void set_reg_ascii_str( HANDLE hkey, const char *name, const char *value )
+{
+ size_t len = strlen( value ) + 1;
+ WCHAR nameW[64], *valueW;
+
+ if (!(valueW = (WCHAR *)malloc( len * sizeof(*valueW) ))) return;
+ asciiz_to_unicode( valueW, value );
+ asciiz_to_unicode( nameW, name );
+ set_reg_value( hkey, nameW, REG_SZ, valueW, len * sizeof(*valueW) );
+ free( valueW );
+}
+
+static void set_reg_ascii_wstr( HANDLE hkey, const char *name, const WCHAR *valueW )
+{
+ size_t len = lstrlenW( valueW ) + 1;
+ WCHAR nameW[64];
+
+ asciiz_to_unicode( nameW, name );
+ set_reg_value( hkey, nameW, REG_SZ, valueW, len * sizeof(*valueW) );
+}
+
+static inline void init_unicode_string( UNICODE_STRING *str, const WCHAR *data )
+{
+ str->Length = wcslen( data ) * sizeof(WCHAR);
+ str->MaximumLength = str->Length + sizeof(WCHAR);
+ str->Buffer = (WCHAR *)data;
+}
+
+static NTSTATUS open_hkcu_key( const char *path, HANDLE *key )
+{
+ NTSTATUS status;
+ char buffer[256];
+ WCHAR bufferW[256];
+ DWORD_PTR sid_data[(sizeof(TOKEN_USER) + SECURITY_MAX_SID_SIZE) / sizeof(DWORD_PTR)];
+ DWORD i, len = sizeof(sid_data);
+ SID *sid;
+ UNICODE_STRING name;
+ OBJECT_ATTRIBUTES attr;
+
+ status = NtQueryInformationToken( GetCurrentThreadEffectiveToken(), TokenUser, sid_data, len, &len );
+ if (status) return status;
+
+ sid = (SID *)((TOKEN_USER *)sid_data)->User.Sid;
+ len = snprintf( buffer, sizeof(buffer), "\\Registry\\User\\S-%u-%u", sid->Revision,
+ (int)MAKELONG( MAKEWORD( sid->IdentifierAuthority.Value[5], sid->IdentifierAuthority.Value[4] ),
+ MAKEWORD( sid->IdentifierAuthority.Value[3], sid->IdentifierAuthority.Value[2] )));
+ for (i = 0; i < sid->SubAuthorityCount; i++)
+ len += snprintf( buffer + len, sizeof(buffer) - len, "-%u", (int)sid->SubAuthority[i] );
+ len += snprintf( buffer + len, sizeof(buffer) - len, "\\%s", path );
+
+ asciiz_to_unicode( bufferW, buffer );
+ init_unicode_string( &name, bufferW );
+ InitializeObjectAttributes( &attr, &name, OBJ_CASE_INSENSITIVE, 0, NULL );
+ return NtCreateKey( key, KEY_ALL_ACCESS, &attr, 0, NULL, 0, NULL );
+}
+
+/* requires steam API to be initialized */
+static void setup_steam_registry( u_ISteamClient_SteamClient017 *client, int pipe, int user )
+{
+ static const int system_locale_appids[] =
+ {
+ 1284210 /* Guild Wars 2 */
+ };
+
+ const char *ui_lang, *language, *languages, *locale = NULL;
+ u_ISteamApps_STEAMAPPS_INTERFACE_VERSION008 *apps;
+ u_ISteamUtils_SteamUtils009 *utils;
+ unsigned int appid, status;
+ char buf[256];
+ HANDLE key;
+ int i;
+
+ utils = (u_ISteamUtils_SteamUtils009 *)client->GetISteamUtils( pipe, "SteamUtils009" );
+ ui_lang = utils->GetSteamUILanguage();
+ TRACE( "UI language: %s\n", debugstr_a(ui_lang) );
+
+ if ((status = open_hkcu_key( "Software\\Valve\\Steam", &key )))
+ ERR( "Could not create key, status %#x\n", status );
+ else
+ {
+ set_reg_ascii_str( key, "language", ui_lang );
+ NtClose( key );
+ }
+
+ appid = utils->GetAppID();
+ TRACE( "appid: %u\n", appid );
+
+ if ((status = open_hkcu_key( "Software\\Valve\\Steam\\Apps", &key )))
+ ERR( "Could not create key, status %#x\n", status );
+ else
+ NtClose( key );
+
+ sprintf( buf, "Software\\Valve\\Steam\\Apps\\%u", appid );
+ if ((status = open_hkcu_key( buf, &key ))) ERR( "Could not create key, status %#x\n", status );
+ else
+ {
+ DWORD value;
+ value = 1;
+ set_reg_ascii_dword( key, "Installed", value );
+ set_reg_ascii_dword( key, "Running", value );
+ value = 0;
+ set_reg_ascii_dword( key, "Updating", value );
+ NtClose( key );
+ }
+
+ apps = (u_ISteamApps_STEAMAPPS_INTERFACE_VERSION008 *)client->GetISteamApps( user, pipe, "STEAMAPPS_INTERFACE_VERSION008" );
+ language = apps->GetCurrentGameLanguage();
+ languages = apps->GetAvailableGameLanguages();
+ TRACE( "Game language %s, available %s\n", debugstr_a(language), debugstr_a(languages) );
+
+ if (!strchr( languages, ',' )) /* If there is a list of languages then respect that */
+ {
+ for (i = 0; language && i < ARRAY_SIZE(system_locale_appids); i++)
+ {
+ if (system_locale_appids[i] == appid)
+ {
+ TRACE( "Not changing system locale for application %i\n", appid );
+ language = NULL;
+ }
+ }
+ }
+
+ if (!language) locale = NULL;
+ else if (!strcmp( language, "arabic" )) locale = "ar_001.UTF-8";
+ else if (!strcmp( language, "bulgarian" )) locale = "bg_BG.UTF-8";
+ else if (!strcmp( language, "schinese" )) locale = "zh_CN.UTF-8";
+ else if (!strcmp( language, "tchinese" )) locale = "zh_TW.UTF-8";
+ else if (!strcmp( language, "czech" )) locale = "cs_CZ.UTF-8";
+ else if (!strcmp( language, "danish" )) locale = "da_DK.UTF-8";
+ else if (!strcmp( language, "dutch" )) locale = "nl_NL.UTF-8";
+ else if (!strcmp( language, "english" )) locale = "en_US.UTF-8";
+ else if (!strcmp( language, "finnish" )) locale = "fi_FI.UTF-8";
+ else if (!strcmp( language, "french" )) locale = "fr_FR.UTF-8";
+ else if (!strcmp( language, "german" )) locale = "de_DE.UTF-8";
+ else if (!strcmp( language, "greek" )) locale = "el_GR.UTF-8";
+ else if (!strcmp( language, "hungarian" )) locale = "hu_HU.UTF-8";
+ else if (!strcmp( language, "italian" )) locale = "it_IT.UTF-8";
+ else if (!strcmp( language, "japanese" )) locale = "ja_JP.UTF-8";
+ else if (!strcmp( language, "koreana" )) locale = "ko_KR.UTF-8";
+ else if (!strcmp( language, "norwegian" )) locale = "nb_NO.UTF-8";
+ else if (!strcmp( language, "polish" )) locale = "pl_PL.UTF-8";
+ else if (!strcmp( language, "portuguese" )) locale = "pt_PT.UTF-8";
+ else if (!strcmp( language, "brazilian" )) locale = "pt_BR.UTF-8";
+ else if (!strcmp( language, "romanian" )) locale = "ro_RO.UTF-8";
+ else if (!strcmp( language, "russian" )) locale = "ru_RU.UTF-8";
+ else if (!strcmp( language, "spanish" )) locale = "es_ES.UTF-8";
+ else if (!strcmp( language, "latam" )) locale = "es_419.UTF-8";
+ else if (!strcmp( language, "swedish" )) locale = "sv_SE.UTF-8";
+ else if (!strcmp( language, "thai" )) locale = "th_TH.UTF-8";
+ else if (!strcmp( language, "turkish" )) locale = "tr_TR.UTF-8";
+ else if (!strcmp( language, "ukrainian" )) locale = "uk_UA.UTF-8";
+ else if (!strcmp( language, "vietnamese" )) locale = "vi_VN.UTF-8";
+ else FIXME( "Unsupported game language %s\n", debugstr_a(language) );
+
+ /* HACK: Bug 23597 Granado Espada Japan (1219160) launcher needs Japanese locale to display correctly */
+ if (appid == 1219160) locale = "ja_JP.UTF-8";
+ /* HACK: Bug 26267 Worms Armageddon (217200) Game Set-Up Does Not Respond to Language Preference on Proton
+ * The game reports only English in ISteamApps::GetCurrentGameLanguage() and ISteamApps::GetAvailableGameLanguages().
+ * So LC_MESSAGES is always set to English. Not setting LC_MESSAGES causes the game to use that from the host.
+ * That allows the game to detect the host language settings for the "Create a new team" settings in game.
+ * The "Create a new team" setting is affected by Settings->Time & Language->Region->Country or Region on Windows 10. */
+ else if (appid == 217200) locale = NULL;
+
+ if (locale)
+ {
+ FIXME( "Game language %s, defaulting LC_CTYPE / LC_MESSAGES to %s.\n", debugstr_a(language), locale );
+ setenv( "LC_CTYPE", locale, FALSE );
+ setenv( "LC_MESSAGES", locale, FALSE );
+ }
+}
+
+/* requires steam API to be initialized */
+static void setup_battleye_bridge( u_ISteamClient_SteamClient017 *client, int pipe, int user )
+{
+ u_ISteamApps_STEAMAPPS_INTERFACE_VERSION008 *apps;
+ const unsigned int be_runtime_appid = 1161040;
+ char path[2048];
+ int error;
+
+ apps = (u_ISteamApps_STEAMAPPS_INTERFACE_VERSION008 *)client->GetISteamApps( user, pipe, "STEAMAPPS_INTERFACE_VERSION008" );
+ if (!apps->BIsAppInstalled( be_runtime_appid )) return;
+ if (!apps->GetAppInstallDir( be_runtime_appid, path, sizeof(path) )) return;
+ TRACE( "Found battleye runtime at %s\n", path );
+ setenv( "PROTON_BATTLEYE_RUNTIME", path, 1 );
+}
+
+static void setup_eac_bridge( u_ISteamClient_SteamClient017 *client, int pipe, int user )
+{
+ u_ISteamApps_STEAMAPPS_INTERFACE_VERSION008 *apps;
+ const unsigned int eac_runtime_appid = 1826330;
+ char path[2048];
+ int error;
+
+ apps = (u_ISteamApps_STEAMAPPS_INTERFACE_VERSION008 *)client->GetISteamApps( user, pipe, "STEAMAPPS_INTERFACE_VERSION008" );
+ if (!apps->BIsAppInstalled( eac_runtime_appid )) return;
+ if (!apps->GetAppInstallDir( eac_runtime_appid, path, sizeof(path) )) return;
+ TRACE( "Found easyanticheat runtime at %s\n", path );
+ setenv( "PROTON_EAC_RUNTIME", path, 1 );
+}
+
+static void setup_proton_voice_files( u_ISteamClient_SteamClient017 *client, int pipe, int user )
+{
+ u_ISteamApps_STEAMAPPS_INTERFACE_VERSION008 *apps;
+ const unsigned int eac_runtime_appid = 3086180;
+ char path[2048];
+ int error;
+
+ apps = (u_ISteamApps_STEAMAPPS_INTERFACE_VERSION008 *)client->GetISteamApps( user, pipe, "STEAMAPPS_INTERFACE_VERSION008" );
+ if (!apps->BIsAppInstalled( eac_runtime_appid )) return;
+ if (!apps->GetAppInstallDir( eac_runtime_appid, path, sizeof(path) )) return;
+ TRACE( "Found proton voice files at %s\n", path );
+ setenv( "PROTON_VOICE_FILES", path, 1 );
+}
+
+static void setup_proton_soundfonts( u_ISteamClient_SteamClient017 *client, int pipe, int user )
+{
+ static const WCHAR PROTON_SOUNDFILES_FILES_W[] = u"PROTON_SOUNDFONT_FILES";
+ static const WCHAR SF2_NAME[] = u"FluidR3_GM.sf2";
+ u_ISteamApps_STEAMAPPS_INTERFACE_VERSION008 *apps;
+ const unsigned int soundfonts_appid = 3368180;
+ WCHAR *dos_path;
+ OBJECT_ATTRIBUTES attr;
+ ULONG nt_path_len = 0;
+ char unix_path[2048];
+ UNICODE_STRING name;
+ NTSTATUS status;
+ char *path_end;
+ HANDLE gm_key;
+
+ apps = (u_ISteamApps_STEAMAPPS_INTERFACE_VERSION008 *)client->GetISteamApps( user, pipe, "STEAMAPPS_INTERFACE_VERSION008" );
+ if (!apps->BIsAppInstalled( soundfonts_appid )) return;
+ if (!apps->GetAppInstallDir( soundfonts_appid, unix_path, sizeof(unix_path) )) return;
+
+ WINE_TRACE( "Found Proton Soundfont at %s\n", unix_path );
+
+ if ((status = ntdll_get_dos_file_name( unix_path, &dos_path, FILE_OPEN )))
+ {
+ WINE_ERR( "Failed to convert unix path to NT: %x\n", status );
+ return;
+ }
+ nt_path_len = wcslen(dos_path);
+ dos_path = (WCHAR*) realloc(dos_path, (nt_path_len + 2 + ARRAYSIZE(SF2_NAME)) * sizeof(*dos_path));
+ dos_path[nt_path_len] = u'\\';
+ wcscpy( dos_path + nt_path_len + 1, SF2_NAME );
+
+ WINE_TRACE( "GM file path %s\n", wine_dbgstr_w(dos_path) );
+
+ init_unicode_string( &name, u"\\Registry\\Machine\\Software\\Microsoft\\DirectMusic" );
+ InitializeObjectAttributes( &attr, &name, OBJ_CASE_INSENSITIVE, 0, NULL );
+ if ((status = NtCreateKey( &gm_key, KEY_ALL_ACCESS, &attr, 0, NULL, 0, NULL )))
+ {
+ WINE_ERR( "Failed to open DirectMusic key: %x\n", status );
+ free(dos_path);
+ return;
+ }
+
+ set_reg_ascii_wstr( gm_key, "GMFilePath", dos_path );
+ NtClose( gm_key );
+
+ init_unicode_string( &name, u"\\Registry\\Machine\\Software\\Wow6432Node\\Microsoft\\DirectMusic" );
+ if ((status = NtCreateKey( &gm_key, KEY_ALL_ACCESS | KEY_WOW64_32KEY, &attr, 0, NULL, 0, NULL)))
+ {
+ WINE_ERR( "Failed to open DirectMusic key (32 bit): %x\n", status);
+ free(dos_path);
+ return;
+ }
+ set_reg_ascii_wstr( gm_key, "GMFilePath", dos_path );
+ NtClose( gm_key );
+ free(dos_path);
+}
+
+template< typename Params >
+static NTSTATUS steamclient_init_registry( Params *params, bool wow64 )
+{
+ u_ISteamClient_SteamClient017 *client;
+ int pipe, user, error;
+
+ client = (u_ISteamClient_SteamClient017 *)p_CreateInterface( "SteamClient017", &error );
+ if (!(pipe = client->CreateSteamPipe()) || !(user = client->ConnectToGlobalUser( pipe )))
+ {
+ ERR( "Failed to connect to Steam\n" );
+ if (pipe) client->BReleaseSteamPipe( pipe );
+ return 0;
+ }
+
+ setup_steam_registry( client, pipe, user );
+ setup_battleye_bridge( client, pipe, user );
+ setup_eac_bridge( client, pipe, user );
+ setup_proton_voice_files( client, pipe, user );
+ setup_proton_soundfonts( client, pipe, user );
+
+ client->BReleaseSteamPipe( pipe );
+ return 0;
+}
+
+static void sync_env_var( const char *name, bool unset, const char *val )
+{
+ const char *s = getenv( name );
+
+ if (unset && s) unsetenv( name );
+ else if (val && (!s || strcmp( s, val ))) setenv( name, val, 1 );
+}
+
+#ifdef __APPLE__
+/* The FEX wine loader is hardened without allow-dyld-environment-variables, so
+ * dyld drops the insert list that would carry the overlay renderer and the
+ * notproton shim. Load them by hand instead. */
+static void load_overlay_libraries( void )
+{
+ const char *inserts = getenv( "STEAM_DYLD_INSERT_LIBRARIES" );
+ const char *shim = getenv( "NOTPROTON_OVERLAY_SHIM" );
+ void *handle, *shim_handle = NULL;
+ void (*install)( void );
+ char *list, *cursor, *path;
+
+ if (!inserts || !*inserts) return;
+
+ if (shim && *shim && (handle = dlopen( shim, RTLD_NOW | RTLD_NOLOAD )))
+ {
+ TRACE( "overlay shim already inserted, its interposes are live\n" );
+ dlclose( handle );
+ return;
+ }
+
+ if (shim && *shim && !(shim_handle = dlopen( shim, RTLD_NOW )))
+ WARN( "unable to load overlay shim %s: %s\n", debugstr_a(shim), dlerror() );
+
+ if (!(list = strdup( inserts ))) return;
+ cursor = list;
+ while ((path = strsep( &cursor, ":" )))
+ {
+ if (!*path) continue;
+ if (!dlopen( path, RTLD_NOW )) WARN( "unable to load %s: %s\n", debugstr_a(path), dlerror() );
+ else TRACE( "Loaded %s\n", debugstr_a(path) );
+ }
+ free( list );
+
+ if (shim_handle && (install = (void (*)( void ))dlsym( shim_handle, "np_overlay_shim_install" )))
+ install();
+}
+#endif /* __APPLE__ */
+
+template< typename Params >
+static NTSTATUS steamclient_init( Params *params, bool wow64 )
+{
+ char path[PATH_MAX], resolved_path[PATH_MAX];
+ static void *steamclient;
+
+ g_tmppath = params->g_tmppath;
+
+ sync_env_var( "SteamAppId", params->steam_app_id_unset, params->steam_app_id );
+ sync_env_var( "IgnoreChildProcesses", params->ignore_child_processes_unset, params->ignore_child_processes );
+
+ if (steamclient) return 0;
+
+#ifdef __APPLE__
+ /* Get the overlay ready */
+ load_overlay_libraries();
+
+ if (getenv( "STEAM_COMPAT_CLIENT_INSTALL_PATH" ))
+ snprintf( path, PATH_MAX, "%s/steamclient.dylib", getenv( "STEAM_COMPAT_CLIENT_INSTALL_PATH" ) );
+ else
+ {
+ WARN( "Old Steam client, falling back to DYLD environment to locate native steamclient "
+ "library\n" );
+ strcpy( path, "steamclient.dylib" );
+ }
+#else /* __APPLE__ */
+#if defined(__x86_64__)
+#define STEAM_ARCH "64"
+#elif defined(__i386__)
+#define STEAM_ARCH "32"
+#elif defined(__aarch64__)
+#define STEAM_ARCH "arm64"
+#else
+#error Unknown target architecture
+#endif
+
+ snprintf( path, PATH_MAX, "%s/.steam/sdk" STEAM_ARCH "/steamclient.so", getenv( "HOME" ) );
+#undef STEAM_ARCH
+
+ if (realpath( path, resolved_path ))
+ {
+ strcpy( path, resolved_path );
+ path[PATH_MAX - 1] = 0;
+ }
+#endif /* __APPLE__ */
+
+ if (!(steamclient = dlopen( path, RTLD_NOW )))
+ {
+ ERR( "unable to load native steamclient library\n" );
+ return -1;
+ }
+
+#define LOAD_FUNC( x ) \
+ if (!(p_##x = (decltype(p_##x))dlsym( steamclient, #x ))) \
+ { \
+ ERR( "unable to load " #x "\n" ); \
+ return -1; \
+ }
+
+ LOAD_FUNC( CreateInterface );
+ LOAD_FUNC( Steam_BGetCallback );
+ LOAD_FUNC( Steam_GetAPICallResult );
+ LOAD_FUNC( Steam_FreeLastCallback );
+ LOAD_FUNC( Steam_ReleaseThreadLocalMemory );
+
+#define LOAD_FUNC_OPTIONAL( x ) \
+ p_##x = (decltype(p_##x))dlsym( steamclient, #x )
+
+ LOAD_FUNC_OPTIONAL( Steam_IsKnownInterface );
+ LOAD_FUNC_OPTIONAL( Steam_NotifyMissingInterface );
+
+ TRACE( "Loaded host steamclient from %s\n", debugstr_a(path) );
+
+ return 0;
+}
+
+namespace std
+{
+template<> struct hash< struct u_buffer >
+{
+ using argument_type = struct u_buffer;
+ using result_type = std::size_t;
+ result_type operator()( argument_type const& buf ) const { return buf.ptr; }
+};
+}
+
+static pthread_mutex_t buffer_cache_lock = PTHREAD_MUTEX_INITIALIZER;
+static std::unordered_map< struct u_buffer, void * > buffer_cache;
+
+template< typename Params >
+static NTSTATUS steamclient_get_unix_buffer( Params *params, bool wow64 )
+{
+ struct cache_entry *entry;
+ struct rb_entry *ptr;
+
+ pthread_mutex_lock( &buffer_cache_lock );
+ auto iter = buffer_cache.find( params->buf );
+ if (iter != buffer_cache.end()) params->ptr = iter->second;
+ else
+ {
+ memcpy( params->ptr, (char *)params->buf, params->buf.len );
+ buffer_cache[params->buf] = params->ptr;
+ }
+ pthread_mutex_unlock( &buffer_cache_lock );
+
+ return 0;
+}
+
+template< typename Params >
+static NTSTATUS steamclient_CreateInterface( Params *params, bool wow64 )
+{
+ params->_ret = p_CreateInterface( params->name, params->return_code );
+ return 0;
+}
+
+template< typename Params >
+static NTSTATUS steamclient_Steam_ReleaseThreadLocalMemory( Params *params, bool wow64 )
+{
+ p_Steam_ReleaseThreadLocalMemory( params->thread_exit );
+ return 0;
+}
+
+template< typename Params >
+static NTSTATUS steamclient_Steam_IsKnownInterface( Params *params, bool wow64 )
+{
+ params->_ret = p_Steam_IsKnownInterface ? p_Steam_IsKnownInterface( params->version ) : true;
+ return 0;
+}
+
+template< typename Params >
+static NTSTATUS steamclient_Steam_NotifyMissingInterface( Params *params, bool wow64 )
+{
+ if (p_Steam_NotifyMissingInterface) p_Steam_NotifyMissingInterface( params->pipe, params->version );
+ return 0;
+}
+
+#define IS_ABSOLUTE( x ) (*x == '/' || *x == '\\' || (*x && *(x + 1) == ':'))
+
+static void collapse_path( WCHAR *path, UINT mark )
+{
+ WCHAR *p, *next;
+
+ /* convert every / into a \ */
+ for (p = path; *p; p++) if (*p == '/') *p = '\\';
+
+ /* collapse duplicate backslashes */
+ next = path + std::max( 1u, mark );
+ for (p = next; *p; p++) if (*p != '\\' || next[-1] != '\\') *next++ = *p;
+ *next = 0;
+
+ p = path + mark;
+ while (*p)
+ {
+ if (*p == '.')
+ {
+ switch(p[1])
+ {
+ case '\\': /* .\ component */
+ next = p + 2;
+ memmove( p, next, (wcslen(next) + 1) * sizeof(WCHAR) );
+ continue;
+ case 0: /* final . */
+ if (p > path + mark) p--;
+ *p = 0;
+ continue;
+ case '.':
+ if (p[2] == '\\') /* ..\ component */
+ {
+ next = p + 3;
+ if (p > path + mark)
+ {
+ p--;
+ while (p > path + mark && p[-1] != '\\') p--;
+ }
+ memmove( p, next, (wcslen(next) + 1) * sizeof(WCHAR) );
+ continue;
+ }
+ else if (!p[2]) /* final .. */
+ {
+ if (p > path + mark)
+ {
+ p--;
+ while (p > path + mark && p[-1] != '\\') p--;
+ if (p > path + mark) p--;
+ }
+ *p = 0;
+ continue;
+ }
+ break;
+ }
+ }
+ /* skip to the next component */
+ while (*p && *p != '\\') p++;
+ if (*p == '\\')
+ {
+ /* remove last dot in previous dir name */
+ if (p > path + mark && p[-1] == '.') memmove( p-1, p, (wcslen(p) + 1) * sizeof(WCHAR) );
+ else p++;
+ }
+ }
+
+ /* remove trailing spaces and dots (yes, Windows really does that, don't ask) */
+ while (p > path + mark && (p[-1] == ' ' || p[-1] == '.')) p--;
+ *p = 0;
+}
+
+static char *get_unix_file_name( const WCHAR *path )
+{
+ NTSTATUS status;
+ ULONG size = 256;
+ char *buffer;
+
+ status = ntdll_get_unix_file_name( path, &buffer, FILE_OPEN_IF );
+
+ if (status && status != STATUS_NO_SUCH_FILE)
+ {
+ free( buffer );
+ return NULL;
+ }
+ return buffer;
+}
+
+static unsigned char hexdigit( WCHAR c )
+{
+ if (c >= '0' && c <= '9') return c - '0';
+ if (c >= 'a' && c <= 'f') return c - 'a' + 10;
+ if (c >= 'A' && c <= 'F') return c - 'A' + 10;
+ return 0xff;
+}
+
+static void url_unescape( WCHAR *s )
+{
+ unsigned int i, len;
+ unsigned char c, d1, d2;
+
+ len = wcslen( s );
+ if (len < 3) return;
+ for (i = 0; i < len - 3; ++i)
+ {
+ if (s[i] != '%') continue;
+ if ((d1 = hexdigit( s[i + 1] )) == 0xff || (d2 = hexdigit( s[i + 2] )) == 0xff)
+ {
+ ERR( "Invalid escape %s.\n", debugstr_wn( s, 3 ) );
+ continue;
+ }
+ s[i] = d1 * 0x10 + d2;
+ len -= 2;
+ memmove( &s[i + 1], &s[i + 3], (len - i) * sizeof(*s) );
+ }
+}
+
+char *steamclient_dos_to_unix_path( const char *src, int is_url )
+{
+ static const char file_prot[] = "file://";
+ char buffer[4096], *dst = buffer;
+ int file_part_len;
+ uint32_t len;
+
+ TRACE( "src %s, is_url %u\n", debugstr_a(src), is_url );
+
+ if (!src) return NULL;
+
+ *dst = 0;
+ if (!*src) goto done;
+
+ if (is_url)
+ {
+ if (strncmp( src, file_prot, 7 ) != 0)
+ {
+ strcpy( dst, src );
+ goto done;
+ }
+
+ src += 7;
+ memcpy( dst, file_prot, sizeof(file_prot) );
+ dst += 7;
+ }
+
+ if (IS_ABSOLUTE( src ))
+ {
+ /* absolute path, use wine conversion */
+ WCHAR srcW[PATH_MAX] = {'\\', '?', '?', '\\', 0};
+ char *unix_path = NULL;
+ const char *p;
+ uint32_t r;
+
+ if (is_url) while (*src == '/') ++src;
+ if (is_url && (p = strpbrk( src, "#?" ))) file_part_len = p - src;
+ else file_part_len = strlen( src );
+ r = ntdll_umbstowcs( src, file_part_len, srcW + 4, PATH_MAX - 4 - 1 );
+ if (r)
+ {
+ srcW[4 + file_part_len] = 0;
+ if (is_url) url_unescape( srcW + 4 );
+ collapse_path( srcW, 4 );
+ unix_path = get_unix_file_name( srcW );
+ }
+
+ if (!unix_path)
+ {
+ ERR( "Unable to convert DOS filename to unix: %s\n", src );
+ goto done;
+ }
+
+ lstrcpynA( dst, unix_path, sizeof(buffer) - (dst - buffer) );
+ free( unix_path );
+ if (is_url)
+ {
+ len = strlen( buffer ) + strlen( src ) - file_part_len;
+ if (len + 1 > sizeof(buffer))
+ {
+ ERR( "Buffer is too short.\n", src );
+ goto done;
+ }
+ strcat( dst, src + file_part_len );
+ }
+ }
+ else
+ {
+ /* relative path, just fix up backslashes */
+ const char *s;
+ char *d;
+
+ for (s = src, d = dst; *s; ++s, ++d)
+ {
+ if (*s == '\\') *d = '/';
+ else *d = *s;
+ }
+
+ *d = 0;
+ }
+
+done:
+ len = strlen( buffer ) + 1;
+ if (!(dst = (char *)malloc( len ))) return NULL;
+ memcpy( dst, buffer, len );
+
+ TRACE( "-> %s\n", debugstr_a(dst) );
+ return dst;
+}
+
+void steamclient_free_path( char *path )
+{
+ free( path );
+}
+
+const char **steamclient_dos_to_unix_path_array( const char **src )
+{
+ size_t len;
+ const char **s;
+ char **out, **o;
+ WCHAR scratch[PATH_MAX] = {'\\', '?', '?', '\\', 0};
+
+ TRACE( "src %p\n", src );
+
+ if (!src) return NULL;
+
+ len = sizeof(char *); /* NUL */
+ for (s = src; *s; ++s) len += sizeof(char *);
+
+ out = (char **)malloc( len );
+
+ for (s = src, o = out; *s; ++s, ++o)
+ {
+ TRACE( " src[%zu] %s\n", s - src, debugstr_a(*s) );
+ if (IS_ABSOLUTE( *s ))
+ {
+ ntdll_umbstowcs( *s, strlen( *s ) + 1, scratch + 4, PATH_MAX - 4 );
+ collapse_path( scratch, 4 );
+ *o = get_unix_file_name( scratch );
+ }
+ else
+ {
+ const char *r;
+ char *l;
+ *o = (char *)malloc( strlen( *s ) + 1 );
+ for (r = *s, l = *o; *r; ++l, ++r)
+ {
+ if (*r == '\\') *l = '/';
+ else *l = *r;
+ }
+ *l = 0;
+ }
+ TRACE( " -> %s\n", debugstr_a(*o) );
+ }
+
+ *o = NULL;
+
+ TRACE( " -> %p\n", out );
+ return (const char **)out;
+}
+
+const char **wow64_steamclient_dos_to_unix_path_array( ptr32< const char ** > src_array )
+{
+ ptr32< const char * > *ptr = src_array, *end = src_array;
+ const char **array, **ret;
+
+ while (*end) end++;
+ array = new const char *[end - ptr + 1];
+ for (end = ptr; *end; end++) array[end - ptr] = *end;
+
+ ret = steamclient_dos_to_unix_path_array( array );
+
+ delete array;
+ return ret;
+}
+
+void steamclient_free_path_array( const char **path_array )
+{
+ const char **path;
+ if (!path_array) return;
+ for (path = path_array; *path; path++) free( *(char **)path );
+ free( path_array );
+}
+
+/* Returns:
+ * - if successful, the number of bytes written to dst, including the NULL terminator;
+ * - 0 if failed;
+ * - PATH_MAX if insufficient output buffer (TODO: should be actual required length including NULL terminator). */
+unsigned int steamclient_unix_path_to_dos_path( bool api_result, const char *src, char *dst, uint32_t dst_bytes, int is_url )
+{
+ static const char file_prot[] = "file://";
+ uint32_t r = 0;
+ WCHAR *dosW;
+
+ TRACE( "api_result %u, src %s, dst %p, dst_bytes %u is_url %u\n", api_result, debugstr_a(src), dst, dst_bytes, is_url );
+
+ if (!src || !*src || !api_result || !dst || !dst_bytes)
+ {
+ if (dst && dst_bytes) *dst = 0;
+ return api_result ? PATH_MAX : 0;
+ }
+
+ if (is_url)
+ {
+ /* convert only file: URLs */
+ if (strncmp( src, file_prot, 7 ))
+ {
+ r = strlen( src ) + 1;
+ if (r > dst_bytes) *dst = 0;
+ else memmove( dst, src, r );
+ return r;
+ }
+ if (dst_bytes < sizeof(file_prot))
+ {
+ *dst = 0;
+ return PATH_MAX;
+ }
+ memmove( dst, src, 7 );
+ src += 7;
+ dst += 7;
+ dst_bytes -= 7;
+ }
+
+ ntdll_get_dos_file_name( src, &dosW, FILE_OPEN );
+ if (dosW) r = ntdll_wcstoumbs( dosW, wcslen( dosW ) + 1, dst, dst_bytes, FALSE );
+ else *dst = 0;
+ free( dosW );
+
+ if (!strncmp( dst, "\\??\\", 4 ))
+ {
+ memmove( dst, dst + 4, r - 4 );
+ r -= 4;
+ }
+
+ TRACE( "-> dst %s, r %u\n", debugstr_a(dst), r );
+ return r;
+}
+
+static const struct callback_def *find_first_callback_def_by_id( int id, bool wow64 )
+{
+ const struct callback_def *data;
+ unsigned int l, r, m;
+
+ if (wow64) r = wow64_callback_data_size;
+ else r = callback_data_size;
+ if (wow64) data = wow64_callback_data;
+ else data = callback_data;
+
+ l = 0;
+ while (l < r)
+ {
+ m = (l + r) /2;
+ if (data[m].id == id)
+ {
+ while (m && data[m - 1].id == id) --m;
+ return &data[m];
+ }
+ if (id < data[m].id) r = m;
+ else l = m + 1;
+ }
+ return NULL;
+}
+
+void *alloc_callback_wtou( int id, void *callback, int *callback_len, bool wow64 )
+{
+ const struct callback_def *c, *end, *best;
+
+ if (!(c = find_first_callback_def_by_id( id, wow64 ))) return callback;
+
+ if (wow64) end = wow64_callback_data + wow64_callback_data_size;
+ else end = callback_data + callback_data_size;
+
+ best = NULL;
+ while (c != end && c->id == id)
+ {
+ if (c->w_callback_len == *callback_len)
+ {
+ best = c;
+ break;
+ }
+ if (!best && *callback_len >= c->w_callback_len) best = c;
+ ++c;
+ }
+
+ if (!best)
+ {
+ ERR( "len %d is too small for callback %d, using default.\n", *callback_len, id );
+ best = find_first_callback_def_by_id( id, wow64 );
+ }
+ if (best->w_callback_len != *callback_len)
+ WARN( "Found len %d for id %d, len %d.\n", best->w_callback_len, id, *callback_len );
+ *callback_len = best->u_callback_len;
+ return malloc( *callback_len );
+}
+
+void convert_callback_utow( int id, void *u_callback, int u_callback_len, void *w_callback, int w_callback_len, bool wow64 )
+{
+ const struct callback_def *c, *end, *best;
+
+ if (!(c = find_first_callback_def_by_id( id, wow64 )))
+ {
+ memcpy( w_callback, u_callback, u_callback_len );
+ return;
+ }
+
+ if (wow64) end = wow64_callback_data + wow64_callback_data_size;
+ else end = callback_data + callback_data_size;
+
+ best = NULL;
+ while (c != end && c->id == id)
+ {
+ if (c->w_callback_len == w_callback_len && c->u_callback_len == u_callback_len)
+ {
+ best = c;
+ break;
+ }
+ if ((!best || best->w_callback_len > w_callback_len)
+ && c->u_callback_len == u_callback_len && c->w_callback_len <= w_callback_len)
+ best = c;
+ if (!best && c->u_callback_len == u_callback_len)
+ best = c;
+ ++c;
+ }
+ if (!best)
+ {
+ ERR( "Could not find id %d, u_callback_len %d, w_callback_len %d.\n", id, u_callback_len, w_callback_len );
+ best = find_first_callback_def_by_id( id, wow64 );
+ }
+
+ if (best->w_callback_len != w_callback_len || best->u_callback_len != u_callback_len)
+ WARN( "Found len %d, %d for id %d, len %d, %d.\n", best->w_callback_len, best->u_callback_len,
+ id, w_callback_len, u_callback_len );
+
+ if (best->conv_w_from_u) best->conv_w_from_u( w_callback, u_callback );
+ else memcpy( w_callback, u_callback, u_callback_len );
+}
+
+#if defined(__x86_64__) || defined(__aarch64__)
+#define STEAMCLIENT_UNIX_WOW64_FUNC( name ) \
+ NTSTATUS wow64_ ## name( void *args ) { return name( (struct wow64_ ## name ## _params *)args, true ); }
+#else
+#define STEAMCLIENT_UNIX_WOW64_FUNC( name )
+#endif
+
+#define STEAMCLIENT_UNIX_FUNC( name ) \
+ NTSTATUS name( void *args ) { return name( (struct name ## _params *)args, false ); } \
+ STEAMCLIENT_UNIX_WOW64_FUNC( name )
+
+STEAMCLIENT_UNIX_FUNC( steamclient_init )
+STEAMCLIENT_UNIX_FUNC( steamclient_init_registry )
+STEAMCLIENT_UNIX_FUNC( steamclient_next_callback )
+STEAMCLIENT_UNIX_FUNC( steamclient_get_unix_buffer )
+STEAMCLIENT_UNIX_FUNC( steamclient_CreateInterface )
+STEAMCLIENT_UNIX_FUNC( steamclient_Steam_GetAPICallResult )
+STEAMCLIENT_UNIX_FUNC( steamclient_Steam_BGetCallback )
+STEAMCLIENT_UNIX_FUNC( steamclient_callback_message_receive )
+STEAMCLIENT_UNIX_FUNC( steamclient_Steam_FreeLastCallback )
+STEAMCLIENT_UNIX_FUNC( steamclient_Steam_ReleaseThreadLocalMemory )
+STEAMCLIENT_UNIX_FUNC( steamclient_Steam_IsKnownInterface )
+STEAMCLIENT_UNIX_FUNC( steamclient_Steam_NotifyMissingInterface )
+
+#if defined(__x86_64__) || defined(__aarch64__)
+
+struct buf32
+{
+ uint32_t pos32;
+ char *pos;
+
+ buf32() : pos(g_tmppath), pos32( (uint32_t)(UINT_PTR)g_tmppath ) {}
+
+ template< typename T > void append_str( ptr32< T* >& dst, const char *src )
+ {
+ size_t len = strlen( src ) + 1;
+
+ if (g_tmppath + TEMP_PATH_BUFFER_LENGTH - pos < len) return;
+ memcpy( pos, src, len );
+ pos += len;
+
+ dst.value = pos32;
+ pos32 += len;
+ }
+
+ void append_path( ptr32< const char * >& dst, const char *src )
+ {
+ size_t len;
+
+ steamclient_unix_path_to_dos_path( 1, src, pos, g_tmppath + TEMP_PATH_BUFFER_LENGTH - pos, 1 );
+ len = strlen( pos ) + 1;
+ pos += len;
+
+ dst.value = pos32;
+ pos32 += len;
+ }
+};
+
+u64_CallbackMsg_t::operator w32_CallbackMsg_t() const
+{
+ w32_CallbackMsg_t ret;
+ ret.m_hSteamUser = this->m_hSteamUser;
+ ret.m_iCallback = this->m_iCallback;
+ /*ret.m_pubParam = this->m_pubParam;*/
+ ret.m_cubParam = this->m_cubParam;
+ return ret;
+}
+
+u64_HTML_ChangedTitle_t::operator w32_HTML_ChangedTitle_t() const
+{
+ w32_HTML_ChangedTitle_t ret;
+ struct buf32 buf;
+
+ ret.unBrowserHandle = this->unBrowserHandle;
+ buf.append_str( ret.pchTitle, this->pchTitle );
+ return ret;
+}
+
+u64_HTML_ComboNeedsPaint_t::operator w32_HTML_ComboNeedsPaint_t() const
+{
+ w32_HTML_ComboNeedsPaint_t ret;
+ struct buf32 buf;
+
+ ret.unBrowserHandle = this->unBrowserHandle;
+ buf.append_str( ret.pBGRA, this->pBGRA );
+ ret.unWide = this->unWide;
+ ret.unTall = this->unTall;
+ return ret;
+}
+
+u64_HTML_FileOpenDialog_t::operator w32_HTML_FileOpenDialog_t() const
+{
+ w32_HTML_FileOpenDialog_t ret;
+ struct buf32 buf;
+
+ ret.unBrowserHandle = this->unBrowserHandle;
+ buf.append_str( ret.pchTitle, this->pchTitle );
+ buf.append_path( ret.pchInitialFile, this->pchInitialFile );
+ return ret;
+}
+
+u64_HTML_FinishedRequest_t::operator w32_HTML_FinishedRequest_t() const
+{
+ w32_HTML_FinishedRequest_t ret;
+ struct buf32 buf;
+
+ ret.unBrowserHandle = this->unBrowserHandle;
+ buf.append_path( ret.pchURL, this->pchURL );
+ buf.append_str( ret.pchPageTitle, this->pchPageTitle );
+ return ret;
+}
+
+u64_HTML_JSAlert_t::operator w32_HTML_JSAlert_t() const
+{
+ w32_HTML_JSAlert_t ret;
+ struct buf32 buf;
+
+ ret.unBrowserHandle = this->unBrowserHandle;
+ buf.append_str( ret.pchMessage, this->pchMessage );
+ return ret;
+}
+
+u64_HTML_JSConfirm_t::operator w32_HTML_JSConfirm_t() const
+{
+ w32_HTML_JSConfirm_t ret;
+ struct buf32 buf;
+
+ ret.unBrowserHandle = this->unBrowserHandle;
+ buf.append_str( ret.pchMessage, this->pchMessage );
+ return ret;
+}
+
+u64_HTML_LinkAtPosition_t::operator w32_HTML_LinkAtPosition_t() const
+{
+ w32_HTML_LinkAtPosition_t ret;
+ struct buf32 buf;
+
+ ret.unBrowserHandle = this->unBrowserHandle;
+ ret.x = this->x;
+ ret.y = this->y;
+ buf.append_path( ret.pchURL, this->pchURL );
+ ret.bInput = this->bInput;
+ ret.bLiveLink = this->bLiveLink;
+ return ret;
+}
+
+u64_HTML_NeedsPaint_t::operator w32_HTML_NeedsPaint_t() const
+{
+ w32_HTML_NeedsPaint_t ret;
+ struct buf32 buf;
+
+ ret.unBrowserHandle = this->unBrowserHandle;
+ buf.append_str( ret.pBGRA, this->pBGRA );
+ ret.unWide = this->unWide;
+ ret.unTall = this->unTall;
+ ret.unUpdateX = this->unUpdateX;
+ ret.unUpdateY = this->unUpdateY;
+ ret.unUpdateWide = this->unUpdateWide;
+ ret.unUpdateTall = this->unUpdateTall;
+ ret.unScrollX = this->unScrollX;
+ ret.unScrollY = this->unScrollY;
+ ret.flPageScale = this->flPageScale;
+ ret.unPageSerial = this->unPageSerial;
+ return ret;
+}
+
+u64_HTML_NewWindow_t_132x::operator w32_HTML_NewWindow_t_132x() const
+{
+ w32_HTML_NewWindow_t_132x ret;
+ struct buf32 buf;
+
+ ret.unBrowserHandle = this->unBrowserHandle;
+ buf.append_path( ret.pchURL, this->pchURL );
+ ret.unX = this->unX;
+ ret.unY = this->unY;
+ ret.unWide = this->unWide;
+ ret.unTall = this->unTall;
+ ret.unNewWindow_BrowserHandle_IGNORE = this->unNewWindow_BrowserHandle_IGNORE;
+ return ret;
+}
+
+u64_HTML_NewWindow_t_130x::operator w32_HTML_NewWindow_t_130x() const
+{
+ w32_HTML_NewWindow_t_130x ret;
+ struct buf32 buf;
+
+ ret.unBrowserHandle = this->unBrowserHandle;
+ buf.append_path( ret.pchURL, this->pchURL );
+ ret.unX = this->unX;
+ ret.unY = this->unY;
+ ret.unWide = this->unWide;
+ ret.unTall = this->unTall;
+ return ret;
+}
+
+u64_HTML_OpenLinkInNewTab_t::operator w32_HTML_OpenLinkInNewTab_t() const
+{
+ w32_HTML_OpenLinkInNewTab_t ret;
+ struct buf32 buf;
+
+ ret.unBrowserHandle = this->unBrowserHandle;
+ buf.append_path( ret.pchURL, this->pchURL );
+ return ret;
+}
+
+u64_HTML_ShowToolTip_t::operator w32_HTML_ShowToolTip_t() const
+{
+ w32_HTML_ShowToolTip_t ret;
+ struct buf32 buf;
+
+ ret.unBrowserHandle = this->unBrowserHandle;
+ buf.append_str( ret.pchMsg, this->pchMsg );
+ return ret;
+}
+
+u64_HTML_StartRequest_t::operator w32_HTML_StartRequest_t() const
+{
+ w32_HTML_StartRequest_t ret;
+ struct buf32 buf;
+
+ ret.unBrowserHandle = this->unBrowserHandle;
+ buf.append_path( ret.pchURL, this->pchURL );
+ buf.append_str( ret.pchTarget, this->pchTarget );
+ buf.append_str( ret.pchPostData, this->pchPostData );
+ ret.bIsRedirect = this->bIsRedirect;
+ return ret;
+}
+
+u64_HTML_StatusText_t::operator w32_HTML_StatusText_t() const
+{
+ w32_HTML_StatusText_t ret;
+ struct buf32 buf;
+
+ ret.unBrowserHandle = this->unBrowserHandle;
+ buf.append_str( ret.pchMsg, this->pchMsg );
+ return ret;
+}
+
+u64_HTML_URLChanged_t::operator w32_HTML_URLChanged_t() const
+{
+ w32_HTML_URLChanged_t ret;
+ struct buf32 buf;
+
+ ret.unBrowserHandle = this->unBrowserHandle;
+ buf.append_path( ret.pchURL, this->pchURL );
+ buf.append_str( ret.pchPostData, this->pchPostData );
+ ret.bIsRedirect = this->bIsRedirect;
+ buf.append_str( ret.pchPageTitle, this->pchPageTitle );
+ ret.bNewNavigation = this->bNewNavigation;
+ return ret;
+}
+
+u64_HTML_UpdateToolTip_t::operator w32_HTML_UpdateToolTip_t() const
+{
+ w32_HTML_UpdateToolTip_t ret;
+ struct buf32 buf;
+
+ ret.unBrowserHandle = this->unBrowserHandle;
+ buf.append_str( ret.pchMsg, this->pchMsg );
+ return ret;
+}
+
+u64_RemoteStorageDownloadUGCResult_t_123::operator w32_RemoteStorageDownloadUGCResult_t_123() const
+{
+ w32_RemoteStorageDownloadUGCResult_t_123 ret;
+ ret.m_eResult = this->m_eResult;
+ ret.m_hFile = this->m_hFile;
+ ret.m_nAppID = this->m_nAppID;
+ ret.m_nSizeInBytes = this->m_nSizeInBytes;
+ ret.m_pchFileName = this->m_pchFileName;
+ ret.m_ulSteamIDOwner = this->m_ulSteamIDOwner;
+ return ret;
+}
+
+u64_RemoteStorageDownloadUGCResult_t_116x::operator w32_RemoteStorageDownloadUGCResult_t_116x() const
+{
+ w32_RemoteStorageDownloadUGCResult_t_116x ret;
+ ret.m_eResult = this->m_eResult;
+ ret.m_hFile = this->m_hFile;
+ ret.m_nAppID = this->m_nAppID;
+ ret.m_nSizeInBytes = this->m_nSizeInBytes;
+ ret.m_pchFileName = this->m_pchFileName;
+ ret.m_ulSteamIDOwner = this->m_ulSteamIDOwner;
+ return ret;
+}
+
+u64_RemoteStorageDownloadUGCResult_t_111x::operator w32_RemoteStorageDownloadUGCResult_t_111x() const
+{
+ w32_RemoteStorageDownloadUGCResult_t_111x ret;
+ struct buf32 buf;
+
+ ret.m_eResult = this->m_eResult;
+ ret.m_hFile = this->m_hFile;
+ ret.m_nAppID = this->m_nAppID;
+ ret.m_nSizeInBytes = this->m_nSizeInBytes;
+ buf.append_str( ret.m_pchFileName, this->m_pchFileName );
+ ret.m_ulSteamIDOwner = this->m_ulSteamIDOwner;
+ return ret;
+}
+
+w64_SteamParamStringArray_t::w64_SteamParamStringArray_t( w32_SteamParamStringArray_t const& w32 )
+ : m_nNumStrings(w32.m_nNumStrings)
+{
+ uint32_t count = m_nNumStrings;
+ m_ppStrings = new const char *[count];
+ while (count--) m_ppStrings[count] = w32.m_ppStrings[count];
+}
+
+w64_SteamParamStringArray_t::w64_SteamParamStringArray_t( w64_SteamParamStringArray_t const& w64 )
+ : m_nNumStrings(w64.m_nNumStrings)
+{
+ m_ppStrings = new const char *[m_nNumStrings];
+ memcpy( m_ppStrings, w64.m_ppStrings, sizeof(*m_ppStrings) * m_nNumStrings );
+}
+
+w64_SteamParamStringArray_t::~w64_SteamParamStringArray_t()
+{
+ delete[] m_ppStrings;
+}
+#endif
diff --git a/ntdll-patch/.gitignore b/ntdll-patch/.gitignore
new file mode 100644
index 0000000..2cbf855
--- /dev/null
+++ b/ntdll-patch/.gitignore
@@ -0,0 +1,4 @@
+*.o
+*.elf
+*.bin
+build/
diff --git a/ntdll-patch/apply.py b/ntdll-patch/apply.py
new file mode 100644
index 0000000..f2d526d
--- /dev/null
+++ b/ntdll-patch/apply.py
@@ -0,0 +1,75 @@
+#!/usr/bin/env python3
+# Development tool. The real patcher lives in the app (NtdllPatcher.swift).
+# This is the original Python version, kept for validating patches against
+# new CrossOver builds.
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from resolve import PE, resolve, shell_vars # noqa: E402
+
+DEFAULT_PAYLOAD = {0x8664: "detour2.bin", 0x14c: "detour32.bin", 0xaa64: "detour64-fex.bin"}
+
+
+def main():
+ if len(sys.argv) < 2:
+ raise SystemExit(f"usage: {sys.argv[0]} <src ntdll.dll> [dst] [payload.bin]")
+ src = sys.argv[1]
+ dst = sys.argv[2] if len(sys.argv) > 2 else "ntdll.dll.patched"
+ here = os.path.dirname(os.path.abspath(__file__))
+
+ r = resolve(src)
+ v = shell_vars(src)
+ if r['machine'] not in DEFAULT_PAYLOAD:
+ raise SystemExit(f"{src}: machine {r['machine']:#x} carries no detour")
+ payload_path = sys.argv[3] if len(sys.argv) > 3 \
+ else os.path.join(here, DEFAULT_PAYLOAD[r['machine']])
+ detour = open(payload_path, "rb").read()
+ payload_rva = int(v['NP_PAYLOAD_RVA'], 16)
+ fill = r['fill']
+ sites = r.get('sites') or [r]
+
+ pe = PE(src)
+ d = bytearray(pe.d)
+ cave_off = pe.off(payload_rva)
+
+ if any(b != fill for b in d[cave_off:cave_off + len(detour)]):
+ raise SystemExit(f"cave at {cave_off:#x} is not {fill:#02x} pad for {len(detour)} bytes")
+ d[cave_off:cave_off + len(detour)] = detour
+
+ hooks = []
+ for site in sites:
+ bm_off = pe.off(site['hookRVA'])
+ stolen = bytes.fromhex(site['stolen'])
+ if d[bm_off:bm_off + len(stolen)] != stolen:
+ raise SystemExit(f"unexpected hook site at {site['hookRVA']:#x}: "
+ f"{d[bm_off:bm_off + len(stolen)].hex()}")
+ if r['machine'] == 0xaa64:
+ rel = payload_rva - site['hookRVA']
+ if rel % 4 or not -(1 << 27) <= rel < (1 << 27):
+ raise SystemExit(f"cave is {rel:#x} from the hook, out of bl range")
+ patch = (0x94000000 | ((rel >> 2) & 0x03ffffff)).to_bytes(4, 'little')
+ else:
+ # E9 rel32 to the shim at the payload start
+ rel = payload_rva - (site['hookRVA'] + 5)
+ patch = b"\xE9" + rel.to_bytes(4, 'little', signed=True) + b"\xCC" * (len(stolen) - 5)
+ assert len(patch) == len(stolen)
+ d[bm_off:bm_off + len(patch)] = patch
+ hooks.append((site, bm_off, rel, stolen))
+
+ # patch in memory and write once, like a pro
+ tmp = dst + ".tmp"
+ with open(tmp, "wb") as f:
+ f.write(d)
+ os.replace(tmp, dst)
+
+ print(f"patched {src} -> {dst}")
+ print(f" payload {os.path.basename(payload_path)}, {len(detour)} bytes at rva "
+ f"{payload_rva:#x} (off {cave_off:#x}), cave pad {fill:#02x}")
+ for site, bm_off, rel, stolen in hooks:
+ print(f" hook {site['hookRVA']:#x} (off {bm_off:#x}) branch rel {rel:#x} to cave "
+ f"entry, stolen {stolen.hex()}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/ntdll-patch/build-ntdll.sh b/ntdll-patch/build-ntdll.sh
new file mode 100755
index 0000000..4e3b90b
--- /dev/null
+++ b/ntdll-patch/build-ntdll.sh
@@ -0,0 +1,131 @@
+#!/bin/sh
+# Script to apply patches and throw them into the CrossOver setup, testing tool
+#
+# ./build-ntdll.sh build and verify
+# ./build-ntdll.sh --install also copy into the bridge
+#
+set -eu
+
+here="$(cd "$(dirname "$0")" && pwd)"
+cd "$here"
+
+CX_ROOT="${CX_ROOT:-/Applications/CrossOver Preview.app/Contents/SharedSupport/CrossOver}"
+BRIDGE_DIR="${BRIDGE_DIR:-$HOME/Library/Application Support/notproton/bridge}"
+OUT="${OUT:-$here/build}"
+
+ROSETTA_CLEAN_X86_64=04c7200b6645decb7c2d1ba6b0195abc9af83257072558d11aa72cc067ac3377
+ROSETTA_CLEAN_I386=94cc7c14c1e9dcf58ef501015c115f8405c73b2a65cefe31faa5d9e47f36e58b
+ROSETTA_PATCHED_X86_64=b21f4bace5a7a0cfef0f74cef9b27561f6eb3ad38daf76f36b186ca0677c2b2c
+ROSETTA_PATCHED_I386=25bfde1f50ee96485763968ef10b9d9ad35e38214232f17ebdc009b098af44a0
+
+FEX_CLEAN_I386=09474795d6f306163cebab6429819999fcff50e07dbc4b067a90ec4f74a3a7d7
+FEX_CLEAN_AARCH64=7823d71fbce6c9947163bf8b96beb299eabb02878245bcaf6759f2a22e81f071
+FEX_PATCHED_I386=e799ea02418294588ee353a90b967358be316a3044ff9515b28aa1ce07e63981
+FEX_PATCHED_AARCH64=560939a0f6e58314fc9d79fe6f839dce2b181f829ae58dca195fa142fcf40f39
+
+install=0
+[ "${1:-}" = "--install" ] && install=1
+
+die() { echo "error: $*" >&2; exit 1; }
+sha() { shasum -a 256 "$1" | cut -d' ' -f1; }
+
+command -v python3 >/dev/null || die "python3 not found"
+
+OBJCOPY=/opt/homebrew/opt/llvm/bin/llvm-objcopy
+
+flavor_of() {
+ for cand in "$CX_ROOT/lib/wine/aarch64-windows/ntdll.dll.notproton-orig" \
+ "$CX_ROOT/lib/wine/aarch64-windows/ntdll.dll"; do
+ [ -f "$cand" ] || continue
+ if [ "$(sha "$cand")" = "$FEX_CLEAN_AARCH64" ]; then echo fex; return 0; fi
+ done
+ for cand in "$CX_ROOT/lib/wine/x86_64-windows/ntdll.dll.notproton-orig" \
+ "$CX_ROOT/lib/wine/x86_64-windows/ntdll.dll"; do
+ [ -f "$cand" ] || continue
+ if [ "$(sha "$cand")" = "$ROSETTA_CLEAN_X86_64" ]; then echo rosetta; return 0; fi
+ done
+ die "no ntdll under $CX_ROOT/lib/wine matches a pinned build
+ pass FLAVOR=rosetta or FLAVOR=fex to choose the pins anyway"
+}
+
+if [ -z "${FLAVOR:-}" ]; then
+ FLAVOR="$(flavor_of)"
+fi
+
+case "$FLAVOR" in
+ rosetta) tools="x86_64-w64-mingw32-gcc i686-w64-mingw32-gcc" ;;
+ fex) tools="i686-w64-mingw32-gcc clang ld.lld" ;;
+ *) die "unknown flavor $FLAVOR, expected rosetta or fex" ;;
+esac
+
+for t in $tools; do
+ command -v "$t" >/dev/null || die "$t not found (brew install mingw-w64 llvm)"
+done
+
+if [ "$FLAVOR" = fex ] && [ ! -x "$OBJCOPY" ]; then
+ die "$OBJCOPY not found (brew install llvm)"
+fi
+
+echo "==> $FLAVOR flavor, reading $CX_ROOT/lib/wine"
+
+clean_for() {
+ arch="$1"; want="$2"
+ for cand in "$CX_ROOT/lib/wine/$arch/ntdll.dll.notproton-orig" \
+ "$CX_ROOT/lib/wine/$arch/ntdll.dll"; do
+ [ -f "$cand" ] || continue
+ [ "$(sha "$cand")" = "$want" ] || continue
+ echo "$cand"
+ return 0
+ done
+ die "no clean $arch ntdll.dll found under $CX_ROOT/lib/wine/$arch
+ expected sha256 $want
+ extract a clean ntdll.dll from the CrossOver installer and point CX_ROOT at it"
+}
+
+mkdir -p "$OUT"
+
+patch_one() {
+ arch="$1"; builder="$2"; variant="$3"; payload="$4"; want_in="$5"; want_out="$6"
+ src="$(clean_for "$arch" "$want_in")"
+ dst="$OUT/$arch/ntdll.dll"
+ mkdir -p "$OUT/$arch"
+ echo "==> building $arch payload from ${src##*/}"
+ ./"$builder" "$src" "$variant" >/dev/null
+ echo "==> patching $arch"
+ python3 apply.py "$src" "$dst" "$payload" >/dev/null
+ got="$(sha "$dst")"
+ [ "$got" = "$want_out" ] || die "$arch output hash $got, expected $want_out
+ the patch no longer reproduces the known-good binary, do not ship this"
+ echo "==> built $arch ntdll.dll $(stat -f %z "$dst") bytes $(echo "$got" | cut -c1-16)"
+}
+
+case "$FLAVOR" in
+ rosetta)
+ ARCHES="x86_64-windows i386-windows"
+ patch_one x86_64-windows build.sh rosetta detour2.bin \
+ "$ROSETTA_CLEAN_X86_64" "$ROSETTA_PATCHED_X86_64"
+ patch_one i386-windows build32.sh rosetta detour32.bin \
+ "$ROSETTA_CLEAN_I386" "$ROSETTA_PATCHED_I386"
+ ;;
+ fex)
+ # The 64 bit guest is served by the arm64 ntdll under FEX
+ ARCHES="i386-windows aarch64-windows"
+ patch_one i386-windows build32.sh fex detour32-fex.bin \
+ "$FEX_CLEAN_I386" "$FEX_PATCHED_I386"
+ patch_one aarch64-windows build64.sh fex detour64-fex.bin \
+ "$FEX_CLEAN_AARCH64" "$FEX_PATCHED_AARCH64"
+ ;;
+esac
+
+if [ "$install" -eq 0 ]; then
+ echo "==> not installing, pass --install to stage into the bridge"
+ exit 0
+fi
+
+for arch in $ARCHES; do
+ d="$BRIDGE_DIR/wine/$arch"
+ mkdir -p "$d"
+ cp "$OUT/$arch/ntdll.dll" "$d/ntdll.dll"
+ echo "==> installed $arch $(sha "$d/ntdll.dll" | cut -c1-16) $d/ntdll.dll"
+done
+echo "==> RUN_SCRIPT copies these into the CrossOver tree on the next Steam launch"
diff --git a/ntdll-patch/build.sh b/ntdll-patch/build.sh
new file mode 100755
index 0000000..cfef057
--- /dev/null
+++ b/ntdll-patch/build.sh
@@ -0,0 +1,55 @@
+#!/bin/sh
+# My old script, used to kick off a set of ntdll patches
+set -eu
+
+here="$(cd "$(dirname "$0")" && pwd)"
+cd "$here"
+
+ntdll="${1:?usage: build.sh <target ntdll.dll> [variant]}"
+variant="${2:-rosetta}"
+[ "$variant" = rosetta ] && out=detour2.bin || out="detour2-$variant.bin"
+
+eval "$(python3 resolve.py --sh "$ntdll")"
+[ "$NP_MACHINE" = 0x8664 ] || { echo "$ntdll is machine $NP_MACHINE, not x86_64" >&2; exit 1; }
+
+CC=x86_64-w64-mingw32-gcc
+LD=x86_64-w64-mingw32-ld
+OBJCOPY=x86_64-w64-mingw32-objcopy
+
+CFLAGS="-Os -fno-asynchronous-unwind-tables -ffreestanding -fno-stack-protector"
+
+# shellcheck disable=SC2086 # CFLAGS carries several flags and has to split
+"$CC" -c $CFLAGS detour.c -o detour_c.o
+"$CC" -c -x assembler-with-cpp shim.S -o shim.o \
+ "-DWM_REG=$NP_WM" "-DSCRATCH_REG=$NP_SCRATCH" "-DLOAD_PATH_SLOT=$NP_LOAD_PATH" \
+ "-DSTOLEN_BYTES=$NP_STOLEN_BYTES"
+"$LD" -T link.ld shim.o detour_c.o -o detour_linked.elf \
+ --defsym "CAVE_VA=$NP_PAYLOAD_VA" \
+ --defsym "BM_RESUME=$NP_RESUME_VA" \
+ --defsym "LDR_GETDLLHANDLE=$NP_LDR_GET_DLL_HANDLE" \
+ --defsym "LDR_LOADDLL=$NP_LDR_LOAD_DLL" \
+ --defsym "NT_PROTECT=$NP_NT_PROTECT_VIRTUAL_MEMORY"
+"$OBJCOPY" -O binary -j .cave detour_linked.elf "$out"
+
+got="$(shasum -a 256 "$out" | cut -d' ' -f1)"
+if [ -n "${NP_PAYLOAD_SHA256:-}" ]; then
+ if [ "$got" != "$NP_PAYLOAD_SHA256" ]; then
+ echo "error: $out is $got, pinned $NP_PAYLOAD_SHA256" >&2
+ echo " the detour sources no longer compile to the payload this build was verified with" >&2
+ exit 1
+ fi
+else
+ echo "note: $NP_SHA256 carries no payload pin, $out is $got"
+fi
+
+echo "built $out ($(wc -c < "$out") bytes) for $NP_ARCH $NP_SHA256"
+echo " cave $NP_CAVE_RVA fill $NP_FILL, payload at $NP_PAYLOAD_RVA, room $NP_CAVE_ROOM"
+echo " hook $NP_HOOK_RVA stolen $NP_STOLEN, wm $NP_WM, load_path rsp+$NP_LOAD_PATH"
+
+app_copy="../app/Sources/NotProtonApp/Resources/$out"
+if [ -f "$app_copy" ] && ! cmp -s "$out" "$app_copy"; then
+ echo "warning: $app_copy is stale" >&2
+ echo " cp $out $app_copy" >&2
+ echo " then update payloadSHA256 for $variant x86_64Windows in NtdllPatcher.swift to" >&2
+ echo " $(shasum -a 256 "$out" | cut -d' ' -f1)" >&2
+fi
diff --git a/ntdll-patch/build32.sh b/ntdll-patch/build32.sh
new file mode 100755
index 0000000..dde8717
--- /dev/null
+++ b/ntdll-patch/build32.sh
@@ -0,0 +1,65 @@
+#!/bin/sh
+# i386 ntdll patch
+set -eu
+
+here="$(cd "$(dirname "$0")" && pwd)"
+cd "$here"
+
+ntdll="${1:?usage: build32.sh <target ntdll.dll> [variant]}"
+variant="${2:-rosetta}"
+[ "$variant" = rosetta ] && out=detour32.bin || out="detour32-$variant.bin"
+
+eval "$(python3 resolve.py --sh "$ntdll")"
+[ "$NP_MACHINE" = 0x14c ] || { echo "$ntdll is machine $NP_MACHINE, not i386" >&2; exit 1; }
+
+CC=i686-w64-mingw32-gcc
+LD=i686-w64-mingw32-ld
+OBJCOPY=i686-w64-mingw32-objcopy
+
+CFLAGS="-Os -fno-asynchronous-unwind-tables -ffreestanding -fno-stack-protector \
+-fno-ident -mno-stack-arg-probe"
+
+# shellcheck disable=SC2086 # CFLAGS carries several flags and has to split
+"$CC" -c $CFLAGS detour32.c -o detour32_c.o \
+ "-DFLAGS_SLOT=$NP_FLAGS_SLOT" "-DLOAD_PATH_SLOT=$NP_LOAD_PATH"
+"$CC" -c -x assembler-with-cpp shim32.S -o shim32.o \
+ "-DWM_REG=$NP_WM" "-DSTOLEN_HEAD_BYTES=$NP_STOLEN_HEAD_BYTES" \
+ "-DSTOLE_BRANCH=${NP_STOLE_BRANCH:-0}"
+"$LD" -T link32.ld shim32.o detour32_c.o -o detour32_linked.elf \
+ --defsym "CAVE_VA=$NP_PAYLOAD_VA" \
+ --defsym "BM_RESUME=$NP_RESUME_VA" \
+ --defsym "BM_SKIP=$NP_SKIP_VA" \
+ --defsym "LDR_GETDLLHANDLE=$NP_LDR_GET_DLL_HANDLE" \
+ --defsym "LDR_LOADDLL=$NP_LDR_LOAD_DLL" \
+ --defsym "NT_PROTECT=$NP_NT_PROTECT_VIRTUAL_MEMORY" \
+ --defsym "NT_OPENFILE=$NP_NT_OPEN_FILE" \
+ --defsym "NT_READFILE=$NP_NT_READ_FILE" \
+ --defsym "NT_CLOSE=$NP_NT_CLOSE"
+"$OBJCOPY" -O binary -j .cave detour32_linked.elf "$out"
+
+got="$(shasum -a 256 "$out" | cut -d' ' -f1)"
+if [ -n "${NP_PAYLOAD_SHA256:-}" ]; then
+ if [ "$got" != "$NP_PAYLOAD_SHA256" ]; then
+ echo "error: $out is $got, pinned $NP_PAYLOAD_SHA256" >&2
+ echo " the detour sources no longer compile to the payload this build was verified with" >&2
+ exit 1
+ fi
+else
+ echo "note: $NP_SHA256 carries no payload pin, $out is $got"
+fi
+
+echo "built $out ($(wc -c < "$out") bytes) for $NP_ARCH $NP_SHA256"
+echo " cave $NP_CAVE_RVA fill $NP_FILL, payload at $NP_PAYLOAD_RVA, room $NP_CAVE_ROOM"
+echo " hook $NP_HOOK_RVA stolen $NP_STOLEN, wm $NP_WM, load_path ebp$NP_LOAD_PATH"
+
+app_copy=../app/Sources/NotProtonApp/Resources/$out
+if [ -f "$app_copy" ] && ! cmp -s "$out" "$app_copy"; then
+ echo "warning: $app_copy is stale" >&2
+ echo " cp $out $app_copy" >&2
+ echo " then update payloadSHA256 for i386Windows in NtdllPatcher.swift to" >&2
+ echo " $(shasum -a 256 "$out" | cut -d' ' -f1)" >&2
+fi
+
+if [ "${APPLY:-}" != "" ]; then
+ python3 apply.py "$ntdll" "$APPLY" "$out"
+fi
diff --git a/ntdll-patch/build64.sh b/ntdll-patch/build64.sh
new file mode 100755
index 0000000..e9b1dfa
--- /dev/null
+++ b/ntdll-patch/build64.sh
@@ -0,0 +1,71 @@
+#!/bin/sh
+# aarch64 ntdll
+set -eu
+
+here="$(cd "$(dirname "$0")" && pwd)"
+cd "$here"
+
+ntdll="${1:?usage: build64.sh <target ntdll.dll> [variant]}"
+variant="${2:-fex}"
+out="detour64-$variant.bin"
+
+eval "$(python3 resolve.py --sh "$ntdll")"
+[ "$NP_MACHINE" = 0xaa64 ] || { echo "$ntdll is machine $NP_MACHINE, not aarch64" >&2; exit 1; }
+
+[ "${NP_SITES:-0}" = 2 ] || { echo "$ntdll has ${NP_SITES:-0} hooks, shim64.S serves two" >&2; exit 1; }
+
+for slot in "$NP_LOAD_PATH_1" "$NP_LOAD_PATH_2"; do
+ if [ "$((slot))" -lt -256 ] || [ "$((slot))" -gt 255 ]; then
+ echo "load_path slot $slot is out of ldur range, shim64.S needs a wider load" >&2
+ exit 1
+ fi
+done
+
+CC=clang
+TARGET=aarch64-unknown-none-elf
+LD=/opt/homebrew/bin/ld.lld
+OBJCOPY=/opt/homebrew/opt/llvm/bin/llvm-objcopy
+
+"$CC" -target "$TARGET" -c -Os -ffreestanding -fno-stack-protector \
+ -fno-asynchronous-unwind-tables -mgeneral-regs-only -ffixed-x18 detour.c -o detour64_c.o
+"$CC" -target "$TARGET" -c -x assembler-with-cpp shim64.S -o shim64.o \
+ "-DLOAD_PATH_1=$NP_LOAD_PATH_1" "-DLOAD_PATH_2=$NP_LOAD_PATH_2"
+
+"$LD" -T link64.ld -e shim_entry64 shim64.o detour64_c.o -o detour64_linked.elf \
+ "--defsym=CAVE_VA=$NP_PAYLOAD_VA" \
+ "--defsym=BM_RESUME_1=$NP_RESUME_VA_1" \
+ "--defsym=LDR_GETDLLHANDLE=$NP_LDR_GET_DLL_HANDLE" \
+ "--defsym=LDR_LOADDLL=$NP_LDR_LOAD_DLL" \
+ "--defsym=NT_PROTECT=$NP_NT_PROTECT_VIRTUAL_MEMORY"
+"$OBJCOPY" -O binary -j .cave detour64_linked.elf "$out"
+
+got="$(shasum -a 256 "$out" | cut -d' ' -f1)"
+if [ -n "${NP_PAYLOAD_SHA256:-}" ]; then
+ if [ "$got" != "$NP_PAYLOAD_SHA256" ]; then
+ echo "error: $out is $got, pinned $NP_PAYLOAD_SHA256" >&2
+ echo " the detour sources no longer compile to the payload this build was verified with" >&2
+ exit 1
+ fi
+else
+ echo "note: $NP_SHA256 carries no payload pin, $out is $got"
+fi
+
+size=$(wc -c < "$out")
+echo "built $out ($size bytes) for $NP_ARCH $NP_SHA256"
+echo " cave $NP_CAVE_RVA fill $NP_FILL, payload at $NP_PAYLOAD_RVA, room $NP_CAVE_ROOM"
+echo " hook 1 $NP_HOOK_RVA_1 resume $NP_RESUME_VA_1, load_path x29$NP_LOAD_PATH_1"
+echo " hook 2 $NP_HOOK_RVA_2 resume $NP_RESUME_VA_2, load_path x29$NP_LOAD_PATH_2"
+
+[ "$size" -le "$NP_CAVE_ROOM" ] || { echo "payload does not fit the cave" >&2; exit 1; }
+
+if [ -n "${APPLY:-}" ]; then
+ python3 apply.py "$ntdll" "$APPLY" "$out"
+fi
+
+app_copy="../app/Sources/NotProtonApp/Resources/$out"
+if [ -f "$app_copy" ] && ! cmp -s "$out" "$app_copy"; then
+ echo "warning: $app_copy is stale" >&2
+ echo " cp $out $app_copy" >&2
+ echo " then update payloadSHA256 for $variant aarch64Windows in NtdllPatcher.swift to" >&2
+ echo " $(shasum -a 256 "$out" | cut -d' ' -f1)" >&2
+fi
diff --git a/ntdll-patch/detour.c b/ntdll-patch/detour.c
new file mode 100644
index 0000000..6c75831
--- /dev/null
+++ b/ntdll-patch/detour.c
@@ -0,0 +1,174 @@
+// Clever detours
+
+typedef unsigned long long u64;
+typedef unsigned int u32;
+typedef unsigned short u16;
+typedef unsigned char u8;
+
+typedef u32 (*ldr_getdllhandle_t)(void *path, void *unused, void *name_us, void **out);
+typedef u32 (*ldr_loaddll_t)(void *path, void *flags, void *name_us, void **out);
+typedef u32 (*nt_protect_t)(void *proc, void **base, u64 *size, u32 newprot, u32 *oldprot);
+
+struct ctx
+{
+ ldr_getdllhandle_t get_dll_handle;
+ ldr_loaddll_t load_dll;
+ nt_protect_t protect;
+};
+
+// PE image structures, minimal subset needed to walk export tables
+struct dos_header { u16 e_magic; u8 pad[58]; u32 e_lfanew; };
+struct data_dir { u32 rva; u32 size; };
+struct opt_hdr64 { u16 magic; // 0
+ u8 pad0[14]; // 2
+ u32 entry_point; // 16
+ u8 pad1[36]; // 20
+ u32 size_of_image; // 56
+ u8 pad2[52]; // 60
+ struct data_dir dir[16]; };// 112
+struct nt_headers { u32 sig; u8 file_hdr[20]; struct opt_hdr64 opt; };
+struct export_dir { u32 flags; u32 stamp; u16 maj; u16 min; u32 name;
+ u32 base; u32 nfuncs; u32 nnames;
+ u32 addr_funcs; u32 addr_names; u32 addr_ords; };
+
+#define LDR_DONT_CALL_DLLMAIN 0x20000000
+
+// WINE_MODREF, x86_64 layout.
+#define WM_DLLBASE(wm) (*(void **)((u8 *)(wm) + 0x30))
+#define WM_FLAGS(wm) ( (u32 *)((u8 *)(wm) + 0x68))
+
+struct us { u16 len; u16 max; u32 pad; void *buf; };
+
+static const u16 name_lsteam[] = {'l','s','t','e','a','m','c','l','i','e','n','t','.','d','l','l',0};
+
+static void *resolve_lsteam(struct ctx *c, void *load_path)
+{
+ struct us u;
+ void *h = 0;
+ u.len = 32; /* "lsteamclient.dll" = 16 wchars */
+ u.max = 34;
+ u.pad = 0;
+ u.buf = (void *)name_lsteam;
+ if (c->get_dll_handle(load_path, 0, &u, &h) == 0 && h)
+ return h;
+ if (c->load_dll(load_path, 0, &u, &h) == 0 && h)
+ return h;
+ return 0;
+}
+
+static struct export_dir *export_of(u8 *mod)
+{
+ struct dos_header *dos = (struct dos_header *)mod;
+ struct nt_headers *nt = (struct nt_headers *)(mod + dos->e_lfanew);
+ u32 rva = nt->opt.dir[0].rva;
+ if (!rva)
+ return 0;
+ return (struct export_dir *)(mod + rva);
+}
+
+static int name_eq(const char *a, const char *b)
+{
+ while (*a && *a == *b) { a++; b++; }
+ return *a == *b;
+}
+
+static void *find_named_export(u8 *mod, const char *want)
+{
+ struct export_dir *e = export_of(mod);
+ u32 *names, *funcs, i;
+ u16 *ords;
+
+ if (!e)
+ return 0;
+ names = (u32 *)(mod + e->addr_names);
+ funcs = (u32 *)(mod + e->addr_funcs);
+ ords = (u16 *)(mod + e->addr_ords);
+ for (i = 0; i < e->nnames; i++)
+ if (name_eq((const char *)(mod + names[i]), want))
+ return mod + funcs[ords[i]];
+ return 0;
+}
+
+// movabs rax, tgt ; jmp rax
+static void write_jump(u8 *src, void *tgt)
+{
+ src[0] = 0x48; src[1] = 0xB8;
+ *(u64 *)(src + 2) = (u64)tgt;
+ src[10] = 0xFF; src[11] = 0xE0;
+}
+
+// Rewrite every named export of sc64 that lsteamclient also exports so it jumps to the
+// lsteamclient one, plus the entry point.
+static void setup_trampolines(struct ctx *c, u8 *sc64, u8 *lsteam)
+{
+ struct nt_headers *snt = (struct nt_headers *)(sc64 + ((struct dos_header *)sc64)->e_lfanew);
+ struct nt_headers *lnt = (struct nt_headers *)(lsteam + ((struct dos_header *)lsteam)->e_lfanew);
+ struct export_dir *se;
+ u32 *snames, *sfuncs, i;
+ u16 *sords;
+ void *base = sc64;
+ u64 size = snt->opt.size_of_image;
+ u32 oldp;
+
+ // make the whole sc64 image writable andexecutable so export stubs can be overwritten //
+ if (c->protect((void *)~0ull, &base, &size, 0x40 /*RWX*/, &oldp) != 0)
+ return;
+
+ se = export_of(sc64);
+ if (!se)
+ return;
+
+ snames = (u32 *)(sc64 + se->addr_names);
+ sfuncs = (u32 *)(sc64 + se->addr_funcs);
+ sords = (u16 *)(sc64 + se->addr_ords);
+ for (i = 0; i < se->nnames; i++)
+ {
+ void *tgt = find_named_export(lsteam, (const char *)(sc64 + snames[i]));
+ if (tgt)
+ write_jump(sc64 + sfuncs[sords[i]], tgt);
+ }
+
+ if (snt->opt.entry_point && lnt->opt.entry_point)
+ write_jump(sc64 + snt->opt.entry_point, lsteam + lnt->opt.entry_point);
+}
+
+// True when the MODREF basename (wm+0x60, a NUL-terminated wide string) is
+// steamclient64.dll
+static int wm_is_sc64(void *wm)
+{
+ static const char want[] = "steamclient64.dll";
+ const u16 *nm = *(const u16 **)((u8 *)wm + 0x60);
+ unsigned i;
+ if (!nm)
+ return 0;
+ for (i = 0; want[i]; i++)
+ {
+ u16 ch = nm[i];
+ if (ch >= 'A' && ch <= 'Z')
+ ch = (u16)(ch + 32);
+ if (ch != (u16)want[i])
+ return 0;
+ }
+ return nm[i] == 0;
+}
+
+// build_module detour
+void detour_build_module(struct ctx *c, void *wm, void *load_path)
+{
+ u8 *sc64, *lsteam;
+
+ if (!wm || !wm_is_sc64(wm))
+ return;
+
+ sc64 = (u8 *)WM_DLLBASE(wm);
+ if (!sc64)
+ return;
+
+ lsteam = (u8 *)resolve_lsteam(c, load_path);
+ if (!lsteam)
+ return; // let sc64 load normally
+
+ setup_trampolines(c, sc64, lsteam);
+
+ *WM_FLAGS(wm) |= LDR_DONT_CALL_DLLMAIN;
+}
diff --git a/ntdll-patch/detour32.c b/ntdll-patch/detour32.c
new file mode 100644
index 0000000..24f66b8
--- /dev/null
+++ b/ntdll-patch/detour32.c
@@ -0,0 +1,263 @@
+//Clever detours, but 32 bit
+
+typedef unsigned long long u64;
+typedef unsigned int u32;
+typedef unsigned short u16;
+typedef unsigned char u8;
+
+#define STDCALL __attribute__((stdcall))
+
+typedef u32 (STDCALL *ldr_getdllhandle_t)(void *path, void *unused, void *name_us, void **out);
+typedef u32 (STDCALL *ldr_loaddll_t)(void *path, void *flags, void *name_us, void **out);
+typedef u32 (STDCALL *nt_protect_t)(void *proc, void **base, u32 *size, u32 newprot, u32 *oldprot);
+typedef u32 (STDCALL *nt_openfile_t)(void **handle, u32 access, void *attr, void *io,
+ u32 share, u32 options);
+typedef u32 (STDCALL *nt_readfile_t)(void *handle, void *event, void *apc, void *apc_ctx, void *io,
+ void *buf, u32 len, u64 *offset, void *key);
+typedef u32 (STDCALL *nt_close_t)(void *handle);
+
+struct ctx
+{
+ ldr_getdllhandle_t get_dll_handle;
+ ldr_loaddll_t load_dll;
+ nt_protect_t protect;
+ nt_openfile_t open_file;
+ nt_readfile_t read_file;
+ nt_close_t close;
+ u32 delta; // load base - preferred base; see shim32.S
+};
+
+#define CAVE_PTR(c, p) ((void *)((u8 *)(p) + (c)->delta))
+
+struct dos_header { u16 e_magic; u8 pad[58]; u32 e_lfanew; };
+struct data_dir { u32 rva; u32 size; };
+struct opt_hdr32 { u16 magic; // 0
+ u8 pad0[14]; // 2
+ u32 entry_point; // 16
+ u8 pad1[8]; // 20
+ u32 image_base; // 28
+ u8 pad2[24]; // 32
+ u32 size_of_image; // 56
+ u8 pad3[36]; // 60
+ struct data_dir dir[16]; };// 96
+struct nt_headers { u32 sig; u8 file_hdr[20]; struct opt_hdr32 opt; };
+struct export_dir { u32 flags; u32 stamp; u16 maj; u16 min; u32 name;
+ u32 base; u32 nfuncs; u32 nnames;
+ u32 addr_funcs; u32 addr_names; u32 addr_ords; };
+
+struct us { u16 len; u16 max; void *buf; };
+struct obj_attr{ u32 len; void *root; void *name; u32 attrs; void *sd; void *sqos; };
+struct io_status { u32 status; u32 information; };
+
+#define ARG_FLAGS(fp) ( (u32 *)((u8 *)(fp) + FLAGS_SLOT))
+#define ARG_LOAD_PATH(fp) (*(void **)((u8 *)(fp) + LOAD_PATH_SLOT))
+
+//WINE_MODREF 32
+#define WM_DLLBASE(wm) (*(u8 **)((u8 *)(wm) + 0x18))
+#define WM_FULLNAME(wm) ( (const struct us *)((u8 *)(wm) + 0x24))
+#define WM_BASENAME(wm) (*(const u16 **)((u8 *)(wm) + 0x30))
+#define WM_FLAGS(wm) ( (u32 *)((u8 *)(wm) + 0x34))
+
+#define LDR_DONT_RESOLVE_REFS 0x00000002
+#define LDR_DONT_CALL_DLLMAIN 0x20000000
+
+static const u16 name_lsteam[] = {'l','s','t','e','a','m','c','l','i','e','n','t','.','d','l','l',0};
+
+static void *resolve_lsteam(struct ctx *c, void *load_path)
+{
+ struct us u;
+ void *h = 0;
+ u.len = 32; // "lsteamclient.dll" = 16 wchars
+ u.max = 34;
+ u.buf = CAVE_PTR(c, name_lsteam);
+ if (c->get_dll_handle(load_path, 0, &u, &h) == 0 && h)
+ return h;
+ if (c->load_dll(load_path, 0, &u, &h) == 0 && h)
+ return h;
+ return 0;
+}
+
+static struct nt_headers *nt_of(u8 *mod)
+{
+ return (struct nt_headers *)(mod + ((struct dos_header *)mod)->e_lfanew);
+}
+
+static struct export_dir *export_of(u8 *mod)
+{
+ u32 rva = nt_of(mod)->opt.dir[0].rva;
+ if (!rva)
+ return 0;
+ return (struct export_dir *)(mod + rva);
+}
+
+static int name_eq(const char *a, const char *b)
+{
+ while (*a && *a == *b) { a++; b++; }
+ return *a == *b;
+}
+
+static void *find_named_export(u8 *mod, const char *want)
+{
+ struct export_dir *e = export_of(mod);
+ u32 *names, *funcs, i;
+ u16 *ords;
+
+ if (!e)
+ return 0;
+ names = (u32 *)(mod + e->addr_names);
+ funcs = (u32 *)(mod + e->addr_funcs);
+ ords = (u16 *)(mod + e->addr_ords);
+ for (i = 0; i < e->nnames; i++)
+ if (name_eq((const char *)(mod + names[i]), want))
+ return mod + funcs[ords[i]];
+ return 0;
+}
+
+// mov eax, tgt ; jmp eax
+static void write_jump(u8 *src, void *tgt)
+{
+ src[0] = 0xB8;
+ *(u32 *)(src + 1) = (u32)tgt;
+ src[5] = 0xFF; src[6] = 0xE0;
+}
+
+static void setup_trampolines(struct ctx *c, u8 *sc, u8 *lsteam)
+{
+ struct nt_headers *snt = nt_of(sc);
+ struct nt_headers *lnt = nt_of(lsteam);
+ struct export_dir *se;
+ u32 *snames, *sfuncs, i;
+ u16 *sords;
+ void *base = sc;
+ u32 size = snt->opt.size_of_image;
+ u32 oldp;
+
+ if (c->protect((void *)~0u, &base, &size, 0x40 /*RWX*/, &oldp) != 0)
+ return;
+
+ se = export_of(sc);
+ if (!se)
+ return;
+
+ snames = (u32 *)(sc + se->addr_names);
+ sfuncs = (u32 *)(sc + se->addr_funcs);
+ sords = (u16 *)(sc + se->addr_ords);
+ for (i = 0; i < se->nnames; i++)
+ {
+ void *tgt = find_named_export(lsteam, (const char *)(sc + snames[i]));
+ if (tgt)
+ write_jump(sc + sfuncs[sords[i]], tgt);
+ }
+
+ if (snt->opt.entry_point && lnt->opt.entry_point)
+ write_jump(sc + snt->opt.entry_point, lsteam + lnt->opt.entry_point);
+}
+
+static int nt_name_of(void *wm, u16 *buf, unsigned cap, struct us *out)
+{
+ const struct us *full = WM_FULLNAME(wm);
+ const u16 *src = (const u16 *)full->buf;
+ unsigned i, n = full->len / 2;
+
+ if (!src || n < 2 || n + 4 > cap || src[0] == '\\')
+ return 0;
+
+ buf[0] = '\\'; buf[1] = '?'; buf[2] = '?'; buf[3] = '\\';
+ for (i = 0; i < n; i++)
+ buf[4 + i] = src[i];
+
+ out->len = (u16)((n + 4) * 2);
+ out->max = out->len;
+ out->buf = buf;
+ return 1;
+}
+
+static void restore_image_base(struct ctx *c, void *wm, u8 *mod)
+{
+ struct nt_headers *nt = nt_of(mod);
+ struct obj_attr attr;
+ struct io_status io;
+ struct us name;
+ u16 path[320];
+ void *addr = mod;
+ void *file = 0;
+ u32 size = 0x1000;
+ u32 oldp;
+ u64 offset;
+
+ if (!nt_name_of(wm, path, 320, &name))
+ return;
+
+ if (c->protect((void *)~0u, &addr, &size, 4 /*PAGE_READWRITE*/, &oldp) != 0)
+ return;
+
+ attr.len = sizeof(attr);
+ attr.root = 0;
+ attr.name = &name;
+ attr.attrs = 0x40;
+ attr.sd = 0;
+ attr.sqos = 0;
+
+ if (c->open_file(&file, 0x80000000u | 0x00100000u, &attr, &io, 1 | 4, 0x20 | 0x40) == 0)
+ {
+ offset = (u64)(u32)((u8 *)&nt->opt.image_base - (u8 *)mod);
+ c->read_file(file, 0, 0, 0, &io, &nt->opt.image_base,
+ sizeof(nt->opt.image_base), &offset, 0);
+ c->close(file);
+ }
+
+ addr = mod;
+ size = 0x1000;
+ c->protect((void *)~0u, &addr, &size, oldp, &oldp);
+}
+
+static int basename_is(void *wm, const char *want)
+{
+ const u16 *nm = WM_BASENAME(wm);
+ unsigned i;
+ if (!nm)
+ return 0;
+ for (i = 0; want[i]; i++)
+ {
+ u16 ch = nm[i];
+ if (ch >= 'A' && ch <= 'Z')
+ ch = (u16)(ch + 32);
+ if (ch != (u16)want[i])
+ return 0;
+ }
+ return nm[i] == 0;
+}
+
+void detour_build_module32(struct ctx *c, void *wm, void *fp)
+{
+ u8 *sc, *lsteam;
+ int is_steamclient32;
+
+ if (!wm)
+ return;
+
+ is_steamclient32 = basename_is(wm, CAVE_PTR(c, "steamclient.dll"));
+ if (!is_steamclient32 && !basename_is(wm, CAVE_PTR(c, "gameoverlayrenderer.dll")))
+ return;
+
+ sc = WM_DLLBASE(wm);
+ if (!sc)
+ return;
+
+ lsteam = (u8 *)resolve_lsteam(c, ARG_LOAD_PATH(fp));
+ if (!lsteam)
+ return;
+
+ setup_trampolines(c, sc, lsteam);
+
+ if (is_steamclient32)
+ {
+ *WM_FLAGS(wm) |= LDR_DONT_RESOLVE_REFS;
+ *ARG_FLAGS(fp) |= LDR_DONT_RESOLVE_REFS;
+ restore_image_base(c, wm, sc);
+ }
+ else
+ {
+ *WM_FLAGS(wm) |= LDR_DONT_CALL_DLLMAIN;
+ }
+}
diff --git a/ntdll-patch/link.ld b/ntdll-patch/link.ld
new file mode 100644
index 0000000..04ce3b1
--- /dev/null
+++ b/ntdll-patch/link.ld
@@ -0,0 +1,11 @@
+// x86_64 ntdll.dll cave layout, link time only
+SECTIONS {
+ . = CAVE_VA;
+ .cave : {
+ shim.o(.text)
+ *(.text .text.*)
+ . = ALIGN(16);
+ *(.rdata .rdata.* .rodata .rodata.*)
+ }
+ /DISCARD/ : { *(.pdata) *(.xdata) *(.bss) *(.data) *(.comment) *(.note.*) }
+}
diff --git a/ntdll-patch/link32.ld b/ntdll-patch/link32.ld
new file mode 100644
index 0000000..192a2a2
--- /dev/null
+++ b/ntdll-patch/link32.ld
@@ -0,0 +1,11 @@
+// i386 ntdll.dll cave layout, link time only
+SECTIONS {
+ . = CAVE_VA;
+ .cave : SUBALIGN(1) {
+ shim32.o(.text)
+ *(.text .text.*)
+ . = ALIGN(16);
+ *(.rdata .rdata.* .rodata .rodata.*)
+ }
+ /DISCARD/ : { *(.pdata) *(.xdata) *(.bss) *(.data) *(.comment) *(.note.*) *(.eh_frame) }
+}
diff --git a/ntdll-patch/link64.ld b/ntdll-patch/link64.ld
new file mode 100644
index 0000000..560cc4e
--- /dev/null
+++ b/ntdll-patch/link64.ld
@@ -0,0 +1,11 @@
+// aarch64 ntdll.dll cave layout, link time only
+SECTIONS {
+ . = CAVE_VA;
+ .cave : {
+ shim64.o(.text)
+ *(.text .text.*)
+ . = ALIGN(8);
+ *(.rodata .rodata.*)
+ }
+ /DISCARD/ : { *(.comment) *(.note.*) *(.llvm_addrsig) *(.eh_frame) *(.bss) *(.data) }
+}
diff --git a/ntdll-patch/resolve.py b/ntdll-patch/resolve.py
new file mode 100755
index 0000000..ea1fa38
--- /dev/null
+++ b/ntdll-patch/resolve.py
@@ -0,0 +1,696 @@
+#!/usr/bin/env python3
+# Reads every per-build constant the ntdll detours need out of the binary, for
+# all archs. Internal development tool, ugly
+import hashlib, pathlib, struct, sys, re, bisect, capstone
+from capstone import x86 as X86, arm64 as A64
+
+ARCH = {0x8664: 'x86_64-windows', 0x14c: 'i386-windows', 0xaa64: 'aarch64-windows'}
+
+PAYLOAD = {0x8664: 864, 0x14c: 1376, 0xaa64: 868} # detour2.bin, detour32.bin, detour64-fex.bin
+
+# Keyed by input sha256 so the comparison only runs against the build the tree pins, so a
+# new build will report derived values rather than a wall of expected mismatches
+PINNED = {
+ '04c7200b6645decb7c2d1ba6b0195abc9af83257072558d11aa72cc067ac3377':
+ {'hookRVA': 0x51f15, 'stolen': '4883bc24f000000000', 'caveRVA': 0x80be0, 'wm': 'rsi',
+ 'resume': 0x51f1e, 'load_path': 0xd0,
+ 'payload': '4ce2ddc11c433fe15f78633fc5c1fda8b27fa642426cb26378f7d7d7b54a79f8',
+ 'exports': {'LdrGetDllHandle': 0x1700176d0, 'LdrLoadDll': 0x1700181f0,
+ 'NtProtectVirtualMemory': 0x17000f640}},
+ '94cc7c14c1e9dcf58ef501015c115f8405c73b2a65cefe31faa5d9e47f36e58b':
+ {'hookRVA': 0x4d828, 'stolen': 'f645bc027526', 'caveRVA': 0x7c830, 'caveSize': 2000,
+ 'resume': 0x4d82e, 'wm': 'edi', 'load_path': -0x54,
+ 'payload': '2758d4f6783c853c460187f83f4fb9b1105380d194126ef83fc85e2596d3036a',
+ 'exports': {'LdrGetDllHandle': 0x7bc125b0, 'LdrLoadDll': 0x7bc130a0,
+ 'NtProtectVirtualMemory': 0x7bc0d764, 'NtOpenFile': 0x7bc0d594,
+ 'NtReadFile': 0x7bc0d2c4, 'NtClose': 0x7bc0d354}},
+ '09474795d6f306163cebab6429819999fcff50e07dbc4b067a90ec4f74a3a7d7':
+ {'hookRVA': 0x2ee12, 'stolen': '8b4514a802', 'caveRVA': 0x6b2fe, 'caveSize': 3330,
+ 'resume': 0x2ee17, 'wm': 'esi', 'load_path': -0x3c,
+ 'payload': 'b4c697ba396ecb59125c505666ad3465d1208b8a1e3e53a0c457657b341376b9',
+ 'exports': {'LdrGetDllHandle': 0x7bc2a6b0, 'LdrLoadDll': 0x7bc286d0,
+ 'NtProtectVirtualMemory': 0x7bc4d020, 'NtOpenFile': 0x7bc4ce50,
+ 'NtReadFile': 0x7bc4cb80, 'NtClose': 0x7bc4cc10}},
+ '7823d71fbce6c9947163bf8b96beb299eabb02878245bcaf6759f2a22e81f071':
+ {'caveRVA': 0xf1185, 'caveSize': 61051,
+ # This image carries the loader twice, once for the native side and once for the
+ # emulated guest, and the detour has to divert both....
+ 'sites': [{'hookRVA': 0x48004, 'stolen': '1f2003d5', 'resume': 0x48008,
+ 'wm': 'x27', 'load_path': -0x98},
+ {'hookRVA': 0xa71bc, 'stolen': '1f2003d5', 'resume': 0xa71c0,
+ 'wm': 'x22', 'load_path': -0x88}],
+ # What link64.ld resolves, and the reason it is not the exports below: from the
+ # guest loader the exported LdrLoadDll takes a lock it does not hold, and the
+ # exported NtProtectVirtualMemory is a syscall thunk whose dispatcher is null.
+ 'guest': {'LdrLoadDll': 0x9f698, 'LdrGetDllHandle': 0x9f698,
+ 'NtProtectVirtualMemory': 0xea8cc},
+ 'payload': 'bee4ee13c235bd5de3cb6ce840b9695effd5623132f6dc0d137496d6a5330f5e',
+ 'exports': {'LdrGetDllHandle': 0x180043328, 'LdrLoadDll': 0x180040e94,
+ 'NtProtectVirtualMemory': 0x180065db0}},
+}
+EXPORTS = ['LdrGetDllHandle', 'LdrLoadDll', 'NtProtectVirtualMemory',
+ 'NtOpenFile', 'NtReadFile', 'NtClose']
+PROLOGUES = [rb'\x55\x89\xe5', rb'\x55\x8b\xec']
+NOP64 = bytes.fromhex('1f2003d5')
+
+# A byte test on a register has to be traced back to the dword that loaded it, so the two
+# names have to compare equal.
+SUBREG = {'al': 'eax', 'ah': 'eax', 'ax': 'eax', 'bl': 'ebx', 'bh': 'ebx', 'bx': 'ebx',
+ 'cl': 'ecx', 'ch': 'ecx', 'cx': 'ecx', 'dl': 'edx', 'dh': 'edx', 'dx': 'edx',
+ 'si': 'esi', 'di': 'edi', 'bp': 'ebp', 'sp': 'esp'}
+
+
+class PE:
+ def __init__(self, path):
+ self.path = path
+ self.d = open(path, 'rb').read()
+ e = struct.unpack_from('<I', self.d, 0x3c)[0]
+ self.machine = struct.unpack_from('<H', self.d, e + 4)[0]
+ nsec = struct.unpack_from('<H', self.d, e + 6)[0]
+ optsz = struct.unpack_from('<H', self.d, e + 20)[0]
+ self.opt = e + 24
+ self.magic = struct.unpack_from('<H', self.d, self.opt)[0]
+ wide = self.magic == 0x20b
+ self.imagebase = (struct.unpack_from('<Q', self.d, self.opt + 24)[0] if wide
+ else struct.unpack_from('<I', self.d, self.opt + 28)[0])
+ self.secs = []
+ for i in range(nsec):
+ o = e + 24 + optsz + i * 40
+ name = self.d[o:o + 8].rstrip(b'\0').decode('latin1')
+ vsize, vrva, rsize, roff = struct.unpack_from('<IIII', self.d, o + 8)
+ if roff:
+ self.secs.append((name, vrva, vsize, roff, rsize))
+ self.dirs = self.opt + (112 if wide else 96)
+
+ def sec(self, prefix):
+ for s in self.secs:
+ if s[0].startswith(prefix):
+ return s
+ raise SystemExit(f"{self.path}: no {prefix} section")
+
+ def off(self, rva):
+ for _, vrva, vsize, roff, rsize in self.secs:
+ if vrva <= rva < vrva + max(vsize, rsize):
+ return roff + (rva - vrva)
+ raise SystemExit(f"{self.path}: rva {rva:#x} not mapped")
+
+ def text(self):
+ _, vrva, _, roff, rsize = self.sec('.text')
+ return vrva, self.d[roff:roff + rsize]
+
+ def cs(self):
+ if self.machine == 0xaa64:
+ md = capstone.Cs(capstone.CS_ARCH_ARM64, capstone.CS_MODE_ARM)
+ else:
+ md = capstone.Cs(capstone.CS_ARCH_X86,
+ capstone.CS_MODE_64 if self.machine == 0x8664 else capstone.CS_MODE_32)
+ md.detail = True
+ return md
+
+ def pdata_starts(self):
+ """Function entry RVAs from the exception directory, ascending."""
+ # aarch64 RUNTIME_FUNCTION is 8 bytes and its length is either packed into the second
+ # word or parked in .xdata, so bounds come from the next entry
+ _, _, _, proff, prsize = self.sec('.pdata')
+ stride = 8 if self.machine == 0xaa64 else 12
+ out = {struct.unpack_from('<I', self.d, o)[0] for o in range(proff, proff + prsize, stride)}
+ return sorted(out - {0})
+
+ def exports(self):
+ edir = struct.unpack_from('<I', self.d, self.dirs)[0]
+ o = self.off(edir)
+ nnames = struct.unpack_from('<I', self.d, o + 0x18)[0]
+ afun, anam, aord = struct.unpack_from('<III', self.d, o + 0x1c)
+ fo, no, oo = self.off(afun), self.off(anam), self.off(aord)
+ out = {}
+ for i in range(nnames):
+ nrva = struct.unpack_from('<I', self.d, no + 4 * i)[0]
+ ordn = struct.unpack_from('<H', self.d, oo + 2 * i)[0]
+ frva = struct.unpack_from('<I', self.d, fo + 4 * ordn)[0]
+ s = self.off(nrva)
+ out[self.d[s:self.d.index(b'\0', s)].decode('latin1')] = frva
+ return out
+
+ def cave(self):
+ # PE sections are padded out to the file alignment, so there's dead space
+ # at the end that the loader maps but nothing touches. Detour goes there.
+ _, vrva, vsize, roff, rsize = self.sec('.text')
+ end = vrva + vsize
+ return {'caveRVA': end, 'caveSize': (vrva + rsize) - end, 'fill': self.d[roff + vsize]}
+
+ def string_refs(self, name):
+ """RVAs of instructions referencing a .rdata C string, however the arch addresses it."""
+ _, rvrva, _, rroff, rrsize = self.sec('.rdata')
+ k = self.d[rroff:rroff + rrsize].find(name.encode() + b'\0')
+ if k == -1:
+ raise SystemExit(f"{self.path}: no {name} string; not a traced wine build")
+ srva = rvrva + k
+ tvrva, text = self.text()
+ if self.machine == 0x14c:
+ # No EIP-relative addressing, so the absolute VA appears as a literal.
+ pat = re.escape(struct.pack('<I', self.imagebase + srva))
+ return srva, [tvrva + m.start() for m in re.finditer(pat, text)]
+ hits = []
+ for i in self.cs().disasm(text, tvrva):
+ for op in i.operands:
+ if op.type == X86.X86_OP_MEM and op.mem.base == X86.X86_REG_RIP:
+ if i.address + i.size + op.mem.disp == srva:
+ hits.append(i.address)
+ return srva, hits
+
+ def func_start(self, before):
+ """Nearest frame-pointer prologue at or before an address."""
+ tvrva, text = self.text()
+ best = None
+ for pat in PROLOGUES:
+ for m in re.finditer(pat, text[:before - tvrva]):
+ if best is None or m.start() > best:
+ best = m.start()
+ if best is None:
+ raise SystemExit(f"{self.path}: no prologue before {before:#x}")
+ return tvrva + best
+
+
+def steal(insns, k, need=5):
+ """Whole instructions from insns[k] totalling at least `need` bytes."""
+ taken, total = [], 0
+ while total < need:
+ taken.append(insns[k + len(taken)])
+ total += taken[-1].size
+ return taken, total
+
+
+def resolve_amd64(pe):
+ md = pe.cs()
+ tvrva, text = pe.text()
+ insns = list(md.disasm(text, tvrva))
+
+ _, pvrva, pvsize, proff, _ = pe.sec('.pdata')
+ funcs = []
+ for o in range(proff, proff + pvsize, 12):
+ begin, end, _ = struct.unpack_from('<III', pe.d, o)
+ if begin:
+ funcs.append((begin, end))
+
+ owner = {}
+ for name in ('build_module', 'alloc_module'):
+ _, refs = pe.string_refs(name)
+ for r in refs:
+ for begin, end in funcs:
+ if begin <= r < end:
+ owner.setdefault(name, (begin, end))
+ bm = owner['build_module']
+ am = owner['alloc_module'][0]
+
+ body = [i for i in insns if bm[0] <= i.address < bm[1]]
+ calls = [k for k, i in enumerate(body) if i.mnemonic == 'call' and i.op_str == hex(am)]
+ if len(calls) != 1:
+ raise SystemExit(f"{pe.path}: {len(calls)} alloc_module calls in build_module, want 1")
+
+ k, wm = calls[0] + 1, None
+ while True:
+ i = body[k]
+ if i.mnemonic == 'test' and i.op_str == 'rax, rax':
+ k += 1
+ elif i.mnemonic == 'mov' and i.op_str.endswith(', rax'):
+ wm = i.op_str.split(',')[0].strip()
+ k += 1
+ elif i.mnemonic in ('je', 'jz'):
+ k += 1
+ else:
+ break
+ hook = body[k]
+ slot = amd64_load_path(pe, body, hook.address)
+ return {'build_module': bm, 'alloc_module': am, 'wm': wm, 'load_path': slot,
+ 'hookRVA': hook.address, 'stolen': hook.bytes.hex(), 'insn': f"{hook.mnemonic} {hook.op_str}"}
+
+
+def amd64_load_path(pe, body, hook):
+ """Frame slot holding the load_path argument, read as [rsp+N] at the hook."""
+ # Neither build keeps the argument in rcx. One spills it to the stack right away,
+ # the other stashes it in a callee-saved register and reuses that a few instructions
+ # later.
+ src, slot, stored_at = 'rcx', None, None
+ for i in body:
+ if i.address >= hook:
+ break
+ if i.mnemonic != 'mov' or ',' not in i.op_str:
+ continue
+ dst, rhs = (x.strip() for x in i.op_str.split(',', 1))
+ if rhs != src:
+ continue
+ if dst.startswith('qword ptr [rsp'):
+ slot = 0 if '+' not in dst else int(dst.split('+')[1].strip().rstrip(']'), 16)
+ stored_at = i.address
+ break
+ if re.fullmatch(r'r[a-z0-9]+', dst):
+ src = dst
+ if slot is None:
+ raise SystemExit(f"{pe.path}: load_path never reaches the frame in build_module")
+
+ # The shim reads the slot off rsp, so anything moving rsp in between would shift it, and
+ # a second write to it would mean the slot is reused for something else.
+ for i in body:
+ if not stored_at < i.address < hook:
+ continue
+ if i.mnemonic in ('push', 'pop') or (i.mnemonic in ('sub', 'add') and i.op_str.startswith('rsp,')):
+ raise SystemExit(f"{pe.path}: rsp moves at {i.address:#x}, load_path slot not rsp-stable")
+ if i.mnemonic == 'mov' and i.op_str.startswith(f'qword ptr [rsp + {slot:#x}],'):
+ raise SystemExit(f"{pe.path}: load_path slot rewritten at {i.address:#x}")
+ return slot
+
+
+def resolve_i386(pe):
+ md = pe.cs()
+ tvrva, _ = pe.text()
+ _, refs = pe.string_refs('build_module')
+ start = pe.func_start(min(refs))
+ body = list(md.disasm(pe.d[pe.off(start):pe.off(start) + 0x1400], start))
+
+ # LDR_DATA_TABLE_ENTRY.Flags is at +0x34, so byte 3 of that field is at +0x37.
+ # The fixup_imports gate tests bit 0 of that byte, and the register being
+ # dereferenced is the MODREF.
+ anchor = None
+ for k, i in enumerate(body):
+ if i.mnemonic == 'test' and re.match(r'^byte ptr \[e\w\w \+ 0x37\], 1$', i.op_str):
+ anchor = k
+ break
+ if anchor is None:
+ raise SystemExit(f"{pe.path}: no MODREF flag test in build_module")
+ wm = re.search(r'\[(e\w\w) \+ 0x37\]', body[anchor].op_str).group(1)
+
+ # The module flags are tested for bit 2 just above. Either the value is still in memory
+ # or the compiler loaded it first, in which case that load starts the hook.
+ gate = None
+ for k in range(anchor - 1, max(anchor - 24, 0), -1):
+ i = body[k]
+ if i.mnemonic == 'test' and i.operands and i.operands[-1].type == X86.X86_OP_IMM \
+ and i.operands[-1].imm == 2:
+ gate = k
+ break
+ if gate is None:
+ raise SystemExit(f"{pe.path}: no module-flags gate above the MODREF flag test")
+ # If the test uses a register, the flags were already loaded before the hook site.
+ # Stealing just the test wouldn't work, the detour would replay a read from a
+ # register it never set up....
+ hook_k = gate
+ tested = body[gate].operands[0]
+ if tested.type == X86.X86_OP_REG:
+ want = SUBREG.get(body[gate].reg_name(tested.reg), body[gate].reg_name(tested.reg))
+ for k in range(gate - 1, max(gate - 8, -1), -1):
+ i = body[k]
+ if i.mnemonic != 'mov' or i.operands[0].type != X86.X86_OP_REG:
+ continue
+ if SUBREG.get(i.reg_name(i.operands[0].reg), i.reg_name(i.operands[0].reg)) == want:
+ hook_k = k
+ break
+ else:
+ raise SystemExit(f"{pe.path}: {want} tested at {body[gate].address:#x} with no load above")
+ # build_module's flags live in a frame slot. The gate either reads the slot
+ # directly or loads it into a register first. Whichever instruction has the
+ # memory operand tells us which slot it is.
+ holder = body[gate] if tested.type != X86.X86_OP_REG else body[hook_k]
+ mem = [o for o in holder.operands if o.type == X86.X86_OP_MEM]
+ if len(mem) != 1:
+ raise SystemExit(f"{pe.path}: {holder.address:#x} does not read the flags from memory")
+ flags_slot = mem[0].mem.disp
+
+ taken, total = steal(body, hook_k)
+
+ jk = None
+ for k in range(gate + 1, min(gate + 8, len(body))):
+ if body[k].mnemonic in ('jne', 'jnz'):
+ jk = k
+ break
+ if X86.X86_REG_EFLAGS in body[k].regs_access()[1]:
+ break
+ if jk is None:
+ raise SystemExit(f"{pe.path}: no branch on the module-flags gate at {body[gate].address:#x}")
+ skip = body[jk].operands[0].imm
+ stole_branch = taken[-1].address == body[jk].address
+
+ load_path = None
+ for i in body[anchor:anchor + 12]:
+ if i.mnemonic == 'mov' and i.op_str.startswith('edx, dword ptr [ebp'):
+ m = re.search(r'ebp ([-+]) (0x[0-9a-f]+)', i.op_str)
+ load_path = int(m.group(2), 16) * (-1 if m.group(1) == '-' else 1)
+ if i.mnemonic == 'call':
+ break
+ return {'build_module': (start, None), 'wm': wm, 'hookRVA': taken[0].address,
+ 'stolen': b''.join(i.bytes for i in taken).hex(), 'stolen_len': total,
+ 'insn': ' ; '.join(f"{i.mnemonic} {i.op_str}" for i in taken),
+ 'load_path': load_path, 'skip': skip, 'stole_branch': stole_branch,
+ 'stolen_head': b''.join(i.bytes for i in (taken[:-1] if stole_branch else taken)).hex(),
+ 'flags_slot': flags_slot}
+
+
+def aarch64_walk(md, text, tv):
+
+ off = 0
+ while off < len(text):
+ last = None
+ for i in md.disasm(text[off:], tv + off):
+ last = i
+ yield i
+ off = (last.address + last.size - tv + 4) if last else off + 4
+
+
+def aarch64_literal_refs(pe, names):
+ _, rvrva, _, rroff, rrsize = pe.sec('.rdata')
+ blob = pe.d[rroff:rroff + rrsize]
+ want = {}
+ for name in names:
+ pat = name.encode() + b'\0'
+ k = blob.find(pat)
+ while k != -1:
+ if k == 0 or blob[k - 1] == 0:
+ want[rvrva + k] = name
+ k = blob.find(pat, k + 1)
+ tv, text = pe.text()
+ out, pages = {}, {}
+ for i in aarch64_walk(pe.cs(), text, tv):
+ if i.mnemonic == 'adrp':
+ pages[i.operands[0].reg] = i.operands[1].imm
+ elif i.mnemonic == 'add' and len(i.operands) == 3 \
+ and i.operands[2].type == A64.ARM64_OP_IMM:
+ page = pages.get(i.operands[1].reg)
+ srva = None if page is None else page + i.operands[2].imm
+ if srva in want:
+ out.setdefault(srva, (want[srva], []))[1].append(i.address)
+ return out
+
+
+def aarch64_body(pe, md, lo, hi):
+ tv, text = pe.text()
+ lo, hi = max(tv, lo) & ~3, min(tv + len(text), hi)
+ return list(aarch64_walk(md, text[lo - tv:hi - tv], lo))
+
+
+def aarch64_open(pe, md, inside):
+ """Prologue RVA of the function containing `inside`."""
+ body = aarch64_body(pe, md, inside - 0x4000, inside + 4)
+ for k in range(len(body) - 1, -1, -1):
+ i = body[k]
+ if i.mnemonic == 'sub' and i.op_str.startswith('sp, sp, #') \
+ and any(n.mnemonic == 'add' and n.op_str.startswith('x29, sp, #')
+ for n in body[k + 1:k + 13]):
+ return i.address
+ raise SystemExit(f"{pe.path}: no frame prologue above {inside:#x}")
+
+
+def aarch64_hook(pe, md, ref, allocs):
+ start = aarch64_open(pe, md, ref)
+ body = aarch64_body(pe, md, start, start + 0x2000)
+
+ def name(i, n):
+ return i.reg_name(i.operands[n].reg)
+
+ call = next((k for k, i in enumerate(body)
+ if i.mnemonic == 'bl' and i.operands[0].imm in allocs), None)
+ if call is None:
+ raise SystemExit(f"{pe.path}: build_module at {start:#x} never calls alloc_module")
+ if body[call + 1].mnemonic != 'cbz' or name(body[call + 1], 0) != 'x0':
+ raise SystemExit(f"{pe.path}: alloc_module at {body[call].address:#x} is not null-checked")
+ join = next((i.operands[1].imm for i in body[call + 2:call + 10] if i.mnemonic == 'cbz'), None)
+ if join is None:
+ raise SystemExit(f"{pe.path}: no id test below alloc_module at {body[call].address:#x}")
+ k = next((k for k, i in enumerate(body) if i.address == join), None)
+ if k is None or body[k].bytes != NOP64:
+ raise SystemExit(f"{pe.path}: the id block from {body[call].address:#x} joins on "
+ f"{join:#x}, which is not a nop")
+
+ # The shim takes the MODREF from x0 rather than from whichever register this copy moved it
+ # into, which only holds while nothing on the way to the join writes x0.
+ for i in body[call + 1:k]:
+ if 'x0' in {i.reg_name(w).replace('w', 'x', 1) for w in i.regs_access()[1]}:
+ raise SystemExit(f"{pe.path}: x0 no longer the MODREF at {i.address:#x}")
+ wm = next((name(i, 0) for i in body[call + 1:k] if i.mnemonic == 'mov'
+ and i.operands[1].type == A64.ARM64_OP_REG and name(i, 1) == 'x0'), None)
+ if wm is None or not any(i.mnemonic == 'add' and i.op_str.endswith('#0x118')
+ and name(i, 1) == wm for i in body[call:k]):
+ raise SystemExit(f"{pe.path}: nothing below {body[call].address:#x} treats the result "
+ f"as a MODREF")
+
+ def spill(src):
+ """The frame slot build_module parks an incoming argument in."""
+ for i in body[:24]:
+ if i.mnemonic == 'stur' and name(i, 0) == src \
+ and i.operands[1].type == A64.ARM64_OP_MEM \
+ and i.reg_name(i.operands[1].mem.base) == 'fp':
+ return i.operands[1].mem.disp
+ raise SystemExit(f"{pe.path}: build_module at {start:#x} never spills {src}")
+
+ return {'build_module': start, 'hookRVA': join, 'stolen': NOP64.hex(), 'stolen_len': 4,
+ 'insn': f"{body[k].mnemonic} {body[k].op_str}".strip(), 'resume': join + 4,
+ 'wm': wm, 'load_path': spill('x0'), 'flags_slot': spill('w5')}
+
+
+def aarch64_guest_syscall(pe, md, native):
+ num = next((int(i.op_str.split('#')[1], 0)
+ for i in aarch64_body(pe, md, native, native + 8)
+ if i.mnemonic == 'mov' and i.op_str.startswith('x8, #')), None)
+ if num is None:
+ raise SystemExit(f"{pe.path}: no syscall number at {native:#x}")
+ tv, text = pe.text()
+ pat = b'\x4c\x8b\xd1\xb8' + num.to_bytes(4, 'little') # mov r10, rcx ; mov eax, num
+ k = text.find(pat)
+ if k < 0 or text.find(pat, k + 1) >= 0:
+ raise SystemExit(f"{pe.path}: guest stub for syscall {num:#x} is "
+ f"{'missing' if k < 0 else 'not unique'}")
+ stub = tv + k
+ body = list(aarch64_walk(md, text, tv))
+ found = set()
+ for n, i in enumerate(body[:-1]):
+ nx = body[n + 1]
+ if i.mnemonic != 'adrp' or not i.op_str.startswith('x11, '):
+ continue
+ if nx.mnemonic != 'add' or not nx.op_str.startswith('x11, x11, #'):
+ continue
+ if int(i.op_str.split('#')[1], 0) + int(nx.op_str.split('#')[1], 0) != stub:
+ continue
+ entry = i.address - 8
+ head = aarch64_body(pe, md, entry, entry + 4)
+ if head and head[0].mnemonic == 'str' and head[0].op_str.startswith('x30, [sp, #-'):
+ found.add(entry)
+ if not found:
+ raise SystemExit(f"{pe.path}: no guest thunk tail branching to {stub:#x}")
+ return found
+
+
+def aarch64_twin(pe, md, native, span):
+ """RVA of the copy of the function at `native` that was compiled into `span`.
+
+ Both copies come from the same source, so the mnemonic sequence is identical even though
+ register numbers and call targets are not.
+ """
+ want = [i.mnemonic for i in aarch64_body(pe, md, native, native + 0x100)]
+ tv, text = pe.text()
+ lo, hi = span
+ opener = text[native - tv:native - tv + 4]
+ hits, k = [], text.find(opener, lo - tv, hi - tv)
+ while k != -1:
+ f = tv + k
+ if f != native and [i.mnemonic for i in aarch64_body(pe, md, f, f + 0x100)] == want:
+ hits.append(f)
+ k = text.find(opener, k + 4, hi - tv)
+ if len(hits) != 1:
+ raise SystemExit(f"{pe.path}: {len(hits)} twins of {native:#x} in {lo:#x}..{hi:#x}")
+ return hits[0]
+
+
+def resolve_aarch64(pe):
+ md = pe.cs()
+ refs = aarch64_literal_refs(pe, ('build_module', 'alloc_module'))
+ allocs = {aarch64_open(pe, md, a[0]) for n, a in refs.values() if n == 'alloc_module'}
+ sites = sorted((aarch64_hook(pe, md, a[0], allocs)
+ for n, a in refs.values() if n == 'build_module'),
+ key=lambda s: s['hookRVA'])
+ if len(sites) != 2:
+ raise SystemExit(f"{pe.path}: {len(sites)} build_module copies, shim64.S hooks two")
+
+ ex = pe.exports()
+ thunks = aarch64_guest_syscall(pe, md, ex['NtProtectVirtualMemory'])
+
+ def calls(s):
+ bm = s['build_module']
+ return {int(i.op_str.lstrip('#'), 0)
+ for i in aarch64_body(pe, md, bm, bm + 0x1000) if i.mnemonic == 'bl'}
+
+ reach = [calls(s) for s in sites]
+ guest = [(s, c & thunks) for s, c in zip(sites, reach)
+ if c & thunks and ex['NtProtectVirtualMemory'] not in c]
+ native = [s for s, c in zip(sites, reach)
+ if ex['NtProtectVirtualMemory'] in c and not c & thunks]
+ if len(guest) != 1 or len(native) != 1 or guest[0][0] is native[0]:
+ raise SystemExit(f"{pe.path}: cannot tell the two build_module copies apart by their "
+ f"route to NtProtectVirtualMemory")
+ if len(guest[0][1]) != 1:
+ raise SystemExit(f"{pe.path}: guest build_module reaches {len(guest[0][1])} protect thunks")
+ thunk = guest[0][1].pop()
+
+ bm = guest[0][0]['build_module']
+ tv, text = pe.text()
+ span = (max(tv, bm - 0x10000), min(tv + len(text), bm + 0x10000))
+ # A detour running under the guest loader has to stay inside it, obviously
+ load = aarch64_twin(pe, md, ex['LdrLoadDll'], span)
+ return dict(sites[0], sites=sites,
+ guest={'LdrLoadDll': load, 'LdrGetDllHandle': load,
+ 'NtProtectVirtualMemory': thunk})
+
+
+def resolve(path):
+ pe = PE(path)
+ r = (resolve_aarch64(pe) if pe.machine == 0xaa64 else
+ resolve_amd64(pe) if pe.machine == 0x8664 else resolve_i386(pe))
+ r.update(pe.cave())
+ r['machine'], r['magic'], r['imageBase'] = pe.machine, pe.magic, pe.imagebase
+ ex = pe.exports()
+ r['exports'] = {n: pe.imagebase + ex[n] for n in EXPORTS if n in ex}
+ r['resume'] = r['hookRVA'] + len(r['stolen']) // 2
+ r['sha256'] = hashlib.sha256(pe.d).hexdigest()
+ return r
+
+
+def report(path):
+ machine = PE(path).machine
+ if machine not in ARCH:
+ print(f"{path}\n machine {machine:#x} carries no detour, skipped\n")
+ return True
+ r = resolve(path)
+ pin = PINNED.get(r['sha256'], {})
+ arch = ARCH[machine]
+ print(f"{path}\n arch {arch} machine {r['machine']:#x} magic {r['magic']:#x}"
+ f" imageBase {r['imageBase']:#x}\n sha256 {r['sha256']}"
+ f"{' (the pinned build, self-testing)' if pin else ' (not a pinned build)'}")
+ ok = True
+
+ def line(label, got, key=None, fmt=lambda v: f"{v:#x}", want=pin):
+ nonlocal ok
+ tag = ""
+ if key and key in want:
+ match = want[key] == got
+ ok = ok and match
+ tag = " MATCH" if match else f" MISMATCH (pinned {fmt(want[key])})"
+ print(f" {label:13} {fmt(got)}{tag}")
+
+ sites = r.get('sites')
+ pinned_sites = pin.get('sites') or []
+ for n, s in enumerate(sites or [r], 1):
+ want = pin
+ if sites:
+ want = pinned_sites[n - 1] if n <= len(pinned_sites) else {}
+ print(f" hook {n} of {len(sites)}, build_module at {s['build_module']:#x}")
+ line('hookRVA', s['hookRVA'], 'hookRVA', want=want)
+ print(f" {'insn':13} {s['insn']}")
+ line('stolen', s['stolen'], 'stolen', fmt=str, want=want)
+ line('resume', s['resume'], 'resume', want=want)
+ line('wm', s['wm'], 'wm', fmt=str, want=want)
+ if s.get('load_path') is not None:
+ frame = {0x8664: 'rsp', 0x14c: 'ebp', 0xaa64: 'x29'}[machine]
+ slot = ((lambda v: f"{frame}+{v:#x}") if machine == 0x8664
+ else (lambda v: f"{frame}{v:+#x}"))
+ line('load_path', s['load_path'], 'load_path', fmt=slot, want=want)
+ line('caveRVA', r['caveRVA'], 'caveRVA')
+ line('caveSize', r['caveSize'], 'caveSize', fmt=str)
+ need = PAYLOAD[r['machine']]
+ print(f" {'cave fill':13} {r['fill']:#02x} room {r['caveSize']} bytes, payload {need}"
+ f" -> {'fits' if r['caveSize'] >= need else 'TOO SMALL'}")
+ def table(items, want):
+ nonlocal ok
+ for n, va in items.items():
+ pinned_va = want.get(n)
+ tag = ""
+ if pinned_va:
+ match = pinned_va == va
+ ok = ok and match
+ tag = " MATCH" if match else f" MISMATCH (pinned {pinned_va:#x})"
+ print(f" {n:24} {va:#x}{tag}")
+
+ table(r['exports'], pin.get('exports', {}))
+ if r.get('guest'):
+ print(" guest loader, which is what link64.ld resolves instead")
+ table(r['guest'], pin.get('guest', {}))
+ if pin:
+ print(f" self-test: {'all pinned values reproduced' if ok else 'FAILED'}")
+ print()
+ return ok if pin else True
+
+
+def ntdlls(arg):
+ """Every ntdll.dll under a bundle, a CrossOver root, or a wine directory."""
+ p = pathlib.Path(arg)
+ if p.is_file():
+ return [str(p)]
+ for root in (p / 'Contents/SharedSupport/CrossOver/lib/wine', p / 'lib/wine', p):
+ archs = sorted(d for d in root.glob('*-windows') if d.is_dir())
+ if not archs:
+ continue
+ found = []
+ for d in archs:
+ for name in ('ntdll.dll.notproton-orig', 'ntdll.dll'):
+ if (d / name).is_file():
+ found.append(str(d / name))
+ break
+ if found:
+ return found
+ raise SystemExit(f"{arg}: no <arch>-windows/ntdll.dll under it")
+
+
+def shell_vars(path):
+ """Everything build.sh and apply.py need for one ntdll, as shell assignments."""
+ r = resolve(path)
+ payload = (r['caveRVA'] + 15) & ~15
+ room = r['caveSize'] - (payload - r['caveRVA'])
+ need = PAYLOAD[r['machine']]
+ if room < need:
+ raise SystemExit(f"{path}: cave has {room} bytes at {payload:#x}, payload needs {need}")
+ scratch = 'rsi' if r['wm'] == 'rbx' else 'rbx'
+ out = {
+ 'NP_ARCH': ARCH[r['machine']], 'NP_MACHINE': f"{r['machine']:#x}",
+ 'NP_MAGIC': f"{r['magic']:#x}", 'NP_IMAGEBASE': f"{r['imageBase']:#x}",
+ 'NP_SHA256': r['sha256'],
+ 'NP_HOOK_RVA': f"{r['hookRVA']:#x}", 'NP_STOLEN': r['stolen'],
+ 'NP_STOLEN_BYTES': ','.join(f"0x{b:02x}" for b in bytes.fromhex(r['stolen'])),
+ 'NP_STOLEN_LEN': str(len(r['stolen']) // 2),
+ 'NP_RESUME_VA': f"{r['imageBase'] + r['resume']:#x}",
+ 'NP_WM': r['wm'], 'NP_SCRATCH': scratch,
+ 'NP_LOAD_PATH': f"{r['load_path']:#x}" if r.get('load_path') is not None else '',
+ 'NP_CAVE_RVA': f"{r['caveRVA']:#x}", 'NP_CAVE_SIZE': str(r['caveSize']),
+ 'NP_PAYLOAD_RVA': f"{payload:#x}", 'NP_PAYLOAD_VA': f"{r['imageBase'] + payload:#x}",
+ 'NP_CAVE_ROOM': str(room), 'NP_FILL': f"{r['fill']:#04x}",
+ }
+ if PINNED.get(r['sha256'], {}).get('payload'):
+ out['NP_PAYLOAD_SHA256'] = PINNED[r['sha256']]['payload']
+ if r.get('skip') is not None:
+ out['NP_SKIP_VA'] = f"{r['imageBase'] + r['skip']:#x}"
+ out['NP_STOLE_BRANCH'] = '1' if r['stole_branch'] else ''
+ out['NP_STOLEN_HEAD_BYTES'] = ','.join(
+ f"0x{b:02x}" for b in bytes.fromhex(r['stolen_head']))
+ out['NP_FLAGS_SLOT'] = ('%#x' if r['flags_slot'] >= 0 else '-%#x') % abs(r['flags_slot'])
+
+ for n, s in enumerate(r.get('sites') or [], 1):
+ out[f'NP_HOOK_RVA_{n}'] = f"{s['hookRVA']:#x}"
+ out[f'NP_STOLEN_{n}'] = s['stolen']
+ out[f'NP_RESUME_VA_{n}'] = f"{r['imageBase'] + s['resume']:#x}"
+ out[f'NP_LOAD_PATH_{n}'] = f"{s['load_path']:#x}"
+ if r.get('sites'):
+ out['NP_SITES'] = str(len(r['sites']))
+
+ for n, va in r['exports'].items():
+ out['NP_' + re.sub(r'(?<!^)(?=[A-Z])', '_', n).upper()] = f"{va:#x}"
+ for n, rva in (r.get('guest') or {}).items():
+ out['NP_' + re.sub(r'(?<!^)(?=[A-Z])', '_', n).upper()] = f"{r['imageBase'] + rva:#x}"
+ return out
+
+
+if __name__ == '__main__':
+ if len(sys.argv) < 2:
+ raise SystemExit(f"usage: {sys.argv[0]} [--sh] <CrossOver bundle | wine dir | ntdll.dll> ...")
+ if sys.argv[1] == '--sh':
+ if len(sys.argv) != 3:
+ raise SystemExit("--sh takes one ntdll.dll")
+ for k, v in shell_vars(sys.argv[2]).items():
+ print(f"{k}='{v}'")
+ sys.exit(0)
+ paths = [p for arg in sys.argv[1:] for p in ntdlls(arg)]
+ sys.exit(0 if all([report(p) for p in paths]) else 1)
diff --git a/ntdll-patch/shim.S b/ntdll-patch/shim.S
new file mode 100644
index 0000000..def0cd3
--- /dev/null
+++ b/ntdll-patch/shim.S
@@ -0,0 +1,49 @@
+// Entry shim (GAS/AT&T) for the build_module steamclient64 trampoline detour.
+
+
+ .intel_syntax noprefix
+ .text
+ .globl shim_entry3
+
+shim_entry3:
+ push SCRATCH_REG
+ mov SCRATCH_REG, [rsp + (LOAD_PATH_SLOT + 8)]
+ push rax
+ push rcx
+ push rdx
+ push rsi
+ push rdi
+ push r8
+ push r9
+ push r10
+ push r11
+ // align stack to 16 and reserve shadow + ctx table
+ mov r10, rsp // remember unaligned rsp
+ and rsp, -16
+ sub rsp, 0x60
+ mov [rsp+0x58], r10 // save pre-align rsp for exact restore
+ // ctx table at [rsp+0x38..0x4f]: {get_dll_handle, load_dll, protect}
+ lea rax, [rip + LDR_GETDLLHANDLE]
+ mov [rsp+0x38], rax
+ lea rax, [rip + LDR_LOADDLL]
+ mov [rsp+0x40], rax
+ lea rax, [rip + NT_PROTECT]
+ mov [rsp+0x48], rax
+ // detour_build_module(ctx, wm, load_path)
+ lea rcx, [rsp+0x38] // &ctx
+ mov rdx, WM_REG // wm
+ mov r8, SCRATCH_REG // load_path
+ call detour_build_module
+ mov rsp, [rsp+0x58] // restore pre-align rsp
+ pop r11
+ pop r10
+ pop r9
+ pop r8
+ pop rdi
+ pop rsi
+ pop rdx
+ pop rcx
+ pop rax
+ pop SCRATCH_REG
+ .byte STOLEN_BYTES
+ jmp BM_RESUME
diff --git a/ntdll-patch/shim32.S b/ntdll-patch/shim32.S
new file mode 100644
index 0000000..ba8fbe1
--- /dev/null
+++ b/ntdll-patch/shim32.S
@@ -0,0 +1,44 @@
+// Entry shim for the i386 build_module steamclient detour.
+
+ .intel_syntax noprefix
+ .text
+ .globl shim_entry32
+
+shim_entry32:
+ pushad // eax ecx edx ebx esp ebp esi edi
+ call delta_ref // pushes delta_ref, the next instruction
+delta_ref:
+ pop ecx
+ sub ecx, offset delta_ref // ecx = load base, preferred base
+ mov ebx, ebp // fp; ebx/esi survive the cdecl call
+ mov esi, WM_REG // wm
+ mov edi, esp // pre-align esp, for an exact restore
+ and esp, -16
+ sub esp, 0x30 // [esp+0x00..0x0B] args, [esp+0x0C..0x27] ctx
+ // ctx table: {get_dll_handle, load_dll, protect, open_file, read_file, close, delta}
+ lea eax, [ecx + LDR_GETDLLHANDLE]
+ mov [esp+0x0C], eax
+ lea eax, [ecx + LDR_LOADDLL]
+ mov [esp+0x10], eax
+ lea eax, [ecx + NT_PROTECT]
+ mov [esp+0x14], eax
+ lea eax, [ecx + NT_OPENFILE]
+ mov [esp+0x18], eax
+ lea eax, [ecx + NT_READFILE]
+ mov [esp+0x1C], eax
+ lea eax, [ecx + NT_CLOSE]
+ mov [esp+0x20], eax
+ mov [esp+0x24], ecx
+ // detour_build_module32(ctx, wm, fp), cdecl
+ lea eax, [esp+0x0C]
+ mov [esp+0x00], eax
+ mov [esp+0x04], esi
+ mov [esp+0x08], ebx
+ call _detour_build_module32
+ mov esp, edi
+ popad
+ .byte STOLEN_HEAD_BYTES
+#if STOLE_BRANCH
+ jnz BM_SKIP
+#endif
+ jmp BM_RESUME
diff --git a/ntdll-patch/shim64.S b/ntdll-patch/shim64.S
new file mode 100644
index 0000000..1345ad5
--- /dev/null
+++ b/ntdll-patch/shim64.S
@@ -0,0 +1,62 @@
+// Entry shim for the aarch64/FEX build_module steamclient detour
+
+ .text
+ .globl shim_entry64
+
+ .set S_X18, 0x90
+ .set S_NZCV, 0x98
+ .set S_X30, 0xa0
+ .set S_CTX, 0xb0
+ .set FRAME, 0xd0
+
+// This was unpleasant
+shim_entry64:
+ sub sp, sp, #FRAME
+ stp x0, x1, [sp, #0x00]
+ stp x2, x3, [sp, #0x10]
+ stp x4, x5, [sp, #0x20]
+ stp x6, x7, [sp, #0x30]
+ stp x8, x9, [sp, #0x40]
+ stp x10, x11, [sp, #0x50]
+ stp x12, x13, [sp, #0x60]
+ stp x14, x15, [sp, #0x70]
+ stp x16, x17, [sp, #0x80]
+ mrs x1, nzcv
+ stp x18, x1, [sp, #S_X18]
+ str x30, [sp, #S_X30]
+
+ /* ctx table {get_dll_handle, load_dll, protect} */
+ adrp x8, LDR_GETDLLHANDLE
+ add x8, x8, :lo12:LDR_GETDLLHANDLE
+ adrp x9, LDR_LOADDLL
+ add x9, x9, :lo12:LDR_LOADDLL
+ stp x8, x9, [sp, #S_CTX]
+ adrp x8, NT_PROTECT
+ add x8, x8, :lo12:NT_PROTECT
+ str x8, [sp, #(S_CTX + 16)]
+
+ add x0, sp, #S_CTX
+ ldr x1, [sp, #0x00]
+ adrp x9, BM_RESUME_1
+ add x9, x9, :lo12:BM_RESUME_1
+ cmp x30, x9
+ b.ne 1f
+ ldur x2, [x29, #LOAD_PATH_1]
+ b 2f
+1: ldur x2, [x29, #LOAD_PATH_2]
+2: bl detour_build_module
+
+ ldr x30, [sp, #S_X30]
+ ldp x18, x1, [sp, #S_X18]
+ msr nzcv, x1
+ ldp x16, x17, [sp, #0x80]
+ ldp x14, x15, [sp, #0x70]
+ ldp x12, x13, [sp, #0x60]
+ ldp x10, x11, [sp, #0x50]
+ ldp x8, x9, [sp, #0x40]
+ ldp x6, x7, [sp, #0x30]
+ ldp x4, x5, [sp, #0x20]
+ ldp x2, x3, [sp, #0x10]
+ ldp x0, x1, [sp, #0x00]
+ add sp, sp, #FRAME
+ ret
diff --git a/overlay-shim/overlay_shim.m b/overlay-shim/overlay_shim.m
new file mode 100644
index 0000000..2d2678b
--- /dev/null
+++ b/overlay-shim/overlay_shim.m
@@ -0,0 +1,963 @@
+// Shim for the Steam overlay. This was deeply unpleasant to make,
+// fixes HDR stuff and Metal 4.
+//
+// Metal 4 notes: D3DMetal 4 commits a frame on MTL4CommandQueue and the
+// drawable goes to [drawable present], but Valve's overlay swizzles only the
+// Metal 3 present family. Bridge signalDrawable: to a Metal 3 presentDrawable:
+// on a shared event so the overlay's own hooks see the frame, fixing the
+// issue...
+
+#import <Metal/Metal.h>
+#import <QuartzCore/CAMetalLayer.h>
+
+#import <dlfcn.h>
+#import <mach-o/dyld.h>
+#import <mach-o/getsect.h>
+#import <objc/message.h>
+#import <os/lock.h>
+#import <objc/runtime.h>
+#import <sys/mman.h>
+#import <stdarg.h>
+#import <stdio.h>
+#include <string.h>
+#import <unistd.h>
+
+__attribute__((format(printf, 1, 2)))
+static void shim_log(const char *fmt, ...) {
+ va_list ap;
+ va_start(ap, fmt);
+ vfprintf(stderr, fmt, ap);
+ va_end(ap);
+ fflush(stderr);
+}
+
+// MTLPixelFormat values the overlay handles, plus the one it doesn't
+enum {
+ format_bgra8_unorm = 80,
+ format_bgra8_unorm_srgb = 81,
+ format_rgb10a2_unorm = 90,
+ format_bgr10a2_unorm = 94,
+ format_rgba16_float = 115,
+};
+
+// Make room for the overlay to rebuild its pipeline set several times per session.
+#define max_pipelines 32
+#define max_variants 4
+
+struct variant {
+ NSUInteger format;
+ id state;
+ int logged;
+};
+
+struct pipeline_entry {
+ id state;
+ MTLRenderPipelineDescriptor *descriptor;
+ id<MTLDevice> device;
+ NSUInteger base_format;
+ struct variant variants[max_variants];
+ int variant_count;
+ int unmarked_logged;
+};
+
+static struct pipeline_entry pipelines[max_pipelines];
+static int pipeline_count;
+
+#define max_encoders 32
+
+struct encoder_slot {
+ id encoder;
+ NSUInteger format;
+};
+
+static struct encoder_slot overlay_encoders[max_encoders];
+
+static os_unfair_lock encoder_lock = OS_UNFAIR_LOCK_INIT;
+static int encoder_table_full_logged;
+
+static const char *format_name(NSUInteger format)
+{
+ switch (format) {
+ case 70:
+ return "RGBA8Unorm";
+ case 71:
+ return "RGBA8Unorm_sRGB";
+ case format_bgra8_unorm:
+ return "BGRA8Unorm";
+ case format_bgra8_unorm_srgb:
+ return "BGRA8Unorm_sRGB";
+ case format_rgb10a2_unorm:
+ return "RGB10A2Unorm";
+ case format_bgr10a2_unorm:
+ return "BGR10A2Unorm";
+ case format_rgba16_float:
+ return "RGBA16Float";
+ default:
+ return "other";
+ }
+}
+
+static int overlay_has_pipeline(NSUInteger format)
+{
+ return format == format_bgra8_unorm || format == format_bgra8_unorm_srgb ||
+ format == format_bgr10a2_unorm || format == format_rgba16_float;
+}
+
+static const void *overlay_text_begin;
+static const void *overlay_text_end;
+static const struct mach_header *overlay_header;
+
+static void image_added(const struct mach_header *header, intptr_t slide)
+{
+ (void)slide;
+
+ if (overlay_text_end != NULL)
+ return;
+
+ Dl_info info;
+ if (dladdr(header, &info) == 0 || info.dli_fname == NULL)
+ return;
+
+ const char *slash = strrchr(info.dli_fname, '/');
+ if (strcmp(slash != NULL ? slash + 1 : info.dli_fname, "gameoverlayrenderer.dylib") != 0)
+ return;
+
+ unsigned long size = 0;
+ uint8_t *text = getsegmentdata((const struct mach_header_64 *)header, "__TEXT", &size);
+ if (text == NULL || size == 0)
+ return;
+
+ overlay_header = header;
+ overlay_text_begin = text;
+ overlay_text_end = text + size;
+ shim_log("overlay_shim image_added: overlay text %p-%p\n", overlay_text_begin,
+ overlay_text_end);
+}
+
+static int from_overlay(const void *address)
+{
+ return overlay_text_end != NULL && address >= overlay_text_begin &&
+ address < overlay_text_end;
+}
+
+typedef void (*set_pixel_format_fn)(id, SEL, NSUInteger);
+typedef void (*set_colorspace_fn)(id, SEL, CGColorSpaceRef);
+typedef void (*set_device_fn)(id, SEL, id);
+typedef id (*new_pipeline_fn)(id, SEL, MTLRenderPipelineDescriptor *, NSError **);
+typedef id (*new_queue_fn)(id, SEL);
+typedef id (*new_queue_count_fn)(id, SEL, NSUInteger);
+typedef id (*command_buffer_fn)(id, SEL);
+typedef id (*render_encoder_fn)(id, SEL, MTLRenderPassDescriptor *);
+typedef void (*set_pipeline_state_fn)(id, SEL, id);
+typedef void (*end_encoding_fn)(id, SEL);
+typedef id (*new_mtl4_queue_fn)(id, SEL);
+typedef void (*signal_drawable_fn)(id, SEL, id);
+typedef void (*drawable_present_fn)(id, SEL);
+typedef void (*drawable_present_after_fn)(id, SEL, CFTimeInterval);
+
+static set_pixel_format_fn next_set_pixel_format;
+static set_colorspace_fn next_set_colorspace;
+static set_device_fn next_set_device;
+static new_pipeline_fn next_new_pipeline;
+static new_queue_fn next_new_queue;
+static new_queue_count_fn next_new_queue_count;
+static command_buffer_fn next_command_buffer;
+static command_buffer_fn next_command_buffer_unretained;
+static render_encoder_fn next_render_encoder;
+static set_pipeline_state_fn next_set_pipeline_state;
+static end_encoding_fn next_end_encoding;
+static new_mtl4_queue_fn next_new_mtl4_queue;
+static signal_drawable_fn next_signal_drawable;
+static drawable_present_fn next_drawable_present;
+static drawable_present_after_fn next_drawable_present_after;
+
+// The Metal 3 queue and event used to order an overlay after a Metal 4
+// frame.
+static id<MTLCommandQueue> sync_queue;
+static id<MTLEvent> frame_ready;
+static uint64_t frame_ready_value;
+
+// The drawable D3DMetal signalled, hooks see it
+// Held without a reference because D3DMetal signals and then
+// presents the same drawable in one call, on one thread.
+static id signalled_drawable;
+static uint64_t signalled_value;
+static int mtl4_sync_logged;
+
+static void queue_signal_event(id queue, id event, uint64_t value)
+{
+ typedef void (*signal_event_fn)(id, SEL, id, uint64_t);
+
+ ((signal_event_fn)objc_msgSend)(queue, sel_registerName("signalEvent:value:"), event, value);
+}
+
+static id object_device(id object)
+{
+ typedef id (*device_fn)(id, SEL);
+
+ return ((device_fn)objc_msgSend)(object, sel_registerName("device"));
+}
+
+static int interpose(Class target, const char *selector_name, IMP replacement, IMP *previous)
+{
+ if (target == Nil)
+ return 0;
+
+ Method method = class_getInstanceMethod(target, sel_registerName(selector_name));
+ if (method == NULL)
+ return 0;
+
+ *previous = method_getImplementation(method);
+ method_setImplementation(method, replacement);
+ return 1;
+}
+
+// The overlay swizzles by renaming the original to steamoverlay_<selector>, so the
+// renamed method is what says its hook survived.
+static int class_has_method(Class target, const char *selector_name)
+{
+ return target != Nil &&
+ class_getInstanceMethod(target, sel_registerName(selector_name)) != NULL;
+}
+
+static Class device_class;
+static Class queue_class;
+static Class command_buffer_class;
+static Class encoder_class;
+static Class drawable_class;
+static Class mtl4_queue_class;
+
+static int stage_claimed(Class seen, Class *held, const char *stage)
+{
+ if (*held == seen)
+ return 0;
+
+ if (*held != Nil) {
+ shim_log("overlay_shim stage_claimed: second %s class %s, first was %s\n",
+ stage, class_getName(seen), class_getName(*held));
+ return 0;
+ }
+
+ *held = seen;
+ return 1;
+}
+
+static void encoder_mark(id encoder, NSUInteger format)
+{
+ os_unfair_lock_lock(&encoder_lock);
+ for (int i = 0; i < max_encoders; i++) {
+ if (overlay_encoders[i].encoder != encoder && overlay_encoders[i].encoder != nil)
+ continue;
+
+ overlay_encoders[i].encoder = encoder;
+ overlay_encoders[i].format = format;
+ os_unfair_lock_unlock(&encoder_lock);
+ return;
+ }
+ os_unfair_lock_unlock(&encoder_lock);
+
+ if (!encoder_table_full_logged) {
+ encoder_table_full_logged = 1;
+ shim_log("overlay_shim encoder_mark: table full, a pass is uncorrected\n");
+ }
+}
+
+static void encoder_clear(id encoder)
+{
+ os_unfair_lock_lock(&encoder_lock);
+ for (int i = 0; i < max_encoders; i++) {
+ if (overlay_encoders[i].encoder == encoder) {
+ overlay_encoders[i].encoder = nil;
+ break;
+ }
+ }
+ os_unfair_lock_unlock(&encoder_lock);
+}
+
+static int encoder_format(id encoder, NSUInteger *format)
+{
+ int found = 0;
+
+ os_unfair_lock_lock(&encoder_lock);
+ for (int i = 0; i < max_encoders; i++) {
+ if (overlay_encoders[i].encoder == encoder) {
+ *format = overlay_encoders[i].format;
+ found = 1;
+ break;
+ }
+ }
+ os_unfair_lock_unlock(&encoder_lock);
+ return found;
+}
+
+static struct variant *variant_for(struct pipeline_entry *entry, NSUInteger format)
+{
+ for (int i = 0; i < entry->variant_count; i++) {
+ if (entry->variants[i].format == format)
+ return &entry->variants[i];
+ }
+
+ if (entry->variant_count == max_variants)
+ return NULL;
+
+ // The descriptor is a private copy, but the copy depth of a color
+ // attachment array is unspecified, so the base format is retained
+ entry->descriptor.colorAttachments[0].pixelFormat = (MTLPixelFormat)format;
+ NSError *error = nil;
+ id state = [entry->device newRenderPipelineStateWithDescriptor:entry->descriptor
+ error:&error];
+ entry->descriptor.colorAttachments[0].pixelFormat = (MTLPixelFormat)entry->base_format;
+
+ if (state == nil) {
+ shim_log("overlay_shim variant_for: format %lu (%s) failed: %s\n",
+ (unsigned long)format, format_name(format),
+ error != nil ? [[error localizedDescription] UTF8String] : "no reason given");
+ return NULL;
+ }
+
+ struct variant *slot = &entry->variants[entry->variant_count];
+ slot->format = format;
+ slot->state = [state retain];
+ slot->logged = 0;
+ entry->variant_count++;
+
+ shim_log("overlay_shim variant_for: built %s pipeline for base %s\n",
+ format_name(format), format_name(entry->base_format));
+ return slot;
+}
+
+static void record_overlay_pipeline(id<MTLDevice> device, MTLRenderPipelineDescriptor *descriptor,
+ id state)
+{
+ for (int i = 0; i < pipeline_count; i++) {
+ if (pipelines[i].state == state)
+ return;
+ }
+
+ if (pipeline_count == max_pipelines) {
+ shim_log("overlay_shim record_overlay_pipeline: table full, %s not tracked\n",
+ format_name(descriptor.colorAttachments[0].pixelFormat));
+ return;
+ }
+
+ struct pipeline_entry *entry = &pipelines[pipeline_count];
+ entry->state = [state retain];
+ entry->descriptor = [descriptor copy];
+ entry->device = [device retain];
+ entry->base_format = descriptor.colorAttachments[0].pixelFormat;
+ entry->variant_count = 0;
+ entry->unmarked_logged = 0;
+ pipeline_count++;
+
+ shim_log("overlay_shim record_overlay_pipeline: overlay pipeline %d format %s\n",
+ pipeline_count - 1, format_name(entry->base_format));
+}
+
+static void ensure_encoder_hooks(id encoder);
+static void ensure_command_buffer_hooks(id buffer);
+static void ensure_queue_hooks(id queue);
+static void ensure_device_hooks(id device);
+static void ensure_drawable_hooks(id drawable);
+static void ensure_mtl4_queue_hooks(id queue);
+
+static void hook_set_pixel_format(id layer, SEL selector, NSUInteger format)
+{
+ static NSUInteger last = (NSUInteger)-1;
+
+ if (format != last) {
+ last = format;
+ shim_log(
+ "overlay_shim hook_set_pixel_format: layer=%s format=%lu (%s) overlay_pipeline=%s\n",
+ class_getName(object_getClass(layer)), (unsigned long)format,
+ format_name(format), overlay_has_pipeline(format) ? "present" : "missing");
+ }
+
+ next_set_pixel_format(layer, selector, format);
+ ensure_device_hooks([(CAMetalLayer *)layer device]);
+}
+
+static void hook_set_colorspace(id layer, SEL selector, CGColorSpaceRef colorspace)
+{
+ static CGColorSpaceRef last = (CGColorSpaceRef)-1;
+
+ if (colorspace != last) {
+ last = colorspace;
+
+ char name[128];
+ name[0] = '\0';
+ if (colorspace != NULL) {
+ CFStringRef copied = CGColorSpaceCopyName(colorspace);
+ if (copied != NULL) {
+ CFStringGetCString(copied, name, sizeof(name), kCFStringEncodingUTF8);
+ CFRelease(copied);
+ }
+ }
+ shim_log("overlay_shim hook_set_colorspace: layer=%s colorspace=%s\n",
+ class_getName(object_getClass(layer)), name[0] != '\0' ? name : "none");
+ }
+
+ next_set_colorspace(layer, selector, colorspace);
+}
+
+static void hook_set_device(id layer, SEL selector, id device)
+{
+ next_set_device(layer, selector, device);
+ ensure_device_hooks(device);
+}
+
+static id hook_new_pipeline(id self, SEL selector, MTLRenderPipelineDescriptor *descriptor,
+ NSError **error)
+{
+ id state = next_new_pipeline(self, selector, descriptor, error);
+
+ if (state != nil && descriptor != nil && from_overlay(__builtin_return_address(0)))
+ record_overlay_pipeline(self, descriptor, state);
+
+ return state;
+}
+
+static id hook_new_queue(id self, SEL selector)
+{
+ id queue = next_new_queue(self, selector);
+ ensure_queue_hooks(queue);
+ return queue;
+}
+
+static id hook_new_queue_count(id self, SEL selector, NSUInteger count)
+{
+ id queue = next_new_queue_count(self, selector, count);
+ ensure_queue_hooks(queue);
+ return queue;
+}
+
+static id hook_command_buffer(id self, SEL selector)
+{
+ id buffer = next_command_buffer(self, selector);
+ ensure_command_buffer_hooks(buffer);
+ return buffer;
+}
+
+static id hook_command_buffer_unretained(id self, SEL selector)
+{
+ id buffer = next_command_buffer_unretained(self, selector);
+ ensure_command_buffer_hooks(buffer);
+ return buffer;
+}
+
+static id hook_render_encoder(id self, SEL selector, MTLRenderPassDescriptor *descriptor)
+{
+ int overlay_pass = from_overlay(__builtin_return_address(0));
+ id<MTLTexture> attachment = descriptor != nil ? descriptor.colorAttachments[0].texture : nil;
+ id encoder = next_render_encoder(self, selector, descriptor);
+
+ if (encoder == nil)
+ return encoder;
+
+ ensure_encoder_hooks(encoder);
+
+ if (attachment == nil)
+ return encoder;
+
+ NSUInteger format = attachment.pixelFormat;
+
+ encoder_mark(encoder, format);
+
+ if (!overlay_pass)
+ return encoder;
+ for (int i = 0; i < pipeline_count; i++) {
+ if (pipelines[i].base_format != format)
+ variant_for(&pipelines[i], format);
+ }
+
+ return encoder;
+}
+static void hook_set_pipeline_state(id self, SEL selector, id state)
+{
+ for (int i = 0; i < pipeline_count; i++) {
+ if (pipelines[i].state != state)
+ continue;
+
+ NSUInteger format = 0;
+ if (!encoder_format(self, &format)) {
+ if (!pipelines[i].unmarked_logged) {
+ pipelines[i].unmarked_logged = 1;
+ shim_log(
+ "overlay_shim hook_set_pipeline_state: pipeline %d %s bound on an "
+ "unmarked pass, left alone\n",
+ i, format_name(pipelines[i].base_format));
+ }
+ break;
+ }
+
+ if (format != pipelines[i].base_format) {
+ struct variant *slot = variant_for(&pipelines[i], format);
+ if (slot != NULL) {
+ if (!slot->logged) {
+ slot->logged = 1;
+ shim_log(
+ "overlay_shim hook_set_pipeline_state: pipeline %d %s bound to %s "
+ "attachment, substituted\n",
+ i, format_name(pipelines[i].base_format), format_name(format));
+ }
+ state = slot->state;
+ }
+ }
+ break;
+ }
+
+ next_set_pipeline_state(self, selector, state);
+}
+
+static void hook_end_encoding(id self, SEL selector)
+{
+ encoder_clear(self);
+ next_end_encoding(self, selector);
+}
+static void hook_signal_drawable(id self, SEL selector, id drawable)
+{
+ next_signal_drawable(self, selector, drawable);
+
+ signalled_drawable = nil;
+
+ if (overlay_text_end == NULL || drawable == nil)
+ return;
+
+ id device = object_device(self);
+ if (device == nil)
+ return;
+
+ if (sync_queue == nil) {
+ sync_queue = [(id<MTLDevice>)device newCommandQueue];
+ frame_ready = [(id<MTLDevice>)device newEvent];
+
+ shim_log("overlay_shim hook_signal_drawable: queue=%s event=%s\n",
+ sync_queue != nil ? "created" : "unavailable",
+ frame_ready != nil ? "created" : "unavailable");
+ }
+
+ if (sync_queue == nil || frame_ready == nil || object_device(sync_queue) != device)
+ return;
+
+ signalled_value = ++frame_ready_value;
+ queue_signal_event(self, frame_ready, signalled_value);
+ signalled_drawable = drawable;
+ ensure_drawable_hooks(drawable);
+}
+
+// presentDrawable: is the selector the overlay swizzles, so this
+// is where the dark magic happens.
+static int present_composited(id drawable, CFTimeInterval duration, int timed)
+{
+ if (drawable == nil || drawable != signalled_drawable || sync_queue == nil ||
+ frame_ready == nil)
+ return 0;
+
+ signalled_drawable = nil;
+
+ id<MTLCommandBuffer> buffer = [sync_queue commandBuffer];
+ if (buffer == nil)
+ return 0;
+
+ [buffer encodeWaitForEvent:frame_ready value:signalled_value];
+
+ if (timed)
+ [buffer presentDrawable:(id<CAMetalDrawable>)drawable afterMinimumDuration:duration];
+ else
+ [buffer presentDrawable:(id<CAMetalDrawable>)drawable];
+
+ [buffer commit];
+
+ if (!mtl4_sync_logged) {
+ mtl4_sync_logged = 1;
+ shim_log("overlay_shim present_composited: Metal 4 frame presented through a "
+ "Metal 3 buffer waiting on the frame event, overlay composites in order\n");
+ }
+
+ return 1;
+}
+
+static void hook_drawable_present(id self, SEL selector)
+{
+ if (present_composited(self, 0.0, 0))
+ return;
+
+ next_drawable_present(self, selector);
+}
+
+static void hook_drawable_present_after(id self, SEL selector, CFTimeInterval duration)
+{
+ if (present_composited(self, duration, 1))
+ return;
+
+ next_drawable_present_after(self, selector, duration);
+}
+
+static id hook_new_mtl4_queue(id self, SEL selector)
+{
+ id queue = next_new_mtl4_queue(self, selector);
+
+ ensure_mtl4_queue_hooks(queue);
+ return queue;
+}
+
+static void ensure_encoder_hooks(id encoder)
+{
+ if (encoder == nil || !stage_claimed(object_getClass(encoder), &encoder_class, "encoder"))
+ return;
+
+ int hooked = interpose(encoder_class, "setRenderPipelineState:", (IMP)hook_set_pipeline_state,
+ (IMP *)&next_set_pipeline_state);
+ hooked += interpose(encoder_class, "endEncoding", (IMP)hook_end_encoding,
+ (IMP *)&next_end_encoding);
+
+ shim_log("overlay_shim ensure_encoder_hooks: %s hooks=%d\n",
+ class_getName(encoder_class), hooked);
+}
+
+static void ensure_command_buffer_hooks(id buffer)
+{
+ if (buffer == nil ||
+ !stage_claimed(object_getClass(buffer), &command_buffer_class, "command buffer"))
+ return;
+
+ int hooked = interpose(command_buffer_class, "renderCommandEncoderWithDescriptor:",
+ (IMP)hook_render_encoder, (IMP *)&next_render_encoder);
+
+ shim_log("overlay_shim ensure_command_buffer_hooks: %s hooks=%d overlay_commit=%s\n",
+ class_getName(command_buffer_class), hooked,
+ class_has_method(command_buffer_class, "steamoverlay_commit") ? "present" : "missing");
+}
+
+static void ensure_queue_hooks(id queue)
+{
+ if (queue == nil || !stage_claimed(object_getClass(queue), &queue_class, "queue"))
+ return;
+
+ int hooked = interpose(queue_class, "commandBuffer", (IMP)hook_command_buffer,
+ (IMP *)&next_command_buffer);
+ hooked += interpose(queue_class, "commandBufferWithUnretainedReferences",
+ (IMP)hook_command_buffer_unretained,
+ (IMP *)&next_command_buffer_unretained);
+
+ shim_log("overlay_shim ensure_queue_hooks: %s hooks=%d\n", class_getName(queue_class),
+ hooked);
+}
+
+static void ensure_drawable_hooks(id drawable)
+{
+ if (drawable == nil || !stage_claimed(object_getClass(drawable), &drawable_class, "drawable"))
+ return;
+
+ int hooked = interpose(drawable_class, "present", (IMP)hook_drawable_present,
+ (IMP *)&next_drawable_present);
+ hooked += interpose(drawable_class, "presentAfterMinimumDuration:",
+ (IMP)hook_drawable_present_after, (IMP *)&next_drawable_present_after);
+
+ shim_log("overlay_shim ensure_drawable_hooks: %s hooks=%d\n",
+ class_getName(drawable_class), hooked);
+}
+
+static void ensure_mtl4_queue_hooks(id queue)
+{
+ if (queue == nil || !stage_claimed(object_getClass(queue), &mtl4_queue_class, "mtl4 queue"))
+ return;
+
+ int hooked = interpose(mtl4_queue_class, "signalDrawable:", (IMP)hook_signal_drawable,
+ (IMP *)&next_signal_drawable);
+
+ shim_log("overlay_shim ensure_mtl4_queue_hooks: %s hooks=%d\n",
+ class_getName(mtl4_queue_class), hooked);
+}
+
+static void ensure_device_hooks(id device)
+{
+ if (device == nil || !stage_claimed(object_getClass(device), &device_class, "device"))
+ return;
+
+ int hooked = interpose(device_class, "newRenderPipelineStateWithDescriptor:error:",
+ (IMP)hook_new_pipeline, (IMP *)&next_new_pipeline);
+ hooked += interpose(device_class, "newCommandQueue", (IMP)hook_new_queue,
+ (IMP *)&next_new_queue);
+ hooked += interpose(device_class, "newCommandQueueWithMaxCommandBufferCount:",
+ (IMP)hook_new_queue_count, (IMP *)&next_new_queue_count);
+ hooked += interpose(device_class, "newMTL4CommandQueue", (IMP)hook_new_mtl4_queue,
+ (IMP *)&next_new_mtl4_queue);
+
+ shim_log("overlay_shim ensure_device_hooks: %s hooks=%d\n", class_getName(device_class),
+ hooked);
+}
+
+// Device hooks have to be in place before D3DMetal builds its command queues,
+// which D3DMCommandQueue does at CreateCommandQueue
+static id shim_MTLCreateSystemDefaultDevice(void)
+{
+ id device = MTLCreateSystemDefaultDevice();
+
+ ensure_device_hooks(device);
+ return device;
+}
+
+static NSArray<id<MTLDevice>> *shim_MTLCopyAllDevices(void)
+{
+ NSArray<id<MTLDevice>> *devices = MTLCopyAllDevices();
+
+ for (id device in devices)
+ ensure_device_hooks(device);
+
+ return devices;
+}
+
+__attribute__((used, section("__DATA,__interpose"))) static const struct {
+ const void *replacement;
+ const void *original;
+} device_interposes[] = {
+ { (const void *)shim_MTLCreateSystemDefaultDevice,
+ (const void *)MTLCreateSystemDefaultDevice },
+ { (const void *)shim_MTLCopyAllDevices, (const void *)MTLCopyAllDevices },
+};
+
+struct interpose_pair {
+ const void *replacement;
+ const void *replacee;
+};
+
+static int store_pointer(const void **slot, const void *value)
+{
+ long page_size = getpagesize();
+ void *page = (void *)((uintptr_t)slot & ~(uintptr_t)(page_size - 1));
+
+ if (mprotect(page, (size_t)page_size, PROT_READ | PROT_WRITE) != 0)
+ return 0;
+
+ *slot = value;
+ return 1;
+}
+
+static int rebind_image(const struct mach_header *header, intptr_t slide,
+ const struct interpose_pair *pairs, unsigned long count)
+{
+ if (header == NULL || header->magic != MH_MAGIC_64)
+ return 0;
+
+ const struct mach_header_64 *header64 = (const struct mach_header_64 *)header;
+ const struct load_command *command = (const struct load_command *)(header64 + 1);
+ int rebound = 0;
+
+ for (uint32_t i = 0; i < header64->ncmds; i++) {
+ if (command->cmd == LC_SEGMENT_64) {
+ const struct segment_command_64 *segment =
+ (const struct segment_command_64 *)command;
+ const struct section_64 *section = (const struct section_64 *)(segment + 1);
+
+ for (uint32_t j = 0; j < segment->nsects; j++, section++) {
+ uint32_t type = section->flags & SECTION_TYPE;
+
+ if (type != S_LAZY_SYMBOL_POINTERS &&
+ type != S_NON_LAZY_SYMBOL_POINTERS)
+ continue;
+
+ const void **slots = (const void **)(section->addr + slide);
+
+ for (uint64_t k = 0; k < section->size / sizeof(*slots); k++) {
+ for (unsigned long p = 0; p < count; p++) {
+ if (slots[k] != pairs[p].replacee)
+ continue;
+ if (store_pointer(&slots[k], pairs[p].replacement))
+ rebound++;
+ break;
+ }
+ }
+ }
+ }
+
+ command = (const struct load_command *)((const char *)command + command->cmdsize);
+ }
+
+ return rebound;
+}
+
+static const void *overlay_replacement(const struct interpose_pair *pairs, unsigned long count,
+ const char *symbol)
+{
+ const void *target = dlsym(RTLD_DEFAULT, symbol);
+
+ if (target == NULL)
+ return NULL;
+
+ for (unsigned long i = 0; i < count; i++)
+ if (pairs[i].replacee == target)
+ return pairs[i].replacement;
+
+ return NULL;
+}
+
+static void announce_through_wrapper(const struct interpose_pair *pairs, unsigned long count)
+{
+ typedef int32_t (*run_in_mode)(CFStringRef, CFTimeInterval, Boolean);
+
+ const void *replacement = overlay_replacement(pairs, count, "CFRunLoopRunInMode");
+
+ if (replacement == NULL) {
+ shim_log("overlay_shim announce_through_wrapper: no runloop entry in table\n");
+ return;
+ }
+
+ ((run_in_mode)replacement)(CFSTR("com.notproton.overlay.announce"), 0.0, true);
+ shim_log("overlay_shim announce_through_wrapper: announced\n");
+}
+
+typedef int (*cgl_flush_fn)(void *);
+
+static cgl_flush_fn overlay_cgl_flush;
+static void (*next_flush_buffer)(id, SEL);
+
+static void hook_flush_buffer(id context, SEL selector)
+{
+ typedef void *(*cgl_context_fn)(id, SEL);
+
+ void *cgl = ((cgl_context_fn)objc_msgSend)(context, sel_registerName("CGLContextObj"));
+
+ if (overlay_cgl_flush != NULL && cgl != NULL) {
+ overlay_cgl_flush(cgl);
+ return;
+ }
+
+ next_flush_buffer(context, selector);
+}
+
+static void adopt_overlay_gl_present(const struct interpose_pair *pairs, unsigned long count)
+{
+ overlay_cgl_flush = (cgl_flush_fn)overlay_replacement(pairs, count, "CGLFlushDrawable");
+
+ int hooked = 0;
+ if (overlay_cgl_flush != NULL)
+ hooked = interpose(objc_getClass("NSOpenGLContext"), "flushBuffer",
+ (IMP)hook_flush_buffer, (IMP *)&next_flush_buffer);
+
+ shim_log("overlay_shim adopt_overlay_gl_present: replacement=%s flushBuffer=%s\n",
+ overlay_cgl_flush != NULL ? "found" : "missing", hooked ? "hooked" : "missed");
+}
+
+static void apply_overlay_interposes(void)
+{
+ if (overlay_header == NULL)
+ return;
+
+ unsigned long size = 0;
+ const struct interpose_pair *pairs =
+ (const struct interpose_pair *)getsectiondata(
+ (const struct mach_header_64 *)overlay_header, "__DATA", "__interpose",
+ &size);
+
+ if (pairs == NULL || size < sizeof(*pairs)) {
+ shim_log("overlay_shim apply_overlay_interposes: overlay has no table\n");
+ return;
+ }
+
+ unsigned long count = size / sizeof(*pairs);
+ uint32_t images = _dyld_image_count();
+ int rebound = 0;
+
+ for (uint32_t i = 0; i < images; i++) {
+ const struct mach_header *header = _dyld_get_image_header(i);
+
+ if (header == overlay_header)
+ continue;
+
+ rebound += rebind_image(header, _dyld_get_image_vmaddr_slide(i), pairs, count);
+ }
+
+ shim_log("overlay_shim apply_overlay_interposes: %lu entries, %d pointers\n", count,
+ rebound);
+
+ announce_through_wrapper(pairs, count);
+ adopt_overlay_gl_present(pairs, count);
+}
+
+static id stub_init(id self, SEL selector)
+{
+ (void)selector;
+ return self;
+}
+
+static void kick_renderer_metal_hooks(void)
+{
+ Class app_class = objc_getClass("NSApplication");
+ if (app_class == Nil)
+ return;
+
+ Method renamed = class_getInstanceMethod(app_class, sel_registerName("steammetalhook_init"));
+ if (renamed == NULL) {
+ shim_log("overlay_shim kick_renderer_metal_hooks: init is not swizzled\n");
+ return;
+ }
+
+ id *app_slot = (id *)dlsym(RTLD_DEFAULT, "NSApp");
+ id app = app_slot != NULL ? *app_slot : nil;
+ if (app == nil) {
+ shim_log("overlay_shim kick_renderer_metal_hooks: no application yet\n");
+ return;
+ }
+
+ IMP original = method_setImplementation(renamed, (IMP)stub_init);
+ ((id (*)(id, SEL))objc_msgSend)(app, sel_registerName("init"));
+ method_setImplementation(renamed, original);
+
+ shim_log("overlay_shim kick_renderer_metal_hooks: drove init on %s\n",
+ class_getName(object_getClass(app)));
+}
+
+static int next_drawable_logged;
+static id (*next_layer_drawable)(id, SEL);
+
+static id hook_next_drawable(id layer, SEL selector)
+{
+ id drawable = next_layer_drawable(layer, selector);
+
+ if (!next_drawable_logged) {
+ next_drawable_logged = 1;
+ shim_log("overlay_shim hook_next_drawable: layer=%s drawable=%s\n",
+ class_getName(object_getClass(layer)), drawable != nil ? "yes" : "no");
+ }
+
+ return drawable;
+}
+
+static void report_renderer_chain(void)
+{
+ Class layer = objc_getClass("CAMetalLayer");
+
+ shim_log("overlay_shim report_renderer_chain: drawable_swizzle=%s\n",
+ class_has_method(layer, "steamoverlay_nextDrawable") ? "present" : "missing");
+
+ interpose(layer, "nextDrawable", (IMP)hook_next_drawable, (IMP *)&next_layer_drawable);
+}
+
+// FEX specific stuff
+__attribute__((visibility("default"))) void np_overlay_shim_install(void)
+{
+ ensure_device_hooks(MTLCreateSystemDefaultDevice());
+ apply_overlay_interposes();
+ kick_renderer_metal_hooks();
+ report_renderer_chain();
+}
+
+__attribute__((constructor)) static void overlay_shim_load(void)
+{
+ Class layer = objc_getClass("CAMetalLayer");
+ if (layer == Nil) {
+ shim_log("overlay_shim_load: CAMetalLayer absent, nothing to correct\n");
+ return;
+ }
+
+ _dyld_register_func_for_add_image(image_added);
+
+ int hooked = interpose(layer, "setPixelFormat:", (IMP)hook_set_pixel_format,
+ (IMP *)&next_set_pixel_format);
+ hooked += interpose(layer, "setColorspace:", (IMP)hook_set_colorspace,
+ (IMP *)&next_set_colorspace);
+ hooked += interpose(layer, "setDevice:", (IMP)hook_set_device, (IMP *)&next_set_device);
+
+ shim_log("overlay_shim_load: pid=%d exe=%s layer_hooks=%d overlay=%s\n", getpid(),
+ getprogname(), hooked, overlay_text_end != NULL ? "present" : "absent");
+}
diff --git a/overlay-shim/tests/bridge.m b/overlay-shim/tests/bridge.m
new file mode 100644
index 0000000..2a019d7
--- /dev/null
+++ b/overlay-shim/tests/bridge.m
@@ -0,0 +1,53 @@
+#import <Metal/Metal.h>
+#import <objc/message.h>
+#import <objc/runtime.h>
+#import <unistd.h>
+
+#import "check.h"
+
+typedef id (*new_fn)(id, SEL);
+typedef id (*dev_fn)(id, SEL);
+typedef void (*sig_fn)(id, SEL, id, uint64_t);
+
+// The overlay hooks Metal 3 present, but D3DMetal 4 presents on a Metal 4
+// queue, so this has to bridge the two with a shared event.
+int main(void)
+{
+ alarm(30);
+
+ id<MTLDevice> device = MTLCreateSystemDefaultDevice();
+ SKIP_IF(device == nil, "no Metal device on this machine");
+
+ SEL new_mtl4 = sel_registerName("newMTL4CommandQueue");
+ SKIP_IF(![device respondsToSelector:new_mtl4], "the Metal 4 interfaces are not on this system");
+
+ id<MTLCommandQueue> mtl3 = [device newCommandQueue];
+ id mtl4 = ((new_fn)objc_msgSend)(device, new_mtl4);
+ id<MTLEvent> event = [device newEvent];
+ CHECK(mtl3 != nil, "newCommandQueue came back nil");
+ CHECK(mtl4 != nil, "newMTL4CommandQueue came back nil");
+ CHECK(event != nil, "newEvent came back nil");
+
+ // object_device() in the shim reads this to pair a queue
+ id d3 = ((dev_fn)objc_msgSend)(mtl3, sel_registerName("device"));
+ id d4 = ((dev_fn)objc_msgSend)(mtl4, sel_registerName("device"));
+ CHECK(d3 == (id)device, "the mtl3 queue reports device %p, not %p", (void *)d3, (void *)device);
+ CHECK(d4 == (id)device, "the mtl4 queue reports device %p, not %p", (void *)d4, (void *)device);
+
+ ((sig_fn)objc_msgSend)(mtl4, sel_registerName("signalEvent:value:"), event, 1);
+
+ id<MTLCommandBuffer> buffer = [mtl3 commandBuffer];
+ [buffer encodeWaitForEvent:event value:1];
+ [buffer commit];
+ [buffer waitUntilCompleted];
+
+ CHECK([buffer status] == MTLCommandBufferStatusCompleted,
+ "the mtl3 buffer ended at status %ld waiting on an mtl4 signal",
+ (long)[buffer status]);
+ CHECK([buffer error] == nil, "the mtl3 buffer failed: %s",
+ [[[buffer error] localizedDescription] UTF8String]);
+
+ printf("an mtl4 signal released an mtl3 buffer on %s\n",
+ class_getName(object_getClass(device)));
+ return 0;
+}
diff --git a/overlay-shim/tests/check.h b/overlay-shim/tests/check.h
new file mode 100644
index 0000000..8b84513
--- /dev/null
+++ b/overlay-shim/tests/check.h
@@ -0,0 +1,28 @@
+#ifndef NP_OVERLAY_TEST_CHECK_H
+#define NP_OVERLAY_TEST_CHECK_H
+
+#include <stdio.h>
+
+#define NP_SKIP 3
+
+#define CHECK(cond, ...) \
+ do { \
+ if (!(cond)) { \
+ printf("FAIL: "); \
+ printf(__VA_ARGS__); \
+ printf("\n"); \
+ return 1; \
+ } \
+ } while (0)
+
+#define SKIP_IF(cond, ...) \
+ do { \
+ if (cond) { \
+ printf("SKIP: "); \
+ printf(__VA_ARGS__); \
+ printf("\n"); \
+ return NP_SKIP; \
+ } \
+ } while (0)
+
+#endif
diff --git a/overlay-shim/tests/delivery.m b/overlay-shim/tests/delivery.m
new file mode 100644
index 0000000..43d7baa
--- /dev/null
+++ b/overlay-shim/tests/delivery.m
@@ -0,0 +1,63 @@
+#import <objc/runtime.h>
+
+#import <dlfcn.h>
+#import <stdlib.h>
+
+#import "check.h"
+
+// for FEX CrossOver, lsteamclient loads the shim by hand
+static int delivery_by_dlopen(void)
+{
+ const char *path = getenv("NOTPROTON_OVERLAY_SHIM");
+
+ SKIP_IF(path == NULL, "NOTPROTON_OVERLAY_SHIM names the shim to load");
+
+ void *shim = dlopen(path, RTLD_NOW | RTLD_LOCAL);
+ CHECK(shim != NULL, "%s does not load: %s", path, dlerror());
+
+ void (*install)(void) = (void (*)(void))dlsym(shim, "np_overlay_shim_install");
+ CHECK(install != NULL, "%s exports no np_overlay_shim_install", path);
+
+ install();
+ printf("%-14s %s\n", "delivery", "dlopen, dlsym, install");
+
+ return 0;
+}
+
+
+static int gl_present_handle(void)
+{
+ void *gl = dlopen("/System/Library/Frameworks/OpenGL.framework/OpenGL",
+ RTLD_LAZY | RTLD_LOCAL);
+
+ CHECK(gl != NULL, "OpenGL does not load: %s", dlerror());
+
+ void *appkit = dlopen("/System/Library/Frameworks/AppKit.framework/AppKit",
+ RTLD_LAZY | RTLD_LOCAL);
+
+ CHECK(appkit != NULL, "AppKit does not load: %s", dlerror());
+
+ Class context = objc_getClass("NSOpenGLContext");
+
+ CHECK(context != NULL, "AppKit carries no NSOpenGLContext");
+ CHECK(class_getInstanceMethod(context, sel_registerName("flushBuffer")) != NULL,
+ "NSOpenGLContext carries no flushBuffer to stand in for");
+ CHECK(class_getInstanceMethod(context, sel_registerName("CGLContextObj")) != NULL,
+ "NSOpenGLContext carries no CGLContextObj");
+ CHECK(dlsym(RTLD_DEFAULT, "CGLFlushDrawable") != NULL,
+ "CGLFlushDrawable has no address for the interpose table to match");
+
+ printf("%-14s %s\n", "gl present", "NSOpenGLContext flushBuffer");
+
+ return 0;
+}
+
+int main(void)
+{
+ int rc = delivery_by_dlopen();
+
+ if (rc != 0)
+ return rc;
+
+ return gl_present_handle();
+}
diff --git a/overlay-shim/tests/device.m b/overlay-shim/tests/device.m
new file mode 100644
index 0000000..2c8f9a1
--- /dev/null
+++ b/overlay-shim/tests/device.m
@@ -0,0 +1,96 @@
+#import <Metal/Metal.h>
+#import <QuartzCore/CAMetalLayer.h>
+#import <objc/message.h>
+#import <objc/runtime.h>
+
+#import "check.h"
+
+typedef id (*new_queue_fn)(id, SEL);
+
+
+static int absent_selectors(Class target, const char *stage, const char *const *selectors)
+{
+ int gone = 0;
+
+ for (int i = 0; selectors[i] != NULL; i++) {
+ if (class_getInstanceMethod(target, sel_registerName(selectors[i])) != NULL)
+ continue;
+
+ printf("FAIL: %s class %s carries no %s\n", stage, class_getName(target),
+ selectors[i]);
+ gone++;
+ }
+
+ if (gone == 0)
+ printf("%-14s %s\n", stage, class_getName(target));
+
+ return gone;
+}
+
+int main(void)
+{
+ static const char *const device_selectors[] = {
+ "newRenderPipelineStateWithDescriptor:error:", "newCommandQueue",
+ "newCommandQueueWithMaxCommandBufferCount:", "newMTL4CommandQueue", NULL
+ };
+ static const char *const queue_selectors[] = {
+ "commandBuffer", "commandBufferWithUnretainedReferences", "device", NULL
+ };
+ static const char *const buffer_selectors[] = { "renderCommandEncoderWithDescriptor:", NULL };
+ static const char *const encoder_selectors[] = { "setRenderPipelineState:", "endEncoding", NULL };
+ static const char *const mtl4_selectors[] = { "signalDrawable:", "signalEvent:value:", NULL };
+ static const char *const layer_selectors[] = { "setPixelFormat:", "setColorspace:", "setDevice:", NULL };
+
+ id<MTLDevice> device = MTLCreateSystemDefaultDevice();
+ SKIP_IF(device == nil, "no Metal device on this machine");
+
+ SEL new_mtl4 = sel_registerName("newMTL4CommandQueue");
+ SKIP_IF(![device respondsToSelector:new_mtl4], "the Metal 4 interfaces are not on this system");
+
+ id<MTLCommandQueue> queue = [device newCommandQueue];
+ CHECK(queue != nil, "newCommandQueue came back nil");
+
+ id<MTLCommandBuffer> buffer = [queue commandBuffer];
+ CHECK(buffer != nil, "commandBuffer came back nil");
+
+ MTLTextureDescriptor *td = [MTLTextureDescriptor
+ texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
+ width:16
+ height:16
+ mipmapped:NO];
+ td.usage = MTLTextureUsageRenderTarget;
+ id<MTLTexture> target = [device newTextureWithDescriptor:td];
+ CHECK(target != nil, "newTextureWithDescriptor: came back nil");
+
+ MTLRenderPassDescriptor *rp = [MTLRenderPassDescriptor renderPassDescriptor];
+ rp.colorAttachments[0].texture = target;
+ id<MTLRenderCommandEncoder> encoder = [buffer renderCommandEncoderWithDescriptor:rp];
+ CHECK(encoder != nil, "renderCommandEncoderWithDescriptor: came back nil");
+
+ id mtl4 = ((new_queue_fn)objc_msgSend)(device, new_mtl4);
+ CHECK(mtl4 != nil, "newMTL4CommandQueue came back nil");
+
+ int gone = 0;
+ gone += absent_selectors(object_getClass(device), "device", device_selectors);
+ gone += absent_selectors(object_getClass(queue), "mtl3 queue", queue_selectors);
+ gone += absent_selectors(object_getClass(buffer), "buffer", buffer_selectors);
+ gone += absent_selectors(object_getClass(encoder), "encoder", encoder_selectors);
+ gone += absent_selectors(object_getClass(mtl4), "mtl4 queue", mtl4_selectors);
+ gone += absent_selectors([CAMetalLayer class], "layer", layer_selectors);
+
+ [encoder endEncoding];
+
+ Class again3 = object_getClass([device newCommandQueue]);
+ CHECK(again3 == object_getClass(queue), "two mtl3 queues, classes %s and %s",
+ class_getName(object_getClass(queue)), class_getName(again3));
+
+ Class again4 = object_getClass(((new_queue_fn)objc_msgSend)(device, new_mtl4));
+ CHECK(again4 == object_getClass(mtl4), "two mtl4 queues, classes %s and %s",
+ class_getName(object_getClass(mtl4)), class_getName(again4));
+
+ CHECK(object_getClass(mtl4) != object_getClass(queue),
+ "one class %s backs both queue kinds, so hooking one hooks the other",
+ class_getName(object_getClass(queue)));
+
+ return gone == 0 ? 0 : 1;
+}
diff --git a/overlay-shim/tests/passbench.m b/overlay-shim/tests/passbench.m
new file mode 100644
index 0000000..9e6416c
--- /dev/null
+++ b/overlay-shim/tests/passbench.m
@@ -0,0 +1,44 @@
+#import <Metal/Metal.h>
+#import <stdio.h>
+#import <mach/mach_time.h>
+
+#define BATCHES 200
+#define PASSES 200
+
+int main(void)
+{
+ id<MTLDevice> device = MTLCreateSystemDefaultDevice();
+ id<MTLCommandQueue> queue = [device newCommandQueue];
+
+ MTLTextureDescriptor *td = [MTLTextureDescriptor
+ texture2DDescriptorWithPixelFormat:MTLPixelFormatRGB10A2Unorm
+ width:64
+ height:64
+ mipmapped:NO];
+ td.usage = MTLTextureUsageRenderTarget;
+ id<MTLTexture> target = [device newTextureWithDescriptor:td];
+
+ MTLRenderPassDescriptor *rp = [MTLRenderPassDescriptor renderPassDescriptor];
+ rp.colorAttachments[0].texture = target;
+ rp.colorAttachments[0].loadAction = MTLLoadActionLoad;
+ rp.colorAttachments[0].storeAction = MTLStoreActionStore;
+
+ mach_timebase_info_data_t tb;
+ mach_timebase_info(&tb);
+
+ uint64_t start = mach_absolute_time();
+ for (int b = 0; b < BATCHES; b++) {
+ id<MTLCommandBuffer> cb = [queue commandBuffer];
+ for (int i = 0; i < PASSES; i++) {
+ id<MTLRenderCommandEncoder> e = [cb renderCommandEncoderWithDescriptor:rp];
+ [e endEncoding];
+ }
+ [cb commit];
+ }
+ uint64_t elapsed = mach_absolute_time() - start;
+
+ double ns = (double)elapsed * tb.numer / tb.denom;
+ printf("passbench: %d passes in %.2f ms = %.0f ns/pass\n", BATCHES * PASSES,
+ ns / 1e6, ns / (BATCHES * PASSES));
+ return 0;
+}
diff --git a/signatures/macos.arm64/1788400362.json b/signatures/macos.arm64/1788400362.json
new file mode 100644
index 0000000..009b37a
--- /dev/null
+++ b/signatures/macos.arm64/1788400362.json
@@ -0,0 +1,172 @@
+{
+ "schema_version": 3,
+ "profile_version": 1,
+ "arch": "arm64",
+ "platform": "macos",
+ "steam_build": 1788400362,
+ "steam_build_date": "",
+ "signatures": [
+ {
+ "name": "CCompatManager::Init",
+ "aob_hex": "?? ?? ?? D1 FC 6F 0B A9 FA 67 0C A9 F8 5F 0D A9 F6 57 0E A9 F4 4F 0F A9 FD 7B 10 A9 FD 03 04 91 F4 03 01 AA F3 03 00 AA ?? ?? ?? ?? 08 A9 40 F9 08 01 40 F9 ?? ?? ?? ?? 29 01 28 91 A8 03 1A F8 09 00 00 F9 F9 03 00 AA 3F 8F 00 F8 1F 08 00 F9",
+ "func_addr_this_build": "0x690f6c",
+ "anchor": {
+ "kind": "string",
+ "value": "STEAM_COMPAT_TOOL_MAPPINGS"
+ }
+ },
+ {
+ "name": "CCompatManager::BIsCompatibilityToolEnabled",
+ "aob_hex": "FF 03 01 D1 F4 4F 02 A9 FD 7B 03 A9 ?? ?? ?? ?? F4 03 01 AA F3 03 00 AA E1 17 00 B9 ?? ?? ?? ?? 08 0D 40 F9 08 01 40 B9 E8 00 00 34 ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? 81 00 80 52 ?? ?? ?? ??",
+ "func_addr_this_build": "0x6962f0",
+ "anchor": {
+ "kind": "string",
+ "value": "CCompatManager::BIsCompatibilityToolEnabled"
+ }
+ },
+ {
+ "name": "CCompatManager::YldRegisterTool",
+ "aob_hex": "88 3E 40 F9 1F 01 00 F1 56 03 88 9A E0 03 16 AA ?? ?? ?? 94 E8 03 00 AA 89 22 40 F9 3F 01 00 F1 40 03 89 9A 88 00 00 34",
+ "func_addr_this_build": "0x699f00",
+ "match_offset": 168,
+ "anchor": {
+ "kind": "string",
+ "value": "CCompatManager::YldRegisterTool"
+ }
+ },
+ {
+ "name": "CCompatManager::GetOSListOverrideForApp.oslist_gate",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695ed0",
+ "aob_hex": "E0 03 14 AA ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? A8 3A 40 F9 1F 01 00 F1 C8 02 88 9A 68 02 00 F9 33 00 80 52",
+ "anchor": {
+ "kind": "insn_pair_in_fn",
+ "value": "pTool != nullptr",
+ "nth_xref": 1,
+ "pair": {
+ "first": "0x94000000",
+ "first_mask": "0xFC000000",
+ "second": "0xB4000000",
+ "second_mask": "0xFF00001F",
+ "tie_mask": "0x0",
+ "land": "second"
+ }
+ }
+ },
+ {
+ "name": "CCompatManager::ResolveCompatToolForApp.local_redirect",
+ "match_offset": -8,
+ "func_addr_this_build": "0x695fc4",
+ "aob_hex": "80 02 40 F9 ?? ?? ?? ?? 01 60 40 B9 ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? 08 01 40 F9 09 30 82 52 00 01 09 8B 02 00 80 52 ?? ?? ?? ??",
+ "anchor": {
+ "kind": "insn_pair_in_fn",
+ "value": "GetAppInstallDir failed for tool %u \"%s\"",
+ "pair": {
+ "first": "0xB9400000",
+ "first_mask": "0xFFC003E0",
+ "second": "0x34000000",
+ "second_mask": "0xFF000000",
+ "tie_mask": "0x1F",
+ "land": "first"
+ }
+ }
+ },
+ {
+ "name": "CAppManager::TerminateProcessByPid",
+ "aob_hex": "F4 4F BE A9 FD 7B 01 A9 FD 43 00 91 F3 03 00 AA ?? ?? ?? ?? F4 03 00 AA ?? ?? ?? ?? 00 F9 45 F9 E2 03 13 AA ?? ?? ?? ?? ?? ?? ?? ?? F3 03 00 AA",
+ "func_addr_this_build": "0xd6f28",
+ "anchor": {
+ "kind": "string",
+ "value": "terminate",
+ "indirect": true,
+ "caller_hops": 1
+ }
+ },
+ {
+ "name": "CCompatManager::FindToolForTargetApp",
+ "aob_hex": "FF 83 01 D1 F6 57 03 A9 F4 4F 04 A9 FD 7B 05 A9 FD 43 01 91 A1 C3 1D B8 08 C0 5E 39 1F 05 00 71 ?? ?? ?? ?? F4 03 01 AA F3 03 00 AA ?? ?? ?? ?? 08 21 38 91 15 01 40 F9 16 07 82 52 A0 02 16 8B ?? ?? ?? ?? A0 02 16 8B E1 03 14 AA ?? ?? ?? ??",
+ "func_addr_this_build": "0x69577c",
+ "anchor": {
+ "kind": "string",
+ "value": "FindToolForTargetApp matched with itself - ignoring: %u %s"
+ }
+ },
+ {
+ "name": "CCompatManager::GetValidPlatforms",
+ "aob_hex": "FF 03 01 D1 F6 57 01 A9 F4 4F 02 A9 FD 7B 03 A9 FD C3 00 91 F4 03 01 AA F6 03 00 AA ?? ?? ?? ?? 08 21 38 91 13 01 40 F9 15 07 82 52 60 02 15 8B ?? ?? ?? ?? 60 02 15 8B E1 03 14 AA 22 00 80 52 ?? ?? ?? ?? ?? ?? ?? ?? F5 03 00 AA ?? ?? ?? ??",
+ "func_addr_this_build": "0x69457c",
+ "anchor": {
+ "kind": "string",
+ "value": "AppID %u does not advertise linux as a supported platform, but a linux specific depot is present.\n"
+ }
+ },
+ {
+ "name": "CWebUIJobDispatcher::RegisterHandler",
+ "func_addr_this_build": "0x8da10",
+ "aob_hex": "FF C3 00 D1 F4 4F 01 A9 FD 7B 02 A9 FD 83 00 91 F4 03 01 AA F3 03 00 AA 28 00 40 F9 08 01 40 F9",
+ "anchor": {
+ "kind": "string",
+ "value": "WebUI method '%s' has already been registered. Skipping duplicate registration"
+ }
+ },
+ {
+ "name": "CWebUITransport::DispatchJob",
+ "func_addr_this_build": "0x8dc14",
+ "aob_hex": "FF 43 07 D1 FC 6F 19 A9 F6 57 1A A9 F4 4F 1B A9 FD 7B 1C A9 FD 03 07 91 F4 03 01 AA F3 03 00 AA",
+ "anchor": {
+ "kind": "string",
+ "value": "no handler for message: %s"
+ }
+ },
+ {
+ "name": "CWebUIMsgJob::SendResponse",
+ "func_addr_this_build": "0x8e0ec",
+ "aob_hex": "FF C3 00 D1 F4 4F 01 A9 FD 7B 02 A9 FD 83 00 91 F3 03 01 AA F4 03 00 AA 20 0C 40 F9 E0 06 00 B4",
+ "anchor": {
+ "kind": "string",
+ "value": "CWebUIMsgJob: failed to send response for job: %s",
+ "nth_xref": 1
+ }
+ },
+ {
+ "name": "CCompatManager::SetCompatToolMapping",
+ "func_addr_this_build": "0x6954cc",
+ "aob_hex": "00 45 80 52 BC A4 30 94 F6 03 00 AA E1 03 17 AA E2 03 18 AA",
+ "match_offset": 44,
+ "anchor": {
+ "kind": "string",
+ "value": "Software\\Valve\\Steam\\CompatToolMapping",
+ "nth_xref": 1,
+ "caller_hops": 1,
+ "caller_tail": true
+ }
+ },
+ {
+ "name": "CCompatManager::InternalSpecifyCompatTool",
+ "func_addr_this_build": "0x6946f0",
+ "aob_hex": "FF 43 02 D1 FA 67 04 A9 F8 5F 05 A9 F6 57 06 A9 F4 4F 07 A9 FD 7B 08 A9 FD 03 02 91 F5 03 04 AA F6 03 03 AA",
+ "anchor": {
+ "kind": "string",
+ "value": "CCompatManager::InternalSpecifyCompatTool"
+ }
+ },
+ {
+ "name": "CCompatManager::FindMapping",
+ "func_addr_this_build": "0x6944a8",
+ "aob_hex": "FF 83 00 D1 FD 7B 01 A9 FD 43 00 91 A1 C3 1F B8 E1 00 00 34 00 60 0E 91 A1 13 00 D1",
+ "anchor": {
+ "kind": "string",
+ "value": "FindMapping: Invalid unAppID == k_nAppIdAll, use GetWildcardMapping()."
+ }
+ },
+ {
+ "name": "CCompatManager::GetWildcardMapping",
+ "func_addr_this_build": "0x695a2c",
+ "aob_hex": "FF 43 01 D1 F6 57 02 A9 F4 4F 03 A9 FD 7B 04 A9 FD 03 01 91 E1 1F 00 B9 21 05 00 34",
+ "anchor": {
+ "kind": "string",
+ "value": "GetWildcardMapping: Invalid unAppID k_nAppIdAll"
+ }
+ }
+ ]
+}
diff --git a/signatures/macos.arm64/1789086785.json b/signatures/macos.arm64/1789086785.json
new file mode 100644
index 0000000..be5ec37
--- /dev/null
+++ b/signatures/macos.arm64/1789086785.json
@@ -0,0 +1,169 @@
+{
+ "schema_version": 3,
+ "profile_version": 1,
+ "arch": "arm64",
+ "platform": "macos",
+ "steam_build": 1789086785,
+ "steam_build_date": "",
+ "signatures": [
+ {
+ "name": "CCompatManager::Init",
+ "func_addr_this_build": "0x6a3bd0",
+ "aob_hex": "FF C3 04 D1 FC 6F 0D A9 FA 67 0E A9 F8 5F 0F A9 F6 57 10 A9 F4 4F 11 A9 FD 7B 12 A9 FD 83 04 91 F6 03 01 AA",
+ "anchor": {
+ "kind": "string",
+ "value": "STEAM_COMPAT_TOOL_MAPPINGS"
+ }
+ },
+ {
+ "name": "CCompatManager::BIsCompatibilityToolEnabled",
+ "func_addr_this_build": "0x6a8424",
+ "aob_hex": "FF 03 01 D1 F4 4F 02 A9 FD 7B 03 A9 FD C3 00 91 F4 03 01 AA F3 03 00 AA E1 17 00 B9",
+ "anchor": {
+ "kind": "string",
+ "value": "CCompatManager::BIsCompatibilityToolEnabled"
+ }
+ },
+ {
+ "name": "CCompatManager::YldRegisterTool",
+ "func_addr_this_build": "0x6ac470",
+ "aob_hex": "FF 43 02 D1 FC 6F 03 A9 FA 67 04 A9 F8 5F 05 A9 F6 57 06 A9 F4 4F 07 A9 FD 7B 08 A9 FD 03 02 91 F4 03 01 AA F3 03 00 AA ?? ?? ?? ?? 08 15 40 F9",
+ "anchor": {
+ "kind": "string",
+ "value": "CCompatManager::YldRegisterTool"
+ }
+ },
+ {
+ "name": "CCompatManager::GetOSListOverrideForApp.oslist_gate",
+ "func_addr_this_build": "0x6a8070",
+ "aob_hex": "?? ?? ?? ?? ?? ?? ?? ?? A8 3E 40 F9 1F 01 00 F1 C8 02 88 9A 68 02 00 F9 33 00 80 52",
+ "anchor": {
+ "kind": "insn_pair_in_fn",
+ "value": "pTool != nullptr",
+ "nth_xref": 1,
+ "pair": {
+ "first": "0x94000000",
+ "first_mask": "0xFC000000",
+ "second": "0xB4000000",
+ "second_mask": "0xFF00001F",
+ "tie_mask": "0x0",
+ "land": "second"
+ }
+ }
+ },
+ {
+ "name": "CCompatManager::ResolveCompatToolForApp.local_redirect",
+ "func_addr_this_build": "0x6a8130",
+ "aob_hex": "01 68 40 B9 ?? ?? ?? ?? ?? ?? ?? ?? 08 21 08 91 08 01 40 F9 09 CC 82 52 00 01 09 8B 02 00 80 52",
+ "anchor": {
+ "kind": "insn_pair_in_fn",
+ "value": "GetAppInstallDir failed for tool %u \"%s\"",
+ "pair": {
+ "first": "0xB9400000",
+ "first_mask": "0xFFC003E0",
+ "second": "0x34000000",
+ "second_mask": "0xFF000000",
+ "tie_mask": "0x1F",
+ "land": "first"
+ }
+ }
+ },
+ {
+ "name": "CAppManager::TerminateProcessByPid",
+ "func_addr_this_build": "0xdd0cc",
+ "aob_hex": "F4 4F BE A9 FD 7B 01 A9 FD 43 00 91 F3 03 00 AA ?? ?? ?? ?? F4 03 00 AA ?? ?? ?? ?? 00 05 46 F9 E2 03 13 AA ?? ?? ?? ?? ?? ?? ?? ?? F3 03 00 AA",
+ "anchor": {
+ "kind": "string",
+ "value": "terminate",
+ "indirect": true,
+ "caller_hops": 1
+ }
+ },
+ {
+ "name": "CCompatManager::FindToolForTargetApp",
+ "func_addr_this_build": "0x6a7b64",
+ "aob_hex": "FF 43 01 D1 F6 57 02 A9 F4 4F 03 A9 FD 7B 04 A9 FD 03 01 91 E1 1F 00 B9 08 40 60 39 1F 05 00 71",
+ "anchor": {
+ "kind": "string",
+ "value": "FindToolForTargetApp matched with itself - ignoring: %u %s"
+ }
+ },
+ {
+ "name": "CCompatManager::GetValidPlatforms",
+ "func_addr_this_build": "0x6a65d0",
+ "aob_hex": "FF 03 01 D1 F6 57 01 A9 F4 4F 02 A9 FD 7B 03 A9 FD C3 00 91 F4 03 01 AA F6 03 00 AA",
+ "anchor": {
+ "kind": "string",
+ "value": "AppID %u does not advertise linux as a supported platform, but a linux specific depot is present.\n"
+ }
+ },
+ {
+ "name": "CWebUIJobDispatcher::RegisterHandler",
+ "func_addr_this_build": "0x93bcc",
+ "aob_hex": "FF C3 00 D1 F4 4F 01 A9 FD 7B 02 A9 FD 83 00 91 F4 03 01 AA F3 03 00 AA 28 00 40 F9 08 01 40 F9",
+ "anchor": {
+ "kind": "string",
+ "value": "WebUI method '%s' has already been registered. Skipping duplicate registration"
+ }
+ },
+ {
+ "name": "CWebUITransport::DispatchJob",
+ "func_addr_this_build": "0x93dd0",
+ "aob_hex": "FF 43 07 D1 FC 6F 19 A9 F6 57 1A A9 F4 4F 1B A9 FD 7B 1C A9 FD 03 07 91 F4 03 01 AA F3 03 00 AA",
+ "anchor": {
+ "kind": "string",
+ "value": "no handler for message: %s"
+ }
+ },
+ {
+ "name": "CWebUIMsgJob::SendResponse",
+ "func_addr_this_build": "0x942a8",
+ "aob_hex": "FF C3 00 D1 F4 4F 01 A9 FD 7B 02 A9 FD 83 00 91 F3 03 01 AA F4 03 00 AA 20 0C 40 F9 E0 06 00 B4",
+ "anchor": {
+ "kind": "string",
+ "value": "CWebUIMsgJob: failed to send response for job: %s",
+ "nth_xref": 1
+ }
+ },
+ {
+ "name": "CCompatManager::SetCompatToolMapping",
+ "func_addr_this_build": "0x6a78b4",
+ "aob_hex": "00 3A 80 52 BA E5 30 94 F6 03 00 AA E1 03 17 AA E2 03 18 AA",
+ "match_offset": 44,
+ "anchor": {
+ "kind": "string",
+ "value": "Software\\Valve\\Steam\\CompatToolMapping",
+ "nth_xref": 1,
+ "caller_hops": 1,
+ "caller_tail": true
+ }
+ },
+ {
+ "name": "CCompatManager::InternalSpecifyCompatTool",
+ "func_addr_this_build": "0x6a6a34",
+ "aob_hex": "FF 43 02 D1 FA 67 04 A9 F8 5F 05 A9 F6 57 06 A9 F4 4F 07 A9 FD 7B 08 A9 FD 03 02 91 F5 03 04 AA F6 03 03 AA",
+ "anchor": {
+ "kind": "string",
+ "value": "CCompatManager::InternalSpecifyCompatTool"
+ }
+ },
+ {
+ "name": "CCompatManager::FindMapping",
+ "func_addr_this_build": "0x6a7d44",
+ "aob_hex": "FF 83 00 D1 FD 7B 01 A9 FD 43 00 91 A1 C3 1F B8 E1 00 00 34 00 E0 0F 91 A1 13 00 D1",
+ "anchor": {
+ "kind": "string",
+ "value": "FindMapping: Invalid unAppID == k_nAppIdAll, use GetWildcardMapping()."
+ }
+ },
+ {
+ "name": "CCompatManager::GetWildcardMapping",
+ "func_addr_this_build": "0x6a7dbc",
+ "aob_hex": "FF 43 01 D1 F6 57 02 A9 F4 4F 03 A9 FD 7B 04 A9 FD 03 01 91 E1 1F 00 B9 21 05 00 34",
+ "anchor": {
+ "kind": "string",
+ "value": "GetWildcardMapping: Invalid unAppID k_nAppIdAll"
+ }
+ }
+ ]
+}
diff --git a/steam-shim/LICENSE b/steam-shim/LICENSE
new file mode 100644
index 0000000..d7531fc
--- /dev/null
+++ b/steam-shim/LICENSE
@@ -0,0 +1,27 @@
+Copyright (c) 2015, 2019, 2020, 2021, 2022 Valve Corporation
+All rights reserved.
+
+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.
+
+3. Neither the name of the copyright holder nor the names of its contributors
+may be used to endorse or promote products derived from this software without
+specific prior written permission.
+
+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 HOLDER 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/steam-shim/Makefile.in b/steam-shim/Makefile.in
new file mode 100644
index 0000000..f18827d
--- /dev/null
+++ b/steam-shim/Makefile.in
@@ -0,0 +1,19 @@
+MODULE = steam.exe
+# CXX_PE_LIBS is Wine's own PE libc++, libc++abi, libunwind, msvcp140 and vcruntime140.
+# mingw's libstdc++ mismatches these and leaves std::basic_string and
+# _Unwind_SjLj_Resume undefined. dlls/dmsynth imports the same way.
+IMPORTS = $(CXX_PE_LIBS) user32 advapi32 shlwapi shell32 msi ole32
+
+EXTRADLLFLAGS = -mwindows -mcygwin -static-libgcc
+# __WINESRC__ is re-added because WINE_EXTERNAL drops it, and ERR() and ARRAY_SIZE()
+# are hidden without it. PATH_MAX is defined because mingw's limits.h has none.
+EXTRADEFS = -DWINE_NO_LONG_TYPES -D__WINESRC__ -DPATH_MAX=4096 -include posix_compat.h
+
+EXTRAINCL = \
+ -I$(srcdir)/proton-headers/steamworks_sdk_142 \
+ -I$(srcdir)/proton-headers/openvr/headers \
+ -I$(srcdir)/proton-headers/wine/include
+
+SOURCES = \
+ jsoncpp.cpp \
+ steam.cpp
diff --git a/steam-shim/build.sh b/steam-shim/build.sh
new file mode 100755
index 0000000..2187bfa
--- /dev/null
+++ b/steam-shim/build.sh
@@ -0,0 +1,94 @@
+#!/bin/bash
+# Build the steam.exe shim from the tracked sources in this directory.
+#
+# The shim is a PE executable and the wine build tree's own make builds it, so
+# unlike the lsteamclient unix half there is no hand-rolled compile or link here.
+#
+# Only x86_64 is built and shipped. The tree can produce an i386 shim as well and
+# nothing consumes it: RUN_SCRIPT stages one flat steam.exe into the prefix Steam
+# directory, and a 32 bit game reaching it gets a separate process under wow64, so
+# the 64 bit build serves both.
+#
+# A rebuild from unchanged source is byte-identical except for TimeDateStamp and
+# the optional header CheckSum, so the hash reported below has those two fields
+# zeroed and is comparable across builds. See pe-info.py.
+#
+# Usage:
+# ./build.sh build and verify
+# ./build.sh --install also install to the bridge
+#
+# Overridable: WINE_BUILD, WINE_SRC_REL, BRIDGE_DIR
+
+set -eu
+
+here=$(cd "$(dirname "$0")" && pwd)
+repo=$(cd "$here/.." && pwd)
+
+WINE_BUILD=${WINE_BUILD:-$repo/scratch/wine-build-dual}
+# Relative because it lands in the debug info. Keep the default sibling layout so
+# a rebuild stays comparable to the shipped binary.
+WINE_SRC_REL=${WINE_SRC_REL:-../wine}
+BRIDGE_DIR=${BRIDGE_DIR:-$HOME/Library/Application Support/notproton/bridge}
+
+install=0
+[ "${1:-}" = "--install" ] && install=1
+
+prog=programs/steam.exe
+out=$prog/x86_64-windows/steam.exe
+
+if [ ! -d "$WINE_BUILD/$prog" ]; then
+ echo "==> no wine build tree at $WINE_BUILD/$prog"
+ echo " run bridge/setup-wine-tree.sh to clone and configure it"
+ exit 1
+fi
+
+cd "$WINE_BUILD"
+
+src=$WINE_SRC_REL/$prog
+[ -d "$src" ] || { echo "==> no wine source tree at $WINE_BUILD/$src"; exit 1; }
+
+command -v x86_64-w64-mingw32-gcc >/dev/null || { echo "==> missing x86_64-w64-mingw32-gcc, install mingw-w64"; exit 1; }
+
+"$here/fetch-headers.sh"
+
+echo "==> syncing tracked sources into $WINE_SRC_REL/$prog"
+# The generated Makefile lists only config.status and makedep as its prerequisites,
+# not the per-module Makefile.in files, so a change to IMPORTS or EXTRAINCL here is
+# silently ignored and the build keeps using the previous flags. Notice it rather
+# than trusting make to.
+regen=0
+cmp -s "$here/Makefile.in" "$src/Makefile.in" || regen=1
+
+# Unchanged files keep their mtime so make does not rebuild what it does not have
+# to. proton-headers/ goes across too: it is generated, but EXTRAINCL is written
+# against srcdir, so it has to sit under it.
+rsync -a --exclude build.sh --exclude fetch-headers.sh "$here/" "$src/"
+
+if [ "$regen" = 1 ]; then
+ echo "==> Makefile.in changed, regenerating the build Makefile"
+ ./config.status Makefile >/dev/null
+fi
+
+echo "==> building $out"
+make "$out" >/dev/null
+
+size=$(stat -f %z "$out")
+# shellcheck disable=SC2046
+set -- $("$here/../bridge/pe-info.py" "$out")
+[ "$1" = "x86_64" ] || { echo "==> built $1, expected x86_64"; exit 1; }
+# The shim statically links jsoncpp and weighs ~14 MB. Anything near zero means
+# the link dropped objects.
+[ "$size" -gt 1000000 ] || { echo "==> only $size bytes, the link dropped objects"; exit 1; }
+echo "==> built $out $1 $size bytes $2 (timestamp and checksum zeroed)"
+
+[ "$install" -eq 1 ] || { echo "==> not installing, pass --install to deploy"; exit 0; }
+
+# One consumer: RUN_SCRIPT copies the flat bridge copy into the prefix Steam
+# directory on every launch. The shim is not a wine builtin, so nothing goes into
+# the CrossOver tree.
+dst=$BRIDGE_DIR/steam.exe
+mkdir -p "$BRIDGE_DIR"
+cp -f "$out" "$dst"
+cmp -s "$out" "$dst" || { echo "==> install verify failed: $dst differs from $out"; exit 1; }
+echo "==> installed $dst"
+echo "==> done. prefixes refresh their copy from the bridge on next launch."
diff --git a/steam-shim/dlfcn.h b/steam-shim/dlfcn.h
new file mode 100644
index 0000000..e17aa78
--- /dev/null
+++ b/steam-shim/dlfcn.h
@@ -0,0 +1,34 @@
+#ifndef STEAM_HELPER_DLFCN_SHIM_H
+#define STEAM_HELPER_DLFCN_SHIM_H
+
+/* Minimal dlfcn shim for the PE build. steam.cpp only calls these from the
+ OpenVR and vulkan bridge paths, which do not run on this target; the inline
+ bodies exist so the source compiles and links unchanged without a POSIX libdl. */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define RTLD_LAZY 0x0001
+#define RTLD_NOW 0x0002
+#define RTLD_GLOBAL 0x0100
+#define RTLD_LOCAL 0x0000
+
+typedef struct {
+ const char *dli_fname;
+ void *dli_fbase;
+ const char *dli_sname;
+ void *dli_saddr;
+} Dl_info;
+
+static inline void *dlopen(const char *file, int mode) { (void)file; (void)mode; return 0; }
+static inline int dlclose(void *handle) { (void)handle; return 0; }
+static inline void *dlsym(void *handle, const char *name) { (void)handle; (void)name; return 0; }
+static inline char *dlerror(void) { return 0; }
+static inline int dladdr(const void *addr, Dl_info *info) { (void)addr; (void)info; return 0; }
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/steam-shim/fetch-headers.sh b/steam-shim/fetch-headers.sh
new file mode 100755
index 0000000..728f6f0
--- /dev/null
+++ b/steam-shim/fetch-headers.sh
@@ -0,0 +1,81 @@
+#!/bin/sh
+# Assemble the headers the shim compiles against, into proton-headers/ next to the
+# sources so the whole include set sits under srcdir once build.sh syncs it across.
+#
+# Three of them come from Proton submodules, which a codeload tarball does not carry:
+# it records openvr and wine as empty directories. They are fetched individually at
+# the commits Proton pins on proton_9.0, which is the branch this shim's steam.cpp
+# comes from, and each is checked against its recorded hash. Nothing else in either
+# submodule is used: openvr.h pulls in only stdint.h and string, ivrclientcore.h
+# includes nothing, and heap.h needs winbase.h, which the wine tree supplies.
+#
+# The Steamworks SDK headers are Valve's too but arrive with lsteamclient, so they
+# are copied from the tree its fetch.sh assembles rather than fetched again.
+#
+# Usage:
+# ./fetch-headers.sh assemble if needed
+# ./fetch-headers.sh --refetch discard the cache first
+#
+# Overridable: OPENVR_COMMIT, WINE_COMMIT, CACHE, OUT, LSC_TREE
+
+set -eu
+
+here=$(cd "$(dirname "$0")" && pwd)
+repo=$(cd "$here/.." && pwd)
+
+# Submodule pins as recorded by Proton at proton_9.0. openvr is ValveSoftware/openvr;
+# the wine submodule url is ../wine relative to Proton, so ValveSoftware/wine.
+OPENVR_COMMIT=${OPENVR_COMMIT:-f51d87ecf8f7903e859b0aa4d617ff1e5f33db5a}
+WINE_COMMIT=${WINE_COMMIT:-015230dc0f78a543032dea0907f6c97304b25ca3}
+
+CACHE=${CACHE:-$repo/scratch/proton-headers}
+OUT=${OUT:-$here/proton-headers}
+LSC_TREE=${LSC_TREE:-$repo/build/lsteamclient}
+
+# repo, commit, path in that repo, destination under OUT, sha256.
+wanted="openvr $OPENVR_COMMIT headers/openvr.h openvr/headers/openvr.h 4f1242febb91d23e1a8317b988dbecec63476603f67458872d3b916cd347df32
+openvr $OPENVR_COMMIT src/ivrclientcore.h openvr/src/ivrclientcore.h 07c8ce981a59fb7cd1dc30572f0c9972d98e6275e95527f0f7a74a18bc0cf846
+wine $WINE_COMMIT include/wine/heap.h wine/include/wine/heap.h e51df7c87744e3cbea4cd03d1e08573205252eb275166c0d01f87340991550e7"
+
+if [ "${1:-}" = "--refetch" ]; then
+ rm -rf "$CACHE" "$OUT"
+elif [ $# -ne 0 ]; then
+ echo "==> unknown argument $1" >&2
+ exit 1
+fi
+
+mkdir -p "$CACHE"
+
+echo "$wanted" | while read -r proj commit path dest want; do
+ [ -n "$proj" ] || continue
+ cached=$CACHE/$proj-$commit-$(echo "$path" | LC_ALL=C tr '/' '_')
+
+ if [ ! -f "$cached" ]; then
+ echo "==> fetching $proj/$path at $(echo "$commit" | LC_ALL=C cut -c1-12)"
+ curl -fsSL -o "$cached.part" \
+ "https://raw.githubusercontent.com/ValveSoftware/$proj/$commit/$path"
+ mv "$cached.part" "$cached"
+ fi
+
+ got=$(shasum -a 256 "$cached" | LC_ALL=C awk '{print $1}')
+ if [ "$got" != "$want" ]; then
+ echo "==> hash mismatch for $proj/$path at $commit" >&2
+ echo " expected $want" >&2
+ echo " got $got" >&2
+ exit 1
+ fi
+
+ mkdir -p "$OUT/$(dirname "$dest")"
+ cp -f "$cached" "$OUT/$dest"
+done
+
+[ -d "$LSC_TREE/steamworks_sdk_142" ] || {
+ echo "==> no $LSC_TREE/steamworks_sdk_142, run lsteamclient/fetch.sh first" >&2
+ exit 1
+}
+rm -rf "$OUT/steamworks_sdk_142"
+mkdir -p "$OUT"
+cp -c -R "$LSC_TREE/steamworks_sdk_142" "$OUT/steamworks_sdk_142" 2>/dev/null \
+ || cp -R "$LSC_TREE/steamworks_sdk_142" "$OUT/steamworks_sdk_142"
+
+echo "==> assembled $OUT"
diff --git a/steam-shim/json/json-forwards.h b/steam-shim/json/json-forwards.h
new file mode 100644
index 0000000..910c7de
--- /dev/null
+++ b/steam-shim/json/json-forwards.h
@@ -0,0 +1,284 @@
+/// Json-cpp amalgated forward header (http://jsoncpp.sourceforge.net/).
+/// It is intended to be used with #include "json/json-forwards.h"
+/// This header provides forward declaration for all JsonCpp types.
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: LICENSE
+// //////////////////////////////////////////////////////////////////////
+
+/*
+The JsonCpp library's source code, including accompanying documentation,
+tests and demonstration applications, are licensed under the following
+conditions...
+
+The author (Baptiste Lepilleur) explicitly disclaims copyright in all
+jurisdictions which recognize such a disclaimer. In such jurisdictions,
+this software is released into the Public Domain.
+
+In jurisdictions which do not recognize Public Domain property (e.g. Germany as of
+2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is
+released under the terms of the MIT License (see below).
+
+In jurisdictions which recognize Public Domain property, the user of this
+software may choose to accept it either as 1) Public Domain, 2) under the
+conditions of the MIT License (see below), or 3) under the terms of dual
+Public Domain/MIT License conditions described here, as they choose.
+
+The MIT License is about as close to Public Domain as a license can get, and is
+described in clear, concise terms at:
+
+ http://en.wikipedia.org/wiki/MIT_License
+
+The full text of the MIT License follows:
+
+========================================================================
+Copyright (c) 2007-2010 Baptiste Lepilleur
+
+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.
+========================================================================
+(END LICENSE TEXT)
+
+The MIT license is compatible with both the GPL and commercial
+software, affording one all of the rights of Public Domain with the
+minor nuisance of being required to keep the above copyright notice
+and license text in the source code. Note also that by accepting the
+Public Domain "license" you can re-license your copy using whatever
+license you like.
+
+*/
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: LICENSE
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+#ifndef JSON_FORWARD_AMALGATED_H_INCLUDED
+# define JSON_FORWARD_AMALGATED_H_INCLUDED
+/// If defined, indicates that the source file is amalgated
+/// to prevent private header inclusion.
+#define JSON_IS_AMALGAMATION
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: include/json/config.h
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2007-2010 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+#ifndef JSON_CONFIG_H_INCLUDED
+#define JSON_CONFIG_H_INCLUDED
+
+/// If defined, indicates that json library is embedded in CppTL library.
+//# define JSON_IN_CPPTL 1
+
+/// If defined, indicates that json may leverage CppTL library
+//# define JSON_USE_CPPTL 1
+/// If defined, indicates that cpptl vector based map should be used instead of
+/// std::map
+/// as Value container.
+//# define JSON_USE_CPPTL_SMALLMAP 1
+
+// If non-zero, the library uses exceptions to report bad input instead of C
+// assertion macros. The default is to use exceptions.
+#ifndef JSON_USE_EXCEPTION
+#define JSON_USE_EXCEPTION 1
+#endif
+
+/// If defined, indicates that the source file is amalgated
+/// to prevent private header inclusion.
+/// Remarks: it is automatically defined in the generated amalgated header.
+// #define JSON_IS_AMALGAMATION
+
+#ifdef JSON_IN_CPPTL
+#include <cpptl/config.h>
+#ifndef JSON_USE_CPPTL
+#define JSON_USE_CPPTL 1
+#endif
+#endif
+
+#ifdef JSON_IN_CPPTL
+#define JSON_API CPPTL_API
+#elif defined(JSON_DLL_BUILD)
+#if defined(_MSC_VER)
+#define JSON_API __declspec(dllexport)
+#define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
+#endif // if defined(_MSC_VER)
+#elif defined(JSON_DLL)
+#if defined(_MSC_VER)
+#define JSON_API __declspec(dllimport)
+#define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
+#endif // if defined(_MSC_VER)
+#endif // ifdef JSON_IN_CPPTL
+#if !defined(JSON_API)
+#define JSON_API
+#endif
+
+// If JSON_NO_INT64 is defined, then Json only support C++ "int" type for
+// integer
+// Storages, and 64 bits integer support is disabled.
+// #define JSON_NO_INT64 1
+
+#if defined(_MSC_VER) // MSVC
+# if _MSC_VER <= 1200 // MSVC 6
+ // Microsoft Visual Studio 6 only support conversion from __int64 to double
+ // (no conversion from unsigned __int64).
+# define JSON_USE_INT64_DOUBLE_CONVERSION 1
+ // Disable warning 4786 for VS6 caused by STL (identifier was truncated to '255'
+ // characters in the debug information)
+ // All projects I've ever seen with VS6 were using this globally (not bothering
+ // with pragma push/pop).
+# pragma warning(disable : 4786)
+# endif // MSVC 6
+
+# if _MSC_VER >= 1500 // MSVC 2008
+ /// Indicates that the following function is deprecated.
+# define JSONCPP_DEPRECATED(message) __declspec(deprecated(message))
+# endif
+
+#endif // defined(_MSC_VER)
+
+
+#ifndef JSON_HAS_RVALUE_REFERENCES
+
+#if defined(_MSC_VER) && _MSC_VER >= 1600 // MSVC >= 2010
+#define JSON_HAS_RVALUE_REFERENCES 1
+#endif // MSVC >= 2010
+
+#ifdef __clang__
+#if __has_feature(cxx_rvalue_references)
+#define JSON_HAS_RVALUE_REFERENCES 1
+#endif // has_feature
+
+#elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc)
+#if defined(__GXX_EXPERIMENTAL_CXX0X__) || (__cplusplus >= 201103L)
+#define JSON_HAS_RVALUE_REFERENCES 1
+#endif // GXX_EXPERIMENTAL
+
+#endif // __clang__ || __GNUC__
+
+#endif // not defined JSON_HAS_RVALUE_REFERENCES
+
+#ifndef JSON_HAS_RVALUE_REFERENCES
+#define JSON_HAS_RVALUE_REFERENCES 0
+#endif
+
+#ifdef __clang__
+#elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc)
+# if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
+# define JSONCPP_DEPRECATED(message) __attribute__ ((deprecated(message)))
+# elif (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
+# define JSONCPP_DEPRECATED(message) __attribute__((__deprecated__))
+# endif // GNUC version
+#endif // __clang__ || __GNUC__
+
+#if !defined(JSONCPP_DEPRECATED)
+#define JSONCPP_DEPRECATED(message)
+#endif // if !defined(JSONCPP_DEPRECATED)
+
+namespace Json {
+typedef int Int;
+typedef unsigned int UInt;
+#if defined(JSON_NO_INT64)
+typedef int LargestInt;
+typedef unsigned int LargestUInt;
+#undef JSON_HAS_INT64
+#else // if defined(JSON_NO_INT64)
+// For Microsoft Visual use specific types as long long is not supported
+#if defined(_MSC_VER) // Microsoft Visual Studio
+typedef __int64 Int64;
+typedef unsigned __int64 UInt64;
+#else // if defined(_MSC_VER) // Other platforms, use long long
+typedef long long int Int64;
+typedef unsigned long long int UInt64;
+#endif // if defined(_MSC_VER)
+typedef Int64 LargestInt;
+typedef UInt64 LargestUInt;
+#define JSON_HAS_INT64
+#endif // if defined(JSON_NO_INT64)
+} // end namespace Json
+
+#endif // JSON_CONFIG_H_INCLUDED
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: include/json/config.h
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: include/json/forwards.h
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2007-2010 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+#ifndef JSON_FORWARDS_H_INCLUDED
+#define JSON_FORWARDS_H_INCLUDED
+
+#if !defined(JSON_IS_AMALGAMATION)
+#include "config.h"
+#endif // if !defined(JSON_IS_AMALGAMATION)
+
+namespace Json {
+
+// writer.h
+class FastWriter;
+class StyledWriter;
+
+// reader.h
+class Reader;
+
+// features.h
+class Features;
+
+// value.h
+typedef unsigned int ArrayIndex;
+class StaticString;
+class Path;
+class PathArgument;
+class Value;
+class ValueIteratorBase;
+class ValueIterator;
+class ValueConstIterator;
+
+} // namespace Json
+
+#endif // JSON_FORWARDS_H_INCLUDED
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: include/json/forwards.h
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+#endif //ifndef JSON_FORWARD_AMALGATED_H_INCLUDED
diff --git a/steam-shim/json/json.h b/steam-shim/json/json.h
new file mode 100644
index 0000000..d27f65d
--- /dev/null
+++ b/steam-shim/json/json.h
@@ -0,0 +1,2077 @@
+/// Json-cpp amalgated header (http://jsoncpp.sourceforge.net/).
+/// It is intended to be used with #include "json/json.h"
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: LICENSE
+// //////////////////////////////////////////////////////////////////////
+
+/*
+The JsonCpp library's source code, including accompanying documentation,
+tests and demonstration applications, are licensed under the following
+conditions...
+
+The author (Baptiste Lepilleur) explicitly disclaims copyright in all
+jurisdictions which recognize such a disclaimer. In such jurisdictions,
+this software is released into the Public Domain.
+
+In jurisdictions which do not recognize Public Domain property (e.g. Germany as of
+2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is
+released under the terms of the MIT License (see below).
+
+In jurisdictions which recognize Public Domain property, the user of this
+software may choose to accept it either as 1) Public Domain, 2) under the
+conditions of the MIT License (see below), or 3) under the terms of dual
+Public Domain/MIT License conditions described here, as they choose.
+
+The MIT License is about as close to Public Domain as a license can get, and is
+described in clear, concise terms at:
+
+ http://en.wikipedia.org/wiki/MIT_License
+
+The full text of the MIT License follows:
+
+========================================================================
+Copyright (c) 2007-2010 Baptiste Lepilleur
+
+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.
+========================================================================
+(END LICENSE TEXT)
+
+The MIT license is compatible with both the GPL and commercial
+software, affording one all of the rights of Public Domain with the
+minor nuisance of being required to keep the above copyright notice
+and license text in the source code. Note also that by accepting the
+Public Domain "license" you can re-license your copy using whatever
+license you like.
+
+*/
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: LICENSE
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+#ifndef JSON_AMALGATED_H_INCLUDED
+# define JSON_AMALGATED_H_INCLUDED
+/// If defined, indicates that the source file is amalgated
+/// to prevent private header inclusion.
+#define JSON_IS_AMALGAMATION
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: include/json/version.h
+// //////////////////////////////////////////////////////////////////////
+
+// DO NOT EDIT. This file (and "version") is generated by CMake.
+// Run CMake configure step to update it.
+#ifndef JSON_VERSION_H_INCLUDED
+# define JSON_VERSION_H_INCLUDED
+
+# define JSONCPP_VERSION_STRING "1.6.5"
+# define JSONCPP_VERSION_MAJOR 1
+# define JSONCPP_VERSION_MINOR 6
+# define JSONCPP_VERSION_PATCH 5
+# define JSONCPP_VERSION_QUALIFIER
+# define JSONCPP_VERSION_HEXA ((JSONCPP_VERSION_MAJOR << 24) | (JSONCPP_VERSION_MINOR << 16) | (JSONCPP_VERSION_PATCH << 8))
+
+#endif // JSON_VERSION_H_INCLUDED
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: include/json/version.h
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: include/json/config.h
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2007-2010 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+#ifndef JSON_CONFIG_H_INCLUDED
+#define JSON_CONFIG_H_INCLUDED
+
+/// If defined, indicates that json library is embedded in CppTL library.
+//# define JSON_IN_CPPTL 1
+
+/// If defined, indicates that json may leverage CppTL library
+//# define JSON_USE_CPPTL 1
+/// If defined, indicates that cpptl vector based map should be used instead of
+/// std::map
+/// as Value container.
+//# define JSON_USE_CPPTL_SMALLMAP 1
+
+// If non-zero, the library uses exceptions to report bad input instead of C
+// assertion macros. The default is to use exceptions.
+#ifndef JSON_USE_EXCEPTION
+#define JSON_USE_EXCEPTION 1
+#endif
+
+/// If defined, indicates that the source file is amalgated
+/// to prevent private header inclusion.
+/// Remarks: it is automatically defined in the generated amalgated header.
+// #define JSON_IS_AMALGAMATION
+
+#ifdef JSON_IN_CPPTL
+#include <cpptl/config.h>
+#ifndef JSON_USE_CPPTL
+#define JSON_USE_CPPTL 1
+#endif
+#endif
+
+#ifdef JSON_IN_CPPTL
+#define JSON_API CPPTL_API
+#elif defined(JSON_DLL_BUILD)
+#if defined(_MSC_VER)
+#define JSON_API __declspec(dllexport)
+#define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
+#endif // if defined(_MSC_VER)
+#elif defined(JSON_DLL)
+#if defined(_MSC_VER)
+#define JSON_API __declspec(dllimport)
+#define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
+#endif // if defined(_MSC_VER)
+#endif // ifdef JSON_IN_CPPTL
+#if !defined(JSON_API)
+#define JSON_API
+#endif
+
+// If JSON_NO_INT64 is defined, then Json only support C++ "int" type for
+// integer
+// Storages, and 64 bits integer support is disabled.
+// #define JSON_NO_INT64 1
+
+#if defined(_MSC_VER) // MSVC
+# if _MSC_VER <= 1200 // MSVC 6
+ // Microsoft Visual Studio 6 only support conversion from __int64 to double
+ // (no conversion from unsigned __int64).
+# define JSON_USE_INT64_DOUBLE_CONVERSION 1
+ // Disable warning 4786 for VS6 caused by STL (identifier was truncated to '255'
+ // characters in the debug information)
+ // All projects I've ever seen with VS6 were using this globally (not bothering
+ // with pragma push/pop).
+# pragma warning(disable : 4786)
+# endif // MSVC 6
+
+# if _MSC_VER >= 1500 // MSVC 2008
+ /// Indicates that the following function is deprecated.
+# define JSONCPP_DEPRECATED(message) __declspec(deprecated(message))
+# endif
+
+#endif // defined(_MSC_VER)
+
+
+#ifndef JSON_HAS_RVALUE_REFERENCES
+
+#if defined(_MSC_VER) && _MSC_VER >= 1600 // MSVC >= 2010
+#define JSON_HAS_RVALUE_REFERENCES 1
+#endif // MSVC >= 2010
+
+#ifdef __clang__
+#if __has_feature(cxx_rvalue_references)
+#define JSON_HAS_RVALUE_REFERENCES 1
+#endif // has_feature
+
+#elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc)
+#if defined(__GXX_EXPERIMENTAL_CXX0X__) || (__cplusplus >= 201103L)
+#define JSON_HAS_RVALUE_REFERENCES 1
+#endif // GXX_EXPERIMENTAL
+
+#endif // __clang__ || __GNUC__
+
+#endif // not defined JSON_HAS_RVALUE_REFERENCES
+
+#ifndef JSON_HAS_RVALUE_REFERENCES
+#define JSON_HAS_RVALUE_REFERENCES 0
+#endif
+
+#ifdef __clang__
+#elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc)
+# if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
+# define JSONCPP_DEPRECATED(message) __attribute__ ((deprecated(message)))
+# elif (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
+# define JSONCPP_DEPRECATED(message) __attribute__((__deprecated__))
+# endif // GNUC version
+#endif // __clang__ || __GNUC__
+
+#if !defined(JSONCPP_DEPRECATED)
+#define JSONCPP_DEPRECATED(message)
+#endif // if !defined(JSONCPP_DEPRECATED)
+
+namespace Json {
+typedef int Int;
+typedef unsigned int UInt;
+#if defined(JSON_NO_INT64)
+typedef int LargestInt;
+typedef unsigned int LargestUInt;
+#undef JSON_HAS_INT64
+#else // if defined(JSON_NO_INT64)
+// For Microsoft Visual use specific types as long long is not supported
+#if defined(_MSC_VER) // Microsoft Visual Studio
+typedef __int64 Int64;
+typedef unsigned __int64 UInt64;
+#else // if defined(_MSC_VER) // Other platforms, use long long
+typedef long long int Int64;
+typedef unsigned long long int UInt64;
+#endif // if defined(_MSC_VER)
+typedef Int64 LargestInt;
+typedef UInt64 LargestUInt;
+#define JSON_HAS_INT64
+#endif // if defined(JSON_NO_INT64)
+} // end namespace Json
+
+#endif // JSON_CONFIG_H_INCLUDED
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: include/json/config.h
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: include/json/forwards.h
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2007-2010 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+#ifndef JSON_FORWARDS_H_INCLUDED
+#define JSON_FORWARDS_H_INCLUDED
+
+#if !defined(JSON_IS_AMALGAMATION)
+#include "config.h"
+#endif // if !defined(JSON_IS_AMALGAMATION)
+
+namespace Json {
+
+// writer.h
+class FastWriter;
+class StyledWriter;
+
+// reader.h
+class Reader;
+
+// features.h
+class Features;
+
+// value.h
+typedef unsigned int ArrayIndex;
+class StaticString;
+class Path;
+class PathArgument;
+class Value;
+class ValueIteratorBase;
+class ValueIterator;
+class ValueConstIterator;
+
+} // namespace Json
+
+#endif // JSON_FORWARDS_H_INCLUDED
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: include/json/forwards.h
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: include/json/features.h
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2007-2010 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+#ifndef CPPTL_JSON_FEATURES_H_INCLUDED
+#define CPPTL_JSON_FEATURES_H_INCLUDED
+
+#if !defined(JSON_IS_AMALGAMATION)
+#include "forwards.h"
+#endif // if !defined(JSON_IS_AMALGAMATION)
+
+namespace Json {
+
+/** \brief Configuration passed to reader and writer.
+ * This configuration object can be used to force the Reader or Writer
+ * to behave in a standard conforming way.
+ */
+class JSON_API Features {
+public:
+ /** \brief A configuration that allows all features and assumes all strings
+ * are UTF-8.
+ * - C & C++ comments are allowed
+ * - Root object can be any JSON value
+ * - Assumes Value strings are encoded in UTF-8
+ */
+ static Features all();
+
+ /** \brief A configuration that is strictly compatible with the JSON
+ * specification.
+ * - Comments are forbidden.
+ * - Root object must be either an array or an object value.
+ * - Assumes Value strings are encoded in UTF-8
+ */
+ static Features strictMode();
+
+ /** \brief Initialize the configuration like JsonConfig::allFeatures;
+ */
+ Features();
+
+ /// \c true if comments are allowed. Default: \c true.
+ bool allowComments_;
+
+ /// \c true if root must be either an array or an object value. Default: \c
+ /// false.
+ bool strictRoot_;
+
+ /// \c true if dropped null placeholders are allowed. Default: \c false.
+ bool allowDroppedNullPlaceholders_;
+
+ /// \c true if numeric object key are allowed. Default: \c false.
+ bool allowNumericKeys_;
+};
+
+} // namespace Json
+
+#endif // CPPTL_JSON_FEATURES_H_INCLUDED
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: include/json/features.h
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: include/json/value.h
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2007-2010 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+#ifndef CPPTL_JSON_H_INCLUDED
+#define CPPTL_JSON_H_INCLUDED
+
+#if !defined(JSON_IS_AMALGAMATION)
+#include "forwards.h"
+#endif // if !defined(JSON_IS_AMALGAMATION)
+#include <string>
+#include <vector>
+#include <exception>
+
+#ifndef JSON_USE_CPPTL_SMALLMAP
+#include <map>
+#else
+#include <cpptl/smallmap.h>
+#endif
+#ifdef JSON_USE_CPPTL
+#include <cpptl/forwards.h>
+#endif
+
+// Disable warning C4251: <data member>: <type> needs to have dll-interface to
+// be used by...
+#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
+#pragma warning(push)
+#pragma warning(disable : 4251)
+#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
+
+/** \brief JSON (JavaScript Object Notation).
+ */
+namespace Json {
+
+/** Base class for all exceptions we throw.
+ *
+ * We use nothing but these internally. Of course, STL can throw others.
+ */
+class JSON_API Exception : public std::exception {
+public:
+ Exception(std::string const& msg);
+ ~Exception() throw();
+ char const* what() const throw();
+protected:
+ std::string msg_;
+};
+
+/** Exceptions which the user cannot easily avoid.
+ *
+ * E.g. out-of-memory (when we use malloc), stack-overflow, malicious input
+ *
+ * \remark derived from Json::Exception
+ */
+class JSON_API RuntimeError : public Exception {
+public:
+ RuntimeError(std::string const& msg);
+};
+
+/** Exceptions thrown by JSON_ASSERT/JSON_FAIL macros.
+ *
+ * These are precondition-violations (user bugs) and internal errors (our bugs).
+ *
+ * \remark derived from Json::Exception
+ */
+class JSON_API LogicError : public Exception {
+public:
+ LogicError(std::string const& msg);
+};
+
+/// used internally
+void throwRuntimeError(std::string const& msg);
+/// used internally
+void throwLogicError(std::string const& msg);
+
+/** \brief Type of the value held by a Value object.
+ */
+enum ValueType {
+ nullValue = 0, ///< 'null' value
+ intValue, ///< signed integer value
+ uintValue, ///< unsigned integer value
+ realValue, ///< double value
+ stringValue, ///< UTF-8 string value
+ booleanValue, ///< bool value
+ arrayValue, ///< array value (ordered list)
+ objectValue ///< object value (collection of name/value pairs).
+};
+
+enum CommentPlacement {
+ commentBefore = 0, ///< a comment placed on the line before a value
+ commentAfterOnSameLine, ///< a comment just after a value on the same line
+ commentAfter, ///< a comment on the line after a value (only make sense for
+ /// root value)
+ numberOfCommentPlacement
+};
+
+//# ifdef JSON_USE_CPPTL
+// typedef CppTL::AnyEnumerator<const char *> EnumMemberNames;
+// typedef CppTL::AnyEnumerator<const Value &> EnumValues;
+//# endif
+
+/** \brief Lightweight wrapper to tag static string.
+ *
+ * Value constructor and objectValue member assignement takes advantage of the
+ * StaticString and avoid the cost of string duplication when storing the
+ * string or the member name.
+ *
+ * Example of usage:
+ * \code
+ * Json::Value aValue( StaticString("some text") );
+ * Json::Value object;
+ * static const StaticString code("code");
+ * object[code] = 1234;
+ * \endcode
+ */
+class JSON_API StaticString {
+public:
+ explicit StaticString(const char* czstring) : c_str_(czstring) {}
+
+ operator const char*() const { return c_str_; }
+
+ const char* c_str() const { return c_str_; }
+
+private:
+ const char* c_str_;
+};
+
+/** \brief Represents a <a HREF="http://www.json.org">JSON</a> value.
+ *
+ * This class is a discriminated union wrapper that can represents a:
+ * - signed integer [range: Value::minInt - Value::maxInt]
+ * - unsigned integer (range: 0 - Value::maxUInt)
+ * - double
+ * - UTF-8 string
+ * - boolean
+ * - 'null'
+ * - an ordered list of Value
+ * - collection of name/value pairs (javascript object)
+ *
+ * The type of the held value is represented by a #ValueType and
+ * can be obtained using type().
+ *
+ * Values of an #objectValue or #arrayValue can be accessed using operator[]()
+ * methods.
+ * Non-const methods will automatically create the a #nullValue element
+ * if it does not exist.
+ * The sequence of an #arrayValue will be automatically resized and initialized
+ * with #nullValue. resize() can be used to enlarge or truncate an #arrayValue.
+ *
+ * The get() methods can be used to obtain default value in the case the
+ * required element does not exist.
+ *
+ * It is possible to iterate over the list of a #objectValue values using
+ * the getMemberNames() method.
+ *
+ * \note #Value string-length fit in size_t, but keys must be < 2^30.
+ * (The reason is an implementation detail.) A #CharReader will raise an
+ * exception if a bound is exceeded to avoid security holes in your app,
+ * but the Value API does *not* check bounds. That is the responsibility
+ * of the caller.
+ */
+class JSON_API Value {
+ friend class ValueIteratorBase;
+public:
+ typedef std::vector<std::string> Members;
+ typedef ValueIterator iterator;
+ typedef ValueConstIterator const_iterator;
+ typedef Json::UInt UInt;
+ typedef Json::Int Int;
+#if defined(JSON_HAS_INT64)
+ typedef Json::UInt64 UInt64;
+ typedef Json::Int64 Int64;
+#endif // defined(JSON_HAS_INT64)
+ typedef Json::LargestInt LargestInt;
+ typedef Json::LargestUInt LargestUInt;
+ typedef Json::ArrayIndex ArrayIndex;
+
+ static const Value& null; ///< We regret this reference to a global instance; prefer the simpler Value().
+ static const Value& nullRef; ///< just a kludge for binary-compatibility; same as null
+ /// Minimum signed integer value that can be stored in a Json::Value.
+ static const LargestInt minLargestInt;
+ /// Maximum signed integer value that can be stored in a Json::Value.
+ static const LargestInt maxLargestInt;
+ /// Maximum unsigned integer value that can be stored in a Json::Value.
+ static const LargestUInt maxLargestUInt;
+
+ /// Minimum signed int value that can be stored in a Json::Value.
+ static const Int minInt;
+ /// Maximum signed int value that can be stored in a Json::Value.
+ static const Int maxInt;
+ /// Maximum unsigned int value that can be stored in a Json::Value.
+ static const UInt maxUInt;
+
+#if defined(JSON_HAS_INT64)
+ /// Minimum signed 64 bits int value that can be stored in a Json::Value.
+ static const Int64 minInt64;
+ /// Maximum signed 64 bits int value that can be stored in a Json::Value.
+ static const Int64 maxInt64;
+ /// Maximum unsigned 64 bits int value that can be stored in a Json::Value.
+ static const UInt64 maxUInt64;
+#endif // defined(JSON_HAS_INT64)
+
+private:
+#ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
+ class CZString {
+ public:
+ enum DuplicationPolicy {
+ noDuplication = 0,
+ duplicate,
+ duplicateOnCopy
+ };
+ CZString(ArrayIndex index);
+ CZString(char const* str, unsigned length, DuplicationPolicy allocate);
+ CZString(CZString const& other);
+#if JSON_HAS_RVALUE_REFERENCES
+ CZString(CZString&& other);
+#endif
+ ~CZString();
+ CZString& operator=(CZString other);
+ bool operator<(CZString const& other) const;
+ bool operator==(CZString const& other) const;
+ ArrayIndex index() const;
+ //const char* c_str() const; ///< \deprecated
+ char const* data() const;
+ unsigned length() const;
+ bool isStaticString() const;
+
+ private:
+ void swap(CZString& other);
+
+ struct StringStorage {
+ unsigned policy_: 2;
+ unsigned length_: 30; // 1GB max
+ };
+
+ char const* cstr_; // actually, a prefixed string, unless policy is noDup
+ union {
+ ArrayIndex index_;
+ StringStorage storage_;
+ };
+ };
+
+public:
+#ifndef JSON_USE_CPPTL_SMALLMAP
+ typedef std::map<CZString, Value> ObjectValues;
+#else
+ typedef CppTL::SmallMap<CZString, Value> ObjectValues;
+#endif // ifndef JSON_USE_CPPTL_SMALLMAP
+#endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
+
+public:
+ /** \brief Create a default Value of the given type.
+
+ This is a very useful constructor.
+ To create an empty array, pass arrayValue.
+ To create an empty object, pass objectValue.
+ Another Value can then be set to this one by assignment.
+This is useful since clear() and resize() will not alter types.
+
+ Examples:
+\code
+Json::Value null_value; // null
+Json::Value arr_value(Json::arrayValue); // []
+Json::Value obj_value(Json::objectValue); // {}
+\endcode
+ */
+ Value(ValueType type = nullValue);
+ Value(Int value);
+ Value(UInt value);
+#if defined(JSON_HAS_INT64)
+ Value(Int64 value);
+ Value(UInt64 value);
+#endif // if defined(JSON_HAS_INT64)
+ Value(double value);
+ Value(const char* value); ///< Copy til first 0. (NULL causes to seg-fault.)
+ Value(const char* begin, const char* end); ///< Copy all, incl zeroes.
+ /** \brief Constructs a value from a static string.
+
+ * Like other value string constructor but do not duplicate the string for
+ * internal storage. The given string must remain alive after the call to this
+ * constructor.
+ * \note This works only for null-terminated strings. (We cannot change the
+ * size of this class, so we have nowhere to store the length,
+ * which might be computed later for various operations.)
+ *
+ * Example of usage:
+ * \code
+ * static StaticString foo("some text");
+ * Json::Value aValue(foo);
+ * \endcode
+ */
+ Value(const StaticString& value);
+ Value(const std::string& value); ///< Copy data() til size(). Embedded zeroes too.
+#ifdef JSON_USE_CPPTL
+ Value(const CppTL::ConstString& value);
+#endif
+ Value(bool value);
+ /// Deep copy.
+ Value(const Value& other);
+#if JSON_HAS_RVALUE_REFERENCES
+ /// Move constructor
+ Value(Value&& other);
+#endif
+ ~Value();
+
+ /// Deep copy, then swap(other).
+ /// \note Over-write existing comments. To preserve comments, use #swapPayload().
+ Value& operator=(Value other);
+ /// Swap everything.
+ void swap(Value& other);
+ /// Swap values but leave comments and source offsets in place.
+ void swapPayload(Value& other);
+
+ ValueType type() const;
+
+ /// Compare payload only, not comments etc.
+ bool operator<(const Value& other) const;
+ bool operator<=(const Value& other) const;
+ bool operator>=(const Value& other) const;
+ bool operator>(const Value& other) const;
+ bool operator==(const Value& other) const;
+ bool operator!=(const Value& other) const;
+ int compare(const Value& other) const;
+
+ const char* asCString() const; ///< Embedded zeroes could cause you trouble!
+ std::string asString() const; ///< Embedded zeroes are possible.
+ /** Get raw char* of string-value.
+ * \return false if !string. (Seg-fault if str or end are NULL.)
+ */
+ bool getString(
+ char const** begin, char const** end) const;
+#ifdef JSON_USE_CPPTL
+ CppTL::ConstString asConstString() const;
+#endif
+ Int asInt() const;
+ UInt asUInt() const;
+#if defined(JSON_HAS_INT64)
+ Int64 asInt64() const;
+ UInt64 asUInt64() const;
+#endif // if defined(JSON_HAS_INT64)
+ LargestInt asLargestInt() const;
+ LargestUInt asLargestUInt() const;
+ float asFloat() const;
+ double asDouble() const;
+ bool asBool() const;
+
+ bool isNull() const;
+ bool isBool() const;
+ bool isInt() const;
+ bool isInt64() const;
+ bool isUInt() const;
+ bool isUInt64() const;
+ bool isIntegral() const;
+ bool isDouble() const;
+ bool isNumeric() const;
+ bool isString() const;
+ bool isArray() const;
+ bool isObject() const;
+
+ bool isConvertibleTo(ValueType other) const;
+
+ /// Number of values in array or object
+ ArrayIndex size() const;
+
+ /// \brief Return true if empty array, empty object, or null;
+ /// otherwise, false.
+ bool empty() const;
+
+ /// Return isNull()
+ bool operator!() const;
+
+ /// Remove all object members and array elements.
+ /// \pre type() is arrayValue, objectValue, or nullValue
+ /// \post type() is unchanged
+ void clear();
+
+ /// Resize the array to size elements.
+ /// New elements are initialized to null.
+ /// May only be called on nullValue or arrayValue.
+ /// \pre type() is arrayValue or nullValue
+ /// \post type() is arrayValue
+ void resize(ArrayIndex size);
+
+ /// Access an array element (zero based index ).
+ /// If the array contains less than index element, then null value are
+ /// inserted
+ /// in the array so that its size is index+1.
+ /// (You may need to say 'value[0u]' to get your compiler to distinguish
+ /// this from the operator[] which takes a string.)
+ Value& operator[](ArrayIndex index);
+
+ /// Access an array element (zero based index ).
+ /// If the array contains less than index element, then null value are
+ /// inserted
+ /// in the array so that its size is index+1.
+ /// (You may need to say 'value[0u]' to get your compiler to distinguish
+ /// this from the operator[] which takes a string.)
+ Value& operator[](int index);
+
+ /// Access an array element (zero based index )
+ /// (You may need to say 'value[0u]' to get your compiler to distinguish
+ /// this from the operator[] which takes a string.)
+ const Value& operator[](ArrayIndex index) const;
+
+ /// Access an array element (zero based index )
+ /// (You may need to say 'value[0u]' to get your compiler to distinguish
+ /// this from the operator[] which takes a string.)
+ const Value& operator[](int index) const;
+
+ /// If the array contains at least index+1 elements, returns the element
+ /// value,
+ /// otherwise returns defaultValue.
+ Value get(ArrayIndex index, const Value& defaultValue) const;
+ /// Return true if index < size().
+ bool isValidIndex(ArrayIndex index) const;
+ /// \brief Append value to array at the end.
+ ///
+ /// Equivalent to jsonvalue[jsonvalue.size()] = value;
+ Value& append(const Value& value);
+
+ /// Access an object value by name, create a null member if it does not exist.
+ /// \note Because of our implementation, keys are limited to 2^30 -1 chars.
+ /// Exceeding that will cause an exception.
+ Value& operator[](const char* key);
+ /// Access an object value by name, returns null if there is no member with
+ /// that name.
+ const Value& operator[](const char* key) const;
+ /// Access an object value by name, create a null member if it does not exist.
+ /// \param key may contain embedded nulls.
+ Value& operator[](const std::string& key);
+ /// Access an object value by name, returns null if there is no member with
+ /// that name.
+ /// \param key may contain embedded nulls.
+ const Value& operator[](const std::string& key) const;
+ /** \brief Access an object value by name, create a null member if it does not
+ exist.
+
+ * If the object has no entry for that name, then the member name used to store
+ * the new entry is not duplicated.
+ * Example of use:
+ * \code
+ * Json::Value object;
+ * static const StaticString code("code");
+ * object[code] = 1234;
+ * \endcode
+ */
+ Value& operator[](const StaticString& key);
+#ifdef JSON_USE_CPPTL
+ /// Access an object value by name, create a null member if it does not exist.
+ Value& operator[](const CppTL::ConstString& key);
+ /// Access an object value by name, returns null if there is no member with
+ /// that name.
+ const Value& operator[](const CppTL::ConstString& key) const;
+#endif
+ /// Return the member named key if it exist, defaultValue otherwise.
+ /// \note deep copy
+ Value get(const char* key, const Value& defaultValue) const;
+ /// Return the member named key if it exist, defaultValue otherwise.
+ /// \note deep copy
+ /// \note key may contain embedded nulls.
+ Value get(const char* begin, const char* end, const Value& defaultValue) const;
+ /// Return the member named key if it exist, defaultValue otherwise.
+ /// \note deep copy
+ /// \param key may contain embedded nulls.
+ Value get(const std::string& key, const Value& defaultValue) const;
+#ifdef JSON_USE_CPPTL
+ /// Return the member named key if it exist, defaultValue otherwise.
+ /// \note deep copy
+ Value get(const CppTL::ConstString& key, const Value& defaultValue) const;
+#endif
+ /// Most general and efficient version of isMember()const, get()const,
+ /// and operator[]const
+ /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
+ Value const* find(char const* begin, char const* end) const;
+ /// Most general and efficient version of object-mutators.
+ /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30
+ /// \return non-zero, but JSON_ASSERT if this is neither object nor nullValue.
+ Value const* demand(char const* begin, char const* end);
+ /// \brief Remove and return the named member.
+ ///
+ /// Do nothing if it did not exist.
+ /// \return the removed Value, or null.
+ /// \pre type() is objectValue or nullValue
+ /// \post type() is unchanged
+ /// \deprecated
+ Value removeMember(const char* key);
+ /// Same as removeMember(const char*)
+ /// \param key may contain embedded nulls.
+ /// \deprecated
+ Value removeMember(const std::string& key);
+ /// Same as removeMember(const char* begin, const char* end, Value* removed),
+ /// but 'key' is null-terminated.
+ bool removeMember(const char* key, Value* removed);
+ /** \brief Remove the named map member.
+
+ Update 'removed' iff removed.
+ \param key may contain embedded nulls.
+ \return true iff removed (no exceptions)
+ */
+ bool removeMember(std::string const& key, Value* removed);
+ /// Same as removeMember(std::string const& key, Value* removed)
+ bool removeMember(const char* begin, const char* end, Value* removed);
+ /** \brief Remove the indexed array element.
+
+ O(n) expensive operations.
+ Update 'removed' iff removed.
+ \return true iff removed (no exceptions)
+ */
+ bool removeIndex(ArrayIndex i, Value* removed);
+
+ /// Return true if the object has a member named key.
+ /// \note 'key' must be null-terminated.
+ bool isMember(const char* key) const;
+ /// Return true if the object has a member named key.
+ /// \param key may contain embedded nulls.
+ bool isMember(const std::string& key) const;
+ /// Same as isMember(std::string const& key)const
+ bool isMember(const char* begin, const char* end) const;
+#ifdef JSON_USE_CPPTL
+ /// Return true if the object has a member named key.
+ bool isMember(const CppTL::ConstString& key) const;
+#endif
+
+ /// \brief Return a list of the member names.
+ ///
+ /// If null, return an empty list.
+ /// \pre type() is objectValue or nullValue
+ /// \post if type() was nullValue, it remains nullValue
+ Members getMemberNames() const;
+
+ //# ifdef JSON_USE_CPPTL
+ // EnumMemberNames enumMemberNames() const;
+ // EnumValues enumValues() const;
+ //# endif
+
+ /// \deprecated Always pass len.
+ JSONCPP_DEPRECATED("Use setComment(std::string const&) instead.")
+ void setComment(const char* comment, CommentPlacement placement);
+ /// Comments must be //... or /* ... */
+ void setComment(const char* comment, size_t len, CommentPlacement placement);
+ /// Comments must be //... or /* ... */
+ void setComment(const std::string& comment, CommentPlacement placement);
+ bool hasComment(CommentPlacement placement) const;
+ /// Include delimiters and embedded newlines.
+ std::string getComment(CommentPlacement placement) const;
+
+ std::string toStyledString() const;
+
+ const_iterator begin() const;
+ const_iterator end() const;
+
+ iterator begin();
+ iterator end();
+
+ // Accessors for the [start, limit) range of bytes within the JSON text from
+ // which this value was parsed, if any.
+ void setOffsetStart(size_t start);
+ void setOffsetLimit(size_t limit);
+ size_t getOffsetStart() const;
+ size_t getOffsetLimit() const;
+
+private:
+ void initBasic(ValueType type, bool allocated = false);
+
+ Value& resolveReference(const char* key);
+ Value& resolveReference(const char* key, const char* end);
+
+ struct CommentInfo {
+ CommentInfo();
+ ~CommentInfo();
+
+ void setComment(const char* text, size_t len);
+
+ char* comment_;
+ };
+
+ // struct MemberNamesTransform
+ //{
+ // typedef const char *result_type;
+ // const char *operator()( const CZString &name ) const
+ // {
+ // return name.c_str();
+ // }
+ //};
+
+ union ValueHolder {
+ LargestInt int_;
+ LargestUInt uint_;
+ double real_;
+ bool bool_;
+ char* string_; // actually ptr to unsigned, followed by str, unless !allocated_
+ ObjectValues* map_;
+ } value_;
+ ValueType type_ : 8;
+ unsigned int allocated_ : 1; // Notes: if declared as bool, bitfield is useless.
+ // If not allocated_, string_ must be null-terminated.
+ CommentInfo* comments_;
+ Value *default_value_; // if via .get( "key", default ), this was the default
+
+ // [start, limit) byte offsets in the source JSON text from which this Value
+ // was extracted.
+ size_t start_;
+ size_t limit_;
+};
+
+/** \brief Experimental and untested: represents an element of the "path" to
+ * access a node.
+ */
+class JSON_API PathArgument {
+public:
+ friend class Path;
+
+ PathArgument();
+ PathArgument(ArrayIndex index);
+ PathArgument(const char* key);
+ PathArgument(const std::string& key);
+
+private:
+ enum Kind {
+ kindNone = 0,
+ kindIndex,
+ kindKey
+ };
+ std::string key_;
+ ArrayIndex index_;
+ Kind kind_;
+};
+
+/** \brief Experimental and untested: represents a "path" to access a node.
+ *
+ * Syntax:
+ * - "." => root node
+ * - ".[n]" => elements at index 'n' of root node (an array value)
+ * - ".name" => member named 'name' of root node (an object value)
+ * - ".name1.name2.name3"
+ * - ".[0][1][2].name1[3]"
+ * - ".%" => member name is provided as parameter
+ * - ".[%]" => index is provied as parameter
+ */
+class JSON_API Path {
+public:
+ Path(const std::string& path,
+ const PathArgument& a1 = PathArgument(),
+ const PathArgument& a2 = PathArgument(),
+ const PathArgument& a3 = PathArgument(),
+ const PathArgument& a4 = PathArgument(),
+ const PathArgument& a5 = PathArgument());
+
+ const Value& resolve(const Value& root) const;
+ Value resolve(const Value& root, const Value& defaultValue) const;
+ /// Creates the "path" to access the specified node and returns a reference on
+ /// the node.
+ Value& make(Value& root) const;
+
+private:
+ typedef std::vector<const PathArgument*> InArgs;
+ typedef std::vector<PathArgument> Args;
+
+ void makePath(const std::string& path, const InArgs& in);
+ void addPathInArg(const std::string& path,
+ const InArgs& in,
+ InArgs::const_iterator& itInArg,
+ PathArgument::Kind kind);
+ void invalidPath(const std::string& path, int location);
+
+ Args args_;
+};
+
+/** \brief base class for Value iterators.
+ *
+ */
+class JSON_API ValueIteratorBase {
+public:
+ typedef std::bidirectional_iterator_tag iterator_category;
+ typedef unsigned int size_t;
+ typedef int difference_type;
+ typedef ValueIteratorBase SelfType;
+
+ bool operator==(const SelfType& other) const { return isEqual(other); }
+
+ bool operator!=(const SelfType& other) const { return !isEqual(other); }
+
+ difference_type operator-(const SelfType& other) const {
+ return other.computeDistance(*this);
+ }
+
+ /// Return either the index or the member name of the referenced value as a
+ /// Value.
+ Value key() const;
+
+ /// Return the index of the referenced Value, or -1 if it is not an arrayValue.
+ UInt index() const;
+
+ /// Return the member name of the referenced Value, or "" if it is not an
+ /// objectValue.
+ /// \note Avoid `c_str()` on result, as embedded zeroes are possible.
+ std::string name() const;
+
+ /// Return the member name of the referenced Value. "" if it is not an
+ /// objectValue.
+ /// \deprecated This cannot be used for UTF-8 strings, since there can be embedded nulls.
+ JSONCPP_DEPRECATED("Use `key = name();` instead.")
+ char const* memberName() const;
+ /// Return the member name of the referenced Value, or NULL if it is not an
+ /// objectValue.
+ /// \note Better version than memberName(). Allows embedded nulls.
+ char const* memberName(char const** end) const;
+
+protected:
+ Value& deref() const;
+
+ void increment();
+
+ void decrement();
+
+ difference_type computeDistance(const SelfType& other) const;
+
+ bool isEqual(const SelfType& other) const;
+
+ void copy(const SelfType& other);
+
+private:
+ Value::ObjectValues::iterator current_;
+ // Indicates that iterator is for a null value.
+ bool isNull_;
+
+public:
+ // For some reason, BORLAND needs these at the end, rather
+ // than earlier. No idea why.
+ ValueIteratorBase();
+ explicit ValueIteratorBase(const Value::ObjectValues::iterator& current);
+};
+
+/** \brief const iterator for object and array value.
+ *
+ */
+class JSON_API ValueConstIterator : public ValueIteratorBase {
+ friend class Value;
+
+public:
+ typedef const Value value_type;
+ //typedef unsigned int size_t;
+ //typedef int difference_type;
+ typedef const Value& reference;
+ typedef const Value* pointer;
+ typedef ValueConstIterator SelfType;
+
+ ValueConstIterator();
+ ValueConstIterator(ValueIterator const& other);
+
+private:
+/*! \internal Use by Value to create an iterator.
+ */
+ explicit ValueConstIterator(const Value::ObjectValues::iterator& current);
+public:
+ SelfType& operator=(const ValueIteratorBase& other);
+
+ SelfType operator++(int) {
+ SelfType temp(*this);
+ ++*this;
+ return temp;
+ }
+
+ SelfType operator--(int) {
+ SelfType temp(*this);
+ --*this;
+ return temp;
+ }
+
+ SelfType& operator--() {
+ decrement();
+ return *this;
+ }
+
+ SelfType& operator++() {
+ increment();
+ return *this;
+ }
+
+ reference operator*() const { return deref(); }
+
+ pointer operator->() const { return &deref(); }
+};
+
+/** \brief Iterator for object and array value.
+ */
+class JSON_API ValueIterator : public ValueIteratorBase {
+ friend class Value;
+
+public:
+ typedef Value value_type;
+ typedef unsigned int size_t;
+ typedef int difference_type;
+ typedef Value& reference;
+ typedef Value* pointer;
+ typedef ValueIterator SelfType;
+
+ ValueIterator();
+ explicit ValueIterator(const ValueConstIterator& other);
+ ValueIterator(const ValueIterator& other);
+
+private:
+/*! \internal Use by Value to create an iterator.
+ */
+ explicit ValueIterator(const Value::ObjectValues::iterator& current);
+public:
+ SelfType& operator=(const SelfType& other);
+
+ SelfType operator++(int) {
+ SelfType temp(*this);
+ ++*this;
+ return temp;
+ }
+
+ SelfType operator--(int) {
+ SelfType temp(*this);
+ --*this;
+ return temp;
+ }
+
+ SelfType& operator--() {
+ decrement();
+ return *this;
+ }
+
+ SelfType& operator++() {
+ increment();
+ return *this;
+ }
+
+ reference operator*() const { return deref(); }
+
+ pointer operator->() const { return &deref(); }
+};
+
+} // namespace Json
+
+
+namespace std {
+/// Specialize std::swap() for Json::Value.
+template<>
+inline void swap(Json::Value& a, Json::Value& b) { a.swap(b); }
+}
+
+
+#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
+#pragma warning(pop)
+#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
+
+#endif // CPPTL_JSON_H_INCLUDED
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: include/json/value.h
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: include/json/reader.h
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2007-2010 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+#ifndef CPPTL_JSON_READER_H_INCLUDED
+#define CPPTL_JSON_READER_H_INCLUDED
+
+#if !defined(JSON_IS_AMALGAMATION)
+#include "features.h"
+#include "value.h"
+#endif // if !defined(JSON_IS_AMALGAMATION)
+#include <deque>
+#include <iosfwd>
+#include <stack>
+#include <string>
+#include <istream>
+
+// Disable warning C4251: <data member>: <type> needs to have dll-interface to
+// be used by...
+#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
+#pragma warning(push)
+#pragma warning(disable : 4251)
+#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
+
+namespace Json {
+
+/** \brief Unserialize a <a HREF="http://www.json.org">JSON</a> document into a
+ *Value.
+ *
+ * \deprecated Use CharReader and CharReaderBuilder.
+ */
+class JSON_API Reader {
+public:
+ typedef char Char;
+ typedef const Char* Location;
+
+ /** \brief An error tagged with where in the JSON text it was encountered.
+ *
+ * The offsets give the [start, limit) range of bytes within the text. Note
+ * that this is bytes, not codepoints.
+ *
+ */
+ struct StructuredError {
+ size_t offset_start;
+ size_t offset_limit;
+ std::string message;
+ };
+
+ /** \brief Constructs a Reader allowing all features
+ * for parsing.
+ */
+ Reader();
+
+ /** \brief Constructs a Reader allowing the specified feature set
+ * for parsing.
+ */
+ Reader(const Features& features);
+
+ /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
+ * document.
+ * \param document UTF-8 encoded string containing the document to read.
+ * \param root [out] Contains the root value of the document if it was
+ * successfully parsed.
+ * \param collectComments \c true to collect comment and allow writing them
+ * back during
+ * serialization, \c false to discard comments.
+ * This parameter is ignored if
+ * Features::allowComments_
+ * is \c false.
+ * \return \c true if the document was successfully parsed, \c false if an
+ * error occurred.
+ */
+ bool
+ parse(const std::string& document, Value& root, bool collectComments = true);
+
+ /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
+ document.
+ * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the
+ document to read.
+ * \param endDoc Pointer on the end of the UTF-8 encoded string of the
+ document to read.
+ * Must be >= beginDoc.
+ * \param root [out] Contains the root value of the document if it was
+ * successfully parsed.
+ * \param collectComments \c true to collect comment and allow writing them
+ back during
+ * serialization, \c false to discard comments.
+ * This parameter is ignored if
+ Features::allowComments_
+ * is \c false.
+ * \return \c true if the document was successfully parsed, \c false if an
+ error occurred.
+ */
+ bool parse(const char* beginDoc,
+ const char* endDoc,
+ Value& root,
+ bool collectComments = true);
+
+ /// \brief Parse from input stream.
+ /// \see Json::operator>>(std::istream&, Json::Value&).
+ bool parse(std::istream& is, Value& root, bool collectComments = true);
+
+ /** \brief Returns a user friendly string that list errors in the parsed
+ * document.
+ * \return Formatted error message with the list of errors with their location
+ * in
+ * the parsed document. An empty string is returned if no error
+ * occurred
+ * during parsing.
+ * \deprecated Use getFormattedErrorMessages() instead (typo fix).
+ */
+ JSONCPP_DEPRECATED("Use getFormattedErrorMessages() instead.")
+ std::string getFormatedErrorMessages() const;
+
+ /** \brief Returns a user friendly string that list errors in the parsed
+ * document.
+ * \return Formatted error message with the list of errors with their location
+ * in
+ * the parsed document. An empty string is returned if no error
+ * occurred
+ * during parsing.
+ */
+ std::string getFormattedErrorMessages() const;
+
+ /** \brief Returns a vector of structured erros encounted while parsing.
+ * \return A (possibly empty) vector of StructuredError objects. Currently
+ * only one error can be returned, but the caller should tolerate
+ * multiple
+ * errors. This can occur if the parser recovers from a non-fatal
+ * parse error and then encounters additional errors.
+ */
+ std::vector<StructuredError> getStructuredErrors() const;
+
+ /** \brief Add a semantic error message.
+ * \param value JSON Value location associated with the error
+ * \param message The error message.
+ * \return \c true if the error was successfully added, \c false if the
+ * Value offset exceeds the document size.
+ */
+ bool pushError(const Value& value, const std::string& message);
+
+ /** \brief Add a semantic error message with extra context.
+ * \param value JSON Value location associated with the error
+ * \param message The error message.
+ * \param extra Additional JSON Value location to contextualize the error
+ * \return \c true if the error was successfully added, \c false if either
+ * Value offset exceeds the document size.
+ */
+ bool pushError(const Value& value, const std::string& message, const Value& extra);
+
+ /** \brief Return whether there are any errors.
+ * \return \c true if there are no errors to report \c false if
+ * errors have occurred.
+ */
+ bool good() const;
+
+private:
+ enum TokenType {
+ tokenEndOfStream = 0,
+ tokenObjectBegin,
+ tokenObjectEnd,
+ tokenArrayBegin,
+ tokenArrayEnd,
+ tokenString,
+ tokenNumber,
+ tokenTrue,
+ tokenFalse,
+ tokenNull,
+ tokenArraySeparator,
+ tokenMemberSeparator,
+ tokenComment,
+ tokenError
+ };
+
+ class Token {
+ public:
+ TokenType type_;
+ Location start_;
+ Location end_;
+ };
+
+ class ErrorInfo {
+ public:
+ Token token_;
+ std::string message_;
+ Location extra_;
+ };
+
+ typedef std::deque<ErrorInfo> Errors;
+
+ bool readToken(Token& token);
+ void skipSpaces();
+ bool match(Location pattern, int patternLength);
+ bool readComment();
+ bool readCStyleComment();
+ bool readCppStyleComment();
+ bool readString();
+ void readNumber();
+ bool readValue();
+ bool readObject(Token& token);
+ bool readArray(Token& token);
+ bool decodeNumber(Token& token);
+ bool decodeNumber(Token& token, Value& decoded);
+ bool decodeString(Token& token);
+ bool decodeString(Token& token, std::string& decoded);
+ bool decodeDouble(Token& token);
+ bool decodeDouble(Token& token, Value& decoded);
+ bool decodeUnicodeCodePoint(Token& token,
+ Location& current,
+ Location end,
+ unsigned int& unicode);
+ bool decodeUnicodeEscapeSequence(Token& token,
+ Location& current,
+ Location end,
+ unsigned int& unicode);
+ bool addError(const std::string& message, Token& token, Location extra = 0);
+ bool recoverFromError(TokenType skipUntilToken);
+ bool addErrorAndRecover(const std::string& message,
+ Token& token,
+ TokenType skipUntilToken);
+ void skipUntilSpace();
+ Value& currentValue();
+ Char getNextChar();
+ void
+ getLocationLineAndColumn(Location location, int& line, int& column) const;
+ std::string getLocationLineAndColumn(Location location) const;
+ std::string getLocationSnippet(Location location) const;
+ void addComment(Location begin, Location end, CommentPlacement placement);
+ void skipCommentTokens(Token& token);
+
+ typedef std::stack<Value*> Nodes;
+ Nodes nodes_;
+ Errors errors_;
+ std::string document_;
+ Location begin_;
+ Location end_;
+ Location current_;
+ Location lastValueEnd_;
+ Value* lastValue_;
+ std::string commentsBefore_;
+ Features features_;
+ bool collectComments_;
+}; // Reader
+
+/** Interface for reading JSON from a char array.
+ */
+class JSON_API CharReader {
+public:
+ virtual ~CharReader() {}
+ /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a>
+ document.
+ * The document must be a UTF-8 encoded string containing the document to read.
+ *
+ * \param beginDoc Pointer on the beginning of the UTF-8 encoded string of the
+ document to read.
+ * \param endDoc Pointer on the end of the UTF-8 encoded string of the
+ document to read.
+ * Must be >= beginDoc.
+ * \param root [out] Contains the root value of the document if it was
+ * successfully parsed.
+ * \param errs [out] Formatted error messages (if not NULL)
+ * a user friendly string that lists errors in the parsed
+ * document.
+ * \return \c true if the document was successfully parsed, \c false if an
+ error occurred.
+ */
+ virtual bool parse(
+ char const* beginDoc, char const* endDoc,
+ Value* root, std::string* errs) = 0;
+
+ class JSON_API Factory {
+ public:
+ virtual ~Factory() {}
+ /** \brief Allocate a CharReader via operator new().
+ * \throw std::exception if something goes wrong (e.g. invalid settings)
+ */
+ virtual CharReader* newCharReader() const = 0;
+ }; // Factory
+}; // CharReader
+
+/** \brief Build a CharReader implementation.
+
+Usage:
+\code
+ using namespace Json;
+ CharReaderBuilder builder;
+ builder["collectComments"] = false;
+ Value value;
+ std::string errs;
+ bool ok = parseFromStream(builder, std::cin, &value, &errs);
+\endcode
+*/
+class JSON_API CharReaderBuilder : public CharReader::Factory {
+public:
+ // Note: We use a Json::Value so that we can add data-members to this class
+ // without a major version bump.
+ /** Configuration of this builder.
+ These are case-sensitive.
+ Available settings (case-sensitive):
+ - `"collectComments": false or true`
+ - true to collect comment and allow writing them
+ back during serialization, false to discard comments.
+ This parameter is ignored if allowComments is false.
+ - `"allowComments": false or true`
+ - true if comments are allowed.
+ - `"strictRoot": false or true`
+ - true if root must be either an array or an object value
+ - `"allowDroppedNullPlaceholders": false or true`
+ - true if dropped null placeholders are allowed. (See StreamWriterBuilder.)
+ - `"allowNumericKeys": false or true`
+ - true if numeric object keys are allowed.
+ - `"allowSingleQuotes": false or true`
+ - true if '' are allowed for strings (both keys and values)
+ - `"stackLimit": integer`
+ - Exceeding stackLimit (recursive depth of `readValue()`) will
+ cause an exception.
+ - This is a security issue (seg-faults caused by deeply nested JSON),
+ so the default is low.
+ - `"failIfExtra": false or true`
+ - If true, `parse()` returns false when extra non-whitespace trails
+ the JSON value in the input string.
+ - `"rejectDupKeys": false or true`
+ - If true, `parse()` returns false when a key is duplicated within an object.
+ - `"allowSpecialFloats": false or true`
+ - If true, special float values (NaNs and infinities) are allowed
+ and their values are lossfree restorable.
+
+ You can examine 'settings_` yourself
+ to see the defaults. You can also write and read them just like any
+ JSON Value.
+ \sa setDefaults()
+ */
+ Json::Value settings_;
+
+ CharReaderBuilder();
+ ~CharReaderBuilder();
+
+ CharReader* newCharReader() const;
+
+ /** \return true if 'settings' are legal and consistent;
+ * otherwise, indicate bad settings via 'invalid'.
+ */
+ bool validate(Json::Value* invalid) const;
+
+ /** A simple way to update a specific setting.
+ */
+ Value& operator[](std::string key);
+
+ /** Called by ctor, but you can use this to reset settings_.
+ * \pre 'settings' != NULL (but Json::null is fine)
+ * \remark Defaults:
+ * \snippet src/lib_json/json_reader.cpp CharReaderBuilderDefaults
+ */
+ static void setDefaults(Json::Value* settings);
+ /** Same as old Features::strictMode().
+ * \pre 'settings' != NULL (but Json::null is fine)
+ * \remark Defaults:
+ * \snippet src/lib_json/json_reader.cpp CharReaderBuilderStrictMode
+ */
+ static void strictMode(Json::Value* settings);
+};
+
+/** Consume entire stream and use its begin/end.
+ * Someday we might have a real StreamReader, but for now this
+ * is convenient.
+ */
+bool JSON_API parseFromStream(
+ CharReader::Factory const&,
+ std::istream&,
+ Value* root, std::string* errs);
+
+/** \brief Read from 'sin' into 'root'.
+
+ Always keep comments from the input JSON.
+
+ This can be used to read a file into a particular sub-object.
+ For example:
+ \code
+ Json::Value root;
+ cin >> root["dir"]["file"];
+ cout << root;
+ \endcode
+ Result:
+ \verbatim
+ {
+ "dir": {
+ "file": {
+ // The input stream JSON would be nested here.
+ }
+ }
+ }
+ \endverbatim
+ \throw std::exception on parse error.
+ \see Json::operator<<()
+*/
+JSON_API std::istream& operator>>(std::istream&, Value&);
+
+} // namespace Json
+
+#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
+#pragma warning(pop)
+#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
+
+#endif // CPPTL_JSON_READER_H_INCLUDED
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: include/json/reader.h
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: include/json/writer.h
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2007-2010 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+#ifndef JSON_WRITER_H_INCLUDED
+#define JSON_WRITER_H_INCLUDED
+
+#if !defined(JSON_IS_AMALGAMATION)
+#include "value.h"
+#endif // if !defined(JSON_IS_AMALGAMATION)
+#include <vector>
+#include <string>
+#include <ostream>
+
+// Disable warning C4251: <data member>: <type> needs to have dll-interface to
+// be used by...
+#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
+#pragma warning(push)
+#pragma warning(disable : 4251)
+#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
+
+namespace Json {
+
+class Value;
+
+/**
+
+Usage:
+\code
+ using namespace Json;
+ void writeToStdout(StreamWriter::Factory const& factory, Value const& value) {
+ std::unique_ptr<StreamWriter> const writer(
+ factory.newStreamWriter());
+ writer->write(value, &std::cout);
+ std::cout << std::endl; // add lf and flush
+ }
+\endcode
+*/
+class JSON_API StreamWriter {
+protected:
+ std::ostream* sout_; // not owned; will not delete
+public:
+ StreamWriter();
+ virtual ~StreamWriter();
+ /** Write Value into document as configured in sub-class.
+ Do not take ownership of sout, but maintain a reference during function.
+ \pre sout != NULL
+ \return zero on success (For now, we always return zero, so check the stream instead.)
+ \throw std::exception possibly, depending on configuration
+ */
+ virtual int write(Value const& root, std::ostream* sout) = 0;
+
+ /** \brief A simple abstract factory.
+ */
+ class JSON_API Factory {
+ public:
+ virtual ~Factory();
+ /** \brief Allocate a CharReader via operator new().
+ * \throw std::exception if something goes wrong (e.g. invalid settings)
+ */
+ virtual StreamWriter* newStreamWriter() const = 0;
+ }; // Factory
+}; // StreamWriter
+
+/** \brief Write into stringstream, then return string, for convenience.
+ * A StreamWriter will be created from the factory, used, and then deleted.
+ */
+std::string JSON_API writeString(StreamWriter::Factory const& factory, Value const& root);
+
+
+/** \brief Build a StreamWriter implementation.
+
+Usage:
+\code
+ using namespace Json;
+ Value value = ...;
+ StreamWriterBuilder builder;
+ builder["commentStyle"] = "None";
+ builder["indentation"] = " "; // or whatever you like
+ std::unique_ptr<Json::StreamWriter> writer(
+ builder.newStreamWriter());
+ writer->write(value, &std::cout);
+ std::cout << std::endl; // add lf and flush
+\endcode
+*/
+class JSON_API StreamWriterBuilder : public StreamWriter::Factory {
+public:
+ // Note: We use a Json::Value so that we can add data-members to this class
+ // without a major version bump.
+ /** Configuration of this builder.
+ Available settings (case-sensitive):
+ - "commentStyle": "None" or "All"
+ - "indentation": "<anything>"
+ - "enableYAMLCompatibility": false or true
+ - slightly change the whitespace around colons
+ - "dropNullPlaceholders": false or true
+ - Drop the "null" string from the writer's output for nullValues.
+ Strictly speaking, this is not valid JSON. But when the output is being
+ fed to a browser's Javascript, it makes for smaller output and the
+ browser can handle the output just fine.
+ - "useSpecialFloats": false or true
+ - If true, outputs non-finite floating point values in the following way:
+ NaN values as "NaN", positive infinity as "Infinity", and negative infinity
+ as "-Infinity".
+
+ You can examine 'settings_` yourself
+ to see the defaults. You can also write and read them just like any
+ JSON Value.
+ \sa setDefaults()
+ */
+ Json::Value settings_;
+
+ StreamWriterBuilder();
+ ~StreamWriterBuilder();
+
+ /**
+ * \throw std::exception if something goes wrong (e.g. invalid settings)
+ */
+ StreamWriter* newStreamWriter() const;
+
+ /** \return true if 'settings' are legal and consistent;
+ * otherwise, indicate bad settings via 'invalid'.
+ */
+ bool validate(Json::Value* invalid) const;
+ /** A simple way to update a specific setting.
+ */
+ Value& operator[](std::string key);
+
+ /** Called by ctor, but you can use this to reset settings_.
+ * \pre 'settings' != NULL (but Json::null is fine)
+ * \remark Defaults:
+ * \snippet src/lib_json/json_writer.cpp StreamWriterBuilderDefaults
+ */
+ static void setDefaults(Json::Value* settings);
+};
+
+/** \brief Abstract class for writers.
+ * \deprecated Use StreamWriter. (And really, this is an implementation detail.)
+ */
+class JSON_API Writer {
+public:
+ virtual ~Writer();
+
+ virtual std::string write(const Value& root) = 0;
+};
+
+/** \brief Outputs a Value in <a HREF="http://www.json.org">JSON</a> format
+ *without formatting (not human friendly).
+ *
+ * The JSON document is written in a single line. It is not intended for 'human'
+ *consumption,
+ * but may be usefull to support feature such as RPC where bandwith is limited.
+ * \sa Reader, Value
+ * \deprecated Use StreamWriterBuilder.
+ */
+class JSON_API FastWriter : public Writer {
+
+public:
+ FastWriter();
+ ~FastWriter() {}
+
+ void enableYAMLCompatibility();
+
+ /** \brief Drop the "null" string from the writer's output for nullValues.
+ * Strictly speaking, this is not valid JSON. But when the output is being
+ * fed to a browser's Javascript, it makes for smaller output and the
+ * browser can handle the output just fine.
+ */
+ void dropNullPlaceholders();
+
+ void omitEndingLineFeed();
+
+public: // overridden from Writer
+ std::string write(const Value& root);
+
+private:
+ void writeValue(const Value& value);
+
+ std::string document_;
+ bool yamlCompatiblityEnabled_;
+ bool dropNullPlaceholders_;
+ bool omitEndingLineFeed_;
+};
+
+/** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a
+ *human friendly way.
+ *
+ * The rules for line break and indent are as follow:
+ * - Object value:
+ * - if empty then print {} without indent and line break
+ * - if not empty the print '{', line break & indent, print one value per
+ *line
+ * and then unindent and line break and print '}'.
+ * - Array value:
+ * - if empty then print [] without indent and line break
+ * - if the array contains no object value, empty array or some other value
+ *types,
+ * and all the values fit on one lines, then print the array on a single
+ *line.
+ * - otherwise, it the values do not fit on one line, or the array contains
+ * object or non empty array, then print one value per line.
+ *
+ * If the Value have comments then they are outputed according to their
+ *#CommentPlacement.
+ *
+ * \sa Reader, Value, Value::setComment()
+ * \deprecated Use StreamWriterBuilder.
+ */
+class JSON_API StyledWriter : public Writer {
+public:
+ StyledWriter();
+ ~StyledWriter() {}
+
+public: // overridden from Writer
+ /** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
+ * \param root Value to serialize.
+ * \return String containing the JSON document that represents the root value.
+ */
+ std::string write(const Value& root);
+
+private:
+ void writeValue(const Value& value);
+ void writeArrayValue(const Value& value);
+ bool isMultineArray(const Value& value);
+ void pushValue(const std::string& value);
+ void writeIndent();
+ void writeWithIndent(const std::string& value);
+ void indent();
+ void unindent();
+ void writeCommentBeforeValue(const Value& root);
+ void writeCommentAfterValueOnSameLine(const Value& root);
+ bool hasCommentForValue(const Value& value);
+ static std::string normalizeEOL(const std::string& text);
+
+ typedef std::vector<std::string> ChildValues;
+
+ ChildValues childValues_;
+ std::string document_;
+ std::string indentString_;
+ int rightMargin_;
+ int indentSize_;
+ bool addChildValues_;
+};
+
+/** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a
+ human friendly way,
+ to a stream rather than to a string.
+ *
+ * The rules for line break and indent are as follow:
+ * - Object value:
+ * - if empty then print {} without indent and line break
+ * - if not empty the print '{', line break & indent, print one value per
+ line
+ * and then unindent and line break and print '}'.
+ * - Array value:
+ * - if empty then print [] without indent and line break
+ * - if the array contains no object value, empty array or some other value
+ types,
+ * and all the values fit on one lines, then print the array on a single
+ line.
+ * - otherwise, it the values do not fit on one line, or the array contains
+ * object or non empty array, then print one value per line.
+ *
+ * If the Value have comments then they are outputed according to their
+ #CommentPlacement.
+ *
+ * \param indentation Each level will be indented by this amount extra.
+ * \sa Reader, Value, Value::setComment()
+ * \deprecated Use StreamWriterBuilder.
+ */
+class JSON_API StyledStreamWriter {
+public:
+ StyledStreamWriter(std::string indentation = "\t");
+ ~StyledStreamWriter() {}
+
+public:
+ /** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format.
+ * \param out Stream to write to. (Can be ostringstream, e.g.)
+ * \param root Value to serialize.
+ * \note There is no point in deriving from Writer, since write() should not
+ * return a value.
+ */
+ void write(std::ostream& out, const Value& root);
+
+private:
+ void writeValue(const Value& value);
+ void writeArrayValue(const Value& value);
+ bool isMultineArray(const Value& value);
+ void pushValue(const std::string& value);
+ void writeIndent();
+ void writeWithIndent(const std::string& value);
+ void indent();
+ void unindent();
+ void writeCommentBeforeValue(const Value& root);
+ void writeCommentAfterValueOnSameLine(const Value& root);
+ bool hasCommentForValue(const Value& value);
+ static std::string normalizeEOL(const std::string& text);
+
+ typedef std::vector<std::string> ChildValues;
+
+ ChildValues childValues_;
+ std::ostream* document_;
+ std::string indentString_;
+ int rightMargin_;
+ std::string indentation_;
+ bool addChildValues_ : 1;
+ bool indented_ : 1;
+};
+
+#if defined(JSON_HAS_INT64)
+std::string JSON_API valueToString(Int value);
+std::string JSON_API valueToString(UInt value);
+#endif // if defined(JSON_HAS_INT64)
+std::string JSON_API valueToString(LargestInt value);
+std::string JSON_API valueToString(LargestUInt value);
+std::string JSON_API valueToString(double value);
+std::string JSON_API valueToString(bool value);
+std::string JSON_API valueToQuotedString(const char* value);
+
+/// \brief Output using the StyledStreamWriter.
+/// \see Json::operator>>()
+JSON_API std::ostream& operator<<(std::ostream&, const Value& root);
+
+} // namespace Json
+
+#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
+#pragma warning(pop)
+#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
+
+#endif // JSON_WRITER_H_INCLUDED
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: include/json/writer.h
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: include/json/assertions.h
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2007-2010 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+#ifndef CPPTL_JSON_ASSERTIONS_H_INCLUDED
+#define CPPTL_JSON_ASSERTIONS_H_INCLUDED
+
+#include <stdlib.h>
+#include <sstream>
+
+#if !defined(JSON_IS_AMALGAMATION)
+#include "config.h"
+#endif // if !defined(JSON_IS_AMALGAMATION)
+
+/** It should not be possible for a maliciously designed file to
+ * cause an abort() or seg-fault, so these macros are used only
+ * for pre-condition violations and internal logic errors.
+ */
+#if JSON_USE_EXCEPTION
+
+// @todo <= add detail about condition in exception
+# define JSON_ASSERT(condition) \
+ {if (!(condition)) {Json::throwLogicError( "assert json failed" );}}
+
+# define JSON_FAIL_MESSAGE(message) \
+ { \
+ std::ostringstream oss; oss << message; \
+ Json::throwLogicError(oss.str()); \
+ abort(); \
+ }
+
+#else // JSON_USE_EXCEPTION
+
+# define JSON_ASSERT(condition) assert(condition)
+
+// The call to assert() will show the failure message in debug builds. In
+// release builds we abort, for a core-dump or debugger.
+# define JSON_FAIL_MESSAGE(message) \
+ { \
+ std::ostringstream oss; oss << message; \
+ assert(false && oss.str().c_str()); \
+ abort(); \
+ }
+
+
+#endif
+
+#define JSON_ASSERT_MESSAGE(condition, message) \
+ if (!(condition)) { \
+ JSON_FAIL_MESSAGE(message); \
+ }
+
+#endif // CPPTL_JSON_ASSERTIONS_H_INCLUDED
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: include/json/assertions.h
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+#endif //ifndef JSON_AMALGATED_H_INCLUDED
diff --git a/steam-shim/jsoncpp.cpp b/steam-shim/jsoncpp.cpp
new file mode 100644
index 0000000..e67d353
--- /dev/null
+++ b/steam-shim/jsoncpp.cpp
@@ -0,0 +1,5266 @@
+/// Json-cpp amalgated source (http://jsoncpp.sourceforge.net/).
+/// It is intended to be used with #include "json/json.h"
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: LICENSE
+// //////////////////////////////////////////////////////////////////////
+
+/*
+The JsonCpp library's source code, including accompanying documentation,
+tests and demonstration applications, are licensed under the following
+conditions...
+
+The author (Baptiste Lepilleur) explicitly disclaims copyright in all
+jurisdictions which recognize such a disclaimer. In such jurisdictions,
+this software is released into the Public Domain.
+
+In jurisdictions which do not recognize Public Domain property (e.g. Germany as of
+2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is
+released under the terms of the MIT License (see below).
+
+In jurisdictions which recognize Public Domain property, the user of this
+software may choose to accept it either as 1) Public Domain, 2) under the
+conditions of the MIT License (see below), or 3) under the terms of dual
+Public Domain/MIT License conditions described here, as they choose.
+
+The MIT License is about as close to Public Domain as a license can get, and is
+described in clear, concise terms at:
+
+ http://en.wikipedia.org/wiki/MIT_License
+
+The full text of the MIT License follows:
+
+========================================================================
+Copyright (c) 2007-2010 Baptiste Lepilleur
+
+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.
+========================================================================
+(END LICENSE TEXT)
+
+The MIT license is compatible with both the GPL and commercial
+software, affording one all of the rights of Public Domain with the
+minor nuisance of being required to keep the above copyright notice
+and license text in the source code. Note also that by accepting the
+Public Domain "license" you can re-license your copy using whatever
+license you like.
+
+*/
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: LICENSE
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+
+#include "json/json.h"
+
+#ifndef JSON_IS_AMALGAMATION
+#error "Compile with -I PATH_TO_JSON_DIRECTORY"
+#endif
+
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: src/lib_json/json_tool.h
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2007-2010 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+#ifndef LIB_JSONCPP_JSON_TOOL_H_INCLUDED
+#define LIB_JSONCPP_JSON_TOOL_H_INCLUDED
+
+/* This header provides common string manipulation support, such as UTF-8,
+ * portable conversion from/to string...
+ *
+ * It is an internal header that must not be exposed.
+ */
+
+namespace Json {
+
+/// Converts a unicode code-point to UTF-8.
+static inline std::string codePointToUTF8(unsigned int cp) {
+ std::string result;
+
+ // based on description from http://en.wikipedia.org/wiki/UTF-8
+
+ if (cp <= 0x7f) {
+ result.resize(1);
+ result[0] = static_cast<char>(cp);
+ } else if (cp <= 0x7FF) {
+ result.resize(2);
+ result[1] = static_cast<char>(0x80 | (0x3f & cp));
+ result[0] = static_cast<char>(0xC0 | (0x1f & (cp >> 6)));
+ } else if (cp <= 0xFFFF) {
+ result.resize(3);
+ result[2] = static_cast<char>(0x80 | (0x3f & cp));
+ result[1] = static_cast<char>(0x80 | (0x3f & (cp >> 6)));
+ result[0] = static_cast<char>(0xE0 | (0xf & (cp >> 12)));
+ } else if (cp <= 0x10FFFF) {
+ result.resize(4);
+ result[3] = static_cast<char>(0x80 | (0x3f & cp));
+ result[2] = static_cast<char>(0x80 | (0x3f & (cp >> 6)));
+ result[1] = static_cast<char>(0x80 | (0x3f & (cp >> 12)));
+ result[0] = static_cast<char>(0xF0 | (0x7 & (cp >> 18)));
+ }
+
+ return result;
+}
+
+/// Returns true if ch is a control character (in range [1,31]).
+static inline bool isControlCharacter(char ch) { return ch > 0 && ch <= 0x1F; }
+
+enum {
+ /// Constant that specify the size of the buffer that must be passed to
+ /// uintToString.
+ uintToStringBufferSize = 3 * sizeof(LargestUInt) + 1
+};
+
+// Defines a char buffer for use with uintToString().
+typedef char UIntToStringBuffer[uintToStringBufferSize];
+
+/** Converts an unsigned integer to string.
+ * @param value Unsigned interger to convert to string
+ * @param current Input/Output string buffer.
+ * Must have at least uintToStringBufferSize chars free.
+ */
+static inline void uintToString(LargestUInt value, char*& current) {
+ *--current = 0;
+ do {
+ *--current = static_cast<signed char>(value % 10U + static_cast<unsigned>('0'));
+ value /= 10;
+ } while (value != 0);
+}
+
+/** Change ',' to '.' everywhere in buffer.
+ *
+ * We had a sophisticated way, but it did not work in WinCE.
+ * @see https://github.com/open-source-parsers/jsoncpp/pull/9
+ */
+static inline void fixNumericLocale(char* begin, char* end) {
+ while (begin < end) {
+ if (*begin == ',') {
+ *begin = '.';
+ }
+ ++begin;
+ }
+}
+
+} // namespace Json {
+
+#endif // LIB_JSONCPP_JSON_TOOL_H_INCLUDED
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: src/lib_json/json_tool.h
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: src/lib_json/json_reader.cpp
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2007-2011 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+#if !defined(JSON_IS_AMALGAMATION)
+#include <json/assertions.h>
+#include <json/reader.h>
+#include <json/value.h>
+#include "json_tool.h"
+#endif // if !defined(JSON_IS_AMALGAMATION)
+#include <utility>
+#include <cstdio>
+#include <cassert>
+#include <cstring>
+#include <istream>
+#include <sstream>
+#include <memory>
+#include <set>
+#include <limits>
+
+#if defined(_MSC_VER)
+#if !defined(WINCE) && defined(__STDC_SECURE_LIB__) && _MSC_VER >= 1500 // VC++ 9.0 and above
+#define snprintf sprintf_s
+#elif _MSC_VER >= 1900 // VC++ 14.0 and above
+#define snprintf std::snprintf
+#else
+#define snprintf _snprintf
+#endif
+#elif defined(__ANDROID__) || defined(__QNXNTO__)
+#define snprintf snprintf
+#elif __cplusplus >= 201103L
+#define snprintf std::snprintf
+#endif
+
+#if defined(__QNXNTO__)
+#define sscanf std::sscanf
+#endif
+
+#if defined(_MSC_VER) && _MSC_VER >= 1400 // VC++ 8.0
+// Disable warning about strdup being deprecated.
+#pragma warning(disable : 4996)
+#endif
+
+static int const stackLimit_g = 1000;
+static int stackDepth_g = 0; // see readValue()
+
+namespace Json {
+
+#if __cplusplus >= 201103L || (defined(_CPPLIB_VER) && _CPPLIB_VER >= 520)
+typedef std::unique_ptr<CharReader> CharReaderPtr;
+#else
+typedef std::auto_ptr<CharReader> CharReaderPtr;
+#endif
+
+// Implementation of class Features
+// ////////////////////////////////
+
+Features::Features()
+ : allowComments_(true), strictRoot_(false),
+ allowDroppedNullPlaceholders_(false), allowNumericKeys_(false) {}
+
+Features Features::all() { return Features(); }
+
+Features Features::strictMode() {
+ Features features;
+ features.allowComments_ = false;
+ features.strictRoot_ = true;
+ features.allowDroppedNullPlaceholders_ = false;
+ features.allowNumericKeys_ = false;
+ return features;
+}
+
+// Implementation of class Reader
+// ////////////////////////////////
+
+static bool containsNewLine(Reader::Location begin, Reader::Location end) {
+ for (; begin < end; ++begin)
+ if (*begin == '\n' || *begin == '\r')
+ return true;
+ return false;
+}
+
+// Class Reader
+// //////////////////////////////////////////////////////////////////
+
+Reader::Reader()
+ : errors_(), document_(), begin_(), end_(), current_(), lastValueEnd_(),
+ lastValue_(), commentsBefore_(), features_(Features::all()),
+ collectComments_() {}
+
+Reader::Reader(const Features& features)
+ : errors_(), document_(), begin_(), end_(), current_(), lastValueEnd_(),
+ lastValue_(), commentsBefore_(), features_(features), collectComments_() {
+}
+
+bool
+Reader::parse(const std::string& document, Value& root, bool collectComments) {
+ document_ = document;
+ const char* begin = document_.c_str();
+ const char* end = begin + document_.length();
+ return parse(begin, end, root, collectComments);
+}
+
+bool Reader::parse(std::istream& sin, Value& root, bool collectComments) {
+ // std::istream_iterator<char> begin(sin);
+ // std::istream_iterator<char> end;
+ // Those would allow streamed input from a file, if parse() were a
+ // template function.
+
+ // Since std::string is reference-counted, this at least does not
+ // create an extra copy.
+ std::string doc;
+ std::getline(sin, doc, (char)EOF);
+ return parse(doc, root, collectComments);
+}
+
+bool Reader::parse(const char* beginDoc,
+ const char* endDoc,
+ Value& root,
+ bool collectComments) {
+ if (!features_.allowComments_) {
+ collectComments = false;
+ }
+
+ begin_ = beginDoc;
+ end_ = endDoc;
+ collectComments_ = collectComments;
+ current_ = begin_;
+ lastValueEnd_ = 0;
+ lastValue_ = 0;
+ commentsBefore_ = "";
+ errors_.clear();
+ while (!nodes_.empty())
+ nodes_.pop();
+ nodes_.push(&root);
+
+ stackDepth_g = 0; // Yes, this is bad coding, but options are limited.
+ bool successful = readValue();
+ Token token;
+ skipCommentTokens(token);
+ if (collectComments_ && !commentsBefore_.empty())
+ root.setComment(commentsBefore_, commentAfter);
+ if (features_.strictRoot_) {
+ if (!root.isArray() && !root.isObject()) {
+ // Set error location to start of doc, ideally should be first token found
+ // in doc
+ token.type_ = tokenError;
+ token.start_ = beginDoc;
+ token.end_ = endDoc;
+ addError(
+ "A valid JSON document must be either an array or an object value.",
+ token);
+ return false;
+ }
+ }
+ return successful;
+}
+
+bool Reader::readValue() {
+ // This is a non-reentrant way to support a stackLimit. Terrible!
+ // But this deprecated class has a security problem: Bad input can
+ // cause a seg-fault. This seems like a fair, binary-compatible way
+ // to prevent the problem.
+ if (stackDepth_g >= stackLimit_g) throwRuntimeError("Exceeded stackLimit in readValue().");
+ ++stackDepth_g;
+
+ Token token;
+ skipCommentTokens(token);
+ bool successful = true;
+
+ if (collectComments_ && !commentsBefore_.empty()) {
+ currentValue().setComment(commentsBefore_, commentBefore);
+ commentsBefore_ = "";
+ }
+
+ switch (token.type_) {
+ case tokenObjectBegin:
+ successful = readObject(token);
+ currentValue().setOffsetLimit(current_ - begin_);
+ break;
+ case tokenArrayBegin:
+ successful = readArray(token);
+ currentValue().setOffsetLimit(current_ - begin_);
+ break;
+ case tokenNumber:
+ successful = decodeNumber(token);
+ break;
+ case tokenString:
+ successful = decodeString(token);
+ break;
+ case tokenTrue:
+ {
+ Value v(true);
+ currentValue().swapPayload(v);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ }
+ break;
+ case tokenFalse:
+ {
+ Value v(false);
+ currentValue().swapPayload(v);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ }
+ break;
+ case tokenNull:
+ {
+ Value v;
+ currentValue().swapPayload(v);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ }
+ break;
+ case tokenArraySeparator:
+ case tokenObjectEnd:
+ case tokenArrayEnd:
+ if (features_.allowDroppedNullPlaceholders_) {
+ // "Un-read" the current token and mark the current value as a null
+ // token.
+ current_--;
+ Value v;
+ currentValue().swapPayload(v);
+ currentValue().setOffsetStart(current_ - begin_ - 1);
+ currentValue().setOffsetLimit(current_ - begin_);
+ break;
+ } // Else, fall through...
+ default:
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ return addError("Syntax error: value, object or array expected.", token);
+ }
+
+ if (collectComments_) {
+ lastValueEnd_ = current_;
+ lastValue_ = &currentValue();
+ }
+
+ --stackDepth_g;
+ return successful;
+}
+
+void Reader::skipCommentTokens(Token& token) {
+ if (features_.allowComments_) {
+ do {
+ readToken(token);
+ } while (token.type_ == tokenComment);
+ } else {
+ readToken(token);
+ }
+}
+
+bool Reader::readToken(Token& token) {
+ skipSpaces();
+ token.start_ = current_;
+ Char c = getNextChar();
+ bool ok = true;
+ switch (c) {
+ case '{':
+ token.type_ = tokenObjectBegin;
+ break;
+ case '}':
+ token.type_ = tokenObjectEnd;
+ break;
+ case '[':
+ token.type_ = tokenArrayBegin;
+ break;
+ case ']':
+ token.type_ = tokenArrayEnd;
+ break;
+ case '"':
+ token.type_ = tokenString;
+ ok = readString();
+ break;
+ case '/':
+ token.type_ = tokenComment;
+ ok = readComment();
+ break;
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ case '-':
+ token.type_ = tokenNumber;
+ readNumber();
+ break;
+ case 't':
+ token.type_ = tokenTrue;
+ ok = match("rue", 3);
+ break;
+ case 'f':
+ token.type_ = tokenFalse;
+ ok = match("alse", 4);
+ break;
+ case 'n':
+ token.type_ = tokenNull;
+ ok = match("ull", 3);
+ break;
+ case ',':
+ token.type_ = tokenArraySeparator;
+ break;
+ case ':':
+ token.type_ = tokenMemberSeparator;
+ break;
+ case 0:
+ token.type_ = tokenEndOfStream;
+ break;
+ default:
+ ok = false;
+ break;
+ }
+ if (!ok)
+ token.type_ = tokenError;
+ token.end_ = current_;
+ return true;
+}
+
+void Reader::skipSpaces() {
+ while (current_ != end_) {
+ Char c = *current_;
+ if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
+ ++current_;
+ else
+ break;
+ }
+}
+
+bool Reader::match(Location pattern, int patternLength) {
+ if (end_ - current_ < patternLength)
+ return false;
+ int index = patternLength;
+ while (index--)
+ if (current_[index] != pattern[index])
+ return false;
+ current_ += patternLength;
+ return true;
+}
+
+bool Reader::readComment() {
+ Location commentBegin = current_ - 1;
+ Char c = getNextChar();
+ bool successful = false;
+ if (c == '*')
+ successful = readCStyleComment();
+ else if (c == '/')
+ successful = readCppStyleComment();
+ if (!successful)
+ return false;
+
+ if (collectComments_) {
+ CommentPlacement placement = commentBefore;
+ if (lastValueEnd_ && !containsNewLine(lastValueEnd_, commentBegin)) {
+ if (c != '*' || !containsNewLine(commentBegin, current_))
+ placement = commentAfterOnSameLine;
+ }
+
+ addComment(commentBegin, current_, placement);
+ }
+ return true;
+}
+
+static std::string normalizeEOL(Reader::Location begin, Reader::Location end) {
+ std::string normalized;
+ normalized.reserve(end - begin);
+ Reader::Location current = begin;
+ while (current != end) {
+ char c = *current++;
+ if (c == '\r') {
+ if (current != end && *current == '\n')
+ // convert dos EOL
+ ++current;
+ // convert Mac EOL
+ normalized += '\n';
+ } else {
+ normalized += c;
+ }
+ }
+ return normalized;
+}
+
+void
+Reader::addComment(Location begin, Location end, CommentPlacement placement) {
+ assert(collectComments_);
+ const std::string& normalized = normalizeEOL(begin, end);
+ if (placement == commentAfterOnSameLine) {
+ assert(lastValue_ != 0);
+ lastValue_->setComment(normalized, placement);
+ } else {
+ commentsBefore_ += normalized;
+ }
+}
+
+bool Reader::readCStyleComment() {
+ while (current_ != end_) {
+ Char c = getNextChar();
+ if (c == '*' && *current_ == '/')
+ break;
+ }
+ return getNextChar() == '/';
+}
+
+bool Reader::readCppStyleComment() {
+ while (current_ != end_) {
+ Char c = getNextChar();
+ if (c == '\n')
+ break;
+ if (c == '\r') {
+ // Consume DOS EOL. It will be normalized in addComment.
+ if (current_ != end_ && *current_ == '\n')
+ getNextChar();
+ // Break on Moc OS 9 EOL.
+ break;
+ }
+ }
+ return true;
+}
+
+void Reader::readNumber() {
+ const char *p = current_;
+ char c = '0'; // stopgap for already consumed character
+ // integral part
+ while (c >= '0' && c <= '9')
+ c = (current_ = p) < end_ ? *p++ : 0;
+ // fractional part
+ if (c == '.') {
+ c = (current_ = p) < end_ ? *p++ : 0;
+ while (c >= '0' && c <= '9')
+ c = (current_ = p) < end_ ? *p++ : 0;
+ }
+ // exponential part
+ if (c == 'e' || c == 'E') {
+ c = (current_ = p) < end_ ? *p++ : 0;
+ if (c == '+' || c == '-')
+ c = (current_ = p) < end_ ? *p++ : 0;
+ while (c >= '0' && c <= '9')
+ c = (current_ = p) < end_ ? *p++ : 0;
+ }
+}
+
+bool Reader::readString() {
+ Char c = 0;
+ while (current_ != end_) {
+ c = getNextChar();
+ if (c == '\\')
+ getNextChar();
+ else if (c == '"')
+ break;
+ }
+ return c == '"';
+}
+
+bool Reader::readObject(Token& tokenStart) {
+ Token tokenName;
+ std::string name;
+ Value init(objectValue);
+ currentValue().swapPayload(init);
+ currentValue().setOffsetStart(tokenStart.start_ - begin_);
+ while (readToken(tokenName)) {
+ bool initialTokenOk = true;
+ while (tokenName.type_ == tokenComment && initialTokenOk)
+ initialTokenOk = readToken(tokenName);
+ if (!initialTokenOk)
+ break;
+ if (tokenName.type_ == tokenObjectEnd && name.empty()) // empty object
+ return true;
+ name = "";
+ if (tokenName.type_ == tokenString) {
+ if (!decodeString(tokenName, name))
+ return recoverFromError(tokenObjectEnd);
+ } else if (tokenName.type_ == tokenNumber && features_.allowNumericKeys_) {
+ Value numberName;
+ if (!decodeNumber(tokenName, numberName))
+ return recoverFromError(tokenObjectEnd);
+ name = numberName.asString();
+ } else {
+ break;
+ }
+
+ Token colon;
+ if (!readToken(colon) || colon.type_ != tokenMemberSeparator) {
+ return addErrorAndRecover(
+ "Missing ':' after object member name", colon, tokenObjectEnd);
+ }
+ Value& value = currentValue()[name];
+ nodes_.push(&value);
+ bool ok = readValue();
+ nodes_.pop();
+ if (!ok) // error already set
+ return recoverFromError(tokenObjectEnd);
+
+ Token comma;
+ if (!readToken(comma) ||
+ (comma.type_ != tokenObjectEnd && comma.type_ != tokenArraySeparator &&
+ comma.type_ != tokenComment)) {
+ return addErrorAndRecover(
+ "Missing ',' or '}' in object declaration", comma, tokenObjectEnd);
+ }
+ bool finalizeTokenOk = true;
+ while (comma.type_ == tokenComment && finalizeTokenOk)
+ finalizeTokenOk = readToken(comma);
+ if (comma.type_ == tokenObjectEnd)
+ return true;
+ }
+ return addErrorAndRecover(
+ "Missing '}' or object member name", tokenName, tokenObjectEnd);
+}
+
+bool Reader::readArray(Token& tokenStart) {
+ Value init(arrayValue);
+ currentValue().swapPayload(init);
+ currentValue().setOffsetStart(tokenStart.start_ - begin_);
+ skipSpaces();
+ if (*current_ == ']') // empty array
+ {
+ Token endArray;
+ readToken(endArray);
+ return true;
+ }
+ int index = 0;
+ for (;;) {
+ Value& value = currentValue()[index++];
+ nodes_.push(&value);
+ bool ok = readValue();
+ nodes_.pop();
+ if (!ok) // error already set
+ return recoverFromError(tokenArrayEnd);
+
+ Token token;
+ // Accept Comment after last item in the array.
+ ok = readToken(token);
+ while (token.type_ == tokenComment && ok) {
+ ok = readToken(token);
+ }
+ bool badTokenType =
+ (token.type_ != tokenArraySeparator && token.type_ != tokenArrayEnd);
+ if (!ok || badTokenType) {
+ return addErrorAndRecover(
+ "Missing ',' or ']' in array declaration", token, tokenArrayEnd);
+ }
+ if (token.type_ == tokenArrayEnd)
+ break;
+ }
+ return true;
+}
+
+bool Reader::decodeNumber(Token& token) {
+ Value decoded;
+ if (!decodeNumber(token, decoded))
+ return false;
+ currentValue().swapPayload(decoded);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ return true;
+}
+
+bool Reader::decodeNumber(Token& token, Value& decoded) {
+ // Attempts to parse the number as an integer. If the number is
+ // larger than the maximum supported value of an integer then
+ // we decode the number as a double.
+ Location current = token.start_;
+ bool isNegative = *current == '-';
+ if (isNegative)
+ ++current;
+ // TODO: Help the compiler do the div and mod at compile time or get rid of them.
+ Value::LargestUInt maxIntegerValue =
+ isNegative ? Value::LargestUInt(Value::maxLargestInt) + 1
+ : Value::maxLargestUInt;
+ Value::LargestUInt threshold = maxIntegerValue / 10;
+ Value::LargestUInt value = 0;
+ while (current < token.end_) {
+ Char c = *current++;
+ if (c < '0' || c > '9')
+ return decodeDouble(token, decoded);
+ Value::UInt digit(c - '0');
+ if (value >= threshold) {
+ // We've hit or exceeded the max value divided by 10 (rounded down). If
+ // a) we've only just touched the limit, b) this is the last digit, and
+ // c) it's small enough to fit in that rounding delta, we're okay.
+ // Otherwise treat this number as a double to avoid overflow.
+ if (value > threshold || current != token.end_ ||
+ digit > maxIntegerValue % 10) {
+ return decodeDouble(token, decoded);
+ }
+ }
+ value = value * 10 + digit;
+ }
+ if (isNegative && value == maxIntegerValue)
+ decoded = Value::minLargestInt;
+ else if (isNegative)
+ decoded = -Value::LargestInt(value);
+ else if (value <= Value::LargestUInt(Value::maxInt))
+ decoded = Value::LargestInt(value);
+ else
+ decoded = value;
+ return true;
+}
+
+bool Reader::decodeDouble(Token& token) {
+ Value decoded;
+ if (!decodeDouble(token, decoded))
+ return false;
+ currentValue().swapPayload(decoded);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ return true;
+}
+
+bool Reader::decodeDouble(Token& token, Value& decoded) {
+ double value = 0;
+ std::string buffer(token.start_, token.end_);
+ std::istringstream is(buffer);
+ if (!(is >> value))
+ return addError("'" + std::string(token.start_, token.end_) +
+ "' is not a number.",
+ token);
+ decoded = value;
+ return true;
+}
+
+bool Reader::decodeString(Token& token) {
+ std::string decoded_string;
+ if (!decodeString(token, decoded_string))
+ return false;
+ Value decoded(decoded_string);
+ currentValue().swapPayload(decoded);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ return true;
+}
+
+bool Reader::decodeString(Token& token, std::string& decoded) {
+ decoded.reserve(token.end_ - token.start_ - 2);
+ Location current = token.start_ + 1; // skip '"'
+ Location end = token.end_ - 1; // do not include '"'
+ while (current != end) {
+ Char c = *current++;
+ if (c == '"')
+ break;
+ else if (c == '\\') {
+ if (current == end)
+ return addError("Empty escape sequence in string", token, current);
+ Char escape = *current++;
+ switch (escape) {
+ case '"':
+ decoded += '"';
+ break;
+ case '/':
+ decoded += '/';
+ break;
+ case '\\':
+ decoded += '\\';
+ break;
+ case 'b':
+ decoded += '\b';
+ break;
+ case 'f':
+ decoded += '\f';
+ break;
+ case 'n':
+ decoded += '\n';
+ break;
+ case 'r':
+ decoded += '\r';
+ break;
+ case 't':
+ decoded += '\t';
+ break;
+ case 'u': {
+ unsigned int unicode;
+ if (!decodeUnicodeCodePoint(token, current, end, unicode))
+ return false;
+ decoded += codePointToUTF8(unicode);
+ } break;
+ default:
+ return addError("Bad escape sequence in string", token, current);
+ }
+ } else {
+ decoded += c;
+ }
+ }
+ return true;
+}
+
+bool Reader::decodeUnicodeCodePoint(Token& token,
+ Location& current,
+ Location end,
+ unsigned int& unicode) {
+
+ if (!decodeUnicodeEscapeSequence(token, current, end, unicode))
+ return false;
+ if (unicode >= 0xD800 && unicode <= 0xDBFF) {
+ // surrogate pairs
+ if (end - current < 6)
+ return addError(
+ "additional six characters expected to parse unicode surrogate pair.",
+ token,
+ current);
+ unsigned int surrogatePair;
+ if (*(current++) == '\\' && *(current++) == 'u') {
+ if (decodeUnicodeEscapeSequence(token, current, end, surrogatePair)) {
+ unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF);
+ } else
+ return false;
+ } else
+ return addError("expecting another \\u token to begin the second half of "
+ "a unicode surrogate pair",
+ token,
+ current);
+ }
+ return true;
+}
+
+bool Reader::decodeUnicodeEscapeSequence(Token& token,
+ Location& current,
+ Location end,
+ unsigned int& unicode) {
+ if (end - current < 4)
+ return addError(
+ "Bad unicode escape sequence in string: four digits expected.",
+ token,
+ current);
+ unicode = 0;
+ for (int index = 0; index < 4; ++index) {
+ Char c = *current++;
+ unicode *= 16;
+ if (c >= '0' && c <= '9')
+ unicode += c - '0';
+ else if (c >= 'a' && c <= 'f')
+ unicode += c - 'a' + 10;
+ else if (c >= 'A' && c <= 'F')
+ unicode += c - 'A' + 10;
+ else
+ return addError(
+ "Bad unicode escape sequence in string: hexadecimal digit expected.",
+ token,
+ current);
+ }
+ return true;
+}
+
+bool
+Reader::addError(const std::string& message, Token& token, Location extra) {
+ ErrorInfo info;
+ info.token_ = token;
+ info.message_ = message;
+ info.extra_ = extra;
+ errors_.push_back(info);
+ return false;
+}
+
+bool Reader::recoverFromError(TokenType skipUntilToken) {
+ int errorCount = int(errors_.size());
+ Token skip;
+ for (;;) {
+ if (!readToken(skip))
+ errors_.resize(errorCount); // discard errors caused by recovery
+ if (skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream)
+ break;
+ }
+ errors_.resize(errorCount);
+ return false;
+}
+
+bool Reader::addErrorAndRecover(const std::string& message,
+ Token& token,
+ TokenType skipUntilToken) {
+ addError(message, token);
+ return recoverFromError(skipUntilToken);
+}
+
+Value& Reader::currentValue() { return *(nodes_.top()); }
+
+Reader::Char Reader::getNextChar() {
+ if (current_ == end_)
+ return 0;
+ return *current_++;
+}
+
+void Reader::getLocationLineAndColumn(Location location,
+ int& line,
+ int& column) const {
+ Location current = begin_;
+ Location lastLineStart = current;
+ line = 0;
+ while (current < location && current != end_) {
+ Char c = *current++;
+ if (c == '\r') {
+ if (*current == '\n')
+ ++current;
+ lastLineStart = current;
+ ++line;
+ } else if (c == '\n') {
+ lastLineStart = current;
+ ++line;
+ }
+ }
+ // column & line start at 1
+ column = int(location - lastLineStart) + 1;
+ ++line;
+}
+
+std::string Reader::getLocationLineAndColumn(Location location) const {
+ int line, column;
+ getLocationLineAndColumn(location, line, column);
+ char buffer[18 + 16 + 16 + 1];
+ snprintf(buffer, sizeof(buffer), "Line %d, Column %d", line, column);
+ return buffer;
+}
+
+std::string Reader::getLocationSnippet(Location location) const {
+ std::string snippet = "";
+ std::istringstream docStream(document_);
+ int lin, col;
+ getLocationLineAndColumn(location, lin, col);
+ std::string line;
+ for (int i=1; i<lin+2 && std::getline(docStream, line); i++)
+ {
+ if (lin-i < 2)
+ {
+ snippet += " " + std::to_string(i) + ": " + line + "\n";
+ }
+ }
+ return snippet;
+}
+
+// Deprecated. Preserved for backward compatibility
+std::string Reader::getFormatedErrorMessages() const {
+ return getFormattedErrorMessages();
+}
+
+std::string Reader::getFormattedErrorMessages() const {
+ std::string formattedMessage;
+ for (Errors::const_iterator itError = errors_.begin();
+ itError != errors_.end();
+ ++itError) {
+ const ErrorInfo& error = *itError;
+ formattedMessage +=
+ "* " + getLocationLineAndColumn(error.token_.start_) + "\n";
+ formattedMessage += getLocationSnippet(error.token_.start_) + "\n";
+ formattedMessage += " " + error.message_ + "\n";
+ if (error.extra_)
+ formattedMessage +=
+ "See " + getLocationLineAndColumn(error.extra_) + " for detail.\n";
+ }
+ return formattedMessage;
+}
+
+std::vector<Reader::StructuredError> Reader::getStructuredErrors() const {
+ std::vector<Reader::StructuredError> allErrors;
+ for (Errors::const_iterator itError = errors_.begin();
+ itError != errors_.end();
+ ++itError) {
+ const ErrorInfo& error = *itError;
+ Reader::StructuredError structured;
+ structured.offset_start = error.token_.start_ - begin_;
+ structured.offset_limit = error.token_.end_ - begin_;
+ structured.message = error.message_;
+ allErrors.push_back(structured);
+ }
+ return allErrors;
+}
+
+bool Reader::pushError(const Value& value, const std::string& message) {
+ size_t length = end_ - begin_;
+ if(value.getOffsetStart() > length
+ || value.getOffsetLimit() > length)
+ return false;
+ Token token;
+ token.type_ = tokenError;
+ token.start_ = begin_ + value.getOffsetStart();
+ token.end_ = end_ + value.getOffsetLimit();
+ ErrorInfo info;
+ info.token_ = token;
+ info.message_ = message;
+ info.extra_ = 0;
+ errors_.push_back(info);
+ return true;
+}
+
+bool Reader::pushError(const Value& value, const std::string& message, const Value& extra) {
+ size_t length = end_ - begin_;
+ if(value.getOffsetStart() > length
+ || value.getOffsetLimit() > length
+ || extra.getOffsetLimit() > length)
+ return false;
+ Token token;
+ token.type_ = tokenError;
+ token.start_ = begin_ + value.getOffsetStart();
+ token.end_ = begin_ + value.getOffsetLimit();
+ ErrorInfo info;
+ info.token_ = token;
+ info.message_ = message;
+ info.extra_ = begin_ + extra.getOffsetStart();
+ errors_.push_back(info);
+ return true;
+}
+
+bool Reader::good() const {
+ return !errors_.size();
+}
+
+// exact copy of Features
+class OurFeatures {
+public:
+ static OurFeatures all();
+ bool allowComments_;
+ bool strictRoot_;
+ bool allowDroppedNullPlaceholders_;
+ bool allowNumericKeys_;
+ bool allowSingleQuotes_;
+ bool failIfExtra_;
+ bool rejectDupKeys_;
+ bool allowSpecialFloats_;
+ int stackLimit_;
+}; // OurFeatures
+
+// exact copy of Implementation of class Features
+// ////////////////////////////////
+
+OurFeatures OurFeatures::all() { return OurFeatures(); }
+
+// Implementation of class Reader
+// ////////////////////////////////
+
+// exact copy of Reader, renamed to OurReader
+class OurReader {
+public:
+ typedef char Char;
+ typedef const Char* Location;
+ struct StructuredError {
+ size_t offset_start;
+ size_t offset_limit;
+ std::string message;
+ };
+
+ OurReader(OurFeatures const& features);
+ bool parse(const char* beginDoc,
+ const char* endDoc,
+ Value& root,
+ bool collectComments = true);
+ std::string getFormattedErrorMessages() const;
+ std::vector<StructuredError> getStructuredErrors() const;
+ bool pushError(const Value& value, const std::string& message);
+ bool pushError(const Value& value, const std::string& message, const Value& extra);
+ bool good() const;
+
+private:
+ OurReader(OurReader const&); // no impl
+ void operator=(OurReader const&); // no impl
+
+ enum TokenType {
+ tokenEndOfStream = 0,
+ tokenObjectBegin,
+ tokenObjectEnd,
+ tokenArrayBegin,
+ tokenArrayEnd,
+ tokenString,
+ tokenNumber,
+ tokenTrue,
+ tokenFalse,
+ tokenNull,
+ tokenNaN,
+ tokenPosInf,
+ tokenNegInf,
+ tokenArraySeparator,
+ tokenMemberSeparator,
+ tokenComment,
+ tokenError
+ };
+
+ class Token {
+ public:
+ TokenType type_;
+ Location start_;
+ Location end_;
+ };
+
+ class ErrorInfo {
+ public:
+ Token token_;
+ std::string message_;
+ Location extra_;
+ };
+
+ typedef std::deque<ErrorInfo> Errors;
+
+ bool readToken(Token& token);
+ void skipSpaces();
+ bool match(Location pattern, int patternLength);
+ bool readComment();
+ bool readCStyleComment();
+ bool readCppStyleComment();
+ bool readString();
+ bool readStringSingleQuote();
+ bool readNumber(bool checkInf);
+ bool readValue();
+ bool readObject(Token& token);
+ bool readArray(Token& token);
+ bool decodeNumber(Token& token);
+ bool decodeNumber(Token& token, Value& decoded);
+ bool decodeString(Token& token);
+ bool decodeString(Token& token, std::string& decoded);
+ bool decodeDouble(Token& token);
+ bool decodeDouble(Token& token, Value& decoded);
+ bool decodeUnicodeCodePoint(Token& token,
+ Location& current,
+ Location end,
+ unsigned int& unicode);
+ bool decodeUnicodeEscapeSequence(Token& token,
+ Location& current,
+ Location end,
+ unsigned int& unicode);
+ bool addError(const std::string& message, Token& token, Location extra = 0);
+ bool recoverFromError(TokenType skipUntilToken);
+ bool addErrorAndRecover(const std::string& message,
+ Token& token,
+ TokenType skipUntilToken);
+ void skipUntilSpace();
+ Value& currentValue();
+ Char getNextChar();
+ void
+ getLocationLineAndColumn(Location location, int& line, int& column) const;
+ std::string getLocationLineAndColumn(Location location) const;
+ void addComment(Location begin, Location end, CommentPlacement placement);
+ void skipCommentTokens(Token& token);
+
+ typedef std::stack<Value*> Nodes;
+ Nodes nodes_;
+ Errors errors_;
+ std::string document_;
+ Location begin_;
+ Location end_;
+ Location current_;
+ Location lastValueEnd_;
+ Value* lastValue_;
+ std::string commentsBefore_;
+ int stackDepth_;
+
+ OurFeatures const features_;
+ bool collectComments_;
+}; // OurReader
+
+// complete copy of Read impl, for OurReader
+
+OurReader::OurReader(OurFeatures const& features)
+ : errors_(), document_(), begin_(), end_(), current_(), lastValueEnd_(),
+ lastValue_(), commentsBefore_(),
+ stackDepth_(0),
+ features_(features), collectComments_() {
+}
+
+bool OurReader::parse(const char* beginDoc,
+ const char* endDoc,
+ Value& root,
+ bool collectComments) {
+ if (!features_.allowComments_) {
+ collectComments = false;
+ }
+
+ begin_ = beginDoc;
+ end_ = endDoc;
+ collectComments_ = collectComments;
+ current_ = begin_;
+ lastValueEnd_ = 0;
+ lastValue_ = 0;
+ commentsBefore_ = "";
+ errors_.clear();
+ while (!nodes_.empty())
+ nodes_.pop();
+ nodes_.push(&root);
+
+ stackDepth_ = 0;
+ bool successful = readValue();
+ Token token;
+ skipCommentTokens(token);
+ if (features_.failIfExtra_) {
+ if (token.type_ != tokenError && token.type_ != tokenEndOfStream) {
+ addError("Extra non-whitespace after JSON value.", token);
+ return false;
+ }
+ }
+ if (collectComments_ && !commentsBefore_.empty())
+ root.setComment(commentsBefore_, commentAfter);
+ if (features_.strictRoot_) {
+ if (!root.isArray() && !root.isObject()) {
+ // Set error location to start of doc, ideally should be first token found
+ // in doc
+ token.type_ = tokenError;
+ token.start_ = beginDoc;
+ token.end_ = endDoc;
+ addError(
+ "A valid JSON document must be either an array or an object value.",
+ token);
+ return false;
+ }
+ }
+ return successful;
+}
+
+bool OurReader::readValue() {
+ if (stackDepth_ >= features_.stackLimit_) throwRuntimeError("Exceeded stackLimit in readValue().");
+ ++stackDepth_;
+ Token token;
+ skipCommentTokens(token);
+ bool successful = true;
+
+ if (collectComments_ && !commentsBefore_.empty()) {
+ currentValue().setComment(commentsBefore_, commentBefore);
+ commentsBefore_ = "";
+ }
+
+ switch (token.type_) {
+ case tokenObjectBegin:
+ successful = readObject(token);
+ currentValue().setOffsetLimit(current_ - begin_);
+ break;
+ case tokenArrayBegin:
+ successful = readArray(token);
+ currentValue().setOffsetLimit(current_ - begin_);
+ break;
+ case tokenNumber:
+ successful = decodeNumber(token);
+ break;
+ case tokenString:
+ successful = decodeString(token);
+ break;
+ case tokenTrue:
+ {
+ Value v(true);
+ currentValue().swapPayload(v);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ }
+ break;
+ case tokenFalse:
+ {
+ Value v(false);
+ currentValue().swapPayload(v);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ }
+ break;
+ case tokenNull:
+ {
+ Value v;
+ currentValue().swapPayload(v);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ }
+ break;
+ case tokenNaN:
+ {
+ Value v(std::numeric_limits<double>::quiet_NaN());
+ currentValue().swapPayload(v);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ }
+ break;
+ case tokenPosInf:
+ {
+ Value v(std::numeric_limits<double>::infinity());
+ currentValue().swapPayload(v);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ }
+ break;
+ case tokenNegInf:
+ {
+ Value v(-std::numeric_limits<double>::infinity());
+ currentValue().swapPayload(v);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ }
+ break;
+ case tokenArraySeparator:
+ case tokenObjectEnd:
+ case tokenArrayEnd:
+ if (features_.allowDroppedNullPlaceholders_) {
+ // "Un-read" the current token and mark the current value as a null
+ // token.
+ current_--;
+ Value v;
+ currentValue().swapPayload(v);
+ currentValue().setOffsetStart(current_ - begin_ - 1);
+ currentValue().setOffsetLimit(current_ - begin_);
+ break;
+ } // else, fall through ...
+ default:
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ return addError("Syntax error: value, object or array expected.", token);
+ }
+
+ if (collectComments_) {
+ lastValueEnd_ = current_;
+ lastValue_ = &currentValue();
+ }
+
+ --stackDepth_;
+ return successful;
+}
+
+void OurReader::skipCommentTokens(Token& token) {
+ if (features_.allowComments_) {
+ do {
+ readToken(token);
+ } while (token.type_ == tokenComment);
+ } else {
+ readToken(token);
+ }
+}
+
+bool OurReader::readToken(Token& token) {
+ skipSpaces();
+ token.start_ = current_;
+ Char c = getNextChar();
+ bool ok = true;
+ switch (c) {
+ case '{':
+ token.type_ = tokenObjectBegin;
+ break;
+ case '}':
+ token.type_ = tokenObjectEnd;
+ break;
+ case '[':
+ token.type_ = tokenArrayBegin;
+ break;
+ case ']':
+ token.type_ = tokenArrayEnd;
+ break;
+ case '"':
+ token.type_ = tokenString;
+ ok = readString();
+ break;
+ case '\'':
+ if (features_.allowSingleQuotes_) {
+ token.type_ = tokenString;
+ ok = readStringSingleQuote();
+ break;
+ } // else continue
+ case '/':
+ token.type_ = tokenComment;
+ ok = readComment();
+ break;
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ token.type_ = tokenNumber;
+ readNumber(false);
+ break;
+ case '-':
+ if (readNumber(true)) {
+ token.type_ = tokenNumber;
+ } else {
+ token.type_ = tokenNegInf;
+ ok = features_.allowSpecialFloats_ && match("nfinity", 7);
+ }
+ break;
+ case 't':
+ token.type_ = tokenTrue;
+ ok = match("rue", 3);
+ break;
+ case 'f':
+ token.type_ = tokenFalse;
+ ok = match("alse", 4);
+ break;
+ case 'n':
+ token.type_ = tokenNull;
+ ok = match("ull", 3);
+ break;
+ case 'N':
+ if (features_.allowSpecialFloats_) {
+ token.type_ = tokenNaN;
+ ok = match("aN", 2);
+ } else {
+ ok = false;
+ }
+ break;
+ case 'I':
+ if (features_.allowSpecialFloats_) {
+ token.type_ = tokenPosInf;
+ ok = match("nfinity", 7);
+ } else {
+ ok = false;
+ }
+ break;
+ case ',':
+ token.type_ = tokenArraySeparator;
+ break;
+ case ':':
+ token.type_ = tokenMemberSeparator;
+ break;
+ case 0:
+ token.type_ = tokenEndOfStream;
+ break;
+ default:
+ ok = false;
+ break;
+ }
+ if (!ok)
+ token.type_ = tokenError;
+ token.end_ = current_;
+ return true;
+}
+
+void OurReader::skipSpaces() {
+ while (current_ != end_) {
+ Char c = *current_;
+ if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
+ ++current_;
+ else
+ break;
+ }
+}
+
+bool OurReader::match(Location pattern, int patternLength) {
+ if (end_ - current_ < patternLength)
+ return false;
+ int index = patternLength;
+ while (index--)
+ if (current_[index] != pattern[index])
+ return false;
+ current_ += patternLength;
+ return true;
+}
+
+bool OurReader::readComment() {
+ Location commentBegin = current_ - 1;
+ Char c = getNextChar();
+ bool successful = false;
+ if (c == '*')
+ successful = readCStyleComment();
+ else if (c == '/')
+ successful = readCppStyleComment();
+ if (!successful)
+ return false;
+
+ if (collectComments_) {
+ CommentPlacement placement = commentBefore;
+ if (lastValueEnd_ && !containsNewLine(lastValueEnd_, commentBegin)) {
+ if (c != '*' || !containsNewLine(commentBegin, current_))
+ placement = commentAfterOnSameLine;
+ }
+
+ addComment(commentBegin, current_, placement);
+ }
+ return true;
+}
+
+void
+OurReader::addComment(Location begin, Location end, CommentPlacement placement) {
+ assert(collectComments_);
+ const std::string& normalized = normalizeEOL(begin, end);
+ if (placement == commentAfterOnSameLine) {
+ assert(lastValue_ != 0);
+ lastValue_->setComment(normalized, placement);
+ } else {
+ commentsBefore_ += normalized;
+ }
+}
+
+bool OurReader::readCStyleComment() {
+ while (current_ != end_) {
+ Char c = getNextChar();
+ if (c == '*' && *current_ == '/')
+ break;
+ }
+ return getNextChar() == '/';
+}
+
+bool OurReader::readCppStyleComment() {
+ while (current_ != end_) {
+ Char c = getNextChar();
+ if (c == '\n')
+ break;
+ if (c == '\r') {
+ // Consume DOS EOL. It will be normalized in addComment.
+ if (current_ != end_ && *current_ == '\n')
+ getNextChar();
+ // Break on Moc OS 9 EOL.
+ break;
+ }
+ }
+ return true;
+}
+
+bool OurReader::readNumber(bool checkInf) {
+ const char *p = current_;
+ if (checkInf && p != end_ && *p == 'I') {
+ current_ = ++p;
+ return false;
+ }
+ char c = '0'; // stopgap for already consumed character
+ // integral part
+ while (c >= '0' && c <= '9')
+ c = (current_ = p) < end_ ? *p++ : 0;
+ // fractional part
+ if (c == '.') {
+ c = (current_ = p) < end_ ? *p++ : 0;
+ while (c >= '0' && c <= '9')
+ c = (current_ = p) < end_ ? *p++ : 0;
+ }
+ // exponential part
+ if (c == 'e' || c == 'E') {
+ c = (current_ = p) < end_ ? *p++ : 0;
+ if (c == '+' || c == '-')
+ c = (current_ = p) < end_ ? *p++ : 0;
+ while (c >= '0' && c <= '9')
+ c = (current_ = p) < end_ ? *p++ : 0;
+ }
+ return true;
+}
+bool OurReader::readString() {
+ Char c = 0;
+ while (current_ != end_) {
+ c = getNextChar();
+ if (c == '\\')
+ getNextChar();
+ else if (c == '"')
+ break;
+ }
+ return c == '"';
+}
+
+
+bool OurReader::readStringSingleQuote() {
+ Char c = 0;
+ while (current_ != end_) {
+ c = getNextChar();
+ if (c == '\\')
+ getNextChar();
+ else if (c == '\'')
+ break;
+ }
+ return c == '\'';
+}
+
+bool OurReader::readObject(Token& tokenStart) {
+ Token tokenName;
+ std::string name;
+ Value init(objectValue);
+ currentValue().swapPayload(init);
+ currentValue().setOffsetStart(tokenStart.start_ - begin_);
+ while (readToken(tokenName)) {
+ bool initialTokenOk = true;
+ while (tokenName.type_ == tokenComment && initialTokenOk)
+ initialTokenOk = readToken(tokenName);
+ if (!initialTokenOk)
+ break;
+ if (tokenName.type_ == tokenObjectEnd && name.empty()) // empty object
+ return true;
+ name = "";
+ if (tokenName.type_ == tokenString) {
+ if (!decodeString(tokenName, name))
+ return recoverFromError(tokenObjectEnd);
+ } else if (tokenName.type_ == tokenNumber && features_.allowNumericKeys_) {
+ Value numberName;
+ if (!decodeNumber(tokenName, numberName))
+ return recoverFromError(tokenObjectEnd);
+ name = numberName.asString();
+ } else {
+ break;
+ }
+
+ Token colon;
+ if (!readToken(colon) || colon.type_ != tokenMemberSeparator) {
+ return addErrorAndRecover(
+ "Missing ':' after object member name", colon, tokenObjectEnd);
+ }
+ if (name.length() >= (1U<<30)) throwRuntimeError("keylength >= 2^30");
+ if (features_.rejectDupKeys_ && currentValue().isMember(name)) {
+ std::string msg = "Duplicate key: '" + name + "'";
+ return addErrorAndRecover(
+ msg, tokenName, tokenObjectEnd);
+ }
+ Value& value = currentValue()[name];
+ nodes_.push(&value);
+ bool ok = readValue();
+ nodes_.pop();
+ if (!ok) // error already set
+ return recoverFromError(tokenObjectEnd);
+
+ Token comma;
+ if (!readToken(comma) ||
+ (comma.type_ != tokenObjectEnd && comma.type_ != tokenArraySeparator &&
+ comma.type_ != tokenComment)) {
+ return addErrorAndRecover(
+ "Missing ',' or '}' in object declaration", comma, tokenObjectEnd);
+ }
+ bool finalizeTokenOk = true;
+ while (comma.type_ == tokenComment && finalizeTokenOk)
+ finalizeTokenOk = readToken(comma);
+ if (comma.type_ == tokenObjectEnd)
+ return true;
+ }
+ return addErrorAndRecover(
+ "Missing '}' or object member name", tokenName, tokenObjectEnd);
+}
+
+bool OurReader::readArray(Token& tokenStart) {
+ Value init(arrayValue);
+ currentValue().swapPayload(init);
+ currentValue().setOffsetStart(tokenStart.start_ - begin_);
+ skipSpaces();
+ if (*current_ == ']') // empty array
+ {
+ Token endArray;
+ readToken(endArray);
+ return true;
+ }
+ int index = 0;
+ for (;;) {
+ Value& value = currentValue()[index++];
+ nodes_.push(&value);
+ bool ok = readValue();
+ nodes_.pop();
+ if (!ok) // error already set
+ return recoverFromError(tokenArrayEnd);
+
+ Token token;
+ // Accept Comment after last item in the array.
+ ok = readToken(token);
+ while (token.type_ == tokenComment && ok) {
+ ok = readToken(token);
+ }
+ bool badTokenType =
+ (token.type_ != tokenArraySeparator && token.type_ != tokenArrayEnd);
+ if (!ok || badTokenType) {
+ return addErrorAndRecover(
+ "Missing ',' or ']' in array declaration", token, tokenArrayEnd);
+ }
+ if (token.type_ == tokenArrayEnd)
+ break;
+ }
+ return true;
+}
+
+bool OurReader::decodeNumber(Token& token) {
+ Value decoded;
+ if (!decodeNumber(token, decoded))
+ return false;
+ currentValue().swapPayload(decoded);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ return true;
+}
+
+bool OurReader::decodeNumber(Token& token, Value& decoded) {
+ // Attempts to parse the number as an integer. If the number is
+ // larger than the maximum supported value of an integer then
+ // we decode the number as a double.
+ Location current = token.start_;
+ bool isNegative = *current == '-';
+ if (isNegative)
+ ++current;
+ // TODO: Help the compiler do the div and mod at compile time or get rid of them.
+ Value::LargestUInt maxIntegerValue =
+ isNegative ? Value::LargestUInt(-Value::minLargestInt)
+ : Value::maxLargestUInt;
+ Value::LargestUInt threshold = maxIntegerValue / 10;
+ Value::LargestUInt value = 0;
+ while (current < token.end_) {
+ Char c = *current++;
+ if (c < '0' || c > '9')
+ return decodeDouble(token, decoded);
+ Value::UInt digit(c - '0');
+ if (value >= threshold) {
+ // We've hit or exceeded the max value divided by 10 (rounded down). If
+ // a) we've only just touched the limit, b) this is the last digit, and
+ // c) it's small enough to fit in that rounding delta, we're okay.
+ // Otherwise treat this number as a double to avoid overflow.
+ if (value > threshold || current != token.end_ ||
+ digit > maxIntegerValue % 10) {
+ return decodeDouble(token, decoded);
+ }
+ }
+ value = value * 10 + digit;
+ }
+ if (isNegative)
+ decoded = -Value::LargestInt(value);
+ else if (value <= Value::LargestUInt(Value::maxInt))
+ decoded = Value::LargestInt(value);
+ else
+ decoded = value;
+ return true;
+}
+
+bool OurReader::decodeDouble(Token& token) {
+ Value decoded;
+ if (!decodeDouble(token, decoded))
+ return false;
+ currentValue().swapPayload(decoded);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ return true;
+}
+
+bool OurReader::decodeDouble(Token& token, Value& decoded) {
+ double value = 0;
+ const int bufferSize = 32;
+ int count;
+ int length = int(token.end_ - token.start_);
+
+ // Sanity check to avoid buffer overflow exploits.
+ if (length < 0) {
+ return addError("Unable to parse token length", token);
+ }
+
+ // Avoid using a string constant for the format control string given to
+ // sscanf, as this can cause hard to debug crashes on OS X. See here for more
+ // info:
+ //
+ // http://developer.apple.com/library/mac/#DOCUMENTATION/DeveloperTools/gcc-4.0.1/gcc/Incompatibilities.html
+ char format[] = "%lf";
+
+ if (length <= bufferSize) {
+ Char buffer[bufferSize + 1];
+ memcpy(buffer, token.start_, length);
+ buffer[length] = 0;
+ count = sscanf(buffer, format, &value);
+ } else {
+ std::string buffer(token.start_, token.end_);
+ count = sscanf(buffer.c_str(), format, &value);
+ }
+
+ if (count != 1)
+ return addError("'" + std::string(token.start_, token.end_) +
+ "' is not a number.",
+ token);
+ decoded = value;
+ return true;
+}
+
+bool OurReader::decodeString(Token& token) {
+ std::string decoded_string;
+ if (!decodeString(token, decoded_string))
+ return false;
+ Value decoded(decoded_string);
+ currentValue().swapPayload(decoded);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ return true;
+}
+
+bool OurReader::decodeString(Token& token, std::string& decoded) {
+ decoded.reserve(token.end_ - token.start_ - 2);
+ Location current = token.start_ + 1; // skip '"'
+ Location end = token.end_ - 1; // do not include '"'
+ while (current != end) {
+ Char c = *current++;
+ if (c == '"')
+ break;
+ else if (c == '\\') {
+ if (current == end)
+ return addError("Empty escape sequence in string", token, current);
+ Char escape = *current++;
+ switch (escape) {
+ case '"':
+ decoded += '"';
+ break;
+ case '/':
+ decoded += '/';
+ break;
+ case '\\':
+ decoded += '\\';
+ break;
+ case 'b':
+ decoded += '\b';
+ break;
+ case 'f':
+ decoded += '\f';
+ break;
+ case 'n':
+ decoded += '\n';
+ break;
+ case 'r':
+ decoded += '\r';
+ break;
+ case 't':
+ decoded += '\t';
+ break;
+ case 'u': {
+ unsigned int unicode;
+ if (!decodeUnicodeCodePoint(token, current, end, unicode))
+ return false;
+ decoded += codePointToUTF8(unicode);
+ } break;
+ default:
+ return addError("Bad escape sequence in string", token, current);
+ }
+ } else {
+ decoded += c;
+ }
+ }
+ return true;
+}
+
+bool OurReader::decodeUnicodeCodePoint(Token& token,
+ Location& current,
+ Location end,
+ unsigned int& unicode) {
+
+ if (!decodeUnicodeEscapeSequence(token, current, end, unicode))
+ return false;
+ if (unicode >= 0xD800 && unicode <= 0xDBFF) {
+ // surrogate pairs
+ if (end - current < 6)
+ return addError(
+ "additional six characters expected to parse unicode surrogate pair.",
+ token,
+ current);
+ unsigned int surrogatePair;
+ if (*(current++) == '\\' && *(current++) == 'u') {
+ if (decodeUnicodeEscapeSequence(token, current, end, surrogatePair)) {
+ unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF);
+ } else
+ return false;
+ } else
+ return addError("expecting another \\u token to begin the second half of "
+ "a unicode surrogate pair",
+ token,
+ current);
+ }
+ return true;
+}
+
+bool OurReader::decodeUnicodeEscapeSequence(Token& token,
+ Location& current,
+ Location end,
+ unsigned int& unicode) {
+ if (end - current < 4)
+ return addError(
+ "Bad unicode escape sequence in string: four digits expected.",
+ token,
+ current);
+ unicode = 0;
+ for (int index = 0; index < 4; ++index) {
+ Char c = *current++;
+ unicode *= 16;
+ if (c >= '0' && c <= '9')
+ unicode += c - '0';
+ else if (c >= 'a' && c <= 'f')
+ unicode += c - 'a' + 10;
+ else if (c >= 'A' && c <= 'F')
+ unicode += c - 'A' + 10;
+ else
+ return addError(
+ "Bad unicode escape sequence in string: hexadecimal digit expected.",
+ token,
+ current);
+ }
+ return true;
+}
+
+bool
+OurReader::addError(const std::string& message, Token& token, Location extra) {
+ ErrorInfo info;
+ info.token_ = token;
+ info.message_ = message;
+ info.extra_ = extra;
+ errors_.push_back(info);
+ return false;
+}
+
+bool OurReader::recoverFromError(TokenType skipUntilToken) {
+ int errorCount = int(errors_.size());
+ Token skip;
+ for (;;) {
+ if (!readToken(skip))
+ errors_.resize(errorCount); // discard errors caused by recovery
+ if (skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream)
+ break;
+ }
+ errors_.resize(errorCount);
+ return false;
+}
+
+bool OurReader::addErrorAndRecover(const std::string& message,
+ Token& token,
+ TokenType skipUntilToken) {
+ addError(message, token);
+ return recoverFromError(skipUntilToken);
+}
+
+Value& OurReader::currentValue() { return *(nodes_.top()); }
+
+OurReader::Char OurReader::getNextChar() {
+ if (current_ == end_)
+ return 0;
+ return *current_++;
+}
+
+void OurReader::getLocationLineAndColumn(Location location,
+ int& line,
+ int& column) const {
+ Location current = begin_;
+ Location lastLineStart = current;
+ line = 0;
+ while (current < location && current != end_) {
+ Char c = *current++;
+ if (c == '\r') {
+ if (*current == '\n')
+ ++current;
+ lastLineStart = current;
+ ++line;
+ } else if (c == '\n') {
+ lastLineStart = current;
+ ++line;
+ }
+ }
+ // column & line start at 1
+ column = int(location - lastLineStart) + 1;
+ ++line;
+}
+
+std::string OurReader::getLocationLineAndColumn(Location location) const {
+ int line, column;
+ getLocationLineAndColumn(location, line, column);
+ char buffer[18 + 16 + 16 + 1];
+ snprintf(buffer, sizeof(buffer), "Line %d, Column %d", line, column);
+ return buffer;
+}
+
+std::string OurReader::getFormattedErrorMessages() const {
+ std::string formattedMessage;
+ for (Errors::const_iterator itError = errors_.begin();
+ itError != errors_.end();
+ ++itError) {
+ const ErrorInfo& error = *itError;
+ formattedMessage +=
+ "* " + getLocationLineAndColumn(error.token_.start_) + "\n";
+ formattedMessage += " " + error.message_ + "\n";
+ if (error.extra_)
+ formattedMessage +=
+ "See " + getLocationLineAndColumn(error.extra_) + " for detail.\n";
+ }
+ return formattedMessage;
+}
+
+std::vector<OurReader::StructuredError> OurReader::getStructuredErrors() const {
+ std::vector<OurReader::StructuredError> allErrors;
+ for (Errors::const_iterator itError = errors_.begin();
+ itError != errors_.end();
+ ++itError) {
+ const ErrorInfo& error = *itError;
+ OurReader::StructuredError structured;
+ structured.offset_start = error.token_.start_ - begin_;
+ structured.offset_limit = error.token_.end_ - begin_;
+ structured.message = error.message_;
+ allErrors.push_back(structured);
+ }
+ return allErrors;
+}
+
+bool OurReader::pushError(const Value& value, const std::string& message) {
+ size_t length = end_ - begin_;
+ if(value.getOffsetStart() > length
+ || value.getOffsetLimit() > length)
+ return false;
+ Token token;
+ token.type_ = tokenError;
+ token.start_ = begin_ + value.getOffsetStart();
+ token.end_ = end_ + value.getOffsetLimit();
+ ErrorInfo info;
+ info.token_ = token;
+ info.message_ = message;
+ info.extra_ = 0;
+ errors_.push_back(info);
+ return true;
+}
+
+bool OurReader::pushError(const Value& value, const std::string& message, const Value& extra) {
+ size_t length = end_ - begin_;
+ if(value.getOffsetStart() > length
+ || value.getOffsetLimit() > length
+ || extra.getOffsetLimit() > length)
+ return false;
+ Token token;
+ token.type_ = tokenError;
+ token.start_ = begin_ + value.getOffsetStart();
+ token.end_ = begin_ + value.getOffsetLimit();
+ ErrorInfo info;
+ info.token_ = token;
+ info.message_ = message;
+ info.extra_ = begin_ + extra.getOffsetStart();
+ errors_.push_back(info);
+ return true;
+}
+
+bool OurReader::good() const {
+ return !errors_.size();
+}
+
+
+class OurCharReader : public CharReader {
+ bool const collectComments_;
+ OurReader reader_;
+public:
+ OurCharReader(
+ bool collectComments,
+ OurFeatures const& features)
+ : collectComments_(collectComments)
+ , reader_(features)
+ {}
+ bool parse(
+ char const* beginDoc, char const* endDoc,
+ Value* root, std::string* errs) {
+ bool ok = reader_.parse(beginDoc, endDoc, *root, collectComments_);
+ if (errs) {
+ *errs = reader_.getFormattedErrorMessages();
+ }
+ return ok;
+ }
+};
+
+CharReaderBuilder::CharReaderBuilder()
+{
+ setDefaults(&settings_);
+}
+CharReaderBuilder::~CharReaderBuilder()
+{}
+CharReader* CharReaderBuilder::newCharReader() const
+{
+ bool collectComments = settings_["collectComments"].asBool();
+ OurFeatures features = OurFeatures::all();
+ features.allowComments_ = settings_["allowComments"].asBool();
+ features.strictRoot_ = settings_["strictRoot"].asBool();
+ features.allowDroppedNullPlaceholders_ = settings_["allowDroppedNullPlaceholders"].asBool();
+ features.allowNumericKeys_ = settings_["allowNumericKeys"].asBool();
+ features.allowSingleQuotes_ = settings_["allowSingleQuotes"].asBool();
+ features.stackLimit_ = settings_["stackLimit"].asInt();
+ features.failIfExtra_ = settings_["failIfExtra"].asBool();
+ features.rejectDupKeys_ = settings_["rejectDupKeys"].asBool();
+ features.allowSpecialFloats_ = settings_["allowSpecialFloats"].asBool();
+ return new OurCharReader(collectComments, features);
+}
+static void getValidReaderKeys(std::set<std::string>* valid_keys)
+{
+ valid_keys->clear();
+ valid_keys->insert("collectComments");
+ valid_keys->insert("allowComments");
+ valid_keys->insert("strictRoot");
+ valid_keys->insert("allowDroppedNullPlaceholders");
+ valid_keys->insert("allowNumericKeys");
+ valid_keys->insert("allowSingleQuotes");
+ valid_keys->insert("stackLimit");
+ valid_keys->insert("failIfExtra");
+ valid_keys->insert("rejectDupKeys");
+ valid_keys->insert("allowSpecialFloats");
+}
+bool CharReaderBuilder::validate(Json::Value* invalid) const
+{
+ Json::Value my_invalid;
+ if (!invalid) invalid = &my_invalid; // so we do not need to test for NULL
+ Json::Value& inv = *invalid;
+ std::set<std::string> valid_keys;
+ getValidReaderKeys(&valid_keys);
+ Value::Members keys = settings_.getMemberNames();
+ size_t n = keys.size();
+ for (size_t i = 0; i < n; ++i) {
+ std::string const& key = keys[i];
+ if (valid_keys.find(key) == valid_keys.end()) {
+ inv[key] = settings_[key];
+ }
+ }
+ return 0u == inv.size();
+}
+Value& CharReaderBuilder::operator[](std::string key)
+{
+ return settings_[key];
+}
+// static
+void CharReaderBuilder::strictMode(Json::Value* settings)
+{
+//! [CharReaderBuilderStrictMode]
+ (*settings)["allowComments"] = false;
+ (*settings)["strictRoot"] = true;
+ (*settings)["allowDroppedNullPlaceholders"] = false;
+ (*settings)["allowNumericKeys"] = false;
+ (*settings)["allowSingleQuotes"] = false;
+ (*settings)["stackLimit"] = 1000;
+ (*settings)["failIfExtra"] = true;
+ (*settings)["rejectDupKeys"] = true;
+ (*settings)["allowSpecialFloats"] = false;
+//! [CharReaderBuilderStrictMode]
+}
+// static
+void CharReaderBuilder::setDefaults(Json::Value* settings)
+{
+//! [CharReaderBuilderDefaults]
+ (*settings)["collectComments"] = true;
+ (*settings)["allowComments"] = true;
+ (*settings)["strictRoot"] = false;
+ (*settings)["allowDroppedNullPlaceholders"] = false;
+ (*settings)["allowNumericKeys"] = false;
+ (*settings)["allowSingleQuotes"] = false;
+ (*settings)["stackLimit"] = 1000;
+ (*settings)["failIfExtra"] = false;
+ (*settings)["rejectDupKeys"] = false;
+ (*settings)["allowSpecialFloats"] = false;
+//! [CharReaderBuilderDefaults]
+}
+
+//////////////////////////////////
+// global functions
+
+bool parseFromStream(
+ CharReader::Factory const& fact, std::istream& sin,
+ Value* root, std::string* errs)
+{
+ std::ostringstream ssin;
+ ssin << sin.rdbuf();
+ std::string doc = ssin.str();
+ char const* begin = doc.data();
+ char const* end = begin + doc.size();
+ // Note that we do not actually need a null-terminator.
+ CharReaderPtr const reader(fact.newCharReader());
+ return reader->parse(begin, end, root, errs);
+}
+
+std::istream& operator>>(std::istream& sin, Value& root) {
+ CharReaderBuilder b;
+ std::string errs;
+ bool ok = parseFromStream(b, sin, &root, &errs);
+ if (!ok) {
+ fprintf(stderr,
+ "Error from reader: %s",
+ errs.c_str());
+
+ throwRuntimeError(errs);
+ }
+ return sin;
+}
+
+} // namespace Json
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: src/lib_json/json_reader.cpp
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: src/lib_json/json_valueiterator.inl
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2007-2010 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+// included by json_value.cpp
+
+namespace Json {
+
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// class ValueIteratorBase
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+
+ValueIteratorBase::ValueIteratorBase()
+ : current_(), isNull_(true) {
+}
+
+ValueIteratorBase::ValueIteratorBase(
+ const Value::ObjectValues::iterator& current)
+ : current_(current), isNull_(false) {}
+
+Value& ValueIteratorBase::deref() const {
+ return current_->second;
+}
+
+void ValueIteratorBase::increment() {
+ ++current_;
+}
+
+void ValueIteratorBase::decrement() {
+ --current_;
+}
+
+ValueIteratorBase::difference_type
+ValueIteratorBase::computeDistance(const SelfType& other) const {
+#ifdef JSON_USE_CPPTL_SMALLMAP
+ return other.current_ - current_;
+#else
+ // Iterator for null value are initialized using the default
+ // constructor, which initialize current_ to the default
+ // std::map::iterator. As begin() and end() are two instance
+ // of the default std::map::iterator, they can not be compared.
+ // To allow this, we handle this comparison specifically.
+ if (isNull_ && other.isNull_) {
+ return 0;
+ }
+
+ // Usage of std::distance is not portable (does not compile with Sun Studio 12
+ // RogueWave STL,
+ // which is the one used by default).
+ // Using a portable hand-made version for non random iterator instead:
+ // return difference_type( std::distance( current_, other.current_ ) );
+ difference_type myDistance = 0;
+ for (Value::ObjectValues::iterator it = current_; it != other.current_;
+ ++it) {
+ ++myDistance;
+ }
+ return myDistance;
+#endif
+}
+
+bool ValueIteratorBase::isEqual(const SelfType& other) const {
+ if (isNull_) {
+ return other.isNull_;
+ }
+ return current_ == other.current_;
+}
+
+void ValueIteratorBase::copy(const SelfType& other) {
+ current_ = other.current_;
+ isNull_ = other.isNull_;
+}
+
+Value ValueIteratorBase::key() const {
+ const Value::CZString czstring = (*current_).first;
+ if (czstring.data()) {
+ if (czstring.isStaticString())
+ return Value(StaticString(czstring.data()));
+ return Value(czstring.data(), czstring.data() + czstring.length());
+ }
+ return Value(czstring.index());
+}
+
+UInt ValueIteratorBase::index() const {
+ const Value::CZString czstring = (*current_).first;
+ if (!czstring.data())
+ return czstring.index();
+ return Value::UInt(-1);
+}
+
+std::string ValueIteratorBase::name() const {
+ char const* keey;
+ char const* end;
+ keey = memberName(&end);
+ if (!keey) return std::string();
+ return std::string(keey, end);
+}
+
+char const* ValueIteratorBase::memberName() const {
+ const char* cname = (*current_).first.data();
+ return cname ? cname : "";
+}
+
+char const* ValueIteratorBase::memberName(char const** end) const {
+ const char* cname = (*current_).first.data();
+ if (!cname) {
+ *end = NULL;
+ return NULL;
+ }
+ *end = cname + (*current_).first.length();
+ return cname;
+}
+
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// class ValueConstIterator
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+
+ValueConstIterator::ValueConstIterator() {}
+
+ValueConstIterator::ValueConstIterator(
+ const Value::ObjectValues::iterator& current)
+ : ValueIteratorBase(current) {}
+
+ValueConstIterator::ValueConstIterator(ValueIterator const& other)
+ : ValueIteratorBase(other) {}
+
+ValueConstIterator& ValueConstIterator::
+operator=(const ValueIteratorBase& other) {
+ copy(other);
+ return *this;
+}
+
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// class ValueIterator
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+
+ValueIterator::ValueIterator() {}
+
+ValueIterator::ValueIterator(const Value::ObjectValues::iterator& current)
+ : ValueIteratorBase(current) {}
+
+ValueIterator::ValueIterator(const ValueConstIterator& other)
+ : ValueIteratorBase(other) {
+ throwRuntimeError("ConstIterator to Iterator should never be allowed.");
+}
+
+ValueIterator::ValueIterator(const ValueIterator& other)
+ : ValueIteratorBase(other) {}
+
+ValueIterator& ValueIterator::operator=(const SelfType& other) {
+ copy(other);
+ return *this;
+}
+
+} // namespace Json
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: src/lib_json/json_valueiterator.inl
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: src/lib_json/json_value.cpp
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2011 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+#if !defined(JSON_IS_AMALGAMATION)
+#include <json/assertions.h>
+#include <json/value.h>
+#include <json/writer.h>
+#endif // if !defined(JSON_IS_AMALGAMATION)
+#include <math.h>
+#include <sstream>
+#include <utility>
+#include <cstring>
+#include <cassert>
+#ifdef JSON_USE_CPPTL
+#include <cpptl/conststring.h>
+#endif
+#include <cstddef> // size_t
+#include <algorithm> // min()
+
+#define JSON_ASSERT_UNREACHABLE assert(false)
+
+/*
+-- Valve 1/7/16
+4702 unreachable code
+*/
+#pragma warning (push)
+#pragma warning (disable: 4702)
+
+namespace Json {
+
+// This is a walkaround to avoid the static initialization of Value::null.
+// kNull must be word-aligned to avoid crashing on ARM. We use an alignment of
+// 8 (instead of 4) as a bit of future-proofing.
+#if defined(__ARMEL__)
+#define ALIGNAS(byte_alignment) __attribute__((aligned(byte_alignment)))
+#else
+#define ALIGNAS(byte_alignment)
+#endif
+static const unsigned char ALIGNAS(8) kNull[sizeof(Value)] = { 0 };
+const unsigned char& kNullRef = kNull[0];
+const Value& Value::null = reinterpret_cast<const Value&>(kNullRef);
+const Value& Value::nullRef = null;
+
+const Int Value::minInt = Int(~(UInt(-1) / 2));
+const Int Value::maxInt = Int(UInt(-1) / 2);
+const UInt Value::maxUInt = UInt(-1);
+#if defined(JSON_HAS_INT64)
+const Int64 Value::minInt64 = Int64(~(UInt64(-1) / 2));
+const Int64 Value::maxInt64 = Int64(UInt64(-1) / 2);
+const UInt64 Value::maxUInt64 = UInt64(-1);
+// The constant is hard-coded because some compiler have trouble
+// converting Value::maxUInt64 to a double correctly (AIX/xlC).
+// Assumes that UInt64 is a 64 bits integer.
+static const double maxUInt64AsDouble = 18446744073709551615.0;
+#endif // defined(JSON_HAS_INT64)
+const LargestInt Value::minLargestInt = LargestInt(~(LargestUInt(-1) / 2));
+const LargestInt Value::maxLargestInt = LargestInt(LargestUInt(-1) / 2);
+const LargestUInt Value::maxLargestUInt = LargestUInt(-1);
+
+#if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
+template <typename T, typename U>
+static inline bool InRange(double d, T min, U max) {
+ return d >= min && d <= max;
+}
+#else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
+static inline double integerToDouble(Json::UInt64 value) {
+ return static_cast<double>(Int64(value / 2)) * 2.0 + Int64(value & 1);
+}
+
+template <typename T> static inline double integerToDouble(T value) {
+ return static_cast<double>(value);
+}
+
+template <typename T, typename U>
+static inline bool InRange(double d, T min, U max) {
+ return d >= integerToDouble(min) && d <= integerToDouble(max);
+}
+#endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
+
+/** Duplicates the specified string value.
+ * @param value Pointer to the string to duplicate. Must be zero-terminated if
+ * length is "unknown".
+ * @param length Length of the value. if equals to unknown, then it will be
+ * computed using strlen(value).
+ * @return Pointer on the duplicate instance of string.
+ */
+static inline char* duplicateStringValue(const char* value,
+ size_t length) {
+ // Avoid an integer overflow in the call to malloc below by limiting length
+ // to a sane value.
+ if (length >= (size_t)Value::maxInt)
+ length = Value::maxInt - 1;
+
+ char* newString = static_cast<char*>(malloc(length + 1));
+ if (newString == NULL) {
+ throwRuntimeError(
+ "in Json::Value::duplicateStringValue(): "
+ "Failed to allocate string value buffer");
+ }
+ memcpy(newString, value, length);
+ newString[length] = 0;
+ return newString;
+}
+
+/* Record the length as a prefix.
+ */
+static inline char* duplicateAndPrefixStringValue(
+ const char* value,
+ unsigned int length)
+{
+ // Avoid an integer overflow in the call to malloc below by limiting length
+ // to a sane value.
+ JSON_ASSERT_MESSAGE(length <= (unsigned)Value::maxInt - sizeof(unsigned) - 1U,
+ "in Json::Value::duplicateAndPrefixStringValue(): "
+ "length too big for prefixing");
+ unsigned actualLength = length + static_cast<unsigned>(sizeof(unsigned)) + 1U;
+ char* newString = static_cast<char*>(malloc(actualLength));
+ if (newString == 0) {
+ throwRuntimeError(
+ "in Json::Value::duplicateAndPrefixStringValue(): "
+ "Failed to allocate string value buffer");
+ }
+ *reinterpret_cast<unsigned*>(newString) = length;
+ memcpy(newString + sizeof(unsigned), value, length);
+ newString[actualLength - 1U] = 0; // to avoid buffer over-run accidents by users later
+ return newString;
+}
+inline static void decodePrefixedString(
+ bool isPrefixed, char const* prefixed,
+ unsigned* length, char const** value)
+{
+ if (!isPrefixed) {
+ *length = static_cast<unsigned>(strlen(prefixed));
+ *value = prefixed;
+ } else {
+ *length = *reinterpret_cast<unsigned const*>(prefixed);
+ *value = prefixed + sizeof(unsigned);
+ }
+}
+/** Free the string duplicated by duplicateStringValue()/duplicateAndPrefixStringValue().
+ */
+static inline void releaseStringValue(char* value) { free(value); }
+
+} // namespace Json
+
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// ValueInternals...
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+#if !defined(JSON_IS_AMALGAMATION)
+
+#include "json_valueiterator.inl"
+#endif // if !defined(JSON_IS_AMALGAMATION)
+
+namespace Json {
+
+Exception::Exception(std::string const& msg)
+ : msg_(msg)
+{}
+Exception::~Exception() throw()
+{}
+char const* Exception::what() const throw()
+{
+ return msg_.c_str();
+}
+RuntimeError::RuntimeError(std::string const& msg)
+ : Exception(msg)
+{}
+LogicError::LogicError(std::string const& msg)
+ : Exception(msg)
+{}
+void throwRuntimeError(std::string const& msg)
+{
+ throw RuntimeError(msg);
+}
+void throwLogicError(std::string const& msg)
+{
+ throw LogicError(msg);
+}
+
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// class Value::CommentInfo
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+
+Value::CommentInfo::CommentInfo() : comment_(0) {}
+
+Value::CommentInfo::~CommentInfo() {
+ if (comment_)
+ releaseStringValue(comment_);
+}
+
+void Value::CommentInfo::setComment(const char* text, size_t len) {
+ if (comment_) {
+ releaseStringValue(comment_);
+ comment_ = 0;
+ }
+ JSON_ASSERT(text != 0);
+ JSON_ASSERT_MESSAGE(
+ text[0] == '\0' || text[0] == '/',
+ "in Json::Value::setComment(): Comments must start with /");
+ // It seems that /**/ style comments are acceptable as well.
+ comment_ = duplicateStringValue(text, len);
+}
+
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// class Value::CZString
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+
+// Notes: policy_ indicates if the string was allocated when
+// a string is stored.
+
+Value::CZString::CZString(ArrayIndex aindex) : cstr_(0), index_(aindex) {}
+
+Value::CZString::CZString(char const* str, unsigned ulength, DuplicationPolicy allocate)
+ : cstr_(str) {
+ // allocate != duplicate
+ storage_.policy_ = allocate & 0x3;
+ storage_.length_ = ulength & 0x3FFFFFFF;
+}
+
+Value::CZString::CZString(const CZString& other)
+ : cstr_(other.storage_.policy_ != noDuplication && other.cstr_ != 0
+ ? duplicateStringValue(other.cstr_, other.storage_.length_)
+ : other.cstr_) {
+ storage_.policy_ = (other.cstr_
+ ? (static_cast<DuplicationPolicy>(other.storage_.policy_) == noDuplication
+ ? noDuplication : duplicate)
+ : static_cast<DuplicationPolicy>(other.storage_.policy_));
+ storage_.length_ = other.storage_.length_;
+}
+
+#if JSON_HAS_RVALUE_REFERENCES
+Value::CZString::CZString(CZString&& other)
+ : cstr_(other.cstr_), index_(other.index_) {
+ other.cstr_ = nullptr;
+}
+#endif
+
+Value::CZString::~CZString() {
+ if (cstr_ && storage_.policy_ == duplicate)
+ releaseStringValue(const_cast<char*>(cstr_));
+}
+
+void Value::CZString::swap(CZString& other) {
+ std::swap(cstr_, other.cstr_);
+ std::swap(index_, other.index_);
+}
+
+Value::CZString& Value::CZString::operator=(CZString other) {
+ swap(other);
+ return *this;
+}
+
+bool Value::CZString::operator<(const CZString& other) const {
+ if (!cstr_) return index_ < other.index_;
+ //return strcmp(cstr_, other.cstr_) < 0;
+ // Assume both are strings.
+ unsigned this_len = this->storage_.length_;
+ unsigned other_len = other.storage_.length_;
+ unsigned min_len = std::min(this_len, other_len);
+ int comp = memcmp(this->cstr_, other.cstr_, min_len);
+ if (comp < 0) return true;
+ if (comp > 0) return false;
+ return (this_len < other_len);
+}
+
+bool Value::CZString::operator==(const CZString& other) const {
+ if (!cstr_) return index_ == other.index_;
+ //return strcmp(cstr_, other.cstr_) == 0;
+ // Assume both are strings.
+ unsigned this_len = this->storage_.length_;
+ unsigned other_len = other.storage_.length_;
+ if (this_len != other_len) return false;
+ int comp = memcmp(this->cstr_, other.cstr_, this_len);
+ return comp == 0;
+}
+
+ArrayIndex Value::CZString::index() const { return index_; }
+
+//const char* Value::CZString::c_str() const { return cstr_; }
+const char* Value::CZString::data() const { return cstr_; }
+unsigned Value::CZString::length() const { return storage_.length_; }
+bool Value::CZString::isStaticString() const { return storage_.policy_ == noDuplication; }
+
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// class Value::Value
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+// //////////////////////////////////////////////////////////////////
+
+/*! \internal Default constructor initialization must be equivalent to:
+ * memset( this, 0, sizeof(Value) )
+ * This optimization is used in ValueInternalMap fast allocator.
+ */
+Value::Value(ValueType vtype) {
+ initBasic(vtype);
+ switch (vtype) {
+ case nullValue:
+ break;
+ case intValue:
+ case uintValue:
+ value_.int_ = 0;
+ break;
+ case realValue:
+ value_.real_ = 0.0;
+ break;
+ case stringValue:
+ value_.string_ = 0;
+ break;
+ case arrayValue:
+ case objectValue:
+ value_.map_ = new ObjectValues();
+ break;
+ case booleanValue:
+ value_.bool_ = false;
+ break;
+ default:
+ JSON_ASSERT_UNREACHABLE;
+ }
+}
+
+Value::Value(Int value) {
+ initBasic(intValue);
+ value_.int_ = value;
+}
+
+Value::Value(UInt value) {
+ initBasic(uintValue);
+ value_.uint_ = value;
+}
+#if defined(JSON_HAS_INT64)
+Value::Value(Int64 value) {
+ initBasic(intValue);
+ value_.int_ = value;
+}
+Value::Value(UInt64 value) {
+ initBasic(uintValue);
+ value_.uint_ = value;
+}
+#endif // defined(JSON_HAS_INT64)
+
+Value::Value(double value) {
+ initBasic(realValue);
+ value_.real_ = value;
+}
+
+Value::Value(const char* value) {
+ initBasic(stringValue, true);
+ value_.string_ = duplicateAndPrefixStringValue(value, static_cast<unsigned>(strlen(value)));
+}
+
+Value::Value(const char* beginValue, const char* endValue) {
+ initBasic(stringValue, true);
+ value_.string_ =
+ duplicateAndPrefixStringValue(beginValue, static_cast<unsigned>(endValue - beginValue));
+}
+
+Value::Value(const std::string& value) {
+ initBasic(stringValue, true);
+ value_.string_ =
+ duplicateAndPrefixStringValue(value.data(), static_cast<unsigned>(value.length()));
+}
+
+Value::Value(const StaticString& value) {
+ initBasic(stringValue);
+ value_.string_ = const_cast<char*>(value.c_str());
+}
+
+#ifdef JSON_USE_CPPTL
+Value::Value(const CppTL::ConstString& value) {
+ initBasic(stringValue, true);
+ value_.string_ = duplicateAndPrefixStringValue(value, static_cast<unsigned>(value.length()));
+}
+#endif
+
+Value::Value(bool value) {
+ initBasic(booleanValue);
+ value_.bool_ = value;
+}
+
+Value::Value(Value const& other)
+ : type_(other.type_), allocated_(false)
+ ,
+ comments_(nullptr), default_value_(nullptr), start_(other.start_), limit_(other.limit_)
+{
+ switch (type_) {
+ case nullValue:
+ case intValue:
+ case uintValue:
+ case realValue:
+ case booleanValue:
+ value_ = other.value_;
+ break;
+ case stringValue:
+ if (other.value_.string_ && other.allocated_) {
+ unsigned len;
+ char const* str;
+ decodePrefixedString(other.allocated_, other.value_.string_,
+ &len, &str);
+ value_.string_ = duplicateAndPrefixStringValue(str, len);
+ allocated_ = true;
+ } else {
+ value_.string_ = other.value_.string_;
+ allocated_ = false;
+ }
+ break;
+ case arrayValue:
+ case objectValue:
+ value_.map_ = new ObjectValues(*other.value_.map_);
+ break;
+ default:
+ JSON_ASSERT_UNREACHABLE;
+ }
+ if (other.comments_) {
+ comments_ = new CommentInfo[numberOfCommentPlacement];
+ for (int comment = 0; comment < numberOfCommentPlacement; ++comment) {
+ const CommentInfo& otherComment = other.comments_[comment];
+ if (otherComment.comment_)
+ comments_[comment].setComment(
+ otherComment.comment_, strlen(otherComment.comment_));
+ }
+ }
+
+ if ( other.default_value_ )
+ {
+ default_value_ = new Value( *other.default_value_ );
+ }
+
+}
+
+#if JSON_HAS_RVALUE_REFERENCES
+// Move constructor
+Value::Value(Value&& other) {
+ initBasic(nullValue);
+ swap(other);
+}
+#endif
+
+Value::~Value() {
+ switch (type_) {
+ case nullValue:
+ case intValue:
+ case uintValue:
+ case realValue:
+ case booleanValue:
+ break;
+ case stringValue:
+ if (allocated_)
+ releaseStringValue(value_.string_);
+ break;
+ case arrayValue:
+ case objectValue:
+ delete value_.map_;
+ break;
+ default:
+ JSON_ASSERT_UNREACHABLE;
+ }
+
+ if (comments_)
+ delete[] comments_;
+
+ if ( default_value_)
+ delete default_value_;
+}
+
+Value& Value::operator=(Value other) {
+ swap(other);
+ return *this;
+}
+
+void Value::swapPayload(Value& other) {
+ ValueType temp = type_;
+ type_ = other.type_;
+ other.type_ = temp;
+ std::swap(value_, other.value_);
+ int temp2 = allocated_;
+ allocated_ = other.allocated_;
+ other.allocated_ = temp2 & 0x1;
+}
+
+void Value::swap(Value& other) {
+ swapPayload(other);
+ std::swap(comments_, other.comments_);
+ std::swap(default_value_, other.default_value_);
+ std::swap(start_, other.start_);
+ std::swap(limit_, other.limit_);
+}
+
+ValueType Value::type() const { return type_; }
+
+int Value::compare(const Value& other) const {
+ if (*this < other)
+ return -1;
+ if (*this > other)
+ return 1;
+ return 0;
+}
+
+bool Value::operator<(const Value& other) const {
+ int typeDelta = type_ - other.type_;
+ if (typeDelta)
+ return typeDelta < 0 ? true : false;
+ switch (type_) {
+ case nullValue:
+ return false;
+ case intValue:
+ return value_.int_ < other.value_.int_;
+ case uintValue:
+ return value_.uint_ < other.value_.uint_;
+ case realValue:
+ return value_.real_ < other.value_.real_;
+ case booleanValue:
+ return value_.bool_ < other.value_.bool_;
+ case stringValue:
+ {
+ if ((value_.string_ == 0) || (other.value_.string_ == 0)) {
+ if (other.value_.string_) return true;
+ else return false;
+ }
+ unsigned this_len;
+ unsigned other_len;
+ char const* this_str;
+ char const* other_str;
+ decodePrefixedString(this->allocated_, this->value_.string_, &this_len, &this_str);
+ decodePrefixedString(other.allocated_, other.value_.string_, &other_len, &other_str);
+ unsigned min_len = std::min(this_len, other_len);
+ int comp = memcmp(this_str, other_str, min_len);
+ if (comp < 0) return true;
+ if (comp > 0) return false;
+ return (this_len < other_len);
+ }
+ case arrayValue:
+ case objectValue: {
+ int delta = int(value_.map_->size() - other.value_.map_->size());
+ if (delta)
+ return delta < 0;
+ return (*value_.map_) < (*other.value_.map_);
+ }
+ default:
+ JSON_ASSERT_UNREACHABLE;
+ }
+ return false; // unreachable
+}
+
+bool Value::operator<=(const Value& other) const { return !(other < *this); }
+
+bool Value::operator>=(const Value& other) const { return !(*this < other); }
+
+bool Value::operator>(const Value& other) const { return other < *this; }
+
+bool Value::operator==(const Value& other) const {
+ // if ( type_ != other.type_ )
+ // GCC 2.95.3 says:
+ // attempt to take address of bit-field structure member `Json::Value::type_'
+ // Beats me, but a temp solves the problem.
+ int temp = other.type_;
+ if (type_ != temp)
+ return false;
+ switch (type_) {
+ case nullValue:
+ return true;
+ case intValue:
+ return value_.int_ == other.value_.int_;
+ case uintValue:
+ return value_.uint_ == other.value_.uint_;
+ case realValue:
+ return value_.real_ == other.value_.real_;
+ case booleanValue:
+ return value_.bool_ == other.value_.bool_;
+ case stringValue:
+ {
+ if ((value_.string_ == 0) || (other.value_.string_ == 0)) {
+ return (value_.string_ == other.value_.string_);
+ }
+ unsigned this_len;
+ unsigned other_len;
+ char const* this_str;
+ char const* other_str;
+ decodePrefixedString(this->allocated_, this->value_.string_, &this_len, &this_str);
+ decodePrefixedString(other.allocated_, other.value_.string_, &other_len, &other_str);
+ if (this_len != other_len) return false;
+ int comp = memcmp(this_str, other_str, this_len);
+ return comp == 0;
+ }
+ case arrayValue:
+ case objectValue:
+ return value_.map_->size() == other.value_.map_->size() &&
+ (*value_.map_) == (*other.value_.map_);
+ default:
+ JSON_ASSERT_UNREACHABLE;
+ }
+ return false; // unreachable
+}
+
+bool Value::operator!=(const Value& other) const { return !(*this == other); }
+
+const char* Value::asCString() const {
+ JSON_ASSERT_MESSAGE(type_ == stringValue,
+ "in Json::Value::asCString(): requires stringValue");
+ if (value_.string_ == 0) return 0;
+ unsigned this_len;
+ char const* this_str;
+ decodePrefixedString(this->allocated_, this->value_.string_, &this_len, &this_str);
+ return this_str;
+}
+
+bool Value::getString(char const** str, char const** cend) const {
+ if (type_ != stringValue) return false;
+ if (value_.string_ == 0) return false;
+ unsigned length;
+ decodePrefixedString(this->allocated_, this->value_.string_, &length, str);
+ *cend = *str + length;
+ return true;
+}
+
+std::string Value::asString() const {
+ switch (type_) {
+ case nullValue:
+ return "";
+ case stringValue:
+ {
+ if (value_.string_ == 0) return "";
+ unsigned this_len;
+ char const* this_str;
+ decodePrefixedString(this->allocated_, this->value_.string_, &this_len, &this_str);
+ return std::string(this_str, this_len);
+ }
+ case booleanValue:
+ return value_.bool_ ? "true" : "false";
+ case intValue:
+ return valueToString(value_.int_);
+ case uintValue:
+ return valueToString(value_.uint_);
+ case realValue:
+ return valueToString(value_.real_);
+ default:
+ if ( default_value_ )
+ return default_value_->asString();
+ else
+ return "";
+ }
+}
+
+#ifdef JSON_USE_CPPTL
+CppTL::ConstString Value::asConstString() const {
+ unsigned len;
+ char const* str;
+ decodePrefixedString(allocated_, value_.string_,
+ &len, &str);
+ return CppTL::ConstString(str, len);
+}
+#endif
+
+Value::Int Value::asInt() const {
+ switch (type_) {
+ case intValue:
+ JSON_ASSERT_MESSAGE(isInt(), "LargestInt out of Int range");
+ return Int(value_.int_);
+ case uintValue:
+ JSON_ASSERT_MESSAGE(isInt(), "LargestUInt out of Int range");
+ return Int(value_.uint_);
+ case realValue:
+ JSON_ASSERT_MESSAGE(InRange(value_.real_, minInt, maxInt),
+ "double out of Int range");
+ return Int(value_.real_);
+ case nullValue:
+ return 0;
+ case booleanValue:
+ return value_.bool_ ? 1 : 0;
+ default:
+ if ( default_value_ )
+ return default_value_->asInt();
+ else
+ return 0;
+ }
+}
+
+Value::UInt Value::asUInt() const {
+ switch (type_) {
+ case intValue:
+ JSON_ASSERT_MESSAGE(isUInt(), "LargestInt out of UInt range");
+ return UInt(value_.int_);
+ case uintValue:
+ JSON_ASSERT_MESSAGE(isUInt(), "LargestUInt out of UInt range");
+ return UInt(value_.uint_);
+ case realValue:
+ JSON_ASSERT_MESSAGE(InRange(value_.real_, 0, maxUInt),
+ "double out of UInt range");
+ return UInt(value_.real_);
+ case nullValue:
+ return 0;
+ case booleanValue:
+ return value_.bool_ ? 1 : 0;
+ default:
+ if ( default_value_ )
+ return default_value_->asUInt();
+ else
+ return 0u;
+ }
+}
+
+#if defined(JSON_HAS_INT64)
+
+Value::Int64 Value::asInt64() const {
+ switch (type_) {
+ case intValue:
+ return Int64(value_.int_);
+ case uintValue:
+ JSON_ASSERT_MESSAGE(isInt64(), "LargestUInt out of Int64 range");
+ return Int64(value_.uint_);
+ case realValue:
+ JSON_ASSERT_MESSAGE(InRange(value_.real_, minInt64, maxInt64),
+ "double out of Int64 range");
+ return Int64(value_.real_);
+ case nullValue:
+ return 0;
+ case booleanValue:
+ return value_.bool_ ? 1 : 0;
+ default:
+ if ( default_value_ )
+ return default_value_->asInt64();
+ else
+ return 0l;
+ }
+}
+
+Value::UInt64 Value::asUInt64() const {
+ switch (type_) {
+ case intValue:
+ JSON_ASSERT_MESSAGE(isUInt64(), "LargestInt out of UInt64 range");
+ return UInt64(value_.int_);
+ case uintValue:
+ return UInt64(value_.uint_);
+ case realValue:
+ JSON_ASSERT_MESSAGE(InRange(value_.real_, 0, maxUInt64),
+ "double out of UInt64 range");
+ return UInt64(value_.real_);
+ case nullValue:
+ return 0;
+ case booleanValue:
+ return value_.bool_ ? 1 : 0;
+ default:
+ if ( default_value_ )
+ return default_value_->asUInt64();
+ else
+ return 0ul;
+ }
+}
+#endif // if defined(JSON_HAS_INT64)
+
+LargestInt Value::asLargestInt() const {
+#if defined(JSON_NO_INT64)
+ return asInt();
+#else
+ return asInt64();
+#endif
+}
+
+LargestUInt Value::asLargestUInt() const {
+#if defined(JSON_NO_INT64)
+ return asUInt();
+#else
+ return asUInt64();
+#endif
+}
+
+double Value::asDouble() const {
+ switch (type_) {
+ case intValue:
+ return static_cast<double>(value_.int_);
+ case uintValue:
+#if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
+ return static_cast<double>(value_.uint_);
+#else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
+ return integerToDouble(value_.uint_);
+#endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
+ case realValue:
+ return value_.real_;
+ case nullValue:
+ return 0.0;
+ case booleanValue:
+ return value_.bool_ ? 1.0 : 0.0;
+ default:
+ if ( default_value_ )
+ return default_value_->asDouble();
+ else
+ return 0.0;
+ }
+}
+
+float Value::asFloat() const {
+ switch (type_) {
+ case intValue:
+ return static_cast<float>(value_.int_);
+ case uintValue:
+#if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
+ return static_cast<float>(value_.uint_);
+#else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
+ return integerToDouble(value_.uint_);
+#endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
+ case realValue:
+ return static_cast<float>(value_.real_);
+ case nullValue:
+ return 0.0;
+ case booleanValue:
+ return value_.bool_ ? 1.0f : 0.0f;
+ default:
+ if ( default_value_ )
+ return default_value_->asFloat();
+ else
+ return 0.0f;
+ }
+}
+
+bool Value::asBool() const {
+ switch (type_) {
+ case booleanValue:
+ return value_.bool_;
+ case nullValue:
+ return false;
+ case intValue:
+ return value_.int_ ? true : false;
+ case uintValue:
+ return value_.uint_ ? true : false;
+ case realValue:
+ // This is kind of strange. Not recommended.
+ return (value_.real_ != 0.0) ? true : false;
+ default:
+ if ( default_value_ )
+ return default_value_->asBool();
+ else
+ return false;
+ }
+}
+
+bool Value::isConvertibleTo(ValueType other) const {
+ switch (other) {
+ case nullValue:
+ return (isNumeric() && asDouble() == 0.0) ||
+ (type_ == booleanValue && value_.bool_ == false) ||
+ (type_ == stringValue && asString() == "") ||
+ (type_ == arrayValue && value_.map_->size() == 0) ||
+ (type_ == objectValue && value_.map_->size() == 0) ||
+ type_ == nullValue;
+ case intValue:
+ return isInt() ||
+ (type_ == realValue && InRange(value_.real_, minInt, maxInt)) ||
+ type_ == booleanValue || type_ == nullValue;
+ case uintValue:
+ return isUInt() ||
+ (type_ == realValue && InRange(value_.real_, 0, maxUInt)) ||
+ type_ == booleanValue || type_ == nullValue;
+ case realValue:
+ return isNumeric() || type_ == booleanValue || type_ == nullValue;
+ case booleanValue:
+ return isNumeric() || type_ == booleanValue || type_ == nullValue;
+ case stringValue:
+ return isNumeric() || type_ == booleanValue || type_ == stringValue ||
+ type_ == nullValue;
+ case arrayValue:
+ return type_ == arrayValue || type_ == nullValue;
+ case objectValue:
+ return type_ == objectValue || type_ == nullValue;
+ }
+ JSON_ASSERT_UNREACHABLE;
+ return false;
+}
+
+/// Number of values in array or object
+ArrayIndex Value::size() const {
+ switch (type_) {
+ case nullValue:
+ case intValue:
+ case uintValue:
+ case realValue:
+ case booleanValue:
+ case stringValue:
+ return 0;
+ case arrayValue: // size of the array is highest index + 1
+ if (!value_.map_->empty()) {
+ ObjectValues::const_iterator itLast = value_.map_->end();
+ --itLast;
+ return (*itLast).first.index() + 1;
+ }
+ return 0;
+ case objectValue:
+ return ArrayIndex(value_.map_->size());
+ }
+ JSON_ASSERT_UNREACHABLE;
+ return 0; // unreachable;
+}
+
+bool Value::empty() const {
+ if (isNull() || isArray() || isObject())
+ return size() == 0u;
+ else
+ return false;
+}
+
+bool Value::operator!() const { return isNull(); }
+
+void Value::clear() {
+ JSON_ASSERT_MESSAGE(type_ == nullValue || type_ == arrayValue ||
+ type_ == objectValue,
+ "in Json::Value::clear(): requires complex value");
+ start_ = 0;
+ limit_ = 0;
+ delete default_value_;
+ default_value_ = nullptr;
+ switch (type_) {
+ case arrayValue:
+ case objectValue:
+ value_.map_->clear();
+ break;
+ default:
+ break;
+ }
+}
+
+void Value::resize(ArrayIndex newSize) {
+ JSON_ASSERT_MESSAGE(type_ == nullValue || type_ == arrayValue,
+ "in Json::Value::resize(): requires arrayValue");
+ if (type_ == nullValue)
+ *this = Value(arrayValue);
+ ArrayIndex oldSize = size();
+ if (newSize == 0)
+ clear();
+ else if (newSize > oldSize)
+ (*this)[newSize - 1];
+ else {
+ for (ArrayIndex index = newSize; index < oldSize; ++index) {
+ value_.map_->erase(index);
+ }
+ assert(size() == newSize);
+ }
+}
+
+Value& Value::operator[](ArrayIndex index) {
+ JSON_ASSERT_MESSAGE(
+ type_ == nullValue || type_ == arrayValue,
+ "in Json::Value::operator[](ArrayIndex): requires arrayValue");
+ if (type_ == nullValue)
+ *this = Value(arrayValue);
+ CZString key(index);
+ ObjectValues::iterator it = value_.map_->lower_bound(key);
+ if (it != value_.map_->end() && (*it).first == key)
+ return (*it).second;
+
+ ObjectValues::value_type defaultValue(key, nullRef);
+ it = value_.map_->insert(it, defaultValue);
+ return (*it).second;
+}
+
+Value& Value::operator[](int index) {
+ JSON_ASSERT_MESSAGE(
+ index >= 0,
+ "in Json::Value::operator[](int index): index cannot be negative");
+ return (*this)[ArrayIndex(index)];
+}
+
+const Value& Value::operator[](ArrayIndex index) const {
+ JSON_ASSERT_MESSAGE(
+ type_ == nullValue || type_ == arrayValue,
+ "in Json::Value::operator[](ArrayIndex)const: requires arrayValue");
+ if (type_ == nullValue)
+ return nullRef;
+ CZString key(index);
+ ObjectValues::const_iterator it = value_.map_->find(key);
+ if (it == value_.map_->end())
+ return nullRef;
+ return (*it).second;
+}
+
+const Value& Value::operator[](int index) const {
+ JSON_ASSERT_MESSAGE(
+ index >= 0,
+ "in Json::Value::operator[](int index) const: index cannot be negative");
+ return (*this)[ArrayIndex(index)];
+}
+
+void Value::initBasic(ValueType vtype, bool allocated) {
+ type_ = vtype;
+ allocated_ = allocated;
+ comments_ = 0;
+ start_ = 0;
+ limit_ = 0;
+ default_value_ = nullptr;
+}
+
+// Access an object value by name, create a null member if it does not exist.
+// @pre Type of '*this' is object or null.
+// @param key is null-terminated.
+Value& Value::resolveReference(const char* key) {
+ JSON_ASSERT_MESSAGE(
+ type_ == nullValue || type_ == objectValue,
+ "in Json::Value::resolveReference(): requires objectValue");
+ if (type_ == nullValue)
+ *this = Value(objectValue);
+ CZString actualKey(
+ key, static_cast<unsigned>(strlen(key)), CZString::noDuplication); // NOTE!
+ ObjectValues::iterator it = value_.map_->lower_bound(actualKey);
+ if (it != value_.map_->end() && (*it).first == actualKey)
+ return (*it).second;
+
+ ObjectValues::value_type defaultValue(actualKey, nullRef);
+ it = value_.map_->insert(it, defaultValue);
+ Value& value = (*it).second;
+ return value;
+}
+
+// @param key is not null-terminated.
+Value& Value::resolveReference(char const* key, char const* cend)
+{
+ JSON_ASSERT_MESSAGE(
+ type_ == nullValue || type_ == objectValue,
+ "in Json::Value::resolveReference(key, end): requires objectValue");
+ if (type_ == nullValue)
+ *this = Value(objectValue);
+ CZString actualKey(
+ key, static_cast<unsigned>(cend-key), CZString::duplicateOnCopy);
+ ObjectValues::iterator it = value_.map_->lower_bound(actualKey);
+ if (it != value_.map_->end() && (*it).first == actualKey)
+ return (*it).second;
+
+ ObjectValues::value_type defaultValue(actualKey, nullRef);
+ it = value_.map_->insert(it, defaultValue);
+ Value& value = (*it).second;
+ return value;
+}
+
+Value Value::get(ArrayIndex index, const Value& defaultValue) const {
+ const Value* value = &((*this)[index]);
+ if ( value == &nullRef )
+ {
+ return defaultValue;
+ }
+ else
+ {
+ Value result = *value;
+ result.default_value_ = new Value( defaultValue );
+ return result;
+ }
+}
+
+bool Value::isValidIndex(ArrayIndex index) const { return index < size(); }
+
+Value const* Value::find(char const* key, char const* cend) const
+{
+ JSON_ASSERT_MESSAGE(
+ type_ == nullValue || type_ == objectValue,
+ "in Json::Value::find(key, end, found): requires objectValue or nullValue");
+ if (type_ == nullValue) return NULL;
+ CZString actualKey(key, static_cast<unsigned>(cend-key), CZString::noDuplication);
+ ObjectValues::const_iterator it = value_.map_->find(actualKey);
+ if (it == value_.map_->end()) return NULL;
+ return &(*it).second;
+}
+const Value& Value::operator[](const char* key) const
+{
+ Value const* found = find(key, key + strlen(key));
+ if (!found) return nullRef;
+ return *found;
+}
+Value const& Value::operator[](std::string const& key) const
+{
+ Value const* found = find(key.data(), key.data() + key.length());
+ if (!found) return nullRef;
+ return *found;
+}
+
+Value& Value::operator[](const char* key) {
+ return resolveReference(key, key + strlen(key));
+}
+
+Value& Value::operator[](const std::string& key) {
+ return resolveReference(key.data(), key.data() + key.length());
+}
+
+Value& Value::operator[](const StaticString& key) {
+ return resolveReference(key.c_str());
+}
+
+#ifdef JSON_USE_CPPTL
+Value& Value::operator[](const CppTL::ConstString& key) {
+ return resolveReference(key.c_str(), key.end_c_str());
+}
+Value const& Value::operator[](CppTL::ConstString const& key) const
+{
+ Value const* found = find(key.c_str(), key.end_c_str());
+ if (!found) return nullRef;
+ return *found;
+}
+#endif
+
+Value& Value::append(const Value& value) { return (*this)[size()] = value; }
+
+Value Value::get(char const* key, char const* cend, Value const& defaultValue) const
+{
+ Value const* found = find(key, cend);
+ if ( !found )
+ {
+ return defaultValue;
+ }
+ else
+ {
+ Value result = *found;
+ result.default_value_ = new Value( defaultValue );
+ return result;
+ }
+}
+Value Value::get(char const* key, Value const& defaultValue) const
+{
+ return get(key, key + strlen(key), defaultValue);
+}
+Value Value::get(std::string const& key, Value const& defaultValue) const
+{
+ return get(key.data(), key.data() + key.length(), defaultValue);
+}
+
+
+bool Value::removeMember(const char* key, const char* cend, Value* removed)
+{
+ if (type_ != objectValue) {
+ return false;
+ }
+ CZString actualKey(key, static_cast<unsigned>(cend-key), CZString::noDuplication);
+ ObjectValues::iterator it = value_.map_->find(actualKey);
+ if (it == value_.map_->end())
+ return false;
+ *removed = it->second;
+ value_.map_->erase(it);
+ return true;
+}
+bool Value::removeMember(const char* key, Value* removed)
+{
+ return removeMember(key, key + strlen(key), removed);
+}
+bool Value::removeMember(std::string const& key, Value* removed)
+{
+ return removeMember(key.data(), key.data() + key.length(), removed);
+}
+Value Value::removeMember(const char* key)
+{
+ JSON_ASSERT_MESSAGE(type_ == nullValue || type_ == objectValue,
+ "in Json::Value::removeMember(): requires objectValue");
+ if (type_ == nullValue)
+ return nullRef;
+
+ Value removed; // null
+ removeMember(key, key + strlen(key), &removed);
+ return removed; // still null if removeMember() did nothing
+}
+Value Value::removeMember(const std::string& key)
+{
+ return removeMember(key.c_str());
+}
+
+bool Value::removeIndex(ArrayIndex index, Value* removed) {
+ if (type_ != arrayValue) {
+ return false;
+ }
+ CZString key(index);
+ ObjectValues::iterator it = value_.map_->find(key);
+ if (it == value_.map_->end()) {
+ return false;
+ }
+ *removed = it->second;
+ ArrayIndex oldSize = size();
+ // shift left all items left, into the place of the "removed"
+ for (ArrayIndex i = index; i < (oldSize - 1); ++i){
+ CZString keey(i);
+ (*value_.map_)[keey] = (*this)[i + 1];
+ }
+ // erase the last one ("leftover")
+ CZString keyLast(oldSize - 1);
+ ObjectValues::iterator itLast = value_.map_->find(keyLast);
+ value_.map_->erase(itLast);
+ return true;
+}
+
+#ifdef JSON_USE_CPPTL
+Value Value::get(const CppTL::ConstString& key,
+ const Value& defaultValue) const {
+ return get(key.c_str(), key.end_c_str(), defaultValue);
+}
+#endif
+
+bool Value::isMember(char const* key, char const* cend) const
+{
+ Value const* value = find(key, cend);
+ return NULL != value;
+}
+bool Value::isMember(char const* key) const
+{
+ return isMember(key, key + strlen(key));
+}
+bool Value::isMember(std::string const& key) const
+{
+ return isMember(key.data(), key.data() + key.length());
+}
+
+#ifdef JSON_USE_CPPTL
+bool Value::isMember(const CppTL::ConstString& key) const {
+ return isMember(key.c_str(), key.end_c_str());
+}
+#endif
+
+Value::Members Value::getMemberNames() const {
+ JSON_ASSERT_MESSAGE(
+ type_ == nullValue || type_ == objectValue,
+ "in Json::Value::getMemberNames(), value must be objectValue");
+ if (type_ == nullValue)
+ return Value::Members();
+ Members members;
+ members.reserve(value_.map_->size());
+ ObjectValues::const_iterator it = value_.map_->begin();
+ ObjectValues::const_iterator itEnd = value_.map_->end();
+ for (; it != itEnd; ++it) {
+ members.push_back(std::string((*it).first.data(),
+ (*it).first.length()));
+ }
+ return members;
+}
+//
+//# ifdef JSON_USE_CPPTL
+// EnumMemberNames
+// Value::enumMemberNames() const
+//{
+// if ( type_ == objectValue )
+// {
+// return CppTL::Enum::any( CppTL::Enum::transform(
+// CppTL::Enum::keys( *(value_.map_), CppTL::Type<const CZString &>() ),
+// MemberNamesTransform() ) );
+// }
+// return EnumMemberNames();
+//}
+//
+//
+// EnumValues
+// Value::enumValues() const
+//{
+// if ( type_ == objectValue || type_ == arrayValue )
+// return CppTL::Enum::anyValues( *(value_.map_),
+// CppTL::Type<const Value &>() );
+// return EnumValues();
+//}
+//
+//# endif
+
+static bool IsIntegral(double d) {
+ double integral_part;
+ return modf(d, &integral_part) == 0.0;
+}
+
+bool Value::isNull() const { return type_ == nullValue; }
+
+bool Value::isBool() const { return type_ == booleanValue; }
+
+bool Value::isInt() const {
+ switch (type_) {
+ case intValue:
+ return value_.int_ >= minInt && value_.int_ <= maxInt;
+ case uintValue:
+ return value_.uint_ <= UInt(maxInt);
+ case realValue:
+ return value_.real_ >= minInt && value_.real_ <= maxInt &&
+ IsIntegral(value_.real_);
+ default:
+ break;
+ }
+ return false;
+}
+
+bool Value::isUInt() const {
+ switch (type_) {
+ case intValue:
+ return value_.int_ >= 0 && LargestUInt(value_.int_) <= LargestUInt(maxUInt);
+ case uintValue:
+ return value_.uint_ <= maxUInt;
+ case realValue:
+ return value_.real_ >= 0 && value_.real_ <= maxUInt &&
+ IsIntegral(value_.real_);
+ default:
+ break;
+ }
+ return false;
+}
+
+bool Value::isInt64() const {
+#if defined(JSON_HAS_INT64)
+ switch (type_) {
+ case intValue:
+ return true;
+ case uintValue:
+ return value_.uint_ <= UInt64(maxInt64);
+ case realValue:
+ // Note that maxInt64 (= 2^63 - 1) is not exactly representable as a
+ // double, so double(maxInt64) will be rounded up to 2^63. Therefore we
+ // require the value to be strictly less than the limit.
+ return value_.real_ >= double(minInt64) &&
+ value_.real_ < double(maxInt64) && IsIntegral(value_.real_);
+ default:
+ break;
+ }
+#endif // JSON_HAS_INT64
+ return false;
+}
+
+bool Value::isUInt64() const {
+#if defined(JSON_HAS_INT64)
+ switch (type_) {
+ case intValue:
+ return value_.int_ >= 0;
+ case uintValue:
+ return true;
+ case realValue:
+ // Note that maxUInt64 (= 2^64 - 1) is not exactly representable as a
+ // double, so double(maxUInt64) will be rounded up to 2^64. Therefore we
+ // require the value to be strictly less than the limit.
+ return value_.real_ >= 0 && value_.real_ < maxUInt64AsDouble &&
+ IsIntegral(value_.real_);
+ default:
+ break;
+ }
+#endif // JSON_HAS_INT64
+ return false;
+}
+
+bool Value::isIntegral() const {
+#if defined(JSON_HAS_INT64)
+ return isInt64() || isUInt64();
+#else
+ return isInt() || isUInt();
+#endif
+}
+
+bool Value::isDouble() const { return type_ == realValue || isIntegral(); }
+
+bool Value::isNumeric() const { return isIntegral() || isDouble(); }
+
+bool Value::isString() const { return type_ == stringValue; }
+
+bool Value::isArray() const { return type_ == arrayValue; }
+
+bool Value::isObject() const { return type_ == objectValue; }
+
+void Value::setComment(const char* comment, size_t len, CommentPlacement placement) {
+ if (!comments_)
+ comments_ = new CommentInfo[numberOfCommentPlacement];
+ if ((len > 0) && (comment[len-1] == '\n')) {
+ // Always discard trailing newline, to aid indentation.
+ len -= 1;
+ }
+ comments_[placement].setComment(comment, len);
+}
+
+void Value::setComment(const char* comment, CommentPlacement placement) {
+ setComment(comment, strlen(comment), placement);
+}
+
+void Value::setComment(const std::string& comment, CommentPlacement placement) {
+ setComment(comment.c_str(), comment.length(), placement);
+}
+
+bool Value::hasComment(CommentPlacement placement) const {
+ return comments_ != 0 && comments_[placement].comment_ != 0;
+}
+
+std::string Value::getComment(CommentPlacement placement) const {
+ if (hasComment(placement))
+ return comments_[placement].comment_;
+ return "";
+}
+
+void Value::setOffsetStart(size_t start) { start_ = start; }
+
+void Value::setOffsetLimit(size_t limit) { limit_ = limit; }
+
+size_t Value::getOffsetStart() const { return start_; }
+
+size_t Value::getOffsetLimit() const { return limit_; }
+
+std::string Value::toStyledString() const {
+ StyledWriter writer;
+ return writer.write(*this);
+}
+
+Value::const_iterator Value::begin() const {
+ switch (type_) {
+ case arrayValue:
+ case objectValue:
+ if (value_.map_)
+ return const_iterator(value_.map_->begin());
+ break;
+ default:
+ break;
+ }
+ return const_iterator();
+}
+
+Value::const_iterator Value::end() const {
+ switch (type_) {
+ case arrayValue:
+ case objectValue:
+ if (value_.map_)
+ return const_iterator(value_.map_->end());
+ break;
+ default:
+ break;
+ }
+ return const_iterator();
+}
+
+Value::iterator Value::begin() {
+ switch (type_) {
+ case arrayValue:
+ case objectValue:
+ if (value_.map_)
+ return iterator(value_.map_->begin());
+ break;
+ default:
+ break;
+ }
+ return iterator();
+}
+
+Value::iterator Value::end() {
+ switch (type_) {
+ case arrayValue:
+ case objectValue:
+ if (value_.map_)
+ return iterator(value_.map_->end());
+ break;
+ default:
+ break;
+ }
+ return iterator();
+}
+
+// class PathArgument
+// //////////////////////////////////////////////////////////////////
+
+PathArgument::PathArgument() : key_(), index_(), kind_(kindNone) {}
+
+PathArgument::PathArgument(ArrayIndex index)
+ : key_(), index_(index), kind_(kindIndex) {}
+
+PathArgument::PathArgument(const char* key)
+ : key_(key), index_(), kind_(kindKey) {}
+
+PathArgument::PathArgument(const std::string& key)
+ : key_(key.c_str()), index_(), kind_(kindKey) {}
+
+// class Path
+// //////////////////////////////////////////////////////////////////
+
+Path::Path(const std::string& path,
+ const PathArgument& a1,
+ const PathArgument& a2,
+ const PathArgument& a3,
+ const PathArgument& a4,
+ const PathArgument& a5) {
+ InArgs in;
+ in.push_back(&a1);
+ in.push_back(&a2);
+ in.push_back(&a3);
+ in.push_back(&a4);
+ in.push_back(&a5);
+ makePath(path, in);
+}
+
+void Path::makePath(const std::string& path, const InArgs& in) {
+ const char* current = path.c_str();
+ const char* end = current + path.length();
+ InArgs::const_iterator itInArg = in.begin();
+ while (current != end) {
+ if (*current == '[') {
+ ++current;
+ if (*current == '%')
+ addPathInArg(path, in, itInArg, PathArgument::kindIndex);
+ else {
+ ArrayIndex index = 0;
+ for (; current != end && *current >= '0' && *current <= '9'; ++current)
+ index = index * 10 + ArrayIndex(*current - '0');
+ args_.push_back(index);
+ }
+ if (current == end || *current++ != ']')
+ invalidPath(path, int(current - path.c_str()));
+ } else if (*current == '%') {
+ addPathInArg(path, in, itInArg, PathArgument::kindKey);
+ ++current;
+ } else if (*current == '.') {
+ ++current;
+ } else {
+ const char* beginName = current;
+ while (current != end && !strchr("[.", *current))
+ ++current;
+ args_.push_back(std::string(beginName, current));
+ }
+ }
+}
+
+void Path::addPathInArg(const std::string& /*path*/,
+ const InArgs& in,
+ InArgs::const_iterator& itInArg,
+ PathArgument::Kind kind) {
+ if (itInArg == in.end()) {
+ // Error: missing argument %d
+ } else if ((*itInArg)->kind_ != kind) {
+ // Error: bad argument type
+ } else {
+ args_.push_back(**itInArg);
+ }
+}
+
+void Path::invalidPath(const std::string& /*path*/, int /*location*/) {
+ // Error: invalid path.
+}
+
+const Value& Path::resolve(const Value& root) const {
+ const Value* node = &root;
+ for (Args::const_iterator it = args_.begin(); it != args_.end(); ++it) {
+ const PathArgument& arg = *it;
+ if (arg.kind_ == PathArgument::kindIndex) {
+ if (!node->isArray() || !node->isValidIndex(arg.index_)) {
+ // Error: unable to resolve path (array value expected at position...
+ }
+ node = &((*node)[arg.index_]);
+ } else if (arg.kind_ == PathArgument::kindKey) {
+ if (!node->isObject()) {
+ // Error: unable to resolve path (object value expected at position...)
+ }
+ node = &((*node)[arg.key_]);
+ if (node == &Value::nullRef) {
+ // Error: unable to resolve path (object has no member named '' at
+ // position...)
+ }
+ }
+ }
+ return *node;
+}
+
+Value Path::resolve(const Value& root, const Value& defaultValue) const {
+ const Value* node = &root;
+ for (Args::const_iterator it = args_.begin(); it != args_.end(); ++it) {
+ const PathArgument& arg = *it;
+ if (arg.kind_ == PathArgument::kindIndex) {
+ if (!node->isArray() || !node->isValidIndex(arg.index_))
+ return defaultValue;
+ node = &((*node)[arg.index_]);
+ } else if (arg.kind_ == PathArgument::kindKey) {
+ if (!node->isObject())
+ return defaultValue;
+ node = &((*node)[arg.key_]);
+ if (node == &Value::nullRef)
+ return defaultValue;
+ }
+ }
+ return *node;
+}
+
+Value& Path::make(Value& root) const {
+ Value* node = &root;
+ for (Args::const_iterator it = args_.begin(); it != args_.end(); ++it) {
+ const PathArgument& arg = *it;
+ if (arg.kind_ == PathArgument::kindIndex) {
+ if (!node->isArray()) {
+ // Error: node is not an array at position ...
+ }
+ node = &((*node)[arg.index_]);
+ } else if (arg.kind_ == PathArgument::kindKey) {
+ if (!node->isObject()) {
+ // Error: node is not an object at position...
+ }
+ node = &((*node)[arg.key_]);
+ }
+ }
+ return *node;
+}
+
+} // namespace Json
+
+#pragma warning (pop)
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: src/lib_json/json_value.cpp
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
+
+// //////////////////////////////////////////////////////////////////////
+// Beginning of content of file: src/lib_json/json_writer.cpp
+// //////////////////////////////////////////////////////////////////////
+
+// Copyright 2011 Baptiste Lepilleur
+// Distributed under MIT license, or public domain if desired and
+// recognized in your jurisdiction.
+// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
+
+#if !defined(JSON_IS_AMALGAMATION)
+#include <json/writer.h>
+#include "json_tool.h"
+#endif // if !defined(JSON_IS_AMALGAMATION)
+#include <iomanip>
+#include <memory>
+#include <sstream>
+#include <utility>
+#include <set>
+#include <cassert>
+#include <cstring>
+#include <cstdio>
+
+#if defined(_MSC_VER) && _MSC_VER >= 1200 && _MSC_VER < 1800 // Between VC++ 6.0 and VC++ 11.0
+#include <float.h>
+#define isfinite _finite
+#elif defined(__sun) && defined(__SVR4) //Solaris
+#if !defined(isfinite)
+#include <ieeefp.h>
+#define isfinite finite
+#endif
+#elif defined(_AIX)
+#if !defined(isfinite)
+#include <math.h>
+#define isfinite finite
+#endif
+#elif defined(__hpux)
+#if !defined(isfinite)
+#if defined(__ia64) && !defined(finite)
+#define isfinite(x) ((sizeof(x) == sizeof(float) ? \
+ _Isfinitef(x) : _IsFinite(x)))
+#else
+#include <math.h>
+#define isfinite finite
+#endif
+#endif
+#else
+#include <cmath>
+#if !(defined(__QNXNTO__)) // QNX already defines isfinite
+#define isfinite std::isfinite
+#endif
+#endif
+
+#if defined(_MSC_VER)
+#if !defined(WINCE) && defined(__STDC_SECURE_LIB__) && _MSC_VER >= 1500 // VC++ 9.0 and above
+#define snprintf sprintf_s
+#elif _MSC_VER >= 1900 // VC++ 14.0 and above
+#define snprintf std::snprintf
+#else
+#define snprintf _snprintf
+#endif
+#elif defined(__ANDROID__) || defined(__QNXNTO__)
+#define snprintf snprintf
+#elif __cplusplus >= 201103L
+#define snprintf std::snprintf
+#endif
+
+#if defined(__BORLANDC__)
+#include <float.h>
+#define isfinite _finite
+#define snprintf _snprintf
+#endif
+
+#if defined(_MSC_VER) && _MSC_VER >= 1400 // VC++ 8.0
+// Disable warning about strdup being deprecated.
+#pragma warning(disable : 4996)
+#endif
+
+namespace Json {
+
+#if __cplusplus >= 201103L || (defined(_CPPLIB_VER) && _CPPLIB_VER >= 520)
+typedef std::unique_ptr<StreamWriter> StreamWriterPtr;
+#else
+typedef std::auto_ptr<StreamWriter> StreamWriterPtr;
+#endif
+
+static bool containsControlCharacter(const char* str) {
+ while (*str) {
+ if (isControlCharacter(*(str++)))
+ return true;
+ }
+ return false;
+}
+
+static bool containsControlCharacter0(const char* str, unsigned len) {
+ char const* end = str + len;
+ while (end != str) {
+ if (isControlCharacter(*str) || 0==*str)
+ return true;
+ ++str;
+ }
+ return false;
+}
+
+std::string valueToString(LargestInt value) {
+ UIntToStringBuffer buffer;
+ char* current = buffer + sizeof(buffer);
+ if (value == Value::minLargestInt) {
+ uintToString(LargestUInt(Value::maxLargestInt) + 1, current);
+ *--current = '-';
+ } else if (value < 0) {
+ uintToString(LargestUInt(-value), current);
+ *--current = '-';
+ } else {
+ uintToString(LargestUInt(value), current);
+ }
+ assert(current >= buffer);
+ return current;
+}
+
+std::string valueToString(LargestUInt value) {
+ UIntToStringBuffer buffer;
+ char* current = buffer + sizeof(buffer);
+ uintToString(value, current);
+ assert(current >= buffer);
+ return current;
+}
+
+#if defined(JSON_HAS_INT64)
+
+std::string valueToString(Int value) {
+ return valueToString(LargestInt(value));
+}
+
+std::string valueToString(UInt value) {
+ return valueToString(LargestUInt(value));
+}
+
+#endif // # if defined(JSON_HAS_INT64)
+
+std::string valueToString(double value, bool useSpecialFloats, unsigned int precision) {
+ // Allocate a buffer that is more than large enough to store the 16 digits of
+ // precision requested below.
+ char buffer[32];
+ int len = -1;
+
+ char formatString[6];
+ sprintf(formatString, "%%.%dg", precision);
+
+ // Print into the buffer. We need not request the alternative representation
+ // that always has a decimal point because JSON doesn't distingish the
+ // concepts of reals and integers.
+ if (isfinite(value)) {
+ len = snprintf(buffer, sizeof(buffer), formatString, value);
+ } else {
+ // IEEE standard states that NaN values will not compare to themselves
+ if (value != value) {
+ len = snprintf(buffer, sizeof(buffer), useSpecialFloats ? "NaN" : "null");
+ } else if (value < 0) {
+ len = snprintf(buffer, sizeof(buffer), useSpecialFloats ? "-Infinity" : "-1e+9999");
+ } else {
+ len = snprintf(buffer, sizeof(buffer), useSpecialFloats ? "Infinity" : "1e+9999");
+ }
+ // For those, we do not need to call fixNumLoc, but it is fast.
+ }
+ assert(len >= 0);
+ fixNumericLocale(buffer, buffer + len);
+ return buffer;
+}
+
+std::string valueToString(double value) { return valueToString(value, false, 17); }
+
+std::string valueToString(bool value) { return value ? "true" : "false"; }
+
+std::string valueToQuotedString(const char* value) {
+ if (value == NULL)
+ return "";
+ // Not sure how to handle unicode...
+ if (strpbrk(value, "\"\\\b\f\n\r\t") == NULL &&
+ !containsControlCharacter(value))
+ return std::string("\"") + value + "\"";
+ // We have to walk value and escape any special characters.
+ // Appending to std::string is not efficient, but this should be rare.
+ // (Note: forward slashes are *not* rare, but I am not escaping them.)
+ std::string::size_type maxsize =
+ strlen(value) * 2 + 3; // allescaped+quotes+NULL
+ std::string result;
+ result.reserve(maxsize); // to avoid lots of mallocs
+ result += "\"";
+ for (const char* c = value; *c != 0; ++c) {
+ switch (*c) {
+ case '\"':
+ result += "\\\"";
+ break;
+ case '\\':
+ result += "\\\\";
+ break;
+ case '\b':
+ result += "\\b";
+ break;
+ case '\f':
+ result += "\\f";
+ break;
+ case '\n':
+ result += "\\n";
+ break;
+ case '\r':
+ result += "\\r";
+ break;
+ case '\t':
+ result += "\\t";
+ break;
+ // case '/':
+ // Even though \/ is considered a legal escape in JSON, a bare
+ // slash is also legal, so I see no reason to escape it.
+ // (I hope I am not misunderstanding something.
+ // blep notes: actually escaping \/ may be useful in javascript to avoid </
+ // sequence.
+ // Should add a flag to allow this compatibility mode and prevent this
+ // sequence from occurring.
+ default:
+ if (isControlCharacter(*c)) {
+ std::ostringstream oss;
+ oss << "\\u" << std::hex << std::uppercase << std::setfill('0')
+ << std::setw(4) << static_cast<int>(*c);
+ result += oss.str();
+ } else {
+ result += *c;
+ }
+ break;
+ }
+ }
+ result += "\"";
+ return result;
+}
+
+// https://github.com/upcaste/upcaste/blob/master/src/upcore/src/cstring/strnpbrk.cpp
+static char const* strnpbrk(char const* s, char const* accept, size_t n) {
+ assert((s || !n) && accept);
+
+ char const* const end = s + n;
+ for (char const* cur = s; cur < end; ++cur) {
+ int const c = *cur;
+ for (char const* a = accept; *a; ++a) {
+ if (*a == c) {
+ return cur;
+ }
+ }
+ }
+ return NULL;
+}
+static std::string valueToQuotedStringN(const char* value, unsigned length) {
+ if (value == NULL)
+ return "";
+ // Not sure how to handle unicode...
+ if (strnpbrk(value, "\"\\\b\f\n\r\t", length) == NULL &&
+ !containsControlCharacter0(value, length))
+ return std::string("\"") + value + "\"";
+ // We have to walk value and escape any special characters.
+ // Appending to std::string is not efficient, but this should be rare.
+ // (Note: forward slashes are *not* rare, but I am not escaping them.)
+ std::string::size_type maxsize =
+ length * 2 + 3; // allescaped+quotes+NULL
+ std::string result;
+ result.reserve(maxsize); // to avoid lots of mallocs
+ result += "\"";
+ char const* end = value + length;
+ for (const char* c = value; c != end; ++c) {
+ switch (*c) {
+ case '\"':
+ result += "\\\"";
+ break;
+ case '\\':
+ result += "\\\\";
+ break;
+ case '\b':
+ result += "\\b";
+ break;
+ case '\f':
+ result += "\\f";
+ break;
+ case '\n':
+ result += "\\n";
+ break;
+ case '\r':
+ result += "\\r";
+ break;
+ case '\t':
+ result += "\\t";
+ break;
+ // case '/':
+ // Even though \/ is considered a legal escape in JSON, a bare
+ // slash is also legal, so I see no reason to escape it.
+ // (I hope I am not misunderstanding something.)
+ // blep notes: actually escaping \/ may be useful in javascript to avoid </
+ // sequence.
+ // Should add a flag to allow this compatibility mode and prevent this
+ // sequence from occurring.
+ default:
+ if ((isControlCharacter(*c)) || (*c == 0)) {
+ std::ostringstream oss;
+ oss << "\\u" << std::hex << std::uppercase << std::setfill('0')
+ << std::setw(4) << static_cast<int>(*c);
+ result += oss.str();
+ } else {
+ result += *c;
+ }
+ break;
+ }
+ }
+ result += "\"";
+ return result;
+}
+
+// Class Writer
+// //////////////////////////////////////////////////////////////////
+Writer::~Writer() {}
+
+// Class FastWriter
+// //////////////////////////////////////////////////////////////////
+
+FastWriter::FastWriter()
+ : yamlCompatiblityEnabled_(false), dropNullPlaceholders_(false),
+ omitEndingLineFeed_(false) {}
+
+void FastWriter::enableYAMLCompatibility() { yamlCompatiblityEnabled_ = true; }
+
+void FastWriter::dropNullPlaceholders() { dropNullPlaceholders_ = true; }
+
+void FastWriter::omitEndingLineFeed() { omitEndingLineFeed_ = true; }
+
+std::string FastWriter::write(const Value& root) {
+ document_ = "";
+ writeValue(root);
+ if (!omitEndingLineFeed_)
+ document_ += "\n";
+ return document_;
+}
+
+void FastWriter::writeValue(const Value& value) {
+ switch (value.type()) {
+ case nullValue:
+ if (!dropNullPlaceholders_)
+ document_ += "null";
+ break;
+ case intValue:
+ document_ += valueToString(value.asLargestInt());
+ break;
+ case uintValue:
+ document_ += valueToString(value.asLargestUInt());
+ break;
+ case realValue:
+ document_ += valueToString(value.asDouble());
+ break;
+ case stringValue:
+ {
+ // Is NULL possible for value.string_?
+ char const* str;
+ char const* end;
+ bool ok = value.getString(&str, &end);
+ if (ok) document_ += valueToQuotedStringN(str, static_cast<unsigned>(end-str));
+ break;
+ }
+ case booleanValue:
+ document_ += valueToString(value.asBool());
+ break;
+ case arrayValue: {
+ document_ += '[';
+ int size = value.size();
+ for (int index = 0; index < size; ++index) {
+ if (index > 0)
+ document_ += ',';
+ writeValue(value[index]);
+ }
+ document_ += ']';
+ } break;
+ case objectValue: {
+ Value::Members members(value.getMemberNames());
+ document_ += '{';
+ for (Value::Members::iterator it = members.begin(); it != members.end();
+ ++it) {
+ const std::string& name = *it;
+ if (it != members.begin())
+ document_ += ',';
+ document_ += valueToQuotedStringN(name.data(), static_cast<unsigned>(name.length()));
+ document_ += yamlCompatiblityEnabled_ ? ": " : ":";
+ writeValue(value[name]);
+ }
+ document_ += '}';
+ } break;
+ }
+}
+
+// Class StyledWriter
+// //////////////////////////////////////////////////////////////////
+
+StyledWriter::StyledWriter()
+ : rightMargin_(74), indentSize_(3), addChildValues_() {}
+
+std::string StyledWriter::write(const Value& root) {
+ document_ = "";
+ addChildValues_ = false;
+ indentString_ = "";
+ writeCommentBeforeValue(root);
+ writeValue(root);
+ writeCommentAfterValueOnSameLine(root);
+ document_ += "\n";
+ return document_;
+}
+
+void StyledWriter::writeValue(const Value& value) {
+ switch (value.type()) {
+ case nullValue:
+ pushValue("null");
+ break;
+ case intValue:
+ pushValue(valueToString(value.asLargestInt()));
+ break;
+ case uintValue:
+ pushValue(valueToString(value.asLargestUInt()));
+ break;
+ case realValue:
+ pushValue(valueToString(value.asDouble()));
+ break;
+ case stringValue:
+ {
+ // Is NULL possible for value.string_?
+ char const* str;
+ char const* end;
+ bool ok = value.getString(&str, &end);
+ if (ok) pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end-str)));
+ else pushValue("");
+ break;
+ }
+ case booleanValue:
+ pushValue(valueToString(value.asBool()));
+ break;
+ case arrayValue:
+ writeArrayValue(value);
+ break;
+ case objectValue: {
+ Value::Members members(value.getMemberNames());
+ if (members.empty())
+ pushValue("{}");
+ else {
+ writeWithIndent("{");
+ indent();
+ Value::Members::iterator it = members.begin();
+ for (;;) {
+ const std::string& name = *it;
+ const Value& childValue = value[name];
+ writeCommentBeforeValue(childValue);
+ writeWithIndent(valueToQuotedString(name.c_str()));
+ document_ += " : ";
+ writeValue(childValue);
+ if (++it == members.end()) {
+ writeCommentAfterValueOnSameLine(childValue);
+ break;
+ }
+ document_ += ',';
+ writeCommentAfterValueOnSameLine(childValue);
+ }
+ unindent();
+ writeWithIndent("}");
+ }
+ } break;
+ }
+}
+
+void StyledWriter::writeArrayValue(const Value& value) {
+ unsigned size = value.size();
+ if (size == 0)
+ pushValue("[]");
+ else {
+ bool isArrayMultiLine = isMultineArray(value);
+ if (isArrayMultiLine) {
+ writeWithIndent("[");
+ indent();
+ bool hasChildValue = !childValues_.empty();
+ unsigned index = 0;
+ for (;;) {
+ const Value& childValue = value[index];
+ writeCommentBeforeValue(childValue);
+ if (hasChildValue)
+ writeWithIndent(childValues_[index]);
+ else {
+ writeIndent();
+ writeValue(childValue);
+ }
+ if (++index == size) {
+ writeCommentAfterValueOnSameLine(childValue);
+ break;
+ }
+ document_ += ',';
+ writeCommentAfterValueOnSameLine(childValue);
+ }
+ unindent();
+ writeWithIndent("]");
+ } else // output on a single line
+ {
+ assert(childValues_.size() == size);
+ document_ += "[ ";
+ for (unsigned index = 0; index < size; ++index) {
+ if (index > 0)
+ document_ += ", ";
+ document_ += childValues_[index];
+ }
+ document_ += " ]";
+ }
+ }
+}
+
+bool StyledWriter::isMultineArray(const Value& value) {
+ int size = value.size();
+ bool isMultiLine = size * 3 >= rightMargin_;
+ childValues_.clear();
+ for (int index = 0; index < size && !isMultiLine; ++index) {
+ const Value& childValue = value[index];
+ isMultiLine = ((childValue.isArray() || childValue.isObject()) &&
+ childValue.size() > 0);
+ }
+ if (!isMultiLine) // check if line length > max line length
+ {
+ childValues_.reserve(size);
+ addChildValues_ = true;
+ int lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
+ for (int index = 0; index < size; ++index) {
+ if (hasCommentForValue(value[index])) {
+ isMultiLine = true;
+ }
+ writeValue(value[index]);
+ lineLength += int(childValues_[index].length());
+ }
+ addChildValues_ = false;
+ isMultiLine = isMultiLine || lineLength >= rightMargin_;
+ }
+ return isMultiLine;
+}
+
+void StyledWriter::pushValue(const std::string& value) {
+ if (addChildValues_)
+ childValues_.push_back(value);
+ else
+ document_ += value;
+}
+
+void StyledWriter::writeIndent() {
+ if (!document_.empty()) {
+ char last = document_[document_.length() - 1];
+ if (last == ' ') // already indented
+ return;
+ if (last != '\n') // Comments may add new-line
+ document_ += '\n';
+ }
+ document_ += indentString_;
+}
+
+void StyledWriter::writeWithIndent(const std::string& value) {
+ writeIndent();
+ document_ += value;
+}
+
+void StyledWriter::indent() { indentString_ += std::string(indentSize_, ' '); }
+
+void StyledWriter::unindent() {
+ assert(int(indentString_.size()) >= indentSize_);
+ indentString_.resize(indentString_.size() - indentSize_);
+}
+
+void StyledWriter::writeCommentBeforeValue(const Value& root) {
+ if (!root.hasComment(commentBefore))
+ return;
+
+ document_ += "\n";
+ writeIndent();
+ const std::string& comment = root.getComment(commentBefore);
+ std::string::const_iterator iter = comment.begin();
+ while (iter != comment.end()) {
+ document_ += *iter;
+ if (*iter == '\n' &&
+ (iter != comment.end() && *(iter + 1) == '/'))
+ writeIndent();
+ ++iter;
+ }
+
+ // Comments are stripped of trailing newlines, so add one here
+ document_ += "\n";
+}
+
+void StyledWriter::writeCommentAfterValueOnSameLine(const Value& root) {
+ if (root.hasComment(commentAfterOnSameLine))
+ document_ += " " + root.getComment(commentAfterOnSameLine);
+
+ if (root.hasComment(commentAfter)) {
+ document_ += "\n";
+ document_ += root.getComment(commentAfter);
+ document_ += "\n";
+ }
+}
+
+bool StyledWriter::hasCommentForValue(const Value& value) {
+ return value.hasComment(commentBefore) ||
+ value.hasComment(commentAfterOnSameLine) ||
+ value.hasComment(commentAfter);
+}
+
+// Class StyledStreamWriter
+// //////////////////////////////////////////////////////////////////
+
+StyledStreamWriter::StyledStreamWriter(std::string indentation)
+ : document_(NULL), rightMargin_(74), indentation_(indentation),
+ addChildValues_() {}
+
+void StyledStreamWriter::write(std::ostream& out, const Value& root) {
+ document_ = &out;
+ addChildValues_ = false;
+ indentString_ = "";
+ indented_ = true;
+ writeCommentBeforeValue(root);
+ if (!indented_) writeIndent();
+ indented_ = true;
+ writeValue(root);
+ writeCommentAfterValueOnSameLine(root);
+ *document_ << "\n";
+ document_ = NULL; // Forget the stream, for safety.
+}
+
+void StyledStreamWriter::writeValue(const Value& value) {
+ switch (value.type()) {
+ case nullValue:
+ pushValue("null");
+ break;
+ case intValue:
+ pushValue(valueToString(value.asLargestInt()));
+ break;
+ case uintValue:
+ pushValue(valueToString(value.asLargestUInt()));
+ break;
+ case realValue:
+ pushValue(valueToString(value.asDouble()));
+ break;
+ case stringValue:
+ {
+ // Is NULL possible for value.string_?
+ char const* str;
+ char const* end;
+ bool ok = value.getString(&str, &end);
+ if (ok) pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end-str)));
+ else pushValue("");
+ break;
+ }
+ case booleanValue:
+ pushValue(valueToString(value.asBool()));
+ break;
+ case arrayValue:
+ writeArrayValue(value);
+ break;
+ case objectValue: {
+ Value::Members members(value.getMemberNames());
+ if (members.empty())
+ pushValue("{}");
+ else {
+ writeWithIndent("{");
+ indent();
+ Value::Members::iterator it = members.begin();
+ for (;;) {
+ const std::string& name = *it;
+ const Value& childValue = value[name];
+ writeCommentBeforeValue(childValue);
+ writeWithIndent(valueToQuotedString(name.c_str()));
+ *document_ << " : ";
+ writeValue(childValue);
+ if (++it == members.end()) {
+ writeCommentAfterValueOnSameLine(childValue);
+ break;
+ }
+ *document_ << ",";
+ writeCommentAfterValueOnSameLine(childValue);
+ }
+ unindent();
+ writeWithIndent("}");
+ }
+ } break;
+ }
+}
+
+void StyledStreamWriter::writeArrayValue(const Value& value) {
+ unsigned size = value.size();
+ if (size == 0)
+ pushValue("[]");
+ else {
+ bool isArrayMultiLine = isMultineArray(value);
+ if (isArrayMultiLine) {
+ writeWithIndent("[");
+ indent();
+ bool hasChildValue = !childValues_.empty();
+ unsigned index = 0;
+ for (;;) {
+ const Value& childValue = value[index];
+ writeCommentBeforeValue(childValue);
+ if (hasChildValue)
+ writeWithIndent(childValues_[index]);
+ else {
+ if (!indented_) writeIndent();
+ indented_ = true;
+ writeValue(childValue);
+ indented_ = false;
+ }
+ if (++index == size) {
+ writeCommentAfterValueOnSameLine(childValue);
+ break;
+ }
+ *document_ << ",";
+ writeCommentAfterValueOnSameLine(childValue);
+ }
+ unindent();
+ writeWithIndent("]");
+ } else // output on a single line
+ {
+ assert(childValues_.size() == size);
+ *document_ << "[ ";
+ for (unsigned index = 0; index < size; ++index) {
+ if (index > 0)
+ *document_ << ", ";
+ *document_ << childValues_[index];
+ }
+ *document_ << " ]";
+ }
+ }
+}
+
+bool StyledStreamWriter::isMultineArray(const Value& value) {
+ int size = value.size();
+ bool isMultiLine = size * 3 >= rightMargin_;
+ childValues_.clear();
+ for (int index = 0; index < size && !isMultiLine; ++index) {
+ const Value& childValue = value[index];
+ isMultiLine = ((childValue.isArray() || childValue.isObject()) &&
+ childValue.size() > 0);
+ }
+ if (!isMultiLine) // check if line length > max line length
+ {
+ childValues_.reserve(size);
+ addChildValues_ = true;
+ int lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
+ for (int index = 0; index < size; ++index) {
+ if (hasCommentForValue(value[index])) {
+ isMultiLine = true;
+ }
+ writeValue(value[index]);
+ lineLength += int(childValues_[index].length());
+ }
+ addChildValues_ = false;
+ isMultiLine = isMultiLine || lineLength >= rightMargin_;
+ }
+ return isMultiLine;
+}
+
+void StyledStreamWriter::pushValue(const std::string& value) {
+ if (addChildValues_)
+ childValues_.push_back(value);
+ else
+ *document_ << value;
+}
+
+void StyledStreamWriter::writeIndent() {
+ // blep intended this to look at the so-far-written string
+ // to determine whether we are already indented, but
+ // with a stream we cannot do that. So we rely on some saved state.
+ // The caller checks indented_.
+ *document_ << '\n' << indentString_;
+}
+
+void StyledStreamWriter::writeWithIndent(const std::string& value) {
+ if (!indented_) writeIndent();
+ *document_ << value;
+ indented_ = false;
+}
+
+void StyledStreamWriter::indent() { indentString_ += indentation_; }
+
+void StyledStreamWriter::unindent() {
+ assert(indentString_.size() >= indentation_.size());
+ indentString_.resize(indentString_.size() - indentation_.size());
+}
+
+void StyledStreamWriter::writeCommentBeforeValue(const Value& root) {
+ if (!root.hasComment(commentBefore))
+ return;
+
+ if (!indented_) writeIndent();
+ const std::string& comment = root.getComment(commentBefore);
+ std::string::const_iterator iter = comment.begin();
+ while (iter != comment.end()) {
+ *document_ << *iter;
+ if (*iter == '\n' &&
+ (iter != comment.end() && *(iter + 1) == '/'))
+ // writeIndent(); // would include newline
+ *document_ << indentString_;
+ ++iter;
+ }
+ indented_ = false;
+}
+
+void StyledStreamWriter::writeCommentAfterValueOnSameLine(const Value& root) {
+ if (root.hasComment(commentAfterOnSameLine))
+ *document_ << ' ' << root.getComment(commentAfterOnSameLine);
+
+ if (root.hasComment(commentAfter)) {
+ writeIndent();
+ *document_ << root.getComment(commentAfter);
+ }
+ indented_ = false;
+}
+
+bool StyledStreamWriter::hasCommentForValue(const Value& value) {
+ return value.hasComment(commentBefore) ||
+ value.hasComment(commentAfterOnSameLine) ||
+ value.hasComment(commentAfter);
+}
+
+//////////////////////////
+// BuiltStyledStreamWriter
+
+/// Scoped enums are not available until C++11.
+struct CommentStyle {
+ /// Decide whether to write comments.
+ enum Enum {
+ None, ///< Drop all comments.
+ Most, ///< Recover odd behavior of previous versions (not implemented yet).
+ All ///< Keep all comments.
+ };
+};
+
+struct BuiltStyledStreamWriter : public StreamWriter
+{
+ BuiltStyledStreamWriter(
+ std::string const& indentation,
+ CommentStyle::Enum cs,
+ std::string const& colonSymbol,
+ std::string const& nullSymbol,
+ std::string const& endingLineFeedSymbol,
+ bool useSpecialFloats,
+ unsigned int precision);
+ int write(Value const& root, std::ostream* sout);
+private:
+ void writeValue(Value const& value);
+ void writeArrayValue(Value const& value);
+ bool isMultineArray(Value const& value);
+ void pushValue(std::string const& value);
+ void writeIndent();
+ void writeWithIndent(std::string const& value);
+ void indent();
+ void unindent();
+ void writeCommentBeforeValue(Value const& root);
+ void writeCommentAfterValueOnSameLine(Value const& root);
+ static bool hasCommentForValue(const Value& value);
+
+ typedef std::vector<std::string> ChildValues;
+
+ ChildValues childValues_;
+ std::string indentString_;
+ int rightMargin_;
+ std::string indentation_;
+ CommentStyle::Enum cs_;
+ std::string colonSymbol_;
+ std::string nullSymbol_;
+ std::string endingLineFeedSymbol_;
+ bool addChildValues_ : 1;
+ bool indented_ : 1;
+ bool useSpecialFloats_ : 1;
+ unsigned int precision_;
+};
+BuiltStyledStreamWriter::BuiltStyledStreamWriter(
+ std::string const& indentation,
+ CommentStyle::Enum cs,
+ std::string const& colonSymbol,
+ std::string const& nullSymbol,
+ std::string const& endingLineFeedSymbol,
+ bool useSpecialFloats,
+ unsigned int precision)
+ : rightMargin_(74)
+ , indentation_(indentation)
+ , cs_(cs)
+ , colonSymbol_(colonSymbol)
+ , nullSymbol_(nullSymbol)
+ , endingLineFeedSymbol_(endingLineFeedSymbol)
+ , addChildValues_(false)
+ , indented_(false)
+ , useSpecialFloats_(useSpecialFloats)
+ , precision_(precision)
+{
+}
+int BuiltStyledStreamWriter::write(Value const& root, std::ostream* sout)
+{
+ sout_ = sout;
+ addChildValues_ = false;
+ indented_ = true;
+ indentString_ = "";
+ writeCommentBeforeValue(root);
+ if (!indented_) writeIndent();
+ indented_ = true;
+ writeValue(root);
+ writeCommentAfterValueOnSameLine(root);
+ *sout_ << endingLineFeedSymbol_;
+ sout_ = NULL;
+ return 0;
+}
+void BuiltStyledStreamWriter::writeValue(Value const& value) {
+ switch (value.type()) {
+ case nullValue:
+ pushValue(nullSymbol_);
+ break;
+ case intValue:
+ pushValue(valueToString(value.asLargestInt()));
+ break;
+ case uintValue:
+ pushValue(valueToString(value.asLargestUInt()));
+ break;
+ case realValue:
+ pushValue(valueToString(value.asDouble(), useSpecialFloats_, precision_));
+ break;
+ case stringValue:
+ {
+ // Is NULL is possible for value.string_?
+ char const* str;
+ char const* end;
+ bool ok = value.getString(&str, &end);
+ if (ok) pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end-str)));
+ else pushValue("");
+ break;
+ }
+ case booleanValue:
+ pushValue(valueToString(value.asBool()));
+ break;
+ case arrayValue:
+ writeArrayValue(value);
+ break;
+ case objectValue: {
+ Value::Members members(value.getMemberNames());
+ if (members.empty())
+ pushValue("{}");
+ else {
+ writeWithIndent("{");
+ indent();
+ Value::Members::iterator it = members.begin();
+ for (;;) {
+ std::string const& name = *it;
+ Value const& childValue = value[name];
+ writeCommentBeforeValue(childValue);
+ writeWithIndent(valueToQuotedStringN(name.data(), static_cast<unsigned>(name.length())));
+ *sout_ << colonSymbol_;
+ writeValue(childValue);
+ if (++it == members.end()) {
+ writeCommentAfterValueOnSameLine(childValue);
+ break;
+ }
+ *sout_ << ",";
+ writeCommentAfterValueOnSameLine(childValue);
+ }
+ unindent();
+ writeWithIndent("}");
+ }
+ } break;
+ }
+}
+
+void BuiltStyledStreamWriter::writeArrayValue(Value const& value) {
+ unsigned size = value.size();
+ if (size == 0)
+ pushValue("[]");
+ else {
+ bool isMultiLine = (cs_ == CommentStyle::All) || isMultineArray(value);
+ if (isMultiLine) {
+ writeWithIndent("[");
+ indent();
+ bool hasChildValue = !childValues_.empty();
+ unsigned index = 0;
+ for (;;) {
+ Value const& childValue = value[index];
+ writeCommentBeforeValue(childValue);
+ if (hasChildValue)
+ writeWithIndent(childValues_[index]);
+ else {
+ if (!indented_) writeIndent();
+ indented_ = true;
+ writeValue(childValue);
+ indented_ = false;
+ }
+ if (++index == size) {
+ writeCommentAfterValueOnSameLine(childValue);
+ break;
+ }
+ *sout_ << ",";
+ writeCommentAfterValueOnSameLine(childValue);
+ }
+ unindent();
+ writeWithIndent("]");
+ } else // output on a single line
+ {
+ assert(childValues_.size() == size);
+ *sout_ << "[";
+ if (!indentation_.empty()) *sout_ << " ";
+ for (unsigned index = 0; index < size; ++index) {
+ if (index > 0)
+ *sout_ << ", ";
+ *sout_ << childValues_[index];
+ }
+ if (!indentation_.empty()) *sout_ << " ";
+ *sout_ << "]";
+ }
+ }
+}
+
+bool BuiltStyledStreamWriter::isMultineArray(Value const& value) {
+ int size = value.size();
+ bool isMultiLine = size * 3 >= rightMargin_;
+ childValues_.clear();
+ for (int index = 0; index < size && !isMultiLine; ++index) {
+ Value const& childValue = value[index];
+ isMultiLine = ((childValue.isArray() || childValue.isObject()) &&
+ childValue.size() > 0);
+ }
+ if (!isMultiLine) // check if line length > max line length
+ {
+ childValues_.reserve(size);
+ addChildValues_ = true;
+ int lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
+ for (int index = 0; index < size; ++index) {
+ if (hasCommentForValue(value[index])) {
+ isMultiLine = true;
+ }
+ writeValue(value[index]);
+ lineLength += int(childValues_[index].length());
+ }
+ addChildValues_ = false;
+ isMultiLine = isMultiLine || lineLength >= rightMargin_;
+ }
+ return isMultiLine;
+}
+
+void BuiltStyledStreamWriter::pushValue(std::string const& value) {
+ if (addChildValues_)
+ childValues_.push_back(value);
+ else
+ *sout_ << value;
+}
+
+void BuiltStyledStreamWriter::writeIndent() {
+ // blep intended this to look at the so-far-written string
+ // to determine whether we are already indented, but
+ // with a stream we cannot do that. So we rely on some saved state.
+ // The caller checks indented_.
+
+ if (!indentation_.empty()) {
+ // In this case, drop newlines too.
+ *sout_ << '\n' << indentString_;
+ }
+}
+
+void BuiltStyledStreamWriter::writeWithIndent(std::string const& value) {
+ if (!indented_) writeIndent();
+ *sout_ << value;
+ indented_ = false;
+}
+
+void BuiltStyledStreamWriter::indent() { indentString_ += indentation_; }
+
+void BuiltStyledStreamWriter::unindent() {
+ assert(indentString_.size() >= indentation_.size());
+ indentString_.resize(indentString_.size() - indentation_.size());
+}
+
+void BuiltStyledStreamWriter::writeCommentBeforeValue(Value const& root) {
+ if (cs_ == CommentStyle::None) return;
+ if (!root.hasComment(commentBefore))
+ return;
+
+ if (!indented_) writeIndent();
+ const std::string& comment = root.getComment(commentBefore);
+ std::string::const_iterator iter = comment.begin();
+ while (iter != comment.end()) {
+ *sout_ << *iter;
+ if (*iter == '\n' &&
+ (iter != comment.end() && *(iter + 1) == '/'))
+ // writeIndent(); // would write extra newline
+ *sout_ << indentString_;
+ ++iter;
+ }
+ indented_ = false;
+}
+
+void BuiltStyledStreamWriter::writeCommentAfterValueOnSameLine(Value const& root) {
+ if (cs_ == CommentStyle::None) return;
+ if (root.hasComment(commentAfterOnSameLine))
+ *sout_ << " " + root.getComment(commentAfterOnSameLine);
+
+ if (root.hasComment(commentAfter)) {
+ writeIndent();
+ *sout_ << root.getComment(commentAfter);
+ }
+}
+
+// static
+bool BuiltStyledStreamWriter::hasCommentForValue(const Value& value) {
+ return value.hasComment(commentBefore) ||
+ value.hasComment(commentAfterOnSameLine) ||
+ value.hasComment(commentAfter);
+}
+
+///////////////
+// StreamWriter
+
+StreamWriter::StreamWriter()
+ : sout_(NULL)
+{
+}
+StreamWriter::~StreamWriter()
+{
+}
+StreamWriter::Factory::~Factory()
+{}
+StreamWriterBuilder::StreamWriterBuilder()
+{
+ setDefaults(&settings_);
+}
+StreamWriterBuilder::~StreamWriterBuilder()
+{}
+StreamWriter* StreamWriterBuilder::newStreamWriter() const
+{
+ std::string indentation = settings_["indentation"].asString();
+ std::string cs_str = settings_["commentStyle"].asString();
+ bool eyc = settings_["enableYAMLCompatibility"].asBool();
+ bool dnp = settings_["dropNullPlaceholders"].asBool();
+ bool usf = settings_["useSpecialFloats"].asBool();
+ unsigned int pre = settings_["precision"].asUInt();
+ CommentStyle::Enum cs = CommentStyle::All;
+ if (cs_str == "All") {
+ cs = CommentStyle::All;
+ } else if (cs_str == "None") {
+ cs = CommentStyle::None;
+ } else {
+ throwRuntimeError("commentStyle must be 'All' or 'None'");
+ }
+ std::string colonSymbol = " : ";
+ if (eyc) {
+ colonSymbol = ": ";
+ } else if (indentation.empty()) {
+ colonSymbol = ":";
+ }
+ std::string nullSymbol = "null";
+ if (dnp) {
+ nullSymbol = "";
+ }
+ if (pre > 17) pre = 17;
+ std::string endingLineFeedSymbol = "";
+ return new BuiltStyledStreamWriter(
+ indentation, cs,
+ colonSymbol, nullSymbol, endingLineFeedSymbol, usf, pre);
+}
+static void getValidWriterKeys(std::set<std::string>* valid_keys)
+{
+ valid_keys->clear();
+ valid_keys->insert("indentation");
+ valid_keys->insert("commentStyle");
+ valid_keys->insert("enableYAMLCompatibility");
+ valid_keys->insert("dropNullPlaceholders");
+ valid_keys->insert("useSpecialFloats");
+ valid_keys->insert("precision");
+}
+bool StreamWriterBuilder::validate(Json::Value* invalid) const
+{
+ Json::Value my_invalid;
+ if (!invalid) invalid = &my_invalid; // so we do not need to test for NULL
+ Json::Value& inv = *invalid;
+ std::set<std::string> valid_keys;
+ getValidWriterKeys(&valid_keys);
+ Value::Members keys = settings_.getMemberNames();
+ size_t n = keys.size();
+ for (size_t i = 0; i < n; ++i) {
+ std::string const& key = keys[i];
+ if (valid_keys.find(key) == valid_keys.end()) {
+ inv[key] = settings_[key];
+ }
+ }
+ return 0u == inv.size();
+}
+Value& StreamWriterBuilder::operator[](std::string key)
+{
+ return settings_[key];
+}
+// static
+void StreamWriterBuilder::setDefaults(Json::Value* settings)
+{
+ //! [StreamWriterBuilderDefaults]
+ (*settings)["commentStyle"] = "All";
+ (*settings)["indentation"] = "\t";
+ (*settings)["enableYAMLCompatibility"] = false;
+ (*settings)["dropNullPlaceholders"] = false;
+ (*settings)["useSpecialFloats"] = false;
+ (*settings)["precision"] = 17;
+ //! [StreamWriterBuilderDefaults]
+}
+
+std::string writeString(StreamWriter::Factory const& builder, Value const& root) {
+ std::ostringstream sout;
+ StreamWriterPtr const writer(builder.newStreamWriter());
+ writer->write(root, &sout);
+ return sout.str();
+}
+
+std::ostream& operator<<(std::ostream& sout, Value const& root) {
+ StreamWriterBuilder builder;
+ StreamWriterPtr const writer(builder.newStreamWriter());
+ writer->write(root, &sout);
+ return sout;
+}
+
+} // namespace Json
+
+// //////////////////////////////////////////////////////////////////////
+// End of content of file: src/lib_json/json_writer.cpp
+// //////////////////////////////////////////////////////////////////////
+
+
+
+
+
diff --git a/steam-shim/posix_compat.h b/steam-shim/posix_compat.h
new file mode 100644
index 0000000..0547c3e
--- /dev/null
+++ b/steam-shim/posix_compat.h
@@ -0,0 +1,24 @@
+#ifndef STEAM_HELPER_POSIX_COMPAT_H
+#define STEAM_HELPER_POSIX_COMPAT_H
+
+/* setenv is POSIX and absent from the mingw PE C runtime. steam.cpp uses it to
+ publish anti-cheat and VR runtime paths into the environment; map it onto the
+ mingw _putenv_s so the source builds unchanged. */
+
+#include <stdlib.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+static inline int setenv(const char *name, const char *value, int overwrite)
+{
+ if (!overwrite && getenv(name)) return 0;
+ return _putenv_s(name, value ? value : "");
+}
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/steam-shim/steam.cpp b/steam-shim/steam.cpp
new file mode 100644
index 0000000..3e79005
--- /dev/null
+++ b/steam-shim/steam.cpp
@@ -0,0 +1,1926 @@
+/*
+ * Copyright (c) 2015, 2019, 2020, 2021, 2022 Valve Corporation
+ * All rights reserved.
+ *
+ * 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.
+ *
+ * 3. Neither the name of the copyright holder nor the names of its contributors
+ * may be used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * 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 HOLDER 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.
+ */
+
+/* This is a stub steam.exe implementation for use inside Proton. It provides
+ * a small subset of the actual Steam functionality for games that expect
+ * Windows version of Steam running. */
+
+#include "ntstatus.h"
+#define WIN32_NO_STATUS
+#include <windows.h>
+#include <winsvc.h>
+#include <winternl.h>
+#include <shellapi.h>
+#include <shlwapi.h>
+#include <string.h>
+#include <stdio.h>
+#include <limits.h>
+#define _USE_GNU
+#include <dlfcn.h>
+
+#pragma push_macro("_WIN32")
+#pragma push_macro("__cdecl")
+#pragma push_macro("strncpy")
+#undef _WIN32
+#undef __cdecl
+#undef strncpy
+#include "steam_api.h"
+#pragma pop_macro("_WIN32")
+#pragma pop_macro("__cdecl")
+#pragma pop_macro("strncpy")
+
+#include "wine/debug.h"
+
+#pragma push_macro("wcsncpy")
+#undef wcsncpy
+#include "json/json.h"
+#pragma pop_macro("wcsncpy")
+
+#include "wine/unixlib.h"
+#include "wine/heap.h"
+#include "wine/vulkan.h"
+#include "openvr.h"
+#include "../src/ivrclientcore.h"
+
+#include <msi.h>
+
+WINE_DEFAULT_DEBUG_CHANNEL(steam);
+
+/* from shlobj.h, which breaks because of DECLSPEC_IMPORT EXTERN_C in C++ */
+#define CSIDL_LOCAL_APPDATA 0x001c
+#define CSIDL_FLAG_CREATE 0x8000
+
+EXTERN_C WINSHELLAPI HRESULT WINAPI SHGetFolderPathA(HWND hwnd, int nFolder, HANDLE hToken, DWORD dwFlags, LPSTR pszPath);
+EXTERN_C WINSHELLAPI HRESULT WINAPI SHGetFolderPathW(HWND hwnd, int nFolder, HANDLE hToken, DWORD dwFlags, LPWSTR pszPath);
+#define SHGetFolderPath WINELIB_NAME_AW(SHGetFolderPath)
+
+static const WCHAR PROTON_VR_RUNTIME_W[] = {'P','R','O','T','O','N','_','V','R','_','R','U','N','T','I','M','E',0};
+static const WCHAR VR_PATHREG_OVERRIDE_W[] = {'V','R','_','P','A','T','H','R','E','G','_','O','V','E','R','R','I','D','E',0};
+static const WCHAR VR_OVERRIDE_W[] = {'V','R','_','O','V','E','R','R','I','D','E',0};
+static const WCHAR VR_CONFIG_PATH_W[] = {'V','R','_','C','O','N','F','I','G','_','P','A','T','H',0};
+static const WCHAR VR_LOG_PATH_W[] = {'V','R','_','L','O','G','_','P','A','T','H',0};
+
+static bool env_nonzero(const char *env)
+{
+ const char *v = getenv(env);
+ return v != NULL && *v && v[0] != '0';
+}
+
+static void set_active_process_pid(void)
+{
+ DWORD pid = GetCurrentProcessId();
+ RegSetKeyValueA(HKEY_CURRENT_USER, "Software\\Valve\\Steam\\ActiveProcess", "pid", REG_DWORD, &pid, sizeof(pid));
+}
+
+static void set_client_dll_paths(void)
+{
+ static const char steam_dir[] = "C:\\Program Files (x86)\\Steam\\";
+ char path64[MAX_PATH];
+ char path32[MAX_PATH];
+ const char *universe = "Public";
+
+ snprintf(path64, sizeof(path64), "%ssteamclient64.dll", steam_dir);
+ snprintf(path32, sizeof(path32), "%ssteamclient.dll", steam_dir);
+
+ RegSetKeyValueA(HKEY_CURRENT_USER, "Software\\Valve\\Steam\\ActiveProcess",
+ "SteamClientDll64", REG_SZ, path64, (DWORD)strlen(path64) + 1);
+ RegSetKeyValueA(HKEY_CURRENT_USER, "Software\\Valve\\Steam\\ActiveProcess",
+ "SteamClientDll", REG_SZ, path32, (DWORD)strlen(path32) + 1);
+ RegSetKeyValueA(HKEY_CURRENT_USER, "Software\\Valve\\Steam\\ActiveProcess",
+ "Universe", REG_SZ, universe, (DWORD)strlen(universe) + 1);
+ RegSetKeyValueA(HKEY_CURRENT_USER, "Software\\Valve\\Steam",
+ "SteamPath", REG_SZ, steam_dir, (DWORD)sizeof(steam_dir));
+}
+
+static DWORD WINAPI create_steam_window(void *arg)
+{
+ static WNDCLASSEXW wndclass = { sizeof(WNDCLASSEXW) };
+ static const WCHAR class_nameW[] = {'v','g','u','i','P','o','p','u','p','W','i','n','d','o','w',0};
+ static const WCHAR steamW[] = {'S','t','e','a','m',0};
+ MSG msg;
+
+ wndclass.lpfnWndProc = DefWindowProcW;
+ wndclass.lpszClassName = class_nameW;
+
+ RegisterClassExW(&wndclass);
+ CreateWindowW(class_nameW, steamW, WS_POPUP, 40, 40,
+ 400, 300, NULL, NULL, NULL, NULL);
+
+ while (GetMessageW(&msg, NULL, 0, 0))
+ {
+ TranslateMessage(&msg);
+ DispatchMessageW(&msg);
+ }
+
+ return 0;
+}
+
+typedef void *(*create_interface_func)(const char *name, int *err);
+
+static HMODULE steamclient_module;
+static ISteamClient *steam_client;
+static HSteamPipe steam_client_pipe;
+static HSteamUser steam_client_user;
+static ISteamUtils *steam_client_utils;
+static ISteamApps *steam_client_apps;
+
+static bool steam_client_init(void)
+{
+ create_interface_func create_interface;
+
+ steamclient_module = LoadLibraryA("steamclient64.dll");
+ if (!steamclient_module)
+ {
+ WINE_ERR("steam_client_init: no steamclient64.dll, error %u\n", GetLastError());
+ return false;
+ }
+
+ create_interface = (create_interface_func)GetProcAddress(steamclient_module, "CreateInterface");
+ if (!create_interface)
+ {
+ WINE_ERR("steam_client_init: steamclient64.dll exports no CreateInterface\n");
+ return false;
+ }
+
+ steam_client = (ISteamClient *)create_interface(STEAMCLIENT_INTERFACE_VERSION, NULL);
+ if (!steam_client)
+ {
+ WINE_ERR("steam_client_init: no %s from steamclient64.dll\n", STEAMCLIENT_INTERFACE_VERSION);
+ return false;
+ }
+
+ steam_client_pipe = steam_client->CreateSteamPipe();
+ if (!steam_client_pipe)
+ {
+ WINE_ERR("steam_client_init: CreateSteamPipe failed\n");
+ return false;
+ }
+
+ steam_client_user = steam_client->ConnectToGlobalUser(steam_client_pipe);
+ if (!steam_client_user)
+ {
+ WINE_ERR("steam_client_init: ConnectToGlobalUser failed\n");
+ return false;
+ }
+
+ steam_client_utils = steam_client->GetISteamUtils(steam_client_pipe, STEAMUTILS_INTERFACE_VERSION);
+ steam_client_apps = steam_client->GetISteamApps(steam_client_user, steam_client_pipe,
+ STEAMAPPS_INTERFACE_VERSION);
+ if (!steam_client_utils || !steam_client_apps)
+ {
+ WINE_ERR("steam_client_init: %s %p, %s %p\n",
+ STEAMUTILS_INTERFACE_VERSION, steam_client_utils,
+ STEAMAPPS_INTERFACE_VERSION, steam_client_apps);
+ return false;
+ }
+
+ return true;
+}
+
+static void steam_client_shutdown(void)
+{
+ if (steam_client && steam_client_pipe)
+ {
+ if (steam_client_user)
+ steam_client->ReleaseUser(steam_client_pipe, steam_client_user);
+ steam_client->BReleaseSteamPipe(steam_client_pipe);
+ steam_client->BShutdownIfAllPipesClosed();
+ }
+
+ if (steamclient_module)
+ FreeLibrary(steamclient_module);
+
+ steam_client = NULL;
+ steam_client_pipe = 0;
+ steam_client_user = 0;
+ steam_client_utils = NULL;
+ steam_client_apps = NULL;
+ steamclient_module = NULL;
+}
+
+/* requires steam API to be initialized */
+static void setup_steam_registry(void)
+{
+ const char *ui_lang, *language, *languages, *locale = NULL;
+ uint32 appid;
+ char buf[256];
+ HKEY key;
+ LSTATUS status;
+ const int system_locale_appids[] = {
+ 1284210 /* Guild Wars 2 */
+ };
+
+ ui_lang = steam_client_utils->GetSteamUILanguage();
+ WINE_TRACE("UI language: %s\n", wine_dbgstr_a(ui_lang));
+ RegSetKeyValueA(HKEY_CURRENT_USER, "Software\\Valve\\Steam", "language",
+ REG_SZ, ui_lang, strlen(ui_lang) + 1);
+
+ appid = steam_client_utils->GetAppID();
+ WINE_TRACE("appid: %u\n", appid);
+ sprintf(buf, "Software\\Valve\\Steam\\Apps\\%u", appid);
+ status = RegCreateKeyA(HKEY_CURRENT_USER, buf, &key);
+ if (!status)
+ {
+ DWORD value;
+ value = 1;
+ RegSetKeyValueA(key, NULL, "Installed", REG_DWORD, &value, sizeof(value));
+ RegSetKeyValueA(key, NULL, "Running", REG_DWORD, &value, sizeof(value));
+ value = 0;
+ RegSetKeyValueA(key, NULL, "Updating", REG_DWORD, &value, sizeof(value));
+ RegCloseKey(key);
+ }
+ else WINE_ERR("Could not create key: %u\n", status);
+
+ language = steam_client_apps->GetCurrentGameLanguage();
+ languages = steam_client_apps->GetAvailableGameLanguages();
+ WINE_TRACE( "Game language %s, available %s\n", wine_dbgstr_a(language), wine_dbgstr_a(languages) );
+
+ if (strchr(languages, ',') == NULL) /* If there is a list of languages then respect that */
+ {
+ for (int i = 0; i < (sizeof(system_locale_appids) / sizeof(*system_locale_appids)); i++)
+ {
+ if (system_locale_appids[i] == appid)
+ {
+ WINE_TRACE("Not changing system locale for application %i\n",appid);
+ language = NULL;
+ }
+ }
+ }
+
+ if (!language) locale = NULL;
+ else if (!strcmp( language, "arabic" )) locale = "ar_001.UTF-8";
+ else if (!strcmp( language, "bulgarian" )) locale = "bg_BG.UTF-8";
+ else if (!strcmp( language, "schinese" )) locale = "zh_CN.UTF-8";
+ else if (!strcmp( language, "tchinese" )) locale = "zh_TW.UTF-8";
+ else if (!strcmp( language, "czech" )) locale = "cs_CZ.UTF-8";
+ else if (!strcmp( language, "danish" )) locale = "da_DK.UTF-8";
+ else if (!strcmp( language, "dutch" )) locale = "nl_NL.UTF-8";
+ else if (!strcmp( language, "english" )) locale = "en_US.UTF-8";
+ else if (!strcmp( language, "finnish" )) locale = "fi_FI.UTF-8";
+ else if (!strcmp( language, "french" )) locale = "fr_FR.UTF-8";
+ else if (!strcmp( language, "german" )) locale = "de_DE.UTF-8";
+ else if (!strcmp( language, "greek" )) locale = "el_GR.UTF-8";
+ else if (!strcmp( language, "hungarian" )) locale = "hu_HU.UTF-8";
+ else if (!strcmp( language, "italian" )) locale = "it_IT.UTF-8";
+ else if (!strcmp( language, "japanese" )) locale = "ja_JP.UTF-8";
+ else if (!strcmp( language, "koreana" )) locale = "ko_KR.UTF-8";
+ else if (!strcmp( language, "norwegian" )) locale = "nb_NO.UTF-8";
+ else if (!strcmp( language, "polish" )) locale = "pl_PL.UTF-8";
+ else if (!strcmp( language, "portuguese" )) locale = "pt_PT.UTF-8";
+ else if (!strcmp( language, "brazilian" )) locale = "pt_BR.UTF-8";
+ else if (!strcmp( language, "romanian" )) locale = "ro_RO.UTF-8";
+ else if (!strcmp( language, "russian" )) locale = "ru_RU.UTF-8";
+ else if (!strcmp( language, "spanish" )) locale = "es_ES.UTF-8";
+ else if (!strcmp( language, "latam" )) locale = "es_419.UTF-8";
+ else if (!strcmp( language, "swedish" )) locale = "sv_SE.UTF-8";
+ else if (!strcmp( language, "thai" )) locale = "th_TH.UTF-8";
+ else if (!strcmp( language, "turkish" )) locale = "tr_TR.UTF-8";
+ else if (!strcmp( language, "ukrainian" )) locale = "uk_UA.UTF-8";
+ else if (!strcmp( language, "vietnamese" )) locale = "vi_VN.UTF-8";
+ else WINE_FIXME( "Unsupported game language %s\n", wine_dbgstr_a(language) );
+
+ /* HACK: Bug 23597 Granado Espada Japan (1219160) launcher needs Japanese locale to display correctly */
+ if (appid == 1219160)
+ locale = "ja_JP.UTF-8";
+
+ if (locale)
+ {
+ WINE_FIXME( "Game language %s, defaulting LC_CTYPE / LC_MESSAGES to %s.\n", wine_dbgstr_a(language), locale );
+ setenv( "LC_CTYPE", locale, FALSE );
+ setenv( "LC_MESSAGES", locale, FALSE );
+ }
+}
+
+static void copy_to_win(const char *unix_path, const WCHAR *win_path)
+{
+ WCHAR *src_path = wine_get_dos_file_name(unix_path);
+ if (!src_path)
+ return;
+
+ CopyFileW(src_path, win_path, FALSE);
+
+ HeapFree(GetProcessHeap(), 0, src_path);
+}
+
+/* requires steam API to be initialized */
+static void setup_battleye_bridge(void)
+{
+ const unsigned int be_runtime_appid = 1161040;
+ char path[2048];
+ char *path_end;
+
+ if (!steam_client_apps->BIsAppInstalled(be_runtime_appid))
+ return;
+
+ if (!steam_client_apps->GetAppInstallDir(be_runtime_appid, path, sizeof(path)))
+ return;
+
+ WINE_TRACE("Found battleye runtime at %s\n", path);
+
+ setenv("PROTON_BATTLEYE_RUNTIME", path, 1);
+}
+
+static void setup_eac_bridge(void)
+{
+ const unsigned int eac_runtime_appid = 1826330;
+ char path[2048];
+ char *path_end;
+
+ if (!steam_client_apps->BIsAppInstalled(eac_runtime_appid))
+ return;
+
+ if (!steam_client_apps->GetAppInstallDir(eac_runtime_appid, path, sizeof(path)))
+ return;
+
+ WINE_TRACE("Found easyanticheat runtime at %s\n", path);
+
+ setenv("PROTON_EAC_RUNTIME", path, 1);
+}
+
+static std::string get_linux_vr_path(void)
+{
+ const char *e;
+
+ static const char *openvr_path = "/openvr/openvrpaths.vrpath";
+
+ e = getenv("VR_PATHREG_OVERRIDE");
+ if(e && *e)
+ return e;
+
+ e = getenv("XDG_CONFIG_HOME");
+ if(e && *e)
+ return std::string(e) + openvr_path;
+
+ e = getenv("HOME");
+ if(e && *e)
+ return std::string(e) + "/.config" + openvr_path;
+
+ return "";
+}
+
+static bool get_windows_vr_path(WCHAR *out_path, bool create)
+{
+ static const WCHAR openvrpathsW[] = {'\\','o','p','e','n','v','r','p','a','t','h','s','.','v','r','p','a','t','h',0};
+ static const WCHAR openvrW[] = {'\\','o','p','e','n','v','r',0};
+
+ if(FAILED(SHGetFolderPathW(NULL, CSIDL_LOCAL_APPDATA | CSIDL_FLAG_CREATE,
+ NULL, 0, out_path)))
+ return false;
+
+ lstrcatW(out_path, openvrW);
+
+ if(create)
+ CreateDirectoryW(out_path, NULL);
+
+ lstrcatW(out_path, openvrpathsW);
+
+ return true;
+}
+
+static WCHAR *str_to_wchar(const std::string &str)
+{
+ DWORD sz = MultiByteToWideChar(CP_UNIXCP, 0, str.c_str(), -1, NULL, 0);
+ if(!sz)
+ return NULL;
+
+ WCHAR *ret = (WCHAR *)HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * sz);
+ if(!ret)
+ return NULL;
+
+ sz = MultiByteToWideChar(CP_UNIXCP, 0, str.c_str(), -1, ret, sz);
+ if(!sz)
+ {
+ HeapFree(GetProcessHeap(), 0, ret);
+ return NULL;
+ }
+
+ return ret;
+}
+
+static std::string read_text_file(const WCHAR *filename)
+{
+ HANDLE ifile = CreateFileW(filename, GENERIC_READ,
+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
+ OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
+ if(ifile == INVALID_HANDLE_VALUE)
+ return "";
+
+ LARGE_INTEGER size;
+
+ if(!GetFileSizeEx(ifile, &size))
+ {
+ CloseHandle(ifile);
+ return "";
+ }
+
+ char *buf = (char *)HeapAlloc(GetProcessHeap(), 0, size.u.LowPart);
+ if(!buf)
+ {
+ CloseHandle(ifile);
+ return "";
+ }
+
+ DWORD readed;
+
+ if(!ReadFile(ifile, buf, size.u.LowPart, &readed, NULL))
+ {
+ HeapFree(GetProcessHeap(), 0, buf);
+ CloseHandle(ifile);
+ return "";
+ }
+
+ CloseHandle(ifile);
+
+ DWORD outsize = 1;
+ for(DWORD i = 1; i < readed; ++i)
+ {
+ if(buf[i] == '\n' && buf[i - 1] == '\r') // CRLF
+ buf[outsize - 1] = '\n';
+ else
+ buf[outsize++] = buf[i];
+ }
+
+ std::string ret(buf, outsize);
+
+ HeapFree(GetProcessHeap(), 0, buf);
+
+ return ret;
+}
+
+static bool write_string_to_file(const WCHAR *filename, const std::string &contents)
+{
+ HANDLE ofile = CreateFileW(filename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
+ FILE_ATTRIBUTE_NORMAL, NULL);
+ if(ofile == INVALID_HANDLE_VALUE)
+ return false;
+
+ DWORD written;
+
+ if(!WriteFile(ofile, contents.data(), (DWORD)contents.length(), &written, NULL))
+ {
+ CloseHandle(ofile);
+ return false;
+ }
+
+ CloseHandle(ofile);
+
+ return true;
+}
+
+static bool convert_path_to_win(std::string &s)
+{
+ WCHAR *path = wine_get_dos_file_name(s.c_str());
+ if(!path)
+ return false;
+
+ DWORD sz = WideCharToMultiByte(CP_UTF8, 0, path, -1, NULL, 0, NULL, NULL);
+ if(!sz)
+ {
+ HeapFree(GetProcessHeap(), 0, path);
+ return false;
+ }
+
+ char *pathUTF8 = (char *)HeapAlloc(GetProcessHeap(), 0, sz);
+ if(!pathUTF8)
+ {
+ HeapFree(GetProcessHeap(), 0, path);
+ return false;
+ }
+
+ sz = WideCharToMultiByte(CP_UTF8, 0, path, -1, pathUTF8, sz, NULL, NULL);
+ if(!sz)
+ {
+ HeapFree(GetProcessHeap(), 0, pathUTF8);
+ HeapFree(GetProcessHeap(), 0, path);
+ return false;
+ }
+
+ s = pathUTF8;
+
+ HeapFree(GetProcessHeap(), 0, pathUTF8);
+ HeapFree(GetProcessHeap(), 0, path);
+
+ return true;
+}
+
+static void convert_json_array_paths(Json::Value &arr)
+{
+ for(uint32_t i = 0; i < arr.size(); ++i)
+ {
+ std::string path(arr[i].asString());
+ if(convert_path_to_win(path))
+ arr[i] = path;
+ }
+}
+
+static void convert_environment_path(const char *nameA, const WCHAR *nameW)
+{
+ /* get linux-side variable */
+ const char *e = getenv(nameA);
+ if(!e || !*e)
+ return;
+
+ /* convert to win and set */
+ WCHAR *path = wine_get_dos_file_name(e);
+ if(!path)
+ return;
+
+ SetEnvironmentVariableW(nameW, path);
+
+ HeapFree(GetProcessHeap(), 0, path);
+}
+
+static void set_env_from_unix(const WCHAR *name, const std::string &val)
+{
+ WCHAR valW[MAX_PATH];
+ DWORD sz;
+
+ sz = MultiByteToWideChar(CP_UTF8, 0, val.c_str(), -1, valW, MAX_PATH);
+ if(!sz)
+ {
+ WINE_WARN("Invalid utf8 seq in vr runtime key\n");
+ return;
+ }
+
+ SetEnvironmentVariableW(name, valW);
+}
+
+static bool convert_linux_vrpaths(void)
+{
+ /* read in linux vrpaths */
+ std::string linux_vrpaths = get_linux_vr_path();
+ if(linux_vrpaths.empty())
+ {
+ WINE_TRACE("Couldn't get openvr vrpaths path\n");
+ return false;
+ }
+
+ WCHAR *linux_vrpathsW = str_to_wchar(linux_vrpaths);
+ if(!linux_vrpathsW)
+ return false;
+
+ std::string contents = read_text_file(linux_vrpathsW);
+ HeapFree(GetProcessHeap(), 0, linux_vrpathsW);
+ if(contents.empty())
+ {
+ WINE_TRACE("openvr vrpaths is empty\n");
+ return false;
+ }
+
+ Json::Value root;
+ Json::Reader reader;
+
+ if(!reader.parse(contents, root))
+ {
+ WINE_WARN("Invalid openvr vrpaths JSON\n");
+ return false;
+ }
+
+ /* pass original runtime path into Wine */
+ const char *vr_override = getenv("VR_OVERRIDE");
+ if(vr_override)
+ {
+ set_env_from_unix(PROTON_VR_RUNTIME_W, vr_override);
+ }
+ else if(root.isMember("runtime") && root["runtime"].isArray() && root["runtime"].size() > 0)
+ {
+ set_env_from_unix(PROTON_VR_RUNTIME_W, root["runtime"][0].asString());
+ }
+
+ /* set hard-coded paths */
+ root["runtime"] = Json::Value(Json::ValueType::arrayValue);
+ root["runtime"][0] = "C:\\vrclient\\";
+ root["runtime"][1] = "C:\\vrclient";
+
+ /* map linux paths into windows filesystem */
+ if(root.isMember("config") && root["config"].isArray())
+ convert_json_array_paths(root["config"]);
+
+ if(root.isMember("log") && root["log"].isArray())
+ convert_json_array_paths(root["log"]);
+
+ /* external_drivers is currently unsupported in Proton */
+ root["external_drivers"] = Json::Value(Json::ValueType::nullValue);
+
+ /* write out windows vrpaths */
+ SetEnvironmentVariableW(VR_PATHREG_OVERRIDE_W, NULL);
+ SetEnvironmentVariableW(VR_OVERRIDE_W, NULL);
+ convert_environment_path("VR_CONFIG_PATH", VR_CONFIG_PATH_W);
+ convert_environment_path("VR_LOG_PATH", VR_LOG_PATH_W);
+ Json::StyledWriter writer;
+
+ WCHAR windows_vrpaths[MAX_PATH];
+ if(!get_windows_vr_path(windows_vrpaths, true))
+ return false;
+
+ contents = writer.write(root);
+
+ write_string_to_file(windows_vrpaths, contents);
+
+ return true;
+}
+
+static void setup_vrpaths(void)
+{
+ bool success = false;
+
+ try{
+ success = convert_linux_vrpaths();
+ }catch(std::exception e){
+ WINE_ERR("got error parsing vrpaths file\n");
+ success = false;
+ }
+
+ if(!success)
+ {
+ /* delete the windows file only if the linux conversion fails */
+ WCHAR windows_vrpaths[MAX_PATH];
+ if(get_windows_vr_path(windows_vrpaths, false))
+ {
+ DeleteFileW(windows_vrpaths);
+ }
+ }
+}
+
+static BOOL set_vr_status(HKEY key, DWORD value)
+{
+ LSTATUS status;
+
+ if ((status = RegSetValueExA(key, "state", 0, REG_DWORD, (BYTE *)&value, sizeof(value))))
+ {
+ WINE_ERR("Could not set state value, status %#x.\n", status);
+ return FALSE;
+ }
+ return TRUE;
+}
+
+void* load_vrclient(void)
+{
+ WCHAR pathW[PATH_MAX];
+ char *pathU;
+ DWORD sz;
+
+#ifdef _WIN64
+ static const char append_path[] = "/bin/linux64/vrclient.so";
+#else
+ static const char append_path[] = "/bin/vrclient.so";
+#endif
+
+ /* PROTON_VR_RUNTIME is provided by the proton setup script */
+ if(!GetEnvironmentVariableW(PROTON_VR_RUNTIME_W, pathW, ARRAY_SIZE(pathW)))
+ {
+ WINE_TRACE("Linux OpenVR runtime is not available\n");
+ return 0;
+ }
+
+ sz = WideCharToMultiByte(CP_UNIXCP, 0, pathW, -1, NULL, 0, NULL, NULL);
+ if(!sz)
+ {
+ WINE_ERR("Can't convert path to unixcp! %s\n", wine_dbgstr_w(pathW));
+ return NULL;
+ }
+
+ pathU = (char *)HeapAlloc(GetProcessHeap(), 0, sz + sizeof(append_path));
+
+ sz = WideCharToMultiByte(CP_UNIXCP, 0, pathW, -1, pathU, sz, NULL, NULL);
+ if(!sz)
+ {
+ WINE_ERR("Can't convert path to unixcp! %s\n", wine_dbgstr_w(pathW));
+ return NULL;
+ }
+
+ strcat(pathU, append_path);
+
+ WINE_TRACE("got openvr runtime path: %s\n", pathU);
+
+ return dlopen(pathU, RTLD_NOW);
+}
+
+static char *strdupA(const char *s)
+{
+ size_t l = strlen(s) + 1;
+ char *r = (char *)heap_alloc(l);
+ memcpy(r, s, l);
+ return r;
+}
+
+static void parse_extensions(const char *in, uint32_t *out_count,
+ char ***out_strs)
+{
+ char *iter, *start;
+ char **list, *str = strdupA(in);
+ uint32_t extension_count = 0, o = 0;
+
+ iter = str;
+ while(*iter){
+ if(*iter++ == ' ')
+ extension_count++;
+ }
+ /* count the one ending in NUL */
+ if(iter != str)
+ extension_count++;
+ if(!extension_count){
+ *out_count = 0;
+ *out_strs = NULL;
+ return;
+ }
+
+ list = (char **)heap_alloc(extension_count * sizeof(*list));
+
+ start = iter = str;
+ do{
+ if(*iter == ' '){
+ *iter = 0;
+ list[o++] = start;
+ WINE_TRACE("added %s to list\n", list[o-1]);
+ iter++;
+ start = iter;
+ }else if(*iter == 0){
+ list[o++] = start;
+ WINE_TRACE("added %s to list\n", list[o-1]);
+ break;
+ }else{
+ iter++;
+ }
+ }while(1);
+
+ *out_count = extension_count;
+ *out_strs = list;
+}
+
+extern "C"
+{
+ VkPhysicalDevice __wine_get_native_VkPhysicalDevice(VkPhysicalDevice phys_dev);
+};
+
+static void *get_winevulkan_unix_lib_handle(HMODULE hvulkan)
+{
+ unixlib_handle_t unix_funcs;
+ NTSTATUS status;
+ Dl_info info;
+
+ status = NtQueryVirtualMemory(GetCurrentProcess(), hvulkan, (MEMORY_INFORMATION_CLASS)1000 /*MemoryWineUnixFuncs*/,
+ &unix_funcs, sizeof(unix_funcs), NULL);
+ if (status)
+ {
+ WINE_ERR("NtQueryVirtualMemory status %#x.\n", (int)status);
+ return NULL;
+ }
+ if (!dladdr((void *)(ULONG_PTR)unix_funcs, &info))
+ {
+ WINE_ERR("dladdr failed.\n");
+ return NULL;
+ }
+ WINE_TRACE("path %s.\n", info.dli_fname);
+ return dlopen(info.dli_fname, RTLD_NOW);
+}
+
+static DWORD WINAPI initialize_vr_data(void *arg)
+{
+ int (WINAPI *p__wineopenxr_get_extensions_internal)(char **instance_extensions, char **device_extensions, uint32_t *physdev_vid, uint32_t *physdev_pid);
+ vr::IVRClientCore* (*vrclient_VRClientCoreFactory)(const char *name, int *return_code);
+ uint32_t instance_extensions_count, device_count;
+ VkPhysicalDevice *phys_devices = NULL;
+ VkPhysicalDeviceProperties prop = {};
+ VkInstanceCreateInfo inst_info = {};
+ char **instance_extensions = NULL;
+ VkApplicationInfo app_info = {};
+ char *buffer = NULL, *new_buffer;
+ vr::IVRClientCore* client_core;
+ char *xr_inst_ext, *xr_dev_ext;
+ vr::IVRCompositor* compositor;
+ VkInstance vk_instance = NULL;
+ BOOL vr_initialized = FALSE;
+ HKEY vr_key = (HKEY)arg;
+ vr::EVRInitError error;
+ HMODULE hvulkan = NULL;
+ DWORD vr_status = ~0u;
+ const char *env_str;
+ unsigned int app_id;
+ unsigned int length;
+ HMODULE hwineopenxr;
+ void *lib_vrclient;
+ void *unix_handle;
+ DWORD hmd_present;
+ int return_code;
+ LSTATUS status;
+ unsigned int i;
+ VkResult res;
+
+ WINE_TRACE("Starting VR info initialization.\n");
+
+ if (!(lib_vrclient = load_vrclient()))
+ {
+ WINE_ERR("Could not load libopenvr_api.so.\n");
+ set_vr_status(vr_key, ~0u);
+ RegCloseKey(vr_key);
+ return 0;
+ }
+
+ if (!(vrclient_VRClientCoreFactory = reinterpret_cast<decltype(vrclient_VRClientCoreFactory)>
+ (dlsym(lib_vrclient, "VRClientCoreFactory"))))
+ {
+ WINE_ERR("Could not find function VRClientCoreFactory.\n");
+ goto done;
+ }
+ if (!(client_core = vrclient_VRClientCoreFactory(vr::IVRClientCore_Version, &return_code)))
+ {
+ WINE_ERR("Could not get IVRClientCore, error %d.\n", return_code);
+ }
+
+ /* Without overriding the app_key vrclient waits 2 seconds for a valid appkey before returning. */
+ error = client_core->Init(vr::VRApplication_Background, NULL);
+ if (error != vr::VRInitError_None)
+ {
+ if (error == vr::VRInitError_Init_NoServerForBackgroundApp)
+ WINE_TRACE("VR server is not available.\n");
+ else
+ WINE_ERR("VR init failed, error %u.\n", error);
+ goto done;
+ }
+ vr_initialized = TRUE;
+
+ hmd_present = !!client_core->BIsHmdPresent();
+ WINE_TRACE("hmd_present %#x.\n", hmd_present);
+ if ((status = RegSetValueExA(vr_key, "is_hmd_present", 0, REG_DWORD, (BYTE *)&hmd_present, sizeof(hmd_present))))
+ WINE_ERR("Could not set is_hmd_present value, status %#x.\n", status);
+
+ compositor = reinterpret_cast<vr::IVRCompositor*>(client_core->GetGenericInterface(vr::IVRCompositor_Version, &error));
+ if (!compositor)
+ {
+ WINE_ERR("Could not get compositor, error %u.\n", error);
+ goto done;
+ }
+
+ length = compositor->GetVulkanInstanceExtensionsRequired(nullptr, 0);
+ if (!(buffer = (char *)heap_alloc(length)))
+ {
+ WINE_ERR("No memory.\n");
+ goto done;
+ }
+ *buffer = 0;
+ compositor->GetVulkanInstanceExtensionsRequired(buffer, length);
+ WINE_TRACE("Instance extensions %s.\n", buffer);
+
+ if ((status = RegSetValueExA(vr_key, "openvr_vulkan_instance_extensions", 0, REG_SZ, (BYTE *)buffer, length)))
+ {
+ WINE_ERR("Could not set openvr_vulkan_instance_extensions value, status %#x.\n", status);
+ return FALSE;
+ }
+
+ if (!(hvulkan = LoadLibraryA("winevulkan.dll")))
+ {
+ WINE_ERR("Could not load winevulkan.\n");
+ goto done;
+ }
+
+#define USE_VULKAN_PROC(name) decltype(name) *p##name;\
+ if (!(p##name = reinterpret_cast<decltype(name) *>(GetProcAddress(hvulkan, "wine_"#name)))\
+ && !(p##name = reinterpret_cast<decltype(name) *>(GetProcAddress(hvulkan, #name))))\
+ {\
+ WINE_ERR("Could not find function %s.\n", #name);\
+ goto done;\
+ }
+ USE_VULKAN_PROC(vkCreateInstance)
+ USE_VULKAN_PROC(vkDestroyInstance)
+ USE_VULKAN_PROC(vkEnumeratePhysicalDevices)
+ USE_VULKAN_PROC(vkGetPhysicalDeviceProperties)
+#undef USE_VULKAN_PROC
+
+ if (!(unix_handle = get_winevulkan_unix_lib_handle(hvulkan)))
+ {
+ WINE_ERR("winevulkan.so not found.\n");
+ goto done;
+ }
+ decltype(__wine_get_native_VkPhysicalDevice) *p__wine_get_native_VkPhysicalDevice;
+ p__wine_get_native_VkPhysicalDevice = reinterpret_cast<decltype(__wine_get_native_VkPhysicalDevice) *>
+ (dlsym(unix_handle, "__wine_get_native_VkPhysicalDevice"));
+
+ dlclose(unix_handle);
+ if (!p__wine_get_native_VkPhysicalDevice)
+ {
+ WINE_ERR("__wine_get_native_VkPhysicalDevice not found.\n");
+ goto done;
+ }
+
+ parse_extensions(buffer, &instance_extensions_count, &instance_extensions);
+
+ app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
+ app_info.pApplicationName = "proton_vrhelper";
+ app_info.applicationVersion = 1;
+ app_info.pEngineName = "proton_vrhelper";
+ app_info.engineVersion = 1;
+ app_info.apiVersion = VK_MAKE_VERSION(1, 1, 0);
+
+ inst_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
+ inst_info.pApplicationInfo = &app_info;
+ inst_info.enabledExtensionCount = instance_extensions_count;
+ inst_info.ppEnabledExtensionNames = instance_extensions;
+
+ if ((res = pvkCreateInstance(&inst_info, NULL, &vk_instance)) != VK_SUCCESS)
+ {
+ WINE_ERR("Could not create VK instance, res %d.\n", res);
+ goto done;
+ }
+
+ if ((res = pvkEnumeratePhysicalDevices(vk_instance, &device_count, NULL)) != VK_SUCCESS)
+ {
+ WINE_ERR("Could not enumerate physical devices, res %d.\n", res);
+ goto done;
+ }
+ if (!(phys_devices = (VkPhysicalDevice *)heap_alloc(device_count * sizeof(*phys_devices))))
+ {
+ WINE_ERR("No memory.\n");
+ goto done;
+ }
+ if ((res = pvkEnumeratePhysicalDevices(vk_instance, &device_count, phys_devices)) != VK_SUCCESS)
+ {
+ WINE_ERR("Could not enumerate physical devices, res %d.\n", res);
+ goto done;
+ }
+
+ for (i = 0; i < device_count; ++i)
+ {
+ char name[256];
+ LUID luid;
+
+ pvkGetPhysicalDeviceProperties(phys_devices[i], &prop);
+ if (prop.apiVersion < VK_MAKE_VERSION(1, 1, 0))
+ {
+ WINE_TRACE("Skipping Vulkan 1.0 adapter %s.\n", prop.deviceName);
+ continue;
+ }
+
+ length = compositor->GetVulkanDeviceExtensionsRequired(p__wine_get_native_VkPhysicalDevice(phys_devices[i]), nullptr, 0);
+ if (!(new_buffer = (char *)heap_realloc(buffer, length)))
+ {
+ WINE_ERR("No memory.\n");
+ goto done;
+ }
+ buffer = new_buffer;
+ compositor->GetVulkanDeviceExtensionsRequired(p__wine_get_native_VkPhysicalDevice(phys_devices[i]), buffer, length);
+ sprintf(name, "PCIID:%04x:%04x", prop.vendorID, prop.deviceID);
+ WINE_TRACE("%s: %s.\n", name, buffer);
+
+ if ((status = RegSetValueExA(vr_key, name, 0, REG_SZ, (BYTE *)buffer, length)))
+ {
+ WINE_ERR("Could not set %s value, status %#x.\n", name, status);
+ goto done;
+ }
+ }
+
+ if (vr_initialized) {
+ client_core->Cleanup();
+ vr_initialized = FALSE;
+ }
+
+ if ((hwineopenxr = LoadLibraryA("wineopenxr.dll")))
+ {
+ p__wineopenxr_get_extensions_internal = reinterpret_cast<decltype(p__wineopenxr_get_extensions_internal)>
+ (GetProcAddress(hwineopenxr, "__wineopenxr_get_extensions_internal"));
+ if (p__wineopenxr_get_extensions_internal)
+ {
+ uint32_t vid, pid;
+ if (!p__wineopenxr_get_extensions_internal(&xr_inst_ext, &xr_dev_ext, &vid, &pid))
+ {
+ WINE_TRACE("Got XR extensions.\n");
+ if ((status = RegSetValueExA(vr_key, "openxr_vulkan_instance_extensions", 0, REG_SZ,
+ (BYTE *)xr_inst_ext, strlen(xr_inst_ext) + 1)))
+ {
+ WINE_ERR("Could not set openxr_vulkan_instance_extensions value, status %#x.\n", status);
+ goto done;
+ }
+ if ((status = RegSetValueExA(vr_key, "openxr_vulkan_device_extensions", 0, REG_SZ,
+ (BYTE *)xr_dev_ext, strlen(xr_dev_ext) + 1)))
+ {
+ WINE_ERR("Could not set openxr_vulkan_device_extensions value, status %#x.\n", status);
+ goto done;
+ }
+ if ((status = RegSetValueExA(vr_key, "openxr_vulkan_device_vid", 0, REG_DWORD,
+ (BYTE *)&vid, sizeof(vid))))
+ {
+ WINE_ERR("Could not set openxr_vulkan_device_vid value, status %#x.\n", status);
+ goto done;
+ }
+ if ((status = RegSetValueExA(vr_key, "openxr_vulkan_device_pid", 0, REG_DWORD,
+ (BYTE *)&pid, sizeof(pid))))
+ {
+ WINE_ERR("Could not set openxr_vulkan_device_pid value, status %#x.\n", status);
+ goto done;
+ }
+ }
+ }
+ else
+ {
+ WINE_ERR("__wineopenxr_get_extensions_internal not found in wineopenxr.dll.\n");
+ }
+ FreeLibrary(hwineopenxr);
+ }
+ else
+ {
+ WINE_WARN("Could not load wineopenxr.dll, err %u.\n", GetLastError());
+ }
+
+ vr_status = 1;
+
+done:
+ set_vr_status(vr_key, vr_status);
+
+ heap_free(phys_devices);
+
+ if (vk_instance)
+ pvkDestroyInstance(vk_instance, NULL);
+
+ if (instance_extensions)
+ {
+ heap_free(instance_extensions[0]);
+ heap_free(instance_extensions);
+ }
+ if (hvulkan)
+ FreeLibrary(hvulkan);
+ heap_free(buffer);
+ if (vr_initialized)
+ client_core->Cleanup();
+ WINE_TRACE("Completed VR info initialization.\n");
+ dlclose(lib_vrclient);
+ RegCloseKey(vr_key);
+ return 0;
+}
+
+static void setup_vr_registry(void)
+{
+ WCHAR pathW[PATH_MAX];
+ LSTATUS status;
+ HANDLE thread;
+ HKEY vr_key;
+ DWORD disp;
+
+ if ((status = RegCreateKeyExA(HKEY_CURRENT_USER, "Software\\Wine\\VR", 0, NULL, REG_OPTION_VOLATILE,
+ KEY_ALL_ACCESS, NULL, &vr_key, &disp)))
+ {
+ WINE_ERR("Could not create key, status %#x.\n", status);
+ return;
+ }
+ if (disp != REG_CREATED_NEW_KEY)
+ {
+ WINE_ERR("VR key already exists, disp %#x.\n", disp);
+ RegCloseKey(vr_key);
+ return;
+ }
+
+ if(GetEnvironmentVariableW(PROTON_VR_RUNTIME_W, pathW, ARRAY_SIZE(pathW)))
+ {
+ if ((status = RegSetValueExW(vr_key, PROTON_VR_RUNTIME_W, 0, REG_SZ,
+ (BYTE *)pathW, (lstrlenW(pathW) + 1) * sizeof(WCHAR))))
+ {
+ WINE_ERR("Could not set PROTON_VR_RUNTIME value, status %#x.\n", status);
+ set_vr_status(vr_key, ~0u);
+ RegCloseKey(vr_key);
+ return;
+ }
+ }
+ else
+ {
+ WINE_TRACE("Linux OpenVR runtime is not available\n");
+ set_vr_status(vr_key, ~0u);
+ RegCloseKey(vr_key);
+ return;
+ }
+
+ if (!set_vr_status(vr_key, 0))
+ {
+ RegCloseKey(vr_key);
+ return;
+ }
+
+ if (!(thread = CreateThread(NULL, 0, initialize_vr_data, (void *)vr_key, 0, NULL)))
+ {
+ WINE_ERR("Could not create thread, error %u.\n", GetLastError());
+ RegCloseKey(vr_key);
+ return;
+ }
+ CloseHandle(thread);
+
+ WINE_TRACE("Queued VR info initialization.\n");
+}
+
+static WCHAR *strchrW(WCHAR *h, WCHAR n)
+{
+ do
+ {
+ if(*h == n)
+ return h;
+ } while (*h++);
+
+ return NULL;
+}
+
+int strncmpW(const WCHAR *l, const WCHAR *r, int n)
+{
+ if(n <= 0)
+ return 0;
+
+ while(--n > 0 && *l && *l == *r){
+ l++;
+ r++;
+ }
+
+ return *l - *r;
+}
+
+static WCHAR *find_quote(WCHAR *str)
+{
+ WCHAR *end = strchrW(str, '"'), *ch;
+ int odd;
+ while (end)
+ {
+ odd = 0;
+ ch = end - 1;
+ while (ch >= str && *ch == '\\')
+ {
+ odd = !odd;
+ --ch;
+ }
+ if (!odd)
+ return end;
+ end = strchrW(end + 1, '"');
+ }
+ return NULL;
+}
+
+static BOOL WINAPI console_ctrl_handler(DWORD dwCtrlType)
+{
+ return TRUE;
+}
+
+static BOOL streq_niw(const WCHAR *l, const WCHAR *r, size_t len)
+{
+ while(len > 0){
+ if(towlower(*l) != towlower(*r))
+ return FALSE;
+ ++l; ++r; --len;
+ }
+ return TRUE;
+}
+
+static WCHAR* get_end_of_excutable_name(WCHAR *cmdline)
+{
+ BOOL quoted = FALSE;
+ WCHAR *executable_name_end = cmdline;
+
+ /* find the end of the first arg...*/
+ while (*executable_name_end != '\0' &&
+ (*executable_name_end != ' ' || quoted))
+ {
+ quoted ^= *executable_name_end == '"';
+
+ executable_name_end++;
+ }
+
+ return executable_name_end;
+}
+
+static BOOL should_use_shell_execute(WCHAR *cmdline)
+{
+ BOOL use_shell_execute = TRUE;
+ const WCHAR *executable_name_end = (const WCHAR*)get_end_of_excutable_name(cmdline);
+
+ /* if the executable is quoted backtrack a bit */
+ if (*(executable_name_end - 1) == '"')
+ --executable_name_end;
+
+
+ /* backtrack to before the end of the arg
+ * and check if we end in .exe or not
+ * and determine whether to use ShellExecute
+ * based on that */
+ executable_name_end -= strlen(".exe");
+
+ if (executable_name_end >= cmdline)
+ {
+ static const WCHAR exeW[] = {'.','e','x','e',0};
+
+ if (streq_niw(executable_name_end, exeW, sizeof(exeW) / sizeof(*exeW) - 1))
+ use_shell_execute = FALSE;
+ }
+
+ return use_shell_execute;
+}
+
+static HANDLE run_process(BOOL *should_await, BOOL game_process)
+{
+ static const WCHAR link2eaW[] = {'l','i','n','k','2','e','a',':','/','/',0};
+ static const WCHAR link2ea_pathW[] =
+ {
+ 'S','o','f','t','w','a','r','e','\\','C','l','a','s','s','e','s','\\','l','i','n','k','2','e','a',0
+ };
+ static const WCHAR ea_desktop_pathW[] =
+ {
+ 'S','o','f','t','w','a','r','e','\\','E','l','e','c','t','r','o','n','i','c',' ','A','r','t','s',
+ '\\','E','A',' ','D','e','s','k','t','o','p',0
+ };
+ static const WCHAR ea_core_pathW[] =
+ {
+ 'S','o','f','t','w','a','r','e','\\','E','l','e','c','t','r','o','n','i','c',' ','A','r','t','s',
+ '\\','E','A',' ','C','o','r','e',0
+ };
+ static const WCHAR IsUnavailableW[] = {'I','s','U','n','a','v','a','i','l','a','b','l','e',0};
+ WCHAR *cmdline = GetCommandLineW();
+ STARTUPINFOW si = { sizeof(si) };
+ PROCESS_INFORMATION pi;
+ DWORD flags = CREATE_UNICODE_ENVIRONMENT;
+ BOOL use_shell_execute = TRUE, link2ea = FALSE;
+ BOOL hide_window;
+
+ /* skip argv[0] */
+ if (*cmdline == '"')
+ {
+ cmdline = find_quote(cmdline + 1);
+ if (cmdline) cmdline++;
+ }
+ else
+ {
+ cmdline = strchrW(cmdline, ' ');
+ }
+ if (!cmdline)
+ {
+ WINE_ERR("Invalid command\n");
+ return INVALID_HANDLE_VALUE;
+ }
+ while (*cmdline == ' ') cmdline++;
+
+ /* convert absolute unix path to dos */
+ if (cmdline[0] == '/' ||
+ (cmdline[0] == '"' && cmdline[1] == '/'))
+ {
+ WCHAR *scratchW;
+ char *scratchA;
+ WCHAR *start, *end, *dos, *remainder, *new_cmdline;
+ size_t argv0_len;
+ int r;
+ DWORD_PTR console;
+ SHFILEINFOW sfi;
+
+ static const WCHAR dquoteW[] = {'"',0};
+
+ WINE_TRACE("Converting unix command: %s\n", wine_dbgstr_w(cmdline));
+
+ if (cmdline[0] == '"')
+ {
+ start = cmdline + 1;
+ end = find_quote(start);
+ if (!end)
+ {
+ WINE_ERR("Unmatched quote? %s\n", wine_dbgstr_w(cmdline));
+ goto run;
+ }
+ remainder = end + 1;
+ }
+ else
+ {
+ start = cmdline;
+ end = strchrW(start, ' ');
+ if (!end)
+ end = strchrW(start, '\0');
+ remainder = end;
+ }
+
+ argv0_len = end - start;
+
+ scratchW = (WCHAR *)HeapAlloc(GetProcessHeap(), 0, (argv0_len + 1) * sizeof(WCHAR));
+ memcpy(scratchW, start, argv0_len * sizeof(WCHAR));
+ scratchW[argv0_len] = '\0';
+
+ r = WideCharToMultiByte(CP_UNIXCP, 0, scratchW, -1,
+ NULL, 0, NULL, NULL);
+ if (!r)
+ {
+ WINE_ERR("Char conversion size failed?\n");
+ goto run;
+ }
+
+ scratchA = (char *)HeapAlloc(GetProcessHeap(), 0, r);
+
+ r = WideCharToMultiByte(CP_UNIXCP, 0, scratchW, -1,
+ scratchA, r, NULL, NULL);
+ if (!r)
+ {
+ WINE_ERR("Char conversion failed?\n");
+ goto run;
+ }
+
+ dos = wine_get_dos_file_name(scratchA);
+
+ CoInitialize(NULL);
+
+ console = SHGetFileInfoW(dos, 0, &sfi, sizeof(sfi), SHGFI_EXETYPE);
+ if (console)
+ {
+ if (!HIWORD(console))
+ flags |= CREATE_NEW_CONSOLE;
+ }
+
+ new_cmdline = (WCHAR *)HeapAlloc(GetProcessHeap(), 0,
+ (lstrlenW(dos) + 3 + lstrlenW(remainder) + 1) * sizeof(WCHAR));
+ lstrcpyW(new_cmdline, dquoteW);
+ lstrcatW(new_cmdline, dos);
+ lstrcatW(new_cmdline, dquoteW);
+ lstrcatW(new_cmdline, remainder);
+
+ cmdline = new_cmdline;
+ }
+
+run:
+ WINE_TRACE("Running command %s\n", wine_dbgstr_w(cmdline));
+
+ SetConsoleCtrlHandler( console_ctrl_handler, TRUE );
+
+ use_shell_execute = should_use_shell_execute(cmdline);
+ if (use_shell_execute && lstrlenW(cmdline) > 10 && !memcmp(cmdline, link2eaW, 10 *sizeof(WCHAR)))
+ {
+ HDESK desktop = GetThreadDesktop(GetCurrentThreadId());
+ DWORD is_unavailable, type, size;
+ SC_HANDLE manager, service;
+ SERVICE_STATUS status;
+ DWORD timeout = 3000;
+ HKEY eakey;
+ BOOL ret;
+
+ link2ea = TRUE;
+ if (!SetUserObjectInformationA(desktop, 1000, &timeout, sizeof(timeout)))
+ WINE_ERR("Failed to set desktop timeout, err %u.\n", GetLastError());
+
+ if (!RegOpenKeyExW(HKEY_LOCAL_MACHINE, ea_desktop_pathW, 0, KEY_ALL_ACCESS, &eakey))
+ {
+ size = sizeof(is_unavailable);
+ if (!RegQueryValueExW(eakey, IsUnavailableW, NULL, &type, (BYTE *)&is_unavailable, &size)
+ && type == REG_DWORD && is_unavailable)
+ {
+ WINE_ERR("EA Desktop\\IsUnavailable is set, clearing.\n");
+ is_unavailable = 0;
+ RegSetValueExW(eakey, IsUnavailableW, 0, REG_DWORD, (BYTE *)&is_unavailable, sizeof(is_unavailable));
+ }
+ RegCloseKey(eakey);
+ }
+ if ((manager = OpenSCManagerA(NULL, SERVICES_ACTIVE_DATABASEA, SERVICE_QUERY_STATUS)))
+ {
+ if ((service = OpenServiceA(manager, "EABackgroundService", SERVICE_QUERY_STATUS)))
+ {
+ if (QueryServiceStatus(service, &status))
+ {
+ TRACE("dwCurrentState %#x.\n", status.dwCurrentState);
+ if (status.dwCurrentState == SERVICE_STOP_PENDING || status.dwCurrentState == SERVICE_STOPPED)
+ {
+ ret = DeleteFileA("C:\\ProgramData\\EA Desktop\\backgroundservice.ini");
+ WARN("Tried to delete backgroundservice.ini, ret %d, error %u.\n", ret, GetLastError());
+ }
+ }
+ else ERR("Could not query service status, error %u.\n", GetLastError());
+ CloseServiceHandle(service);
+ }
+ else TRACE("Could not open EABackgroundService, error %u.\n", GetLastError());
+ CloseServiceHandle(manager);
+ }
+ else ERR("Could not open service manager, error %u.\n", GetLastError());
+ }
+ hide_window = env_nonzero("PROTON_HIDE_PROCESS_WINDOW");
+
+ /* only await the process finishing if we launch a process directly...
+ * Steam simply calls ShellExecuteA with the same parameters.
+ * this avoids the edge case where we could ShellExecute and
+ * then that process ends up ShellExecuting something as a throw away */
+ *should_await = !use_shell_execute;
+
+ WINE_TRACE("Executing via %s\n",
+ wine_dbgstr_a(use_shell_execute ? "ShellExecuteW" : "CreateProcessW"));
+
+ if (use_shell_execute)
+ {
+ WCHAR *param = NULL;
+ WCHAR *executable_name_end = get_end_of_excutable_name(cmdline);
+ if (*executable_name_end != '\0')
+ {
+ *executable_name_end = '\0';
+ param = executable_name_end+1;
+ }
+ static const WCHAR verb[] = { 'o', 'p', 'e', 'n', 0 };
+ INT_PTR ret;
+
+ if ((ret = (INT_PTR)ShellExecuteW(NULL, verb, cmdline, param, NULL, hide_window ? SW_HIDE : SW_SHOWNORMAL)) < 32)
+ {
+ WINE_ERR("Failed to execute %s, ret %u.\n", wine_dbgstr_w(cmdline), (unsigned int)ret);
+ if (game_process && ret == SE_ERR_NOASSOC && link2ea)
+ {
+ static const WCHAR msi_guidW[] = {'{','C','2','6','2','2','0','8','5','-','A','B','D','2','-','4','9','E','5','-','8','A','B','9','-','D','3','D','6','A','6','4','2','C','0','9','1','}',0};
+ static const WCHAR REMOVE_ALL_W[] = {'R','E','M','O','V','E','=','A','L','L',0};
+
+ /* Try to uninstall EA desktop so it is set up from prerequisites on the next run. */
+ UINT ret = MsiConfigureProductExW(msi_guidW, 0, INSTALLSTATE_DEFAULT, REMOVE_ALL_W);
+
+ WINE_TRACE("MsiConfigureProductExW ret %u.\n", ret);
+ /* If uninstall failed this should trigger interactive repair window on the EA setup run. */
+ RegDeleteTreeW(HKEY_LOCAL_MACHINE, link2ea_pathW);
+ RegDeleteTreeW(HKEY_LOCAL_MACHINE, ea_desktop_pathW);
+ RegDeleteTreeW(HKEY_LOCAL_MACHINE, ea_core_pathW);
+ }
+ }
+ return INVALID_HANDLE_VALUE;
+ }
+ else
+ {
+ if (hide_window)
+ {
+ si.dwFlags |= STARTF_USESHOWWINDOW;
+ si.wShowWindow = SW_HIDE;
+ }
+
+ if (!CreateProcessW(NULL, cmdline, NULL, NULL, FALSE, flags, NULL, NULL, &si, &pi))
+ {
+ WINE_ERR("Failed to create process %s: %u\n", wine_dbgstr_w(cmdline), GetLastError());
+ return INVALID_HANDLE_VALUE;
+ }
+
+ CloseHandle(pi.hThread);
+
+ return pi.hProcess;
+ }
+}
+
+/* Forward stub steam.exe commands to the native steam client */
+static BOOL steam_command_handler(int argc, char *argv[])
+{
+ BOOL restart_self = FALSE;
+ const char *sgi;
+
+ /* If there are command line options, only forward steam:// and options start with - */
+ if (argc > 1 && StrStrIA(argv[1], "steam://") != argv[1] && argv[1][0] != '-')
+ return FALSE;
+
+ if (argc > 2 && !strcmp(argv[1], "--") && (sgi = getenv("SteamGameId")))
+ {
+ char s[64];
+
+ snprintf(s, sizeof(s), "steam://launch/%s", sgi);
+ if (!(restart_self = !strcmp(argv[2], s)))
+ {
+ snprintf(s, sizeof(s), "steam://rungameid/%s", sgi);
+ restart_self = !strcmp(argv[2], s);
+ }
+ }
+ if (restart_self)
+ {
+ HANDLE event;
+
+ event = OpenEventA(SYNCHRONIZE, FALSE, "PROTON_STEAM_EXE_RESTART_APP");
+ if (event)
+ {
+ SetEvent(event);
+ CloseHandle(event);
+ WINE_TRACE("Signalled app restart.\n");
+ }
+ else
+ WINE_ERR("Restart event not found.\n");
+ return TRUE;
+ }
+
+ if (argc <= 1)
+ return FALSE;
+
+ for (int i = 1; i < argc; ++i)
+ {
+ char cmdline[1024];
+ STARTUPINFOA si = { sizeof(si) };
+ PROCESS_INFORMATION pi;
+
+ if (StrStrIA(argv[i], "steam://") != argv[i])
+ continue;
+
+ snprintf(cmdline, sizeof(cmdline),
+ "C:\\windows\\system32\\winebrowser.exe \"%s\"", argv[i]);
+ if (!CreateProcessA(NULL, cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
+ {
+ WINE_ERR("Failed to forward %s.\n", argv[i]);
+ break;
+ }
+ CloseHandle(pi.hProcess);
+ CloseHandle(pi.hThread);
+ WINE_TRACE("Forwarded %s to the native client.\n", argv[i]);
+ break;
+ }
+
+ return TRUE;
+}
+
+static void setup_steam_files(void)
+{
+ static const WCHAR config_pathW[] =
+ {
+ 'C',':','\\','P','r','o','g','r','a','m',' ','F','i','l','e','s',' ','(','x','8','6',')','\\','S','t','e','a','m',
+ '\\','c','o','n','f','i','g',0,
+ };
+ static const WCHAR steamapps_pathW[] =
+ {
+ 'C',':','\\','P','r','o','g','r','a','m',' ','F','i','l','e','s',' ','(','x','8','6',')','\\','S','t','e','a','m',
+ '\\','s','t','e','a','m','a','p','p','s',0,
+ };
+ static const WCHAR libraryfolders_nameW[] =
+ {
+ 'C',':','\\','P','r','o','g','r','a','m',' ','F','i','l','e','s',' ','(','x','8','6',')','\\','S','t','e','a','m',
+ '\\','s','t','e','a','m','a','p','p','s','\\','l','i','b','r','a','r','y','f','o','l','d','e','r','s','.','v','d','f',0,
+ };
+ const char *steam_install_path = getenv("STEAM_COMPAT_CLIENT_INSTALL_PATH");
+ const char *steam_library_paths = getenv("STEAM_COMPAT_LIBRARY_PATHS");
+ const char *start, *end, *next;
+ unsigned int i, index = 0;
+ std::string contents;
+ char idx_str[10];
+
+ if (!CreateDirectoryW(config_pathW, NULL) && GetLastError() != ERROR_ALREADY_EXISTS)
+ {
+ WINE_ERR("Failed to create config directory, GetLastError() %u.\n", GetLastError());
+ return;
+ }
+
+ if (!CreateDirectoryW(steamapps_pathW, NULL) && GetLastError() != ERROR_ALREADY_EXISTS)
+ {
+ WINE_ERR("Failed to create steamapps directory, GetLastError() %u.\n", GetLastError());
+ return;
+ }
+
+ contents += "\"LibraryFolders\"\n{\n";
+
+ WINE_TRACE("steam_install_path %s.\n", wine_dbgstr_a(steam_install_path));
+
+ if (steam_install_path)
+ {
+ std::string s = steam_install_path;
+
+ if (convert_path_to_win(s))
+ {
+ sprintf(idx_str, "%u", index);
+ ++index;
+
+ for (i = 0; i < s.length(); ++i)
+ {
+ if (s[i] == '\\')
+ {
+ s.insert(i, 1, '\\');
+ ++i;
+ }
+ }
+
+ contents += std::string("\t\"") + idx_str + "\"\n\t{\n\t\t\"path\"\t\t\"" + s + "\"\n\t}\n";
+ }
+ else
+ {
+ WINE_ERR("Could not convert %s to win path.\n", wine_dbgstr_a(s.c_str()));
+ }
+ }
+
+ WINE_TRACE("steam_library_paths %s.\n", wine_dbgstr_a(steam_library_paths));
+
+ start = steam_library_paths;
+ while (start && *start)
+ {
+ std::string s;
+
+ if (!(next = strchr(start, ':')))
+ next = start + strlen(start);
+ end = next;
+
+ if (end != start && end[-1] == '/')
+ --end;
+
+ while (end != start && end[-1] != '/' )
+ --end;
+ if (end != start)
+ --end;
+
+ s.append(start, end - start);
+ if (convert_path_to_win(s))
+ {
+ sprintf(idx_str, "%u", index);
+ ++index;
+
+ for (i = 0; i < s.length(); ++i)
+ {
+ if (s[i] == '\\')
+ {
+ s.insert(i, 1, '\\');
+ ++i;
+ }
+ }
+
+ contents += std::string("\t\"") + idx_str + "\"\n\t{\n\t\t\"path\"\t\t\"" + s + "\"\n\t}\n";
+ }
+ else
+ {
+ WINE_ERR("Could not convert %s to win path.\n", wine_dbgstr_a(s.c_str()));
+ }
+ if (*next == ':')
+ ++next;
+ start = next;
+ }
+
+ contents += "}\n";
+
+ if (!write_string_to_file(libraryfolders_nameW, contents))
+ WINE_ERR("Could not write %s.\n", wine_dbgstr_w(libraryfolders_nameW));
+}
+
+#ifndef DIRECTORY_QUERY
+#define DIRECTORY_QUERY 0x0001
+#endif
+
+static HANDLE find_ack_event(void)
+{
+ static const WCHAR steam_ack_event[] = {'S','T','E','A','M','_','S','T','A','R','T','_','A','C','K','_','E','V','E','N','T',0};
+ static const WCHAR name[] = {'\\','B','a','s','e','N','a','m','e','d','O','b','j','e','c','t','s','\\','S','e','s','s','i','o','n','\\','1',0};
+ DIRECTORY_BASIC_INFORMATION *di;
+ OBJECT_ATTRIBUTES attr;
+ HANDLE dir, ret = NULL;
+ ULONG context, size;
+ UNICODE_STRING str;
+ char buffer[1024];
+ NTSTATUS status;
+
+ di = (DIRECTORY_BASIC_INFORMATION *)buffer;
+
+ RtlInitUnicodeString(&str, name);
+ InitializeObjectAttributes(&attr, &str, 0, 0, NULL);
+ status = NtOpenDirectoryObject( &dir, DIRECTORY_QUERY, &attr );
+ if (status)
+ {
+ WINE_WARN("Failed to open directory %s, status %#x.\n", wine_dbgstr_w(name), status);
+ return NULL;
+ }
+
+ status = NtQueryDirectoryObject(dir, di, sizeof(buffer), TRUE, TRUE, &context, &size);
+ while (!status)
+ {
+ if (!strncmpW(di->ObjectName.Buffer, steam_ack_event, ARRAY_SIZE(steam_ack_event) - 1))
+ {
+ WINE_TRACE("Found event %s.\n", wine_dbgstr_w(di->ObjectName.Buffer));
+ ret = OpenEventW(SYNCHRONIZE, FALSE, di->ObjectName.Buffer);
+ if (!ret)
+ WINE_WARN("Failed to create event, err %u.\n", GetLastError());
+ break;
+ }
+ status = NtQueryDirectoryObject(dir, di, sizeof(buffer), TRUE, FALSE, &context, &size);
+ }
+ if (status && status != STATUS_NO_MORE_ENTRIES)
+ WINE_WARN("NtQueryDirectoryObject failed, status %#x.\n", status);
+ WINE_TRACE("ret %p.\n", ret);
+
+ CloseHandle(dir);
+ return ret;
+}
+
+static DWORD WINAPI steam_drm_thread(void *arg)
+{
+ HANDLE consume, produce;
+ HANDLE start_ack = NULL;
+ HANDLE child = arg;
+ DWORD pid;
+ LONG prev;
+
+ consume = CreateSemaphoreA(NULL, 0, 512, "STEAM_DIPC_CONSUME");
+ if (!consume)
+ {
+ WINE_ERR("Failed to create consume semaphore, err %u.\n", GetLastError());
+ return -1;
+ }
+ produce = CreateSemaphoreA(NULL, 1, 512, "SREAM_DIPC_PRODUCE");
+ if (!produce)
+ {
+ CloseHandle(consume);
+ WINE_ERR("Failed to create produce semaphore, err %u.\n", GetLastError());
+ return -1;
+ }
+
+ pid = GetProcessId(child);
+
+ WINE_TRACE("Child pid %04x.\n", pid);
+
+ while (WaitForSingleObject(consume, INFINITE) == WAIT_OBJECT_0)
+ {
+ WINE_TRACE("Got event.\n");
+
+ if (!start_ack)
+ start_ack = find_ack_event();
+ if (start_ack)
+ SetEvent(start_ack);
+ ReleaseSemaphore(produce, 1, &prev);
+ WINE_TRACE("prev %d.\n", prev);
+ }
+
+ return 0;
+}
+
+BOOL is_ptraced(void)
+{
+ char key[50];
+ int value;
+ FILE *fp = fopen("/proc/self/status", "r");
+ BOOL ret = FALSE;
+
+ if (!fp) return FALSE;
+
+ while (fscanf(fp, " %s %d\n", key, &value) > 0)
+ {
+ if (!strcmp("TracerPid:", key))
+ {
+ ret = (value != 0);
+ break;
+ }
+ }
+
+ fclose(fp);
+ return ret;
+}
+
+int main(int argc, char *argv[])
+{
+ HANDLE wait_handle = INVALID_HANDLE_VALUE;
+ HANDLE event2 = INVALID_HANDLE_VALUE;
+ HANDLE event = INVALID_HANDLE_VALUE;
+ HANDLE child = INVALID_HANDLE_VALUE;
+ BOOL game_process = FALSE;
+ DWORD rc = 0;
+
+ WINE_TRACE("\n");
+
+ if (steam_command_handler(argc, argv))
+ return 0;
+
+ if (getenv("SteamGameId"))
+ {
+ /* do setup only for game process */
+ event = CreateEventA(NULL, FALSE, FALSE, "Steam3Master_SharedMemLock");
+
+ /* For 2K Launcher. */
+ event2 = CreateEventA(NULL, FALSE, FALSE, "Global\\Valve_SteamIPC_Class");
+
+ CreateThread(NULL, 0, create_steam_window, NULL, 0, NULL);
+
+ set_active_process_pid();
+ set_client_dll_paths();
+
+ if (steam_client_init())
+ {
+ setup_steam_registry();
+ setup_battleye_bridge();
+ setup_eac_bridge();
+ }
+ else
+ {
+ WINE_ERR("steam_client_init failed\n");
+ }
+
+ setup_steam_files();
+
+ if (env_nonzero("PROTON_WAIT_ATTACH"))
+ {
+ unsigned int sleep_count = 0;
+ WINE_TRACE("PROTON_WAIT_ATTACH is set, waiting for debugger...\n");
+ while (!IsDebuggerPresent() && !is_ptraced())
+ {
+ Sleep(100);
+ ++sleep_count;
+ if (sleep_count >= 10)
+ {
+ WINE_TRACE("still waiting for debugger...\n");
+ sleep_count = 0;
+ }
+ }
+ }
+
+ steam_client_shutdown();
+
+ game_process = TRUE;
+ }
+
+ if (argc > 1)
+ {
+ BOOL should_await;
+
+ setup_vrpaths();
+
+ if (game_process)
+ setup_vr_registry();
+
+ child = run_process(&should_await, game_process);
+
+ if (should_await)
+ {
+ if (child == INVALID_HANDLE_VALUE)
+ return 1;
+
+ wait_handle = child;
+ }
+
+ if (game_process)
+ CreateThread(NULL, 0, steam_drm_thread, child, 0, NULL);
+ }
+ else if (game_process)
+ {
+ setup_vrpaths();
+ setup_vr_registry();
+ CreateThread(NULL, 0, steam_drm_thread, INVALID_HANDLE_VALUE, 0, NULL);
+ }
+
+ if (game_process)
+ NtSetInformationProcess( GetCurrentProcess(), (PROCESSINFOCLASS)1000 /* ProcessWineMakeProcessSystem */,
+ &wait_handle, sizeof(HANDLE *) );
+
+ if (game_process && wait_handle == INVALID_HANDLE_VALUE)
+ {
+ FreeConsole();
+ for (;;)
+ Sleep(INFINITE);
+ }
+
+ if(wait_handle != INVALID_HANDLE_VALUE)
+ {
+ HANDLE waits[2];
+ DWORD ret;
+ int wait_count;
+
+ waits[0] = wait_handle;
+ waits[1] = NULL;
+ wait_count = 1;
+ if (game_process)
+ {
+ if ((waits[1] = CreateEventA(NULL, FALSE, FALSE, "PROTON_STEAM_EXE_RESTART_APP")))
+ {
+ ++wait_count;
+ }
+ else
+ {
+ WINE_ERR("Failed to create restart event, err %lu.\n", GetLastError());
+ }
+ }
+ FreeConsole();
+ while ((ret = WaitForMultipleObjects(wait_count, waits, FALSE, INFINITE) != WAIT_OBJECT_0))
+ {
+ BOOL should_await;
+
+ if (ret != WAIT_OBJECT_0 + 1)
+ {
+ WINE_ERR("Wait failed.\n");
+ break;
+ }
+ if (child != INVALID_HANDLE_VALUE)
+ {
+ if (WaitForSingleObject(child, 0) == WAIT_TIMEOUT)
+ {
+ WINE_ERR("Child is still running, not restarting.\n");
+ continue;
+ }
+ CloseHandle(child);
+ }
+ child = run_process(&should_await, game_process);
+ }
+ CloseHandle(waits[1]);
+ }
+
+ if (event != INVALID_HANDLE_VALUE)
+ CloseHandle(event);
+ if (event2 != INVALID_HANDLE_VALUE)
+ CloseHandle(event2);
+
+ if (child != INVALID_HANDLE_VALUE)
+ {
+ GetExitCodeProcess(child, &rc);
+ CloseHandle(child);
+ }
+
+ return rc;
+}
diff --git a/vendor/README.md b/vendor/README.md
new file mode 100644
index 0000000..1435185
--- /dev/null
+++ b/vendor/README.md
@@ -0,0 +1,25 @@
+# Vendored dependencies
+
+## cJSON
+
+Tracked in this repo as `cJSON.c` and `cJSON.h`. MIT. Used only by the signature
+database loader.
+
+## Dobby
+
+Not tracked. `.gitignore` ignores `vendor/dobby/`, so a fresh checkout has to fetch
+it before `make dobby` will work:
+
+ git clone https://github.com/jmpews/Dobby.git vendor/dobby
+ git -C vendor/dobby checkout 5dfc8546954ce3b3198132ab13fddb89ee92cdd7
+
+That commit is `Fixup typo`, 2024-03-14, and is the revision every measurement in
+this project was taken against. Apache-2.0.
+
+Dobby is pinned rather than tracked at a moving `main` because the inline hook
+trampolines are architecture-specific and a newer revision changes code generation.
+Do not advance the pin without a good reason as well as verifying that hooks still
+install on a supported Steam version.
+
+Build it with `make dobby`. The libraries land in `build/dobby/` and the top-level
+`Makefile` links them from there.
diff --git a/vendor/cJSON.c b/vendor/cJSON.c
new file mode 100644
index 0000000..88c2d95
--- /dev/null
+++ b/vendor/cJSON.c
@@ -0,0 +1,3206 @@
+/*
+ Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
+
+ 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.
+*/
+
+/* cJSON */
+/* JSON parser in C. */
+
+/* disable warnings about old C89 functions in MSVC */
+#if !defined(_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER)
+#define _CRT_SECURE_NO_DEPRECATE
+#endif
+
+#ifdef __GNUC__
+#pragma GCC visibility push(default)
+#endif
+#if defined(_MSC_VER)
+#pragma warning (push)
+/* disable warning about single line comments in system headers */
+#pragma warning (disable : 4001)
+#endif
+
+#include <string.h>
+#include <stdio.h>
+#include <math.h>
+#include <stdlib.h>
+#include <limits.h>
+#include <ctype.h>
+#include <float.h>
+
+#ifdef ENABLE_LOCALES
+#include <locale.h>
+#endif
+
+#if defined(_MSC_VER)
+#pragma warning (pop)
+#endif
+#ifdef __GNUC__
+#pragma GCC visibility pop
+#endif
+
+#include "cJSON.h"
+
+/* define our own boolean type */
+#ifdef true
+#undef true
+#endif
+#define true ((cJSON_bool)1)
+
+#ifdef false
+#undef false
+#endif
+#define false ((cJSON_bool)0)
+
+/* define isnan and isinf for ANSI C, if in C99 or above, isnan and isinf has been defined in math.h */
+#ifndef isinf
+#define isinf(d) (isnan((d - d)) && !isnan(d))
+#endif
+#ifndef isnan
+#define isnan(d) (d != d)
+#endif
+
+#ifndef NAN
+#ifdef _WIN32
+#define NAN sqrt(-1.0)
+#else
+#define NAN 0.0/0.0
+#endif
+#endif
+
+typedef struct {
+ const unsigned char *json;
+ size_t position;
+} error;
+static error global_error = { NULL, 0 };
+
+CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void)
+{
+ return (const char*) (global_error.json + global_error.position);
+}
+
+CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item)
+{
+ if (!cJSON_IsString(item))
+ {
+ return NULL;
+ }
+
+ return item->valuestring;
+}
+
+CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item)
+{
+ if (!cJSON_IsNumber(item))
+ {
+ return (double) NAN;
+ }
+
+ return item->valuedouble;
+}
+
+/* This is a safeguard to prevent copy-pasters from using incompatible C and header files */
+#if (CJSON_VERSION_MAJOR != 1) || (CJSON_VERSION_MINOR != 7) || (CJSON_VERSION_PATCH != 19)
+ #error cJSON.h and cJSON.c have different versions. Make sure that both have the same.
+#endif
+
+CJSON_PUBLIC(const char*) cJSON_Version(void)
+{
+ static char version[15];
+ sprintf(version, "%i.%i.%i", CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, CJSON_VERSION_PATCH);
+
+ return version;
+}
+
+/* Case insensitive string comparison, doesn't consider two NULL pointers equal though */
+static int case_insensitive_strcmp(const unsigned char *string1, const unsigned char *string2)
+{
+ if ((string1 == NULL) || (string2 == NULL))
+ {
+ return 1;
+ }
+
+ if (string1 == string2)
+ {
+ return 0;
+ }
+
+ for(; tolower(*string1) == tolower(*string2); (void)string1++, string2++)
+ {
+ if (*string1 == '\0')
+ {
+ return 0;
+ }
+ }
+
+ return tolower(*string1) - tolower(*string2);
+}
+
+typedef struct internal_hooks
+{
+ void *(CJSON_CDECL *allocate)(size_t size);
+ void (CJSON_CDECL *deallocate)(void *pointer);
+ void *(CJSON_CDECL *reallocate)(void *pointer, size_t size);
+} internal_hooks;
+
+#if defined(_MSC_VER)
+/* work around MSVC error C2322: '...' address of dllimport '...' is not static */
+static void * CJSON_CDECL internal_malloc(size_t size)
+{
+ return malloc(size);
+}
+static void CJSON_CDECL internal_free(void *pointer)
+{
+ free(pointer);
+}
+static void * CJSON_CDECL internal_realloc(void *pointer, size_t size)
+{
+ return realloc(pointer, size);
+}
+#else
+#define internal_malloc malloc
+#define internal_free free
+#define internal_realloc realloc
+#endif
+
+/* strlen of character literals resolved at compile time */
+#define static_strlen(string_literal) (sizeof(string_literal) - sizeof(""))
+
+static internal_hooks global_hooks = { internal_malloc, internal_free, internal_realloc };
+
+static unsigned char* cJSON_strdup(const unsigned char* string, const internal_hooks * const hooks)
+{
+ size_t length = 0;
+ unsigned char *copy = NULL;
+
+ if (string == NULL)
+ {
+ return NULL;
+ }
+
+ length = strlen((const char*)string) + sizeof("");
+ copy = (unsigned char*)hooks->allocate(length);
+ if (copy == NULL)
+ {
+ return NULL;
+ }
+ memcpy(copy, string, length);
+
+ return copy;
+}
+
+CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks)
+{
+ if (hooks == NULL)
+ {
+ /* Reset hooks */
+ global_hooks.allocate = malloc;
+ global_hooks.deallocate = free;
+ global_hooks.reallocate = realloc;
+ return;
+ }
+
+ global_hooks.allocate = malloc;
+ if (hooks->malloc_fn != NULL)
+ {
+ global_hooks.allocate = hooks->malloc_fn;
+ }
+
+ global_hooks.deallocate = free;
+ if (hooks->free_fn != NULL)
+ {
+ global_hooks.deallocate = hooks->free_fn;
+ }
+
+ /* use realloc only if both free and malloc are used */
+ global_hooks.reallocate = NULL;
+ if ((global_hooks.allocate == malloc) && (global_hooks.deallocate == free))
+ {
+ global_hooks.reallocate = realloc;
+ }
+}
+
+/* Internal constructor. */
+static cJSON *cJSON_New_Item(const internal_hooks * const hooks)
+{
+ cJSON* node = (cJSON*)hooks->allocate(sizeof(cJSON));
+ if (node)
+ {
+ memset(node, '\0', sizeof(cJSON));
+ }
+
+ return node;
+}
+
+/* Delete a cJSON structure. */
+CJSON_PUBLIC(void) cJSON_Delete(cJSON *item)
+{
+ cJSON *next = NULL;
+ while (item != NULL)
+ {
+ next = item->next;
+ if (!(item->type & cJSON_IsReference) && (item->child != NULL))
+ {
+ cJSON_Delete(item->child);
+ }
+ if (!(item->type & cJSON_IsReference) && (item->valuestring != NULL))
+ {
+ global_hooks.deallocate(item->valuestring);
+ item->valuestring = NULL;
+ }
+ if (!(item->type & cJSON_StringIsConst) && (item->string != NULL))
+ {
+ global_hooks.deallocate(item->string);
+ item->string = NULL;
+ }
+ global_hooks.deallocate(item);
+ item = next;
+ }
+}
+
+/* get the decimal point character of the current locale */
+static unsigned char get_decimal_point(void)
+{
+#ifdef ENABLE_LOCALES
+ struct lconv *lconv = localeconv();
+ return (unsigned char) lconv->decimal_point[0];
+#else
+ return '.';
+#endif
+}
+
+typedef struct
+{
+ const unsigned char *content;
+ size_t length;
+ size_t offset;
+ size_t depth; /* How deeply nested (in arrays/objects) is the input at the current offset. */
+ internal_hooks hooks;
+} parse_buffer;
+
+/* check if the given size is left to read in a given parse buffer (starting with 1) */
+#define can_read(buffer, size) ((buffer != NULL) && (((buffer)->offset + size) <= (buffer)->length))
+/* check if the buffer can be accessed at the given index (starting with 0) */
+#define can_access_at_index(buffer, index) ((buffer != NULL) && (((buffer)->offset + index) < (buffer)->length))
+#define cannot_access_at_index(buffer, index) (!can_access_at_index(buffer, index))
+/* get a pointer to the buffer at the position */
+#define buffer_at_offset(buffer) ((buffer)->content + (buffer)->offset)
+
+/* Parse the input text to generate a number, and populate the result into item. */
+static cJSON_bool parse_number(cJSON * const item, parse_buffer * const input_buffer)
+{
+ double number = 0;
+ unsigned char *after_end = NULL;
+ unsigned char *number_c_string;
+ unsigned char decimal_point = get_decimal_point();
+ size_t i = 0;
+ size_t number_string_length = 0;
+ cJSON_bool has_decimal_point = false;
+
+ if ((input_buffer == NULL) || (input_buffer->content == NULL))
+ {
+ return false;
+ }
+
+ /* copy the number into a temporary buffer and replace '.' with the decimal point
+ * of the current locale (for strtod)
+ * This also takes care of '\0' not necessarily being available for marking the end of the input */
+ for (i = 0; can_access_at_index(input_buffer, i); i++)
+ {
+ switch (buffer_at_offset(input_buffer)[i])
+ {
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ case '+':
+ case '-':
+ case 'e':
+ case 'E':
+ number_string_length++;
+ break;
+
+ case '.':
+ number_string_length++;
+ has_decimal_point = true;
+ break;
+
+ default:
+ goto loop_end;
+ }
+ }
+loop_end:
+ /* malloc for temporary buffer, add 1 for '\0' */
+ number_c_string = (unsigned char *) input_buffer->hooks.allocate(number_string_length + 1);
+ if (number_c_string == NULL)
+ {
+ return false; /* allocation failure */
+ }
+
+ memcpy(number_c_string, buffer_at_offset(input_buffer), number_string_length);
+ number_c_string[number_string_length] = '\0';
+
+ if (has_decimal_point)
+ {
+ for (i = 0; i < number_string_length; i++)
+ {
+ if (number_c_string[i] == '.')
+ {
+ /* replace '.' with the decimal point of the current locale (for strtod) */
+ number_c_string[i] = decimal_point;
+ }
+ }
+ }
+
+ number = strtod((const char*)number_c_string, (char**)&after_end);
+ if (number_c_string == after_end)
+ {
+ /* free the temporary buffer */
+ input_buffer->hooks.deallocate(number_c_string);
+ return false; /* parse_error */
+ }
+
+ item->valuedouble = number;
+
+ /* use saturation in case of overflow */
+ if (number >= INT_MAX)
+ {
+ item->valueint = INT_MAX;
+ }
+ else if (number <= (double)INT_MIN)
+ {
+ item->valueint = INT_MIN;
+ }
+ else
+ {
+ item->valueint = (int)number;
+ }
+
+ item->type = cJSON_Number;
+
+ input_buffer->offset += (size_t)(after_end - number_c_string);
+ /* free the temporary buffer */
+ input_buffer->hooks.deallocate(number_c_string);
+ return true;
+}
+
+/* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */
+CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number)
+{
+ if (object == NULL)
+ {
+ return (double)NAN;
+ }
+
+ if (number >= INT_MAX)
+ {
+ object->valueint = INT_MAX;
+ }
+ else if (number <= (double)INT_MIN)
+ {
+ object->valueint = INT_MIN;
+ }
+ else
+ {
+ object->valueint = (int)number;
+ }
+
+ return object->valuedouble = number;
+}
+
+/* Note: when passing a NULL valuestring, cJSON_SetValuestring treats this as an error and return NULL */
+CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring)
+{
+ char *copy = NULL;
+ size_t v1_len;
+ size_t v2_len;
+ /* if object's type is not cJSON_String or is cJSON_IsReference, it should not set valuestring */
+ if ((object == NULL) || !(object->type & cJSON_String) || (object->type & cJSON_IsReference))
+ {
+ return NULL;
+ }
+ /* return NULL if the object is corrupted or valuestring is NULL */
+ if (object->valuestring == NULL || valuestring == NULL)
+ {
+ return NULL;
+ }
+
+ v1_len = strlen(valuestring);
+ v2_len = strlen(object->valuestring);
+
+ if (v1_len <= v2_len)
+ {
+ /* strcpy does not handle overlapping string: [X1, X2] [Y1, Y2] => X2 < Y1 or Y2 < X1 */
+ if (!( valuestring + v1_len < object->valuestring || object->valuestring + v2_len < valuestring ))
+ {
+ return NULL;
+ }
+ strcpy(object->valuestring, valuestring);
+ return object->valuestring;
+ }
+ copy = (char*) cJSON_strdup((const unsigned char*)valuestring, &global_hooks);
+ if (copy == NULL)
+ {
+ return NULL;
+ }
+ if (object->valuestring != NULL)
+ {
+ cJSON_free(object->valuestring);
+ }
+ object->valuestring = copy;
+
+ return copy;
+}
+
+typedef struct
+{
+ unsigned char *buffer;
+ size_t length;
+ size_t offset;
+ size_t depth; /* current nesting depth (for formatted printing) */
+ cJSON_bool noalloc;
+ cJSON_bool format; /* is this print a formatted print */
+ internal_hooks hooks;
+} printbuffer;
+
+/* realloc printbuffer if necessary to have at least "needed" bytes more */
+static unsigned char* ensure(printbuffer * const p, size_t needed)
+{
+ unsigned char *newbuffer = NULL;
+ size_t newsize = 0;
+
+ if ((p == NULL) || (p->buffer == NULL))
+ {
+ return NULL;
+ }
+
+ if ((p->length > 0) && (p->offset >= p->length))
+ {
+ /* make sure that offset is valid */
+ return NULL;
+ }
+
+ if (needed > INT_MAX)
+ {
+ /* sizes bigger than INT_MAX are currently not supported */
+ return NULL;
+ }
+
+ needed += p->offset + 1;
+ if (needed <= p->length)
+ {
+ return p->buffer + p->offset;
+ }
+
+ if (p->noalloc) {
+ return NULL;
+ }
+
+ /* calculate new buffer size */
+ if (needed > (INT_MAX / 2))
+ {
+ /* overflow of int, use INT_MAX if possible */
+ if (needed <= INT_MAX)
+ {
+ newsize = INT_MAX;
+ }
+ else
+ {
+ return NULL;
+ }
+ }
+ else
+ {
+ newsize = needed * 2;
+ }
+
+ if (p->hooks.reallocate != NULL)
+ {
+ /* reallocate with realloc if available */
+ newbuffer = (unsigned char*)p->hooks.reallocate(p->buffer, newsize);
+ if (newbuffer == NULL)
+ {
+ p->hooks.deallocate(p->buffer);
+ p->length = 0;
+ p->buffer = NULL;
+
+ return NULL;
+ }
+ }
+ else
+ {
+ /* otherwise reallocate manually */
+ newbuffer = (unsigned char*)p->hooks.allocate(newsize);
+ if (!newbuffer)
+ {
+ p->hooks.deallocate(p->buffer);
+ p->length = 0;
+ p->buffer = NULL;
+
+ return NULL;
+ }
+
+ memcpy(newbuffer, p->buffer, p->offset + 1);
+ p->hooks.deallocate(p->buffer);
+ }
+ p->length = newsize;
+ p->buffer = newbuffer;
+
+ return newbuffer + p->offset;
+}
+
+/* calculate the new length of the string in a printbuffer and update the offset */
+static void update_offset(printbuffer * const buffer)
+{
+ const unsigned char *buffer_pointer = NULL;
+ if ((buffer == NULL) || (buffer->buffer == NULL))
+ {
+ return;
+ }
+ buffer_pointer = buffer->buffer + buffer->offset;
+
+ buffer->offset += strlen((const char*)buffer_pointer);
+}
+
+/* securely comparison of floating-point variables */
+static cJSON_bool compare_double(double a, double b)
+{
+ double maxVal = fabs(a) > fabs(b) ? fabs(a) : fabs(b);
+ return (fabs(a - b) <= maxVal * DBL_EPSILON);
+}
+
+/* Render the number nicely from the given item into a string. */
+static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer)
+{
+ unsigned char *output_pointer = NULL;
+ double d = item->valuedouble;
+ int length = 0;
+ size_t i = 0;
+ unsigned char number_buffer[26] = {0}; /* temporary buffer to print the number into */
+ unsigned char decimal_point = get_decimal_point();
+ double test = 0.0;
+
+ if (output_buffer == NULL)
+ {
+ return false;
+ }
+
+ /* This checks for NaN and Infinity */
+ if (isnan(d) || isinf(d))
+ {
+ length = sprintf((char*)number_buffer, "null");
+ }
+ else if(d == (double)item->valueint)
+ {
+ length = sprintf((char*)number_buffer, "%d", item->valueint);
+ }
+ else
+ {
+ /* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */
+ length = sprintf((char*)number_buffer, "%1.15g", d);
+
+ /* Check whether the original double can be recovered */
+ if ((sscanf((char*)number_buffer, "%lg", &test) != 1) || !compare_double((double)test, d))
+ {
+ /* If not, print with 17 decimal places of precision */
+ length = sprintf((char*)number_buffer, "%1.17g", d);
+ }
+ }
+
+ /* sprintf failed or buffer overrun occurred */
+ if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1)))
+ {
+ return false;
+ }
+
+ /* reserve appropriate space in the output */
+ output_pointer = ensure(output_buffer, (size_t)length + sizeof(""));
+ if (output_pointer == NULL)
+ {
+ return false;
+ }
+
+ /* copy the printed number to the output and replace locale
+ * dependent decimal point with '.' */
+ for (i = 0; i < ((size_t)length); i++)
+ {
+ if (number_buffer[i] == decimal_point)
+ {
+ output_pointer[i] = '.';
+ continue;
+ }
+
+ output_pointer[i] = number_buffer[i];
+ }
+ output_pointer[i] = '\0';
+
+ output_buffer->offset += (size_t)length;
+
+ return true;
+}
+
+/* parse 4 digit hexadecimal number */
+static unsigned parse_hex4(const unsigned char * const input)
+{
+ unsigned int h = 0;
+ size_t i = 0;
+
+ for (i = 0; i < 4; i++)
+ {
+ /* parse digit */
+ if ((input[i] >= '0') && (input[i] <= '9'))
+ {
+ h += (unsigned int) input[i] - '0';
+ }
+ else if ((input[i] >= 'A') && (input[i] <= 'F'))
+ {
+ h += (unsigned int) 10 + input[i] - 'A';
+ }
+ else if ((input[i] >= 'a') && (input[i] <= 'f'))
+ {
+ h += (unsigned int) 10 + input[i] - 'a';
+ }
+ else /* invalid */
+ {
+ return 0;
+ }
+
+ if (i < 3)
+ {
+ /* shift left to make place for the next nibble */
+ h = h << 4;
+ }
+ }
+
+ return h;
+}
+
+/* converts a UTF-16 literal to UTF-8
+ * A literal can be one or two sequences of the form \uXXXX */
+static unsigned char utf16_literal_to_utf8(const unsigned char * const input_pointer, const unsigned char * const input_end, unsigned char **output_pointer)
+{
+ long unsigned int codepoint = 0;
+ unsigned int first_code = 0;
+ const unsigned char *first_sequence = input_pointer;
+ unsigned char utf8_length = 0;
+ unsigned char utf8_position = 0;
+ unsigned char sequence_length = 0;
+ unsigned char first_byte_mark = 0;
+
+ if ((input_end - first_sequence) < 6)
+ {
+ /* input ends unexpectedly */
+ goto fail;
+ }
+
+ /* get the first utf16 sequence */
+ first_code = parse_hex4(first_sequence + 2);
+
+ /* check that the code is valid */
+ if (((first_code >= 0xDC00) && (first_code <= 0xDFFF)))
+ {
+ goto fail;
+ }
+
+ /* UTF16 surrogate pair */
+ if ((first_code >= 0xD800) && (first_code <= 0xDBFF))
+ {
+ const unsigned char *second_sequence = first_sequence + 6;
+ unsigned int second_code = 0;
+ sequence_length = 12; /* \uXXXX\uXXXX */
+
+ if ((input_end - second_sequence) < 6)
+ {
+ /* input ends unexpectedly */
+ goto fail;
+ }
+
+ if ((second_sequence[0] != '\\') || (second_sequence[1] != 'u'))
+ {
+ /* missing second half of the surrogate pair */
+ goto fail;
+ }
+
+ /* get the second utf16 sequence */
+ second_code = parse_hex4(second_sequence + 2);
+ /* check that the code is valid */
+ if ((second_code < 0xDC00) || (second_code > 0xDFFF))
+ {
+ /* invalid second half of the surrogate pair */
+ goto fail;
+ }
+
+
+ /* calculate the unicode codepoint from the surrogate pair */
+ codepoint = 0x10000 + (((first_code & 0x3FF) << 10) | (second_code & 0x3FF));
+ }
+ else
+ {
+ sequence_length = 6; /* \uXXXX */
+ codepoint = first_code;
+ }
+
+ /* encode as UTF-8
+ * takes at maximum 4 bytes to encode:
+ * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
+ if (codepoint < 0x80)
+ {
+ /* normal ascii, encoding 0xxxxxxx */
+ utf8_length = 1;
+ }
+ else if (codepoint < 0x800)
+ {
+ /* two bytes, encoding 110xxxxx 10xxxxxx */
+ utf8_length = 2;
+ first_byte_mark = 0xC0; /* 11000000 */
+ }
+ else if (codepoint < 0x10000)
+ {
+ /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */
+ utf8_length = 3;
+ first_byte_mark = 0xE0; /* 11100000 */
+ }
+ else if (codepoint <= 0x10FFFF)
+ {
+ /* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */
+ utf8_length = 4;
+ first_byte_mark = 0xF0; /* 11110000 */
+ }
+ else
+ {
+ /* invalid unicode codepoint */
+ goto fail;
+ }
+
+ /* encode as utf8 */
+ for (utf8_position = (unsigned char)(utf8_length - 1); utf8_position > 0; utf8_position--)
+ {
+ /* 10xxxxxx */
+ (*output_pointer)[utf8_position] = (unsigned char)((codepoint | 0x80) & 0xBF);
+ codepoint >>= 6;
+ }
+ /* encode first byte */
+ if (utf8_length > 1)
+ {
+ (*output_pointer)[0] = (unsigned char)((codepoint | first_byte_mark) & 0xFF);
+ }
+ else
+ {
+ (*output_pointer)[0] = (unsigned char)(codepoint & 0x7F);
+ }
+
+ *output_pointer += utf8_length;
+
+ return sequence_length;
+
+fail:
+ return 0;
+}
+
+/* Parse the input text into an unescaped cinput, and populate item. */
+static cJSON_bool parse_string(cJSON * const item, parse_buffer * const input_buffer)
+{
+ const unsigned char *input_pointer = buffer_at_offset(input_buffer) + 1;
+ const unsigned char *input_end = buffer_at_offset(input_buffer) + 1;
+ unsigned char *output_pointer = NULL;
+ unsigned char *output = NULL;
+
+ /* not a string */
+ if (buffer_at_offset(input_buffer)[0] != '\"')
+ {
+ goto fail;
+ }
+
+ {
+ /* calculate approximate size of the output (overestimate) */
+ size_t allocation_length = 0;
+ size_t skipped_bytes = 0;
+ while (((size_t)(input_end - input_buffer->content) < input_buffer->length) && (*input_end != '\"'))
+ {
+ /* is escape sequence */
+ if (input_end[0] == '\\')
+ {
+ if ((size_t)(input_end + 1 - input_buffer->content) >= input_buffer->length)
+ {
+ /* prevent buffer overflow when last input character is a backslash */
+ goto fail;
+ }
+ skipped_bytes++;
+ input_end++;
+ }
+ input_end++;
+ }
+ if (((size_t)(input_end - input_buffer->content) >= input_buffer->length) || (*input_end != '\"'))
+ {
+ goto fail; /* string ended unexpectedly */
+ }
+
+ /* This is at most how much we need for the output */
+ allocation_length = (size_t) (input_end - buffer_at_offset(input_buffer)) - skipped_bytes;
+ output = (unsigned char*)input_buffer->hooks.allocate(allocation_length + sizeof(""));
+ if (output == NULL)
+ {
+ goto fail; /* allocation failure */
+ }
+ }
+
+ output_pointer = output;
+ /* loop through the string literal */
+ while (input_pointer < input_end)
+ {
+ if (*input_pointer != '\\')
+ {
+ *output_pointer++ = *input_pointer++;
+ }
+ /* escape sequence */
+ else
+ {
+ unsigned char sequence_length = 2;
+ if ((input_end - input_pointer) < 1)
+ {
+ goto fail;
+ }
+
+ switch (input_pointer[1])
+ {
+ case 'b':
+ *output_pointer++ = '\b';
+ break;
+ case 'f':
+ *output_pointer++ = '\f';
+ break;
+ case 'n':
+ *output_pointer++ = '\n';
+ break;
+ case 'r':
+ *output_pointer++ = '\r';
+ break;
+ case 't':
+ *output_pointer++ = '\t';
+ break;
+ case '\"':
+ case '\\':
+ case '/':
+ *output_pointer++ = input_pointer[1];
+ break;
+
+ /* UTF-16 literal */
+ case 'u':
+ sequence_length = utf16_literal_to_utf8(input_pointer, input_end, &output_pointer);
+ if (sequence_length == 0)
+ {
+ /* failed to convert UTF16-literal to UTF-8 */
+ goto fail;
+ }
+ break;
+
+ default:
+ goto fail;
+ }
+ input_pointer += sequence_length;
+ }
+ }
+
+ /* zero terminate the output */
+ *output_pointer = '\0';
+
+ item->type = cJSON_String;
+ item->valuestring = (char*)output;
+
+ input_buffer->offset = (size_t) (input_end - input_buffer->content);
+ input_buffer->offset++;
+
+ return true;
+
+fail:
+ if (output != NULL)
+ {
+ input_buffer->hooks.deallocate(output);
+ output = NULL;
+ }
+
+ if (input_pointer != NULL)
+ {
+ input_buffer->offset = (size_t)(input_pointer - input_buffer->content);
+ }
+
+ return false;
+}
+
+/* Render the cstring provided to an escaped version that can be printed. */
+static cJSON_bool print_string_ptr(const unsigned char * const input, printbuffer * const output_buffer)
+{
+ const unsigned char *input_pointer = NULL;
+ unsigned char *output = NULL;
+ unsigned char *output_pointer = NULL;
+ size_t output_length = 0;
+ /* numbers of additional characters needed for escaping */
+ size_t escape_characters = 0;
+
+ if (output_buffer == NULL)
+ {
+ return false;
+ }
+
+ /* empty string */
+ if (input == NULL)
+ {
+ output = ensure(output_buffer, sizeof("\"\""));
+ if (output == NULL)
+ {
+ return false;
+ }
+ strcpy((char*)output, "\"\"");
+
+ return true;
+ }
+
+ /* set "flag" to 1 if something needs to be escaped */
+ for (input_pointer = input; *input_pointer; input_pointer++)
+ {
+ switch (*input_pointer)
+ {
+ case '\"':
+ case '\\':
+ case '\b':
+ case '\f':
+ case '\n':
+ case '\r':
+ case '\t':
+ /* one character escape sequence */
+ escape_characters++;
+ break;
+ default:
+ if (*input_pointer < 32)
+ {
+ /* UTF-16 escape sequence uXXXX */
+ escape_characters += 5;
+ }
+ break;
+ }
+ }
+ output_length = (size_t)(input_pointer - input) + escape_characters;
+
+ output = ensure(output_buffer, output_length + sizeof("\"\""));
+ if (output == NULL)
+ {
+ return false;
+ }
+
+ /* no characters have to be escaped */
+ if (escape_characters == 0)
+ {
+ output[0] = '\"';
+ memcpy(output + 1, input, output_length);
+ output[output_length + 1] = '\"';
+ output[output_length + 2] = '\0';
+
+ return true;
+ }
+
+ output[0] = '\"';
+ output_pointer = output + 1;
+ /* copy the string */
+ for (input_pointer = input; *input_pointer != '\0'; (void)input_pointer++, output_pointer++)
+ {
+ if ((*input_pointer > 31) && (*input_pointer != '\"') && (*input_pointer != '\\'))
+ {
+ /* normal character, copy */
+ *output_pointer = *input_pointer;
+ }
+ else
+ {
+ /* character needs to be escaped */
+ *output_pointer++ = '\\';
+ switch (*input_pointer)
+ {
+ case '\\':
+ *output_pointer = '\\';
+ break;
+ case '\"':
+ *output_pointer = '\"';
+ break;
+ case '\b':
+ *output_pointer = 'b';
+ break;
+ case '\f':
+ *output_pointer = 'f';
+ break;
+ case '\n':
+ *output_pointer = 'n';
+ break;
+ case '\r':
+ *output_pointer = 'r';
+ break;
+ case '\t':
+ *output_pointer = 't';
+ break;
+ default:
+ /* escape and print as unicode codepoint */
+ sprintf((char*)output_pointer, "u%04x", *input_pointer);
+ output_pointer += 4;
+ break;
+ }
+ }
+ }
+ output[output_length + 1] = '\"';
+ output[output_length + 2] = '\0';
+
+ return true;
+}
+
+/* Invoke print_string_ptr (which is useful) on an item. */
+static cJSON_bool print_string(const cJSON * const item, printbuffer * const p)
+{
+ return print_string_ptr((unsigned char*)item->valuestring, p);
+}
+
+/* Predeclare these prototypes. */
+static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer);
+static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer);
+static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer);
+static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer);
+static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer);
+static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer);
+
+/* Utility to jump whitespace and cr/lf */
+static parse_buffer *buffer_skip_whitespace(parse_buffer * const buffer)
+{
+ if ((buffer == NULL) || (buffer->content == NULL))
+ {
+ return NULL;
+ }
+
+ if (cannot_access_at_index(buffer, 0))
+ {
+ return buffer;
+ }
+
+ while (can_access_at_index(buffer, 0) && (buffer_at_offset(buffer)[0] <= 32))
+ {
+ buffer->offset++;
+ }
+
+ if (buffer->offset == buffer->length)
+ {
+ buffer->offset--;
+ }
+
+ return buffer;
+}
+
+/* skip the UTF-8 BOM (byte order mark) if it is at the beginning of a buffer */
+static parse_buffer *skip_utf8_bom(parse_buffer * const buffer)
+{
+ if ((buffer == NULL) || (buffer->content == NULL) || (buffer->offset != 0))
+ {
+ return NULL;
+ }
+
+ if (can_access_at_index(buffer, 4) && (strncmp((const char*)buffer_at_offset(buffer), "\xEF\xBB\xBF", 3) == 0))
+ {
+ buffer->offset += 3;
+ }
+
+ return buffer;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated)
+{
+ size_t buffer_length;
+
+ if (NULL == value)
+ {
+ return NULL;
+ }
+
+ /* Adding null character size due to require_null_terminated. */
+ buffer_length = strlen(value) + sizeof("");
+
+ return cJSON_ParseWithLengthOpts(value, buffer_length, return_parse_end, require_null_terminated);
+}
+
+/* Parse an object - create a new root, and populate. */
+CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated)
+{
+ parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } };
+ cJSON *item = NULL;
+
+ /* reset error position */
+ global_error.json = NULL;
+ global_error.position = 0;
+
+ if (value == NULL || 0 == buffer_length)
+ {
+ goto fail;
+ }
+
+ buffer.content = (const unsigned char*)value;
+ buffer.length = buffer_length;
+ buffer.offset = 0;
+ buffer.hooks = global_hooks;
+
+ item = cJSON_New_Item(&global_hooks);
+ if (item == NULL) /* memory fail */
+ {
+ goto fail;
+ }
+
+ if (!parse_value(item, buffer_skip_whitespace(skip_utf8_bom(&buffer))))
+ {
+ /* parse failure. ep is set. */
+ goto fail;
+ }
+
+ /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */
+ if (require_null_terminated)
+ {
+ buffer_skip_whitespace(&buffer);
+ if ((buffer.offset >= buffer.length) || buffer_at_offset(&buffer)[0] != '\0')
+ {
+ goto fail;
+ }
+ }
+ if (return_parse_end)
+ {
+ *return_parse_end = (const char*)buffer_at_offset(&buffer);
+ }
+
+ return item;
+
+fail:
+ if (item != NULL)
+ {
+ cJSON_Delete(item);
+ }
+
+ if (value != NULL)
+ {
+ error local_error;
+ local_error.json = (const unsigned char*)value;
+ local_error.position = 0;
+
+ if (buffer.offset < buffer.length)
+ {
+ local_error.position = buffer.offset;
+ }
+ else if (buffer.length > 0)
+ {
+ local_error.position = buffer.length - 1;
+ }
+
+ if (return_parse_end != NULL)
+ {
+ *return_parse_end = (const char*)local_error.json + local_error.position;
+ }
+
+ global_error = local_error;
+ }
+
+ return NULL;
+}
+
+/* Default options for cJSON_Parse */
+CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value)
+{
+ return cJSON_ParseWithOpts(value, 0, 0);
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length)
+{
+ return cJSON_ParseWithLengthOpts(value, buffer_length, 0, 0);
+}
+
+#define cjson_min(a, b) (((a) < (b)) ? (a) : (b))
+
+static unsigned char *print(const cJSON * const item, cJSON_bool format, const internal_hooks * const hooks)
+{
+ static const size_t default_buffer_size = 256;
+ printbuffer buffer[1];
+ unsigned char *printed = NULL;
+
+ memset(buffer, 0, sizeof(buffer));
+
+ /* create buffer */
+ buffer->buffer = (unsigned char*) hooks->allocate(default_buffer_size);
+ buffer->length = default_buffer_size;
+ buffer->format = format;
+ buffer->hooks = *hooks;
+ if (buffer->buffer == NULL)
+ {
+ goto fail;
+ }
+
+ /* print the value */
+ if (!print_value(item, buffer))
+ {
+ goto fail;
+ }
+ update_offset(buffer);
+
+ /* check if reallocate is available */
+ if (hooks->reallocate != NULL)
+ {
+ printed = (unsigned char*) hooks->reallocate(buffer->buffer, buffer->offset + 1);
+ if (printed == NULL) {
+ goto fail;
+ }
+ buffer->buffer = NULL;
+ }
+ else /* otherwise copy the JSON over to a new buffer */
+ {
+ printed = (unsigned char*) hooks->allocate(buffer->offset + 1);
+ if (printed == NULL)
+ {
+ goto fail;
+ }
+ memcpy(printed, buffer->buffer, cjson_min(buffer->length, buffer->offset + 1));
+ printed[buffer->offset] = '\0'; /* just to be sure */
+
+ /* free the buffer */
+ hooks->deallocate(buffer->buffer);
+ buffer->buffer = NULL;
+ }
+
+ return printed;
+
+fail:
+ if (buffer->buffer != NULL)
+ {
+ hooks->deallocate(buffer->buffer);
+ buffer->buffer = NULL;
+ }
+
+ if (printed != NULL)
+ {
+ hooks->deallocate(printed);
+ printed = NULL;
+ }
+
+ return NULL;
+}
+
+/* Render a cJSON item/entity/structure to text. */
+CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item)
+{
+ return (char*)print(item, true, &global_hooks);
+}
+
+CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item)
+{
+ return (char*)print(item, false, &global_hooks);
+}
+
+CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt)
+{
+ printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } };
+
+ if (prebuffer < 0)
+ {
+ return NULL;
+ }
+
+ p.buffer = (unsigned char*)global_hooks.allocate((size_t)prebuffer);
+ if (!p.buffer)
+ {
+ return NULL;
+ }
+
+ p.length = (size_t)prebuffer;
+ p.offset = 0;
+ p.noalloc = false;
+ p.format = fmt;
+ p.hooks = global_hooks;
+
+ if (!print_value(item, &p))
+ {
+ global_hooks.deallocate(p.buffer);
+ p.buffer = NULL;
+ return NULL;
+ }
+
+ return (char*)p.buffer;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format)
+{
+ printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } };
+
+ if ((length < 0) || (buffer == NULL))
+ {
+ return false;
+ }
+
+ p.buffer = (unsigned char*)buffer;
+ p.length = (size_t)length;
+ p.offset = 0;
+ p.noalloc = true;
+ p.format = format;
+ p.hooks = global_hooks;
+
+ return print_value(item, &p);
+}
+
+/* Parser core - when encountering text, process appropriately. */
+static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer)
+{
+ if ((input_buffer == NULL) || (input_buffer->content == NULL))
+ {
+ return false; /* no input */
+ }
+
+ /* parse the different types of values */
+ /* null */
+ if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "null", 4) == 0))
+ {
+ item->type = cJSON_NULL;
+ input_buffer->offset += 4;
+ return true;
+ }
+ /* false */
+ if (can_read(input_buffer, 5) && (strncmp((const char*)buffer_at_offset(input_buffer), "false", 5) == 0))
+ {
+ item->type = cJSON_False;
+ input_buffer->offset += 5;
+ return true;
+ }
+ /* true */
+ if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "true", 4) == 0))
+ {
+ item->type = cJSON_True;
+ item->valueint = 1;
+ input_buffer->offset += 4;
+ return true;
+ }
+ /* string */
+ if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '\"'))
+ {
+ return parse_string(item, input_buffer);
+ }
+ /* number */
+ if (can_access_at_index(input_buffer, 0) && ((buffer_at_offset(input_buffer)[0] == '-') || ((buffer_at_offset(input_buffer)[0] >= '0') && (buffer_at_offset(input_buffer)[0] <= '9'))))
+ {
+ return parse_number(item, input_buffer);
+ }
+ /* array */
+ if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '['))
+ {
+ return parse_array(item, input_buffer);
+ }
+ /* object */
+ if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '{'))
+ {
+ return parse_object(item, input_buffer);
+ }
+
+ return false;
+}
+
+/* Render a value to text. */
+static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer)
+{
+ unsigned char *output = NULL;
+
+ if ((item == NULL) || (output_buffer == NULL))
+ {
+ return false;
+ }
+
+ switch ((item->type) & 0xFF)
+ {
+ case cJSON_NULL:
+ output = ensure(output_buffer, 5);
+ if (output == NULL)
+ {
+ return false;
+ }
+ strcpy((char*)output, "null");
+ return true;
+
+ case cJSON_False:
+ output = ensure(output_buffer, 6);
+ if (output == NULL)
+ {
+ return false;
+ }
+ strcpy((char*)output, "false");
+ return true;
+
+ case cJSON_True:
+ output = ensure(output_buffer, 5);
+ if (output == NULL)
+ {
+ return false;
+ }
+ strcpy((char*)output, "true");
+ return true;
+
+ case cJSON_Number:
+ return print_number(item, output_buffer);
+
+ case cJSON_Raw:
+ {
+ size_t raw_length = 0;
+ if (item->valuestring == NULL)
+ {
+ return false;
+ }
+
+ raw_length = strlen(item->valuestring) + sizeof("");
+ output = ensure(output_buffer, raw_length);
+ if (output == NULL)
+ {
+ return false;
+ }
+ memcpy(output, item->valuestring, raw_length);
+ return true;
+ }
+
+ case cJSON_String:
+ return print_string(item, output_buffer);
+
+ case cJSON_Array:
+ return print_array(item, output_buffer);
+
+ case cJSON_Object:
+ return print_object(item, output_buffer);
+
+ default:
+ return false;
+ }
+}
+
+/* Build an array from input text. */
+static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer)
+{
+ cJSON *head = NULL; /* head of the linked list */
+ cJSON *current_item = NULL;
+
+ if (input_buffer->depth >= CJSON_NESTING_LIMIT)
+ {
+ return false; /* to deeply nested */
+ }
+ input_buffer->depth++;
+
+ if (buffer_at_offset(input_buffer)[0] != '[')
+ {
+ /* not an array */
+ goto fail;
+ }
+
+ input_buffer->offset++;
+ buffer_skip_whitespace(input_buffer);
+ if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ']'))
+ {
+ /* empty array */
+ goto success;
+ }
+
+ /* check if we skipped to the end of the buffer */
+ if (cannot_access_at_index(input_buffer, 0))
+ {
+ input_buffer->offset--;
+ goto fail;
+ }
+
+ /* step back to character in front of the first element */
+ input_buffer->offset--;
+ /* loop through the comma separated array elements */
+ do
+ {
+ /* allocate next item */
+ cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks));
+ if (new_item == NULL)
+ {
+ goto fail; /* allocation failure */
+ }
+
+ /* attach next item to list */
+ if (head == NULL)
+ {
+ /* start the linked list */
+ current_item = head = new_item;
+ }
+ else
+ {
+ /* add to the end and advance */
+ current_item->next = new_item;
+ new_item->prev = current_item;
+ current_item = new_item;
+ }
+
+ /* parse next value */
+ input_buffer->offset++;
+ buffer_skip_whitespace(input_buffer);
+ if (!parse_value(current_item, input_buffer))
+ {
+ goto fail; /* failed to parse value */
+ }
+ buffer_skip_whitespace(input_buffer);
+ }
+ while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ','));
+
+ if (cannot_access_at_index(input_buffer, 0) || buffer_at_offset(input_buffer)[0] != ']')
+ {
+ goto fail; /* expected end of array */
+ }
+
+success:
+ input_buffer->depth--;
+
+ if (head != NULL) {
+ head->prev = current_item;
+ }
+
+ item->type = cJSON_Array;
+ item->child = head;
+
+ input_buffer->offset++;
+
+ return true;
+
+fail:
+ if (head != NULL)
+ {
+ cJSON_Delete(head);
+ }
+
+ return false;
+}
+
+/* Render an array to text */
+static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer)
+{
+ unsigned char *output_pointer = NULL;
+ size_t length = 0;
+ cJSON *current_element = item->child;
+
+ if (output_buffer == NULL)
+ {
+ return false;
+ }
+
+ if (output_buffer->depth >= CJSON_NESTING_LIMIT)
+ {
+ return false; /* nesting is too deep */
+ }
+
+ /* Compose the output array. */
+ /* opening square bracket */
+ output_pointer = ensure(output_buffer, 1);
+ if (output_pointer == NULL)
+ {
+ return false;
+ }
+
+ *output_pointer = '[';
+ output_buffer->offset++;
+ output_buffer->depth++;
+
+ while (current_element != NULL)
+ {
+ if (!print_value(current_element, output_buffer))
+ {
+ return false;
+ }
+ update_offset(output_buffer);
+ if (current_element->next)
+ {
+ length = (size_t) (output_buffer->format ? 2 : 1);
+ output_pointer = ensure(output_buffer, length + 1);
+ if (output_pointer == NULL)
+ {
+ return false;
+ }
+ *output_pointer++ = ',';
+ if(output_buffer->format)
+ {
+ *output_pointer++ = ' ';
+ }
+ *output_pointer = '\0';
+ output_buffer->offset += length;
+ }
+ current_element = current_element->next;
+ }
+
+ output_pointer = ensure(output_buffer, 2);
+ if (output_pointer == NULL)
+ {
+ return false;
+ }
+ *output_pointer++ = ']';
+ *output_pointer = '\0';
+ output_buffer->depth--;
+
+ return true;
+}
+
+/* Build an object from the text. */
+static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer)
+{
+ cJSON *head = NULL; /* linked list head */
+ cJSON *current_item = NULL;
+
+ if (input_buffer->depth >= CJSON_NESTING_LIMIT)
+ {
+ return false; /* to deeply nested */
+ }
+ input_buffer->depth++;
+
+ if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '{'))
+ {
+ goto fail; /* not an object */
+ }
+
+ input_buffer->offset++;
+ buffer_skip_whitespace(input_buffer);
+ if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '}'))
+ {
+ goto success; /* empty object */
+ }
+
+ /* check if we skipped to the end of the buffer */
+ if (cannot_access_at_index(input_buffer, 0))
+ {
+ input_buffer->offset--;
+ goto fail;
+ }
+
+ /* step back to character in front of the first element */
+ input_buffer->offset--;
+ /* loop through the comma separated array elements */
+ do
+ {
+ /* allocate next item */
+ cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks));
+ if (new_item == NULL)
+ {
+ goto fail; /* allocation failure */
+ }
+
+ /* attach next item to list */
+ if (head == NULL)
+ {
+ /* start the linked list */
+ current_item = head = new_item;
+ }
+ else
+ {
+ /* add to the end and advance */
+ current_item->next = new_item;
+ new_item->prev = current_item;
+ current_item = new_item;
+ }
+
+ if (cannot_access_at_index(input_buffer, 1))
+ {
+ goto fail; /* nothing comes after the comma */
+ }
+
+ /* parse the name of the child */
+ input_buffer->offset++;
+ buffer_skip_whitespace(input_buffer);
+ if (!parse_string(current_item, input_buffer))
+ {
+ goto fail; /* failed to parse name */
+ }
+ buffer_skip_whitespace(input_buffer);
+
+ /* swap valuestring and string, because we parsed the name */
+ current_item->string = current_item->valuestring;
+ current_item->valuestring = NULL;
+
+ if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != ':'))
+ {
+ goto fail; /* invalid object */
+ }
+
+ /* parse the value */
+ input_buffer->offset++;
+ buffer_skip_whitespace(input_buffer);
+ if (!parse_value(current_item, input_buffer))
+ {
+ goto fail; /* failed to parse value */
+ }
+ buffer_skip_whitespace(input_buffer);
+ }
+ while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ','));
+
+ if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '}'))
+ {
+ goto fail; /* expected end of object */
+ }
+
+success:
+ input_buffer->depth--;
+
+ if (head != NULL) {
+ head->prev = current_item;
+ }
+
+ item->type = cJSON_Object;
+ item->child = head;
+
+ input_buffer->offset++;
+ return true;
+
+fail:
+ if (head != NULL)
+ {
+ cJSON_Delete(head);
+ }
+
+ return false;
+}
+
+/* Render an object to text. */
+static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer)
+{
+ unsigned char *output_pointer = NULL;
+ size_t length = 0;
+ cJSON *current_item = item->child;
+
+ if (output_buffer == NULL)
+ {
+ return false;
+ }
+
+ if (output_buffer->depth >= CJSON_NESTING_LIMIT)
+ {
+ return false; /* nesting is too deep */
+ }
+
+ /* Compose the output: */
+ length = (size_t) (output_buffer->format ? 2 : 1); /* fmt: {\n */
+ output_pointer = ensure(output_buffer, length + 1);
+ if (output_pointer == NULL)
+ {
+ return false;
+ }
+
+ *output_pointer++ = '{';
+ output_buffer->depth++;
+ if (output_buffer->format)
+ {
+ *output_pointer++ = '\n';
+ }
+ output_buffer->offset += length;
+
+ while (current_item)
+ {
+ if (output_buffer->format)
+ {
+ size_t i;
+ output_pointer = ensure(output_buffer, output_buffer->depth);
+ if (output_pointer == NULL)
+ {
+ return false;
+ }
+ for (i = 0; i < output_buffer->depth; i++)
+ {
+ *output_pointer++ = '\t';
+ }
+ output_buffer->offset += output_buffer->depth;
+ }
+
+ /* print key */
+ if (!print_string_ptr((unsigned char*)current_item->string, output_buffer))
+ {
+ return false;
+ }
+ update_offset(output_buffer);
+
+ length = (size_t) (output_buffer->format ? 2 : 1);
+ output_pointer = ensure(output_buffer, length);
+ if (output_pointer == NULL)
+ {
+ return false;
+ }
+ *output_pointer++ = ':';
+ if (output_buffer->format)
+ {
+ *output_pointer++ = '\t';
+ }
+ output_buffer->offset += length;
+
+ /* print value */
+ if (!print_value(current_item, output_buffer))
+ {
+ return false;
+ }
+ update_offset(output_buffer);
+
+ /* print comma if not last */
+ length = ((size_t)(output_buffer->format ? 1 : 0) + (size_t)(current_item->next ? 1 : 0));
+ output_pointer = ensure(output_buffer, length + 1);
+ if (output_pointer == NULL)
+ {
+ return false;
+ }
+ if (current_item->next)
+ {
+ *output_pointer++ = ',';
+ }
+
+ if (output_buffer->format)
+ {
+ *output_pointer++ = '\n';
+ }
+ *output_pointer = '\0';
+ output_buffer->offset += length;
+
+ current_item = current_item->next;
+ }
+
+ output_pointer = ensure(output_buffer, output_buffer->format ? (output_buffer->depth + 1) : 2);
+ if (output_pointer == NULL)
+ {
+ return false;
+ }
+ if (output_buffer->format)
+ {
+ size_t i;
+ for (i = 0; i < (output_buffer->depth - 1); i++)
+ {
+ *output_pointer++ = '\t';
+ }
+ }
+ *output_pointer++ = '}';
+ *output_pointer = '\0';
+ output_buffer->depth--;
+
+ return true;
+}
+
+/* Get Array size/item / object item. */
+CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array)
+{
+ cJSON *child = NULL;
+ size_t size = 0;
+
+ if (array == NULL)
+ {
+ return 0;
+ }
+
+ child = array->child;
+
+ while(child != NULL)
+ {
+ size++;
+ child = child->next;
+ }
+
+ /* FIXME: Can overflow here. Cannot be fixed without breaking the API */
+
+ return (int)size;
+}
+
+static cJSON* get_array_item(const cJSON *array, size_t index)
+{
+ cJSON *current_child = NULL;
+
+ if (array == NULL)
+ {
+ return NULL;
+ }
+
+ current_child = array->child;
+ while ((current_child != NULL) && (index > 0))
+ {
+ index--;
+ current_child = current_child->next;
+ }
+
+ return current_child;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index)
+{
+ if (index < 0)
+ {
+ return NULL;
+ }
+
+ return get_array_item(array, (size_t)index);
+}
+
+static cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive)
+{
+ cJSON *current_element = NULL;
+
+ if ((object == NULL) || (name == NULL))
+ {
+ return NULL;
+ }
+
+ current_element = object->child;
+ if (case_sensitive)
+ {
+ while ((current_element != NULL) && (current_element->string != NULL) && (strcmp(name, current_element->string) != 0))
+ {
+ current_element = current_element->next;
+ }
+ }
+ else
+ {
+ while ((current_element != NULL) && (case_insensitive_strcmp((const unsigned char*)name, (const unsigned char*)(current_element->string)) != 0))
+ {
+ current_element = current_element->next;
+ }
+ }
+
+ if ((current_element == NULL) || (current_element->string == NULL)) {
+ return NULL;
+ }
+
+ return current_element;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string)
+{
+ return get_object_item(object, string, false);
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string)
+{
+ return get_object_item(object, string, true);
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string)
+{
+ return cJSON_GetObjectItem(object, string) ? 1 : 0;
+}
+
+/* Utility for array list handling. */
+static void suffix_object(cJSON *prev, cJSON *item)
+{
+ prev->next = item;
+ item->prev = prev;
+}
+
+/* Utility for handling references. */
+static cJSON *create_reference(const cJSON *item, const internal_hooks * const hooks)
+{
+ cJSON *reference = NULL;
+ if (item == NULL)
+ {
+ return NULL;
+ }
+
+ reference = cJSON_New_Item(hooks);
+ if (reference == NULL)
+ {
+ return NULL;
+ }
+
+ memcpy(reference, item, sizeof(cJSON));
+ reference->string = NULL;
+ reference->type |= cJSON_IsReference;
+ reference->next = reference->prev = NULL;
+ return reference;
+}
+
+static cJSON_bool add_item_to_array(cJSON *array, cJSON *item)
+{
+ cJSON *child = NULL;
+
+ if ((item == NULL) || (array == NULL) || (array == item))
+ {
+ return false;
+ }
+
+ child = array->child;
+ /*
+ * To find the last item in array quickly, we use prev in array
+ */
+ if (child == NULL)
+ {
+ /* list is empty, start new one */
+ array->child = item;
+ item->prev = item;
+ item->next = NULL;
+ }
+ else
+ {
+ /* append to the end */
+ if (child->prev)
+ {
+ suffix_object(child->prev, item);
+ array->child->prev = item;
+ }
+ }
+
+ return true;
+}
+
+/* Add item to array/object. */
+CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item)
+{
+ return add_item_to_array(array, item);
+}
+
+#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
+ #pragma GCC diagnostic push
+#endif
+#ifdef __GNUC__
+#pragma GCC diagnostic ignored "-Wcast-qual"
+#endif
+/* helper function to cast away const */
+static void* cast_away_const(const void* string)
+{
+ return (void*)string;
+}
+#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5))))
+ #pragma GCC diagnostic pop
+#endif
+
+
+static cJSON_bool add_item_to_object(cJSON * const object, const char * const string, cJSON * const item, const internal_hooks * const hooks, const cJSON_bool constant_key)
+{
+ char *new_key = NULL;
+ int new_type = cJSON_Invalid;
+
+ if ((object == NULL) || (string == NULL) || (item == NULL) || (object == item))
+ {
+ return false;
+ }
+
+ if (constant_key)
+ {
+ new_key = (char*)cast_away_const(string);
+ new_type = item->type | cJSON_StringIsConst;
+ }
+ else
+ {
+ new_key = (char*)cJSON_strdup((const unsigned char*)string, hooks);
+ if (new_key == NULL)
+ {
+ return false;
+ }
+
+ new_type = item->type & ~cJSON_StringIsConst;
+ }
+
+ if (!(item->type & cJSON_StringIsConst) && (item->string != NULL))
+ {
+ hooks->deallocate(item->string);
+ }
+
+ item->string = new_key;
+ item->type = new_type;
+
+ return add_item_to_array(object, item);
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item)
+{
+ return add_item_to_object(object, string, item, &global_hooks, false);
+}
+
+/* Add an item to an object with constant string as key */
+CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item)
+{
+ return add_item_to_object(object, string, item, &global_hooks, true);
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item)
+{
+ if (array == NULL)
+ {
+ return false;
+ }
+
+ return add_item_to_array(array, create_reference(item, &global_hooks));
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item)
+{
+ if ((object == NULL) || (string == NULL))
+ {
+ return false;
+ }
+
+ return add_item_to_object(object, string, create_reference(item, &global_hooks), &global_hooks, false);
+}
+
+CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name)
+{
+ cJSON *null = cJSON_CreateNull();
+ if (add_item_to_object(object, name, null, &global_hooks, false))
+ {
+ return null;
+ }
+
+ cJSON_Delete(null);
+ return NULL;
+}
+
+CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name)
+{
+ cJSON *true_item = cJSON_CreateTrue();
+ if (add_item_to_object(object, name, true_item, &global_hooks, false))
+ {
+ return true_item;
+ }
+
+ cJSON_Delete(true_item);
+ return NULL;
+}
+
+CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name)
+{
+ cJSON *false_item = cJSON_CreateFalse();
+ if (add_item_to_object(object, name, false_item, &global_hooks, false))
+ {
+ return false_item;
+ }
+
+ cJSON_Delete(false_item);
+ return NULL;
+}
+
+CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean)
+{
+ cJSON *bool_item = cJSON_CreateBool(boolean);
+ if (add_item_to_object(object, name, bool_item, &global_hooks, false))
+ {
+ return bool_item;
+ }
+
+ cJSON_Delete(bool_item);
+ return NULL;
+}
+
+CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number)
+{
+ cJSON *number_item = cJSON_CreateNumber(number);
+ if (add_item_to_object(object, name, number_item, &global_hooks, false))
+ {
+ return number_item;
+ }
+
+ cJSON_Delete(number_item);
+ return NULL;
+}
+
+CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string)
+{
+ cJSON *string_item = cJSON_CreateString(string);
+ if (add_item_to_object(object, name, string_item, &global_hooks, false))
+ {
+ return string_item;
+ }
+
+ cJSON_Delete(string_item);
+ return NULL;
+}
+
+CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw)
+{
+ cJSON *raw_item = cJSON_CreateRaw(raw);
+ if (add_item_to_object(object, name, raw_item, &global_hooks, false))
+ {
+ return raw_item;
+ }
+
+ cJSON_Delete(raw_item);
+ return NULL;
+}
+
+CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name)
+{
+ cJSON *object_item = cJSON_CreateObject();
+ if (add_item_to_object(object, name, object_item, &global_hooks, false))
+ {
+ return object_item;
+ }
+
+ cJSON_Delete(object_item);
+ return NULL;
+}
+
+CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name)
+{
+ cJSON *array = cJSON_CreateArray();
+ if (add_item_to_object(object, name, array, &global_hooks, false))
+ {
+ return array;
+ }
+
+ cJSON_Delete(array);
+ return NULL;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item)
+{
+ if ((parent == NULL) || (item == NULL) || (item != parent->child && item->prev == NULL))
+ {
+ return NULL;
+ }
+
+ if (item != parent->child)
+ {
+ /* not the first element */
+ item->prev->next = item->next;
+ }
+ if (item->next != NULL)
+ {
+ /* not the last element */
+ item->next->prev = item->prev;
+ }
+
+ if (item == parent->child)
+ {
+ /* first element */
+ parent->child = item->next;
+ }
+ else if (item->next == NULL)
+ {
+ /* last element */
+ parent->child->prev = item->prev;
+ }
+
+ /* make sure the detached item doesn't point anywhere anymore */
+ item->prev = NULL;
+ item->next = NULL;
+
+ return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which)
+{
+ if (which < 0)
+ {
+ return NULL;
+ }
+
+ return cJSON_DetachItemViaPointer(array, get_array_item(array, (size_t)which));
+}
+
+CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which)
+{
+ cJSON_Delete(cJSON_DetachItemFromArray(array, which));
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string)
+{
+ cJSON *to_detach = cJSON_GetObjectItem(object, string);
+
+ return cJSON_DetachItemViaPointer(object, to_detach);
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string)
+{
+ cJSON *to_detach = cJSON_GetObjectItemCaseSensitive(object, string);
+
+ return cJSON_DetachItemViaPointer(object, to_detach);
+}
+
+CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string)
+{
+ cJSON_Delete(cJSON_DetachItemFromObject(object, string));
+}
+
+CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string)
+{
+ cJSON_Delete(cJSON_DetachItemFromObjectCaseSensitive(object, string));
+}
+
+/* Replace array/object items with new ones. */
+CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem)
+{
+ cJSON *after_inserted = NULL;
+
+ if (which < 0 || newitem == NULL)
+ {
+ return false;
+ }
+
+ after_inserted = get_array_item(array, (size_t)which);
+ if (after_inserted == NULL)
+ {
+ return add_item_to_array(array, newitem);
+ }
+
+ if (after_inserted != array->child && after_inserted->prev == NULL) {
+ /* return false if after_inserted is a corrupted array item */
+ return false;
+ }
+
+ newitem->next = after_inserted;
+ newitem->prev = after_inserted->prev;
+ after_inserted->prev = newitem;
+ if (after_inserted == array->child)
+ {
+ array->child = newitem;
+ }
+ else
+ {
+ newitem->prev->next = newitem;
+ }
+ return true;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement)
+{
+ if ((parent == NULL) || (parent->child == NULL) || (replacement == NULL) || (item == NULL))
+ {
+ return false;
+ }
+
+ if (replacement == item)
+ {
+ return true;
+ }
+
+ replacement->next = item->next;
+ replacement->prev = item->prev;
+
+ if (replacement->next != NULL)
+ {
+ replacement->next->prev = replacement;
+ }
+ if (parent->child == item)
+ {
+ if (parent->child->prev == parent->child)
+ {
+ replacement->prev = replacement;
+ }
+ parent->child = replacement;
+ }
+ else
+ { /*
+ * To find the last item in array quickly, we use prev in array.
+ * We can't modify the last item's next pointer where this item was the parent's child
+ */
+ if (replacement->prev != NULL)
+ {
+ replacement->prev->next = replacement;
+ }
+ if (replacement->next == NULL)
+ {
+ parent->child->prev = replacement;
+ }
+ }
+
+ item->next = NULL;
+ item->prev = NULL;
+ cJSON_Delete(item);
+
+ return true;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem)
+{
+ if (which < 0)
+ {
+ return false;
+ }
+
+ return cJSON_ReplaceItemViaPointer(array, get_array_item(array, (size_t)which), newitem);
+}
+
+static cJSON_bool replace_item_in_object(cJSON *object, const char *string, cJSON *replacement, cJSON_bool case_sensitive)
+{
+ if ((replacement == NULL) || (string == NULL))
+ {
+ return false;
+ }
+
+ /* replace the name in the replacement */
+ if (!(replacement->type & cJSON_StringIsConst) && (replacement->string != NULL))
+ {
+ cJSON_free(replacement->string);
+ }
+ replacement->string = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks);
+ if (replacement->string == NULL)
+ {
+ return false;
+ }
+
+ replacement->type &= ~cJSON_StringIsConst;
+
+ return cJSON_ReplaceItemViaPointer(object, get_object_item(object, string, case_sensitive), replacement);
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem)
+{
+ return replace_item_in_object(object, string, newitem, false);
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, const char *string, cJSON *newitem)
+{
+ return replace_item_in_object(object, string, newitem, true);
+}
+
+/* Create basic types: */
+CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void)
+{
+ cJSON *item = cJSON_New_Item(&global_hooks);
+ if(item)
+ {
+ item->type = cJSON_NULL;
+ }
+
+ return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void)
+{
+ cJSON *item = cJSON_New_Item(&global_hooks);
+ if(item)
+ {
+ item->type = cJSON_True;
+ }
+
+ return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void)
+{
+ cJSON *item = cJSON_New_Item(&global_hooks);
+ if(item)
+ {
+ item->type = cJSON_False;
+ }
+
+ return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean)
+{
+ cJSON *item = cJSON_New_Item(&global_hooks);
+ if(item)
+ {
+ item->type = boolean ? cJSON_True : cJSON_False;
+ }
+
+ return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num)
+{
+ cJSON *item = cJSON_New_Item(&global_hooks);
+ if(item)
+ {
+ item->type = cJSON_Number;
+ item->valuedouble = num;
+
+ /* use saturation in case of overflow */
+ if (num >= INT_MAX)
+ {
+ item->valueint = INT_MAX;
+ }
+ else if (num <= (double)INT_MIN)
+ {
+ item->valueint = INT_MIN;
+ }
+ else
+ {
+ item->valueint = (int)num;
+ }
+ }
+
+ return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string)
+{
+ cJSON *item = cJSON_New_Item(&global_hooks);
+ if(item)
+ {
+ item->type = cJSON_String;
+ item->valuestring = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks);
+ if(!item->valuestring)
+ {
+ cJSON_Delete(item);
+ return NULL;
+ }
+ }
+
+ return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string)
+{
+ cJSON *item = cJSON_New_Item(&global_hooks);
+ if (item != NULL)
+ {
+ item->type = cJSON_String | cJSON_IsReference;
+ item->valuestring = (char*)cast_away_const(string);
+ }
+
+ return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child)
+{
+ cJSON *item = cJSON_New_Item(&global_hooks);
+ if (item != NULL) {
+ item->type = cJSON_Object | cJSON_IsReference;
+ item->child = (cJSON*)cast_away_const(child);
+ }
+
+ return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child) {
+ cJSON *item = cJSON_New_Item(&global_hooks);
+ if (item != NULL) {
+ item->type = cJSON_Array | cJSON_IsReference;
+ item->child = (cJSON*)cast_away_const(child);
+ }
+
+ return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw)
+{
+ cJSON *item = cJSON_New_Item(&global_hooks);
+ if(item)
+ {
+ item->type = cJSON_Raw;
+ item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw, &global_hooks);
+ if(!item->valuestring)
+ {
+ cJSON_Delete(item);
+ return NULL;
+ }
+ }
+
+ return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void)
+{
+ cJSON *item = cJSON_New_Item(&global_hooks);
+ if(item)
+ {
+ item->type=cJSON_Array;
+ }
+
+ return item;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void)
+{
+ cJSON *item = cJSON_New_Item(&global_hooks);
+ if (item)
+ {
+ item->type = cJSON_Object;
+ }
+
+ return item;
+}
+
+/* Create Arrays: */
+CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count)
+{
+ size_t i = 0;
+ cJSON *n = NULL;
+ cJSON *p = NULL;
+ cJSON *a = NULL;
+
+ if ((count < 0) || (numbers == NULL))
+ {
+ return NULL;
+ }
+
+ a = cJSON_CreateArray();
+
+ for(i = 0; a && (i < (size_t)count); i++)
+ {
+ n = cJSON_CreateNumber(numbers[i]);
+ if (!n)
+ {
+ cJSON_Delete(a);
+ return NULL;
+ }
+ if(!i)
+ {
+ a->child = n;
+ }
+ else
+ {
+ suffix_object(p, n);
+ }
+ p = n;
+ }
+
+ if (a && a->child) {
+ a->child->prev = n;
+ }
+
+ return a;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count)
+{
+ size_t i = 0;
+ cJSON *n = NULL;
+ cJSON *p = NULL;
+ cJSON *a = NULL;
+
+ if ((count < 0) || (numbers == NULL))
+ {
+ return NULL;
+ }
+
+ a = cJSON_CreateArray();
+
+ for(i = 0; a && (i < (size_t)count); i++)
+ {
+ n = cJSON_CreateNumber((double)numbers[i]);
+ if(!n)
+ {
+ cJSON_Delete(a);
+ return NULL;
+ }
+ if(!i)
+ {
+ a->child = n;
+ }
+ else
+ {
+ suffix_object(p, n);
+ }
+ p = n;
+ }
+
+ if (a && a->child) {
+ a->child->prev = n;
+ }
+
+ return a;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count)
+{
+ size_t i = 0;
+ cJSON *n = NULL;
+ cJSON *p = NULL;
+ cJSON *a = NULL;
+
+ if ((count < 0) || (numbers == NULL))
+ {
+ return NULL;
+ }
+
+ a = cJSON_CreateArray();
+
+ for(i = 0; a && (i < (size_t)count); i++)
+ {
+ n = cJSON_CreateNumber(numbers[i]);
+ if(!n)
+ {
+ cJSON_Delete(a);
+ return NULL;
+ }
+ if(!i)
+ {
+ a->child = n;
+ }
+ else
+ {
+ suffix_object(p, n);
+ }
+ p = n;
+ }
+
+ if (a && a->child) {
+ a->child->prev = n;
+ }
+
+ return a;
+}
+
+CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count)
+{
+ size_t i = 0;
+ cJSON *n = NULL;
+ cJSON *p = NULL;
+ cJSON *a = NULL;
+
+ if ((count < 0) || (strings == NULL))
+ {
+ return NULL;
+ }
+
+ a = cJSON_CreateArray();
+
+ for (i = 0; a && (i < (size_t)count); i++)
+ {
+ n = cJSON_CreateString(strings[i]);
+ if(!n)
+ {
+ cJSON_Delete(a);
+ return NULL;
+ }
+ if(!i)
+ {
+ a->child = n;
+ }
+ else
+ {
+ suffix_object(p,n);
+ }
+ p = n;
+ }
+
+ if (a && a->child) {
+ a->child->prev = n;
+ }
+
+ return a;
+}
+
+/* Duplication */
+cJSON * cJSON_Duplicate_rec(const cJSON *item, size_t depth, cJSON_bool recurse);
+
+CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse)
+{
+ return cJSON_Duplicate_rec(item, 0, recurse );
+}
+
+cJSON * cJSON_Duplicate_rec(const cJSON *item, size_t depth, cJSON_bool recurse)
+{
+ cJSON *newitem = NULL;
+ cJSON *child = NULL;
+ cJSON *next = NULL;
+ cJSON *newchild = NULL;
+
+ /* Bail on bad ptr */
+ if (!item)
+ {
+ goto fail;
+ }
+ /* Create new item */
+ newitem = cJSON_New_Item(&global_hooks);
+ if (!newitem)
+ {
+ goto fail;
+ }
+ /* Copy over all vars */
+ newitem->type = item->type & (~cJSON_IsReference);
+ newitem->valueint = item->valueint;
+ newitem->valuedouble = item->valuedouble;
+ if (item->valuestring)
+ {
+ newitem->valuestring = (char*)cJSON_strdup((unsigned char*)item->valuestring, &global_hooks);
+ if (!newitem->valuestring)
+ {
+ goto fail;
+ }
+ }
+ if (item->string)
+ {
+ newitem->string = (item->type&cJSON_StringIsConst) ? item->string : (char*)cJSON_strdup((unsigned char*)item->string, &global_hooks);
+ if (!newitem->string)
+ {
+ goto fail;
+ }
+ }
+ /* If non-recursive, then we're done! */
+ if (!recurse)
+ {
+ return newitem;
+ }
+ /* Walk the ->next chain for the child. */
+ child = item->child;
+ while (child != NULL)
+ {
+ if(depth >= CJSON_CIRCULAR_LIMIT) {
+ goto fail;
+ }
+ newchild = cJSON_Duplicate_rec(child, depth + 1, true); /* Duplicate (with recurse) each item in the ->next chain */
+ if (!newchild)
+ {
+ goto fail;
+ }
+ if (next != NULL)
+ {
+ /* If newitem->child already set, then crosswire ->prev and ->next and move on */
+ next->next = newchild;
+ newchild->prev = next;
+ next = newchild;
+ }
+ else
+ {
+ /* Set newitem->child and move to it */
+ newitem->child = newchild;
+ next = newchild;
+ }
+ child = child->next;
+ }
+ if (newitem && newitem->child)
+ {
+ newitem->child->prev = newchild;
+ }
+
+ return newitem;
+
+fail:
+ if (newitem != NULL)
+ {
+ cJSON_Delete(newitem);
+ }
+
+ return NULL;
+}
+
+static void skip_oneline_comment(char **input)
+{
+ *input += static_strlen("//");
+
+ for (; (*input)[0] != '\0'; ++(*input))
+ {
+ if ((*input)[0] == '\n') {
+ *input += static_strlen("\n");
+ return;
+ }
+ }
+}
+
+static void skip_multiline_comment(char **input)
+{
+ *input += static_strlen("/*");
+
+ for (; (*input)[0] != '\0'; ++(*input))
+ {
+ if (((*input)[0] == '*') && ((*input)[1] == '/'))
+ {
+ *input += static_strlen("*/");
+ return;
+ }
+ }
+}
+
+static void minify_string(char **input, char **output) {
+ (*output)[0] = (*input)[0];
+ *input += static_strlen("\"");
+ *output += static_strlen("\"");
+
+
+ for (; (*input)[0] != '\0'; (void)++(*input), ++(*output)) {
+ (*output)[0] = (*input)[0];
+
+ if ((*input)[0] == '\"') {
+ (*output)[0] = '\"';
+ *input += static_strlen("\"");
+ *output += static_strlen("\"");
+ return;
+ } else if (((*input)[0] == '\\') && ((*input)[1] == '\"')) {
+ (*output)[1] = (*input)[1];
+ *input += static_strlen("\"");
+ *output += static_strlen("\"");
+ }
+ }
+}
+
+CJSON_PUBLIC(void) cJSON_Minify(char *json)
+{
+ char *into = json;
+
+ if (json == NULL)
+ {
+ return;
+ }
+
+ while (json[0] != '\0')
+ {
+ switch (json[0])
+ {
+ case ' ':
+ case '\t':
+ case '\r':
+ case '\n':
+ json++;
+ break;
+
+ case '/':
+ if (json[1] == '/')
+ {
+ skip_oneline_comment(&json);
+ }
+ else if (json[1] == '*')
+ {
+ skip_multiline_comment(&json);
+ } else {
+ json++;
+ }
+ break;
+
+ case '\"':
+ minify_string(&json, (char**)&into);
+ break;
+
+ default:
+ into[0] = json[0];
+ json++;
+ into++;
+ }
+ }
+
+ /* and null-terminate. */
+ *into = '\0';
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item)
+{
+ if (item == NULL)
+ {
+ return false;
+ }
+
+ return (item->type & 0xFF) == cJSON_Invalid;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item)
+{
+ if (item == NULL)
+ {
+ return false;
+ }
+
+ return (item->type & 0xFF) == cJSON_False;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item)
+{
+ if (item == NULL)
+ {
+ return false;
+ }
+
+ return (item->type & 0xff) == cJSON_True;
+}
+
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item)
+{
+ if (item == NULL)
+ {
+ return false;
+ }
+
+ return (item->type & (cJSON_True | cJSON_False)) != 0;
+}
+CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item)
+{
+ if (item == NULL)
+ {
+ return false;
+ }
+
+ return (item->type & 0xFF) == cJSON_NULL;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item)
+{
+ if (item == NULL)
+ {
+ return false;
+ }
+
+ return (item->type & 0xFF) == cJSON_Number;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item)
+{
+ if (item == NULL)
+ {
+ return false;
+ }
+
+ return (item->type & 0xFF) == cJSON_String;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item)
+{
+ if (item == NULL)
+ {
+ return false;
+ }
+
+ return (item->type & 0xFF) == cJSON_Array;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item)
+{
+ if (item == NULL)
+ {
+ return false;
+ }
+
+ return (item->type & 0xFF) == cJSON_Object;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item)
+{
+ if (item == NULL)
+ {
+ return false;
+ }
+
+ return (item->type & 0xFF) == cJSON_Raw;
+}
+
+CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive)
+{
+ if ((a == NULL) || (b == NULL) || ((a->type & 0xFF) != (b->type & 0xFF)))
+ {
+ return false;
+ }
+
+ /* check if type is valid */
+ switch (a->type & 0xFF)
+ {
+ case cJSON_False:
+ case cJSON_True:
+ case cJSON_NULL:
+ case cJSON_Number:
+ case cJSON_String:
+ case cJSON_Raw:
+ case cJSON_Array:
+ case cJSON_Object:
+ break;
+
+ default:
+ return false;
+ }
+
+ /* identical objects are equal */
+ if (a == b)
+ {
+ return true;
+ }
+
+ switch (a->type & 0xFF)
+ {
+ /* in these cases and equal type is enough */
+ case cJSON_False:
+ case cJSON_True:
+ case cJSON_NULL:
+ return true;
+
+ case cJSON_Number:
+ if (compare_double(a->valuedouble, b->valuedouble))
+ {
+ return true;
+ }
+ return false;
+
+ case cJSON_String:
+ case cJSON_Raw:
+ if ((a->valuestring == NULL) || (b->valuestring == NULL))
+ {
+ return false;
+ }
+ if (strcmp(a->valuestring, b->valuestring) == 0)
+ {
+ return true;
+ }
+
+ return false;
+
+ case cJSON_Array:
+ {
+ cJSON *a_element = a->child;
+ cJSON *b_element = b->child;
+
+ for (; (a_element != NULL) && (b_element != NULL);)
+ {
+ if (!cJSON_Compare(a_element, b_element, case_sensitive))
+ {
+ return false;
+ }
+
+ a_element = a_element->next;
+ b_element = b_element->next;
+ }
+
+ /* one of the arrays is longer than the other */
+ if (a_element != b_element) {
+ return false;
+ }
+
+ return true;
+ }
+
+ case cJSON_Object:
+ {
+ cJSON *a_element = NULL;
+ cJSON *b_element = NULL;
+ cJSON_ArrayForEach(a_element, a)
+ {
+ /* TODO This has O(n^2) runtime, which is horrible! */
+ b_element = get_object_item(b, a_element->string, case_sensitive);
+ if (b_element == NULL)
+ {
+ return false;
+ }
+
+ if (!cJSON_Compare(a_element, b_element, case_sensitive))
+ {
+ return false;
+ }
+ }
+
+ /* doing this twice, once on a and b to prevent true comparison if a subset of b
+ * TODO: Do this the proper way, this is just a fix for now */
+ cJSON_ArrayForEach(b_element, b)
+ {
+ a_element = get_object_item(a, b_element->string, case_sensitive);
+ if (a_element == NULL)
+ {
+ return false;
+ }
+
+ if (!cJSON_Compare(b_element, a_element, case_sensitive))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ default:
+ return false;
+ }
+}
+
+CJSON_PUBLIC(void *) cJSON_malloc(size_t size)
+{
+ return global_hooks.allocate(size);
+}
+
+CJSON_PUBLIC(void) cJSON_free(void *object)
+{
+ global_hooks.deallocate(object);
+ object = NULL;
+}
diff --git a/vendor/cJSON.h b/vendor/cJSON.h
new file mode 100644
index 0000000..cab5feb
--- /dev/null
+++ b/vendor/cJSON.h
@@ -0,0 +1,306 @@
+/*
+ Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
+
+ 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.
+*/
+
+#ifndef cJSON__h
+#define cJSON__h
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+#if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32))
+#define __WINDOWS__
+#endif
+
+#ifdef __WINDOWS__
+
+/* When compiling for windows, we specify a specific calling convention to avoid issues where we are being called from a project with a different default calling convention. For windows you have 3 define options:
+
+CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols
+CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default)
+CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol
+
+For *nix builds that support visibility attribute, you can define similar behavior by
+
+setting default visibility to hidden by adding
+-fvisibility=hidden (for gcc)
+or
+-xldscope=hidden (for sun cc)
+to CFLAGS
+
+then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJSON_EXPORT_SYMBOLS does
+
+*/
+
+#define CJSON_CDECL __cdecl
+#define CJSON_STDCALL __stdcall
+
+/* export symbols by default, this is necessary for copy pasting the C and header file */
+#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS)
+#define CJSON_EXPORT_SYMBOLS
+#endif
+
+#if defined(CJSON_HIDE_SYMBOLS)
+#define CJSON_PUBLIC(type) type CJSON_STDCALL
+#elif defined(CJSON_EXPORT_SYMBOLS)
+#define CJSON_PUBLIC(type) __declspec(dllexport) type CJSON_STDCALL
+#elif defined(CJSON_IMPORT_SYMBOLS)
+#define CJSON_PUBLIC(type) __declspec(dllimport) type CJSON_STDCALL
+#endif
+#else /* !__WINDOWS__ */
+#define CJSON_CDECL
+#define CJSON_STDCALL
+
+#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY)
+#define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type
+#else
+#define CJSON_PUBLIC(type) type
+#endif
+#endif
+
+/* project version */
+#define CJSON_VERSION_MAJOR 1
+#define CJSON_VERSION_MINOR 7
+#define CJSON_VERSION_PATCH 19
+
+#include <stddef.h>
+
+/* cJSON Types: */
+#define cJSON_Invalid (0)
+#define cJSON_False (1 << 0)
+#define cJSON_True (1 << 1)
+#define cJSON_NULL (1 << 2)
+#define cJSON_Number (1 << 3)
+#define cJSON_String (1 << 4)
+#define cJSON_Array (1 << 5)
+#define cJSON_Object (1 << 6)
+#define cJSON_Raw (1 << 7) /* raw json */
+
+#define cJSON_IsReference 256
+#define cJSON_StringIsConst 512
+
+/* The cJSON structure: */
+typedef struct cJSON
+{
+ /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
+ struct cJSON *next;
+ struct cJSON *prev;
+ /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */
+ struct cJSON *child;
+
+ /* The type of the item, as above. */
+ int type;
+
+ /* The item's string, if type==cJSON_String and type == cJSON_Raw */
+ char *valuestring;
+ /* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */
+ int valueint;
+ /* The item's number, if type==cJSON_Number */
+ double valuedouble;
+
+ /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
+ char *string;
+} cJSON;
+
+typedef struct cJSON_Hooks
+{
+ /* malloc/free are CDECL on Windows regardless of the default calling convention of the compiler, so ensure the hooks allow passing those functions directly. */
+ void *(CJSON_CDECL *malloc_fn)(size_t sz);
+ void (CJSON_CDECL *free_fn)(void *ptr);
+} cJSON_Hooks;
+
+typedef int cJSON_bool;
+
+/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them.
+ * This is to prevent stack overflows. */
+#ifndef CJSON_NESTING_LIMIT
+#define CJSON_NESTING_LIMIT 1000
+#endif
+
+/* Limits the length of circular references can be before cJSON rejects to parse them.
+ * This is to prevent stack overflows. */
+#ifndef CJSON_CIRCULAR_LIMIT
+#define CJSON_CIRCULAR_LIMIT 10000
+#endif
+
+/* returns the version of cJSON as a string */
+CJSON_PUBLIC(const char*) cJSON_Version(void);
+
+/* Supply malloc, realloc and free functions to cJSON */
+CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks);
+
+/* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */
+/* Supply a block of JSON, and this returns a cJSON object you can interrogate. */
+CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value);
+CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length);
+/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */
+/* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */
+CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated);
+CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated);
+
+/* Render a cJSON entity to text for transfer/storage. */
+CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item);
+/* Render a cJSON entity to text for transfer/storage without any formatting. */
+CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item);
+/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */
+CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt);
+/* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */
+/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */
+CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format);
+/* Delete a cJSON entity and all subentities. */
+CJSON_PUBLIC(void) cJSON_Delete(cJSON *item);
+
+/* Returns the number of items in an array (or object). */
+CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array);
+/* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */
+CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index);
+/* Get item "string" from object. Case insensitive. */
+CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string);
+CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string);
+CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string);
+/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */
+CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void);
+
+/* Check item type and return its value */
+CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item);
+CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item);
+
+/* These functions check the type of an item */
+CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item);
+CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item);
+CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item);
+CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item);
+CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item);
+CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item);
+CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item);
+CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item);
+CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item);
+CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item);
+
+/* These calls create a cJSON item of the appropriate type. */
+CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void);
+CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void);
+CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void);
+CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean);
+CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num);
+CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string);
+/* raw json */
+CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw);
+CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void);
+CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void);
+
+/* Create a string where valuestring references a string so
+ * it will not be freed by cJSON_Delete */
+CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string);
+/* Create an object/array that only references it's elements so
+ * they will not be freed by cJSON_Delete */
+CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child);
+CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child);
+
+/* These utilities create an Array of count items.
+ * The parameter count cannot be greater than the number of elements in the number array, otherwise array access will be out of bounds.*/
+CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count);
+CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count);
+CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count);
+CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count);
+
+/* Append item to the specified array/object. */
+CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item);
+CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item);
+/* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object.
+ * WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before
+ * writing to `item->string` */
+CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item);
+/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */
+CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);
+CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item);
+
+/* Remove/Detach items from Arrays/Objects. */
+CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item);
+CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which);
+CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which);
+CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string);
+CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string);
+CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string);
+CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string);
+
+/* Update array items. */
+CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */
+CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement);
+CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem);
+CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);
+CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem);
+
+/* Duplicate a cJSON item */
+CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse);
+/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will
+ * need to be released. With recurse!=0, it will duplicate any children connected to the item.
+ * The item->next and ->prev pointers are always zero on return from Duplicate. */
+/* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal.
+ * case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */
+CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive);
+
+/* Minify a strings, remove blank characters(such as ' ', '\t', '\r', '\n') from strings.
+ * The input pointer json cannot point to a read-only address area, such as a string constant,
+ * but should point to a readable and writable address area. */
+CJSON_PUBLIC(void) cJSON_Minify(char *json);
+
+/* Helper functions for creating and adding items to an object at the same time.
+ * They return the added item or NULL on failure. */
+CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name);
+CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name);
+CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name);
+CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean);
+CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number);
+CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string);
+CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw);
+CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name);
+CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name);
+
+/* When assigning an integer value, it needs to be propagated to valuedouble too. */
+#define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number))
+/* helper for the cJSON_SetNumberValue macro */
+CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number);
+#define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number))
+/* Change the valuestring of a cJSON_String object, only takes effect when type of object is cJSON_String */
+CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring);
+
+/* If the object is not a boolean type this does nothing and returns cJSON_Invalid else it returns the new type*/
+#define cJSON_SetBoolValue(object, boolValue) ( \
+ (object != NULL && ((object)->type & (cJSON_False|cJSON_True))) ? \
+ (object)->type=((object)->type &(~(cJSON_False|cJSON_True)))|((boolValue)?cJSON_True:cJSON_False) : \
+ cJSON_Invalid\
+)
+
+/* Macro for iterating over an array or object */
+#define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next)
+
+/* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */
+CJSON_PUBLIC(void *) cJSON_malloc(size_t size);
+CJSON_PUBLIC(void) cJSON_free(void *object);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif