Home > Back-end >  How can I compile x86_64 asm code on M1 Mac (ARM)
How can I compile x86_64 asm code on M1 Mac (ARM)

Time:03-12

I have a compilers course in college, as part of which we work on a nano pass compiler and create passes. So in the process there is a step

gcc -g -std=c99 runtime.o tests/var_test_1.s

runtime.o is a compilation of runtime.c file.

and I get an error:

tests/var_test_1.s:3:12: error: unknown token in expression
 movq $42, %rax
           ^
tests/var_test_1.s:3:12: error: invalid operand
 movq $42, %rax
           ^
tests/var_test_1.s:4:2: error: unrecognized instruction mnemonic, did you mean: cmp?
 jmp _conclusion
 ^
tests/var_test_1.s:9:8: error: unknown token in expression
 pushq %rbp
       ^
tests/var_test_1.s:9:8: error: invalid operand
 pushq %rbp
       ^
tests/var_test_1.s:10:7: error: unknown token in expression
 movq %rsp, %rbp
      ^
tests/var_test_1.s:10:7: error: invalid operand
 movq %rsp, %rbp
      ^
tests/var_test_1.s:11:11: error: unknown token in expression
 subq $0, %rsp
          ^
tests/var_test_1.s:11:11: error: invalid operand
 subq $0, %rsp
          ^
tests/var_test_1.s:12:2: error: unrecognized instruction mnemonic, did you mean: cmp?
 jmp _start
 ^
tests/var_test_1.s:16:11: error: unknown token in expression
 addq $0, %rsp
          ^
tests/var_test_1.s:16:11: error: invalid operand
 addq $0, %rsp
          ^
tests/var_test_1.s:17:7: error: unknown token in expression
 popq %rbp
      ^
tests/var_test_1.s:17:7: error: invalid operand
 popq %rbp
      ^
tests/var_test_1.s:18:2: error: unrecognized instruction mnemonic, did you mean: eret, ret?
 retq
 ^

On further reading I found out it was because M1 Mac due to being ARM architecture does not directly compile x86_64 asm code. Is there any flag or any version of gcc that I can use to compile the x86 code on arm architecture?
I have seen rosetta and qemu, but I do not want to running a vm for such a task. qemu-static doesn't seem to work on M1 that straightforward.

The following are the contents of var_1_test.s (this file is generated by the compiler which only supports x86 [as per nature of course])

    .align 16
_start:
    movq    $42, %rax
    jmp _conclusion

    .globl _main
    .align 16
_main:
    pushq   %rbp
    movq    %rsp, %rbp
    subq    $0, %rsp
    jmp _start

    .align 16
_conclusion:
    addq    $0, %rsp
    popq    %rbp
    ret

If any further details are needed I would be more than happy to provide. Thanks!

CodePudding user response:

So after digging through a bunch more of stack overflow answer, and thanks to @paweł-Łukasik, through the term cross-compiler, I got an answer on how to run x86 code, or as a matter of fact any command in x86 architecture on cli using Rosetta 2.

How to run the Homebrew installer under Rosetta 2 on M1 Macbook

I made changes to makefile to add arch -x86_64 ...
and everything else ran perfectly.

  • Related