简体   繁体   中英

How to correctly use the "write" syscall on MacOS to print to stdout?

I have looked at similar questions, but cannot seem to find what is wrong with my code.

I am attempting to make the "write" syscall on MacOS to print a string to standard output.

I am able to do it with printf perfectly, and am familiar with calling other functions in x64 assembly.

This is, however, my first attempt at a syscall .

I am using GCC's GAS assembler.

This is my code:

.section __TEXT,__text

.globl _main

_main:
    pushq %rbp
    movq %rsp, %rbp

    subq $32, %rsp

    movq $0x20000004, %rax
    movq $1, %rdi
    leaq syscall_str(%rip), %rsi
    movq $25, %rdx
    syscall

    jc error

    xorq %rax, %rax

    leave
    ret

error:
    movq $1, %rax
    leave
    ret

.section __DATA,__data
syscall_str:
    .asciz "Printed with a syscall.\n"

There does not seem to be any error; there is simply nothing written to stdout .

I know that start is usually used as the starting point for an executable on MacOS, but it does not compile with GCC.

There are a couple of things you can try to fix this issue.

Make sure that you are using the correct value for the %rax register. The write syscall has a different number on different systems. On macOS, the write syscall has a number of 0x2000004.

Make sure that you are using the correct arguments for the write syscall. The write syscall expects the following arguments:

%rdi: file descriptor to write to (eg 1 for standard output) %rsi: pointer to the buffer containing the data to be written %rdx: number of bytes to be written Make sure that you are using the correct instruction to invoke the syscall. On macOS, you should use the syscall instruction to invoke a syscall.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM