#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <dlfcn.h>
#include <sys/mman.h>
void *orignal_=0;
unsigned char orignal_text_[12];
int orignal_page_;
int pagesize_;
void set(void *orignal, void * mock_func) {
int ret;
pagesize_ = sysconf(_SC_PAGE_SIZE);
orignal_page_ = reinterpret_cast<unsigned long int>(orignal) / pagesize_;
orignal_page_ *= pagesize_;
unsigned char machine_code[] = { 0x48, 0xb8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,0xff, 0xe0 };
ret = mprotect(reinterpret_cast<void*>(orignal_page_), pagesize_, PROT_READ | PROT_WRITE | PROT_EXEC);
if (ret < 0) {
printf("mproterct error");
return;
}
if (0 == orignal_) {
memcpy(orignal_text_, orignal, sizeof(orignal_text_));
}
memcpy(machine_code + 2, &mock_func, sizeof(mock_func));
memcpy(orignal, machine_code, sizeof(machine_code));
mprotect(reinterpret_cast<void*>(orignal_page_), pagesize_, PROT_READ | PROT_EXEC);
orignal_ = orignal;
}
void clear() {
if (0 != orignal_) {
int ret;
ret = mprotect(reinterpret_cast<void*>(orignal_page_), pagesize_, PROT_READ | PROT_WRITE | PROT_EXEC);
if (ret < 0) {
printf("mproterct error");
return;
}
memcpy(orignal_, orignal_text_, sizeof(orignal_text_));
mprotect(reinterpret_cast<void*>(orignal_page_), pagesize_, PROT_READ | PROT_EXEC);
orignal_ = 0;
}
}
void original(int a,int b){
int c = a+b;
c=c*100;
printf("original out:%d\n",c);
}
void newfunc(int a,int b){
int c = a-b;
printf("newfunc out:%d\n",c);
}
int main()
{
set((void*)original,(void*)newfunc);
original(1,2);
return 0;
}
linux hook demo
最新推荐文章于 2020-03-30 19:40:08 发布