summaryrefslogtreecommitdiff
path: root/libtcc-test.c
blob: fddd143cd9c37fbdb1cfb52996efecf839b42729 (plain)
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <libtcc.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

typedef struct tcc_state tcc_state;

struct tcc_state {
	TCCState *s;
	tcc_state *prev;
	tcc_state *next;
};

const char *files[] = {
	"test.c",
	"test2.c",
	NULL
};

tcc_state *states = NULL;
tcc_state *last_state = NULL;

int is_ready = 0;

void print_sym(void *ctx, const char *name, const void *val) {
	printf("symbol: %s, address: %p\n", name, val);
	is_ready = 1;
}

tcc_state *make_state(TCCState *s) {
	tcc_state *new_state = malloc(sizeof(tcc_state));
	memset(new_state, 0, sizeof(tcc_state));
	(last_state) ? (last_state->next = new_state) : (states = new_state);

	new_state->s = s;
	new_state->prev = (last_state) ? last_state : NULL;
	new_state->next = NULL;

	last_state = new_state;

	return new_state;
}

void free_states(tcc_state *st) {
	tcc_state *state;
	TCCState *s;

	if (st != NULL) {
		state = st;
		s = st->s;
		st = st->next;
		memset(state, 0, sizeof(tcc_state));
		tcc_delete(s);
		free(state);
		state = NULL;
		free_states(st);
	}
}

void cleanup() {
	if (states) {
		free_states(states);
	}
}

int main(int argc, char **argv) {
	int (*start)(void);

	tcc_state *st = make_state(tcc_new());
	tcc_set_output_type(st->s, TCC_OUTPUT_MEMORY);

	for (int i = 0; files[i]; i++) {
		/*printf("files[%i]: %s\n", i, files[i]);*/
		if (tcc_add_file(st->s, files[i]) < 0) {
			printf("oof, press f, failed to compile %s.\n", files[i]);
			cleanup();
			return 1;
		}
	}

	tcc_relocate(st->s, TCC_RELOCATE_AUTO);

	/*while (!is_ready) {
		tcc_list_symbols(st->s, NULL, &print_sym);
	}
	is_ready = 0;*/

	start = tcc_get_symbol(st->s, "start");
	/*printf("start: %p\n", start);*/

	int ret = start();

	cleanup();

	return 0;
}