输出自身的程序
复制本地路径 | 在线编辑
之前学习了一个关于在编译器中加入后门代码的项目,里面涉及到输出自身程序(但其实没必要),这里简单记录一下。
这有个专业的名词叫做 Quine,不直接兜圈子,直接看下面的代码,写的极好,也很容易理解:
#include<stdio.h>
char *s = "\";\n\
int main() {\n\
printf(\"#include<stdio.h>\\nchar *s = \\\"\");\n\
char *p = s;\n\
while (*p != 0)\n\
if (*p == '\\\\' || *p == '\"')\n\
printf(\"\\\\%c\", *p++);\n\
else if (*p == '\\n')\n\
printf(\"\\\\n\\\\%c\", *p++);\n\
else\n\
printf(\"%c\", *p++);\n\
printf(\"%s\", s);\n\
/* Here we can put any code */\n\
}\n\
";
int main() {
printf("#include<stdio.h>\nchar *s = \"");
char *p = s;
while (*p != 0)
if (*p == '\\' || *p == '"')
printf("\\%c", *p++);
else if (*p == '\n')
printf("\\n\\%c", *p++);
else
printf("%c", *p++);
printf("%s", s);
/* Here we can put any code */
}
这就实现了输出自身的功能,非常地精妙。他相当于在 while 循环的时候把最上面的字符串输出了,最后再用要给 printf 把下面的字符串输出了。
只要在 /* Here we can put any code*/ 那儿同步放下任意的代码,那么程序始终可以输出自身,很有意思。
来源:https://github.com/bojieli/CompilerBackdoor/blob/master/self-print/hello.c