Assembly Challenge
From MRL Wiki
Challenge 1
Originally published 3/13/2006.
Contents |
[edit] Challenge
Write a stub program in assembler that returns "1" as the return code. Test it with this shell script:
#!/bin/sh
./stub
if test "$?" -ne 1; then
echo "You lose"
else
echo "You win"
fi
Rules:
- Must be written in assembly language. Processor and OS don't matter.
- Must be 100% original code.
- Either Intel or AT&T syntax is fine for x86 machines.
Some helpful pages:
[edit] Resources
FreeBSD application binary interface for x86
Mac OS X application binary interface (all platforms)
Linux standard base specification (all platforms)
[edit] Official Solutions
Here is a NASM version for Linux on x86:
SECTION .text
GLOBAL main
main
mov eax,1
mov ebx,1
int 80h
Here is a GNU as version for FreeBSD on x86:
.globl _start
.text
_start:
pushl $1
movl $1, %eax
int $0x80
Here is a GNU as version for Darwin (Mac OS X) on x86, using the new sysenter trap found on Darwin 8.4 (OS X 10.4.4) and up:
.globl _main
.text
_main:
movl $0x1, %eax
pushl $1
pushl $0x31337 # ignored
movl %esp, %ecx
pushl %ecx
sysenter
[edit] Contributed Solutions
Below is the solution using Linux exit system call. Compiled and tested using GNU Assembler on Intel platform.
#stub.s Sample program that returns 1
.section .text
.globl _start
_start:
movl $1, %eax
movl $1, %ebx
int $0x80
A solution that literally prints "1", without using exit codes.
.globl main
.type main, @function
main:
pushl %ebp
movl %esp, %ebp
subl $8, %esp
andl $-16, %esp
movl $0, %eax
addl $15, %eax
addl $15, %eax
shrl $4, %eax
sall $4, %eax
subl %eax, %esp
subl $12, %esp
pushl $49
call putchar
addl $16, %esp
subl $12, %esp
pushl $0
call exit
.size main, .-main
And now for something completely ridiculous. Completes with nasm -f; ld -s -o.
SECTION .data .text
GLOBAL _start
_start:
mov eax,1
mov ebx,1
int 80h