├── .gitignore ├── CMakeLists.txt ├── LICENSE ├── README.md ├── benchmark ├── CMakeLists.txt └── benchmark_hotpatch.cpp ├── examples ├── CMakeLists.txt ├── add_func.cpp ├── add_one.cpp ├── fibonacci_func.cpp ├── prebuilt_server.cpp └── simple_server.cpp ├── preload ├── CMakeLists.txt └── preload_hotpatch.cpp ├── python ├── hotpatch │ ├── __init__.py │ └── cli │ │ ├── __init__.py │ │ └── hotpatch_cli.py └── setup.py ├── src ├── CMakeLists.txt ├── hotpatch_command.cpp ├── hotpatch_command.h ├── hotpatch_command_test.cpp ├── hotpatch_server.cpp └── hotpatch_server.h └── thirdparty └── install_thirdparty.md /.gitignore: -------------------------------------------------------------------------------- 1 | # IDE 2 | .vscode/ 3 | *.code-workspace 4 | .idea/ 5 | 6 | # Thirdparty 7 | thirdparty/lib/ 8 | thirdparty/include/ 9 | 10 | # Python 11 | python/dist/ 12 | python/hotpatch.egg-info/ 13 | python/hotpatch/__pycache__/ 14 | python/hotpatch/cli/__pycache__/ 15 | 16 | # CMake 17 | build/ 18 | 19 | # Prerequisites 20 | *.d 21 | 22 | # Compiled Object files 23 | *.slo 24 | *.lo 25 | *.o 26 | *.obj 27 | 28 | # Precompiled Headers 29 | *.gch 30 | *.pch 31 | 32 | # Compiled Dynamic libraries 33 | *.so 34 | *.dylib 35 | *.dll 36 | 37 | # Fortran module files 38 | *.mod 39 | *.smod 40 | 41 | # Compiled Static libraries 42 | *.lai 43 | *.la 44 | *.a 45 | *.lib 46 | 47 | # Executables 48 | *.exe 49 | *.out 50 | *.app 51 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.0) 2 | 3 | project(hotpatch VERSION 0.1.0) 4 | 5 | add_compile_options(-std=c++14) 6 | 7 | # set(CMAKE_C_COMPILER "gcc") 8 | # set(CMAKE_CXX_COMPILER "g++") 9 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC") 10 | 11 | find_package(GTest REQUIRED) 12 | find_package(Threads REQUIRED) 13 | 14 | include_directories(${PROJECT_SOURCE_DIR}/thirdparty/include) 15 | link_directories(${PROJECT_SOURCE_DIR}/thirdparty/lib) 16 | 17 | include_directories(${GTEST_INCLUDE_DIRS}) 18 | 19 | add_subdirectory("src") 20 | add_subdirectory("examples") 21 | add_subdirectory("benchmark") 22 | add_subdirectory("preload") 23 | 24 | enable_testing() -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # HotPatch 2 | 3 | ## Introduction 4 | 5 | Computer progroms are like humans in a way which is extensible to do almost everything. But human can learn and react continuously while softwares need to restart after adding features and applying patches. In some cases, we can apply the hot patches which are different from the static code patches without restarting the processes. 6 | 7 | This project helps to patch and upgrade your programs with the following features. 8 | 9 | - [x] Set and get the [gflags](https://github.com/gflags/gflags) on the fly. 10 | - [x] Set the logging properties of [glogs](https://github.com/google/glog) on the fly. 11 | - [x] Set and print any registered variables on the fly. 12 | - [x] Load and unload the dynamic libraries on the fly. 13 | - [x] Upgrade and rollback the implementation of registered functions on the fly. 14 | 15 | ## Installation 16 | 17 | Build the project from scratch. Required to install `gflags`, `glogs`, `gtest` and `subhook` in advance. 18 | 19 | ``` 20 | mkdir ./build/ 21 | cd ./build/ 22 | cmake .. 23 | make 24 | ``` 25 | 26 | Integrated with your C++ programs. 27 | 28 | ``` 29 | cmake -DCMAKE_INSTALL_PREFIX=/foo/bar/ .. 30 | make 31 | make install 32 | ``` 33 | 34 | ## Quickstart 35 | 36 | We can run any pre-built binary with the preload library to change the properties at any time. 37 | 38 | ``` 39 | # For Linux 40 | LD_PRELOAD="./preload/libpreload_hotpatch.so" ./examples/prebuilt_server 41 | 42 | # For Mac 43 | DYLD_INSERT_LIBRARIES=./preload/libpreload_hotpatch.dylib ./examples/prebuilt_server 44 | ``` 45 | 46 | Use the Python client or command `nc` to set and get the log level on the fly. 47 | 48 | ``` 49 | hotpatch -p $PID gflags set minloglevel 2 50 | 51 | hotpatch -p $PID gflags get minloglevel 52 | ``` 53 | 54 | We can register the variables and functions in your C++ program, take [simple_server](./examples/simple_server.cpp) for example. 55 | 56 | ``` 57 | // Use Hotpatch 58 | hotpatch::InitHotpatchServer(); 59 | 60 | // Register variable 61 | std::string user_name = "myname"; 62 | hotpatch::RegisterVariable("user_name", &user_name); 63 | int age = 10; 64 | hotpatch::RegisterVariable("age", &age); 65 | 66 | // Register function 67 | hotpatch::RegisterFunction("add_func", reinterpret_cast(add_func)); 68 | ``` 69 | 70 | Then we can get and set the values in any time while the program is running. It is meaningful for debuging and changing the logic of your programs without re-compiling and restarting the process. 71 | 72 | ``` 73 | hotpatch -p $PID var get string user_name 74 | hotpatch -p $PID var set string user_name new_name 75 | 76 | hotpatch -p $PID var get int age 77 | hotpatch -p $PID var set int age 20 78 | ``` 79 | 80 | Loading the new libraries allows developers to inject the new implementation of the functions on the fly and rollback is supported as well. 81 | 82 | ``` 83 | hotpatch -p $PID lib load add_func_patch1 ./examples/libadd_func_patch1.dylib 84 | 85 | hotpatch -p $PID func upgrade add_func_patch1 add_func 86 | 87 | hotpatch -p $PID func rollback add_func 88 | ``` 89 | 90 | ## Clients 91 | 92 | ### Python Client 93 | 94 | The command `hotpatch` is the socket client in Python which can be installed easily. 95 | 96 | ``` 97 | pip install hotpatch 98 | ``` 99 | 100 | Get and set the `gflags` or `glogs` properties. 101 | 102 | ``` 103 | hotpatch -p $PID gflags list 104 | 105 | hotpatch -p $PID gflags get minloglevel 106 | 107 | hotpatch -p $PID gflags set minloglevel 2 108 | ``` 109 | 110 | Get and set the registered variables. 111 | 112 | ``` 113 | hotpatch -p $PID var list 114 | 115 | hotpatch -p $PID var get string user_name 116 | 117 | hotpatch -p $PID var set string user_name new_name 118 | ``` 119 | 120 | Load and unload the dynamic libraries. 121 | 122 | ``` 123 | hotpatch -p $PID lib list 124 | 125 | hotpatch -p $PID lib load add_func_patch1 ./examples/libadd_func_patch1.dylib 126 | 127 | hotpatch -p $PID lib unload add_func_patch1 128 | ``` 129 | 130 | Upgrade and rollback the function implementation. 131 | 132 | ``` 133 | hotpatch -p $PID func upgrade add_func_patch1 add_func 134 | 135 | hotpatch -p $PID func rollback add_func 136 | ``` 137 | 138 | ### Shell Client 139 | 140 | `nc` is the built-in tool in most operating systems which can access the unix socket as well. 141 | 142 | Get and set the `gflags` or `glogs` properties. 143 | 144 | ``` 145 | echo "gflags list" | nc -U /tmp/$PID.socket 146 | 147 | echo "gflags get minloglevel" | nc -U /tmp/$PID.socket 148 | 149 | echo "gflags set minloglevel 2" | nc -U /tmp/$PID.socket 150 | ``` 151 | 152 | Get and set the registered variables. 153 | 154 | ``` 155 | echo "var list" | nc -U /tmp/$PID.socket 156 | 157 | echo "var get string user_name" | nc -U /tmp/$PID.socket 158 | 159 | echo "var set string user_name new_name" | nc -U /tmp/$PID.socket 160 | ``` 161 | 162 | Load and unload the dynamic libraries. 163 | 164 | ``` 165 | echo "lib list" | nc -U /tmp/$PID.socket 166 | 167 | echo "lib load add_func_patch1 ./examples/libadd_func_patch1.dylib" | nc -U /tmp/$PID.socket 168 | 169 | echo "lib unload add_func_patch1" | nc -U /tmp/$PID.socket 170 | ``` 171 | 172 | Upgrade and rollback the function implementation. 173 | 174 | ``` 175 | echo "func upgrade add_func_patch1 add_func" | nc -U /tmp/$PID.socket 176 | 177 | echo "func rollback add_func" | nc -U /tmp/$PID.socket 178 | ``` 179 | 180 | ## Performance 181 | 182 | **No performance overhead for your application!** 183 | 184 | Under the hood, `gflags` manages all the flag information globally and provide the APIs to access. For registered variables, we use the void pointer to access and only support for primitive types so far. For registered functions, the underlying instructions are mofified to jump to the new function address which brings no performance degradation. Here is the underlying implementation of [subhook](https://github.com/Zeex/subhook) for x86 architecture. 185 | 186 | ``` 187 | static int subhook_make_jmp64(void *src, void *dst) { 188 | struct subhook_jmp64 *jmp = (struct subhook_jmp64 *)src; 189 | 190 | jmp->push_opcode = PUSH_OPCODE; 191 | jmp->push_addr = (uint32_t)(uintptr_t)dst; /* truncate */ 192 | jmp->mov_opcode = MOV_OPCODE; 193 | jmp->mov_modrm = JMP64_MOV_MODRM; 194 | jmp->mov_sib = JMP64_MOV_SIB; 195 | jmp->mov_offset = JMP64_MOV_OFFSET; 196 | jmp->mov_addr = (uint32_t)(((uintptr_t)dst) >> 32); 197 | jmp->ret_opcode = RET_OPCODE; 198 | 199 | return 0; 200 | } 201 | ``` 202 | 203 | You can get more benchmark results with the scripts in [benchmark](./benchmark/). 204 | 205 | ## Notice 206 | 207 | For MacOS Catalina users, you need to set `printf '\x07' | dd of= bs=1 seek=160 count=1 conv=notrunc` because of the [security issue](https://stackoverflow.com/questions/60654834/using-mprotect-to-make-text-segment-writable-on-macos). 208 | -------------------------------------------------------------------------------- /benchmark/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | 2 | include_directories( 3 | ${INCLUDE_DIRECTORIES} 4 | ${PROJECT_SOURCE_DIR}/src 5 | ${PROJECT_BINARY_DIR}/src 6 | ) 7 | 8 | add_executable(benchmark_hotpatch benchmark_hotpatch.cpp) 9 | target_link_libraries(benchmark_hotpatch hotpatch_server) 10 | -------------------------------------------------------------------------------- /benchmark/benchmark_hotpatch.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #include "hotpatch_server.h" 8 | 9 | using namespace std; 10 | 11 | typedef unsigned long long timestamp_t; 12 | static timestamp_t get_timestamp () { 13 | struct timeval now; 14 | gettimeofday (&now, NULL); 15 | return now.tv_usec + (timestamp_t)now.tv_sec * 1000000; 16 | } 17 | 18 | int fibonacci(int n) { 19 | if (n <= 1) { 20 | return n; 21 | } else { 22 | return fibonacci(n-1) + fibonacci(n-2); 23 | } 24 | } 25 | 26 | int main(int argc, char **argv) { 27 | const int BENCHMARK_ITERATION = 1; 28 | timestamp_t start; 29 | timestamp_t end; 30 | double duration; 31 | 32 | auto hotpatch_server = std::make_unique(); 33 | hotpatch_server->Init(); 34 | 35 | // Test native C++ function 36 | printf("start"); 37 | start = get_timestamp(); 38 | for (int i=0; iRegisterFunction("fibonacci", (void*)fibonacci); 48 | hotpatch_server->GetHotpathCommand()->HandleLibLoad("fibonacci_patch1", "./examples/libfibonacci_patch1.so"); 49 | hotpatch_server->GetHotpathCommand()->HandleFuncUpgrade("fibonacci_patch1", "fibonacci"); 50 | 51 | // Test hotpatch C++ function 52 | start = get_timestamp(); 53 | for (int i=0; i 3 | 4 | using namespace std; 5 | 6 | extern "C" int add_func(int a, int b) { 7 | 8 | cout << "Call new extra add func" << endl; 9 | int result = (a + b) * 2; 10 | cout << "Result: " << result << endl; 11 | return result; 12 | } 13 | 14 | 15 | -------------------------------------------------------------------------------- /examples/add_one.cpp: -------------------------------------------------------------------------------- 1 | extern "C" int add_one(int a) { 2 | return a+1; 3 | } 4 | -------------------------------------------------------------------------------- /examples/fibonacci_func.cpp: -------------------------------------------------------------------------------- 1 | extern "C" int fibonacci(int n) { 2 | if (n <= 1) { 3 | return n; 4 | } else { 5 | return fibonacci(n-1) + fibonacci(n-2); 6 | } 7 | } -------------------------------------------------------------------------------- /examples/prebuilt_server.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | DEFINE_bool(debug, true, "Use debug or not"); 10 | DEFINE_string(log_level, "debug,info,warn", "The log level"); 11 | 12 | int add_func(int a, int b) { 13 | cout << "Call simple add" << endl; 14 | int result = a + b; 15 | cout << "Result: " << result << endl; 16 | return result; 17 | } 18 | 19 | int main(int argc, char **argv) { 20 | // Use gflags 21 | gflags::ParseCommandLineFlags(&argc, &argv, true); 22 | 23 | // Use glog 24 | google::InitGoogleLogging(argv[0]); 25 | FLAGS_logtostderr = 1; 26 | FLAGS_minloglevel = 0; 27 | 28 | for(int i=0; i<10; i++) { 29 | cout << "Sleep for one second" << endl; 30 | std::this_thread::sleep_for(std::chrono::milliseconds(1000)); 31 | 32 | cout << "Config debug: " << FLAGS_debug << endl; 33 | cout << "Config log_level: " << FLAGS_log_level << endl; 34 | 35 | LOG(INFO) << "glog debug message"; 36 | LOG(WARNING) << "glog warning message"; 37 | LOG(ERROR) << "glog erro message"; 38 | 39 | add_func(1, 2); 40 | } 41 | 42 | } 43 | 44 | -------------------------------------------------------------------------------- /examples/simple_server.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | #include "hotpatch_server.h" 11 | 12 | using namespace std; 13 | 14 | DEFINE_bool(debug, true, "Use debug or not"); 15 | DEFINE_string(log_level, "debug,info,warn", "The log level"); 16 | 17 | int add_func(int a, int b) { 18 | cout << "Call simple add" << endl; 19 | int result = a + b; 20 | cout << "Result: " << result << endl; 21 | return result; 22 | } 23 | 24 | int main(int argc, char **argv) { 25 | // Use gflags 26 | gflags::ParseCommandLineFlags(&argc, &argv, true); 27 | 28 | // Use glog 29 | google::InitGoogleLogging(argv[0]); 30 | FLAGS_logtostderr = 1; 31 | FLAGS_minloglevel = 0; 32 | 33 | // Use Hotpatch 34 | hotpatch::InitHotpatchServer(); 35 | 36 | // Register variable 37 | std::string user_name = "myname"; 38 | hotpatch::RegisterVariable("user_name", &user_name); 39 | int age = 10; 40 | hotpatch::RegisterVariable("age", &age); 41 | 42 | // Register function 43 | hotpatch::RegisterFunction("add_func", (void*) add_func); 44 | 45 | for(int i=0; i<60; i++) { 46 | cout << "Sleep for one second" << endl; 47 | std::this_thread::sleep_for(std::chrono::milliseconds(1000)); 48 | 49 | cout << "Config debug: " << FLAGS_debug << endl; 50 | cout << "Config log_level: " << FLAGS_log_level << endl; 51 | cout << "User name: " << user_name << endl; 52 | 53 | LOG(INFO) << "glog debug message"; 54 | LOG(WARNING) << "glog warning message"; 55 | LOG(ERROR) << "glog erro message"; 56 | 57 | add_func(1, 2); 58 | } 59 | 60 | } 61 | 62 | -------------------------------------------------------------------------------- /preload/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | 2 | include_directories( 3 | ${INCLUDE_DIRECTORIES} 4 | ${PROJECT_SOURCE_DIR}/src 5 | ${PROJECT_BINARY_DIR}/src 6 | ) 7 | 8 | add_library(preload_hotpatch SHARED preload_hotpatch.cpp) 9 | target_include_directories(preload_hotpatch PUBLIC "/usr/local/include/") 10 | target_link_directories(preload_hotpatch PUBLIC "/usr/local/lib/") 11 | target_link_libraries(preload_hotpatch hotpatch_server) 12 | 13 | install(TARGETS preload_hotpatch 14 | LIBRARY DESTINATION lib 15 | ARCHIVE DESTINATION lib 16 | RUNTIME DESTINATION bin) -------------------------------------------------------------------------------- /preload/preload_hotpatch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "hotpatch_server.h" 5 | 6 | /* 7 | For Linux, LD_PRELOAD="./libpreload_hotpatch.so" /bin/echo foo 8 | For MacOS, DYLD_INSERT_LIBRARIES=./libpreload_hotpatch.dylib /bin/echo foo 9 | */ 10 | __attribute__((constructor)) 11 | static void customConstructor(int argc, const char **argv) { 12 | printf("---------- Welcome to hotpatch ----------\n"); 13 | hotpatch::InitHotpatchServer(); 14 | } -------------------------------------------------------------------------------- /python/hotpatch/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tobegit3hub/hotpatch/876ed02988cf999254a61db3f9ca7116247fe389/python/hotpatch/__init__.py -------------------------------------------------------------------------------- /python/hotpatch/cli/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tobegit3hub/hotpatch/876ed02988cf999254a61db3f9ca7116247fe389/python/hotpatch/cli/__init__.py -------------------------------------------------------------------------------- /python/hotpatch/cli/hotpatch_cli.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import argparse 4 | import socket 5 | import sys 6 | import os 7 | import logging 8 | 9 | """ 10 | parser = argparse.ArgumentParser() 11 | parser.add_argument("-p", "--pid", type=int, required=True, help="Pid of the running process") 12 | root_subparsers = parser.add_subparsers() 13 | 14 | gflags_parser = root_subparsers.add_parser("gflags", help="Set gflags") 15 | gflags_parser.add_argument("method", type=str, help="Methods", choices=["list", "set", "get"]) 16 | 17 | var_parser = root_subparsers.add_parser("var", help="Set var") 18 | var_parser.add_argument("method", type=str, help="Methods", choices=["list", "set", "get"]) 19 | 20 | lib_parser = root_subparsers.add_parser("lib", help="Set lib") 21 | lib_parser.add_argument("method", type=str, help="Methods", choices=["load", "unload"]) 22 | 23 | func_parser = root_subparsers.add_parser("func", help="Set func") 24 | func_parser.add_argument("method", type=str, help="Methods", choices=["upgrade", "rollback"]) 25 | 26 | args = parser.parse_args() 27 | """ 28 | 29 | def main(): 30 | 31 | #pid = args.pid 32 | pid = int(sys.argv[2]) 33 | command = " ".join(sys.argv[3:]) 34 | 35 | socket_file = "/tmp/{}.socket".format(pid) 36 | print("Try to connect to socket file: {}".format(socket_file)) 37 | try: 38 | client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) 39 | client.connect(socket_file) 40 | except socket.error as msg: 41 | print("Fail to connect socket: {}".format(msg)) 42 | sys.exit(1) 43 | 44 | print("Try to send command: {}".format(command)) 45 | client.sendall(command.encode("utf-8")) 46 | 47 | result = client.recv(16) 48 | print("Receive result: {}".format(result)) 49 | 50 | client.close() 51 | 52 | if __name__ == "__main__": 53 | main() 54 | -------------------------------------------------------------------------------- /python/setup.py: -------------------------------------------------------------------------------- 1 | # Upload the package to pypi. 2 | # 1. python ./setup.py bdist_wheel --universal 3 | # 2. twine upload dist/hotpatch-x.x.x-py2.py3-none-any.whl 4 | 5 | from setuptools import setup, find_packages 6 | 7 | setup( 8 | name="hotpatch", 9 | version="0.1.0", 10 | author="tobe", 11 | author_email="tobeg3oogle@gmail.com", 12 | url="https://github.com/tobegit3hub/hotpatch", 13 | description="Apply hot patches for running processes without restarting", 14 | packages=find_packages(), 15 | install_requires=[], 16 | include_package_data=True, 17 | zip_safe=False, 18 | entry_points={ 19 | "console_scripts": [ 20 | "hotpatch=hotpatch.cli.hotpatch_cli:main" 21 | ] 22 | } 23 | ) 24 | -------------------------------------------------------------------------------- /src/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | 2 | set(HOTPATCH_HEADERS hotpatch_server.h hotpatch_command.h) 3 | set(HOTPATCH_SOURCES hotpatch_command.cpp hotpatch_server.cpp) 4 | 5 | add_library(hotpatch_server ${HOTPATCH_SOURCES}) 6 | target_include_directories(hotpatch_server PUBLIC "/usr/local/include/") 7 | target_link_directories(hotpatch_server PUBLIC "/usr/local/lib/") 8 | target_link_libraries(hotpatch_server gflags glog pthread dl subhook) 9 | 10 | add_executable(HotpatchCommandTest hotpatch_command_test.cpp) 11 | target_link_libraries(HotpatchCommandTest ${GTEST_BOTH_LIBRARIES} pthread) 12 | add_test(Test HotpatchCommandTest) 13 | enable_testing() 14 | 15 | #if(APPLE AND CMAKE_SIZEOF_VOID_P EQUAL 8 AND NOT SUBHOOK_FORCE_32BIT) 16 | # set_property(TARGET subhook_cxx_test_exe2 APPEND_STRING PROPERTY LINK_FLAGS " -Wl,-no_pie") 17 | #endif() 18 | 19 | install(TARGETS hotpatch_server 20 | LIBRARY DESTINATION lib 21 | ARCHIVE DESTINATION lib 22 | RUNTIME DESTINATION bin) 23 | install(FILES ${HOTPATCH_HEADERS} DESTINATION include) 24 | -------------------------------------------------------------------------------- /src/hotpatch_command.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | #include "hotpatch_command.h" 12 | 13 | using namespace std; 14 | using google::INFO; 15 | 16 | namespace hotpatch { 17 | 18 | 19 | HotpatchCommand::HotpatchCommand(std::map ®istered_variables, std::map ®istered_libraries, std::map ®istered_dl_handlers, std::map ®istered_functions): _registered_variables(registered_variables), _registered_libraries(registered_libraries), _registered_dl_handlers(registered_dl_handlers), _registered_functions(registered_functions) { 20 | 21 | } 22 | 23 | HotpatchCommand::~HotpatchCommand() { 24 | 25 | } 26 | 27 | void HotpatchCommand::ParseCommand(std::string command) { 28 | LOG(INFO) << "Parse input command: " << command; 29 | 30 | // Split string with space to vector 31 | std::vector split_keys; 32 | std::istringstream iss(command); 33 | for(std::string s; iss >> s; ) { 34 | split_keys.push_back(s); 35 | } 36 | 37 | // TODO: Check command format 38 | HandleCommand(split_keys); 39 | } 40 | 41 | bool HotpatchCommand::HandleCommand(std::vector command) { 42 | 43 | auto type = command[0]; 44 | auto method = command[1]; 45 | 46 | if (type.compare("gflags") == 0) { 47 | if (method.compare("list") == 0) { 48 | return HandleGflagsList(); 49 | } else if (method.compare("set") == 0) { 50 | return HandleGflagsSet(command[2], command[3]); 51 | } else if (method.compare("get") == 0) { 52 | return HandleGflagsGet(command[2]); 53 | } 54 | } else if (type.compare("var") == 0) { 55 | if (method.compare("list") == 0) { 56 | return HandleVarList(); 57 | } else if (method.compare("set") == 0) { 58 | return HandleVarSet(command[2], command[3], command[4]); 59 | } else if (method.compare("get") == 0) { 60 | return HandleVarGet(command[2], command[3]); 61 | } 62 | } else if (type.compare("lib") == 0) { 63 | if (method.compare("list") == 0) { 64 | return HandleLibList(); 65 | } else if (method.compare("load") == 0) { 66 | return HandleLibLoad(command[2], command[3]); 67 | } else if (method.compare("unload") == 0) { 68 | return HandleLibUnload(command[2]); 69 | } 70 | } else if (type.compare("func") == 0) { 71 | if (method.compare("upgrade") == 0) { 72 | return HandleFuncUpgrade(command[2], command[3]); 73 | } else if (method.compare("rollback") == 0) { 74 | return HandleFuncRollback(command[2]); 75 | } 76 | } 77 | 78 | return false; 79 | } 80 | 81 | bool HotpatchCommand::HandleGflagsList() { 82 | LOG(INFO) << "Try to list all gflags"; 83 | 84 | std::vector flags; 85 | gflags::GetAllFlags(&flags); 86 | std::vector::iterator i; 87 | for (i = flags.begin(); i != flags.end(); ++i) { 88 | LOG(INFO) << "Flag name: " << i->name << ", value: " << i->current_value; 89 | } 90 | 91 | return true; 92 | } 93 | 94 | bool HotpatchCommand::HandleGflagsGet(string key) { 95 | LOG(INFO) << "Try to get gflags with key: " << key; 96 | 97 | gflags::CommandLineFlagInfo flag; 98 | auto result = gflags::GetCommandLineFlagInfo(key.c_str(), &flag); 99 | 100 | LOG(INFO) << "Flag name: " << flag.name << ", value: " << flag.current_value; 101 | 102 | return result; 103 | } 104 | 105 | bool HotpatchCommand::HandleGflagsSet(string key, string value) { 106 | LOG(INFO) << "Try to set gflags with key: " << key << ", value: " << value; 107 | 108 | auto result = gflags::SetCommandLineOption(key.c_str(), value.c_str()); 109 | LOG(INFO) << "Set gflags result: " << result; 110 | 111 | return true; 112 | } 113 | 114 | bool HotpatchCommand::HandleVarList() { 115 | LOG(INFO) << "Try to list all variables"; 116 | 117 | for(std::map::iterator it = _registered_variables.begin(); it != _registered_variables.end(); ++it) { 118 | LOG(INFO) << "Get variable: " << it->first << ", pointer: " << it->second; 119 | } 120 | 121 | return true; 122 | } 123 | 124 | 125 | bool HotpatchCommand::HandleVarGet(string type, string key) { 126 | LOG(INFO) << "Try to get variable: " << key << ", type: "<< type; 127 | 128 | // TODO: Support most primitive types 129 | if (type.compare("string") == 0) { 130 | LOG(INFO) << *reinterpret_cast(_registered_variables[key]); 131 | } else if (type.compare("int") == 0) { 132 | LOG(INFO) << *reinterpret_cast(_registered_variables[key]); 133 | } else if (type.compare("double") == 0) { 134 | LOG(INFO) << *reinterpret_cast(_registered_variables[key]); 135 | } 136 | 137 | return true; 138 | } 139 | 140 | bool HotpatchCommand::HandleVarSet(string type, string key, string value) { 141 | 142 | if (type.compare("string") == 0) { 143 | std::string &v = *reinterpret_cast(_registered_variables[key]); 144 | v = value; 145 | } else if (type.compare("int") == 0) { 146 | int &v = *reinterpret_cast(_registered_variables[key]); 147 | v = std::stoi(value); 148 | } else if (type.compare("doble") == 0) { 149 | double &v = *reinterpret_cast(_registered_variables[key]); 150 | v = std::stod(value); 151 | } 152 | 153 | return true; 154 | } 155 | 156 | bool HotpatchCommand::HandleLibList() { 157 | LOG(INFO) << "Try to list all dynamic libraries"; 158 | 159 | // List all the registered libraries which are recorded in memory 160 | for(std::map::iterator it = _registered_dl_handlers.begin(); it != _registered_dl_handlers.end(); ++it) { 161 | LOG(INFO) << "Get library: " << it->first << ", pointer: " << it->second; 162 | } 163 | 164 | return true; 165 | } 166 | 167 | bool HotpatchCommand::HandleLibLoad(string name, string path) { 168 | LOG(INFO) << "Try to load dynamic library: " << name << ", path: " << path; 169 | 170 | // Load the dynamic library and register in memory 171 | _registered_dl_handlers[name] = dlopen(path.c_str(), RTLD_LAZY); 172 | if (!_registered_dl_handlers[name] ) { 173 | std::cerr << "Cannot open library: " << dlerror() << '\n'; 174 | return false; 175 | } 176 | 177 | return true; 178 | } 179 | 180 | bool HotpatchCommand::HandleLibUnload(string name) { 181 | LOG(INFO) << "Try to unload dynamic library: " << name; 182 | 183 | // Close the dl handler 184 | if (_registered_dl_handlers[name] != NULL) { 185 | dlclose(_registered_dl_handlers[name]); 186 | } 187 | 188 | // Remove the key in map 189 | _registered_dl_handlers.erase(name); 190 | 191 | return true; 192 | } 193 | 194 | 195 | bool HotpatchCommand::HandleFuncUpgrade(string lib_name, string func_name) { 196 | LOG(INFO) << "Try to upgrade function from dynamic library: " << lib_name << ", function name: " << func_name; 197 | 198 | if (_registered_libraries.find(lib_name) == _registered_libraries.end() ) { 199 | auto dl_handler = _registered_dl_handlers[lib_name]; 200 | if (dl_handler == NULL) { 201 | std::cerr << "dl_handler is null\n"; 202 | return false; 203 | } 204 | 205 | // TODO: Handle if method name is different from registered name 206 | auto origin_func = _registered_functions[func_name]; 207 | if (origin_func == NULL) { 208 | std::cerr << "origin_func is null\n"; 209 | return false; 210 | } 211 | 212 | auto load_func = dlsym(dl_handler, func_name.c_str()); 213 | if (load_func == NULL) { 214 | std::cerr << "load_func is null\n"; 215 | return false; 216 | } 217 | 218 | // TODO: Release the old one when register the one with the same name 219 | subhook_t func_hook = subhook_new((void *)origin_func, (void *)load_func, SUBHOOK_64BIT_OFFSET); 220 | if (func_hook == NULL) { 221 | std::cerr << "func_hook is null\n"; 222 | return false; 223 | } 224 | 225 | subhook_install(func_hook); 226 | 227 | _registered_func_subhook[func_name] = func_hook; 228 | 229 | } 230 | 231 | return true; 232 | } 233 | 234 | bool HotpatchCommand::HandleFuncRollback(string func_name) { 235 | LOG(INFO) << "Try to rollback function: " << func_name; 236 | 237 | // TODO: Check if it is registered or not 238 | subhook_t func_subhook = _registered_func_subhook[func_name]; 239 | 240 | subhook_remove(func_subhook); 241 | subhook_free(func_subhook); 242 | 243 | return true; 244 | } 245 | 246 | 247 | } // End of namespace -------------------------------------------------------------------------------- /src/hotpatch_command.h: -------------------------------------------------------------------------------- 1 | #ifndef _H_HOTPATCH_COMMAND 2 | #define _H_HOTPATCH_COMMAND 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | using namespace std; 10 | 11 | namespace hotpatch { 12 | 13 | class HotpatchCommand { 14 | 15 | private: 16 | std::map &_registered_variables; 17 | std::map &_registered_libraries; 18 | std::map &_registered_dl_handlers; 19 | 20 | std::map &_registered_functions; 21 | std::map _registered_func_subhook; 22 | 23 | public: 24 | 25 | HotpatchCommand(std::map& registered_variables, std::map& registered_libraries, std::map& registered_dl_handlers, std::map& registered_functions); 26 | ~HotpatchCommand(); 27 | 28 | void ParseCommand(std::string command); 29 | 30 | bool HandleCommand(std::vector command); 31 | 32 | bool HandleGflagsList(); 33 | bool HandleGflagsGet(string key); 34 | bool HandleGflagsSet(string key, string value); 35 | bool HandleVarList(); 36 | bool HandleVarGet(string type, string key); 37 | bool HandleVarSet(string type, string key, string value); 38 | bool HandleLibList(); 39 | bool HandleLibLoad(string name, string path); 40 | bool HandleLibUnload(string name); 41 | bool HandleFuncUpgrade(string lib_name, string func_name); 42 | bool HandleFuncRollback(string func_name); 43 | 44 | }; 45 | 46 | } // End of namespace 47 | 48 | 49 | #endif 50 | -------------------------------------------------------------------------------- /src/hotpatch_command_test.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "hotpatch_command.h" 5 | 6 | using namespace std; 7 | using namespace hotpatch; 8 | 9 | TEST(HotpatchCommand, Parse) { 10 | EXPECT_EQ(15, 15); 11 | } 12 | 13 | int main(int argc, char **argv) { 14 | ::testing::InitGoogleTest(&argc, argv); 15 | return RUN_ALL_TESTS(); 16 | } -------------------------------------------------------------------------------- /src/hotpatch_server.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | 22 | #include "hotpatch_server.h" 23 | 24 | using google::INFO; 25 | 26 | namespace hotpatch { 27 | 28 | // The global object 29 | HotpatchServer* global_hotpatch_server_ = NULL; 30 | 31 | HotpatchServer* GetHotpatchServer() { 32 | // TODO: Use lock to avoid conflict 33 | if (!global_hotpatch_server_) { 34 | global_hotpatch_server_ = new HotpatchServer; 35 | } 36 | return global_hotpatch_server_; 37 | } 38 | 39 | void InitHotpatchServer() { 40 | GetHotpatchServer()->Init(); 41 | } 42 | 43 | void ShutdownHotpatchServer() { 44 | delete global_hotpatch_server_; 45 | global_hotpatch_server_ = NULL; 46 | } 47 | 48 | void RegisterVariable(std::string key, void *p_value) { 49 | auto hp = GetHotpatchServer(); 50 | hp->RegisterVariable(key, p_value); 51 | } 52 | 53 | 54 | void RegisterFunction(std::string name, void* p_func) { 55 | auto hp = GetHotpatchServer(); 56 | hp->RegisterFunction(name, p_func); 57 | } 58 | 59 | // Constructor 60 | HotpatchServer::HotpatchServer() { 61 | hotpatch_command = std::make_shared(registered_variables, registered_libraries, registered_dl_handlers, registered_functions); 62 | } 63 | 64 | HotpatchServer::~HotpatchServer() { 65 | // Release resources 66 | Close(); 67 | } 68 | 69 | void start_socket_server(HotpatchServer* p_hotpatch_server) { 70 | 71 | const int buffer_size = 128; 72 | const int client_size = 8; 73 | 74 | // Get pid to set socket file 75 | pid_t pid = getpid(); 76 | std::string socket_path = "/tmp/" + std::to_string(pid) + ".socket"; 77 | std::cout << "Unix socket path: " << socket_path << std::endl; 78 | 79 | struct sockaddr_un serun; 80 | int listenfd, size; 81 | 82 | if ((listenfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) { 83 | perror("socket error"); 84 | exit(1); 85 | } 86 | 87 | memset(&serun, 0, sizeof(serun)); 88 | serun.sun_family = AF_UNIX; 89 | strcpy(serun.sun_path, socket_path.c_str()); 90 | size = offsetof(struct sockaddr_un, sun_path) + strlen(serun.sun_path); 91 | unlink(socket_path.c_str()); 92 | 93 | if (::bind(listenfd, (struct sockaddr *)&serun, size) < 0) { 94 | perror("bind error"); 95 | exit(1); 96 | } 97 | 98 | // Start unix socket server 99 | if (listen(listenfd, client_size) < 0) { 100 | perror("listen error"); 101 | exit(1); 102 | } 103 | 104 | struct sockaddr_un cliun; 105 | socklen_t cliun_len = sizeof(cliun); 106 | int connfd; 107 | while(p_hotpatch_server->GetShouldStop() == false) { 108 | // TODO: Use async API to close the socket 109 | // Accept socket client 110 | if ((connfd = accept(listenfd, (struct sockaddr *)&cliun, &cliun_len)) < 0){ 111 | perror("accept error"); 112 | continue; 113 | } 114 | 115 | // TODO: Pass the flag to stop waiting clients 116 | while(1) { 117 | char read_buf[buffer_size]; 118 | int readSize = read(connfd, read_buf, sizeof(read_buf)); 119 | if (readSize < 0) { 120 | perror("read error"); 121 | break; 122 | } else if(readSize == 0) { 123 | printf("EOF\n"); 124 | break; 125 | } 126 | 127 | // TODO: Create new buffer to load actual command 128 | char new_read_buf[readSize]; 129 | memcpy(new_read_buf, read_buf, readSize); 130 | 131 | // Handle command 132 | p_hotpatch_server->GetHotpathCommand()->ParseCommand(std::string(new_read_buf)); 133 | 134 | // Output result 135 | std::string sendResult = "Success to run"; 136 | write(connfd, sendResult.c_str(), sendResult.size()); 137 | } 138 | close(connfd); 139 | } 140 | close(listenfd); 141 | } 142 | 143 | void HotpatchServer::Init() { 144 | socket_server_thread = std::thread(&start_socket_server, this); 145 | } 146 | 147 | void HotpatchServer::Close() { 148 | cout << "Close the Hotpatch server" << endl; 149 | 150 | // Close the opened dynamic libraries handlers 151 | for(std::map::iterator it = registered_dl_handlers.begin(); it != registered_dl_handlers.end(); ++it) { 152 | cout << "Close dynamic library: " << it->first << endl; 153 | if (it->second != NULL) { 154 | dlclose(it->second); 155 | } 156 | } 157 | 158 | SetShouldStop(true); 159 | 160 | socket_server_thread.detach(); 161 | //socket_server_thread.join(); 162 | } 163 | 164 | void HotpatchServer::RegisterVariable(std::string key, void *p_value) { 165 | // TODO: Make share to release smart pointers 166 | registered_variables[key] = p_value; 167 | } 168 | 169 | void HotpatchServer::RegisterFunction(std::string func_name, void* p_func) { 170 | registered_functions[func_name] = p_func; 171 | } 172 | 173 | bool HotpatchServer::GetShouldStop() { 174 | return should_stop; 175 | } 176 | 177 | void HotpatchServer::SetShouldStop(bool stop) { 178 | should_stop = stop; 179 | } 180 | 181 | std::shared_ptr HotpatchServer::GetHotpathCommand() { 182 | return hotpatch_command; 183 | } 184 | 185 | } // End of namespace -------------------------------------------------------------------------------- /src/hotpatch_server.h: -------------------------------------------------------------------------------- 1 | #ifndef _H_HOTPATCH_SERVER 2 | #define _H_HOTPATCH_SERVER 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | #include "hotpatch_command.h" 9 | 10 | using namespace std; 11 | 12 | namespace hotpatch { 13 | 14 | extern void InitHotpatchServer(); 15 | extern void ShutdownHotpatchServer(); 16 | extern void RegisterVariable(std::string key, void *p_value); 17 | extern void RegisterFunction(std::string name, void *p_func); 18 | 19 | class HotpatchServer { 20 | 21 | private: 22 | std::thread socket_server_thread; 23 | bool should_stop = false; 24 | 25 | std::map registered_variables; 26 | std::map registered_libraries; 27 | std::map registered_dl_handlers; 28 | 29 | // Map of function name and function pointer which casts to void* 30 | std::map registered_functions; 31 | 32 | 33 | // TODO: Support multiple handlers for more libraries 34 | void* dl_handler; 35 | std::shared_ptr hotpatch_command; 36 | 37 | public: 38 | 39 | HotpatchServer(); 40 | 41 | ~HotpatchServer(); 42 | 43 | void Init(); 44 | 45 | void Close(); 46 | 47 | void RegisterVariable(std::string key, void *p_value); 48 | 49 | void RegisterFunction(std::string func_name, void* p_func); 50 | 51 | bool GetShouldStop(); 52 | 53 | void SetShouldStop(bool stop); 54 | 55 | std::shared_ptr GetHotpathCommand(); 56 | 57 | }; 58 | 59 | } // End of namespace 60 | 61 | #endif -------------------------------------------------------------------------------- /thirdparty/install_thirdparty.md: -------------------------------------------------------------------------------- 1 | 2 | ``` 3 | cmake -DCMAKE_INSTALL_PREFIX=/home/tobe/code/hotpatch/thirdparty/ . 4 | make install 5 | ``` 6 | --------------------------------------------------------------------------------