3

I have a file which content represents x64 machine code in hex.

48 c7 c0 7b 00 00 00 48 c7 c1 59 01 00 00 48 01 c8 c3

The example above can be disassembled to:

0:  48 c7 c0 7b 00 00 00    mov    rax,0x7b
7:  48 c7 c1 59 01 00 00    mov    rcx,0x159
e:  48 01 c8                add    rax,rcx
11: c3                      ret

This machine code is being generated directly, so the assembler shown above is for the sake of the example. I do not have access to it in general.

What I want to do is convert this hex file to and executable in the most direct way possible. I tried using xxd -r, but this does not seem to create a well-formatted executable since I get a Exec format error when trying to run it.

How should I generate an executable from the hex code under Linux?

Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
  • 1
    Essentially you want an elf binary? The most straightforward way would be to assemble the disassembled code you already have. – PiRocks Apr 24 '20 at 22:10
  • 1
    @PiRocks Seems like it yes! Although, I have a "compiler" which specifically does the job of the assembler, for that reason I do not want to depend on an external assembler. I guess my question is: now that I generated machine code, what is the last step to make it into an elf file? – Olivier Melançon Apr 24 '20 at 22:17
  • The generated machine code does not need linking, it is guaranteed not to use external libraries. – Olivier Melançon Apr 24 '20 at 22:21
  • 1
    So your looking for a programmatic way of creating an elf file instead of tool based approach? If so the two approaches are to generate an object file and use a linker to get a final elf file, or to generate the elf file yourself. – PiRocks Apr 24 '20 at 22:21
  • There's a header file called elf.h which defines the elf file format, which would be a starting point for a programmatic approach – PiRocks Apr 24 '20 at 22:22
  • Should I be able to do this using only, say, `ld` and `xxd`? From what I understand, I have my ELF data, I just need to create a header? – Olivier Melançon Apr 24 '20 at 22:32
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/212453/discussion-between-pirocks-and-olivier-melancon). – PiRocks Apr 24 '20 at 22:33
  • 2
    Does https://stackoverflow.com/questions/26294034/how-to-make-an-executable-elf-file-in-linux-using-a-hex-editor help? – tink Apr 24 '20 at 22:37

1 Answers1

0

From my understanding of the discussion which followed my question, what I want to do is create an ELF file. This question covers how to create your own ELF header.

Although, if you do not want to go through the trouble, you can actually use gcc to compile a sequence of bytes to an executable.

.section .text
    .global main
main:
    .byte 0x48 0xc7 0xc0 0x7b 0x00 0x00 0x00 0x48 0xc7 0xc1 0x59 0x01 ...

You can then compile the above with gcc file.S -o file. This will create the desired ELF file.

Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73