Search code examples
cassemblyinline-assemblynoreturn

How to tell compiler to not generate "retq" after inline asm in a _Noreturn function?


I wrote the following code to call syscall exit without linking with glibc:

// a.c
#include <stdlib.h>
#include <sys/syscall.h>
#include <unistd.h>

_Noreturn void _start()
{
    register int syscall_num asm ("rax") = __NR_exit;
    register int exit_code   asm ("rdi") = 0;

    // The actual syscall to exit
    asm volatile ("syscall"
        : /* no output Operands */
        : "r" (syscall_num), "r" (exit_code));
}

The Makefile:

.PHONY: clean

a.out: a.o
    $(CC) -nostartfiles -nostdlib -Wl,--strip-all a.o

a.o: a.c
    $(CC) -Oz -c a.c

clean:
    rm a.o a.out

I make it with CC=clang-7 and it works perfectly well except that when I inspect the assembly generated by objdump -d a.out:

a.out:     file format elf64-x86-64


Disassembly of section .text:

0000000000201000 <.text>:
  201000:   6a 3c                   pushq  $0x3c
  201002:   58                      pop    %rax
  201003:   31 ff                   xor    %edi,%edi
  201005:   0f 05                   syscall 
  201007:   c3                      retq   

there is a useless retq following the syscall. I wonder, is there any way to remove that without resorting to writing the whole function in assembly?


Solution

  • Add this after the system call that doesn't return:

        __builtin_unreachable();