0

Here's the code:

.text       # Section declaration
    .global _start

_start:
    # Write our string to stdout
    movl $len, %edx
    movl $msg, %ecx
    movl $1, %ebx
    movl $4, %eax
    syscall

    # Exit
    movl $0, %ebx
    movl $1, %eax
    syscall

.data
msg:
    .ascii "Hello, world!\n"        # Our string
    len = . - msg       # Length of the string

I use these shell commands to compile and build it:

as -o hello.o hello.S

ld -s -o hello hello.o

./hello

But when I run it, I get this error message:

Illegal instruction

I have tried to replace "syscall" with "int $0x80", but then I get this error:

Segmentation fault

I use Windows 10 64 bit, so, does anyone have any idea of how I can fix this?

ndim
  • 35,870
  • 12
  • 47
  • 57
  • "Windows 10" + "Segmentation fault" = that's not a valid combination. Are you using a VM? Or WSL? –  Jan 14 '22 at 13:23
  • ebx, eax... I assume you're aiming at 32-bit(?) Linux(??). So `int 80` is probably the better choice, now to figure out what the crash is. gdb will tell you which instruction crashed. Give it a try. –  Jan 14 '22 at 13:28
  • You may need to force 32-bit compilation with some extra options: https://stackoverflow.com/questions/18429901/compiling-32-bit-assembly-on-64bit-system-ubuntu –  Jan 14 '22 at 13:37
  • If you wanted 64-bit code, then you would use `syscall` but the arguments are in different registers from what you have. –  Jan 14 '22 at 13:39

1 Answers1

0

Assuming that you are running this on x86 Linux e.g. by using WSL (so int 0x80 is correct), there are two issues:

  1. movl $msg, %ecx just moves the value of msg into ecx (i.e. the first 4 Bytes of msg), but you want the adress pointing to the string => use lea
  2. as already pointed out in the comments, you will neeed to compile it with the -m32-flag to compile an x86-executable

So here's a working version of your code:

.text       # Section declaration
    .global main

main:
    # Write our string to stdout
    movl $len, %edx
    lea msg, %ecx # load the effective address (=lea) of msg into ecx
    movl $1, %ebx
    movl $4, %eax
    int $0x80 # call the Kernel

    # Exit
    movl $0, %ebx
    movl $1, %eax
    int $0x80

.data
msg:
    .ascii "Hello, world!\n"        # Our string
    len = . - msg       # Length of the string

Compile it with

gcc -o <outputFile> <inputFile> -m32 -no-pie (replace <inputFile> and <outputFile>) And you get your output

Hello, world!

If you actually want to write this for x86 Windows, check https://stackoverflow.com/a/1029093/5821910 for an example

Tobias
  • 168
  • 7