After staying away from assembly language for one year, I’m back :). And my first piece of code is a partial touch for Linux AMD64 architecture to debug 2 bugs (249878, 250066), I recently filed in Fedora 7 Bugzilla. Anyways, following is the gas code, I hacked:
/* touchs.S */
.globl _start
.section .text
#define SCR %rax
#define RETVAL %rax
#define ARG0 %rdi
#define ARG1 %rsi
#define ARG2 %rdx
#define ARG3 %r10
#define ARG4 %r8
#define ARG5 %r9
.p2align 4
_write:
mov $1, SCR
syscall
ret
.p2align 4
_exit:
mov $60, SCR
syscall
ret
.p2align 4
_open:
mov $2, SCR
syscall
ret
.p2align 4
_close:
mov $3, SCR
syscall
ret
.p2align 4
strlen:
xorb %al, %al
xorq %rcx, %rcx
decq %rcx
repne scasb
notq %rcx
decq %rcx
ret
.p2align 4
_start:
leaq 8(%rsp), %rbp
mov (%rsp), %r12 /* load argc into r12 */
cmp $2, %r12
jne 2f /* if(argc != 2) goto 3 */
mov 8(%rbp), ARG0 /* filename */
mov $(01|0100|01000), ARG1 /* O_WRONLY | O_CREAT | O_TRUNC */
mov $(0600), ARG2 /* File mode */
call _open /* fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600) */
cmpq $(~1), RETVAL
jle 1f /* if (fd <= -1) goto 1 */
mov RETVAL, ARG0 /* fd */
call _close /* close(fd) */
xorq ARG0, ARG0 /* 0 */
call _exit /* exit(0) */
1: notq RETVAL /* undo */
incq RETVAL /* 2's complement */
mov RETVAL, ARG0 /* -fd */
call _exit /* exit(-fd) */
2: leaq usage, %rdi
call strlen
mov %rcx, ARG2
mov $1, ARG0
leaq usage, ARG1
call _write
xorq ARG0,ARG0
call _exit
.p2align 4
usage:
.ascii "Usage: touchs [file-name-to-be-touched]"
.byte 10
.ascii "Touches the file in sameway as sudo. "
.ascii "Error if any, will be reported in exit code."
.word 10
Following is the command line to compile the code:
[wahjava@chatteau ~]$ gcc -g -o touchs -nostdinc -nostdlib touchs.S
And to run it:
[wahjava@chatteau ~]$ ./touchs "/tmp/_dc7u4C" && ls -l "/tmp/_dc7u4C"
So, happy hacking in .S world :-D