I have a simple dprintf program written in NASM which prints a long format with more than 6 arguments. I am passing the arguments as the calling convention requires (RDI, RSI, RDX, RCX, R8, R9). As long as I use only those my program works fine.
I can't figure out why I get a segfault each time I try to push something to the stack as additional arguments. Here is the source:
;a comment
%macro DATA 0
section .data
string: db "%6$ca comment%1$c%4$cmacro DATA 0%1$csection .data%1$c%2$cstring: db %3$c%5$s%3$c, 0%1$c%2$cpath: db %3$cGrace_kid.s%3$c, 0%1$c%4$cendmacro%1$c%4$cdefine SC_OPEN 0x2000005%1$c%4$cmacro MAIN 0%1$c%1$cDATA%1$c%1$csection .text%1$c%2$cglobal start%1$c%2$cglobal _main%1$c%2$cextern _dprintf%1$c%1$cstart:%1$c%2$ccall _main%1$c%2$cret%1$c%1$c_main:%1$c%2$cpush rbp%1$c%2$cmov rbp, rsp%1$c%2$cmov rax, SC_OPEN%1$c%2$clea rdi, [rel path]%1$c%2$cmov rsi, 0x0200%1$c%2$cxor rsi, 0x0002%1$c%2$cmov rdx, 0640o%1$c%2$cclc%1$c%2$csyscall%1$c%2$cjc ret%1$c%2$ccmp rax, 0%1$c%2$cjle ret%1$c%2$cmov rdi,rax%1$c%2$clea rsi, [rel string]%1$c%2$cmov rdx, 10%1$c%2$cmov rcx, 9%1$c%2$ccall _dprintf%1$c%2$cxor rax, rax%1$cret:%1$c%2$cleave%1$c%2$cret%1$c%4$cendmacro%1$c%1$cMAIN%1$c", 0
path: db "Grace_kid.s", 0
%endmacro
%define SC_OPEN 0x2000005
%macro MAIN 0
DATA
section .text
global start
global _main
extern _dprintf
start:
call _main
ret
_main:
push rbp
mov rbp, rsp
;sub rsp, 16
mov rax, SC_OPEN
lea rdi, [rel path]
mov rsi, 0x0200
xor rsi, 0x0002
mov rdx, 0640o
clc
syscall
jc ret
cmp rax, 0
jle ret
mov rdi, rax
lea rsi, [rel string]
mov rdx, 10
mov rcx, 9
mov r8, 34
mov r9, 37
mov rbx, 59
push rbx
xor rax, rax
call _dprintf
xor rax, rax
ret:
leave
ret
%endmacro
MAIN
I assemble and link with these commands:
nasm -fmacho64 file.s
ld file.o -macosx_version_min 10.14 -lSystem
This works just fine but I would like to add extra parameters. I tried to push it on the stack using:
mov rbx, 59
push rbx
It segfaults whether I sub some bytes to RSP or not.
I am under MacOS Mojave and I'm using the latest version of NASM.
call _dprintf.By pushing an 8 byte value on the stack you have misaligned the stack.You may have to adjust RSP by subtracting 8 from RSP beforepush 59(and then add 16 to RSP after thecall) - Michael Petch_dprintf, I assume you are calling the system one. - Michael Petch