[
  {
    "path": ".gitignore",
    "content": "### macOS ###\n# General\n.DS_Store\n.AppleDouble\n.LSOverride\n\n# Icon must end with two \\r\nIcon\n\n\n# Thumbnails\n._*\n\n# Files that might appear in the root of a volume\n.DocumentRevisions-V100\n.fseventsd\n.Spotlight-V100\n.TemporaryItems\n.Trashes\n.VolumeIcon.icns\n.com.apple.timemachine.donotpresent\n\n# Directories potentially created on remote AFP share\n.AppleDB\n.AppleDesktop\nNetwork Trash Folder\nTemporary Items\n.apdisk\n\n### Windows ###\n# Windows thumbnail cache files\nThumbs.db\nThumbs.db:encryptable\nehthumbs.db\nehthumbs_vista.db\n\n# Dump file\n*.stackdump\n\n# Folder config file\n[Dd]esktop.ini\n\n# Recycle Bin used on file shares\n$RECYCLE.BIN/\n\n# Windows Installer files\n*.cab\n*.msi\n*.msix\n*.msm\n*.msp\n\n# Windows shortcuts\n*.lnk\n\n### Xcode ###\n# Xcode\n#\n# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore\n\n## User settings\nxcuserdata/\n\n## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9)\n*.xcscmblueprint\n*.xccheckout\n\n## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4)\nbuild/\nDerivedData/\n*.moved-aside\n*.pbxuser\n!default.pbxuser\n*.mode1v3\n!default.mode1v3\n*.mode2v3\n!default.mode2v3\n*.perspectivev3\n!default.perspectivev3\n\n## Gcc Patch\n/*.gcno\n\n### Xcode Patch ###\n*.xcodeproj/*\n!*.xcodeproj/project.pbxproj\n!*.xcodeproj/xcshareddata/\n!*.xcworkspace/contents.xcworkspacedata\n**/xcshareddata/WorkspaceSettings.xcsettings\n\n### SwiftPackageManager ###\nPackages\n.build/\n.swiftpm/\nxcuserdata\nDerivedData/\n*.xcodeproj\n\n### Release ###\n\n/wechattweak-cli\n"
  },
  {
    "path": "CNAME",
    "content": "cli.tweaks.app"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "Makefile",
    "content": ".DEFAULT := build\n\nbuild:\n\tswift package purge-cache\n\tswift package clean\n\tswift build -c release --arch arm64 --arch x86_64\n\tcp .build/apple/Products/Release/wechattweak-cli .\n\nclean:\n\tswift package purge-cache\n\tswift package clean\n\trm -rf .build wechattweak-cli\n"
  },
  {
    "path": "Package.resolved",
    "content": "{\n  \"object\": {\n    \"pins\": [\n      {\n        \"package\": \"Alamofire\",\n        \"repositoryURL\": \"https://github.com/Alamofire/Alamofire\",\n        \"state\": {\n          \"branch\": null,\n          \"revision\": \"bc268c28fb170f494de9e9927c371b8342979ece\",\n          \"version\": \"5.7.1\"\n        }\n      },\n      {\n        \"package\": \"PromiseKit\",\n        \"repositoryURL\": \"https://github.com/mxcl/PromiseKit\",\n        \"state\": {\n          \"branch\": null,\n          \"revision\": \"8a98e31a47854d3180882c8068cc4d9381bf382d\",\n          \"version\": \"6.22.1\"\n        }\n      },\n      {\n        \"package\": \"swift-argument-parser\",\n        \"repositoryURL\": \"https://github.com/apple/swift-argument-parser\",\n        \"state\": {\n          \"branch\": null,\n          \"revision\": \"fee6933f37fde9a5e12a1e4aeaa93fe60116ff2a\",\n          \"version\": \"1.2.2\"\n        }\n      }\n    ]\n  },\n  \"version\": 1\n}\n"
  },
  {
    "path": "Package.swift",
    "content": "// swift-tools-version:5.5\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"WeChatTweak-CLI\",\n    platforms: [\n        .macOS(.v10_12)\n    ],\n    products: [\n        .executable(\n            name: \"wechattweak-cli\",\n            targets: [\n                \"WeChatTweak-CLI\"\n            ]\n        )\n    ],\n    dependencies: [\n        .package(url: \"https://github.com/Alamofire/Alamofire\", from: \"5.7.1\"),\n        .package(url: \"https://github.com/mxcl/PromiseKit\", from: \"6.22.1\"),\n        .package(url: \"https://github.com/apple/swift-argument-parser\", from: \"1.2.2\")\n    ],\n    targets: [\n        .executableTarget(\n            name: \"WeChatTweak-CLI\",\n            dependencies: [\n                \"Alamofire\",\n                \"PromiseKit\",\n                \"insert_dylib\",\n                .product(name: \"ArgumentParser\", package: \"swift-argument-parser\")\n            ]\n        ),\n        .systemLibrary(\n            name: \"insert_dylib\",\n            path: \"Sources/insert_dylib\"\n        )\n    ]\n)\n"
  },
  {
    "path": "README.md",
    "content": "# WeChatTweak-CLI\n\n## ⚠️ NOTICE ⚠️\n\nWeChatTweak-CLI is no longer maintained. To reduce maintenance cost and avoid confusion, the CLI features have been consolidated into [**WeChatTweak**](https://github.com/sunnyyoung/WeChatTweak), which will keep adapting to future WeChat client releases.\n\n## License\n\nThe [Apache License 2.0](LICENSE).\n"
  },
  {
    "path": "Sources/WeChatTweak-CLI/Command.swift",
    "content": "//\n//  Command.swift\n//\n//  Created by Sunny Young.\n//\n\nimport Foundation\nimport Alamofire\nimport PromiseKit\nimport ArgumentParser\nimport insert_dylib\n\nstruct Command {\n    static func check() -> Promise<Void> {\n        return getuid() == 0 ? .value(()) : .init(error: CLIError.permission)\n    }\n\n    static func cleanup() -> Guarantee<Void> {\n        return Guarantee { seal in\n            try? FileManager.default.removeItem(atPath: Temp.zip)\n            try? FileManager.default.removeItem(atPath: Temp.binary)\n            seal(())\n        }\n    }\n\n    static func backup() -> Promise<Void> {\n        print(\"------ Backup ------\")\n        return Promise { seal in\n            do {\n                if FileManager.default.fileExists(atPath: App.backup) {\n                    print(\"WeChat.bak exists, skip it...\")\n                } else {\n                    try FileManager.default.copyItem(atPath: App.binary, toPath: App.backup)\n                    print(\"Created WeChat.bak...\")\n                }\n                seal.fulfill(())\n            } catch {\n                seal.reject(error)\n            }\n        }\n    }\n\n    static func restore() -> Promise<Void> {\n        print(\"------ Restore ------\")\n        return Promise { seal in\n            do {\n                if FileManager.default.fileExists(atPath: App.backup) {\n                    try FileManager.default.removeItem(atPath: App.binary)\n                    try FileManager.default.moveItem(atPath: App.backup, toPath: App.binary)\n                    try? FileManager.default.removeItem(atPath: App.framework)\n                    print(\"Restored WeChat...\")\n                } else {\n                    print(\"WeChat.bak not exists, skip it...\")\n                }\n                seal.fulfill(())\n            } catch {\n                seal.reject(error)\n            }\n        }\n    }\n\n    static func download() -> Promise<Void> {\n        print(\"------ Download ------\")\n        return Promise { seal in\n            let destination: DownloadRequest.Destination = { _, _ in\n                return (.init(fileURLWithPath: Temp.zip), [.removePreviousFile])\n            }\n            AF.download(Constant.url, to: destination).response { response in\n                if let error = response.error {\n                    seal.reject(CLIError.downloading(error))\n                } else {\n                    seal.fulfill(())\n                }\n            }\n        }\n    }\n\n    static func unzip() -> Promise<Void> {\n        print(\"------ Unzip ------\")\n        return Command.execute(command: \"rm -rf \\(App.framework); unzip \\(Temp.zip) -d \\(App.macos)\")\n    }\n\n    static func insert() -> Promise<Void> {\n        print(\"------ Insert Dylib ------\")\n        return Promise { seal in\n            insert_dylib.insert(\"@executable_path/WeChatTweak.framework/WeChatTweak\", App.binary) == EXIT_SUCCESS ? seal.fulfill(()) : seal.reject(CLIError.insertDylib)\n        }\n    }\n\n    static func removeCodesign() -> Promise<Void> {\n        print(\"------ Remove Codesign ------\")\n        return Command.execute(command: \"codesign --remove-sign \\(App.binary)\")\n    }\n\n    static func addCodesign() -> Promise<Void> {\n        print(\"------ Add Codesign ------\")\n        return Command.execute(command: \"codesign --force --deep --sign - \\(App.binary)\")\n    }\n\n    static func resetPermission() -> Promise<Void> {\n        print(\"------ Reset ScreenCapture privacy permission ------\")\n        return Command.execute(command: \"tccutil reset ScreenCapture com.tencent.xinWeChat\")\n    }\n\n    private static func execute(command: String) -> Promise<Void> {\n        return Promise { seal in\n            print(\"Execute command: \\(command)\")\n            var error: NSDictionary?\n            guard let script = NSAppleScript(source: \"do shell script \\\"\\(command)\\\"\") else {\n                return seal.reject(CLIError.executing(command: command, error: [\"error\": \"Create script failed.\"]))\n            }\n            script.executeAndReturnError(&error)\n            if let error = error {\n                seal.reject(CLIError.executing(command: command, error: error))\n            } else {\n                seal.fulfill(())\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Sources/WeChatTweak-CLI/main.swift",
    "content": "//\n//  main.swift\n//\n//  Created by Sunny Young.\n//\n\nimport Foundation\nimport PromiseKit\nimport ArgumentParser\n\nstruct Constant {\n    static let url = URL(string: \"https://github.com/Sunnyyoung/WeChatTweak-macOS/releases/latest/download/WeChatTweak.framework.zip\")!\n}\n\nstruct App {\n    static let root = \"/Applications\"\n    static let app = root.appending(\"/WeChat.app\")\n    static let macos = app.appending(\"/Contents/MacOS\")\n    static let binary = app.appending(\"/Contents/MacOS/WeChat\")\n    static let backup = app.appending(\"/Contents/MacOS/WeChat.bak\")\n\n    static let framework = macos.appending(\"/WeChatTweak.framework\")\n}\n\nstruct Temp {\n    static let root = \"/tmp\"\n    static let binary = root.appending(\"/WeChat\")\n    static let zip = root.appending(\"/WeChatTweak.zip\")\n}\n\nenum CLIError: LocalizedError {\n    case permission\n    case downloading(Error)\n    case insertDylib\n    case executing(command: String, error: NSDictionary)\n\n    var errorDescription: String? {\n        switch self {\n        case .permission:\n            return \"Please run with `sudo`.\"\n        case let .downloading(error):\n            return \"Download failed with error: \\(error)\"\n        case .insertDylib:\n            return \"Insert dylib failed\"\n        case let .executing(command, error):\n            return \"Execute command: \\(command) failed: \\(error)\"\n        }\n    }\n}\n\nstruct Install: ParsableCommand {\n    static var configuration = CommandConfiguration(abstract: \"Install or upgrade tweak.\")\n\n    func run() throws {\n        firstly {\n            Command.check()\n        }.then {\n            Command.cleanup()\n        }.then {\n            Command.download()\n        }.then {\n            Command.unzip()\n        }.then {\n            Command.backup()\n        }.then {\n            Command.removeCodesign()\n        }.then {\n            Command.insert()\n        }.then {\n            Command.addCodesign()\n        }.then {\n            Command.resetPermission()\n        }.done {\n            print(\"Install success!\")\n        }.catch { error in\n            print(\"Install failed: \\(error.localizedDescription)\")\n        }.finally {\n            CFRunLoopStop(CFRunLoopGetCurrent())\n        }\n    }\n}\n\nstruct Uninstall: ParsableCommand {\n    static var configuration = CommandConfiguration(abstract: \"Uninstall tweak.\")\n\n    func run() throws {\n        firstly {\n            Command.check()\n        }.then {\n            Command.cleanup()\n        }.then {\n            Command.restore()\n        }.done {\n            print(\"Uninstall success!\")\n        }.catch { error in\n            print(\"Uninstall failed: \\(error)\")\n        }.finally {\n            CFRunLoopStop(CFRunLoopGetCurrent())\n        }\n    }\n}\n\nstruct Version: ParsableCommand {\n    static var configuration = CommandConfiguration(abstract: \"Get current version of WeChatTweak.\")\n\n    func run() throws {\n        return firstly {\n            getVersion()\n        }.done { version in\n            print(version ?? \"Unknown\")\n        }.catch { error in\n            print(\"Get version failed: \\(error)\")\n        }.finally {\n            CFRunLoopStop(CFRunLoopGetCurrent())\n        }\n    }\n\n    func getVersion() -> Promise<String?> {\n        return Promise { seal in\n            do {\n                let data = try Data(contentsOf: URL(fileURLWithPath: App.framework.appending(\"/Versions/A/Resources/Info.plist\")))\n                let info = try PropertyListSerialization.propertyList(from: data, options: [], format: nil)\n                seal.fulfill((info as? [String: Any])?[\"CFBundleShortVersionString\"] as? String)\n            } catch {\n                seal.reject(error)\n            }\n        }\n    }\n}\n\nstruct Resign: ParsableCommand {\n    static var configuration = CommandConfiguration(abstract: \"Force resign WeChat.app\")\n\n    func run() throws {\n        firstly {\n            Command.removeCodesign()\n        }.then {\n            Command.addCodesign()\n        }.catch { error in\n            print(\"Resign failed: \\(error.localizedDescription)\")\n        }.finally {\n            CFRunLoopStop(CFRunLoopGetCurrent())\n        }\n    }\n}\n\nstruct Tweak: ParsableCommand {\n    static var configuration = CommandConfiguration(\n        commandName: \"wechattweak-cli\",\n        abstract: \"A command line utility to work with WeChatTweak-macOS.\",\n        subcommands: [\n            Install.self,\n            Uninstall.self,\n            Resign.self,\n            Version.self\n        ],\n        defaultSubcommand: Self.self\n    )\n}\n\ndefer {\n    try? FileManager.default.removeItem(atPath: Temp.zip)\n    try? FileManager.default.removeItem(atPath: Temp.binary)\n}\n\nTweak.main()\nCFRunLoopRun()\n"
  },
  {
    "path": "Sources/insert_dylib/insert_dylib.h",
    "content": "#include <stdlib.h>\n#include <stdio.h>\n#include <stdbool.h>\n#include <stdarg.h>\n#include <string.h>\n#include <unistd.h>\n#include <getopt.h>\n#include <sys/stat.h>\n#include <sys/param.h>\n#include <copyfile.h>\n#include <mach-o/loader.h>\n#include <mach-o/fat.h>\n\n#define IS_64_BIT(x) ((x) == MH_MAGIC_64 || (x) == MH_CIGAM_64)\n#define IS_LITTLE_ENDIAN(x) ((x) == FAT_CIGAM || (x) == MH_CIGAM_64 || (x) == MH_CIGAM)\n#define SWAP32(x, magic) (IS_LITTLE_ENDIAN(magic)? OSSwapInt32(x): (x))\n#define SWAP64(x, magic) (IS_LITTLE_ENDIAN(magic)? OSSwapInt64(x): (x))\n\n#define ROUND_UP(x, y) (((x) + (y) - 1) & -(y))\n\n#define ABSDIFF(x, y) ((x) > (y)? (uintmax_t)(x) - (uintmax_t)(y): (uintmax_t)(y) - (uintmax_t)(x))\n\n#define BUFSIZE 512\n\nvoid fbzero(FILE *f, off_t offset, size_t len) {\n    static unsigned char zeros[BUFSIZE] = {0};\n    fseeko(f, offset, SEEK_SET);\n    while(len != 0) {\n        size_t size = MIN(len, sizeof(zeros));\n        fwrite(zeros, size, 1, f);\n        len -= size;\n    }\n}\n\nvoid fmemmove(FILE *f, off_t dst, off_t src, size_t len) {\n    static unsigned char buf[BUFSIZE];\n    while(len != 0) {\n        size_t size = MIN(len, sizeof(buf));\n        fseeko(f, src, SEEK_SET);\n        fread(&buf, size, 1, f);\n        fseeko(f, dst, SEEK_SET);\n        fwrite(buf, size, 1, f);\n\n        len -= size;\n        src += size;\n        dst += size;\n    }\n}\n\nint weak_flag = false;\n\nsize_t fpeek(void *restrict ptr, size_t size, size_t nitems, FILE *restrict stream) {\n    off_t pos = ftello(stream);\n    size_t result = fread(ptr, size, nitems, stream);\n    fseeko(stream, pos, SEEK_SET);\n    return result;\n}\n\nvoid *read_load_command(FILE *f, uint32_t cmdsize) {\n    void *lc = malloc(cmdsize);\n\n    fpeek(lc, cmdsize, 1, f);\n\n    return lc;\n}\n\nbool check_load_commands(FILE *f, struct mach_header *mh, size_t header_offset, size_t commands_offset, const char *dylib_path, off_t *slice_size) {\n    fseeko(f, commands_offset, SEEK_SET);\n\n    uint32_t ncmds = SWAP32(mh->ncmds, mh->magic);\n\n    off_t linkedit_32_pos = -1;\n    off_t linkedit_64_pos = -1;\n    struct segment_command linkedit_32;\n    struct segment_command_64 linkedit_64;\n\n    off_t symtab_pos = -1;\n    uint32_t symtab_size = 0;\n\n    for(int i = 0; i < ncmds; i++) {\n        struct load_command lc;\n        fpeek(&lc, sizeof(lc), 1, f);\n\n        uint32_t cmdsize = SWAP32(lc.cmdsize, mh->magic);\n        uint32_t cmd = SWAP32(lc.cmd, mh->magic);\n\n        switch(cmd) {\n            case LC_CODE_SIGNATURE:\n                if(i == ncmds - 1) {\n                    printf(\"LC_CODE_SIGNATURE load command found. Remove it.\\n\");\n\n                    struct linkedit_data_command *cmd = read_load_command(f, cmdsize);\n\n                    fbzero(f, ftello(f), cmdsize);\n\n                    uint32_t dataoff = SWAP32(cmd->dataoff, mh->magic);\n                    uint32_t datasize = SWAP32(cmd->datasize, mh->magic);\n\n                    free(cmd);\n\n                    uint64_t linkedit_fileoff = 0;\n                    uint64_t linkedit_filesize = 0;\n\n                    if(linkedit_32_pos != -1) {\n                        linkedit_fileoff = SWAP32(linkedit_32.fileoff, mh->magic);\n                        linkedit_filesize = SWAP32(linkedit_32.filesize, mh->magic);\n                    } else if(linkedit_64_pos != -1) {\n                        linkedit_fileoff = SWAP64(linkedit_64.fileoff, mh->magic);\n                        linkedit_filesize = SWAP64(linkedit_64.filesize, mh->magic);\n                    } else {\n                        fprintf(stderr, \"Warning: __LINKEDIT segment not found.\\n\");\n                    }\n\n                    if(linkedit_32_pos != -1 || linkedit_64_pos != -1) {\n                        if(linkedit_fileoff + linkedit_filesize != *slice_size) {\n                            fprintf(stderr, \"Warning: __LINKEDIT segment is not at the end of the file, so codesign will not work on the patched binary.\\n\");\n                        } else {\n                            if(dataoff + datasize != *slice_size) {\n                                fprintf(stderr, \"Warning: Codesignature is not at the end of __LINKEDIT segment, so codesign will not work on the patched binary.\\n\");\n                            } else {\n                                *slice_size -= datasize;\n                                //int64_t diff_size = 0;\n                                if(symtab_pos == -1) {\n                                    fprintf(stderr, \"Warning: LC_SYMTAB load command not found. codesign might not work on the patched binary.\\n\");\n                                } else {\n                                    fseeko(f, symtab_pos, SEEK_SET);\n                                    struct symtab_command *symtab = read_load_command(f, symtab_size);\n\n                                    uint32_t strsize = SWAP32(symtab->strsize, mh->magic);\n                                    int64_t diff_size = SWAP32(symtab->stroff, mh->magic) + strsize - (int64_t)*slice_size;\n                                    if(-0x10 <= diff_size && diff_size <= 0) {\n                                        symtab->strsize = SWAP32((uint32_t)(strsize - diff_size), mh->magic);\n                                        fwrite(symtab, symtab_size, 1, f);\n                                    } else {\n                                        fprintf(stderr, \"Warning: String table doesn't appear right before code signature. codesign might not work on the patched binary. (0x%llx)\\n\", diff_size);\n                                    }\n\n                                    free(symtab);\n                                }\n\n                                linkedit_filesize -= datasize;\n                                uint64_t linkedit_vmsize = ROUND_UP(linkedit_filesize, 0x1000);\n\n                                if(linkedit_32_pos != -1) {\n                                    linkedit_32.filesize = SWAP32((uint32_t)linkedit_filesize, mh->magic);\n                                    linkedit_32.vmsize = SWAP32((uint32_t)linkedit_vmsize, mh->magic);\n\n                                    fseeko(f, linkedit_32_pos, SEEK_SET);\n                                    fwrite(&linkedit_32, sizeof(linkedit_32), 1, f);\n                                } else {\n                                    linkedit_64.filesize = SWAP64(linkedit_filesize, mh->magic);\n                                    linkedit_64.vmsize = SWAP64(linkedit_vmsize, mh->magic);\n\n                                    fseeko(f, linkedit_64_pos, SEEK_SET);\n                                    fwrite(&linkedit_64, sizeof(linkedit_64), 1, f);\n                                }\n\n                                goto fix_header;\n                            }\n                        }\n                    }\n\n                    // If we haven't truncated the file, zero out the code signature\n                    fbzero(f, header_offset + dataoff, datasize);\n\n                fix_header:\n                    mh->ncmds = SWAP32(ncmds - 1, mh->magic);\n                    mh->sizeofcmds = SWAP32(SWAP32(mh->sizeofcmds, mh->magic) - cmdsize, mh->magic);\n\n                    return true;\n                } else {\n                    printf(\"LC_CODE_SIGNATURE is not the last load command, so couldn't remove.\\n\");\n                }\n                break;\n            case LC_LOAD_DYLIB:\n            case LC_LOAD_WEAK_DYLIB: {\n                struct dylib_command *dylib_command = read_load_command(f, cmdsize);\n\n                union lc_str offset = dylib_command->dylib.name;\n                char *name = &((char *)dylib_command)[SWAP32(offset.offset, mh->magic)];\n\n                int cmp = strcmp(name, dylib_path);\n\n                free(dylib_command);\n\n                if(cmp == 0) {\n                    printf(\"Binary already contains a load command for that dylib. Skip it.\\n\");\n                    return false;\n                }\n\n                break;\n            }\n            case LC_SEGMENT:\n            case LC_SEGMENT_64:\n                if(cmd == LC_SEGMENT) {\n                    struct segment_command *cmd = read_load_command(f, cmdsize);\n                    if(strcmp(cmd->segname, \"__LINKEDIT\") == 0) {\n                        linkedit_32_pos = ftello(f);\n                        linkedit_32 = *cmd;\n                    }\n                    free(cmd);\n                } else {\n                    struct segment_command_64 *cmd = read_load_command(f, cmdsize);\n                    if(strcmp(cmd->segname, \"__LINKEDIT\") == 0) {\n                        linkedit_64_pos = ftello(f);\n                        linkedit_64 = *cmd;\n                    }\n                    free(cmd);\n                }\n            case LC_SYMTAB:\n                symtab_pos = ftello(f);\n                symtab_size = cmdsize;\n        }\n\n        fseeko(f, SWAP32(lc.cmdsize, mh->magic), SEEK_CUR);\n    }\n\n    return true;\n}\n\nbool _insert_dylib(FILE *f, size_t header_offset, const char *dylib_path, off_t *slice_size) {\n    fseeko(f, header_offset, SEEK_SET);\n\n    struct mach_header mh;\n    fread(&mh, sizeof(struct mach_header), 1, f);\n\n    if(mh.magic != MH_MAGIC_64 && mh.magic != MH_CIGAM_64 && mh.magic != MH_MAGIC && mh.magic != MH_CIGAM) {\n        printf(\"Unknown magic: 0x%x\\n\", mh.magic);\n        return false;\n    }\n\n    size_t commands_offset = header_offset + (IS_64_BIT(mh.magic)? sizeof(struct mach_header_64): sizeof(struct mach_header));\n\n    bool cont = check_load_commands(f, &mh, header_offset, commands_offset, dylib_path, slice_size);\n\n    if(!cont) {\n        return true;\n    }\n\n    // Even though a padding of 4 works for x86_64, codesign doesn't like it\n    size_t path_padding = 8;\n\n    size_t dylib_path_len = strlen(dylib_path);\n    size_t dylib_path_size = (dylib_path_len & ~(path_padding - 1)) + path_padding;\n    uint32_t cmdsize = (uint32_t)(sizeof(struct dylib_command) + dylib_path_size);\n\n    struct dylib_command dylib_command = {\n        .cmd = SWAP32(weak_flag? LC_LOAD_WEAK_DYLIB: LC_LOAD_DYLIB, mh.magic),\n        .cmdsize = SWAP32(cmdsize, mh.magic),\n        .dylib = {\n            .name = SWAP32(sizeof(struct dylib_command), mh.magic),\n            .timestamp = 0,\n            .current_version = 0,\n            .compatibility_version = 0\n        }\n    };\n\n    uint32_t sizeofcmds = SWAP32(mh.sizeofcmds, mh.magic);\n\n    fseeko(f, commands_offset + sizeofcmds, SEEK_SET);\n    char space[cmdsize];\n\n    fread(&space, cmdsize, 1, f);\n\n    bool empty = true;\n    for(int i = 0; i < cmdsize; i++) {\n        if(space[i] != 0) {\n            empty = false;\n            break;\n        }\n    }\n\n    if(!empty) {\n        printf(\"It doesn't seem like there is enough empty space. Continue anyway.\");\n    }\n\n    fseeko(f, -((off_t)cmdsize), SEEK_CUR);\n\n    char *dylib_path_padded = calloc(dylib_path_size, 1);\n    memcpy(dylib_path_padded, dylib_path, dylib_path_len);\n\n    fwrite(&dylib_command, sizeof(dylib_command), 1, f);\n    fwrite(dylib_path_padded, dylib_path_size, 1, f);\n\n    free(dylib_path_padded);\n\n    mh.ncmds = SWAP32(SWAP32(mh.ncmds, mh.magic) + 1, mh.magic);\n    sizeofcmds += cmdsize;\n    mh.sizeofcmds = SWAP32(sizeofcmds, mh.magic);\n\n    fseeko(f, header_offset, SEEK_SET);\n    fwrite(&mh, sizeof(mh), 1, f);\n\n    return true;\n}\n\nint insert(const char *lib_path, const char *bin_path) {\n    const char *lc_name = weak_flag? \"LC_LOAD_WEAK_DYLIB\": \"LC_LOAD_DYLIB\";\n\n    struct stat s;\n\n    if(stat(bin_path, &s) != 0) {\n        perror(bin_path);\n        return EXIT_FAILURE;\n    }\n\n    if(lib_path[0] != '@' && stat(lib_path, &s) != 0) {\n        return EXIT_FAILURE;\n    }\n\n    FILE *f = fopen(bin_path, \"r+\");\n\n    if(!f) {\n        printf(\"Couldn't open file %s\\n\", bin_path);\n        return EXIT_FAILURE;\n    }\n\n    bool success = true;\n\n    fseeko(f, 0, SEEK_END);\n    off_t file_size = ftello(f);\n    rewind(f);\n\n    uint32_t magic;\n    fread(&magic, sizeof(uint32_t), 1, f);\n\n    switch(magic) {\n        case FAT_MAGIC:\n        case FAT_CIGAM: {\n            fseeko(f, 0, SEEK_SET);\n\n            struct fat_header fh;\n            fread(&fh, sizeof(fh), 1, f);\n\n            uint32_t nfat_arch = SWAP32(fh.nfat_arch, magic);\n\n            printf(\"Binary is a fat binary with %d archs.\\n\", nfat_arch);\n\n            struct fat_arch archs[nfat_arch];\n            fread(archs, sizeof(archs), 1, f);\n\n            int fails = 0;\n\n            uint32_t offset = 0;\n            if(nfat_arch > 0) {\n                offset = SWAP32(archs[0].offset, magic);\n            }\n\n            for(int i = 0; i < nfat_arch; i++) {\n                off_t orig_offset = SWAP32(archs[i].offset, magic);\n                off_t orig_slice_size = SWAP32(archs[i].size, magic);\n                offset = ROUND_UP(offset, 1 << SWAP32(archs[i].align, magic));\n                if(orig_offset != offset) {\n                    fmemmove(f, offset, orig_offset, orig_slice_size);\n                    fbzero(f, MIN(offset, orig_offset) + orig_slice_size, ABSDIFF(offset, orig_offset));\n\n                    archs[i].offset = SWAP32(offset, magic);\n                }\n\n                off_t slice_size = orig_slice_size;\n                bool r = _insert_dylib(f, offset, lib_path, &slice_size);\n                if(!r) {\n                    printf(\"Failed to add %s to arch #%d!\\n\", lc_name, i + 1);\n                    fails++;\n                }\n\n                if(slice_size < orig_slice_size && i < nfat_arch - 1) {\n                    fbzero(f, offset + slice_size, orig_slice_size - slice_size);\n                }\n\n                file_size = offset + slice_size;\n                offset += slice_size;\n                archs[i].size = SWAP32((uint32_t)slice_size, magic);\n            }\n\n            rewind(f);\n            fwrite(&fh, sizeof(fh), 1, f);\n            fwrite(archs, sizeof(archs), 1, f);\n\n            // We need to flush before truncating\n            fflush(f);\n            ftruncate(fileno(f), file_size);\n\n            if(fails == 0) {\n                printf(\"Added %s to all archs in %s\\n\", lc_name, bin_path);\n            } else if(fails == nfat_arch) {\n                printf(\"Failed to add %s to any archs.\\n\", lc_name);\n                success = false;\n            } else {\n                printf(\"Added %s to %d/%d archs in %s\\n\", lc_name, nfat_arch - fails, nfat_arch, bin_path);\n            }\n\n            break;\n        }\n        case MH_MAGIC_64:\n        case MH_CIGAM_64:\n        case MH_MAGIC:\n        case MH_CIGAM:\n            if(_insert_dylib(f, 0, lib_path, &file_size)) {\n                ftruncate(fileno(f), file_size);\n                printf(\"Added %s to %s\\n\", lc_name, bin_path);\n            } else {\n                printf(\"Failed to add %s!\\n\", lc_name);\n                success = false;\n            }\n            break;\n        default:\n            printf(\"Unknown magic: 0x%x\\n\", magic);\n            return EXIT_FAILURE;\n    }\n\n    fclose(f);\n\n    if(!success) {\n        unlink(bin_path);\n        return EXIT_FAILURE;\n    } else {\n        return EXIT_SUCCESS;\n    }\n}\n"
  },
  {
    "path": "Sources/insert_dylib/module.modulemap",
    "content": "module insert_dylib {\n  header \"insert_dylib.h\"\n  export *\n}\n"
  }
]