Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiling C++ under Linux without the runtime library

I have recently started to explore the way that the C++ runtime library is used by the generated code.

Mostly I am very curious, but I also want to evaluate the amount of work needed to develop the minimum required stuff to start a kernel in C++.

So I started to implement my own runtime library, but I have a small issue.

int main(int argc, char **argv)
{
  return 0;
}

Compiling this with the following command:

$ g++ -ffreestanding -nostdlib -fno-builtin -fno-rtti -fno-exceptions -c main.cpp

I get this warning:

/usr/bin/ld: warning: cannot find entry symbol _start; defaulting to 00000000080480b8

Then when I try to execute the binary produced I get a "Segmentation fault". I have tried to compile "main.cpp" and an ASM file.

[global _start]
[extern main]

_start:
  call main

Linking the object files manually with "ld", I don't have the warning but the binary is still raising a "Segmentation fault".

I suppose I am missing something. Probably something that has to be done before and after the call to "main" as the system C library does in "__libc_start_main" for instance.

Also, if someone has any recommendation of websites, documentation or books about this topic that I should read, I would really appreciate it.

Thanks,

Patrick

like image 658
Patrick Samy Avatar asked Apr 21 '11 00:04

Patrick Samy


People also ask

Can G ++ compile C code?

gcc is used to compile C program. g++ can compile any . c or . cpp files but they will be treated as C++ files only.

What does GCC compile to?

GCC stands for GNU Compiler Collections which is used to compile mainly C and C++ language. It can also be used to compile Objective C and Objective C++.


1 Answers

Okay so thanks to QuantumMechanic's link I managed to find the problem: http://www.muppetlabs.com/~breadbox/software/tiny/teensy.html

I just forgot my basics in linux programming, more importantly how program end is handled.

Basically, I needed to generate the syscall interrupt "exit" to handle the end of the program.

[BITS 32]

[global _start]
[extern main]

_start:
  call main
  mov ebx, eax  ; Move the returned value in the register used as argument of exit()
  mov eax, 1    ; Indicates the id of the syscall to execute
  int 0x80      ; Triggers the syscall interrupt

So now I can compile any C++ program on linux using my own RTL to make some tests.

Note that it won't be needed in the kernel should the end of the "main" function never be reached.

Thanks !

like image 194
Patrick Samy Avatar answered Oct 08 '22 15:10

Patrick Samy