Linux hook函数简单实践

本文介绍了Linux环境下,通过hook技术拦截系统调用如malloc、open等的实践过程,详细展示了如何避免递归调用导致的segment fault问题,并通过示例代码说明了hook函数的实现。在实际应用中,由于ssh等程序的特殊性,用户态函数hook可能存在局限性,包括可被检测、不可扩展和编写复杂等问题。
摘要由CSDN通过智能技术生成

#起因
最近对hook函数比较感兴趣,希望能捕获所有某种系统调用,看网上有一篇文章(http://opensourceforu.com/2011/08/lets-hook-a-library-function/) 介绍hook malloc函数,但可能内核实现不同,4.4.0上有问题。特写一篇文章进行更新。

原文中,hook函数中调用printf,其实printf、fprintf等函数都会再调用malloc函数,导致segment fault。正确的方式应该是用snprintf写入内存,然后调用write函数输出。同理,如果在hook open函数的时候,调用了open函数,也会造成segment fault的问题。

#示例
a.c:

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
int main(void)
{
int p;
printf("calling from main...\n");
p=(int *)malloc(10);
if(!p)
{
printf("Got allocation error...\n");
exit(1);
}
printf("returning to main...\n");
free(p); /
freeing memory from heap */
printf("freeing memory...\n");
return 0;
}

prog2.c

#define _GNU_SOURCE
#include <stdio.h>
#include <stdint.h>
#include <stdarg.h>
#include <string.h>
#include <dlfcn.h> /* header required for dlsym() */
#include <unistd.h>

/* lcheck() is for memory leak check; its code is not shown
here /
void lcheck(void);
void print(const char
format, ...);

void* malloc(size_t size)
{
static void* (my_malloc)(size_t) = NULL;
print("inside shared object...\n");
if (!my_malloc)
my_malloc =

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值