.comm system__errno,4,4
.comm environ,4,4

.text
.global _start
_start:
	popl	%ecx			/* %ecx = argc */
	movl	%esp,%esi		/* %esi = argv */
	pushl	%ecx
	leal	4(%esi,%ecx,4),%eax	/* %eax = envp = (4*ecx)+%esi+4 */

	pushl	%eax
	pushl	%esi
	pushl	%ecx
	movl	%eax,environ

	call	main
	pushl	%eax
	call	exit
	hlt	/* die now ! will ya ... */
.size	 _start,.-_start

/* ------------------------------------------------------- */
.text
.weak exit
exit:
.global _exit
.type	_exit,@function
_exit:
	movb	$1,%al
.size _exit,.-_exit

.global __unified_syscall
.type	__unified_syscall,@function
__unified_syscall:
	movzbl	%al, %eax
.size __unified_syscall,.-__unified_syscall

.global __unified_return
.type	__unified_return,@function
__unified_return:
	push	%edi
	push	%esi
	push	%ebx
	movl	%esp,%edi
	/* we use movl instead of pop because otherwise a signal would
	   destroy the stack frame and crash the program, although it
	   would save a few bytes. */
	movl	0x10(%edi),%ebx
	movl	0x14(%edi),%ecx
	movl	0x18(%edi),%edx
	movl	0x1c(%edi),%esi
	movl	0x20(%edi),%edi
	int	$0x80

	cmp	$-124,%eax
	jb	.Lnoerror
	neg	%eax
	mov	%eax,system__errno
	sbb	%eax,%eax               # eax = eax - eax - CY = -1
.Lnoerror:
	pop	%ebx
	pop	%esi
	pop	%edi
	ret
.size __unified_return,.-__unified_return

/* ------------------------------------------------------- */
#define do_it(name,sym) \
.type sym,@function; \
.global sym; \
sym: \
.ifle __NR_##name-255; \
	movb $__NR_##name,%al; \
	jmp __unified_syscall; \
.else; \
	movw $__NR_##name,%ax; \
	jmp __unified_syscall_256; \
.endif; \
.size sym,.-sym


#define syscall(name,sym) \
.text; \
do_it(name,sym)


#define syscall_weak(name,wsym,sym) \
.text; \
.type wsym,@function; \
.weak wsym; \
wsym:; \
do_it(name,sym)

/* ------------------------------------------------------- */
#include <asm/unistd.h>
	
#define S(x)	syscall(x,x)
#define S__(x)	syscall(x,__##x)

S(nanosleep)
S(fork)
S(dup2)
S(close)
S(execve)
S(chown)
S(chmod)
S(open)
S(kill)
S(waitpid)
S(poll)
S__(rt_sigaction)
		
/* ------------------------------------------------------- */
#if 0
.text
.global __unified_syscall_256
.type __unified_syscall_256,@function
__unified_syscall_256:
	movzwl %ax,%eax
	jmp __unified_return
.size	__unified_syscall_256,.-__unified_syscall_256
#endif
