求大神啊,刚入门 的小弟遇到难题了
实验四 interposition lab
【开发语言及实现平台或实验环境】
CentOS/Linux
【实验目的】
1、理解包装函数。
2、掌握运行时打桩技术。
【实验内容】
一、对malloc和free函数打桩
首先编写包装函数malloc和free。
示例程序A:mymalloc.c
#ifdef RUNTIME
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
void *malloc(size_t size)
{
void *(*mallocp)(size_t size);
char *error;
mallocp = dlsym(RTLD_NEXT, "malloc");
if ((error = dlerror()) != NULL) {
fputs(error, stderr);
exit(1);
}
char *ptr = mallocp(size);
printf("malloc(%d) = %p\n", (int)size, ptr);
return ptr;
}
void free(void *ptr)
{
void (*freep)(void *) = NULL;
char *error;
if(!ptr) return;
freep = dlsym(RTLD_NEXT, "free");
if ((error = dlerror()) != NULL) {
fputs(error, stderr);
exit(1);
}
freep(ptr);
printf("free(%p)\n", ptr);
}
#endif
编译mymalloc.c并生成共享库mymalloc.so。
编写主程序:int.c
#include <stdio.h>
#include <malloc.h>
int main()
{
int *p = malloc(32);
free(p);
return 0;
}
编译并运行,可见没有任何输出
接下来用包装函数打桩运行(不要重新编译int.c)
二、本次实验内容(须提交实验报告)
对rand函数打桩,每次取随机数时,累计奇偶数的个数并输出。
主程序:randout.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int i, a[100];
srand(time(NULL));
for (i = 0; i < 100; i ++)
a[i] = rand();
for (i = 0; i < 100; i ++)
printf("%d ", a[i]);
printf("\n");
}
包装函数(部分代码):rand.c
#ifdef RUNTIME
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
static int n1 = 0, n2 = 0;
/* rand wrapper function */
int rand()
{
/* insert codes */
}
#endif
补充剩余代码,其中n1保存奇数个数,n2保存偶数个数。主程序运行的效果类似下图: