0

I'm trying to embed an executable binary inside an other one and then write the first binary to a file.

I successfully achieved this with a plain text file but when it comes to writing an executable I cant make it work.

So for example I want to copy /usr/bin/ls to ls2, so here what I tried

  • First: objcopy --input binary --output elf64-x86-64 --binary-architecture i386 /usr/bin/ls lss.o

  • the C code:

    #include <stdio.h> FILE *f; extern char _binary_lss_start; extern char _binary_lss_end; main() { f = fopen("lss", "w"); fprintf(f, &_binary_lss_start); fclose(f); return 0; } 
  • Compilation: gcc main.c lss.o

The Code successfully compiled but when i'm trying ./a.out nothing is written to lss.

(I'm using Arch Linux 4.18.5 and gcc 8.2.0.)

Can I achieve this?

1
  • 1
    Possible duplicate of Embedding resources in executable using GCC. In the past I seem to recall using objcpy to do it. In your case you should use fwrite and not fprintf. The start of data is binary_lss_start and the length of data is binary_lss_end - binary_lss_start + 1. Commented Aug 30, 2018 at 17:46

1 Answer 1

2

As @jww mentioned you should use fwrite. fprintf is looking for a 0 terminated string at _binary_lss_start which it might encounter in the very first byte and not write anything.

#include <stdio.h> FILE *f; extern char _binary_lss_start; extern char _binary_lss_end; int main(int c, char *v[]) { size_t size_to_write = &_binary_lss_end - &_binary_lss_start; f = fopen("lscpu2", "w"); if (f != NULL) { printf("Writing %ld bytes\n", size_to_write); fwrite(&_binary_lss_start, 1, size_to_write, f); fclose(f); } else { printf("File not found [%s]\n", "lss"); } return 0; } 
Sign up to request clarification or add additional context in comments.

2 Comments

i've tried but i wasnt able to make it work (compil error, seg fault, exec error..) As i alrady my c knoledge is very low, can you provide a basic exemple ?
@V1n5 I've added an example, it's untested but should work.