How to write and execute PURE machine code manually without containers like EXE or ELF?

Machine Code

Machine Code Problem Overview


I just need a hello world demo to see how machine code actually works.

Though windows' EXE and linux' ELF is near machine code,but it's not PURE

How can I write/execute PURE machine code?

Machine Code Solutions


Solution 1 - Machine Code

You can write in PURE machine code manually WITHOUT ASSEMBLY

Linux/ELF: https://github.com/XlogicX/m2elf. This is still a work in progress, I just started working on this yesterday.

Source file for "Hello World" would look like this:

b8    21 0a 00 00	#moving "!\n" into eax
a3    0c 10 00 06	#moving eax into first memory location
b8    6f 72 6c 64	#moving "orld" into eax
a3    08 10 00 06	#moving eax into next memory location
b8    6f 2c 20 57	#moving "o, W" into eax
a3    04 10 00 06	#moving eax into next memory location
b8    48 65 6c 6c	#moving "Hell" into eax
a3    00 10 00 06	#moving eax into next memory location
b9    00 10 00 06	#moving pointer to start of memory location into ecx
ba    10 00 00 00	#moving string size into edx
bb    01 00 00 00	#moving "stdout" number to ebx
b8    04 00 00 00	#moving "print out" syscall number to eax
cd    80	        #calling the linux kernel to execute our print to stdout
b8    01 00 00 00	#moving "sys_exit" call number to eax
cd    80	        #executing it via linux sys_call

WIN/MZ/PE:

shellcode2exe.py (takes asciihex shellcode and creates a legit MZ PE exe file) script location:

https://web.archive.org/web/20140725045200/http://zeltser.com/reverse-malware/shellcode2exe.py.txt

dependency:

https://github.com/radare/toys/tree/master/InlineEgg

extract

python setup.py build




sudo python setup.py install

Solution 2 - Machine Code

Everyone knows that the application we usually wrote is run on the operating system. And managed by it.

It means that the operating system is run on the machine. So I think that is PURE machine code which you said.

So, you need to study how an operating system works.

Here is some NASM assembly code for a boot sector which can print "Hello world" in PURE.

 org
   xor ax, ax
   mov ds, ax
   mov si, msg
boot_loop:lodsb
   or al, al 
   jz go_flag   
   mov ah, 0x0E
   int 0x10
   jmp boot_loop
 
go_flag:
   jmp go_flag
 
msg   db 'hello world', 13, 10, 0
 
   times 510-($-$$) db 0
   db 0x55
   db 0xAA

And you can find more resources here: http://wiki.osdev.org/Main_Page.

END.

If you had installed nasm and had a floppy, You can

nasm boot.asm -f bin -o boot.bin
dd if=boot.bin of=/dev/fd0

Then, you can boot from this floppy and you will see the message. (NOTE: you should make the first boot of your computer the floppy.)

In fact, I suggest you run that code in full virtual machine, like: bochs, virtualbox etc. Because it is hard to find a machines with a floppy.

So, the steps are First, you should need to install a full virtual machine. Second, create a visual floppy by commend: bximage Third, write bin file to that visual floppy. Last, start your visual machine from that visual floppy.

NOTE: In https://wiki.osdev.org , there are some basic information about that topic.

Solution 3 - Machine Code

Real Machine Code

What you need to run the test: Linux x86 or x64 (in my case I am using Ubuntu x64)

Let's Start

This Assembly (x86) moves the value 666 into the eax register:

movl $666, %eax
ret

Let's make the binary representation of it:

Opcode movl (movl is a mov with operand size 32) in binary is = 1011

Instruction width in binary is = 1

Register eax in binary is = 000

Number 666 in signed 32 bits binary is = 00000000 00000000 00000010 10011010

666 converted to little endian is = 10011010 00000010 00000000 00000000

Instruction ret (return) in binary is = 11000011

So finally our pure binary instructions will look like this:

1011(movl)1(width)000(eax)10011010000000100000000000000000(666) 11000011(ret)

Putting it all together:

1011100010011010000000100000000000000000
11000011

For executing it the binary code has to be placed in a memory page with execution privileges, we can do that using the following C code:

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>

/* Allocate size bytes of executable memory. */
unsigned char *alloc_exec_mem(size_t size)
{
    void *ptr;

    ptr = mmap(0, size, PROT_READ | PROT_WRITE | PROT_EXEC,
               MAP_PRIVATE | MAP_ANON, -1, 0);

    if (ptr == MAP_FAILED) {
            perror("mmap");
            exit(1);
    }

    return ptr;
}

/* Read up to buffer_size bytes, encoded as 1's and 0's, into buffer. */
void read_ones_and_zeros(unsigned char *buffer, size_t buffer_size)
{
    unsigned char byte = 0;
    int bit_index = 0;
    int c;

    while ((c = getchar()) != EOF) {
            if (isspace(c)) {
                    continue;
            } else if (c != '0' && c != '1') {
                    fprintf(stderr, "error: expected 1 or 0!\n");
                    exit(1);
            }

            byte = (byte << 1) | (c == '1');
            bit_index++;

            if (bit_index == 8) {
                    if (buffer_size == 0) {
                            fprintf(stderr, "error: buffer full!\n");
                            exit(1);
                    }
                    *buffer++ = byte;
                    --buffer_size;
                    byte = 0;
                    bit_index = 0;
            }
    }

    if (bit_index != 0) {
            fprintf(stderr, "error: left-over bits!\n");
            exit(1);
    }
}

