0

I had the following C code:

void test_func()
{
    __asm__ ("mov    $0x2,%rax");
    __asm__ ("mov    $0x6000dd,%rdi");
    __asm__ ("mov    $0x0,%rsi");
    __asm__ ("syscall");
}
int main(int argc, char *argv[]) {
    test_func();
    return 0;
}

when I compile it like this gcc mine.cxx -S -no-pie I get in assembly file the following:

.globl _Z9test_funcv

Why does the name of my function change and how to prevent this / predict its new name?

phuclv
  • 37,963
  • 15
  • 156
  • 475
  • 1
    How do you compile it? – bereal Jun 21 '21 at 10:05
  • [Don't split up instructions into splitting separate `__asm__` statements like that](https://stackoverflow.com/a/43054507/995714). The compiler may insert instructions between them or even *"reorder these relative to one another since they are basic assembler with no dependencies"* – phuclv Jun 21 '21 at 10:27
  • @phuclv like how? –  Jun 21 '21 at 12:22
  • @ariel did you read the link above? Also [this](https://stackoverflow.com/q/27685548/995714#comment85353418_27687809). Just separate the instructions with `\n` or `;` – phuclv Jun 21 '21 at 13:22

1 Answers1

4

You're compiling it as C++ code, not C. In C++ names are mangled to support things like function overloading and templates. Mangling rules depend on compiler but it usually begins with _Z, especially in compilers following Itanium C++ ABI

See What is name mangling, and how does it work?

You need to compile the code as C. The compiler usually determines the language based on the extension, and in GCC cxx is one of the C++ extensions so just rename the file to *.c. You can also force the compiler to compile code as C regardless of the extension. The option to do that depends on compiler, for example in MSVC use /TC and in GCC use -x c

Note that you should never put instructions in separate __asm__ statements like that because the compiler is allowed to put arbitrary instructions between them

phuclv
  • 37,963
  • 15
  • 156
  • 475
  • Sorry you are wrong here is how I did it: gcc mine.cxx -S -no-pie –  Jun 21 '21 at 12:22
  • 1
    @ariel: Why did you give your file a C++ file extension if you wanted to write C? – user2357112 Jun 21 '21 at 12:30
  • cxx isn't C++ extension –  Jun 21 '21 at 12:36
  • 3
    @ariel Reading the manual https://gcc.gnu.org/onlinedocs/gcc/Invoking-G_002b_002b.html#Invoking-G_002b_002b shows you that the extension `cxx` **is** causing GCC to compiie as C++. – harper Jun 21 '21 at 12:40
  • 1
    @ariel if you rotate `xx` 45° then it'll (roughly) become `++`. That's why `CXX` is often used in macros denoting C++ code. Same to the cxx extension – phuclv Jun 21 '21 at 13:20