## Copyright (C) 2016 Jeremiah Orians
## This file is part of M2-Planet.
##
## M2-Planet is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## M2-Planet is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with M2-Planet.  If not, see <http://www.gnu.org/licenses/>.

:_start

	COPY_rsp_to_rbp             ; Protect rsp

	;; Prepare argv
	LOAD_BASE_ADDRESS_rax %8    ; ARGV_address = RBP + 8
	PUSH_RAX                    ; Put argv on the stack

	;; Prepare envp
	COPY_rbp_to_rax             ; Address we need to load from
	LOAD_INTEGER                ; Get ARGC
	ADD_IMMEDIATE_to_rax %2     ; OFFSET = ARGC + 2
	SAL_rax_Immediate8 !3       ; OFFSET = OFFSET * WORDSIZE
	ADD_rbp_to_rax              ; ENVP_address = RSP + OFFSET
	PUSH_RAX                    ; Put envp on the stack

	;; Stack offset
	ADD_IMMEDIATE_to_rbp %8     ; Fix rbp

	;; Perform the main loop
	CALL_IMMEDIATE %FUNCTION_main

	;; Exit to kernel
	COPY_rax_to_rdi             ; Using the return code given by main
	LOAD_IMMEDIATE_rax %0x3C    ; Syscall exit
	SYSCALL                     ; Exit with that code
