首页 文章

在平面二进制文件中包含char数组的内容

提问于
浏览
3

我使用平面二进制文件作为我的操作系统的外部程序 . 当我编译它们时,如下:

gcc -Wall ctest.c -o ctest.bin -nostdlib -Wl,-Ttext=0x8000,-nostdlib -masm=intel
objcopy -O binary -j .text ctest.bin ctest

但是这样做,字符数组的内容不会放在文件中 . 这是我的代码:

static volatile char string[4] = "Hi!\0";
static volatile char string2[15] = "Hello, World!\n\0";

int _start()
{
    asm("mov eax, [string]");
    asm("mov ebx, 0x00");
    asm("int 0x01");
    asm("mov eax, [string2]");
    asm("mov ebx, 0x00");
    asm("int 0x01");
    return 0;
}

当我运行objdump(我在精灵上运行它,但我验证它有与此相同的代码):

00008000 <_start>:
8000:   55                      push   ebp
8001:   89 e5                   mov    ebp,esp
8003:   a1 70 90 00 00          mov    eax,ds:0x9070
8008:   bb 00 00 00 00          mov    ebx,0x0
800d:   cd 01                   int    0x1
800f:   a1 74 90 00 00          mov    eax,ds:0x9074
8014:   bb 00 00 00 00          mov    ebx,0x0
8019:   cd 01                   int    0x1
801b:   b8 00 00 00 00          mov    eax,0x0
8020:   5d                      pop    ebp
8021:   c3                      ret

如您所见,文本无处可寻 . 我希望它能做到这样的事情: string db "Hi!", 0 我会用nasm做的 .

我应该怎么做才包含输出bin文件中的字符而不在汇编中编码?
提前致谢 .

2 回答

  • 1

    二进制可执行文件通常分为几个部分 . 您的字符串只是放在与代码不同的部分 . 这是有道理的,因为代码应该是只读的,但字符串已被声明为非const和volatile .

  • 4

    我想出了怎么做 . 首先,我创建了一个这样的链接器脚本(您可以将 phys 更改为您想要加载它的任何地址):

    OUTPUT_FORMAT("binary")
    ENTRY(start)
    phys = 0x8000;
    SECTIONS
    {
      .text phys : AT(phys) {
        code = .;
        *(.text)
        *(.rodata)
        . = ALIGN(0);
      }
      .data : AT(phys + (data - code))
      {
        data = .;
        *(.data)
        . = ALIGN(0);
      }
      .bss : AT(phys + (bss - code))
      {
        bss = .;
        *(.bss)
        . = ALIGN(0);
      }
      end = .;
    }
    

    然后编译并链接可执行文件,如下所示:

    gcc -m32 -nostdlib -nostdinc -fno-builtin -o exec.o exec.c
    ld -T link.ld -melf_i386 -o exec.bin exec.o
    

相关问题