Skip to content

Instantly share code, notes, and snippets.

@djg
Created November 24, 2013 23:30
Show Gist options
  • Save djg/7633936 to your computer and use it in GitHub Desktop.
Save djg/7633936 to your computer and use it in GitHub Desktop.
crap0 - Level 0 compiler nasm -f bin crap0.asm && chmod +x crap0
%define STDIN_FILENO 0
%define STDOUT_FILENO 1
%define SYS_EXIT 1
%define SYS_READ 3
%define SYS_WRITE 4
USE32
ORG 0x1000
_mach_header: ; struct mach_header
dd 0xfeedface ; magic
dd 7 ; cputype (CPU_TYPE_X86)
dd 3 ; cpusubtype (CPU_SUBTYPE_I386_ALL)
dd 2 ; filetype (MH_EXECUTE)
dd 2 ; ncmds
dd _start - _cmds ; sizeofcmds
dd 0 ; flags
_cmds:
; Text Segment ; struct segment_command
dd 1 ; cmd (LC_SEGMENT)
dd 124 ; cmdsize
db '__TEXT' ; segname[16]
db 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
dd 0x1000 ; vmaddr
dd 0x1000 ; vmsize
dd 0 ; fileoff
dd filesize ; filesize
dd 7 ; maxprot
dd 5 ; initprot
dd 1 ; nsects
dd 0 ; flags
; Text section ; struct section
db '__text' ; sectname[16]
db 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
db '__TEXT' ; segname[16]
db 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
dd _start ; addr
dd _end - _start ; size
dd _start - 0x1000 ; offset
dd 2 ; align
dd 0 ; reloff
dd 0 ; nreloc
dd 0 ; flags
dd 0 ; reserved1
dd 0 ; reserved2
; ; struct thread_command
dd 5 ; cmd (LC_UNIXTHREAD)
dd 80 ; cmdsize
dd 1 ; flavor (i386_THREAD_STATE)
dd 16 ; uint32_t count
dd 0, 0, 0, 0, 0, 0, 0, 0 ; state
dd 0, 0, _start, 0, 0, 0, 0, 0 ; state
_start:
call gethex
sal eax, 4
push eax
call gethex
add [esp], eax
call putchar
pop eax
jmp _start
putchar: ; write a byte to stdout
LEA eax, [esp+4]
push 1 ; output length
push eax ; memory address
push STDOUT_FILENO ; write to standard output
push SYS_WRITE ; sys_write system call
pop eax
push eax
int 80h ; syscall(SYS_WRITE, STDOUT_FILENO, ch, 1)
add esp, 16
ret
gethex:
call getchar
cmp eax, 35 ; check for '#'
jne .convhex
.loop:
call getchar
cmp eax, 10 ; check for '\n'
jne .loop
jmp gethex
.convhex:
sub eax, 48 ; ch - '0'
jl gethex
cmp eax, 48
jl .ret
sub eax, 39
.ret:
ret
getchar: ; read a byte from stdin
push 0 ; ch
mov eax, esp ; &ch
push 1 ; input length
push eax ; memory address
push STDIN_FILENO ; read from standard input
push SYS_READ ; sys_read system call
pop eax
push eax
int 80h ; syscall(SYS_READ, STDIN_FILENO, &ch, 1)
test eax, eax
je exit
add esp, 16
pop eax
ret
exit: ; quit the program
push 0 ; program return value
push SYS_EXIT ; sys_exit system call
pop eax
push eax
int 80h ; syscall(SYS_EXIT, 0)
_end:
filesize equ $ - $$
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment