β

How to make Linux shared library executable

Heiher's Blog 384 阅读

Examples for Linux x86_64 platform:
Library

/* test.c
 * Heiher <root@heiher.info>
 */
 
#include <stdio.h>
#include <stdlib.h>
 
int main (int argc, char *argv[]);
 
#if defined(__x86_64__)
const char lib_interp[] __attribute__((section(".interp"))) = "/lib64/ld-linux-x86-64.so.2";
#define init_args(argc, argv) __asm__ volatile ( \
			"mov 0x8(%%rbp), %%edx \n\tmov %%edx, %0 \n\tlea 0x10(%%rbp), %1 \n\t" \
			:"=m"(argc), "=r"(argv)::"memory")
#endif /* __x86_64__ */
 
void
_entry (void)
{
	int ret = 0;
	int argc = 0;
	char **argv = NULL;
 
	init_args (argc, argv);
	ret = main (argc, argv);
	exit (ret);
}
 
int
main (int argc, char *argv[])
{
	int i = 0;
	void *p = malloc (4096);
 
	printf ("argc: %d, argv: %p, p: %p\n", argc, argv, p);
	for (i=0; i<argc; i++)
	  printf ("argv[%d]: %s\n", i, argv[i]);
 
	free (p);
 
	return 0;
}
 
int
test (int a, int b)
{
	return a + b;
}

Build

gcc -fPIC -shared -o libtest.so test.c -Wl,-e_entry

Run

./libtest.so a b c
argc: 4, argv: 0x7ffff3c165b8, p: 0x7fea935c4010
argv[0]: ./libtest.so
argv[1]: a
argv[2]: b
argv[3]: c

App

/* call.c
 * Heiher <root@heiher.info>
 */
 
#include <stdio.h>
 
int test(int a, int b);
 
int
main (int argc, char *argv[])
{
	printf ("%d\n", test (1, 2));
 
	return 0;
}

Build

gcc -o call call.c -L. -ltest

Run

LD_LIBRARY_PATH=. ./call

Over!

作者:Heiher's Blog
Across the great firewall we can reach every corner in the world.
原文地址:How to make Linux shared library executable, 感谢原作者分享。