程序打印自身代码的两种方法
方法一:利用fopen,打开可执行程序对应的source code file
/*****************************************
code writer : EOF
code file : print_my_self.c
code date : 2014.08.01
e-mail: jasonleaster@gmail.com
code purpose :
Aha, print out myself!
******************************************/
#include <stdio.h>
#include <fcntl.h>
#define BUFFSIZE 1024
char buffer[BUFFSIZE];
int main()
{
FILE* fp = NULL;
int ret = 0;
if((fp = fopen("./print_my_self.c","r")) == NULL)
{
printf("Damn it,fopen failed\n");
return 0;
}
while((ret = fread(buffer,sizeof(char),BUFFSIZE-1,fp)) > 0)
{
buffer[ret-1] = '\0';
printf("%s",buffer);
}
fclose(fp);
return 0;
}
打印什么。。。不用说
上面这种策略就是骗小孩儿的
第二种方法还有点看头,不过也挺。。。没劲的。。。如果看透了的话
方法二:
利用objcopy,然后将source code file 生成一个可以和elf格式文件合并的文件,代码中引用该文件的一个指针,最后用gcc 将两个文件共同编译进可执行程序
/*******************************************
code writer : EOF
code date : 2014.08.01
code file : test.c
code purpose:
just a demo for a useful tool -- objcopy
and a point which was produced by the tool and
point to the start of this file.
*******************************************/
#include <stdio.h>
extern char* _binary_test_c_start;
int main()
{
printf("%s",(char*)&_binary_test_c_start);
return 0;
}
jasonleaster@ubuntu:~$ objcopy -I binary -O elf64-x86-64 -B i386 test.c test.bin
jasonleaster@ubuntu:~$ gcc ./test.bin ./test.c -o ./a.out
jasonleaster@ubuntu:~$ ./a.out
/*******************************************
code writer : EOF
code date : 2014.08.01
code file : test.c
code purpose:
just a demo for a useful tool -- objcopy
and a point which was produced by the tool and
point to the start of this file.
*******************************************/
#include <stdio.h>
extern char* _binary_test_c_start;
int main()
{
printf("%s",(char*)&_binary_test_c_start);
return 0;
}
思(che)考(dan):
其实这个demo有个“bug”,要求是代码打印自身,其实只要在main里面随便加个printf,就会打印额外的信息,打印的就不止是source code file的字符了
第二种方法个人看来就是提升逼格用的,感觉和第一种傻瓜用法没什么本质区别,都离不开原本的source code file--test.c