├── .gitignore ├── FridaHook.py ├── LICENSE ├── README.md ├── hook_android_asset.js ├── hook_android_gl.js ├── hook_android_inject.js ├── hook_android_mt.js ├── hook_android_webview.js ├── hook_ios_bug.js └── hook_ios_scheme.js /.gitignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wrlu/FridaHookUniversal/91e6da001e686dd02a6e82db222a3da5368f2606/.gitignore -------------------------------------------------------------------------------- /FridaHook.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | import frida 4 | import hashlib 5 | import json 6 | import numpy 7 | import OpenEXR 8 | import Imath 9 | from PIL import Image 10 | 11 | # For frida version 15 or higher 12 | # Please use real App name for `name` and package name for `identifier` on Android 13 | # For Android native processes or iOS processes, keep identifier and name as same 14 | processes_to_hook = [ 15 | # Android 16 | # {'identifier': 'com.ss.android.ugc.aweme', 'name': '抖音'}, 17 | # {'identifier': 'com.mt.mtxx.mtxx', 'name': '美图秀秀'}, 18 | {'identifier': 'com.meitu.wink', 'name': 'Wink'}, 19 | 20 | # iOS 21 | # {'identifier': 'com.ss.iphone.ugc.Aweme', 'name': '抖音'}, 22 | ] 23 | 24 | class Log: 25 | @staticmethod 26 | def send(msg): 27 | print('[Send] ' + msg) 28 | 29 | @staticmethod 30 | def println(msg): 31 | print(msg) 32 | 33 | @staticmethod 34 | def info(msg): 35 | print('[Info] ' + msg) 36 | 37 | @staticmethod 38 | def warn(msg): 39 | print('\033[0;33m[Warning] ' + msg + '\033[0m') 40 | 41 | @staticmethod 42 | def error(msg): 43 | print('\033[0;31m[Error] ' + msg + '\033[0m') 44 | 45 | def on_message(message): 46 | if message['type'] == 'error': 47 | Log.error(message['description']) 48 | Log.error(message['stack']) 49 | else: 50 | Log.error(str(message)) 51 | 52 | unique_shader_hash = [] 53 | unique_texture_hash = [] 54 | 55 | def glFormat2PILFormat(glFormat): 56 | if glFormat == 'GL_RGBA': 57 | return 'RGBA' 58 | elif glFormat == 'GL_LUMINANCE': 59 | return 'L' 60 | return 'unsupported' 61 | 62 | # 保存OpenGL shader source 63 | def saveShader(payload): 64 | shader_source = payload.encode('utf8') 65 | source_hash = get_hash(shader_source) 66 | if source_hash not in unique_shader_hash: 67 | Log.send('Received shader source: ' + source_hash) 68 | unique_shader_hash.append(source_hash) 69 | with open(processes_to_hook[0]['identifier'] + '/shader/glShaderSource_' + source_hash + '.txt', 'wb') as f: 70 | f.write(shader_source) 71 | f.close() 72 | 73 | # 尝试使用PIL处理SDR图像,例如GL_RGBA和GL_LUMINANCE 74 | def saveSdrImageWithPil(param, data): 75 | pilFormat = glFormat2PILFormat(param['internalformat']) 76 | if pilFormat != 'unsupported': 77 | texture_hash = get_hash(data) 78 | if texture_hash not in unique_texture_hash: 79 | Log.send('Received SDR texture: ' + texture_hash + ', datalen: ' + str(len(data))) 80 | unique_texture_hash.append(texture_hash) 81 | rgba_image = Image.frombytes(pilFormat, (param['width'], param['height']), data) 82 | rgba_image.save(processes_to_hook[0]['identifier'] + '/texture/glTexImage2D_' + texture_hash + '.png', format='PNG') 83 | return True 84 | else: 85 | return False 86 | 87 | # 尝试使用OpenEXR处理HDR图像 88 | def saveHdrImageWithOpenExr(param, data): 89 | texture_hash = get_hash(data) 90 | if texture_hash not in unique_texture_hash: 91 | Log.send('Received HDR texture: ' + texture_hash + ', datalen: ' + str(len(data))) 92 | # 根据不同的格式确定数据类型和像素类型 93 | if param['internalformat'] == 'GL_RGBA32F': 94 | dtype = numpy.float32 95 | pixel_type = Imath.PixelType.FLOAT 96 | channels = 4 97 | elif param['internalformat'] == 'GL_RGBA16F': 98 | dtype = numpy.float16 99 | pixel_type = Imath.PixelType.HALF 100 | channels = 4 101 | elif param['internalformat'] == 'GL_RGB32F': 102 | dtype = numpy.float32 103 | pixel_type = Imath.PixelType.FLOAT 104 | channels = 3 105 | elif param['internalformat'] == 'GL_RGB16F': 106 | dtype = numpy.float16 107 | pixel_type = Imath.PixelType.HALF 108 | channels = 3 109 | else: 110 | Log.warn('Unsupported') 111 | return 112 | 113 | pixels = numpy.frombuffer(data, dtype=dtype) 114 | pixels = pixels.reshape((int(param['height']), int(param['width']), channels)) 115 | if channels == 4: 116 | r = pixels[:, :, 0].flatten().astype(dtype).tobytes() 117 | g = pixels[:, :, 1].flatten().astype(dtype).tobytes() 118 | b = pixels[:, :, 2].flatten().astype(dtype).tobytes() 119 | a = pixels[:, :, 3].flatten().astype(dtype).tobytes() 120 | channel_names = "RGBA" 121 | channel_data = {'R': r, 'G': g, 'B': b, 'A': a} 122 | elif channels == 3: 123 | r = pixels[:, :, 0].flatten().astype(dtype).tobytes() 124 | g = pixels[:, :, 1].flatten().astype(dtype).tobytes() 125 | b = pixels[:, :, 2].flatten().astype(dtype).tobytes() 126 | channel_names = "RGB" 127 | channel_data = {'R': r, 'G': g, 'B': b} 128 | 129 | header = OpenEXR.Header(int(param['width']), int(param['height'])) 130 | half_chan = Imath.Channel(Imath.PixelType(pixel_type)) 131 | header['channels'] = dict([(c, half_chan) for c in channel_names]) 132 | 133 | path = os.getcwd() + os.sep + processes_to_hook[0]['identifier'] + os.sep + 'texture' + os.sep + 'glTexImage2D_' + texture_hash + '.exr' 134 | 135 | out = OpenEXR.OutputFile(path, header) 136 | out.writePixels(channel_data) 137 | out.close() 138 | unique_texture_hash.append(texture_hash) 139 | 140 | def on_gl_message(message, data): 141 | global unique_shader_hash 142 | global unique_texture_hash 143 | if message['type'] == 'send': 144 | payload = message['payload'] 145 | if payload.startswith('glTexImage2D:'): 146 | if data == None or data == '': 147 | Log.println('data is None') 148 | return 149 | param = json.loads(payload.replace('glTexImage2D:', '')) 150 | if saveSdrImageWithPil(param, data): 151 | return 152 | if saveHdrImageWithOpenExr(param, data): 153 | return 154 | elif payload.startswith('glTexSubImage2D:'): 155 | if data == None or data == '': 156 | Log.println('data is None') 157 | return 158 | param = json.loads(payload.replace('glTexSubImage2D:', '')) 159 | if saveSdrImageWithPil(param, data): 160 | return 161 | if saveHdrImageWithOpenExr(param, data): 162 | return 163 | else: 164 | saveShader(payload) 165 | else: 166 | on_message(message) 167 | 168 | # Full file name: hook_[platform]_[name].js 169 | js_modules = [ 170 | # {'platform': 'android', 'name': 'gl', 'on': on_gl_message}, 171 | {'platform': 'android', 'name': 'asset', 'on': on_message}, 172 | {'platform': 'android', 'name': 'mt', 'on': on_message}, 173 | ] 174 | 175 | def get_hash(data): 176 | hash = hashlib.sha256() 177 | hash.update(data) 178 | return hash.hexdigest() 179 | 180 | def init_device(): 181 | Log.info('Current frida version: '+str(frida.__version__)) 182 | manager = frida.get_device_manager() 183 | Log.println('Select a frida device:') 184 | devices = manager.enumerate_devices() 185 | i = 0 186 | for ldevice in devices: 187 | i = i + 1 188 | Log.println(str(i) + ' => ' + str(ldevice)) 189 | if i == 4: 190 | select = 4 191 | Log.warn('Auto select the only usb device...') 192 | elif i == 1 or i == 2: 193 | select = 1 194 | Log.warn('Auto select local system device...') 195 | else: 196 | select = int(input()) 197 | if select > len(devices): 198 | Log.error('Out of range.') 199 | sys.exit(1) 200 | device_id = devices[select - 1].id 201 | 202 | device = manager.get_device(device_id, 1) 203 | Log.info('Connect to device \''+device.name+'\' successfully.') 204 | return device 205 | 206 | 207 | if __name__ == '__main__': 208 | try: 209 | device = init_device() 210 | for per_hook_process in processes_to_hook: 211 | try: 212 | device.get_process(per_hook_process['name']) 213 | except frida.ProcessNotFoundError as e: 214 | Log.warn('Unable to find process \''+per_hook_process['name']+'\', try to spawn...') 215 | # Must use identifier to spawn 216 | try: 217 | pid = device.spawn(per_hook_process['identifier']) 218 | device.resume(pid) 219 | except frida.ExecutableNotFoundError as e2: 220 | Log.error('Unable to find execuable \''+per_hook_process['name']+'\'.') 221 | 222 | session = device.attach(per_hook_process['name']) 223 | 224 | for js_module in js_modules: 225 | full_script_name = 'hook_' + js_module['platform'] + '_' + js_module['name'] + '.js' 226 | with open(full_script_name, 'rb') as f: 227 | script = session.create_script(f.read().decode('utf8')) 228 | if 'on' in js_module: 229 | script.on('message', js_module['on']) 230 | else: 231 | script.on('message', on_message) 232 | Log.info('Load script name: ' + full_script_name) 233 | script.load() 234 | 235 | Log.info('Waiting for JavaScript...') 236 | print('--------------------------------------------------') 237 | sys.stdin.read() 238 | 239 | except Exception as e: 240 | Log.error(repr(e)) 241 | 242 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # FridaHookUniversal 2 | ## Feature 3 | - Support Android & iOS 4 | - Support muti-devices 5 | - Support muti-scripts injecting 6 | - Support muti-processes hooking 7 | - Support logs 8 | 9 | ## License 10 | - Apache License 2.0 11 | -------------------------------------------------------------------------------- /hook_android_asset.js: -------------------------------------------------------------------------------- 1 | function printStackTrace(context) { 2 | let backtrace = Thread.backtrace(context, Backtracer.ACCURATE); 3 | let symbols = backtrace.map(DebugSymbol.fromAddress); 4 | symbols.forEach(function (symbol, index) { 5 | console.log(" " + (index + 1) + ". " + symbol); 6 | }); 7 | } 8 | 9 | function hook_native_asset() { 10 | Interceptor.attach(Module.findExportByName("libandroid.so", "AAssetManager_open"), { 11 | onEnter: function(args) { 12 | this.fileName = ptr(args[1]).readCString(); 13 | }, 14 | 15 | onLeave:function(retval) { 16 | if (retval != 0) { 17 | console.log(`file://android_asset/${this.fileName}`) 18 | } 19 | } 20 | }); 21 | } 22 | 23 | function hook_java_asset() { 24 | let AssetManager = Java.use("android.content.res.AssetManager"); 25 | AssetManager["open"].overload("java.lang.String", "int").implementation = function (fileName, accessMode) { 26 | console.log(`file://android_asset/${fileName}`); 27 | return this["open"](fileName, accessMode); 28 | }; 29 | AssetManager["openFd"].overload("java.lang.String").implementation = function (fileName) { 30 | console.log(`file://android_asset/${fileName}`); 31 | return this["openFd"](fileName); 32 | }; 33 | } 34 | 35 | function hook_native_fopen() { 36 | Interceptor.attach(Module.findExportByName("libc.so", "fopen"), { 37 | onEnter: function(args) { 38 | let path = args[0]; 39 | let path_str = `${path.readCString()}` 40 | if (path_str.startsWith('/data') || path_str.startsWith('/storage') || path_str.startsWith('/sdcard')) { 41 | console.log(`file://${path_str}`); 42 | } 43 | }, 44 | onLeave:function(retval) {} 45 | }); 46 | } 47 | 48 | function main() { 49 | hook_native_asset(); 50 | hook_native_fopen(); 51 | if (Java.available) { 52 | Java.perform(function() { 53 | hook_java_asset(); 54 | }); 55 | } 56 | } 57 | 58 | setImmediate(main); -------------------------------------------------------------------------------- /hook_android_gl.js: -------------------------------------------------------------------------------- 1 | function printStackTrace(context) { 2 | let backtrace = Thread.backtrace(context, Backtracer.ACCURATE); 3 | let symbols = backtrace.map(DebugSymbol.fromAddress); 4 | symbols.forEach(function (symbol, index) { 5 | console.log(" " + (index + 1) + ". " + symbol); 6 | }); 7 | } 8 | 9 | // Qualcomm Adreno GPU devices. 10 | let ADRENO_GLES_ELF = "libGLESv2_adreno.so"; 11 | // Mali GPU devices (Google Tensor, MTK, Samsung Exynos, Hisilicon before kirin9000 and etc). 12 | let MALI_GLES_ELF = "libGLES_mali.so"; 13 | let gles_elf = MALI_GLES_ELF 14 | 15 | function hook_gl_shader() { 16 | let glGetProgramiv = new NativeFunction(Module.findExportByName(gles_elf, "glGetProgramiv"), 'void', ['pointer', 'int', 'pointer']) 17 | let glGetAttachedShaders = new NativeFunction(Module.findExportByName(gles_elf, "glGetAttachedShaders"), 'void', ['pointer', 'int', 'pointer', 'pointer']) 18 | let glGetShaderiv = new NativeFunction(Module.findExportByName(gles_elf, "glGetShaderiv"), 'void', ['uint', 'int', 'pointer']) 19 | let glGetShaderSource = new NativeFunction(Module.findExportByName(gles_elf, "glGetShaderSource"), 'void', ['uint', 'int', 'pointer', 'pointer']) 20 | let glUseProgram = Module.findExportByName(gles_elf, "glUseProgram") 21 | 22 | Interceptor.attach(glUseProgram, { 23 | onEnter: function(args) { 24 | let program = args[0] 25 | // 1. Get shader count in program. 26 | let shaderCountPointer = Memory.alloc(8) 27 | glGetProgramiv(program, 0x8b85 /* GL_ATTACHED_SHADERS */, shaderCountPointer) 28 | var shaderCount = shaderCountPointer.readInt() 29 | // 2. Alloc memory for attached shaders. 30 | let realShaderCountPointer = Memory.alloc(8) 31 | let attachedShadersPointer = Memory.alloc(Process.pointerSize) 32 | for (var i = 0; i < shaderCount; i++) { 33 | attachedShadersPointer.add(i * Process.pointerSize) 34 | attachedShadersPointer.writeUInt(0) 35 | } 36 | // 3. Get attached shaders 37 | glGetAttachedShaders(program, shaderCount, realShaderCountPointer, attachedShadersPointer) 38 | var realShaderCount = realShaderCountPointer.readInt() 39 | for (var i = 0; i < realShaderCount; i++) { 40 | // 4. Get each shader source length. 41 | let attachedShader = Memory.readUInt(attachedShadersPointer.add(i * Process.pointerSize)) 42 | let shaderSourceLenPointer = Memory.alloc(Process.pointerSize) 43 | glGetShaderiv(attachedShader, 0x8b88 /* GL_SHADER_SOURCE_LENGTH */, shaderSourceLenPointer) 44 | var shaderSourceLen = shaderSourceLenPointer.readInt() 45 | if (shaderSourceLen != 0) { 46 | // 5. Alloc memory for each shader source. 47 | let realShaderSourceLenPointer = Memory.alloc(Process.pointerSize) 48 | let shaderSourcePointer = Memory.alloc(shaderSourceLen) 49 | // 6. Get shader source. 50 | glGetShaderSource(attachedShader, shaderSourceLen, realShaderSourceLenPointer, shaderSourcePointer) 51 | let shaderSource = shaderSourcePointer.readCString() 52 | send(shaderSource) 53 | } 54 | } 55 | }, 56 | onLeave: function(retval) {} 57 | }) 58 | } 59 | 60 | function parseFormat(value) { 61 | value = parseInt(value, 16) 62 | const formatMap = { 63 | 0x1903: 'GL_ALPHA', 64 | 0x1907: 'GL_RGB', 65 | 0x1908: 'GL_RGBA', 66 | 0x1909: 'GL_LUMINANCE', 67 | 0x8814: 'GL_RGBA32F', 68 | 0x8815: 'GL_RGB32F', 69 | 0x881a: 'GL_RGBA16F', 70 | 0x881b: 'GL_RGB16F' 71 | }; 72 | return formatMap[value] || value; 73 | } 74 | 75 | function parseType(value) { 76 | value = parseInt(value, 16) 77 | const typeMap = { 78 | 0x1400: 'GL_BYTE', 79 | 0x1401: 'GL_UNSIGNED_BYTE', 80 | 0x1402: 'GL_SHORT', 81 | 0x1403: 'GL_UNSIGNED_SHORT', 82 | 0x1404: 'GL_INT', 83 | 0x1405: 'GL_UNSIGNED_INT', 84 | 0x1406: 'GL_FLOAT', 85 | 0x140B: 'GL_UNSIGNED_BYTE_3_3_2', 86 | 0x140C: 'GL_UNSIGNED_BYTE_2_3_3_REV', 87 | 0x140D: 'GL_UNSIGNED_SHORT_5_6_5', 88 | 0x140E: 'GL_UNSIGNED_SHORT_5_6_5_REV', 89 | 0x140F: 'GL_UNSIGNED_SHORT_4_4_4_4', 90 | 0x1410: 'GL_UNSIGNED_SHORT_4_4_4_4_REV', 91 | 0x1411: 'GL_UNSIGNED_SHORT_5_5_5_1', 92 | 0x1412: 'GL_UNSIGNED_SHORT_1_5_5_5_REV', 93 | 0x8033: 'GL_UNSIGNED_INT_8_8_8_8', 94 | 0x8034: 'GL_UNSIGNED_INT_8_8_8_8_REV', 95 | 0x8035: 'GL_UNSIGNED_INT_10_10_10_2', 96 | 0x8036: 'GL_UNSIGNED_INT_2_10_10_10_REV', 97 | 0x8D61: 'GL_HALF_FLOAT' 98 | }; 99 | return typeMap[value] || value; 100 | } 101 | 102 | function parseTarget(value) { 103 | value = parseInt(value, 16) 104 | const targetMap = { 105 | 0xde1: 'GL_TEXTURE_2D' 106 | }; 107 | return targetMap[value] || value; 108 | } 109 | 110 | function parseUsage(value) { 111 | value = parseInt(value, 16) 112 | const targetMap = { 113 | 0x88e0: 'GL_STREAM_DRAW', 114 | 0x88e4: 'GL_STATIC_DRAW', 115 | 0x88e8: 'GL_DYNAMIC_DRAW' 116 | }; 117 | return targetMap[value] || value; 118 | } 119 | 120 | function getTypeByteSize(typeName) { 121 | const typeByteSizes = { 122 | 'GL_BYTE': 1, 123 | 'GL_UNSIGNED_BYTE': 1, 124 | 'GL_SHORT': 2, 125 | 'GL_UNSIGNED_SHORT': 2, 126 | 'GL_INT': 4, 127 | 'GL_UNSIGNED_INT': 4, 128 | 'GL_FLOAT': 4, 129 | 'GL_HALF_FLOAT': 2 130 | }; 131 | return typeByteSizes[typeName] || 0; 132 | } 133 | 134 | function getFormatSize(formatName) { 135 | const formatSizes = { 136 | 'GL_RGBA': 4, 137 | 'GL_RGBA32F': 4, 138 | 'GL_RGBA16F': 4, 139 | 'GL_LUMINANCE': 1, 140 | 'GL_RGB': 3, 141 | 'GL_RGB32F': 3, 142 | 'GL_RGB16F': 3 143 | }; 144 | return formatSizes[formatName] || 0; 145 | } 146 | 147 | function calculateDataSize(formatName, typeName, width, height) { 148 | if (formatName == 'GL_RGBA16F' && typeName == 'GL_FLOAT') { 149 | typeName = 'GL_HALF_FLOAT' 150 | } 151 | const formatSize = getFormatSize(formatName); 152 | const typeByteSize = getTypeByteSize(typeName); 153 | return width * height * formatSize * typeByteSize; 154 | } 155 | 156 | function hook_gl_texture() { 157 | let glTexImage2D = Module.findExportByName(gles_elf, "glTexImage2D") 158 | Interceptor.attach(glTexImage2D, { 159 | onEnter: function(args) { 160 | let target = args[0] 161 | let level = args[1] 162 | let internalformat = args[2] 163 | let width = args[3] 164 | let height = args[4] 165 | let border = args[5] 166 | let format = args[6] 167 | let type = args[7] 168 | let data = args[8] 169 | 170 | let formatName = parseFormat(format) 171 | let internalformatName = parseFormat(internalformat) 172 | let typeName = parseType(type) 173 | const size = calculateDataSize(internalformatName, typeName, width, height); 174 | console.log(`glTexImage2D: target=${parseTarget(target)}, format=${formatName}, internalformat=${internalformatName}, width=${Number(width)}, height=${Number(height)}, type=${typeName}, data=${data}`) 175 | let textureData = data.readByteArray(size) 176 | send(`glTexImage2D:{"width": ${Number(width)}, "height": ${Number(height)}, "format": "${formatName}", "internalformat": "${internalformatName}", "type": "${typeName}"}`, textureData) 177 | 178 | }, 179 | onLeave: function(retval) {} 180 | }) 181 | 182 | let glTexSubImage2D = Module.findExportByName(gles_elf, "glTexSubImage2D") 183 | Interceptor.attach(glTexSubImage2D, { 184 | onEnter: function(args) { 185 | let target = args[0] 186 | let level = args[1] 187 | let xoffset = args[2] 188 | let yoffset = args[3] 189 | let width = args[4] 190 | let height = args[5] 191 | let format = args[6] 192 | let type = args[7] 193 | let data = args[8] 194 | 195 | let formatName = parseFormat(format) 196 | console.log(format) 197 | let typeName = parseType(type) 198 | const size = calculateDataSize(formatName, typeName, width, height); 199 | console.log(`glTexSubImage2D: target=${parseTarget(target)}, xoffset=${Number(xoffset)}, yoffset=${Number(yoffset)}, width=${Number(width)}, height=${Number(height)}, format=${formatName}, type=${typeName}, data=${data}`) 200 | let textureData = data.readByteArray(size) 201 | send(`glTexSubImage2D:{"xoffset": ${Number(xoffset)}, "yoffset": ${Number(yoffset)}, "width": ${Number(width)}, "height": ${Number(height)}, "format": "${formatName}", "type": "${typeName}"}`, textureData) 202 | }, 203 | onLeave: function(retval) {} 204 | }) 205 | } 206 | 207 | function hook_gl_bufferdata() { 208 | let glBufferData = Module.findExportByName(gles_elf, "glBufferData") 209 | Interceptor.attach(glBufferData, { 210 | onEnter: function(args) { 211 | let buffer = args[0] 212 | let bytesize = args[1] 213 | let data = args[2] 214 | let usage = args[3] 215 | console.log(`glBufferData: buffer=${Number(buffer)}, bytesize=${Number(bytesize)}, data=${data}, usage=${parseUsage(usage)}`) 216 | printStackTrace(this.context); 217 | }, 218 | onLeave: function(retval) {} 219 | }) 220 | } 221 | 222 | function main() { 223 | // hook_gl_shader() 224 | // hook_gl_texture() 225 | // hook_gl_bufferdata() 226 | } 227 | 228 | setImmediate(main); -------------------------------------------------------------------------------- /hook_android_inject.js: -------------------------------------------------------------------------------- 1 | function loaddex(dexPath, targetClassName, targetMethod) { 2 | let activityThreadObj = Java.use('android.app.ActivityThread').currentActivityThread() 3 | let classLoaderObj = activityThreadObj.getClass().getClassLoader() 4 | 5 | let dexClassLoaderObj = Java.use('dalvik.system.DexClassLoader').$new(dexPath, null, null, classLoaderObj) 6 | let ppsTaskClass = dexClassLoaderObj.findClass(targetClassName) 7 | ppsTaskClass.getDeclaredMethod(targetMethod, null).invoke(null, null) 8 | } 9 | 10 | function main() { 11 | let dexPath = 'test.dex' 12 | let targetClassName = 'com.wrlus.Example' 13 | let targetMethod = 'directCall' 14 | if (Java.available) { 15 | loaddex(dexPath, targetClassName, targetMethod) 16 | } 17 | } 18 | 19 | setImmediate(main) -------------------------------------------------------------------------------- /hook_android_mt.js: -------------------------------------------------------------------------------- 1 | function printStackTrace() { 2 | var stackTrace = Java.use("java.lang.Thread").currentThread().getStackTrace(); 3 | for (var i = 0; i < stackTrace.length; i++) { 4 | console.log(" " + (i + 1) + ". " + stackTrace[i].toString()); 5 | } 6 | } 7 | 8 | function hook_record() { 9 | let PugImplEnum = Java.use("com.meitu.pug.core.PugImplEnum"); 10 | PugImplEnum["printAndRecord"].implementation = function (level, tag, msg, obj, args) { 11 | console.log(`[ ${tag} ] ${msg}, ${obj}, ${args}`); 12 | this["printAndRecord"](level, tag, msg, obj, args); 13 | }; 14 | } 15 | 16 | 17 | function main() { 18 | if (Java.available) { 19 | Java.perform(function () { 20 | hook_record(); 21 | }); 22 | } 23 | } 24 | 25 | setImmediate(main); -------------------------------------------------------------------------------- /hook_android_webview.js: -------------------------------------------------------------------------------- 1 | function hook_webview() { 2 | var WebView = Java.use('android.webkit.WebView') 3 | WebView.loadUrl.overload('java.lang.String').implementation = function (url) { 4 | console.log('loadUrl: this = ' + this + ', url = ' + url); 5 | this.loadUrl(url); 6 | }; 7 | WebView.loadUrl.overload('java.lang.String', 'java.util.Map').implementation = function (url, params) { 8 | console.log('loadUrl: this = ' + this + ', url = ' + url); 9 | this.loadUrl(url, params); 10 | }; 11 | } 12 | 13 | function main() { 14 | if (Java.available) { 15 | Java.perform(function() { 16 | hook_webview(); 17 | }) 18 | } 19 | } 20 | 21 | setImmediate(main); -------------------------------------------------------------------------------- /hook_ios_bug.js: -------------------------------------------------------------------------------- 1 | function test() { 2 | var ViewController = ObjC.classes.ViewController 3 | Interceptor.attach(ViewController['+ functionTest:x3:x4:x5:x6:x7:stack1:stack2:stack3:stack4:stack5:'].implementation, { 4 | onEnter: function (args) { 5 | console.log('stack1: ' + args[8]) 6 | console.log('stack2: ' + args[9]) 7 | console.log('stack3: ' + args[10]) 8 | console.log('stack4: ' + args[11]) 9 | console.log('stack5: ' + args[12]) 10 | }, 11 | onLeave: function (retval) { 12 | 13 | } 14 | }); 15 | } 16 | 17 | function main() { 18 | if (ObjC.available) { 19 | test() 20 | } 21 | } 22 | 23 | setImmediate(main); -------------------------------------------------------------------------------- /hook_ios_scheme.js: -------------------------------------------------------------------------------- 1 | function hook_openurl() { 2 | var UIApplication = ObjC.classes.UIApplication 3 | Interceptor.attach(UIApplication['- _applicationOpenURLAction:payload:origin:'].implementation, { 4 | onEnter: function (args) { 5 | console.log('URL Scheme: ' + new ObjC.Object(args[2]).url()) 6 | }, 7 | onLeave: function (retval) { 8 | 9 | } 10 | }); 11 | 12 | Interceptor.attach(UIApplication['- activityContinuationManager:continueUserActivity:'].implementation, { 13 | onEnter: function (args) { 14 | console.log('Universal Link: ' + new ObjC.Object(args[3]).webpageURL()) 15 | }, 16 | onLeave: function (retval) { 17 | 18 | } 19 | }); 20 | Interceptor.attach(UIApplication['- openURL:options:completionHandler:'].implementation, { 21 | onEnter: function (args) { 22 | console.log('Open URL: ' + new ObjC.Object(args[2])) 23 | }, 24 | onLeave: function (retval) { 25 | 26 | } 27 | }); 28 | } 29 | 30 | function main() { 31 | if (ObjC.available) { 32 | hook_openurl() 33 | } 34 | } 35 | 36 | setImmediate(main); --------------------------------------------------------------------------------