objcopy and link
前言
貌似挺旧每写过东西了,emm……..,jemalloc的东西也刚开始,就随意写写吧。
假设说,我写一个程序,要展示一样东西,一段文字/图片/视频。很简单对吧,open一下,看看文件大小,申请个内存,把二进制读进内存,放入相关的函数,done了。但是,我很任性,我不想open,不想读文件属性,不想自己申请内存,怎么办呢。有办法了,把文件导出一个16进制串,赋值给一个buff。
拉拉请冷静,办法还是有的,其实就是把文件转换为目标文件然后跟源代码目标文件链接一起,就可以了
将文件转换为目标文件
这是一个随手写的文件
***************************************************************
* Hello, I'm Muse.
*
***************************************************************
[Muse]# file picture
picture: ASCII text
使用objcopy将picture转换为obj
[Muse]# objcopy -I binary -O elf64-x86-64 -B i386 picture picture.o
[Muse]# objdump -x picture.o
picture.o: 文件格式 elf64-x86-64
picture.o
体系结构:i386:x86-64,标志 0x00000010:
HAS_SYMS
起始地址 0x0000000000000000
节:
Idx Name Size VMA LMA File off Algn
0 .data 000000a7 0000000000000000 0000000000000000 00000040 2**0
CONTENTS, ALLOC, LOAD, DATA
SYMBOL TABLE:
0000000000000000 l d .data 0000000000000000 .data
0000000000000000 g .data 0000000000000000 _binary_picture_start
00000000000000a7 g .data 0000000000000000 _binary_picture_end
00000000000000a7 g *ABS* 0000000000000000 _binary_picture_size
目标文件已生成,那么,代码里面怎么用呢
使用并生成
/* test.c */
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include <malloc.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
extern int32_t _binary_picture_start, _binary_picture_end;
int main(void)
{
char *start = (char *)&_binary_picture_start;
char *end = (char *)&_binary_picture_end;
printf("%.*s\n", (int32_t)(end - start), start);
return EXIT_SUCCESS;
}
直接extern链接外部符号就可以了,代码已写好,编译链接一条龙
[Muse]# gcc -c -g -Wall test.c -o test.o
[Muse]# gcc test.o picture.o -o test
[Muse]# ./test
***************************************************************
* Hello, I'm Muse.
*
***************************************************************