tccrun.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  1. /*
  2. * TCC - Tiny C Compiler - Support for -run switch
  3. *
  4. * Copyright (c) 2001-2004 Fabrice Bellard
  5. *
  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.
  10. *
  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.
  15. *
  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
  19. */
  20. #include "tcc.h"
  21. /* only native compiler supports -run */
  22. #ifdef TCC_IS_NATIVE
  23. #ifndef _WIN32
  24. # include <sys/mman.h>
  25. #endif
  26. #ifdef CONFIG_TCC_BACKTRACE
  27. # ifndef _WIN32
  28. # include <signal.h>
  29. # ifndef __OpenBSD__
  30. # include <sys/ucontext.h>
  31. # endif
  32. # else
  33. # define ucontext_t CONTEXT
  34. # endif
  35. ST_DATA int rt_num_callers = 6;
  36. ST_DATA const char **rt_bound_error_msg;
  37. ST_DATA void *rt_prog_main;
  38. static int rt_get_caller_pc(addr_t *paddr, ucontext_t *uc, int level);
  39. static void rt_error(ucontext_t *uc, const char *fmt, ...);
  40. static void set_exception_handler(void);
  41. #endif
  42. static void set_pages_executable(void *ptr, unsigned long length);
  43. static int tcc_relocate_ex(TCCState *s1, void *ptr, addr_t ptr_diff);
  44. #ifdef _WIN64
  45. static void *win64_add_function_table(TCCState *s1);
  46. static void win64_del_function_table(void *);
  47. #endif
  48. /* ------------------------------------------------------------- */
  49. /* Do all relocations (needed before using tcc_get_symbol())
  50. Returns -1 on error. */
  51. LIBTCCAPI int tcc_relocate(TCCState *s1, void *ptr)
  52. {
  53. int size;
  54. addr_t ptr_diff = 0;
  55. if (TCC_RELOCATE_AUTO != ptr)
  56. return tcc_relocate_ex(s1, ptr, 0);
  57. size = tcc_relocate_ex(s1, NULL, 0);
  58. if (size < 0)
  59. return -1;
  60. #ifdef HAVE_SELINUX
  61. {
  62. /* Using mmap instead of malloc */
  63. void *prx;
  64. char tmpfname[] = "/tmp/.tccrunXXXXXX";
  65. int fd = mkstemp(tmpfname);
  66. unlink(tmpfname);
  67. ftruncate(fd, size);
  68. ptr = mmap (NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
  69. prx = mmap (NULL, size, PROT_READ|PROT_EXEC, MAP_SHARED, fd, 0);
  70. if (ptr == MAP_FAILED || prx == MAP_FAILED)
  71. tcc_error("tccrun: could not map memory");
  72. dynarray_add(&s1->runtime_mem, &s1->nb_runtime_mem, (void*)(addr_t)size);
  73. dynarray_add(&s1->runtime_mem, &s1->nb_runtime_mem, prx);
  74. ptr_diff = (char*)prx - (char*)ptr;
  75. }
  76. #else
  77. ptr = tcc_malloc(size);
  78. #endif
  79. tcc_relocate_ex(s1, ptr, ptr_diff); /* no more errors expected */
  80. dynarray_add(&s1->runtime_mem, &s1->nb_runtime_mem, ptr);
  81. return 0;
  82. }
  83. ST_FUNC void tcc_run_free(TCCState *s1)
  84. {
  85. int i;
  86. for (i = 0; i < s1->nb_runtime_mem; ++i) {
  87. #ifdef HAVE_SELINUX
  88. unsigned size = (unsigned)(addr_t)s1->runtime_mem[i++];
  89. munmap(s1->runtime_mem[i++], size);
  90. munmap(s1->runtime_mem[i], size);
  91. #else
  92. #ifdef _WIN64
  93. win64_del_function_table(*(void**)s1->runtime_mem[i]);
  94. #endif
  95. tcc_free(s1->runtime_mem[i]);
  96. #endif
  97. }
  98. tcc_free(s1->runtime_mem);
  99. }
  100. /* launch the compiled program with the given arguments */
  101. LIBTCCAPI int tcc_run(TCCState *s1, int argc, char **argv)
  102. {
  103. int (*prog_main)(int, char **);
  104. s1->runtime_main = "main";
  105. if ((s1->dflag & 16) && !find_elf_sym(s1->symtab, s1->runtime_main))
  106. return 0;
  107. if (tcc_relocate(s1, TCC_RELOCATE_AUTO) < 0)
  108. return -1;
  109. prog_main = tcc_get_symbol_err(s1, s1->runtime_main);
  110. #ifdef CONFIG_TCC_BACKTRACE
  111. if (s1->do_debug) {
  112. set_exception_handler();
  113. rt_prog_main = prog_main;
  114. }
  115. #endif
  116. errno = 0; /* clean errno value */
  117. #ifdef CONFIG_TCC_BCHECK
  118. if (s1->do_bounds_check) {
  119. void (*bound_init)(void);
  120. void (*bound_exit)(void);
  121. void (*bound_new_region)(void *p, addr_t size);
  122. int (*bound_delete_region)(void *p);
  123. int i, ret;
  124. /* set error function */
  125. rt_bound_error_msg = tcc_get_symbol_err(s1, "__bound_error_msg");
  126. /* XXX: use .init section so that it also work in binary ? */
  127. bound_init = tcc_get_symbol_err(s1, "__bound_init");
  128. bound_exit = tcc_get_symbol_err(s1, "__bound_exit");
  129. bound_new_region = tcc_get_symbol_err(s1, "__bound_new_region");
  130. bound_delete_region = tcc_get_symbol_err(s1, "__bound_delete_region");
  131. bound_init();
  132. /* mark argv area as valid */
  133. bound_new_region(argv, argc*sizeof(argv[0]));
  134. for (i=0; i<argc; ++i)
  135. bound_new_region(argv[i], strlen(argv[i]) + 1);
  136. ret = (*prog_main)(argc, argv);
  137. /* unmark argv area */
  138. for (i=0; i<argc; ++i)
  139. bound_delete_region(argv[i]);
  140. bound_delete_region(argv);
  141. bound_exit();
  142. return ret;
  143. }
  144. #endif
  145. return (*prog_main)(argc, argv);
  146. }
  147. #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
  148. /* To avoid that x86 processors would reload cached instructions
  149. each time when data is written in the near, we need to make
  150. sure that code and data do not share the same 64 byte unit */
  151. #define RUN_SECTION_ALIGNMENT 63
  152. #else
  153. #define RUN_SECTION_ALIGNMENT 0
  154. #endif
  155. /* relocate code. Return -1 on error, required size if ptr is NULL,
  156. otherwise copy code into buffer passed by the caller */
  157. static int tcc_relocate_ex(TCCState *s1, void *ptr, addr_t ptr_diff)
  158. {
  159. Section *s;
  160. unsigned offset, length, align, max_align, i, k, f;
  161. addr_t mem, addr;
  162. if (NULL == ptr) {
  163. s1->nb_errors = 0;
  164. #ifdef TCC_TARGET_PE
  165. pe_output_file(s1, NULL);
  166. #else
  167. tcc_add_runtime(s1);
  168. resolve_common_syms(s1);
  169. build_got_entries(s1);
  170. #endif
  171. if (s1->nb_errors)
  172. return -1;
  173. }
  174. offset = max_align = 0, mem = (addr_t)ptr;
  175. #ifdef _WIN64
  176. offset += sizeof (void*); /* space for function_table pointer */
  177. #endif
  178. for (k = 0; k < 2; ++k) {
  179. f = 0, addr = k ? mem : mem + ptr_diff;
  180. for(i = 1; i < s1->nb_sections; i++) {
  181. s = s1->sections[i];
  182. if (0 == (s->sh_flags & SHF_ALLOC))
  183. continue;
  184. if (k != !(s->sh_flags & SHF_EXECINSTR))
  185. continue;
  186. align = s->sh_addralign - 1;
  187. if (++f == 1 && align < RUN_SECTION_ALIGNMENT)
  188. align = RUN_SECTION_ALIGNMENT;
  189. if (max_align < align)
  190. max_align = align;
  191. offset += -(addr + offset) & align;
  192. s->sh_addr = mem ? addr + offset : 0;
  193. offset += s->data_offset;
  194. #if 0
  195. if (mem)
  196. printf("%-16s %p len %04x align %2d\n",
  197. s->name, (void*)s->sh_addr, (unsigned)s->data_offset, align + 1);
  198. #endif
  199. }
  200. }
  201. /* relocate symbols */
  202. relocate_syms(s1, s1->symtab, 1);
  203. if (s1->nb_errors)
  204. return -1;
  205. if (0 == mem)
  206. return offset + max_align;
  207. #ifdef TCC_TARGET_PE
  208. s1->pe_imagebase = mem;
  209. #endif
  210. /* relocate each section */
  211. for(i = 1; i < s1->nb_sections; i++) {
  212. s = s1->sections[i];
  213. if (s->reloc)
  214. relocate_section(s1, s);
  215. }
  216. relocate_plt(s1);
  217. for(i = 1; i < s1->nb_sections; i++) {
  218. s = s1->sections[i];
  219. if (0 == (s->sh_flags & SHF_ALLOC))
  220. continue;
  221. length = s->data_offset;
  222. ptr = (void*)s->sh_addr;
  223. if (s->sh_flags & SHF_EXECINSTR)
  224. ptr = (char*)ptr - ptr_diff;
  225. if (NULL == s->data || s->sh_type == SHT_NOBITS)
  226. memset(ptr, 0, length);
  227. else
  228. memcpy(ptr, s->data, length);
  229. /* mark executable sections as executable in memory */
  230. if (s->sh_flags & SHF_EXECINSTR)
  231. set_pages_executable((char*)ptr + ptr_diff, length);
  232. }
  233. #ifdef _WIN64
  234. *(void**)mem = win64_add_function_table(s1);
  235. #endif
  236. return 0;
  237. }
  238. /* ------------------------------------------------------------- */
  239. /* allow to run code in memory */
  240. static void set_pages_executable(void *ptr, unsigned long length)
  241. {
  242. #ifdef _WIN32
  243. unsigned long old_protect;
  244. VirtualProtect(ptr, length, PAGE_EXECUTE_READWRITE, &old_protect);
  245. #else
  246. void __clear_cache(void *beginning, void *end);
  247. # ifndef HAVE_SELINUX
  248. addr_t start, end;
  249. # ifndef PAGESIZE
  250. # define PAGESIZE 4096
  251. # endif
  252. start = (addr_t)ptr & ~(PAGESIZE - 1);
  253. end = (addr_t)ptr + length;
  254. end = (end + PAGESIZE - 1) & ~(PAGESIZE - 1);
  255. if (mprotect((void *)start, end - start, PROT_READ | PROT_WRITE | PROT_EXEC))
  256. tcc_error("mprotect failed: did you mean to configure --with-selinux?");
  257. # endif
  258. # if defined TCC_TARGET_ARM || defined TCC_TARGET_ARM64
  259. __clear_cache(ptr, (char *)ptr + length);
  260. # endif
  261. #endif
  262. }
  263. #ifdef _WIN64
  264. static void *win64_add_function_table(TCCState *s1)
  265. {
  266. void *p = NULL;
  267. if (s1->uw_pdata) {
  268. p = (void*)s1->uw_pdata->sh_addr;
  269. RtlAddFunctionTable(
  270. (RUNTIME_FUNCTION*)p,
  271. s1->uw_pdata->data_offset / sizeof (RUNTIME_FUNCTION),
  272. s1->pe_imagebase
  273. );
  274. s1->uw_pdata = NULL;
  275. }
  276. return p;
  277. }
  278. static void win64_del_function_table(void *p)
  279. {
  280. if (p) {
  281. RtlDeleteFunctionTable((RUNTIME_FUNCTION*)p);
  282. }
  283. }
  284. #endif
  285. /* ------------------------------------------------------------- */
  286. #ifdef CONFIG_TCC_BACKTRACE
  287. ST_FUNC void tcc_set_num_callers(int n)
  288. {
  289. rt_num_callers = n;
  290. }
  291. /* print the position in the source file of PC value 'pc' by reading
  292. the stabs debug information */
  293. static addr_t rt_printline(addr_t wanted_pc, const char *msg)
  294. {
  295. char func_name[128], last_func_name[128];
  296. addr_t func_addr, last_pc, pc;
  297. const char *incl_files[INCLUDE_STACK_SIZE];
  298. int incl_index, len, last_line_num, i;
  299. const char *str, *p;
  300. Stab_Sym *stab_sym = NULL, *stab_sym_end, *sym;
  301. int stab_len = 0;
  302. char *stab_str = NULL;
  303. if (stab_section) {
  304. stab_len = stab_section->data_offset;
  305. stab_sym = (Stab_Sym *)stab_section->data;
  306. stab_str = (char *) stabstr_section->data;
  307. }
  308. func_name[0] = '\0';
  309. func_addr = 0;
  310. incl_index = 0;
  311. last_func_name[0] = '\0';
  312. last_pc = (addr_t)-1;
  313. last_line_num = 1;
  314. if (!stab_sym)
  315. goto no_stabs;
  316. stab_sym_end = (Stab_Sym*)((char*)stab_sym + stab_len);
  317. for (sym = stab_sym + 1; sym < stab_sym_end; ++sym) {
  318. switch(sym->n_type) {
  319. /* function start or end */
  320. case N_FUN:
  321. if (sym->n_strx == 0) {
  322. /* we test if between last line and end of function */
  323. pc = sym->n_value + func_addr;
  324. if (wanted_pc >= last_pc && wanted_pc < pc)
  325. goto found;
  326. func_name[0] = '\0';
  327. func_addr = 0;
  328. } else {
  329. str = stab_str + sym->n_strx;
  330. p = strchr(str, ':');
  331. if (!p) {
  332. pstrcpy(func_name, sizeof(func_name), str);
  333. } else {
  334. len = p - str;
  335. if (len > sizeof(func_name) - 1)
  336. len = sizeof(func_name) - 1;
  337. memcpy(func_name, str, len);
  338. func_name[len] = '\0';
  339. }
  340. func_addr = sym->n_value;
  341. }
  342. break;
  343. /* line number info */
  344. case N_SLINE:
  345. pc = sym->n_value + func_addr;
  346. if (wanted_pc >= last_pc && wanted_pc < pc)
  347. goto found;
  348. last_pc = pc;
  349. last_line_num = sym->n_desc;
  350. /* XXX: slow! */
  351. strcpy(last_func_name, func_name);
  352. break;
  353. /* include files */
  354. case N_BINCL:
  355. str = stab_str + sym->n_strx;
  356. add_incl:
  357. if (incl_index < INCLUDE_STACK_SIZE) {
  358. incl_files[incl_index++] = str;
  359. }
  360. break;
  361. case N_EINCL:
  362. if (incl_index > 1)
  363. incl_index--;
  364. break;
  365. case N_SO:
  366. if (sym->n_strx == 0) {
  367. incl_index = 0; /* end of translation unit */
  368. } else {
  369. str = stab_str + sym->n_strx;
  370. /* do not add path */
  371. len = strlen(str);
  372. if (len > 0 && str[len - 1] != '/')
  373. goto add_incl;
  374. }
  375. break;
  376. }
  377. }
  378. no_stabs:
  379. /* second pass: we try symtab symbols (no line number info) */
  380. incl_index = 0;
  381. if (symtab_section)
  382. {
  383. ElfW(Sym) *sym, *sym_end;
  384. int type;
  385. sym_end = (ElfW(Sym) *)(symtab_section->data + symtab_section->data_offset);
  386. for(sym = (ElfW(Sym) *)symtab_section->data + 1;
  387. sym < sym_end;
  388. sym++) {
  389. type = ELFW(ST_TYPE)(sym->st_info);
  390. if (type == STT_FUNC || type == STT_GNU_IFUNC) {
  391. if (wanted_pc >= sym->st_value &&
  392. wanted_pc < sym->st_value + sym->st_size) {
  393. pstrcpy(last_func_name, sizeof(last_func_name),
  394. (char *) symtab_section->link->data + sym->st_name);
  395. func_addr = sym->st_value;
  396. goto found;
  397. }
  398. }
  399. }
  400. }
  401. /* did not find any info: */
  402. fprintf(stderr, "%s %p ???\n", msg, (void*)wanted_pc);
  403. fflush(stderr);
  404. return 0;
  405. found:
  406. i = incl_index;
  407. if (i > 0)
  408. fprintf(stderr, "%s:%d: ", incl_files[--i], last_line_num);
  409. fprintf(stderr, "%s %p", msg, (void*)wanted_pc);
  410. if (last_func_name[0] != '\0')
  411. fprintf(stderr, " %s()", last_func_name);
  412. if (--i >= 0) {
  413. fprintf(stderr, " (included from ");
  414. for (;;) {
  415. fprintf(stderr, "%s", incl_files[i]);
  416. if (--i < 0)
  417. break;
  418. fprintf(stderr, ", ");
  419. }
  420. fprintf(stderr, ")");
  421. }
  422. fprintf(stderr, "\n");
  423. fflush(stderr);
  424. return func_addr;
  425. }
  426. /* emit a run time error at position 'pc' */
  427. static void rt_error(ucontext_t *uc, const char *fmt, ...)
  428. {
  429. va_list ap;
  430. addr_t pc;
  431. int i;
  432. fprintf(stderr, "Runtime error: ");
  433. va_start(ap, fmt);
  434. vfprintf(stderr, fmt, ap);
  435. va_end(ap);
  436. fprintf(stderr, "\n");
  437. for(i=0;i<rt_num_callers;i++) {
  438. if (rt_get_caller_pc(&pc, uc, i) < 0)
  439. break;
  440. pc = rt_printline(pc, i ? "by" : "at");
  441. if (pc == (addr_t)rt_prog_main && pc)
  442. break;
  443. }
  444. }
  445. /* ------------------------------------------------------------- */
  446. #ifndef _WIN32
  447. /* signal handler for fatal errors */
  448. static void sig_error(int signum, siginfo_t *siginf, void *puc)
  449. {
  450. ucontext_t *uc = puc;
  451. switch(signum) {
  452. case SIGFPE:
  453. switch(siginf->si_code) {
  454. case FPE_INTDIV:
  455. case FPE_FLTDIV:
  456. rt_error(uc, "division by zero");
  457. break;
  458. default:
  459. rt_error(uc, "floating point exception");
  460. break;
  461. }
  462. break;
  463. case SIGBUS:
  464. case SIGSEGV:
  465. if (rt_bound_error_msg && *rt_bound_error_msg)
  466. rt_error(uc, *rt_bound_error_msg);
  467. else
  468. rt_error(uc, "dereferencing invalid pointer");
  469. break;
  470. case SIGILL:
  471. rt_error(uc, "illegal instruction");
  472. break;
  473. case SIGABRT:
  474. rt_error(uc, "abort() called");
  475. break;
  476. default:
  477. rt_error(uc, "caught signal %d", signum);
  478. break;
  479. }
  480. exit(255);
  481. }
  482. #ifndef SA_SIGINFO
  483. # define SA_SIGINFO 0x00000004u
  484. #endif
  485. /* Generate a stack backtrace when a CPU exception occurs. */
  486. static void set_exception_handler(void)
  487. {
  488. struct sigaction sigact;
  489. /* install TCC signal handlers to print debug info on fatal
  490. runtime errors */
  491. sigact.sa_flags = SA_SIGINFO | SA_RESETHAND;
  492. sigact.sa_sigaction = sig_error;
  493. sigemptyset(&sigact.sa_mask);
  494. sigaction(SIGFPE, &sigact, NULL);
  495. sigaction(SIGILL, &sigact, NULL);
  496. sigaction(SIGSEGV, &sigact, NULL);
  497. sigaction(SIGBUS, &sigact, NULL);
  498. sigaction(SIGABRT, &sigact, NULL);
  499. }
  500. /* ------------------------------------------------------------- */
  501. #ifdef __i386__
  502. /* fix for glibc 2.1 */
  503. #ifndef REG_EIP
  504. #define REG_EIP EIP
  505. #define REG_EBP EBP
  506. #endif
  507. /* return the PC at frame level 'level'. Return negative if not found */
  508. static int rt_get_caller_pc(addr_t *paddr, ucontext_t *uc, int level)
  509. {
  510. addr_t fp;
  511. int i;
  512. if (level == 0) {
  513. #if defined(__APPLE__)
  514. *paddr = uc->uc_mcontext->__ss.__eip;
  515. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  516. *paddr = uc->uc_mcontext.mc_eip;
  517. #elif defined(__dietlibc__)
  518. *paddr = uc->uc_mcontext.eip;
  519. #elif defined(__NetBSD__)
  520. *paddr = uc->uc_mcontext.__gregs[_REG_EIP];
  521. #elif defined(__OpenBSD__)
  522. *paddr = uc->sc_eip;
  523. #else
  524. *paddr = uc->uc_mcontext.gregs[REG_EIP];
  525. #endif
  526. return 0;
  527. } else {
  528. #if defined(__APPLE__)
  529. fp = uc->uc_mcontext->__ss.__ebp;
  530. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  531. fp = uc->uc_mcontext.mc_ebp;
  532. #elif defined(__dietlibc__)
  533. fp = uc->uc_mcontext.ebp;
  534. #elif defined(__NetBSD__)
  535. fp = uc->uc_mcontext.__gregs[_REG_EBP];
  536. #elif defined(__OpenBSD__)
  537. *paddr = uc->sc_ebp;
  538. #else
  539. fp = uc->uc_mcontext.gregs[REG_EBP];
  540. #endif
  541. for(i=1;i<level;i++) {
  542. /* XXX: check address validity with program info */
  543. if (fp <= 0x1000 || fp >= 0xc0000000)
  544. return -1;
  545. fp = ((addr_t *)fp)[0];
  546. }
  547. *paddr = ((addr_t *)fp)[1];
  548. return 0;
  549. }
  550. }
  551. /* ------------------------------------------------------------- */
  552. #elif defined(__x86_64__)
  553. /* return the PC at frame level 'level'. Return negative if not found */
  554. static int rt_get_caller_pc(addr_t *paddr, ucontext_t *uc, int level)
  555. {
  556. addr_t fp;
  557. int i;
  558. if (level == 0) {
  559. /* XXX: only support linux */
  560. #if defined(__APPLE__)
  561. *paddr = uc->uc_mcontext->__ss.__rip;
  562. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  563. *paddr = uc->uc_mcontext.mc_rip;
  564. #elif defined(__NetBSD__)
  565. *paddr = uc->uc_mcontext.__gregs[_REG_RIP];
  566. #else
  567. *paddr = uc->uc_mcontext.gregs[REG_RIP];
  568. #endif
  569. return 0;
  570. } else {
  571. #if defined(__APPLE__)
  572. fp = uc->uc_mcontext->__ss.__rbp;
  573. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  574. fp = uc->uc_mcontext.mc_rbp;
  575. #elif defined(__NetBSD__)
  576. fp = uc->uc_mcontext.__gregs[_REG_RBP];
  577. #else
  578. fp = uc->uc_mcontext.gregs[REG_RBP];
  579. #endif
  580. for(i=1;i<level;i++) {
  581. /* XXX: check address validity with program info */
  582. if (fp <= 0x1000)
  583. return -1;
  584. fp = ((addr_t *)fp)[0];
  585. }
  586. *paddr = ((addr_t *)fp)[1];
  587. return 0;
  588. }
  589. }
  590. /* ------------------------------------------------------------- */
  591. #elif defined(__arm__)
  592. /* return the PC at frame level 'level'. Return negative if not found */
  593. static int rt_get_caller_pc(addr_t *paddr, ucontext_t *uc, int level)
  594. {
  595. addr_t fp, sp;
  596. int i;
  597. if (level == 0) {
  598. /* XXX: only supports linux */
  599. #if defined(__linux__)
  600. *paddr = uc->uc_mcontext.arm_pc;
  601. #else
  602. return -1;
  603. #endif
  604. return 0;
  605. } else {
  606. #if defined(__linux__)
  607. fp = uc->uc_mcontext.arm_fp;
  608. sp = uc->uc_mcontext.arm_sp;
  609. if (sp < 0x1000)
  610. sp = 0x1000;
  611. #else
  612. return -1;
  613. #endif
  614. /* XXX: specific to tinycc stack frames */
  615. if (fp < sp + 12 || fp & 3)
  616. return -1;
  617. for(i = 1; i < level; i++) {
  618. sp = ((addr_t *)fp)[-2];
  619. if (sp < fp || sp - fp > 16 || sp & 3)
  620. return -1;
  621. fp = ((addr_t *)fp)[-3];
  622. if (fp <= sp || fp - sp < 12 || fp & 3)
  623. return -1;
  624. }
  625. /* XXX: check address validity with program info */
  626. *paddr = ((addr_t *)fp)[-1];
  627. return 0;
  628. }
  629. }
  630. /* ------------------------------------------------------------- */
  631. #elif defined(__aarch64__)
  632. static int rt_get_caller_pc(addr_t *paddr, ucontext_t *uc, int level)
  633. {
  634. if (level < 0)
  635. return -1;
  636. else if (level == 0) {
  637. *paddr = uc->uc_mcontext.pc;
  638. return 0;
  639. }
  640. else {
  641. addr_t *fp = (addr_t *)uc->uc_mcontext.regs[29];
  642. int i;
  643. for (i = 1; i < level; i++)
  644. fp = (addr_t *)fp[0];
  645. *paddr = fp[1];
  646. return 0;
  647. }
  648. }
  649. /* ------------------------------------------------------------- */
  650. #else
  651. #warning add arch specific rt_get_caller_pc()
  652. static int rt_get_caller_pc(addr_t *paddr, ucontext_t *uc, int level)
  653. {
  654. return -1;
  655. }
  656. #endif /* !__i386__ */
  657. /* ------------------------------------------------------------- */
  658. #else /* WIN32 */
  659. static long __stdcall cpu_exception_handler(EXCEPTION_POINTERS *ex_info)
  660. {
  661. EXCEPTION_RECORD *er = ex_info->ExceptionRecord;
  662. CONTEXT *uc = ex_info->ContextRecord;
  663. switch (er->ExceptionCode) {
  664. case EXCEPTION_ACCESS_VIOLATION:
  665. if (rt_bound_error_msg && *rt_bound_error_msg)
  666. rt_error(uc, *rt_bound_error_msg);
  667. else
  668. rt_error(uc, "access violation");
  669. break;
  670. case EXCEPTION_STACK_OVERFLOW:
  671. rt_error(uc, "stack overflow");
  672. break;
  673. case EXCEPTION_INT_DIVIDE_BY_ZERO:
  674. rt_error(uc, "division by zero");
  675. break;
  676. default:
  677. rt_error(uc, "exception caught");
  678. break;
  679. }
  680. return EXCEPTION_EXECUTE_HANDLER;
  681. }
  682. /* Generate a stack backtrace when a CPU exception occurs. */
  683. static void set_exception_handler(void)
  684. {
  685. SetUnhandledExceptionFilter(cpu_exception_handler);
  686. }
  687. /* return the PC at frame level 'level'. Return non zero if not found */
  688. static int rt_get_caller_pc(addr_t *paddr, CONTEXT *uc, int level)
  689. {
  690. addr_t fp, pc;
  691. int i;
  692. #ifdef _WIN64
  693. pc = uc->Rip;
  694. fp = uc->Rbp;
  695. #else
  696. pc = uc->Eip;
  697. fp = uc->Ebp;
  698. #endif
  699. if (level > 0) {
  700. for(i=1;i<level;i++) {
  701. /* XXX: check address validity with program info */
  702. if (fp <= 0x1000 || fp >= 0xc0000000)
  703. return -1;
  704. fp = ((addr_t*)fp)[0];
  705. }
  706. pc = ((addr_t*)fp)[1];
  707. }
  708. *paddr = pc;
  709. return 0;
  710. }
  711. #endif /* _WIN32 */
  712. #endif /* CONFIG_TCC_BACKTRACE */
  713. /* ------------------------------------------------------------- */
  714. #ifdef CONFIG_TCC_STATIC
  715. /* dummy function for profiling */
  716. ST_FUNC void *dlopen(const char *filename, int flag)
  717. {
  718. return NULL;
  719. }
  720. ST_FUNC void dlclose(void *p)
  721. {
  722. }
  723. ST_FUNC const char *dlerror(void)
  724. {
  725. return "error";
  726. }
  727. typedef struct TCCSyms {
  728. char *str;
  729. void *ptr;
  730. } TCCSyms;
  731. /* add the symbol you want here if no dynamic linking is done */
  732. static TCCSyms tcc_syms[] = {
  733. #if !defined(CONFIG_TCCBOOT)
  734. #define TCCSYM(a) { #a, &a, },
  735. TCCSYM(printf)
  736. TCCSYM(fprintf)
  737. TCCSYM(fopen)
  738. TCCSYM(fclose)
  739. #undef TCCSYM
  740. #endif
  741. { NULL, NULL },
  742. };
  743. ST_FUNC void *dlsym(void *handle, const char *symbol)
  744. {
  745. TCCSyms *p;
  746. p = tcc_syms;
  747. while (p->str != NULL) {
  748. if (!strcmp(p->str, symbol))
  749. return p->ptr;
  750. p++;
  751. }
  752. return NULL;
  753. }
  754. #endif /* CONFIG_TCC_STATIC */
  755. #endif /* TCC_IS_NATIVE */
  756. /* ------------------------------------------------------------- */