AoC x64 Day 1
Advent of x64 Machine Code
Welcome to day one of Advent of Machine Code. I figured this would be a fun way to start blogging about my foray into the x86_64 instruction set encoding and executable file formats. Sadly, this won’t be a tutorial or a set of programming challenges like the GitHub Advent of Code.
Preface
The platform specific calls will be targeting Windows. I’ve chosen to focus on Windows here as it’s still the most widely installed operating system for this architecture (x86_64). On top of that I’ve been primarly learning x64 assembly on Windows, though I’ve done some on Linux as well. The book I’ve used, The Art of 64-bit Assembly, targets Windows and uses the MASM assembler. MASM is still around and supports modern 64-bit programming. On Linux, I’ve used the NASM assembler to write some basic programs, though I’ve not gotten too deep into macros there yet. At the time of writing this first post, I’m not really sure how much I want to try to pack into this series. I will most likely keep each day short and sweet. In the future, I’d like to explore Linux ELF binaries and system APIs.
I’ll try to call out where I’m covering platform specific things or instruction set architecture (ISA) specific things. All of the instruction encoding in the executable code section of the executable will apply to both Linux as well as Windows.
Machine Code?
So what I mean by machine code is the raw executable bytes of the instructions that the CPU consumes. The executable file itself also includes bytes that essentially tell the OS what type of executable image this is, where various sections live in the file, what to load, where to load it and a bunch more. A lot of the executable image format pertains to stuff that a normal compiler tool-chain might care about that doesn’t really matter if you’re writing the executable directly by hand. The same format covers object files, dll and exe files.
In this series I’ll be using a basic text editor to write the
hexadecimal in plain ASCII. I’ll also use ; as the first
character on a line to denote a comment. This keeps things simple
as it means that in order to generate the executable, all I have
to do is ignore the lines that begin with a ; and then covert
the hexadecimal to binary. One goal I have here is to keep the
usage of external tools and SDKs to a minimum. Nothing I do in
this series should require extra tools that don’t come installed
on modern versions of Windows.
Bootstrapping
In the olden days of computing a programmer would have to “bootstrap” a computer. Computers had a series of physical switches and indicator lights on a front panel that programmers would toggle in sequence to enter a program manually. This was cumbersome so this initial program would do the barest amount of initialization to allow for more automatic entry of program data.
As I began to figure how to even approach writing an executable by
hand, I had to figure out how to process my hexadecimal text into
binary. Unfortunately there isn’t, from what I could find, a built
in hex editor on Windows. I found out the tool certutil can
convert ASCII hex data into binary. Another thing that is a huge
benefit is having the ability to write inline comments to keep
things organized. Without comments I’d be in write-only mode
so-to-speak–I’d have to decode the data or keep a separate notes
file that references to a given offset and keeping that in sync
would be more of a challenge. The tool that I wound up using to
handle stripping out comments is findstr.
So with a text editor and those two tools via cmd.exe, I was
ultimately able to write an executable PE Image. Here is the
command:
findstr /v /b /c:";" in.txt > out.txt && ^
certutil -f -decodehex out.txt bin.exe
Now with those tools I was able to test the waters and write a
simple program that returns a specific number from it’s entry
point and then use echo %ERRORLEVEL% to inspect the result from
cmd.exe. But the ultimate goal is to write a program that
handles stripping comments and ASCII to binary. Doing this will
serve as a stepping-stone to a slightly more advanced parser that
adds a few creature comforts like labels and directives for
computing addresses, etc. The usefulness of this will become
apparent later on.
Machine Code Listing Format
Here’s an example:
; 0040: 50 45 00 00 (PE00 signature)
; :64 86 (Machine x86_64)
; :01 00 (NumberOfSections)
;+0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F
50 45 00 00 64 86 01 00 00 00 00 00 00 00 00 00
Firstly, the comments are there to assist in reading the hex
bytes. The first comments are denoting the address location
followed by the bytes that are being inserted. So, 0040: 50 45
means I’m inserting the bytes 50 and 45 starting at address
0040. The stuff in the parenthesis are just noting what
the given bytes represent. A separate comment line may be used for
more complex data. And look at these lines:
; :64 86 (Machine x86_64)
; :01 00 (NumberOfSections)
If a start address is missing before the :, it means the bytes
are appended after the preceeding bytes, so the above would result
in the data: 64 86 01 00 beginning from address 0044 which is
just after the first four bytes that got inserted.
Next is this:
;+0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F
For readability I’ll be laying out bytes in rows of 16 so that each row begins on a new multiple of 16. So the first row would be 0000, the second row 0010, next 0020 and so on. So to find the address of a given byte, I find the row address then the column number and replace the last 0 of the row address with the column number.
PE Format
The Windows executable format is called Portable Executable (PE).
You may hear it referred to as PE/COFF. COFF stands for Common
Object File Format, which isn’t relevant to my usage here. Sadly
there really isn’t an official formal spec from what I could
gather, but the best resource and, for all intents and purposes
(from what I can tell), spec for this is PE
Format.
The source of truth for the struct layouts, constants, etc. is
definitely the headers themselves, namely winnt.h in the Windows
SDK.
MS-DOS Header
The first thing to specify is the MS-DOS Stub Header:
; 0000: 4D 5A
;+0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F
4D 5A 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
; 3c:40 00 (points to the offset of the PE signature)
00 00 00 00 00 00 00 00 00 00 00 00 40 00 00 00
The MS-DOS Stub Header is present for legacy reasons. During the
transition from DOS to Windows, this is used to set up a stub DOS
program to print a message to DOS users that an executable
required Windows. For my usage, I only needed to specify the first
magic number and the address of the next section which lives at
address 00000040. The magic number is 4D 5A which is ASCII for
MZ. These are actually someone’s initials, another reference I
came across that goes into some historical detail can be found
here.
All of the fields after aren’t needed. The struct itself is
called IMAGE_DOS_HEADER and I filled in e_magic and
e_lfanew. Note: I think there are definitely tricks people have
used in the PE format to shrink the executable size by effectively
overlapping structs – I won’t be doing that here.
PE Signature & Image File Header
After the DOS Stub I need to put another magic number to tell the OS that this is a PE image (executable). Just like this:
; 40:50 45 00 00
;+0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F
50 45 00 00 00 00 00 00 00 00 00 00 00 00 00 00
This is the letters PE followed by two zero bytes. After this, comes the Image File Header which is where the data about the actual executable starts to get entered:
; 40:50 45 00 00 (PE00 signature)
; :64 86 (Machine x86_64)
; :01 00 (NumberOfSections)
;+0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F
50 45 00 00 64 86 01 00 00 00 00 00 00 00 00 00
The alignment gets a little wonky here due to the PE
signature–I’m re-specifying it here. Just after it, the
architecture is provided. This field is a WORD sized int (16-
bit) and the constant is 0x8664 but since I need to encode this
binary image in little-endian the least significant byte goes
first, hence 64 86. Then the number of sections for now is just
1 and that’s another WORD so 01 00. There are a few more
fields that spill into the next row:
; 54:F0 00 (SizeOfOptionalHeader)
; : 22 00 (Characteristics)
;+0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F
00 00 00 00 F0 00 22 00 00 00 00 00 00 00 00 00
The size is the size of the proceeding header which I left zero
until I figured the next header out. The size happens to be
F0. The Characteristics is a WORD sized bit field that
specifies the attributes of the image file. In this case I’m using
0x0002 which is IMAGE_FILE_EXECUTABLE_IMAGE and 0x0020 which
is IMAGE_FILE_LARGE_ADDRESS_AWARE, hence 22 00.
Image Optional Header
This is the next header after the file header. It actually isn’t
optional for image files, it is for object files though apparently
which maybe makes sense when you look at the information in it.
This header, as you saw above, is F0 or 140 bytes long for
64-bit images. Here’s the beginning of the header which also
includes the last two fields from the previous header struct:
; 54:F0 00 (SizeOfOptionalHeader)
; : 22 00 (Characteristics)
; == Image Optional Header ==
; :0B 02 (PE32+ magic number)
; 5C:00 02 00 00 (SizeOfCode)
;+0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F
00 00 00 00 F0 00 22 00 0B 02 00 00 00 02 00 00
So this struct (IMAGE_OPTIONAL_HEADER64) immediately follows the
image file header and begins with the magic number for PE+ and the
size of the code section. Then the size of the code is set to 200,
remember this is hexadecimal so 200 hex is 512 in decimal. 512 is
the minimum size, according
to the PE
Format.
Going with that size is working for me. This field needs to be a
power of two between 512 and 64k so 0x200 and 0x10000. That means
for this minimal example, most of the code section is just zero
padding.
Then there’s:
; 68:00 10 00 00 (AddressOfEntryPoint)
; :00 10 00 00 (BaseOfCode)
;+0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F
00 00 00 00 00 00 00 00 00 10 00 00 00 10 00 00
So skipping a few zero fields, I then set up the entry point address and base of code which is the start address of the code section. These are both address 0x1000 which are Relative Virtual Addresses (RVA). That means that the address is relative to the base of the image after it’s loaded into virtual memory. So this means that the entry point and the start of the code section begin 0x1000 bytes after the base address that the OS decides to load our program at. Up next:
; 70:00 00 40 00 00 00 00 00 (ImageBase)
; :00 10 00 00 (SectionAlignment)
; :00 02 00 00 (FileAlignment)
;+0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F
00 00 40 00 00 00 00 00 00 10 00 00 00 02 00 00
This sets up the ImageBase which is the preferred base virtual
address to load the program at. I set this to the default of
0x400000 it’s an 8 byte (QWORD) field. The next two are 4 byte
(DWORD) fields. The first is a section alignment of 0x1000
which is the minimum. This is the minimum alignment from what I
can gather since it’s the virtual memory page size for x64. All
sections will be aligned to this when loaded into memory. The
file alignment pertains to the actual image file itself. The as
mentioned earlier, the minimum is 0x200 which is 512 bytes.
Skipping to the next non-zero fields:
; 88:06 00 (MajorSubsystemVersion)
;+0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F
00 00 00 00 00 00 00 00 06 00 00 00 00 00 00 00
This just sets the major subsystem version to 6 which is what I
can tell is the right value for subsystem: console programs.
; 90:00 20 00 00 (SizeOfImage)
; :00 02 00 00 (SizeOfHeaders)
; 9C:03 00 (Subsystem: CUI)
;+0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F
00 20 00 00 00 02 00 00 00 00 00 00 03 00 00 00
SizeOfImage specifies the size of the image in bytes when loaded
into memory. This has to be a multiple of the section alignment so
0x2000 is the minimum size when loaded into memory. The next field
is the SizeOfHeaders which is the size of all of these headers
including the section headers I have yet to define. This all fits
in under 512 (0x200) bytes and this size has to be a multiple of
the file alignment so this is also the minimum size for this
field. Lastly the subsystem being used is
IMAGE_SUBSYSTEM_WINDOWS_CUI which is the constant in winnt.h
and equates to 3 since I’m starting with a console application.
; A0:00 00 10 00 00 00 00 00 (SizeOfStackReserve 1MB)
; :00 10 00 00 00 00 00 00 (SizeOfStackCommit 4KB)
;+0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F
00 00 10 00 00 00 00 00 00 10 00 00 00 00 00 00
Tells the loader to give the process a 1MB stack and to commit the first 4KB page of it.
; B0:00 00 10 00 00 00 00 00 (SizeOfHeapReserve 1MB)
; :00 10 00 00 00 00 00 00 (SizeOfHeapCommit 4KB)
;+0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F
00 00 10 00 00 00 00 00 00 10 00 00 00 00 00 00
Similar setup for Heap. Both stack and heap sizes are the defaults used by the windows linker. Then the last non-zero field of the struct is:
; C4:10 00 00 00 (NumberOfRvaAndSizes)
;+0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F
00 00 00 00 10 00 00 00 00 00 00 00 00 00 00 00
This declares the number of “data-directory entries”. I’m setting it to 0x10 which is all of them. The data directories are essentially a pointer and a size. They point to tables that contain various information. For this first image, they are all zeroed out and unused. So each data directory element takes up 8 bytes and there are 16 of them so there’s a fair bit of padding:
; D0
;+0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
; E0
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
; F0
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
; 100
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
; 110
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
; 120
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
; 130
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
; 140: 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
And that that’s finally the entire “optional” header.
Section Headers
There’s only one section in my first program, the code section.
The section headers are held in a table. The number of rows is
dictated by the NumberOfSections field that I set to 1 above.
Each header is 40 bytes long and describes the type of section it
is. It follows immediately after the optional image header:
; .text
; 148: 2E 74 65 78 74 00 00 00 (Name)
;+0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F
00 00 00 00 00 00 00 00 2E 74 65 78 74 00 00 00
The name field is 8 bytes and is a null terminated/zero padded string. If the name is exactly 8 bytes then it doesn’t need to be terminated. But they can’t be longer than 8 bytes for image files. And then:
; 150: 06 00 00 00 (VirtualSize)
; :00 10 00 00 (VirtualAddress)
; :00 02 00 00 (SizeOfRawData)
; :00 02 00 00 (PointerToRawData)
;+0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F
06 00 00 00 00 10 00 00 00 02 00 00 00 02 00 00
Virtual size is the size of the section when loaded into memory.
This is just set to 6 since I only need 6 bytes worth of
instruction data for this simple program. The virtual address is
0x1000, this is where the loader should put the section
relative to the base address. Size of raw data is 0x200 which
is the size in the file itself (min of 0x200). Then the pointer
to raw data is the offset into the file for the section. Again
this is 0x200 since it occupies the second 512 byte chunk.
Then the next row has some fields I don’t need to use until the
last:
; 16C:20 00 00 60 (Characteristics)
; 0x20 | 0x20 00 00 00 | 0x40 00 00 00
;+0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F
00 00 00 00 00 00 00 00 00 00 00 00 20 00 00 60
The characteristics is a bitmask that details what the section is
and what attributes it should take on. The fields I set here are:
IMAGE_SCN_MEM_EXECUTE : 0x20000000, IMAGE_SCN_MEM_READ : 0x40000000 and IMAGE_SCN_CNT_CODE : 0x00000020. Remember, this
is little-endian so the 60 is the highest order byte here. At
this point, the rest of the bytes are padded out up until file
address 0x200 where the .text section begins.
Executable Code
Well this might seem underwhelming, but here’s the code to return a result from the program.
; == .text Section ==
; 200:B8 2A 00 00 00 (mov eax, 2Ah)
; :C3 (ret)
;+0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +A +B +C +D +E +F
B8 2A 00 00 00 C3 00 00 00 00 00 00 00 00 00 00
The first byte is the opcode for mov r32, imm32. The next four
are for the imm32 immediate value. And lastly, the ret
instruction is encoded with just C3. And the rest of the
executable image is padded out with zeros up to address 3FF.
Final Thoughts
There is just a bit more boilerplate I need to set up and then the rest is just a matter of making some small tweaks to the PE related data structures. The majority of the work after that will be in encoding instructions and data for the program.