Search code examples
cmacosassemblyterminalnasm

Socket opening macOS assembly


I'm trying to create a socket in NASM but nothing happens, while in C everything is OK.

My C code:

#include <sys/socket.h>
#include "personalUtils.h"

int main() {
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    tryElse(fd, "Error creating a socket"); //macro

    pauseHere() //macro
}

After running this, I open the terminal and run, lsof -i -a -p <PID> and the socket is there, but trying to run the below NASM code and calling lsof again nothing is being listed. What am I doing wrong?

%include "utils.asm"

;#################################
;       Usefull constants
;#################################
AF_INET      equ 2   ; family internetwork to UDP, TCP, etc
SOCK_STREAM  equ 1   ; stream socket
NO_FLAGS     equ 0

;#################################
;       Main function call
;#################################
        global      _main
        SECTION     .text

_main:  mov rax, 0x2000097
        mov rdi, AF_INET
        mov rsi, SOCK_STREAM
        mov rdx, NO_FLAGS
        syscall

        pauseHere ; NASM macro

Solution

  • The correct socket(2) value to load to rax is 0x2000061, which is the same as 0x2000000 + 97, which is the same as 0x2000000 + SYS_socket. It's documented in https://github.com/radareorg/radare2/blob/master/libr/syscall/d/darwin-x86-64.sdb.txt

    See 64-bit syscall documentation for MacOS assembly for write(2) that works.