tccrun.c 23 KB

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