Repository: sunnyyoung/WeChatTweak-CLI
Branch: master
Commit: a90b370b6c27
Files: 11
Total size: 38.3 KB
Directory structure:
gitextract_827__s9_/
├── .gitignore
├── CNAME
├── LICENSE
├── Makefile
├── Package.resolved
├── Package.swift
├── README.md
└── Sources/
├── WeChatTweak-CLI/
│ ├── Command.swift
│ └── main.swift
└── insert_dylib/
├── insert_dylib.h
└── module.modulemap
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
### macOS ###
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
### Windows ###
# Windows thumbnail cache files
Thumbs.db
Thumbs.db:encryptable
ehthumbs.db
ehthumbs_vista.db
# Dump file
*.stackdump
# Folder config file
[Dd]esktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp
# Windows shortcuts
*.lnk
### Xcode ###
# Xcode
#
# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
## User settings
xcuserdata/
## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9)
*.xcscmblueprint
*.xccheckout
## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4)
build/
DerivedData/
*.moved-aside
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
## Gcc Patch
/*.gcno
### Xcode Patch ###
*.xcodeproj/*
!*.xcodeproj/project.pbxproj
!*.xcodeproj/xcshareddata/
!*.xcworkspace/contents.xcworkspacedata
**/xcshareddata/WorkspaceSettings.xcsettings
### SwiftPackageManager ###
Packages
.build/
.swiftpm/
xcuserdata
DerivedData/
*.xcodeproj
### Release ###
/wechattweak-cli
================================================
FILE: CNAME
================================================
cli.tweaks.app
================================================
FILE: LICENSE
================================================
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.
================================================
FILE: Makefile
================================================
.DEFAULT := build
build:
swift package purge-cache
swift package clean
swift build -c release --arch arm64 --arch x86_64
cp .build/apple/Products/Release/wechattweak-cli .
clean:
swift package purge-cache
swift package clean
rm -rf .build wechattweak-cli
================================================
FILE: Package.resolved
================================================
{
"object": {
"pins": [
{
"package": "Alamofire",
"repositoryURL": "https://github.com/Alamofire/Alamofire",
"state": {
"branch": null,
"revision": "bc268c28fb170f494de9e9927c371b8342979ece",
"version": "5.7.1"
}
},
{
"package": "PromiseKit",
"repositoryURL": "https://github.com/mxcl/PromiseKit",
"state": {
"branch": null,
"revision": "8a98e31a47854d3180882c8068cc4d9381bf382d",
"version": "6.22.1"
}
},
{
"package": "swift-argument-parser",
"repositoryURL": "https://github.com/apple/swift-argument-parser",
"state": {
"branch": null,
"revision": "fee6933f37fde9a5e12a1e4aeaa93fe60116ff2a",
"version": "1.2.2"
}
}
]
},
"version": 1
}
================================================
FILE: Package.swift
================================================
// swift-tools-version:5.5
import PackageDescription
let package = Package(
name: "WeChatTweak-CLI",
platforms: [
.macOS(.v10_12)
],
products: [
.executable(
name: "wechattweak-cli",
targets: [
"WeChatTweak-CLI"
]
)
],
dependencies: [
.package(url: "https://github.com/Alamofire/Alamofire", from: "5.7.1"),
.package(url: "https://github.com/mxcl/PromiseKit", from: "6.22.1"),
.package(url: "https://github.com/apple/swift-argument-parser", from: "1.2.2")
],
targets: [
.executableTarget(
name: "WeChatTweak-CLI",
dependencies: [
"Alamofire",
"PromiseKit",
"insert_dylib",
.product(name: "ArgumentParser", package: "swift-argument-parser")
]
),
.systemLibrary(
name: "insert_dylib",
path: "Sources/insert_dylib"
)
]
)
================================================
FILE: README.md
================================================
# WeChatTweak-CLI
## ⚠️ NOTICE ⚠️
WeChatTweak-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.
## License
The [Apache License 2.0](LICENSE).
================================================
FILE: Sources/WeChatTweak-CLI/Command.swift
================================================
//
// Command.swift
//
// Created by Sunny Young.
//
import Foundation
import Alamofire
import PromiseKit
import ArgumentParser
import insert_dylib
struct Command {
static func check() -> Promise<Void> {
return getuid() == 0 ? .value(()) : .init(error: CLIError.permission)
}
static func cleanup() -> Guarantee<Void> {
return Guarantee { seal in
try? FileManager.default.removeItem(atPath: Temp.zip)
try? FileManager.default.removeItem(atPath: Temp.binary)
seal(())
}
}
static func backup() -> Promise<Void> {
print("------ Backup ------")
return Promise { seal in
do {
if FileManager.default.fileExists(atPath: App.backup) {
print("WeChat.bak exists, skip it...")
} else {
try FileManager.default.copyItem(atPath: App.binary, toPath: App.backup)
print("Created WeChat.bak...")
}
seal.fulfill(())
} catch {
seal.reject(error)
}
}
}
static func restore() -> Promise<Void> {
print("------ Restore ------")
return Promise { seal in
do {
if FileManager.default.fileExists(atPath: App.backup) {
try FileManager.default.removeItem(atPath: App.binary)
try FileManager.default.moveItem(atPath: App.backup, toPath: App.binary)
try? FileManager.default.removeItem(atPath: App.framework)
print("Restored WeChat...")
} else {
print("WeChat.bak not exists, skip it...")
}
seal.fulfill(())
} catch {
seal.reject(error)
}
}
}
static func download() -> Promise<Void> {
print("------ Download ------")
return Promise { seal in
let destination: DownloadRequest.Destination = { _, _ in
return (.init(fileURLWithPath: Temp.zip), [.removePreviousFile])
}
AF.download(Constant.url, to: destination).response { response in
if let error = response.error {
seal.reject(CLIError.downloading(error))
} else {
seal.fulfill(())
}
}
}
}
static func unzip() -> Promise<Void> {
print("------ Unzip ------")
return Command.execute(command: "rm -rf \(App.framework); unzip \(Temp.zip) -d \(App.macos)")
}
static func insert() -> Promise<Void> {
print("------ Insert Dylib ------")
return Promise { seal in
insert_dylib.insert("@executable_path/WeChatTweak.framework/WeChatTweak", App.binary) == EXIT_SUCCESS ? seal.fulfill(()) : seal.reject(CLIError.insertDylib)
}
}
static func removeCodesign() -> Promise<Void> {
print("------ Remove Codesign ------")
return Command.execute(command: "codesign --remove-sign \(App.binary)")
}
static func addCodesign() -> Promise<Void> {
print("------ Add Codesign ------")
return Command.execute(command: "codesign --force --deep --sign - \(App.binary)")
}
static func resetPermission() -> Promise<Void> {
print("------ Reset ScreenCapture privacy permission ------")
return Command.execute(command: "tccutil reset ScreenCapture com.tencent.xinWeChat")
}
private static func execute(command: String) -> Promise<Void> {
return Promise { seal in
print("Execute command: \(command)")
var error: NSDictionary?
guard let script = NSAppleScript(source: "do shell script \"\(command)\"") else {
return seal.reject(CLIError.executing(command: command, error: ["error": "Create script failed."]))
}
script.executeAndReturnError(&error)
if let error = error {
seal.reject(CLIError.executing(command: command, error: error))
} else {
seal.fulfill(())
}
}
}
}
================================================
FILE: Sources/WeChatTweak-CLI/main.swift
================================================
//
// main.swift
//
// Created by Sunny Young.
//
import Foundation
import PromiseKit
import ArgumentParser
struct Constant {
static let url = URL(string: "https://github.com/Sunnyyoung/WeChatTweak-macOS/releases/latest/download/WeChatTweak.framework.zip")!
}
struct App {
static let root = "/Applications"
static let app = root.appending("/WeChat.app")
static let macos = app.appending("/Contents/MacOS")
static let binary = app.appending("/Contents/MacOS/WeChat")
static let backup = app.appending("/Contents/MacOS/WeChat.bak")
static let framework = macos.appending("/WeChatTweak.framework")
}
struct Temp {
static let root = "/tmp"
static let binary = root.appending("/WeChat")
static let zip = root.appending("/WeChatTweak.zip")
}
enum CLIError: LocalizedError {
case permission
case downloading(Error)
case insertDylib
case executing(command: String, error: NSDictionary)
var errorDescription: String? {
switch self {
case .permission:
return "Please run with `sudo`."
case let .downloading(error):
return "Download failed with error: \(error)"
case .insertDylib:
return "Insert dylib failed"
case let .executing(command, error):
return "Execute command: \(command) failed: \(error)"
}
}
}
struct Install: ParsableCommand {
static var configuration = CommandConfiguration(abstract: "Install or upgrade tweak.")
func run() throws {
firstly {
Command.check()
}.then {
Command.cleanup()
}.then {
Command.download()
}.then {
Command.unzip()
}.then {
Command.backup()
}.then {
Command.removeCodesign()
}.then {
Command.insert()
}.then {
Command.addCodesign()
}.then {
Command.resetPermission()
}.done {
print("Install success!")
}.catch { error in
print("Install failed: \(error.localizedDescription)")
}.finally {
CFRunLoopStop(CFRunLoopGetCurrent())
}
}
}
struct Uninstall: ParsableCommand {
static var configuration = CommandConfiguration(abstract: "Uninstall tweak.")
func run() throws {
firstly {
Command.check()
}.then {
Command.cleanup()
}.then {
Command.restore()
}.done {
print("Uninstall success!")
}.catch { error in
print("Uninstall failed: \(error)")
}.finally {
CFRunLoopStop(CFRunLoopGetCurrent())
}
}
}
struct Version: ParsableCommand {
static var configuration = CommandConfiguration(abstract: "Get current version of WeChatTweak.")
func run() throws {
return firstly {
getVersion()
}.done { version in
print(version ?? "Unknown")
}.catch { error in
print("Get version failed: \(error)")
}.finally {
CFRunLoopStop(CFRunLoopGetCurrent())
}
}
func getVersion() -> Promise<String?> {
return Promise { seal in
do {
let data = try Data(contentsOf: URL(fileURLWithPath: App.framework.appending("/Versions/A/Resources/Info.plist")))
let info = try PropertyListSerialization.propertyList(from: data, options: [], format: nil)
seal.fulfill((info as? [String: Any])?["CFBundleShortVersionString"] as? String)
} catch {
seal.reject(error)
}
}
}
}
struct Resign: ParsableCommand {
static var configuration = CommandConfiguration(abstract: "Force resign WeChat.app")
func run() throws {
firstly {
Command.removeCodesign()
}.then {
Command.addCodesign()
}.catch { error in
print("Resign failed: \(error.localizedDescription)")
}.finally {
CFRunLoopStop(CFRunLoopGetCurrent())
}
}
}
struct Tweak: ParsableCommand {
static var configuration = CommandConfiguration(
commandName: "wechattweak-cli",
abstract: "A command line utility to work with WeChatTweak-macOS.",
subcommands: [
Install.self,
Uninstall.self,
Resign.self,
Version.self
],
defaultSubcommand: Self.self
)
}
defer {
try? FileManager.default.removeItem(atPath: Temp.zip)
try? FileManager.default.removeItem(atPath: Temp.binary)
}
Tweak.main()
CFRunLoopRun()
================================================
FILE: Sources/insert_dylib/insert_dylib.h
================================================
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdarg.h>
#include <string.h>
#include <unistd.h>
#include <getopt.h>
#include <sys/stat.h>
#include <sys/param.h>
#include <copyfile.h>
#include <mach-o/loader.h>
#include <mach-o/fat.h>
#define IS_64_BIT(x) ((x) == MH_MAGIC_64 || (x) == MH_CIGAM_64)
#define IS_LITTLE_ENDIAN(x) ((x) == FAT_CIGAM || (x) == MH_CIGAM_64 || (x) == MH_CIGAM)
#define SWAP32(x, magic) (IS_LITTLE_ENDIAN(magic)? OSSwapInt32(x): (x))
#define SWAP64(x, magic) (IS_LITTLE_ENDIAN(magic)? OSSwapInt64(x): (x))
#define ROUND_UP(x, y) (((x) + (y) - 1) & -(y))
#define ABSDIFF(x, y) ((x) > (y)? (uintmax_t)(x) - (uintmax_t)(y): (uintmax_t)(y) - (uintmax_t)(x))
#define BUFSIZE 512
void fbzero(FILE *f, off_t offset, size_t len) {
static unsigned char zeros[BUFSIZE] = {0};
fseeko(f, offset, SEEK_SET);
while(len != 0) {
size_t size = MIN(len, sizeof(zeros));
fwrite(zeros, size, 1, f);
len -= size;
}
}
void fmemmove(FILE *f, off_t dst, off_t src, size_t len) {
static unsigned char buf[BUFSIZE];
while(len != 0) {
size_t size = MIN(len, sizeof(buf));
fseeko(f, src, SEEK_SET);
fread(&buf, size, 1, f);
fseeko(f, dst, SEEK_SET);
fwrite(buf, size, 1, f);
len -= size;
src += size;
dst += size;
}
}
int weak_flag = false;
size_t fpeek(void *restrict ptr, size_t size, size_t nitems, FILE *restrict stream) {
off_t pos = ftello(stream);
size_t result = fread(ptr, size, nitems, stream);
fseeko(stream, pos, SEEK_SET);
return result;
}
void *read_load_command(FILE *f, uint32_t cmdsize) {
void *lc = malloc(cmdsize);
fpeek(lc, cmdsize, 1, f);
return lc;
}
bool 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) {
fseeko(f, commands_offset, SEEK_SET);
uint32_t ncmds = SWAP32(mh->ncmds, mh->magic);
off_t linkedit_32_pos = -1;
off_t linkedit_64_pos = -1;
struct segment_command linkedit_32;
struct segment_command_64 linkedit_64;
off_t symtab_pos = -1;
uint32_t symtab_size = 0;
for(int i = 0; i < ncmds; i++) {
struct load_command lc;
fpeek(&lc, sizeof(lc), 1, f);
uint32_t cmdsize = SWAP32(lc.cmdsize, mh->magic);
uint32_t cmd = SWAP32(lc.cmd, mh->magic);
switch(cmd) {
case LC_CODE_SIGNATURE:
if(i == ncmds - 1) {
printf("LC_CODE_SIGNATURE load command found. Remove it.\n");
struct linkedit_data_command *cmd = read_load_command(f, cmdsize);
fbzero(f, ftello(f), cmdsize);
uint32_t dataoff = SWAP32(cmd->dataoff, mh->magic);
uint32_t datasize = SWAP32(cmd->datasize, mh->magic);
free(cmd);
uint64_t linkedit_fileoff = 0;
uint64_t linkedit_filesize = 0;
if(linkedit_32_pos != -1) {
linkedit_fileoff = SWAP32(linkedit_32.fileoff, mh->magic);
linkedit_filesize = SWAP32(linkedit_32.filesize, mh->magic);
} else if(linkedit_64_pos != -1) {
linkedit_fileoff = SWAP64(linkedit_64.fileoff, mh->magic);
linkedit_filesize = SWAP64(linkedit_64.filesize, mh->magic);
} else {
fprintf(stderr, "Warning: __LINKEDIT segment not found.\n");
}
if(linkedit_32_pos != -1 || linkedit_64_pos != -1) {
if(linkedit_fileoff + linkedit_filesize != *slice_size) {
fprintf(stderr, "Warning: __LINKEDIT segment is not at the end of the file, so codesign will not work on the patched binary.\n");
} else {
if(dataoff + datasize != *slice_size) {
fprintf(stderr, "Warning: Codesignature is not at the end of __LINKEDIT segment, so codesign will not work on the patched binary.\n");
} else {
*slice_size -= datasize;
//int64_t diff_size = 0;
if(symtab_pos == -1) {
fprintf(stderr, "Warning: LC_SYMTAB load command not found. codesign might not work on the patched binary.\n");
} else {
fseeko(f, symtab_pos, SEEK_SET);
struct symtab_command *symtab = read_load_command(f, symtab_size);
uint32_t strsize = SWAP32(symtab->strsize, mh->magic);
int64_t diff_size = SWAP32(symtab->stroff, mh->magic) + strsize - (int64_t)*slice_size;
if(-0x10 <= diff_size && diff_size <= 0) {
symtab->strsize = SWAP32((uint32_t)(strsize - diff_size), mh->magic);
fwrite(symtab, symtab_size, 1, f);
} else {
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);
}
free(symtab);
}
linkedit_filesize -= datasize;
uint64_t linkedit_vmsize = ROUND_UP(linkedit_filesize, 0x1000);
if(linkedit_32_pos != -1) {
linkedit_32.filesize = SWAP32((uint32_t)linkedit_filesize, mh->magic);
linkedit_32.vmsize = SWAP32((uint32_t)linkedit_vmsize, mh->magic);
fseeko(f, linkedit_32_pos, SEEK_SET);
fwrite(&linkedit_32, sizeof(linkedit_32), 1, f);
} else {
linkedit_64.filesize = SWAP64(linkedit_filesize, mh->magic);
linkedit_64.vmsize = SWAP64(linkedit_vmsize, mh->magic);
fseeko(f, linkedit_64_pos, SEEK_SET);
fwrite(&linkedit_64, sizeof(linkedit_64), 1, f);
}
goto fix_header;
}
}
}
// If we haven't truncated the file, zero out the code signature
fbzero(f, header_offset + dataoff, datasize);
fix_header:
mh->ncmds = SWAP32(ncmds - 1, mh->magic);
mh->sizeofcmds = SWAP32(SWAP32(mh->sizeofcmds, mh->magic) - cmdsize, mh->magic);
return true;
} else {
printf("LC_CODE_SIGNATURE is not the last load command, so couldn't remove.\n");
}
break;
case LC_LOAD_DYLIB:
case LC_LOAD_WEAK_DYLIB: {
struct dylib_command *dylib_command = read_load_command(f, cmdsize);
union lc_str offset = dylib_command->dylib.name;
char *name = &((char *)dylib_command)[SWAP32(offset.offset, mh->magic)];
int cmp = strcmp(name, dylib_path);
free(dylib_command);
if(cmp == 0) {
printf("Binary already contains a load command for that dylib. Skip it.\n");
return false;
}
break;
}
case LC_SEGMENT:
case LC_SEGMENT_64:
if(cmd == LC_SEGMENT) {
struct segment_command *cmd = read_load_command(f, cmdsize);
if(strcmp(cmd->segname, "__LINKEDIT") == 0) {
linkedit_32_pos = ftello(f);
linkedit_32 = *cmd;
}
free(cmd);
} else {
struct segment_command_64 *cmd = read_load_command(f, cmdsize);
if(strcmp(cmd->segname, "__LINKEDIT") == 0) {
linkedit_64_pos = ftello(f);
linkedit_64 = *cmd;
}
free(cmd);
}
case LC_SYMTAB:
symtab_pos = ftello(f);
symtab_size = cmdsize;
}
fseeko(f, SWAP32(lc.cmdsize, mh->magic), SEEK_CUR);
}
return true;
}
bool _insert_dylib(FILE *f, size_t header_offset, const char *dylib_path, off_t *slice_size) {
fseeko(f, header_offset, SEEK_SET);
struct mach_header mh;
fread(&mh, sizeof(struct mach_header), 1, f);
if(mh.magic != MH_MAGIC_64 && mh.magic != MH_CIGAM_64 && mh.magic != MH_MAGIC && mh.magic != MH_CIGAM) {
printf("Unknown magic: 0x%x\n", mh.magic);
return false;
}
size_t commands_offset = header_offset + (IS_64_BIT(mh.magic)? sizeof(struct mach_header_64): sizeof(struct mach_header));
bool cont = check_load_commands(f, &mh, header_offset, commands_offset, dylib_path, slice_size);
if(!cont) {
return true;
}
// Even though a padding of 4 works for x86_64, codesign doesn't like it
size_t path_padding = 8;
size_t dylib_path_len = strlen(dylib_path);
size_t dylib_path_size = (dylib_path_len & ~(path_padding - 1)) + path_padding;
uint32_t cmdsize = (uint32_t)(sizeof(struct dylib_command) + dylib_path_size);
struct dylib_command dylib_command = {
.cmd = SWAP32(weak_flag? LC_LOAD_WEAK_DYLIB: LC_LOAD_DYLIB, mh.magic),
.cmdsize = SWAP32(cmdsize, mh.magic),
.dylib = {
.name = SWAP32(sizeof(struct dylib_command), mh.magic),
.timestamp = 0,
.current_version = 0,
.compatibility_version = 0
}
};
uint32_t sizeofcmds = SWAP32(mh.sizeofcmds, mh.magic);
fseeko(f, commands_offset + sizeofcmds, SEEK_SET);
char space[cmdsize];
fread(&space, cmdsize, 1, f);
bool empty = true;
for(int i = 0; i < cmdsize; i++) {
if(space[i] != 0) {
empty = false;
break;
}
}
if(!empty) {
printf("It doesn't seem like there is enough empty space. Continue anyway.");
}
fseeko(f, -((off_t)cmdsize), SEEK_CUR);
char *dylib_path_padded = calloc(dylib_path_size, 1);
memcpy(dylib_path_padded, dylib_path, dylib_path_len);
fwrite(&dylib_command, sizeof(dylib_command), 1, f);
fwrite(dylib_path_padded, dylib_path_size, 1, f);
free(dylib_path_padded);
mh.ncmds = SWAP32(SWAP32(mh.ncmds, mh.magic) + 1, mh.magic);
sizeofcmds += cmdsize;
mh.sizeofcmds = SWAP32(sizeofcmds, mh.magic);
fseeko(f, header_offset, SEEK_SET);
fwrite(&mh, sizeof(mh), 1, f);
return true;
}
int insert(const char *lib_path, const char *bin_path) {
const char *lc_name = weak_flag? "LC_LOAD_WEAK_DYLIB": "LC_LOAD_DYLIB";
struct stat s;
if(stat(bin_path, &s) != 0) {
perror(bin_path);
return EXIT_FAILURE;
}
if(lib_path[0] != '@' && stat(lib_path, &s) != 0) {
return EXIT_FAILURE;
}
FILE *f = fopen(bin_path, "r+");
if(!f) {
printf("Couldn't open file %s\n", bin_path);
return EXIT_FAILURE;
}
bool success = true;
fseeko(f, 0, SEEK_END);
off_t file_size = ftello(f);
rewind(f);
uint32_t magic;
fread(&magic, sizeof(uint32_t), 1, f);
switch(magic) {
case FAT_MAGIC:
case FAT_CIGAM: {
fseeko(f, 0, SEEK_SET);
struct fat_header fh;
fread(&fh, sizeof(fh), 1, f);
uint32_t nfat_arch = SWAP32(fh.nfat_arch, magic);
printf("Binary is a fat binary with %d archs.\n", nfat_arch);
struct fat_arch archs[nfat_arch];
fread(archs, sizeof(archs), 1, f);
int fails = 0;
uint32_t offset = 0;
if(nfat_arch > 0) {
offset = SWAP32(archs[0].offset, magic);
}
for(int i = 0; i < nfat_arch; i++) {
off_t orig_offset = SWAP32(archs[i].offset, magic);
off_t orig_slice_size = SWAP32(archs[i].size, magic);
offset = ROUND_UP(offset, 1 << SWAP32(archs[i].align, magic));
if(orig_offset != offset) {
fmemmove(f, offset, orig_offset, orig_slice_size);
fbzero(f, MIN(offset, orig_offset) + orig_slice_size, ABSDIFF(offset, orig_offset));
archs[i].offset = SWAP32(offset, magic);
}
off_t slice_size = orig_slice_size;
bool r = _insert_dylib(f, offset, lib_path, &slice_size);
if(!r) {
printf("Failed to add %s to arch #%d!\n", lc_name, i + 1);
fails++;
}
if(slice_size < orig_slice_size && i < nfat_arch - 1) {
fbzero(f, offset + slice_size, orig_slice_size - slice_size);
}
file_size = offset + slice_size;
offset += slice_size;
archs[i].size = SWAP32((uint32_t)slice_size, magic);
}
rewind(f);
fwrite(&fh, sizeof(fh), 1, f);
fwrite(archs, sizeof(archs), 1, f);
// We need to flush before truncating
fflush(f);
ftruncate(fileno(f), file_size);
if(fails == 0) {
printf("Added %s to all archs in %s\n", lc_name, bin_path);
} else if(fails == nfat_arch) {
printf("Failed to add %s to any archs.\n", lc_name);
success = false;
} else {
printf("Added %s to %d/%d archs in %s\n", lc_name, nfat_arch - fails, nfat_arch, bin_path);
}
break;
}
case MH_MAGIC_64:
case MH_CIGAM_64:
case MH_MAGIC:
case MH_CIGAM:
if(_insert_dylib(f, 0, lib_path, &file_size)) {
ftruncate(fileno(f), file_size);
printf("Added %s to %s\n", lc_name, bin_path);
} else {
printf("Failed to add %s!\n", lc_name);
success = false;
}
break;
default:
printf("Unknown magic: 0x%x\n", magic);
return EXIT_FAILURE;
}
fclose(f);
if(!success) {
unlink(bin_path);
return EXIT_FAILURE;
} else {
return EXIT_SUCCESS;
}
}
================================================
FILE: Sources/insert_dylib/module.modulemap
================================================
module insert_dylib {
header "insert_dylib.h"
export *
}
gitextract_827__s9_/
├── .gitignore
├── CNAME
├── LICENSE
├── Makefile
├── Package.resolved
├── Package.swift
├── README.md
└── Sources/
├── WeChatTweak-CLI/
│ ├── Command.swift
│ └── main.swift
└── insert_dylib/
├── insert_dylib.h
└── module.modulemap
SYMBOL INDEX (6 symbols across 1 files)
FILE: Sources/insert_dylib/insert_dylib.h
function fbzero (line 25) | void fbzero(FILE *f, off_t offset, size_t len) {
function fmemmove (line 35) | void fmemmove(FILE *f, off_t dst, off_t src, size_t len) {
function fpeek (line 52) | size_t fpeek(void *restrict ptr, size_t size, size_t nitems, FILE *restr...
function check_load_commands (line 67) | bool check_load_commands(FILE *f, struct mach_header *mh, size_t header_...
function _insert_dylib (line 221) | bool _insert_dylib(FILE *f, size_t header_offset, const char *dylib_path...
function insert (line 297) | int insert(const char *lib_path, const char *bin_path) {
Condensed preview — 11 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (41K chars).
[
{
"path": ".gitignore",
"chars": 1563,
"preview": "### 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"
},
{
"path": "CNAME",
"chars": 14,
"preview": "cli.tweaks.app"
},
{
"path": "LICENSE",
"chars": 11357,
"preview": " Apache License\n Version 2.0, January 2004\n "
},
{
"path": "Makefile",
"chars": 264,
"preview": ".DEFAULT := build\n\nbuild:\n\tswift package purge-cache\n\tswift package clean\n\tswift build -c release --arch arm64 --arch x8"
},
{
"path": "Package.resolved",
"chars": 873,
"preview": "{\n \"object\": {\n \"pins\": [\n {\n \"package\": \"Alamofire\",\n \"repositoryURL\": \"https://github.com/Alamo"
},
{
"path": "Package.swift",
"chars": 1011,
"preview": "// swift-tools-version:5.5\n\nimport PackageDescription\n\nlet package = Package(\n name: \"WeChatTweak-CLI\",\n platforms"
},
{
"path": "README.md",
"chars": 339,
"preview": "# WeChatTweak-CLI\n\n## ⚠️ NOTICE ⚠️\n\nWeChatTweak-CLI is no longer maintained. To reduce maintenance cost and avoid confus"
},
{
"path": "Sources/WeChatTweak-CLI/Command.swift",
"chars": 4188,
"preview": "//\n// Command.swift\n//\n// Created by Sunny Young.\n//\n\nimport Foundation\nimport Alamofire\nimport PromiseKit\nimport Argu"
},
{
"path": "Sources/WeChatTweak-CLI/main.swift",
"chars": 4632,
"preview": "//\n// main.swift\n//\n// Created by Sunny Young.\n//\n\nimport Foundation\nimport PromiseKit\nimport ArgumentParser\n\nstruct C"
},
{
"path": "Sources/insert_dylib/insert_dylib.h",
"chars": 14937,
"preview": "#include <stdlib.h>\n#include <stdio.h>\n#include <stdbool.h>\n#include <stdarg.h>\n#include <string.h>\n#include <unistd.h>\n"
},
{
"path": "Sources/insert_dylib/module.modulemap",
"chars": 61,
"preview": "module insert_dylib {\n header \"insert_dylib.h\"\n export *\n}\n"
}
]
About this extraction
This page contains the full source code of the sunnyyoung/WeChatTweak-CLI GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 11 files (38.3 KB), approximately 9.3k tokens, and a symbol index with 6 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.