一段自己打印自己的c程序
2013-08-11 16:19
330 查看
今天发现了一段很有意思的C程序(http://blog.chinaunix.net/uid-233938-id-162628.html),实现的功能就是自己打印自已的内容。
这其中的道理其实是在程序链接阶段做了手脚!先看程序如下:
Makefile内容为:
这其中最重要的还是使用objcopy的技巧,没想到objcopy这么强大,可以把纯C文本转化成目标文件,那么文件内容就被插入最终生成的test.obj目标文件中。这点可以用hexdump验证
可以看到我们的程序内容直接插在ELF文件头的后面了。
到这里可能还有童鞋问,为什么是_binary_test_c_start呢?这就得了解objcopy的功能选项了
这下就一切都明了了吧,其中的objfile是变化的!
我们可以通过readelf查看程序中的符号:
可以看出,转换过程中,程序中自动添加了三个符号!
一开始我以为_binary_objfile_start是指针类型,指向我们的程序内容,但经过调试发现,并不是这样,它只是我们程序内容的第一个字符,同样的,_binary_objfile_end是程序内容的自后一个字符,既然这样,程序改成下面这样,我感觉更好理解一些:
其实程序本身没什么价值,就是觉得好玩而已,但是我觉得熟悉这些工具才是最重要的,不是吗? 某种程度上就是增加了解决问题的途径!
这其中的道理其实是在程序链接阶段做了手脚!先看程序如下:
#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; }
其实程序本身没什么价值,就是觉得好玩而已,但是我觉得熟悉这些工具才是最重要的,不是吗? 某种程度上就是增加了解决问题的途径!
相关文章推荐
- 一段自己打印自己的c程序
- js中设计一段程序,让它能够打印自己的方法收集藏
- js中设计一段程序,让它能够打印自己的方法收集藏
- 打印自己的一段漂亮C程序
- 一段自己打印自己的c程序
- 一段自己打印自己的c程序
- 一个有意思的东东 linux c打印自己的程序
- 用进程相关API函数编程一个程序,使之产生一个进程扇,父进程产生一系列子进程,每个子进程打印自己的PID然后退出。要求父进程最后打印PID
- 打印自己的程序
- 趣味程序:打印自己代码的程序
- 编写一个程序,开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示;如:ABCABC….依次递推。
- 编写一个程序,开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示;如:ABCABC….依次递推
- 打印自己的程序C#版
- 趣味程序:打印自己代码的程序
- 定义一个数组days,将其初始化今年每月的天数,编写一段程序,将每月的天数打印出来,
- 编写一个程序,开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示;如:ABCABC
- 编写一个程序,开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示;如:ABCABC….依次递推。
- 打印自己源代码的程序
- 转:定义一个数组days,将其初始化今年每月的天数,编写一段程序,将每月的天数打印出来, 分类: c语言经典题
- 分享一段用VC调用默认打印机打印菜单的程序