allow tcc be build from separate objects
[tinycc.git] / tccrun.c
blobe88f87e4b719b35210d0c9773d16e02eab4a3c85
1 /*
2 * TCC - Tiny C Compiler - Support for -run switch
4 * Copyright (c) 2001-2004 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #include "tcc.h"
23 #ifdef _WIN32
24 #define ucontext_t CONTEXT
25 #endif
27 static void set_pages_executable(void *ptr, unsigned long length);
28 static void set_exception_handler(void);
29 static int rt_get_caller_pc(uplong *paddr, ucontext_t *uc, int level);
30 static void rt_error(ucontext_t *uc, const char *fmt, ...);
31 static int tcc_relocate_ex(TCCState *s1, void *ptr);
33 /* ------------------------------------------------------------- */
34 /* Do all relocations (needed before using tcc_get_symbol())
35 Returns -1 on error. */
37 int tcc_relocate(TCCState *s1)
39 int ret;
41 ret = tcc_relocate_ex(s1, NULL);
42 if (-1 != ret) {
43 s1->runtime_mem = tcc_malloc(ret);
44 ret = tcc_relocate_ex(s1, s1->runtime_mem);
46 return ret;
49 /* launch the compiled program with the given arguments */
50 int tcc_run(TCCState *s1, int argc, char **argv)
52 int (*prog_main)(int, char **);
54 if (tcc_relocate(s1) < 0)
55 return -1;
57 prog_main = tcc_get_symbol_err(s1, "main");
59 #ifdef CONFIG_TCC_BACKTRACE
60 if (s1->do_debug)
61 set_exception_handler();
62 #endif
64 #ifdef CONFIG_TCC_BCHECK
65 if (s1->do_bounds_check) {
66 void (*bound_init)(void);
67 void (*bound_exit)(void);
68 int ret;
69 /* set error function */
70 rt_bound_error_msg = tcc_get_symbol_err(s1, "__bound_error_msg");
71 rt_prog_main = prog_main;
72 /* XXX: use .init section so that it also work in binary ? */
73 bound_init = tcc_get_symbol_err(s1, "__bound_init");
74 bound_exit = tcc_get_symbol_err(s1, "__bound_exit");
75 bound_init();
76 ret = (*prog_main)(argc, argv);
77 bound_exit();
78 return ret;
80 #endif
81 return (*prog_main)(argc, argv);
85 /* relocate code. Return -1 on error, required size if ptr is NULL,
86 otherwise copy code into buffer passed by the caller */
87 static int tcc_relocate_ex(TCCState *s1, void *ptr)
89 Section *s;
90 unsigned long offset, length;
91 uplong mem;
92 int i;
94 if (0 == s1->runtime_added) {
95 s1->runtime_added = 1;
96 s1->nb_errors = 0;
97 #ifdef TCC_TARGET_PE
98 pe_output_file(s1, NULL);
99 #else
100 tcc_add_runtime(s1);
101 relocate_common_syms();
102 tcc_add_linker_symbols(s1);
103 build_got_entries(s1);
104 #endif
105 if (s1->nb_errors)
106 return -1;
109 offset = 0, mem = (uplong)ptr;
110 for(i = 1; i < s1->nb_sections; i++) {
111 s = s1->sections[i];
112 if (0 == (s->sh_flags & SHF_ALLOC))
113 continue;
114 length = s->data_offset;
115 s->sh_addr = mem ? (mem + offset + 15) & ~15 : 0;
116 offset = (offset + length + 15) & ~15;
118 offset += 16;
120 /* relocate symbols */
121 relocate_syms(s1, 1);
122 if (s1->nb_errors)
123 return -1;
125 #if defined TCC_TARGET_X86_64 && !defined TCC_TARGET_PE
126 s1->runtime_plt_and_got_offset = 0;
127 s1->runtime_plt_and_got = (char *)(mem + offset);
128 /* double the size of the buffer for got and plt entries
129 XXX: calculate exact size for them? */
130 offset *= 2;
131 #endif
133 if (0 == mem)
134 return offset;
136 /* relocate each section */
137 for(i = 1; i < s1->nb_sections; i++) {
138 s = s1->sections[i];
139 if (s->reloc)
140 relocate_section(s1, s);
143 for(i = 1; i < s1->nb_sections; i++) {
144 s = s1->sections[i];
145 if (0 == (s->sh_flags & SHF_ALLOC))
146 continue;
147 length = s->data_offset;
148 // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
149 ptr = (void*)(uplong)s->sh_addr;
150 if (NULL == s->data || s->sh_type == SHT_NOBITS)
151 memset(ptr, 0, length);
152 else
153 memcpy(ptr, s->data, length);
154 /* mark executable sections as executable in memory */
155 if (s->sh_flags & SHF_EXECINSTR)
156 set_pages_executable(ptr, length);
159 #if defined TCC_TARGET_X86_64 && !defined TCC_TARGET_PE
160 set_pages_executable(s1->runtime_plt_and_got,
161 s1->runtime_plt_and_got_offset);
162 #endif
163 return 0;
166 /* ------------------------------------------------------------- */
167 /* allow to run code in memory */
169 static void set_pages_executable(void *ptr, unsigned long length)
171 #ifdef _WIN32
172 unsigned long old_protect;
173 VirtualProtect(ptr, length, PAGE_EXECUTE_READWRITE, &old_protect);
174 #else
175 unsigned long start, end;
176 start = (uplong)ptr & ~(PAGESIZE - 1);
177 end = (uplong)ptr + length;
178 end = (end + PAGESIZE - 1) & ~(PAGESIZE - 1);
179 mprotect((void *)start, end - start, PROT_READ | PROT_WRITE | PROT_EXEC);
180 #endif
183 /* ------------------------------------------------------------- */
184 #ifdef CONFIG_TCC_BACKTRACE
186 /* print the position in the source file of PC value 'pc' by reading
187 the stabs debug information */
188 static uplong rt_printline(uplong wanted_pc)
190 Stab_Sym *sym, *sym_end;
191 char func_name[128], last_func_name[128];
192 unsigned long func_addr, last_pc, pc;
193 const char *incl_files[INCLUDE_STACK_SIZE];
194 int incl_index, len, last_line_num, i;
195 const char *str, *p;
197 fprintf(stderr, "0x%08lx:", (unsigned long)wanted_pc);
199 func_name[0] = '\0';
200 func_addr = 0;
201 incl_index = 0;
202 last_func_name[0] = '\0';
203 last_pc = 0xffffffff;
204 last_line_num = 1;
205 sym = (Stab_Sym *)stab_section->data + 1;
206 sym_end = (Stab_Sym *)(stab_section->data + stab_section->data_offset);
207 while (sym < sym_end) {
208 switch(sym->n_type) {
209 /* function start or end */
210 case N_FUN:
211 if (sym->n_strx == 0) {
212 /* we test if between last line and end of function */
213 pc = sym->n_value + func_addr;
214 if (wanted_pc >= last_pc && wanted_pc < pc)
215 goto found;
216 func_name[0] = '\0';
217 func_addr = 0;
218 } else {
219 str = stabstr_section->data + sym->n_strx;
220 p = strchr(str, ':');
221 if (!p) {
222 pstrcpy(func_name, sizeof(func_name), str);
223 } else {
224 len = p - str;
225 if (len > sizeof(func_name) - 1)
226 len = sizeof(func_name) - 1;
227 memcpy(func_name, str, len);
228 func_name[len] = '\0';
230 func_addr = sym->n_value;
232 break;
233 /* line number info */
234 case N_SLINE:
235 pc = sym->n_value + func_addr;
236 if (wanted_pc >= last_pc && wanted_pc < pc)
237 goto found;
238 last_pc = pc;
239 last_line_num = sym->n_desc;
240 /* XXX: slow! */
241 strcpy(last_func_name, func_name);
242 break;
243 /* include files */
244 case N_BINCL:
245 str = stabstr_section->data + sym->n_strx;
246 add_incl:
247 if (incl_index < INCLUDE_STACK_SIZE) {
248 incl_files[incl_index++] = str;
250 break;
251 case N_EINCL:
252 if (incl_index > 1)
253 incl_index--;
254 break;
255 case N_SO:
256 if (sym->n_strx == 0) {
257 incl_index = 0; /* end of translation unit */
258 } else {
259 str = stabstr_section->data + sym->n_strx;
260 /* do not add path */
261 len = strlen(str);
262 if (len > 0 && str[len - 1] != '/')
263 goto add_incl;
265 break;
267 sym++;
270 /* second pass: we try symtab symbols (no line number info) */
271 incl_index = 0;
273 ElfW(Sym) *sym, *sym_end;
274 int type;
276 sym_end = (ElfW(Sym) *)(symtab_section->data + symtab_section->data_offset);
277 for(sym = (ElfW(Sym) *)symtab_section->data + 1;
278 sym < sym_end;
279 sym++) {
280 type = ELFW(ST_TYPE)(sym->st_info);
281 if (type == STT_FUNC) {
282 if (wanted_pc >= sym->st_value &&
283 wanted_pc < sym->st_value + sym->st_size) {
284 pstrcpy(last_func_name, sizeof(last_func_name),
285 strtab_section->data + sym->st_name);
286 func_addr = sym->st_value;
287 goto found;
292 /* did not find any info: */
293 fprintf(stderr, " ???\n");
294 return 0;
295 found:
296 if (last_func_name[0] != '\0') {
297 fprintf(stderr, " %s()", last_func_name);
299 if (incl_index > 0) {
300 fprintf(stderr, " (%s:%d",
301 incl_files[incl_index - 1], last_line_num);
302 for(i = incl_index - 2; i >= 0; i--)
303 fprintf(stderr, ", included from %s", incl_files[i]);
304 fprintf(stderr, ")");
306 fprintf(stderr, "\n");
307 return func_addr;
310 /* emit a run time error at position 'pc' */
311 static void rt_error(ucontext_t *uc, const char *fmt, ...)
313 va_list ap;
314 uplong pc;
315 int i;
317 va_start(ap, fmt);
318 fprintf(stderr, "Runtime error: ");
319 vfprintf(stderr, fmt, ap);
320 fprintf(stderr, "\n");
322 for(i=0;i<num_callers;i++) {
323 if (rt_get_caller_pc(&pc, uc, i) < 0)
324 break;
325 if (i == 0)
326 fprintf(stderr, "at ");
327 else
328 fprintf(stderr, "by ");
329 pc = rt_printline(pc);
330 if (pc == (uplong)rt_prog_main && pc)
331 break;
333 exit(255);
334 va_end(ap);
337 /* ------------------------------------------------------------- */
338 #ifndef _WIN32
340 /* signal handler for fatal errors */
341 static void sig_error(int signum, siginfo_t *siginf, void *puc)
343 ucontext_t *uc = puc;
345 switch(signum) {
346 case SIGFPE:
347 switch(siginf->si_code) {
348 case FPE_INTDIV:
349 case FPE_FLTDIV:
350 rt_error(uc, "division by zero");
351 break;
352 default:
353 rt_error(uc, "floating point exception");
354 break;
356 break;
357 case SIGBUS:
358 case SIGSEGV:
359 if (rt_bound_error_msg && *rt_bound_error_msg)
360 rt_error(uc, *rt_bound_error_msg);
361 else
362 rt_error(uc, "dereferencing invalid pointer");
363 break;
364 case SIGILL:
365 rt_error(uc, "illegal instruction");
366 break;
367 case SIGABRT:
368 rt_error(uc, "abort() called");
369 break;
370 default:
371 rt_error(uc, "caught signal %d", signum);
372 break;
374 exit(255);
377 /* Generate a stack backtrace when a CPU exception occurs. */
378 static void set_exception_handler(void)
380 struct sigaction sigact;
381 /* install TCC signal handlers to print debug info on fatal
382 runtime errors */
383 sigact.sa_flags = SA_SIGINFO | SA_RESETHAND;
384 sigact.sa_sigaction = sig_error;
385 sigemptyset(&sigact.sa_mask);
386 sigaction(SIGFPE, &sigact, NULL);
387 sigaction(SIGILL, &sigact, NULL);
388 sigaction(SIGSEGV, &sigact, NULL);
389 sigaction(SIGBUS, &sigact, NULL);
390 sigaction(SIGABRT, &sigact, NULL);
393 /* ------------------------------------------------------------- */
394 #ifdef __i386__
396 /* fix for glibc 2.1 */
397 #ifndef REG_EIP
398 #define REG_EIP EIP
399 #define REG_EBP EBP
400 #endif
402 /* return the PC at frame level 'level'. Return non zero if not found */
403 static int rt_get_caller_pc(unsigned long *paddr, ucontext_t *uc, int level)
405 unsigned long fp;
406 int i;
408 if (level == 0) {
409 #if defined(__FreeBSD__)
410 *paddr = uc->uc_mcontext.mc_eip;
411 #elif defined(__dietlibc__)
412 *paddr = uc->uc_mcontext.eip;
413 #else
414 *paddr = uc->uc_mcontext.gregs[REG_EIP];
415 #endif
416 return 0;
417 } else {
418 #if defined(__FreeBSD__)
419 fp = uc->uc_mcontext.mc_ebp;
420 #elif defined(__dietlibc__)
421 fp = uc->uc_mcontext.ebp;
422 #else
423 fp = uc->uc_mcontext.gregs[REG_EBP];
424 #endif
425 for(i=1;i<level;i++) {
426 /* XXX: check address validity with program info */
427 if (fp <= 0x1000 || fp >= 0xc0000000)
428 return -1;
429 fp = ((unsigned long *)fp)[0];
431 *paddr = ((unsigned long *)fp)[1];
432 return 0;
436 /* ------------------------------------------------------------- */
437 #elif defined(__x86_64__)
439 /* return the PC at frame level 'level'. Return non zero if not found */
440 static int rt_get_caller_pc(unsigned long *paddr,
441 ucontext_t *uc, int level)
443 unsigned long fp;
444 int i;
446 if (level == 0) {
447 /* XXX: only support linux */
448 #if defined(__FreeBSD__)
449 *paddr = uc->uc_mcontext.mc_rip;
450 #else
451 *paddr = uc->uc_mcontext.gregs[REG_RIP];
452 #endif
453 return 0;
454 } else {
455 #if defined(__FreeBSD__)
456 fp = uc->uc_mcontext.mc_rbp;
457 #else
458 fp = uc->uc_mcontext.gregs[REG_RBP];
459 #endif
460 for(i=1;i<level;i++) {
461 /* XXX: check address validity with program info */
462 if (fp <= 0x1000)
463 return -1;
464 fp = ((unsigned long *)fp)[0];
466 *paddr = ((unsigned long *)fp)[1];
467 return 0;
471 /* ------------------------------------------------------------- */
472 #else
474 #warning add arch specific rt_get_caller_pc()
475 static int rt_get_caller_pc(unsigned long *paddr,
476 ucontext_t *uc, int level)
478 return -1;
481 #endif /* !__i386__ */
483 /* ------------------------------------------------------------- */
484 #else /* WIN32 */
486 static long __stdcall cpu_exception_handler(EXCEPTION_POINTERS *ex_info)
488 CONTEXT *uc = ex_info->ContextRecord;
490 EXCEPTION_RECORD *er = ex_info->ExceptionRecord;
491 printf("CPU exception: code=%08lx addr=%p\n",
492 er->ExceptionCode, er->ExceptionAddress);
494 if (rt_bound_error_msg && *rt_bound_error_msg)
495 rt_error(uc, *rt_bound_error_msg);
496 else
497 rt_error(uc, "dereferencing invalid pointer");
498 exit(255);
499 //return EXCEPTION_CONTINUE_SEARCH;
502 /* Generate a stack backtrace when a CPU exception occurs. */
503 static void set_exception_handler(void)
505 SetUnhandledExceptionFilter(cpu_exception_handler);
508 #ifdef _WIN64
509 #define Eip Rip
510 #define Ebp Rbp
511 #endif
513 /* return the PC at frame level 'level'. Return non zero if not found */
514 static int rt_get_caller_pc(uplong *paddr, CONTEXT *uc, int level)
516 uplong fp;
517 int i;
519 if (level == 0) {
520 *paddr = uc->Eip;
521 return 0;
522 } else {
523 fp = uc->Ebp;
524 for(i=1;i<level;i++) {
525 /* XXX: check address validity with program info */
526 if (fp <= 0x1000 || fp >= 0xc0000000)
527 return -1;
528 fp = ((uplong*)fp)[0];
530 *paddr = ((uplong*)fp)[1];
531 return 0;
535 #undef Eip
536 #undef Ebp
538 #endif /* _WIN32 */
539 #endif /* CONFIG_TCC_BACKTRACE */
540 /* ------------------------------------------------------------- */
542 #ifdef CONFIG_TCC_STATIC
544 #define RTLD_LAZY 0x001
545 #define RTLD_NOW 0x002
546 #define RTLD_GLOBAL 0x100
547 #define RTLD_DEFAULT NULL
549 /* dummy function for profiling */
550 void *dlopen(const char *filename, int flag)
552 return NULL;
555 void dlclose(void *p)
559 const char *dlerror(void)
561 return "error";
564 typedef struct TCCSyms {
565 char *str;
566 void *ptr;
567 } TCCSyms;
569 #define TCCSYM(a) { #a, &a, },
571 /* add the symbol you want here if no dynamic linking is done */
572 static TCCSyms tcc_syms[] = {
573 #if !defined(CONFIG_TCCBOOT)
574 TCCSYM(printf)
575 TCCSYM(fprintf)
576 TCCSYM(fopen)
577 TCCSYM(fclose)
578 #endif
579 { NULL, NULL },
582 void *resolve_sym(TCCState *s1, const char *symbol)
584 TCCSyms *p;
585 p = tcc_syms;
586 while (p->str != NULL) {
587 if (!strcmp(p->str, symbol))
588 return p->ptr;
589 p++;
591 return NULL;
594 #elif !defined(_WIN32)
596 void *resolve_sym(TCCState *s1, const char *sym)
598 return dlsym(RTLD_DEFAULT, sym);
601 #endif /* CONFIG_TCC_STATIC */
603 /* ------------------------------------------------------------- */