Subversion Repositories Kolibri OS

Rev

Rev 6441 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed

  1. /*
  2.  *  TCC - Tiny C Compiler
  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.  
  21. #include "tcc.h"
  22.  
  23. /********************************************************/
  24. /* global variables */
  25.  
  26. /* use GNU C extensions */
  27. ST_DATA int gnu_ext = 1;
  28.  
  29. /* use TinyCC extensions */
  30. ST_DATA int tcc_ext = 1;
  31.  
  32. /* XXX: get rid of this ASAP */
  33. ST_DATA struct TCCState *tcc_state;
  34.  
  35. /********************************************************/
  36.  
  37. #ifdef ONE_SOURCE
  38. #include "tccpp.c"
  39. #include "tccgen.c"
  40. #include "tccelf.c"
  41. #ifdef TCC_IS_NATIVE
  42. # include "tccrun.c"
  43. #endif
  44. #ifdef TCC_TARGET_I386
  45. #include "i386-gen.c"
  46. #endif
  47. #ifdef TCC_TARGET_ARM
  48. #include "arm-gen.c"
  49. #endif
  50. #ifdef TCC_TARGET_ARM64
  51. #include "arm64-gen.c"
  52. #endif
  53. #ifdef TCC_TARGET_C67
  54. #include "c67-gen.c"
  55. #endif
  56. #ifdef TCC_TARGET_X86_64
  57. #include "x86_64-gen.c"
  58. #endif
  59. #ifdef CONFIG_TCC_ASM
  60. #include "tccasm.c"
  61. #if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
  62. #include "i386-asm.c"
  63. #endif
  64. #endif
  65. #ifdef TCC_TARGET_COFF
  66. #include "tcccoff.c"
  67. #endif
  68. #if defined(TCC_TARGET_PE) || defined(TCC_TARGET_MEOS)
  69. #include "tccpe.c"
  70. #endif
  71. #ifdef TCC_TARGET_MEOS
  72. #include "tccmeos.c"
  73. #endif
  74.  
  75. #endif /* ONE_SOURCE */
  76.  
  77. /********************************************************/
  78. #ifndef CONFIG_TCC_ASM
  79. ST_FUNC void asm_instr(void)
  80. {
  81.     tcc_error("inline asm() not supported");
  82. }
  83. ST_FUNC void asm_global_instr(void)
  84. {
  85.     tcc_error("inline asm() not supported");
  86. }
  87. #endif
  88.  
  89. /********************************************************/
  90. #ifdef _WIN32
  91. static char *normalize_slashes(char *path)
  92. {
  93.     char *p;
  94.     for (p = path; *p; ++p)
  95.         if (*p == '\\')
  96.             *p = '/';
  97.     return path;
  98. }
  99.  
  100. static HMODULE tcc_module;
  101.  
  102. /* on win32, we suppose the lib and includes are at the location of 'tcc.exe' */
  103. static void tcc_set_lib_path_w32(TCCState *s)
  104. {
  105.     char path[1024], *p;
  106.     GetModuleFileNameA(tcc_module, path, sizeof path);
  107.     p = tcc_basename(normalize_slashes(strlwr(path)));
  108.     if (p - 5 > path && 0 == strncmp(p - 5, "/bin/", 5))
  109.         p -= 5;
  110.     else if (p > path)
  111.         p--;
  112.     *p = 0;
  113.     tcc_set_lib_path(s, path);
  114. }
  115.  
  116. #ifdef TCC_TARGET_PE
  117. static void tcc_add_systemdir(TCCState *s)
  118. {
  119.     char buf[1000];
  120.     GetSystemDirectory(buf, sizeof buf);
  121.     tcc_add_library_path(s, normalize_slashes(buf));
  122. }
  123. #endif
  124.  
  125. #ifndef CONFIG_TCC_STATIC
  126. void dlclose(void *p)
  127. {
  128.     FreeLibrary((HMODULE)p);
  129. }
  130. #endif
  131.  
  132. #ifdef LIBTCC_AS_DLL
  133. BOOL WINAPI DllMain (HINSTANCE hDll, DWORD dwReason, LPVOID lpReserved)
  134. {
  135.     if (DLL_PROCESS_ATTACH == dwReason)
  136.         tcc_module = hDll;
  137.     return TRUE;
  138. }
  139. #endif
  140. #endif
  141.  
  142. /********************************************************/
  143. /* copy a string and truncate it. */
  144. PUB_FUNC char *pstrcpy(char *buf, int buf_size, const char *s)
  145. {
  146.     char *q, *q_end;
  147.     int c;
  148.  
  149.     if (buf_size > 0) {
  150.         q = buf;
  151.         q_end = buf + buf_size - 1;
  152.         while (q < q_end) {
  153.             c = *s++;
  154.             if (c == '\0')
  155.                 break;
  156.             *q++ = c;
  157.         }
  158.         *q = '\0';
  159.     }
  160.     return buf;
  161. }
  162.  
  163. /* strcat and truncate. */
  164. PUB_FUNC char *pstrcat(char *buf, int buf_size, const char *s)
  165. {
  166.     int len;
  167.     len = strlen(buf);
  168.     if (len < buf_size)
  169.         pstrcpy(buf + len, buf_size - len, s);
  170.     return buf;
  171. }
  172.  
  173. PUB_FUNC char *pstrncpy(char *out, const char *in, size_t num)
  174. {
  175.     memcpy(out, in, num);
  176.     out[num] = '\0';
  177.     return out;
  178. }
  179.  
  180. /* extract the basename of a file */
  181. PUB_FUNC char *tcc_basename(const char *name)
  182. {
  183.     char *p = strchr(name, 0);
  184.     while (p > name && !IS_DIRSEP(p[-1]))
  185.         --p;
  186.     return p;
  187. }
  188.  
  189. /* extract extension part of a file
  190.  *
  191.  * (if no extension, return pointer to end-of-string)
  192.  */
  193. PUB_FUNC char *tcc_fileextension (const char *name)
  194. {
  195.     char *b = tcc_basename(name);
  196.     char *e = strrchr(b, '.');
  197.     return e ? e : strchr(b, 0);
  198. }
  199.  
  200. /********************************************************/
  201. /* memory management */
  202.  
  203. #undef free
  204. #undef malloc
  205. #undef realloc
  206.  
  207. #ifndef MEM_DEBUG
  208.  
  209. PUB_FUNC void tcc_free(void *ptr)
  210. {
  211.     free(ptr);
  212. }
  213.  
  214. PUB_FUNC void *tcc_malloc(unsigned long size)
  215. {
  216.     void *ptr;
  217.     ptr = malloc(size);
  218.     if (!ptr && size)
  219.         tcc_error("memory full (malloc)");
  220.     return ptr;
  221. }
  222.  
  223. PUB_FUNC void *tcc_mallocz(unsigned long size)
  224. {
  225.     void *ptr;
  226.     ptr = tcc_malloc(size);
  227.     memset(ptr, 0, size);
  228.     return ptr;
  229. }
  230.  
  231. PUB_FUNC void *tcc_realloc(void *ptr, unsigned long size)
  232. {
  233.     void *ptr1;
  234.     ptr1 = realloc(ptr, size);
  235.     if (!ptr1 && size)
  236.         tcc_error("memory full (realloc)");
  237.     return ptr1;
  238. }
  239.  
  240. PUB_FUNC char *tcc_strdup(const char *str)
  241. {
  242.     char *ptr;
  243.     ptr = tcc_malloc(strlen(str) + 1);
  244.     strcpy(ptr, str);
  245.     return ptr;
  246. }
  247.  
  248. PUB_FUNC void tcc_memstats(int bench)
  249. {
  250. }
  251.  
  252. #else
  253.  
  254. #define MEM_DEBUG_MAGIC1 0xFEEDDEB1
  255. #define MEM_DEBUG_MAGIC2 0xFEEDDEB2
  256. #define MEM_DEBUG_FILE_LEN 15
  257.  
  258. struct mem_debug_header {
  259.     size_t      magic1;
  260.     size_t      size;
  261.     struct mem_debug_header *prev;
  262.     struct mem_debug_header *next;
  263.     size_t      line_num;
  264.     char        file_name[MEM_DEBUG_FILE_LEN + 1];
  265.     size_t      magic2;
  266. };
  267.  
  268. typedef struct mem_debug_header mem_debug_header_t;
  269.  
  270. static mem_debug_header_t *mem_debug_chain;
  271. static size_t mem_cur_size;
  272. static size_t mem_max_size;
  273.  
  274. PUB_FUNC void *tcc_malloc_debug(unsigned long size, const char *file, int line)
  275. {
  276.     void *ptr;
  277.     int ofs;
  278.  
  279.     mem_debug_header_t *header;
  280.  
  281.     ptr = malloc(sizeof(mem_debug_header_t) + size);
  282.     if (!ptr)
  283.         tcc_error("memory full (malloc)");
  284.  
  285.     mem_cur_size += size;
  286.     if (mem_cur_size > mem_max_size)
  287.         mem_max_size = mem_cur_size;
  288.  
  289.     header = (mem_debug_header_t *)ptr;
  290.  
  291.     header->magic1 = MEM_DEBUG_MAGIC1;
  292.     header->magic2 = MEM_DEBUG_MAGIC2;
  293.     header->size = size;
  294.     header->line_num = line;
  295.  
  296.     ofs = strlen(file) - MEM_DEBUG_FILE_LEN;
  297.     strncpy(header->file_name, file + (ofs > 0 ? ofs : 0), MEM_DEBUG_FILE_LEN);
  298.     header->file_name[MEM_DEBUG_FILE_LEN] = 0;
  299.  
  300.     header->next = mem_debug_chain;
  301.     header->prev = NULL;
  302.  
  303.     if (header->next)
  304.         header->next->prev = header;
  305.  
  306.     mem_debug_chain = header;
  307.  
  308.     ptr = (char *)ptr + sizeof(mem_debug_header_t);
  309.     return ptr;
  310. }
  311.  
  312. PUB_FUNC void tcc_free_debug(void *ptr)
  313. {
  314.     mem_debug_header_t *header;
  315.  
  316.     if (!ptr)
  317.         return;
  318.  
  319.     ptr = (char *)ptr - sizeof(mem_debug_header_t);
  320.     header = (mem_debug_header_t *)ptr;
  321.     if (header->magic1 != MEM_DEBUG_MAGIC1 ||
  322.         header->magic2 != MEM_DEBUG_MAGIC2 ||
  323.         header->size == (size_t)-1 )
  324.     {
  325.         tcc_error("tcc_free check failed");
  326.     }
  327.  
  328.     mem_cur_size -= header->size;
  329.     header->size = (size_t)-1;
  330.    
  331.     if (header->next)
  332.         header->next->prev = header->prev;
  333.  
  334.     if (header->prev)
  335.         header->prev->next = header->next;
  336.  
  337.     if (header == mem_debug_chain)
  338.         mem_debug_chain = header->next;
  339.  
  340.     free(ptr);
  341. }
  342.  
  343.  
  344. PUB_FUNC void *tcc_mallocz_debug(unsigned long size, const char *file, int line)
  345. {
  346.     void *ptr;
  347.     ptr = tcc_malloc_debug(size,file,line);
  348.     memset(ptr, 0, size);
  349.     return ptr;
  350. }
  351.  
  352. PUB_FUNC void *tcc_realloc_debug(void *ptr, unsigned long size, const char *file, int line)
  353. {
  354.     mem_debug_header_t *header;
  355.     int mem_debug_chain_update = 0;
  356.  
  357.     if (!ptr) {
  358.         ptr = tcc_malloc_debug(size, file, line);
  359.         return ptr;
  360.     }
  361.  
  362.     ptr = (char *)ptr - sizeof(mem_debug_header_t);
  363.     header = (mem_debug_header_t *)ptr;
  364.     if (header->magic1 != MEM_DEBUG_MAGIC1 ||
  365.         header->magic2 != MEM_DEBUG_MAGIC2 ||
  366.         header->size == (size_t)-1 )
  367.     {
  368.         check_error:
  369.             tcc_error("tcc_realloc check failed");
  370.     }
  371.  
  372.     mem_debug_chain_update = (header == mem_debug_chain);
  373.  
  374.     mem_cur_size -= header->size;
  375.     ptr = realloc(ptr, sizeof(mem_debug_header_t) + size);
  376.     if (!ptr)
  377.         tcc_error("memory full (realloc)");
  378.  
  379.     header = (mem_debug_header_t *)ptr;
  380.     if (header->magic1 != MEM_DEBUG_MAGIC1 ||
  381.         header->magic2 != MEM_DEBUG_MAGIC2)
  382.     {
  383.         goto check_error;
  384.     }
  385.  
  386.     mem_cur_size += size;
  387.     if (mem_cur_size > mem_max_size)
  388.         mem_max_size = mem_cur_size;
  389.  
  390.     header->size = size;
  391.     if (header->next)
  392.         header->next->prev = header;
  393.  
  394.     if (header->prev)
  395.         header->prev->next = header;
  396.  
  397.     if (mem_debug_chain_update)
  398.         mem_debug_chain = header;
  399.  
  400.     ptr = (char *)ptr + sizeof(mem_debug_header_t);
  401.     return ptr;
  402. }
  403.  
  404. PUB_FUNC char *tcc_strdup_debug(const char *str, const char *file, int line)
  405. {
  406.     char *ptr;
  407.     ptr = tcc_malloc_debug(strlen(str) + 1, file, line);
  408.     strcpy(ptr, str);
  409.     return ptr;
  410. }
  411.  
  412. PUB_FUNC void tcc_memstats(int bench)
  413. {
  414.     if (mem_cur_size) {
  415.         mem_debug_header_t *header = mem_debug_chain;
  416.  
  417.         fprintf(stderr, "MEM_DEBUG: mem_leak= %d bytes, mem_max_size= %d bytes\n",
  418.             mem_cur_size, mem_max_size);
  419.  
  420.         while (header) {
  421.             fprintf(stderr, "  file %s, line %u: %u bytes\n",
  422.                 header->file_name, header->line_num, header->size);
  423.             header = header->next;
  424.         }
  425.     }
  426.     else if (bench)
  427.         fprintf(stderr, "mem_max_size= %d bytes\n", mem_max_size);
  428. }
  429.  
  430. #undef MEM_DEBUG_MAGIC1
  431. #undef MEM_DEBUG_MAGIC2
  432. #undef MEM_DEBUG_FILE_LEN
  433.  
  434. #endif
  435.  
  436. #define free(p) use_tcc_free(p)
  437. #define malloc(s) use_tcc_malloc(s)
  438. #define realloc(p, s) use_tcc_realloc(p, s)
  439.  
  440. /********************************************************/
  441. /* dynarrays */
  442.  
  443. ST_FUNC void dynarray_add(void ***ptab, int *nb_ptr, void *data)
  444. {
  445.     int nb, nb_alloc;
  446.     void **pp;
  447.  
  448.     nb = *nb_ptr;
  449.     pp = *ptab;
  450.     /* every power of two we double array size */
  451.     if ((nb & (nb - 1)) == 0) {
  452.         if (!nb)
  453.             nb_alloc = 1;
  454.         else
  455.             nb_alloc = nb * 2;
  456.         pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
  457.         *ptab = pp;
  458.     }
  459.     pp[nb++] = data;
  460.     *nb_ptr = nb;
  461. }
  462.  
  463. ST_FUNC void dynarray_reset(void *pp, int *n)
  464. {
  465.     void **p;
  466.     for (p = *(void***)pp; *n; ++p, --*n)
  467.         if (*p)
  468.             tcc_free(*p);
  469.     tcc_free(*(void**)pp);
  470.     *(void**)pp = NULL;
  471. }
  472.  
  473. static void tcc_split_path(TCCState *s, void ***p_ary, int *p_nb_ary, const char *in)
  474. {
  475.     const char *p;
  476.     do {
  477.         int c;
  478.         CString str;
  479.  
  480.         cstr_new(&str);
  481.         for (p = in; c = *p, c != '\0' && c != PATHSEP; ++p) {
  482.             if (c == '{' && p[1] && p[2] == '}') {
  483.                 c = p[1], p += 2;
  484.                 if (c == 'B')
  485.                     cstr_cat(&str, s->tcc_lib_path, -1);
  486.             } else {
  487.                 cstr_ccat(&str, c);
  488.             }
  489.         }
  490.         cstr_ccat(&str, '\0');
  491.         dynarray_add(p_ary, p_nb_ary, tcc_strdup(str.data));
  492.         cstr_free(&str);
  493.         in = p+1;
  494.     } while (*p);
  495. }
  496.  
  497. /********************************************************/
  498.  
  499. ST_FUNC Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags)
  500. {
  501.     Section *sec;
  502.  
  503.     sec = tcc_mallocz(sizeof(Section) + strlen(name));
  504.     strcpy(sec->name, name);
  505.     sec->sh_type = sh_type;
  506.     sec->sh_flags = sh_flags;
  507.     switch(sh_type) {
  508.     case SHT_HASH:
  509.     case SHT_REL:
  510.     case SHT_RELA:
  511.     case SHT_DYNSYM:
  512.     case SHT_SYMTAB:
  513.     case SHT_DYNAMIC:
  514.         sec->sh_addralign = 4;
  515.         break;
  516.     case SHT_STRTAB:
  517.         sec->sh_addralign = 1;
  518.         break;
  519.     default:
  520.         sec->sh_addralign =  PTR_SIZE; /* gcc/pcc default aligment */
  521.         break;
  522.     }
  523.  
  524.     if (sh_flags & SHF_PRIVATE) {
  525.         dynarray_add((void ***)&s1->priv_sections, &s1->nb_priv_sections, sec);
  526.     } else {
  527.         sec->sh_num = s1->nb_sections;
  528.         dynarray_add((void ***)&s1->sections, &s1->nb_sections, sec);
  529.     }
  530.  
  531.     return sec;
  532. }
  533.  
  534. static void free_section(Section *s)
  535. {
  536.     tcc_free(s->data);
  537. }
  538.  
  539. /* realloc section and set its content to zero */
  540. ST_FUNC void section_realloc(Section *sec, unsigned long new_size)
  541. {
  542.     unsigned long size;
  543.     unsigned char *data;
  544.  
  545.     size = sec->data_allocated;
  546.     if (size == 0)
  547.         size = 1;
  548.     while (size < new_size)
  549.         size = size * 2;
  550.     data = tcc_realloc(sec->data, size);
  551.     memset(data + sec->data_allocated, 0, size - sec->data_allocated);
  552.     sec->data = data;
  553.     sec->data_allocated = size;
  554. }
  555.  
  556. /* reserve at least 'size' bytes in section 'sec' from
  557.    sec->data_offset. */
  558. ST_FUNC void *section_ptr_add(Section *sec, addr_t size)
  559. {
  560.     size_t offset, offset1;
  561.  
  562.     offset = sec->data_offset;
  563.     offset1 = offset + size;
  564.     if (offset1 > sec->data_allocated)
  565.         section_realloc(sec, offset1);
  566.     sec->data_offset = offset1;
  567.     return sec->data + offset;
  568. }
  569.  
  570. /* reserve at least 'size' bytes from section start */
  571. ST_FUNC void section_reserve(Section *sec, unsigned long size)
  572. {
  573.     if (size > sec->data_allocated)
  574.         section_realloc(sec, size);
  575.     if (size > sec->data_offset)
  576.         sec->data_offset = size;
  577. }
  578.  
  579. /* return a reference to a section, and create it if it does not
  580.    exists */
  581. ST_FUNC Section *find_section(TCCState *s1, const char *name)
  582. {
  583.     Section *sec;
  584.     int i;
  585.     for(i = 1; i < s1->nb_sections; i++) {
  586.         sec = s1->sections[i];
  587.         if (!strcmp(name, sec->name))
  588.             return sec;
  589.     }
  590.     /* sections are created as PROGBITS */
  591.     return new_section(s1, name, SHT_PROGBITS, SHF_ALLOC);
  592. }
  593.  
  594. /* update sym->c so that it points to an external symbol in section
  595.    'section' with value 'value' */
  596. ST_FUNC void put_extern_sym2(Sym *sym, Section *section,
  597.                             addr_t value, unsigned long size,
  598.                             int can_add_underscore)
  599. {
  600.     int sym_type, sym_bind, sh_num, info, other;
  601.     ElfW(Sym) *esym;
  602.     const char *name;
  603.     char buf1[256];
  604.  
  605. #ifdef CONFIG_TCC_BCHECK
  606.     char buf[32];
  607. #endif
  608.  
  609.     if (section == NULL)
  610.         sh_num = SHN_UNDEF;
  611.     else if (section == SECTION_ABS)
  612.         sh_num = SHN_ABS;
  613.     else
  614.         sh_num = section->sh_num;
  615.  
  616.     if ((sym->type.t & VT_BTYPE) == VT_FUNC) {
  617.         sym_type = STT_FUNC;
  618.     } else if ((sym->type.t & VT_BTYPE) == VT_VOID) {
  619.         sym_type = STT_NOTYPE;
  620.     } else {
  621.         sym_type = STT_OBJECT;
  622.     }
  623.  
  624.     if (sym->type.t & VT_STATIC)
  625.         sym_bind = STB_LOCAL;
  626.     else {
  627.         if (sym->type.t & VT_WEAK)
  628.             sym_bind = STB_WEAK;
  629.         else
  630.             sym_bind = STB_GLOBAL;
  631.     }
  632.  
  633.     if (!sym->c) {
  634.         name = get_tok_str(sym->v, NULL);
  635. #ifdef CONFIG_TCC_BCHECK
  636.         if (tcc_state->do_bounds_check) {
  637.             /* XXX: avoid doing that for statics ? */
  638.             /* if bound checking is activated, we change some function
  639.                names by adding the "__bound" prefix */
  640.             switch(sym->v) {
  641. #ifdef TCC_TARGET_PE
  642.             /* XXX: we rely only on malloc hooks */
  643.             case TOK_malloc:
  644.             case TOK_free:
  645.             case TOK_realloc:
  646.             case TOK_memalign:
  647.             case TOK_calloc:
  648. #endif
  649.             case TOK_memcpy:
  650.             case TOK_memmove:
  651.             case TOK_memset:
  652.             case TOK_strlen:
  653.             case TOK_strcpy:
  654.             case TOK_alloca:
  655.                 strcpy(buf, "__bound_");
  656.                 strcat(buf, name);
  657.                 name = buf;
  658.                 break;
  659.             }
  660.         }
  661. #endif
  662.         other = 0;
  663.  
  664. #ifdef TCC_TARGET_PE
  665.         if (sym->type.t & VT_EXPORT)
  666.             other |= ST_PE_EXPORT;
  667.         if (sym_type == STT_FUNC && sym->type.ref) {
  668.             Sym *ref = sym->type.ref;
  669.             if (ref->a.func_export)
  670.                 other |= ST_PE_EXPORT;
  671.             if (ref->a.func_call == FUNC_STDCALL && can_add_underscore) {
  672.                 sprintf(buf1, "_%s@%d", name, ref->a.func_args * PTR_SIZE);
  673.                 name = buf1;
  674.                 other |= ST_PE_STDCALL;
  675.                 can_add_underscore = 0;
  676.             }
  677.         } else {
  678.             if (find_elf_sym(tcc_state->dynsymtab_section, name))
  679.                 other |= ST_PE_IMPORT;
  680.             if (sym->type.t & VT_IMPORT)
  681.                 other |= ST_PE_IMPORT;
  682.         }
  683. #else
  684.         if (! (sym->type.t & VT_STATIC))
  685.             other = (sym->type.t & VT_VIS_MASK) >> VT_VIS_SHIFT;
  686. #endif
  687.         if (tcc_state->leading_underscore && can_add_underscore) {
  688.             buf1[0] = '_';
  689.             pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
  690.             name = buf1;
  691.         }
  692.         if (sym->asm_label) {
  693.             name = get_tok_str(sym->asm_label, NULL);
  694.         }
  695.         info = ELFW(ST_INFO)(sym_bind, sym_type);
  696.         sym->c = add_elf_sym(symtab_section, value, size, info, other, sh_num, name);
  697.     } else {
  698.         esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
  699.         esym->st_value = value;
  700.         esym->st_size = size;
  701.         esym->st_shndx = sh_num;
  702.     }
  703. }
  704.  
  705. ST_FUNC void put_extern_sym(Sym *sym, Section *section,
  706.                            addr_t value, unsigned long size)
  707. {
  708.     put_extern_sym2(sym, section, value, size, 1);
  709. }
  710.  
  711. /* add a new relocation entry to symbol 'sym' in section 's' */
  712. ST_FUNC void greloca(Section *s, Sym *sym, unsigned long offset, int type,
  713.                      addr_t addend)
  714. {
  715.     int c = 0;
  716.     if (sym) {
  717.         if (0 == sym->c)
  718.             put_extern_sym(sym, NULL, 0, 0);
  719.         c = sym->c;
  720.     }
  721.     /* now we can add ELF relocation info */
  722.     put_elf_reloca(symtab_section, s, offset, type, c, addend);
  723. }
  724.  
  725. ST_FUNC void greloc(Section *s, Sym *sym, unsigned long offset, int type)
  726. {
  727.     greloca(s, sym, offset, type, 0);
  728. }
  729.  
  730. /********************************************************/
  731.  
  732. static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
  733. {
  734.     int len;
  735.     len = strlen(buf);
  736.     vsnprintf(buf + len, buf_size - len, fmt, ap);
  737. }
  738.  
  739. static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
  740. {
  741.     va_list ap;
  742.     va_start(ap, fmt);
  743.     strcat_vprintf(buf, buf_size, fmt, ap);
  744.     va_end(ap);
  745. }
  746.  
  747. static void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
  748. {
  749.     char buf[2048];
  750.     BufferedFile **pf, *f;
  751.  
  752.     buf[0] = '\0';
  753.     /* use upper file if inline ":asm:" or token ":paste:" */
  754.     for (f = file; f && f->filename[0] == ':'; f = f->prev)
  755.      ;
  756.     if (f) {
  757.         for(pf = s1->include_stack; pf < s1->include_stack_ptr; pf++)
  758.             strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
  759.                 (*pf)->filename, (*pf)->line_num);
  760.         if (f->line_num > 0) {
  761.             strcat_printf(buf, sizeof(buf), "%s:%d: ",
  762.                 f->filename, f->line_num);
  763.         } else {
  764.             strcat_printf(buf, sizeof(buf), "%s: ",
  765.                 f->filename);
  766.         }
  767.     } else {
  768.         strcat_printf(buf, sizeof(buf), "tcc: ");
  769.     }
  770.     if (is_warning)
  771.         strcat_printf(buf, sizeof(buf), "warning: ");
  772.     else
  773.         strcat_printf(buf, sizeof(buf), "error: ");
  774.     strcat_vprintf(buf, sizeof(buf), fmt, ap);
  775.  
  776.     if (!s1->error_func) {
  777.         /* default case: stderr */
  778.         if (s1->ppfp) /* print a newline during tcc -E */
  779.             fprintf(s1->ppfp, "\n"), fflush(s1->ppfp);
  780.         fprintf(stderr, "%s\n", buf);
  781.         fflush(stderr); /* print error/warning now (win32) */
  782.     } else {
  783.         s1->error_func(s1->error_opaque, buf);
  784.     }
  785.     if (!is_warning || s1->warn_error)
  786.         s1->nb_errors++;
  787. }
  788.  
  789. LIBTCCAPI void tcc_set_error_func(TCCState *s, void *error_opaque,
  790.                         void (*error_func)(void *opaque, const char *msg))
  791. {
  792.     s->error_opaque = error_opaque;
  793.     s->error_func = error_func;
  794. }
  795.  
  796. /* error without aborting current compilation */
  797. PUB_FUNC void tcc_error_noabort(const char *fmt, ...)
  798. {
  799.     TCCState *s1 = tcc_state;
  800.     va_list ap;
  801.  
  802.     va_start(ap, fmt);
  803.     error1(s1, 0, fmt, ap);
  804.     va_end(ap);
  805. }
  806.  
  807. PUB_FUNC void tcc_error(const char *fmt, ...)
  808. {
  809.     TCCState *s1 = tcc_state;
  810.     va_list ap;
  811.  
  812.     va_start(ap, fmt);
  813.     error1(s1, 0, fmt, ap);
  814.     va_end(ap);
  815.     /* better than nothing: in some cases, we accept to handle errors */
  816.     if (s1->error_set_jmp_enabled) {
  817.         longjmp(s1->error_jmp_buf, 1);
  818.     } else {
  819.         /* XXX: eliminate this someday */
  820.         exit(1);
  821.     }
  822. }
  823.  
  824. PUB_FUNC void tcc_warning(const char *fmt, ...)
  825. {
  826.     TCCState *s1 = tcc_state;
  827.     va_list ap;
  828.  
  829.     if (s1->warn_none)
  830.         return;
  831.  
  832.     va_start(ap, fmt);
  833.     error1(s1, 1, fmt, ap);
  834.     va_end(ap);
  835. }
  836.  
  837. /********************************************************/
  838. /* I/O layer */
  839.  
  840. ST_FUNC void tcc_open_bf(TCCState *s1, const char *filename, int initlen)
  841. {
  842.     BufferedFile *bf;
  843.     int buflen = initlen ? initlen : IO_BUF_SIZE;
  844.  
  845.     bf = tcc_mallocz(sizeof(BufferedFile) + buflen);
  846.     bf->buf_ptr = bf->buffer;
  847.     bf->buf_end = bf->buffer + initlen;
  848.     bf->buf_end[0] = CH_EOB; /* put eob symbol */
  849.     pstrcpy(bf->filename, sizeof(bf->filename), filename);
  850. #ifdef _WIN32
  851.     normalize_slashes(bf->filename);
  852. #endif
  853.     bf->line_num = 1;
  854.     bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
  855.     bf->fd = -1;
  856.     bf->prev = file;
  857.     file = bf;
  858. }
  859.  
  860. ST_FUNC void tcc_close(void)
  861. {
  862.     BufferedFile *bf = file;
  863.     if (bf->fd > 0) {
  864.         close(bf->fd);
  865.         total_lines += bf->line_num;
  866.     }
  867.     file = bf->prev;
  868.     tcc_free(bf);
  869. }
  870.  
  871. ST_FUNC int tcc_open(TCCState *s1, const char *filename)
  872. {
  873.     int fd;
  874.     if (strcmp(filename, "-") == 0)
  875.         fd = 0, filename = "<stdin>";
  876.     else
  877.         fd = open(filename, O_RDONLY | O_BINARY);
  878.     if ((s1->verbose == 2 && fd >= 0) || s1->verbose == 3)
  879.         printf("%s %*s%s\n", fd < 0 ? "nf":"->",
  880.                (int)(s1->include_stack_ptr - s1->include_stack), "", filename);
  881.     if (fd < 0)
  882.         return -1;
  883.  
  884.     tcc_open_bf(s1, filename, 0);
  885.     file->fd = fd;
  886.     return fd;
  887. }
  888.  
  889. /* compile the C file opened in 'file'. Return non zero if errors. */
  890. static int tcc_compile(TCCState *s1)
  891. {
  892.     Sym *define_start;
  893.     char buf[512];
  894.     volatile int section_sym;
  895.  
  896. #ifdef INC_DEBUG
  897.     printf("%s: **** new file\n", file->filename);
  898. #endif
  899.     preprocess_init(s1);
  900.  
  901.     cur_text_section = NULL;
  902.     funcname = "";
  903.     anon_sym = SYM_FIRST_ANOM;
  904.  
  905.     /* file info: full path + filename */
  906.     section_sym = 0; /* avoid warning */
  907.     if (s1->do_debug) {
  908.         section_sym = put_elf_sym(symtab_section, 0, 0,
  909.                                   ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
  910.                                   text_section->sh_num, NULL);
  911.         getcwd(buf, sizeof(buf));
  912. #ifdef _WIN32
  913.         normalize_slashes(buf);
  914. #endif
  915.         pstrcat(buf, sizeof(buf), "/");
  916.         put_stabs_r(buf, N_SO, 0, 0,
  917.                     text_section->data_offset, text_section, section_sym);
  918.         put_stabs_r(file->filename, N_SO, 0, 0,
  919.                     text_section->data_offset, text_section, section_sym);
  920.     }
  921.     /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
  922.        symbols can be safely used */
  923.     put_elf_sym(symtab_section, 0, 0,
  924.                 ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
  925.                 SHN_ABS, file->filename);
  926.  
  927.     /* define some often used types */
  928.     int_type.t = VT_INT;
  929.  
  930.     char_pointer_type.t = VT_BYTE;
  931.     mk_pointer(&char_pointer_type);
  932.  
  933. #if PTR_SIZE == 4
  934.     size_type.t = VT_INT;
  935. #else
  936.     size_type.t = VT_LLONG;
  937. #endif
  938.  
  939.     func_old_type.t = VT_FUNC;
  940.     func_old_type.ref = sym_push(SYM_FIELD, &int_type, FUNC_CDECL, FUNC_OLD);
  941. #ifdef TCC_TARGET_ARM
  942.     arm_init(s1);
  943. #endif
  944.  
  945. #if 0
  946.     /* define 'void *alloca(unsigned int)' builtin function */
  947.     {
  948.         Sym *s1;
  949.  
  950.         p = anon_sym++;
  951.         sym = sym_push(p, mk_pointer(VT_VOID), FUNC_CDECL, FUNC_NEW);
  952.         s1 = sym_push(SYM_FIELD, VT_UNSIGNED | VT_INT, 0, 0);
  953.         s1->next = NULL;
  954.         sym->next = s1;
  955.         sym_push(TOK_alloca, VT_FUNC | (p << VT_STRUCT_SHIFT), VT_CONST, 0);
  956.     }
  957. #endif
  958.  
  959.     define_start = define_stack;
  960.     nocode_wanted = 1;
  961.  
  962.     if (setjmp(s1->error_jmp_buf) == 0) {
  963.         s1->nb_errors = 0;
  964.         s1->error_set_jmp_enabled = 1;
  965.  
  966.         ch = file->buf_ptr[0];
  967.         tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
  968.         parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM | PARSE_FLAG_TOK_STR;
  969.         next();
  970.         decl(VT_CONST);
  971.         if (tok != TOK_EOF)
  972.             expect("declaration");
  973.         check_vstack();
  974.  
  975.         /* end of translation unit info */
  976.         if (s1->do_debug) {
  977.             put_stabs_r(NULL, N_SO, 0, 0,
  978.                         text_section->data_offset, text_section, section_sym);
  979.         }
  980.     }
  981.  
  982.     s1->error_set_jmp_enabled = 0;
  983.  
  984.     /* reset define stack, but leave -Dsymbols (may be incorrect if
  985.        they are undefined) */
  986.     free_defines(define_start);
  987.  
  988.     gen_inline_functions();
  989.  
  990.     sym_pop(&global_stack, NULL);
  991.     sym_pop(&local_stack, NULL);
  992.  
  993.     return s1->nb_errors != 0 ? -1 : 0;
  994. }
  995.  
  996. LIBTCCAPI int tcc_compile_string(TCCState *s, const char *str)
  997. {
  998.     int len, ret;
  999.  
  1000.     len = strlen(str);
  1001.     tcc_open_bf(s, "<string>", len);
  1002.     memcpy(file->buffer, str, len);
  1003.     ret = tcc_compile(s);
  1004.     tcc_close();
  1005.     return ret;
  1006. }
  1007.  
  1008. /* define a preprocessor symbol. A value can also be provided with the '=' operator */
  1009. LIBTCCAPI void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
  1010. {
  1011.     int len1, len2;
  1012.     /* default value */
  1013.     if (!value)
  1014.         value = "1";
  1015.     len1 = strlen(sym);
  1016.     len2 = strlen(value);
  1017.  
  1018.     /* init file structure */
  1019.     tcc_open_bf(s1, "<define>", len1 + len2 + 1);
  1020.     memcpy(file->buffer, sym, len1);
  1021.     file->buffer[len1] = ' ';
  1022.     memcpy(file->buffer + len1 + 1, value, len2);
  1023.  
  1024.     /* parse with define parser */
  1025.     ch = file->buf_ptr[0];
  1026.     next_nomacro();
  1027.     parse_define();
  1028.  
  1029.     tcc_close();
  1030. }
  1031.  
  1032. /* undefine a preprocessor symbol */
  1033. LIBTCCAPI void tcc_undefine_symbol(TCCState *s1, const char *sym)
  1034. {
  1035.     TokenSym *ts;
  1036.     Sym *s;
  1037.     ts = tok_alloc(sym, strlen(sym));
  1038.     s = define_find(ts->tok);
  1039.     /* undefine symbol by putting an invalid name */
  1040.     if (s)
  1041.         define_undef(s);
  1042. }
  1043.  
  1044. /* cleanup all static data used during compilation */
  1045. static void tcc_cleanup(void)
  1046. {
  1047.     if (NULL == tcc_state)
  1048.         return;
  1049.     tcc_state = NULL;
  1050.  
  1051.     preprocess_delete();
  1052.  
  1053.     /* free sym_pools */
  1054.     dynarray_reset(&sym_pools, &nb_sym_pools);
  1055.     /* reset symbol stack */
  1056.     sym_free_first = NULL;
  1057. }
  1058.  
  1059. LIBTCCAPI TCCState *tcc_new(void)
  1060. {
  1061.     TCCState *s;
  1062.     char buffer[100];
  1063.     int a,b,c;
  1064.  
  1065.     tcc_cleanup();
  1066.  
  1067.     s = tcc_mallocz(sizeof(TCCState));
  1068.     if (!s)
  1069.         return NULL;
  1070.     tcc_state = s;
  1071. #ifdef _WIN32
  1072.     tcc_set_lib_path_w32(s);
  1073. #else
  1074.     tcc_set_lib_path(s, CONFIG_TCCDIR);
  1075. #endif
  1076.     s->output_type = 0;
  1077.     preprocess_new();
  1078.     s->include_stack_ptr = s->include_stack;
  1079.  
  1080.     /* we add dummy defines for some special macros to speed up tests
  1081.        and to have working defined() */
  1082.     define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
  1083.     define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
  1084.     define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
  1085.     define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
  1086.  
  1087.     /* define __TINYC__ 92X  */
  1088.     sscanf(TCC_VERSION, "%d.%d.%d", &a, &b, &c);
  1089.     sprintf(buffer, "%d", a*10000 + b*100 + c);
  1090.     tcc_define_symbol(s, "__TINYC__", buffer);
  1091.  
  1092.     /* standard defines */
  1093.     tcc_define_symbol(s, "__STDC__", NULL);
  1094.     tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
  1095.     tcc_define_symbol(s, "__STDC_HOSTED__", NULL);
  1096.  
  1097.     /* target defines */
  1098. #if defined(TCC_TARGET_I386)
  1099.     tcc_define_symbol(s, "__i386__", NULL);
  1100.     tcc_define_symbol(s, "__i386", NULL);
  1101.     tcc_define_symbol(s, "i386", NULL);
  1102. #elif defined(TCC_TARGET_X86_64)
  1103.     tcc_define_symbol(s, "__x86_64__", NULL);
  1104. #elif defined(TCC_TARGET_ARM)
  1105.     tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
  1106.     tcc_define_symbol(s, "__arm_elf__", NULL);
  1107.     tcc_define_symbol(s, "__arm_elf", NULL);
  1108.     tcc_define_symbol(s, "arm_elf", NULL);
  1109.     tcc_define_symbol(s, "__arm__", NULL);
  1110.     tcc_define_symbol(s, "__arm", NULL);
  1111.     tcc_define_symbol(s, "arm", NULL);
  1112.     tcc_define_symbol(s, "__APCS_32__", NULL);
  1113.     tcc_define_symbol(s, "__ARMEL__", NULL);
  1114. #if defined(TCC_ARM_EABI)
  1115.     tcc_define_symbol(s, "__ARM_EABI__", NULL);
  1116. #endif
  1117. #if defined(TCC_ARM_HARDFLOAT)
  1118.     s->float_abi = ARM_HARD_FLOAT;
  1119.     tcc_define_symbol(s, "__ARM_PCS_VFP", NULL);
  1120. #else
  1121.     s->float_abi = ARM_SOFTFP_FLOAT;
  1122. #endif
  1123. #elif defined(TCC_TARGET_ARM64)
  1124.     tcc_define_symbol(s, "__aarch64__", NULL);
  1125. #endif
  1126.  
  1127. #ifdef TCC_TARGET_PE
  1128.     tcc_define_symbol(s, "_WIN32", NULL);
  1129. # ifdef TCC_TARGET_X86_64
  1130.     tcc_define_symbol(s, "_WIN64", NULL);
  1131. # endif
  1132. #else
  1133.     tcc_define_symbol(s, "__unix__", NULL);
  1134.     tcc_define_symbol(s, "__unix", NULL);
  1135.     tcc_define_symbol(s, "unix", NULL);
  1136. # if defined(__linux__)
  1137.     tcc_define_symbol(s, "__linux__", NULL);
  1138.     tcc_define_symbol(s, "__linux", NULL);
  1139. # endif
  1140. # if defined(__FreeBSD__)
  1141. #  define str(s) #s
  1142.     tcc_define_symbol(s, "__FreeBSD__", str( __FreeBSD__));
  1143. #  undef str
  1144. # endif
  1145. # if defined(__FreeBSD_kernel__)
  1146.     tcc_define_symbol(s, "__FreeBSD_kernel__", NULL);
  1147. # endif
  1148. #endif
  1149. # if defined(__NetBSD__)
  1150. #  define str(s) #s
  1151.     tcc_define_symbol(s, "__NetBSD__", str( __NetBSD__));
  1152. #  undef str
  1153. # endif
  1154.  
  1155.     /* TinyCC & gcc defines */
  1156. #if defined TCC_TARGET_PE && defined TCC_TARGET_X86_64
  1157.     tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long long");
  1158.     tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long long");
  1159. #else
  1160.     tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned long");
  1161.     tcc_define_symbol(s, "__PTRDIFF_TYPE__", "long");
  1162. #endif
  1163.  
  1164. #ifdef TCC_TARGET_PE
  1165.     tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
  1166.     tcc_define_symbol(s, "__WINT_TYPE__", "unsigned short");
  1167. #else
  1168.     tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
  1169.     /* wint_t is unsigned int by default, but (signed) int on BSDs
  1170.        and unsigned short on windows.  Other OSes might have still
  1171.        other conventions, sigh.  */
  1172. #if defined(__FreeBSD__) || defined (__FreeBSD_kernel__) || defined(__NetBSD__)
  1173.     tcc_define_symbol(s, "__WINT_TYPE__", "int");
  1174. #else
  1175.     tcc_define_symbol(s, "__WINT_TYPE__", "unsigned int");
  1176. #endif
  1177. #endif
  1178.  
  1179. #ifndef TCC_TARGET_PE
  1180.     /* glibc defines */
  1181.     tcc_define_symbol(s, "__REDIRECT(name, proto, alias)", "name proto __asm__ (#alias)");
  1182.     tcc_define_symbol(s, "__REDIRECT_NTH(name, proto, alias)", "name proto __asm__ (#alias) __THROW");
  1183.     /* paths for crt objects */
  1184.     tcc_split_path(s, (void ***)&s->crt_paths, &s->nb_crt_paths, CONFIG_TCC_CRTPREFIX);
  1185. #endif
  1186.  
  1187.     /* no section zero */
  1188.     dynarray_add((void ***)&s->sections, &s->nb_sections, NULL);
  1189.  
  1190.     /* create standard sections */
  1191.     text_section = new_section(s, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
  1192.     data_section = new_section(s, ".data", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
  1193.     bss_section = new_section(s, ".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
  1194.  
  1195.     /* symbols are always generated for linking stage */
  1196.     symtab_section = new_symtab(s, ".symtab", SHT_SYMTAB, 0,
  1197.                                 ".strtab",
  1198.                                 ".hashtab", SHF_PRIVATE);
  1199.     strtab_section = symtab_section->link;
  1200.     s->symtab = symtab_section;
  1201.  
  1202.     /* private symbol table for dynamic symbols */
  1203.     s->dynsymtab_section = new_symtab(s, ".dynsymtab", SHT_SYMTAB, SHF_PRIVATE,
  1204.                                       ".dynstrtab",
  1205.                                       ".dynhashtab", SHF_PRIVATE);
  1206.     s->alacarte_link = 1;
  1207.     s->nocommon = 1;
  1208.     s->warn_implicit_function_declaration = 1;
  1209.  
  1210. #ifdef CHAR_IS_UNSIGNED
  1211.     s->char_is_unsigned = 1;
  1212. #endif
  1213.     /* enable this if you want symbols with leading underscore on windows: */
  1214. #if 0 /* def TCC_TARGET_PE */
  1215.     s->leading_underscore = 1;
  1216. #endif
  1217. #if 0 /* TCC_TARGET_MEOS */
  1218.     s->leading_underscore = 1;
  1219. #endif
  1220. #ifdef TCC_TARGET_I386
  1221.     s->seg_size = 32;
  1222. #endif
  1223. #ifdef TCC_IS_NATIVE
  1224.     s->runtime_main = "main";
  1225. #endif
  1226.     return s;
  1227. }
  1228.  
  1229. LIBTCCAPI void tcc_delete(TCCState *s1)
  1230. {
  1231.     int i;
  1232.     int bench = s1->do_bench;
  1233.  
  1234.     tcc_cleanup();
  1235.  
  1236.     /* close a preprocessor output */
  1237.     if (s1->ppfp && s1->ppfp != stdout)
  1238.         fclose(s1->ppfp);
  1239.     if (s1->dffp && s1->dffp != s1->ppfp)
  1240.         fclose(s1->dffp);
  1241.  
  1242.     /* free all sections */
  1243.     for(i = 1; i < s1->nb_sections; i++)
  1244.         free_section(s1->sections[i]);
  1245.     dynarray_reset(&s1->sections, &s1->nb_sections);
  1246.  
  1247.     for(i = 0; i < s1->nb_priv_sections; i++)
  1248.         free_section(s1->priv_sections[i]);
  1249.     dynarray_reset(&s1->priv_sections, &s1->nb_priv_sections);
  1250.  
  1251.     /* free any loaded DLLs */
  1252. #ifdef TCC_IS_NATIVE
  1253.     for ( i = 0; i < s1->nb_loaded_dlls; i++) {
  1254.         DLLReference *ref = s1->loaded_dlls[i];
  1255.         if ( ref->handle )
  1256.             dlclose(ref->handle);
  1257.     }
  1258. #endif
  1259.  
  1260.     /* free loaded dlls array */
  1261.     dynarray_reset(&s1->loaded_dlls, &s1->nb_loaded_dlls);
  1262.  
  1263.     /* free library paths */
  1264.     dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
  1265.     dynarray_reset(&s1->crt_paths, &s1->nb_crt_paths);
  1266.  
  1267.     /* free include paths */
  1268.     dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
  1269.     dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
  1270.     dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
  1271.  
  1272.     tcc_free(s1->tcc_lib_path);
  1273.     tcc_free(s1->soname);
  1274.     tcc_free(s1->rpath);
  1275.     tcc_free(s1->init_symbol);
  1276.     tcc_free(s1->fini_symbol);
  1277.     tcc_free(s1->outfile);
  1278.     tcc_free(s1->deps_outfile);
  1279.     dynarray_reset(&s1->files, &s1->nb_files);
  1280.     dynarray_reset(&s1->target_deps, &s1->nb_target_deps);
  1281.     dynarray_reset(&s1->pragma_libs, &s1->nb_pragma_libs);
  1282.  
  1283. #ifdef TCC_IS_NATIVE
  1284. # ifdef HAVE_SELINUX
  1285.     munmap (s1->write_mem, s1->mem_size);
  1286.     munmap (s1->runtime_mem, s1->mem_size);
  1287. # else
  1288.     tcc_free(s1->runtime_mem);
  1289. # endif
  1290. #endif
  1291.  
  1292.     tcc_free(s1->sym_attrs);
  1293.     tcc_free(s1);
  1294.     tcc_memstats(bench);
  1295. }
  1296.  
  1297. LIBTCCAPI int tcc_add_include_path(TCCState *s, const char *pathname)
  1298. {
  1299.     tcc_split_path(s, (void ***)&s->include_paths, &s->nb_include_paths, pathname);
  1300.     return 0;
  1301. }
  1302.  
  1303. LIBTCCAPI int tcc_add_sysinclude_path(TCCState *s, const char *pathname)
  1304. {
  1305.     tcc_split_path(s, (void ***)&s->sysinclude_paths, &s->nb_sysinclude_paths, pathname);
  1306.     return 0;
  1307. }
  1308.  
  1309. ST_FUNC int tcc_add_file_internal(TCCState *s1, const char *filename, int flags, int filetype)
  1310. {
  1311.     ElfW(Ehdr) ehdr;
  1312.     int fd, ret, size;
  1313.  
  1314.     parse_flags = 0;
  1315. #ifdef CONFIG_TCC_ASM
  1316.     /* if .S file, define __ASSEMBLER__ like gcc does */
  1317.     if ((filetype == TCC_FILETYPE_ASM) || (filetype == TCC_FILETYPE_ASM_PP)) {
  1318.         tcc_define_symbol(s1, "__ASSEMBLER__", NULL);
  1319.         parse_flags = PARSE_FLAG_ASM_FILE;
  1320.     }
  1321. #endif
  1322.  
  1323.     /* open the file */
  1324.     ret = tcc_open(s1, filename);
  1325.     if (ret < 0) {
  1326.         if (flags & AFF_PRINT_ERROR)
  1327.             tcc_error_noabort("file '%s' not found", filename);
  1328.         return ret;
  1329.     }
  1330.  
  1331.     /* update target deps */
  1332.     dynarray_add((void ***)&s1->target_deps, &s1->nb_target_deps,
  1333.             tcc_strdup(filename));
  1334.  
  1335.     if (flags & AFF_PREPROCESS) {
  1336.         ret = tcc_preprocess(s1);
  1337.         goto the_end;
  1338.     }
  1339.  
  1340.     if (filetype == TCC_FILETYPE_C) {
  1341.         /* C file assumed */
  1342.         ret = tcc_compile(s1);
  1343.         goto the_end;
  1344.     }
  1345.  
  1346. #ifdef CONFIG_TCC_ASM
  1347.     if (filetype == TCC_FILETYPE_ASM_PP) {
  1348.         /* non preprocessed assembler */
  1349.         ret = tcc_assemble(s1, 1);
  1350.         goto the_end;
  1351.     }
  1352.  
  1353.     if (filetype == TCC_FILETYPE_ASM) {
  1354.         /* preprocessed assembler */
  1355.         ret = tcc_assemble(s1, 0);
  1356.         goto the_end;
  1357.     }
  1358. #endif
  1359.  
  1360.     fd = file->fd;
  1361.     /* assume executable format: auto guess file type */
  1362.     size = read(fd, &ehdr, sizeof(ehdr));
  1363.     lseek(fd, 0, SEEK_SET);
  1364.     if (size <= 0) {
  1365.         tcc_error_noabort("could not read header");
  1366.         goto the_end;
  1367.     }
  1368.  
  1369.     if (size == sizeof(ehdr) &&
  1370.         ehdr.e_ident[0] == ELFMAG0 &&
  1371.         ehdr.e_ident[1] == ELFMAG1 &&
  1372.         ehdr.e_ident[2] == ELFMAG2 &&
  1373.         ehdr.e_ident[3] == ELFMAG3) {
  1374.  
  1375.         /* do not display line number if error */
  1376.         file->line_num = 0;
  1377.         if (ehdr.e_type == ET_REL) {
  1378.             ret = tcc_load_object_file(s1, fd, 0);
  1379.             goto the_end;
  1380.  
  1381.         }
  1382. #if !defined(TCC_TARGET_PE) && !defined(TCC_TARGET_MEOS)
  1383.         if (ehdr.e_type == ET_DYN) {
  1384.             if (s1->output_type == TCC_OUTPUT_MEMORY) {
  1385. #ifdef TCC_IS_NATIVE
  1386.                 void *h;
  1387.                 h = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
  1388.                 if (h)
  1389. #endif
  1390.                     ret = 0;
  1391.             } else {
  1392.                 ret = tcc_load_dll(s1, fd, filename,
  1393.                                    (flags & AFF_REFERENCED_DLL) != 0);
  1394.             }
  1395.             goto the_end;
  1396.         }
  1397. #endif
  1398.         tcc_error_noabort("unrecognized ELF file");
  1399.         goto the_end;
  1400.     }
  1401.  
  1402.     if (memcmp((char *)&ehdr, ARMAG, 8) == 0) {
  1403.         file->line_num = 0; /* do not display line number if error */
  1404.         ret = tcc_load_archive(s1, fd);
  1405.         goto the_end;
  1406.     }
  1407.  
  1408. #ifdef TCC_TARGET_COFF
  1409.     if (*(uint16_t *)(&ehdr) == COFF_C67_MAGIC) {
  1410.         ret = tcc_load_coff(s1, fd);
  1411.         goto the_end;
  1412.     }
  1413. #endif
  1414.  
  1415. #if defined(TCC_TARGET_PE) ||  defined(TCC_TARGET_MEOS)
  1416.     ret = pe_load_file(s1, filename, fd);
  1417. #else
  1418.     /* as GNU ld, consider it is an ld script if not recognized */
  1419.     ret = tcc_load_ldscript(s1);
  1420. #endif
  1421.     if (ret < 0)
  1422.         tcc_error_noabort("unrecognized file type");
  1423.  
  1424. the_end:
  1425.     tcc_close();
  1426.     return ret;
  1427. }
  1428.  
  1429. LIBTCCAPI int tcc_add_file(TCCState *s, const char *filename, int filetype)
  1430. {
  1431.     if (s->output_type == TCC_OUTPUT_PREPROCESS)
  1432.         return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | AFF_PREPROCESS, filetype);
  1433.     else
  1434.         return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR, filetype);
  1435. }
  1436.  
  1437. LIBTCCAPI int tcc_add_library_path(TCCState *s, const char *pathname)
  1438. {
  1439.     tcc_split_path(s, (void ***)&s->library_paths, &s->nb_library_paths, pathname);
  1440.     return 0;
  1441. }
  1442.  
  1443. static int tcc_add_library_internal(TCCState *s, const char *fmt,
  1444.     const char *filename, int flags, char **paths, int nb_paths)
  1445. {
  1446.     char buf[1024];
  1447.     int i;
  1448.  
  1449.     for(i = 0; i < nb_paths; i++) {
  1450.         snprintf(buf, sizeof(buf), fmt, paths[i], filename);
  1451. //printf("added lib [%s]\n", buf);
  1452.         if (tcc_add_file_internal(s, buf, flags, TCC_FILETYPE_BINARY) == 0)
  1453.             return 0;
  1454.     }
  1455.     return -1;
  1456. }
  1457.  
  1458. #if !defined(TCC_TARGET_PE) && !defined(TCC_TARGET_MEOS)
  1459. /* find and load a dll. Return non zero if not found */
  1460. /* XXX: add '-rpath' option support ? */
  1461. ST_FUNC int tcc_add_dll(TCCState *s, const char *filename, int flags)
  1462. {
  1463.     return tcc_add_library_internal(s, "%s/%s", filename, flags,
  1464.         s->library_paths, s->nb_library_paths);
  1465. }
  1466. #endif
  1467.  
  1468. ST_FUNC int tcc_add_crt(TCCState *s, const char *filename)
  1469. {
  1470.     if (-1 == tcc_add_library_internal(s, "%s/%s",
  1471.         filename, 0, s->crt_paths, s->nb_crt_paths))
  1472.         tcc_error_noabort("file '%s' not found", filename);
  1473.     return 0;
  1474. }
  1475.  
  1476. /* the library name is the same as the argument of the '-l' option */
  1477. LIBTCCAPI int tcc_add_library(TCCState *s, const char *libraryname)
  1478. {
  1479. #if defined(TCC_TARGET_PE) || defined(TCC_TARGET_MEOS)
  1480.     const char *libs[] = { "%s/%s.def", "%s/lib%s.def", "%s/%s.dll", "%s/lib%s.dll", "%s/lib%s.a", NULL };
  1481.     const char **pp = s->static_link ? libs + 4 : libs;
  1482. #else
  1483.     const char *libs[] = { "%s/lib%s.so", "%s/lib%s.a", NULL };
  1484.     const char **pp = s->static_link ? libs + 1 : libs;
  1485. #endif
  1486.     while (*pp) {
  1487.         if (0 == tcc_add_library_internal(s, *pp,
  1488.             libraryname, 0, s->library_paths, s->nb_library_paths))
  1489.             return 0;
  1490.         ++pp;
  1491.     }
  1492.     return -1;
  1493. }
  1494.  
  1495. PUB_FUNC int tcc_add_library_err(TCCState *s, const char *libname)
  1496. {
  1497.     int ret = tcc_add_library(s, libname);
  1498.     if (ret < 0)
  1499.         tcc_error_noabort("cannot find library 'lib%s'", libname);
  1500.     return ret;
  1501. }
  1502.  
  1503. /* habdle #pragma comment(lib,) */
  1504. ST_FUNC void tcc_add_pragma_libs(TCCState *s1)
  1505. {
  1506.     int i;
  1507.     for (i = 0; i < s1->nb_pragma_libs; i++)
  1508.         tcc_add_library_err(s1, s1->pragma_libs[i]);
  1509. }
  1510.  
  1511. LIBTCCAPI int tcc_add_symbol(TCCState *s, const char *name, const void *val)
  1512. {
  1513. #if defined(TCC_TARGET_PE) || defined(TCC_TARGET_MEOS)
  1514.     /* On x86_64 'val' might not be reachable with a 32bit offset.
  1515.        So it is handled here as if it were in a DLL. */
  1516.     pe_putimport(s, 0, name, (uintptr_t)val);
  1517. #else
  1518.     add_elf_sym(symtab_section, (uintptr_t)val, 0,
  1519.         ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
  1520.         SHN_ABS, name);
  1521. #endif
  1522.     return 0;
  1523. }
  1524.  
  1525.  
  1526. /* Windows stat* ( https://msdn.microsoft.com/en-us/library/14h5k7ff.aspx ):
  1527.  * - st_gid, st_ino, st_uid: only valid on "unix" file systems (not FAT, NTFS, etc)
  1528.  * - st_atime, st_ctime: not valid on FAT, valid on NTFS.
  1529.  * - Other fields should be reasonably compatible (and S_ISDIR should work).
  1530.  *
  1531.  * BY_HANDLE_FILE_INFORMATION ( https://msdn.microsoft.com/en-us/library/windows/desktop/aa363788%28v=vs.85%29.aspx ):
  1532.  * - File index (combined nFileIndexHigh and nFileIndexLow) _may_ change when the file is opened.
  1533.  *   - But on NTFS: it's guaranteed to be the same value until the file is deleted.
  1534.  * - On windows server 2012 there's a 128b file id, and the 64b one via
  1535.  *   nFileIndex* is not guaranteed to be unique.
  1536.  *
  1537.  * - MS Docs suggest to that volume number with the file index could be used to
  1538.  *   check if two handles refer to the same file.
  1539.  */
  1540. #ifndef _WIN32
  1541. typedef struct stat                file_info_t;
  1542. #else
  1543. typedef BY_HANDLE_FILE_INFORMATION file_info_t;
  1544. #endif
  1545.  
  1546. int get_file_info(const char *fname, file_info_t *out_info)
  1547. {
  1548. #ifndef _WIN32
  1549.     return stat(fname, out_info);
  1550. #else
  1551.     int rv = 1;
  1552.     HANDLE h = CreateFile(fname, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
  1553.                           FILE_ATTRIBUTE_NORMAL|FILE_FLAG_BACKUP_SEMANTICS, NULL);
  1554.  
  1555.     if (h != INVALID_HANDLE_VALUE) {
  1556.         rv = !GetFileInformationByHandle(h, out_info);
  1557.         CloseHandle(h);
  1558.     }
  1559.     return rv;
  1560. #endif
  1561. }
  1562.  
  1563. int is_dir(file_info_t *info)
  1564. {
  1565. #ifndef _WIN32
  1566.     return S_ISDIR(info->st_mode);
  1567. #else
  1568.     return (info->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ==
  1569.            FILE_ATTRIBUTE_DIRECTORY;
  1570. #endif
  1571. }
  1572.  
  1573. int is_same_file(const file_info_t *fi1, const file_info_t *fi2)
  1574. {
  1575. #ifndef _WIN32
  1576.     return fi1->st_dev == fi2->st_dev &&
  1577.            fi1->st_ino == fi2->st_ino;
  1578. #else
  1579.     return fi1->dwVolumeSerialNumber == fi2->dwVolumeSerialNumber &&
  1580.            fi1->nFileIndexHigh       == fi2->nFileIndexHigh &&
  1581.            fi1->nFileIndexLow        == fi2->nFileIndexLow;
  1582. #endif
  1583. }
  1584.  
  1585. static void
  1586. tcc_normalize_inc_dirs_aux(file_info_t *stats, size_t *pnum, char **path)
  1587. {
  1588.     size_t i, num = *pnum;
  1589.     if (get_file_info(*path, &stats[num]) || !is_dir(&stats[num]))
  1590.         goto remove;
  1591.     for (i = 0; i < num; i++)
  1592.         if (is_same_file(&stats[i], &stats[num]))
  1593.             goto remove;
  1594.     *pnum = num + 1;
  1595.     return;
  1596.  remove:
  1597.     tcc_free(*path);
  1598.     *path = 0;
  1599. }
  1600.  
  1601. /* Remove non-existent and duplicate directories from include paths. */
  1602. ST_FUNC void tcc_normalize_inc_dirs(TCCState *s)
  1603. {
  1604.     file_info_t *stats =
  1605.         tcc_malloc(((size_t)s->nb_sysinclude_paths + s->nb_include_paths) *
  1606.                    sizeof(*stats));
  1607.     size_t i, num = 0;
  1608.     for (i = 0; i < s->nb_sysinclude_paths; i++)
  1609.         tcc_normalize_inc_dirs_aux(stats, &num, &s->sysinclude_paths[i]);
  1610.     for (i = 0; i < s->nb_include_paths; i++)
  1611.         tcc_normalize_inc_dirs_aux(stats, &num, &s->include_paths[i]);
  1612.     tcc_free(stats);
  1613. }
  1614.  
  1615. LIBTCCAPI int tcc_set_output_type(TCCState *s, int output_type)
  1616. {
  1617.     s->output_type = output_type;
  1618.  
  1619.     if (s->output_type == TCC_OUTPUT_PREPROCESS) {
  1620.         if (!s->outfile) {
  1621.             s->ppfp = stdout;
  1622.         } else {
  1623.             s->ppfp = fopen(s->outfile, "w");
  1624.             if (!s->ppfp)
  1625.                 tcc_error("could not write '%s'", s->outfile);
  1626.         }
  1627.         s->dffp = s->ppfp;
  1628.         if (s->dflag == 'M')
  1629.             s->ppfp = NULL;
  1630.     }
  1631.     if (s->option_C && !s->ppfp)
  1632.         s->option_C = 0;
  1633.  
  1634.     if (!s->nostdinc) {
  1635.         /* default include paths */
  1636.         /* -isystem paths have already been handled */
  1637.         tcc_add_sysinclude_path(s, CONFIG_TCC_SYSINCLUDEPATHS);
  1638.     }
  1639.  
  1640.     /* if bound checking, then add corresponding sections */
  1641. #ifdef CONFIG_TCC_BCHECK
  1642.     if (s->do_bounds_check) {
  1643.         /* define symbol */
  1644.         tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
  1645.         /* create bounds sections */
  1646.         bounds_section = new_section(s, ".bounds",
  1647.                                      SHT_PROGBITS, SHF_ALLOC);
  1648.         lbounds_section = new_section(s, ".lbounds",
  1649.                                       SHT_PROGBITS, SHF_ALLOC);
  1650.     }
  1651. #endif
  1652.  
  1653.     if (s->char_is_unsigned) {
  1654.         tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
  1655.     }
  1656.  
  1657.     /* add debug sections */
  1658.     if (s->do_debug) {
  1659.         /* stab symbols */
  1660.         stab_section = new_section(s, ".stab", SHT_PROGBITS, 0);
  1661.         stab_section->sh_entsize = sizeof(Stab_Sym);
  1662.         stabstr_section = new_section(s, ".stabstr", SHT_STRTAB, 0);
  1663.         put_elf_str(stabstr_section, "");
  1664.         stab_section->link = stabstr_section;
  1665.         /* put first entry */
  1666.         put_stabs("", 0, 0, 0, 0);
  1667.     }
  1668.  
  1669.     tcc_add_library_path(s, CONFIG_TCC_LIBPATHS);
  1670. #ifdef TCC_TARGET_PE
  1671. # ifdef _WIN32
  1672.     tcc_add_systemdir(s);
  1673. # endif
  1674. #elif defined(TCC_TARGET_MEOS)
  1675.     if (s->output_type != TCC_OUTPUT_OBJ && !s->nostdlib)
  1676.     {
  1677.         tcc_add_crt(s,"start.o");
  1678. //        tcc_add_library(s,"ck"); // adding libck.a dont work, because need to be added last
  1679.     }
  1680. #else
  1681.     /* add libc crt1/crti objects */
  1682.     if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
  1683.         !s->nostdlib) {
  1684.         if (output_type != TCC_OUTPUT_DLL)
  1685.             tcc_add_crt(s, "crt1.o");
  1686.         tcc_add_crt(s, "crti.o");
  1687.     }
  1688. #endif
  1689.  
  1690. #ifdef CONFIG_TCC_BCHECK
  1691.     if (s->do_bounds_check && (output_type == TCC_OUTPUT_EXE))
  1692.     {
  1693.         /* force a bcheck.o linking */
  1694.         addr_t func = TOK___bound_init;
  1695.         Sym *sym = external_global_sym(func, &func_old_type, 0);
  1696.         if (!sym->c)
  1697.             put_extern_sym(sym, NULL, 0, 0);
  1698.     }
  1699. #endif
  1700.  
  1701.     if (s->normalize_inc_dirs)
  1702.         tcc_normalize_inc_dirs(s);
  1703.     if (s->output_type == TCC_OUTPUT_PREPROCESS)
  1704.         print_defines();
  1705.  
  1706.     return 0;
  1707. }
  1708.  
  1709. LIBTCCAPI void tcc_set_lib_path(TCCState *s, const char *path)
  1710. {
  1711.     tcc_free(s->tcc_lib_path);
  1712.     s->tcc_lib_path = tcc_strdup(path);
  1713. }
  1714.  
  1715. #define WD_ALL    0x0001 /* warning is activated when using -Wall */
  1716. #define FD_INVERT 0x0002 /* invert value before storing */
  1717.  
  1718. typedef struct FlagDef {
  1719.     uint16_t offset;
  1720.     uint16_t flags;
  1721.     const char *name;
  1722. } FlagDef;
  1723.  
  1724. static const FlagDef warning_defs[] = {
  1725.     { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
  1726.     { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
  1727.     { offsetof(TCCState, warn_error), 0, "error" },
  1728.     { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
  1729.       "implicit-function-declaration" },
  1730. };
  1731.  
  1732. ST_FUNC int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
  1733.                     const char *name, int value)
  1734. {
  1735.     int i;
  1736.     const FlagDef *p;
  1737.     const char *r;
  1738.  
  1739.     r = name;
  1740.     if (r[0] == 'n' && r[1] == 'o' && r[2] == '-') {
  1741.         r += 3;
  1742.         value = !value;
  1743.     }
  1744.     for(i = 0, p = flags; i < nb_flags; i++, p++) {
  1745.         if (!strcmp(r, p->name))
  1746.             goto found;
  1747.     }
  1748.     return -1;
  1749.  found:
  1750.     if (p->flags & FD_INVERT)
  1751.         value = !value;
  1752.     *(int *)((uint8_t *)s + p->offset) = value;
  1753.     return 0;
  1754. }
  1755.  
  1756. /* set/reset a warning */
  1757. static int tcc_set_warning(TCCState *s, const char *warning_name, int value)
  1758. {
  1759.     int i;
  1760.     const FlagDef *p;
  1761.  
  1762.     if (!strcmp(warning_name, "all")) {
  1763.         for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
  1764.             if (p->flags & WD_ALL)
  1765.                 *(int *)((uint8_t *)s + p->offset) = 1;
  1766.         }
  1767.                 s->warn_unsupported = 1;  // siemargl. was unused flag about compiler features
  1768.         return 0;
  1769.     } else {
  1770.         return set_flag(s, warning_defs, countof(warning_defs),
  1771.                         warning_name, value);
  1772.     }
  1773. }
  1774.  
  1775. static const FlagDef flag_defs[] = {
  1776.     { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
  1777.     { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
  1778.     { offsetof(TCCState, nocommon), FD_INVERT, "common" },
  1779.     { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
  1780.     { offsetof(TCCState, ms_extensions), 0, "ms-extensions" },
  1781.     { offsetof(TCCState, old_struct_init_code), 0, "old-struct-init-code" },
  1782.     { offsetof(TCCState, dollars_in_identifiers), 0, "dollars-in-identifiers" },
  1783.     { offsetof(TCCState, normalize_inc_dirs), 0, "normalize-inc-dirs" },
  1784. };
  1785.  
  1786. /* set/reset a flag */
  1787. static int tcc_set_flag(TCCState *s, const char *flag_name, int value)
  1788. {
  1789.     return set_flag(s, flag_defs, countof(flag_defs),
  1790.                     flag_name, value);
  1791. }
  1792.  
  1793.  
  1794. static int strstart(const char *val, const char **str)
  1795. {
  1796.     const char *p, *q;
  1797.     p = *str;
  1798.     q = val;
  1799.     while (*q) {
  1800.         if (*p != *q)
  1801.             return 0;
  1802.         p++;
  1803.         q++;
  1804.     }
  1805.     *str = p;
  1806.     return 1;
  1807. }
  1808.  
  1809. /* Like strstart, but automatically takes into account that ld options can
  1810.  *
  1811.  * - start with double or single dash (e.g. '--soname' or '-soname')
  1812.  * - arguments can be given as separate or after '=' (e.g. '-Wl,-soname,x.so'
  1813.  *   or '-Wl,-soname=x.so')
  1814.  *
  1815.  * you provide `val` always in 'option[=]' form (no leading -)
  1816.  */
  1817. static int link_option(const char *str, const char *val, const char **ptr)
  1818. {
  1819.     const char *p, *q;
  1820.  
  1821.     /* there should be 1 or 2 dashes */
  1822.     if (*str++ != '-')
  1823.         return 0;
  1824.     if (*str == '-')
  1825.         str++;
  1826.  
  1827.     /* then str & val should match (potentialy up to '=') */
  1828.     p = str;
  1829.     q = val;
  1830.  
  1831.     while (*q != '\0' && *q != '=') {
  1832.         if (*p != *q)
  1833.             return 0;
  1834.         p++;
  1835.         q++;
  1836.     }
  1837.  
  1838.     /* '=' near eos means ',' or '=' is ok */
  1839.     if (*q == '=') {
  1840.         if (*p != ',' && *p != '=')
  1841.             return 0;
  1842.         p++;
  1843.         q++;
  1844.     }
  1845.  
  1846.     if (ptr)
  1847.         *ptr = p;
  1848.     return 1;
  1849. }
  1850.  
  1851. static const char *skip_linker_arg(const char **str)
  1852. {
  1853.     const char *s1 = *str;
  1854.     const char *s2 = strchr(s1, ',');
  1855.     *str = s2 ? s2++ : (s2 = s1 + strlen(s1));
  1856.     return s2;
  1857. }
  1858.  
  1859. static char *copy_linker_arg(const char *p)
  1860. {
  1861.     const char *q = p;
  1862.     skip_linker_arg(&q);
  1863.     return pstrncpy(tcc_malloc(q - p + 1), p, q - p);
  1864. }
  1865.  
  1866. /* set linker options */
  1867. static int tcc_set_linker(TCCState *s, const char *option)
  1868. {
  1869.     while (option && *option) {
  1870.  
  1871.         const char *p = option;
  1872.         char *end = NULL;
  1873.         int ignoring = 0;
  1874.  
  1875.         if (link_option(option, "Bsymbolic", &p)) {
  1876.             s->symbolic = 1;
  1877.         } else if (link_option(option, "nostdlib", &p)) {
  1878.             s->nostdlib = 1;
  1879.         } else if (link_option(option, "fini=", &p)) {
  1880.             s->fini_symbol = copy_linker_arg(p);
  1881.             ignoring = 1;
  1882.         } else if (link_option(option, "image-base=", &p)
  1883.                 || link_option(option, "Ttext=", &p)) {
  1884.             s->text_addr = strtoull(p, &end, 16);
  1885.             s->has_text_addr = 1;
  1886.         } else if (link_option(option, "init=", &p)) {
  1887.             s->init_symbol = copy_linker_arg(p);
  1888.             ignoring = 1;
  1889.         } else if (link_option(option, "oformat=", &p)) {
  1890. #if defined(TCC_TARGET_PE)
  1891.             if (strstart("pe-", &p)) {
  1892. #elif defined(TCC_TARGET_ARM64) || defined(TCC_TARGET_X86_64)
  1893.             if (strstart("elf64-", &p)) {
  1894. #else
  1895.             if (strstart("elf32-", &p)) {
  1896. #endif
  1897.                 s->output_format = TCC_OUTPUT_FORMAT_ELF;
  1898.             } else if (!strcmp(p, "binary")) {
  1899.                 s->output_format = TCC_OUTPUT_FORMAT_BINARY;
  1900. #ifdef TCC_TARGET_COFF
  1901.             } else if (!strcmp(p, "coff")) {
  1902.                 s->output_format = TCC_OUTPUT_FORMAT_COFF;
  1903. #endif
  1904.             } else
  1905.                 goto err;
  1906.  
  1907.         } else if (link_option(option, "as-needed", &p)) {
  1908.             ignoring = 1;
  1909.         } else if (link_option(option, "O", &p)) {
  1910.             ignoring = 1;
  1911.         } else if (link_option(option, "rpath=", &p)) {
  1912.             s->rpath = copy_linker_arg(p);
  1913.         } else if (link_option(option, "section-alignment=", &p)) {
  1914.             s->section_align = strtoul(p, &end, 16);
  1915.         } else if (link_option(option, "soname=", &p)) {
  1916.             s->soname = copy_linker_arg(p);
  1917. #ifdef TCC_TARGET_PE
  1918.         } else if (link_option(option, "file-alignment=", &p)) {
  1919.             s->pe_file_align = strtoul(p, &end, 16);
  1920.         } else if (link_option(option, "stack=", &p)) {
  1921.             s->pe_stack_size = strtoul(p, &end, 10);
  1922.         } else if (link_option(option, "subsystem=", &p)) {
  1923. #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
  1924.             if (!strcmp(p, "native")) {
  1925.                 s->pe_subsystem = 1;
  1926.             } else if (!strcmp(p, "console")) {
  1927.                 s->pe_subsystem = 3;
  1928.             } else if (!strcmp(p, "gui")) {
  1929.                 s->pe_subsystem = 2;
  1930.             } else if (!strcmp(p, "posix")) {
  1931.                 s->pe_subsystem = 7;
  1932.             } else if (!strcmp(p, "efiapp")) {
  1933.                 s->pe_subsystem = 10;
  1934.             } else if (!strcmp(p, "efiboot")) {
  1935.                 s->pe_subsystem = 11;
  1936.             } else if (!strcmp(p, "efiruntime")) {
  1937.                 s->pe_subsystem = 12;
  1938.             } else if (!strcmp(p, "efirom")) {
  1939.                 s->pe_subsystem = 13;
  1940. #elif defined(TCC_TARGET_ARM)
  1941.             if (!strcmp(p, "wince")) {
  1942.                 s->pe_subsystem = 9;
  1943. #endif
  1944.             } else
  1945.                 goto err;
  1946. #endif
  1947.         } else
  1948.             goto err;
  1949.  
  1950.         if (ignoring && s->warn_unsupported) err: {
  1951.             char buf[100], *e;
  1952.             pstrcpy(buf, sizeof buf, e = copy_linker_arg(option)), tcc_free(e);
  1953.             if (ignoring)
  1954.                 tcc_warning("unsupported linker option '%s'", buf);
  1955.             else
  1956.                 tcc_error("unsupported linker option '%s'", buf);
  1957.         }
  1958.         option = skip_linker_arg(&p);
  1959.     }
  1960.     return 0;
  1961. }
  1962.  
  1963. typedef struct TCCOption {
  1964.     const char *name;
  1965.     uint16_t index;
  1966.     uint16_t flags;
  1967. } TCCOption;
  1968.  
  1969. enum {
  1970.     TCC_OPTION_HELP,
  1971.     TCC_OPTION_I,
  1972.     TCC_OPTION_D,
  1973.     TCC_OPTION_U,
  1974.     TCC_OPTION_P,
  1975.     TCC_OPTION_L,
  1976.     TCC_OPTION_B,
  1977.     TCC_OPTION_l,
  1978.     TCC_OPTION_bench,
  1979.     TCC_OPTION_bt,
  1980.     TCC_OPTION_b,
  1981.     TCC_OPTION_g,
  1982.     TCC_OPTION_c,
  1983.     TCC_OPTION_C,
  1984.     TCC_OPTION_dumpversion,
  1985.     TCC_OPTION_d,
  1986.     TCC_OPTION_float_abi,
  1987.     TCC_OPTION_static,
  1988.     TCC_OPTION_std,
  1989.     TCC_OPTION_shared,
  1990.     TCC_OPTION_soname,
  1991.     TCC_OPTION_o,
  1992.     TCC_OPTION_r,
  1993.     TCC_OPTION_s,
  1994.     TCC_OPTION_traditional,
  1995.     TCC_OPTION_Wl,
  1996.     TCC_OPTION_W,
  1997.     TCC_OPTION_O,
  1998.     TCC_OPTION_m,
  1999.     TCC_OPTION_f,
  2000.     TCC_OPTION_isystem,
  2001.     TCC_OPTION_iwithprefix,
  2002.     TCC_OPTION_nostdinc,
  2003.     TCC_OPTION_nostdlib,
  2004.     TCC_OPTION_print_search_dirs,
  2005.     TCC_OPTION_rdynamic,
  2006.     TCC_OPTION_pedantic,
  2007.     TCC_OPTION_pthread,
  2008.     TCC_OPTION_run,
  2009.     TCC_OPTION_v,
  2010.     TCC_OPTION_w,
  2011.     TCC_OPTION_pipe,
  2012.     TCC_OPTION_E,
  2013.     TCC_OPTION_MD,
  2014.     TCC_OPTION_MF,
  2015.     TCC_OPTION_x
  2016. };
  2017.  
  2018. #define TCC_OPTION_HAS_ARG 0x0001
  2019. #define TCC_OPTION_NOSEP   0x0002 /* cannot have space before option and arg */
  2020.  
  2021. static const TCCOption tcc_options[] = {
  2022.     { "h", TCC_OPTION_HELP, 0 },
  2023.     { "-help", TCC_OPTION_HELP, 0 },
  2024.     { "?", TCC_OPTION_HELP, 0 },
  2025.     { "I", TCC_OPTION_I, TCC_OPTION_HAS_ARG },
  2026.     { "D", TCC_OPTION_D, TCC_OPTION_HAS_ARG },
  2027.     { "U", TCC_OPTION_U, TCC_OPTION_HAS_ARG },
  2028.     { "P", TCC_OPTION_P, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
  2029.     { "L", TCC_OPTION_L, TCC_OPTION_HAS_ARG },
  2030.     { "B", TCC_OPTION_B, TCC_OPTION_HAS_ARG },
  2031.     { "l", TCC_OPTION_l, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
  2032.     { "bench", TCC_OPTION_bench, 0 },
  2033. #ifdef CONFIG_TCC_BACKTRACE
  2034.     { "bt", TCC_OPTION_bt, TCC_OPTION_HAS_ARG },
  2035. #endif
  2036. #ifdef CONFIG_TCC_BCHECK
  2037.     { "b", TCC_OPTION_b, 0 },
  2038. #endif
  2039.     { "g", TCC_OPTION_g, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
  2040.     { "c", TCC_OPTION_c, 0 },
  2041.     { "C", TCC_OPTION_C, 0 },
  2042.     { "dumpversion", TCC_OPTION_dumpversion, 0},
  2043.     { "d", TCC_OPTION_d, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
  2044. #ifdef TCC_TARGET_ARM
  2045.     { "mfloat-abi", TCC_OPTION_float_abi, TCC_OPTION_HAS_ARG },
  2046. #endif
  2047.     { "static", TCC_OPTION_static, 0 },
  2048.     { "std", TCC_OPTION_std, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
  2049.     { "shared", TCC_OPTION_shared, 0 },
  2050.     { "soname", TCC_OPTION_soname, TCC_OPTION_HAS_ARG },
  2051.     { "o", TCC_OPTION_o, TCC_OPTION_HAS_ARG },
  2052.     { "pedantic", TCC_OPTION_pedantic, 0},
  2053.     { "pthread", TCC_OPTION_pthread, 0},
  2054.     { "run", TCC_OPTION_run, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
  2055.     { "rdynamic", TCC_OPTION_rdynamic, 0 },
  2056.     { "r", TCC_OPTION_r, 0 },
  2057.     { "s", TCC_OPTION_s, 0 },
  2058.     { "traditional", TCC_OPTION_traditional, 0 },
  2059.     { "Wl,", TCC_OPTION_Wl, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
  2060.     { "W", TCC_OPTION_W, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
  2061.     { "O", TCC_OPTION_O, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
  2062.     { "m", TCC_OPTION_m, TCC_OPTION_HAS_ARG },
  2063.     { "f", TCC_OPTION_f, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
  2064.     { "isystem", TCC_OPTION_isystem, TCC_OPTION_HAS_ARG },
  2065.     { "iwithprefix", TCC_OPTION_iwithprefix, TCC_OPTION_HAS_ARG },
  2066.     { "nostdinc", TCC_OPTION_nostdinc, 0 },
  2067.     { "nostdlib", TCC_OPTION_nostdlib, 0 },
  2068.     { "print-search-dirs", TCC_OPTION_print_search_dirs, 0 },
  2069.     { "v", TCC_OPTION_v, TCC_OPTION_HAS_ARG | TCC_OPTION_NOSEP },
  2070.     { "w", TCC_OPTION_w, 0 },
  2071.     { "pipe", TCC_OPTION_pipe, 0},
  2072.     { "E", TCC_OPTION_E, 0},
  2073.     { "MD", TCC_OPTION_MD, 0},
  2074.     { "MF", TCC_OPTION_MF, TCC_OPTION_HAS_ARG },
  2075.     { "x", TCC_OPTION_x, TCC_OPTION_HAS_ARG },
  2076.     { NULL, 0, 0 },
  2077. };
  2078.  
  2079. static void parse_option_D(TCCState *s1, const char *optarg)
  2080. {
  2081.     char *sym = tcc_strdup(optarg);
  2082.     char *value = strchr(sym, '=');
  2083.     if (value)
  2084.         *value++ = '\0';
  2085.     tcc_define_symbol(s1, sym, value);
  2086.     tcc_free(sym);
  2087. }
  2088.  
  2089. static void args_parser_add_file(TCCState *s, const char* filename, int filetype)
  2090. {
  2091.     int len = strlen(filename);
  2092.     char *p = tcc_malloc(len + 2);
  2093.     if (filetype) {
  2094.         *p = filetype;
  2095.     }
  2096.     else {
  2097.         /* use a file extension to detect a filetype */
  2098.         const char *ext = tcc_fileextension(filename);
  2099.         if (ext[0]) {
  2100.             ext++;
  2101.             if (!strcmp(ext, "S"))
  2102.                 *p = TCC_FILETYPE_ASM_PP;
  2103.             else
  2104.             if (!strcmp(ext, "s"))
  2105.                 *p = TCC_FILETYPE_ASM;
  2106.             else
  2107.             if (!PATHCMP(ext, "c") || !PATHCMP(ext, "i"))
  2108.                 *p = TCC_FILETYPE_C;
  2109.             else
  2110.                 *p = TCC_FILETYPE_BINARY;
  2111.         }
  2112.         else {
  2113.             *p = TCC_FILETYPE_C;
  2114.         }
  2115.     }
  2116.     strcpy(p+1, filename);
  2117.     dynarray_add((void ***)&s->files, &s->nb_files, p);
  2118. }
  2119.  
  2120. ST_FUNC int tcc_parse_args1(TCCState *s, int argc, char **argv)
  2121. {
  2122.     const TCCOption *popt;
  2123.     const char *optarg, *r;
  2124.     int optind = 0;
  2125.     ParseArgsState *pas = s->parse_args_state;
  2126.  
  2127.     while (optind < argc) {
  2128.  
  2129.         r = argv[optind++];
  2130.         if (r[0] != '-' || r[1] == '\0') {
  2131.             /* handle list files */
  2132.             if (r[0] == '@' && r[1]) {
  2133.                 char buf[sizeof file->filename], *p;
  2134.                 char **argv = NULL;
  2135.                 int argc = 0;
  2136.                 FILE *fp;
  2137.  
  2138.                 fp = fopen(r + 1, "rb");
  2139.                 if (fp == NULL)
  2140.                     tcc_error("list file '%s' not found", r + 1);
  2141.                 while (fgets(buf, sizeof buf, fp)) {
  2142.                     p = trimfront(trimback(buf, strchr(buf, 0)));
  2143.                     if (0 == *p || ';' == *p)
  2144.                         continue;
  2145.                     dynarray_add((void ***)&argv, &argc, tcc_strdup(p));
  2146.                 }
  2147.                 fclose(fp);
  2148.                 tcc_parse_args1(s, argc, argv);
  2149.                 dynarray_reset(&argv, &argc);
  2150.             } else {
  2151.                 args_parser_add_file(s, r, pas->filetype);
  2152.                 if (pas->run) {
  2153.                     optind--;
  2154.                     /* argv[0] will be this file */
  2155.                     break;
  2156.                 }
  2157.             }
  2158.             continue;
  2159.         }
  2160.  
  2161.         /* find option in table */
  2162.         for(popt = tcc_options; ; ++popt) {
  2163.             const char *p1 = popt->name;
  2164.             const char *r1 = r + 1;
  2165.             if (p1 == NULL)
  2166.                 tcc_error("invalid option -- '%s'", r);
  2167.             if (!strstart(p1, &r1))
  2168.                 continue;
  2169.             optarg = r1;
  2170.             if (popt->flags & TCC_OPTION_HAS_ARG) {
  2171.                 if (*r1 == '\0' && !(popt->flags & TCC_OPTION_NOSEP)) {
  2172.                     if (optind >= argc)
  2173.                         tcc_error("argument to '%s' is missing", r);
  2174.                     optarg = argv[optind++];
  2175.                 }
  2176.             } else if (*r1 != '\0')
  2177.                 continue;
  2178.             break;
  2179.         }
  2180.  
  2181.         switch(popt->index) {
  2182.         case TCC_OPTION_HELP:
  2183.             return 0;
  2184.         case TCC_OPTION_I:
  2185.             tcc_add_include_path(s, optarg);
  2186.             break;
  2187.         case TCC_OPTION_D:
  2188.             parse_option_D(s, optarg);
  2189.             break;
  2190.         case TCC_OPTION_U:
  2191.             tcc_undefine_symbol(s, optarg);
  2192.             break;
  2193.         case TCC_OPTION_L:
  2194.             tcc_add_library_path(s, optarg);
  2195.             break;
  2196.         case TCC_OPTION_B:
  2197.             /* set tcc utilities path (mainly for tcc development) */
  2198.             tcc_set_lib_path(s, optarg);
  2199.             break;
  2200.         case TCC_OPTION_l:
  2201.             args_parser_add_file(s, r, TCC_FILETYPE_BINARY);
  2202.             s->nb_libraries++;
  2203.             break;
  2204.         case TCC_OPTION_pthread:
  2205.             parse_option_D(s, "_REENTRANT");
  2206.             pas->pthread = 1;
  2207.             break;
  2208.         case TCC_OPTION_bench:
  2209.             s->do_bench = 1;
  2210.             break;
  2211. #ifdef CONFIG_TCC_BACKTRACE
  2212.         case TCC_OPTION_bt:
  2213.             tcc_set_num_callers(atoi(optarg));
  2214.             break;
  2215. #endif
  2216. #ifdef CONFIG_TCC_BCHECK
  2217.         case TCC_OPTION_b:
  2218.             s->do_bounds_check = 1;
  2219.             s->do_debug = 1;
  2220.             break;
  2221. #endif
  2222.         case TCC_OPTION_g:
  2223.             s->do_debug = 1;
  2224.             break;
  2225.         case TCC_OPTION_c:
  2226.             if (s->output_type)
  2227.                 tcc_warning("-c: some compiler action already specified (%d)", s->output_type);
  2228.             s->output_type = TCC_OUTPUT_OBJ;
  2229.             break;
  2230.         case TCC_OPTION_C:
  2231.             s->option_C = 1;
  2232.             break;
  2233.         case TCC_OPTION_d:
  2234.             if (*optarg == 'D' || *optarg == 'M')
  2235.                 s->dflag = *optarg;
  2236.             else {
  2237.                 if (s->warn_unsupported)
  2238.                     goto unsupported_option;
  2239.                 tcc_error("invalid option -- '%s'", r);
  2240.             }
  2241.             break;
  2242. #ifdef TCC_TARGET_ARM
  2243.         case TCC_OPTION_float_abi:
  2244.             /* tcc doesn't support soft float yet */
  2245.             if (!strcmp(optarg, "softfp")) {
  2246.                 s->float_abi = ARM_SOFTFP_FLOAT;
  2247.                 tcc_undefine_symbol(s, "__ARM_PCS_VFP");
  2248.             } else if (!strcmp(optarg, "hard"))
  2249.                 s->float_abi = ARM_HARD_FLOAT;
  2250.             else
  2251.                 tcc_error("unsupported float abi '%s'", optarg);
  2252.             break;
  2253. #endif
  2254.         case TCC_OPTION_static:
  2255.             s->static_link = 1;
  2256.             break;
  2257.         case TCC_OPTION_std:
  2258.             /* silently ignore, a current purpose:
  2259.                allow to use a tcc as a reference compiler for "make test" */
  2260.             break;
  2261.         case TCC_OPTION_shared:
  2262.             if (s->output_type)
  2263.                 tcc_warning("-shared: some compiler action already specified (%d)", s->output_type);
  2264.             s->output_type = TCC_OUTPUT_DLL;
  2265.             break;
  2266.         case TCC_OPTION_soname:
  2267.             s->soname = tcc_strdup(optarg);
  2268.             break;
  2269.         case TCC_OPTION_m:
  2270.             s->option_m = tcc_strdup(optarg);
  2271.             break;
  2272.         case TCC_OPTION_o:
  2273.             if (s->outfile) {
  2274.                 tcc_warning("multiple -o option");
  2275.                 tcc_free(s->outfile);
  2276.             }
  2277.             s->outfile = tcc_strdup(optarg);
  2278.             break;
  2279.         case TCC_OPTION_r:
  2280.             /* generate a .o merging several output files */
  2281.             if (s->output_type)
  2282.                 tcc_warning("-r: some compiler action already specified (%d)", s->output_type);
  2283.             s->option_r = 1;
  2284.             s->output_type = TCC_OUTPUT_OBJ;
  2285.             break;
  2286.         case TCC_OPTION_isystem:
  2287.             tcc_add_sysinclude_path(s, optarg);
  2288.             break;
  2289.         case TCC_OPTION_iwithprefix:
  2290.             if (1) {
  2291.                 char buf[1024];
  2292.                 int buf_size = sizeof(buf)-1;
  2293.                 char *p = &buf[0];
  2294.  
  2295.                 char *sysroot = "{B}/";
  2296.                 int len = strlen(sysroot);
  2297.                 if (len > buf_size)
  2298.                     len = buf_size;
  2299.                 strncpy(p, sysroot, len);
  2300.                 p += len;
  2301.                 buf_size -= len;
  2302.  
  2303.                 len = strlen(optarg);
  2304.                 if (len > buf_size)
  2305.                     len = buf_size;
  2306.                 strncpy(p, optarg, len+1);
  2307.                 tcc_add_sysinclude_path(s, buf);
  2308.             }
  2309.             break;
  2310.         case TCC_OPTION_nostdinc:
  2311.             s->nostdinc = 1;
  2312.             break;
  2313.         case TCC_OPTION_nostdlib:
  2314.             s->nostdlib = 1;
  2315.             break;
  2316.         case TCC_OPTION_print_search_dirs:
  2317.             s->print_search_dirs = 1;
  2318.             break;
  2319.         case TCC_OPTION_run:
  2320.             if (s->output_type)
  2321.                 tcc_warning("-run: some compiler action already specified (%d)", s->output_type);
  2322.             s->output_type = TCC_OUTPUT_MEMORY;
  2323.             tcc_set_options(s, optarg);
  2324.             pas->run = 1;
  2325.             break;
  2326.         case TCC_OPTION_v:
  2327.             do ++s->verbose; while (*optarg++ == 'v');
  2328.             break;
  2329.         case TCC_OPTION_f:
  2330.             if (tcc_set_flag(s, optarg, 1) < 0 && s->warn_unsupported)
  2331.                 goto unsupported_option;
  2332.             break;
  2333.         case TCC_OPTION_W:
  2334.             if (tcc_set_warning(s, optarg, 1) < 0 &&
  2335.                 s->warn_unsupported)
  2336.                 goto unsupported_option;
  2337.             break;
  2338.         case TCC_OPTION_w:
  2339.             s->warn_none = 1;
  2340.             break;
  2341.         case TCC_OPTION_rdynamic:
  2342.             s->rdynamic = 1;
  2343.             break;
  2344.         case TCC_OPTION_Wl:
  2345.             if (pas->linker_arg.size)
  2346.                 --pas->linker_arg.size, cstr_ccat(&pas->linker_arg, ',');
  2347.             cstr_cat(&pas->linker_arg, optarg, 0);
  2348.             break;
  2349.         case TCC_OPTION_E:
  2350.             if (s->output_type)
  2351.                 tcc_warning("-E: some compiler action already specified (%d)", s->output_type);
  2352.             s->output_type = TCC_OUTPUT_PREPROCESS;
  2353.             break;
  2354.         case TCC_OPTION_P:
  2355.             s->Pflag = atoi(optarg) + 1;
  2356.             break;
  2357.         case TCC_OPTION_MD:
  2358.             s->gen_deps = 1;
  2359.             break;
  2360.         case TCC_OPTION_MF:
  2361.             s->deps_outfile = tcc_strdup(optarg);
  2362.             break;
  2363.         case TCC_OPTION_dumpversion:
  2364.             printf ("%s\n", TCC_VERSION);
  2365.             exit(0);
  2366.         case TCC_OPTION_s:
  2367.             s->do_strip = 1;
  2368.             break;
  2369.         case TCC_OPTION_traditional:
  2370.             break;
  2371.         case TCC_OPTION_x:
  2372.             if (*optarg == 'c')
  2373.                 pas->filetype = TCC_FILETYPE_C;
  2374.             else
  2375.             if (*optarg == 'a')
  2376.                 pas->filetype = TCC_FILETYPE_ASM_PP;
  2377.             else
  2378.             if (*optarg == 'n')
  2379.                 pas->filetype = 0;
  2380.             else
  2381.                 tcc_warning("unsupported language '%s'", optarg);
  2382.             break;
  2383.         case TCC_OPTION_O:
  2384.             if (1) {
  2385.                 int opt = atoi(optarg);
  2386.                 char *sym = "__OPTIMIZE__";
  2387.                 if (opt)
  2388.                     tcc_define_symbol(s, sym, 0);
  2389.                 else
  2390.                     tcc_undefine_symbol(s, sym);
  2391.             }
  2392.             break;
  2393.         case TCC_OPTION_pedantic:
  2394.         case TCC_OPTION_pipe:
  2395.             /* ignored */
  2396.             break;
  2397.         default:
  2398.             if (s->warn_unsupported) {
  2399.             unsupported_option:
  2400.                 tcc_warning("unsupported option '%s'", r);
  2401.             }
  2402.             break;
  2403.         }
  2404.     }
  2405.     return optind;
  2406. }
  2407.  
  2408. PUB_FUNC int tcc_parse_args(TCCState *s, int argc, char **argv)
  2409. {
  2410.     ParseArgsState *pas;
  2411.     int ret, is_allocated = 0;
  2412.  
  2413.     if (!s->parse_args_state) {
  2414.         s->parse_args_state = tcc_mallocz(sizeof(ParseArgsState));
  2415.         cstr_new(&s->parse_args_state->linker_arg);
  2416.         is_allocated = 1;
  2417.     }
  2418.     pas = s->parse_args_state;
  2419.  
  2420.     ret = tcc_parse_args1(s, argc, argv);
  2421.  
  2422.     if (s->output_type == 0)
  2423.         s->output_type = TCC_OUTPUT_EXE;
  2424.  
  2425.     if (pas->pthread && s->output_type != TCC_OUTPUT_OBJ)
  2426.         tcc_set_options(s, "-lpthread");
  2427.  
  2428.     if (s->output_type == TCC_OUTPUT_EXE)
  2429.         tcc_set_linker(s, (const char *)pas->linker_arg.data);
  2430.  
  2431.     if (is_allocated) {
  2432.         cstr_free(&pas->linker_arg);
  2433.         tcc_free(pas);
  2434.         s->parse_args_state = NULL;
  2435.     }
  2436.     return ret;
  2437. }
  2438.  
  2439. LIBTCCAPI int tcc_set_options(TCCState *s, const char *str)
  2440. {
  2441.     const char *s1;
  2442.     char **argv, *arg;
  2443.     int argc, len;
  2444.     int ret;
  2445.  
  2446.     argc = 0, argv = NULL;
  2447.     for(;;) {
  2448.         while (is_space(*str))
  2449.             str++;
  2450.         if (*str == '\0')
  2451.             break;
  2452.         s1 = str;
  2453.         while (*str != '\0' && !is_space(*str))
  2454.             str++;
  2455.         len = str - s1;
  2456.         arg = tcc_malloc(len + 1);
  2457.         pstrncpy(arg, s1, len);
  2458.         dynarray_add((void ***)&argv, &argc, arg);
  2459.     }
  2460.     ret = tcc_parse_args(s, argc, argv);
  2461.     dynarray_reset(&argv, &argc);
  2462.     return ret;
  2463. }
  2464.  
  2465. PUB_FUNC void tcc_print_stats(TCCState *s, int64_t total_time)
  2466. {
  2467.     double tt;
  2468.     tt = (double)total_time / 1000000.0;
  2469.     if (tt < 0.001)
  2470.         tt = 0.001;
  2471.     if (total_bytes < 1)
  2472.         total_bytes = 1;
  2473.     fprintf(stderr, "%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
  2474.            tok_ident - TOK_IDENT, total_lines, total_bytes,
  2475.            tt, (int)(total_lines / tt),
  2476.            total_bytes / tt / 1000000.0);
  2477. }
  2478.  
  2479. PUB_FUNC void tcc_set_environment(TCCState *s)
  2480. {
  2481.     char * path;
  2482.  
  2483.     path = getenv("C_INCLUDE_PATH");
  2484.     if(path != NULL) {
  2485.         tcc_add_include_path(s, path);
  2486.     }
  2487.     path = getenv("CPATH");
  2488.     if(path != NULL) {
  2489.         tcc_add_include_path(s, path);
  2490.     }
  2491.     path = getenv("LIBRARY_PATH");
  2492.     if(path != NULL) {
  2493.         tcc_add_library_path(s, path);
  2494.     }
  2495. }
  2496.