Piling mechanism of reservoir

Posted by sirkodo on Wed, 01 Apr 2020 15:42:46 +0200

1. Pile driving at compile time
linux>gcc -DCOMPILETIME -c mymalloc.c
linux>gcc -I. -o intc int.c mymalloc.o
linux>./intc
Using the - I. parameter, it causes the C preprocessor to look in the current directory before searching the usual system directory

mymalloc.c:
#ifdef COMPILETIME
#include <stdio.h>
#include <malloc.h>
void * mymalloc(size_t size){
    void * ptr=malloc(size);
    printf("malloc(%d)=%p\n",(int)size,ptr);
    return ptr;
}
void myfree(void * ptr){
    free(ptr);
    printf("free(%p)\n",ptr);
}
#endif

malloc.h:
#define malloc(size) mymalloc(size)
#define free(ptr) myfree(ptr)
void * mymalloc(size_t size);
void myfree(void * ptr);

int.c:
#include <stdio.h>
#include <malloc.h>
int main(){
    int * p=malloc(32);
    free(p);
    return 0;
}

  

2. Driving when linking
Linux static connector supports the use of -- wrap f flag to drive when linking. Linker will resolve f to wrap F and the symbol real f to F.
linux>gcc -DLINKTIME -c mymalloc.c
linux>gcc -c int.c
linux>gcc -Wl,--wrap,malloc --Wl,--wrap,free -o intl int.o mymalloc.o

mymalloc:
#ifdef LINKTIME
#include <stdio.h>
void * __real_malloc(size_t size);
void __real_free(void * ptr);
void * __wrap_malloc(size_t size){
	void * ptr=__real_malloc(size);
	printf("malloc(%d)=%p\n",(int)size,ptr);
	return ptr;
}
void __wrap_free(void * ptr){
	__real_free(ptr);
	printf("free(%p)\n",ptr);
}
#endif

malloc.h:
#define malloc(size) mymalloc(size)
#define free(ptr) myfree(ptr)
void * mymalloc(size_t size)
void myfree(void * free)

int.c
#include <stdio.h>
#include <malloc.h>
int main()
{
	int * p=malloc(32);
	free(p);
	return 0;
}

  

3. Driving during operation
By setting the LD? Preload environment variable, the dynamic linker searches the LD? Preload library first, and then other libraries.
linux>gcc -DRUNTIME -shared -fpic -o mymalloc.so mymalloc.c -ldl
linux>gcc -o intr int.c
linux>LD_PRELOAD="./mymalloc.so" ./intr

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

//The other two are the same

Topics: Linux Linker