int main()
{
    typedef int (*func_ptr_t)(void);

    func_ptr_t func;
    unsigned char *mem;
    int x;

    mem = alloc_exec_mem(1024);
    func = (func_ptr_t) mem;

    read_ones_and_zeros(mem, 1024);

    x = (*func)();

    printf("function returned %d\n", x);

    return 0;
}

Source: https://www.hanshq.net/files/ones-and-zeros_42.c

We can compile it using:

gcc source.c -o binaryexec

To execute it:

./binaryexec

Then we pass the first sets of instructions:

1011100010011010000000100000000000000000

press enter

and pass the return instruction:

11000011

press enter

finally ctrl+d to end the program and get the output:

> function returned 666

Solution 4 - Machine Code

It sounds like you're looking for the old 16-bit DOS .COM file format. The bytes of a .COM file are loaded at offset 100h in the program segment (limiting them to a maximum size of 64k - 256 bytes), and the CPU simply started executing at offset 100h. There are no headers or any required information of any kind, just raw CPU instructions.

Solution 5 - Machine Code

The OS is not running the instructions, the CPU does (except if we're talking about a virtual machine OS, which do exist, I'm thinking about Forth or such things). The OS however does require some metainformation to know, that a file does in fact contain executable code, and how it expects its environment to look like. ELF is not just near machine code. It is machine code, together with some information for the OS to know that it's supposed to put the CPU to actually execute that thing.

If you want something simpler than ELF but *nix, have a look at the a.out format, which is much simpler. Traditionally *nix C compilers do (still) write their executable to a file called a.out, if no output name is specified.

Solution 6 - Machine Code

When targeting an embedded system you can make a binary image of the rom or ram that is strictly the instructions and associated data from the program. And often can write that binary into a flash/rom and run it.

Operating systems want to know more than that, and developers often want to leave more than that in their file so they can debug or do other things with it later (disassemble with some recognizable symbol names). Also, embedded or on an operating system you may need to separate .text from .data from .bss from .rodata, etc and file formats like .elf provide a mechanism for that, and the preferred use case is to load that elf with some sort of loader be it the operating system or something programming the rom and ram of a microcontroller.

.exe has some header info as well. As mentioned .com didnt it loaded at address 0x100h and branched there.

to create a raw binary from an executable, with a gcc created elf file for example you can do something like

objcopy file.elf -O binary file.bin

If the program is segmented (.text, .data, etc) and those segments are not back to back the binary can get quite large. Again using embedded as an example if the rom is at 0x00000000 and data or bss is at 0x20000000 even if your program only has 4 bytes of data objcopy will create a 0x20000004 byte file filling in the gap between .text and .data (as it should because that is what you asked it to do).

What is it you are trying to do? Reading a elf or intel hex or srec file are quite trivial and from that you can see all the bits and bytes of the binary. Or disassembling the elf or whatever will also show you that in a human readable form. (objdump -D file.elf > file.list)

Solution 7 - Machine Code

With pure machine code, you can use any language that has an ability to write files. even visual basic.net can write 8,16,32,64 bit while interchanging between the int types while it writes.

You can even set up to have vb write out machine code in a loop as needed for something like setpixel, where x,y changes and you have your argb colors.

or, create your vb.net program regularly in windows, and use NGEN.exe to make a native code file of your program. It creates pure machine code specific to ia-32 all in one shot throwing the JIT debugger aside.

Solution 8 - Machine Code

This are nice responses, but why someone would want to do this might guide the answer better. I think the most important reason is to get full control of their machine, especially over its cache writing, for maximum performance, and prevent any OS from sharing the processor or virtualizing your code (thus slowing it down) or especially in these days snooping on your code as well. As far as I can tell, assembler doesn't handle these issues and M$/Intel and other companies treat this like an infringement or "for hackers." This is very wrong headed however. If your assembler code is handed over to an OS or proprietary hardware, true optimization (potentially at GHz frequencies) will be out of reach. This is an very important issue with regards to science and technology, as our computers cannot be used to their full potential without hardware optimization, and are often computing several orders of magnitude below it. There probably is some workaround or some open-source hardware that enables this but I have yet to find it. Penny for anyones thoughts.

Solution 9 - Machine Code

The next program is an Hello World program I wrote in Machine Code 16 bit (intel 8086), If you want to know machine code, I suggest that you learn Assembly first, because every line of code in Assembly is converted to A code line in Machine Code. For well I know I am from the few people in the world, still programming in Machine Code, instead of Assembly.

BTW, To run it, save the file with a ".com" extension and run on DOSBOX!

So, this is an Hello World Program.

Solution 10 - Machine Code

On Windows--at least 32bit Windows--you can execute RAW INSTRUCTIONS using a .com file.

For instance, if you take this string and save it in notepad with a .com extension:

X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*

It will print a string and set off your antivirus software.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncompilerView Question on Stackoverflow
Solution 1 - Machine CodeXlogicXView Answer on Stackoverflow
Solution 2 - Machine CodegelosieView Answer on Stackoverflow
Solution 3 - Machine CodeD.SnapView Answer on Stackoverflow
Solution 4 - Machine CodeGreg HewgillView Answer on Stackoverflow
Solution 5 - Machine CodedatenwolfView Answer on Stackoverflow
Solution 6 - Machine Codeold_timerView Answer on Stackoverflow
Solution 7 - Machine CodeJasonView Answer on Stackoverflow
Solution 8 - Machine CodeZack BarkleyView Answer on Stackoverflow
Solution 9 - Machine Codeגיא כהןView Answer on Stackoverflow
Solution 10 - Machine CodePatrickView Answer on Stackoverflow