How to create a socket on Apple Silicon (aarch64 macos) assembly

82 Views Asked by At

I'm trying to create a socket using aarch64 assembly on a Apple Silicon device, here's what I have so far.

.equ SYS_write, 4
.equ SYS_exit, 0x80
.equ SYS_socket, 196

SOCK_ID:  .byte 0

.text
.global _main
.align 8            // Make sure everything is aligned properly

_main:
    // write(1, msg, msg_len);
    MOV x0, #1              // 1 = StdOut
    ADR x1, msg             // string to print
    MOV x2, msg_len         // length of our string
    BL write                // Call the write function

    // socket(int domain, int type, int protocol);
    BL socket               // Call the socket function
    ADR x3, SOCK_ID
    STR x0, [x3]

    BL _exit                // Exit program

socket:
    MOV x0, PF_INET6
    MOV x1, SOCK_STREAM
    MOV x2, protocol
    MOV x16, SYS_socket     // Unix socket system call
    SVC #0                  // Call kernel to create a socket
    RET

write:
    MOV x16, SYS_write      // Unix write system call
    SVC #0                  // Call kernel to output the string
    RET

_exit:
    MOV x0, #0x00           // Use 0 return code
    MOV x16, #0x01          // System call number 1 terminates this program
    SVC SYS_exit            // Call kernel to terminate the program


// Misc Variables
msg:    .asciz "Starting Program!\n"
msg_len = (. - msg)

// Socket Variables
PF_INET6 = 30
SOCK_STREAM = 1
protocol = 1

Essentially, I want to store the value of the socket id saved in x0 after executing the system call into another register or label. In this case SOCK_ID is the label where I want to store the socket id.

However, when I run this I'm getting a Bus error: 10.

I'm using a Makefile to assemble and run the file, here's what my Makefile looks like

.PHONY: all

all: main

run:
    ./file

main: file.o
    ld -o file file.o \
        -lSystem \
        -syslibroot `xcrun -sdk macosx --show-sdk-path` \
        -arch arm64 

file.o: file.s
    as -arch arm64 -o file.o file.s
0

There are 0 best solutions below