From 137773052db18d869c6f8f8db493d39b00ca5b36 Mon Sep 17 00:00:00 2001 From: Perfare Date: Tue, 22 Feb 2022 10:34:30 +0800 Subject: [PATCH] =?UTF-8?q?=E8=BF=81=E7=A7=BB=E5=88=B0Zygisk=20=E6=9B=B4?= =?UTF-8?q?=E6=96=B0Dobby?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- gradle.properties | 7 +- module.gradle | 29 +- module/build.gradle | 54 +-- module/src/main/AndroidManifest.xml | 2 +- module/src/main/cpp/CMakeLists.txt | 17 +- module/src/main/cpp/Dobby/.clang-format | 8 +- module/src/main/cpp/Dobby/.gitignore | 7 +- module/src/main/cpp/Dobby/CMakeLists.txt | 200 ++++++----- module/src/main/cpp/Dobby/README.md | 31 +- .../Dobby/{ => build-workspace}/auto-build.sh | 47 ++- .../prefab/AndroidManifest.xml | 9 + .../dobby/libs/android.arm64-v8a/abi.json | 6 + .../dobby/libs/android.armeabi-v7a/abi.json | 6 + .../modules/dobby/libs/android.x86/abi.json | 6 + .../dobby/libs/android.x86_64/abi.json | 6 + .../prefab/modules/dobby/module.json | 4 + .../Dobby/build-workspace/prefab/prefab.json | 5 + .../MGCopyAnswerMonitor.cc | 14 +- .../dynamic_loader_monitor.cc | 2 +- .../file_operation_monitor.cc | 4 +- .../memory_operation_instrument.cc | 20 +- ...posix_file_descriptor_operation_monitor.cc | 4 +- .../bionic_linker_restriction.cc | 32 +- .../linker_restriction_demo.cc | 6 +- .../Dyld2HideLibrary/dyld2_hide_library.cc | 2 +- .../GlobalOffsetTableHook/CMakeLists.txt | 13 + .../global_offset_table_hook.cc | 66 ++-- .../global_offset_table_hook.h | 7 +- .../builtin-plugin/HideSystemCall/README | 1 + .../HideSystemCall/syscall.darwin.s | 0 .../HideSystemCall/syscall.linux.s | 0 .../IntegrityReadCallback/README | 1 + .../linker_load_callback.cc | 2 +- .../builtin-plugin/MemoryRemapHook/README | 1 + .../MemoryRemapHook/runtime_sdk.cc | 16 - .../ObjcRuntimeHook/objc_runtime_hook.h | 1 - .../ObjcRuntimeHook/objc_runtime_hook.mm | 14 +- .../SupervisorCallMonitor/CMakeLists.txt | 4 +- .../SupervisorCallMonitor/README | 1 + .../deprecated/mach_system_call.cc | 22 +- .../deprecated/system_call.cc | 36 +- .../mach_system_call_log_handler.cc | 47 ++- .../SupervisorCallMonitor/misc_utility.cc | 26 +- .../SupervisorCallMonitor/misc_utility.h | 12 +- .../sensitive_api_monitor.cc | 22 +- .../supervisor_call_monitor.cc | 74 ++-- .../system_call_log_handler.cc | 39 +- .../SymbolResolver/CMakeLists.txt | 37 ++ .../elf/dobby_symbol_resolver.cc | 62 ++-- .../macho/dobby_symbol_resolver.cc | 96 ++--- ...dyld_shared_cache_symbol_table_iterator.cc | 48 +-- .../macho/shared-cache/dyld_cache_format.h | 18 +- .../macho/shared_cache_internal.h | 35 +- .../pe/dobby_symbol_resolver.cc | 26 ++ .../cpp/Dobby/cmake/dobby.xcode.source.cmake | 20 +- module/src/main/cpp/Dobby/docs/CNAME | 1 - .../cpp/Dobby/docs/build-documentation.md | 64 ++-- .../cpp/Dobby/docs/get-started-android.md | 40 +-- .../main/cpp/Dobby/docs/get-started-ios.md | 14 +- module/src/main/cpp/Dobby/docs/get-started.md | 14 +- module/src/main/cpp/Dobby/docs/intro-board.md | 2 +- .../src/main/cpp/Dobby/example/CMakeLists.txt | 2 +- .../cpp/Dobby/example/android_common_api.cc | 28 +- .../cpp/Dobby/example/darwin_common_api.cc | 48 +-- .../external/external_helper/CMakeLists.txt | 16 - .../cpp/Dobby/external/logging/CMakeLists.txt | 10 +- .../external/logging/logging/check_logging.h | 48 +-- .../external/logging/logging/cxxlogging.h | 6 +- .../Dobby/external/logging/logging/logging.h | 32 +- .../Dobby/external/misc-helper/CMakeLists.txt | 16 + .../async_logger.cc | 12 +- .../misc-helper}/async_logger.h | 0 .../misc-helper}/variable_cache.h | 2 +- .../external/misc-helper/pthread_helper.cc | 147 ++++++++ .../external/misc-helper/pthread_helper.h | 86 +++++ .../external/misc-helper/unistd_helper.h | 32 ++ .../variable_cache.c | 18 +- .../cpp/Dobby/external/xnucxx/CMakeLists.txt | 16 +- .../cpp/Dobby/external/xnucxx/LiteIterator.cc | 4 +- .../Dobby/external/xnucxx/LiteMutableArray.cc | 22 +- .../external/xnucxx/LiteMutableBuffer.cc | 8 +- .../external/xnucxx/xnucxx/LiteMutableArray.h | 2 +- .../Dobby/external/xnucxx/xnucxx/LiteObject.h | 2 +- module/src/main/cpp/Dobby/include/dobby.h | 24 +- .../InstructionRelocation.h | 3 + .../arm/ARMInstructionRelocation.cc | 208 +++++------ .../arm/ARMInstructionRelocation.h | 33 +- .../arm64/ARM64InstructionRelocation.cc | 74 ++-- .../arm64/ARM64InstructionRelocation.h | 5 +- .../x64/X64InstructionRelocation.cc | 38 +- .../x64/X64InstructionRelocation.h | 11 +- .../x86/X86InstructionRelocation.cc | 31 +- .../x86/X86InstructionRelocation.h | 11 +- .../x86/deprecated/Ia32Disassembler.cc | 4 +- .../x86/deprecated/X86OpcodoDecodeTable.cc | 4 +- .../x86/deprecated/X86OpcodoDecodeTable.h | 4 +- .../x86/x86_insn_decode/build_config.h | 9 +- .../x86/x86_insn_decode/x86_insn_decode.c | 81 +++-- .../x86/x86_insn_decode/x86_insn_decode.h | 41 +-- .../IntegrityReadCallback.cc | 0 .../IntegrityReadCallback.h | 0 .../ExtraInternalPlugin/RegisterPlugin.cc | 15 - .../InterceptRouting/InterceptRouting.cpp | 79 ++-- .../InterceptRouting/InterceptRouting.h | 19 +- .../DynamicBinaryInstrumentExport.cc | 17 +- .../dynamic-binary-instrument.cc | 25 +- .../dynamic-binary-instrument.h | 4 +- .../intercept_routing_handler.cc | 12 +- .../intercept_routing_handler.h | 0 .../FunctionInlineReplaceExport.cc | 16 +- .../function-inline-replace.cc | 24 ++ .../function-inline-replace.h | 2 +- .../FunctionWrapper/FunctionWrapperExport.cc | 10 +- .../FunctionWrapper/function-wrapper.cc | 2 +- .../FunctionWrapper/function-wrapper.h | 2 +- .../intercept_routing_handler.cc | 14 +- .../intercept_routing_handler.h | 0 .../function-inline-replace.cc | 24 -- .../NeaBranchTrampoline.cc | 20 +- .../NearBranchTrampoline.h | 5 +- .../RoutingPlugin/RoutingPlugin.cc | 15 + .../RoutingPlugin.h} | 28 +- .../src/main/cpp/Dobby/source/Interceptor.cpp | 70 ++-- .../src/main/cpp/Dobby/source/Interceptor.h | 55 +-- .../MemoryAllocator/AssemblyCodeBuilder.cc | 12 +- .../CodeBuffer/code-buffer-arm.cc | 3 +- .../CodeBuffer/code-buffer-arm64.cc | 2 +- .../CodeBuffer/code-buffer-x64.cc | 2 +- .../CodeBuffer/code-buffer-x86.cc | 2 +- .../source/MemoryAllocator/MemoryArena.cc | 18 +- .../source/MemoryAllocator/MemoryArena.h | 10 +- .../source/MemoryAllocator/NearMemoryArena.cc | 132 +++++-- .../ExecMemory/ClearCacheTool.h | 9 +- .../PlatformUnifiedInterface/StdMemory.h | 8 +- .../AssemblyClosureTrampoline.h | 25 +- .../arm/ARMAssemblyClosureTrampoline.cc | 18 +- .../arm/closure-bridge-arm.cc | 8 +- .../ClosureTrampolineBridge/arm/helper-arm.cc | 2 +- .../arm64/ARM64AssemblyClosureTrampoline.cc | 19 +- .../arm64/closure-bridge-arm64.cc | 15 +- .../arm64/helper-arm64.cc | 2 +- .../closure-trampoline-common-handler.cc | 28 -- .../common-bridge-handler.cc | 22 ++ ...mmon-handler.h => common-bridge-handler.h} | 3 +- .../x64/X64AssemblyClosureTrampoline.cc | 31 +- .../x64/closure-bridge-x64.cc | 8 +- .../ClosureTrampolineBridge/x64/helper-x64.cc | 4 +- .../x86/X86AssemblyClosureTrampoline.cc | 22 +- .../x86/closure-bridge-x86.cc | 8 +- .../ClosureTrampolineBridge/x86/helper-x86.cc | 4 +- .../TrampolineBridge/Trampoline/Trampoline.h | 5 + .../arm/trampoline-arm.cc | 4 +- .../arm64/trampoline-arm64.cc | 18 +- .../x64/trampoline-x64.cc | 8 +- .../x86/trampoline-x86.cc | 6 +- .../ExecMemory/clear-cache-tool-all.c | 165 +++++++++ .../ExecMemory/clear-cache-tool-all.cc | 113 ------ .../clear-cache-tool-arm-dummy.cc | 2 +- .../clear-cache-tool-arm64-dummy.cc | 12 +- .../ExecMemory/code-patch-tool-darwin.cc | 65 ++-- .../ExecMemory/code-patch-tool-posix.cc | 4 +- .../ExecMemory/code-patch-tool-windows.cc | 2 +- .../ExecMemory/substrated/include/bootstrap.h | 34 +- .../ExecMemory/substrated/include/xpc/base.h | 80 ++--- .../substrated_client.h | 12 +- .../substrated_server.h | 24 +- .../MultiThreadSupport/ThreadSupport.h | 4 +- ...imeUtility.cc => ProcessRuntimeUtility.cc} | 16 +- ...imeUtility.cc => ProcessRuntimeUtility.cc} | 28 +- .../PlatformUtil/ProcessRuntimeUtility.h | 2 +- ...imeUtility.cc => ProcessRuntimeUtility.cc} | 42 +++ .../source/UserMode/Thread/PlatformThread.h | 2 +- .../UserMode/Thread/platform-thread-posix.cc | 6 +- .../platform-darwin/mach_vm.h | 340 +++++++++--------- .../UnifiedInterface/platform-posix.cc | 8 +- .../UnifiedInterface/platform-windows.cc | 27 +- .../UserMode/UnifiedInterface/platform.h | 8 +- .../UserMode/UnifiedInterface/semaphore.cc | 6 +- .../source/common/headers/common_header.h | 12 - .../source/common/macros/constants_macro.h | 8 - .../cpp/Dobby/source/core/arch/CpuFeature.h | 2 +- .../source/core/arch/arm/constants-arm.h | 14 +- .../source/core/arch/arm64/constants-arm64.h | 168 ++++----- .../source/core/arch/arm64/registers-arm64.h | 14 +- .../source/core/arch/x64/constants-x64.h | 10 +- .../source/core/arch/x64/registers-x64.h | 8 +- .../source/core/arch/x86/constants-x86.h | 10 +- .../cpp/Dobby/source/core/arch/x86/cpu-x86.cc | 72 ++-- .../cpp/Dobby/source/core/arch/x86/cpu-x86.h | 4 +- .../source/core/arch/x86/registers-x86.h | 8 +- .../core/modules/assembler/assembler-arm.cc | 2 +- .../core/modules/assembler/assembler-arm.h | 26 +- .../core/modules/assembler/assembler-arm64.cc | 14 +- .../core/modules/assembler/assembler-arm64.h | 54 +-- .../core/modules/assembler/assembler-ia32.cc | 2 +- .../core/modules/assembler/assembler-ia32.h | 20 +- .../core/modules/assembler/assembler-x64.cc | 2 +- .../core/modules/assembler/assembler-x64.h | 30 +- .../modules/assembler/assembler-x86-shared.cc | 2 +- .../modules/assembler/assembler-x86-shared.h | 20 +- .../core/modules/codegen/codegen-arm.cc | 2 +- .../core/modules/codegen/codegen-arm64.cc | 2 +- .../core/modules/codegen/codegen-ia32.cc | 6 +- .../core/modules/codegen/codegen-x64.cc | 6 +- module/src/main/cpp/Dobby/source/dobby.cpp | 2 +- .../main/cpp/Dobby/source/dobby_internal.h | 8 +- .../cpp/Dobby/source/include/common_header.h | 11 + .../cpp/Dobby/source/include/list_structure.h | 52 +++ .../macros => include}/platform_macro.h | 5 +- .../types_macro.h => include/type_macro.h} | 7 +- .../utility_macro.h} | 28 +- .../test_aarch64_instruction_relocation.cc | 4 +- .../x64/test_x64_instruction_relocation.cc | 14 +- module/src/main/cpp/include/config.h | 8 - module/src/main/cpp/main.cpp | 130 ++----- module/src/main/cpp/template/config.cpp | 8 - module/src/main/cpp/zygisk.hpp | 326 +++++++++++++++++ template/magisk_module/.gitattributes | 10 - template/magisk_module/README.md | 1 - template/magisk_module/customize.sh | 70 ---- template/magisk_module/riru.sh | 44 --- template/magisk_module/uninstall.sh | 2 - template/magisk_module/verify.sh | 39 -- 223 files changed, 3111 insertions(+), 2642 deletions(-) rename module/src/main/cpp/Dobby/{ => build-workspace}/auto-build.sh (72%) create mode 100644 module/src/main/cpp/Dobby/build-workspace/prefab/AndroidManifest.xml create mode 100644 module/src/main/cpp/Dobby/build-workspace/prefab/modules/dobby/libs/android.arm64-v8a/abi.json create mode 100644 module/src/main/cpp/Dobby/build-workspace/prefab/modules/dobby/libs/android.armeabi-v7a/abi.json create mode 100644 module/src/main/cpp/Dobby/build-workspace/prefab/modules/dobby/libs/android.x86/abi.json create mode 100644 module/src/main/cpp/Dobby/build-workspace/prefab/modules/dobby/libs/android.x86_64/abi.json create mode 100644 module/src/main/cpp/Dobby/build-workspace/prefab/modules/dobby/module.json create mode 100644 module/src/main/cpp/Dobby/build-workspace/prefab/prefab.json create mode 100644 module/src/main/cpp/Dobby/builtin-plugin/GlobalOffsetTableHook/CMakeLists.txt create mode 100644 module/src/main/cpp/Dobby/builtin-plugin/HideSystemCall/README delete mode 100644 module/src/main/cpp/Dobby/builtin-plugin/HideSystemCall/syscall.darwin.s delete mode 100644 module/src/main/cpp/Dobby/builtin-plugin/HideSystemCall/syscall.linux.s create mode 100644 module/src/main/cpp/Dobby/builtin-plugin/IntegrityReadCallback/README create mode 100644 module/src/main/cpp/Dobby/builtin-plugin/MemoryRemapHook/README delete mode 100644 module/src/main/cpp/Dobby/builtin-plugin/MemoryRemapHook/runtime_sdk.cc create mode 100644 module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/README create mode 100644 module/src/main/cpp/Dobby/builtin-plugin/SymbolResolver/CMakeLists.txt create mode 100644 module/src/main/cpp/Dobby/builtin-plugin/SymbolResolver/pe/dobby_symbol_resolver.cc delete mode 100644 module/src/main/cpp/Dobby/docs/CNAME delete mode 100644 module/src/main/cpp/Dobby/external/external_helper/CMakeLists.txt create mode 100644 module/src/main/cpp/Dobby/external/misc-helper/CMakeLists.txt rename module/src/main/cpp/Dobby/external/{external_helper => misc-helper}/async_logger.cc (81%) rename module/src/main/cpp/Dobby/external/{external_helper => misc-helper/misc-helper}/async_logger.h (100%) rename module/src/main/cpp/Dobby/external/{external_helper => misc-helper/misc-helper}/variable_cache.h (91%) create mode 100644 module/src/main/cpp/Dobby/external/misc-helper/pthread_helper.cc create mode 100644 module/src/main/cpp/Dobby/external/misc-helper/pthread_helper.h create mode 100644 module/src/main/cpp/Dobby/external/misc-helper/unistd_helper.h rename module/src/main/cpp/Dobby/external/{external_helper => misc-helper}/variable_cache.c (90%) create mode 100644 module/src/main/cpp/Dobby/source/InstructionRelocation/InstructionRelocation.h delete mode 100644 module/src/main/cpp/Dobby/source/InterceptRouting/ExtraInternalPlugin/IntegrityReadCallback.cc delete mode 100644 module/src/main/cpp/Dobby/source/InterceptRouting/ExtraInternalPlugin/IntegrityReadCallback.h delete mode 100644 module/src/main/cpp/Dobby/source/InterceptRouting/ExtraInternalPlugin/RegisterPlugin.cc rename module/src/main/cpp/Dobby/source/InterceptRouting/{RoutingPlugin => Routing}/DynamicBinaryInstrument/DynamicBinaryInstrumentExport.cc (61%) rename module/src/main/cpp/Dobby/source/InterceptRouting/{RoutingPlugin => Routing}/DynamicBinaryInstrument/dynamic-binary-instrument.cc (64%) rename module/src/main/cpp/Dobby/source/InterceptRouting/{RoutingPlugin => Routing}/DynamicBinaryInstrument/dynamic-binary-instrument.h (90%) rename module/src/main/cpp/Dobby/source/InterceptRouting/{RoutingPlugin => Routing}/DynamicBinaryInstrument/intercept_routing_handler.cc (65%) rename module/src/main/cpp/Dobby/source/InterceptRouting/{RoutingPlugin => Routing}/DynamicBinaryInstrument/intercept_routing_handler.h (100%) rename module/src/main/cpp/Dobby/source/InterceptRouting/{RoutingPlugin => Routing}/FunctionInlineReplace/FunctionInlineReplaceExport.cc (66%) create mode 100644 module/src/main/cpp/Dobby/source/InterceptRouting/Routing/FunctionInlineReplace/function-inline-replace.cc rename module/src/main/cpp/Dobby/source/InterceptRouting/{RoutingPlugin => Routing}/FunctionInlineReplace/function-inline-replace.h (94%) rename module/src/main/cpp/Dobby/source/InterceptRouting/{RoutingPlugin => Routing}/FunctionWrapper/FunctionWrapperExport.cc (69%) rename module/src/main/cpp/Dobby/source/InterceptRouting/{RoutingPlugin => Routing}/FunctionWrapper/function-wrapper.cc (96%) rename module/src/main/cpp/Dobby/source/InterceptRouting/{RoutingPlugin => Routing}/FunctionWrapper/function-wrapper.h (96%) rename module/src/main/cpp/Dobby/source/InterceptRouting/{RoutingPlugin => Routing}/FunctionWrapper/intercept_routing_handler.cc (89%) rename module/src/main/cpp/Dobby/source/InterceptRouting/{RoutingPlugin => Routing}/FunctionWrapper/intercept_routing_handler.h (100%) delete mode 100644 module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/FunctionInlineReplace/function-inline-replace.cc rename module/src/main/cpp/Dobby/source/InterceptRouting/{ExtraInternalPlugin => RoutingPlugin}/NearBranchTrampoline/NeaBranchTrampoline.cc (64%) rename module/src/main/cpp/Dobby/source/InterceptRouting/{ExtraInternalPlugin => RoutingPlugin}/NearBranchTrampoline/NearBranchTrampoline.h (74%) create mode 100644 module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/RoutingPlugin.cc rename module/src/main/cpp/Dobby/source/InterceptRouting/{ExtraInternalPlugin/RegisterPlugin.h => RoutingPlugin/RoutingPlugin.h} (71%) delete mode 100644 module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/closure-trampoline-common-handler.cc create mode 100644 module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/common-bridge-handler.cc rename module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/{closure-trampoline-common-handler.h => common-bridge-handler.h} (99%) create mode 100644 module/src/main/cpp/Dobby/source/TrampolineBridge/Trampoline/Trampoline.h rename module/src/main/cpp/Dobby/source/TrampolineBridge/{InterceptRoutingTrampoline => Trampoline}/arm/trampoline-arm.cc (93%) rename module/src/main/cpp/Dobby/source/TrampolineBridge/{InterceptRoutingTrampoline => Trampoline}/arm64/trampoline-arm64.cc (83%) rename module/src/main/cpp/Dobby/source/TrampolineBridge/{InterceptRoutingTrampoline => Trampoline}/x64/trampoline-x64.cc (85%) rename module/src/main/cpp/Dobby/source/TrampolineBridge/{InterceptRoutingTrampoline => Trampoline}/x86/trampoline-x86.cc (80%) create mode 100644 module/src/main/cpp/Dobby/source/UserMode/ExecMemory/clear-cache-tool-all.c delete mode 100644 module/src/main/cpp/Dobby/source/UserMode/ExecMemory/clear-cache-tool-all.cc rename module/src/main/cpp/Dobby/source/UserMode/PlatformUtil/Darwin/{ProcesssRuntimeUtility.cc => ProcessRuntimeUtility.cc} (88%) rename module/src/main/cpp/Dobby/source/UserMode/PlatformUtil/Linux/{ProcesssRuntimeUtility.cc => ProcessRuntimeUtility.cc} (92%) rename module/src/main/cpp/Dobby/source/UserMode/PlatformUtil/Windows/{ProcesssRuntimeUtility.cc => ProcessRuntimeUtility.cc} (51%) delete mode 100644 module/src/main/cpp/Dobby/source/common/headers/common_header.h delete mode 100644 module/src/main/cpp/Dobby/source/common/macros/constants_macro.h create mode 100644 module/src/main/cpp/Dobby/source/include/common_header.h create mode 100644 module/src/main/cpp/Dobby/source/include/list_structure.h rename module/src/main/cpp/Dobby/source/{common/macros => include}/platform_macro.h (89%) rename module/src/main/cpp/Dobby/source/{common/macros/types_macro.h => include/type_macro.h} (90%) rename module/src/main/cpp/Dobby/source/{common/macros/utilities_macro.h => include/utility_macro.h} (68%) delete mode 100644 module/src/main/cpp/include/config.h delete mode 100644 module/src/main/cpp/template/config.cpp create mode 100644 module/src/main/cpp/zygisk.hpp delete mode 100644 template/magisk_module/.gitattributes delete mode 100644 template/magisk_module/README.md delete mode 100644 template/magisk_module/customize.sh delete mode 100644 template/magisk_module/riru.sh delete mode 100644 template/magisk_module/uninstall.sh delete mode 100644 template/magisk_module/verify.sh diff --git a/gradle.properties b/gradle.properties index 73229782..01b80d70 100644 --- a/gradle.properties +++ b/gradle.properties @@ -6,17 +6,14 @@ # http://www.gradle.org/docs/current/userguide/build_environment.html # Specifies the JVM arguments used for the daemon process. # The setting is particularly useful for tweaking memory settings. -org.gradle.jvmargs=-Xmx1536m +org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 # When configured, Gradle will run in incubating parallel mode. # This option should only be used with decoupled projects. More details, visit # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects # org.gradle.parallel=true # AndroidX package structure to make it clearer which packages are bundled with the -# Android operating system, and which are packaged with your app's APK +# Android operating system, and which are packaged with your app"s APK # https://developer.android.com/topic/libraries/support-library/androidx-rn android.useAndroidX=true # Automatically convert third-party libraries to use AndroidX android.enableJetifier=true -# https://github.com/google/prefab/issues/122 -# Remove this until AGP update prefab version -android.prefabVersion=1.1.3 diff --git a/module.gradle b/module.gradle index 693c142b..b7a12926 100644 --- a/module.gradle +++ b/module.gradle @@ -1,30 +1,9 @@ ext { - /* - This name will be used in the name of the so file ("lib${moduleLibraryName}.so"). - */ moduleLibraryName = "il2cppdumper" - - /* Minimal supported Riru API version, used in the version check of riru.sh */ - moduleMinRiruApiVersion = 24 - - /* The version name of minimal supported Riru, used in the version check of riru.sh */ - moduleMinRiruVersionName = "v24.0.0" - - /* Maximum supported Riru API version, used in the version check of riru.sh */ - moduleRiruApiVersion = 26 - - /* - Magisk module ID - Since Magisk use it to distinguish different modules, you should never change it. - - Note, the older version of the template uses '-' instead of '_', if your are upgrading from - the older version, please pay attention. - */ - magiskModuleId = "riru_il2cppdumper" - + magiskModuleId = "zygisk_il2cppdumper" moduleName = "Il2CppDumper" moduleAuthor = "Perfare" - moduleDescription = "Il2CppDumper Riru version." - moduleVersion = "v26.0.0" - moduleVersionCode = 26 + moduleDescription = "Il2CppDumper Zygisk version." + moduleVersion = "v1.0.0" + moduleVersionCode = 1 } diff --git a/module/build.gradle b/module/build.gradle index 89588c6c..e31a8058 100644 --- a/module/build.gradle +++ b/module/build.gradle @@ -1,7 +1,7 @@ import org.apache.tools.ant.filters.FixCrLfFilter -import org.apache.tools.ant.filters.ReplaceTokens -import java.security.MessageDigest +import java.nio.file.Paths +import java.nio.file.Files apply plugin: 'com.android.library' apply from: file(rootProject.file('module.gradle')) @@ -13,11 +13,7 @@ android { targetSdkVersion rootProject.ext.targetSdkVersion externalNativeBuild { cmake { - arguments "-DMODULE_NAME:STRING=$moduleLibraryName", - "-DRIRU_MODULE_API_VERSION=$moduleRiruApiVersion", - "-DRIRU_MODULE_VERSION=$moduleVersionCode", - "-DRIRU_MODULE_VERSION_NAME:STRING=$moduleVersion", - "-DRIRU_MODULE_MIN_API_VERSION=$moduleMinRiruApiVersion" + arguments "-DMODULE_NAME:STRING=$moduleLibraryName" } } } @@ -27,7 +23,7 @@ android { externalNativeBuild { cmake { path "src/main/cpp/CMakeLists.txt" - version "3.10.2" + version "3.18.1" } } } @@ -36,19 +32,6 @@ repositories { mavenLocal() } -dependencies { - // This is prefab aar which contains "riru.h" - // If you want to use older versions of AGP, - // you can copy this file from https://github.com/RikkaApps/Riru/blob/master/riru/src/main/cpp/include_riru/riru.h - - // The default version of prefab in AGP has problem to process header only package, - // you may have to add "android.prefabVersion" in your gradle.properties. - // See https://github.com/google/prefab/issues/122 - - implementation 'dev.rikka.ndk:riru:26.0.0' -} - - afterEvaluate { android.libraryVariants.forEach { variant -> def variantCapped = variant.name.capitalize() @@ -64,18 +47,7 @@ afterEvaluate { into magiskDir from(templatePath) { - exclude 'riru.sh', 'module.prop' - } - from(templatePath) { - include 'riru.sh' - filter(ReplaceTokens.class, tokens: [ - "RIRU_MODULE_LIB_NAME" : moduleLibraryName, - "RIRU_MODULE_API_VERSION" : moduleRiruApiVersion.toString(), - "RIRU_MODULE_MIN_API_VERSION" : moduleMinRiruApiVersion.toString(), - "RIRU_MODULE_MIN_RIRU_VERSION_NAME": moduleMinRiruVersionName, - ]) - filter(FixCrLfFilter.class, - eol: FixCrLfFilter.CrLf.newInstance("lf")) + exclude 'module.prop' } from(templatePath) { include 'module.prop' @@ -94,16 +66,14 @@ afterEvaluate { into 'lib' } doLast { - fileTree("$magiskDir").visit { f -> - if (f.directory) return - if (f.file.name == '.gitattributes') return - - def md = MessageDigest.getInstance("SHA-256") - f.file.eachByte 4096, { bytes, size -> - md.update(bytes, 0, size) - } - file(f.file.path + ".sha256sum").text = md.digest().encodeHex() + file("$magiskDir/zygisk").mkdir() + fileTree("$magiskDir/lib").visit { f -> + if (!f.directory) return + def srcPath = Paths.get("${f.file.absolutePath}/lib${moduleLibraryName}.so") + def dstPath = Paths.get("$magiskDir/zygisk/${f.path}.so") + Files.move(srcPath, dstPath) } + new File("$magiskDir/lib").deleteDir() } } diff --git a/module/src/main/AndroidManifest.xml b/module/src/main/AndroidManifest.xml index 235c6578..762b99d9 100644 --- a/module/src/main/AndroidManifest.xml +++ b/module/src/main/AndroidManifest.xml @@ -1 +1 @@ - + diff --git a/module/src/main/cpp/CMakeLists.txt b/module/src/main/cpp/CMakeLists.txt index 8866be17..87d0bf5a 100644 --- a/module/src/main/cpp/CMakeLists.txt +++ b/module/src/main/cpp/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.4.1) +cmake_minimum_required(VERSION 3.18.1) if (NOT DEFINED MODULE_NAME) message(FATAL_ERROR "MODULE_NAME is not set") @@ -13,16 +13,13 @@ include_directories( macro(SET_OPTION option value) set(${option} ${value} CACHE INTERNAL "" FORCE) endmacro() +SET_OPTION(DOBBY_DEBUG OFF) SET_OPTION(DOBBY_GENERATE_SHARED OFF) add_subdirectory(${DobbyHome} dobby) -add_definitions(-DRIRU_MODULE) - -configure_file(template/config.cpp config.cpp) - message("Build type: ${CMAKE_BUILD_TYPE}") -set(CMAKE_CXX_STANDARD 11) +set(CMAKE_CXX_STANDARD 20) set(LINKER_FLAGS "-ffixed-x18 -Wl,--hash-style=both") set(C_FLAGS "-Werror=format -fdata-sections -ffunction-sections") @@ -41,12 +38,8 @@ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${C_FLAGS} ${CXX_FLAGS}") set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${LINKER_FLAGS}") set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} ${LINKER_FLAGS}") -find_package(riru REQUIRED CONFIG) - -include_directories(include) - -add_library(${MODULE_NAME} SHARED main.cpp ${CMAKE_CURRENT_BINARY_DIR}/config.cpp hook.cpp il2cpp_dump.cpp) -target_link_libraries(${MODULE_NAME} log riru::riru dobby) +add_library(${MODULE_NAME} SHARED main.cpp hook.cpp il2cpp_dump.cpp) +target_link_libraries(${MODULE_NAME} log dobby) if (NOT CMAKE_BUILD_TYPE STREQUAL "Debug") add_custom_command(TARGET ${MODULE_NAME} POST_BUILD diff --git a/module/src/main/cpp/Dobby/.clang-format b/module/src/main/cpp/Dobby/.clang-format index 4838347e..17d6bc41 100644 --- a/module/src/main/cpp/Dobby/.clang-format +++ b/module/src/main/cpp/Dobby/.clang-format @@ -5,10 +5,12 @@ TabWidth: 2 UseTab: Never ColumnLimit: 120 +FixNamespaceComments: true + # default is false -AlignConsecutiveMacros: true -AlignConsecutiveAssignments: true -AlignConsecutiveDeclarations: true +#AlignConsecutiveMacros: true +#AlignConsecutiveAssignments: true +#AlignConsecutiveDeclarations: true # default is true ReflowComments: false diff --git a/module/src/main/cpp/Dobby/.gitignore b/module/src/main/cpp/Dobby/.gitignore index 9092c458..4bbed764 100644 --- a/module/src/main/cpp/Dobby/.gitignore +++ b/module/src/main/cpp/Dobby/.gitignore @@ -72,4 +72,9 @@ xcuserdata/ # Executables *.exe *.out -*.app \ No newline at end of file +*.app + +# Prefab +/prefab/**/*.a +/prefab/**/*.h +/AndroidManifest.xml diff --git a/module/src/main/cpp/Dobby/CMakeLists.txt b/module/src/main/cpp/Dobby/CMakeLists.txt index eaa7615d..8ae9820f 100644 --- a/module/src/main/cpp/Dobby/CMakeLists.txt +++ b/module/src/main/cpp/Dobby/CMakeLists.txt @@ -19,12 +19,10 @@ if(0) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Wextra -Werror") endif() -set(CMAKE_CXX_FLAGS "${CMAKE_C_FLAGS} ${CMAKE_CXX_FLAGS}") - # ===== Handle Option ===== option(DOBBY_GENERATE_SHARED "Build shared library" ON) -option(DOBBY_DEBUG "Enable debug logging" ON) +option(DOBBY_DEBUG "Enable debug logging" OFF) option(NearBranch "Enable Near Branch Trampoline" ON) @@ -32,7 +30,7 @@ option(DynamicBinaryInstrument "Enable Dynamic Binary Instrument" ON) option(FullFloatingPointRegisterPack "Save and pack all floating-point registers" OFF) -option(GenerateDarwinFramework "Build darwin framework library" ON) +option(EnableObfuscation "Enable llvm obfuscation" OFF) option(Plugin.SymbolResolver "Resolve symbol by [DobbySymbolResolver] " ON) @@ -52,8 +50,9 @@ option(Plugin.Android.BionicLinkerRestriction "Enable android bionic linker rest # add_definitions(-DENABLE_CLOSURE_BRIDGE_TEMPLATE) # endif() -# Enable debug will log more infomation -if (CMAKE_BUILD_TYPE STREQUAL "Debug") +# Enable debug will log more information +if ((NOT DEFINED CMAKE_BUILD_TYPE) OR (CMAKE_BUILD_TYPE STREQUAL "Debug")) + message(STATUS "[Dobby] Enabling debug logging because CMAKE_BUILD_TYPE is Debug or undefined") set(DOBBY_DEBUG ON) endif() if(DOBBY_DEBUG) @@ -69,16 +68,17 @@ if(FullFloatingPointRegisterPack) message(STATUS "[Dobby] Save and pack all floating-point registers") endif() - if(SYSTEM.Darwin) # -lstdc++ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -stdlib=libc++") if (NOT DOBBY_DEBUG) - set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-s -Wl,-X -Wl,-dead_strip") - set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-exported_symbol,_log_internal_impl") + set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-x -Wl,-S") + set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-exported_symbol,_log_internal_impl -Wl,-exported_symbol,_log_set_level") set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-exported_symbol,_CodePatch") - set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-exported_symbol,_DobbyBuildVersion -Wl,-exported_symbol,_DobbyHook -Wl,-exported_symbol,_DobbyInstrument") + set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-exported_symbol,_DobbyBuildVersion -Wl,-exported_symbol,_DobbyHook -Wl,-exported_symbol,_DobbyInstrument -Wl,-exported_symbol,_DobbyDestroy") + set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-exported_symbol,_DobbyGlobalOffsetTableReplace") set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-exported_symbol,_DobbySymbolResolver") + set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-exported_symbol,_intercept_routing_common_bridge_handler") set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-exported_symbol,_dobby_enable_near_branch_trampoline -Wl,-exported_symbol,_dobby_disable_near_branch_trampoline") endif() elseif(SYSTEM.Android) @@ -90,6 +90,7 @@ elseif(SYSTEM.Android) elseif(SYSTEM.Linux) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fPIC") elseif(SYSTEM.Windows) + add_definitions(-D_CRT_SECURE_NO_WARNINGS -D_CRT_NONSTDC_NO_DEPRECATE -D_CRT_SECURE_NO_DEPRECATE) if(NOT DOBBY_DEBUG) set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} /export:log_internal_impl") set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} /export:DobbyHook /export:DobbyInstrument /export:DobbySymbolResolver") @@ -99,7 +100,8 @@ endif() if(COMPILER.Clang) if(NOT DOBBY_DEBUG) - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O3 -fno-rtti -fvisibility=hidden -fvisibility-inlines-hidden") + # set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O3") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fno-rtti -fvisibility=hidden -fvisibility-inlines-hidden") endif() if(PROCESSOR.ARM) set(CMAKE_ASM_FLAGS "${CMAKE_ASM_FLAGS} -arch armv7 -x assembler-with-cpp") @@ -108,12 +110,14 @@ if(COMPILER.Clang) endif() endif() -# refer apple ld -# set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-unexported_symbol -Wl,_DobbyHook -Wl,-unexported_symbol -Wl,_DobbyInstrument -Wl,-unexported_symbol -Wl,_DobbySymbolResolver -Wl,-unexported_symbol -Wl,_svc_0x80_stub -Wl,-unexported_symbol -Wl,_svc_mprotect") -# set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-s -Wl,-X -Wl,-dead_strip -Wl,-exported_symbol,_main") - set(CMAKE_CXX_FLAGS "${CMAKE_C_FLAGS} ${CMAKE_CXX_FLAGS}") +message(STATUS "CMAKE_C_COMPILER: ${CMAKE_C_COMPILER}") +message(STATUS "CMAKE_CXX_COMPILER: ${CMAKE_CXX_COMPILER}") +message(STATUS "CMAKE_C_FLAGS: ${CMAKE_C_FLAGS}") +message(STATUS "CMAKE_CXX_FLAGS: ${CMAKE_CXX_FLAGS}") +message(STATUS "CMAKE_SHARED_LINKER_FLAGS: ${CMAKE_SHARED_LINKER_FLAGS}") + # arch prefix if(PROCESSOR.ARM) set(ARCH1 ARM) @@ -151,6 +155,24 @@ if(CMAKE_GENERATOR STREQUAL Xcode) endif() include(cmake/dobby.xcode.source.cmake) +include_directories( + . + + ./include + + ./source + ./source/include + ./source/UserMode + + ./external + ./external/logging + ./external/xnucxx + ./external/misc-helper + + builtin-plugin +) + +set(DOBBY_DIR ${CMAKE_CURRENT_SOURCE_DIR}) set(dobby.SOURCE_FILE_LIST ${dobby.SOURCE_FILE_LIST} # cpu source/core/arch/CpuFeature.cc @@ -176,24 +198,24 @@ set(dobby.SOURCE_FILE_LIST ${dobby.SOURCE_FILE_LIST} source/InterceptRouting/InterceptRouting.cpp # intercept routing trampoline - source/TrampolineBridge/InterceptRoutingTrampoline/${arch1}/trampoline-${arch1}.cc + source/TrampolineBridge/Trampoline/${arch1}/trampoline-${arch1}.cc # intercept routing plugin (buildin) - source/InterceptRouting/RoutingPlugin/FunctionInlineReplace/function-inline-replace.cc - source/InterceptRouting/RoutingPlugin/FunctionInlineReplace/FunctionInlineReplaceExport.cc + source/InterceptRouting/Routing/FunctionInlineReplace/function-inline-replace.cc + source/InterceptRouting/Routing/FunctionInlineReplace/FunctionInlineReplaceExport.cc # plugin register - source/InterceptRouting/ExtraInternalPlugin/RegisterPlugin.cc + source/InterceptRouting/RoutingPlugin/RoutingPlugin.cc # platform util - source/UserMode/PlatformUtil/${platform2}/ProcesssRuntimeUtility.cc + source/UserMode/PlatformUtil/${platform2}/ProcessRuntimeUtility.cc # user mode - platform interface source/UserMode/UnifiedInterface/platform-${platform1}.cc # user mode - executable memory source/UserMode/ExecMemory/code-patch-tool-${platform1}.cc - source/UserMode/ExecMemory/clear-cache-tool-all.cc + source/UserMode/ExecMemory/clear-cache-tool-all.c # main source/dobby.cpp @@ -227,7 +249,7 @@ endif() if(FunctionWrapper OR DynamicBinaryInstrument) set(dobby.SOURCE_FILE_LIST ${dobby.SOURCE_FILE_LIST} # closure trampoline bridge - source/TrampolineBridge/ClosureTrampolineBridge/closure-trampoline-common-handler.cc + source/TrampolineBridge/ClosureTrampolineBridge/common-bridge-handler.cc source/TrampolineBridge/ClosureTrampolineBridge/${arch1}/helper-${arch1}.cc source/TrampolineBridge/ClosureTrampolineBridge/${arch1}/closure-bridge-${arch1}.cc source/TrampolineBridge/ClosureTrampolineBridge/${arch1}/${ARCH1}AssemblyClosureTrampoline.cc @@ -246,72 +268,50 @@ endif() if(DynamicBinaryInstrument) message(STATUS "[Dobby] Enable dynamic binary instrument(hook instruction with register context)") set(dobby.SOURCE_FILE_LIST ${dobby.SOURCE_FILE_LIST} - source/InterceptRouting/RoutingPlugin/DynamicBinaryInstrument/dynamic-binary-instrument.cc - source/InterceptRouting/RoutingPlugin/DynamicBinaryInstrument/DynamicBinaryInstrumentExport.cc - source/InterceptRouting/RoutingPlugin/DynamicBinaryInstrument/intercept_routing_handler.cc + source/InterceptRouting/Routing/DynamicBinaryInstrument/dynamic-binary-instrument.cc + source/InterceptRouting/Routing/DynamicBinaryInstrument/DynamicBinaryInstrumentExport.cc + source/InterceptRouting/Routing/DynamicBinaryInstrument/intercept_routing_handler.cc ) endif() if(NearBranch) message(STATUS "[Dobby] Enable near branch trampoline(trampoline within single instruction)") set(dobby.SOURCE_FILE_LIST ${dobby.SOURCE_FILE_LIST} - source/InterceptRouting/ExtraInternalPlugin/NearBranchTrampoline/NeaBranchTrampoline.cc + source/InterceptRouting/RoutingPlugin/NearBranchTrampoline/NeaBranchTrampoline.cc source/MemoryAllocator/NearMemoryArena.cc) endif() -add_subdirectory(external/external_helper) +add_subdirectory(external/misc-helper) +get_target_property(misc_helper.SOURCE_FILE_LIST misc_helper SOURCES) # add logging library -# add_subdirectory(external/logging) -set(logging.SOURCE_FILE_LIST - external/logging/logging.c - external/logging/cxxlogging.cc - ) +add_subdirectory(external/logging) +get_target_property(logging.SOURCE_FILE_LIST logging SOURCES) # add xnucxx library -# add_subdirectory(external/xnucxx) -set(xnucxx.SOURCE_FILE_LIST - external/xnucxx/LiteObject.cc - external/xnucxx/LiteMemOpt.cc - external/xnucxx/LiteCollection.cc - external/xnucxx/LiteIterator.cc - external/xnucxx/LiteMutableArray.cc - external/xnucxx/LiteMutableBuffer.cc - ) +add_subdirectory(external/xnucxx) +get_target_property(xnucxx.SOURCE_FILE_LIST xnucxx SOURCES) -set(dobby.plugin.SOURCE_FILE_LIST -) - -set(dobby.HEADER_FILE_LIST - include/dobby.h - ) +if(Plugin.GlobalOffsetTableHook AND SYSTEM.Darwin) + message(STATUS "[Dobby] Enable global offset table hook") -if(Plugin.GlobalOffsetTableHook) include_directories(builtin-plugin/GlobalOffsetTableHook) - - message(STATUS "[Dobby] Enable Global offset table hook") - if(SYSTEM.Darwin) - set(dobby.plugin.SOURCE_FILE_LIST ${dobby.plugin.SOURCE_FILE_LIST} - builtin-plugin/GlobalOffsetTableHook/global_offset_table_hook.cc + add_subdirectory(builtin-plugin/GlobalOffsetTableHook) + get_target_property(global_offset_table_hook.SOURCE_FILE_LIST global_offset_table_hook SOURCES) + set(dobby.plugin.SOURCE_FILE_LIST ${dobby.plugin.SOURCE_FILE_LIST} + ${global_offset_table_hook.SOURCE_FILE_LIST} ) - endif() endif() if(Plugin.SymbolResolver) - include_directories(builtin-plugin/SymbolResolver) - message(STATUS "[Dobby] Enable symbol resolver") - if(SYSTEM.Darwin) - set(dobby.plugin.SOURCE_FILE_LIST ${dobby.plugin.SOURCE_FILE_LIST} - builtin-plugin/SymbolResolver/macho/dyld_shared_cache_symbol_table_iterator.cc - builtin-plugin/SymbolResolver/macho/dobby_symbol_resolver.cc - ) - endif() - if(SYSTEM.Linux OR SYSTEM.Android) - set(dobby.plugin.SOURCE_FILE_LIST ${dobby.plugin.SOURCE_FILE_LIST} - builtin-plugin/SymbolResolver/elf/dobby_symbol_resolver.cc + + include_directories(builtin-plugin/SymbolResolver) + add_subdirectory(builtin-plugin/SymbolResolver) + get_target_property(symbol_resolver.SOURCE_FILE_LIST symbol_resolver SOURCES) + set(dobby.plugin.SOURCE_FILE_LIST ${dobby.plugin.SOURCE_FILE_LIST} + ${symbol_resolver.SOURCE_FILE_LIST} ) - endif() endif() if(Plugin.Android.BionicLinkerRestriction) @@ -335,20 +335,9 @@ if(Plugin.LinkerLoadCallback) ) endif() -include_directories( - . - - ./include - - ./source - ./source/UserMode - - ./external - ./external/logging - ./external/xnucxx - - builtin-plugin -) +set(dobby.HEADER_FILE_LIST + include/dobby.h + ) # add build version string(TIMESTAMP TODAY "%Y%m%d") @@ -368,26 +357,35 @@ set(DOBBY_BUILD_VERSION "Dobby${VERSION_REVISION}") add_definitions(-D__DOBBY_BUILD_VERSION__="${DOBBY_BUILD_VERSION}") message(STATUS "[Dobby] ${DOBBY_BUILD_VERSION}") -# upper framework output name -set(dobby_output_name dobby) -if(SYSTEM.Darwin AND GenerateDarwinFramework) - message(STATUS "[Dobby] Generate darwin framework") - set(dobby_output_name Dobby) -endif() - if(DOBBY_GENERATE_SHARED) message(STATUS "[Dobby] Generate shared library") - add_library(${dobby_output_name} SHARED ${dobby.HEADER_FILE_LIST} ${dobby.SOURCE_FILE_LIST} ${logging.SOURCE_FILE_LIST} ${xnucxx.SOURCE_FILE_LIST} ${dobby.plugin.SOURCE_FILE_LIST}) + set(DOBBY_LIBRARY_TYPE SHARED) else() message(STATUS "[Dobby] Generate static library") - add_library(${dobby_output_name} STATIC ${dobby.HEADER_FILE_LIST} ${dobby.SOURCE_FILE_LIST} ${logging.SOURCE_FILE_LIST} ${xnucxx.SOURCE_FILE_LIST} ${dobby.plugin.SOURCE_FILE_LIST}) + set(DOBBY_LIBRARY_TYPE STATIC) endif() +add_library(dobby ${DOBBY_LIBRARY_TYPE} ${dobby.HEADER_FILE_LIST} ${dobby.SOURCE_FILE_LIST} ${logging.SOURCE_FILE_LIST} ${xnucxx.SOURCE_FILE_LIST} ${dobby.plugin.SOURCE_FILE_LIST}) -target_include_directories(${dobby_output_name} PUBLIC include) +target_include_directories(dobby PUBLIC include) + +if(EnableObfuscation) +set(linker_flags "${linker_flags} -Wl,-mllvm -Wl,-obfuscator-conf=all") +endif() +set_target_properties(dobby + PROPERTIES LINK_FLAGS "${linker_flags}" + ) +if(SYSTEM.Darwin) + # set(CMAKE_BUILD_WITH_INSTALL_NAME_DIR TRUE) + set(CMAKE_INSTALL_NAME_DIR "@rpath") + set(CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG "-Wl,-rpath,") + add_library(DobbyX ${DOBBY_LIBRARY_TYPE} ${dobby.HEADER_FILE_LIST} ${dobby.SOURCE_FILE_LIST} ${logging.SOURCE_FILE_LIST} ${xnucxx.SOURCE_FILE_LIST} ${dobby.plugin.SOURCE_FILE_LIST}) + + set_target_properties(DobbyX + PROPERTIES LINK_FLAGS "${linker_flags}" + ) -if(SYSTEM.Darwin AND GenerateDarwinFramework) # set framework property - set_target_properties(Dobby PROPERTIES + set_target_properties(DobbyX PROPERTIES FRAMEWORK TRUE FRAMEWORK_VERSION A MACOSX_FRAMEWORK_IDENTIFIER "com.dobby.dobby" @@ -397,6 +395,9 @@ if(SYSTEM.Darwin AND GenerateDarwinFramework) PUBLIC_HEADER include/dobby.h XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY "Apple Development" ) + # set_target_properties(Dobby PROPERTIES + # LINK_FLAGS "${CMAKE_SHARED_LINKER_FLAGS}" + # ) # message(STATUS "[Dobby] Enable Gollum.framework(iOS: 11.0 <= version, version <= 12.2, version == 12.4 )") # add_custom_command(TARGET Dobby @@ -415,14 +416,25 @@ if(SYSTEM.Linux) endif() if(SYSTEM.Darwin) - target_link_libraries(${dobby_output_name} + target_link_libraries(DobbyX "-framework Foundation") endif() +if(SYSTEM.Darwin) + install(TARGETS DobbyX + FRAMEWORK DESTINATION Framework) +endif() + +install(TARGETS dobby + LIBRARY DESTINATION lib) + if(SYSTEM.Darwin) add_subdirectory(builtin-plugin/Dyld2HideLibrary) - add_subdirectory(builtin-plugin/SupervisorCallMonitor) add_subdirectory(builtin-plugin/ObjcRuntimeHook) + if(PROCESSOR.AARCH64) + add_subdirectory(builtin-plugin/SupervisorCallMonitor) + endif() endif() add_subdirectory(example) + diff --git a/module/src/main/cpp/Dobby/README.md b/module/src/main/cpp/Dobby/README.md index bb197a76..43e39471 100644 --- a/module/src/main/cpp/Dobby/README.md +++ b/module/src/main/cpp/Dobby/README.md @@ -1,6 +1,6 @@ ## Dobby -[![Contact me Telegram](https://img.shields.io/badge/Contact%20me-Telegram-blue.svg)](https://t.me/RadeonRayTrace) [![Join group Telegram](https://img.shields.io/badge/Join%20group-Telegram-brightgreen.svg)](https://t.me/dobby_group) +[![Contact me Telegram](https://img.shields.io/badge/Contact%20me-Telegram-blue.svg)](https://t.me/IOFramebuffer) [![Join group Telegram](https://img.shields.io/badge/Join%20group-Telegram-brightgreen.svg)](https://t.me/dobby_group) Dobby a lightweight, multi-platform, multi-architecture exploit hook framework. @@ -27,36 +27,9 @@ Or download [latest release](https://github.com/jmpews/Dobby/releases/tag/latest #### [Getting Started with Android](docs/get-started-android.md) -## Quick demo - -#### iOS ARM64E - -``` -void *posix_spawn_ptr = __builtin_ptrauth_strip((void *)posix_spawn, ptrauth_key_asia); -void *fake_posix_spawn_ptr = __builtin_ptrauth_strip((void *)fake_posix_spawn, ptrauth_key_asia); -DobbyHook((void *)posix_spawn_ptr, (void *)fake_posix_spawn_ptr, (void **)&orig_posix_spawn); -*(void **)&orig_posix_spawn = (void *)ptrauth_sign_unauthenticated((void *)orig_posix_spawn, ptrauth_key_asia, 0); -``` - -#### Android Linker Restriction - -``` -# impl at SymbolResolver/elf/dobby_symbol_resolver.cc -void *__loader_dlopen = DobbySymbolResolver(NULL, "__loader_dlopen"); -DobbyHook((void *)__loader_dlopen, (void *)fake_loader_dlopen, (void **)&orig_loader_dlopen); -``` - -``` -# impl at AndroidRestriction/android_restriction.cc -linker_disable_namespace_restriction(); -void *handle = NULL; -handle = dlopen(lib, RTLD_LAZY); -vm = dlsym(handle, "_ZN7android14AndroidRuntime7mJavaVME"); -``` - ## Documentation -[full Installation documentation site](http://dobby.libkernel.com) +[full Installation documentation site](https://jmpews.github.io/Dobby/#/) ## Download diff --git a/module/src/main/cpp/Dobby/auto-build.sh b/module/src/main/cpp/Dobby/build-workspace/auto-build.sh similarity index 72% rename from module/src/main/cpp/Dobby/auto-build.sh rename to module/src/main/cpp/Dobby/build-workspace/auto-build.sh index 71ed0f53..72542e66 100644 --- a/module/src/main/cpp/Dobby/auto-build.sh +++ b/module/src/main/cpp/Dobby/build-workspace/auto-build.sh @@ -4,6 +4,7 @@ set - CURRENT_DIR=$(dirname "$0") +SOURCE_DIR=${CURRENT_DIR}/.. compress_dir_array="" @@ -21,8 +22,8 @@ output_dir_name=auto-build-workspace/darwin-x86_64-build echo "prepare build ${output_dir_name}" mkdir -p ${CURRENT_DIR}/${output_dir_name} -cmake -S . -B ${output_dir_name} -DCMAKE_BUILD_TYPE=Release \ - -DDOBBY_GENERATE_SHARED=OFF -DGenerateDarwinFramework=OFF -DDOBBY_DEBUG=OFF +cmake -S ${SOURCE_DIR} -B ${output_dir_name} -DCMAKE_BUILD_TYPE=Release \ + -DDOBBY_GENERATE_SHARED=OFF -DDOBBY_DEBUG=OFF cmake --build ${output_dir_name} --parallel 4 --target dobby mkdir -p ${summary_output_dir_name}/darwin/x86_64 @@ -34,11 +35,9 @@ compress_dir_array="$compress_dir_array $output_dir_name" echo "prepare build ${output_dir_name}" mkdir -p ${CURRENT_DIR}/${output_dir_name} -cmake -S . -B ${output_dir_name} -DCMAKE_BUILD_TYPE=Release \ - -DCMAKE_TOOLCHAIN_FILE=cmake/ios.toolchain.cmake \ - -DPLATFORM=OS64 -DARCHS="arm64" -DCMAKE_SYSTEM_PROCESSOR=arm64 \ - -DENABLE_BITCODE=0 -DENABLE_ARC=0 -DENABLE_VISIBILITY=1 -DDEPLOYMENT_TARGET=9.3 \ - -DDOBBY_GENERATE_SHARED=OFF -DGenerateDarwinFramework=OFF -DDOBBY_DEBUG=OFF +cmake -S ${SOURCE_DIR} -B ${output_dir_name} -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_SYSTEM_NAME=iOS -DCMAKE_OSX_ARCHITECTURES=arm64 -DCMAKE_SYSTEM_PROCESSOR=arm64 -DCMAKE_OSX_DEPLOYMENT_TARGET=9.3 \ + -DDOBBY_GENERATE_SHARED=OFF -DDOBBY_DEBUG=OFF cmake --build ${output_dir_name} --parallel 4 --target dobby mkdir -p ${summary_output_dir_name}/darwin/arm64 @@ -50,11 +49,11 @@ compress_dir_array="$compress_dir_array $output_dir_name" echo "prepare build ${output_dir_name}" mkdir -p ${CURRENT_DIR}/${output_dir_name} -cmake -S . -B ${output_dir_name} -DCMAKE_BUILD_TYPE=Release \ +cmake -S ${SOURCE_DIR} -B ${output_dir_name} -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_TOOLCHAIN_FILE=cmake/ios.toolchain.cmake \ -DPLATFORM=OS64 -DARCHS="arm64e" -DCMAKE_SYSTEM_PROCESSOR=arm64e \ -DENABLE_BITCODE=0 -DENABLE_ARC=0 -DENABLE_VISIBILITY=1 -DDEPLOYMENT_TARGET=9.3 \ - -DDOBBY_GENERATE_SHARED=OFF -DGenerateDarwinFramework=OFF -DDOBBY_DEBUG=OFF + -DDOBBY_GENERATE_SHARED=OFF -DDOBBY_DEBUG=OFF cmake --build ${output_dir_name} --parallel 4 --target dobby mkdir -p ${summary_output_dir_name}/darwin/arm64e @@ -86,53 +85,65 @@ output_dir_name=auto-build-workspace/android-arm64-build compress_dir_array="$compress_dir_array $output_dir_name" echo "prepare build ${output_dir_name}" -cmake -S . -B ${output_dir_name} -DCMAKE_BUILD_TYPE=Release \ +cmake -S ${SOURCE_DIR} -B ${output_dir_name} -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_SYSTEM_NAME=Android -DCMAKE_ANDROID_ARCH_ABI="arm64-v8a" -DCMAKE_ANDROID_NDK=$ANDROID_NDK_DIR -DCMAKE_SYSTEM_VERSION=21 -DCMAKE_ANDROID_NDK_TOOLCHAIN_VERSION=clang \ - -DDOBBY_GENERATE_SHARED=OFF -DDOBBY_DEBUG=OFF + -DDOBBY_GENERATE_SHARED=OFF -DDOBBY_DEBUG=OFF -DPlugin.Android.BionicLinkerRestriction=ON cmake --build ${output_dir_name} --parallel 4 --target dobby mkdir -p ${summary_output_dir_name}/android/arm64 mv ${output_dir_name}/${android_library_name} ${summary_output_dir_name}/android/arm64/${android_library_name} +mv ${output_dir_name}/${android_library_name} "prefab/modules/dobby/libs/android.arm64-v8a/${android_library_name}" # build android armv7 output_dir_name=auto-build-workspace/android-armv7-build compress_dir_array="$compress_dir_array $output_dir_name" echo "prepare build ${output_dir_name}" -cmake -S . -B ${output_dir_name} -DCMAKE_BUILD_TYPE=Release \ +cmake -S ${SOURCE_DIR} -B ${output_dir_name} -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_SYSTEM_NAME=Android -DCMAKE_ANDROID_ARCH_ABI="armeabi-v7a" -DCMAKE_ANDROID_NDK=$ANDROID_NDK_DIR -DCMAKE_SYSTEM_VERSION=16 -DCMAKE_ANDROID_NDK_TOOLCHAIN_VERSION=clang \ - -DDOBBY_GENERATE_SHARED=OFF -DDOBBY_DEBUG=OFF + -DDOBBY_GENERATE_SHARED=OFF -DDOBBY_DEBUG=OFF -DPlugin.Android.BionicLinkerRestriction=ON cmake --build ${output_dir_name} --parallel 4 --target dobby mkdir -p ${summary_output_dir_name}/android/armv7 mv ${output_dir_name}/${android_library_name} ${summary_output_dir_name}/android/armv7/${android_library_name} +mv ${output_dir_name}/${android_library_name} "prefab/modules/dobby/libs/android.armeabi-v7a/${android_library_name}" # build android x86 output_dir_name=auto-build-workspace/android-x86-build compress_dir_array="$compress_dir_array $output_dir_name" echo "prepare build ${output_dir_name}" -cmake -S . -B ${output_dir_name} -DCMAKE_BUILD_TYPE=Release \ +cmake -S ${SOURCE_DIR} -B ${output_dir_name} -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_SYSTEM_NAME=Android -DCMAKE_ANDROID_ARCH_ABI="x86" -DCMAKE_ANDROID_NDK=$ANDROID_NDK_DIR -DCMAKE_ANDROID_NDK_TOOLCHAIN_VERSION=clang \ - -DDOBBY_GENERATE_SHARED=OFF -DDOBBY_DEBUG=OFF + -DDOBBY_GENERATE_SHARED=OFF -DDOBBY_DEBUG=OFF -DPlugin.Android.BionicLinkerRestriction=ON cmake --build ${output_dir_name} --parallel 4 --target dobby mkdir -p ${summary_output_dir_name}/android/x86 mv ${output_dir_name}/${android_library_name} ${summary_output_dir_name}/android/x86/${android_library_name} +mv ${output_dir_name}/${android_library_name} "prefab/modules/dobby/libs/android.x86/${android_library_name}" # build android x86_64 output_dir_name=auto-build-workspace/android-x86_64-build compress_dir_array="$compress_dir_array $output_dir_name" echo "prepare build ${output_dir_name}" -cmake -S . -B ${output_dir_name} -DCMAKE_BUILD_TYPE=Release \ +cmake -S ${SOURCE_DIR} -B ${output_dir_name} -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_SYSTEM_NAME=Android -DCMAKE_ANDROID_ARCH_ABI="x86_64" -DCMAKE_ANDROID_NDK=$ANDROID_NDK_DIR -DCMAKE_ANDROID_NDK_TOOLCHAIN_VERSION=clang \ - -DDOBBY_GENERATE_SHARED=OFF -DDOBBY_DEBUG=OFF + -DDOBBY_GENERATE_SHARED=OFF -DDOBBY_DEBUG=OFF -DPlugin.Android.BionicLinkerRestriction=ON cmake --build ${output_dir_name} --parallel 4 --target dobby mkdir -p ${summary_output_dir_name}/android/x86_64 mv ${output_dir_name}/${android_library_name} ${summary_output_dir_name}/android/x86_64/${android_library_name} +#mv ${output_dir_name}/${android_library_name} "prefab/modules/dobby/libs/android.x86_64/${android_library_name}" + +## zip android prefab +#mkdir -p prefab/modules/dobby/include +#cp "include/dobby.h" "prefab/modules/dobby/include/" +#cp "builtin-plugin/BionicLinkerRestriction/bionic_linker_restriction.h" "prefab/modules/dobby/include/" +#cp "builtin-plugin/SymbolResolver/dobby_symbol_resolver.h" "prefab/modules/dobby/include/" +#cp "prefab/AndroidManifest.xml" . +#zip -r ${summary_output_dir_name}/android_prefab.aar prefab AndroidManifest.xml -x prefab/AndroidManifest.xml if [ $DOBBY_BUILD_OUTPUT_NAME ]; then tar czvf ${DOBBY_BUILD_OUTPUT_NAME} ${summary_output_dir_name} -fi \ No newline at end of file +fi diff --git a/module/src/main/cpp/Dobby/build-workspace/prefab/AndroidManifest.xml b/module/src/main/cpp/Dobby/build-workspace/prefab/AndroidManifest.xml new file mode 100644 index 00000000..c7fb4f35 --- /dev/null +++ b/module/src/main/cpp/Dobby/build-workspace/prefab/AndroidManifest.xml @@ -0,0 +1,9 @@ + + + + + + diff --git a/module/src/main/cpp/Dobby/build-workspace/prefab/modules/dobby/libs/android.arm64-v8a/abi.json b/module/src/main/cpp/Dobby/build-workspace/prefab/modules/dobby/libs/android.arm64-v8a/abi.json new file mode 100644 index 00000000..64805a3c --- /dev/null +++ b/module/src/main/cpp/Dobby/build-workspace/prefab/modules/dobby/libs/android.arm64-v8a/abi.json @@ -0,0 +1,6 @@ +{ + "abi": "arm64-v8a", + "api": 21, + "ndk": 21, + "stl": "c++_static" +} diff --git a/module/src/main/cpp/Dobby/build-workspace/prefab/modules/dobby/libs/android.armeabi-v7a/abi.json b/module/src/main/cpp/Dobby/build-workspace/prefab/modules/dobby/libs/android.armeabi-v7a/abi.json new file mode 100644 index 00000000..143d3034 --- /dev/null +++ b/module/src/main/cpp/Dobby/build-workspace/prefab/modules/dobby/libs/android.armeabi-v7a/abi.json @@ -0,0 +1,6 @@ +{ + "abi": "armeabi-v7a", + "api": 16, + "ndk": 21, + "stl": "c++_static" +} diff --git a/module/src/main/cpp/Dobby/build-workspace/prefab/modules/dobby/libs/android.x86/abi.json b/module/src/main/cpp/Dobby/build-workspace/prefab/modules/dobby/libs/android.x86/abi.json new file mode 100644 index 00000000..00d05a42 --- /dev/null +++ b/module/src/main/cpp/Dobby/build-workspace/prefab/modules/dobby/libs/android.x86/abi.json @@ -0,0 +1,6 @@ +{ + "abi": "x86", + "api": 16, + "ndk": 21, + "stl": "c++_static" +} diff --git a/module/src/main/cpp/Dobby/build-workspace/prefab/modules/dobby/libs/android.x86_64/abi.json b/module/src/main/cpp/Dobby/build-workspace/prefab/modules/dobby/libs/android.x86_64/abi.json new file mode 100644 index 00000000..2adf0060 --- /dev/null +++ b/module/src/main/cpp/Dobby/build-workspace/prefab/modules/dobby/libs/android.x86_64/abi.json @@ -0,0 +1,6 @@ +{ + "abi": "x86_64", + "api": 21, + "ndk": 21, + "stl": "c++_static" +} diff --git a/module/src/main/cpp/Dobby/build-workspace/prefab/modules/dobby/module.json b/module/src/main/cpp/Dobby/build-workspace/prefab/modules/dobby/module.json new file mode 100644 index 00000000..5d239944 --- /dev/null +++ b/module/src/main/cpp/Dobby/build-workspace/prefab/modules/dobby/module.json @@ -0,0 +1,4 @@ +{ + "export_libraries": [], + "android": {} +} diff --git a/module/src/main/cpp/Dobby/build-workspace/prefab/prefab.json b/module/src/main/cpp/Dobby/build-workspace/prefab/prefab.json new file mode 100644 index 00000000..ba38d7fc --- /dev/null +++ b/module/src/main/cpp/Dobby/build-workspace/prefab/prefab.json @@ -0,0 +1,5 @@ +{ + "name": "dobby", + "schema_version": 1, + "dependencies": [] +} diff --git a/module/src/main/cpp/Dobby/builtin-plugin/ApplicationEventMonitor/MGCopyAnswerMonitor.cc b/module/src/main/cpp/Dobby/builtin-plugin/ApplicationEventMonitor/MGCopyAnswerMonitor.cc index c16e7ca5..275a25be 100644 --- a/module/src/main/cpp/Dobby/builtin-plugin/ApplicationEventMonitor/MGCopyAnswerMonitor.cc +++ b/module/src/main/cpp/Dobby/builtin-plugin/ApplicationEventMonitor/MGCopyAnswerMonitor.cc @@ -5,27 +5,27 @@ #define LOG_TAG "MGCopyAnswer" -static uintptr_t getCallFirstArg(RegisterContext *reg_ctx) { +static uintptr_t getCallFirstArg(RegisterContext *ctx) { uintptr_t result; #if defined(_M_X64) || defined(__x86_64__) #if defined(_WIN32) - result = reg_ctx->general.regs.rcx; + result = ctx->general.regs.rcx; #else - result = reg_ctx->general.regs.rdi; + result = ctx->general.regs.rdi; #endif #elif defined(__arm64__) || defined(__aarch64__) - result = reg_ctx->general.regs.x0; + result = ctx->general.regs.x0; #elif defined(__arm__) - result = reg_ctx->general.regs.r0; + result = ctx->general.regs.r0; #else #error "Not Support Architecture." #endif return result; } -void common_handler(RegisterContext *reg_ctx, const HookEntryInfo *info) { +void common_handler(RegisterContext *ctx, const HookEntryInfo *info) { CFStringRef key_ = 0; - key_ = (CFStringRef)getCallFirstArg(reg_ctx); + key_ = (CFStringRef)getCallFirstArg(ctx); char str_key[256] = {0}; CFStringGetCString(key_, str_key, 256, kCFStringEncodingUTF8); diff --git a/module/src/main/cpp/Dobby/builtin-plugin/ApplicationEventMonitor/dynamic_loader_monitor.cc b/module/src/main/cpp/Dobby/builtin-plugin/ApplicationEventMonitor/dynamic_loader_monitor.cc index 16f635ad..5de42843 100644 --- a/module/src/main/cpp/Dobby/builtin-plugin/ApplicationEventMonitor/dynamic_loader_monitor.cc +++ b/module/src/main/cpp/Dobby/builtin-plugin/ApplicationEventMonitor/dynamic_loader_monitor.cc @@ -13,7 +13,7 @@ #include "dobby.h" -#include "common/headers/common_header.h" +#include "common_header.h" #define LOG_TAG "DynamicLoaderMonitor" diff --git a/module/src/main/cpp/Dobby/builtin-plugin/ApplicationEventMonitor/file_operation_monitor.cc b/module/src/main/cpp/Dobby/builtin-plugin/ApplicationEventMonitor/file_operation_monitor.cc index 391221d4..d4f09ca5 100644 --- a/module/src/main/cpp/Dobby/builtin-plugin/ApplicationEventMonitor/file_operation_monitor.cc +++ b/module/src/main/cpp/Dobby/builtin-plugin/ApplicationEventMonitor/file_operation_monitor.cc @@ -17,7 +17,7 @@ std::unordered_map *TracedFopenFileList; FILE *(*orig_fopen)(const char *filename, const char *mode); FILE *fake_fopen(const char *filename, const char *mode) { FILE *result = NULL; - result = orig_fopen(filename, mode); + result = orig_fopen(filename, mode); if (result != NULL) { char *traced_filename = (char *)malloc(MAXPATHLEN); // FIXME: strncpy @@ -74,7 +74,7 @@ __attribute__((constructor)) void __main() { // DobbyHook((void *)fwrite, (void *)fake_fwrite, (void **)&orig_fwrite); // DobbyHook((void *)fread, (void *)fake_fread, (void **)&orig_fread); - char *home = getenv("HOME"); + char *home = getenv("HOME"); char *subdir = (char *)"/Library/Caches/"; std::string filePath = std::string(home) + std::string(subdir) + "temp.log"; diff --git a/module/src/main/cpp/Dobby/builtin-plugin/ApplicationEventMonitor/memory_operation_instrument.cc b/module/src/main/cpp/Dobby/builtin-plugin/ApplicationEventMonitor/memory_operation_instrument.cc index 5efaa63a..7604e68e 100644 --- a/module/src/main/cpp/Dobby/builtin-plugin/ApplicationEventMonitor/memory_operation_instrument.cc +++ b/module/src/main/cpp/Dobby/builtin-plugin/ApplicationEventMonitor/memory_operation_instrument.cc @@ -4,18 +4,18 @@ #include #include -static uintptr_t getCallFirstArg(RegisterContext *reg_ctx) { +static uintptr_t getCallFirstArg(RegisterContext *ctx) { uintptr_t result; #if defined(_M_X64) || defined(__x86_64__) #if defined(_WIN32) - result = reg_ctx->general.regs.rcx; + result = ctx->general.regs.rcx; #else - result = reg_ctx->general.regs.rdi; + result = ctx->general.regs.rdi; #endif #elif defined(__arm64__) || defined(__aarch64__) - result = reg_ctx->general.regs.x0; + result = ctx->general.regs.x0; #elif defined(__arm__) - result = reg_ctx->general.regs.r0; + result = ctx->general.regs.r0; #else #error "Not Support Architecture." #endif @@ -33,18 +33,18 @@ void format_integer_manually(char *buf, uint64_t integer) { // [ATTENTION]: // printf will call 'malloc' internally, and will crash in a loop. // so, use 'puts' is a better choice. -void malloc_handler(RegisterContext *reg_ctx, const HookEntryInfo *info) { - size_t size_ = 0; - size_ = getCallFirstArg(reg_ctx); +void malloc_handler(RegisterContext *ctx, const HookEntryInfo *info) { + size_t size_ = 0; + size_ = getCallFirstArg(ctx); char *buffer_ = (char *)"[-] function malloc first arg: 0x00000000.\n"; format_integer_manually(strchr(buffer_, '.') - 1, size_); puts(buffer_); } -void free_handler(RegisterContext *reg_ctx, const HookEntryInfo *info) { +void free_handler(RegisterContext *ctx, const HookEntryInfo *info) { uintptr_t mem_ptr; - mem_ptr = getCallFirstArg(reg_ctx); + mem_ptr = getCallFirstArg(ctx); char *buffer = (char *)"[-] function free first arg: 0x00000000.\n"; format_integer_manually(strchr(buffer, '.') - 1, mem_ptr); diff --git a/module/src/main/cpp/Dobby/builtin-plugin/ApplicationEventMonitor/posix_file_descriptor_operation_monitor.cc b/module/src/main/cpp/Dobby/builtin-plugin/ApplicationEventMonitor/posix_file_descriptor_operation_monitor.cc index 570c3ca2..4aaa2f4d 100644 --- a/module/src/main/cpp/Dobby/builtin-plugin/ApplicationEventMonitor/posix_file_descriptor_operation_monitor.cc +++ b/module/src/main/cpp/Dobby/builtin-plugin/ApplicationEventMonitor/posix_file_descriptor_operation_monitor.cc @@ -17,7 +17,7 @@ #include #include "dobby.h" -#include "common/headers/common_header.h" +#include "common_header.h" #define LOG_TAG "PosixFileOperationMonitor" @@ -68,7 +68,7 @@ int fake___open(const char *pathname, int flags, int mode) { } static const char *get_traced_filename(int fd, bool removed) { - if(posix_file_descriptors == NULL) + if (posix_file_descriptors == NULL) return NULL; std::unordered_map::iterator it; it = posix_file_descriptors->find(fd); diff --git a/module/src/main/cpp/Dobby/builtin-plugin/BionicLinkerRestriction/bionic_linker_restriction.cc b/module/src/main/cpp/Dobby/builtin-plugin/BionicLinkerRestriction/bionic_linker_restriction.cc index 10d92ae8..1fdba7ba 100644 --- a/module/src/main/cpp/Dobby/builtin-plugin/BionicLinkerRestriction/bionic_linker_restriction.cc +++ b/module/src/main/cpp/Dobby/builtin-plugin/BionicLinkerRestriction/bionic_linker_restriction.cc @@ -17,11 +17,13 @@ #include "dobby.h" #include "dobby_symbol_resolver.h" -#include "common/headers/common_header.h" +#include "common_header.h" #undef LOG_TAG #define LOG_TAG "AndroidLinkerRestriction" +#undef Q +#define Q 29 // impl at "dobby_symbol_resolver.cc" extern void *resolve_elf_internal_symbol(const char *library_name, const char *symbol_name); @@ -33,18 +35,18 @@ static int get_android_system_version() { return os_version_int; } -static char *get_android_linker_path() { +static const char *get_android_linker_path() { #if __LP64__ - if (get_android_system_version() >= 10) { - return "/apex/com.android.runtime/bin/linker64"; + if (get_android_system_version() >= Q) { + return (const char *)"/apex/com.android.runtime/bin/linker64"; } else { - return "/system/bin/linker64"; + return (const char *)"/system/bin/linker64"; } #else - if (get_android_system_version() >= 10) { - return "/apex/com.android.runtime/bin/linker"; + if (get_android_system_version() >= Q) { + return (const char *)"/apex/com.android.runtime/bin/linker"; } else { - return "/system/bin/linker"; + return (const char *)"/system/bin/linker"; } #endif } @@ -86,7 +88,7 @@ std::vector linker_get_solist() { // Generate the name for an offset. #define PARAM_OFFSET(type_, member_) __##type_##__##member_##__offset_ -#define STRUCT_OFFSET PARAM_OFFSET +#define STRUCT_OFFSET PARAM_OFFSET int STRUCT_OFFSET(solist, next) = 0; for (size_t i = 0; i < 1024 / sizeof(void *); i++) { if (*(addr_t *)((addr_t)solist_head + i * sizeof(void *)) == somain) { @@ -98,7 +100,7 @@ std::vector linker_get_solist() { linker_solist.push_back(solist_head); addr_t sonext = 0; - sonext = *(addr_t *)((addr_t)solist_head + STRUCT_OFFSET(solist, next)); + sonext = *(addr_t *)((addr_t)solist_head + STRUCT_OFFSET(solist, next)); while (sonext) { linker_solist.push_back((void *)sonext); sonext = *(addr_t *)((addr_t)sonext + STRUCT_OFFSET(solist, next)); @@ -123,7 +125,7 @@ uintptr_t linker_soinfo_to_handle(soinfo_t soinfo) { return _linker_soinfo_to_handle(soinfo); } -typedef void * android_namespace_t; +typedef void *android_namespace_t; android_namespace_t linker_soinfo_get_primary_namespace(soinfo_t soinfo) { static android_namespace_t (*_get_primary_namespace)(soinfo_t) = NULL; if (!_get_primary_namespace) @@ -143,16 +145,16 @@ void linker_iterate_soinfo(int (*cb)(soinfo_t soinfo)) { static int iterate_soinfo_cb(soinfo_t soinfo) { android_namespace_t ns = NULL; - ns = linker_soinfo_get_primary_namespace(soinfo); + ns = linker_soinfo_get_primary_namespace(soinfo); LOG(1, "lib: %s", linker_soinfo_get_realpath(soinfo)); // set is_isolated_ as false // no need for this actually - int STRUCT_OFFSET(android_namespace_t, is_isolated_) = 0x8; + int STRUCT_OFFSET(android_namespace_t, is_isolated_) = 0x8; *(uint8_t *)((addr_t)ns + STRUCT_OFFSET(android_namespace_t, is_isolated_)) = false; std::vector ld_library_paths = {"/system/lib64", "/sytem/lib"}; - if (get_android_system_version() >= 10) { + if (get_android_system_version() >= Q) { ld_library_paths.push_back("/apex/com.android.runtime/lib64"); ld_library_paths.push_back("/apex/com.android.runtime/lib"); } @@ -192,4 +194,4 @@ void linker_disable_namespace_restriction() { (void **)&orig_linker_namespace_is_is_accessible); LOG(1, "disable namespace restriction done"); -} \ No newline at end of file +} diff --git a/module/src/main/cpp/Dobby/builtin-plugin/BionicLinkerRestriction/linker_restriction_demo.cc b/module/src/main/cpp/Dobby/builtin-plugin/BionicLinkerRestriction/linker_restriction_demo.cc index 865b4216..eb96607a 100644 --- a/module/src/main/cpp/Dobby/builtin-plugin/BionicLinkerRestriction/linker_restriction_demo.cc +++ b/module/src/main/cpp/Dobby/builtin-plugin/BionicLinkerRestriction/linker_restriction_demo.cc @@ -14,7 +14,7 @@ __attribute__((constructor)) static void ctor() { #if defined(__LP64__) lib = "/system/lib64/libandroid_runtime.so"; #else - lib = "/system/lib/libandroid_runtime.so"; + lib = "/system/lib/libandroid_runtime.so"; #endif void *vm = NULL; @@ -29,8 +29,8 @@ __attribute__((constructor)) static void ctor() { vm = dlsym(handle, "_ZN7android14AndroidRuntime7mJavaVME"); #else void *handle = NULL; - handle = linker_dlopen(lib, RTLD_LAZY); - vm = dlsym(handle, "_ZN7android14AndroidRuntime7mJavaVME"); + handle = linker_dlopen(lib, RTLD_LAZY); + vm = dlsym(handle, "_ZN7android14AndroidRuntime7mJavaVME"); #endif LOG(1, "vm %p", vm); } diff --git a/module/src/main/cpp/Dobby/builtin-plugin/Dyld2HideLibrary/dyld2_hide_library.cc b/module/src/main/cpp/Dobby/builtin-plugin/Dyld2HideLibrary/dyld2_hide_library.cc index 0c2f1f0a..9ca9d786 100644 --- a/module/src/main/cpp/Dobby/builtin-plugin/Dyld2HideLibrary/dyld2_hide_library.cc +++ b/module/src/main/cpp/Dobby/builtin-plugin/Dyld2HideLibrary/dyld2_hide_library.cc @@ -113,7 +113,7 @@ PUBLIC int dyld2_hide_library(const char *library_name) { g_prepare_remove_array->push_back((char *)library_name); } -static void common_handler(RegisterContext *reg_ctx, const HookEntryInfo *info) { +static void common_handler(RegisterContext *ctx, const HookEntryInfo *info) { if (g_prepare_remove_array == nullptr) return; for (auto name : *g_prepare_remove_array) { diff --git a/module/src/main/cpp/Dobby/builtin-plugin/GlobalOffsetTableHook/CMakeLists.txt b/module/src/main/cpp/Dobby/builtin-plugin/GlobalOffsetTableHook/CMakeLists.txt new file mode 100644 index 00000000..194b450f --- /dev/null +++ b/module/src/main/cpp/Dobby/builtin-plugin/GlobalOffsetTableHook/CMakeLists.txt @@ -0,0 +1,13 @@ +if(SYSTEM.Darwin) +set(SOURCE_FILE_LIST + ${CMAKE_CURRENT_SOURCE_DIR}/global_offset_table_hook.cc + ) +endif() + +add_library(global_offset_table_hook STATIC + ${SOURCE_FILE_LIST} + ) + +include_directories( + . +) diff --git a/module/src/main/cpp/Dobby/builtin-plugin/GlobalOffsetTableHook/global_offset_table_hook.cc b/module/src/main/cpp/Dobby/builtin-plugin/GlobalOffsetTableHook/global_offset_table_hook.cc index 7a61c501..70fbe045 100644 --- a/module/src/main/cpp/Dobby/builtin-plugin/GlobalOffsetTableHook/global_offset_table_hook.cc +++ b/module/src/main/cpp/Dobby/builtin-plugin/GlobalOffsetTableHook/global_offset_table_hook.cc @@ -1,4 +1,4 @@ -#include "GlobalOffsetTableHook/global_offset_table_hook.h" +#include "global_offset_table_hook.h" #include #include @@ -15,46 +15,46 @@ #include -#include "common/headers/common_header.h" +#include "common_header.h" #include "logging/logging.h" #include "PlatformUtil/ProcessRuntimeUtility.h" #if defined(__LP64__) -typedef struct mach_header_64 mach_header_t; +typedef struct mach_header_64 mach_header_t; typedef struct segment_command_64 segment_command_t; -typedef struct section_64 section_t; -typedef struct nlist_64 nlist_t; +typedef struct section_64 section_t; +typedef struct nlist_64 nlist_t; #define LC_SEGMENT_ARCH_DEPENDENT LC_SEGMENT_64 #else -typedef struct mach_header mach_header_t; +typedef struct mach_header mach_header_t; typedef struct segment_command segment_command_t; -typedef struct section section_t; -typedef struct nlist nlist_t; +typedef struct section section_t; +typedef struct nlist nlist_t; #define LC_SEGMENT_ARCH_DEPENDENT LC_SEGMENT #endif static void *iterate_indirect_symtab(char *symbol_name, section_t *section, intptr_t slide, nlist_t *symtab, char *strtab, uint32_t *indirect_symtab) { - const bool is_data_const = strcmp(section->segname, "__DATA_CONST") == 0; - uint32_t * indirect_symbol_indices = indirect_symtab + section->reserved1; - void ** indirect_symbol_bindings = (void **)((uintptr_t)slide + section->addr); - - vm_prot_t old_protection = VM_PROT_READ; + const bool is_data_const = strcmp(section->segname, "__DATA_CONST") == 0; + uint32_t *indirect_symbol_indices = indirect_symtab + section->reserved1; + void **indirect_symbol_bindings = (void **)((uintptr_t)slide + section->addr); + + vm_prot_t old_protection = VM_PROT_READ; if (is_data_const) { mprotect(indirect_symbol_bindings, section->size, PROT_READ | PROT_WRITE); } - + for (uint i = 0; i < section->size / sizeof(void *); i++) { uint32_t symtab_index = indirect_symbol_indices[i]; if (symtab_index == INDIRECT_SYMBOL_ABS || symtab_index == INDIRECT_SYMBOL_LOCAL || symtab_index == (INDIRECT_SYMBOL_LOCAL | INDIRECT_SYMBOL_ABS)) { continue; } - uint32_t strtab_offset = symtab[symtab_index].n_un.n_strx; - char * local_symbol_name = strtab + strtab_offset; - bool symbol_name_longer_than_1 = symbol_name[0] && symbol_name[1]; + uint32_t strtab_offset = symtab[symtab_index].n_un.n_strx; + char *local_symbol_name = strtab + strtab_offset; + bool symbol_name_longer_than_1 = symbol_name[0] && symbol_name[1]; if (strcmp(local_symbol_name, symbol_name) == 0) { return &indirect_symbol_bindings[i]; } @@ -64,7 +64,7 @@ static void *iterate_indirect_symtab(char *symbol_name, section_t *section, intp } } } - + if (is_data_const && 0) { int protection = 0; if (old_protection & VM_PROT_READ) { @@ -82,9 +82,9 @@ static void *iterate_indirect_symtab(char *symbol_name, section_t *section, intp } static void *get_global_offset_table_stub(mach_header_t *header, char *symbol_name) { - segment_command_t * curr_seg_cmd; - segment_command_t * text_segment, *data_segment, *linkedit_segment; - struct symtab_command * symtab_cmd = NULL; + segment_command_t *curr_seg_cmd; + segment_command_t *text_segment, *data_segment, *linkedit_segment; + struct symtab_command *symtab_cmd = NULL; struct dysymtab_command *dysymtab_cmd = NULL; uintptr_t cur = (uintptr_t)header + sizeof(mach_header_t); @@ -109,11 +109,11 @@ static void *get_global_offset_table_stub(mach_header_t *header, char *symbol_na return NULL; } - uintptr_t slide = (uintptr_t)header - (uintptr_t)text_segment->vmaddr; + uintptr_t slide = (uintptr_t)header - (uintptr_t)text_segment->vmaddr; uintptr_t linkedit_base = (uintptr_t)slide + linkedit_segment->vmaddr - linkedit_segment->fileoff; - nlist_t * symtab = (nlist_t *)(linkedit_base + symtab_cmd->symoff); - char * strtab = (char *)(linkedit_base + symtab_cmd->stroff); - uint32_t symtab_count = symtab_cmd->nsyms; + nlist_t *symtab = (nlist_t *)(linkedit_base + symtab_cmd->symoff); + char *strtab = (char *)(linkedit_base + symtab_cmd->stroff); + uint32_t symtab_count = symtab_cmd->nsyms; uint32_t *indirect_symtab = (uint32_t *)(linkedit_base + dysymtab_cmd->indirectsymoff); @@ -143,7 +143,7 @@ static void *get_global_offset_table_stub(mach_header_t *header, char *symbol_na return NULL; } -int DobbyGlobalOffsetTableReplace(char *image_name, char *symbol_name, void *fake_func, void **orig_func_ptr) { +PUBLIC int DobbyGlobalOffsetTableReplace(char *image_name, char *symbol_name, void *fake_func, void **orig_func_ptr) { std::vector ProcessModuleMap = ProcessRuntimeUtility::GetProcessModuleMap(); for (auto module : ProcessModuleMap) { @@ -151,7 +151,7 @@ int DobbyGlobalOffsetTableReplace(char *image_name, char *symbol_name, void *fak continue; addr_t header = (addr_t)module.load_address; - size_t slide = 0; + size_t slide = 0; #if 0 if (header) { @@ -161,12 +161,12 @@ int DobbyGlobalOffsetTableReplace(char *image_name, char *symbol_name, void *fak #endif #if 0 - LOG(1, "resolve image: %s", path); + LOG(1, "resolve image: %s", module.path); #endif uint32_t nlist_count = 0; nlist_t *nlist_array = 0; - char * string_pool = 0; + char *string_pool = 0; void *stub = get_global_offset_table_stub((mach_header_t *)header, symbol_name); if (stub) { @@ -177,14 +177,16 @@ int DobbyGlobalOffsetTableReplace(char *image_name, char *symbol_name, void *fak orig_func = ptrauth_sign_unauthenticated(orig_func, ptrauth_key_asia, 0); #endif *orig_func_ptr = orig_func; - + #if __has_feature(ptrauth_calls) fake_func = (void *)ptrauth_strip(fake_func, ptrauth_key_asia); fake_func = ptrauth_sign_unauthenticated(fake_func, ptrauth_key_asia, stub); #endif *(void **)stub = fake_func; - return RT_SUCCESS; } + + if (image_name) + return 0; } - return RT_FAILED; + return -1; } diff --git a/module/src/main/cpp/Dobby/builtin-plugin/GlobalOffsetTableHook/global_offset_table_hook.h b/module/src/main/cpp/Dobby/builtin-plugin/GlobalOffsetTableHook/global_offset_table_hook.h index 304b331d..f88c0670 100644 --- a/module/src/main/cpp/Dobby/builtin-plugin/GlobalOffsetTableHook/global_offset_table_hook.h +++ b/module/src/main/cpp/Dobby/builtin-plugin/GlobalOffsetTableHook/global_offset_table_hook.h @@ -1,5 +1,4 @@ -#ifndef DOBBY_GLOBAL_OFFSET_TABLE_HOOK -#define DOBBY_GLOBAL_OFFSET_TABLE_HOOK +#pragma once #ifdef __cplusplus extern "C" { @@ -9,6 +8,4 @@ int DobbyGlobalOffsetTableReplace(char *image_name, char *symbol_name, void *fak #ifdef __cplusplus } -#endif - -#endif +#endif \ No newline at end of file diff --git a/module/src/main/cpp/Dobby/builtin-plugin/HideSystemCall/README b/module/src/main/cpp/Dobby/builtin-plugin/HideSystemCall/README new file mode 100644 index 00000000..c8c6761a --- /dev/null +++ b/module/src/main/cpp/Dobby/builtin-plugin/HideSystemCall/README @@ -0,0 +1 @@ +private \ No newline at end of file diff --git a/module/src/main/cpp/Dobby/builtin-plugin/HideSystemCall/syscall.darwin.s b/module/src/main/cpp/Dobby/builtin-plugin/HideSystemCall/syscall.darwin.s deleted file mode 100644 index e69de29b..00000000 diff --git a/module/src/main/cpp/Dobby/builtin-plugin/HideSystemCall/syscall.linux.s b/module/src/main/cpp/Dobby/builtin-plugin/HideSystemCall/syscall.linux.s deleted file mode 100644 index e69de29b..00000000 diff --git a/module/src/main/cpp/Dobby/builtin-plugin/IntegrityReadCallback/README b/module/src/main/cpp/Dobby/builtin-plugin/IntegrityReadCallback/README new file mode 100644 index 00000000..c8c6761a --- /dev/null +++ b/module/src/main/cpp/Dobby/builtin-plugin/IntegrityReadCallback/README @@ -0,0 +1 @@ +private \ No newline at end of file diff --git a/module/src/main/cpp/Dobby/builtin-plugin/LinkerImageLoadCallback/linker_load_callback.cc b/module/src/main/cpp/Dobby/builtin-plugin/LinkerImageLoadCallback/linker_load_callback.cc index 2bcf4060..a3f026a6 100644 --- a/module/src/main/cpp/Dobby/builtin-plugin/LinkerImageLoadCallback/linker_load_callback.cc +++ b/module/src/main/cpp/Dobby/builtin-plugin/LinkerImageLoadCallback/linker_load_callback.cc @@ -1,5 +1,5 @@ #include "dobby.h" -#include "common/headers/common_header.h" +#include "common_header.h" #include diff --git a/module/src/main/cpp/Dobby/builtin-plugin/MemoryRemapHook/README b/module/src/main/cpp/Dobby/builtin-plugin/MemoryRemapHook/README new file mode 100644 index 00000000..c8c6761a --- /dev/null +++ b/module/src/main/cpp/Dobby/builtin-plugin/MemoryRemapHook/README @@ -0,0 +1 @@ +private \ No newline at end of file diff --git a/module/src/main/cpp/Dobby/builtin-plugin/MemoryRemapHook/runtime_sdk.cc b/module/src/main/cpp/Dobby/builtin-plugin/MemoryRemapHook/runtime_sdk.cc deleted file mode 100644 index 971f1f63..00000000 --- a/module/src/main/cpp/Dobby/builtin-plugin/MemoryRemapHook/runtime_sdk.cc +++ /dev/null @@ -1,16 +0,0 @@ -#include -#include -#include - -#include "dobby_internal.h" - -#include "PlatformUtil/ProcessRuntimeUtility.h" - -std::vector remap_addr_array; - -void DumpMemoryRemapPoint() { - LiteCollectionIterator *iter = LiteCollectionIterator::withCollection(Interceptor::entries); - while ((entry = reinterpret_cast(iter->getNextObject())) != NULL) { - remap_addr_array->push_back(entry->target_address == address); - } -} \ No newline at end of file diff --git a/module/src/main/cpp/Dobby/builtin-plugin/ObjcRuntimeHook/objc_runtime_hook.h b/module/src/main/cpp/Dobby/builtin-plugin/ObjcRuntimeHook/objc_runtime_hook.h index 8957515f..bb721da9 100644 --- a/module/src/main/cpp/Dobby/builtin-plugin/ObjcRuntimeHook/objc_runtime_hook.h +++ b/module/src/main/cpp/Dobby/builtin-plugin/ObjcRuntimeHook/objc_runtime_hook.h @@ -4,7 +4,6 @@ #include #include - #ifdef __cplusplus extern "C" { #endif diff --git a/module/src/main/cpp/Dobby/builtin-plugin/ObjcRuntimeHook/objc_runtime_hook.mm b/module/src/main/cpp/Dobby/builtin-plugin/ObjcRuntimeHook/objc_runtime_hook.mm index 3854e23c..292fa99e 100644 --- a/module/src/main/cpp/Dobby/builtin-plugin/ObjcRuntimeHook/objc_runtime_hook.mm +++ b/module/src/main/cpp/Dobby/builtin-plugin/ObjcRuntimeHook/objc_runtime_hook.mm @@ -5,7 +5,7 @@ #include extern "C" { -#include "external_helper/variable_cache.h" +#include "misc-helper/variable_cache.h" } /* clang -rewrite-objc main.m */ @@ -16,7 +16,7 @@ IMP DobbyObjcReplace(Class class_, SEL sel_, IMP fake_impl) { method_ = class_getClassMethod(class_, sel_); if (!method_) { - DLOG(1, "Not found class: %s, selector: %s method\n", class_getName(class_), sel_getName(sel_)); + DLOG(0, "Not found class: %s, selector: %s method\n", class_getName(class_), sel_getName(sel_)); return NULL; } @@ -25,19 +25,19 @@ IMP DobbyObjcReplace(Class class_, SEL sel_, IMP fake_impl) { void DobbyObjcReplaceEx(const char *class_name, const char *selector_name, void *fake_impl, void **out_orig_impl) { Class class_ = objc_getClass(class_name); - SEL sel_ = sel_registerName(selector_name); + SEL sel_ = sel_registerName(selector_name); Method method_ = class_getInstanceMethod(class_, sel_); if (!method_) method_ = class_getClassMethod(class_, sel_); if (!method_) { - DLOG(1, "Not found class: %s, selector: %s method\n", class_name, selector_name); + DLOG(0, "Not found class: %s, selector: %s method\n", class_name, selector_name); return; } void *orig_impl = NULL; - orig_impl = (void *)method_setImplementation(method_, (IMP)fake_impl); + orig_impl = (void *)method_setImplementation(method_, (IMP)fake_impl); if (out_orig_impl) { *out_orig_impl = orig_impl; } @@ -46,14 +46,14 @@ void DobbyObjcReplaceEx(const char *class_name, const char *selector_name, void void *DobbyObjcResolveMethodImp(const char *class_name, const char *selector_name) { Class class_ = objc_getClass(class_name); - SEL sel_ = sel_registerName(selector_name); + SEL sel_ = sel_registerName(selector_name); Method method_ = class_getInstanceMethod(class_, sel_); if (!method_) method_ = class_getClassMethod(class_, sel_); if (!method_) { - DLOG(1, "Not found class: %s, selector: %s method\n", class_name, selector_name); + DLOG(0, "Not found class: %s, selector: %s method\n", class_name, selector_name); return NULL; } return (void *)method_getImplementation(method_); diff --git a/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/CMakeLists.txt b/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/CMakeLists.txt index 092b1f4d..ddddfd76 100644 --- a/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/CMakeLists.txt +++ b/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/CMakeLists.txt @@ -6,8 +6,8 @@ add_library(supervisor_call_monitor STATIC misc_utility.cc ) target_link_libraries(supervisor_call_monitor - external_helper - ${dobby_output_name} + misc_helper + dobby ) add_library(test_supervisor_call_monitor SHARED diff --git a/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/README b/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/README new file mode 100644 index 00000000..3832eb51 --- /dev/null +++ b/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/README @@ -0,0 +1 @@ +Monitor all supervisor call \ No newline at end of file diff --git a/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/deprecated/mach_system_call.cc b/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/deprecated/mach_system_call.cc index 2cb213d3..d8243da0 100644 --- a/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/deprecated/mach_system_call.cc +++ b/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/deprecated/mach_system_call.cc @@ -9,7 +9,7 @@ #include -#include "external_helper/async_logger.h" +#include "misc-helper/async_logger.h" extern char *mach_msg_to_str(mach_msg_header_t *msg); @@ -40,32 +40,32 @@ void mach_system_call_monitor() { } #endif -static addr_t getCallFirstArg(RegisterContext *reg_ctx) { +static addr_t getCallFirstArg(RegisterContext *ctx) { addr_t result; #if defined(_M_X64) || defined(__x86_64__) #if defined(_WIN32) - result = reg_ctx->general.regs.rcx; + result = ctx->general.regs.rcx; #else - result = reg_ctx->general.regs.rdi; + result = ctx->general.regs.rdi; #endif #elif defined(__arm64__) || defined(__aarch64__) - result = reg_ctx->general.regs.x0; + result = ctx->general.regs.x0; #elif defined(__arm__) - result = reg_ctx->general.regs.r0; + result = ctx->general.regs.r0; #else #error "Not Support Architecture." #endif return result; } -static void common_handler(RegisterContext *reg_ctx, const HookEntryInfo *info) { - addr_t caller = get_caller_from_main_binary(reg_ctx); +static void common_handler(RegisterContext *ctx, const HookEntryInfo *info) { + addr_t caller = get_caller_from_main_binary(ctx); if (caller == 0) return; - char buffer[256] = {0}; - mach_msg_header_t *msg = (typeof(msg))getCallFirstArg(reg_ctx); - char * mach_msg_name = mach_msg_to_str(msg); + char buffer[256] = {0}; + mach_msg_header_t *msg = (typeof(msg))getCallFirstArg(ctx); + char *mach_msg_name = mach_msg_to_str(msg); if (mach_msg_name) { sprintf(buffer, "[mach msg %p] %s\n", caller, mach_msg_name); } else { diff --git a/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/deprecated/system_call.cc b/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/deprecated/system_call.cc index 9a540570..22f05d9a 100644 --- a/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/deprecated/system_call.cc +++ b/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/deprecated/system_call.cc @@ -13,20 +13,20 @@ #include #include -#include "external_helper/async_logger.h" +#include "misc-helper/async_logger.h" -static addr_t getCallFirstArg(RegisterContext *reg_ctx) { +static addr_t getCallFirstArg(RegisterContext *ctx) { addr_t result; #if defined(_M_X64) || defined(__x86_64__) #if defined(_WIN32) - result = reg_ctx->general.regs.rcx; + result = ctx->general.regs.rcx; #else - result = reg_ctx->general.regs.rdi; + result = ctx->general.regs.rdi; #endif #elif defined(__arm64__) || defined(__aarch64__) - result = reg_ctx->general.regs.x0; + result = ctx->general.regs.x0; #elif defined(__arm__) - result = reg_ctx->general.regs.r0; + result = ctx->general.regs.r0; #else #error "Not Support Architecture." #endif @@ -39,16 +39,16 @@ extern const char *mach_syscall_num_to_str(int num); extern char *mach_msg_to_str(mach_msg_header_t *msg); -static void common_handler(RegisterContext *reg_ctx, const HookEntryInfo *info) { +static void common_handler(RegisterContext *ctx, const HookEntryInfo *info) { char buffer[256] = {0}; - int syscall_rum = reg_ctx->general.regs.x16; + int syscall_rum = ctx->general.regs.x16; if (syscall_rum == 0) { - syscall_rum = (int)getCallFirstArg(reg_ctx); + syscall_rum = (int)getCallFirstArg(ctx); sprintf(buffer, "[syscall svc-%d] %s\n", syscall_rum, syscall_num_to_str(syscall_rum)); } else if (syscall_rum == -31) { // mach_msg_trap - mach_msg_header_t *msg = (typeof(msg))getCallFirstArg(reg_ctx); - char * mach_msg_name = mach_msg_to_str(msg); + mach_msg_header_t *msg = (typeof(msg))getCallFirstArg(ctx); + char *mach_msg_name = mach_msg_to_str(msg); if (mach_msg_name) { sprintf(buffer, "[mach msg svc] %s\n", mach_msg_name); } else { @@ -65,14 +65,14 @@ static void common_handler(RegisterContext *reg_ctx, const HookEntryInfo *info) typedef int32_t arm64_instr_t; void monitor_libsystem_kernel_dylib() { - auto libsystem_c = ProcessRuntimeUtility::GetProcessModule("libsystem_kernel.dylib"); + auto libsystem_c = ProcessRuntimeUtility::GetProcessModule("libsystem_kernel.dylib"); addr_t libsystem_c_header = (addr_t)libsystem_c.load_address; - auto text_section = + auto text_section = mach_kit::macho_get_section_by_name_64((struct mach_header_64 *)libsystem_c_header, "__TEXT", "__text"); addr_t shared_cache_load_addr = (addr_t)mach_kit::macho_get_shared_cache(); - addr_t insn_addr = shared_cache_load_addr + (addr_t)text_section->offset; - addr_t insn_addr_end = insn_addr + text_section->size; + addr_t insn_addr = shared_cache_load_addr + (addr_t)text_section->offset; + addr_t insn_addr_end = insn_addr + text_section->size; addr_t write_svc_addr = (addr_t)DobbySymbolResolver("libsystem_kernel.dylib", "write"); write_svc_addr += 4; @@ -95,11 +95,11 @@ void monitor_libsystem_kernel_dylib() { } void monitor_main_binary() { - auto main = ProcessRuntimeUtility::GetProcessModuleMap()[0]; + auto main = ProcessRuntimeUtility::GetProcessModuleMap()[0]; addr_t main_header = (addr_t)main.load_address; - auto text_section = mach_kit::macho_get_section_by_name_64((struct mach_header_64 *)main_header, "__TEXT", "__text"); + auto text_section = mach_kit::macho_get_section_by_name_64((struct mach_header_64 *)main_header, "__TEXT", "__text"); - addr_t insn_addr = main_header + (addr_t)text_section->offset; + addr_t insn_addr = main_header + (addr_t)text_section->offset; addr_t insn_addr_end = insn_addr + text_section->size; for (; insn_addr < insn_addr_end; insn_addr += sizeof(arm64_instr_t)) { diff --git a/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/mach_system_call_log_handler.cc b/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/mach_system_call_log_handler.cc index 8f498df1..fac21886 100644 --- a/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/mach_system_call_log_handler.cc +++ b/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/mach_system_call_log_handler.cc @@ -10,7 +10,7 @@ #include #include -#include "external_helper/async_logger.h" +#include "misc-helper/async_logger.h" #include "PlatformUtil/ProcessRuntimeUtility.h" #include "SupervisorCallMonitor/misc_utility.h" #include "SupervisorCallMonitor/supervisor_call_monitor.h" @@ -37,7 +37,7 @@ typedef struct { char *mach_msg_name; - int mach_msg_id; + int mach_msg_id; } mach_msg_entry_t; // clang-format off @@ -63,7 +63,7 @@ mach_msg_entry_t mach_msg_array[] = { // clang-format on #define PRIME_NUMBER 8387 -char * mach_msg_name_table[PRIME_NUMBER] = {0}; +char *mach_msg_name_table[PRIME_NUMBER] = {0}; static int hash_mach_msg_num_to_ndx(int mach_msg_num) { return mach_msg_num % PRIME_NUMBER; } @@ -76,8 +76,8 @@ static void mach_msg_id_hash_table_init() { int count = sizeof(mach_msg_array) / sizeof(mach_msg_array[0]); for (size_t i = 0; i < count; i++) { - mach_msg_entry_t entry = mach_msg_array[i]; - int ndx = hash_mach_msg_num_to_ndx(entry.mach_msg_id); + mach_msg_entry_t entry = mach_msg_array[i]; + int ndx = hash_mach_msg_num_to_ndx(entry.mach_msg_id); mach_msg_name_table[ndx] = entry.mach_msg_name; } } @@ -104,18 +104,18 @@ char *mach_msg_to_str(mach_msg_header_t *msg) { return NULL; } -static addr_t getCallFirstArg(RegisterContext *reg_ctx) { +static addr_t getCallFirstArg(RegisterContext *ctx) { addr_t result; #if defined(_M_X64) || defined(__x86_64__) #if defined(_WIN32) - result = reg_ctx->general.regs.rcx; + result = ctx->general.regs.rcx; #else - result = reg_ctx->general.regs.rdi; + result = ctx->general.regs.rdi; #endif #elif defined(__arm64__) || defined(__aarch64__) - result = reg_ctx->general.regs.x0; + result = ctx->general.regs.x0; #elif defined(__arm__) - result = reg_ctx->general.regs.r0; + result = ctx->general.regs.r0; #else #error "Not Support Architecture." #endif @@ -131,19 +131,18 @@ static addr_t fast_get_caller_from_main_binary(RegisterContext *ctx) { static addr_t text_section_start = 0, text_section_end = 0; static addr_t slide = 0; if (text_section_start == 0 || text_section_end == 0) { - auto main = ProcessRuntimeUtility::GetProcessModule("mobilex"); + auto main = ProcessRuntimeUtility::GetProcessModule("mobilex"); addr_t main_header = (addr_t)main.load_address; auto text_segment = macho_kit_get_segment_by_name((mach_header_t *)main_header, "__TEXT"); - slide = main_header - text_segment->vmaddr; + slide = main_header - text_segment->vmaddr; - auto text_section = - macho_kit_get_section_by_name((mach_header_t *)main_header, "__TEXT", "__text"); + auto text_section = macho_kit_get_section_by_name((mach_header_t *)main_header, "__TEXT", "__text"); text_section_start = main_header + (addr_t)text_section->offset; - text_section_end = text_section_start + text_section->size; + text_section_end = text_section_start + text_section->size; } - - if(ctx == NULL) + + if (ctx == NULL) return 0; addr_t lr = getRealLr(ctx); @@ -152,30 +151,30 @@ static addr_t fast_get_caller_from_main_binary(RegisterContext *ctx) { #define MAX_STACK_ITERATE_LEVEL 8 addr_t fp = ctx->fp; - if(fp == 0) + if (fp == 0) return 0; for (int i = 0; i < MAX_STACK_ITERATE_LEVEL; i++) { addr_t lr = *(addr_t *)(fp + sizeof(addr_t)); if (lr > text_section_start && lr < text_section_end) return lr - slide; fp = *(addr_t *)fp; - if(fp == 0) + if (fp == 0) return 0; } return 0; } -static void mach_syscall_log_handler(RegisterContext *reg_ctx, const HookEntryInfo *info) { - addr_t caller = fast_get_caller_from_main_binary(reg_ctx); +static void mach_syscall_log_handler(RegisterContext *ctx, const HookEntryInfo *info) { + addr_t caller = fast_get_caller_from_main_binary(ctx); if (caller == 0) return; char buffer[256] = {0}; - int syscall_rum = reg_ctx->general.regs.x16; + int syscall_rum = ctx->general.regs.x16; if (syscall_rum == -31) { // mach_msg_trap - mach_msg_header_t *msg = (typeof(msg))getCallFirstArg(reg_ctx); - char * mach_msg_name = mach_msg_to_str(msg); + mach_msg_header_t *msg = (typeof(msg))getCallFirstArg(ctx); + char *mach_msg_name = mach_msg_to_str(msg); if (mach_msg_name) { sprintf(buffer, "[mach msg svc] %s\n", mach_msg_name); } else { diff --git a/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/misc_utility.cc b/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/misc_utility.cc index 163c162d..2a0a05bc 100644 --- a/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/misc_utility.cc +++ b/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/misc_utility.cc @@ -2,17 +2,13 @@ #include -segment_command_t *macho_kit_get_segment_by_name(mach_header_t *header, const char *segname) -{ +segment_command_t *macho_kit_get_segment_by_name(mach_header_t *header, const char *segname) { segment_command_t *curr_seg_cmd = NULL; curr_seg_cmd = (segment_command_t *)((addr_t)header + sizeof(mach_header_t)); - for (int i = 0; i < header->ncmds; i++) - { - if (curr_seg_cmd->cmd == LC_SEGMENT_ARCH_DEPENDENT) - { - if (!strncmp(curr_seg_cmd->segname, segname, sizeof(curr_seg_cmd->segname))) - { + for (int i = 0; i < header->ncmds; i++) { + if (curr_seg_cmd->cmd == LC_SEGMENT_ARCH_DEPENDENT) { + if (!strncmp(curr_seg_cmd->segname, segname, sizeof(curr_seg_cmd->segname))) { break; } } @@ -22,8 +18,7 @@ segment_command_t *macho_kit_get_segment_by_name(mach_header_t *header, const ch return curr_seg_cmd; } -section_t *macho_kit_get_section_by_name(mach_header_t *header, const char *segname, const char *sectname) -{ +section_t *macho_kit_get_section_by_name(mach_header_t *header, const char *segname, const char *sectname) { section_t *section = NULL; segment_command_t *segment = NULL; @@ -34,19 +29,16 @@ section_t *macho_kit_get_section_by_name(mach_header_t *header, const char *segn goto finish; section = (section_t *)((addr_t)segment + sizeof(segment_command_t)); - for (i = 0; i < segment->nsects; ++i) - { - if (!strncmp(section->sectname, sectname, sizeof(section->sectname))) - { + for (i = 0; i < segment->nsects; ++i) { + if (!strncmp(section->sectname, sectname, sizeof(section->sectname))) { break; } section += 1; } - if (i == segment->nsects) - { + if (i == segment->nsects) { section = NULL; } - finish: +finish: return section; } \ No newline at end of file diff --git a/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/misc_utility.h b/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/misc_utility.h index 7259674c..1c356c03 100644 --- a/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/misc_utility.h +++ b/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/misc_utility.h @@ -8,16 +8,16 @@ typedef uintptr_t addr_t; #include #if defined(__LP64__) -typedef struct mach_header_64 mach_header_t; +typedef struct mach_header_64 mach_header_t; typedef struct segment_command_64 segment_command_t; -typedef struct section_64 section_t; -typedef struct nlist_64 nlist_t; +typedef struct section_64 section_t; +typedef struct nlist_64 nlist_t; #define LC_SEGMENT_ARCH_DEPENDENT LC_SEGMENT_64 #else -typedef struct mach_header mach_header_t; +typedef struct mach_header mach_header_t; typedef struct segment_command segment_command_t; -typedef struct section section_t; -typedef struct nlist nlist_t; +typedef struct section section_t; +typedef struct nlist nlist_t; #define LC_SEGMENT_ARCH_DEPENDENT LC_SEGMENT #endif diff --git a/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/sensitive_api_monitor.cc b/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/sensitive_api_monitor.cc index 1eb1a9ae..23a759bf 100644 --- a/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/sensitive_api_monitor.cc +++ b/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/sensitive_api_monitor.cc @@ -5,19 +5,19 @@ #include #include "SupervisorCallMonitor/supervisor_call_monitor.h" -#include "external_helper/async_logger.h" +#include "misc-helper/async_logger.h" #define PT_DENY_ATTACH 31 -static void sensitive_api_handler(RegisterContext *reg_ctx, const HookEntryInfo *info) { +static void sensitive_api_handler(RegisterContext *ctx, const HookEntryInfo *info) { char buffer[256] = {0}; - int syscall_rum = reg_ctx->general.regs.x16; + int syscall_rum = ctx->general.regs.x16; if (syscall_rum == 0) { - syscall_rum = (int)reg_ctx->general.x[0]; + syscall_rum = (int)ctx->general.x[0]; if (syscall_rum == SYS_ptrace) { - int request = reg_ctx->general.x[1]; + int request = ctx->general.x[1]; if (request == PT_DENY_ATTACH) { - reg_ctx->general.x[1] = 0; + ctx->general.x[1] = 0; // LOG(2, "syscall svc ptrace deny"); } } @@ -26,9 +26,9 @@ static void sensitive_api_handler(RegisterContext *reg_ctx, const HookEntryInfo } } else if (syscall_rum > 0) { if (syscall_rum == SYS_ptrace) { - int request = reg_ctx->general.x[0]; + int request = ctx->general.x[0]; if (request == PT_DENY_ATTACH) { - reg_ctx->general.x[0] = 0; + ctx->general.x[0] = 0; // LOG(2, "svc ptrace deny"); } } @@ -54,7 +54,7 @@ static int get_func_svc_offset(addr_t func_addr) { __typeof(sysctl) *orig_sysctl; int fake_sysctl(int *name, u_int namelen, void *oldp, size_t *oldlenp, void *newp, size_t newlen) { struct kinfo_proc *info = NULL; - int ret = orig_sysctl(name, namelen, oldp, oldlenp, newp, newlen); + int ret = orig_sysctl(name, namelen, oldp, oldlenp, newp, newlen); if (name[0] == CTL_KERN && name[1] == KERN_PROC && name[2] == KERN_PROC_PID) { info = (struct kinfo_proc *)oldp; info->kp_proc.p_flag &= ~(P_TRACED); @@ -63,8 +63,8 @@ int fake_sysctl(int *name, u_int namelen, void *oldp, size_t *oldlenp, void *new } void supervisor_call_monitor_register_sensitive_api_handler() { - char * sensitive_func_array[] = {"ptrace", "exit"}; - size_t count = sizeof(sensitive_func_array) / sizeof(char *); + char *sensitive_func_array[] = {"ptrace", "exit"}; + size_t count = sizeof(sensitive_func_array) / sizeof(char *); for (size_t i = 0; i < count; i++) { addr_t func_addr = 0; diff --git a/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/supervisor_call_monitor.cc b/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/supervisor_call_monitor.cc index 144ae64e..d4b7d3e2 100644 --- a/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/supervisor_call_monitor.cc +++ b/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/supervisor_call_monitor.cc @@ -2,33 +2,33 @@ #include "dobby_internal.h" #include "PlatformUtil/ProcessRuntimeUtility.h" -#include "external_helper/async_logger.h" +#include "misc-helper/async_logger.h" #include std::vector *g_supervisor_call_handlers; static const char *fast_get_main_app_bundle_udid() { static char *main_app_bundle_udid = NULL; - if(main_app_bundle_udid) + if (main_app_bundle_udid) return main_app_bundle_udid; auto main = ProcessRuntimeUtility::GetProcessModuleMap()[0]; char main_binary_path[2048] = {0}; - if(realpath(main.path, main_binary_path) == NULL) + if (realpath(main.path, main_binary_path) == NULL) return NULL; char *bundle_udid_ndx = main_binary_path + strlen("/private/var/containers/Bundle/Application/"); - main_app_bundle_udid = (char *)malloc(36+1); + main_app_bundle_udid = (char *)malloc(36 + 1); strncpy(main_app_bundle_udid, bundle_udid_ndx, 36); main_app_bundle_udid[36] = 0; return main_app_bundle_udid; } static void common_supervisor_call_monitor_handler(RegisterContext *ctx, const HookEntryInfo *info) { -if(g_supervisor_call_handlers == NULL) { -return; -} - for(auto handler : *g_supervisor_call_handlers) { + if (g_supervisor_call_handlers == NULL) { + return; + } + for (auto handler : *g_supervisor_call_handlers) { handler(ctx, info); } } @@ -43,14 +43,14 @@ void supervisor_call_monitor_register_handler(DBICallTy handler) { std::vector *g_svc_addr_array; void supervisor_call_monitor_register_svc(addr_t svc_addr) { - if(g_svc_addr_array == NULL) { + if (g_svc_addr_array == NULL) { g_svc_addr_array = new std::vector(); } - if(g_svc_addr_array) { + if (g_svc_addr_array) { auto iter = g_svc_addr_array->begin(); - for(; iter != g_svc_addr_array->end(); iter++) { - if(*iter == svc_addr) + for (; iter != g_svc_addr_array->end(); iter++) { + if (*iter == svc_addr) return; } } @@ -61,9 +61,9 @@ void supervisor_call_monitor_register_svc(addr_t svc_addr) { } void supervisor_call_monitor_register_image(void *header) { - auto text_section = macho_kit_get_section_by_name((mach_header_t *)header, "__TEXT", "__text"); + auto text_section = macho_kit_get_section_by_name((mach_header_t *)header, "__TEXT", "__text"); - addr_t insn_addr = (addr_t)header + (addr_t)text_section->offset; + addr_t insn_addr = (addr_t)header + (addr_t)text_section->offset; addr_t insn_addr_end = insn_addr + text_section->size; for (; insn_addr < insn_addr_end; insn_addr += sizeof(uint32_t)) { @@ -76,8 +76,8 @@ void supervisor_call_monitor_register_image(void *header) { void supervisor_call_monitor_register_main_app() { const char *main_bundle_udid = fast_get_main_app_bundle_udid(); auto module_map = ProcessRuntimeUtility::GetProcessModuleMap(); - for(auto module : module_map) { - if(strstr(module.path, main_bundle_udid)) { + for (auto module : module_map) { + if (strstr(module.path, main_bundle_udid)) { LOG(2, "[supervisor_call_monitor] %s", module.path); supervisor_call_monitor_register_image((void *)module.load_address); } @@ -96,35 +96,35 @@ struct dyld_cache_header *shared_cache_get_load_addr() { // FIXME: if (__shared_region_check_np((uint64_t *)&shared_cache_load_addr) != 0) { #endif - shared_cache_load_addr = 0; - } - return shared_cache_load_addr; + shared_cache_load_addr = 0; +} +return shared_cache_load_addr; } void supervisor_call_monitor_register_system_kernel() { - auto libsystem = ProcessRuntimeUtility::GetProcessModule("libsystem_kernel.dylib"); - addr_t libsystem_header = (addr_t)libsystem.load_address; - auto text_section = macho_kit_get_section_by_name((mach_header_t *)libsystem_header, "__TEXT", "__text"); + auto libsystem = ProcessRuntimeUtility::GetProcessModule("libsystem_kernel.dylib"); + addr_t libsystem_header = (addr_t)libsystem.load_address; + auto text_section = macho_kit_get_section_by_name((mach_header_t *)libsystem_header, "__TEXT", "__text"); - addr_t shared_cache_load_addr = (addr_t)shared_cache_get_load_addr(); - addr_t insn_addr = shared_cache_load_addr + (addr_t)text_section->offset; - addr_t insn_addr_end = insn_addr + text_section->size; + addr_t shared_cache_load_addr = (addr_t)shared_cache_get_load_addr(); + addr_t insn_addr = shared_cache_load_addr + (addr_t)text_section->offset; + addr_t insn_addr_end = insn_addr + text_section->size; - addr_t write_svc_addr = (addr_t)DobbySymbolResolver("libsystem_kernel.dylib", "write"); - write_svc_addr += 4; + addr_t write_svc_addr = (addr_t)DobbySymbolResolver("libsystem_kernel.dylib", "write"); + write_svc_addr += 4; - addr_t __psynch_mutexwait_svc_addr = (addr_t)DobbySymbolResolver("libsystem_kernel.dylib", "__psynch_mutexwait"); - __psynch_mutexwait_svc_addr += 4; + addr_t __psynch_mutexwait_svc_addr = (addr_t)DobbySymbolResolver("libsystem_kernel.dylib", "__psynch_mutexwait"); + __psynch_mutexwait_svc_addr += 4; - for (; insn_addr < insn_addr_end; insn_addr += sizeof(uint32_t)) { - if (*(uint32_t *)insn_addr == 0xd4001001) { - if (insn_addr == write_svc_addr) - continue; + for (; insn_addr < insn_addr_end; insn_addr += sizeof(uint32_t)) { + if (*(uint32_t *)insn_addr == 0xd4001001) { + if (insn_addr == write_svc_addr) + continue; - if (insn_addr == __psynch_mutexwait_svc_addr) - continue; - supervisor_call_monitor_register_svc((addr_t)insn_addr); - } + if (insn_addr == __psynch_mutexwait_svc_addr) + continue; + supervisor_call_monitor_register_svc((addr_t)insn_addr); } + } } void supervisor_call_monitor_init() { diff --git a/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/system_call_log_handler.cc b/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/system_call_log_handler.cc index 784ebc53..90f9209d 100644 --- a/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/system_call_log_handler.cc +++ b/module/src/main/cpp/Dobby/builtin-plugin/SupervisorCallMonitor/system_call_log_handler.cc @@ -2,7 +2,7 @@ #include -#include "external_helper/async_logger.h" +#include "misc-helper/async_logger.h" #include "PlatformUtil/ProcessRuntimeUtility.h" #include "SupervisorCallMonitor/misc_utility.h" #include "SupervisorCallMonitor/supervisor_call_monitor.h" @@ -13,18 +13,18 @@ static const char *syscall_num_to_str(int num) { return syscallnames[num]; } -static addr_t getCallFirstArg(RegisterContext *reg_ctx) { +static addr_t getCallFirstArg(RegisterContext *ctx) { addr_t result; #if defined(_M_X64) || defined(__x86_64__) #if defined(_WIN32) - result = reg_ctx->general.regs.rcx; + result = ctx->general.regs.rcx; #else - result = reg_ctx->general.regs.rdi; + result = ctx->general.regs.rdi; #endif #elif defined(__arm64__) || defined(__aarch64__) - result = reg_ctx->general.regs.x0; + result = ctx->general.regs.x0; #elif defined(__arm__) - result = reg_ctx->general.regs.r0; + result = ctx->general.regs.r0; #else #error "Not Support Architecture." #endif @@ -40,19 +40,18 @@ static addr_t fast_get_caller_from_main_binary(RegisterContext *ctx) { static addr_t text_section_start = 0, text_section_end = 0; static addr_t slide = 0; if (text_section_start == 0 || text_section_end == 0) { - auto main = ProcessRuntimeUtility::GetProcessModule("mobilex"); + auto main = ProcessRuntimeUtility::GetProcessModule("mobilex"); addr_t main_header = (addr_t)main.load_address; auto text_segment = macho_kit_get_segment_by_name((mach_header_t *)main_header, "__TEXT"); - slide = main_header - text_segment->vmaddr; + slide = main_header - text_segment->vmaddr; - auto text_section = - macho_kit_get_section_by_name((mach_header_t *)main_header, "__TEXT", "__text"); + auto text_section = macho_kit_get_section_by_name((mach_header_t *)main_header, "__TEXT", "__text"); text_section_start = main_header + (addr_t)text_section->offset; - text_section_end = text_section_start + text_section->size; + text_section_end = text_section_start + text_section->size; } - if(ctx == NULL) + if (ctx == NULL) return 0; addr_t lr = getRealLr(ctx); @@ -61,33 +60,33 @@ static addr_t fast_get_caller_from_main_binary(RegisterContext *ctx) { #define MAX_STACK_ITERATE_LEVEL 8 addr_t fp = ctx->fp; - if(fp == 0) + if (fp == 0) return 0; for (int i = 0; i < MAX_STACK_ITERATE_LEVEL; i++) { addr_t lr = *(addr_t *)(fp + sizeof(addr_t)); if (lr > text_section_start && lr < text_section_end) return lr - slide; fp = *(addr_t *)fp; - if(fp == 0) + if (fp == 0) return 0; } return 0; } -static void syscall_log_handler(RegisterContext *reg_ctx, const HookEntryInfo *info) { - addr_t caller = fast_get_caller_from_main_binary(reg_ctx); +static void syscall_log_handler(RegisterContext *ctx, const HookEntryInfo *info) { + addr_t caller = fast_get_caller_from_main_binary(ctx); if (caller == 0) return; char buffer[2048] = {0}; - int syscall_rum = reg_ctx->general.regs.x16; + int syscall_rum = ctx->general.regs.x16; if (syscall_rum == 0) { - syscall_rum = (int)getCallFirstArg(reg_ctx); + syscall_rum = (int)getCallFirstArg(ctx); sprintf(buffer, "[syscall svc-%d] %s\n", syscall_rum, syscall_num_to_str(syscall_rum)); } else if (syscall_rum > 0) { sprintf(buffer, "[svc-%d] %s\n", syscall_rum, syscall_num_to_str(syscall_rum)); - if(syscall_rum == 5) { - sprintf(buffer, "[svc-%d] %s:%s\n", syscall_rum, syscall_num_to_str(syscall_rum), (char *)reg_ctx->general.regs.x0); + if (syscall_rum == 5) { + sprintf(buffer, "[svc-%d] %s:%s\n", syscall_rum, syscall_num_to_str(syscall_rum), (char *)ctx->general.regs.x0); } } async_logger_print(buffer); diff --git a/module/src/main/cpp/Dobby/builtin-plugin/SymbolResolver/CMakeLists.txt b/module/src/main/cpp/Dobby/builtin-plugin/SymbolResolver/CMakeLists.txt new file mode 100644 index 00000000..6151f167 --- /dev/null +++ b/module/src/main/cpp/Dobby/builtin-plugin/SymbolResolver/CMakeLists.txt @@ -0,0 +1,37 @@ +set(SOURCE_FILE_LIST ) + +if(NOT DEFINED DOBBY_DIR) + message(FATAL_ERROR "DOBBY_DIR must be set!") +endif() + +if(SYSTEM.Darwin) + set(SOURCE_FILE_LIST ${SOURCE_FILE_LIST} + ${CMAKE_CURRENT_SOURCE_DIR}/macho/dyld_shared_cache_symbol_table_iterator.cc + ${CMAKE_CURRENT_SOURCE_DIR}/macho/dobby_symbol_resolver.cc + + ${DOBBY_DIR}/source/UserMode/PlatformUtil/Darwin/ProcessRuntimeUtility.cc + ) +endif() +if(SYSTEM.Linux OR SYSTEM.Android) + set(SOURCE_FILE_LIST ${SOURCE_FILE_LIST} + ${CMAKE_CURRENT_SOURCE_DIR}/elf/dobby_symbol_resolver.cc + + ${DOBBY_DIR}/source/UserMode/PlatformUtil/Linux/ProcessRuntimeUtility.cc + ) +endif() +if(SYSTEM.Windows) + set(SOURCE_FILE_LIST ${SOURCE_FILE_LIST} + ${CMAKE_CURRENT_SOURCE_DIR}/pe/dobby_symbol_resolver.cc + + ${DOBBY_DIR}/source/UserMode/PlatformUtil/Windows/ProcessRuntimeUtility.cc + ) +endif() + +add_library(symbol_resolver STATIC + ${SOURCE_FILE_LIST} + ) + +include_directories( + . +) + diff --git a/module/src/main/cpp/Dobby/builtin-plugin/SymbolResolver/elf/dobby_symbol_resolver.cc b/module/src/main/cpp/Dobby/builtin-plugin/SymbolResolver/elf/dobby_symbol_resolver.cc index 5f6a0ac7..fb0cd28f 100644 --- a/module/src/main/cpp/Dobby/builtin-plugin/SymbolResolver/elf/dobby_symbol_resolver.cc +++ b/module/src/main/cpp/Dobby/builtin-plugin/SymbolResolver/elf/dobby_symbol_resolver.cc @@ -1,5 +1,5 @@ #include "SymbolResolver/dobby_symbol_resolver.h" -#include "common/headers/common_header.h" +#include "common_header.h" #include #include @@ -21,7 +21,7 @@ static void file_mmap(const char *file_path, uint8_t **data_ptr, size_t *data_size_ptr) { uint8_t *mmap_data = NULL; - size_t file_size = 0; + size_t file_size = 0; int fd = open(file_path, O_RDONLY, 0); if (fd < 0) { @@ -31,7 +31,7 @@ static void file_mmap(const char *file_path, uint8_t **data_ptr, size_t *data_si { struct stat s; - int rt = fstat(fd, &s); + int rt = fstat(fd, &s); if (rt != 0) { ERROR_LOG("mmap failed"); goto finished; @@ -77,33 +77,33 @@ typedef struct elf_ctx { const char *dynstrtab_; ElfW(Sym) * dynsymtab_; - size_t nbucket_; - size_t nchain_; + size_t nbucket_; + size_t nchain_; uint32_t *bucket_; uint32_t *chain_; - size_t gnu_nbucket_; + size_t gnu_nbucket_; uint32_t *gnu_bucket_; uint32_t *gnu_chain_; - uint32_t gnu_maskwords_; - uint32_t gnu_shift2_; + uint32_t gnu_maskwords_; + uint32_t gnu_shift2_; ElfW(Addr) * gnu_bloom_filter_; } elf_ctx_t; static void get_syms(ElfW(Ehdr) * header, ElfW(Sym) * *symtab_ptr, char **strtab_ptr, int *count_ptr) { ElfW(Shdr) *section_header = NULL; - section_header = (ElfW(Shdr) *)((addr_t)header + header->e_shoff); + section_header = (ElfW(Shdr) *)((addr_t)header + header->e_shoff); ElfW(Shdr) *section_strtab_section_header = NULL; section_strtab_section_header = (ElfW(Shdr) *)((addr_t)section_header + header->e_shstrndx * header->e_shentsize); - char *section_strtab = NULL; - section_strtab = (char *)((addr_t)header + section_strtab_section_header->sh_offset); + char *section_strtab = NULL; + section_strtab = (char *)((addr_t)header + section_strtab_section_header->sh_offset); for (int i = 0; i < header->e_shnum; ++i) { const char *section_name = (const char *)(section_strtab + section_header->sh_name); if (section_header->sh_type == SHT_SYMTAB && strcmp(section_name, ".symtab") == 0) { *symtab_ptr = (ElfW(Sym) *)((addr_t)header + section_header->sh_offset); - *count_ptr = section_header->sh_size / sizeof(ElfW(Sym)); + *count_ptr = section_header->sh_size / sizeof(ElfW(Sym)); } if (section_header->sh_type == SHT_STRTAB && strcmp(section_name, ".strtab") == 0) { @@ -115,21 +115,21 @@ static void get_syms(ElfW(Ehdr) * header, ElfW(Sym) * *symtab_ptr, char **strtab int elf_ctx_init(elf_ctx_t *ctx, void *header_) { ElfW(Ehdr) *ehdr = (ElfW(Ehdr) *)header_; - ctx->header = ehdr; + ctx->header = ehdr; ElfW(Addr) ehdr_addr = (ElfW(Addr))ehdr; // Handle dynamic segment { - ElfW(Addr) addr = 0; - ElfW(Dyn) *dyn = NULL; + ElfW(Addr) addr = 0; + ElfW(Dyn) *dyn = NULL; ElfW(Phdr) *phdr = reinterpret_cast(ehdr_addr + ehdr->e_phoff); for (size_t i = 0; i < ehdr->e_phnum; i++) { if (phdr[i].p_type == PT_DYNAMIC) { dyn = reinterpret_cast(ehdr_addr + phdr[i].p_offset); } else if (phdr[i].p_type == PT_LOAD) { addr = ehdr_addr + phdr[i].p_offset - phdr[i].p_vaddr; - if(ctx->load_bias == 0) + if (ctx->load_bias == 0) ctx->load_bias = ehdr_addr - (phdr[i].p_vaddr - phdr[i].p_offset); } else if (phdr[i].p_type == PT_PHDR) { ctx->load_bias = (ElfW(Addr))phdr - phdr[i].p_vaddr; @@ -157,24 +157,24 @@ int elf_ctx_init(elf_ctx_t *ctx, void *header_) { ElfW(Shdr) *shdr = reinterpret_cast(ehdr_addr + ehdr->e_shoff); ElfW(Shdr) *shstr_sh = NULL; - shstr_sh = &shdr[ehdr->e_shstrndx]; - char *shstrtab = NULL; - shstrtab = (char *)((addr_t)ehdr_addr + shstr_sh->sh_offset); + shstr_sh = &shdr[ehdr->e_shstrndx]; + char *shstrtab = NULL; + shstrtab = (char *)((addr_t)ehdr_addr + shstr_sh->sh_offset); for (size_t i = 0; i < ehdr->e_shnum; i++) { if (shdr[i].sh_type == SHT_SYMTAB) { - sym_sh = &shdr[i]; + sym_sh = &shdr[i]; ctx->sym_sh_ = sym_sh; ctx->symtab_ = (ElfW(Sym) *)(ehdr_addr + shdr[i].sh_offset); } else if (shdr[i].sh_type == SHT_STRTAB && strcmp(shstrtab + shdr[i].sh_name, ".strtab") == 0) { - str_sh = &shdr[i]; + str_sh = &shdr[i]; ctx->strtab_ = (const char *)(ehdr_addr + shdr[i].sh_offset); } else if (shdr[i].sh_type == SHT_DYNSYM) { - dynsym_sh = &shdr[i]; + dynsym_sh = &shdr[i]; ctx->dynsym_sh_ = dynsym_sh; ctx->dynsymtab_ = (ElfW(Sym) *)(ehdr_addr + shdr[i].sh_offset); } else if (shdr[i].sh_type == SHT_STRTAB && strcmp(shstrtab + shdr[i].sh_name, ".dynstr") == 0) { - dynstr_sh = &shdr[i]; + dynstr_sh = &shdr[i]; ctx->dynstrtab_ = (const char *)(ehdr_addr + shdr[i].sh_offset); } } @@ -185,7 +185,7 @@ int elf_ctx_init(elf_ctx_t *ctx, void *header_) { static void *iterate_symbol_table_impl(const char *symbol_name, ElfW(Sym) * symtab, const char *strtab, int count) { for (int i = 0; i < count; ++i) { - ElfW(Sym) *sym = symtab + i; + ElfW(Sym) *sym = symtab + i; const char *symbol_name_ = strtab + sym->st_name; if (strcmp(symbol_name_, symbol_name) == 0) { return (void *)sym->st_value; @@ -198,14 +198,14 @@ void *elf_ctx_iterate_symbol_table(elf_ctx_t *ctx, const char *symbol_name) { void *result = NULL; if (ctx->symtab_ && ctx->strtab_) { size_t count = ctx->sym_sh_->sh_size / sizeof(ElfW(Sym)); - result = iterate_symbol_table_impl(symbol_name, ctx->symtab_, ctx->strtab_, count); + result = iterate_symbol_table_impl(symbol_name, ctx->symtab_, ctx->strtab_, count); if (result) return result; } if (ctx->dynsymtab_ && ctx->dynstrtab_) { size_t count = ctx->dynsym_sh_->sh_size / sizeof(ElfW(Sym)); - result = iterate_symbol_table_impl(symbol_name, ctx->dynsymtab_, ctx->dynstrtab_, count); + result = iterate_symbol_table_impl(symbol_name, ctx->dynsymtab_, ctx->dynstrtab_, count); if (result) return result; } @@ -218,8 +218,8 @@ void *resolve_elf_internal_symbol(const char *library_name, const char *symbol_n if (library_name) { RuntimeModule module = ProcessRuntimeUtility::GetProcessModule(library_name); - uint8_t *file_mem = NULL; - size_t file_mem_size = 0; + uint8_t *file_mem = NULL; + size_t file_mem_size = 0; if (module.load_address) file_mmap(module.path, &file_mem, &file_mem_size); @@ -240,8 +240,8 @@ void *resolve_elf_internal_symbol(const char *library_name, const char *symbol_n if (!result) { std::vector ProcessModuleMap = ProcessRuntimeUtility::GetProcessModuleMap(); for (auto module : ProcessModuleMap) { - uint8_t *file_mem = NULL; - size_t file_mem_size = 0; + uint8_t *file_mem = NULL; + size_t file_mem_size = 0; if (module.load_address) file_mmap(module.path, &file_mem, &file_mem_size); @@ -254,7 +254,7 @@ void *resolve_elf_internal_symbol(const char *library_name, const char *symbol_n } if (result) - result = (void *)((addr_t)result + (addr_t)module.load_address - ((addr_t)file_mem-(addr_t)ctx.load_bias)); + result = (void *)((addr_t)result + (addr_t)module.load_address - ((addr_t)file_mem - (addr_t)ctx.load_bias)); if (file_mem) file_unmap(file_mem, file_mem_size); diff --git a/module/src/main/cpp/Dobby/builtin-plugin/SymbolResolver/macho/dobby_symbol_resolver.cc b/module/src/main/cpp/Dobby/builtin-plugin/SymbolResolver/macho/dobby_symbol_resolver.cc index fa5dd2b1..88cbe90b 100644 --- a/module/src/main/cpp/Dobby/builtin-plugin/SymbolResolver/macho/dobby_symbol_resolver.cc +++ b/module/src/main/cpp/Dobby/builtin-plugin/SymbolResolver/macho/dobby_symbol_resolver.cc @@ -15,7 +15,7 @@ #include "SymbolResolver/dobby_symbol_resolver.h" #include "SymbolResolver/macho/shared_cache_internal.h" -#include "common/headers/common_header.h" +#include "common_header.h" #include "logging/logging.h" @@ -31,35 +31,35 @@ typedef struct macho_ctx { uintptr_t linkedit_base; segment_command_t *segments[16]; - int segments_count; + int segments_count; segment_command_t *text_seg; segment_command_t *data_seg; segment_command_t *data_const_seg; segment_command_t *linkedit_seg; - struct symtab_command * symtab_cmd; - struct dysymtab_command * dysymtab_cmd; + struct symtab_command *symtab_cmd; + struct dysymtab_command *dysymtab_cmd; struct dyld_info_command *dyld_info_cmd; - nlist_t * symtab; - char * strtab; + nlist_t *symtab; + char *strtab; uint32_t *indirect_symtab; } macho_ctx_t; uintptr_t read_uleb128(const uint8_t **pp, const uint8_t *end) { - uint8_t *p = (uint8_t *)*pp; + uint8_t *p = (uint8_t *)*pp; uint64_t result = 0; - int bit = 0; + int bit = 0; do { if (p == end) - assert(p == end); + ASSERT(p == end); uint64_t slice = *p & 0x7f; if (bit > 63) - assert(bit > 63); + ASSERT(bit > 63); else { result |= (slice << bit); bit += 7; @@ -75,11 +75,11 @@ intptr_t read_sleb128(const uint8_t **pp, const uint8_t *end) { uint8_t *p = (uint8_t *)*pp; int64_t result = 0; - int bit = 0; + int bit = 0; uint8_t byte; do { if (p == end) - assert(p == end); + ASSERT(p == end); byte = *p++; result |= (((int64_t)(byte & 0x7f)) << bit); bit += 7; @@ -97,9 +97,9 @@ intptr_t read_sleb128(const uint8_t **pp, const uint8_t *end) { // bool MachOLoaded::findExportedSymbol uint8_t *walk_exported_trie(const uint8_t *start, const uint8_t *end, const char *symbol) { uint32_t visitedNodeOffsets[128]; - int visitedNodeOffsetCount = 0; + int visitedNodeOffsetCount = 0; visitedNodeOffsets[visitedNodeOffsetCount++] = 0; - const uint8_t *p = start; + const uint8_t *p = start; while (p < end) { uint64_t terminalSize = *p++; if (terminalSize > 127) { @@ -119,11 +119,11 @@ uint8_t *walk_exported_trie(const uint8_t *start, const uint8_t *end, const char return NULL; } uint8_t childrenRemaining = *children++; - p = children; - uint64_t nodeOffset = 0; + p = children; + uint64_t nodeOffset = 0; for (; childrenRemaining > 0; --childrenRemaining) { - const char *ss = symbol; - bool wrongEdge = false; + const char *ss = symbol; + bool wrongEdge = false; // scan whole edge to get to next edge // if edge is longer than target symbol name, don't read past end of symbol name char c = *p; @@ -184,10 +184,10 @@ uint8_t *walk_exported_trie(const uint8_t *start, const uint8_t *end, const char } uintptr_t iterate_exported_symbol(mach_header_t *header, const char *symbol_name, uint64_t *out_flags) { - segment_command_t * curr_seg_cmd; - struct dyld_info_command * dyld_info_cmd = NULL; + segment_command_t *curr_seg_cmd; + struct dyld_info_command *dyld_info_cmd = NULL; struct linkedit_data_command *exports_trie_cmd = NULL; - segment_command_t * text_segment, *data_segment, *linkedit_segment; + segment_command_t *text_segment, *data_segment, *linkedit_segment; curr_seg_cmd = (segment_command_t *)((uintptr_t)header + sizeof(mach_header_t)); for (int i = 0; i < header->ncmds; i++) { @@ -220,9 +220,9 @@ uintptr_t iterate_exported_symbol(mach_header_t *header, const char *symbol_name return 0; uint32_t trieFileOffset = dyld_info_cmd ? dyld_info_cmd->export_off : exports_trie_cmd->dataoff; - uint32_t trieFileSize = dyld_info_cmd ? dyld_info_cmd->export_size : exports_trie_cmd->datasize; + uint32_t trieFileSize = dyld_info_cmd ? dyld_info_cmd->export_size : exports_trie_cmd->datasize; - uintptr_t slide = (uintptr_t)header - (uintptr_t)text_segment->vmaddr; + uintptr_t slide = (uintptr_t)header - (uintptr_t)text_segment->vmaddr; uintptr_t linkedit_base = (uintptr_t)slide + linkedit_segment->vmaddr - linkedit_segment->fileoff; void *exports = (void *)(linkedit_base + trieFileOffset); @@ -230,11 +230,11 @@ uintptr_t iterate_exported_symbol(mach_header_t *header, const char *symbol_name return 0; uint8_t *exports_start = (uint8_t *)exports; - uint8_t *exports_end = exports_start + trieFileSize; - uint8_t *node = (uint8_t *)walk_exported_trie(exports_start, exports_end, symbol_name); + uint8_t *exports_end = exports_start + trieFileSize; + uint8_t *node = (uint8_t *)walk_exported_trie(exports_start, exports_end, symbol_name); if (node == NULL) return 0; - const uint8_t * p = node; + const uint8_t *p = node; const uintptr_t flags = read_uleb128(&p, exports_end); if (flags & EXPORT_SYMBOL_FLAGS_REEXPORT) { return 0; @@ -257,10 +257,10 @@ uintptr_t iterate_exported_symbol(mach_header_t *header, const char *symbol_name void macho_ctx_init(macho_ctx_t *ctx, mach_header_t *header) { ctx->header = header; - segment_command_t * curr_seg_cmd; - segment_command_t * text_segment, *data_segment, *data_const_segment, *linkedit_segment; - struct symtab_command * symtab_cmd = NULL; - struct dysymtab_command * dysymtab_cmd = NULL; + segment_command_t *curr_seg_cmd; + segment_command_t *text_segment, *data_segment, *data_const_segment, *linkedit_segment; + struct symtab_command *symtab_cmd = NULL; + struct dysymtab_command *dysymtab_cmd = NULL; struct dyld_info_command *dyld_info_cmd = NULL; curr_seg_cmd = (segment_command_t *)((uintptr_t)header + sizeof(mach_header_t)); @@ -288,23 +288,23 @@ void macho_ctx_init(macho_ctx_t *ctx, mach_header_t *header) { curr_seg_cmd = (segment_command_t *)((uintptr_t)curr_seg_cmd + curr_seg_cmd->cmdsize); } - uintptr_t slide = (uintptr_t)header - (uintptr_t)text_segment->vmaddr; + uintptr_t slide = (uintptr_t)header - (uintptr_t)text_segment->vmaddr; uintptr_t linkedit_base = (uintptr_t)slide + linkedit_segment->vmaddr - linkedit_segment->fileoff; - ctx->text_seg = text_segment; - ctx->data_seg = data_segment; + ctx->text_seg = text_segment; + ctx->data_seg = data_segment; ctx->data_const_seg = data_const_segment; - ctx->linkedit_seg = linkedit_segment; + ctx->linkedit_seg = linkedit_segment; - ctx->symtab_cmd = symtab_cmd; - ctx->dysymtab_cmd = dysymtab_cmd; + ctx->symtab_cmd = symtab_cmd; + ctx->dysymtab_cmd = dysymtab_cmd; ctx->dyld_info_cmd = dyld_info_cmd; - ctx->slide = slide; + ctx->slide = slide; ctx->linkedit_base = linkedit_base; - ctx->symtab = (nlist_t *)(ctx->linkedit_base + ctx->symtab_cmd->symoff); - ctx->strtab = (char *)(ctx->linkedit_base + ctx->symtab_cmd->stroff); + ctx->symtab = (nlist_t *)(ctx->linkedit_base + ctx->symtab_cmd->symoff); + ctx->strtab = (char *)(ctx->linkedit_base + ctx->symtab_cmd->stroff); ctx->indirect_symtab = (uint32_t *)(ctx->linkedit_base + ctx->dysymtab_cmd->indirectsymoff); } @@ -312,7 +312,7 @@ uintptr_t iterate_symbol_table(char *name_pattern, nlist_t *symtab, uint32_t sym for (uint32_t i = 0; i < symtab_count; i++) { if (symtab[i].n_value) { uint32_t strtab_offset = symtab[i].n_un.n_strx; - char * symbol_name = strtab + strtab_offset; + char *symbol_name = strtab + strtab_offset; #if 0 LOG(1, "> %s", symbol_name); #endif @@ -357,7 +357,7 @@ PUBLIC void *DobbySymbolResolver(const char *image_name, const char *symbol_name continue; mach_header_t *header = (mach_header_t *)module.load_address; - size_t slide = 0; + size_t slide = 0; if (header) { if (header->magic == MH_MAGIC_64) @@ -368,17 +368,19 @@ PUBLIC void *DobbySymbolResolver(const char *image_name, const char *symbol_name LOG(1, "resolve image: %s", path); #endif - nlist_t *symtab = NULL; + nlist_t *symtab = NULL; uint32_t symtab_count = 0; - char * strtab = NULL; + char *strtab = NULL; #if defined(__arm__) || defined(__aarch64__) + static int shared_cache_ctx_init_once = 0; static shared_cache_ctx_t shared_cache_ctx; - if (shared_cache_ctx.mmap_shared_cache == NULL) { + if (shared_cache_ctx_init_once == 0) { + shared_cache_ctx_init_once = 1; memset(&shared_cache_ctx, 0, sizeof(shared_cache_ctx_t)); shared_cache_ctx_init(&shared_cache_ctx); } - if(shared_cache_ctx.runtime_shared_cache) { + if (shared_cache_ctx.runtime_shared_cache) { // shared cache library if (shared_cache_is_contain(&shared_cache_ctx, (addr_t)header, 0)) { shared_cache_get_symbol_table(&shared_cache_ctx, header, &symtab, &symtab_count, &strtab); @@ -427,7 +429,7 @@ PUBLIC void *DobbySymbolResolver(const char *image_name, const char *symbol_name mach_header_t *dyld_header = NULL; if (image_name != NULL && strcmp(image_name, "dyld") == 0) { // task info - task_dyld_info_data_t task_dyld_info; + task_dyld_info_data_t task_dyld_info; mach_msg_type_number_t count = TASK_DYLD_INFO_COUNT; if (task_info(mach_task_self(), TASK_DYLD_INFO, (task_info_t)&task_dyld_info, &count)) { return NULL; @@ -454,7 +456,7 @@ PUBLIC void *DobbySymbolResolver(const char *image_name, const char *symbol_name #if defined(DOBBY_DEBUG) && 0 __attribute__((constructor)) static void ctor() { mach_header_t *header = NULL; - header = (mach_header_t *)_dyld_get_image_header(0); + header = (mach_header_t *)_dyld_get_image_header(0); void *addr = (void *)((addr_t)iterate_exported_symbol(header, "_mainxx") + (addr_t)header); LOG(1, "export %p", addr); diff --git a/module/src/main/cpp/Dobby/builtin-plugin/SymbolResolver/macho/dyld_shared_cache_symbol_table_iterator.cc b/module/src/main/cpp/Dobby/builtin-plugin/SymbolResolver/macho/dyld_shared_cache_symbol_table_iterator.cc index 37d36dc5..27e1dc54 100644 --- a/module/src/main/cpp/Dobby/builtin-plugin/SymbolResolver/macho/dyld_shared_cache_symbol_table_iterator.cc +++ b/module/src/main/cpp/Dobby/builtin-plugin/SymbolResolver/macho/dyld_shared_cache_symbol_table_iterator.cc @@ -33,8 +33,8 @@ static char *fast_get_shared_cache_path() { #if defined(_M_IX86) || defined(__i386__) || defined(_M_X64) || defined(__x86_64__) return NULL; #endif - char *result = NULL; - char path_buffer[2048] = {0}; + char *result = NULL; + char path_buffer[2048] = {0}; const char *path = NULL; do { @@ -43,25 +43,25 @@ static char *fast_get_shared_cache_path() { break; } else { struct stat statbuf; - int r = 0; + int r = 0; path = IPHONE_DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME "arm64"; - r = stat(path, &statbuf); + r = stat(path, &statbuf); if (r == 0) { break; } path = IPHONE_DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME "arm64e"; - r = stat(path, &statbuf); + r = stat(path, &statbuf); if (r == 0) { break; } path = MACOSX_MRM_DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME "arm64"; - r = stat(path, &statbuf); + r = stat(path, &statbuf); if (r == 0) { break; } path = MACOSX_MRM_DYLD_SHARED_CACHE_DIR DYLD_SHARED_CACHE_BASE_NAME "arm64e"; - r = stat(path, &statbuf); + r = stat(path, &statbuf); if (r == 0) { break; } @@ -84,7 +84,7 @@ struct dyld_cache_header *shared_cache_get_load_addr() { static struct dyld_cache_header *shared_cache_load_addr = 0; // task info - task_dyld_info_data_t task_dyld_info; + task_dyld_info_data_t task_dyld_info; mach_msg_type_number_t count = TASK_DYLD_INFO_COUNT; if (task_info(mach_task_self(), TASK_DYLD_INFO, (task_info_t)&task_dyld_info, &count)) { return NULL; @@ -112,7 +112,7 @@ struct dyld_cache_header *shared_cache_get_load_addr() { } int shared_cache_ctx_init(shared_cache_ctx_t *ctx) { - int fd; + int fd; const char *cache_file_path = NULL; cache_file_path = fast_get_shared_cache_path(); @@ -130,7 +130,7 @@ int shared_cache_ctx_init(shared_cache_ctx_t *ctx) { // auto align runtime_shared_cache = shared_cache_get_load_addr(); - if(runtime_shared_cache == NULL) { + if (runtime_shared_cache == NULL) { return KERN_FAILURE; } @@ -140,11 +140,11 @@ int shared_cache_ctx_init(shared_cache_ctx_t *ctx) { } size_t mmap_length = runtime_shared_cache->localSymbolsSize; - off_t mmap_offset = runtime_shared_cache->localSymbolsOffset; + off_t mmap_offset = runtime_shared_cache->localSymbolsOffset; mmap_shared_cache = (struct dyld_cache_header *)mmap(0, mmap_length, PROT_READ, MAP_FILE | MAP_PRIVATE, fd, mmap_offset); if (mmap_shared_cache == MAP_FAILED) { - ERROR_LOG("mmap shared cache failed"); + DLOG(0, "mmap shared cache failed"); return KERN_FAILURE; } @@ -153,12 +153,12 @@ int shared_cache_ctx_init(shared_cache_ctx_t *ctx) { (struct dyld_cache_header *)((addr_t)mmap_shared_cache - runtime_shared_cache->localSymbolsOffset); ctx->runtime_shared_cache = runtime_shared_cache; - ctx->mmap_shared_cache = mmap_shared_cache; + ctx->mmap_shared_cache = mmap_shared_cache; // shared cache slide const struct dyld_cache_mapping_info *mappings = (struct dyld_cache_mapping_info *)((char *)runtime_shared_cache + runtime_shared_cache->mappingOffset); - uintptr_t slide = (uintptr_t)runtime_shared_cache - (uintptr_t)(mappings[0].address); + uintptr_t slide = (uintptr_t)runtime_shared_cache - (uintptr_t)(mappings[0].address); ctx->runtime_slide = slide; // shared cache symbol table @@ -169,7 +169,7 @@ int shared_cache_ctx_init(shared_cache_ctx_t *ctx) { static struct dyld_cache_local_symbols_entry *localEntries = NULL; localEntries = (struct dyld_cache_local_symbols_entry *)((char *)localInfo + localInfo->entriesOffset); - ctx->local_symbols_info = localInfo; + ctx->local_symbols_info = localInfo; ctx->local_symbols_entries = localEntries; ctx->symtab = (nlist_t *)((char *)localInfo + localInfo->nlistOffset); @@ -188,7 +188,7 @@ bool shared_cache_is_contain(shared_cache_ctx_t *ctx, addr_t addr, size_t length const struct dyld_cache_mapping_info *mappings = (struct dyld_cache_mapping_info *)((char *)runtime_shared_cache + runtime_shared_cache->mappingOffset); - uintptr_t slide = (uintptr_t)runtime_shared_cache - (uintptr_t)(mappings[0].address); + uintptr_t slide = (uintptr_t)runtime_shared_cache - (uintptr_t)(mappings[0].address); uintptr_t unslidStart = (uintptr_t)addr - slide; // quick out if after end of cache @@ -197,7 +197,7 @@ bool shared_cache_is_contain(shared_cache_ctx_t *ctx, addr_t addr, size_t length // walk cache regions const struct dyld_cache_mapping_info *mappingsEnd = &mappings[runtime_shared_cache->mappingCount]; - uintptr_t unslidEnd = unslidStart + length; + uintptr_t unslidEnd = unslidStart + length; for (const struct dyld_cache_mapping_info *m = mappings; m < mappingsEnd; ++m) { if ((unslidStart >= m->address) && (unslidEnd < (m->address + m->size))) { return true; @@ -214,16 +214,16 @@ int shared_cache_get_symbol_table(shared_cache_ctx_t *ctx, mach_header_t *image_ uint64_t textOffsetInCache = (uint64_t)image_header - (uint64_t)runtime_shared_cache; - nlist_t * localNlists = NULL; - uint32_t localNlistCount = 0; - const char *localStrings = NULL; + nlist_t *localNlists = NULL; + uint32_t localNlistCount = 0; + const char *localStrings = NULL; const uint32_t entriesCount = ctx->local_symbols_info->entriesCount; for (uint32_t i = 0; i < entriesCount; ++i) { if (ctx->local_symbols_entries[i].dylibOffset == textOffsetInCache) { uint32_t localNlistStart = ctx->local_symbols_entries[i].nlistStartIndex; - localNlistCount = ctx->local_symbols_entries[i].nlistCount; - localNlists = &ctx->symtab[localNlistStart]; + localNlistCount = ctx->local_symbols_entries[i].nlistCount; + localNlists = &ctx->symtab[localNlistStart]; #if 0 static struct dyld_cache_image_info *imageInfos = NULL; @@ -233,8 +233,8 @@ int shared_cache_get_symbol_table(shared_cache_ctx_t *ctx, mach_header_t *image_ #endif } } - *out_symtab = localNlists; + *out_symtab = localNlists; *out_symtab_count = (uint32_t)localNlistCount; - *out_strtab = (char *)ctx->strtab; + *out_strtab = (char *)ctx->strtab; return 0; } diff --git a/module/src/main/cpp/Dobby/builtin-plugin/SymbolResolver/macho/shared-cache/dyld_cache_format.h b/module/src/main/cpp/Dobby/builtin-plugin/SymbolResolver/macho/shared-cache/dyld_cache_format.h index 4de33c8d..714291cd 100644 --- a/module/src/main/cpp/Dobby/builtin-plugin/SymbolResolver/macho/shared-cache/dyld_cache_format.h +++ b/module/src/main/cpp/Dobby/builtin-plugin/SymbolResolver/macho/shared-cache/dyld_cache_format.h @@ -28,7 +28,7 @@ #include struct dyld_cache_header { - char magic[16]; // e.g. "dyld_v0 i386" + char magic[16]; // e.g. "dyld_v0 i386" uint32_t mappingOffset; // file offset to first dyld_cache_mapping_info uint32_t mappingCount; // number of dyld_cache_mapping_info entries uint32_t imagesOffset; // file offset to first dyld_cache_image_info @@ -40,7 +40,7 @@ struct dyld_cache_header { uint64_t slideInfoSizeUnused; // unused. Used to be size of kernel slid info uint64_t localSymbolsOffset; // file offset of where local symbols are stored uint64_t localSymbolsSize; // size of local symbols information - uint8_t uuid[16]; // unique value for each shared cache file + uint8_t uuid[16]; // unique value for each shared cache file uint64_t cacheType; // 0 for development, 1 for production uint32_t branchPoolsOffset; // file offset to table of uint64_t pool addresses uint32_t branchPoolsCount; // number of uint64_t entries @@ -91,7 +91,7 @@ struct dyld_cache_mapping_info { // Contains the flags for the dyld_cache_mapping_and_slide_info flgs field enum { - DYLD_CACHE_MAPPING_AUTH_DATA = 1 << 0U, + DYLD_CACHE_MAPPING_AUTH_DATA = 1 << 0U, DYLD_CACHE_MAPPING_DIRTY_DATA = 1 << 1U, DYLD_CACHE_MAPPING_CONST_DATA = 1 << 2U, }; @@ -162,7 +162,7 @@ struct dyld_cache_accelerator_dof { }; struct dyld_cache_image_text_info { - uuid_t uuid; + uuid_t uuid; uint64_t loadAddress; // unslid address of start of __TEXT uint32_t textSegmentSize; uint32_t pathOffset; // offset from start of cache file @@ -261,10 +261,10 @@ struct dyld_cache_slide_info2 { //uint16_t page_starts[page_starts_count]; //uint16_t page_extras[page_extras_count]; }; -#define DYLD_CACHE_SLIDE_PAGE_ATTRS 0xC000 // high bits of uint16_t are flags -#define DYLD_CACHE_SLIDE_PAGE_ATTR_EXTRA 0x8000 // index is into extras array (not starts array) +#define DYLD_CACHE_SLIDE_PAGE_ATTRS 0xC000 // high bits of uint16_t are flags +#define DYLD_CACHE_SLIDE_PAGE_ATTR_EXTRA 0x8000 // index is into extras array (not starts array) #define DYLD_CACHE_SLIDE_PAGE_ATTR_NO_REBASE 0x4000 // page has no rebasing -#define DYLD_CACHE_SLIDE_PAGE_ATTR_END 0x8000 // last chain entry for page +#define DYLD_CACHE_SLIDE_PAGE_ATTR_END 0x8000 // last chain entry for page // The version 3 of the slide info uses a different compression scheme. Since // only interior pointers (pointers that point within the cache) are rebased @@ -413,7 +413,7 @@ struct dyld_cache_slide_info4 { //uint16_t page_extras[page_extras_count]; }; #define DYLD_CACHE_SLIDE4_PAGE_NO_REBASE 0xFFFF // page has no rebasing -#define DYLD_CACHE_SLIDE4_PAGE_INDEX 0x7FFF // mask of page_starts[] values +#define DYLD_CACHE_SLIDE4_PAGE_INDEX 0x7FFF // mask of page_starts[] values #define DYLD_CACHE_SLIDE4_PAGE_USE_EXTRA 0x8000 // index is into extras array (not a chain start offset) #define DYLD_CACHE_SLIDE4_PAGE_EXTRA_END 0x8000 // last chain entry for page @@ -476,6 +476,6 @@ struct dyld_cache_patchable_location { #define DYLD_SHARED_CACHE_DEVELOPMENT_EXT ".development" static const uint64_t kDyldSharedCacheTypeDevelopment = 0; -static const uint64_t kDyldSharedCacheTypeProduction = 1; +static const uint64_t kDyldSharedCacheTypeProduction = 1; #endif // __DYLD_CACHE_FORMAT__ diff --git a/module/src/main/cpp/Dobby/builtin-plugin/SymbolResolver/macho/shared_cache_internal.h b/module/src/main/cpp/Dobby/builtin-plugin/SymbolResolver/macho/shared_cache_internal.h index 190392cf..928cbe3e 100644 --- a/module/src/main/cpp/Dobby/builtin-plugin/SymbolResolver/macho/shared_cache_internal.h +++ b/module/src/main/cpp/Dobby/builtin-plugin/SymbolResolver/macho/shared_cache_internal.h @@ -3,45 +3,45 @@ #include #if defined(__LP64__) -typedef struct mach_header_64 mach_header_t; +typedef struct mach_header_64 mach_header_t; typedef struct segment_command_64 segment_command_t; -typedef struct section_64 section_t; -typedef struct nlist_64 nlist_t; +typedef struct section_64 section_t; +typedef struct nlist_64 nlist_t; #define LC_SEGMENT_ARCH_DEPENDENT LC_SEGMENT_64 #else -typedef struct mach_header mach_header_t; +typedef struct mach_header mach_header_t; typedef struct segment_command segment_command_t; -typedef struct section section_t; -typedef struct nlist nlist_t; +typedef struct section section_t; +typedef struct nlist nlist_t; #define LC_SEGMENT_ARCH_DEPENDENT LC_SEGMENT #endif #if __i386__ -#define ARCH_NAME "i386" +#define ARCH_NAME "i386" #define ARCH_CACHE_MAGIC "dyld_v1 i386" #elif __x86_64__ -#define ARCH_NAME "x86_64" -#define ARCH_CACHE_MAGIC "dyld_v1 x86_64" -#define ARCH_NAME_H "x86_64h" +#define ARCH_NAME "x86_64" +#define ARCH_CACHE_MAGIC "dyld_v1 x86_64" +#define ARCH_NAME_H "x86_64h" #define ARCH_CACHE_MAGIC_H "dyld_v1 x86_64h" #elif __ARM_ARCH_7K__ -#define ARCH_NAME "armv7k" +#define ARCH_NAME "armv7k" #define ARCH_CACHE_MAGIC "dyld_v1 armv7k" #elif __ARM_ARCH_7A__ -#define ARCH_NAME "armv7" +#define ARCH_NAME "armv7" #define ARCH_CACHE_MAGIC "dyld_v1 armv7" #elif __ARM_ARCH_7S__ -#define ARCH_NAME "armv7s" +#define ARCH_NAME "armv7s" #define ARCH_CACHE_MAGIC "dyld_v1 armv7s" #elif __arm64e__ -#define ARCH_NAME "arm64e" +#define ARCH_NAME "arm64e" #define ARCH_CACHE_MAGIC "dyld_v1 arm64e" #elif __arm64__ #if __LP64__ -#define ARCH_NAME "arm64" +#define ARCH_NAME "arm64" #define ARCH_CACHE_MAGIC "dyld_v1 arm64" #else -#define ARCH_NAME "arm64_32" +#define ARCH_NAME "arm64_32" #define ARCH_CACHE_MAGIC "dyld_v1arm64_32" #endif #endif @@ -66,4 +66,5 @@ int shared_cache_ctx_init(shared_cache_ctx_t *ctx); bool shared_cache_is_contain(shared_cache_ctx_t *ctx, addr_t addr, size_t length); -int shared_cache_get_symbol_table(shared_cache_ctx_t *ctx, mach_header_t *image_header, nlist_t **out_symtab, uint32_t *out_symtab_count,char **out_strtab); +int shared_cache_get_symbol_table(shared_cache_ctx_t *ctx, mach_header_t *image_header, nlist_t **out_symtab, + uint32_t *out_symtab_count, char **out_strtab); diff --git a/module/src/main/cpp/Dobby/builtin-plugin/SymbolResolver/pe/dobby_symbol_resolver.cc b/module/src/main/cpp/Dobby/builtin-plugin/SymbolResolver/pe/dobby_symbol_resolver.cc new file mode 100644 index 00000000..65920a0c --- /dev/null +++ b/module/src/main/cpp/Dobby/builtin-plugin/SymbolResolver/pe/dobby_symbol_resolver.cc @@ -0,0 +1,26 @@ +#include "SymbolResolver/dobby_symbol_resolver.h" +#include "common_header.h" + +#include + +#include +#include + +#include "PlatformUtil/ProcessRuntimeUtility.h" + +#include + +#undef LOG_TAG +#define LOG_TAG "DobbySymbolResolver" + +PUBLIC void *DobbySymbolResolver(const char *image_name, const char *symbol_name_pattern) { + void *result = NULL; + + HMODULE hMod = LoadLibraryExA(image_name, NULL, DONT_RESOLVE_DLL_REFERENCES); + result = GetProcAddress(hMod, symbol_name_pattern); + if (result) + return result; + + //result = resolve_elf_internal_symbol(image_name, symbol_name_pattern); + return result; +} \ No newline at end of file diff --git a/module/src/main/cpp/Dobby/cmake/dobby.xcode.source.cmake b/module/src/main/cpp/Dobby/cmake/dobby.xcode.source.cmake index b6843ab5..0949c5f3 100644 --- a/module/src/main/cpp/Dobby/cmake/dobby.xcode.source.cmake +++ b/module/src/main/cpp/Dobby/cmake/dobby.xcode.source.cmake @@ -42,29 +42,29 @@ set(dobby.SOURCE_FILE_LIST source/InterceptRouting/InterceptRouting.cpp # intercept routing trampoline - source/TrampolineBridge/InterceptRoutingTrampoline/arm/trampoline-arm.cc - source/TrampolineBridge/InterceptRoutingTrampoline/arm64/trampoline-arm64.cc - source/TrampolineBridge/InterceptRoutingTrampoline/x86/trampoline-x86.cc - source/TrampolineBridge/InterceptRoutingTrampoline/x64/trampoline-x64.cc + source/TrampolineBridge/Trampoline/arm/trampoline-arm.cc + source/TrampolineBridge/Trampoline/arm64/trampoline-arm64.cc + source/TrampolineBridge/Trampoline/x86/trampoline-x86.cc + source/TrampolineBridge/Trampoline/x64/trampoline-x64.cc # intercept routing plugin (buildin) - source/InterceptRouting/RoutingPlugin/FunctionInlineReplace/function-inline-replace.cc - source/InterceptRouting/RoutingPlugin/FunctionInlineReplace/FunctionInlineReplaceExport.cc + source/InterceptRouting/Routing/FunctionInlineReplace/function-inline-replace.cc + source/InterceptRouting/Routing/FunctionInlineReplace/FunctionInlineReplaceExport.cc # plugin register - source/InterceptRouting/ExtraInternalPlugin/RegisterPlugin.cc + source/InterceptRouting/RoutingPlugin/RoutingPlugin.cc # unified interface # platform util - source/UserMode/PlatformUtil/${platform2}/ProcesssRuntimeUtility.cc + source/UserMode/PlatformUtil/${platform2}/ProcessRuntimeUtility.cc # user mode - platform interface source/UserMode/UnifiedInterface/platform-${platform1}.cc # user mode - executable memory source/UserMode/ExecMemory/code-patch-tool-${platform1}.cc - source/UserMode/ExecMemory/clear-cache-tool-all.cc + source/UserMode/ExecMemory/clear-cache-tool-all.c # main source/dobby.cpp @@ -74,7 +74,7 @@ set(dobby.SOURCE_FILE_LIST if(FunctionWrapper OR DynamicBinaryInstrument) set(dobby.SOURCE_FILE_LIST ${dobby.SOURCE_FILE_LIST} # closure trampoline bridge - source/TrampolineBridge/ClosureTrampolineBridge/closure-trampoline-common-handler.cc + source/TrampolineBridge/ClosureTrampolineBridge/common-bridge-handler.cc source/TrampolineBridge/ClosureTrampolineBridge/arm/helper-arm.cc source/TrampolineBridge/ClosureTrampolineBridge/arm/closure-bridge-arm.cc diff --git a/module/src/main/cpp/Dobby/docs/CNAME b/module/src/main/cpp/Dobby/docs/CNAME deleted file mode 100644 index a5ce774c..00000000 --- a/module/src/main/cpp/Dobby/docs/CNAME +++ /dev/null @@ -1 +0,0 @@ -dobby.libkernel.com \ No newline at end of file diff --git a/module/src/main/cpp/Dobby/docs/build-documentation.md b/module/src/main/cpp/Dobby/docs/build-documentation.md index e57be29b..270fafac 100644 --- a/module/src/main/cpp/Dobby/docs/build-documentation.md +++ b/module/src/main/cpp/Dobby/docs/build-documentation.md @@ -1,10 +1,4 @@ -# Installation - -## Clone the project - -``` -git clone --depth 1 git@github.com:jmpews/Dobby.git -``` +# Build ## Cmake build options @@ -19,13 +13,17 @@ option(DynamicBinaryInstrument "Enable Dynamic Binary Instrument" ON) option(FullFloatingPointRegisterPack "Save and pack all floating-point registers" OFF) -option(GenerateDarwinFramework "Build darwin framework library" ON) - option(Plugin.SymbolResolver "Resolve symbol by [DobbySymbolResolver] " ON) +option(Plugin.GlobalOffsetTableHook "Global Offset Table Hook by [DobbyGlobalOffsetTableReplace] " ON) + option(Plugin.LinkerLoadCallback "Register image load callback " OFF) ``` +## Build script + +refer: [build-workspace/auto-build.sh](build-workspace/auto-build.sh) + ## Build for host ``` @@ -54,10 +52,7 @@ make -j4 ``` cd Dobby && mkdir build_for_ios_arm64 && cd build_for_ios_arm64 -cmake .. \ --DCMAKE_TOOLCHAIN_FILE=cmake/ios.toolchain.cmake \ --DPLATFORM=OS64 -DARCHS="arm64" -DCMAKE_SYSTEM_PROCESSOR=arm64 \ --DENABLE_BITCODE=0 -DENABLE_ARC=0 -DENABLE_VISIBILITY=1 -DDEPLOYMENT_TARGET=9.3 +cmake .. -DCMAKE_SYSTEM_NAME=iOS -DCMAKE_OSX_ARCHITECTURES=arm64 -DCMAKE_SYSTEM_PROCESSOR=arm64 -DCMAKE_OSX_DEPLOYMENT_TARGET=9.3 make -j4 ``` @@ -96,35 +91,26 @@ make -j4 #### Android Studio CMake ``` -set(DobbyHome D:/TimeDisk/Workspace/Project.wrk/Dobby) +if(NOT TARGET dobby) +set(DOBBY_DIR /Users/jmpews/Workspace/Project.wrk/Dobby) +macro(SET_OPTION option value) + set(${option} ${value} CACHE INTERNAL "" FORCE) +endmacro() +SET_OPTION(DOBBY_DEBUG OFF) +SET_OPTION(DOBBY_GENERATE_SHARED OFF) +add_subdirectory(${DOBBY_DIR} dobby) +get_property(DOBBY_INCLUDE_DIRECTORIES + TARGET dobby + PROPERTY INCLUDE_DIRECTORIES) include_directories( - ${DobbyHome}/include - ${DobbyHome}/builtin-plugin - ${DobbyHome}/builtin-plugin/SymbolResolver - ${DobbyHome}/builtin-plugin/AndroidRestriction - ${DobbyHome}/external/logging + . + ${DOBBY_INCLUDE_DIRECTORIES} + $ ) +endif() -add_library( # Sets the name of the library. - native-lib - # Sets the library as a shared library. - SHARED - - ${DobbyHome}/builtin-plugin/AndroidRestriction/android_restriction_demo.cc - - ${DobbyHome}/builtin-plugin/ApplicationEventMonitor/posix_file_descriptor_operation_monitor.cc - ${DobbyHome}/builtin-plugin/ApplicationEventMonitor/dynamic_loader_monitor.cc +add_library(native-lib SHARED + ${DOBBY_DIR}/example/android_common_api.cc - # Provides a relative path to your source file(s). native-lib.cpp) - -macro(SET_OPTION option value) - set(${option} ${value} CACHE INTERNAL "" FORCE) -endmacro() -SET_OPTION(DOBBY_DEBUG ON) -SET_OPTION(DOBBY_GENERATE_SHARED OFF) -SET_OPTION(DynamicBinaryInstrument ON) -SET_OPTION(NearBranch ON) -SET_OPTION(Plugin.SymbolResolver ON) -add_subdirectory(${DobbyHome} dobby) ``` \ No newline at end of file diff --git a/module/src/main/cpp/Dobby/docs/get-started-android.md b/module/src/main/cpp/Dobby/docs/get-started-android.md index ab47a3f2..5615028e 100644 --- a/module/src/main/cpp/Dobby/docs/get-started-android.md +++ b/module/src/main/cpp/Dobby/docs/get-started-android.md @@ -3,34 +3,28 @@ ## create native project and update CMakeLists.txt ``` -set(DobbyHome D:/TimeDisk/Workspace/Project.wrk/Dobby) +if(NOT TARGET dobby) +set(DOBBY_DIR /Users/jmpews/Workspace/Project.wrk/Dobby) +macro(SET_OPTION option value) + set(${option} ${value} CACHE INTERNAL "" FORCE) +endmacro() +SET_OPTION(DOBBY_DEBUG OFF) +SET_OPTION(DOBBY_GENERATE_SHARED OFF) +add_subdirectory(${DOBBY_DIR} dobby) +get_property(DOBBY_INCLUDE_DIRECTORIES + TARGET dobby + PROPERTY INCLUDE_DIRECTORIES) include_directories( - ${DobbyHome}/include - ${DobbyHome}/builtin-plugin - ${DobbyHome}/builtin-plugin/SymbolResolver - ${DobbyHome}/builtin-plugin/AndroidRestriction - ${DobbyHome}/external/logging + . + ${DOBBY_INCLUDE_DIRECTORIES} + $ ) +endif() -add_library( # Sets the name of the library. - native-lib - # Sets the library as a shared library. - SHARED - - ${DobbyHome}/builtin-plugin/AndroidRestriction/android_restriction_demo.cc - - ${DobbyHome}/builtin-plugin/ApplicationEventMonitor/posix_file_descriptor_operation_monitor.cc - ${DobbyHome}/builtin-plugin/ApplicationEventMonitor/dynamic_loader_monitor.cc +add_library(native-lib SHARED + ${DOBBY_DIR}/example/android_common_api.cc - # Provides a relative path to your source file(s). native-lib.cpp) - -macro(SET_OPTION option value) - set(${option} ${value} CACHE INTERNAL "" FORCE) -endmacro() -SET_OPTION(DOBBY_DEBUG ON) -SET_OPTION(DOBBY_GENERATE_SHARED OFF) -add_subdirectory(${DobbyHome} dobby) ``` ## replace hook function diff --git a/module/src/main/cpp/Dobby/docs/get-started-ios.md b/module/src/main/cpp/Dobby/docs/get-started-ios.md index 6d98d930..f234b950 100644 --- a/module/src/main/cpp/Dobby/docs/get-started-ios.md +++ b/module/src/main/cpp/Dobby/docs/get-started-ios.md @@ -1,19 +1,13 @@ -# Getting Started With iOS +# Getting Started -available build option within iOS: - -## add Dobby.framework to your project +## add DobbyX.framework to your project ``` -cmake .. -G Xcode \ --DCMAKE_TOOLCHAIN_FILE=cmake/ios.toolchain.cmake \ --DPLATFORM=OS64 -DARCHS="arm64" -DCMAKE_SYSTEM_PROCESSOR=arm64 \ --DENABLE_BITCODE=0 -DENABLE_ARC=0 -DENABLE_VISIBILITY=1 -DDEPLOYMENT_TARGET=9.3 \ --DDOBBY_GENERATE_SHARED=OFF -DGenerateDarwinFramework=ON +cmake .. -G Xcode -DCMAKE_SYSTEM_NAME=iOS -DCMAKE_OSX_ARCHITECTURES=arm64 -DCMAKE_SYSTEM_PROCESSOR=arm64 -DCMAKE_OSX_DEPLOYMENT_TARGET=9.3 ``` -**drag the `Dobby.xcodeproj` to your project** +**drag the `DobbyX.xcodeproj` to your project** ## replace hook function diff --git a/module/src/main/cpp/Dobby/docs/get-started.md b/module/src/main/cpp/Dobby/docs/get-started.md index 3af08278..2cc63fde 100644 --- a/module/src/main/cpp/Dobby/docs/get-started.md +++ b/module/src/main/cpp/Dobby/docs/get-started.md @@ -21,18 +21,18 @@ DobbyHook((void *)fread, (void *)fake_fread, (void **)&origin_fread); ``` -uintptr_t getCallFirstArg(RegisterContext *reg_ctx) { +uintptr_t getCallFirstArg(RegisterContext *ctx) { uintptr_t result; #if defined(_M_X64) || defined(__x86_64__) #if defined(_WIN32) - result = reg_ctx->general.regs.rcx; + result = ctx->general.regs.rcx; #else - result = reg_ctx->general.regs.rdi; + result = ctx->general.regs.rdi; #endif #elif defined(__arm64__) || defined(__aarch64__) - result = reg_ctx->general.regs.x0; + result = ctx->general.regs.x0; #elif defined(__arm__) - result = reg_ctx->general.regs.r0; + result = ctx->general.regs.r0; #else #error "Not Support Architecture." #endif @@ -50,9 +50,9 @@ void format_integer_manually(char *buf, uint64_t integer) { // [ATTENTION]: // printf will call 'malloc' internally, and will crash in a loop. // so, use 'puts' is a better choice. -void malloc_handler(RegisterContext *reg_ctx, const HookEntryInfo *info) { +void malloc_handler(RegisterContext *ctx, const HookEntryInfo *info) { size_t size_ = 0; - size_ = getCallFirstArg(reg_ctx); + size_ = getCallFirstArg(ctx); char *buffer = "[-] function malloc first arg: 0x00000000.\n"; format_integer_manually(strchr(buffer, '.') - 1, size_); puts(buffer); diff --git a/module/src/main/cpp/Dobby/docs/intro-board.md b/module/src/main/cpp/Dobby/docs/intro-board.md index 0e5de67d..e99ddb12 100644 --- a/module/src/main/cpp/Dobby/docs/intro-board.md +++ b/module/src/main/cpp/Dobby/docs/intro-board.md @@ -2,7 +2,7 @@ a lightweight, multi-platform, multi-architecture exploit hook framework. -**tips: any question [go to Discord](https://discordapp.com/invite/dAEEywt)** +**tips: any question [go to Telegram](https://t.me/dobby_group)** - Minimal and modular library - Multi-platform support(Windows/macOS/iOS/Android/Linux) diff --git a/module/src/main/cpp/Dobby/example/CMakeLists.txt b/module/src/main/cpp/Dobby/example/CMakeLists.txt index a1ff657b..d5ac28c7 100644 --- a/module/src/main/cpp/Dobby/example/CMakeLists.txt +++ b/module/src/main/cpp/Dobby/example/CMakeLists.txt @@ -5,7 +5,7 @@ if(SYSTEM.Darwin) ) target_link_libraries(darwin_example - ${dobby_output_name} + DobbyX ) endif() diff --git a/module/src/main/cpp/Dobby/example/android_common_api.cc b/module/src/main/cpp/Dobby/example/android_common_api.cc index 189ad5c0..5213f6fe 100644 --- a/module/src/main/cpp/Dobby/example/android_common_api.cc +++ b/module/src/main/cpp/Dobby/example/android_common_api.cc @@ -13,7 +13,7 @@ std::map *func_map; -void common_handler(RegisterContext *reg_ctx, const HookEntryInfo *info) { +void common_handler(RegisterContext *ctx, const HookEntryInfo *info) { auto iter = func_map->find(info->function_address); if (iter != func_map->end()) { LOG(1, "func %s:%p invoke", iter->second, iter->first); @@ -93,12 +93,12 @@ __attribute__((constructor)) static void ctor() { DobbyInstrument((void *)((addr_t)art::gc::Heap::_11::PreZygoteFork + 1), common_handler); pthread_t socket_server; - uint64_t socket_demo_server(void *ctx); + uint64_t socket_demo_server(void *ctx); pthread_create(&socket_server, NULL, (void *(*)(void *))socket_demo_server, NULL); usleep(1000); pthread_t socket_client; - uint64_t socket_demo_client(void *ctx); + uint64_t socket_demo_client(void *ctx); pthread_create(&socket_client, NULL, (void *(*)(void *))socket_demo_client, NULL); } @@ -108,12 +108,12 @@ __attribute__((constructor)) static void ctor() { #define PORT 8080 uint64_t socket_demo_server(void *ctx) { - int server_fd, new_socket, valread; + int server_fd, new_socket, valread; struct sockaddr_in address; - int opt = 1; - int addrlen = sizeof(address); - char buffer[1024] = {0}; - char * hello = "Hello from server"; + int opt = 1; + int addrlen = sizeof(address); + char buffer[1024] = {0}; + char *hello = "Hello from server"; // Creating socket file descriptor if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) { @@ -126,9 +126,9 @@ uint64_t socket_demo_server(void *ctx) { perror("setsockopt"); exit(EXIT_FAILURE); } - address.sin_family = AF_INET; + address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; - address.sin_port = htons(PORT); + address.sin_port = htons(PORT); // Forcefully attaching socket to the port 8080 if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) { @@ -151,17 +151,17 @@ uint64_t socket_demo_server(void *ctx) { } uint64_t socket_demo_client(void *ctx) { - int sock = 0, valread; + int sock = 0, valread; struct sockaddr_in serv_addr; - char * hello = "Hello from client"; - char buffer[1024] = {0}; + char *hello = "Hello from client"; + char buffer[1024] = {0}; if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("\n Socket creation error \n"); return -1; } serv_addr.sin_family = AF_INET; - serv_addr.sin_port = htons(PORT); + serv_addr.sin_port = htons(PORT); // Convert IPv4 and IPv6 addresses from text to binary form if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) { diff --git a/module/src/main/cpp/Dobby/example/darwin_common_api.cc b/module/src/main/cpp/Dobby/example/darwin_common_api.cc index d476a822..eb5f52ae 100644 --- a/module/src/main/cpp/Dobby/example/darwin_common_api.cc +++ b/module/src/main/cpp/Dobby/example/darwin_common_api.cc @@ -13,7 +13,7 @@ std::map *func_map; -void common_handler(RegisterContext *reg_ctx, const HookEntryInfo *info) { +void common_handler(RegisterContext *ctx, const HookEntryInfo *info) { auto iter = func_map->find(info->function_address); if (iter != func_map->end()) { LOG(1, "func %s:%p invoke", iter->second, iter->first); @@ -44,7 +44,6 @@ const char *func_array[] = { typeof(pthread_create) *orig_pthread_create; int fake_pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg) { - LOG(1, "pthread_create: %p", start_routine); return orig_pthread_create(thread, attr, start_routine, arg); } @@ -52,7 +51,7 @@ int fake_pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*s #if 1 __attribute__((constructor)) static void ctor() { void *func = NULL; - log_set_level(0); + log_set_level(1); func_map = new std::map(); @@ -63,37 +62,42 @@ __attribute__((constructor)) static void ctor() { continue; } func_map->insert(std::pair(func, func_array[i])); - DobbyInstrument(func, common_handler); } - DobbyGlobalOffsetTableReplace(NULL, "_pthread_create", (void *)fake_pthread_create, - (void **)&orig_pthread_create); + for (auto i = func_map->begin(), e = func_map->end(); i != e; i++) { + DobbyInstrument(i->first, common_handler); + } + + DobbyGlobalOffsetTableReplace(NULL, "_pthread_create", (void *)fake_pthread_create, (void **)&orig_pthread_create); pthread_t socket_server; - uint64_t socket_demo_server(void *ctx); + uint64_t socket_demo_server(void *ctx); pthread_create(&socket_server, NULL, (void *(*)(void *))socket_demo_server, NULL); usleep(1000); pthread_t socket_client; - uint64_t socket_demo_client(void *ctx); + uint64_t socket_demo_client(void *ctx); pthread_create(&socket_client, NULL, (void *(*)(void *))socket_demo_client, NULL); + + pthread_join(socket_client, 0); + pthread_join(socket_server, 0); } #include #include #include -#define PORT 8080 +#define PORT 8989 uint64_t socket_demo_server(void *ctx) { - int server_fd, new_socket, valread; + int server_fd, new_socket, valread; struct sockaddr_in address; - int opt = 1; - int addrlen = sizeof(address); - char buffer[1024] = {0}; - char * hello = "Hello from server"; + int opt = 1; + int addrlen = sizeof(address); + char buffer[1024] = {0}; + char *hello = "Hello from server"; // Creating socket file descriptor - if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) { + if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket failed"); exit(EXIT_FAILURE); } @@ -103,10 +107,10 @@ uint64_t socket_demo_server(void *ctx) { perror("setsockopt"); exit(EXIT_FAILURE); } - - address.sin_family = AF_INET; + + address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; - address.sin_port = htons(PORT); + address.sin_port = htons(PORT); // Forcefully attaching socket to the port 8080 if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) { @@ -129,17 +133,17 @@ uint64_t socket_demo_server(void *ctx) { } uint64_t socket_demo_client(void *ctx) { - int sock = 0, valread; + int sock = 0, valread; struct sockaddr_in serv_addr; - char * hello = "Hello from client"; - char buffer[1024] = {0}; + char *hello = "Hello from client"; + char buffer[1024] = {0}; if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("\n Socket creation error \n"); return -1; } serv_addr.sin_family = AF_INET; - serv_addr.sin_port = htons(PORT); + serv_addr.sin_port = htons(PORT); // Convert IPv4 and IPv6 addresses from text to binary form if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) { diff --git a/module/src/main/cpp/Dobby/external/external_helper/CMakeLists.txt b/module/src/main/cpp/Dobby/external/external_helper/CMakeLists.txt deleted file mode 100644 index 6da1c09a..00000000 --- a/module/src/main/cpp/Dobby/external/external_helper/CMakeLists.txt +++ /dev/null @@ -1,16 +0,0 @@ -include_directories(.) - -set(SOURCE_FILE_LIST - variable_cache.c - async_logger.cc -) - -set(SOURCE_HEADER_LIST - async_logger.cc - variable_cache.h -) - -add_library(external_helper STATIC - ${SOURCE_FILE_LIST} - ${SOURCE_HEADER_LIST} -) \ No newline at end of file diff --git a/module/src/main/cpp/Dobby/external/logging/CMakeLists.txt b/module/src/main/cpp/Dobby/external/logging/CMakeLists.txt index 5d88e3cd..db01ceef 100644 --- a/module/src/main/cpp/Dobby/external/logging/CMakeLists.txt +++ b/module/src/main/cpp/Dobby/external/logging/CMakeLists.txt @@ -1,14 +1,8 @@ include_directories(.) set(SOURCE_FILE_LIST - ./cxxlogging.cc - ./logging.c -) - -set(SOURCE_HEADER_LIST - logging/logging.h - logging/check_logging.h - logging/cxxlogging.h + ${CMAKE_CURRENT_SOURCE_DIR}/cxxlogging.cc + ${CMAKE_CURRENT_SOURCE_DIR}/logging.c ) add_library(logging STATIC diff --git a/module/src/main/cpp/Dobby/external/logging/logging/check_logging.h b/module/src/main/cpp/Dobby/external/logging/logging/check_logging.h index dc607946..d13e947d 100644 --- a/module/src/main/cpp/Dobby/external/logging/logging/check_logging.h +++ b/module/src/main/cpp/Dobby/external/logging/logging/check_logging.h @@ -52,35 +52,35 @@ #endif -#define CHECK_EQ(lhs, rhs) CHECK_OP(EQ, ==, lhs, rhs) -#define CHECK_NE(lhs, rhs) CHECK_OP(NE, !=, lhs, rhs) -#define CHECK_LE(lhs, rhs) CHECK_OP(LE, <=, lhs, rhs) -#define CHECK_LT(lhs, rhs) CHECK_OP(LT, <, lhs, rhs) -#define CHECK_GE(lhs, rhs) CHECK_OP(GE, >=, lhs, rhs) -#define CHECK_GT(lhs, rhs) CHECK_OP(GT, >, lhs, rhs) -#define CHECK_NULL(val) CHECK((val) == NULL) +#define CHECK_EQ(lhs, rhs) CHECK_OP(EQ, ==, lhs, rhs) +#define CHECK_NE(lhs, rhs) CHECK_OP(NE, !=, lhs, rhs) +#define CHECK_LE(lhs, rhs) CHECK_OP(LE, <=, lhs, rhs) +#define CHECK_LT(lhs, rhs) CHECK_OP(LT, <, lhs, rhs) +#define CHECK_GE(lhs, rhs) CHECK_OP(GE, >=, lhs, rhs) +#define CHECK_GT(lhs, rhs) CHECK_OP(GT, >, lhs, rhs) +#define CHECK_NULL(val) CHECK((val) == NULL) #define CHECK_NOT_NULL(val) CHECK((val) != NULL) #ifdef LOGGING_DEBUG -#define DCHECK_EQ(lhs, rhs) DCHECK_OP(EQ, ==, lhs, rhs) -#define DCHECK_NE(lhs, rhs) DCHECK_OP(NE, !=, lhs, rhs) -#define DCHECK_GT(lhs, rhs) DCHECK_OP(GT, >, lhs, rhs) -#define DCHECK_GE(lhs, rhs) DCHECK_OP(GE, >=, lhs, rhs) -#define DCHECK_LT(lhs, rhs) DCHECK_OP(LT, <, lhs, rhs) -#define DCHECK_LE(lhs, rhs) DCHECK_OP(LE, <=, lhs, rhs) -#define DCHECK_NULL(val) DCHECK((val) == nullptr) -#define DCHECK_NOT_NULL(val) DCHECK((val) != nullptr) +#define DCHECK_EQ(lhs, rhs) DCHECK_OP(EQ, ==, lhs, rhs) +#define DCHECK_NE(lhs, rhs) DCHECK_OP(NE, !=, lhs, rhs) +#define DCHECK_GT(lhs, rhs) DCHECK_OP(GT, >, lhs, rhs) +#define DCHECK_GE(lhs, rhs) DCHECK_OP(GE, >=, lhs, rhs) +#define DCHECK_LT(lhs, rhs) DCHECK_OP(LT, <, lhs, rhs) +#define DCHECK_LE(lhs, rhs) DCHECK_OP(LE, <=, lhs, rhs) +#define DCHECK_NULL(val) DCHECK((val) == nullptr) +#define DCHECK_NOT_NULL(val) DCHECK((val) != nullptr) #define DCHECK_IMPLIES(lhs, rhs) DCHECK_WITH_MSG(!(lhs) || (rhs), #lhs " implies " #rhs) #else -#define DCHECK(condition) ((void)0) -#define DCHECK_EQ(v1, v2) ((void)0) -#define DCHECK_NE(v1, v2) ((void)0) -#define DCHECK_GT(v1, v2) ((void)0) -#define DCHECK_GE(v1, v2) ((void)0) -#define DCHECK_LT(v1, v2) ((void)0) -#define DCHECK_LE(v1, v2) ((void)0) -#define DCHECK_NULL(val) ((void)0) -#define DCHECK_NOT_NULL(val) ((void)0) +#define DCHECK(condition) ((void)0) +#define DCHECK_EQ(v1, v2) ((void)0) +#define DCHECK_NE(v1, v2) ((void)0) +#define DCHECK_GT(v1, v2) ((void)0) +#define DCHECK_GE(v1, v2) ((void)0) +#define DCHECK_LT(v1, v2) ((void)0) +#define DCHECK_LE(v1, v2) ((void)0) +#define DCHECK_NULL(val) ((void)0) +#define DCHECK_NOT_NULL(val) ((void)0) #define DCHECK_IMPLIES(v1, v2) ((void)0) #endif diff --git a/module/src/main/cpp/Dobby/external/logging/logging/cxxlogging.h b/module/src/main/cpp/Dobby/external/logging/logging/cxxlogging.h index ae0881ef..1ccea1f1 100644 --- a/module/src/main/cpp/Dobby/external/logging/logging/cxxlogging.h +++ b/module/src/main/cpp/Dobby/external/logging/logging/cxxlogging.h @@ -4,10 +4,10 @@ #include "logging.h" typedef enum { - LOG_LEVEL_FATAL = 0, - LOG_LEVEL_ERROR = 1, + LOG_LEVEL_FATAL = 0, + LOG_LEVEL_ERROR = 1, LOG_LEVEL_WARNING = 2, - LOG_LEVEL_DEBUG = 3, + LOG_LEVEL_DEBUG = 3, LOG_LEVEL_VERBOSE = 4 } LogLevel; diff --git a/module/src/main/cpp/Dobby/external/logging/logging/logging.h b/module/src/main/cpp/Dobby/external/logging/logging/logging.h index 10e62944..af7c6945 100644 --- a/module/src/main/cpp/Dobby/external/logging/logging/logging.h +++ b/module/src/main/cpp/Dobby/external/logging/logging/logging.h @@ -24,6 +24,10 @@ void log_switch_to_file(const char *path); #endif int log_internal_impl(unsigned int level, const char *, ...); +#if defined(LOGGING_DISABLE) +#define LOG_FUNCTION_IMPL(...) +#endif + #ifdef __cplusplus } #endif @@ -40,19 +44,16 @@ extern "C" { #define LOG(level, fmt, ...) \ do { \ if (LOG_TAG) \ - LOG_FUNCTION_IMPL(level, "[*] [%s] " fmt "\n", LOG_TAG, ##__VA_ARGS__); \ + LOG_FUNCTION_IMPL(level, "[*] [%s] " fmt "\n", LOG_TAG, ##__VA_ARGS__); \ else \ - LOG_FUNCTION_IMPL(level, "[*] " fmt "\n", ##__VA_ARGS__); \ + LOG_FUNCTION_IMPL(level, "[*] " fmt "\n", ##__VA_ARGS__); \ } while (0) #define RAW_LOG(level, fmt, ...) \ do { \ - LOG_FUNCTION_IMPL(level, fmt, ##__VA_ARGS__); \ + LOG_FUNCTION_IMPL(level, fmt, ##__VA_ARGS__); \ } while (0) -#if defined(LOGGING_DEBUG) -#define DLOG(level, fmt, ...) LOG(level, fmt, ##__VA_ARGS__) - #define FATAL(fmt, ...) \ do { \ RAW_LOG(-1, "[!] [%s:%d:%s]: \n", __FILE__, __LINE__, __func__); \ @@ -65,15 +66,24 @@ extern "C" { RAW_LOG(-1, "[!] [%s:%d:%s]: \n", __FILE__, __LINE__, __func__); \ RAW_LOG(-1, "[!] " fmt "\n", ##__VA_ARGS__); \ } while (0) -#else -#define DLOG(level, fmt, ...) -#define FATAL(fmt, ...) +#define ERROR_TRACE_LOG() \ + do { \ + RAW_LOG(-1, "[!] %s:%d:%s\n", __FILE__, __LINE__, __func__); \ + } while (0) + +#define INVOKE_TRACE_LOG() \ + do { \ + RAW_LOG(-1, "[%s] %s:%d:%s\n", __TIME__, __FILE_NAME__, __LINE__, __func__); \ + } while (0) -#define ERROR_LOG(fmt, ...) +#if defined(LOGGING_DEBUG) +#define DLOG(level, fmt, ...) LOG(level, fmt, ##__VA_ARGS__) +#else +#define DLOG(level, fmt, ...) #endif #define UNIMPLEMENTED() FATAL("%s\n", "unimplemented code!!!") -#define UNREACHABLE() FATAL("%s\n", "unreachable code!!!") +#define UNREACHABLE() FATAL("%s\n", "unreachable code!!!") #endif diff --git a/module/src/main/cpp/Dobby/external/misc-helper/CMakeLists.txt b/module/src/main/cpp/Dobby/external/misc-helper/CMakeLists.txt new file mode 100644 index 00000000..de66e962 --- /dev/null +++ b/module/src/main/cpp/Dobby/external/misc-helper/CMakeLists.txt @@ -0,0 +1,16 @@ +include_directories(.) + +set(SOURCE_FILE_LIST + # memory cache database + ${CMAKE_CURRENT_SOURCE_DIR}/variable_cache.c + + # async logger + ${CMAKE_CURRENT_SOURCE_DIR}/async_logger.cc + + ${CMAKE_CURRENT_SOURCE_DIR}/pthread_helper.cc +) + +add_library(misc_helper STATIC + ${SOURCE_FILE_LIST} + ${SOURCE_HEADER_LIST} +) \ No newline at end of file diff --git a/module/src/main/cpp/Dobby/external/external_helper/async_logger.cc b/module/src/main/cpp/Dobby/external/misc-helper/async_logger.cc similarity index 81% rename from module/src/main/cpp/Dobby/external/external_helper/async_logger.cc rename to module/src/main/cpp/Dobby/external/misc-helper/async_logger.cc index 3326fbfe..4aa9fda9 100644 --- a/module/src/main/cpp/Dobby/external/external_helper/async_logger.cc +++ b/module/src/main/cpp/Dobby/external/misc-helper/async_logger.cc @@ -1,19 +1,19 @@ #include -#include #include #include -#include +#include "pthread_helper.h" +#include "unistd_helper.h" #include #include #include #define aync_logger_buffer_size (20 * 1024 * 1024) -int async_logger_buffer_cursor = 0; +int async_logger_buffer_cursor = 0; char async_logger_buffer[aync_logger_buffer_size]; -static pthread_mutex_t async_logger_mutex = PTHREAD_MUTEX_INITIALIZER; +static pthread_mutex_t async_logger_mutex; static int output_fd = -1; @@ -54,12 +54,12 @@ void async_logger_init(char *logger_path) { output_fd = STDOUT_FILENO; if (logger_path) { - int fd = open(logger_path, O_CREAT | O_WRONLY | O_TRUNC, 0644); + int fd = open(logger_path, O_CREAT | O_WRONLY | O_TRUNC, 0644); output_fd = fd; } // init async logger pthread_mutex_init(&async_logger_mutex, NULL); pthread_t async_logger_thread; - int ret = pthread_create(&async_logger_thread, NULL, async_logger_print_impl, NULL); + int ret = pthread_create(&async_logger_thread, NULL, async_logger_print_impl, NULL); } diff --git a/module/src/main/cpp/Dobby/external/external_helper/async_logger.h b/module/src/main/cpp/Dobby/external/misc-helper/misc-helper/async_logger.h similarity index 100% rename from module/src/main/cpp/Dobby/external/external_helper/async_logger.h rename to module/src/main/cpp/Dobby/external/misc-helper/misc-helper/async_logger.h diff --git a/module/src/main/cpp/Dobby/external/external_helper/variable_cache.h b/module/src/main/cpp/Dobby/external/misc-helper/misc-helper/variable_cache.h similarity index 91% rename from module/src/main/cpp/Dobby/external/external_helper/variable_cache.h rename to module/src/main/cpp/Dobby/external/misc-helper/misc-helper/variable_cache.h index b51431fd..ca3a1fa8 100644 --- a/module/src/main/cpp/Dobby/external/external_helper/variable_cache.h +++ b/module/src/main/cpp/Dobby/external/misc-helper/misc-helper/variable_cache.h @@ -7,7 +7,7 @@ #define cache_set stash void cache_set(const char *name, uint64_t value); -#define cache_get(x) cache(x) +#define cache_get(x) cache(x) #define assert_cache(x) (assert(cache(x)), cache(x)) uint64_t cache_get(const char *name); diff --git a/module/src/main/cpp/Dobby/external/misc-helper/pthread_helper.cc b/module/src/main/cpp/Dobby/external/misc-helper/pthread_helper.cc new file mode 100644 index 00000000..a539fc1d --- /dev/null +++ b/module/src/main/cpp/Dobby/external/misc-helper/pthread_helper.cc @@ -0,0 +1,147 @@ +#include "pthread_helper.h" +#include +#ifdef _WIN32 + +typedef void (*windows_thread)(void *); + +int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void + *(*start_routine)(void *), void *arg) +{ + uintptr_t handle = _beginthread((windows_thread)start_routine,0,arg); + thread->handle = (HANDLE)handle; + if(thread->handle == (HANDLE)-1){ + return 1; + }else{ + return 0; + } +} + +int pthread_detach(pthread_t thread) +{ + /* Do nothing */ + return 0; +} + +void pthread_exit(void *value_ptr) +{ + _endthread(); +} + +int pthread_join(pthread_t thread, void **value_ptr) +{ + DWORD retvalue = WaitForSingleObject(thread.handle,INFINITE); + if(retvalue == WAIT_OBJECT_0){ + return 0; + }else{ + return EINVAL; + } +} + +pthread_t pthread_self(void) +{ + pthread_t pt; + pt.handle = GetCurrentThread(); + return pt; +} + +int pthread_cancel(pthread_t thread) +{ + fprintf(stderr,"DO NOT USE THIS FUNCTION. pthread_cancel\n"); + abort(); + return 0; +} + +/* --------------------- MUTEX --------------------*/ + +int pthread_mutexattr_destroy(pthread_mutexattr_t *attr) +{ + /* do nothing */ + return 0; +} + +int pthread_mutexattr_init(pthread_mutexattr_t *attr) +{ + /* do nothing */ + return 0; +} + +int pthread_mutex_destroy(pthread_mutex_t *mutex) +{ + return !CloseHandle(mutex->handle); +} + +int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr) +{ + HANDLE handle = CreateMutex(NULL,FALSE,NULL); + if(handle != NULL){ + mutex->handle = handle; + return 0; + }else{ + return 1; + } +} + +int pthread_mutex_lock(pthread_mutex_t *mutex) +{ + DWORD retvalue = WaitForSingleObject(mutex->handle,INFINITE); + if(retvalue == WAIT_OBJECT_0){ + return 0; + }else{ + return EINVAL; + } +} + +int pthread_mutex_trylock(pthread_mutex_t *mutex) +{ + DWORD retvalue = WaitForSingleObject(mutex->handle,0); + if(retvalue == WAIT_OBJECT_0){ + return 0; + }else if(retvalue == WAIT_TIMEOUT){ + return EBUSY; + }else{ + return EINVAL; + } +} + +int pthread_mutex_unlock(pthread_mutex_t *mutex) +{ + return !ReleaseMutex(mutex->handle); +} + +/* ------------------- Thead Specific Data ------------------ */ + +int pthread_key_create(pthread_key_t *key, void (*destr_function) (void *)) +{ + DWORD dkey = TlsAlloc(); + if(dkey != 0xFFFFFFFF){ + *key = dkey; + return 0; + }else{ + return EAGAIN; + } +} + +int pthread_key_delete(pthread_key_t key) +{ + if(TlsFree(key)){ + return 0; + }else{ + return EINVAL; + } +} + +int pthread_setspecific(pthread_key_t key, const void *pointer) +{ + if(TlsSetValue(key,(LPVOID)pointer)){ + return 0; + }else{ + return EINVAL; + } +} + +void * pthread_getspecific(pthread_key_t key) +{ + return TlsGetValue(key); +} + +#endif \ No newline at end of file diff --git a/module/src/main/cpp/Dobby/external/misc-helper/pthread_helper.h b/module/src/main/cpp/Dobby/external/misc-helper/pthread_helper.h new file mode 100644 index 00000000..2a19b697 --- /dev/null +++ b/module/src/main/cpp/Dobby/external/misc-helper/pthread_helper.h @@ -0,0 +1,86 @@ +/* + * light weight pthread compatible library for Windows + * (C) 2009 Okamura Yasunobu + * + * WARNING This library does NOT support all future of pthread + * + */ + +#ifndef CROSS_THREAD_H +#define CROSS_THREAD_H + +#ifdef _WIN32 + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include + +typedef struct pthread_tag { + HANDLE handle; +} pthread_t; + +typedef struct pthread_mutex_tag { + HANDLE handle; +} pthread_mutex_t; + +/* stub */ +typedef struct pthread_attr_tag { + int attr; +} pthread_attr_t; + +typedef struct pthread_mutexattr_tag { + int attr; +} pthread_mutexattr_t; + +typedef DWORD pthread_key_t; + +/* ignore attribute */ +int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void + *(*start_routine)(void *), void *arg); + +/* ignore value_ptr */ +void pthread_exit(void *value_ptr); + +/* ignore value_ptr */ +int pthread_join(pthread_t thread, void **value_ptr); + +pthread_t pthread_self(void); + +/* do nothing */ +int pthread_detach(pthread_t thread); + +/* DO NOT USE */ +int pthread_cancel(pthread_t thread); + +int pthread_mutexattr_destroy(pthread_mutexattr_t *attr); /* do nothing */ +int pthread_mutexattr_init(pthread_mutexattr_t *attr); /* do nothing */ + +int pthread_mutex_destroy(pthread_mutex_t *mutex); +int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr); +int pthread_mutex_lock(pthread_mutex_t *mutex); +int pthread_mutex_trylock(pthread_mutex_t *mutex); +int pthread_mutex_unlock(pthread_mutex_t *mutex); + +/* ignore deconstructor */ +int pthread_key_create(pthread_key_t *key, void (*destr_function) (void *)); +int pthread_key_delete(pthread_key_t key); +int pthread_setspecific(pthread_key_t key, const void *pointer); +void * pthread_getspecific(pthread_key_t key); + +#define sleep(num) Sleep(1000*(num)) + +#ifdef __cplusplus +} +#endif + +#else +#include +#include +#define Sleep(num) usleep(num*1000) +#endif + +#endif /* CROSS_THREAD_H */ diff --git a/module/src/main/cpp/Dobby/external/misc-helper/unistd_helper.h b/module/src/main/cpp/Dobby/external/misc-helper/unistd_helper.h new file mode 100644 index 00000000..eee45095 --- /dev/null +++ b/module/src/main/cpp/Dobby/external/misc-helper/unistd_helper.h @@ -0,0 +1,32 @@ +#ifdef _WIN32 + +#include +#define open _open +#define read _read +#define O_RDONLY _O_RDONLY +#define O_WRONLY _O_WRONLY +#define O_CREAT _O_CREAT +#define O_TRUNC _O_TRUNC + + + +#define ssize_t int + +#define STDIN_FILENO 0 +#define STDOUT_FILENO 1 +#define STDERR_FILENO 2 +/* should be in some equivalent to */ +typedef __int8 int8_t; +typedef __int16 int16_t; +typedef __int32 int32_t; +typedef __int64 int64_t; +typedef unsigned __int8 uint8_t; +typedef unsigned __int16 uint16_t; +typedef unsigned __int32 uint32_t; +typedef unsigned __int64 uint64_t; + +#else + +#include + +#endif \ No newline at end of file diff --git a/module/src/main/cpp/Dobby/external/external_helper/variable_cache.c b/module/src/main/cpp/Dobby/external/misc-helper/variable_cache.c similarity index 90% rename from module/src/main/cpp/Dobby/external/external_helper/variable_cache.c rename to module/src/main/cpp/Dobby/external/misc-helper/variable_cache.c index e701f0ae..2e88a736 100644 --- a/module/src/main/cpp/Dobby/external/external_helper/variable_cache.c +++ b/module/src/main/cpp/Dobby/external/misc-helper/variable_cache.c @@ -1,9 +1,11 @@ -#include "./variable_cache.h" +#include "misc-helper/variable_cache.h" #include #include #include -#include + +#include +#include "unistd_helper.h" #include @@ -45,7 +47,7 @@ void cache_set(const char *name, uint64_t value) { entry->value = value; entry->entry_.next = (struct queue_entry *)root; - root = entry; + root = entry; } uint64_t cache_get(const char *name) { @@ -56,15 +58,13 @@ uint64_t cache_get(const char *name) { return 0; } -#include - typedef struct entry_block { int key_length; int value_length; } entry_block_t; int serialized_to_file(const char *filepath) { - int fd = open(filepath, O_WRONLY | O_CREAT | O_TRUNC); + int fd = open(filepath, O_WRONLY | O_CREAT | O_TRUNC, 0660); if (fd == -1) { printf("open %s failed: %s\n", filepath, strerror(errno)); return -1; @@ -75,7 +75,7 @@ int serialized_to_file(const char *filepath) { while (entry != NULL) { entry_block_t block = {0}; { - block.key_length = strlen(entry->key) + 1; + block.key_length = strlen(entry->key) + 1; block.value_length = sizeof(uint64_t); write(fd, &block, sizeof(block)); } @@ -98,7 +98,7 @@ int unserialized_from_file(const char *filepath) { entry_block_t block = {0}; while (read(fd, &block, sizeof(block)) > 0) { - char key[128] = {0}; + char key[128] = {0}; uint64_t value = 0; read(fd, (void *)&key, block.key_length); @@ -110,7 +110,7 @@ int unserialized_from_file(const char *filepath) { entry->value = value; entry->entry_.next = (struct queue_entry *)root; - root = entry; + root = entry; } } diff --git a/module/src/main/cpp/Dobby/external/xnucxx/CMakeLists.txt b/module/src/main/cpp/Dobby/external/xnucxx/CMakeLists.txt index 00c58b1a..e6031df6 100644 --- a/module/src/main/cpp/Dobby/external/xnucxx/CMakeLists.txt +++ b/module/src/main/cpp/Dobby/external/xnucxx/CMakeLists.txt @@ -6,16 +6,14 @@ if(KERNELMODE) endif() set(xnucxx.SOURCE_FILE_LIST - LiteMemOpt.cc - LiteObject.cc - LiteIterator.cc - LiteCollection.cc - LiteMutableBuffer.cc - LiteMutableArray.cc + ${CMAKE_CURRENT_SOURCE_DIR}/LiteMemOpt.cc + ${CMAKE_CURRENT_SOURCE_DIR}/LiteObject.cc + ${CMAKE_CURRENT_SOURCE_DIR}/LiteIterator.cc + ${CMAKE_CURRENT_SOURCE_DIR}/LiteCollection.cc + ${CMAKE_CURRENT_SOURCE_DIR}/LiteMutableBuffer.cc + ${CMAKE_CURRENT_SOURCE_DIR}/LiteMutableArray.cc ) -if(BUILD_INDEPENDENT_LIBRARY) add_library(xnucxx STATIC ${xnucxx.SOURCE_FILE_LIST} -) -endif() \ No newline at end of file +) \ No newline at end of file diff --git a/module/src/main/cpp/Dobby/external/xnucxx/LiteIterator.cc b/module/src/main/cpp/Dobby/external/xnucxx/LiteIterator.cc index 360da7a8..2df5b41c 100644 --- a/module/src/main/cpp/Dobby/external/xnucxx/LiteIterator.cc +++ b/module/src/main/cpp/Dobby/external/xnucxx/LiteIterator.cc @@ -7,7 +7,7 @@ void LiteCollectionIterator::reset() { } bool LiteCollectionIterator::initWithCollection(const LiteCollectionInterface *inCollection) { - int *ndxPtr = (int *)LiteMemOpt::alloc(sizeof(int)); + int *ndxPtr = (int *)LiteMemOpt::alloc(sizeof(int)); innerIterator = (void *)ndxPtr; inCollection->initIterator(this->innerIterator); @@ -23,7 +23,7 @@ LiteObject *LiteCollectionIterator::getNextObject() { } void LiteCollectionIterator::release() { - if(innerIterator) { + if (innerIterator) { LiteMemOpt::free(innerIterator, sizeof(int)); innerIterator = NULL; diff --git a/module/src/main/cpp/Dobby/external/xnucxx/LiteMutableArray.cc b/module/src/main/cpp/Dobby/external/xnucxx/LiteMutableArray.cc index 847ceca0..6459a5fc 100644 --- a/module/src/main/cpp/Dobby/external/xnucxx/LiteMutableArray.cc +++ b/module/src/main/cpp/Dobby/external/xnucxx/LiteMutableArray.cc @@ -3,17 +3,17 @@ LiteMutableArray::LiteMutableArray(int initCapacity) { unsigned int arraySize = 0; - arraySize = initCapacity * sizeof(LiteObject *); - array = (const LiteObject **)LiteMemOpt::alloc(arraySize); - array_count = 0; - array_capacity = initCapacity; + arraySize = initCapacity * sizeof(LiteObject *); + array = (const LiteObject **)LiteMemOpt::alloc(arraySize); + array_count = 0; + array_capacity = initCapacity; } LiteMutableArray::~LiteMutableArray() { release(); } -LiteObject *LiteMutableArray::getObject(const int index) { +LiteObject *LiteMutableArray::getObject(const unsigned int index) { return (LiteObject *)array[index]; } @@ -43,9 +43,9 @@ unsigned int LiteMutableArray::ensureCapacity(unsigned int newCapacity) { newCapacity = (int)ALIGN(newCapacity + CAPACITY_STEP, CAPACITY_STEP); // alloc new buffer - int newSize; + int newSize; const LiteObject **newArray; - newSize = sizeof(LiteObject *) * newCapacity; + newSize = sizeof(LiteObject *) * newCapacity; newArray = (const LiteObject **)LiteMemOpt::alloc(newSize); if (newArray == nullptr) { return 0; @@ -63,7 +63,7 @@ unsigned int LiteMutableArray::ensureCapacity(unsigned int newCapacity) { LiteMemOpt::free(array, originArraySize); // update info - this->array = newArray; + this->array = newArray; this->array_capacity = newCapacity; return newCapacity; @@ -72,14 +72,14 @@ unsigned int LiteMutableArray::ensureCapacity(unsigned int newCapacity) { // impl iterator delegate bool LiteMutableArray::initIterator(void *iterator) const { unsigned int *ndxPtr = (unsigned int *)iterator; - *ndxPtr = 0; + *ndxPtr = 0; return true; } // impl iterator delegate bool LiteMutableArray::getNextObjectForIterator(void *iterator, LiteObject **ret) const { unsigned int *ndxPtr = (unsigned int *)iterator; - unsigned int ndx = (*ndxPtr)++; + unsigned int ndx = (*ndxPtr)++; if (ndx < array_count) { *ret = (LiteObject *)array[ndx]; @@ -93,7 +93,7 @@ bool LiteMutableArray::getNextObjectForIterator(void *iterator, LiteObject **ret void LiteMutableArray::release() { if (array != NULL) { unsigned int arraySize = 0; - arraySize = array_capacity * sizeof(LiteObject *); + arraySize = array_capacity * sizeof(LiteObject *); LiteMemOpt::free(array, arraySize); array = NULL; diff --git a/module/src/main/cpp/Dobby/external/xnucxx/LiteMutableBuffer.cc b/module/src/main/cpp/Dobby/external/xnucxx/LiteMutableBuffer.cc index 86a9f286..5d0246f6 100644 --- a/module/src/main/cpp/Dobby/external/xnucxx/LiteMutableBuffer.cc +++ b/module/src/main/cpp/Dobby/external/xnucxx/LiteMutableBuffer.cc @@ -6,7 +6,7 @@ bool LiteMutableBuffer::initWithCapacity(uint32_t initCapacity) { return false; this->buffer = (uint8_t *)LiteMemOpt::alloc(initCapacity); - this->buffer_cursor = buffer; + this->buffer_cursor = buffer; this->buffer_capacity = initCapacity; return true; } @@ -21,7 +21,7 @@ uint32_t LiteMutableBuffer::ensureCapacity(uint32_t newCapacity) { // alloc new buffer uint8_t *newBuffer; newBuffer = (uint8_t *)LiteMemOpt::alloc(newCapacity); - if(newBuffer == nullptr) { + if (newBuffer == nullptr) { return 0; } @@ -37,8 +37,8 @@ uint32_t LiteMutableBuffer::ensureCapacity(uint32_t newCapacity) { LiteMemOpt::free(buffer, originBufferSize); // update info - this->buffer = newBuffer; - this->buffer_cursor = newBuffer + originContentSize; + this->buffer = newBuffer; + this->buffer_cursor = newBuffer + originContentSize; this->buffer_capacity = newCapacity; return newCapacity; diff --git a/module/src/main/cpp/Dobby/external/xnucxx/xnucxx/LiteMutableArray.h b/module/src/main/cpp/Dobby/external/xnucxx/xnucxx/LiteMutableArray.h index 82ced375..e315b2c0 100644 --- a/module/src/main/cpp/Dobby/external/xnucxx/xnucxx/LiteMutableArray.h +++ b/module/src/main/cpp/Dobby/external/xnucxx/xnucxx/LiteMutableArray.h @@ -32,7 +32,7 @@ class LiteMutableArray : public LiteCollectionInterface { bool getNextObjectForIterator(void *iterator, LiteObject **ret) const override; - virtual LiteObject *getObject(int index); + virtual LiteObject *getObject(unsigned int index); virtual bool pushObject(const LiteObject *object); }; diff --git a/module/src/main/cpp/Dobby/external/xnucxx/xnucxx/LiteObject.h b/module/src/main/cpp/Dobby/external/xnucxx/xnucxx/LiteObject.h index c753c52e..a4c0f208 100644 --- a/module/src/main/cpp/Dobby/external/xnucxx/xnucxx/LiteObject.h +++ b/module/src/main/cpp/Dobby/external/xnucxx/xnucxx/LiteObject.h @@ -1,7 +1,7 @@ #ifndef LITE_OBJECT_H #define LITE_OBJECT_H -#include "common/headers/common_header.h" +#include "common_header.h" class LiteObject { public: diff --git a/module/src/main/cpp/Dobby/include/dobby.h b/module/src/main/cpp/Dobby/include/dobby.h index d15d713e..bc4c96b7 100644 --- a/module/src/main/cpp/Dobby/include/dobby.h +++ b/module/src/main/cpp/Dobby/include/dobby.h @@ -4,8 +4,8 @@ // obfuscated interface #if 0 #define DobbyBuildVersion c343f74888dffad84d9ad08d9c433456 -#define DobbyHook c8dc3ffa44f22dbd10ccae213dd8b1f8 -#define DobbyInstrument b71e27bca2c362de90c1034f19d839f9 +#define DobbyHook c8dc3ffa44f22dbd10ccae213dd8b1f8 +#define DobbyInstrument b71e27bca2c362de90c1034f19d839f9 #endif #ifdef __cplusplus @@ -15,6 +15,10 @@ extern "C" { #include #include +void log_set_level(int level); +void log_switch_to_syslog(); +void log_switch_to_file(const char *path); + typedef enum { kMemoryOperationSuccess, kMemoryOperationError, @@ -27,8 +31,8 @@ typedef enum { MemoryOperationError CodePatch(void *address, uint8_t *buffer, uint32_t buffer_size); typedef uintptr_t addr_t; -typedef uint32_t addr32_t; -typedef uint64_t addr64_t; +typedef uint32_t addr32_t; +typedef uint64_t addr64_t; #if defined(__arm64__) || defined(__aarch64__) @@ -125,7 +129,7 @@ typedef struct _RegisterContext { } RegisterContext; #endif -#define RT_FAILED -1 +#define RT_FAILED -1 #define RT_SUCCESS 0 typedef enum _RetStatus { RS_FAILED = -1, RS_SUCCESS = 0 } RetStatus; @@ -141,8 +145,8 @@ typedef struct _HookEntryInfo { // DobbyWrap <==> DobbyInstrument, so use DobbyInstrument instead of DobbyWrap #if 0 // wrap function with pre_call and post_call -typedef void (*PreCallTy)(RegisterContext *reg_ctx, const HookEntryInfo *info); -typedef void (*PostCallTy)(RegisterContext *reg_ctx, const HookEntryInfo *info); +typedef void (*PreCallTy)(RegisterContext *ctx, const HookEntryInfo *info); +typedef void (*PostCallTy)(RegisterContext *ctx, const HookEntryInfo *info); int DobbyWrap(void *function_address, PreCallTy pre_call, PostCallTy post_call); #endif @@ -150,13 +154,13 @@ int DobbyWrap(void *function_address, PreCallTy pre_call, PostCallTy post_call); const char *DobbyBuildVersion(); // replace function -int DobbyHook(void *function_address, void *replace_call, void **origin_call); +int DobbyHook(void *address, void *replace_call, void **origin_call); // dynamic binary instrument for instruction // [!!! READ ME !!!] // for Arm64, can't access q8 - q31, unless you enable full floating-point register pack -typedef void (*DBICallTy)(RegisterContext *reg_ctx, const HookEntryInfo *info); -int DobbyInstrument(void *instr_address, DBICallTy dbi_call); +typedef void (*DBICallTy)(RegisterContext *ctx, const HookEntryInfo *info); +int DobbyInstrument(void *address, DBICallTy dbi_call); // destory and restore hook int DobbyDestroy(void *address); diff --git a/module/src/main/cpp/Dobby/source/InstructionRelocation/InstructionRelocation.h b/module/src/main/cpp/Dobby/source/InstructionRelocation/InstructionRelocation.h new file mode 100644 index 00000000..69f5cb6e --- /dev/null +++ b/module/src/main/cpp/Dobby/source/InstructionRelocation/InstructionRelocation.h @@ -0,0 +1,3 @@ +#include "dobby_internal.h" + +void GenRelocateCodeAndBranch(void *buffer, AssemblyCodeChunk *origin, AssemblyCodeChunk *relocated); diff --git a/module/src/main/cpp/Dobby/source/InstructionRelocation/arm/ARMInstructionRelocation.cc b/module/src/main/cpp/Dobby/source/InstructionRelocation/arm/ARMInstructionRelocation.cc index ebbe5c6d..c0ceb833 100644 --- a/module/src/main/cpp/Dobby/source/InstructionRelocation/arm/ARMInstructionRelocation.cc +++ b/module/src/main/cpp/Dobby/source/InstructionRelocation/arm/ARMInstructionRelocation.cc @@ -1,4 +1,4 @@ -#include "common/macros/platform_macro.h" +#include "platform_macro.h" #if defined(TARGET_ARCH_ARM) #include "InstructionRelocation/arm/ARMInstructionRelocation.h" @@ -15,7 +15,7 @@ using namespace zz::arm; typedef struct ReloMapEntry { addr32_t orig_instr; addr32_t relocated_instr; - int relocated_code_len; + int relocated_code_len; } ReloMapEntry; static bool is_thumb2(uint32_t instr) { @@ -39,19 +39,19 @@ static void ARMRelocateSingleInstr(TurboAssembler *turbo_assembler, int32_t inst // top level encoding uint32_t cond, op0, op1; cond = bits(instr, 28, 31); - op0 = bits(instr, 25, 27); - op1 = bit(instr, 4); + op0 = bits(instr, 25, 27); + op1 = bit(instr, 4); // Load/Store Word, Unsigned byte (immediate, literal) if (cond != 0b1111 && op0 == 0b010) { uint32_t P, U, o2, W, o1, Rn, Rt, imm12; - P = bit(instr, 24); - U = bit(instr, 23); - W = bit(instr, 21); - imm12 = bits(instr, 0, 11); - Rn = bits(instr, 16, 19); - Rt = bits(instr, 12, 15); - o1 = bit(instr, 20); - o2 = bit(instr, 22); + P = bit(instr, 24); + U = bit(instr, 23); + W = bit(instr, 21); + imm12 = bits(instr, 0, 11); + Rn = bits(instr, 16, 19); + Rt = bits(instr, 12, 15); + o1 = bit(instr, 20); + o2 = bit(instr, 22); uint32_t P_W = (P << 1) | W; do { // LDR (literal) @@ -71,7 +71,7 @@ static void ARMRelocateSingleInstr(TurboAssembler *turbo_assembler, int32_t inst Register regRt = Register::R(Rt); RelocLabelEntry *pseudoDataLabel = new RelocLabelEntry(target_address); - _ AppendRelocLabelEntry(pseudoDataLabel); + _ AppendRelocLabelEntry(pseudoDataLabel); // === if (regRt.code() == pc.code()) { @@ -99,13 +99,13 @@ static void ARMRelocateSingleInstr(TurboAssembler *turbo_assembler, int32_t inst if ((op0 & 0b10) == 0b00) { uint32_t opc, S, Rn; opc = bits(instr, 21, 23); - S = bit(instr, 20); - Rn = bits(instr, 16, 19); + S = bit(instr, 20); + Rn = bits(instr, 16, 19); do { uint32_t target_address; - int Rd = bits(instr, 12, 15); - int imm12 = bits(instr, 0, 11); - int label = imm12; + int Rd = bits(instr, 12, 15); + int imm12 = bits(instr, 0, 11); + int label = imm12; if (opc == 0b010 && S == 0b0 && Rn == 0b1111) { // ADR - A2 variant // add = FALSE @@ -117,9 +117,9 @@ static void ARMRelocateSingleInstr(TurboAssembler *turbo_assembler, int32_t inst } else break; - Register regRd = Register::R(Rd); + Register regRd = Register::R(Rd); RelocLabelEntry *pseudoDataLabel = new RelocLabelEntry(target_address); - _ AppendRelocLabelEntry(pseudoDataLabel); + _ AppendRelocLabelEntry(pseudoDataLabel); // === _ Ldr(regRd, pseudoDataLabel); // === @@ -138,14 +138,14 @@ static void ARMRelocateSingleInstr(TurboAssembler *turbo_assembler, int32_t inst if ((op0 & 0b110) == 0b100) { uint32_t cond, op0; cond = bits(instr, 28, 31); - op0 = bit(instr, 25); + op0 = bit(instr, 25); // Branch (immediate) if (op0 == 1) { uint32_t cond = 0, H = 0, imm24 = 0; - bool flag_link; + bool flag_link; do { - int imm24 = bits(instr, 0, 23); - int label = imm24 << 2; + int imm24 = bits(instr, 0, 23); + int label = imm24 << 2; uint32_t target_address = from_pc + label; if (cond != 0b1111 && H == 0) { // B @@ -193,7 +193,7 @@ static void Thumb1RelocateSingleInstr(ThumbTurboAssembler *turbo_assembler, Lite _ AlignThumbNop(); uint32_t val = 0, op = 0, rt = 0, rm = 0, rn = 0, rd = 0, shift = 0, cond = 0; - int32_t offset = 0; + int32_t offset = 0; int32_t op0 = 0, op1 = 0; op0 = bits(instr, 10, 15); @@ -208,10 +208,10 @@ static void Thumb1RelocateSingleInstr(ThumbTurboAssembler *turbo_assembler, Lite val = from_pc; uint16_t rewrite_inst = 0; - rewrite_inst = (instr & 0xff87) | LeftShift((VOLATILE_REGISTER.code()), 4, 3); + rewrite_inst = (instr & 0xff87) | LeftShift((VOLATILE_REGISTER.code()), 4, 3); ThumbRelocLabelEntry *label = new ThumbRelocLabelEntry(val, false); - _ AppendRelocLabelEntry(label); + _ AppendRelocLabelEntry(label); _ T2_Ldr(VOLATILE_REGISTER, label); _ EmitInt16(rewrite_inst); @@ -227,32 +227,32 @@ static void Thumb1RelocateSingleInstr(ThumbTurboAssembler *turbo_assembler, Lite if (L == 0b0) { rm = bits(instr, 3, 6); if (rm == pc.code()) { - val = from_pc; + val = from_pc; ThumbRelocLabelEntry *label = new ThumbRelocLabelEntry(val, true); - _ AppendRelocLabelEntry(label); + _ AppendRelocLabelEntry(label); _ T2_Ldr(pc, label); *execute_state_changed_pc_ptr = val; - is_instr_relocated = true; + is_instr_relocated = true; } } // BLX if (L == 0b1) { if (rm == pc.code()) { - val = from_pc; + val = from_pc; ThumbRelocLabelEntry *label = new ThumbRelocLabelEntry(val, true); - _ AppendRelocLabelEntry(label); + _ AppendRelocLabelEntry(label); int label_branch_off = 4, label_continue_off = 4; - _ t2_bl(label_branch_off); - _ t2_b(label_continue_off); + _ t2_bl(label_branch_off); + _ t2_b(label_continue_off); /* Label: branch */ _ T2_Ldr(pc, label); /* Label: continue */ *execute_state_changed_pc_ptr = val; - is_instr_relocated = true; + is_instr_relocated = true; } } } @@ -260,14 +260,14 @@ static void Thumb1RelocateSingleInstr(ThumbTurboAssembler *turbo_assembler, Lite // ldr literal if ((instr & 0xf800) == 0x4800) { - int32_t imm8 = bits(instr, 0, 7); + int32_t imm8 = bits(instr, 0, 7); int32_t offset = imm8 << 2; - val = from_pc + offset; - val = ALIGN_FLOOR(val, 4); - rt = bits(instr, 8, 10); + val = from_pc + offset; + val = ALIGN_FLOOR(val, 4); + rt = bits(instr, 8, 10); ThumbRelocLabelEntry *label = new ThumbRelocLabelEntry(val, false); - _ AppendRelocLabelEntry(label); + _ AppendRelocLabelEntry(label); _ T2_Ldr(Register::R(rt), label); _ t2_ldr(Register::R(rt), MemOperand(Register::R(rt), 0)); @@ -277,12 +277,12 @@ static void Thumb1RelocateSingleInstr(ThumbTurboAssembler *turbo_assembler, Lite // adr if ((instr & 0xf800) == 0xa000) { - rd = bits(instr, 8, 10); + rd = bits(instr, 8, 10); uint16_t imm8 = bits(instr, 0, 7); - val = from_pc + imm8; + val = from_pc + imm8; ThumbRelocLabelEntry *label = new ThumbRelocLabelEntry(val, false); - _ AppendRelocLabelEntry(label); + _ AppendRelocLabelEntry(label); _ T2_Ldr(Register::R(rd), label); @@ -298,12 +298,12 @@ static void Thumb1RelocateSingleInstr(ThumbTurboAssembler *turbo_assembler, Lite if (cond >= 0b1110) { UNREACHABLE(); } - uint16_t imm8 = bits(instr, 0, 7); + uint16_t imm8 = bits(instr, 0, 7); uint32_t offset = imm8 << 1; - val = from_pc + offset; + val = from_pc + offset; ThumbRelocLabelEntry *label = new ThumbRelocLabelEntry(val + 1, true); - _ AppendRelocLabelEntry(label); + _ AppendRelocLabelEntry(label); // modify imm8 field imm8 = 0x4 >> 1; @@ -318,17 +318,17 @@ static void Thumb1RelocateSingleInstr(ThumbTurboAssembler *turbo_assembler, Lite // compare branch (cbz, cbnz) if ((instr & 0xf500) == 0xb100) { - uint16_t imm5 = bits(instr, 3, 7); - uint16_t i = bit(instr, 9); + uint16_t imm5 = bits(instr, 3, 7); + uint16_t i = bit(instr, 9); uint32_t offset = (i << 6) | (imm5 << 1); - val = from_pc + offset; - rn = bits(instr, 0, 2); + val = from_pc + offset; + rn = bits(instr, 0, 2); ThumbRelocLabelEntry *label = new ThumbRelocLabelEntry(val + 1, true); - _ AppendRelocLabelEntry(label); + _ AppendRelocLabelEntry(label); imm5 = bits(0x4 >> 1, 1, 5); - i = bit(0x4 >> 1, 6); + i = bit(0x4 >> 1, 6); _ EmitInt16((instr & 0xfd07) | imm5 << 3 | i << 9); _ t1_nop(); // manual align @@ -340,12 +340,12 @@ static void Thumb1RelocateSingleInstr(ThumbTurboAssembler *turbo_assembler, Lite // unconditional branch if ((instr & 0xf800) == 0xe000) { - uint16_t imm11 = bits(instr, 0, 10); + uint16_t imm11 = bits(instr, 0, 10); uint32_t offset = imm11 << 1; - val = from_pc + offset; + val = from_pc + offset; ThumbRelocLabelEntry *label = new ThumbRelocLabelEntry(val + 1, true); - _ AppendRelocLabelEntry(label); + _ AppendRelocLabelEntry(label); _ T2_Ldr(pc, label); @@ -382,14 +382,14 @@ static void Thumb2RelocateSingleInstr(ThumbTurboAssembler *turbo_assembler, Lite // B-T3 AKA b.cond if (((op1 & 0b1110) != 0b1110) && ((op3 & 0b101) == 0b000)) { - int S = sbits(inst1, 10, 10); - int J1 = bit(inst2, 13); - int J2 = bit(inst2, 11); - int imm6 = bits(inst1, 0, 5); + int S = sbits(inst1, 10, 10); + int J1 = bit(inst2, 13); + int J2 = bit(inst2, 11); + int imm6 = bits(inst1, 0, 5); int imm11 = bits(inst2, 0, 10); - int32_t label = (S << 20) | (J2 << 19) | (J1 << 18) | (imm6 << 12) | (imm11 << 1); - addr32_t val = from_pc + label; + int32_t label = (S << 20) | (J2 << 19) | (J1 << 18) | (imm6 << 12) | (imm11 << 1); + addr32_t val = from_pc + label; // === imm11 = 0x4 >> 1; @@ -405,16 +405,16 @@ static void Thumb2RelocateSingleInstr(ThumbTurboAssembler *turbo_assembler, Lite // B-T4 AKA b.w if ((op3 & 0b101) == 0b001) { - int S = bit(inst1, 10); - int J1 = bit(inst2, 13); - int J2 = bit(inst2, 11); + int S = bit(inst1, 10); + int J1 = bit(inst2, 13); + int J2 = bit(inst2, 11); int imm10 = bits(inst1, 0, 9); int imm11 = bits(inst2, 0, 10); - int i1 = !(J1 ^ S); - int i2 = !(J2 ^ S); + int i1 = !(J1 ^ S); + int i2 = !(J2 ^ S); - int32_t label = (-S << 24) | (i1 << 23) | (i2 << 22) | (imm10 << 12) | (imm11 << 1); - addr32_t val = from_pc + label; + int32_t label = (-S << 24) | (i1 << 23) | (i2 << 22) | (imm10 << 12) | (imm11 << 1); + addr32_t val = from_pc + label; _ t2_ldr(pc, MemOperand(pc, 0)); _ EmitAddress(val + THUMB_ADDRESS_FLAG); @@ -424,16 +424,16 @@ static void Thumb2RelocateSingleInstr(ThumbTurboAssembler *turbo_assembler, Lite // BL, BLX (immediate) - T1 variant AKA bl if ((op3 & 0b101) == 0b101) { - int S = bit(inst1, 10); - int J1 = bit(inst2, 13); - int J2 = bit(inst2, 11); - int i1 = !(J1 ^ S); - int i2 = !(J2 ^ S); + int S = bit(inst1, 10); + int J1 = bit(inst2, 13); + int J2 = bit(inst2, 11); + int i1 = !(J1 ^ S); + int i2 = !(J2 ^ S); int imm11 = bits(inst2, 0, 10); int imm10 = bits(inst1, 0, 9); // S is sign-bit, '-S' maybe not better - int32_t label = (imm11 << 1) | (imm10 << 12) | (i2 << 22) | (i1 << 23) | (-S << 24); - addr32_t val = from_pc + label; + int32_t label = (imm11 << 1) | (imm10 << 12) | (i2 << 22) | (i1 << 23) | (-S << 24); + addr32_t val = from_pc + label; _ t2_bl(4); _ t2_b(8); @@ -445,16 +445,16 @@ static void Thumb2RelocateSingleInstr(ThumbTurboAssembler *turbo_assembler, Lite // BL, BLX (immediate) - T2 variant AKA blx if ((op3 & 0b101) == 0b100) { - int S = bit(inst1, 10); - int J1 = bit(inst2, 13); - int J2 = bit(inst2, 11); - int i1 = !(J1 ^ S); - int i2 = !(J2 ^ S); + int S = bit(inst1, 10); + int J1 = bit(inst2, 13); + int J2 = bit(inst2, 11); + int i1 = !(J1 ^ S); + int i2 = !(J2 ^ S); int imm10h = bits(inst1, 0, 9); int imm10l = bits(inst2, 1, 10); // S is sign-bit, '-S' maybe not better - int32_t label = (imm10l << 2) | (imm10h << 12) | (i2 << 22) | (i1 << 23) | (-S << 24); - addr32_t val = ALIGN(from_pc, 4) + label; + int32_t label = (imm10l << 2) | (imm10h << 12) | (i2 << 22) | (i1 << 23) | (-S << 24); + addr32_t val = ALIGN(from_pc, 4) + label; _ t2_bl(4); _ t2_b(8); @@ -479,12 +479,12 @@ static void Thumb2RelocateSingleInstr(ThumbTurboAssembler *turbo_assembler, Lite // ADR if (((o1 == 0 && o2 == 0) || (o1 == 1 && o2 == 1)) && rn == 0b1111) { - uint32_t i = bit(inst1, 10); - uint32_t imm3 = bits(inst2, 12, 14); - uint32_t imm8 = bits(inst2, 0, 7); - uint32_t rd = bits(inst2, 8, 11); + uint32_t i = bit(inst1, 10); + uint32_t imm3 = bits(inst2, 12, 14); + uint32_t imm8 = bits(inst2, 0, 7); + uint32_t rd = bits(inst2, 8, 11); uint32_t label = imm8 | (imm3 << 8) | (i << 11); - addr32_t val = 0; + addr32_t val = 0; if (o1 == 0 && o2 == 0) { // ADR - T3 // ADR - T3 variant @@ -510,12 +510,12 @@ static void Thumb2RelocateSingleInstr(ThumbTurboAssembler *turbo_assembler, Lite // LDR literal (T2) if ((inst1 & 0xff7f) == 0xf85f) { - uint32_t U = bit(inst1, 7); + uint32_t U = bit(inst1, 7); uint32_t imm12 = bits(inst2, 0, 11); - uint16_t rt = bits(inst2, 12, 15); + uint16_t rt = bits(inst2, 12, 15); uint32_t label = imm12; - addr32_t val = 0; + addr32_t val = 0; if (U == 1) { val = from_pc + label; } else { @@ -553,8 +553,8 @@ void gen_arm_relocate_code(LiteMutableArray *relo_map, TurboAssembler *turbo_ass addr32_t curr_orig_pc = origin->raw_instruction_start() + ARM_PC_OFFSET; addr32_t curr_relo_pc = relocated->raw_instruction_start() + ARM_PC_OFFSET + turbo_assembler_->pc_offset(); - addr_t buffer_cursor = (addr_t)buffer; - arm_inst_t instr = *(arm_inst_t *)buffer_cursor; + addr_t buffer_cursor = (addr_t)buffer; + arm_inst_t instr = *(arm_inst_t *)buffer_cursor; int predefined_relocate_size = origin->raw_instruction_size(); @@ -569,10 +569,10 @@ void gen_arm_relocate_code(LiteMutableArray *relo_map, TurboAssembler *turbo_ass { // 1 orignal instrution => ? relocated instruction int relo_offset = turbo_assembler_->GetCodeBuffer()->getSize(); - int relo_len = relo_offset - last_relo_offset; + int relo_len = relo_offset - last_relo_offset; - ReloMapEntry *map = new ReloMapEntry{.orig_instr = curr_orig_pc - ARM_PC_OFFSET, - .relocated_instr = curr_relo_pc - ARM_PC_OFFSET, + ReloMapEntry *map = new ReloMapEntry{.orig_instr = curr_orig_pc - ARM_PC_OFFSET, + .relocated_instr = curr_relo_pc - ARM_PC_OFFSET, .relocated_code_len = relo_len}; relo_map->pushObject(reinterpret_cast(map)); } @@ -611,8 +611,8 @@ void gen_thumb_relocate_code(LiteMutableArray *relo_map, ThumbTurboAssembler *tu addr32_t curr_orig_pc = origin->raw_instruction_start() + Thumb_PC_OFFSET; addr32_t curr_relo_pc = relocated->raw_instruction_start() + Thumb_PC_OFFSET; - addr_t buffer_cursor = (addr_t)buffer; - thumb2_inst_t instr = *(thumb2_inst_t *)buffer_cursor; + addr_t buffer_cursor = (addr_t)buffer; + thumb2_inst_t instr = *(thumb2_inst_t *)buffer_cursor; int predefined_relocate_size = origin->raw_instruction_size(); DLOG(0, "[arm] Thumb relocate %d start >>>>>", predefined_relocate_size); @@ -639,10 +639,10 @@ void gen_thumb_relocate_code(LiteMutableArray *relo_map, ThumbTurboAssembler *tu { // 1 orignal instrution => ? relocated instruction int relo_offset = turbo_assembler_->GetCodeBuffer()->getSize(); - int relo_len = relo_offset - last_relo_offset; + int relo_len = relo_offset - last_relo_offset; - ReloMapEntry *map = new ReloMapEntry{.orig_instr = curr_orig_pc - Thumb_PC_OFFSET, - .relocated_instr = curr_relo_pc - Thumb_PC_OFFSET, + ReloMapEntry *map = new ReloMapEntry{.orig_instr = curr_orig_pc - Thumb_PC_OFFSET, + .relocated_instr = curr_relo_pc - Thumb_PC_OFFSET, .relocated_code_len = relo_len}; relo_map->pushObject(reinterpret_cast(map)); } @@ -697,10 +697,10 @@ static addr32_t get_orig_instr_relocated_addr(LiteMutableArray *relo_map, addr32 static void reloc_label_fixup(AssemblyCodeChunk *origin, LiteMutableArray *relo_map, ThumbTurboAssembler *thumb_turbo_assembler, TurboAssembler *arm_turbo_assembler) { addr32_t origin_instr_start = origin->raw_instruction_start(); - addr32_t origin_instr_end = origin_instr_start + origin->raw_instruction_size(); + addr32_t origin_instr_end = origin_instr_start + origin->raw_instruction_size(); LiteMutableArray *labels = NULL; - labels = thumb_turbo_assembler->GetLabels(); + labels = thumb_turbo_assembler->GetLabels(); if (labels) { for (size_t i = 0; i < labels->getCount(); i++) { ThumbRelocLabelEntry *label = (ThumbRelocLabelEntry *)labels->getObject(i); @@ -722,7 +722,7 @@ static void reloc_label_fixup(AssemblyCodeChunk *origin, LiteMutableArray *relo_ if (labels) { for (size_t i = 0; i < labels->getCount(); i++) { RelocLabelEntry *label = (RelocLabelEntry *)labels->getObject(i); - addr32_t val = label->data(); + addr32_t val = label->data(); if (val >= origin_instr_start && val < origin_instr_end) { DLOG(0, "[reloc label fixup warning]found thumb instr branch / access in origin code range"); @@ -846,7 +846,7 @@ void GenRelocateCodeAndBranch(void *buffer, AssemblyCodeChunk *origin, AssemblyC reloc_label_fixup(origin, &relo_map, &thumb_turbo_assembler_, &arm_turbo_assembler_); AssemblyCodeChunk *code = NULL; - code = AssemblyCodeBuilder::FinalizeFromTurboAssembler(curr_assembler_); + code = AssemblyCodeBuilder::FinalizeFromTurboAssembler(curr_assembler_); relocated->re_init_region_range(code->raw_instruction_start(), code->raw_instruction_size()); delete code; } diff --git a/module/src/main/cpp/Dobby/source/InstructionRelocation/arm/ARMInstructionRelocation.h b/module/src/main/cpp/Dobby/source/InstructionRelocation/arm/ARMInstructionRelocation.h index cc2a3c8b..1573adf1 100644 --- a/module/src/main/cpp/Dobby/source/InstructionRelocation/arm/ARMInstructionRelocation.h +++ b/module/src/main/cpp/Dobby/source/InstructionRelocation/arm/ARMInstructionRelocation.h @@ -34,11 +34,11 @@ class ThumbPseudoLabel : public PseudoLabel { UNREACHABLE(); } break; case kThumb2LiteralLdr: { - int32_t offset = pos() - ALIGN(instruction->position_, 4) - Thumb_PC_OFFSET; - uint32_t imm12 = offset; + int32_t offset = pos() - ALIGN(instruction->position_, 4) - Thumb_PC_OFFSET; + uint32_t imm12 = offset; CHECK(imm12 < (1 << 12)); uint16_t encoding = inst2 & 0xf000; - encoding = encoding | imm12; + encoding = encoding | imm12; _buffer->RewriteThumb1Inst(instruction->position_, inst1 | B7); // add = (U == '1'); _buffer->RewriteThumb1Inst(instruction->position_ + Thumb1_INST_LEN, encoding); @@ -163,9 +163,9 @@ class ThumbAssembler : public Assembler { private: void EmitThumb2LoadLiteral(Register rt, const MemOperand x) { - bool add = true; + bool add = true; uint32_t U, imm12; - int32_t offset = x.offset(); + int32_t offset = x.offset(); #if 0 // literal ldr, base = ALIGN(pc, 4) @@ -179,10 +179,10 @@ class ThumbAssembler : public Assembler { #endif if (offset > 0) { - U = B7; + U = B7; imm12 = offset; } else { - U = 0; + U = 0; imm12 = -offset; } EmitInt16(0xf85f | U); @@ -204,14 +204,14 @@ class ThumbAssembler : public Assembler { // use bit accelerate uint32_t P = 0, W = 0, U = 0; uint32_t imm8 = x.offset() > 0 ? x.offset() : -x.offset(); - U = x.offset() > 0 ? 0 : B9; + U = x.offset() > 0 ? 0 : B9; if (x.IsPostIndex()) { P = 0, W = B8; } else if (x.IsPreIndex()) { P = B10, W = B8; } index = (P == B10); - add = (U == B9); + add = (U == B9); wback = (W == B8); EmitInt16(0xf850 | (x.rn().code() << 0)); EmitInt16(0x0800 | (rt.code() << 12) | P | U | W | imm8); @@ -225,12 +225,12 @@ class ThumbAssembler : public Assembler { ASSERT(CheckAlign(operand, 2)); uint32_t signbit = (imm >> 31) & 0x1; - uint32_t i1 = (operand >> 22) & 0x1; - uint32_t i2 = (operand >> 21) & 0x1; - uint32_t imm10 = (operand >> 11) & 0x03ff; - uint32_t imm11 = operand & 0x07ff; - uint32_t j1 = (!(i1 ^ signbit)); - uint32_t j2 = (!(i2 ^ signbit)); + uint32_t i1 = (operand >> 22) & 0x1; + uint32_t i2 = (operand >> 21) & 0x1; + uint32_t imm10 = (operand >> 11) & 0x03ff; + uint32_t imm11 = operand & 0x07ff; + uint32_t j1 = (!(i1 ^ signbit)); + uint32_t j2 = (!(i2 ^ signbit)); if (cond != AL) { UNIMPLEMENTED(); @@ -350,8 +350,9 @@ class ThumbTurboAssembler : public ThumbAssembler { LiteMutableArray *data_labels_; }; -// Generate the relocated instruction +#if 0 void GenRelocateCodeAndBranch(void *buffer, AssemblyCodeChunk *origin, AssemblyCodeChunk *relocated); +#endif } // namespace arm } // namespace zz diff --git a/module/src/main/cpp/Dobby/source/InstructionRelocation/arm64/ARM64InstructionRelocation.cc b/module/src/main/cpp/Dobby/source/InstructionRelocation/arm64/ARM64InstructionRelocation.cc index 17df7974..f116b7bf 100644 --- a/module/src/main/cpp/Dobby/source/InstructionRelocation/arm64/ARM64InstructionRelocation.cc +++ b/module/src/main/cpp/Dobby/source/InstructionRelocation/arm64/ARM64InstructionRelocation.cc @@ -1,4 +1,4 @@ -#include "common/macros/platform_macro.h" +#include "platform_macro.h" #if defined(TARGET_ARCH_ARM64) #include "InstructionRelocation/arm64/ARM64InstructionRelocation.h" @@ -13,25 +13,25 @@ using namespace zz::arm64; // Compare and branch. enum CompareBranchOp { - CompareBranchFixed = 0x34000000, + CompareBranchFixed = 0x34000000, CompareBranchFixedMask = 0x7E000000, - CompareBranchMask = 0xFF000000, + CompareBranchMask = 0xFF000000, }; // Conditional branch. enum ConditionalBranchOp { - ConditionalBranchFixed = 0x54000000, + ConditionalBranchFixed = 0x54000000, ConditionalBranchFixedMask = 0xFE000000, - ConditionalBranchMask = 0xFF000010, + ConditionalBranchMask = 0xFF000010, }; // Test and branch. enum TestBranchOp { - TestBranchFixed = 0x36000000, + TestBranchFixed = 0x36000000, TestBranchFixedMask = 0x7E000000, - TestBranchMask = 0x7F000000, - TBZ = TestBranchFixed | 0x00000000, - TBNZ = TestBranchFixed | 0x01000000 + TestBranchMask = 0x7F000000, + TBZ = TestBranchFixed | 0x00000000, + TBNZ = TestBranchFixed | 0x01000000 }; static inline int64_t SignExtend(unsigned long x, int M, int N) { @@ -58,7 +58,7 @@ static inline int64_t decode_imm14_offset(uint32_t instr) { int64_t offset; { int64_t imm19 = bits(instr, 5, 18); - offset = (imm19 << 2); + offset = (imm19 << 2); } offset = SignExtend(offset, 2 + 14, 64); return offset; @@ -68,7 +68,7 @@ static inline int64_t decode_imm19_offset(uint32_t instr) { int64_t offset; { int64_t imm19 = bits(instr, 5, 23); - offset = (imm19 << 2); + offset = (imm19 << 2); } offset = SignExtend(offset, 2 + 19, 64); return offset; @@ -78,7 +78,7 @@ static inline int64_t decode_imm26_offset(uint32_t instr) { int64_t offset; { int64_t imm26 = bits(instr, 0, 25); - offset = (imm26 << 2); + offset = (imm26 << 2); } offset = SignExtend(offset, 2 + 26, 64); return offset; @@ -97,13 +97,13 @@ static inline int64_t decode_immhi_immlo_offset(uint32_t instr) { *(instr_t *)&instr_decode = instr; int64_t imm = instr_decode.immlo + (instr_decode.immhi << 2); - imm = SignExtend(imm, 2 + 19, 64); + imm = SignExtend(imm, 2 + 19, 64); return imm; } static inline int64_t decode_immhi_immlo_zero12_offset(uint32_t instr) { int64_t imm = decode_immhi_immlo_offset(instr); - imm = imm << 12; + imm = imm << 12; return imm; } @@ -128,8 +128,8 @@ void GenRelocateCodeAndBranch(void *buffer, AssemblyCodeChunk *origin, AssemblyC uint64_t curr_orig_pc = origin->raw_instruction_start(); uint64_t curr_relo_pc = relocated->raw_instruction_start(); - addr_t buffer_cursor = (addr_t)buffer; - arm64_inst_t instr = *(arm64_inst_t *)buffer_cursor; + addr_t buffer_cursor = (addr_t)buffer; + arm64_inst_t instr = *(arm64_inst_t *)buffer_cursor; int predefined_relocate_size = origin->raw_instruction_size(); @@ -137,8 +137,8 @@ void GenRelocateCodeAndBranch(void *buffer, AssemblyCodeChunk *origin, AssemblyC int last_relo_offset = turbo_assembler_.GetCodeBuffer()->getSize(); if ((instr & LoadRegLiteralFixedMask) == LoadRegLiteralFixed) { // ldr x0, #16 - int rt = decode_rt(instr); - char opc = bits(instr, 30, 31); + int rt = decode_rt(instr); + char opc = bits(instr, 30, 31); addr64_t memory_address = decode_imm19_offset(instr) + curr_orig_pc; #define MEM(reg, offset) MemOperand(reg, offset) @@ -157,13 +157,13 @@ void GenRelocateCodeAndBranch(void *buffer, AssemblyCodeChunk *origin, AssemblyC } else if ((instr & PCRelAddressingFixedMask) == PCRelAddressingFixed) { int rd = decode_rd(instr); - int64_t imm = 0; + int64_t imm = 0; addr64_t runtime_address = 0; if ((instr & PCRelAddressingMask) == ADR) { - imm = decode_immhi_immlo_offset(instr); + imm = decode_immhi_immlo_offset(instr); runtime_address = curr_orig_pc + imm; } else { - imm = decode_immhi_immlo_zero12_offset(instr); + imm = decode_immhi_immlo_zero12_offset(instr); runtime_address = ALIGN_FLOOR(curr_orig_pc, (1 << 12)) + imm; } @@ -175,9 +175,9 @@ void GenRelocateCodeAndBranch(void *buffer, AssemblyCodeChunk *origin, AssemblyC debug_nop(); } else if ((instr & UnconditionalBranchFixedMask) == UnconditionalBranchFixed) { // b xxx - addr_t branch_address = decode_imm26_offset(instr) + curr_orig_pc; + addr_t branch_address = decode_imm26_offset(instr) + curr_orig_pc; RelocLabelEntry *branchAddressLabel = new RelocLabelEntry(branch_address); - _ AppendRelocLabelEntry(branchAddressLabel); + _ AppendRelocLabelEntry(branchAddressLabel); debug_nop(); { @@ -190,18 +190,18 @@ void GenRelocateCodeAndBranch(void *buffer, AssemblyCodeChunk *origin, AssemblyC } debug_nop(); } else if ((instr & TestBranchFixedMask) == TestBranchFixed) { // tbz, tbnz - addr64_t branch_address = decode_imm14_offset(instr) + curr_orig_pc; + addr64_t branch_address = decode_imm14_offset(instr) + curr_orig_pc; RelocLabelEntry *branchAddressLabel = new RelocLabelEntry(branch_address); - _ AppendRelocLabelEntry(branchAddressLabel); + _ AppendRelocLabelEntry(branchAddressLabel); arm64_inst_t branch_instr = instr; char op = bit(instr, 24); - op = op ^ 1; + op = op ^ 1; set_bit(branch_instr, 24, op); - int64_t offset = 4 * 3; // branch_instr; ldr x17, #label; br x17 - uint32_t imm14 = offset >> 2; + int64_t offset = 4 * 3; // branch_instr; ldr x17, #label; br x17 + uint32_t imm14 = offset >> 2; set_bits(branch_instr, 5, 18, imm14); debug_nop(); @@ -220,15 +220,15 @@ void GenRelocateCodeAndBranch(void *buffer, AssemblyCodeChunk *origin, AssemblyC arm64_inst_t branch_instr = instr; char op = bit(instr, 24); - op = op ^ 1; + op = op ^ 1; set_bit(branch_instr, 24, op); - int64_t offset = 4 * 3; - uint32_t imm19 = offset >> 2; + int64_t offset = 4 * 3; + uint32_t imm19 = offset >> 2; set_bits(branch_instr, 5, 23, imm19); RelocLabelEntry *branchAddressLabel = new RelocLabelEntry(branch_address); - _ AppendRelocLabelEntry(branchAddressLabel); + _ AppendRelocLabelEntry(branchAddressLabel); debug_nop(); { @@ -245,15 +245,15 @@ void GenRelocateCodeAndBranch(void *buffer, AssemblyCodeChunk *origin, AssemblyC arm64_inst_t branch_instr = instr; char cond = bits(instr, 0, 3); - cond = cond ^ 1; + cond = cond ^ 1; set_bits(branch_instr, 0, 3, cond); - int64_t offset = 4 * 3; - uint32_t imm19 = offset >> 2; + int64_t offset = 4 * 3; + uint32_t imm19 = offset >> 2; set_bits(branch_instr, 5, 23, imm19); RelocLabelEntry *branchAddressLabel = new RelocLabelEntry(branch_address); - _ AppendRelocLabelEntry(branchAddressLabel); + _ AppendRelocLabelEntry(branchAddressLabel); debug_nop(); { @@ -309,7 +309,7 @@ void GenRelocateCodeAndBranch(void *buffer, AssemblyCodeChunk *origin, AssemblyC // Generate executable code { AssemblyCodeChunk *code = NULL; - code = AssemblyCodeBuilder::FinalizeFromTurboAssembler(&turbo_assembler_); + code = AssemblyCodeBuilder::FinalizeFromTurboAssembler(&turbo_assembler_); relocated->re_init_region_range(code->raw_instruction_start(), code->raw_instruction_size()); delete code; } diff --git a/module/src/main/cpp/Dobby/source/InstructionRelocation/arm64/ARM64InstructionRelocation.h b/module/src/main/cpp/Dobby/source/InstructionRelocation/arm64/ARM64InstructionRelocation.h index 435042fb..93396631 100644 --- a/module/src/main/cpp/Dobby/source/InstructionRelocation/arm64/ARM64InstructionRelocation.h +++ b/module/src/main/cpp/Dobby/source/InstructionRelocation/arm64/ARM64InstructionRelocation.h @@ -5,13 +5,12 @@ #include "core/arch/arm64/constants-arm64.h" +#if 0 namespace zz { namespace arm64 { - -// Generate the relocated instruction void GenRelocateCodeAndBranch(void *buffer, AssemblyCodeChunk *origin, AssemblyCodeChunk *relocated); - } // namespace arm64 } // namespace zz +#endif #endif diff --git a/module/src/main/cpp/Dobby/source/InstructionRelocation/x64/X64InstructionRelocation.cc b/module/src/main/cpp/Dobby/source/InstructionRelocation/x64/X64InstructionRelocation.cc index 439fe173..fd5543b0 100644 --- a/module/src/main/cpp/Dobby/source/InstructionRelocation/x64/X64InstructionRelocation.cc +++ b/module/src/main/cpp/Dobby/source/InstructionRelocation/x64/X64InstructionRelocation.cc @@ -1,4 +1,4 @@ -#include "common/macros/platform_macro.h" +#include "platform_macro.h" #if defined(TARGET_ARCH_X64) #include "InstructionRelocation/x64/X64InstructionRelocation.h" @@ -19,7 +19,7 @@ static int GenRelocateCodeFixed(void *buffer, AssemblyCodeChunk *origin, Assembl TurboAssembler turbo_assembler_(0); // Set fixed executable code chunk address turbo_assembler_.SetRealizedAddress((void *)relocated->raw_instruction_start()); -#define _ turbo_assembler_. +#define _ turbo_assembler_. #define __ turbo_assembler_.GetCodeBuffer()-> addr64_t curr_orig_ip = origin->raw_instruction_start(); @@ -27,7 +27,8 @@ static int GenRelocateCodeFixed(void *buffer, AssemblyCodeChunk *origin, Assembl addr_t buffer_cursor = (addr_t)buffer; - x86_options_t conf = {.mode = 64}; + x86_options_t conf = {0}; + conf.mode = 64; int predefined_relocate_size = origin->raw_instruction_size(); @@ -40,37 +41,40 @@ static int GenRelocateCodeFixed(void *buffer, AssemblyCodeChunk *origin, Assembl x86_insn_decode(&insn, (uint8_t *)buffer_cursor, &conf); if (insn.primary_opcode >= 0x70 && insn.primary_opcode <= 0x7F) { // jc rel8 - DLOG(1, "[x86 relo] jc rel8, %p", buffer_cursor); + DLOG(0, "[x86 relo] jc rel8, %p", buffer_cursor); - int8_t orig_offset = insn.immediate; - int new_offset = (int)(curr_orig_ip + orig_offset - curr_relo_ip); - uint8_t opcode = 0x80 | (insn.primary_opcode & 0x0f); + int8_t orig_offset = insn.immediate; + int new_offset = (int)(curr_orig_ip + orig_offset - curr_relo_ip); + uint8_t opcode = 0x80 | (insn.primary_opcode & 0x0f); __ Emit8(0x0F); __ Emit8(opcode); __ Emit32(new_offset); } else if (insn.primary_opcode == 0xEB) { // jmp rel8 - DLOG(1, "[x86 relo] jmp rel8, %p", buffer_cursor); + DLOG(0, "[x86 relo] jmp rel8, %p", buffer_cursor); int8_t orig_offset = insn.immediate; - int8_t new_offset = (int8_t)(curr_orig_ip + orig_offset - curr_relo_ip); + int8_t new_offset = (int8_t)(curr_orig_ip + orig_offset - curr_relo_ip); __ Emit8(0xE9); __ Emit32(new_offset); } else if ((insn.flags & X86_INSN_DECODE_FLAG_IP_RELATIVE) && (insn.operands[1].mem.base == RIP)) { // RIP - DLOG(1, "[x86 relo] rip, %p", buffer_cursor); + DLOG(0, "[x86 relo] rip, %p", buffer_cursor); // dword orig_disp = *(dword *)(buffer_cursor + insn.operands[1].mem.disp); dword orig_disp = insn.operands[1].mem.disp; - dword disp = (dword)(curr_orig_ip + orig_disp - curr_relo_ip); + dword new_disp = (dword)(curr_orig_ip + orig_disp - curr_relo_ip); __ EmitBuffer((void *)buffer_cursor, insn.displacement_offset); - __ Emit32(disp); + __ Emit32(new_disp); + if (insn.immediate_offset) { + __ EmitBuffer((void *)(buffer_cursor + insn.immediate_offset), insn.length - insn.immediate_offset); + } } else if (insn.primary_opcode == 0xE8 || insn.primary_opcode == 0xE9) { // call or jmp rel32 - DLOG(1, "[x86 relo] jmp or call rel32, %p", buffer_cursor); + DLOG(0, "[x86 relo] jmp or call rel32, %p", buffer_cursor); dword orig_offset = insn.immediate; - dword offset = (dword)(curr_orig_ip + orig_offset - curr_relo_ip); + dword offset = (dword)(curr_orig_ip + orig_offset - curr_relo_ip); __ EmitBuffer((void *)buffer_cursor, insn.immediate_offset); __ Emit32(offset); @@ -120,7 +124,7 @@ static int GenRelocateCodeFixed(void *buffer, AssemblyCodeChunk *origin, Assembl // Generate executable code { AssemblyCodeChunk *code = NULL; - code = AssemblyCodeBuilder::FinalizeFromTurboAssembler(&turbo_assembler_); + code = AssemblyCodeBuilder::FinalizeFromTurboAssembler(&turbo_assembler_); delete code; } @@ -131,8 +135,8 @@ void GenRelocateCodeAndBranch(void *buffer, AssemblyCodeChunk *origin, AssemblyC // pre-alloc code chunk AssemblyCodeChunk *cchunk = NULL; - int relo_code_chunk_size = 32; - const int chunk_size_step = 16; + int relo_code_chunk_size = 32; + const int chunk_size_step = 16; x64_try_again: if (relocated->raw_instruction_start() == 0) { diff --git a/module/src/main/cpp/Dobby/source/InstructionRelocation/x64/X64InstructionRelocation.h b/module/src/main/cpp/Dobby/source/InstructionRelocation/x64/X64InstructionRelocation.h index c90bce10..ceff7777 100644 --- a/module/src/main/cpp/Dobby/source/InstructionRelocation/x64/X64InstructionRelocation.h +++ b/module/src/main/cpp/Dobby/source/InstructionRelocation/x64/X64InstructionRelocation.h @@ -1,19 +1,10 @@ #ifndef INSTRUCTION_RELOCATION_X64_H #define INSTRUCTION_RELOCATION_X64_H -#include "common/headers/common_header.h" +#include "common_header.h" #include "core/arch/x64/constants-x64.h" #include "MemoryAllocator/AssemblyCodeBuilder.h" -namespace zz { -namespace x64 { - -// Generate the relocated instruction -AssemblyCodeChunk *GenRelocateCodeAndBranch(void *buffer, int *relocate_size, addr_t from_ip, addr_t to_ip); - -} // namespace x64 -} // namespace zz - #endif \ No newline at end of file diff --git a/module/src/main/cpp/Dobby/source/InstructionRelocation/x86/X86InstructionRelocation.cc b/module/src/main/cpp/Dobby/source/InstructionRelocation/x86/X86InstructionRelocation.cc index d12bba45..eb0a2081 100644 --- a/module/src/main/cpp/Dobby/source/InstructionRelocation/x86/X86InstructionRelocation.cc +++ b/module/src/main/cpp/Dobby/source/InstructionRelocation/x86/X86InstructionRelocation.cc @@ -1,4 +1,4 @@ -#include "common/macros/platform_macro.h" +#include "platform_macro.h" #if defined(TARGET_ARCH_IA32) #include "InstructionRelocation/x86//X86InstructionRelocation.h" @@ -19,7 +19,7 @@ static int GenRelocateCodeFixed(void *buffer, AssemblyCodeChunk *origin, Assembl TurboAssembler turbo_assembler_(0); // Set fixed executable code chunk address turbo_assembler_.SetRealizedAddress((void *)relocated->raw_instruction_start()); -#define _ turbo_assembler_. +#define _ turbo_assembler_. #define __ turbo_assembler_.GetCodeBuffer()-> addr64_t curr_orig_ip = origin->raw_instruction_start(); @@ -27,7 +27,8 @@ static int GenRelocateCodeFixed(void *buffer, AssemblyCodeChunk *origin, Assembl addr_t buffer_cursor = (addr_t)buffer; - x86_options_t conf = {.mode = 32}; + x86_options_t conf = {0}; + conf.mode = 32; int predefined_relocate_size = origin->raw_instruction_size(); @@ -40,28 +41,28 @@ static int GenRelocateCodeFixed(void *buffer, AssemblyCodeChunk *origin, Assembl x86_insn_decode(&insn, (uint8_t *)buffer_cursor, &conf); if (insn.primary_opcode >= 0x70 && insn.primary_opcode <= 0x7F) { // jc rel8 - DLOG(1, "[x86 relo] jc rel8, %p", buffer_cursor); + DLOG(0, "[x86 relo] jc rel8, %p", buffer_cursor); - int8_t orig_offset = insn.immediate; - int new_offset = (int)(curr_orig_ip + orig_offset - curr_relo_ip); - uint8_t opcode = 0x80 | (insn.primary_opcode & 0x0f); + int8_t orig_offset = insn.immediate; + int new_offset = (int)(curr_orig_ip + orig_offset - curr_relo_ip); + uint8_t opcode = 0x80 | (insn.primary_opcode & 0x0f); __ Emit8(0x0F); __ Emit8(opcode); __ Emit32(new_offset); } else if (insn.primary_opcode == 0xEB) { // jmp rel8 - DLOG(1, "[x86 relo] jmp rel8, %p", buffer_cursor); + DLOG(0, "[x86 relo] jmp rel8, %p", buffer_cursor); int8_t orig_offset = insn.immediate; - int8_t new_offset = (int8_t)(curr_orig_ip + orig_offset - curr_relo_ip); + int8_t new_offset = (int8_t)(curr_orig_ip + orig_offset - curr_relo_ip); __ Emit8(0xE9); __ Emit32(new_offset); } else if (insn.primary_opcode == 0xE8 || insn.primary_opcode == 0xE9) { // call or jmp rel32 - DLOG(1, "[x86 relo] jmp or call rel32, %p", buffer_cursor); + DLOG(0, "[x86 relo] jmp or call rel32, %p", buffer_cursor); dword orig_offset = insn.immediate; - dword offset = (dword)(curr_orig_ip + orig_offset - curr_relo_ip); + dword offset = (dword)(curr_orig_ip + orig_offset - curr_relo_ip); __ EmitBuffer((void *)buffer_cursor, insn.immediate_offset); __ Emit32(offset); @@ -92,7 +93,7 @@ static int GenRelocateCodeFixed(void *buffer, AssemblyCodeChunk *origin, Assembl } // jmp to the origin rest instructions - CodeGen codegen(&turbo_assembler_); + CodeGen codegen(&turbo_assembler_); addr64_t stub_addr = curr_relo_ip + 6; codegen.JmpNear(curr_orig_ip); @@ -109,7 +110,7 @@ static int GenRelocateCodeFixed(void *buffer, AssemblyCodeChunk *origin, Assembl // Generate executable code { AssemblyCodeChunk *code = NULL; - code = AssemblyCodeBuilder::FinalizeFromTurboAssembler(&turbo_assembler_); + code = AssemblyCodeBuilder::FinalizeFromTurboAssembler(&turbo_assembler_); delete code; } @@ -120,8 +121,8 @@ void GenRelocateCodeAndBranch(void *buffer, AssemblyCodeChunk *origin, AssemblyC // pre-alloc code chunk AssemblyCodeChunk *cchunk = NULL; - int relo_code_chunk_size = 32; - const int chunk_size_step = 16; + int relo_code_chunk_size = 32; + const int chunk_size_step = 16; x86_try_again: if (relocated->raw_instruction_start() == 0) { diff --git a/module/src/main/cpp/Dobby/source/InstructionRelocation/x86/X86InstructionRelocation.h b/module/src/main/cpp/Dobby/source/InstructionRelocation/x86/X86InstructionRelocation.h index 16a68fac..9dea6628 100644 --- a/module/src/main/cpp/Dobby/source/InstructionRelocation/x86/X86InstructionRelocation.h +++ b/module/src/main/cpp/Dobby/source/InstructionRelocation/x86/X86InstructionRelocation.h @@ -1,19 +1,10 @@ #ifndef INSTRUCTION_RELOCATION_X64_H #define INSTRUCTION_RELOCATION_X64_H -#include "common/headers/common_header.h" +#include "common_header.h" #include "core/arch/x86/constants-x86.h" #include "MemoryAllocator/AssemblyCodeBuilder.h" -namespace zz { -namespace x86 { - -// Generate the relocated instruction -AssemblyCodeChunk *GenRelocateCodeAndBranch(void *buffer, int *relocate_size, addr_t from_pc, addr_t to_pc); - -} // namespace x86 -} // namespace zz - #endif \ No newline at end of file diff --git a/module/src/main/cpp/Dobby/source/InstructionRelocation/x86/deprecated/Ia32Disassembler.cc b/module/src/main/cpp/Dobby/source/InstructionRelocation/x86/deprecated/Ia32Disassembler.cc index 6e7dc91a..e9774d12 100644 --- a/module/src/main/cpp/Dobby/source/InstructionRelocation/x86/deprecated/Ia32Disassembler.cc +++ b/module/src/main/cpp/Dobby/source/InstructionRelocation/x86/deprecated/Ia32Disassembler.cc @@ -16,7 +16,7 @@ bool supports_rex_ = false; void DecodeInstruction(uint8_t *instr) { bool have_prefixes = true; - uint8_t prefix[4] = {0, 0, 0, 0}; + uint8_t prefix[4] = {0, 0, 0, 0}; // decode legacy prefix do { @@ -59,7 +59,7 @@ void DecodeInstruction(uint8_t *instr) { instr++; } - bool has_modrm = false; + bool has_modrm = false; bool reg_is_opcode = false; size_t immediate_bytes = 0; diff --git a/module/src/main/cpp/Dobby/source/InstructionRelocation/x86/deprecated/X86OpcodoDecodeTable.cc b/module/src/main/cpp/Dobby/source/InstructionRelocation/x86/deprecated/X86OpcodoDecodeTable.cc index 879b43fa..84bfad76 100644 --- a/module/src/main/cpp/Dobby/source/InstructionRelocation/x86/deprecated/X86OpcodoDecodeTable.cc +++ b/module/src/main/cpp/Dobby/source/InstructionRelocation/x86/deprecated/X86OpcodoDecodeTable.cc @@ -1,4 +1,4 @@ -#include "common/macros/platform_macro.h" +#include "platform_macro.h" #if defined(TARGET_ARCH_IA32) || defined(TARGET_ARCH_X64) #include "./X86OpcodoDecodeTable.h" @@ -103,7 +103,7 @@ void _DecodeDisplacement8(InstrMnemonic *instr, addr_t p) { } void _DecodeDisplacement32(InstrMnemonic *instr, addr_t p) { - instr->instr.DisplacementOffset = instr->len; + instr->instr.DisplacementOffset = instr->len; *(dword *)&instr->instr.Displacement = *(byte_t *)p; instr->len += 4; } diff --git a/module/src/main/cpp/Dobby/source/InstructionRelocation/x86/deprecated/X86OpcodoDecodeTable.h b/module/src/main/cpp/Dobby/source/InstructionRelocation/x86/deprecated/X86OpcodoDecodeTable.h index 61ecac9c..778fdb30 100644 --- a/module/src/main/cpp/Dobby/source/InstructionRelocation/x86/deprecated/X86OpcodoDecodeTable.h +++ b/module/src/main/cpp/Dobby/source/InstructionRelocation/x86/deprecated/X86OpcodoDecodeTable.h @@ -61,10 +61,10 @@ struct Instr { }; byte_t Displacement[4]; - int DisplacementOffset; + int DisplacementOffset; byte_t Immediate[4]; - int ImmediateOffset; + int ImmediateOffset; }; // clang-format off diff --git a/module/src/main/cpp/Dobby/source/InstructionRelocation/x86/x86_insn_decode/build_config.h b/module/src/main/cpp/Dobby/source/InstructionRelocation/x86/x86_insn_decode/build_config.h index fc620717..6206267e 100644 --- a/module/src/main/cpp/Dobby/source/InstructionRelocation/x86/x86_insn_decode/build_config.h +++ b/module/src/main/cpp/Dobby/source/InstructionRelocation/x86/x86_insn_decode/build_config.h @@ -9,7 +9,7 @@ #define OS_MACOSX 1 #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE #define OS_IOS 1 -#endif // defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE +#endif // defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE #elif defined(__linux__) #define OS_LINUX 1 // include a system header to pull in features.h for glibc/uclibc macros. @@ -50,10 +50,9 @@ // For access to standard POSIXish features, use OS_POSIX instead of a // more specific macro. -#if defined(OS_AIX) || defined(OS_ANDROID) || defined(OS_ASMJS) || \ - defined(OS_FREEBSD) || defined(OS_LINUX) || defined(OS_MACOSX) || \ - defined(OS_NACL) || defined(OS_NETBSD) || defined(OS_OPENBSD) || \ - defined(OS_QNX) || defined(OS_SOLARIS) +#if defined(OS_AIX) || defined(OS_ANDROID) || defined(OS_ASMJS) || defined(OS_FREEBSD) || defined(OS_LINUX) || \ + defined(OS_MACOSX) || defined(OS_NACL) || defined(OS_NETBSD) || defined(OS_OPENBSD) || defined(OS_QNX) || \ + defined(OS_SOLARIS) #define OS_POSIX 1 #endif diff --git a/module/src/main/cpp/Dobby/source/InstructionRelocation/x86/x86_insn_decode/x86_insn_decode.c b/module/src/main/cpp/Dobby/source/InstructionRelocation/x86/x86_insn_decode/x86_insn_decode.c index 1f6bf59c..087ac982 100644 --- a/module/src/main/cpp/Dobby/source/InstructionRelocation/x86/x86_insn_decode/x86_insn_decode.c +++ b/module/src/main/cpp/Dobby/source/InstructionRelocation/x86/x86_insn_decode/x86_insn_decode.c @@ -1,6 +1,5 @@ #include "./x86_insn_decode.h" -#include #include #include #include @@ -12,13 +11,13 @@ #define REX_X(byte) ((byte & 0b00000010) >> 1) #define REX_B(byte) ((byte & 0b00000001) >> 0) -#define ModRM_Mod(byte) ((byte & 0b11000000) >> 6) +#define ModRM_Mod(byte) ((byte & 0b11000000) >> 6) #define ModRM_RegOpcode(byte) ((byte & 0b00111000) >> 3) -#define ModRM_RM(byte) (byte & 0b00000111) +#define ModRM_RM(byte) (byte & 0b00000111) #define SIB_Scale(sib) ((sib & 0b11000000) >> 6) #define SIB_Index(sib) ((sib & 0b00111000) >> 3) -#define SIB_Base(sib) ((sib & 0b00000111) >> 0) +#define SIB_Base(sib) ((sib & 0b00000111) >> 0) #if 0 /* Build an encoding specification from scratch. */ @@ -27,25 +26,25 @@ ((uint64_t)(opr3) << 32) | ((uint64_t)(opr4) << 40)) /* Get the operation in an encoding specification. */ -#define SPEC_INSN(spec) ((int16_t)((spec)&0xffff)) +#define SPEC_INSN(spec) ((int16_t)((spec)&0xffff)) /* Get the given operand (zero-based) in an encoding specification. */ -#define SPEC_OPERAND(spec, i) ((uint8_t)(((spec) >> (16 + (i)*8)) & 0xff)) +#define SPEC_OPERAND(spec, i) ((uint8_t)(((spec) >> (16 + (i)*8)) & 0xff)) /* Get the operands part of an encoding specification. */ -#define SPEC_OPERANDS(spec) ((spec)&0xffffffffffff0000ULL) +#define SPEC_OPERANDS(spec) ((spec)&0xffffffffffff0000ULL) /* Merges two encoding specifications. */ #define SPEC_MERGE(spec1, spec2) ((spec1) | (spec2)) #define OP4(insn, oper1, oper2, oper3, oper4) SPEC_MAKE(I_##insn, O_##oper1, O_##oper2, O_##oper3, O_##oper4) -#define OP3(insn, oper1, oper2, oper3) OP4(insn, oper1, oper2, oper3, NONE) -#define OP2(insn, oper1, oper2) OP3(insn, oper1, oper2, NONE) -#define OP1(insn, oper1) OP2(insn, oper1, NONE) -#define OP0(insn) OP1(insn, NONE) -#define OP_EMPTY OP0(NONE) -#define OP_EMPTY_4 OP_EMPTY, OP_EMPTY, OP_EMPTY, OP_EMPTY -#define OP_EMPTY_8 OP_EMPTY_4, OP_EMPTY_4 +#define OP3(insn, oper1, oper2, oper3) OP4(insn, oper1, oper2, oper3, NONE) +#define OP2(insn, oper1, oper2) OP3(insn, oper1, oper2, NONE) +#define OP1(insn, oper1) OP2(insn, oper1, NONE) +#define OP0(insn) OP1(insn, NONE) +#define OP_EMPTY OP0(NONE) +#define OP_EMPTY_4 OP_EMPTY, OP_EMPTY, OP_EMPTY, OP_EMPTY +#define OP_EMPTY_8 OP_EMPTY_4, OP_EMPTY_4 #endif #define op3_flag(x, f, o0, o1, o2) \ @@ -54,8 +53,8 @@ .operands[2] = {.data = #o2}, \ } #define op2_flag(x, f, o0, o1) op3_flag(x, f, o0, o1, __) -#define op1_flag(x, f, o0) op2_flag(x, f, o0, __) -#define op0_flag(x, f) op1_flag(x, f, __) +#define op1_flag(x, f, o0) op2_flag(x, f, o0, __) +#define op0_flag(x, f) op1_flag(x, f, __) #define op3f op3_flag #define op2f op2_flag @@ -63,9 +62,9 @@ #define op0f op0_flag #define op3(x, o0, o1, o2) op3f(x, 0, o0, o1, o2) -#define op2(x, o0, o1) op2f(x, 0, o0, o1) -#define op1(x, o0) op1f(x, 0, o0) -#define op0(x) op0f(x, 0) +#define op2(x, o0, o1) op2f(x, 0, o0, o1) +#define op1(x, o0) op1f(x, 0, o0) +#define op0(x) op0f(x, 0) /* Opcode extension in modrm byte reg field. */ #define foreach_x86_insn_modrm_reg_group \ @@ -87,7 +86,7 @@ enum { X86_INSN_GROUP_END = 35 }; -#define X86_INSN_GROUP_END_MASK ((1 << 6) - 1) +#define X86_INSN_GROUP_END_MASK ((1 << 6) - 1) #define X86_INSN_FLAG_SET_GROUP(n) ((n) << 5) #define X86_INSN_FLAG_GET_GROUP(f) (((f) >> 5) & X86_INSN_GROUP_END_MASK) @@ -129,7 +128,7 @@ static x86_insn_prefix_t x86_insn_decode_prefix(x86_insn_reader_t *rd, x86_insn_ */ x86_insn_prefix_t insn_prefix = 0; for (;;) { - uint8_t c = peek_byte(rd); + uint8_t c = peek_byte(rd); x86_insn_prefix_t t = 0; /* Check for REX prefix if we're in 64-bit mode. */ @@ -196,7 +195,7 @@ static x86_insn_prefix_t x86_insn_decode_prefix(x86_insn_reader_t *rd, x86_insn_ int x86_insn_has_modrm_byte(x86_insn_spec_t *insn) { int i; - for (i = 0; i < sizeof(insn->operands); i++) + for (i = 0; i < sizeof(insn->operands) / sizeof(x86_insn_operand_spec_t); i++) switch (insn->operands[i].code) { case 'G': case 'E': @@ -222,7 +221,7 @@ int x86_insn_immediate_type(x86_insn_spec_t *insn) { int x86_insn_has_immediate(x86_insn_spec_t *insn) { int i; - for (i = 0; i < sizeof(insn->operands); i++) { + for (i = 0; i < sizeof(insn->operands) / sizeof(x86_insn_operand_spec_t); i++) { switch (insn->operands[i].code) { case 'J': case 'I': @@ -260,11 +259,11 @@ void x86_insn_decode_modrm_sib(x86_insn_reader_t *rd, x86_insn_decode_t *insn, x uint8_t mod, rm, reg; x86_insn_modrm_t modrm; - modrm.byte = read_byte(rd); + modrm.byte = read_byte(rd); insn->modrm = modrm; mod = modrm.mode; - rm = (REX_B(insn->rex) << 3) | modrm.rm; + rm = (REX_B(insn->rex) << 3) | modrm.rm; reg = (REX_R(insn->rex) << 3) | modrm.reg; x86_insn_operand_t *reg_op = &insn->operands[0]; @@ -296,9 +295,9 @@ void x86_insn_decode_modrm_sib(x86_insn_reader_t *rd, x86_insn_decode_t *insn, x insn->flags |= X86_INSN_DECODE_FLAG_HAS_BASE; if (mod == 0 && (rm & 7) == 5) { - insn->flags = X86_INSN_DECODE_FLAG_IP_RELATIVE; + insn->flags = X86_INSN_DECODE_FLAG_IP_RELATIVE; mem_op->mem.base = RIP; - disp_bits = 32; + disp_bits = 32; } else if (mod == 0) { disp_bits = 0; } else if (mod == 1) { @@ -311,16 +310,16 @@ void x86_insn_decode_modrm_sib(x86_insn_reader_t *rd, x86_insn_decode_t *insn, x uint8_t has_sib = 0; if ((rm & 7) == 4) { - assert(modrm.rm == (rm & 7)); + ASSERT(modrm.rm == (rm & 7)); has_sib = 1; } if (has_sib) { x86_insn_sib_t sib = {0}; - sib.byte = read_byte(rd); - insn->sib = sib; + sib.byte = read_byte(rd); + insn->sib = sib; - uint8_t base = sib.base | (REX_B(insn->rex) << 3); + uint8_t base = sib.base | (REX_B(insn->rex) << 3); uint8_t index = sib.index | (REX_X(insn->rex) << 3); uint8_t scale = 1 << sib.log2_scale; @@ -330,7 +329,7 @@ void x86_insn_decode_modrm_sib(x86_insn_reader_t *rd, x86_insn_decode_t *insn, x insn->flags |= X86_INSN_DECODE_FLAG_HAS_INDEX; } - insn->operands[1].mem.base = base; + insn->operands[1].mem.base = base; insn->operands[1].mem.index = index; insn->operands[1].mem.scale = scale; @@ -388,14 +387,14 @@ void x86_insn_decode_modrm_sib(x86_insn_reader_t *rd, x86_insn_decode_t *insn, x switch (modrm.rm) { case 0: /* [bx + si/di] */ case 1: - mem_op->mem.base = X86_INSN_GP_REG_BX; + mem_op->mem.base = X86_INSN_GP_REG_BX; mem_op->mem.index = X86_INSN_GP_REG_SI + (modrm.rm & 1); insn->flags |= X86_INSN_DECODE_FLAG_HAS_BASE | X86_INSN_DECODE_FLAG_HAS_INDEX; break; case 2: /* [bp + si/di] */ case 3: - mem_op->mem.base = X86_INSN_GP_REG_BP; + mem_op->mem.base = X86_INSN_GP_REG_BP; mem_op->mem.index = X86_INSN_GP_REG_SI + (modrm.rm & 1); insn->flags |= X86_INSN_DECODE_FLAG_HAS_BASE | X86_INSN_DECODE_FLAG_HAS_INDEX; break; @@ -441,7 +440,7 @@ static void x86_insn_decode_opcode(x86_insn_reader_t *rd, x86_insn_decode_t *ins x86_insn_spec_t insn_spec; if (opcode == 0x0f) { - opcode = read_byte(rd); + opcode = read_byte(rd); insn_spec = x86_opcode_map_two_byte[opcode]; } else { insn_spec = x86_opcode_map_one_byte[opcode]; @@ -459,20 +458,20 @@ static void x86_insn_decode_opcode(x86_insn_reader_t *rd, x86_insn_decode_t *ins // get gp insn index in group x86_insn_modrm_t modrm; - modrm.byte = peek_byte(rd); + modrm.byte = peek_byte(rd); int insn_ndx = modrm.reg; // get insn in group x86_insn_spec_t *group_insn = NULL; - group_insn = &x86_insn_modrm_reg_groups[group_ndx].insns[insn_ndx]; + group_insn = &x86_insn_modrm_reg_groups[group_ndx].insns[insn_ndx]; // update the insn spec - insn_spec.name = group_insn->name; + insn_spec.name = group_insn->name; insn_spec.flags = group_insn->flags; } insn->primary_opcode = opcode; - insn->insn_spec = insn_spec; + insn->insn_spec = insn_spec; } uint8_t x86_insn_imm_bits(x86_insn_spec_t *insn, uint8_t operand_bits) { @@ -522,7 +521,7 @@ void x86_insn_decode_immediate(x86_insn_reader_t *rd, x86_insn_decode_t *insn, x effective_operand_bits = 64; int64_t immediate = 0; - uint8_t imm_bits = x86_insn_imm_bits(&insn->insn_spec, effective_operand_bits); + uint8_t imm_bits = x86_insn_imm_bits(&insn->insn_spec, effective_operand_bits); if (imm_bits == 0) return; @@ -555,7 +554,7 @@ void x86_insn_decode(x86_insn_decode_t *insn, uint8_t *buffer, x86_options_t *co } #if 1 - DLOG(1, "[x86 insn] %s", insn->insn_spec.name); + DLOG(0, "[x86 insn] %s", insn->insn_spec.name); #endif // set insn length diff --git a/module/src/main/cpp/Dobby/source/InstructionRelocation/x86/x86_insn_decode/x86_insn_decode.h b/module/src/main/cpp/Dobby/source/InstructionRelocation/x86/x86_insn_decode/x86_insn_decode.h index 3fc3d118..bb395fde 100644 --- a/module/src/main/cpp/Dobby/source/InstructionRelocation/x86/x86_insn_decode/x86_insn_decode.h +++ b/module/src/main/cpp/Dobby/source/InstructionRelocation/x86/x86_insn_decode/x86_insn_decode.h @@ -2,6 +2,7 @@ #define X86_INSN_DECODE_H #include +#include "common_header.h" typedef enum { X86_INSN_SPEC_DEFAULT_64_BIT = 1 << 0, @@ -24,22 +25,22 @@ typedef enum { /* Group 1: lock and repeat prefixes */ INSN_PREFIX_GROUP1 = 0x07, - INSN_PREFIX_LOCK = 0x01, /* F0 */ - INSN_PREFIX_REPNZ = 0x02, /* F2 */ - INSN_PREFIX_REPNE = INSN_PREFIX_REPNZ, - INSN_PREFIX_REP = 0x04, /* F3 */ - INSN_PREFIX_REPZ = INSN_PREFIX_REP, - INSN_PREFIX_REPE = INSN_PREFIX_REPZ, + INSN_PREFIX_LOCK = 0x01, /* F0 */ + INSN_PREFIX_REPNZ = 0x02, /* F2 */ + INSN_PREFIX_REPNE = INSN_PREFIX_REPNZ, + INSN_PREFIX_REP = 0x04, /* F3 */ + INSN_PREFIX_REPZ = INSN_PREFIX_REP, + INSN_PREFIX_REPE = INSN_PREFIX_REPZ, /* Group 2: segment override or branch hints */ - INSN_PREFIX_GROUP2 = 0x01f8, - INSN_PREFIX_ES = 0x0008, /* 26 */ - INSN_PREFIX_CS = 0x0010, /* 2E */ - INSN_PREFIX_SS = 0x0020, /* 36 */ - INSN_PREFIX_DS = 0x0040, /* 3E */ - INSN_PREFIX_FS = 0x0080, /* 64 */ - INSN_PREFIX_GS = 0x0100, /* 65 */ - INSN_PREFIX_BRANCH_TAKEN = INSN_PREFIX_CS, /* 2E */ + INSN_PREFIX_GROUP2 = 0x01f8, + INSN_PREFIX_ES = 0x0008, /* 26 */ + INSN_PREFIX_CS = 0x0010, /* 2E */ + INSN_PREFIX_SS = 0x0020, /* 36 */ + INSN_PREFIX_DS = 0x0040, /* 3E */ + INSN_PREFIX_FS = 0x0080, /* 64 */ + INSN_PREFIX_GS = 0x0100, /* 65 */ + INSN_PREFIX_BRANCH_TAKEN = INSN_PREFIX_CS, /* 2E */ INSN_PREFIX_BRANCH_NOT_TAKEN = INSN_PREFIX_DS, /* 3E */ /* Group 3: operand-size override */ @@ -66,8 +67,8 @@ typedef struct { // insn flag uint16_t flags; -#define X86_INSN_FLAG_SET_SSE_GROUP(n) ((n) << 5) -#define X86_INSN_FLAG_GET_SSE_GROUP(f) (((f) >> 5) & 0x1f) +#define X86_INSN_FLAG_SET_SSE_GROUP(n) ((n) << 5) +#define X86_INSN_FLAG_GET_SSE_GROUP(f) (((f) >> 5) & 0x1f) #define X86_INSN_FLAG_SET_MODRM_REG_GROUP(n) (((n)&0x3f) << 10) #define X86_INSN_FLAG_GET_MODRM_REG_GROUP(f) (((f) >> 10) & 0x3f) } x86_insn_spec_t; @@ -123,9 +124,9 @@ typedef struct { uint8_t reg; struct { - uint8_t base; - uint8_t index; - uint8_t scale; + uint8_t base; + uint8_t index; + uint8_t scale; uint32_t disp; } mem; } x86_insn_operand_t; @@ -158,7 +159,7 @@ typedef struct x86_insn_decode_t { x86_insn_operand_t operands[3]; - struct { // insn field combine + struct { // insn field combine // insn prefix x86_insn_prefix_t prefix; diff --git a/module/src/main/cpp/Dobby/source/InterceptRouting/ExtraInternalPlugin/IntegrityReadCallback.cc b/module/src/main/cpp/Dobby/source/InterceptRouting/ExtraInternalPlugin/IntegrityReadCallback.cc deleted file mode 100644 index e69de29b..00000000 diff --git a/module/src/main/cpp/Dobby/source/InterceptRouting/ExtraInternalPlugin/IntegrityReadCallback.h b/module/src/main/cpp/Dobby/source/InterceptRouting/ExtraInternalPlugin/IntegrityReadCallback.h deleted file mode 100644 index e69de29b..00000000 diff --git a/module/src/main/cpp/Dobby/source/InterceptRouting/ExtraInternalPlugin/RegisterPlugin.cc b/module/src/main/cpp/Dobby/source/InterceptRouting/ExtraInternalPlugin/RegisterPlugin.cc deleted file mode 100644 index a6612f09..00000000 --- a/module/src/main/cpp/Dobby/source/InterceptRouting/ExtraInternalPlugin/RegisterPlugin.cc +++ /dev/null @@ -1,15 +0,0 @@ -#include "InterceptRouting/ExtraInternalPlugin/RegisterPlugin.h" - -LiteMutableArray *ExtraInternalPlugin::plugins; - -ExtraInternalPlugin *ExtraInternalPlugin::near_branch_trampoline = NULL; - -void ExtraInternalPlugin::registerPlugin(const char *name, ExtraInternalPlugin *plugin) { - DLOG(1, "register %s plugin", name); - - if (ExtraInternalPlugin::plugins == NULL) { - ExtraInternalPlugin::plugins = new LiteMutableArray(8); - } - - ExtraInternalPlugin::plugins->pushObject(reinterpret_cast(plugin)); -} diff --git a/module/src/main/cpp/Dobby/source/InterceptRouting/InterceptRouting.cpp b/module/src/main/cpp/Dobby/source/InterceptRouting/InterceptRouting.cpp index 497ec820..a78079f8 100644 --- a/module/src/main/cpp/Dobby/source/InterceptRouting/InterceptRouting.cpp +++ b/module/src/main/cpp/Dobby/source/InterceptRouting/InterceptRouting.cpp @@ -1,7 +1,7 @@ #include "dobby_internal.h" #include "InterceptRouting/InterceptRouting.h" -#include "InterceptRouting/ExtraInternalPlugin/RegisterPlugin.h" +#include "InterceptRouting/RoutingPlugin/RoutingPlugin.h" using namespace zz; @@ -9,64 +9,64 @@ void InterceptRouting::Prepare() { } // Generate relocated code -void InterceptRouting::GenerateRelocatedCode() { +bool InterceptRouting::GenerateRelocatedCode(int tramp_size) { // generate original code - AssemblyCodeChunk *origin = NULL; - int trampoline_len = trampoline_buffer_->getSize(); - origin = AssemblyCodeBuilder::FinalizeFromAddress((addr_t)entry_->target_address, trampoline_len); + AssemblyCodeChunk *origin = NULL; + origin = AssemblyCodeBuilder::FinalizeFromAddress((addr_t)entry_->target_address, tramp_size); origin_ = origin; // generate the relocated code AssemblyCodeChunk *relocated = NULL; - relocated = AssemblyCodeBuilder::FinalizeFromAddress(0, 0); - relocated_ = relocated; + relocated = AssemblyCodeBuilder::FinalizeFromAddress(0, 0); + relocated_ = relocated; void *relocate_buffer = NULL; - relocate_buffer = entry_->target_address; + relocate_buffer = entry_->target_address; GenRelocateCodeAndBranch(relocate_buffer, origin, relocated); if (relocated->raw_instruction_start() == 0) - return; + return false; // set the relocated instruction address entry_->relocated_origin_instructions = (void *)relocated->raw_instruction_start(); - DLOG(1, "[insn relocate] origin %p - %d", origin->raw_instruction_start(), origin->raw_instruction_size()); - DLOG(1, "[insn relocate] relocated %p - %d", relocated->raw_instruction_start(), relocated->raw_instruction_size()); + DLOG(0, "[insn relocate] origin %p - %d", origin->raw_instruction_start(), origin->raw_instruction_size()); + DLOG(0, "[insn relocate] relocated %p - %d", relocated->raw_instruction_start(), relocated->raw_instruction_size()); // save original prologue memcpy((void *)entry_->origin_chunk_.chunk_buffer, (void *)origin_->raw_instruction_start(), origin_->raw_instruction_size()); entry_->origin_chunk_.chunk.re_init_region_range(origin_); + return true; } -/* -X86_64 (14 bytes) - [jmp rip] - [branch_address] - -ARM64 - 16 bytes - [ldr literal] - [br] - [branch_address] +bool InterceptRouting::GenerateTrampolineBuffer(void *src, void *dst) { + CodeBufferBase *trampoline_buffer = NULL; + // if near branch trampoline plugin enabled + if (RoutingPluginManager::near_branch_trampoline) { + RoutingPluginInterface *plugin = NULL; + plugin = reinterpret_cast(RoutingPluginManager::near_branch_trampoline); + if (plugin->GenerateTrampolineBuffer(this, src, dst) == false) { + DLOG(0, "Failed enable near branch trampoline plugin"); + } + } -ARM64 - 12 bytes - [adrp] - [add] - [br] + if (this->GetTrampolineBuffer() == NULL) { + trampoline_buffer = GenerateNormalTrampolineBuffer((addr_t)src, (addr_t)dst); + this->SetTrampolineBuffer(trampoline_buffer); -ARM - 8 bytes: - [ldr pc literal] - [data_address] -*/ + DLOG(0, "[trampoline] Generate trampoline buffer %p -> %p", src, dst); + } + return true; +} // Active routing, will patch the origin insturctions, and forward to our custom routing. // Patch the address with branch instr void InterceptRouting::Active() { void *patch_address = NULL; - patch_address = (void *)origin_->raw_instruction_start(); + patch_address = (void *)origin_->raw_instruction_start(); CodePatch(patch_address, (uint8_t *)trampoline_buffer_->getRawBuffer(), trampoline_buffer_->getSize()); - DLOG(1, "[intercept routing] Active patch %p", patch_address); + DLOG(0, "[intercept routing] Active patch %p", patch_address); } void InterceptRouting::Commit() { @@ -83,25 +83,6 @@ int InterceptRouting::PredefinedTrampolineSize() { } #endif -void InterceptRouting::GenerateTrampolineBuffer(void *src, void *dst) { - CodeBufferBase *trampoline_buffer = NULL; - // if near branch trampoline plugin enabled - if (ExtraInternalPlugin::near_branch_trampoline) { - RoutingPlugin *plugin = NULL; - plugin = reinterpret_cast(ExtraInternalPlugin::near_branch_trampoline); - if (plugin->GenerateTrampolineBuffer(this, src, dst) == false) { - DLOG(0, "Failed enable near branch trampoline plugin"); - } - } - - if (this->GetTrampolineBuffer() == NULL) { - trampoline_buffer = GenerateNormalTrampolineBuffer((addr_t)src, (addr_t)dst); - this->SetTrampolineBuffer(trampoline_buffer); - - DLOG(1, "[trampoline] Generate trampoline buffer %p -> %p", src, dst); - } -} - HookEntry *InterceptRouting::GetHookEntry() { return entry_; }; diff --git a/module/src/main/cpp/Dobby/source/InterceptRouting/InterceptRouting.h b/module/src/main/cpp/Dobby/source/InterceptRouting/InterceptRouting.h index 4fc9190e..5917cd49 100644 --- a/module/src/main/cpp/Dobby/source/InterceptRouting/InterceptRouting.h +++ b/module/src/main/cpp/Dobby/source/InterceptRouting/InterceptRouting.h @@ -3,22 +3,20 @@ #include "Interceptor.h" #include "MemoryAllocator/AssemblyCodeBuilder.h" - -extern CodeBufferBase *GenerateNormalTrampolineBuffer(addr_t from, addr_t to); - -extern void GenRelocateCodeAndBranch(void *buffer, AssemblyCodeChunk *origin, AssemblyCodeChunk *relocated); +#include "InstructionRelocation/InstructionRelocation.h" +#include "TrampolineBridge/Trampoline/Trampoline.h" class InterceptRouting { public: InterceptRouting(HookEntry *entry) : entry_(entry) { entry->route = this; - trampoline_ = NULL; + trampoline_ = NULL; trampoline_buffer_ = NULL; trampoline_target_ = NULL; } - virtual void Dispatch() = 0; + virtual void DispatchRouting() = 0; virtual void Prepare(); @@ -28,10 +26,6 @@ class InterceptRouting { HookEntry *GetHookEntry(); - void GenerateRelocatedCode(); - - void GenerateTrampolineBuffer(void *src, void *dst); - void SetTrampolineBuffer(CodeBufferBase *buffer) { trampoline_buffer_ = buffer; } @@ -48,6 +42,11 @@ class InterceptRouting { return trampoline_target_; } +protected: + bool GenerateRelocatedCode(int tramp_size); + + bool GenerateTrampolineBuffer(void *src, void *dst); + protected: HookEntry *entry_; diff --git a/module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/DynamicBinaryInstrument/DynamicBinaryInstrumentExport.cc b/module/src/main/cpp/Dobby/source/InterceptRouting/Routing/DynamicBinaryInstrument/DynamicBinaryInstrumentExport.cc similarity index 61% rename from module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/DynamicBinaryInstrument/DynamicBinaryInstrumentExport.cc rename to module/src/main/cpp/Dobby/source/InterceptRouting/Routing/DynamicBinaryInstrument/DynamicBinaryInstrumentExport.cc index 902aaf14..ff573151 100644 --- a/module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/DynamicBinaryInstrument/DynamicBinaryInstrumentExport.cc +++ b/module/src/main/cpp/Dobby/source/InterceptRouting/Routing/DynamicBinaryInstrument/DynamicBinaryInstrumentExport.cc @@ -1,14 +1,16 @@ #include "dobby_internal.h" #include "InterceptRouting/InterceptRouting.h" -#include "InterceptRouting/RoutingPlugin/DynamicBinaryInstrument/dynamic-binary-instrument.h" +#include "InterceptRouting/Routing/DynamicBinaryInstrument/dynamic-binary-instrument.h" PUBLIC int DobbyInstrument(void *address, DBICallTy handler) { if (!address) { ERROR_LOG("the function address is 0x0.\n"); return RS_FAILED; } - DLOG(1, "[DobbyInstrument] Initialize at %p", address); + + RAW_LOG(1, "\n\n"); + DLOG(0, "[DobbyInstrument] Initialize at %p", address); // check if we already instruemnt HookEntry *entry = Interceptor::SharedInstance()->FindHookEntry(address); @@ -20,17 +22,16 @@ PUBLIC int DobbyInstrument(void *address, DBICallTy handler) { } } - entry = new HookEntry(); - entry->id = Interceptor::SharedInstance()->GetHookEntryCount(); - entry->type = kDynamicBinaryInstrument; + entry = new HookEntry(); + entry->id = Interceptor::SharedInstance()->GetHookEntryCount(); + entry->type = kDynamicBinaryInstrument; entry->instruction_address = address; - DLOG(1, "================ DynamicBinaryInstrumentRouting Start ================"); DynamicBinaryInstrumentRouting *route = new DynamicBinaryInstrumentRouting(entry, (void *)handler); - route->Dispatch(); + route->Prepare(); + route->DispatchRouting(); Interceptor::SharedInstance()->AddHookEntry(entry); route->Commit(); - DLOG(1, "================ DynamicBinaryInstrumentRouting End ================"); return RS_SUCCESS; } diff --git a/module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/DynamicBinaryInstrument/dynamic-binary-instrument.cc b/module/src/main/cpp/Dobby/source/InterceptRouting/Routing/DynamicBinaryInstrument/dynamic-binary-instrument.cc similarity index 64% rename from module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/DynamicBinaryInstrument/dynamic-binary-instrument.cc rename to module/src/main/cpp/Dobby/source/InterceptRouting/Routing/DynamicBinaryInstrument/dynamic-binary-instrument.cc index 2a7e1160..54335f0c 100644 --- a/module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/DynamicBinaryInstrument/dynamic-binary-instrument.cc +++ b/module/src/main/cpp/Dobby/source/InterceptRouting/Routing/DynamicBinaryInstrument/dynamic-binary-instrument.cc @@ -1,21 +1,22 @@ -#include "InterceptRouting/RoutingPlugin/DynamicBinaryInstrument/dynamic-binary-instrument.h" +#include "InterceptRouting/Routing/DynamicBinaryInstrument/dynamic-binary-instrument.h" #include "dobby_internal.h" #include "TrampolineBridge/ClosureTrampolineBridge/AssemblyClosureTrampoline.h" -#include "InterceptRouting/RoutingPlugin/DynamicBinaryInstrument/intercept_routing_handler.h" +#include "InterceptRouting/Routing/DynamicBinaryInstrument/intercept_routing_handler.h" -void DynamicBinaryInstrumentRouting::Dispatch() { - Prepare(); +void DynamicBinaryInstrumentRouting::DispatchRouting() { BuildDynamicBinaryInstrumentRouting(); + + // generate relocated code which size == trampoline size + GenerateRelocatedCode(trampoline_buffer_->getSize()); } // Add dbi_call handler before running the origin instructions void DynamicBinaryInstrumentRouting::BuildDynamicBinaryInstrumentRouting() { // create closure trampoline jump to prologue_routing_dispath with the `entry_` data ClosureTrampolineEntry *closure_trampoline; - // forward trampoline void *handler = (void *)instrument_routing_dispatch; #if __APPLE__ @@ -23,22 +24,18 @@ void DynamicBinaryInstrumentRouting::BuildDynamicBinaryInstrumentRouting() { handler = __builtin_ptrauth_strip(handler, ptrauth_key_asia); #endif #endif - closure_trampoline = ClosureTrampoline::CreateClosureTrampoline(entry_, handler); - DLOG(1, "[closure bridge] Carry data %p ", entry_); - DLOG(1, "[closure bridge] Create prologue_dispatch_bridge %p", closure_trampoline->address); - // set trampoline target address + closure_trampoline = ClosureTrampoline::CreateClosureTrampoline(entry_, handler); this->SetTrampolineTarget(closure_trampoline->address); + DLOG(0, "[closure bridge] Carry data %p ", entry_); + DLOG(0, "[closure bridge] Create prologue_dispatch_bridge %p", closure_trampoline->address); - this->prologue_dispatch_bridge = closure_trampoline->address; - + // generate trampoline buffer, run before `GenerateRelocatedCode` GenerateTrampolineBuffer(entry_->target_address, GetTrampolineTarget()); - - GenerateRelocatedCode(); } #if 0 void *DynamicBinaryInstrumentRouting::GetTrampolineTarget() { return this->prologue_dispatch_bridge; } -#endif +#endif \ No newline at end of file diff --git a/module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/DynamicBinaryInstrument/dynamic-binary-instrument.h b/module/src/main/cpp/Dobby/source/InterceptRouting/Routing/DynamicBinaryInstrument/dynamic-binary-instrument.h similarity index 90% rename from module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/DynamicBinaryInstrument/dynamic-binary-instrument.h rename to module/src/main/cpp/Dobby/source/InterceptRouting/Routing/DynamicBinaryInstrument/dynamic-binary-instrument.h index 01ac87f0..b098233d 100644 --- a/module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/DynamicBinaryInstrument/dynamic-binary-instrument.h +++ b/module/src/main/cpp/Dobby/source/InterceptRouting/Routing/DynamicBinaryInstrument/dynamic-binary-instrument.h @@ -9,7 +9,7 @@ #include "TrampolineBridge/ClosureTrampolineBridge/AssemblyClosureTrampoline.h" -#define X64InterceptRouting InterceptRouting +#define X64InterceptRouting InterceptRouting #define ARM64InterceptRouting InterceptRouting class DynamicBinaryInstrumentRouting : public X64InterceptRouting { @@ -18,7 +18,7 @@ class DynamicBinaryInstrumentRouting : public X64InterceptRouting { this->handler = handler; } - void Dispatch(); + void DispatchRouting(); public: void *handler; diff --git a/module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/DynamicBinaryInstrument/intercept_routing_handler.cc b/module/src/main/cpp/Dobby/source/InterceptRouting/Routing/DynamicBinaryInstrument/intercept_routing_handler.cc similarity index 65% rename from module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/DynamicBinaryInstrument/intercept_routing_handler.cc rename to module/src/main/cpp/Dobby/source/InterceptRouting/Routing/DynamicBinaryInstrument/intercept_routing_handler.cc index e99b7560..bd43afd2 100644 --- a/module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/DynamicBinaryInstrument/intercept_routing_handler.cc +++ b/module/src/main/cpp/Dobby/source/InterceptRouting/Routing/DynamicBinaryInstrument/intercept_routing_handler.cc @@ -1,19 +1,19 @@ -#include "InterceptRouting/RoutingPlugin/DynamicBinaryInstrument/intercept_routing_handler.h" +#include "InterceptRouting/Routing/DynamicBinaryInstrument/intercept_routing_handler.h" #include "dobby_internal.h" -#include "InterceptRouting/RoutingPlugin/DynamicBinaryInstrument/dynamic-binary-instrument.h" +#include "InterceptRouting/Routing/DynamicBinaryInstrument/dynamic-binary-instrument.h" -#include "TrampolineBridge/ClosureTrampolineBridge/closure-trampoline-common-handler.h" +#include "TrampolineBridge/ClosureTrampolineBridge/common-bridge-handler.h" void instrument_call_forward_handler(RegisterContext *ctx, HookEntry *entry) { DynamicBinaryInstrumentRouting *route = (DynamicBinaryInstrumentRouting *)entry->route; if (route->handler) { - DBICallTy handler; + DBICallTy handler; HookEntryInfo entry_info; - entry_info.hook_id = entry->id; + entry_info.hook_id = entry->id; entry_info.instruction_address = entry->instruction_address; - handler = (DBICallTy)route->handler; + handler = (DBICallTy)route->handler; (*handler)(ctx, (const HookEntryInfo *)&entry_info); } diff --git a/module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/DynamicBinaryInstrument/intercept_routing_handler.h b/module/src/main/cpp/Dobby/source/InterceptRouting/Routing/DynamicBinaryInstrument/intercept_routing_handler.h similarity index 100% rename from module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/DynamicBinaryInstrument/intercept_routing_handler.h rename to module/src/main/cpp/Dobby/source/InterceptRouting/Routing/DynamicBinaryInstrument/intercept_routing_handler.h diff --git a/module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/FunctionInlineReplace/FunctionInlineReplaceExport.cc b/module/src/main/cpp/Dobby/source/InterceptRouting/Routing/FunctionInlineReplace/FunctionInlineReplaceExport.cc similarity index 66% rename from module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/FunctionInlineReplace/FunctionInlineReplaceExport.cc rename to module/src/main/cpp/Dobby/source/InterceptRouting/Routing/FunctionInlineReplace/FunctionInlineReplaceExport.cc index 31871d60..0252e196 100644 --- a/module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/FunctionInlineReplace/FunctionInlineReplaceExport.cc +++ b/module/src/main/cpp/Dobby/source/InterceptRouting/Routing/FunctionInlineReplace/FunctionInlineReplaceExport.cc @@ -2,14 +2,15 @@ #include "Interceptor.h" #include "InterceptRouting/InterceptRouting.h" -#include "InterceptRouting/RoutingPlugin/FunctionInlineReplace/function-inline-replace.h" +#include "InterceptRouting/Routing/FunctionInlineReplace/function-inline-replace.h" PUBLIC int DobbyHook(void *address, void *replace_call, void **origin_call) { if (!address) { ERROR_LOG("function address is 0x0"); return RS_FAILED; } - DLOG(1, "[DobbyHook] Initialize at %p", address); + + DLOG(0, "[DobbyHook] Initialize at %p", address); // check if already hooked HookEntry *entry = Interceptor::SharedInstance()->FindHookEntry(address); @@ -21,14 +22,14 @@ PUBLIC int DobbyHook(void *address, void *replace_call, void **origin_call) { } } - entry = new HookEntry(); - entry->id = Interceptor::SharedInstance()->GetHookEntryCount(); - entry->type = kFunctionInlineHook; + entry = new HookEntry(); + entry->id = Interceptor::SharedInstance()->GetHookEntryCount(); + entry->type = kFunctionInlineHook; entry->function_address = address; - DLOG(1, "================ FunctionInlineReplaceRouting Start ================"); FunctionInlineReplaceRouting *route = new FunctionInlineReplaceRouting(entry, replace_call); - route->Dispatch(); + route->Prepare(); + route->DispatchRouting(); Interceptor::SharedInstance()->AddHookEntry(entry); // set origin call with relocated function @@ -36,7 +37,6 @@ PUBLIC int DobbyHook(void *address, void *replace_call, void **origin_call) { // code patch & hijack original control flow entry route->Commit(); - DLOG(1, "================ FunctionInlineReplaceRouting End ================"); return RS_SUCCESS; } diff --git a/module/src/main/cpp/Dobby/source/InterceptRouting/Routing/FunctionInlineReplace/function-inline-replace.cc b/module/src/main/cpp/Dobby/source/InterceptRouting/Routing/FunctionInlineReplace/function-inline-replace.cc new file mode 100644 index 00000000..4e17d6d9 --- /dev/null +++ b/module/src/main/cpp/Dobby/source/InterceptRouting/Routing/FunctionInlineReplace/function-inline-replace.cc @@ -0,0 +1,24 @@ +#include "InterceptRouting/Routing/FunctionInlineReplace/function-inline-replace.h" + +#include "dobby_internal.h" + +void FunctionInlineReplaceRouting::DispatchRouting() { + BuildReplaceRouting(); + + // generate relocated code which size == trampoline size + GenerateRelocatedCode(trampoline_buffer_->getSize()); +} + +void FunctionInlineReplaceRouting::BuildReplaceRouting() { + this->SetTrampolineTarget(this->replace_call); + DLOG(0, "[inline] Set trampoline target => %p", GetTrampolineTarget()); + + // generate trampoline buffer, run before `GenerateRelocatedCode` + GenerateTrampolineBuffer(entry_->target_address, GetTrampolineTarget()); +} + +#if 0 +void *FunctionInlineReplaceRouting::GetTrampolineTarget() { + return this->replace_call; +} +#endif diff --git a/module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/FunctionInlineReplace/function-inline-replace.h b/module/src/main/cpp/Dobby/source/InterceptRouting/Routing/FunctionInlineReplace/function-inline-replace.h similarity index 94% rename from module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/FunctionInlineReplace/function-inline-replace.h rename to module/src/main/cpp/Dobby/source/InterceptRouting/Routing/FunctionInlineReplace/function-inline-replace.h index f77f70e5..ff7e1f38 100644 --- a/module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/FunctionInlineReplace/function-inline-replace.h +++ b/module/src/main/cpp/Dobby/source/InterceptRouting/Routing/FunctionInlineReplace/function-inline-replace.h @@ -14,7 +14,7 @@ class FunctionInlineReplaceRouting : public InterceptRouting { this->replace_call = replace_call; } - void Dispatch() override; + void DispatchRouting() override; private: virtual void BuildReplaceRouting(); diff --git a/module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/FunctionWrapper/FunctionWrapperExport.cc b/module/src/main/cpp/Dobby/source/InterceptRouting/Routing/FunctionWrapper/FunctionWrapperExport.cc similarity index 69% rename from module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/FunctionWrapper/FunctionWrapperExport.cc rename to module/src/main/cpp/Dobby/source/InterceptRouting/Routing/FunctionWrapper/FunctionWrapperExport.cc index 665b3e9f..cc8301d2 100644 --- a/module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/FunctionWrapper/FunctionWrapperExport.cc +++ b/module/src/main/cpp/Dobby/source/InterceptRouting/Routing/FunctionWrapper/FunctionWrapperExport.cc @@ -8,17 +8,17 @@ #include "function-wrapper.h" PUBLIC int DobbyWrap(void *function_address, PreCallTy pre_call, PostCallTy post_call) { - DLOG(1, "Initialize 'DobbyWrap' hook at %p", function_address); + DLOG(0, "Initialize 'DobbyWrap' hook at %p", function_address); Interceptor *interceptor = Interceptor::SharedInstance(); - HookEntry *entry = new HookEntry(); - entry->id = interceptor->entries->getCount(); - entry->type = kFunctionWrapper; + HookEntry *entry = new HookEntry(); + entry->id = interceptor->entries->getCount(); + entry->type = kFunctionWrapper; entry->function_address = function_address; FunctionWrapperRouting *route = new FunctionWrapperRouting(entry); - route->Dispatch(); + route->DispatchRouting(); interceptor->AddHookEntry(entry); route->Commit(); diff --git a/module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/FunctionWrapper/function-wrapper.cc b/module/src/main/cpp/Dobby/source/InterceptRouting/Routing/FunctionWrapper/function-wrapper.cc similarity index 96% rename from module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/FunctionWrapper/function-wrapper.cc rename to module/src/main/cpp/Dobby/source/InterceptRouting/Routing/FunctionWrapper/function-wrapper.cc index 9222c7be..2f25dc9c 100644 --- a/module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/FunctionWrapper/function-wrapper.cc +++ b/module/src/main/cpp/Dobby/source/InterceptRouting/Routing/FunctionWrapper/function-wrapper.cc @@ -6,7 +6,7 @@ #include "function-wrapper.h" -void FunctionWrapperRouting::Dispatch() { +void FunctionWrapperRouting::DispatchRouting() { Prepare(); BuildPreCallRouting(); BuildPostCallRouting(); diff --git a/module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/FunctionWrapper/function-wrapper.h b/module/src/main/cpp/Dobby/source/InterceptRouting/Routing/FunctionWrapper/function-wrapper.h similarity index 96% rename from module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/FunctionWrapper/function-wrapper.h rename to module/src/main/cpp/Dobby/source/InterceptRouting/Routing/FunctionWrapper/function-wrapper.h index e3d1e4bc..29bf5496 100644 --- a/module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/FunctionWrapper/function-wrapper.h +++ b/module/src/main/cpp/Dobby/source/InterceptRouting/Routing/FunctionWrapper/function-wrapper.h @@ -22,7 +22,7 @@ class FunctionWrapperRouting : public InterceptRouting { FunctionWrapperRouting(HookEntry *entry) : InterceptRouting(entry) { } - void Dispatch(); + void DispatchRouting(); void *GetTrampolineTarget(); diff --git a/module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/FunctionWrapper/intercept_routing_handler.cc b/module/src/main/cpp/Dobby/source/InterceptRouting/Routing/FunctionWrapper/intercept_routing_handler.cc similarity index 89% rename from module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/FunctionWrapper/intercept_routing_handler.cc rename to module/src/main/cpp/Dobby/source/InterceptRouting/Routing/FunctionWrapper/intercept_routing_handler.cc index 28159e28..189e2206 100644 --- a/module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/FunctionWrapper/intercept_routing_handler.cc +++ b/module/src/main/cpp/Dobby/source/InterceptRouting/Routing/FunctionWrapper/intercept_routing_handler.cc @@ -10,7 +10,7 @@ #include "MultiThreadSupport/ThreadSupport.h" -#include "TrampolineBridge/ClosureTrampolineBridge/closure-trampoline-common-handler.h" +#include "TrampolineBridge/ClosureTrampolineBridge/common-bridge-handler.h" void pre_call_forward_handler(RegisterContext *ctx, HookEntry *entry) { FunctionWrapperRouting *route = (FunctionWrapperRouting *)entry->route; @@ -21,11 +21,11 @@ void pre_call_forward_handler(RegisterContext *ctx, HookEntry *entry) { // run the `pre_call` before execute origin function which has been relocated(fixed) if (route->pre_call) { - PreCallTy pre_call; + PreCallTy pre_call; HookEntryInfo entry_info; - entry_info.hook_id = entry->id; + entry_info.hook_id = entry->id; entry_info.target_address = entry->target_address; - pre_call = route->pre_call; + pre_call = route->pre_call; // run the pre_call with the power of accessing all registers (*pre_call)(ctx, (const HookEntryInfo *)&entry_info); } @@ -48,11 +48,11 @@ void post_call_forward_handler(RegisterContext *ctx, HookEntry *entry) { // run the `post_call`, and access all the register value, as the origin function done, if (route->post_call) { - PostCallTy post_call; + PostCallTy post_call; HookEntryInfo entry_info; - entry_info.hook_id = entry->id; + entry_info.hook_id = entry->id; entry_info.target_address = entry->target_address; - post_call = route->post_call; + post_call = route->post_call; // run the post_call with the power of accessing all registers (*post_call)(ctx, (const HookEntryInfo *)&entry_info); diff --git a/module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/FunctionWrapper/intercept_routing_handler.h b/module/src/main/cpp/Dobby/source/InterceptRouting/Routing/FunctionWrapper/intercept_routing_handler.h similarity index 100% rename from module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/FunctionWrapper/intercept_routing_handler.h rename to module/src/main/cpp/Dobby/source/InterceptRouting/Routing/FunctionWrapper/intercept_routing_handler.h diff --git a/module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/FunctionInlineReplace/function-inline-replace.cc b/module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/FunctionInlineReplace/function-inline-replace.cc deleted file mode 100644 index 7d87a2c4..00000000 --- a/module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/FunctionInlineReplace/function-inline-replace.cc +++ /dev/null @@ -1,24 +0,0 @@ -#include "InterceptRouting/RoutingPlugin/FunctionInlineReplace/function-inline-replace.h" - -#include "dobby_internal.h" - -void FunctionInlineReplaceRouting::Dispatch() { - Prepare(); - BuildReplaceRouting(); -} - -void FunctionInlineReplaceRouting::BuildReplaceRouting() { - // direct => replace call - this->SetTrampolineTarget(this->replace_call); - DLOG(0, "Set trampoline target => %p", GetTrampolineTarget()); - - GenerateTrampolineBuffer(entry_->target_address, GetTrampolineTarget()); - - GenerateRelocatedCode(); -} - -#if 0 -void *FunctionInlineReplaceRouting::GetTrampolineTarget() { - return this->replace_call; -} -#endif diff --git a/module/src/main/cpp/Dobby/source/InterceptRouting/ExtraInternalPlugin/NearBranchTrampoline/NeaBranchTrampoline.cc b/module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/NearBranchTrampoline/NeaBranchTrampoline.cc similarity index 64% rename from module/src/main/cpp/Dobby/source/InterceptRouting/ExtraInternalPlugin/NearBranchTrampoline/NeaBranchTrampoline.cc rename to module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/NearBranchTrampoline/NeaBranchTrampoline.cc index 6e8ff772..0b836de5 100644 --- a/module/src/main/cpp/Dobby/source/InterceptRouting/ExtraInternalPlugin/NearBranchTrampoline/NeaBranchTrampoline.cc +++ b/module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/NearBranchTrampoline/NeaBranchTrampoline.cc @@ -1,23 +1,23 @@ -#include "InterceptRouting/ExtraInternalPlugin/NearBranchTrampoline/NearBranchTrampoline.h" +#include "InterceptRouting/RoutingPlugin/NearBranchTrampoline/NearBranchTrampoline.h" #include "dobby_internal.h" #include "MemoryAllocator/NearMemoryArena.h" -#include "InterceptRouting/ExtraInternalPlugin/RegisterPlugin.h" +#include "InterceptRouting/RoutingPlugin/RoutingPlugin.h" using namespace zz; PUBLIC void dobby_enable_near_branch_trampoline() { - RoutingPlugin *plugin = new NearBranchTrampolinePlugin; - ExtraInternalPlugin::registerPlugin("near_branch_trampoline", plugin); - ExtraInternalPlugin::near_branch_trampoline = plugin; + RoutingPluginInterface *plugin = new NearBranchTrampolinePlugin; + RoutingPluginManager::registerPlugin("near_branch_trampoline", plugin); + RoutingPluginManager::near_branch_trampoline = plugin; } PUBLIC void dobby_disable_near_branch_trampoline() { - NearBranchTrampolinePlugin *plugin = (NearBranchTrampolinePlugin *)ExtraInternalPlugin::near_branch_trampoline; + NearBranchTrampolinePlugin *plugin = (NearBranchTrampolinePlugin *)RoutingPluginManager::near_branch_trampoline; delete plugin; - ExtraInternalPlugin::near_branch_trampoline = NULL; + RoutingPluginManager::near_branch_trampoline = NULL; } #if 0 @@ -42,9 +42,9 @@ bool NearBranchTrampolinePlugin::GenerateTrampolineBuffer(InterceptRouting *rout // generate trampoline, patch the original entry bool NearBranchTrampolinePlugin::Active(InterceptRouting *routing) { - addr_t src, dst; + addr_t src, dst; HookEntry *entry = routing->GetHookEntry(); - src = (addr_t)entry->target_address; - dst = (addr_t)routing->GetTrampolineTarget(); + src = (addr_t)entry->target_address; + dst = (addr_t)routing->GetTrampolineTarget(); return true; } diff --git a/module/src/main/cpp/Dobby/source/InterceptRouting/ExtraInternalPlugin/NearBranchTrampoline/NearBranchTrampoline.h b/module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/NearBranchTrampoline/NearBranchTrampoline.h similarity index 74% rename from module/src/main/cpp/Dobby/source/InterceptRouting/ExtraInternalPlugin/NearBranchTrampoline/NearBranchTrampoline.h rename to module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/NearBranchTrampoline/NearBranchTrampoline.h index 333439a2..6ac6b72e 100644 --- a/module/src/main/cpp/Dobby/source/InterceptRouting/ExtraInternalPlugin/NearBranchTrampoline/NearBranchTrampoline.h +++ b/module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/NearBranchTrampoline/NearBranchTrampoline.h @@ -3,9 +3,9 @@ #include "dobby_internal.h" -#include "InterceptRouting/ExtraInternalPlugin/RegisterPlugin.h" +#include "InterceptRouting/RoutingPlugin/RoutingPlugin.h" -class NearBranchTrampolinePlugin : public RoutingPlugin { +class NearBranchTrampolinePlugin : public RoutingPluginInterface { // @Return: if false will continue to iter next plugin bool Prepare(InterceptRouting *routing) { return false; @@ -14,7 +14,6 @@ class NearBranchTrampolinePlugin : public RoutingPlugin { bool Active(InterceptRouting *routing); bool GenerateTrampolineBuffer(InterceptRouting *routing, void *src, void *dst); - }; #endif diff --git a/module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/RoutingPlugin.cc b/module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/RoutingPlugin.cc new file mode 100644 index 00000000..39842115 --- /dev/null +++ b/module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/RoutingPlugin.cc @@ -0,0 +1,15 @@ +#include "InterceptRouting/RoutingPlugin/RoutingPlugin.h" + +LiteMutableArray *RoutingPluginManager::plugins; + +RoutingPluginInterface *RoutingPluginManager::near_branch_trampoline = NULL; + +void RoutingPluginManager::registerPlugin(const char *name, RoutingPluginInterface *plugin) { + DLOG(0, "register %s plugin", name); + + if (RoutingPluginManager::plugins == NULL) { + RoutingPluginManager::plugins = new LiteMutableArray(8); + } + + RoutingPluginManager::plugins->pushObject(reinterpret_cast(plugin)); +} diff --git a/module/src/main/cpp/Dobby/source/InterceptRouting/ExtraInternalPlugin/RegisterPlugin.h b/module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/RoutingPlugin.h similarity index 71% rename from module/src/main/cpp/Dobby/source/InterceptRouting/ExtraInternalPlugin/RegisterPlugin.h rename to module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/RoutingPlugin.h index 121354c3..b653a16a 100644 --- a/module/src/main/cpp/Dobby/source/InterceptRouting/ExtraInternalPlugin/RegisterPlugin.h +++ b/module/src/main/cpp/Dobby/source/InterceptRouting/RoutingPlugin/RoutingPlugin.h @@ -5,20 +5,7 @@ #include "InterceptRouting/InterceptRouting.h" -// Internal Plugin -class ExtraInternalPlugin { -public: - static void registerPlugin(const char *name, ExtraInternalPlugin *plugin); - -public: - // global plugin array - static LiteMutableArray *plugins; - - static ExtraInternalPlugin *near_branch_trampoline; -}; - -// Plugin for Intercept Routing -class RoutingPlugin : public ExtraInternalPlugin { +class RoutingPluginInterface { public: // @Return: if false will continue to iter next plugin virtual bool Prepare(InterceptRouting *routing) = 0; @@ -33,4 +20,17 @@ class RoutingPlugin : public ExtraInternalPlugin { char name_[256]; }; +class RoutingPluginManager { +public: + static void registerPlugin(const char *name, RoutingPluginInterface *plugin); + +public: + // global plugin array + static LiteMutableArray *plugins; + + static RoutingPluginInterface *near_branch_trampoline; +}; + + + #endif \ No newline at end of file diff --git a/module/src/main/cpp/Dobby/source/Interceptor.cpp b/module/src/main/cpp/Dobby/source/Interceptor.cpp index 2ba05b54..7b5f4c8a 100644 --- a/module/src/main/cpp/Dobby/source/Interceptor.cpp +++ b/module/src/main/cpp/Dobby/source/Interceptor.cpp @@ -2,59 +2,69 @@ #include "dobby_internal.h" -Interceptor * Interceptor::priv_interceptor_ = nullptr; +Interceptor *Interceptor::priv_interceptor_ = nullptr; -Interceptor *Interceptor::SharedInstance() { - if (Interceptor::priv_interceptor_ == NULL) { - Interceptor::priv_interceptor_ = new Interceptor(); +Interceptor *Interceptor::SharedInstance() { + if (Interceptor::priv_interceptor_ == nullptr) { + Interceptor::priv_interceptor_ = new Interceptor(); INIT_LIST_HEAD(&Interceptor::priv_interceptor_->hook_entry_list_); } return Interceptor::priv_interceptor_; } -HookEntryListNode *Interceptor::FindHookEntryNode(void *address) { - HookEntry *entry = NULL; - - struct list_head *node = NULL; - for (node = hook_entry_list_.next; node != &hook_entry_list_; node = node->next) { - if(((HookEntryListNode *)node)->info.target_address == address) { - return (HookEntryListNode *)node; +HookEntryNode *Interceptor::find_hook_entry_node(void *address) { + HookEntryNode *entry_node = nullptr; +#if defined(_MSC_VER) +#if 0 // only valid if offsetof(HookEntryNode, list_node) == 0 + for(entry_node = (HookEntryNode *)hook_entry_list_.next; &entry_node->list_node != &hook_entry_list_; entry_node = (HookEntryNode *)entry_node->list_node.next); +#endif + struct list_head *list_node = nullptr; + for(list_node = hook_entry_list_.next; list_node != &hook_entry_list_; list_node = list_node->next) { + entry_node = (HookEntryNode *)((char *)list_node - offsetof(HookEntryNode, list_node)); +#else + list_for_each_entry(entry_node, &hook_entry_list_, list_node) { +#endif + HookEntry *entry = entry_node->entry; + if (entry->instruction_address == address) { + return entry_node; } } - - return NULL; + return nullptr; } HookEntry *Interceptor::FindHookEntry(void *address) { - HookEntryListNode *node = NULL; - node = FindHookEntryNode(address); - if(node) - return &node->info; + HookEntryNode *entry_node = nullptr; + entry_node = find_hook_entry_node(address); + if (entry_node) { + return entry_node->entry; + } - return NULL; + return nullptr; } - - void Interceptor::AddHookEntry(HookEntry *entry) { - HookEntryListNode *node = new HookEntryListNode ; - node->info = *entry; - list_add((struct list_head *)node, &hook_entry_list_); + HookEntryNode *entry_node = new HookEntryNode; + entry_node->entry = entry; + + list_add(&entry_node->list_node, &hook_entry_list_); } void Interceptor::RemoveHookEntry(void *address) { - HookEntryListNode *node = NULL; - node = FindHookEntryNode(address); - if(node) { - list_del((struct list_head *)node); + if (HookEntryNode *entry_node = find_hook_entry_node(address)) { + list_del(&entry_node->list_node); } } int Interceptor::GetHookEntryCount() { int count = 0; - - struct list_head *node = &hook_entry_list_; - while((node = node->next) != &hook_entry_list_) { + HookEntryNode *entry_node = nullptr; +#if defined(_MSC_VER) + struct list_head *list_node = nullptr; + for(list_node = hook_entry_list_.next; list_node != &hook_entry_list_; list_node = list_node->next) { + entry_node = (HookEntryNode *)((char *)list_node - offsetof(HookEntryNode, list_node)); +#else + list_for_each_entry(entry_node, &hook_entry_list_, list_node) { +#endif count += 1; } return count; diff --git a/module/src/main/cpp/Dobby/source/Interceptor.h b/module/src/main/cpp/Dobby/source/Interceptor.h index fcdc43bb..2c5afb0e 100644 --- a/module/src/main/cpp/Dobby/source/Interceptor.h +++ b/module/src/main/cpp/Dobby/source/Interceptor.h @@ -3,57 +3,12 @@ #include "dobby_internal.h" -// List utilty - -struct list_head { - struct list_head *next; - struct list_head *prev; -}; -#define container_of(ptr, type, member) \ - ({ \ - const __typeof(((type *)0)->member) *__mptr = (ptr); \ - (type *)((char *)__mptr - offsetof(type, member)); \ - }) - -#define list_entry(ptr, type, member) container_of(ptr, type, member) - -#define INIT_LIST_HEAD(ptr) \ - do { \ - (ptr)->next = (ptr); \ - (ptr)->prev = (ptr); \ - } while (0) - -static inline int list_empty(struct list_head *head) -{ - return head->next == head; -} - -static void __list_add(struct list_head *new_node, struct list_head *prev, struct list_head *next) { - next->prev = new_node; - new_node->next = next; - new_node->prev = prev; - prev->next = new_node; -} - -static inline void list_add(struct list_head *new_node, struct list_head *head) { - __list_add(new_node, head, head->next); -} - -static inline void __list_del(struct list_head *prev, struct list_head *next) { - next->prev = prev; - prev->next = next; -} - -static inline void list_del(struct list_head *entry) { - __list_del(entry->prev, entry->next); - entry->next = NULL; - entry->prev = NULL; -} +#include "include/list_structure.h" typedef struct { - struct list_head list; - HookEntry info; -} HookEntryListNode; + struct list_head list_node; + HookEntry *entry; +} HookEntryNode; class Interceptor { public: @@ -71,7 +26,7 @@ class Interceptor { Interceptor() { } - HookEntryListNode *FindHookEntryNode(void *address); + HookEntryNode *find_hook_entry_node(void *address); private: struct list_head hook_entry_list_; diff --git a/module/src/main/cpp/Dobby/source/MemoryAllocator/AssemblyCodeBuilder.cc b/module/src/main/cpp/Dobby/source/MemoryAllocator/AssemblyCodeBuilder.cc index 3c2339e9..2e123a6a 100644 --- a/module/src/main/cpp/Dobby/source/MemoryAllocator/AssemblyCodeBuilder.cc +++ b/module/src/main/cpp/Dobby/source/MemoryAllocator/AssemblyCodeBuilder.cc @@ -5,7 +5,7 @@ AssemblyCodeChunk *AssemblyCodeBuilder::FinalizeFromAddress(addr_t address, int size) { AssemblyCodeChunk *result = NULL; - result = new AssemblyCodeChunk; + result = new AssemblyCodeChunk; result->init_region_range(address, size); return result; } @@ -13,14 +13,14 @@ AssemblyCodeChunk *AssemblyCodeBuilder::FinalizeFromAddress(addr_t address, int AssemblyCodeChunk *AssemblyCodeBuilder::FinalizeFromTurboAssembler(AssemblerBase *assembler) { AssemblyCodeChunk *result = NULL; - CodeBufferBase *code_buffer =NULL; - code_buffer = (CodeBufferBase *)assembler->GetCodeBuffer(); + CodeBufferBase *buffer = NULL; + buffer = (CodeBufferBase *)assembler->GetCodeBuffer(); void *realized_address = assembler->GetRealizedAddress(); if (realized_address == NULL) { int buffer_size = 0; { - buffer_size = code_buffer->getSize(); + buffer_size = buffer->getSize(); #if TARGET_ARCH_ARM64 || TARGET_ARCH_ARM // FIXME: need it ? actually ??? // extra bytes for align needed @@ -36,12 +36,12 @@ AssemblyCodeChunk *AssemblyCodeBuilder::FinalizeFromTurboAssembler(AssemblerBase realized_address = (void *)result->raw_instruction_start(); assembler->SetRealizedAddress(realized_address); } else { - result = AssemblyCodeBuilder::FinalizeFromAddress((addr_t)realized_address, code_buffer->getSize()); + result = AssemblyCodeBuilder::FinalizeFromAddress((addr_t)realized_address, buffer->getSize()); } // Realize(Relocate) the buffer_code to the executable_memory_address, remove the ExternalLabels, etc, the pc-relative // instructions - CodePatch(realized_address, (uint8_t *)code_buffer->getRawBuffer(), code_buffer->getSize()); + CodePatch(realized_address, (uint8_t *)buffer->getRawBuffer(), buffer->getSize()); return result; } \ No newline at end of file diff --git a/module/src/main/cpp/Dobby/source/MemoryAllocator/CodeBuffer/code-buffer-arm.cc b/module/src/main/cpp/Dobby/source/MemoryAllocator/CodeBuffer/code-buffer-arm.cc index 500a7a10..7d985c2d 100644 --- a/module/src/main/cpp/Dobby/source/MemoryAllocator/CodeBuffer/code-buffer-arm.cc +++ b/module/src/main/cpp/Dobby/source/MemoryAllocator/CodeBuffer/code-buffer-arm.cc @@ -1,11 +1,10 @@ -#include "common/macros/platform_macro.h" +#include "platform_macro.h" #if defined(TARGET_ARCH_ARM) #include #include "MemoryAllocator/CodeBuffer/code-buffer-arm.h" - arm_inst_t CodeBuffer::LoadARMInst(int offset) { return *reinterpret_cast(buffer + offset); } diff --git a/module/src/main/cpp/Dobby/source/MemoryAllocator/CodeBuffer/code-buffer-arm64.cc b/module/src/main/cpp/Dobby/source/MemoryAllocator/CodeBuffer/code-buffer-arm64.cc index 01e8302f..cea9be1e 100644 --- a/module/src/main/cpp/Dobby/source/MemoryAllocator/CodeBuffer/code-buffer-arm64.cc +++ b/module/src/main/cpp/Dobby/source/MemoryAllocator/CodeBuffer/code-buffer-arm64.cc @@ -1,4 +1,4 @@ -#include "common/macros/platform_macro.h" +#include "platform_macro.h" #if defined(TARGET_ARCH_ARM64) #include "MemoryAllocator/CodeBuffer/code-buffer-arm64.h" diff --git a/module/src/main/cpp/Dobby/source/MemoryAllocator/CodeBuffer/code-buffer-x64.cc b/module/src/main/cpp/Dobby/source/MemoryAllocator/CodeBuffer/code-buffer-x64.cc index 30016d4d..0c7615c4 100644 --- a/module/src/main/cpp/Dobby/source/MemoryAllocator/CodeBuffer/code-buffer-x64.cc +++ b/module/src/main/cpp/Dobby/source/MemoryAllocator/CodeBuffer/code-buffer-x64.cc @@ -1,4 +1,4 @@ -#include "common/macros/platform_macro.h" +#include "platform_macro.h" #if defined(TARGET_ARCH_X64) #include "MemoryAllocator/CodeBuffer/code-buffer-x64.h" diff --git a/module/src/main/cpp/Dobby/source/MemoryAllocator/CodeBuffer/code-buffer-x86.cc b/module/src/main/cpp/Dobby/source/MemoryAllocator/CodeBuffer/code-buffer-x86.cc index 6fbeb5f0..1f2c04bd 100644 --- a/module/src/main/cpp/Dobby/source/MemoryAllocator/CodeBuffer/code-buffer-x86.cc +++ b/module/src/main/cpp/Dobby/source/MemoryAllocator/CodeBuffer/code-buffer-x86.cc @@ -1,4 +1,4 @@ -#include "common/macros/platform_macro.h" +#include "platform_macro.h" #if defined(TARGET_ARCH_IA32) #include "MemoryAllocator/CodeBuffer/code-buffer-x86.h" diff --git a/module/src/main/cpp/Dobby/source/MemoryAllocator/MemoryArena.cc b/module/src/main/cpp/Dobby/source/MemoryAllocator/MemoryArena.cc index 857dfeb1..05fe6c74 100644 --- a/module/src/main/cpp/Dobby/source/MemoryAllocator/MemoryArena.cc +++ b/module/src/main/cpp/Dobby/source/MemoryAllocator/MemoryArena.cc @@ -16,7 +16,7 @@ MemoryChunk *MemoryArena::AllocateChunk(int alloc_size, MemoryPermission permiss } LiteCollectionIterator iter(page_chunks); - PageChunk * page = NULL; + PageChunk *page = NULL; while ((page = reinterpret_cast(iter.getNextObject())) != NULL) { if (page->permission == permission) { // check the page remain space is enough for the new chunk @@ -28,28 +28,28 @@ MemoryChunk *MemoryArena::AllocateChunk(int alloc_size, MemoryPermission permiss // alloc a new executable page. if (!page) { - int pageSize = OSMemory::PageSize(); + int pageSize = OSMemory::PageSize(); void *pageAddress = OSMemory::Allocate(NULL, pageSize, permission); if (pageAddress == NULL) { ERROR_LOG("Failed to alloc page"); return NULL; } - PageChunk *newPage = new PageChunk; + PageChunk *newPage = new PageChunk; newPage->page.address = pageAddress; - newPage->page.length = pageSize; - newPage->page_cursor = (addr_t)pageAddress; - newPage->permission = permission; - newPage->chunks = new LiteMutableArray(8); + newPage->page.length = pageSize; + newPage->page_cursor = (addr_t)pageAddress; + newPage->permission = permission; + newPage->chunks = new LiteMutableArray(8); MemoryArena::page_chunks->pushObject(reinterpret_cast(newPage)); page = newPage; } MemoryChunk *chunk = NULL; if (page) { - chunk = new MemoryChunk; + chunk = new MemoryChunk; chunk->address = (void *)page->page_cursor; - chunk->length = alloc_size; + chunk->length = alloc_size; // update page cursor page->chunks->pushObject(reinterpret_cast(chunk)); diff --git a/module/src/main/cpp/Dobby/source/MemoryAllocator/MemoryArena.h b/module/src/main/cpp/Dobby/source/MemoryAllocator/MemoryArena.h index 6aa0bd16..0679b834 100644 --- a/module/src/main/cpp/Dobby/source/MemoryAllocator/MemoryArena.h +++ b/module/src/main/cpp/Dobby/source/MemoryAllocator/MemoryArena.h @@ -6,9 +6,9 @@ #include "PlatformUnifiedInterface/StdMemory.h" struct MemoryChunk : MemoryRange { - inline void init_region_range(addr_t address, int size) { + inline void init_region_range(addr_t address, size_t size) { this->address = (void *)address; - this->length = size; + this->length = size; } inline void re_init_region_range(addr_t address, int size) { @@ -31,9 +31,9 @@ struct MemoryChunk : MemoryRange { typedef MemoryChunk AssemblyCodeChunk, WritableDataChunk; typedef struct { - MemoryChunk page; - addr_t page_cursor; - MemoryPermission permission; + MemoryChunk page; + addr_t page_cursor; + MemoryPermission permission; LiteMutableArray *chunks; } PageChunk; diff --git a/module/src/main/cpp/Dobby/source/MemoryAllocator/NearMemoryArena.cc b/module/src/main/cpp/Dobby/source/MemoryAllocator/NearMemoryArena.cc index 641d718f..a635ff94 100644 --- a/module/src/main/cpp/Dobby/source/MemoryAllocator/NearMemoryArena.cc +++ b/module/src/main/cpp/Dobby/source/MemoryAllocator/NearMemoryArena.cc @@ -15,14 +15,63 @@ using namespace zz; LiteMutableArray *NearMemoryArena::page_chunks; +#if defined(WIN32) +static const void *memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen) { + if (!haystack || !needle) { + return haystack; + } else { + const char *h = (const char *)haystack; + const char *n = (const char *)needle; + size_t l = needlelen; + const char *r = h; + while (l && (l <= haystacklen)) { + if (*n++ != *h++) { + r = h; + n = (const char *)needle; + l = needlelen; + } else { + --l; + } + --haystacklen; + } + return l ? NULL : r; + } +} +#endif + +static addr_t addr_max(addr_t a, addr_t b) { + return a > b ? a : b; +} + +static addr_t addr_sub(addr_t a, addr_t b) { + return a > a - b ? a - b : 0; +} + +static addr_t addr_add(addr_t a, addr_t b) { + return a < a + b ? a + b : (addr_t)-1; +} + +static addr_t prev_page(addr_t cur, int pagesize) { + addr_t aligned_addr = ALIGN(cur, pagesize); + addr_t ret = aligned_addr - pagesize; + return ret <= aligned_addr ? ret : aligned_addr; +} + +static addr_t next_page(addr_t cur, int pagesize) { + addr_t aligned_addr = ALIGN(cur, pagesize); + addr_t ret = aligned_addr + pagesize; + return ret >= aligned_addr ? ret : aligned_addr; +} + #if 1 static addr_t search_near_blank_page(addr_t pos, size_t alloc_range) { addr_t min_page_addr, max_page_addr; - min_page_addr = ALIGN((pos - alloc_range), OSMemory::PageSize()) + OSMemory::PageSize(); - max_page_addr = ALIGN((pos + alloc_range), OSMemory::PageSize()) - OSMemory::PageSize(); + min_page_addr = next_page(addr_sub(pos, alloc_range), OSMemory::AllocPageSize()); + max_page_addr = prev_page(addr_add(pos, alloc_range), OSMemory::AllocPageSize()); // region.start sorted std::vector process_memory_layout = ProcessRuntimeUtility::GetProcessMemoryLayout(); + assert(process_memory_layout.size() > 0); /* * min_page_addr/--special-blank--/==region==/--right-blank--/max_page_addr @@ -33,20 +82,20 @@ static addr_t search_near_blank_page(addr_t pos, size_t alloc_range) { // check first region addr_t first_region_start = (addr_t)process_memory_layout[0].address; if (min_page_addr < first_region_start) { - resultPageAddr = first_region_start - OSMemory::PageSize(); + resultPageAddr = prev_page(first_region_start, OSMemory::AllocPageSize()); resultPageAddr = - (addr_t)OSMemory::Allocate((void *)assumePageAddr, OSMemory::PageSize(), MemoryPermission::kReadExecute); + (addr_t)OSMemory::Allocate((void *)assumePageAddr, OSMemory::AllocPageSize(), MemoryPermission::kReadExecute); if (resultPageAddr) return resultPageAddr; } // check last region - MemoryRegion last_region = process_memory_layout[process_memory_layout.size() - 1]; - addr_t last_region_end = (addr_t)last_region.address + last_region.length; + MemoryRegion last_region = process_memory_layout[process_memory_layout.size() - 1]; + addr_t last_region_end = (addr_t)last_region.address + last_region.length; if (max_page_addr < last_region_end) { - resultPageAddr = last_region_end + OSMemory::PageSize(); + resultPageAddr = next_page(last_region_end, OSMemory::AllocPageSize()); resultPageAddr = - (addr_t)OSMemory::Allocate((void *)assumePageAddr, OSMemory::PageSize(), MemoryPermission::kReadExecute); + (addr_t)OSMemory::Allocate((void *)assumePageAddr, OSMemory::AllocPageSize(), MemoryPermission::kReadExecute); if (resultPageAddr) return resultPageAddr; } @@ -54,36 +103,39 @@ static addr_t search_near_blank_page(addr_t pos, size_t alloc_range) { for (int i = 0; i < process_memory_layout.size(); ++i) { MemoryRegion region = process_memory_layout[i]; // check if assume-page-addr in memory-layout - addr_t region_end = (addr_t)region.address + region.length; + addr_t region_end = (addr_t)region.address + region.length; addr_t region_start = (addr_t)region.address; if (region_end < max_page_addr) { if (region_start >= min_page_addr) { // find the region locate in the [min_page_addr, max_page_addr] - if (assumePageAddr == min_page_addr) { + if (i >= 1 && assumePageAddr == min_page_addr) { MemoryRegion prev_region; - prev_region = process_memory_layout[i - 1]; - addr_t prev_region_end = (addr_t)prev_region.address + prev_region.length; + prev_region = process_memory_layout[i - 1]; + addr_t prev_region_end = + next_page((addr_t)prev_region.address + prev_region.length, OSMemory::AllocPageSize()); // check if have blank cave page if (region_start > prev_region_end) { - assumePageAddr = min_page_addr > prev_region_end ? min_page_addr : prev_region_end; - resultPageAddr = (addr_t)OSMemory::Allocate((void *)assumePageAddr, OSMemory::PageSize(), + assumePageAddr = addr_max(min_page_addr, prev_region_end); + resultPageAddr = (addr_t)OSMemory::Allocate((void *)assumePageAddr, OSMemory::AllocPageSize(), MemoryPermission::kReadExecute); if (resultPageAddr) break; } } - // right-blank - MemoryRegion next_region = process_memory_layout[i + 1]; - // check if have blank cave page - if (region_end < (addr_t)next_region.address) { - assumePageAddr = (addr_t)region.address + region.length; - resultPageAddr = - (addr_t)OSMemory::Allocate((void *)assumePageAddr, OSMemory::PageSize(), MemoryPermission::kReadExecute); - if (resultPageAddr) - break; + if (i <= process_memory_layout.size() - 2) { + // right-blank + MemoryRegion next_region = process_memory_layout[i + 1]; + // check if have blank cave page + if (region_end < (addr_t)next_region.address) { + assumePageAddr = next_page((addr_t)region.address + region.length, OSMemory::AllocPageSize()); + resultPageAddr = (addr_t)OSMemory::Allocate((void *)assumePageAddr, OSMemory::AllocPageSize(), + MemoryPermission::kReadExecute); + if (resultPageAddr) + break; + } } } } @@ -96,8 +148,8 @@ NearMemoryArena::NearMemoryArena() { static addr_t search_near_blank_memory_chunk(addr_t pos, size_t alloc_range, int alloc_size) { addr_t min_page_addr, max_page_addr; - min_page_addr = ALIGN((pos - alloc_range), OSMemory::PageSize()) + OSMemory::PageSize(); - max_page_addr = ALIGN((pos + alloc_range), OSMemory::PageSize()) - OSMemory::PageSize(); + min_page_addr = next_page(addr_sub(pos, alloc_range), OSMemory::AllocPageSize()); + max_page_addr = prev_page(addr_add(pos, alloc_range), OSMemory::AllocPageSize()); std::vector process_memory_layout = ProcessRuntimeUtility::GetProcessMemoryLayout(); @@ -134,13 +186,15 @@ static addr_t search_near_blank_memory_chunk(addr_t pos, size_t alloc_range, int } #endif +#define NEAR_PAGE_ARRAYLEN 8 + int NearMemoryArena::PushPage(addr_t page_addr, MemoryPermission permission) { - PageChunk *newPage = new PageChunk; + PageChunk *newPage = new PageChunk; newPage->page.address = (void *)page_addr; - newPage->page.length = OSMemory::PageSize(); - newPage->page_cursor = page_addr; - newPage->permission = permission; - newPage->chunks = new LiteMutableArray(8); + newPage->page.length = OSMemory::PageSize(); + newPage->page_cursor = page_addr; + newPage->permission = permission; + newPage->chunks = new LiteMutableArray(NEAR_PAGE_ARRAYLEN); NearMemoryArena::page_chunks->pushObject(reinterpret_cast(newPage)); return RT_SUCCESS; } @@ -157,13 +211,13 @@ MemoryChunk *NearMemoryArena::AllocateChunk(addr_t position, size_t alloc_range, MemoryPermission permission) { if (page_chunks == NULL) { - page_chunks = new LiteMutableArray(8); + page_chunks = new LiteMutableArray(NEAR_PAGE_ARRAYLEN); } MemoryChunk *result = NULL; search_once_more: LiteCollectionIterator iter(NearMemoryArena::page_chunks); - PageChunk * page = NULL; + PageChunk *page = NULL; while ((page = reinterpret_cast(iter.getNextObject())) != NULL) { if (page->permission == permission) { if (llabs((intptr_t)(page->page_cursor - position)) < alloc_range) { @@ -176,9 +230,9 @@ MemoryChunk *NearMemoryArena::AllocateChunk(addr_t position, size_t alloc_range, MemoryChunk *chunk = NULL; if (page) { - chunk = new MemoryChunk; + chunk = new MemoryChunk; chunk->address = (void *)page->page_cursor; - chunk->length = alloc_size; + chunk->length = alloc_size; // update page cursor page->chunks->pushObject(reinterpret_cast(chunk)); @@ -187,7 +241,7 @@ MemoryChunk *NearMemoryArena::AllocateChunk(addr_t position, size_t alloc_range, } addr_t blank_page_addr = 0; - blank_page_addr = search_near_blank_page(position, alloc_range); + blank_page_addr = search_near_blank_page(position, alloc_range); if (blank_page_addr) { OSMemory::SetPermission((void *)blank_page_addr, OSMemory::PageSize(), permission); NearMemoryArena::PushPage(blank_page_addr, permission); @@ -200,12 +254,12 @@ MemoryChunk *NearMemoryArena::AllocateChunk(addr_t position, size_t alloc_range, } addr_t blank_chunk_addr = 0; - blank_chunk_addr = search_near_blank_memory_chunk(position, alloc_range, alloc_size); + blank_chunk_addr = search_near_blank_memory_chunk(position, alloc_range, alloc_size); if (blank_chunk_addr) { MemoryChunk *chunk = NULL; - chunk = new MemoryChunk; - chunk->address = (void *)blank_chunk_addr; - chunk->length = alloc_size; + chunk = new MemoryChunk; + chunk->address = (void *)blank_chunk_addr; + chunk->length = alloc_size; return chunk; } diff --git a/module/src/main/cpp/Dobby/source/PlatformUnifiedInterface/ExecMemory/ClearCacheTool.h b/module/src/main/cpp/Dobby/source/PlatformUnifiedInterface/ExecMemory/ClearCacheTool.h index 604ddfc6..ee407cb9 100644 --- a/module/src/main/cpp/Dobby/source/PlatformUnifiedInterface/ExecMemory/ClearCacheTool.h +++ b/module/src/main/cpp/Dobby/source/PlatformUnifiedInterface/ExecMemory/ClearCacheTool.h @@ -1,6 +1,11 @@ -#ifndef PLATFORM_INTERFACE_CLEAR_CACHE_TOOL_H -#define PLATFORM_INTERFACE_CLEAR_CACHE_TOOL_H +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif void ClearCache(void *start, void *end); +#ifdef __cplusplus +} #endif \ No newline at end of file diff --git a/module/src/main/cpp/Dobby/source/PlatformUnifiedInterface/StdMemory.h b/module/src/main/cpp/Dobby/source/PlatformUnifiedInterface/StdMemory.h index e6b7a0f1..384f38cb 100644 --- a/module/src/main/cpp/Dobby/source/PlatformUnifiedInterface/StdMemory.h +++ b/module/src/main/cpp/Dobby/source/PlatformUnifiedInterface/StdMemory.h @@ -1,18 +1,18 @@ #ifndef UNIFIED_INTERFACE_STD_MEMORY_H #define UNIFIED_INTERFACE_STD_MEMORY_H -#include "common/headers/common_header.h" +#include "common_header.h" enum MemoryPermission { kNoAccess, kRead, kReadWrite, kReadWriteExecute, kReadExecute }; typedef struct _MemoryRange { - void * address; + void *address; size_t length; } MemoryRange; typedef struct _MemoryRegion { - void * address; - size_t length; + void *address; + size_t length; MemoryPermission permission; } MemoryRegion; diff --git a/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/AssemblyClosureTrampoline.h b/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/AssemblyClosureTrampoline.h index ff5b1e26..2c904ee4 100644 --- a/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/AssemblyClosureTrampoline.h +++ b/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/AssemblyClosureTrampoline.h @@ -3,25 +3,28 @@ #include "dobby_internal.h" -#include "xnucxx/LiteMutableArray.h" +#ifdef ENABLE_CLOSURE_TRAMPOLINE_TEMPLATE +#ifdef __cplusplus +extern "C" { +#endif //__cplusplus +void closure_trampoline_template(); +void closure_bridge_template(); +#ifdef __cplusplus +} +#endif //__cplusplus +#endif #ifdef __cplusplus extern "C" { #endif //__cplusplus typedef struct _ClosureTrampolineEntry { - void * carry_handler; - void * carry_data; - void * address; - uintptr_t size; + void *address; + int size; + void *carry_handler; + void *carry_data; } ClosureTrampolineEntry; -typedef void (*USER_CODE_CALL)(RegisterContext *ctx, ClosureTrampolineEntry *entry); - -void closure_trampoline_template(); - -void closure_bridge_template(); - void *get_closure_bridge(); #ifdef __cplusplus diff --git a/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/arm/ARMAssemblyClosureTrampoline.cc b/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/arm/ARMAssemblyClosureTrampoline.cc index cfbfdb62..f38e9266 100644 --- a/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/arm/ARMAssemblyClosureTrampoline.cc +++ b/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/arm/ARMAssemblyClosureTrampoline.cc @@ -1,4 +1,4 @@ -#include "common/macros/platform_macro.h" +#include "platform_macro.h" #if defined(TARGET_ARCH_ARM) #include "dobby_internal.h" @@ -11,14 +11,13 @@ using namespace zz; using namespace zz::arm; ClosureTrampolineEntry *ClosureTrampoline::CreateClosureTrampoline(void *carry_data, void *carry_handler) { - - ClosureTrampolineEntry *entry = new ClosureTrampolineEntry; + ClosureTrampolineEntry *entry = nullptr; + entry = new ClosureTrampolineEntry; #ifdef ENABLE_CLOSURE_TRAMPOLINE_TEMPLATE #define CLOSURE_TRAMPOLINE_SIZE (7 * 4) // use closure trampoline template code, find the executable memory and patch it. Code *code = Code::FinalizeCodeFromAddress(closure_trampoline_template, CLOSURE_TRAMPOLINE_SIZE); - #else // use assembler and codegen modules instead of template_code @@ -36,16 +35,15 @@ ClosureTrampolineEntry *ClosureTrampoline::CreateClosureTrampoline(void *carry_d _ PseudoBind(&forward_bridge_label); _ EmitAddress((uint32_t)get_closure_bridge()); - AssemblyCodeChunk *code = - AssemblyCodeBuilder::FinalizeFromTurboAssembler(reinterpret_cast(&turbo_assembler_)); + AssemblyCodeChunk *code = nullptr; + code = AssemblyCodeBuilder::FinalizeFromTurboAssembler(&turbo_assembler_); - entry->address = (void *)code->raw_instruction_start(); - entry->carry_data = carry_data; + entry->address = (void *)code->raw_instruction_start(); + entry->size = code->raw_instruction_size(); + entry->carry_data = carry_data; entry->carry_handler = carry_handler; - entry->size = code->raw_instruction_size(); delete code; - return entry; #endif } diff --git a/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/arm/closure-bridge-arm.cc b/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/arm/closure-bridge-arm.cc index c56de92c..9e10d953 100644 --- a/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/arm/closure-bridge-arm.cc +++ b/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/arm/closure-bridge-arm.cc @@ -1,11 +1,11 @@ -#include "common/macros/platform_macro.h" +#include "platform_macro.h" #if defined(TARGET_ARCH_ARM) #include "dobby_internal.h" #include "core/modules/assembler/assembler-arm.h" -#include "TrampolineBridge/ClosureTrampolineBridge/closure-trampoline-common-handler.h" +#include "TrampolineBridge/ClosureTrampolineBridge/common-bridge-handler.h" using namespace zz; using namespace zz::arm; @@ -80,9 +80,9 @@ void *get_closure_bridge() { _ mov(pc, Operand(r12)); AssemblyCodeChunk *code = AssemblyCodeBuilder::FinalizeFromTurboAssembler(&turbo_assembler_); - closure_bridge = (void *)code->raw_instruction_start(); + closure_bridge = (void *)code->raw_instruction_start(); - DLOG(1, "[closure bridge] Build the closure bridge at %p", closure_bridge); + DLOG(0, "[closure bridge] Build the closure bridge at %p", closure_bridge); #endif return (void *)closure_bridge; } diff --git a/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/arm/helper-arm.cc b/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/arm/helper-arm.cc index 41c1df74..1adb0519 100644 --- a/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/arm/helper-arm.cc +++ b/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/arm/helper-arm.cc @@ -1,4 +1,4 @@ -#include "common/macros/platform_macro.h" +#include "platform_macro.h" #if defined(TARGET_ARCH_ARM) #include "dobby_internal.h" diff --git a/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/arm64/ARM64AssemblyClosureTrampoline.cc b/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/arm64/ARM64AssemblyClosureTrampoline.cc index 1b7f031e..0ab57ec5 100644 --- a/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/arm64/ARM64AssemblyClosureTrampoline.cc +++ b/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/arm64/ARM64AssemblyClosureTrampoline.cc @@ -1,4 +1,4 @@ -#include "common/macros/platform_macro.h" +#include "platform_macro.h" #if defined(TARGET_ARCH_ARM64) #include "dobby_internal.h" @@ -7,8 +7,6 @@ #include "TrampolineBridge/ClosureTrampolineBridge/AssemblyClosureTrampoline.h" -extern void closure_trampoline_template(); - using namespace zz; using namespace zz::arm64; @@ -18,7 +16,8 @@ using namespace zz::arm64; // use assembler and codegen modules instead of template_code ClosureTrampolineEntry *ClosureTrampoline::CreateClosureTrampoline(void *carry_data, void *carry_handler) { - ClosureTrampolineEntry *entry = new ClosureTrampolineEntry; + ClosureTrampolineEntry *entry = nullptr; + entry = new ClosureTrampolineEntry; #define _ turbo_assembler_. TurboAssembler turbo_assembler_(0); @@ -49,13 +48,15 @@ ClosureTrampolineEntry *ClosureTrampoline::CreateClosureTrampoline(void *carry_d _ PseudoBind(&forward_bridge_label); _ EmitInt64((uint64_t)get_closure_bridge()); - AssemblyCodeChunk *code = - AssemblyCodeBuilder::FinalizeFromTurboAssembler(reinterpret_cast(&turbo_assembler_)); + AssemblyCodeChunk *code = nullptr; + code = AssemblyCodeBuilder::FinalizeFromTurboAssembler(reinterpret_cast(&turbo_assembler_)); - entry->address = (void *)code->raw_instruction_start(); - entry->carry_data = carry_data; + entry->address = (void *)code->raw_instruction_start(); + entry->size = code->raw_instruction_size(); + entry->carry_data = carry_data; entry->carry_handler = carry_handler; - entry->size = code->raw_instruction_size(); + + delete code; return entry; } diff --git a/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/arm64/closure-bridge-arm64.cc b/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/arm64/closure-bridge-arm64.cc index 0e53ef1d..d86aa2f1 100644 --- a/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/arm64/closure-bridge-arm64.cc +++ b/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/arm64/closure-bridge-arm64.cc @@ -1,4 +1,4 @@ -#include "common/macros/platform_macro.h" +#include "platform_macro.h" #if defined(TARGET_ARCH_ARM64) #include "dobby_internal.h" @@ -6,7 +6,7 @@ #include "core/modules/assembler/assembler.h" #include "core/modules/assembler/assembler-arm64.h" -#include "TrampolineBridge/ClosureTrampolineBridge/closure-trampoline-common-handler.h" +#include "TrampolineBridge/ClosureTrampolineBridge/common-bridge-handler.h" using namespace zz; using namespace zz::arm64; @@ -14,7 +14,6 @@ using namespace zz::arm64; static void *closure_bridge = NULL; void *get_closure_bridge() { - // if already initialized, just return. if (closure_bridge) return closure_bridge; @@ -25,8 +24,8 @@ void *get_closure_bridge() { closure_bridge = closure_bridge_template; // otherwise, use the Assembler build the closure_bridge #else -#define _ turbo_assembler_. -#define MEM(reg, offset) MemOperand(reg, offset) +#define _ turbo_assembler_. +#define MEM(reg, offset) MemOperand(reg, offset) #define MEM_EXT(reg, offset, addrmode) MemOperand(reg, offset, addrmode) TurboAssembler turbo_assembler_(0); @@ -81,7 +80,7 @@ void *get_closure_bridge() { _ add(TMP_REG_0, SP, 2 * 8); // closure trampoline reserved _ add(TMP_REG_0, TMP_REG_0, 2 * 8 + 30 * 8 + 8 * 16); // x0, x1-x30, q0-q7 reserved #if defined(FULL_FLOATING_POINT_REGISTER_PACK) - _ add(TMP_REG_0, TMP_REG_0, 24 * 16); // q8-q31 reserved + _ add(TMP_REG_0, TMP_REG_0, 24 * 16); // q8-q31 reserved #endif // alloc stack, store original sp @@ -150,9 +149,9 @@ void *get_closure_bridge() { _ ret(); // AKA br x30 AssemblyCodeChunk *code = AssemblyCodeBuilder::FinalizeFromTurboAssembler(&turbo_assembler_); - closure_bridge = (void *)code->raw_instruction_start(); + closure_bridge = (void *)code->raw_instruction_start(); - DLOG(1, "[closure bridge] Build the closure bridge at %p", closure_bridge); + DLOG(0, "[closure bridge] Build the closure bridge at %p", closure_bridge); #endif return (void *)closure_bridge; } diff --git a/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/arm64/helper-arm64.cc b/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/arm64/helper-arm64.cc index 3d219fc4..5ff5be48 100644 --- a/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/arm64/helper-arm64.cc +++ b/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/arm64/helper-arm64.cc @@ -1,4 +1,4 @@ -#include "common/macros/platform_macro.h" +#include "platform_macro.h" #if defined(TARGET_ARCH_ARM64) #include "core/modules/assembler/assembler-arm64.h" diff --git a/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/closure-trampoline-common-handler.cc b/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/closure-trampoline-common-handler.cc deleted file mode 100644 index 366dda7d..00000000 --- a/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/closure-trampoline-common-handler.cc +++ /dev/null @@ -1,28 +0,0 @@ - -#include "logging/logging.h" - -#include "TrampolineBridge/ClosureTrampolineBridge/closure-trampoline-common-handler.h" - -#if 0 -void get_routing_bridge_next_hop(RegisterContext *ctx, void *address) { -} - -void set_routing_bridge_next_hop(RegisterContext *ctx, void *address) { -} -#endif - -// Closure bridge branch here unitily, then common_bridge_handler will dispatch to other handler. -void intercept_routing_common_bridge_handler(RegisterContext *ctx, ClosureTrampolineEntry *entry) { - DLOG(0, "Catch common bridge handler, carry data: %p, carry handler: %p", (HookEntry *)entry->carry_data, - entry->carry_handler); - USER_CODE_CALL UserCodeCall = (USER_CODE_CALL)entry->carry_handler; - -#if __APPLE__ -#if __has_feature(ptrauth_calls) - UserCodeCall = (typeof(UserCodeCall))__builtin_ptrauth_sign_unauthenticated((void *)UserCodeCall, ptrauth_key_asia, 0); -#endif -#endif - - UserCodeCall(ctx, entry); - return; -} diff --git a/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/common-bridge-handler.cc b/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/common-bridge-handler.cc new file mode 100644 index 00000000..f50dc8d5 --- /dev/null +++ b/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/common-bridge-handler.cc @@ -0,0 +1,22 @@ + +#include "logging/logging.h" + +#include "TrampolineBridge/ClosureTrampolineBridge/common-bridge-handler.h" + +PUBLIC void intercept_routing_common_bridge_handler(RegisterContext *ctx, ClosureTrampolineEntry *entry) { + DLOG(0, "Catch common bridge handler, carry data: %p, carry handler: %p", (HookEntry *)entry->carry_data, + entry->carry_handler); + + typedef void (*intercept_routing_handler_t)(RegisterContext * ctx, ClosureTrampolineEntry * entry); + intercept_routing_handler_t routing_handler = (intercept_routing_handler_t)entry->carry_handler; + +#if __APPLE__ +#if __has_feature(ptrauth_calls) + routing_handler = + (typeof(routing_handler))__builtin_ptrauth_sign_unauthenticated((void *)routing_handler, ptrauth_key_asia, 0); +#endif +#endif + + routing_handler(ctx, entry); + return; +} diff --git a/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/closure-trampoline-common-handler.h b/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/common-bridge-handler.h similarity index 99% rename from module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/closure-trampoline-common-handler.h rename to module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/common-bridge-handler.h index 9aab24b5..d371e314 100644 --- a/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/closure-trampoline-common-handler.h +++ b/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/common-bridge-handler.h @@ -3,9 +3,8 @@ #include "dobby_internal.h" -#include "TrampolineBridge/ClosureTrampolineBridge/AssemblyClosureTrampoline.h" - #include "Interceptor.h" +#include "TrampolineBridge/ClosureTrampolineBridge/AssemblyClosureTrampoline.h" extern "C" { void intercept_routing_common_bridge_handler(RegisterContext *ctx, ClosureTrampolineEntry *entry); diff --git a/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/x64/X64AssemblyClosureTrampoline.cc b/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/x64/X64AssemblyClosureTrampoline.cc index 8fe32850..b33fc7be 100644 --- a/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/x64/X64AssemblyClosureTrampoline.cc +++ b/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/x64/X64AssemblyClosureTrampoline.cc @@ -1,4 +1,4 @@ -#include "common/macros/platform_macro.h" +#include "platform_macro.h" #if defined(TARGET_ARCH_X64) #include "dobby_internal.h" @@ -7,35 +7,36 @@ #include "TrampolineBridge/ClosureTrampolineBridge/AssemblyClosureTrampoline.h" -extern void closure_trampoline_template(); - using namespace zz; using namespace zz::x64; ClosureTrampolineEntry *ClosureTrampoline::CreateClosureTrampoline(void *carry_data, void *carry_handler) { - - ClosureTrampolineEntry *entry = new ClosureTrampolineEntry; - -#include "TrampolineBridge/ClosureTrampolineBridge/AssemblyClosureTrampoline.h" -#define _ turbo_assembler_. + ClosureTrampolineEntry *entry = nullptr; + entry = new ClosureTrampolineEntry; + + AssemblyCodeChunk *cchunk = MemoryArena::AllocateCodeChunk(32); + if (cchunk == nullptr) { + return NULL; + } +#define _ turbo_assembler_. #define __ turbo_assembler_.GetCodeBuffer()-> TurboAssembler turbo_assembler_(0); char *push_rip_6 = (char *)"\xff\x35\x06\x00\x00\x00"; - char *jmp_rip_8 = (char *)"\xff\x25\x08\x00\x00\x00"; + char *jmp_rip_8 = (char *)"\xff\x25\x08\x00\x00\x00"; __ EmitBuffer(push_rip_6, 6); __ EmitBuffer(jmp_rip_8, 6); __ Emit64((uint64_t)entry); __ Emit64((uint64_t)get_closure_bridge()); - AssemblyCodeChunk *code = - AssemblyCodeBuilder::FinalizeFromTurboAssembler(reinterpret_cast(&turbo_assembler_)); - - entry->address = (void *)code->raw_instruction_start(); - entry->carry_data = carry_data; + entry->address = (void *)cchunk->raw_instruction_start(); + entry->size = cchunk->raw_instruction_size(); + entry->carry_data = carry_data; entry->carry_handler = carry_handler; - entry->size = code->raw_instruction_size(); + + CodeBufferBase *buffer = reinterpret_cast(turbo_assembler_.GetCodeBuffer()); + CodePatch(cchunk->address, (uint8_t *)buffer->getRawBuffer(), buffer->getSize()); return entry; } diff --git a/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/x64/closure-bridge-x64.cc b/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/x64/closure-bridge-x64.cc index 9f3364d7..26ef4ad1 100644 --- a/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/x64/closure-bridge-x64.cc +++ b/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/x64/closure-bridge-x64.cc @@ -1,11 +1,11 @@ -#include "common/macros/platform_macro.h" +#include "platform_macro.h" #if defined(TARGET_ARCH_X64) #include "dobby_internal.h" #include "core/modules/assembler/assembler-x64.h" -#include "TrampolineBridge/ClosureTrampolineBridge/closure-trampoline-common-handler.h" +#include "TrampolineBridge/ClosureTrampolineBridge/common-bridge-handler.h" using namespace zz; using namespace zz::x64; @@ -26,7 +26,7 @@ void *get_closure_bridge() { #else // otherwise, use the Assembler build the closure_bridge -#define _ turbo_assembler_. +#define _ turbo_assembler_. #define __ turbo_assembler_.GetCodeBuffer()-> char *pushfq = (char *)"\x9c"; @@ -133,7 +133,7 @@ void *get_closure_bridge() { AssemblyCodeChunk *code = AssemblyCodeBuilder::FinalizeFromTurboAssembler(&turbo_assembler_); closure_bridge = (void *)code->raw_instruction_start(); - DLOG(1, "[closure bridge] Build the closure bridge at %p", closure_bridge); + DLOG(0, "[closure bridge] Build the closure bridge at %p", closure_bridge); #endif return (void *)closure_bridge; } diff --git a/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/x64/helper-x64.cc b/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/x64/helper-x64.cc index b8eaba2c..e0f3da9a 100644 --- a/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/x64/helper-x64.cc +++ b/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/x64/helper-x64.cc @@ -1,4 +1,4 @@ -#include "common/macros/platform_macro.h" +#include "platform_macro.h" #if defined(TARGET_ARCH_X64) #include "dobby_internal.h" @@ -7,7 +7,7 @@ void set_routing_bridge_next_hop(RegisterContext *ctx, void *address) { addr_t rsp = ctx->rsp; // ClosureTrampolineEntry reserved stack - addr_t entry_placeholder_stack_addr = rsp - 8; + addr_t entry_placeholder_stack_addr = rsp - 8; *(addr_t *)entry_placeholder_stack_addr = (addr_t)address; } diff --git a/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/x86/X86AssemblyClosureTrampoline.cc b/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/x86/X86AssemblyClosureTrampoline.cc index 4e952871..b5c01352 100644 --- a/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/x86/X86AssemblyClosureTrampoline.cc +++ b/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/x86/X86AssemblyClosureTrampoline.cc @@ -1,4 +1,4 @@ -#include "common/macros/platform_macro.h" +#include "platform_macro.h" #if defined(TARGET_ARCH_IA32) #include "dobby_internal.h" @@ -7,24 +7,20 @@ #include "TrampolineBridge/ClosureTrampolineBridge/AssemblyClosureTrampoline.h" -extern void closure_trampoline_template(); - using namespace zz; using namespace zz::x86; ClosureTrampolineEntry *ClosureTrampoline::CreateClosureTrampoline(void *carry_data, void *carry_handler) { - - ClosureTrampolineEntry *entry = new ClosureTrampolineEntry; - -#include "TrampolineBridge/ClosureTrampolineBridge/AssemblyClosureTrampoline.h" -#define _ turbo_assembler_. -#define __ turbo_assembler_.GetCodeBuffer()-> + ClosureTrampolineEntry *entry = nullptr; + entry = new ClosureTrampolineEntry; AssemblyCodeChunk *cchunk = MemoryArena::AllocateCodeChunk(32); if (cchunk == nullptr) { return NULL; } - // init assembler + +#define _ turbo_assembler_. +#define __ turbo_assembler_.GetCodeBuffer()-> TurboAssembler turbo_assembler_(cchunk->address); int32_t offset = (int32_t)get_closure_bridge() - ((int32_t)cchunk->address + 18); @@ -33,10 +29,10 @@ ClosureTrampolineEntry *ClosureTrampoline::CreateClosureTrampoline(void *carry_d _ mov(Address(esp, 4 * 0), Immediate((int32_t)entry, 32)); _ jmp(Immediate(offset, 32)); - entry->address = (void *)cchunk->raw_instruction_start(); - entry->carry_data = carry_data; + entry->address = (void *)cchunk->raw_instruction_start(); + entry->size = cchunk->raw_instruction_size(); + entry->carry_data = carry_data; entry->carry_handler = carry_handler; - entry->size = cchunk->raw_instruction_size(); CodeBufferBase *buffer = reinterpret_cast(turbo_assembler_.GetCodeBuffer()); CodePatch(cchunk->address, (uint8_t *)buffer->getRawBuffer(), buffer->getSize()); diff --git a/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/x86/closure-bridge-x86.cc b/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/x86/closure-bridge-x86.cc index eb99ecb4..b55edb2e 100644 --- a/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/x86/closure-bridge-x86.cc +++ b/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/x86/closure-bridge-x86.cc @@ -1,11 +1,11 @@ -#include "common/macros/platform_macro.h" +#include "platform_macro.h" #if defined(TARGET_ARCH_IA32) #include "dobby_internal.h" #include "core/modules/assembler/assembler-ia32.h" -#include "TrampolineBridge/ClosureTrampolineBridge/closure-trampoline-common-handler.h" +#include "TrampolineBridge/ClosureTrampolineBridge/common-bridge-handler.h" using namespace zz; using namespace zz::x86; @@ -26,7 +26,7 @@ void *get_closure_bridge() { #else // otherwise, use the Assembler build the closure_bridge -#define _ turbo_assembler_. +#define _ turbo_assembler_. #define __ turbo_assembler_.GetCodeBuffer()-> char *pushfd = (char *)"\x9c"; @@ -104,7 +104,7 @@ void *get_closure_bridge() { AssemblyCodeChunk *code = AssemblyCodeBuilder::FinalizeFromTurboAssembler(&turbo_assembler_); closure_bridge = (void *)code->raw_instruction_start(); - DLOG(1, "[closure bridge] Build the closure bridge at %p", closure_bridge); + DLOG(0, "[closure bridge] Build the closure bridge at %p", closure_bridge); #endif return (void *)closure_bridge; } diff --git a/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/x86/helper-x86.cc b/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/x86/helper-x86.cc index db3d0390..75f80fcf 100644 --- a/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/x86/helper-x86.cc +++ b/module/src/main/cpp/Dobby/source/TrampolineBridge/ClosureTrampolineBridge/x86/helper-x86.cc @@ -1,4 +1,4 @@ -#include "common/macros/platform_macro.h" +#include "platform_macro.h" #if defined(TARGET_ARCH_IA32) #include "dobby_internal.h" @@ -6,7 +6,7 @@ void set_routing_bridge_next_hop(RegisterContext *ctx, void *address) { addr_t esp = ctx->esp; - addr_t entry_placeholder_stack_addr = esp - 4; + addr_t entry_placeholder_stack_addr = esp - 4; *(addr_t *)entry_placeholder_stack_addr = (addr_t)address; } diff --git a/module/src/main/cpp/Dobby/source/TrampolineBridge/Trampoline/Trampoline.h b/module/src/main/cpp/Dobby/source/TrampolineBridge/Trampoline/Trampoline.h new file mode 100644 index 00000000..53f3779b --- /dev/null +++ b/module/src/main/cpp/Dobby/source/TrampolineBridge/Trampoline/Trampoline.h @@ -0,0 +1,5 @@ +#pragma once + +#include "MemoryAllocator/AssemblyCodeBuilder.h" + +CodeBufferBase *GenerateNormalTrampolineBuffer(addr_t from, addr_t to); \ No newline at end of file diff --git a/module/src/main/cpp/Dobby/source/TrampolineBridge/InterceptRoutingTrampoline/arm/trampoline-arm.cc b/module/src/main/cpp/Dobby/source/TrampolineBridge/Trampoline/arm/trampoline-arm.cc similarity index 93% rename from module/src/main/cpp/Dobby/source/TrampolineBridge/InterceptRoutingTrampoline/arm/trampoline-arm.cc rename to module/src/main/cpp/Dobby/source/TrampolineBridge/Trampoline/arm/trampoline-arm.cc index 6e1ac138..7dfca4db 100644 --- a/module/src/main/cpp/Dobby/source/TrampolineBridge/InterceptRoutingTrampoline/arm/trampoline-arm.cc +++ b/module/src/main/cpp/Dobby/source/TrampolineBridge/Trampoline/arm/trampoline-arm.cc @@ -1,4 +1,4 @@ -#include "common/macros/platform_macro.h" +#include "platform_macro.h" #if defined(TARGET_ARCH_ARM) #include "core/modules/assembler/assembler-arm.h" @@ -7,7 +7,7 @@ #include "InstructionRelocation/arm/ARMInstructionRelocation.h" #include "MemoryAllocator/NearMemoryArena.h" -#include "InterceptRouting/ExtraInternalPlugin/RegisterPlugin.h" +#include "InterceptRouting/RoutingPlugin/RoutingPlugin.h" using namespace zz::arm; diff --git a/module/src/main/cpp/Dobby/source/TrampolineBridge/InterceptRoutingTrampoline/arm64/trampoline-arm64.cc b/module/src/main/cpp/Dobby/source/TrampolineBridge/Trampoline/arm64/trampoline-arm64.cc similarity index 83% rename from module/src/main/cpp/Dobby/source/TrampolineBridge/InterceptRoutingTrampoline/arm64/trampoline-arm64.cc rename to module/src/main/cpp/Dobby/source/TrampolineBridge/Trampoline/arm64/trampoline-arm64.cc index f3b4e4ff..139ca400 100644 --- a/module/src/main/cpp/Dobby/source/TrampolineBridge/InterceptRoutingTrampoline/arm64/trampoline-arm64.cc +++ b/module/src/main/cpp/Dobby/source/TrampolineBridge/Trampoline/arm64/trampoline-arm64.cc @@ -1,4 +1,4 @@ -#include "common/macros/platform_macro.h" +#include "platform_macro.h" #if defined(TARGET_ARCH_ARM64) #include "dobby_internal.h" @@ -9,7 +9,7 @@ #include "InstructionRelocation/arm64/ARM64InstructionRelocation.h" #include "MemoryAllocator/NearMemoryArena.h" -#include "InterceptRouting/ExtraInternalPlugin/RegisterPlugin.h" +#include "InterceptRouting/RoutingPlugin/RoutingPlugin.h" using namespace zz::arm64; @@ -17,7 +17,7 @@ CodeBufferBase *GenerateNormalTrampolineBuffer(addr_t from, addr_t to) { TurboAssembler turbo_assembler_((void *)from); #define _ turbo_assembler_. - uint64_t distance = llabs((int64_t)(from - to)); + uint64_t distance = llabs((int64_t)(from - to)); uint64_t adrp_range = ((uint64_t)1 << (2 + 19 + 12 - 1)); if (distance < adrp_range) { // adrp, add, br @@ -32,7 +32,7 @@ CodeBufferBase *GenerateNormalTrampolineBuffer(addr_t from, addr_t to) { } CodeBufferBase *result = NULL; - result = turbo_assembler_.GetCodeBuffer()->Copy(); + result = turbo_assembler_.GetCodeBuffer()->Copy(); return result; } @@ -52,7 +52,7 @@ static AssemblyCodeChunk *GenerateFastForwardTrampoline(addr_t source_address, a } // Use adrp + add branch - uint64_t distance = llabs((int64_t)((addr_t)cchunk->address - target_address)); + uint64_t distance = llabs((int64_t)((addr_t)cchunk->address - target_address)); uint64_t adrp_range = ((uint64_t)1 << (2 + 19 + 12 - 1)); if (distance < adrp_range) { // Use adrp + add branch == (3 * 4) trampoline size _ AdrpAdd(TMP_REG_0, (addr_t)cchunk->address, target_address); @@ -80,7 +80,7 @@ static AssemblyCodeChunk *GenerateFastForwardTrampoline(addr_t source_address, a #endif size_t tramp_size = turbo_assembler_.GetCodeBuffer()->getSize(); - cchunk = NearMemoryArena::AllocateCodeChunk((addr_t)source_address, ARM64_B_XXX_RANGE, tramp_size); + cchunk = NearMemoryArena::AllocateCodeChunk((addr_t)source_address, ARM64_B_XXX_RANGE, tramp_size); if (cchunk == nullptr) { ERROR_LOG("Can't found near code chunk"); return NULL; @@ -90,7 +90,7 @@ static AssemblyCodeChunk *GenerateFastForwardTrampoline(addr_t source_address, a turbo_assembler_.SetRealizedAddress(cchunk->address); AssemblyCodeChunk *result = NULL; - result = AssemblyCodeBuilder::FinalizeFromTurboAssembler(&turbo_assembler_); + result = AssemblyCodeBuilder::FinalizeFromTurboAssembler(&turbo_assembler_); { // release delete cchunk; @@ -109,12 +109,12 @@ CodeBufferBase *GenerateNearTrampolineBuffer(InterceptRouting *routing, addr_t s _ b(dst - src); } else { AssemblyCodeChunk *fast_forward_trampoline = NULL; - fast_forward_trampoline = GenerateFastForwardTrampoline(src, dst); + fast_forward_trampoline = GenerateFastForwardTrampoline(src, dst); if (!fast_forward_trampoline) return NULL; // trampoline => fast_forward_trampoline addr_t fast_forward_trampoline_addr = fast_forward_trampoline->raw_instruction_start(); - _ b(fast_forward_trampoline_addr - src); + _ b(fast_forward_trampoline_addr - src); } // free the original trampoline diff --git a/module/src/main/cpp/Dobby/source/TrampolineBridge/InterceptRoutingTrampoline/x64/trampoline-x64.cc b/module/src/main/cpp/Dobby/source/TrampolineBridge/Trampoline/x64/trampoline-x64.cc similarity index 85% rename from module/src/main/cpp/Dobby/source/TrampolineBridge/InterceptRoutingTrampoline/x64/trampoline-x64.cc rename to module/src/main/cpp/Dobby/source/TrampolineBridge/Trampoline/x64/trampoline-x64.cc index 9314e5d5..252f0034 100644 --- a/module/src/main/cpp/Dobby/source/TrampolineBridge/InterceptRoutingTrampoline/x64/trampoline-x64.cc +++ b/module/src/main/cpp/Dobby/source/TrampolineBridge/Trampoline/x64/trampoline-x64.cc @@ -1,4 +1,4 @@ -#include "common/macros/platform_macro.h" +#include "platform_macro.h" #if defined(TARGET_ARCH_X64) #include "dobby_internal.h" @@ -9,7 +9,7 @@ #include "InstructionRelocation/x64/X64InstructionRelocation.h" #include "MemoryAllocator/NearMemoryArena.h" -#include "InterceptRouting/ExtraInternalPlugin/RegisterPlugin.h" +#include "InterceptRouting/RoutingPlugin/RoutingPlugin.h" using namespace zz::x64; @@ -32,13 +32,13 @@ CodeBufferBase *GenerateNormalTrampolineBuffer(addr_t from, addr_t to) { // branch void **branch_stub = AllocIndirectStub(from); - *branch_stub = (void *)to; + *branch_stub = (void *)to; CodeGen codegen(&turbo_assembler_); codegen.JmpNearIndirect((uint64_t)branch_stub); CodeBufferBase *result = NULL; - result = turbo_assembler_.GetCodeBuffer()->Copy(); + result = turbo_assembler_.GetCodeBuffer()->Copy(); return result; } diff --git a/module/src/main/cpp/Dobby/source/TrampolineBridge/InterceptRoutingTrampoline/x86/trampoline-x86.cc b/module/src/main/cpp/Dobby/source/TrampolineBridge/Trampoline/x86/trampoline-x86.cc similarity index 80% rename from module/src/main/cpp/Dobby/source/TrampolineBridge/InterceptRoutingTrampoline/x86/trampoline-x86.cc rename to module/src/main/cpp/Dobby/source/TrampolineBridge/Trampoline/x86/trampoline-x86.cc index 03cbd392..f86ceac9 100644 --- a/module/src/main/cpp/Dobby/source/TrampolineBridge/InterceptRoutingTrampoline/x86/trampoline-x86.cc +++ b/module/src/main/cpp/Dobby/source/TrampolineBridge/Trampoline/x86/trampoline-x86.cc @@ -1,4 +1,4 @@ -#include "common/macros/platform_macro.h" +#include "platform_macro.h" #if defined(TARGET_ARCH_IA32) #include "dobby_internal.h" @@ -9,7 +9,7 @@ #include "InstructionRelocation/x86/X86InstructionRelocation.h" #include "MemoryAllocator/NearMemoryArena.h" -#include "InterceptRouting/ExtraInternalPlugin/RegisterPlugin.h" +#include "InterceptRouting/RoutingPlugin/RoutingPlugin.h" using namespace zz::x86; @@ -21,7 +21,7 @@ CodeBufferBase *GenerateNormalTrampolineBuffer(addr_t from, addr_t to) { codegen.JmpNear((uint32_t)to); CodeBufferBase *result = NULL; - result = turbo_assembler_.GetCodeBuffer()->Copy(); + result = turbo_assembler_.GetCodeBuffer()->Copy(); return result; } diff --git a/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/clear-cache-tool-all.c b/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/clear-cache-tool-all.c new file mode 100644 index 00000000..7479587b --- /dev/null +++ b/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/clear-cache-tool-all.c @@ -0,0 +1,165 @@ +//===-- clear_cache.c - Implement __clear_cache ---------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include +#include +#include + +#if __APPLE__ +#include +#endif + +#if defined(_WIN32) +// Forward declare Win32 APIs since the GCC mode driver does not handle the +// newer SDKs as well as needed. +uint32_t FlushInstructionCache(uintptr_t hProcess, void *lpBaseAddress, uintptr_t dwSize); +uintptr_t GetCurrentProcess(void); +#endif + +#if defined(__FreeBSD__) && defined(__arm__) +// clang-format off +#include +#include +// clang-format on +#endif + +#if defined(__NetBSD__) && defined(__arm__) +#include +#endif + +#if defined(__OpenBSD__) && (defined(__arm__) || defined(__mips__)) +// clang-format off +#include +#include +// clang-format on +#endif + +#if defined(__linux__) && defined(__mips__) +#include +#include +#include +#endif + +// The compiler generates calls to __clear_cache() when creating +// trampoline functions on the stack for use with nested functions. +// It is expected to invalidate the instruction cache for the +// specified range. + +void __clear_cache(void *start, void *end) { +#if __i386__ || __x86_64__ || defined(_M_IX86) || defined(_M_X64) +// Intel processors have a unified instruction and data cache +// so there is nothing to do +#elif defined(_WIN32) && (defined(__arm__) || defined(__aarch64__)) + FlushInstructionCache(GetCurrentProcess(), start, end - start); +#elif defined(__arm__) && !defined(__APPLE__) +#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) + struct arm_sync_icache_args arg; + + arg.addr = (uintptr_t)start; + arg.len = (uintptr_t)end - (uintptr_t)start; + + sysarch(ARM_SYNC_ICACHE, &arg); +#elif defined(__linux__) +// We used to include asm/unistd.h for the __ARM_NR_cacheflush define, but +// it also brought many other unused defines, as well as a dependency on +// kernel headers to be installed. +// +// This value is stable at least since Linux 3.13 and should remain so for +// compatibility reasons, warranting it's re-definition here. +#define __ARM_NR_cacheflush 0x0f0002 + register int start_reg __asm("r0") = (int)(intptr_t)start; + const register int end_reg __asm("r1") = (int)(intptr_t)end; + const register int flags __asm("r2") = 0; + const register int syscall_nr __asm("r7") = __ARM_NR_cacheflush; + __asm __volatile("svc 0x0" : "=r"(start_reg) : "r"(syscall_nr), "r"(start_reg), "r"(end_reg), "r"(flags)); + assert(start_reg == 0 && "Cache flush syscall failed."); +#else + compilerrt_abort(); +#endif +#elif defined(__linux__) && defined(__mips__) + const uintptr_t start_int = (uintptr_t)start; + const uintptr_t end_int = (uintptr_t)end; + syscall(__NR_cacheflush, start, (end_int - start_int), BCACHE); +#elif defined(__mips__) && defined(__OpenBSD__) + cacheflush(start, (uintptr_t)end - (uintptr_t)start, BCACHE); +#elif defined(__aarch64__) && !defined(__APPLE__) + uint64_t xstart = (uint64_t)(uintptr_t)start; + uint64_t xend = (uint64_t)(uintptr_t)end; + + // Get Cache Type Info. + static uint64_t ctr_el0 = 0; + if (ctr_el0 == 0) + __asm __volatile("mrs %0, ctr_el0" : "=r"(ctr_el0)); + + // The DC and IC instructions must use 64-bit registers so we don't use + // uintptr_t in case this runs in an IPL32 environment. + uint64_t addr; + + // If CTR_EL0.IDC is set, data cache cleaning to the point of unification + // is not required for instruction to data coherence. + if (((ctr_el0 >> 28) & 0x1) == 0x0) { + const size_t dcache_line_size = 4 << ((ctr_el0 >> 16) & 15); + for (addr = xstart & ~(dcache_line_size - 1); addr < xend; addr += dcache_line_size) + __asm __volatile("dc cvau, %0" ::"r"(addr)); + } + __asm __volatile("dsb ish"); + + // If CTR_EL0.DIC is set, instruction cache invalidation to the point of + // unification is not required for instruction to data coherence. + if (((ctr_el0 >> 29) & 0x1) == 0x0) { + const size_t icache_line_size = 4 << ((ctr_el0 >> 0) & 15); + for (addr = xstart & ~(icache_line_size - 1); addr < xend; addr += icache_line_size) + __asm __volatile("ic ivau, %0" ::"r"(addr)); + } + __asm __volatile("isb sy"); +#elif defined(__powerpc64__) + const size_t line_size = 32; + const size_t len = (uintptr_t)end - (uintptr_t)start; + + const uintptr_t mask = ~(line_size - 1); + const uintptr_t start_line = ((uintptr_t)start) & mask; + const uintptr_t end_line = ((uintptr_t)start + len + line_size - 1) & mask; + + for (uintptr_t line = start_line; line < end_line; line += line_size) + __asm__ volatile("dcbf 0, %0" : : "r"(line)); + __asm__ volatile("sync"); + + for (uintptr_t line = start_line; line < end_line; line += line_size) + __asm__ volatile("icbi 0, %0" : : "r"(line)); + __asm__ volatile("isync"); +#elif defined(__sparc__) + const size_t dword_size = 8; + const size_t len = (uintptr_t)end - (uintptr_t)start; + + const uintptr_t mask = ~(dword_size - 1); + const uintptr_t start_dword = ((uintptr_t)start) & mask; + const uintptr_t end_dword = ((uintptr_t)start + len + dword_size - 1) & mask; + + for (uintptr_t dword = start_dword; dword < end_dword; dword += dword_size) + __asm__ volatile("flush %0" : : "r"(dword)); +#elif defined(__riscv) && defined(__linux__) +#define __NR_riscv_flush_icache (244 + 15) + register void * start_reg __asm("a0") = start; + const register void *end_reg __asm("a1") = end; + const register long flags __asm("a2") = 0; + const register long syscall_nr __asm("a7") = __NR_riscv_flush_icache; + __asm __volatile("ecall" : "=r"(start_reg) : "r"(start_reg), "r"(end_reg), "r"(flags), "r"(syscall_nr)); + assert(start_reg == 0 && "Cache flush syscall failed."); +#else +#if __APPLE__ + // On Darwin, sys_icache_invalidate() provides this functionality + sys_icache_invalidate(start, end - start); +#else + compilerrt_abort(); +#endif +#endif +} + +void ClearCache(void *start, void *end) { + return __clear_cache(start, end); +} diff --git a/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/clear-cache-tool-all.cc b/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/clear-cache-tool-all.cc deleted file mode 100644 index aeb81cf9..00000000 --- a/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/clear-cache-tool-all.cc +++ /dev/null @@ -1,113 +0,0 @@ - -#include "core/arch/CpuFeature.h" - -#if defined(__APPLE__) -#include -#endif - -#include - -/* - * The compiler generates calls to __clear_cache() when creating - * trampoline functions on the stack for use with nested functions. - * It is expected to invalidate the instruction cache for the - * specified range. - */ - -void ClearCache(void *start, void *end) { -#if __i386__ || __x86_64__ || defined(_M_IX86) || defined(_M_X64) -/* - * Intel processors have a unified instruction and data cache - * so there is nothing to do - */ -#elif defined(_WIN32) && (defined(__arm__) || defined(__aarch64__)) - FlushInstructionCache(GetCurrentProcess(), start, end - start); -#elif defined(__arm__) && !defined(__APPLE__) -#if defined(__FreeBSD__) || defined(__NetBSD__) - struct arm_sync_icache_args arg; - - arg.addr = (uintptr_t)start; - arg.len = (uintptr_t)end - (uintptr_t)start; - - sysarch(ARM_SYNC_ICACHE, &arg); -#elif defined(__linux__) -/* - * We used to include asm/unistd.h for the __ARM_NR_cacheflush define, but - * it also brought many other unused defines, as well as a dependency on - * kernel headers to be installed. - * - * This value is stable at least since Linux 3.13 and should remain so for - * compatibility reasons, warranting it's re-definition here. - */ -#define __ARM_NR_cacheflush 0x0f0002 - register int start_reg __asm("r0") = (int)(intptr_t)start; - const register int end_reg __asm("r1") = (int)(intptr_t)end; - const register int flags __asm("r2") = 0; - const register int syscall_nr __asm("r7") = __ARM_NR_cacheflush; - __asm __volatile("svc 0x0" : "=r"(start_reg) : "r"(syscall_nr), "r"(start_reg), "r"(end_reg), "r"(flags)); - assert(start_reg == 0 && "Cache flush syscall failed."); -#else - compilerrt_abort(); -#endif -#elif defined(__linux__) && defined(__mips__) - const uintptr_t start_int = (uintptr_t)start; - const uintptr_t end_int = (uintptr_t)end; -#if defined(__ANDROID__) && defined(__LP64__) - // Call synci implementation for short address range. - const uintptr_t address_range_limit = 256; - if ((end_int - start_int) <= address_range_limit) { - clear_mips_cache(start, (end_int - start_int)); - } else { - syscall(__NR_cacheflush, start, (end_int - start_int), BCACHE); - } -#else - syscall(__NR_cacheflush, start, (end_int - start_int), BCACHE); -#endif -#elif defined(__mips__) && defined(__OpenBSD__) - cacheflush(start, (uintptr_t)end - (uintptr_t)start, BCACHE); -#elif defined(__aarch64__) && !defined(__APPLE__) - uint64_t xstart = (uint64_t)(uintptr_t)start; - uint64_t xend = (uint64_t)(uintptr_t)end; - uint64_t addr; - - // Get Cache Type Info - uint64_t ctr_el0; - __asm __volatile("mrs %0, ctr_el0" : "=r"(ctr_el0)); - - /* - * dc & ic instructions must use 64bit registers so we don't use - * uintptr_t in case this runs in an IPL32 environment. - */ - const int dcache_line_size = 4 << ((ctr_el0 >> 16) & 15); - for (addr = xstart & ~(dcache_line_size - 1); addr < xend; addr += dcache_line_size) - __asm __volatile("dc cvau, %0" ::"r"(addr)); - __asm __volatile("dsb ish"); - - const int icache_line_size = 4 << ((ctr_el0 >> 0) & 15); - for (addr = xstart & ~(icache_line_size - 1); addr < xend; addr += icache_line_size) - __asm __volatile("ic ivau, %0" ::"r"(addr)); - __asm __volatile("isb sy"); -#elif defined(__powerpc64__) - const int line_size = 32; - const int len = (uintptr_t)end - (uintptr_t)start; - - const uintptr_t mask = ~(line_size - 1); - const uintptr_t start_line = ((uintptr_t)start) & mask; - const uintptr_t end_line = ((uintptr_t)start + len + line_size - 1) & mask; - - for (uintptr_t line = start_line; line < end_line; line += line_size) - __asm__ volatile("dcbf 0, %0" : : "r"(line)); - __asm__ volatile("sync"); - - for (uintptr_t line = start_line; line < end_line; line += line_size) - __asm__ volatile("icbi 0, %0" : : "r"(line)); - __asm__ volatile("isync"); -#else -#if __APPLE__ - /* On Darwin, sys_icache_invalidate() provides this functionality */ - sys_icache_invalidate(start, (uintptr_t)end - (uintptr_t)start); -#else - compilerrt_abort(); -#endif -#endif -} diff --git a/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/clear-cache-tool/clear-cache-tool-arm-dummy.cc b/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/clear-cache-tool/clear-cache-tool-arm-dummy.cc index 978e26ce..abe26c45 100644 --- a/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/clear-cache-tool/clear-cache-tool-arm-dummy.cc +++ b/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/clear-cache-tool/clear-cache-tool-arm-dummy.cc @@ -44,7 +44,7 @@ void CpuFeatures::FlushICache(void *startp, void *endp) { " pop {r7}\n" : - : "r"(beg), "r"(end), "r"(flg), [ scno ] "i"(__ARM_NR_cacheflush) + : "r"(beg), "r"(end), "r"(flg), [scno] "i"(__ARM_NR_cacheflush) : "memory"); #endif #endif diff --git a/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/clear-cache-tool/clear-cache-tool-arm64-dummy.cc b/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/clear-cache-tool/clear-cache-tool-arm64-dummy.cc index 7b22725b..60580a5c 100644 --- a/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/clear-cache-tool/clear-cache-tool-arm64-dummy.cc +++ b/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/clear-cache-tool/clear-cache-tool-arm64-dummy.cc @@ -10,7 +10,7 @@ class CacheLineSizes { CacheLineSizes() { // Copy the content of the cache type register to a core register. __asm__ __volatile__("mrs %x[ctr], ctr_el0" // NOLINT - : [ ctr ] "=r"(cache_type_register_)); + : [ctr] "=r"(cache_type_register_)); } uint32_t icache_line_size() const { @@ -42,12 +42,12 @@ void CpuFeatures::FlushICache(void *startp, void *endp) { uintptr_t start = reinterpret_cast(startp); // Sizes will be used to generate a mask big enough to cover a pointer. CacheLineSizes sizes; - uintptr_t dsize = sizes.dcache_line_size(); - uintptr_t isize = sizes.icache_line_size(); + uintptr_t dsize = sizes.dcache_line_size(); + uintptr_t isize = sizes.icache_line_size(); // Cache line sizes are always a power of 2. uintptr_t dstart = start & ~(dsize - 1); uintptr_t istart = start & ~(isize - 1); - uintptr_t end = reinterpret_cast(endp); + uintptr_t end = reinterpret_cast(endp); __asm__ __volatile__( // NOLINT // Clean every line of the D cache containing the target data. @@ -92,8 +92,8 @@ void CpuFeatures::FlushICache(void *startp, void *endp) { // discarded. // isb : Instruction Synchronisation Barrier "isb \n\t" - : [ dline ] "+r"(dstart), [ iline ] "+r"(istart) - : [ dsize ] "r"(dsize), [ isize ] "r"(isize), [ end ] "r"(end) + : [dline] "+r"(dstart), [iline] "+r"(istart) + : [dsize] "r"(dsize), [isize] "r"(isize), [end] "r"(end) // This code does not write to memory but without the dependency gcc might // move this code before the code is generated. : "cc", "memory"); // NOLINT diff --git a/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/code-patch-tool-darwin.cc b/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/code-patch-tool-darwin.cc index 91a72c25..16312a81 100644 --- a/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/code-patch-tool-darwin.cc +++ b/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/code-patch-tool-darwin.cc @@ -20,7 +20,8 @@ #include "logging/check_logging.h" -#include "common/macros/platform_macro.h" +#include "platform_macro.h" + #if defined(CODE_PATCH_WITH_SUBSTRATED) && defined(TARGET_ARCH_ARM64) #include #include "bootstrap.h" @@ -35,12 +36,14 @@ static mach_port_t substrated_server_port = MACH_PORT_NULL; -mach_port_t connect_mach_service(const char *name) { - mach_port_t port = MACH_PORT_NULL; +static mach_port_t connect_mach_service(const char *name) { + mach_port_t port = MACH_PORT_NULL; kern_return_t kr; +#if 0 kr = task_get_special_port(mach_task_self(), TASK_BOOTSTRAP_PORT, &bootstrap_port); KERN_ERROR_RETURN(kr, MACH_PORT_NULL) +#endif kr = bootstrap_look_up(bootstrap_port, (char *)name, &port); KERN_ERROR_RETURN(kr, MACH_PORT_NULL); @@ -70,72 +73,54 @@ int code_remap_with_substrated(uint8_t *buffer, uint32_t buffer_size, addr_t add PUBLIC MemoryOperationError CodePatch(void *address, uint8_t *buffer, uint32_t buffer_size) { kern_return_t kr; - int page_size = (int)sysconf(_SC_PAGESIZE); - addr_t page_align_address = ALIGN_FLOOR(address, page_size); - int offset = static_cast((addr_t)address - page_align_address); + int page_size = (int)sysconf(_SC_PAGESIZE); + addr_t page_aligned_address = ALIGN_FLOOR(address, page_size); + int offset = (int)((addr_t)address - page_aligned_address); static mach_port_t self_port = mach_task_self(); #ifdef __APPLE__ - -#if 0 // REMOVE - vm_prot_t prot; - vm_inherit_t inherit; - mach_port_t task_self = mach_task_self(); - vm_address_t region = (vm_address_t)page_align_address; - vm_size_t region_size = 0; - struct vm_region_submap_short_info_64 info; - mach_msg_type_number_t info_count = VM_REGION_SUBMAP_SHORT_INFO_COUNT_64; - natural_t max_depth = -1; - kr = vm_region_recurse_64(task_self, ®ion, ®ion_size, &max_depth, (vm_region_recurse_info_t)&info, &info_count); - if (kr != KERN_SUCCESS) { - return kMemoryOperationError; - } - prot = info.protection; - inherit = info.inheritance; -#endif - // try modify with substrated (steal from frida-gum) - - addr_t remap_page = + addr_t remap_dummy_page = (addr_t)mmap(0, page_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, VM_MAKE_TAG(255), 0); - if ((void *)remap_page == MAP_FAILED) + if ((void *)remap_dummy_page == MAP_FAILED) return kMemoryOperationError; - // copy origin page - memcpy((void *)remap_page, (void *)page_align_address, page_size); + // copy original page + memcpy((void *)remap_dummy_page, (void *)page_aligned_address, page_size); // patch buffer - memcpy((void *)(remap_page + offset), buffer, buffer_size); + memcpy((void *)(remap_dummy_page + offset), buffer, buffer_size); // change permission - mprotect((void *)remap_page, page_size, PROT_READ | PROT_WRITE); + mprotect((void *)remap_dummy_page, page_size, PROT_READ | PROT_WRITE); int ret = RT_FAILED; -#if defined(CODE_PATCH_WITH_SUBSTRATED) && defined(TARGET_ARCH_ARM64) - ret = code_remap_with_substrated((uint8_t *)remap_page, (uint32_t)page_size, (addr_t)page_align_address); +#if 0 && defined(CODE_PATCH_WITH_SUBSTRATED) && defined(TARGET_ARCH_ARM64) + ret = code_remap_with_substrated((uint8_t *)remap_dummy_page, (uint32_t)page_size, (addr_t)page_aligned_address); if (0 && ret == RT_FAILED) DLOG(0, "substrated failed, use vm_remap"); #endif if (ret == RT_FAILED) { - mprotect((void *)remap_page, page_size, PROT_READ | PROT_EXEC); - mach_vm_address_t dest_page_address_ = (mach_vm_address_t)page_align_address; - vm_prot_t curr_protection, max_protection; - kr = mach_vm_remap(self_port, &dest_page_address_, page_size, 0, VM_FLAGS_OVERWRITE | VM_FLAGS_FIXED, self_port, - (mach_vm_address_t)remap_page, TRUE, &curr_protection, &max_protection, VM_INHERIT_COPY); + mprotect((void *)remap_dummy_page, page_size, PROT_READ | PROT_EXEC); + mach_vm_address_t remap_dest_page = (mach_vm_address_t)page_aligned_address; + vm_prot_t curr_protection, max_protection; + kr = mach_vm_remap(self_port, (mach_vm_address_t *)&remap_dest_page, page_size, 0, + VM_FLAGS_OVERWRITE | VM_FLAGS_FIXED, self_port, (mach_vm_address_t)remap_dummy_page, TRUE, + &curr_protection, &max_protection, VM_INHERIT_COPY); if (kr != KERN_SUCCESS) { return kMemoryOperationError; } } // unmap the origin page - int err = munmap((void *)remap_page, (mach_vm_address_t)page_size); + int err = munmap((void *)remap_dummy_page, (mach_vm_address_t)page_size); if (err == -1) { return kMemoryOperationError; } #endif - addr_t clear_start = (addr_t)page_align_address + offset; + addr_t clear_start = (addr_t)page_aligned_address + offset; DCHECK_EQ(clear_start, (addr_t)address); ClearCache((void *)address, (void *)((addr_t)address + buffer_size)); diff --git a/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/code-patch-tool-posix.cc b/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/code-patch-tool-posix.cc index 3c4d9ef7..1badae18 100644 --- a/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/code-patch-tool-posix.cc +++ b/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/code-patch-tool-posix.cc @@ -9,9 +9,9 @@ #if !defined(__APPLE__) PUBLIC MemoryOperationError CodePatch(void *address, uint8_t *buffer, uint32_t buffer_size) { - int page_size = (int)sysconf(_SC_PAGESIZE); + int page_size = (int)sysconf(_SC_PAGESIZE); uintptr_t page_align_address = ALIGN_FLOOR(address, page_size); - int offset = (uintptr_t)address - page_align_address; + int offset = (uintptr_t)address - page_align_address; #if defined(__ANDROID__) || defined(__linux__) diff --git a/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/code-patch-tool-windows.cc b/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/code-patch-tool-windows.cc index 8ed2c3cc..a58e46f3 100644 --- a/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/code-patch-tool-windows.cc +++ b/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/code-patch-tool-windows.cc @@ -6,7 +6,7 @@ using namespace zz; PUBLIC MemoryOperationError CodePatch(void *address, uint8_t *buffer, uint32_t buffer_size) { DWORD oldProtect; - int pageSize; + int pageSize; // Get page size SYSTEM_INFO si; diff --git a/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/substrated/include/bootstrap.h b/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/substrated/include/bootstrap.h index 2d247285..0cb0acf2 100644 --- a/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/substrated/include/bootstrap.h +++ b/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/substrated/include/bootstrap.h @@ -19,31 +19,31 @@ __BEGIN_DECLS; #include #define BOOTSTRAP_MAX_NAME_LEN 128 -#define BOOTSTRAP_MAX_CMD_LEN 512 - -typedef char name_t[BOOTSTRAP_MAX_NAME_LEN]; -typedef char cmd_t[BOOTSTRAP_MAX_CMD_LEN]; -typedef name_t * name_array_t; -typedef int bootstrap_status_t; -typedef bootstrap_status_t * bootstrap_status_array_t; -typedef unsigned int bootstrap_property_t; +#define BOOTSTRAP_MAX_CMD_LEN 512 + +typedef char name_t[BOOTSTRAP_MAX_NAME_LEN]; +typedef char cmd_t[BOOTSTRAP_MAX_CMD_LEN]; +typedef name_t *name_array_t; +typedef int bootstrap_status_t; +typedef bootstrap_status_t *bootstrap_status_array_t; +typedef unsigned int bootstrap_property_t; typedef bootstrap_property_t *bootstrap_property_array_t; typedef boolean_t *bool_array_t; #define BOOTSTRAP_MAX_LOOKUP_COUNT 20 -#define BOOTSTRAP_SUCCESS 0 -#define BOOTSTRAP_NOT_PRIVILEGED 1100 -#define BOOTSTRAP_NAME_IN_USE 1101 +#define BOOTSTRAP_SUCCESS 0 +#define BOOTSTRAP_NOT_PRIVILEGED 1100 +#define BOOTSTRAP_NAME_IN_USE 1101 #define BOOTSTRAP_UNKNOWN_SERVICE 1102 -#define BOOTSTRAP_SERVICE_ACTIVE 1103 -#define BOOTSTRAP_BAD_COUNT 1104 -#define BOOTSTRAP_NO_MEMORY 1105 -#define BOOTSTRAP_NO_CHILDREN 1106 +#define BOOTSTRAP_SERVICE_ACTIVE 1103 +#define BOOTSTRAP_BAD_COUNT 1104 +#define BOOTSTRAP_NO_MEMORY 1105 +#define BOOTSTRAP_NO_CHILDREN 1106 -#define BOOTSTRAP_STATUS_INACTIVE 0 -#define BOOTSTRAP_STATUS_ACTIVE 1 +#define BOOTSTRAP_STATUS_INACTIVE 0 +#define BOOTSTRAP_STATUS_ACTIVE 1 #define BOOTSTRAP_STATUS_ON_DEMAND 2 XPC_EXPORT diff --git a/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/substrated/include/xpc/base.h b/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/substrated/include/xpc/base.h index 3e2ec23a..87b84dbc 100644 --- a/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/substrated/include/xpc/base.h +++ b/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/substrated/include/xpc/base.h @@ -41,32 +41,32 @@ __BEGIN_DECLS #pragma mark Attribute Shims #ifdef __GNUC__ -#define XPC_CONSTRUCTOR __attribute__((constructor)) -#define XPC_NORETURN __attribute__((__noreturn__)) -#define XPC_NOTHROW __attribute__((__nothrow__)) -#define XPC_NONNULL1 __attribute__((__nonnull__(1))) -#define XPC_NONNULL2 __attribute__((__nonnull__(2))) -#define XPC_NONNULL3 __attribute__((__nonnull__(3))) -#define XPC_NONNULL4 __attribute__((__nonnull__(4))) -#define XPC_NONNULL5 __attribute__((__nonnull__(5))) -#define XPC_NONNULL6 __attribute__((__nonnull__(6))) -#define XPC_NONNULL7 __attribute__((__nonnull__(7))) -#define XPC_NONNULL8 __attribute__((__nonnull__(8))) -#define XPC_NONNULL9 __attribute__((__nonnull__(9))) -#define XPC_NONNULL10 __attribute__((__nonnull__(10))) -#define XPC_NONNULL11 __attribute__((__nonnull__(11))) -#define XPC_NONNULL_ALL __attribute__((__nonnull__)) -#define XPC_SENTINEL __attribute__((__sentinel__)) -#define XPC_PURE __attribute__((__pure__)) -#define XPC_WARN_RESULT __attribute__((__warn_unused_result__)) -#define XPC_MALLOC __attribute__((__malloc__)) -#define XPC_UNUSED __attribute__((__unused__)) -#define XPC_USED __attribute__((__used__)) -#define XPC_PACKED __attribute__((__packed__)) +#define XPC_CONSTRUCTOR __attribute__((constructor)) +#define XPC_NORETURN __attribute__((__noreturn__)) +#define XPC_NOTHROW __attribute__((__nothrow__)) +#define XPC_NONNULL1 __attribute__((__nonnull__(1))) +#define XPC_NONNULL2 __attribute__((__nonnull__(2))) +#define XPC_NONNULL3 __attribute__((__nonnull__(3))) +#define XPC_NONNULL4 __attribute__((__nonnull__(4))) +#define XPC_NONNULL5 __attribute__((__nonnull__(5))) +#define XPC_NONNULL6 __attribute__((__nonnull__(6))) +#define XPC_NONNULL7 __attribute__((__nonnull__(7))) +#define XPC_NONNULL8 __attribute__((__nonnull__(8))) +#define XPC_NONNULL9 __attribute__((__nonnull__(9))) +#define XPC_NONNULL10 __attribute__((__nonnull__(10))) +#define XPC_NONNULL11 __attribute__((__nonnull__(11))) +#define XPC_NONNULL_ALL __attribute__((__nonnull__)) +#define XPC_SENTINEL __attribute__((__sentinel__)) +#define XPC_PURE __attribute__((__pure__)) +#define XPC_WARN_RESULT __attribute__((__warn_unused_result__)) +#define XPC_MALLOC __attribute__((__malloc__)) +#define XPC_UNUSED __attribute__((__unused__)) +#define XPC_USED __attribute__((__used__)) +#define XPC_PACKED __attribute__((__packed__)) #define XPC_PRINTF(m, n) __attribute__((format(printf, m, n))) -#define XPC_INLINE static __inline__ __attribute__((__always_inline__)) -#define XPC_NOINLINE __attribute__((noinline)) -#define XPC_NOIMPL __attribute__((unavailable)) +#define XPC_INLINE static __inline__ __attribute__((__always_inline__)) +#define XPC_NOINLINE __attribute__((noinline)) +#define XPC_NOIMPL __attribute__((unavailable)) #if __has_attribute(noescape) #define XPC_NOESCAPE __attribute__((__noescape__)) @@ -80,10 +80,10 @@ __BEGIN_DECLS #define XPC_UNAVAILABLE(m) XPC_NOIMPL #endif // __has_extension(attribute_unavailable_with_message) -#define XPC_EXPORT extern __attribute__((visibility("default"))) -#define XPC_NOEXPORT __attribute__((visibility("hidden"))) -#define XPC_WEAKIMPORT extern __attribute__((weak_import)) -#define XPC_DEBUGGER_EXCL XPC_NOEXPORT XPC_USED +#define XPC_EXPORT extern __attribute__((visibility("default"))) +#define XPC_NOEXPORT __attribute__((visibility("hidden"))) +#define XPC_WEAKIMPORT extern __attribute__((weak_import)) +#define XPC_DEBUGGER_EXCL XPC_NOEXPORT XPC_USED #define XPC_TRANSPARENT_UNION __attribute__((transparent_union)) #if __clang__ #define XPC_DEPRECATED(m) __attribute__((deprecated(m))) @@ -100,21 +100,21 @@ __BEGIN_DECLS #endif // __XPC_TEST__ #if __has_feature(objc_arc) -#define XPC_GIVES_REFERENCE __strong -#define XPC_UNRETAINED __unsafe_unretained -#define XPC_BRIDGE(xo) ((__bridge void *)(xo)) -#define XPC_BRIDGEREF_BEGIN(xo) ((__bridge_retained void *)(xo)) +#define XPC_GIVES_REFERENCE __strong +#define XPC_UNRETAINED __unsafe_unretained +#define XPC_BRIDGE(xo) ((__bridge void *)(xo)) +#define XPC_BRIDGEREF_BEGIN(xo) ((__bridge_retained void *)(xo)) #define XPC_BRIDGEREF_BEGIN_WITH_REF(xo) ((__bridge void *)(xo)) -#define XPC_BRIDGEREF_MIDDLE(xo) ((__bridge id)(xo)) -#define XPC_BRIDGEREF_END(xo) ((__bridge_transfer id)(xo)) +#define XPC_BRIDGEREF_MIDDLE(xo) ((__bridge id)(xo)) +#define XPC_BRIDGEREF_END(xo) ((__bridge_transfer id)(xo)) #else // __has_feature(objc_arc) #define XPC_GIVES_REFERENCE #define XPC_UNRETAINED -#define XPC_BRIDGE(xo) (xo) -#define XPC_BRIDGEREF_BEGIN(xo) (xo) +#define XPC_BRIDGE(xo) (xo) +#define XPC_BRIDGEREF_BEGIN(xo) (xo) #define XPC_BRIDGEREF_BEGIN_WITH_REF(xo) (xo) -#define XPC_BRIDGEREF_MIDDLE(xo) (xo) -#define XPC_BRIDGEREF_END(xo) (xo) +#define XPC_BRIDGEREF_MIDDLE(xo) (xo) +#define XPC_BRIDGEREF_END(xo) (xo) #endif // __has_feature(objc_arc) #define _xpc_unreachable() __builtin_unreachable() @@ -185,7 +185,7 @@ __BEGIN_DECLS #if __has_feature(assume_nonnull) #define XPC_ASSUME_NONNULL_BEGIN _Pragma("clang assume_nonnull begin") -#define XPC_ASSUME_NONNULL_END _Pragma("clang assume_nonnull end") +#define XPC_ASSUME_NONNULL_END _Pragma("clang assume_nonnull end") #else #define XPC_ASSUME_NONNULL_BEGIN #define XPC_ASSUME_NONNULL_END diff --git a/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/substrated/mach_interface_support/substrated_client.h b/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/substrated/mach_interface_support/substrated_client.h index f5c87eaa..8c44b3fb 100644 --- a/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/substrated/mach_interface_support/substrated_client.h +++ b/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/substrated/mach_interface_support/substrated_client.h @@ -64,7 +64,7 @@ extern int mig_strncpy_zerofill(char *dest, const char *src, int len) __attribut #define FUNCTION_PTR_T typedef void (*function_ptr_t)(mach_port_t, char *, mach_msg_type_number_t); typedef struct { - char * name; + char *name; function_ptr_t function; } function_table_entry; typedef function_table_entry *function_table_t; @@ -121,12 +121,12 @@ __END_DECLS typedef struct { mach_msg_header_t Head; /* start of the kernel processed data */ - mach_msg_body_t msgh_body; + mach_msg_body_t msgh_body; mach_msg_port_descriptor_t task; /* end of the kernel processed data */ - NDR_record_t NDR; + NDR_record_t NDR; mach_vm_address_t source_address; - mach_vm_size_t source_size; + mach_vm_size_t source_size; mach_vm_address_t target_address; } __Request__substrated_mark_t __attribute__((unused)); #ifdef __MigPackStructs @@ -152,8 +152,8 @@ union __RequestUnion__substrated_subsystem { #endif typedef struct { mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; + NDR_record_t NDR; + kern_return_t RetCode; mach_vm_address_t target_address; } __Reply__substrated_mark_t __attribute__((unused)); #ifdef __MigPackStructs diff --git a/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/substrated/mach_interface_support/substrated_server.h b/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/substrated/mach_interface_support/substrated_server.h index 57e29f70..605cc6ee 100644 --- a/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/substrated/mach_interface_support/substrated_server.h +++ b/module/src/main/cpp/Dobby/source/UserMode/ExecMemory/substrated/mach_interface_support/substrated_server.h @@ -64,7 +64,7 @@ extern int mig_strncpy_zerofill(char *dest, const char *src, int len) __attribut #define FUNCTION_PTR_T typedef void (*function_ptr_t)(mach_port_t, char *, mach_msg_type_number_t); typedef struct { - char * name; + char *name; function_ptr_t function; } function_table_entry; typedef function_table_entry *function_table_t; @@ -116,12 +116,12 @@ extern /* Description of this subsystem, for use in direct RPC */ extern const struct substrated_subsystem { - mig_server_routine_t server; /* Server routine */ - mach_msg_id_t start; /* Min routine number */ - mach_msg_id_t end; /* Max routine number + 1 */ - unsigned int maxsize; /* Max msg size */ - vm_address_t reserved; /* Reserved */ - struct routine_descriptor /*Array of routine descriptors */ + mig_server_routine_t server; /* Server routine */ + mach_msg_id_t start; /* Min routine number */ + mach_msg_id_t end; /* Max routine number + 1 */ + unsigned int maxsize; /* Max msg size */ + vm_address_t reserved; /* Reserved */ + struct routine_descriptor /*Array of routine descriptors */ routine[1]; } substrated_subsystem; @@ -136,12 +136,12 @@ extern const struct substrated_subsystem { typedef struct { mach_msg_header_t Head; /* start of the kernel processed data */ - mach_msg_body_t msgh_body; + mach_msg_body_t msgh_body; mach_msg_port_descriptor_t task; /* end of the kernel processed data */ - NDR_record_t NDR; + NDR_record_t NDR; mach_vm_address_t source_address; - mach_vm_size_t source_size; + mach_vm_size_t source_size; mach_vm_address_t target_address; } __Request__substrated_mark_t __attribute__((unused)); #ifdef __MigPackStructs @@ -167,8 +167,8 @@ union __RequestUnion__substrated_subsystem { #endif typedef struct { mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; + NDR_record_t NDR; + kern_return_t RetCode; mach_vm_address_t target_address; } __Reply__substrated_mark_t __attribute__((unused)); #ifdef __MigPackStructs diff --git a/module/src/main/cpp/Dobby/source/UserMode/MultiThreadSupport/ThreadSupport.h b/module/src/main/cpp/Dobby/source/UserMode/MultiThreadSupport/ThreadSupport.h index 416f9da0..06d997a1 100644 --- a/module/src/main/cpp/Dobby/source/UserMode/MultiThreadSupport/ThreadSupport.h +++ b/module/src/main/cpp/Dobby/source/UserMode/MultiThreadSupport/ThreadSupport.h @@ -32,7 +32,7 @@ class ThreadSupport { // Pop stack frame static StackFrame *PopStackFrame() { - CallStack * callstack = ThreadSupport::CurrentThreadCallStack(); + CallStack *callstack = ThreadSupport::CurrentThreadCallStack(); StackFrame *stackframe = callstack->stackframes.back(); callstack->stackframes.pop_back(); return stackframe; @@ -45,7 +45,7 @@ class ThreadSupport { }; static void *GetStackFrameContextValue(StackFrame *stackframe, char *key) { - std::map kv_context = stackframe->kv_context; + std::map kv_context = stackframe->kv_context; std::map::iterator it; it = kv_context.find(key); if (it != kv_context.end()) { diff --git a/module/src/main/cpp/Dobby/source/UserMode/PlatformUtil/Darwin/ProcesssRuntimeUtility.cc b/module/src/main/cpp/Dobby/source/UserMode/PlatformUtil/Darwin/ProcessRuntimeUtility.cc similarity index 88% rename from module/src/main/cpp/Dobby/source/UserMode/PlatformUtil/Darwin/ProcesssRuntimeUtility.cc rename to module/src/main/cpp/Dobby/source/UserMode/PlatformUtil/Darwin/ProcessRuntimeUtility.cc index 90af4ad5..9dfb4aab 100644 --- a/module/src/main/cpp/Dobby/source/UserMode/PlatformUtil/Darwin/ProcesssRuntimeUtility.cc +++ b/module/src/main/cpp/Dobby/source/UserMode/PlatformUtil/Darwin/ProcessRuntimeUtility.cc @@ -44,10 +44,10 @@ std::vector ProcessRuntimeUtility::GetProcessMemoryLayout() { std::vector ProcessMemoryLayout; struct vm_region_submap_short_info_64 submap_info; - mach_msg_type_number_t count = VM_REGION_SUBMAP_SHORT_INFO_COUNT_64; - mach_vm_address_t addr = 0; - mach_vm_size_t size = 0; - natural_t depth = 0; + mach_msg_type_number_t count = VM_REGION_SUBMAP_SHORT_INFO_COUNT_64; + mach_vm_address_t addr = 0; + mach_vm_size_t size = 0; + natural_t depth = 0; while (true) { count = VM_REGION_SUBMAP_SHORT_INFO_COUNT_64; kern_return_t kr = @@ -94,17 +94,17 @@ std::vector ProcessRuntimeUtility::GetProcessModuleMap() { std::vector ProcessModuleMap; kern_return_t kr; - task_dyld_info_data_t task_dyld_info; + task_dyld_info_data_t task_dyld_info; mach_msg_type_number_t count = TASK_DYLD_INFO_COUNT; - kr = task_info(mach_task_self_, TASK_DYLD_INFO, (task_info_t)&task_dyld_info, &count); + kr = task_info(mach_task_self_, TASK_DYLD_INFO, (task_info_t)&task_dyld_info, &count); if (kr != KERN_SUCCESS) { return ProcessModuleMap; } struct dyld_all_image_infos *infos = (struct dyld_all_image_infos *)task_dyld_info.all_image_info_addr; - const struct dyld_image_info *infoArray = infos->infoArray; + const struct dyld_image_info *infoArray = infos->infoArray; uint32_t infoArrayCount = infos->infoArrayCount; - + for (int i = 0; i < infoArrayCount; ++i) { const struct dyld_image_info *info = &infoArray[i]; diff --git a/module/src/main/cpp/Dobby/source/UserMode/PlatformUtil/Linux/ProcesssRuntimeUtility.cc b/module/src/main/cpp/Dobby/source/UserMode/PlatformUtil/Linux/ProcessRuntimeUtility.cc similarity index 92% rename from module/src/main/cpp/Dobby/source/UserMode/PlatformUtil/Linux/ProcesssRuntimeUtility.cc rename to module/src/main/cpp/Dobby/source/UserMode/PlatformUtil/Linux/ProcessRuntimeUtility.cc index e0e3abb0..97ca3965 100644 --- a/module/src/main/cpp/Dobby/source/UserMode/PlatformUtil/Linux/ProcesssRuntimeUtility.cc +++ b/module/src/main/cpp/Dobby/source/UserMode/PlatformUtil/Linux/ProcessRuntimeUtility.cc @@ -42,13 +42,13 @@ std::vector ProcessRuntimeUtility::GetProcessMemoryLayout() { break; } - addr_t region_start, region_end; - addr_t region_offset; - char permissions[5] = {'\0'}; // Ensure NUL-terminated string. - uint8_t dev_major = 0; - uint8_t dev_minor = 0; - long inode = 0; - int path_index = 0; + addr_t region_start, region_end; + addr_t region_offset; + char permissions[5] = {'\0'}; // Ensure NUL-terminated string. + uint8_t dev_major = 0; + uint8_t dev_minor = 0; + long inode = 0; + int path_index = 0; // Sample format from man 5 proc: // @@ -117,13 +117,13 @@ static std::vector get_process_map_with_proc_maps() { break; } - addr_t region_start, region_end; - addr_t region_offset; - char permissions[5] = {'\0'}; // Ensure NUL-terminated string. - uint8_t dev_major = 0; - uint8_t dev_minor = 0; - long inode = 0; - int path_index = 0; + addr_t region_start, region_end; + addr_t region_offset; + char permissions[5] = {'\0'}; // Ensure NUL-terminated string. + uint8_t dev_major = 0; + uint8_t dev_minor = 0; + long inode = 0; + int path_index = 0; // Sample format from man 5 proc: // diff --git a/module/src/main/cpp/Dobby/source/UserMode/PlatformUtil/ProcessRuntimeUtility.h b/module/src/main/cpp/Dobby/source/UserMode/PlatformUtil/ProcessRuntimeUtility.h index 86db4962..7eed5aef 100644 --- a/module/src/main/cpp/Dobby/source/UserMode/PlatformUtil/ProcessRuntimeUtility.h +++ b/module/src/main/cpp/Dobby/source/UserMode/PlatformUtil/ProcessRuntimeUtility.h @@ -7,7 +7,7 @@ #include typedef struct _RuntimeModule { - char path[1024]; + char path[1024]; void *load_address; } RuntimeModule; diff --git a/module/src/main/cpp/Dobby/source/UserMode/PlatformUtil/Windows/ProcesssRuntimeUtility.cc b/module/src/main/cpp/Dobby/source/UserMode/PlatformUtil/Windows/ProcessRuntimeUtility.cc similarity index 51% rename from module/src/main/cpp/Dobby/source/UserMode/PlatformUtil/Windows/ProcesssRuntimeUtility.cc rename to module/src/main/cpp/Dobby/source/UserMode/PlatformUtil/Windows/ProcessRuntimeUtility.cc index ce2d0ea5..02f3cf52 100644 --- a/module/src/main/cpp/Dobby/source/UserMode/PlatformUtil/Windows/ProcesssRuntimeUtility.cc +++ b/module/src/main/cpp/Dobby/source/UserMode/PlatformUtil/Windows/ProcessRuntimeUtility.cc @@ -2,6 +2,8 @@ #include +#include + #define LINE_MAX 2048 // ================================================================ @@ -11,12 +13,52 @@ static bool memory_region_comparator(MemoryRegion a, MemoryRegion b) { return (a.address > b.address); } + +// https://gist.github.com/jedwardsol/9d4fe1fd806043a5767affbd200088ca + + std::vector ProcessMemoryLayout; std::vector ProcessRuntimeUtility::GetProcessMemoryLayout() { if (!ProcessMemoryLayout.empty()) { ProcessMemoryLayout.clear(); } + + char *address{nullptr}; + MEMORY_BASIC_INFORMATION region; + + while(VirtualQuery(address,®ion,sizeof(region))) + { + address += region.RegionSize; + if (!(region.State & (MEM_COMMIT | MEM_RESERVE))) { + continue; + } + MemoryPermission permission = MemoryPermission::kNoAccess; + auto mask = PAGE_GUARD | PAGE_NOCACHE | PAGE_WRITECOMBINE; + switch(region.Protect & ~mask) + { + case PAGE_NOACCESS: + case PAGE_READONLY: + break; + + case PAGE_EXECUTE: + case PAGE_EXECUTE_READ: + permission = MemoryPermission::kReadExecute; + break; + + case PAGE_READWRITE: + case PAGE_WRITECOPY: + permission = MemoryPermission::kReadWrite; + break; + + case PAGE_EXECUTE_READWRITE: + case PAGE_EXECUTE_WRITECOPY: + permission = MemoryPermission::kReadWriteExecute; + break; + } + + ProcessMemoryLayout.push_back(MemoryRegion{(void *)region.BaseAddress, region.RegionSize, permission}); + } return ProcessMemoryLayout; } diff --git a/module/src/main/cpp/Dobby/source/UserMode/Thread/PlatformThread.h b/module/src/main/cpp/Dobby/source/UserMode/Thread/PlatformThread.h index 19acaa4a..ea030911 100644 --- a/module/src/main/cpp/Dobby/source/UserMode/Thread/PlatformThread.h +++ b/module/src/main/cpp/Dobby/source/UserMode/Thread/PlatformThread.h @@ -1,7 +1,7 @@ #ifndef USER_MODE_PLATFORM_THREAD_H #define USER_MODE_PLATFORM_THREAD_H -#include "common/headers/common_header.h" +#include "common_header.h" namespace zz { diff --git a/module/src/main/cpp/Dobby/source/UserMode/Thread/platform-thread-posix.cc b/module/src/main/cpp/Dobby/source/UserMode/Thread/platform-thread-posix.cc index 33b2aaf7..486618c7 100644 --- a/module/src/main/cpp/Dobby/source/UserMode/Thread/platform-thread-posix.cc +++ b/module/src/main/cpp/Dobby/source/UserMode/Thread/platform-thread-posix.cc @@ -47,7 +47,7 @@ static pthread_key_t LocalKeyToPthreadKey(OSThread::LocalStorageKey local_key) { OSThread::LocalStorageKey OSThread::CreateThreadLocalKey() { pthread_key_t key; - int result = pthread_key_create(&key, nullptr); + int result = pthread_key_create(&key, nullptr); DCHECK_EQ(0, result); LocalStorageKey local_key = PthreadKeyToLocalKey(key); return local_key; @@ -55,7 +55,7 @@ OSThread::LocalStorageKey OSThread::CreateThreadLocalKey() { void OSThread::DeleteThreadLocalKey(LocalStorageKey key) { pthread_key_t pthread_key = LocalKeyToPthreadKey(key); - int result = pthread_key_delete(pthread_key); + int result = pthread_key_delete(pthread_key); DCHECK_EQ(0, result); } @@ -66,6 +66,6 @@ void *OSThread::GetThreadLocal(LocalStorageKey key) { void OSThread::SetThreadLocal(LocalStorageKey key, void *value) { pthread_key_t pthread_key = LocalKeyToPthreadKey(key); - int result = pthread_setspecific(pthread_key, value); + int result = pthread_setspecific(pthread_key, value); DCHECK_EQ(0, result); } diff --git a/module/src/main/cpp/Dobby/source/UserMode/UnifiedInterface/platform-darwin/mach_vm.h b/module/src/main/cpp/Dobby/source/UserMode/UnifiedInterface/platform-darwin/mach_vm.h index cecbbbe4..a9cab322 100644 --- a/module/src/main/cpp/Dobby/source/UserMode/UnifiedInterface/platform-darwin/mach_vm.h +++ b/module/src/main/cpp/Dobby/source/UserMode/UnifiedInterface/platform-darwin/mach_vm.h @@ -40,7 +40,7 @@ extern int mig_strncpy_zerofill(char *dest, const char *src, int len) __attribut #define FUNCTION_PTR_T typedef void (*function_ptr_t)(mach_port_t, char *, mach_msg_type_number_t); typedef struct { - char * name; + char *name; function_ptr_t function; } function_table_entry; typedef function_table_entry *function_table_t; @@ -282,10 +282,10 @@ __END_DECLS #endif typedef struct { mach_msg_header_t Head; - NDR_record_t NDR; + NDR_record_t NDR; mach_vm_address_t address; - mach_vm_size_t size; - int flags; + mach_vm_size_t size; + int flags; } __Request__mach_vm_allocate_t __attribute__((unused)); #ifdef __MigPackStructs #pragma pack() @@ -296,9 +296,9 @@ typedef struct { #endif typedef struct { mach_msg_header_t Head; - NDR_record_t NDR; + NDR_record_t NDR; mach_vm_address_t address; - mach_vm_size_t size; + mach_vm_size_t size; } __Request__mach_vm_deallocate_t __attribute__((unused)); #ifdef __MigPackStructs #pragma pack() @@ -309,11 +309,11 @@ typedef struct { #endif typedef struct { mach_msg_header_t Head; - NDR_record_t NDR; + NDR_record_t NDR; mach_vm_address_t address; - mach_vm_size_t size; - boolean_t set_maximum; - vm_prot_t new_protection; + mach_vm_size_t size; + boolean_t set_maximum; + vm_prot_t new_protection; } __Request__mach_vm_protect_t __attribute__((unused)); #ifdef __MigPackStructs #pragma pack() @@ -324,10 +324,10 @@ typedef struct { #endif typedef struct { mach_msg_header_t Head; - NDR_record_t NDR; + NDR_record_t NDR; mach_vm_address_t address; - mach_vm_size_t size; - vm_inherit_t new_inheritance; + mach_vm_size_t size; + vm_inherit_t new_inheritance; } __Request__mach_vm_inherit_t __attribute__((unused)); #ifdef __MigPackStructs #pragma pack() @@ -338,9 +338,9 @@ typedef struct { #endif typedef struct { mach_msg_header_t Head; - NDR_record_t NDR; + NDR_record_t NDR; mach_vm_address_t address; - mach_vm_size_t size; + mach_vm_size_t size; } __Request__mach_vm_read_t __attribute__((unused)); #ifdef __MigPackStructs #pragma pack() @@ -350,10 +350,10 @@ typedef struct { #pragma pack(4) #endif typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; + mach_msg_header_t Head; + NDR_record_t NDR; mach_vm_read_entry_t data_list; - natural_t count; + natural_t count; } __Request__mach_vm_read_list_t __attribute__((unused)); #ifdef __MigPackStructs #pragma pack() @@ -365,11 +365,11 @@ typedef struct { typedef struct { mach_msg_header_t Head; /* start of the kernel processed data */ - mach_msg_body_t msgh_body; + mach_msg_body_t msgh_body; mach_msg_ool_descriptor_t data; /* end of the kernel processed data */ - NDR_record_t NDR; - mach_vm_address_t address; + NDR_record_t NDR; + mach_vm_address_t address; mach_msg_type_number_t dataCnt; } __Request__mach_vm_write_t __attribute__((unused)); #ifdef __MigPackStructs @@ -381,9 +381,9 @@ typedef struct { #endif typedef struct { mach_msg_header_t Head; - NDR_record_t NDR; + NDR_record_t NDR; mach_vm_address_t source_address; - mach_vm_size_t size; + mach_vm_size_t size; mach_vm_address_t dest_address; } __Request__mach_vm_copy_t __attribute__((unused)); #ifdef __MigPackStructs @@ -395,9 +395,9 @@ typedef struct { #endif typedef struct { mach_msg_header_t Head; - NDR_record_t NDR; + NDR_record_t NDR; mach_vm_address_t address; - mach_vm_size_t size; + mach_vm_size_t size; mach_vm_address_t data; } __Request__mach_vm_read_overwrite_t __attribute__((unused)); #ifdef __MigPackStructs @@ -409,10 +409,10 @@ typedef struct { #endif typedef struct { mach_msg_header_t Head; - NDR_record_t NDR; + NDR_record_t NDR; mach_vm_address_t address; - mach_vm_size_t size; - vm_sync_t sync_flags; + mach_vm_size_t size; + vm_sync_t sync_flags; } __Request__mach_vm_msync_t __attribute__((unused)); #ifdef __MigPackStructs #pragma pack() @@ -423,10 +423,10 @@ typedef struct { #endif typedef struct { mach_msg_header_t Head; - NDR_record_t NDR; + NDR_record_t NDR; mach_vm_address_t address; - mach_vm_size_t size; - vm_behavior_t new_behavior; + mach_vm_size_t size; + vm_behavior_t new_behavior; } __Request__mach_vm_behavior_set_t __attribute__((unused)); #ifdef __MigPackStructs #pragma pack() @@ -438,19 +438,19 @@ typedef struct { typedef struct { mach_msg_header_t Head; /* start of the kernel processed data */ - mach_msg_body_t msgh_body; + mach_msg_body_t msgh_body; mach_msg_port_descriptor_t object; /* end of the kernel processed data */ - NDR_record_t NDR; - mach_vm_address_t address; - mach_vm_size_t size; - mach_vm_offset_t mask; - int flags; + NDR_record_t NDR; + mach_vm_address_t address; + mach_vm_size_t size; + mach_vm_offset_t mask; + int flags; memory_object_offset_t offset; - boolean_t copy; - vm_prot_t curr_protection; - vm_prot_t max_protection; - vm_inherit_t inheritance; + boolean_t copy; + vm_prot_t curr_protection; + vm_prot_t max_protection; + vm_inherit_t inheritance; } __Request__mach_vm_map_t __attribute__((unused)); #ifdef __MigPackStructs #pragma pack() @@ -460,11 +460,11 @@ typedef struct { #pragma pack(4) #endif typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_vm_address_t address; - mach_vm_size_t size; - vm_machine_attribute_t attribute; + mach_msg_header_t Head; + NDR_record_t NDR; + mach_vm_address_t address; + mach_vm_size_t size; + vm_machine_attribute_t attribute; vm_machine_attribute_val_t value; } __Request__mach_vm_machine_attribute_t __attribute__((unused)); #ifdef __MigPackStructs @@ -477,17 +477,17 @@ typedef struct { typedef struct { mach_msg_header_t Head; /* start of the kernel processed data */ - mach_msg_body_t msgh_body; + mach_msg_body_t msgh_body; mach_msg_port_descriptor_t src_task; /* end of the kernel processed data */ - NDR_record_t NDR; + NDR_record_t NDR; mach_vm_address_t target_address; - mach_vm_size_t size; - mach_vm_offset_t mask; - int flags; + mach_vm_size_t size; + mach_vm_offset_t mask; + int flags; mach_vm_address_t src_address; - boolean_t copy; - vm_inherit_t inheritance; + boolean_t copy; + vm_inherit_t inheritance; } __Request__mach_vm_remap_t __attribute__((unused)); #ifdef __MigPackStructs #pragma pack() @@ -498,8 +498,8 @@ typedef struct { #endif typedef struct { mach_msg_header_t Head; - NDR_record_t NDR; - mach_vm_offset_t offset; + NDR_record_t NDR; + mach_vm_offset_t offset; } __Request__mach_vm_page_query_t __attribute__((unused)); #ifdef __MigPackStructs #pragma pack() @@ -509,10 +509,10 @@ typedef struct { #pragma pack(4) #endif typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_vm_address_t address; - natural_t nesting_depth; + mach_msg_header_t Head; + NDR_record_t NDR; + mach_vm_address_t address; + natural_t nesting_depth; mach_msg_type_number_t infoCnt; } __Request__mach_vm_region_recurse_t __attribute__((unused)); #ifdef __MigPackStructs @@ -523,10 +523,10 @@ typedef struct { #pragma pack(4) #endif typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_vm_address_t address; - vm_region_flavor_t flavor; + mach_msg_header_t Head; + NDR_record_t NDR; + mach_vm_address_t address; + vm_region_flavor_t flavor; mach_msg_type_number_t infoCnt; } __Request__mach_vm_region_t __attribute__((unused)); #ifdef __MigPackStructs @@ -539,13 +539,13 @@ typedef struct { typedef struct { mach_msg_header_t Head; /* start of the kernel processed data */ - mach_msg_body_t msgh_body; + mach_msg_body_t msgh_body; mach_msg_port_descriptor_t parent_handle; /* end of the kernel processed data */ - NDR_record_t NDR; - memory_object_size_t size; + NDR_record_t NDR; + memory_object_size_t size; memory_object_offset_t offset; - vm_prot_t permission; + vm_prot_t permission; } __Request___mach_make_memory_entry_t __attribute__((unused)); #ifdef __MigPackStructs #pragma pack() @@ -556,10 +556,10 @@ typedef struct { #endif typedef struct { mach_msg_header_t Head; - NDR_record_t NDR; + NDR_record_t NDR; mach_vm_address_t address; - vm_purgable_t control; - int state; + vm_purgable_t control; + int state; } __Request__mach_vm_purgable_control_t __attribute__((unused)); #ifdef __MigPackStructs #pragma pack() @@ -569,10 +569,10 @@ typedef struct { #pragma pack(4) #endif typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - mach_vm_address_t address; - vm_page_info_flavor_t flavor; + mach_msg_header_t Head; + NDR_record_t NDR; + mach_vm_address_t address; + vm_page_info_flavor_t flavor; mach_msg_type_number_t infoCnt; } __Request__mach_vm_page_info_t __attribute__((unused)); #ifdef __MigPackStructs @@ -585,26 +585,26 @@ typedef struct { #ifndef __RequestUnion__mach_vm_subsystem__defined #define __RequestUnion__mach_vm_subsystem__defined union __RequestUnion__mach_vm_subsystem { - __Request__mach_vm_allocate_t Request_mach_vm_allocate; - __Request__mach_vm_deallocate_t Request_mach_vm_deallocate; - __Request__mach_vm_protect_t Request_mach_vm_protect; - __Request__mach_vm_inherit_t Request_mach_vm_inherit; - __Request__mach_vm_read_t Request_mach_vm_read; - __Request__mach_vm_read_list_t Request_mach_vm_read_list; - __Request__mach_vm_write_t Request_mach_vm_write; - __Request__mach_vm_copy_t Request_mach_vm_copy; - __Request__mach_vm_read_overwrite_t Request_mach_vm_read_overwrite; - __Request__mach_vm_msync_t Request_mach_vm_msync; - __Request__mach_vm_behavior_set_t Request_mach_vm_behavior_set; - __Request__mach_vm_map_t Request_mach_vm_map; + __Request__mach_vm_allocate_t Request_mach_vm_allocate; + __Request__mach_vm_deallocate_t Request_mach_vm_deallocate; + __Request__mach_vm_protect_t Request_mach_vm_protect; + __Request__mach_vm_inherit_t Request_mach_vm_inherit; + __Request__mach_vm_read_t Request_mach_vm_read; + __Request__mach_vm_read_list_t Request_mach_vm_read_list; + __Request__mach_vm_write_t Request_mach_vm_write; + __Request__mach_vm_copy_t Request_mach_vm_copy; + __Request__mach_vm_read_overwrite_t Request_mach_vm_read_overwrite; + __Request__mach_vm_msync_t Request_mach_vm_msync; + __Request__mach_vm_behavior_set_t Request_mach_vm_behavior_set; + __Request__mach_vm_map_t Request_mach_vm_map; __Request__mach_vm_machine_attribute_t Request_mach_vm_machine_attribute; - __Request__mach_vm_remap_t Request_mach_vm_remap; - __Request__mach_vm_page_query_t Request_mach_vm_page_query; - __Request__mach_vm_region_recurse_t Request_mach_vm_region_recurse; - __Request__mach_vm_region_t Request_mach_vm_region; - __Request___mach_make_memory_entry_t Request__mach_make_memory_entry; - __Request__mach_vm_purgable_control_t Request_mach_vm_purgable_control; - __Request__mach_vm_page_info_t Request_mach_vm_page_info; + __Request__mach_vm_remap_t Request_mach_vm_remap; + __Request__mach_vm_page_query_t Request_mach_vm_page_query; + __Request__mach_vm_region_recurse_t Request_mach_vm_region_recurse; + __Request__mach_vm_region_t Request_mach_vm_region; + __Request___mach_make_memory_entry_t Request__mach_make_memory_entry; + __Request__mach_vm_purgable_control_t Request_mach_vm_purgable_control; + __Request__mach_vm_page_info_t Request_mach_vm_page_info; }; #endif /* !__RequestUnion__mach_vm_subsystem__defined */ /* typedefs for all replies */ @@ -617,8 +617,8 @@ union __RequestUnion__mach_vm_subsystem { #endif typedef struct { mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; + NDR_record_t NDR; + kern_return_t RetCode; mach_vm_address_t address; } __Reply__mach_vm_allocate_t __attribute__((unused)); #ifdef __MigPackStructs @@ -630,8 +630,8 @@ typedef struct { #endif typedef struct { mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; + NDR_record_t NDR; + kern_return_t RetCode; } __Reply__mach_vm_deallocate_t __attribute__((unused)); #ifdef __MigPackStructs #pragma pack() @@ -642,8 +642,8 @@ typedef struct { #endif typedef struct { mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; + NDR_record_t NDR; + kern_return_t RetCode; } __Reply__mach_vm_protect_t __attribute__((unused)); #ifdef __MigPackStructs #pragma pack() @@ -654,8 +654,8 @@ typedef struct { #endif typedef struct { mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; + NDR_record_t NDR; + kern_return_t RetCode; } __Reply__mach_vm_inherit_t __attribute__((unused)); #ifdef __MigPackStructs #pragma pack() @@ -667,10 +667,10 @@ typedef struct { typedef struct { mach_msg_header_t Head; /* start of the kernel processed data */ - mach_msg_body_t msgh_body; + mach_msg_body_t msgh_body; mach_msg_ool_descriptor_t data; /* end of the kernel processed data */ - NDR_record_t NDR; + NDR_record_t NDR; mach_msg_type_number_t dataCnt; } __Reply__mach_vm_read_t __attribute__((unused)); #ifdef __MigPackStructs @@ -681,9 +681,9 @@ typedef struct { #pragma pack(4) #endif typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; + mach_msg_header_t Head; + NDR_record_t NDR; + kern_return_t RetCode; mach_vm_read_entry_t data_list; } __Reply__mach_vm_read_list_t __attribute__((unused)); #ifdef __MigPackStructs @@ -695,8 +695,8 @@ typedef struct { #endif typedef struct { mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; + NDR_record_t NDR; + kern_return_t RetCode; } __Reply__mach_vm_write_t __attribute__((unused)); #ifdef __MigPackStructs #pragma pack() @@ -707,8 +707,8 @@ typedef struct { #endif typedef struct { mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; + NDR_record_t NDR; + kern_return_t RetCode; } __Reply__mach_vm_copy_t __attribute__((unused)); #ifdef __MigPackStructs #pragma pack() @@ -719,9 +719,9 @@ typedef struct { #endif typedef struct { mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - mach_vm_size_t outsize; + NDR_record_t NDR; + kern_return_t RetCode; + mach_vm_size_t outsize; } __Reply__mach_vm_read_overwrite_t __attribute__((unused)); #ifdef __MigPackStructs #pragma pack() @@ -732,8 +732,8 @@ typedef struct { #endif typedef struct { mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; + NDR_record_t NDR; + kern_return_t RetCode; } __Reply__mach_vm_msync_t __attribute__((unused)); #ifdef __MigPackStructs #pragma pack() @@ -744,8 +744,8 @@ typedef struct { #endif typedef struct { mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; + NDR_record_t NDR; + kern_return_t RetCode; } __Reply__mach_vm_behavior_set_t __attribute__((unused)); #ifdef __MigPackStructs #pragma pack() @@ -756,8 +756,8 @@ typedef struct { #endif typedef struct { mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; + NDR_record_t NDR; + kern_return_t RetCode; mach_vm_address_t address; } __Reply__mach_vm_map_t __attribute__((unused)); #ifdef __MigPackStructs @@ -768,9 +768,9 @@ typedef struct { #pragma pack(4) #endif typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; + mach_msg_header_t Head; + NDR_record_t NDR; + kern_return_t RetCode; vm_machine_attribute_val_t value; } __Reply__mach_vm_machine_attribute_t __attribute__((unused)); #ifdef __MigPackStructs @@ -782,11 +782,11 @@ typedef struct { #endif typedef struct { mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; + NDR_record_t NDR; + kern_return_t RetCode; mach_vm_address_t target_address; - vm_prot_t curr_protection; - vm_prot_t max_protection; + vm_prot_t curr_protection; + vm_prot_t max_protection; } __Reply__mach_vm_remap_t __attribute__((unused)); #ifdef __MigPackStructs #pragma pack() @@ -797,10 +797,10 @@ typedef struct { #endif typedef struct { mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - integer_t disposition; - integer_t ref_count; + NDR_record_t NDR; + kern_return_t RetCode; + integer_t disposition; + integer_t ref_count; } __Reply__mach_vm_page_query_t __attribute__((unused)); #ifdef __MigPackStructs #pragma pack() @@ -810,14 +810,14 @@ typedef struct { #pragma pack(4) #endif typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - mach_vm_address_t address; - mach_vm_size_t size; - natural_t nesting_depth; + mach_msg_header_t Head; + NDR_record_t NDR; + kern_return_t RetCode; + mach_vm_address_t address; + mach_vm_size_t size; + natural_t nesting_depth; mach_msg_type_number_t infoCnt; - int info[19]; + int info[19]; } __Reply__mach_vm_region_recurse_t __attribute__((unused)); #ifdef __MigPackStructs #pragma pack() @@ -829,14 +829,14 @@ typedef struct { typedef struct { mach_msg_header_t Head; /* start of the kernel processed data */ - mach_msg_body_t msgh_body; + mach_msg_body_t msgh_body; mach_msg_port_descriptor_t object_name; /* end of the kernel processed data */ - NDR_record_t NDR; - mach_vm_address_t address; - mach_vm_size_t size; + NDR_record_t NDR; + mach_vm_address_t address; + mach_vm_size_t size; mach_msg_type_number_t infoCnt; - int info[10]; + int info[10]; } __Reply__mach_vm_region_t __attribute__((unused)); #ifdef __MigPackStructs #pragma pack() @@ -848,10 +848,10 @@ typedef struct { typedef struct { mach_msg_header_t Head; /* start of the kernel processed data */ - mach_msg_body_t msgh_body; + mach_msg_body_t msgh_body; mach_msg_port_descriptor_t object_handle; /* end of the kernel processed data */ - NDR_record_t NDR; + NDR_record_t NDR; memory_object_size_t size; } __Reply___mach_make_memory_entry_t __attribute__((unused)); #ifdef __MigPackStructs @@ -863,9 +863,9 @@ typedef struct { #endif typedef struct { mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; - int state; + NDR_record_t NDR; + kern_return_t RetCode; + int state; } __Reply__mach_vm_purgable_control_t __attribute__((unused)); #ifdef __MigPackStructs #pragma pack() @@ -875,11 +875,11 @@ typedef struct { #pragma pack(4) #endif typedef struct { - mach_msg_header_t Head; - NDR_record_t NDR; - kern_return_t RetCode; + mach_msg_header_t Head; + NDR_record_t NDR; + kern_return_t RetCode; mach_msg_type_number_t infoCnt; - int info[32]; + int info[32]; } __Reply__mach_vm_page_info_t __attribute__((unused)); #ifdef __MigPackStructs #pragma pack() @@ -891,26 +891,26 @@ typedef struct { #ifndef __ReplyUnion__mach_vm_subsystem__defined #define __ReplyUnion__mach_vm_subsystem__defined union __ReplyUnion__mach_vm_subsystem { - __Reply__mach_vm_allocate_t Reply_mach_vm_allocate; - __Reply__mach_vm_deallocate_t Reply_mach_vm_deallocate; - __Reply__mach_vm_protect_t Reply_mach_vm_protect; - __Reply__mach_vm_inherit_t Reply_mach_vm_inherit; - __Reply__mach_vm_read_t Reply_mach_vm_read; - __Reply__mach_vm_read_list_t Reply_mach_vm_read_list; - __Reply__mach_vm_write_t Reply_mach_vm_write; - __Reply__mach_vm_copy_t Reply_mach_vm_copy; - __Reply__mach_vm_read_overwrite_t Reply_mach_vm_read_overwrite; - __Reply__mach_vm_msync_t Reply_mach_vm_msync; - __Reply__mach_vm_behavior_set_t Reply_mach_vm_behavior_set; - __Reply__mach_vm_map_t Reply_mach_vm_map; + __Reply__mach_vm_allocate_t Reply_mach_vm_allocate; + __Reply__mach_vm_deallocate_t Reply_mach_vm_deallocate; + __Reply__mach_vm_protect_t Reply_mach_vm_protect; + __Reply__mach_vm_inherit_t Reply_mach_vm_inherit; + __Reply__mach_vm_read_t Reply_mach_vm_read; + __Reply__mach_vm_read_list_t Reply_mach_vm_read_list; + __Reply__mach_vm_write_t Reply_mach_vm_write; + __Reply__mach_vm_copy_t Reply_mach_vm_copy; + __Reply__mach_vm_read_overwrite_t Reply_mach_vm_read_overwrite; + __Reply__mach_vm_msync_t Reply_mach_vm_msync; + __Reply__mach_vm_behavior_set_t Reply_mach_vm_behavior_set; + __Reply__mach_vm_map_t Reply_mach_vm_map; __Reply__mach_vm_machine_attribute_t Reply_mach_vm_machine_attribute; - __Reply__mach_vm_remap_t Reply_mach_vm_remap; - __Reply__mach_vm_page_query_t Reply_mach_vm_page_query; - __Reply__mach_vm_region_recurse_t Reply_mach_vm_region_recurse; - __Reply__mach_vm_region_t Reply_mach_vm_region; - __Reply___mach_make_memory_entry_t Reply__mach_make_memory_entry; - __Reply__mach_vm_purgable_control_t Reply_mach_vm_purgable_control; - __Reply__mach_vm_page_info_t Reply_mach_vm_page_info; + __Reply__mach_vm_remap_t Reply_mach_vm_remap; + __Reply__mach_vm_page_query_t Reply_mach_vm_page_query; + __Reply__mach_vm_region_recurse_t Reply_mach_vm_region_recurse; + __Reply__mach_vm_region_t Reply_mach_vm_region; + __Reply___mach_make_memory_entry_t Reply__mach_make_memory_entry; + __Reply__mach_vm_purgable_control_t Reply_mach_vm_purgable_control; + __Reply__mach_vm_page_info_t Reply_mach_vm_page_info; }; #endif /* !__RequestUnion__mach_vm_subsystem__defined */ diff --git a/module/src/main/cpp/Dobby/source/UserMode/UnifiedInterface/platform-posix.cc b/module/src/main/cpp/Dobby/source/UserMode/UnifiedInterface/platform-posix.cc index 5daddffa..e941179a 100644 --- a/module/src/main/cpp/Dobby/source/UserMode/UnifiedInterface/platform-posix.cc +++ b/module/src/main/cpp/Dobby/source/UserMode/UnifiedInterface/platform-posix.cc @@ -83,7 +83,7 @@ bool ThreadInterface::Create(ThreadInterface::Delegate *delegate, ThreadHandle * thread_handle_t *handle_impl = new thread_handle_t; int err = 0; - err = pthread_create(&(handle_impl->thread), nullptr, thread_handler_wrapper, delegate); + err = pthread_create(&(handle_impl->thread), nullptr, thread_handler_wrapper, delegate); if (err != 0) { FATAL("pthread create failed"); return false; @@ -121,6 +121,10 @@ static int GetProtectionFromMemoryPermission(MemoryPermission access) { UNREACHABLE(); } +int OSMemory::AllocPageSize() { + return OSMemory::PageSize(); +} + int OSMemory::PageSize() { return static_cast(sysconf(_SC_PAGESIZE)); } @@ -159,7 +163,7 @@ bool OSMemory::SetPermission(void *address, int size, MemoryPermission access) { DCHECK_EQ(0, size % PageSize()); int prot = GetProtectionFromMemoryPermission(access); - int ret = mprotect(address, size, prot); + int ret = mprotect(address, size, prot); if (ret == 0 && access == MemoryPermission::kNoAccess) { // This is advisory; ignore errors and continue execution. // ReclaimInaccessibleMemory(address, size); diff --git a/module/src/main/cpp/Dobby/source/UserMode/UnifiedInterface/platform-windows.cc b/module/src/main/cpp/Dobby/source/UserMode/UnifiedInterface/platform-windows.cc index b303fe1f..ef233253 100644 --- a/module/src/main/cpp/Dobby/source/UserMode/UnifiedInterface/platform-windows.cc +++ b/module/src/main/cpp/Dobby/source/UserMode/UnifiedInterface/platform-windows.cc @@ -2,6 +2,11 @@ #include + +#include "logging/logging.h" +#include "logging/check_logging.h" +#include "UnifiedInterface/platform.h" + int GetProtectionFromMemoryPermission(MemoryPermission access) { if (kReadWriteExecute == access) return PAGE_EXECUTE_READWRITE; @@ -9,14 +14,28 @@ int GetProtectionFromMemoryPermission(MemoryPermission access) { return PAGE_EXECUTE_READ; } +int OSMemory::AllocPageSize() { + static int lastRet = -1; + if (lastRet == -1) { + SYSTEM_INFO si; + GetSystemInfo(&si); + lastRet = si.dwAllocationGranularity; // should be used with VirtualAlloc(MEM_RESERVE) + } + return lastRet; +} + int OSMemory::PageSize() { - SYSTEM_INFO si; - GetSystemInfo(&si); - return si.dwPageSize; + static int lastRet = -1; + if (lastRet == -1) { + SYSTEM_INFO si; + GetSystemInfo(&si); + lastRet = si.dwPageSize; // should be used with VirtualAlloc(MEM_RESERVE) + } + return lastRet; } void *OSMemory::Allocate(void *address, int size, MemoryPermission access) { - DCHECK_EQ(0, reinterpret_cast(address) % PageSize()); + DCHECK_EQ(0, reinterpret_cast(address) % AllocPageSize()); DCHECK_EQ(0, size % PageSize()); void *result = VirtualAlloc(address, size, MEM_COMMIT | MEM_RESERVE, PAGE_NOACCESS); diff --git a/module/src/main/cpp/Dobby/source/UserMode/UnifiedInterface/platform.h b/module/src/main/cpp/Dobby/source/UserMode/UnifiedInterface/platform.h index 28755f5d..5330f8c1 100644 --- a/module/src/main/cpp/Dobby/source/UserMode/UnifiedInterface/platform.h +++ b/module/src/main/cpp/Dobby/source/UserMode/UnifiedInterface/platform.h @@ -14,9 +14,9 @@ class ThreadLocalStorageInterface { // Thread-local storage. static LocalStorageKey CreateThreadLocalKey(); - static void DeleteThreadLocalKey(LocalStorageKey key); - static void * GetThreadLocal(LocalStorageKey key); - static int GetThreadLocalInt(LocalStorageKey key) { + static void DeleteThreadLocalKey(LocalStorageKey key); + static void *GetThreadLocal(LocalStorageKey key); + static int GetThreadLocalInt(LocalStorageKey key) { return static_cast(reinterpret_cast(GetThreadLocal(key))); } static void SetThreadLocal(LocalStorageKey key, void *value); @@ -67,6 +67,8 @@ class Thread : public ThreadInterface, public ThreadInterface::Delegate { class OSMemory { public: static int PageSize(); + + static int AllocPageSize(); static void *Allocate(void *address, int size, MemoryPermission access); diff --git a/module/src/main/cpp/Dobby/source/UserMode/UnifiedInterface/semaphore.cc b/module/src/main/cpp/Dobby/source/UserMode/UnifiedInterface/semaphore.cc index 7eaf1872..12a15e02 100644 --- a/module/src/main/cpp/Dobby/source/UserMode/UnifiedInterface/semaphore.cc +++ b/module/src/main/cpp/Dobby/source/UserMode/UnifiedInterface/semaphore.cc @@ -79,8 +79,8 @@ void Semaphore::Wait() { bool Semaphore::WaitFor(const TimeDelta &rel_time) { // Compute the time for end of timeout. - const Time time = Time::NowFromSystemTime() + rel_time; - const struct timespec ts = time.ToTimespec(); + const Time time = Time::NowFromSystemTime() + rel_time; + const struct timespec ts = time.ToTimespec(); // Wait for semaphore signalled or timeout. while (true) { @@ -90,7 +90,7 @@ bool Semaphore::WaitFor(const TimeDelta &rel_time) { #if V8_LIBC_GLIBC && !V8_GLIBC_PREREQ(2, 4) if (result > 0) { // sem_timedwait in glibc prior to 2.3.4 returns the errno instead of -1. - errno = result; + errno = result; result = -1; } #endif diff --git a/module/src/main/cpp/Dobby/source/common/headers/common_header.h b/module/src/main/cpp/Dobby/source/common/headers/common_header.h deleted file mode 100644 index 73b0b2c5..00000000 --- a/module/src/main/cpp/Dobby/source/common/headers/common_header.h +++ /dev/null @@ -1,12 +0,0 @@ -#ifndef COMMON_HEADER_H -#define COMMON_HEADER_H - -#include "common/macros/constants_macro.h" -#include "common/macros/types_macro.h" -#include "common/macros/platform_macro.h" -#include "common/macros/utilities_macro.h" - -#include "logging/logging.h" -#include "logging/check_logging.h" - -#endif \ No newline at end of file diff --git a/module/src/main/cpp/Dobby/source/common/macros/constants_macro.h b/module/src/main/cpp/Dobby/source/common/macros/constants_macro.h deleted file mode 100644 index 05ac22a1..00000000 --- a/module/src/main/cpp/Dobby/source/common/macros/constants_macro.h +++ /dev/null @@ -1,8 +0,0 @@ - -#ifndef CONSTANTS_HEADER_H -#define CONSTANTS_HEADER_H - -#define RT_FAILED -1 -#define RT_SUCCESS 0 - -#endif \ No newline at end of file diff --git a/module/src/main/cpp/Dobby/source/core/arch/CpuFeature.h b/module/src/main/cpp/Dobby/source/core/arch/CpuFeature.h index 766ec618..302bb16a 100644 --- a/module/src/main/cpp/Dobby/source/core/arch/CpuFeature.h +++ b/module/src/main/cpp/Dobby/source/core/arch/CpuFeature.h @@ -1,7 +1,7 @@ #ifndef CORE_ARCH_CPU_FEATURE_H #define CORE_ARCH_CPU_FEATURE_H -#include "common/headers/common_header.h" +#include "common_header.h" class CpuFeatures { private: diff --git a/module/src/main/cpp/Dobby/source/core/arch/arm/constants-arm.h b/module/src/main/cpp/Dobby/source/core/arch/arm/constants-arm.h index 9b56f80a..b326d348 100644 --- a/module/src/main/cpp/Dobby/source/core/arch/arm/constants-arm.h +++ b/module/src/main/cpp/Dobby/source/core/arch/arm/constants-arm.h @@ -30,13 +30,13 @@ enum Shift { }; enum { - B0 = 1 << 0, - B4 = 1 << 4, - B5 = 1 << 5, - B6 = 1 << 6, - B7 = 1 << 7, - B8 = 1 << 8, - B9 = 1 << 9, + B0 = 1 << 0, + B4 = 1 << 4, + B5 = 1 << 5, + B6 = 1 << 6, + B7 = 1 << 7, + B8 = 1 << 8, + B9 = 1 << 9, B10 = 1 << 10, B12 = 1 << 12, B14 = 1 << 14, diff --git a/module/src/main/cpp/Dobby/source/core/arch/arm64/constants-arm64.h b/module/src/main/cpp/Dobby/source/core/arch/arm64/constants-arm64.h index 09dc7557..5540e6b1 100644 --- a/module/src/main/cpp/Dobby/source/core/arch/arm64/constants-arm64.h +++ b/module/src/main/cpp/Dobby/source/core/arch/arm64/constants-arm64.h @@ -1,7 +1,7 @@ #ifndef CORE_ARCH_CONSTANTS_ARM64_H #define CORE_ARCH_CONSTANTS_ARM64_H -#include "common/headers/common_header.h" +#include "common_header.h" enum Shift { NO_SHIFT = -1, LSL = 0x0, LSR = 0x1, ASR = 0x2, ROR = 0x3, MSL = 0x4 }; @@ -14,24 +14,24 @@ enum FlagsUpdate { SetFlags = 1, LeaveFlags = 0 }; enum InstructionFields { // Registers. - kRdShift = 0, - kRdBits = 5, - kRnShift = 5, - kRnBits = 5, - kRaShift = 10, - kRaBits = 5, - kRmShift = 16, - kRmBits = 5, - kRtShift = 0, - kRtBits = 5, + kRdShift = 0, + kRdBits = 5, + kRnShift = 5, + kRnBits = 5, + kRaShift = 10, + kRaBits = 5, + kRmShift = 16, + kRmBits = 5, + kRtShift = 0, + kRtBits = 5, kRt2Shift = 10, - kRt2Bits = 5, - kRsShift = 16, - kRsBits = 5, + kRt2Bits = 5, + kRsShift = 16, + kRsBits = 5, }; -#define OP(op) op +#define OP(op) op #define OP_W(op) op##_w #define OP_X(op) op##_x #define OP_B(op) op##_b @@ -40,7 +40,7 @@ enum InstructionFields { #define OP_D(op) op##_d #define OP_Q(op) op##_q -#define OPT(op, attribute) op##_##attribute +#define OPT(op, attribute) op##_##attribute #define OPT_W(op, attribute) op##_w_##attribute #define OPT_X(op, attribute) op##_x_##attribute #define OPT_B(op, attribute) op##_b_##attribute @@ -55,13 +55,13 @@ enum InstructionFields { enum ExceptionOp { ExceptionFixed = 0xD4000000, ExceptionFMask = 0xFF000000, - ExceptionMask = 0xFFE0001F, + ExceptionMask = 0xFFE0001F, - HLT = ExceptionFixed | 0x00400000, - BRK = ExceptionFixed | 0x00200000, - SVC = ExceptionFixed | 0x00000001, - HVC = ExceptionFixed | 0x00000002, - SMC = ExceptionFixed | 0x00000003, + HLT = ExceptionFixed | 0x00400000, + BRK = ExceptionFixed | 0x00200000, + SVC = ExceptionFixed | 0x00000001, + HVC = ExceptionFixed | 0x00000002, + SMC = ExceptionFixed | 0x00000003, DCPS1 = ExceptionFixed | 0x00A00001, DCPS2 = ExceptionFixed | 0x00A00002, DCPS3 = ExceptionFixed | 0x00A00003 @@ -71,11 +71,11 @@ enum ExceptionOp { // Unconditional branch. enum UnconditionalBranchOp { - UnconditionalBranchFixed = 0x14000000, + UnconditionalBranchFixed = 0x14000000, UnconditionalBranchFixedMask = 0x7C000000, - UnconditionalBranchMask = 0xFC000000, + UnconditionalBranchMask = 0xFC000000, - B = UnconditionalBranchFixed | 0x00000000, + B = UnconditionalBranchFixed | 0x00000000, BL = UnconditionalBranchFixed | 0x80000000 }; @@ -83,11 +83,11 @@ enum UnconditionalBranchOp { // Unconditional branch to register. enum UnconditionalBranchToRegisterOp { - UnconditionalBranchToRegisterFixed = 0xD6000000, + UnconditionalBranchToRegisterFixed = 0xD6000000, UnconditionalBranchToRegisterFixedMask = 0xFE000000, - UnconditionalBranchToRegisterMask = 0xFFFFFC1F, + UnconditionalBranchToRegisterMask = 0xFFFFFC1F, - BR = UnconditionalBranchToRegisterFixed | 0x001F0000, + BR = UnconditionalBranchToRegisterFixed | 0x001F0000, BLR = UnconditionalBranchToRegisterFixed | 0x003F0000, RET = UnconditionalBranchToRegisterFixed | 0x005F0000 }; @@ -95,15 +95,15 @@ enum UnconditionalBranchToRegisterOp { // ===== enum LoadRegLiteralOp { - LoadRegLiteralFixed = 0x18000000, + LoadRegLiteralFixed = 0x18000000, LoadRegLiteralFixedMask = 0x3B000000, - LoadRegLiteralMask = 0xFF000000, + LoadRegLiteralMask = 0xFF000000, #define LoadRegLiteralSub(opc, V) LoadRegLiteralFixed | LeftShift(opc, 2, 30) | LeftShift(V, 1, 26) OPT_W(LDR, literal) = LoadRegLiteralSub(0b00, 0), OPT_X(LDR, literal) = LoadRegLiteralSub(0b01, 0), OPT(LDRSW, literal) = LoadRegLiteralSub(0b10, 0), - OPT(PRFM, literal) = LoadRegLiteralSub(0b11, 0), + OPT(PRFM, literal) = LoadRegLiteralSub(0b11, 0), OPT_S(LDR, literal) = LoadRegLiteralSub(0b00, 1), OPT_D(LDR, literal) = LoadRegLiteralSub(0b01, 1), OPT_Q(LDR, literal) = LoadRegLiteralSub(0b10, 1), @@ -141,7 +141,7 @@ enum LoadRegLiteralOp { // Load/store enum LoadStoreOp { -#define LoadStoreOpSub(size, V, opc) LeftShift(size, 2, 30) | LeftShift(V, 1, 26) | LeftShift(opc, 2, 22) +#define LoadStoreOpSub(size, V, opc) LeftShift(size, 2, 30) | LeftShift(V, 1, 26) | LeftShift(opc, 2, 22) #define LOAD_STORE(opname, size, V, opc) OP(opname) = LoadStoreOpSub(size, V, opc) LOAD_STORE_OP_LIST(LOAD_STORE) #undef LOAD_STORE @@ -149,9 +149,9 @@ enum LoadStoreOp { // Load/store register offset. enum LoadStoreRegisterOffsetOp { - LoadStoreRegisterOffsetFixed = 0x38200800, + LoadStoreRegisterOffsetFixed = 0x38200800, LoadStoreRegisterOffsetFixedMask = 0x3B200C00, - LoadStoreRegisterOffsetMask = 0xFFE00C00, + LoadStoreRegisterOffsetMask = 0xFFE00C00, #define LoadStoreRegisterOffsetOpSub(size, V, opc) \ LoadStoreRegisterOffsetFixed | LeftShift(size, 2, 30) | LeftShift(V, 1, 26) | LeftShift(opc, 2, 22) @@ -163,9 +163,9 @@ enum LoadStoreRegisterOffsetOp { // Load/store register (unscaled immediate) enum LoadStoreUnscaledOffsetOp { - LoadStoreUnscaledOffsetFixed = 0x38000000, + LoadStoreUnscaledOffsetFixed = 0x38000000, LoadStoreUnscaledOffsetFixedMask = 0x3B200C00, - LoadStoreUnscaledOffsetMask = 0xFFE00C00, + LoadStoreUnscaledOffsetMask = 0xFFE00C00, #define LoadStoreUnscaledOffsetOpSub(size, V, opc) \ LoadStoreUnscaledOffsetFixed | LeftShift(size, 2, 30) | LeftShift(V, 1, 26) | LeftShift(opc, 2, 22) @@ -176,9 +176,9 @@ enum LoadStoreUnscaledOffsetOp { // Load/store unsigned offset. enum LoadStoreUnsignedOffset { - LoadStoreUnsignedOffsetFixed = 0x39000000, + LoadStoreUnsignedOffsetFixed = 0x39000000, LoadStoreUnsignedOffsetFixedMask = 0x3B000000, - LoadStoreUnsignedOffsetMask = 0xFFC00000, + LoadStoreUnsignedOffsetMask = 0xFFC00000, #define LoadStoreUnsignedOffsetSub(size, V, opc) \ LoadStoreUnsignedOffsetFixed | LeftShift(size, 2, 30) | LeftShift(V, 1, 26) | LeftShift(opc, 2, 22) @@ -206,16 +206,16 @@ enum LoadStoreUnsignedOffset { // clang-format on enum LoadStorePairOp { -#define LoadStorePairOpSub(opc, V, L) LeftShift(opc, 2, 30) | LeftShift(V, 1, 26) | LeftShift(L, 1, 22) +#define LoadStorePairOpSub(opc, V, L) LeftShift(opc, 2, 30) | LeftShift(V, 1, 26) | LeftShift(L, 1, 22) #define LOAD_STORE_PAIR(opname, opc, V, L) OP(opname) = LoadStorePairOpSub(opc, V, L) LOAD_STORE_PAIR_OP_LIST(LOAD_STORE_PAIR) #undef LOAD_STORE_PAIR }; enum LoadStorePairOffsetOp { - LoadStorePairOffsetFixed = 0x29000000, + LoadStorePairOffsetFixed = 0x29000000, LoadStorePairOffsetFixedMask = 0x3B800000, - LoadStorePairOffsetMask = 0xFFC00000, + LoadStorePairOffsetMask = 0xFFC00000, #define LoadStorePairOffsetOpSub(opc, V, L) \ LoadStorePairOffsetFixed | LeftShift(opc, 2, 30) | LeftShift(V, 1, 26) | LeftShift(L, 1, 22) @@ -225,9 +225,9 @@ enum LoadStorePairOffsetOp { }; enum LoadStorePairPostIndexOp { - LoadStorePairPostIndexFixed = 0x28800000, + LoadStorePairPostIndexFixed = 0x28800000, LoadStorePairPostIndexFixedMask = 0x3B800000, - LoadStorePairPostIndexMask = 0xFFC00000, + LoadStorePairPostIndexMask = 0xFFC00000, #define LoadStorePairPostOpSub(opc, V, L) \ LoadStorePairPostIndexFixed | LeftShift(opc, 2, 30) | LeftShift(V, 1, 26) | LeftShift(L, 1, 22) @@ -237,9 +237,9 @@ enum LoadStorePairPostIndexOp { }; enum LoadStorePairPreIndexOp { - LoadStorePairPreIndexFixed = 0x29800000, + LoadStorePairPreIndexFixed = 0x29800000, LoadStorePairPreIndexFixedMask = 0x3B800000, - LoadStorePairPreIndexMask = 0xFFC00000, + LoadStorePairPreIndexMask = 0xFFC00000, #define LoadStorePairPreOpSub(opc, V, L) \ LoadStorePairPreIndexFixed | LeftShift(opc, 2, 30) | LeftShift(V, 1, 26) | LeftShift(L, 1, 22) @@ -260,9 +260,9 @@ enum GenericInstrField { SixtyFourBits = 0x80000000, ThirtyTwoBits = 0x00000000, // Move wide immediate. enum MoveWideImmediateOp { - MoveWideImmediateFixed = 0x12800000, + MoveWideImmediateFixed = 0x12800000, MoveWideImmediateFixedMask = 0x1F800000, - MoveWideImmediateMask = 0xFF800000, + MoveWideImmediateMask = 0xFF800000, OP(MOVN) = 0x00000000, OP(MOVZ) = 0x40000000, @@ -280,53 +280,53 @@ enum MoveWideImmediateOp { // ===== enum AddSubImmediateOp { - AddSubImmediateFixed = 0x11000000, + AddSubImmediateFixed = 0x11000000, AddSubImmediateFixedMask = 0x1F000000, - AddSubImmediateMask = 0xFF000000, + AddSubImmediateMask = 0xFF000000, #define AddSubImmediateOpSub(sf, op, S) \ AddSubImmediateFixed | LeftShift(sf, 1, 31) | LeftShift(op, 1, 30) | LeftShift(S, 1, 29) - OPT_W(ADD, imm) = AddSubImmediateOpSub(0, 0, 0), + OPT_W(ADD, imm) = AddSubImmediateOpSub(0, 0, 0), OPT_W(ADDS, imm) = AddSubImmediateOpSub(0, 0, 1), - OPT_W(SUB, imm) = AddSubImmediateOpSub(0, 1, 0), + OPT_W(SUB, imm) = AddSubImmediateOpSub(0, 1, 0), OPT_W(SUBS, imm) = AddSubImmediateOpSub(0, 1, 1), - OPT_X(ADD, imm) = AddSubImmediateOpSub(1, 0, 0), + OPT_X(ADD, imm) = AddSubImmediateOpSub(1, 0, 0), OPT_X(ADDS, imm) = AddSubImmediateOpSub(1, 0, 1), - OPT_X(SUB, imm) = AddSubImmediateOpSub(1, 1, 0), + OPT_X(SUB, imm) = AddSubImmediateOpSub(1, 1, 0), OPT_X(SUBS, imm) = AddSubImmediateOpSub(1, 1, 1) }; enum AddSubShiftedOp { - AddSubShiftedFixed = 0x0B000000, + AddSubShiftedFixed = 0x0B000000, AddSubShiftedFixedMask = 0x1F200000, - AddSubShiftedMask = 0xFF200000, + AddSubShiftedMask = 0xFF200000, #define AddSubShiftedOpSub(sf, op, S) \ AddSubShiftedFixed | LeftShift(sf, 1, 31) | LeftShift(op, 1, 30) | LeftShift(S, 1, 29) - OPT_W(ADD, shift) = AddSubShiftedOpSub(0, 0, 0), + OPT_W(ADD, shift) = AddSubShiftedOpSub(0, 0, 0), OPT_W(ADDS, shift) = AddSubShiftedOpSub(0, 0, 1), - OPT_W(SUB, shift) = AddSubShiftedOpSub(0, 1, 0), + OPT_W(SUB, shift) = AddSubShiftedOpSub(0, 1, 0), OPT_W(SUBS, shift) = AddSubShiftedOpSub(0, 1, 1), - OPT_X(ADD, shift) = AddSubShiftedOpSub(1, 0, 0), + OPT_X(ADD, shift) = AddSubShiftedOpSub(1, 0, 0), OPT_X(ADDS, shift) = AddSubShiftedOpSub(1, 0, 1), - OPT_X(SUB, shift) = AddSubShiftedOpSub(1, 1, 0), + OPT_X(SUB, shift) = AddSubShiftedOpSub(1, 1, 0), OPT_X(SUBS, shift) = AddSubShiftedOpSub(1, 1, 1) }; enum AddSubExtendedOp { - AddSubExtendedFixed = 0x0B200000, + AddSubExtendedFixed = 0x0B200000, AddSubExtendedFixedMask = 0x1F200000, - AddSubExtendedMask = 0xFFE00000, + AddSubExtendedMask = 0xFFE00000, #define AddSubExtendedOpSub(sf, op, S) \ AddSubExtendedFixed | LeftShift(sf, 1, 31) | LeftShift(op, 1, 30) | LeftShift(S, 1, 29) - OPT_W(ADD, extend) = AddSubExtendedOpSub(0, 0, 0), + OPT_W(ADD, extend) = AddSubExtendedOpSub(0, 0, 0), OPT_W(ADDS, extend) = AddSubExtendedOpSub(0, 0, 1), - OPT_W(SUB, extend) = AddSubExtendedOpSub(0, 1, 0), + OPT_W(SUB, extend) = AddSubExtendedOpSub(0, 1, 0), OPT_W(SUBS, extend) = AddSubExtendedOpSub(0, 1, 1), - OPT_X(ADD, extend) = AddSubExtendedOpSub(1, 0, 0), + OPT_X(ADD, extend) = AddSubExtendedOpSub(1, 0, 0), OPT_X(ADDS, extend) = AddSubExtendedOpSub(1, 0, 1), - OPT_X(SUB, extend) = AddSubExtendedOpSub(1, 1, 0), + OPT_X(SUB, extend) = AddSubExtendedOpSub(1, 1, 0), OPT_X(SUBS, extend) = AddSubExtendedOpSub(1, 1, 1) }; @@ -335,25 +335,25 @@ enum AddSubExtendedOp { // Logical (immediate and shifted register). enum LogicalOp { LogicalOpMask = 0x60200000, - NOT = 0x00200000, - AND = 0x00000000, - BIC = AND | NOT, - ORR = 0x20000000, - ORN = ORR | NOT, - EOR = 0x40000000, - EON = EOR | NOT, - ANDS = 0x60000000, - BICS = ANDS | NOT + NOT = 0x00200000, + AND = 0x00000000, + BIC = AND | NOT, + ORR = 0x20000000, + ORN = ORR | NOT, + EOR = 0x40000000, + EON = EOR | NOT, + ANDS = 0x60000000, + BICS = ANDS | NOT }; // Logical immediate. enum LogicalImmediateOp { - LogicalImmediateFixed = 0x12000000, + LogicalImmediateFixed = 0x12000000, LogicalImmediateFixedMask = 0x1F800000, - LogicalImmediateMask = 0xFF800000, + LogicalImmediateMask = 0xFF800000, #define W_X_OP(opname, combine_fields) \ - OPT_W(opname, imm) = LogicalImmediateFixed | combine_fields | ThirtyTwoBits, \ + OPT_W(opname, imm) = LogicalImmediateFixed | combine_fields | ThirtyTwoBits, \ OPT_X(opname, imm) = LogicalImmediateFixed | combine_fields | SixtyFourBits #define W_X_OP_LIST(V) V(AND, AND), V(ORR, ORR), V(EOR, EOR), V(ANDS, ANDS) #undef W_X_OP @@ -362,12 +362,12 @@ enum LogicalImmediateOp { // Logical shifted register. enum LogicalShiftedOp { - LogicalShiftedFixed = 0x0A000000, + LogicalShiftedFixed = 0x0A000000, LogicalShiftedFixedMask = 0x1F000000, - LogicalShiftedMask = 0xFF200000, + LogicalShiftedMask = 0xFF200000, #define W_X_OP(opname, combine_fields) \ - OPT_W(opname, shift) = LogicalShiftedFixed | combine_fields | ThirtyTwoBits, \ + OPT_W(opname, shift) = LogicalShiftedFixed | combine_fields | ThirtyTwoBits, \ OPT_X(opname, shift) = LogicalShiftedFixed | combine_fields | SixtyFourBits #define W_X_OP_LIST(V) \ V(AND, AND), V(BIC, BIC), V(ORR, ORR), V(ORN, ORN), V(EOR, EOR), V(EON, EON), V(ANDS, ANDS), V(BICS, BICS) @@ -377,11 +377,11 @@ enum LogicalShiftedOp { // PC relative addressing. enum PCRelAddressingOp { - PCRelAddressingFixed = 0x10000000, + PCRelAddressingFixed = 0x10000000, PCRelAddressingFixedMask = 0x1F000000, - PCRelAddressingMask = 0x9F000000, - ADR = PCRelAddressingFixed | 0x00000000, - ADRP = PCRelAddressingFixed | 0x80000000 + PCRelAddressingMask = 0x9F000000, + ADR = PCRelAddressingFixed | 0x00000000, + ADRP = PCRelAddressingFixed | 0x80000000 }; #endif diff --git a/module/src/main/cpp/Dobby/source/core/arch/arm64/registers-arm64.h b/module/src/main/cpp/Dobby/source/core/arch/arm64/registers-arm64.h index f119f9d5..84a6d6b9 100644 --- a/module/src/main/cpp/Dobby/source/core/arch/arm64/registers-arm64.h +++ b/module/src/main/cpp/Dobby/source/core/arch/arm64/registers-arm64.h @@ -86,7 +86,7 @@ class CPURegister : RegisterBase { private: RegisterType reg_type_; - int reg_size_; + int reg_size_; }; typedef CPURegister Register; @@ -124,19 +124,19 @@ GENERAL_REGISTER_CODE_LIST(DEFINE_VREGISTERS) constexpr Register wzr = w31; constexpr Register xzr = x31; -constexpr Register SP = x31; +constexpr Register SP = x31; constexpr Register wSP = w31; -constexpr Register FP = x29; +constexpr Register FP = x29; constexpr Register wFP = w29; -constexpr Register LR = x30; +constexpr Register LR = x30; constexpr Register wLR = w30; } // namespace arm64 } // namespace zz -#define W(code) CPURegister::W(code) -#define X(code) CPURegister::X(code) -#define Q(code) CPURegister::Q(code) +#define W(code) CPURegister::W(code) +#define X(code) CPURegister::X(code) +#define Q(code) CPURegister::Q(code) #define InvalidRegister CPURegister::InvalidRegister() #endif diff --git a/module/src/main/cpp/Dobby/source/core/arch/x64/constants-x64.h b/module/src/main/cpp/Dobby/source/core/arch/x64/constants-x64.h index c2d06203..d72f44f4 100644 --- a/module/src/main/cpp/Dobby/source/core/arch/x64/constants-x64.h +++ b/module/src/main/cpp/Dobby/source/core/arch/x64/constants-x64.h @@ -5,11 +5,11 @@ namespace zz { namespace x64 { enum ScaleFactor { - TIMES_1 = 0, - TIMES_2 = 1, - TIMES_4 = 2, - TIMES_8 = 3, - TIMES_16 = 4, + TIMES_1 = 0, + TIMES_2 = 1, + TIMES_4 = 2, + TIMES_8 = 3, + TIMES_16 = 4, TIMES_HALF_WORD_SIZE = sizeof(void *) / 2 - 1 }; diff --git a/module/src/main/cpp/Dobby/source/core/arch/x64/registers-x64.h b/module/src/main/cpp/Dobby/source/core/arch/x64/registers-x64.h index ac73fef2..4c7c612b 100644 --- a/module/src/main/cpp/Dobby/source/core/arch/x64/registers-x64.h +++ b/module/src/main/cpp/Dobby/source/core/arch/x64/registers-x64.h @@ -125,7 +125,7 @@ class CPURegister : public RegisterBase { private: RegisterType reg_type_; - int reg_size_; + int reg_size_; }; typedef CPURegister Register; @@ -182,11 +182,11 @@ constexpr Register arg_reg_4 = rcx; V(xmm14) \ V(xmm15) -#define FLOAT_REGISTERS DOUBLE_REGISTERS +#define FLOAT_REGISTERS DOUBLE_REGISTERS #define SIMD128_REGISTERS DOUBLE_REGISTERS -constexpr bool kPadArguments = false; -constexpr bool kSimpleFPAliasing = true; +constexpr bool kPadArguments = false; +constexpr bool kSimpleFPAliasing = true; constexpr bool kSimdMaskRegisters = false; enum DoubleRegisterCode { diff --git a/module/src/main/cpp/Dobby/source/core/arch/x86/constants-x86.h b/module/src/main/cpp/Dobby/source/core/arch/x86/constants-x86.h index 2092a237..a243a76d 100644 --- a/module/src/main/cpp/Dobby/source/core/arch/x86/constants-x86.h +++ b/module/src/main/cpp/Dobby/source/core/arch/x86/constants-x86.h @@ -5,11 +5,11 @@ namespace zz { namespace x86 { enum ScaleFactor { - TIMES_1 = 0, - TIMES_2 = 1, - TIMES_4 = 2, - TIMES_8 = 3, - TIMES_16 = 4, + TIMES_1 = 0, + TIMES_2 = 1, + TIMES_4 = 2, + TIMES_8 = 3, + TIMES_16 = 4, TIMES_HALF_WORD_SIZE = sizeof(void *) / 2 - 1 }; diff --git a/module/src/main/cpp/Dobby/source/core/arch/x86/cpu-x86.cc b/module/src/main/cpp/Dobby/source/core/arch/x86/cpu-x86.cc index ad00aad9..ce241656 100644 --- a/module/src/main/cpp/Dobby/source/core/arch/x86/cpu-x86.cc +++ b/module/src/main/cpp/Dobby/source/core/arch/x86/cpu-x86.cc @@ -1,4 +1,4 @@ -#include "common/macros/platform_macro.h" +#include "platform_macro.h" #if defined(TARGET_ARCH_IA32) || defined(TARGET_ARCH_X64) #include "./cpu-x86.h" @@ -7,25 +7,25 @@ X86CpuInfo::X86CpuInfo() { icache_line_size_ = 0; dcache_line_size_ = 0; - has_fpu_ = false; - has_cmov_ = false; - has_sahf_ = false; - has_mmx_ = false; - has_sse_ = false; - has_sse2_ = false; - has_sse3_ = false; - has_ssse3_ = false; - has_sse41_ = false; + has_fpu_ = false; + has_cmov_ = false; + has_sahf_ = false; + has_mmx_ = false; + has_sse_ = false; + has_sse2_ = false; + has_sse3_ = false; + has_ssse3_ = false; + has_sse41_ = false; - has_sse42_ = false; + has_sse42_ = false; has_osxsave_ = false; - has_avx_ = false; - has_fma3_ = false; - has_bmi1_ = false; - has_bmi2_ = false; - has_lzcnt_ = false; - has_popcnt_ = false; - is_atom_ = false; + has_avx_ = false; + has_fma3_ = false; + has_bmi1_ = false; + has_bmi2_ = false; + has_lzcnt_ = false; + has_popcnt_ = false; + is_atom_ = false; _memcpy(vendor_, (void *)"Unknown", 8); #if V8_HOST_ARCH_IA32 || V8_HOST_ARCH_X64 @@ -39,25 +39,25 @@ X86CpuInfo::X86CpuInfo() { // Interpret CPU feature information. if (num_ids > 0) { __cpuid(cpu_info, 1); - stepping_ = cpu_info[0] & 0xF; - model_ = ((cpu_info[0] >> 4) & 0xF) + ((cpu_info[0] >> 12) & 0xF0); - family_ = (cpu_info[0] >> 8) & 0xF; - type_ = (cpu_info[0] >> 12) & 0x3; - ext_model_ = (cpu_info[0] >> 16) & 0xF; - ext_family_ = (cpu_info[0] >> 20) & 0xFF; - has_fpu_ = (cpu_info[3] & 0x00000001) != 0; - has_cmov_ = (cpu_info[3] & 0x00008000) != 0; - has_mmx_ = (cpu_info[3] & 0x00800000) != 0; - has_sse_ = (cpu_info[3] & 0x02000000) != 0; - has_sse2_ = (cpu_info[3] & 0x04000000) != 0; - has_sse3_ = (cpu_info[2] & 0x00000001) != 0; - has_ssse3_ = (cpu_info[2] & 0x00000200) != 0; - has_sse41_ = (cpu_info[2] & 0x00080000) != 0; - has_sse42_ = (cpu_info[2] & 0x00100000) != 0; - has_popcnt_ = (cpu_info[2] & 0x00800000) != 0; + stepping_ = cpu_info[0] & 0xF; + model_ = ((cpu_info[0] >> 4) & 0xF) + ((cpu_info[0] >> 12) & 0xF0); + family_ = (cpu_info[0] >> 8) & 0xF; + type_ = (cpu_info[0] >> 12) & 0x3; + ext_model_ = (cpu_info[0] >> 16) & 0xF; + ext_family_ = (cpu_info[0] >> 20) & 0xFF; + has_fpu_ = (cpu_info[3] & 0x00000001) != 0; + has_cmov_ = (cpu_info[3] & 0x00008000) != 0; + has_mmx_ = (cpu_info[3] & 0x00800000) != 0; + has_sse_ = (cpu_info[3] & 0x02000000) != 0; + has_sse2_ = (cpu_info[3] & 0x04000000) != 0; + has_sse3_ = (cpu_info[2] & 0x00000001) != 0; + has_ssse3_ = (cpu_info[2] & 0x00000200) != 0; + has_sse41_ = (cpu_info[2] & 0x00080000) != 0; + has_sse42_ = (cpu_info[2] & 0x00100000) != 0; + has_popcnt_ = (cpu_info[2] & 0x00800000) != 0; has_osxsave_ = (cpu_info[2] & 0x08000000) != 0; - has_avx_ = (cpu_info[2] & 0x10000000) != 0; - has_fma3_ = (cpu_info[2] & 0x00001000) != 0; + has_avx_ = (cpu_info[2] & 0x10000000) != 0; + has_fma3_ = (cpu_info[2] & 0x00001000) != 0; if (family_ == 0x6) { switch (model_) { case 0x1C: // SLT diff --git a/module/src/main/cpp/Dobby/source/core/arch/x86/cpu-x86.h b/module/src/main/cpp/Dobby/source/core/arch/x86/cpu-x86.h index 7089cc42..68fd62c3 100644 --- a/module/src/main/cpp/Dobby/source/core/arch/x86/cpu-x86.h +++ b/module/src/main/cpp/Dobby/source/core/arch/x86/cpu-x86.h @@ -79,8 +79,8 @@ class X86CpuInfo { char vendor_[13]; // General features - int icache_line_size_; - int dcache_line_size_; + int icache_line_size_; + int dcache_line_size_; bool has_fpu_; // x86 features diff --git a/module/src/main/cpp/Dobby/source/core/arch/x86/registers-x86.h b/module/src/main/cpp/Dobby/source/core/arch/x86/registers-x86.h index 94d06774..65b06b2b 100644 --- a/module/src/main/cpp/Dobby/source/core/arch/x86/registers-x86.h +++ b/module/src/main/cpp/Dobby/source/core/arch/x86/registers-x86.h @@ -58,7 +58,7 @@ class CPURegister : public RegisterBase { private: RegisterType reg_type_; - int reg_size_; + int reg_size_; }; typedef CPURegister Register; @@ -77,11 +77,11 @@ GENERAL_REGISTERS(DEFINE_REGISTER) V(xmm6) \ V(xmm7) -#define FLOAT_REGISTERS DOUBLE_REGISTERS +#define FLOAT_REGISTERS DOUBLE_REGISTERS #define SIMD128_REGISTERS DOUBLE_REGISTERS -constexpr bool kPadArguments = false; -constexpr bool kSimpleFPAliasing = true; +constexpr bool kPadArguments = false; +constexpr bool kSimpleFPAliasing = true; constexpr bool kSimdMaskRegisters = false; enum DoubleRegisterCode { diff --git a/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-arm.cc b/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-arm.cc index 640a8155..25f9d3e5 100644 --- a/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-arm.cc +++ b/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-arm.cc @@ -1,4 +1,4 @@ -#include "common/macros/platform_macro.h" +#include "platform_macro.h" #if TARGET_ARCH_ARM #include "core/modules/assembler/assembler-arm.h" diff --git a/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-arm.h b/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-arm.h index f38924c2..c4a87e89 100644 --- a/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-arm.h +++ b/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-arm.h @@ -1,7 +1,7 @@ #ifndef CORE_ASSEMBLER_ARM_H #define CORE_ASSEMBLER_ARM_H -#include "common/headers/common_header.h" +#include "common_header.h" #include "core/arch/arm/constants-arm.h" #include "core/arch/arm/registers-arm.h" @@ -18,11 +18,11 @@ namespace zz { namespace arm { // ARM design had a 3-stage pipeline (fetch-decode-execute) -#define ARM_PC_OFFSET 8 +#define ARM_PC_OFFSET 8 #define Thumb_PC_OFFSET 4 // define instruction length -#define ARM_INST_LEN 4 +#define ARM_INST_LEN 4 #define Thumb1_INST_LEN 2 #define Thumb2_INST_LEN 4 @@ -72,13 +72,13 @@ class PseudoLabel : public Label { for (size_t i = 0; i < instructions_.getCount(); i++) { PseudoLabelInstruction *instruction = (PseudoLabelInstruction *)instructions_.getObject(i); - int32_t offset = pos() - instruction->position_; - const int32_t inst32 = _buffer->LoadARMInst(instruction->position_); - int32_t encoded = 0; + int32_t offset = pos() - instruction->position_; + const int32_t inst32 = _buffer->LoadARMInst(instruction->position_); + int32_t encoded = 0; switch (instruction->type_) { case kLdrLiteral: { - encoded = inst32 & 0xfffff000; + encoded = inst32 & 0xfffff000; uint32_t imm12 = offset - ARM_PC_OFFSET; ASSERT(CheckSignLength(imm12)); encoded = encoded | imm12; @@ -94,8 +94,8 @@ class PseudoLabel : public Label { // compatible for thumb with int type void link_to(int pos, int type) { PseudoLabelInstruction *instruction = new PseudoLabelInstruction; - instruction->position_ = pos; - instruction->type_ = type; + instruction->position_ = pos; + instruction->type_ = type; instructions_.pushObject((LiteObject *)instruction); } @@ -154,7 +154,7 @@ class Operand { Register rs_; Shift shift_; - int shift_imm_; + int shift_imm_; int imm_; @@ -210,7 +210,7 @@ class MemOperand { int32_t offset_; // valid if rm_ == no_reg - Shift shift_; + Shift shift_; uint32_t shift_imm_; // valid if rm_ != no_reg && rs_ == no_reg AddrMode addrmode_; // bits P, U, and W @@ -278,14 +278,14 @@ class Assembler : public AssemblerBase { public: Assembler(void *address) : AssemblerBase(address) { execute_state_ = ARMExecuteState; - buffer_ = new CodeBuffer(64); + buffer_ = new CodeBuffer(64); } // shared_ptr is better choice // but we can't use it at kernelspace Assembler(void *address, CodeBuffer *buffer) : AssemblerBase(address) { execute_state_ = ARMExecuteState; - buffer_ = buffer; + buffer_ = buffer; } void ClearCodeBuffer() { diff --git a/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-arm64.cc b/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-arm64.cc index 18442588..0b83ce43 100644 --- a/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-arm64.cc +++ b/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-arm64.cc @@ -1,4 +1,4 @@ -#include "common/macros/platform_macro.h" +#include "platform_macro.h" #if TARGET_ARCH_ARM64 #include "core/modules/assembler/assembler-arm64.h" @@ -17,23 +17,23 @@ void Assembler::EmitInt64(int64_t value) { void Assembler::bind(Label *label) { const intptr_t bound_pc = pc_offset(); while (label->is_linked()) { - int linkpos = label->pos(); - int32_t instr = buffer_->LoadInst(linkpos); + int linkpos = label->pos(); + int32_t instr = buffer_->LoadInst(linkpos); int prevlinkpos = 0; if ((instr & UnconditionalBranchMask) == UnconditionalBranchFixed) { int32_t imm26 = 0; // fix the b-instr - int offset = bound_pc - linkpos; - imm26 = bits(offset >> 2, 0, 25); + int offset = bound_pc - linkpos; + imm26 = bits(offset >> 2, 0, 25); int32_t rewrite_inst = (instr & 0xfc000000) | LeftShift(imm26, 26, 0); buffer_->FixBindLabel(linkpos, rewrite_inst); // caculate next label - imm26 = bits(instr, 0, 25); + imm26 = bits(instr, 0, 25); int next_label_offset = imm26 << 2; - prevlinkpos = linkpos - next_label_offset; + prevlinkpos = linkpos - next_label_offset; } if ((linkpos - prevlinkpos) == kStartOfLabelLinkChain) { diff --git a/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-arm64.h b/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-arm64.h index 7f4b2270..4aeb4c01 100644 --- a/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-arm64.h +++ b/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-arm64.h @@ -1,7 +1,7 @@ #ifndef CORE_ASSEMBLER_ARM64_H #define CORE_ASSEMBLER_ARM64_H -#include "common/headers/common_header.h" +#include "common_header.h" #include "core/arch/arm64/constants-arm64.h" #include "core/arch/arm64/registers-arm64.h" @@ -35,11 +35,11 @@ namespace arm64 { constexpr Register TMP_REG_0 = X(ARM64_TMP_REG_NDX_0); -#define Rd(rd) (rd.code() << kRdShift) -#define Rt(rt) (rt.code() << kRtShift) +#define Rd(rd) (rd.code() << kRdShift) +#define Rt(rt) (rt.code() << kRtShift) #define Rt2(rt) (rt.code() << kRt2Shift) -#define Rn(rn) (rn.code() << kRnShift) -#define Rm(rm) (rm.code() << kRmShift) +#define Rn(rn) (rn.code() << kRnShift) +#define Rm(rm) (rm.code() << kRmShift) // ================================================================ // PseudoLabel @@ -49,7 +49,7 @@ class PseudoLabel : public Label { enum PseudoLabelType { kLdrLiteral }; typedef struct _PseudoLabelInstruction { - int position_; + int position_; PseudoLabelType type_; } PseudoLabelInstruction; @@ -77,9 +77,9 @@ class PseudoLabel : public Label { for (size_t i = 0; i < instructions_.getCount(); i++) { PseudoLabelInstruction *instruction = (PseudoLabelInstruction *)instructions_.getObject(i); - int32_t offset = pos() - instruction->position_; - const int32_t inst32 = _buffer->LoadInst(instruction->position_); - int32_t encoded = 0; + int32_t offset = pos() - instruction->position_; + const int32_t inst32 = _buffer->LoadInst(instruction->position_); + int32_t encoded = 0; switch (instruction->type_) { case kLdrLiteral: { @@ -96,8 +96,8 @@ class PseudoLabel : public Label { void link_to(int pos, PseudoLabelType type) { PseudoLabelInstruction *instruction = new PseudoLabelInstruction; - instruction->position_ = pos; - instruction->type_ = type; + instruction->position_ = pos; + instruction->type_ = type; instructions_.pushObject((LiteObject *)instruction); } @@ -182,8 +182,8 @@ class Operand { Register reg_; - Shift shift_; - Extend extend_; + Shift shift_; + Extend extend_; int32_t shift_extent_imm_; }; @@ -210,18 +210,18 @@ class MemOperand { inline explicit MemOperand(Register base, const Operand &offset, AddrMode addrmode = Offset) : base_(base), regoffset_(InvalidRegister), addrmode_(addrmode) { if (offset.IsShiftedRegister()) { - regoffset_ = offset.reg(); - shift_ = offset.shift(); + regoffset_ = offset.reg(); + shift_ = offset.shift(); shift_extend_imm_ = offset.shift_extend_imm(); extend_ = NO_EXTEND; offset_ = 0; } else if (offset.IsExtendedRegister()) { - regoffset_ = offset.reg(); - extend_ = offset.extend(); + regoffset_ = offset.reg(); + extend_ = offset.extend(); shift_extend_imm_ = offset.shift_extend_imm(); - shift_ = NO_SHIFT; + shift_ = NO_SHIFT; offset_ = 0; } } @@ -267,8 +267,8 @@ class MemOperand { int64_t offset_; - Shift shift_; - Extend extend_; + Shift shift_; + Extend extend_; uint32_t shift_extend_imm_; AddrMode addrmode_; @@ -320,7 +320,7 @@ class OpEncode { int32_t N, imms, immr; immr = bits(imm, 0, 5); imms = bits(imm, 6, 11); - N = bit(imm, 12); + N = bit(imm, 12); return (sf(rd) | LeftShift(immr, 6, 16) | LeftShift(imms, 6, 10) | Rd(rd) | Rn(rn)); } @@ -334,8 +334,8 @@ class OpEncode { // LoadStore static int32_t LoadStorePair(LoadStorePairOp op, CPURegister rt, CPURegister rt2, const MemOperand &addr) { int32_t scale = 2; - int32_t opc = 0; - int imm7; + int32_t opc = 0; + int imm7; opc = bits(op, 30, 31); if (rt.IsRegister()) { scale += bit(opc, 1); @@ -527,7 +527,7 @@ class Assembler : public AssemblerBase { private: // label helpers. static constexpr int kStartOfLabelLinkChain = 0; - int LinkAndGetByteOffsetTo(Label *label); + int LinkAndGetByteOffsetTo(Label *label); // load helpers. void EmitLoadRegLiteral(LoadRegLiteralOp op, CPURegister rt, int64_t imm) { @@ -578,7 +578,7 @@ class Assembler : public AssemblerBase { void AddSubImmediate(const Register &rd, const Register &rn, const Operand &operand, AddSubImmediateOp op) { if (operand.IsImmediate()) { int64_t immediate = operand.Immediate(); - int32_t imm12 = LeftShift(immediate, 12, 10); + int32_t imm12 = LeftShift(immediate, 12, 10); Emit(op | Rd(rd) | Rn(rn) | imm12); } else { UNREACHABLE(); @@ -652,8 +652,8 @@ class TurboAssembler : public Assembler { } void AdrpAdd(Register rd, uint64_t from, uint64_t to) { - uint64_t from_PAGE = ALIGN(from, 0x1000); - uint64_t to_PAGE = ALIGN(to, 0x1000); + uint64_t from_PAGE = ALIGN(from, 0x1000); + uint64_t to_PAGE = ALIGN(to, 0x1000); uint64_t to_PAGEOFF = (uint64_t)to % 0x1000; adrp(rd, to_PAGE - from_PAGE); diff --git a/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-ia32.cc b/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-ia32.cc index b0feb19b..6fb2cb08 100644 --- a/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-ia32.cc +++ b/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-ia32.cc @@ -1,4 +1,4 @@ -#include "common/macros/platform_macro.h" +#include "platform_macro.h" #if TARGET_ARCH_IA32 #include "core/modules/assembler/assembler-ia32.h" diff --git a/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-ia32.h b/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-ia32.h index 2dc11066..44f75e2b 100644 --- a/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-ia32.h +++ b/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-ia32.h @@ -1,7 +1,7 @@ #ifndef CORE_ASSEMBLER_X86_H #define CORE_ASSEMBLER_X86_H -#include "common/headers/common_header.h" +#include "common_header.h" #include "core/arch/x86/registers-x86.h" #include "core/modules/assembler/assembler.h" @@ -26,7 +26,7 @@ class PseudoLabel : public Label { enum PseudoLabelType { kDisp32_off_7 }; typedef struct _PseudoLabelInstruction { - int position_; + int position_; PseudoLabelType type_; } PseudoLabelInstruction; @@ -74,8 +74,8 @@ class PseudoLabel : public Label { void link_to(int pos, PseudoLabelType type) { PseudoLabelInstruction *instruction = new PseudoLabelInstruction; - instruction->position_ = pos; - instruction->type_ = type; + instruction->position_ = pos; + instruction->type_ = type; instructions_.pushObject((LiteObject *)instruction); } @@ -99,9 +99,9 @@ class RelocLabelEntry : public PseudoLabel { int data_size_; }; -#define ModRM_Mod(byte) ((byte & 0b11000000) >> 6) +#define ModRM_Mod(byte) ((byte & 0b11000000) >> 6) #define ModRM_RegOpcode(byte) ((byte & 0b00111000) >> 3) -#define ModRM_RM(byte) (byte & 0b00000111) +#define ModRM_RM(byte) (byte & 0b00000111) typedef union _ModRM { byte_t ModRM; @@ -203,14 +203,14 @@ class Operand { void SetModRM(int mod, Register rm) { ASSERT((mod & ~3) == 0); encoding_[0] = (mod << 6) | rm.code(); - length_ = 1; + length_ = 1; } void SetSIB(ScaleFactor scale, Register index, Register base) { ASSERT(length_ == 1); ASSERT((scale & ~3) == 0); encoding_[1] = (scale << 6) | (index.code() << 3) | base.code(); - length_ = 2; + length_ = 2; } void SetDisp8(int8_t disp) { @@ -245,8 +245,8 @@ class Address : public Operand { public: Address(Register base, int32_t disp) { int base_ = base.code(); - int ebp_ = ebp.code(); - int esp_ = esp.code(); + int ebp_ = ebp.code(); + int esp_ = esp.code(); if ((disp == 0) && (base_ != ebp_)) { SetModRM(0, base); if (base_ == esp_) diff --git a/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-x64.cc b/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-x64.cc index ecf8954e..dee32526 100644 --- a/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-x64.cc +++ b/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-x64.cc @@ -1,4 +1,4 @@ -#include "common/macros/platform_macro.h" +#include "platform_macro.h" #if defined(TARGET_ARCH_X64) #include "core/modules/assembler/assembler-x64.h" diff --git a/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-x64.h b/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-x64.h index 791979ef..f13e2b73 100644 --- a/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-x64.h +++ b/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-x64.h @@ -1,7 +1,7 @@ #ifndef CORE_ASSEMBLER_X86_SHARED_H #define CORE_ASSEMBLER_X86_SHARED_H -#include "common/headers/common_header.h" +#include "common_header.h" #include "core/arch/x64/registers-x64.h" #include "core/modules/assembler/assembler.h" @@ -26,7 +26,7 @@ class PseudoLabel : public Label { enum PseudoLabelType { kDisp32_off_9 }; typedef struct _PseudoLabelInstruction { - int position_; + int position_; PseudoLabelType type_; } PseudoLabelInstruction; @@ -35,7 +35,7 @@ class PseudoLabel : public Label { } ~PseudoLabel(void) { - for (size_t i = 0; i < instructions_.getCount(); i++) { + for (unsigned i = 0; i < instructions_.getCount(); i++) { PseudoLabelInstruction *item = (PseudoLabelInstruction *)instructions_.getObject(i); delete item; } @@ -52,7 +52,7 @@ class PseudoLabel : public Label { UNREACHABLE(); CodeBuffer *_buffer = buffer; - for (size_t i = 0; i < instructions_.getCount(); i++) { + for (unsigned i = 0; i < instructions_.getCount(); i++) { PseudoLabelInstruction *instruction = (PseudoLabelInstruction *)instructions_.getObject(i); int32_t offset = pos() - instruction->position_; @@ -75,8 +75,8 @@ class PseudoLabel : public Label { void link_to(int pos, PseudoLabelType type) { PseudoLabelInstruction *instruction = new PseudoLabelInstruction; - instruction->position_ = pos; - instruction->type_ = type; + instruction->position_ = pos; + instruction->type_ = type; instructions_.pushObject((LiteObject *)instruction); } @@ -100,9 +100,9 @@ class RelocLabelEntry : public PseudoLabel { int data_size_; }; -#define ModRM_Mod(byte) ((byte & 0b11000000) >> 6) +#define ModRM_Mod(byte) ((byte & 0b11000000) >> 6) #define ModRM_RegOpcode(byte) ((byte & 0b00111000) >> 3) -#define ModRM_RM(byte) (byte & 0b00000111) +#define ModRM_RM(byte) (byte & 0b00000111) typedef union _ModRM { byte_t ModRM; @@ -233,7 +233,7 @@ class Operand { rex_ |= REX_B; } encoding_[0] = (mod << 6) | (rm.code() & 7); - length_ = 1; + length_ = 1; } void SetSIB(ScaleFactor scale, Register index, Register base) { @@ -248,7 +248,7 @@ class Operand { rex_ |= REX_X; encoding_[1] = (scale << 6) | ((index.code() & 7) << 3) | (base.code() & 7); - length_ = 2; + length_ = 2; } void SetDisp8(int8_t disp) { @@ -286,8 +286,8 @@ class Address : public Operand { public: Address(Register base, int32_t disp) { int base_ = base.code(); - int rbp_ = rbp.code(); - int rsp_ = rsp.code(); + int rbp_ = rbp.code(); + int rsp_ = rsp.code(); if ((disp == 0) && ((base_ & 7) != rbp_)) { SetModRM(0, base); if ((base_ & 7) == rsp_) { @@ -661,7 +661,7 @@ class TurboAssembler : public Assembler { ~TurboAssembler() { if (data_labels_) { - for (size_t i = 0; i < data_labels_->getCount(); i++) { + for (unsigned i = 0; i < data_labels_->getCount(); i++) { RelocLabelEntry *label = (RelocLabelEntry *)data_labels_->getObject(i); delete label; } @@ -698,7 +698,7 @@ class TurboAssembler : public Assembler { // RelocLabelEntry void PseudoBind(PseudoLabel *label) { - const addr_t bound_pc = buffer_->getSize(); + const uint32_t bound_pc = buffer_->getSize(); label->bind_to(bound_pc); // If some instructions have been wrote, before the label bound, we need link these `confused` instructions if (label->has_confused_instructions()) { @@ -709,7 +709,7 @@ class TurboAssembler : public Assembler { void RelocBind() { if (data_labels_ == NULL) return; - for (size_t i = 0; i < data_labels_->getCount(); i++) { + for (unsigned i = 0; i < data_labels_->getCount(); i++) { RelocLabelEntry *label = (RelocLabelEntry *)data_labels_->getObject(i); PseudoBind(label); EmitInt64(label->data()); diff --git a/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-x86-shared.cc b/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-x86-shared.cc index afef77d6..f5f560c7 100644 --- a/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-x86-shared.cc +++ b/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-x86-shared.cc @@ -1,4 +1,4 @@ -#include "common/macros/platform_macro.h" +#include "platform_macro.h" #if defined(TARGET_ARCH_X64) || defined(TARGET_ARCH_IA32) #include "core/modules/assembler/assembler-x86-shared.h" diff --git a/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-x86-shared.h b/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-x86-shared.h index f512f030..a5cf76d3 100644 --- a/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-x86-shared.h +++ b/module/src/main/cpp/Dobby/source/core/modules/assembler/assembler-x86-shared.h @@ -1,7 +1,7 @@ #ifndef CORE_ASSEMBLER_X64_H #define CORE_ASSEMBLER_X64_H -#include "common/headers/common_header.h" +#include "common_header.h" #include "core/arch/x64/registers-x64.h" #include "core/modules/assembler/assembler.h" @@ -28,7 +28,7 @@ class PseudoLabel : public Label { enum PseudoLabelType { kDisp32_off_9 }; typedef struct _PseudoLabelInstruction { - int position_; + int position_; PseudoLabelType type_; } PseudoLabelInstruction; @@ -73,8 +73,8 @@ class PseudoLabel : public Label { void link_to(int pos, PseudoLabelType type) { PseudoLabelInstruction *instruction = new PseudoLabelInstruction; - instruction->position_ = pos; - instruction->type_ = type; + instruction->position_ = pos; + instruction->type_ = type; instructions_.pushObject((LiteObject *)instruction); } @@ -98,9 +98,9 @@ class RelocLabelEntry : public PseudoLabel { int data_size_; }; -#define ModRM_Mod(byte) ((byte & 0b11000000) >> 6) +#define ModRM_Mod(byte) ((byte & 0b11000000) >> 6) #define ModRM_RegOpcode(byte) ((byte & 0b00111000) >> 3) -#define ModRM_RM(byte) (byte & 0b00000111) +#define ModRM_RM(byte) (byte & 0b00000111) typedef union _ModRM { byte_t ModRM; @@ -231,7 +231,7 @@ class Operand { rex_ |= REX_B; } encoding_[0] = (mod << 6) | (rm.code() & 7); - length_ = 1; + length_ = 1; } void SetSIB(ScaleFactor scale, Register index, Register base) { @@ -245,7 +245,7 @@ class Operand { if (index.code() > 7) rex_ |= REX_X; encoding_[1] = (scale << 6) | ((index.code() & 7) << 3) | (base.code() & 7); - length_ = 2; + length_ = 2; } void SetDisp8(int8_t disp) { @@ -283,8 +283,8 @@ class Address : public Operand { public: Address(Register base, int32_t disp) { int base_ = base.code(); - int rbp_ = rbp.code(); - int rsp_ = rsp.code(); + int rbp_ = rbp.code(); + int rsp_ = rsp.code(); if ((disp == 0) && ((base_ & 7) != rbp_)) { SetModRM(0, base); if ((base_ & 7) == rsp_) { diff --git a/module/src/main/cpp/Dobby/source/core/modules/codegen/codegen-arm.cc b/module/src/main/cpp/Dobby/source/core/modules/codegen/codegen-arm.cc index 52a7fea8..dfdff9de 100644 --- a/module/src/main/cpp/Dobby/source/core/modules/codegen/codegen-arm.cc +++ b/module/src/main/cpp/Dobby/source/core/modules/codegen/codegen-arm.cc @@ -1,4 +1,4 @@ -#include "common/macros/platform_macro.h" +#include "platform_macro.h" #if defined(TARGET_ARCH_ARM) #include "core/modules/codegen/codegen-arm.h" diff --git a/module/src/main/cpp/Dobby/source/core/modules/codegen/codegen-arm64.cc b/module/src/main/cpp/Dobby/source/core/modules/codegen/codegen-arm64.cc index b046778c..dc6b12e6 100644 --- a/module/src/main/cpp/Dobby/source/core/modules/codegen/codegen-arm64.cc +++ b/module/src/main/cpp/Dobby/source/core/modules/codegen/codegen-arm64.cc @@ -1,4 +1,4 @@ -#include "common/macros/platform_macro.h" +#include "platform_macro.h" #if defined(TARGET_ARCH_ARM64) #include "dobby_internal.h" diff --git a/module/src/main/cpp/Dobby/source/core/modules/codegen/codegen-ia32.cc b/module/src/main/cpp/Dobby/source/core/modules/codegen/codegen-ia32.cc index bb40802e..3bf1b61d 100644 --- a/module/src/main/cpp/Dobby/source/core/modules/codegen/codegen-ia32.cc +++ b/module/src/main/cpp/Dobby/source/core/modules/codegen/codegen-ia32.cc @@ -1,4 +1,4 @@ -#include "common/macros/platform_macro.h" +#include "platform_macro.h" #if defined(TARGET_ARCH_IA32) #include "core/modules/codegen/codegen-ia32.h" @@ -8,10 +8,10 @@ namespace x86 { void CodeGen::JmpNear(uint32_t address) { TurboAssembler *turbo_assembler_ = reinterpret_cast(this->assembler_); -#define _ turbo_assembler_-> +#define _ turbo_assembler_-> #define __ turbo_assembler_->GetCodeBuffer()-> uint32_t currIP = turbo_assembler_->CurrentIP() + 5; - dword offset = (dword)(address - currIP); + dword offset = (dword)(address - currIP); __ Emit8(0xe9); __ Emit32(offset); diff --git a/module/src/main/cpp/Dobby/source/core/modules/codegen/codegen-x64.cc b/module/src/main/cpp/Dobby/source/core/modules/codegen/codegen-x64.cc index 63af9aca..c3bd7606 100644 --- a/module/src/main/cpp/Dobby/source/core/modules/codegen/codegen-x64.cc +++ b/module/src/main/cpp/Dobby/source/core/modules/codegen/codegen-x64.cc @@ -1,4 +1,4 @@ -#include "common/macros/platform_macro.h" +#include "platform_macro.h" #if defined(TARGET_ARCH_X64) #include "core/modules/codegen/codegen-x64.h" @@ -8,10 +8,10 @@ namespace x64 { void CodeGen::JmpNearIndirect(uint64_t address) { TurboAssembler *turbo_assembler_ = reinterpret_cast(this->assembler_); -#define _ turbo_assembler_-> +#define _ turbo_assembler_-> #define __ turbo_assembler_->GetCodeBuffer()-> uint64_t currIP = turbo_assembler_->CurrentIP() + 6; - dword offset = (dword)(address - currIP); + dword offset = (dword)(address - currIP); // RIP-relative addressing __ Emit8(0xFF); diff --git a/module/src/main/cpp/Dobby/source/dobby.cpp b/module/src/main/cpp/Dobby/source/dobby.cpp index 85c670fb..bd286fee 100644 --- a/module/src/main/cpp/Dobby/source/dobby.cpp +++ b/module/src/main/cpp/Dobby/source/dobby.cpp @@ -22,7 +22,7 @@ PUBLIC int DobbyDestroy(void *address) { // check if we already hook HookEntry *entry = Interceptor::SharedInstance()->FindHookEntry(address); if (entry) { - uint8_t *buffer = entry->origin_chunk_.chunk_buffer; + uint8_t *buffer = entry->origin_chunk_.chunk_buffer; uint32_t buffer_size = entry->origin_chunk_.chunk.length; #if defined(TARGET_ARCH_ARM) address = (void *)((addr_t)address - 1); diff --git a/module/src/main/cpp/Dobby/source/dobby_internal.h b/module/src/main/cpp/Dobby/source/dobby_internal.h index f68d3994..b037d88a 100644 --- a/module/src/main/cpp/Dobby/source/dobby_internal.h +++ b/module/src/main/cpp/Dobby/source/dobby_internal.h @@ -28,14 +28,10 @@ typedef struct _AssemblyCodeChunkBuffer { AssemblyCodeChunk chunk; - uint8_t chunk_buffer[64]; + uint8_t chunk_buffer[64]; } AssemblyCodeChunkBuffer; -typedef enum { - kFunctionWrapper, - kFunctionInlineHook, - kDynamicBinaryInstrument -} HookEntryType; +typedef enum { kFunctionWrapper, kFunctionInlineHook, kDynamicBinaryInstrument } HookEntryType; typedef struct { int id; diff --git a/module/src/main/cpp/Dobby/source/include/common_header.h b/module/src/main/cpp/Dobby/source/include/common_header.h new file mode 100644 index 00000000..094bc83d --- /dev/null +++ b/module/src/main/cpp/Dobby/source/include/common_header.h @@ -0,0 +1,11 @@ +#ifndef COMMON_HEADER_H +#define COMMON_HEADER_H + +#include "include/type_macro.h" +#include "include/platform_macro.h" +#include "include/utility_macro.h" + +#include "logging/logging.h" +#include "logging/check_logging.h" + +#endif \ No newline at end of file diff --git a/module/src/main/cpp/Dobby/source/include/list_structure.h b/module/src/main/cpp/Dobby/source/include/list_structure.h new file mode 100644 index 00000000..2d179d27 --- /dev/null +++ b/module/src/main/cpp/Dobby/source/include/list_structure.h @@ -0,0 +1,52 @@ +#pragma once + +struct list_head { + struct list_head *next; + struct list_head *prev; +}; +#define container_of(ptr, type, member) \ + ({ \ + const __typeof(((type *)0)->member) *__mptr = (ptr); \ + (type *)((char *)__mptr - offsetof(type, member)); \ + }) + +#define INIT_LIST_HEAD(ptr) \ + do { \ + (ptr)->next = (ptr); \ + (ptr)->prev = (ptr); \ + } while (0) + +static inline int list_empty(struct list_head *head) { + return head->next == head; +} + +static void __list_add(struct list_head *new_node, struct list_head *prev, struct list_head *next) { + next->prev = new_node; + new_node->next = next; + new_node->prev = prev; + prev->next = new_node; +} + +static inline void list_add(struct list_head *new_node, struct list_head *head) { + __list_add(new_node, head, head->next); +} + +static inline void __list_del(struct list_head *prev, struct list_head *next) { + next->prev = prev; + prev->next = next; +} + +static inline void list_del(struct list_head *entry) { + __list_del(entry->prev, entry->next); + entry->next = NULL; + entry->prev = NULL; +} + +#define list_entry(ptr, type, member) container_of(ptr, type, member) + +#define list_first_entry(ptr, type, member) list_entry((ptr)->next, type, member) + +#define list_next_entry(pos, member) list_entry((pos)->member.next, typeof(*(pos)), member) + +#define list_for_each_entry(pos, head, member) \ + for (pos = list_first_entry(head, typeof(*pos), member); &pos->member != (head); pos = list_next_entry(pos, member)) \ No newline at end of file diff --git a/module/src/main/cpp/Dobby/source/common/macros/platform_macro.h b/module/src/main/cpp/Dobby/source/include/platform_macro.h similarity index 89% rename from module/src/main/cpp/Dobby/source/common/macros/platform_macro.h rename to module/src/main/cpp/Dobby/source/include/platform_macro.h index e5acd353..95c25d7a 100644 --- a/module/src/main/cpp/Dobby/source/common/macros/platform_macro.h +++ b/module/src/main/cpp/Dobby/source/include/platform_macro.h @@ -1,5 +1,4 @@ -#ifndef PLATFORM_HEADER_H -#define PLATFORM_HEADER_H +#pragma once #if defined(_M_X64) || defined(__x86_64__) #define TARGET_ARCH_X64 1 @@ -18,5 +17,3 @@ #else #error Target architecture was not detected as supported by Dobby #endif - -#endif \ No newline at end of file diff --git a/module/src/main/cpp/Dobby/source/common/macros/types_macro.h b/module/src/main/cpp/Dobby/source/include/type_macro.h similarity index 90% rename from module/src/main/cpp/Dobby/source/common/macros/types_macro.h rename to module/src/main/cpp/Dobby/source/include/type_macro.h index 90fdd668..013e9313 100644 --- a/module/src/main/cpp/Dobby/source/common/macros/types_macro.h +++ b/module/src/main/cpp/Dobby/source/include/type_macro.h @@ -1,5 +1,4 @@ -#ifndef TYPES_HEADER_H -#define TYPES_HEADER_H +#pragma once #include @@ -36,6 +35,4 @@ typedef int dword; #ifndef NULL #define NULL 0 -#endif - -#endif +#endif \ No newline at end of file diff --git a/module/src/main/cpp/Dobby/source/common/macros/utilities_macro.h b/module/src/main/cpp/Dobby/source/include/utility_macro.h similarity index 68% rename from module/src/main/cpp/Dobby/source/common/macros/utilities_macro.h rename to module/src/main/cpp/Dobby/source/include/utility_macro.h index 1869ae67..74bb73d6 100644 --- a/module/src/main/cpp/Dobby/source/common/macros/utilities_macro.h +++ b/module/src/main/cpp/Dobby/source/include/utility_macro.h @@ -1,5 +1,5 @@ -#ifndef UTILITIES_MACRO_H -#define UTILITIES_MACRO_H +#pragma once + // offset of struct member #define OFFSETOF(TYPE, ELEMENT) ((size_t) & (((TYPE *)0)->ELEMENT)) @@ -8,7 +8,7 @@ #define ASSERT(X) // left/right shift -#define LeftShift(a, b, c) ((a & ((1 << b) - 1)) << c) +#define LeftShift(a, b, c) ((a & ((1 << b) - 1)) << c) #define RightShift(a, b, c) ((a >> c) & ((1 << b) - 1)) // align @@ -16,27 +16,27 @@ #define ALIGN ALIGN_FLOOR #endif #define ALIGN_FLOOR(address, range) ((addr_t)address & ~((addr_t)range - 1)) -#define ALIGN_CEIL(address, range) (((addr_t)address + (addr_t)range - 1) & ~((addr_t)range - 1)) +#define ALIGN_CEIL(address, range) (((addr_t)address + (addr_t)range - 1) & ~((addr_t)range - 1)) // borrow from gdb, refer: binutils-gdb/gdb/arch/arm.h -#define submask(x) ((1L << ((x) + 1)) - 1) -#define bits(obj, st, fn) (((obj) >> (st)) & submask((fn) - (st))) -#define bit(obj, st) (((obj) >> (st)) & 1) +#define submask(x) ((1L << ((x) + 1)) - 1) +#define bits(obj, st, fn) (((obj) >> (st)) & submask((fn) - (st))) +#define bit(obj, st) (((obj) >> (st)) & 1) #define sbits(obj, st, fn) ((long)(bits(obj, st, fn) | ((long)bit(obj, fn) * ~submask(fn - st)))) // make it easy -#define set_bit(obj, st, bit) obj = (((~(1 << st)) & obj) | (bit << st)) +#define set_bit(obj, st, bit) obj = (((~(1 << st)) & obj) | (bit << st)) #define set_bits(obj, st, fn, bits) obj = (((~(submask(fn - st) << st)) & obj) | (bits << st)) // definition to expand macro then apply to pragma message // #pragma message(VAR_NAME_VALUE(HOST_OS_IOS)) -#define VALUE_TO_STRING(x) #x -#define VALUE(x) VALUE_TO_STRING(x) +#define VALUE_TO_STRING(x) #x +#define VALUE(x) VALUE_TO_STRING(x) #define VAR_NAME_VALUE(var) #var "=" VALUE(var) // format print #ifdef __LP64__ -#define __PRI_64_prefix "l" +#define __PRI_64_prefix "l" #define __PRI_PTR_prefix "l" #else #define __PRI_64_prefix "ll" @@ -58,8 +58,6 @@ #if defined(_WIN32) #define PUBLIC #else -#define PUBLIC __attribute__((visibility("default"))) +#define PUBLIC __attribute__((visibility("default"))) #define INTERNAL __attribute__((visibility("internal"))) -#endif - -#endif +#endif \ No newline at end of file diff --git a/module/src/main/cpp/Dobby/tests/InstructionRelocation/aarch64/test_aarch64_instruction_relocation.cc b/module/src/main/cpp/Dobby/tests/InstructionRelocation/aarch64/test_aarch64_instruction_relocation.cc index a80be111..d0f2a9cc 100644 --- a/module/src/main/cpp/Dobby/tests/InstructionRelocation/aarch64/test_aarch64_instruction_relocation.cc +++ b/module/src/main/cpp/Dobby/tests/InstructionRelocation/aarch64/test_aarch64_instruction_relocation.cc @@ -50,8 +50,8 @@ int _main(int argc, const char **argv) { char *relo_buffer = (char *)malloc(0x1000); - int relo_size = (uint64_t)pc_relative_instructions_end - (uint64_t)pc_relative_instructions; - zz::AssemblyCode *code = GenRelocateCodeAndBranch((void *)pc_relative_instructions, &relo_size, 0, 0); + int relo_size = (uint64_t)pc_relative_instructions_end - (uint64_t)pc_relative_instructions; + zz::AssemblyCode *code = GenRelocateCodeAndBranch((void *)pc_relative_instructions, &relo_size, 0, 0); unsigned char *instruction_bytes = (unsigned char *)code->raw_instruction_start(); for (int i = 0; i < code->raw_instruction_size(); i += 1) { diff --git a/module/src/main/cpp/Dobby/tests/InstructionRelocation/x64/test_x64_instruction_relocation.cc b/module/src/main/cpp/Dobby/tests/InstructionRelocation/x64/test_x64_instruction_relocation.cc index 072f88f2..f57391c0 100644 --- a/module/src/main/cpp/Dobby/tests/InstructionRelocation/x64/test_x64_instruction_relocation.cc +++ b/module/src/main/cpp/Dobby/tests/InstructionRelocation/x64/test_x64_instruction_relocation.cc @@ -104,14 +104,14 @@ int instrLenArray[] = { // clang-format on TEST_CASE(">>> InstructionRelocation/x64", "[InstructionRelocation]") { - void * TargetFunction = hexData; - uintptr_t srcIP = (uintptr_t)TargetFunction; - uintptr_t currIP = srcIP; - int funcLen = sizeof(hexData); - unsigned char opcode1 = 0; - InstrMnemonic instr = {0}; + void *TargetFunction = hexData; + uintptr_t srcIP = (uintptr_t)TargetFunction; + uintptr_t currIP = srcIP; + int funcLen = sizeof(hexData); + unsigned char opcode1 = 0; + InstrMnemonic instr = {0}; - int i = 0; + int i = 0; opcode1 = *(byte *)srcIP; do { diff --git a/module/src/main/cpp/include/config.h b/module/src/main/cpp/include/config.h deleted file mode 100644 index 6203e3d8..00000000 --- a/module/src/main/cpp/include/config.h +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once - -namespace riru { - extern const int moduleVersionCode; - extern const char* const moduleVersionName; - extern const int moduleApiVersion; - extern const int moduleMinApiVersion; -} diff --git a/module/src/main/cpp/main.cpp b/module/src/main/cpp/main.cpp index 4aac3278..89833b73 100644 --- a/module/src/main/cpp/main.cpp +++ b/module/src/main/cpp/main.cpp @@ -1,30 +1,29 @@ -#include -#include -#include -#include #include -#include +#include #include #include "hook.h" +#include "zygisk.hpp" + -static void forkAndSpecializePre( - JNIEnv *env, jclass clazz, jint *uid, jint *gid, jintArray *gids, jint *runtimeFlags, - jobjectArray *rlimits, jint *mountExternal, jstring *seInfo, jstring *niceName, - jintArray *fdsToClose, jintArray *fdsToIgnore, jboolean *is_child_zygote, - jstring *instructionSet, jstring *appDataDir, jboolean *isTopApp, jobjectArray *pkgDataInfoList, - jobjectArray *whitelistedDataInfoList, jboolean *bindMountAppDataDirs, jboolean *bindMountAppStorageDirs) { - // Called "before" com_android_internal_os_Zygote_nativeForkAndSpecialize in frameworks/base/core/jni/com_android_internal_os_Zygote.cpp - // Parameters are pointers, you can change the value of them if you want - // Some parameters are not exist is older Android versions, in this case, they are null or 0 - enable_hack = isGame(env, *appDataDir); -} +using zygisk::Api; +using zygisk::AppSpecializeArgs; +using zygisk::ServerSpecializeArgs; -static void forkAndSpecializePost(JNIEnv *env, jclass clazz, jint res) { - // Called "after" com_android_internal_os_Zygote_nativeForkAndSpecialize in frameworks/base/core/jni/com_android_internal_os_Zygote.cpp - // "res" is the return value of com_android_internal_os_Zygote_nativeForkAndSpecialize +class MyModule : public zygisk::ModuleBase { +public: + void onLoad(Api *api, JNIEnv *env) override { + env_ = env; + } - if (res == 0) { - // In app process + void preAppSpecialize(AppSpecializeArgs *args) override { + if (!args || !args->nice_name) { + LOGE("Skip unknown process"); + return; + } + enable_hack = isGame(env_, args->app_data_dir); + } + + void postAppSpecialize(const AppSpecializeArgs *) override { if (enable_hack) { int ret; pthread_t ntid; @@ -32,93 +31,10 @@ static void forkAndSpecializePost(JNIEnv *env, jclass clazz, jint res) { LOGE("can't create thread: %s\n", strerror(ret)); } } - // When unload allowed is true, the module will be unloaded (dlclose) by Riru - // If this modules has hooks installed, DONOT set it to true, or there will be SIGSEGV - // This value will be automatically reset to false before the "pre" function is called - riru_set_unload_allowed(false); - } else { - // In zygote process } -} - -static void specializeAppProcessPre( - JNIEnv *env, jclass clazz, jint *uid, jint *gid, jintArray *gids, jint *runtimeFlags, - jobjectArray *rlimits, jint *mountExternal, jstring *seInfo, jstring *niceName, - jboolean *startChildZygote, jstring *instructionSet, jstring *appDataDir, - jboolean *isTopApp, jobjectArray *pkgDataInfoList, jobjectArray *whitelistedDataInfoList, - jboolean *bindMountAppDataDirs, jboolean *bindMountAppStorageDirs) { - // Called "before" com_android_internal_os_Zygote_nativeSpecializeAppProcess in frameworks/base/core/jni/com_android_internal_os_Zygote.cpp - // Parameters are pointers, you can change the value of them if you want - // Some parameters are not exist is older Android versions, in this case, they are null or 0 -} - -static void specializeAppProcessPost( - JNIEnv *env, jclass clazz) { - // Called "after" com_android_internal_os_Zygote_nativeSpecializeAppProcess in frameworks/base/core/jni/com_android_internal_os_Zygote.cpp - - // When unload allowed is true, the module will be unloaded (dlclose) by Riru - // If this modules has hooks installed, DONOT set it to true, or there will be SIGSEGV - // This value will be automatically reset to false before the "pre" function is called - riru_set_unload_allowed(true); -} - -static void forkSystemServerPre( - JNIEnv *env, jclass clazz, uid_t *uid, gid_t *gid, jintArray *gids, jint *runtimeFlags, - jobjectArray *rlimits, jlong *permittedCapabilities, jlong *effectiveCapabilities) { - // Called "before" com_android_internal_os_Zygote_forkSystemServer in frameworks/base/core/jni/com_android_internal_os_Zygote.cpp - // Parameters are pointers, you can change the value of them if you want - // Some parameters are not exist is older Android versions, in this case, they are null or 0 -} -static void forkSystemServerPost(JNIEnv *env, jclass clazz, jint res) { - // Called "after" com_android_internal_os_Zygote_forkSystemServer in frameworks/base/core/jni/com_android_internal_os_Zygote.cpp - - if (res == 0) { - // In system server process - } else { - // In zygote process - } -} - -static void onModuleLoaded() { - // Called when this library is loaded and "hidden" by Riru (see Riru's hide.cpp) - - // If you want to use threads, start them here rather than the constructors - // __attribute__((constructor)) or constructors of static variables, - // or the "hide" will cause SIGSEGV -} - -extern "C" { - -int riru_api_version; -const char *riru_magisk_module_path = nullptr; -int *riru_allow_unload = nullptr; - -static auto module = RiruVersionedModuleInfo{ - .moduleApiVersion = riru::moduleApiVersion, - .moduleInfo= RiruModuleInfo{ - .supportHide = true, - .version = riru::moduleVersionCode, - .versionName = riru::moduleVersionName, - .onModuleLoaded = onModuleLoaded, - .forkAndSpecializePre = forkAndSpecializePre, - .forkAndSpecializePost = forkAndSpecializePost, - .forkSystemServerPre = forkSystemServerPre, - .forkSystemServerPost = forkSystemServerPost, - .specializeAppProcessPre = specializeAppProcessPre, - .specializeAppProcessPost = specializeAppProcessPost - } +private: + JNIEnv *env_{}; }; -RiruVersionedModuleInfo *init(Riru *riru) { - auto core_max_api_version = riru->riruApiVersion; - riru_api_version = core_max_api_version <= riru::moduleApiVersion ? core_max_api_version : riru::moduleApiVersion; - module.moduleApiVersion = riru_api_version; - - riru_magisk_module_path = strdup(riru->magiskModulePath); - if (riru_api_version >= 25) { - riru_allow_unload = riru->allowUnload; - } - return &module; -} -} +REGISTER_ZYGISK_MODULE(MyModule) \ No newline at end of file diff --git a/module/src/main/cpp/template/config.cpp b/module/src/main/cpp/template/config.cpp deleted file mode 100644 index 36e2f460..00000000 --- a/module/src/main/cpp/template/config.cpp +++ /dev/null @@ -1,8 +0,0 @@ -#include "config.h" - -namespace riru { - const int moduleVersionCode = ${RIRU_MODULE_VERSION}; - const char* const moduleVersionName = "${RIRU_MODULE_VERSION_NAME}"; - const int moduleApiVersion = ${RIRU_MODULE_API_VERSION}; - const int moduleMinApiVersion = ${RIRU_MODULE_MIN_API_VERSION}; -} diff --git a/module/src/main/cpp/zygisk.hpp b/module/src/main/cpp/zygisk.hpp new file mode 100644 index 00000000..a7383e54 --- /dev/null +++ b/module/src/main/cpp/zygisk.hpp @@ -0,0 +1,326 @@ +// This is the public API for Zygisk modules. +// DO NOT MODIFY ANY CODE IN THIS HEADER. + +#pragma once + +#include + +#define ZYGISK_API_VERSION 2 + +/* + +Define a class and inherit zygisk::ModuleBase to implement the functionality of your module. +Use the macro REGISTER_ZYGISK_MODULE(className) to register that class to Zygisk. + +Please note that modules will only be loaded after zygote has forked the child process. +THIS MEANS ALL OF YOUR CODE RUNS IN THE APP/SYSTEM SERVER PROCESS, NOT THE ZYGOTE DAEMON! + +Example code: + +static jint (*orig_logger_entry_max)(JNIEnv *env); +static jint my_logger_entry_max(JNIEnv *env) { return orig_logger_entry_max(env); } + +static void example_handler(int socket) { ... } + +class ExampleModule : public zygisk::ModuleBase { +public: + void onLoad(zygisk::Api *api, JNIEnv *env) override { + this->api = api; + this->env = env; + } + void preAppSpecialize(zygisk::AppSpecializeArgs *args) override { + JNINativeMethod methods[] = { + { "logger_entry_max_payload_native", "()I", (void*) my_logger_entry_max }, + }; + api->hookJniNativeMethods(env, "android/util/Log", methods, 1); + *(void **) &orig_logger_entry_max = methods[0].fnPtr; + } +private: + zygisk::Api *api; + JNIEnv *env; +}; + +REGISTER_ZYGISK_MODULE(ExampleModule) + +REGISTER_ZYGISK_COMPANION(example_handler) + +*/ + +namespace zygisk { + +struct Api; +struct AppSpecializeArgs; +struct ServerSpecializeArgs; + +class ModuleBase { +public: + + // This function is called when the module is loaded into the target process. + // A Zygisk API handle will be sent as an argument; call utility functions or interface + // with Zygisk through this handle. + virtual void onLoad([[maybe_unused]] Api *api, [[maybe_unused]] JNIEnv *env) {} + + // This function is called before the app process is specialized. + // At this point, the process just got forked from zygote, but no app specific specialization + // is applied. This means that the process does not have any sandbox restrictions and + // still runs with the same privilege of zygote. + // + // All the arguments that will be sent and used for app specialization is passed as a single + // AppSpecializeArgs object. You can read and overwrite these arguments to change how the app + // process will be specialized. + // + // If you need to run some operations as superuser, you can call Api::connectCompanion() to + // get a socket to do IPC calls with a root companion process. + // See Api::connectCompanion() for more info. + virtual void preAppSpecialize([[maybe_unused]] AppSpecializeArgs *args) {} + + // This function is called after the app process is specialized. + // At this point, the process has all sandbox restrictions enabled for this application. + // This means that this function runs as the same privilege of the app's own code. + virtual void postAppSpecialize([[maybe_unused]] const AppSpecializeArgs *args) {} + + // This function is called before the system server process is specialized. + // See preAppSpecialize(args) for more info. + virtual void preServerSpecialize([[maybe_unused]] ServerSpecializeArgs *args) {} + + // This function is called after the system server process is specialized. + // At this point, the process runs with the privilege of system_server. + virtual void postServerSpecialize([[maybe_unused]] const ServerSpecializeArgs *args) {} +}; + +struct AppSpecializeArgs { + // Required arguments. These arguments are guaranteed to exist on all Android versions. + jint &uid; + jint &gid; + jintArray &gids; + jint &runtime_flags; + jint &mount_external; + jstring &se_info; + jstring &nice_name; + jstring &instruction_set; + jstring &app_data_dir; + + // Optional arguments. Please check whether the pointer is null before de-referencing + jboolean *const is_child_zygote; + jboolean *const is_top_app; + jobjectArray *const pkg_data_info_list; + jobjectArray *const whitelisted_data_info_list; + jboolean *const mount_data_dirs; + jboolean *const mount_storage_dirs; + + AppSpecializeArgs() = delete; +}; + +struct ServerSpecializeArgs { + jint &uid; + jint &gid; + jintArray &gids; + jint &runtime_flags; + jlong &permitted_capabilities; + jlong &effective_capabilities; + + ServerSpecializeArgs() = delete; +}; + +namespace internal { +struct api_table; +template void entry_impl(api_table *, JNIEnv *); +} + +// These values are used in Api::setOption(Option) +enum Option : int { + // Force Magisk's denylist unmount routines to run on this process. + // + // Setting this option only makes sense in preAppSpecialize. + // The actual unmounting happens during app process specialization. + // + // Set this option to force all Magisk and modules' files to be unmounted from the + // mount namespace of the process, regardless of the denylist enforcement status. + FORCE_DENYLIST_UNMOUNT = 0, + + // When this option is set, your module's library will be dlclose-ed after post[XXX]Specialize. + // Be aware that after dlclose-ing your module, all of your code will be unmapped from memory. + // YOU MUST NOT ENABLE THIS OPTION AFTER HOOKING ANY FUNCTIONS IN THE PROCESS. + DLCLOSE_MODULE_LIBRARY = 1, +}; + +// Bit masks of the return value of Api::getFlags() +enum StateFlag : uint32_t { + // The user has granted root access to the current process + PROCESS_GRANTED_ROOT = (1u << 0), + + // The current process was added on the denylist + PROCESS_ON_DENYLIST = (1u << 1), +}; + +// All API functions will stop working after post[XXX]Specialize as Zygisk will be unloaded +// from the specialized process afterwards. +struct Api { + + // Connect to a root companion process and get a Unix domain socket for IPC. + // + // This API only works in the pre[XXX]Specialize functions due to SELinux restrictions. + // + // The pre[XXX]Specialize functions run with the same privilege of zygote. + // If you would like to do some operations with superuser permissions, register a handler + // function that would be called in the root process with REGISTER_ZYGISK_COMPANION(func). + // Another good use case for a companion process is that if you want to share some resources + // across multiple processes, hold the resources in the companion process and pass it over. + // + // The root companion process is ABI aware; that is, when calling this function from a 32-bit + // process, you will be connected to a 32-bit companion process, and vice versa for 64-bit. + // + // Returns a file descriptor to a socket that is connected to the socket passed to your + // module's companion request handler. Returns -1 if the connection attempt failed. + int connectCompanion(); + + // Get the file descriptor of the root folder of the current module. + // + // This API only works in the pre[XXX]Specialize functions. + // Accessing the directory returned is only possible in the pre[XXX]Specialize functions + // or in the root companion process (assuming that you sent the fd over the socket). + // Both restrictions are due to SELinux and UID. + // + // Returns -1 if errors occurred. + int getModuleDir(); + + // Set various options for your module. + // Please note that this function accepts one single option at a time. + // Check zygisk::Option for the full list of options available. + void setOption(Option opt); + + // Get information about the current process. + // Returns bitwise-or'd zygisk::StateFlag values. + uint32_t getFlags(); + + // Hook JNI native methods for a class + // + // Lookup all registered JNI native methods and replace it with your own functions. + // The original function pointer will be saved in each JNINativeMethod's fnPtr. + // If no matching class, method name, or signature is found, that specific JNINativeMethod.fnPtr + // will be set to nullptr. + void hookJniNativeMethods(JNIEnv *env, const char *className, JNINativeMethod *methods, int numMethods); + + // For ELFs loaded in memory matching `regex`, replace function `symbol` with `newFunc`. + // If `oldFunc` is not nullptr, the original function pointer will be saved to `oldFunc`. + void pltHookRegister(const char *regex, const char *symbol, void *newFunc, void **oldFunc); + + // For ELFs loaded in memory matching `regex`, exclude hooks registered for `symbol`. + // If `symbol` is nullptr, then all symbols will be excluded. + void pltHookExclude(const char *regex, const char *symbol); + + // Commit all the hooks that was previously registered. + // Returns false if an error occurred. + bool pltHookCommit(); + +private: + internal::api_table *impl; + template friend void internal::entry_impl(internal::api_table *, JNIEnv *); +}; + +// Register a class as a Zygisk module + +#define REGISTER_ZYGISK_MODULE(clazz) \ +void zygisk_module_entry(zygisk::internal::api_table *table, JNIEnv *env) { \ + zygisk::internal::entry_impl(table, env); \ +} + +// Register a root companion request handler function for your module +// +// The function runs in a superuser daemon process and handles a root companion request from +// your module running in a target process. The function has to accept an integer value, +// which is a socket that is connected to the target process. +// See Api::connectCompanion() for more info. +// +// NOTE: the function can run concurrently on multiple threads. +// Be aware of race conditions if you have a globally shared resource. + +#define REGISTER_ZYGISK_COMPANION(func) \ +void zygisk_companion_entry(int client) { func(client); } + +/************************************************************************************ + * All the code after this point is internal code used to interface with Zygisk + * and guarantee ABI stability. You do not have to understand what it is doing. + ************************************************************************************/ + +namespace internal { + +struct module_abi { + long api_version; + ModuleBase *_this; + + void (*preAppSpecialize)(ModuleBase *, AppSpecializeArgs *); + void (*postAppSpecialize)(ModuleBase *, const AppSpecializeArgs *); + void (*preServerSpecialize)(ModuleBase *, ServerSpecializeArgs *); + void (*postServerSpecialize)(ModuleBase *, const ServerSpecializeArgs *); + + module_abi(ModuleBase *module) : api_version(ZYGISK_API_VERSION), _this(module) { + preAppSpecialize = [](auto self, auto args) { self->preAppSpecialize(args); }; + postAppSpecialize = [](auto self, auto args) { self->postAppSpecialize(args); }; + preServerSpecialize = [](auto self, auto args) { self->preServerSpecialize(args); }; + postServerSpecialize = [](auto self, auto args) { self->postServerSpecialize(args); }; + } +}; + +struct api_table { + // These first 2 entries are permanent, shall never change + void *_this; + bool (*registerModule)(api_table *, module_abi *); + + // Utility functions + void (*hookJniNativeMethods)(JNIEnv *, const char *, JNINativeMethod *, int); + void (*pltHookRegister)(const char *, const char *, void *, void **); + void (*pltHookExclude)(const char *, const char *); + bool (*pltHookCommit)(); + + // Zygisk functions + int (*connectCompanion)(void * /* _this */); + void (*setOption)(void * /* _this */, Option); + int (*getModuleDir)(void * /* _this */); + uint32_t (*getFlags)(void * /* _this */); +}; + +template +void entry_impl(api_table *table, JNIEnv *env) { + ModuleBase *module = new T(); + if (!table->registerModule(table, new module_abi(module))) + return; + auto api = new Api(); + api->impl = table; + module->onLoad(api, env); +} + +} // namespace internal + +inline int Api::connectCompanion() { + return impl->connectCompanion ? impl->connectCompanion(impl->_this) : -1; +} +inline int Api::getModuleDir() { + return impl->getModuleDir ? impl->getModuleDir(impl->_this) : -1; +} +inline void Api::setOption(Option opt) { + if (impl->setOption) impl->setOption(impl->_this, opt); +} +inline uint32_t Api::getFlags() { + return impl->getFlags ? impl->getFlags(impl->_this) : 0; +} +inline void Api::hookJniNativeMethods(JNIEnv *env, const char *className, JNINativeMethod *methods, int numMethods) { + if (impl->hookJniNativeMethods) impl->hookJniNativeMethods(env, className, methods, numMethods); +} +inline void Api::pltHookRegister(const char *regex, const char *symbol, void *newFunc, void **oldFunc) { + if (impl->pltHookRegister) impl->pltHookRegister(regex, symbol, newFunc, oldFunc); +} +inline void Api::pltHookExclude(const char *regex, const char *symbol) { + if (impl->pltHookExclude) impl->pltHookExclude(regex, symbol); +} +inline bool Api::pltHookCommit() { + return impl->pltHookCommit != nullptr && impl->pltHookCommit(); +} + +} // namespace zygisk + +[[gnu::visibility("default")]] [[gnu::used]] +extern "C" void zygisk_module_entry(zygisk::internal::api_table *, JNIEnv *); + +[[gnu::visibility("default")]] [[gnu::used]] +extern "C" void zygisk_companion_entry(int); diff --git a/template/magisk_module/.gitattributes b/template/magisk_module/.gitattributes deleted file mode 100644 index 11e33e9b..00000000 --- a/template/magisk_module/.gitattributes +++ /dev/null @@ -1,10 +0,0 @@ -# Declare files that will always have LF line endings on checkout. -META-INF/** text eol=lf -*.prop text eol=lf -*.sh text eol=lf -*.md text eol=lf -sepolicy.rule text eol=lf - -# Denote all files that are truly binary and should not be modified. -system/** binary -system_x86/** binary \ No newline at end of file diff --git a/template/magisk_module/README.md b/template/magisk_module/README.md deleted file mode 100644 index c316e8b9..00000000 --- a/template/magisk_module/README.md +++ /dev/null @@ -1 +0,0 @@ -# Riru - Template \ No newline at end of file diff --git a/template/magisk_module/customize.sh b/template/magisk_module/customize.sh deleted file mode 100644 index 11f86b9c..00000000 --- a/template/magisk_module/customize.sh +++ /dev/null @@ -1,70 +0,0 @@ -SKIPUNZIP=1 - -# Extract verify.sh -ui_print "- Extracting verify.sh" -unzip -o "$ZIPFILE" 'verify.sh' -d "$TMPDIR" >&2 -if [ ! -f "$TMPDIR/verify.sh" ]; then - ui_print "*********************************************************" - ui_print "! Unable to extract verify.sh!" - ui_print "! This zip may be corrupted, please try downloading again" - abort "*********************************************************" -fi -. $TMPDIR/verify.sh - -# Extract riru.sh - -# Variables provided by riru.sh: -# -# RIRU_API: API version of installed Riru, 0 if not installed -# RIRU_MIN_COMPATIBLE_API: minimal supported API version by installed Riru, 0 if not installed or version < v23.2 -# RIRU_VERSION_CODE: version code of installed Riru, 0 if not installed or version < v23.2 -# RIRU_VERSION_NAME: version name of installed Riru, "" if not installed or version < v23.2 - -extract "$ZIPFILE" 'riru.sh' "$TMPDIR" -. $TMPDIR/riru.sh - -# Functions from util_functions.sh (it will be loaded by riru.sh) -check_riru_version -enforce_install_from_magisk_app - -# Check architecture -if [ "$ARCH" != "arm" ] && [ "$ARCH" != "arm64" ] && [ "$ARCH" != "x86" ] && [ "$ARCH" != "x64" ]; then - abort "! Unsupported platform: $ARCH" -else - ui_print "- Device platform: $ARCH" -fi - -# Extract libs -ui_print "- Extracting module files" - -extract "$ZIPFILE" 'module.prop' "$MODPATH" -extract "$ZIPFILE" 'uninstall.sh' "$MODPATH" - -# Riru v24+ load files from the "riru" folder in the Magisk module folder -# This "riru" folder is also used to determine if a Magisk module is a Riru module - -mkdir "$MODPATH/riru" -mkdir "$MODPATH/riru/lib" -mkdir "$MODPATH/riru/lib64" - -if [ "$ARCH" = "arm" ] || [ "$ARCH" = "arm64" ]; then - ui_print "- Extracting arm libraries" - extract "$ZIPFILE" "lib/armeabi-v7a/lib$RIRU_MODULE_LIB_NAME.so" "$MODPATH/riru/lib" true - - if [ "$IS64BIT" = true ]; then - ui_print "- Extracting arm64 libraries" - extract "$ZIPFILE" "lib/arm64-v8a/lib$RIRU_MODULE_LIB_NAME.so" "$MODPATH/riru/lib64" true - fi -fi - -if [ "$ARCH" = "x86" ] || [ "$ARCH" = "x64" ]; then - ui_print "- Extracting x86 libraries" - extract "$ZIPFILE" "lib/x86/lib$RIRU_MODULE_LIB_NAME.so" "$MODPATH/riru/lib" true - - if [ "$IS64BIT" = true ]; then - ui_print "- Extracting x64 libraries" - extract "$ZIPFILE" "lib/x86_64/lib$RIRU_MODULE_LIB_NAME.so" "$MODPATH/riru/lib64" true - fi -fi - -set_perm_recursive "$MODPATH" 0 0 0755 0644 diff --git a/template/magisk_module/riru.sh b/template/magisk_module/riru.sh deleted file mode 100644 index c3152c5b..00000000 --- a/template/magisk_module/riru.sh +++ /dev/null @@ -1,44 +0,0 @@ -#!/sbin/sh -RIRU_MODULE_LIB_NAME="@RIRU_MODULE_LIB_NAME@" - -# Variables for customize.sh -RIRU_API=0 -RIRU_MIN_COMPATIBLE_API=0 -RIRU_VERSION_CODE=0 -RIRU_VERSION_NAME="" - -# Used by util_functions.sh -RIRU_MODULE_API_VERSION=@RIRU_MODULE_API_VERSION@ -RIRU_MODULE_MIN_API_VERSION=@RIRU_MODULE_MIN_API_VERSION@ -RIRU_MODULE_MIN_RIRU_VERSION_NAME="@RIRU_MODULE_MIN_RIRU_VERSION_NAME@" - -if [ "$MAGISK_VER_CODE" -ge 21000 ]; then - MAGISK_CURRENT_RIRU_MODULE_PATH=$(magisk --path)/.magisk/modules/riru-core -else - MAGISK_CURRENT_RIRU_MODULE_PATH=/sbin/.magisk/modules/riru-core -fi - -if [ ! -d $MAGISK_CURRENT_RIRU_MODULE_PATH ]; then - ui_print "*********************************************************" - ui_print "! Riru is not installed" - ui_print "! Please install Riru from Magisk Manager or https://github.com/RikkaApps/Riru/releases" - abort "*********************************************************" -fi - -if [ -f "$MAGISK_CURRENT_RIRU_MODULE_PATH/disable" ] || [ -f "$MAGISK_CURRENT_RIRU_MODULE_PATH/remove" ]; then - ui_print "*********************************************************" - ui_print "! Riru is not enabled or will be removed" - ui_print "! Please enable Riru in Magisk first" - abort "*********************************************************" -fi - -if [ -f $MAGISK_CURRENT_RIRU_MODULE_PATH/util_functions.sh ]; then - ui_print "- Load $MAGISK_CURRENT_RIRU_MODULE_PATH/util_functions.sh" - # shellcheck disable=SC1090 - . $MAGISK_CURRENT_RIRU_MODULE_PATH/util_functions.sh -else - ui_print "*********************************************************" - ui_print "! Riru $RIRU_MODULE_MIN_RIRU_VERSION_NAME or above is required" - ui_print "! Please upgrade Riru from Magisk Manager or https://github.com/RikkaApps/Riru/releases" - abort "*********************************************************" -fi diff --git a/template/magisk_module/uninstall.sh b/template/magisk_module/uninstall.sh deleted file mode 100644 index 3c86bf32..00000000 --- a/template/magisk_module/uninstall.sh +++ /dev/null @@ -1,2 +0,0 @@ -#!/sbin/sh -MODDIR=${0%/*} diff --git a/template/magisk_module/verify.sh b/template/magisk_module/verify.sh deleted file mode 100644 index fc706b6f..00000000 --- a/template/magisk_module/verify.sh +++ /dev/null @@ -1,39 +0,0 @@ -TMPDIR_FOR_VERIFY="$TMPDIR/.vunzip" -mkdir "$TMPDIR_FOR_VERIFY" - -abort_verify() { - ui_print "*********************************************************" - ui_print "! $1" - ui_print "! This zip may be corrupted, please try downloading again" - abort "*********************************************************" -} - -# extract -extract() { - zip=$1 - file=$2 - dir=$3 - junk_paths=$4 - [ -z "$junk_paths" ] && junk_paths=false - opts="-o" - [ $junk_paths = true ] && opts="-oj" - - file_path="" - hash_path="" - if [ $junk_paths = true ]; then - file_path="$dir/$(basename "$file")" - hash_path="$TMPDIR_FOR_VERIFY/$(basename "$file").sha256sum" - else - file_path="$dir/$file" - hash_path="$TMPDIR_FOR_VERIFY/$file.sha256sum" - fi - - unzip $opts "$zip" "$file" -d "$dir" >&2 - [ -f "$file_path" ] || abort_verify "$file not exists" - - unzip $opts "$zip" "$file.sha256sum" -d "$TMPDIR_FOR_VERIFY" >&2 - [ -f "$hash_path" ] || abort_verify "$file.sha256sum not exists" - - (echo "$(cat "$hash_path") $file_path" | sha256sum -c -s -) || abort_verify "Failed to verify $file" - ui_print "- Verified $file" >&1 -}