您的位置:首页 > 其它

一段自己打印自己的c程序

2013-08-11 16:19 330 查看
今天发现了一段很有意思的C程序(http://blog.chinaunix.net/uid-233938-id-162628.html),实现的功能就是自己打印自已的内容。

这其中的道理其实是在程序链接阶段做了手脚!先看程序如下:

#include <stdio.h>
#include <stdlib.h>

extern char * _binary_test_c_start;
int main()
{
        printf("%s", (char *)&_binary_test_c_start);
}


Makefile内容为:

#Makefile
test: test.obj test.c
	gcc -o test test.c test.obj
test.obj:test.c
	objcopy -I binary -B i386 -O elf32-i386 test.c test.obj
 
clean:
@-rm test.obj test

这其中最重要的还是使用objcopy的技巧,没想到objcopy这么强大,可以把纯C文本转化成目标文件,那么文件内容就被插入最终生成的test.obj目标文件中。这点可以用hexdump验证



可以看到我们的程序内容直接插在ELF文件头的后面了。

到这里可能还有童鞋问,为什么是_binary_test_c_start呢?这就得了解objcopy的功能选项了

-B bfdarch
       --binary-architecture=bfdarch
           Useful when transforming a architecture-less input file into an object file.  In this case the output architecture can be set to
           bfdarch.  This option will be ignored if the input file has a known bfdarch.  You can access this binary data inside a program by
           referencing the special symbols that are created by the conversion process.  These symbols are called _binary_objfile_start,
           _binary_objfile_end and _binary_objfile_size.  e.g. you can transform a picture file into an object file and then access it in your
           code using these symbols.

这下就一切都明了了吧,其中的objfile是变化的!

我们可以通过readelf查看程序中的符号:



可以看出,转换过程中,程序中自动添加了三个符号!

一开始我以为_binary_objfile_start是指针类型,指向我们的程序内容,但经过调试发现,并不是这样,它只是我们程序内容的第一个字符,同样的,_binary_objfile_end是程序内容的自后一个字符,既然这样,程序改成下面这样,我感觉更好理解一些:

#include <stdio.h>
#include <stdlib.h>

extern char     _binary_test_c_start;
int main(int argc, char *argv[])
{
        printf("%s", (char *)&_binary_test_c_start);
        return 0;
}


其实程序本身没什么价值,就是觉得好玩而已,但是我觉得熟悉这些工具才是最重要的,不是吗? 某种程度上就是增加了解决问题的途径!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