linux hook demo

#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;
}                                                                                                                                                   


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值