Search code examples
macosassemblyarmapple-m1arm64

Why is hello world in assembly for ARM mac 'invalid'?


The other answers don't tell me how to compile, I'm stuck

I have a simple hello world in assembly

    .global start
    .align 2

    start: mov X0, #1
        adr     X1, hello
        mov     X2, #13
        mov     X16, #4
        svc     0

        mov     X0, #0
        mov     X16, #1
        svc     0

    hello: .ascii  "Hello\n"

I compiled it using clang hello.s -nostdlib -static
File says

% file ./a.out 
./a.out: Mach-O 64-bit executable arm64

obj dump shows this and perhaps UNKNOWN_ARCHITECTURE is the problem?

    ./a.out:     file format mach-o-arm64


    Disassembly of section .text:

    0000000100003fd8 <start>:
        100003fd8:  d2800020    mov x0, #0x1                    // #1
        100003fdc:  100000e1    adr x1, 100003ff8 <hello>
        100003fe0:  d28001a2    mov x2, #0xd                    // #13
        100003fe4:  d2800090    mov x16, #0x4                       // #4
        100003fe8:  d4000001    svc #0x0
        100003fec:  d2800000    mov x0, #0x0                    // #0
        100003ff0:  d2800030    mov x16, #0x1                       // #1
        100003ff4:  d4000001    svc #0x0

    0000000100003ff8 <hello>:
        100003ff8:  6c6c6548    ldnp    d8, d25, [x10, #-320]
        100003ffc:  Address 0x0000000100003ffc is out of bounds.


    Disassembly of section LC_THREAD.UNKNOWN_ARCHITECTURE.0:

    0000000000000000 <LC_THREAD.UNKNOWN_ARCHITECTURE.0>:
        ...
    100:    00003fd8    udf #16344
    104:    00000001    udf #1
        ...

Running in zsh says "killed" with error code 137.

This is what dtruss says

    % sudo dtruss ./a.out                                     
    dtrace: system integrity protection is on, some features will not be available

    dtrace: failed to execute ./a.out: Bad executable (or shared library)

Where did I go wrong? I'm on a M2


Solution

  • The kernel on arm64 macOS does not allow static binaries. It's as simple as that, see Why does macOS kill static executables created by clang?

    But you don't need your binary to be static. Just rename start to _main and compile with clang hello.s and it will work.