blob: 50bbdb708141c913e2eabafed844582afe43ce15 [file] [log] [blame]
Chris Lattnerfdab7282003-05-14 13:09:41 +00001/*===- crtend.c - Initialization code for programs ------------------------===*\
2 *
3 * This file defines the __main function, which is used to run static
4 * constructors and destructors in C++ programs, or with C programs that use GCC
5 * extensions to accomplish the same effect.
6 *
7 * The main data structures used to implement this functionality is the
8 * llvm.global_ctors and llvm.global_dtors lists, which are null terminated
9 * lists of TorRec (defined below) structures.
10 *
11\*===----------------------------------------------------------------------===*/
12
13#include <stdlib.h>
14
15/* TorRec - The record type for each element of the ctor/dtor list */
16typedef struct TorRec {
17 int Priority;
18 void (*FP)(void);
19} TorRec;
20
21/* __llvm_getGlobalCtors, __llvm_getGlobalDtors - Interface to the LLVM
22 * listend.ll file to get access to the start of the ctor and dtor lists...
23 */
24TorRec *__llvm_getGlobalCtors(void);
25TorRec *__llvm_getGlobalDtors(void);
26
27static void run_destructors(void);
28
29/* __main - A call to this function is automatically inserted into the top of
30 * the "main" function in the program compiled. This function is responsible
31 * for calling static constructors before the program starts executing.
32 */
33void __main(void) {
34 /* Loop over all of the constructor records, calling each function pointer. */
35 TorRec *R = __llvm_getGlobalCtors();
36
Chris Lattner5d243c22003-06-26 04:20:38 +000037 /* Only register the global dtor handler if there is at least one global
38 * dtor!
39 */
40 if (__llvm_getGlobalDtors()[0].FP)
41 if (atexit(run_destructors))
42 abort(); /* Should be able to install ONE atexit handler! */
Chris Lattnerfdab7282003-05-14 13:09:41 +000043
44 /* FIXME: This should sort the list by priority! */
45 for (; R->FP; ++R)
46 R->FP();
47}
48
49static void run_destructors(void) {
50 /* Loop over all of the destructor records, calling each function pointer. */
51 TorRec *R = __llvm_getGlobalDtors();
52
53 /* FIXME: This should sort the list by priority! */
54 for (; R->FP; ++R)
55 R->FP();
56}