aboutsummaryrefslogtreecommitdiff
path: root/libpsn00b/libc/start.c
blob: c234e0334e706f3bea4615be0f74e1d9b2bc368d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <stdio.h>
#include <malloc.h>

#define load_gp() __asm__ volatile ( \
	"la $gp, _gp;" )

extern int _end;
extern int main(int argc, const char* argv[]);

void _mem_init(void);


static void _call_global_ctors(void)
{
	extern void (*__CTOR_LIST__[])(void);

	// Constructors are called in reverse order of the list
	int i;
	for (i = (int)__CTOR_LIST__[0]; i >= 1; i--) {
		// Each function handles one or more destructor (within
		// file scope)
		__CTOR_LIST__[i]();
	}
}

static void _call_global_dtors(void)
{
	extern void (*__DTOR_LIST__[])(void);

	/* Destructors in forward order */
	int i;
	for (i = 0; i < (int)__DTOR_LIST__[0]; i++) {
			/* Each function handles one or more destructor (within
			 * file scope) */
			__DTOR_LIST__[i + 1]();
	}
}

void _start(void) {
	
	// Load GP address
	load_gp();
	
	// Mem init assembly function (clears BSS and InitHeap to _end which is
	// not possible to do purely in C because the linker complains about
	// relocation truncated to fit: R_MIPS_GPREL16 against `_end'
	// Workaround is to do it in assembly because la pseudo-op doesn't use
	// stupid gp relative addressing
	_mem_init();
	
	_call_global_ctors();
	
	main(0, NULL);
	
	_call_global_dtors();
	
}