Hello World x86_64. Is this 100% correct?

98 views Asked by At

I'm on an Ubuntu 22.04 x86_64 system, kernel 6.5.0-15-generic. I'm learning how to make simple programs that make system calls by using GAS AT&T assembly format. This assembly program is in the file hello.s:

.section .rodata
msg: .ascii "Hello, World!\n"
.set msglen, (. - msg)

.section .text 
.global main
main:
  mov $1, %rax
  mov $1, %rdi 
  lea msg(%rip), %rsi 
  mov $msglen, %rdx
  syscall

  mov $60, %rax
  mov $0, %rdi 
  syscall

The way I obtain the executable is this:

  • I assemble to get the object file with as hello.s -o hello.o

  • I link to get the executable with gcc hello.o -o hello

The program works fine. I just have some doubts about the following:

  1. What if I had used a file named hello.S instead of hello.s? Would it have been different doing something like:

    as hello.S -o hello.o
    gcc hello.o -o hello
    

    Are both forms correct?

  2. Why is it that when I do something like gcc -S demo.i I get demo.s and not demo.S?

  3. My goal was to create a simple classic main program in assembly that makes the write system call to write "Hello World". Is my code 100% correct?

1

There are 1 answers

0
Nate Eldredge On

You can also assemble and link your file in one shot by just doing gcc -o hello hello.s.

And this is related to your question. gcc looks at input file suffixes to decide how to handle them. A .s file gets fed directly to the assembler. If it is named .S instead, then it gets filtered through the C preprocessor and then fed to the assembler.

So, if you would like to use C preprocessor features in your assembly source code (e.g. #define), then name your file with .S and use gcc (or clang) to build it. If you don't want that feature, then keep using .s.

The compiler generates assembly that can go straight to the assembler without needing further preprocessing, so its assembly output files are named .s rather than .S.

Your code itself looks fine as far as correct operation. There are some things you could improve related to efficiency.