libtcc.c 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260
  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. #include "tcc.h"
  21. /********************************************************/
  22. /* global variables */
  23. /* display benchmark infos */
  24. int total_lines;
  25. int total_bytes;
  26. /* parser */
  27. static struct BufferedFile *file;
  28. static int ch, tok;
  29. static CValue tokc;
  30. static CString tokcstr; /* current parsed string, if any */
  31. /* additional informations about token */
  32. static int tok_flags;
  33. #define TOK_FLAG_BOL 0x0001 /* beginning of line before */
  34. #define TOK_FLAG_BOF 0x0002 /* beginning of file before */
  35. #define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */
  36. #define TOK_FLAG_EOF 0x0008 /* end of file */
  37. static int *macro_ptr, *macro_ptr_allocated;
  38. static int *unget_saved_macro_ptr;
  39. static int unget_saved_buffer[TOK_MAX_SIZE + 1];
  40. static int unget_buffer_enabled;
  41. static int parse_flags;
  42. #define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
  43. #define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
  44. #define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
  45. token. line feed is also
  46. returned at eof */
  47. #define PARSE_FLAG_ASM_COMMENTS 0x0008 /* '#' can be used for line comment */
  48. #define PARSE_FLAG_SPACES 0x0010 /* next() returns space tokens (for -E) */
  49. static Section *text_section, *data_section, *bss_section; /* predefined sections */
  50. static Section *cur_text_section; /* current section where function code is
  51. generated */
  52. #ifdef CONFIG_TCC_ASM
  53. static Section *last_text_section; /* to handle .previous asm directive */
  54. #endif
  55. /* bound check related sections */
  56. static Section *bounds_section; /* contains global data bound description */
  57. static Section *lbounds_section; /* contains local data bound description */
  58. /* symbol sections */
  59. static Section *symtab_section, *strtab_section;
  60. /* debug sections */
  61. static Section *stab_section, *stabstr_section;
  62. /* loc : local variable index
  63. ind : output code index
  64. rsym: return symbol
  65. anon_sym: anonymous symbol index
  66. */
  67. static int rsym, anon_sym, ind, loc;
  68. /* expression generation modifiers */
  69. static int const_wanted; /* true if constant wanted */
  70. static int nocode_wanted; /* true if no code generation wanted for an expression */
  71. static int global_expr; /* true if compound literals must be allocated
  72. globally (used during initializers parsing */
  73. static CType func_vt; /* current function return type (used by return
  74. instruction) */
  75. static int func_vc;
  76. static int last_line_num, last_ind, func_ind; /* debug last line number and pc */
  77. static int tok_ident;
  78. static TokenSym **table_ident;
  79. static TokenSym *hash_ident[TOK_HASH_SIZE];
  80. static char token_buf[STRING_MAX_SIZE + 1];
  81. static char *funcname;
  82. static Sym *global_stack, *local_stack;
  83. static Sym *define_stack;
  84. static Sym *global_label_stack, *local_label_stack;
  85. /* symbol allocator */
  86. #define SYM_POOL_NB (8192 / sizeof(Sym))
  87. static Sym *sym_free_first;
  88. static void **sym_pools;
  89. static int nb_sym_pools;
  90. static SValue vstack[VSTACK_SIZE], *vtop;
  91. /* some predefined types */
  92. static CType char_pointer_type, func_old_type, int_type;
  93. /* use GNU C extensions */
  94. static int gnu_ext = 1;
  95. /* use Tiny C extensions */
  96. static int tcc_ext = 1;
  97. /* max number of callers shown if error */
  98. #ifdef CONFIG_TCC_BACKTRACE
  99. int num_callers = 6;
  100. const char **rt_bound_error_msg;
  101. #endif
  102. /* XXX: get rid of this ASAP */
  103. static struct TCCState *tcc_state;
  104. /********************************************************/
  105. /* function prototypes */
  106. /* tccpp.c */
  107. static void next(void);
  108. char *get_tok_str(int v, CValue *cv);
  109. /* tccgen.c */
  110. static void parse_expr_type(CType *type);
  111. static void expr_type(CType *type);
  112. static void unary_type(CType *type);
  113. static void block(int *bsym, int *csym, int *case_sym, int *def_sym,
  114. int case_reg, int is_expr);
  115. static int expr_const(void);
  116. static void expr_eq(void);
  117. static void gexpr(void);
  118. static void gen_inline_functions(void);
  119. static void decl(int l);
  120. static void decl_initializer(CType *type, Section *sec, unsigned long c,
  121. int first, int size_only);
  122. static void decl_initializer_alloc(CType *type, AttributeDef *ad, int r,
  123. int has_init, int v, int scope);
  124. int gv(int rc);
  125. void gv2(int rc1, int rc2);
  126. void move_reg(int r, int s);
  127. void save_regs(int n);
  128. void save_reg(int r);
  129. void vpop(void);
  130. void vswap(void);
  131. void vdup(void);
  132. int get_reg(int rc);
  133. int get_reg_ex(int rc,int rc2);
  134. void gen_op(int op);
  135. void force_charshort_cast(int t);
  136. static void gen_cast(CType *type);
  137. void vstore(void);
  138. static Sym *sym_find(int v);
  139. static Sym *sym_push(int v, CType *type, int r, int c);
  140. /* type handling */
  141. static int type_size(CType *type, int *a);
  142. static inline CType *pointed_type(CType *type);
  143. static int pointed_size(CType *type);
  144. static int lvalue_type(int t);
  145. static int parse_btype(CType *type, AttributeDef *ad);
  146. static void type_decl(CType *type, AttributeDef *ad, int *v, int td);
  147. static int compare_types(CType *type1, CType *type2, int unqualified);
  148. static int is_compatible_types(CType *type1, CType *type2);
  149. static int is_compatible_parameter_types(CType *type1, CType *type2);
  150. int ieee_finite(double d);
  151. void vpushi(int v);
  152. void vpushll(long long v);
  153. void vrott(int n);
  154. void vnrott(int n);
  155. void lexpand_nr(void);
  156. static void vpush_global_sym(CType *type, int v);
  157. void vset(CType *type, int r, int v);
  158. void type_to_str(char *buf, int buf_size,
  159. CType *type, const char *varstr);
  160. static Sym *get_sym_ref(CType *type, Section *sec,
  161. unsigned long offset, unsigned long size);
  162. static Sym *external_global_sym(int v, CType *type, int r);
  163. /* section generation */
  164. static void section_realloc(Section *sec, unsigned long new_size);
  165. static void *section_ptr_add(Section *sec, unsigned long size);
  166. static void put_extern_sym(Sym *sym, Section *section,
  167. unsigned long value, unsigned long size);
  168. static void greloc(Section *s, Sym *sym, unsigned long addr, int type);
  169. static int put_elf_str(Section *s, const char *sym);
  170. static int put_elf_sym(Section *s,
  171. unsigned long value, unsigned long size,
  172. int info, int other, int shndx, const char *name);
  173. static int add_elf_sym(Section *s, unsigned long value, unsigned long size,
  174. int info, int other, int sh_num, const char *name);
  175. static void put_elf_reloc(Section *symtab, Section *s, unsigned long offset,
  176. int type, int symbol);
  177. static void put_stabs(const char *str, int type, int other, int desc,
  178. unsigned long value);
  179. static void put_stabs_r(const char *str, int type, int other, int desc,
  180. unsigned long value, Section *sec, int sym_index);
  181. static void put_stabn(int type, int other, int desc, int value);
  182. static void put_stabd(int type, int other, int desc);
  183. static int tcc_add_dll(TCCState *s, const char *filename, int flags);
  184. #define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
  185. #define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
  186. #define AFF_PREPROCESS 0x0004 /* preprocess file */
  187. static int tcc_add_file_internal(TCCState *s, const char *filename, int flags);
  188. /* tcccoff.c */
  189. int tcc_output_coff(TCCState *s1, FILE *f);
  190. /* tccpe.c */
  191. void *resolve_sym(TCCState *s1, const char *sym, int type);
  192. int pe_load_def_file(struct TCCState *s1, int fd);
  193. int pe_test_res_file(void *v, int size);
  194. int pe_load_res_file(struct TCCState *s1, int fd);
  195. void pe_add_runtime(struct TCCState *s1);
  196. void pe_guess_outfile(char *objfilename, int output_type);
  197. int pe_output_file(struct TCCState *s1, const char *filename);
  198. /* tccasm.c */
  199. #ifdef CONFIG_TCC_ASM
  200. static void asm_expr(TCCState *s1, ExprValue *pe);
  201. static int asm_int_expr(TCCState *s1);
  202. static int find_constraint(ASMOperand *operands, int nb_operands,
  203. const char *name, const char **pp);
  204. static int tcc_assemble(TCCState *s1, int do_preprocess);
  205. #endif
  206. static void asm_instr(void);
  207. static void asm_global_instr(void);
  208. /********************************************************/
  209. /* global variables */
  210. #ifdef TCC_TARGET_I386
  211. #include "i386-gen.c"
  212. #endif
  213. #ifdef TCC_TARGET_ARM
  214. #include "arm-gen.c"
  215. #endif
  216. #ifdef TCC_TARGET_C67
  217. #include "c67-gen.c"
  218. #endif
  219. #ifdef TCC_TARGET_X86_64
  220. #include "x86_64-gen.c"
  221. #endif
  222. #ifdef CONFIG_TCC_STATIC
  223. #define RTLD_LAZY 0x001
  224. #define RTLD_NOW 0x002
  225. #define RTLD_GLOBAL 0x100
  226. #define RTLD_DEFAULT NULL
  227. /* dummy function for profiling */
  228. void *dlopen(const char *filename, int flag)
  229. {
  230. return NULL;
  231. }
  232. void dlclose(void *p)
  233. {
  234. }
  235. const char *dlerror(void)
  236. {
  237. return "error";
  238. }
  239. typedef struct TCCSyms {
  240. char *str;
  241. void *ptr;
  242. } TCCSyms;
  243. #define TCCSYM(a) { #a, &a, },
  244. /* add the symbol you want here if no dynamic linking is done */
  245. static TCCSyms tcc_syms[] = {
  246. #if !defined(CONFIG_TCCBOOT)
  247. TCCSYM(printf)
  248. TCCSYM(fprintf)
  249. TCCSYM(fopen)
  250. TCCSYM(fclose)
  251. #endif
  252. { NULL, NULL },
  253. };
  254. void *resolve_sym(TCCState *s1, const char *symbol, int type)
  255. {
  256. TCCSyms *p;
  257. p = tcc_syms;
  258. while (p->str != NULL) {
  259. if (!strcmp(p->str, symbol))
  260. return p->ptr;
  261. p++;
  262. }
  263. return NULL;
  264. }
  265. #elif !defined(_WIN32)
  266. #include <dlfcn.h>
  267. void *resolve_sym(TCCState *s1, const char *sym, int type)
  268. {
  269. return dlsym(RTLD_DEFAULT, sym);
  270. }
  271. #endif
  272. /********************************************************/
  273. /* we use our own 'finite' function to avoid potential problems with
  274. non standard math libs */
  275. /* XXX: endianness dependent */
  276. int ieee_finite(double d)
  277. {
  278. int *p = (int *)&d;
  279. return ((unsigned)((p[1] | 0x800fffff) + 1)) >> 31;
  280. }
  281. /* copy a string and truncate it. */
  282. char *pstrcpy(char *buf, int buf_size, const char *s)
  283. {
  284. char *q, *q_end;
  285. int c;
  286. if (buf_size > 0) {
  287. q = buf;
  288. q_end = buf + buf_size - 1;
  289. while (q < q_end) {
  290. c = *s++;
  291. if (c == '\0')
  292. break;
  293. *q++ = c;
  294. }
  295. *q = '\0';
  296. }
  297. return buf;
  298. }
  299. /* strcat and truncate. */
  300. char *pstrcat(char *buf, int buf_size, const char *s)
  301. {
  302. int len;
  303. len = strlen(buf);
  304. if (len < buf_size)
  305. pstrcpy(buf + len, buf_size - len, s);
  306. return buf;
  307. }
  308. /* extract the basename of a file */
  309. char *tcc_basename(const char *name)
  310. {
  311. char *p = strchr(name, 0);
  312. while (p > name && !IS_PATHSEP(p[-1]))
  313. --p;
  314. return p;
  315. }
  316. char *tcc_fileextension (const char *name)
  317. {
  318. char *b = tcc_basename(name);
  319. char *e = strrchr(b, '.');
  320. return e ? e : strchr(b, 0);
  321. }
  322. #ifdef _WIN32
  323. char *normalize_slashes(char *path)
  324. {
  325. char *p;
  326. for (p = path; *p; ++p)
  327. if (*p == '\\')
  328. *p = '/';
  329. return path;
  330. }
  331. void tcc_set_lib_path_w32(TCCState *s)
  332. {
  333. /* on win32, we suppose the lib and includes are at the location
  334. of 'tcc.exe' */
  335. char path[1024], *p;
  336. GetModuleFileNameA(NULL, path, sizeof path);
  337. p = tcc_basename(normalize_slashes(strlwr(path)));
  338. if (p - 5 > path && 0 == strncmp(p - 5, "/bin/", 5))
  339. p -= 5;
  340. else if (p > path)
  341. p--;
  342. *p = 0;
  343. tcc_set_lib_path(s, path);
  344. }
  345. #endif
  346. void set_pages_executable(void *ptr, unsigned long length)
  347. {
  348. #ifdef _WIN32
  349. unsigned long old_protect;
  350. VirtualProtect(ptr, length, PAGE_EXECUTE_READWRITE, &old_protect);
  351. #else
  352. unsigned long start, end;
  353. start = (unsigned long)ptr & ~(PAGESIZE - 1);
  354. end = (unsigned long)ptr + length;
  355. end = (end + PAGESIZE - 1) & ~(PAGESIZE - 1);
  356. mprotect((void *)start, end - start, PROT_READ | PROT_WRITE | PROT_EXEC);
  357. #endif
  358. }
  359. /* memory management */
  360. #ifdef MEM_DEBUG
  361. int mem_cur_size;
  362. int mem_max_size;
  363. unsigned malloc_usable_size(void*);
  364. #endif
  365. void tcc_free(void *ptr)
  366. {
  367. #ifdef MEM_DEBUG
  368. mem_cur_size -= malloc_usable_size(ptr);
  369. #endif
  370. free(ptr);
  371. }
  372. void *tcc_malloc(unsigned long size)
  373. {
  374. void *ptr;
  375. ptr = malloc(size);
  376. if (!ptr && size)
  377. error("memory full");
  378. #ifdef MEM_DEBUG
  379. mem_cur_size += malloc_usable_size(ptr);
  380. if (mem_cur_size > mem_max_size)
  381. mem_max_size = mem_cur_size;
  382. #endif
  383. return ptr;
  384. }
  385. void *tcc_mallocz(unsigned long size)
  386. {
  387. void *ptr;
  388. ptr = tcc_malloc(size);
  389. memset(ptr, 0, size);
  390. return ptr;
  391. }
  392. void *tcc_realloc(void *ptr, unsigned long size)
  393. {
  394. void *ptr1;
  395. #ifdef MEM_DEBUG
  396. mem_cur_size -= malloc_usable_size(ptr);
  397. #endif
  398. ptr1 = realloc(ptr, size);
  399. #ifdef MEM_DEBUG
  400. /* NOTE: count not correct if alloc error, but not critical */
  401. mem_cur_size += malloc_usable_size(ptr1);
  402. if (mem_cur_size > mem_max_size)
  403. mem_max_size = mem_cur_size;
  404. #endif
  405. return ptr1;
  406. }
  407. char *tcc_strdup(const char *str)
  408. {
  409. char *ptr;
  410. ptr = tcc_malloc(strlen(str) + 1);
  411. strcpy(ptr, str);
  412. return ptr;
  413. }
  414. #define free(p) use_tcc_free(p)
  415. #define malloc(s) use_tcc_malloc(s)
  416. #define realloc(p, s) use_tcc_realloc(p, s)
  417. void dynarray_add(void ***ptab, int *nb_ptr, void *data)
  418. {
  419. int nb, nb_alloc;
  420. void **pp;
  421. nb = *nb_ptr;
  422. pp = *ptab;
  423. /* every power of two we double array size */
  424. if ((nb & (nb - 1)) == 0) {
  425. if (!nb)
  426. nb_alloc = 1;
  427. else
  428. nb_alloc = nb * 2;
  429. pp = tcc_realloc(pp, nb_alloc * sizeof(void *));
  430. if (!pp)
  431. error("memory full");
  432. *ptab = pp;
  433. }
  434. pp[nb++] = data;
  435. *nb_ptr = nb;
  436. }
  437. void dynarray_reset(void *pp, int *n)
  438. {
  439. void **p;
  440. for (p = *(void***)pp; *n; ++p, --*n)
  441. if (*p)
  442. tcc_free(*p);
  443. tcc_free(*(void**)pp);
  444. *(void**)pp = NULL;
  445. }
  446. /* symbol allocator */
  447. static Sym *__sym_malloc(void)
  448. {
  449. Sym *sym_pool, *sym, *last_sym;
  450. int i;
  451. sym_pool = tcc_malloc(SYM_POOL_NB * sizeof(Sym));
  452. dynarray_add(&sym_pools, &nb_sym_pools, sym_pool);
  453. last_sym = sym_free_first;
  454. sym = sym_pool;
  455. for(i = 0; i < SYM_POOL_NB; i++) {
  456. sym->next = last_sym;
  457. last_sym = sym;
  458. sym++;
  459. }
  460. sym_free_first = last_sym;
  461. return last_sym;
  462. }
  463. static inline Sym *sym_malloc(void)
  464. {
  465. Sym *sym;
  466. sym = sym_free_first;
  467. if (!sym)
  468. sym = __sym_malloc();
  469. sym_free_first = sym->next;
  470. return sym;
  471. }
  472. static inline void sym_free(Sym *sym)
  473. {
  474. sym->next = sym_free_first;
  475. sym_free_first = sym;
  476. }
  477. Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags)
  478. {
  479. Section *sec;
  480. sec = tcc_mallocz(sizeof(Section) + strlen(name));
  481. strcpy(sec->name, name);
  482. sec->sh_type = sh_type;
  483. sec->sh_flags = sh_flags;
  484. switch(sh_type) {
  485. case SHT_HASH:
  486. case SHT_REL:
  487. case SHT_RELA:
  488. case SHT_DYNSYM:
  489. case SHT_SYMTAB:
  490. case SHT_DYNAMIC:
  491. sec->sh_addralign = 4;
  492. break;
  493. case SHT_STRTAB:
  494. sec->sh_addralign = 1;
  495. break;
  496. default:
  497. sec->sh_addralign = 32; /* default conservative alignment */
  498. break;
  499. }
  500. if (sh_flags & SHF_PRIVATE) {
  501. dynarray_add((void ***)&s1->priv_sections, &s1->nb_priv_sections, sec);
  502. } else {
  503. sec->sh_num = s1->nb_sections;
  504. dynarray_add((void ***)&s1->sections, &s1->nb_sections, sec);
  505. }
  506. return sec;
  507. }
  508. static void free_section(Section *s)
  509. {
  510. tcc_free(s->data);
  511. }
  512. /* realloc section and set its content to zero */
  513. static void section_realloc(Section *sec, unsigned long new_size)
  514. {
  515. unsigned long size;
  516. unsigned char *data;
  517. size = sec->data_allocated;
  518. if (size == 0)
  519. size = 1;
  520. while (size < new_size)
  521. size = size * 2;
  522. data = tcc_realloc(sec->data, size);
  523. if (!data)
  524. error("memory full");
  525. memset(data + sec->data_allocated, 0, size - sec->data_allocated);
  526. sec->data = data;
  527. sec->data_allocated = size;
  528. }
  529. /* reserve at least 'size' bytes in section 'sec' from
  530. sec->data_offset. */
  531. static void *section_ptr_add(Section *sec, unsigned long size)
  532. {
  533. unsigned long offset, offset1;
  534. offset = sec->data_offset;
  535. offset1 = offset + size;
  536. if (offset1 > sec->data_allocated)
  537. section_realloc(sec, offset1);
  538. sec->data_offset = offset1;
  539. return sec->data + offset;
  540. }
  541. /* return a reference to a section, and create it if it does not
  542. exists */
  543. Section *find_section(TCCState *s1, const char *name)
  544. {
  545. Section *sec;
  546. int i;
  547. for(i = 1; i < s1->nb_sections; i++) {
  548. sec = s1->sections[i];
  549. if (!strcmp(name, sec->name))
  550. return sec;
  551. }
  552. /* sections are created as PROGBITS */
  553. return new_section(s1, name, SHT_PROGBITS, SHF_ALLOC);
  554. }
  555. /* update sym->c so that it points to an external symbol in section
  556. 'section' with value 'value' */
  557. static void put_extern_sym2(Sym *sym, Section *section,
  558. unsigned long value, unsigned long size,
  559. int can_add_underscore)
  560. {
  561. int sym_type, sym_bind, sh_num, info, other, attr;
  562. ElfW(Sym) *esym;
  563. const char *name;
  564. char buf1[256];
  565. if (section == NULL)
  566. sh_num = SHN_UNDEF;
  567. else if (section == SECTION_ABS)
  568. sh_num = SHN_ABS;
  569. else
  570. sh_num = section->sh_num;
  571. other = attr = 0;
  572. if ((sym->type.t & VT_BTYPE) == VT_FUNC) {
  573. sym_type = STT_FUNC;
  574. #ifdef TCC_TARGET_PE
  575. if (sym->type.ref)
  576. attr = sym->type.ref->r;
  577. if (FUNC_EXPORT(attr))
  578. other |= 1;
  579. if (FUNC_CALL(attr) == FUNC_STDCALL)
  580. other |= 2;
  581. #endif
  582. } else {
  583. sym_type = STT_OBJECT;
  584. }
  585. if (sym->type.t & VT_STATIC)
  586. sym_bind = STB_LOCAL;
  587. else
  588. sym_bind = STB_GLOBAL;
  589. if (!sym->c) {
  590. name = get_tok_str(sym->v, NULL);
  591. #ifdef CONFIG_TCC_BCHECK
  592. if (tcc_state->do_bounds_check) {
  593. char buf[32];
  594. /* XXX: avoid doing that for statics ? */
  595. /* if bound checking is activated, we change some function
  596. names by adding the "__bound" prefix */
  597. switch(sym->v) {
  598. #if 0
  599. /* XXX: we rely only on malloc hooks */
  600. case TOK_malloc:
  601. case TOK_free:
  602. case TOK_realloc:
  603. case TOK_memalign:
  604. case TOK_calloc:
  605. #endif
  606. case TOK_memcpy:
  607. case TOK_memmove:
  608. case TOK_memset:
  609. case TOK_strlen:
  610. case TOK_strcpy:
  611. case TOK_alloca:
  612. strcpy(buf, "__bound_");
  613. strcat(buf, name);
  614. name = buf;
  615. break;
  616. }
  617. }
  618. #endif
  619. #ifdef TCC_TARGET_PE
  620. if ((other & 2) && can_add_underscore) {
  621. sprintf(buf1, "_%s@%d", name, FUNC_ARGS(attr));
  622. name = buf1;
  623. } else
  624. #endif
  625. if (tcc_state->leading_underscore && can_add_underscore) {
  626. buf1[0] = '_';
  627. pstrcpy(buf1 + 1, sizeof(buf1) - 1, name);
  628. name = buf1;
  629. }
  630. info = ELFW(ST_INFO)(sym_bind, sym_type);
  631. sym->c = add_elf_sym(symtab_section, value, size, info, other, sh_num, name);
  632. } else {
  633. esym = &((ElfW(Sym) *)symtab_section->data)[sym->c];
  634. esym->st_value = value;
  635. esym->st_size = size;
  636. esym->st_shndx = sh_num;
  637. esym->st_other |= other;
  638. }
  639. }
  640. static void put_extern_sym(Sym *sym, Section *section,
  641. unsigned long value, unsigned long size)
  642. {
  643. put_extern_sym2(sym, section, value, size, 1);
  644. }
  645. /* add a new relocation entry to symbol 'sym' in section 's' */
  646. static void greloc(Section *s, Sym *sym, unsigned long offset, int type)
  647. {
  648. if (!sym->c)
  649. put_extern_sym(sym, NULL, 0, 0);
  650. /* now we can add ELF relocation info */
  651. put_elf_reloc(symtab_section, s, offset, type, sym->c);
  652. }
  653. static inline int isid(int c)
  654. {
  655. return (c >= 'a' && c <= 'z') ||
  656. (c >= 'A' && c <= 'Z') ||
  657. c == '_';
  658. }
  659. static inline int isnum(int c)
  660. {
  661. return c >= '0' && c <= '9';
  662. }
  663. static inline int isoct(int c)
  664. {
  665. return c >= '0' && c <= '7';
  666. }
  667. static inline int toup(int c)
  668. {
  669. if (c >= 'a' && c <= 'z')
  670. return c - 'a' + 'A';
  671. else
  672. return c;
  673. }
  674. static void strcat_vprintf(char *buf, int buf_size, const char *fmt, va_list ap)
  675. {
  676. int len;
  677. len = strlen(buf);
  678. vsnprintf(buf + len, buf_size - len, fmt, ap);
  679. }
  680. static void strcat_printf(char *buf, int buf_size, const char *fmt, ...)
  681. {
  682. va_list ap;
  683. va_start(ap, fmt);
  684. strcat_vprintf(buf, buf_size, fmt, ap);
  685. va_end(ap);
  686. }
  687. void error1(TCCState *s1, int is_warning, const char *fmt, va_list ap)
  688. {
  689. char buf[2048];
  690. BufferedFile **f;
  691. buf[0] = '\0';
  692. if (file) {
  693. for(f = s1->include_stack; f < s1->include_stack_ptr; f++)
  694. strcat_printf(buf, sizeof(buf), "In file included from %s:%d:\n",
  695. (*f)->filename, (*f)->line_num);
  696. if (file->line_num > 0) {
  697. strcat_printf(buf, sizeof(buf),
  698. "%s:%d: ", file->filename, file->line_num);
  699. } else {
  700. strcat_printf(buf, sizeof(buf),
  701. "%s: ", file->filename);
  702. }
  703. } else {
  704. strcat_printf(buf, sizeof(buf),
  705. "tcc: ");
  706. }
  707. if (is_warning)
  708. strcat_printf(buf, sizeof(buf), "warning: ");
  709. strcat_vprintf(buf, sizeof(buf), fmt, ap);
  710. if (!s1->error_func) {
  711. /* default case: stderr */
  712. fprintf(stderr, "%s\n", buf);
  713. }
  714. if (!is_warning || s1->warn_error) {
  715. s1->error_func(s1->error_opaque, buf);
  716. s1->nb_errors++;
  717. }
  718. }
  719. void tcc_set_error_func(TCCState *s, void *error_opaque,
  720. void (*error_func)(void *opaque, const char *msg))
  721. {
  722. s->error_opaque = error_opaque;
  723. s->error_func = error_func;
  724. }
  725. /* error without aborting current compilation */
  726. void error_noabort(const char *fmt, ...)
  727. {
  728. TCCState *s1 = tcc_state;
  729. va_list ap;
  730. va_start(ap, fmt);
  731. error1(s1, 0, fmt, ap);
  732. va_end(ap);
  733. }
  734. void error(const char *fmt, ...)
  735. {
  736. TCCState *s1 = tcc_state;
  737. va_list ap;
  738. va_start(ap, fmt);
  739. error1(s1, 0, fmt, ap);
  740. va_end(ap);
  741. /* better than nothing: in some cases, we accept to handle errors */
  742. if (s1->error_set_jmp_enabled) {
  743. longjmp(s1->error_jmp_buf, 1);
  744. } else {
  745. /* XXX: eliminate this someday */
  746. exit(1);
  747. }
  748. }
  749. void expect(const char *msg)
  750. {
  751. error("%s expected", msg);
  752. }
  753. void warning(const char *fmt, ...)
  754. {
  755. TCCState *s1 = tcc_state;
  756. va_list ap;
  757. if (s1->warn_none)
  758. return;
  759. va_start(ap, fmt);
  760. error1(s1, 1, fmt, ap);
  761. va_end(ap);
  762. }
  763. void skip(int c)
  764. {
  765. if (tok != c)
  766. error("'%c' expected", c);
  767. next();
  768. }
  769. static void test_lvalue(void)
  770. {
  771. if (!(vtop->r & VT_LVAL))
  772. expect("lvalue");
  773. }
  774. /* CString handling */
  775. static void cstr_realloc(CString *cstr, int new_size)
  776. {
  777. int size;
  778. void *data;
  779. size = cstr->size_allocated;
  780. if (size == 0)
  781. size = 8; /* no need to allocate a too small first string */
  782. while (size < new_size)
  783. size = size * 2;
  784. data = tcc_realloc(cstr->data_allocated, size);
  785. if (!data)
  786. error("memory full");
  787. cstr->data_allocated = data;
  788. cstr->size_allocated = size;
  789. cstr->data = data;
  790. }
  791. /* add a byte */
  792. static inline void cstr_ccat(CString *cstr, int ch)
  793. {
  794. int size;
  795. size = cstr->size + 1;
  796. if (size > cstr->size_allocated)
  797. cstr_realloc(cstr, size);
  798. ((unsigned char *)cstr->data)[size - 1] = ch;
  799. cstr->size = size;
  800. }
  801. static void cstr_cat(CString *cstr, const char *str)
  802. {
  803. int c;
  804. for(;;) {
  805. c = *str;
  806. if (c == '\0')
  807. break;
  808. cstr_ccat(cstr, c);
  809. str++;
  810. }
  811. }
  812. /* add a wide char */
  813. static void cstr_wccat(CString *cstr, int ch)
  814. {
  815. int size;
  816. size = cstr->size + sizeof(nwchar_t);
  817. if (size > cstr->size_allocated)
  818. cstr_realloc(cstr, size);
  819. *(nwchar_t *)(((unsigned char *)cstr->data) + size - sizeof(nwchar_t)) = ch;
  820. cstr->size = size;
  821. }
  822. static void cstr_new(CString *cstr)
  823. {
  824. memset(cstr, 0, sizeof(CString));
  825. }
  826. /* free string and reset it to NULL */
  827. static void cstr_free(CString *cstr)
  828. {
  829. tcc_free(cstr->data_allocated);
  830. cstr_new(cstr);
  831. }
  832. #define cstr_reset(cstr) cstr_free(cstr)
  833. /* XXX: unicode ? */
  834. static void add_char(CString *cstr, int c)
  835. {
  836. if (c == '\'' || c == '\"' || c == '\\') {
  837. /* XXX: could be more precise if char or string */
  838. cstr_ccat(cstr, '\\');
  839. }
  840. if (c >= 32 && c <= 126) {
  841. cstr_ccat(cstr, c);
  842. } else {
  843. cstr_ccat(cstr, '\\');
  844. if (c == '\n') {
  845. cstr_ccat(cstr, 'n');
  846. } else {
  847. cstr_ccat(cstr, '0' + ((c >> 6) & 7));
  848. cstr_ccat(cstr, '0' + ((c >> 3) & 7));
  849. cstr_ccat(cstr, '0' + (c & 7));
  850. }
  851. }
  852. }
  853. /* push, without hashing */
  854. static Sym *sym_push2(Sym **ps, int v, int t, long c)
  855. {
  856. Sym *s;
  857. s = sym_malloc();
  858. s->v = v;
  859. s->type.t = t;
  860. s->c = c;
  861. s->next = NULL;
  862. /* add in stack */
  863. s->prev = *ps;
  864. *ps = s;
  865. return s;
  866. }
  867. /* find a symbol and return its associated structure. 's' is the top
  868. of the symbol stack */
  869. static Sym *sym_find2(Sym *s, int v)
  870. {
  871. while (s) {
  872. if (s->v == v)
  873. return s;
  874. s = s->prev;
  875. }
  876. return NULL;
  877. }
  878. /* structure lookup */
  879. static inline Sym *struct_find(int v)
  880. {
  881. v -= TOK_IDENT;
  882. if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
  883. return NULL;
  884. return table_ident[v]->sym_struct;
  885. }
  886. /* find an identifier */
  887. static inline Sym *sym_find(int v)
  888. {
  889. v -= TOK_IDENT;
  890. if ((unsigned)v >= (unsigned)(tok_ident - TOK_IDENT))
  891. return NULL;
  892. return table_ident[v]->sym_identifier;
  893. }
  894. /* push a given symbol on the symbol stack */
  895. static Sym *sym_push(int v, CType *type, int r, int c)
  896. {
  897. Sym *s, **ps;
  898. TokenSym *ts;
  899. if (local_stack)
  900. ps = &local_stack;
  901. else
  902. ps = &global_stack;
  903. s = sym_push2(ps, v, type->t, c);
  904. s->type.ref = type->ref;
  905. s->r = r;
  906. /* don't record fields or anonymous symbols */
  907. /* XXX: simplify */
  908. if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
  909. /* record symbol in token array */
  910. ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
  911. if (v & SYM_STRUCT)
  912. ps = &ts->sym_struct;
  913. else
  914. ps = &ts->sym_identifier;
  915. s->prev_tok = *ps;
  916. *ps = s;
  917. }
  918. return s;
  919. }
  920. /* push a global identifier */
  921. static Sym *global_identifier_push(int v, int t, int c)
  922. {
  923. Sym *s, **ps;
  924. s = sym_push2(&global_stack, v, t, c);
  925. /* don't record anonymous symbol */
  926. if (v < SYM_FIRST_ANOM) {
  927. ps = &table_ident[v - TOK_IDENT]->sym_identifier;
  928. /* modify the top most local identifier, so that
  929. sym_identifier will point to 's' when popped */
  930. while (*ps != NULL)
  931. ps = &(*ps)->prev_tok;
  932. s->prev_tok = NULL;
  933. *ps = s;
  934. }
  935. return s;
  936. }
  937. /* pop symbols until top reaches 'b' */
  938. static void sym_pop(Sym **ptop, Sym *b)
  939. {
  940. Sym *s, *ss, **ps;
  941. TokenSym *ts;
  942. int v;
  943. s = *ptop;
  944. while(s != b) {
  945. ss = s->prev;
  946. v = s->v;
  947. /* remove symbol in token array */
  948. /* XXX: simplify */
  949. if (!(v & SYM_FIELD) && (v & ~SYM_STRUCT) < SYM_FIRST_ANOM) {
  950. ts = table_ident[(v & ~SYM_STRUCT) - TOK_IDENT];
  951. if (v & SYM_STRUCT)
  952. ps = &ts->sym_struct;
  953. else
  954. ps = &ts->sym_identifier;
  955. *ps = s->prev_tok;
  956. }
  957. sym_free(s);
  958. s = ss;
  959. }
  960. *ptop = b;
  961. }
  962. /* I/O layer */
  963. BufferedFile *tcc_open(TCCState *s1, const char *filename)
  964. {
  965. int fd;
  966. BufferedFile *bf;
  967. if (strcmp(filename, "-") == 0)
  968. fd = 0, filename = "stdin";
  969. else
  970. fd = open(filename, O_RDONLY | O_BINARY);
  971. if ((s1->verbose == 2 && fd >= 0) || s1->verbose == 3)
  972. printf("%s %*s%s\n", fd < 0 ? "nf":"->",
  973. (s1->include_stack_ptr - s1->include_stack), "", filename);
  974. if (fd < 0)
  975. return NULL;
  976. bf = tcc_malloc(sizeof(BufferedFile));
  977. bf->fd = fd;
  978. bf->buf_ptr = bf->buffer;
  979. bf->buf_end = bf->buffer;
  980. bf->buffer[0] = CH_EOB; /* put eob symbol */
  981. pstrcpy(bf->filename, sizeof(bf->filename), filename);
  982. #ifdef _WIN32
  983. normalize_slashes(bf->filename);
  984. #endif
  985. bf->line_num = 1;
  986. bf->ifndef_macro = 0;
  987. bf->ifdef_stack_ptr = s1->ifdef_stack_ptr;
  988. // printf("opening '%s'\n", filename);
  989. return bf;
  990. }
  991. void tcc_close(BufferedFile *bf)
  992. {
  993. total_lines += bf->line_num;
  994. close(bf->fd);
  995. tcc_free(bf);
  996. }
  997. #include "tccpp.c"
  998. #include "tccgen.c"
  999. /* compile the C file opened in 'file'. Return non zero if errors. */
  1000. static int tcc_compile(TCCState *s1)
  1001. {
  1002. Sym *define_start;
  1003. char buf[512];
  1004. volatile int section_sym;
  1005. #ifdef INC_DEBUG
  1006. printf("%s: **** new file\n", file->filename);
  1007. #endif
  1008. preprocess_init(s1);
  1009. cur_text_section = NULL;
  1010. funcname = "";
  1011. anon_sym = SYM_FIRST_ANOM;
  1012. /* file info: full path + filename */
  1013. section_sym = 0; /* avoid warning */
  1014. if (s1->do_debug) {
  1015. section_sym = put_elf_sym(symtab_section, 0, 0,
  1016. ELFW(ST_INFO)(STB_LOCAL, STT_SECTION), 0,
  1017. text_section->sh_num, NULL);
  1018. getcwd(buf, sizeof(buf));
  1019. #ifdef _WIN32
  1020. normalize_slashes(buf);
  1021. #endif
  1022. pstrcat(buf, sizeof(buf), "/");
  1023. put_stabs_r(buf, N_SO, 0, 0,
  1024. text_section->data_offset, text_section, section_sym);
  1025. put_stabs_r(file->filename, N_SO, 0, 0,
  1026. text_section->data_offset, text_section, section_sym);
  1027. }
  1028. /* an elf symbol of type STT_FILE must be put so that STB_LOCAL
  1029. symbols can be safely used */
  1030. put_elf_sym(symtab_section, 0, 0,
  1031. ELFW(ST_INFO)(STB_LOCAL, STT_FILE), 0,
  1032. SHN_ABS, file->filename);
  1033. /* define some often used types */
  1034. int_type.t = VT_INT;
  1035. char_pointer_type.t = VT_BYTE;
  1036. mk_pointer(&char_pointer_type);
  1037. func_old_type.t = VT_FUNC;
  1038. func_old_type.ref = sym_push(SYM_FIELD, &int_type, FUNC_CDECL, FUNC_OLD);
  1039. #if defined(TCC_ARM_EABI) && defined(TCC_ARM_VFP)
  1040. float_type.t = VT_FLOAT;
  1041. double_type.t = VT_DOUBLE;
  1042. func_float_type.t = VT_FUNC;
  1043. func_float_type.ref = sym_push(SYM_FIELD, &float_type, FUNC_CDECL, FUNC_OLD);
  1044. func_double_type.t = VT_FUNC;
  1045. func_double_type.ref = sym_push(SYM_FIELD, &double_type, FUNC_CDECL, FUNC_OLD);
  1046. #endif
  1047. #if 0
  1048. /* define 'void *alloca(unsigned int)' builtin function */
  1049. {
  1050. Sym *s1;
  1051. p = anon_sym++;
  1052. sym = sym_push(p, mk_pointer(VT_VOID), FUNC_CDECL, FUNC_NEW);
  1053. s1 = sym_push(SYM_FIELD, VT_UNSIGNED | VT_INT, 0, 0);
  1054. s1->next = NULL;
  1055. sym->next = s1;
  1056. sym_push(TOK_alloca, VT_FUNC | (p << VT_STRUCT_SHIFT), VT_CONST, 0);
  1057. }
  1058. #endif
  1059. define_start = define_stack;
  1060. nocode_wanted = 1;
  1061. if (setjmp(s1->error_jmp_buf) == 0) {
  1062. s1->nb_errors = 0;
  1063. s1->error_set_jmp_enabled = 1;
  1064. ch = file->buf_ptr[0];
  1065. tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
  1066. parse_flags = PARSE_FLAG_PREPROCESS | PARSE_FLAG_TOK_NUM;
  1067. next();
  1068. decl(VT_CONST);
  1069. if (tok != TOK_EOF)
  1070. expect("declaration");
  1071. /* end of translation unit info */
  1072. if (s1->do_debug) {
  1073. put_stabs_r(NULL, N_SO, 0, 0,
  1074. text_section->data_offset, text_section, section_sym);
  1075. }
  1076. }
  1077. s1->error_set_jmp_enabled = 0;
  1078. /* reset define stack, but leave -Dsymbols (may be incorrect if
  1079. they are undefined) */
  1080. free_defines(define_start);
  1081. gen_inline_functions();
  1082. sym_pop(&global_stack, NULL);
  1083. sym_pop(&local_stack, NULL);
  1084. return s1->nb_errors != 0 ? -1 : 0;
  1085. }
  1086. int tcc_compile_string(TCCState *s, const char *str)
  1087. {
  1088. BufferedFile bf1, *bf = &bf1;
  1089. int ret, len;
  1090. char *buf;
  1091. /* init file structure */
  1092. bf->fd = -1;
  1093. /* XXX: avoid copying */
  1094. len = strlen(str);
  1095. buf = tcc_malloc(len + 1);
  1096. if (!buf)
  1097. return -1;
  1098. memcpy(buf, str, len);
  1099. buf[len] = CH_EOB;
  1100. bf->buf_ptr = buf;
  1101. bf->buf_end = buf + len;
  1102. pstrcpy(bf->filename, sizeof(bf->filename), "<string>");
  1103. bf->line_num = 1;
  1104. file = bf;
  1105. ret = tcc_compile(s);
  1106. file = NULL;
  1107. tcc_free(buf);
  1108. /* currently, no need to close */
  1109. return ret;
  1110. }
  1111. /* define a preprocessor symbol. A value can also be provided with the '=' operator */
  1112. void tcc_define_symbol(TCCState *s1, const char *sym, const char *value)
  1113. {
  1114. BufferedFile bf1, *bf = &bf1;
  1115. pstrcpy(bf->buffer, IO_BUF_SIZE, sym);
  1116. pstrcat(bf->buffer, IO_BUF_SIZE, " ");
  1117. /* default value */
  1118. if (!value)
  1119. value = "1";
  1120. pstrcat(bf->buffer, IO_BUF_SIZE, value);
  1121. /* init file structure */
  1122. bf->fd = -1;
  1123. bf->buf_ptr = bf->buffer;
  1124. bf->buf_end = bf->buffer + strlen(bf->buffer);
  1125. *bf->buf_end = CH_EOB;
  1126. bf->filename[0] = '\0';
  1127. bf->line_num = 1;
  1128. file = bf;
  1129. s1->include_stack_ptr = s1->include_stack;
  1130. /* parse with define parser */
  1131. ch = file->buf_ptr[0];
  1132. next_nomacro();
  1133. parse_define();
  1134. file = NULL;
  1135. }
  1136. /* undefine a preprocessor symbol */
  1137. void tcc_undefine_symbol(TCCState *s1, const char *sym)
  1138. {
  1139. TokenSym *ts;
  1140. Sym *s;
  1141. ts = tok_alloc(sym, strlen(sym));
  1142. s = define_find(ts->tok);
  1143. /* undefine symbol by putting an invalid name */
  1144. if (s)
  1145. define_undef(s);
  1146. }
  1147. #ifdef CONFIG_TCC_ASM
  1148. #ifdef TCC_TARGET_I386
  1149. #include "i386-asm.c"
  1150. #endif
  1151. #include "tccasm.c"
  1152. #else
  1153. static void asm_instr(void)
  1154. {
  1155. error("inline asm() not supported");
  1156. }
  1157. static void asm_global_instr(void)
  1158. {
  1159. error("inline asm() not supported");
  1160. }
  1161. #endif
  1162. #include "tccelf.c"
  1163. #ifdef TCC_TARGET_COFF
  1164. #include "tcccoff.c"
  1165. #endif
  1166. #ifdef TCC_TARGET_PE
  1167. #include "tccpe.c"
  1168. #endif
  1169. #ifdef CONFIG_TCC_BACKTRACE
  1170. /* print the position in the source file of PC value 'pc' by reading
  1171. the stabs debug information */
  1172. static void rt_printline(unsigned long wanted_pc)
  1173. {
  1174. Stab_Sym *sym, *sym_end;
  1175. char func_name[128], last_func_name[128];
  1176. unsigned long func_addr, last_pc, pc;
  1177. const char *incl_files[INCLUDE_STACK_SIZE];
  1178. int incl_index, len, last_line_num, i;
  1179. const char *str, *p;
  1180. fprintf(stderr, "0x%08lx:", wanted_pc);
  1181. func_name[0] = '\0';
  1182. func_addr = 0;
  1183. incl_index = 0;
  1184. last_func_name[0] = '\0';
  1185. last_pc = 0xffffffff;
  1186. last_line_num = 1;
  1187. sym = (Stab_Sym *)stab_section->data + 1;
  1188. sym_end = (Stab_Sym *)(stab_section->data + stab_section->data_offset);
  1189. while (sym < sym_end) {
  1190. switch(sym->n_type) {
  1191. /* function start or end */
  1192. case N_FUN:
  1193. if (sym->n_strx == 0) {
  1194. /* we test if between last line and end of function */
  1195. pc = sym->n_value + func_addr;
  1196. if (wanted_pc >= last_pc && wanted_pc < pc)
  1197. goto found;
  1198. func_name[0] = '\0';
  1199. func_addr = 0;
  1200. } else {
  1201. str = stabstr_section->data + sym->n_strx;
  1202. p = strchr(str, ':');
  1203. if (!p) {
  1204. pstrcpy(func_name, sizeof(func_name), str);
  1205. } else {
  1206. len = p - str;
  1207. if (len > sizeof(func_name) - 1)
  1208. len = sizeof(func_name) - 1;
  1209. memcpy(func_name, str, len);
  1210. func_name[len] = '\0';
  1211. }
  1212. func_addr = sym->n_value;
  1213. }
  1214. break;
  1215. /* line number info */
  1216. case N_SLINE:
  1217. pc = sym->n_value + func_addr;
  1218. if (wanted_pc >= last_pc && wanted_pc < pc)
  1219. goto found;
  1220. last_pc = pc;
  1221. last_line_num = sym->n_desc;
  1222. /* XXX: slow! */
  1223. strcpy(last_func_name, func_name);
  1224. break;
  1225. /* include files */
  1226. case N_BINCL:
  1227. str = stabstr_section->data + sym->n_strx;
  1228. add_incl:
  1229. if (incl_index < INCLUDE_STACK_SIZE) {
  1230. incl_files[incl_index++] = str;
  1231. }
  1232. break;
  1233. case N_EINCL:
  1234. if (incl_index > 1)
  1235. incl_index--;
  1236. break;
  1237. case N_SO:
  1238. if (sym->n_strx == 0) {
  1239. incl_index = 0; /* end of translation unit */
  1240. } else {
  1241. str = stabstr_section->data + sym->n_strx;
  1242. /* do not add path */
  1243. len = strlen(str);
  1244. if (len > 0 && str[len - 1] != '/')
  1245. goto add_incl;
  1246. }
  1247. break;
  1248. }
  1249. sym++;
  1250. }
  1251. /* second pass: we try symtab symbols (no line number info) */
  1252. incl_index = 0;
  1253. {
  1254. ElfW(Sym) *sym, *sym_end;
  1255. int type;
  1256. sym_end = (ElfW(Sym) *)(symtab_section->data + symtab_section->data_offset);
  1257. for(sym = (ElfW(Sym) *)symtab_section->data + 1;
  1258. sym < sym_end;
  1259. sym++) {
  1260. type = ELFW(ST_TYPE)(sym->st_info);
  1261. if (type == STT_FUNC) {
  1262. if (wanted_pc >= sym->st_value &&
  1263. wanted_pc < sym->st_value + sym->st_size) {
  1264. pstrcpy(last_func_name, sizeof(last_func_name),
  1265. strtab_section->data + sym->st_name);
  1266. goto found;
  1267. }
  1268. }
  1269. }
  1270. }
  1271. /* did not find any info: */
  1272. fprintf(stderr, " ???\n");
  1273. return;
  1274. found:
  1275. if (last_func_name[0] != '\0') {
  1276. fprintf(stderr, " %s()", last_func_name);
  1277. }
  1278. if (incl_index > 0) {
  1279. fprintf(stderr, " (%s:%d",
  1280. incl_files[incl_index - 1], last_line_num);
  1281. for(i = incl_index - 2; i >= 0; i--)
  1282. fprintf(stderr, ", included from %s", incl_files[i]);
  1283. fprintf(stderr, ")");
  1284. }
  1285. fprintf(stderr, "\n");
  1286. }
  1287. #ifdef __i386__
  1288. /* fix for glibc 2.1 */
  1289. #ifndef REG_EIP
  1290. #define REG_EIP EIP
  1291. #define REG_EBP EBP
  1292. #endif
  1293. /* return the PC at frame level 'level'. Return non zero if not found */
  1294. static int rt_get_caller_pc(unsigned long *paddr,
  1295. ucontext_t *uc, int level)
  1296. {
  1297. unsigned long fp;
  1298. int i;
  1299. if (level == 0) {
  1300. #if defined(__FreeBSD__)
  1301. *paddr = uc->uc_mcontext.mc_eip;
  1302. #elif defined(__dietlibc__)
  1303. *paddr = uc->uc_mcontext.eip;
  1304. #else
  1305. *paddr = uc->uc_mcontext.gregs[REG_EIP];
  1306. #endif
  1307. return 0;
  1308. } else {
  1309. #if defined(__FreeBSD__)
  1310. fp = uc->uc_mcontext.mc_ebp;
  1311. #elif defined(__dietlibc__)
  1312. fp = uc->uc_mcontext.ebp;
  1313. #else
  1314. fp = uc->uc_mcontext.gregs[REG_EBP];
  1315. #endif
  1316. for(i=1;i<level;i++) {
  1317. /* XXX: check address validity with program info */
  1318. if (fp <= 0x1000 || fp >= 0xc0000000)
  1319. return -1;
  1320. fp = ((unsigned long *)fp)[0];
  1321. }
  1322. *paddr = ((unsigned long *)fp)[1];
  1323. return 0;
  1324. }
  1325. }
  1326. #elif defined(__x86_64__)
  1327. /* return the PC at frame level 'level'. Return non zero if not found */
  1328. static int rt_get_caller_pc(unsigned long *paddr,
  1329. ucontext_t *uc, int level)
  1330. {
  1331. unsigned long fp;
  1332. int i;
  1333. if (level == 0) {
  1334. /* XXX: only support linux */
  1335. *paddr = uc->uc_mcontext.gregs[REG_RIP];
  1336. return 0;
  1337. } else {
  1338. fp = uc->uc_mcontext.gregs[REG_RBP];
  1339. for(i=1;i<level;i++) {
  1340. /* XXX: check address validity with program info */
  1341. if (fp <= 0x1000)
  1342. return -1;
  1343. fp = ((unsigned long *)fp)[0];
  1344. }
  1345. *paddr = ((unsigned long *)fp)[1];
  1346. return 0;
  1347. }
  1348. }
  1349. #else
  1350. #warning add arch specific rt_get_caller_pc()
  1351. static int rt_get_caller_pc(unsigned long *paddr,
  1352. ucontext_t *uc, int level)
  1353. {
  1354. return -1;
  1355. }
  1356. #endif
  1357. /* emit a run time error at position 'pc' */
  1358. void rt_error(ucontext_t *uc, const char *fmt, ...)
  1359. {
  1360. va_list ap;
  1361. unsigned long pc;
  1362. int i;
  1363. va_start(ap, fmt);
  1364. fprintf(stderr, "Runtime error: ");
  1365. vfprintf(stderr, fmt, ap);
  1366. fprintf(stderr, "\n");
  1367. for(i=0;i<num_callers;i++) {
  1368. if (rt_get_caller_pc(&pc, uc, i) < 0)
  1369. break;
  1370. if (i == 0)
  1371. fprintf(stderr, "at ");
  1372. else
  1373. fprintf(stderr, "by ");
  1374. rt_printline(pc);
  1375. }
  1376. exit(255);
  1377. va_end(ap);
  1378. }
  1379. /* signal handler for fatal errors */
  1380. static void sig_error(int signum, siginfo_t *siginf, void *puc)
  1381. {
  1382. ucontext_t *uc = puc;
  1383. switch(signum) {
  1384. case SIGFPE:
  1385. switch(siginf->si_code) {
  1386. case FPE_INTDIV:
  1387. case FPE_FLTDIV:
  1388. rt_error(uc, "division by zero");
  1389. break;
  1390. default:
  1391. rt_error(uc, "floating point exception");
  1392. break;
  1393. }
  1394. break;
  1395. case SIGBUS:
  1396. case SIGSEGV:
  1397. if (rt_bound_error_msg && *rt_bound_error_msg)
  1398. rt_error(uc, *rt_bound_error_msg);
  1399. else
  1400. rt_error(uc, "dereferencing invalid pointer");
  1401. break;
  1402. case SIGILL:
  1403. rt_error(uc, "illegal instruction");
  1404. break;
  1405. case SIGABRT:
  1406. rt_error(uc, "abort() called");
  1407. break;
  1408. default:
  1409. rt_error(uc, "caught signal %d", signum);
  1410. break;
  1411. }
  1412. exit(255);
  1413. }
  1414. #endif
  1415. /* copy code into memory passed in by the caller and do all relocations
  1416. (needed before using tcc_get_symbol()).
  1417. returns -1 on error and required size if ptr is NULL */
  1418. int tcc_relocate(TCCState *s1, void *ptr)
  1419. {
  1420. Section *s;
  1421. unsigned long offset, length, mem;
  1422. int i;
  1423. if (0 == s1->runtime_added) {
  1424. s1->runtime_added = 1;
  1425. s1->nb_errors = 0;
  1426. #ifdef TCC_TARGET_PE
  1427. pe_add_runtime(s1);
  1428. relocate_common_syms();
  1429. tcc_add_linker_symbols(s1);
  1430. #else
  1431. tcc_add_runtime(s1);
  1432. relocate_common_syms();
  1433. tcc_add_linker_symbols(s1);
  1434. build_got_entries(s1);
  1435. #endif
  1436. }
  1437. offset = 0, mem = (unsigned long)ptr;
  1438. for(i = 1; i < s1->nb_sections; i++) {
  1439. s = s1->sections[i];
  1440. if (0 == (s->sh_flags & SHF_ALLOC))
  1441. continue;
  1442. length = s->data_offset;
  1443. s->sh_addr = mem ? (mem + offset + 15) & ~15 : 0;
  1444. offset = (offset + length + 15) & ~15;
  1445. }
  1446. /* relocate symbols */
  1447. relocate_syms(s1, 1);
  1448. if (s1->nb_errors)
  1449. return -1;
  1450. #ifdef TCC_TARGET_X86_64
  1451. s1->runtime_plt_and_got_offset = 0;
  1452. s1->runtime_plt_and_got = (char *)(mem + offset);
  1453. /* double the size of the buffer for got and plt entries
  1454. XXX: calculate exact size for them? */
  1455. offset *= 2;
  1456. #endif
  1457. if (0 == mem)
  1458. return offset + 15;
  1459. /* relocate each section */
  1460. for(i = 1; i < s1->nb_sections; i++) {
  1461. s = s1->sections[i];
  1462. if (s->reloc)
  1463. relocate_section(s1, s);
  1464. }
  1465. for(i = 1; i < s1->nb_sections; i++) {
  1466. s = s1->sections[i];
  1467. if (0 == (s->sh_flags & SHF_ALLOC))
  1468. continue;
  1469. length = s->data_offset;
  1470. // printf("%-12s %08x %04x\n", s->name, s->sh_addr, length);
  1471. ptr = (void*)s->sh_addr;
  1472. if (NULL == s->data || s->sh_type == SHT_NOBITS)
  1473. memset(ptr, 0, length);
  1474. else
  1475. memcpy(ptr, s->data, length);
  1476. /* mark executable sections as executable in memory */
  1477. if (s->sh_flags & SHF_EXECINSTR)
  1478. set_pages_executable(ptr, length);
  1479. }
  1480. #ifdef TCC_TARGET_X86_64
  1481. set_pages_executable(s1->runtime_plt_and_got,
  1482. s1->runtime_plt_and_got_offset);
  1483. #endif
  1484. return 0;
  1485. }
  1486. /* launch the compiled program with the given arguments */
  1487. int tcc_run(TCCState *s1, int argc, char **argv)
  1488. {
  1489. int (*prog_main)(int, char **);
  1490. void *ptr;
  1491. int ret;
  1492. ret = tcc_relocate(s1, NULL);
  1493. if (ret < 0)
  1494. return -1;
  1495. ptr = tcc_malloc(ret);
  1496. tcc_relocate(s1, ptr);
  1497. prog_main = tcc_get_symbol_err(s1, "main");
  1498. if (s1->do_debug) {
  1499. #ifdef CONFIG_TCC_BACKTRACE
  1500. struct sigaction sigact;
  1501. /* install TCC signal handlers to print debug info on fatal
  1502. runtime errors */
  1503. sigact.sa_flags = SA_SIGINFO | SA_RESETHAND;
  1504. sigact.sa_sigaction = sig_error;
  1505. sigemptyset(&sigact.sa_mask);
  1506. sigaction(SIGFPE, &sigact, NULL);
  1507. sigaction(SIGILL, &sigact, NULL);
  1508. sigaction(SIGSEGV, &sigact, NULL);
  1509. sigaction(SIGBUS, &sigact, NULL);
  1510. sigaction(SIGABRT, &sigact, NULL);
  1511. #else
  1512. error("debug mode not available");
  1513. #endif
  1514. }
  1515. #ifdef CONFIG_TCC_BCHECK
  1516. if (s1->do_bounds_check) {
  1517. void (*bound_init)(void);
  1518. /* set error function */
  1519. rt_bound_error_msg = tcc_get_symbol_err(s1, "__bound_error_msg");
  1520. /* XXX: use .init section so that it also work in binary ? */
  1521. bound_init = (void *)tcc_get_symbol_err(s1, "__bound_init");
  1522. bound_init();
  1523. }
  1524. #endif
  1525. ret = (*prog_main)(argc, argv);
  1526. tcc_free(ptr);
  1527. return ret;
  1528. }
  1529. void tcc_memstats(void)
  1530. {
  1531. #ifdef MEM_DEBUG
  1532. printf("memory in use: %d\n", mem_cur_size);
  1533. #endif
  1534. }
  1535. static void tcc_cleanup(void)
  1536. {
  1537. int i, n;
  1538. if (NULL == tcc_state)
  1539. return;
  1540. tcc_state = NULL;
  1541. /* free -D defines */
  1542. free_defines(NULL);
  1543. /* free tokens */
  1544. n = tok_ident - TOK_IDENT;
  1545. for(i = 0; i < n; i++)
  1546. tcc_free(table_ident[i]);
  1547. tcc_free(table_ident);
  1548. /* free sym_pools */
  1549. dynarray_reset(&sym_pools, &nb_sym_pools);
  1550. /* string buffer */
  1551. cstr_free(&tokcstr);
  1552. /* reset symbol stack */
  1553. sym_free_first = NULL;
  1554. /* cleanup from error/setjmp */
  1555. macro_ptr = NULL;
  1556. }
  1557. TCCState *tcc_new(void)
  1558. {
  1559. TCCState *s;
  1560. tcc_cleanup();
  1561. s = tcc_mallocz(sizeof(TCCState));
  1562. if (!s)
  1563. return NULL;
  1564. tcc_state = s;
  1565. s->output_type = TCC_OUTPUT_MEMORY;
  1566. s->tcc_lib_path = CONFIG_TCCDIR;
  1567. preprocess_new();
  1568. /* we add dummy defines for some special macros to speed up tests
  1569. and to have working defined() */
  1570. define_push(TOK___LINE__, MACRO_OBJ, NULL, NULL);
  1571. define_push(TOK___FILE__, MACRO_OBJ, NULL, NULL);
  1572. define_push(TOK___DATE__, MACRO_OBJ, NULL, NULL);
  1573. define_push(TOK___TIME__, MACRO_OBJ, NULL, NULL);
  1574. /* standard defines */
  1575. tcc_define_symbol(s, "__STDC__", NULL);
  1576. tcc_define_symbol(s, "__STDC_VERSION__", "199901L");
  1577. #if defined(TCC_TARGET_I386)
  1578. tcc_define_symbol(s, "__i386__", NULL);
  1579. #endif
  1580. #if defined(TCC_TARGET_X86_64)
  1581. tcc_define_symbol(s, "__x86_64__", NULL);
  1582. #endif
  1583. #if defined(TCC_TARGET_ARM)
  1584. tcc_define_symbol(s, "__ARM_ARCH_4__", NULL);
  1585. tcc_define_symbol(s, "__arm_elf__", NULL);
  1586. tcc_define_symbol(s, "__arm_elf", NULL);
  1587. tcc_define_symbol(s, "arm_elf", NULL);
  1588. tcc_define_symbol(s, "__arm__", NULL);
  1589. tcc_define_symbol(s, "__arm", NULL);
  1590. tcc_define_symbol(s, "arm", NULL);
  1591. tcc_define_symbol(s, "__APCS_32__", NULL);
  1592. #endif
  1593. #ifdef TCC_TARGET_PE
  1594. tcc_define_symbol(s, "_WIN32", NULL);
  1595. #else
  1596. tcc_define_symbol(s, "__unix__", NULL);
  1597. tcc_define_symbol(s, "__unix", NULL);
  1598. #if defined(__linux)
  1599. tcc_define_symbol(s, "__linux__", NULL);
  1600. tcc_define_symbol(s, "__linux", NULL);
  1601. #endif
  1602. #endif
  1603. /* tiny C specific defines */
  1604. tcc_define_symbol(s, "__TINYC__", NULL);
  1605. /* tiny C & gcc defines */
  1606. tcc_define_symbol(s, "__SIZE_TYPE__", "unsigned int");
  1607. tcc_define_symbol(s, "__PTRDIFF_TYPE__", "int");
  1608. #ifdef TCC_TARGET_PE
  1609. tcc_define_symbol(s, "__WCHAR_TYPE__", "unsigned short");
  1610. #else
  1611. tcc_define_symbol(s, "__WCHAR_TYPE__", "int");
  1612. #endif
  1613. #ifndef TCC_TARGET_PE
  1614. /* default library paths */
  1615. tcc_add_library_path(s, CONFIG_SYSROOT "/usr/local/lib");
  1616. tcc_add_library_path(s, CONFIG_SYSROOT "/usr/lib");
  1617. tcc_add_library_path(s, CONFIG_SYSROOT "/lib");
  1618. #endif
  1619. /* no section zero */
  1620. dynarray_add((void ***)&s->sections, &s->nb_sections, NULL);
  1621. /* create standard sections */
  1622. text_section = new_section(s, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
  1623. data_section = new_section(s, ".data", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
  1624. bss_section = new_section(s, ".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
  1625. /* symbols are always generated for linking stage */
  1626. symtab_section = new_symtab(s, ".symtab", SHT_SYMTAB, 0,
  1627. ".strtab",
  1628. ".hashtab", SHF_PRIVATE);
  1629. strtab_section = symtab_section->link;
  1630. /* private symbol table for dynamic symbols */
  1631. s->dynsymtab_section = new_symtab(s, ".dynsymtab", SHT_SYMTAB, SHF_PRIVATE,
  1632. ".dynstrtab",
  1633. ".dynhashtab", SHF_PRIVATE);
  1634. s->alacarte_link = 1;
  1635. #ifdef CHAR_IS_UNSIGNED
  1636. s->char_is_unsigned = 1;
  1637. #endif
  1638. #if defined(TCC_TARGET_PE) && 0
  1639. /* XXX: currently the PE linker is not ready to support that */
  1640. s->leading_underscore = 1;
  1641. #endif
  1642. return s;
  1643. }
  1644. void tcc_delete(TCCState *s1)
  1645. {
  1646. int i;
  1647. tcc_cleanup();
  1648. /* free all sections */
  1649. for(i = 1; i < s1->nb_sections; i++)
  1650. free_section(s1->sections[i]);
  1651. dynarray_reset(&s1->sections, &s1->nb_sections);
  1652. for(i = 0; i < s1->nb_priv_sections; i++)
  1653. free_section(s1->priv_sections[i]);
  1654. dynarray_reset(&s1->priv_sections, &s1->nb_priv_sections);
  1655. /* free any loaded DLLs */
  1656. for ( i = 0; i < s1->nb_loaded_dlls; i++) {
  1657. DLLReference *ref = s1->loaded_dlls[i];
  1658. if ( ref->handle )
  1659. dlclose(ref->handle);
  1660. }
  1661. /* free loaded dlls array */
  1662. dynarray_reset(&s1->loaded_dlls, &s1->nb_loaded_dlls);
  1663. /* free library paths */
  1664. dynarray_reset(&s1->library_paths, &s1->nb_library_paths);
  1665. /* free include paths */
  1666. dynarray_reset(&s1->cached_includes, &s1->nb_cached_includes);
  1667. dynarray_reset(&s1->include_paths, &s1->nb_include_paths);
  1668. dynarray_reset(&s1->sysinclude_paths, &s1->nb_sysinclude_paths);
  1669. tcc_free(s1);
  1670. }
  1671. int tcc_add_include_path(TCCState *s1, const char *pathname)
  1672. {
  1673. char *pathname1;
  1674. pathname1 = tcc_strdup(pathname);
  1675. dynarray_add((void ***)&s1->include_paths, &s1->nb_include_paths, pathname1);
  1676. return 0;
  1677. }
  1678. int tcc_add_sysinclude_path(TCCState *s1, const char *pathname)
  1679. {
  1680. char *pathname1;
  1681. pathname1 = tcc_strdup(pathname);
  1682. dynarray_add((void ***)&s1->sysinclude_paths, &s1->nb_sysinclude_paths, pathname1);
  1683. return 0;
  1684. }
  1685. static int tcc_add_file_internal(TCCState *s1, const char *filename, int flags)
  1686. {
  1687. const char *ext;
  1688. ElfW(Ehdr) ehdr;
  1689. int fd, ret;
  1690. BufferedFile *saved_file;
  1691. /* find source file type with extension */
  1692. ext = tcc_fileextension(filename);
  1693. if (ext[0])
  1694. ext++;
  1695. /* open the file */
  1696. saved_file = file;
  1697. file = tcc_open(s1, filename);
  1698. if (!file) {
  1699. if (flags & AFF_PRINT_ERROR) {
  1700. error_noabort("file '%s' not found", filename);
  1701. }
  1702. ret = -1;
  1703. goto fail1;
  1704. }
  1705. if (flags & AFF_PREPROCESS) {
  1706. ret = tcc_preprocess(s1);
  1707. } else if (!ext[0] || !PATHCMP(ext, "c")) {
  1708. /* C file assumed */
  1709. ret = tcc_compile(s1);
  1710. } else
  1711. #ifdef CONFIG_TCC_ASM
  1712. if (!strcmp(ext, "S")) {
  1713. /* preprocessed assembler */
  1714. ret = tcc_assemble(s1, 1);
  1715. } else if (!strcmp(ext, "s")) {
  1716. /* non preprocessed assembler */
  1717. ret = tcc_assemble(s1, 0);
  1718. } else
  1719. #endif
  1720. #ifdef TCC_TARGET_PE
  1721. if (!PATHCMP(ext, "def")) {
  1722. ret = pe_load_def_file(s1, file->fd);
  1723. } else
  1724. #endif
  1725. {
  1726. fd = file->fd;
  1727. /* assume executable format: auto guess file type */
  1728. ret = read(fd, &ehdr, sizeof(ehdr));
  1729. lseek(fd, 0, SEEK_SET);
  1730. if (ret <= 0) {
  1731. error_noabort("could not read header");
  1732. goto fail;
  1733. } else if (ret != sizeof(ehdr)) {
  1734. goto try_load_script;
  1735. }
  1736. if (ehdr.e_ident[0] == ELFMAG0 &&
  1737. ehdr.e_ident[1] == ELFMAG1 &&
  1738. ehdr.e_ident[2] == ELFMAG2 &&
  1739. ehdr.e_ident[3] == ELFMAG3) {
  1740. file->line_num = 0; /* do not display line number if error */
  1741. if (ehdr.e_type == ET_REL) {
  1742. ret = tcc_load_object_file(s1, fd, 0);
  1743. } else if (ehdr.e_type == ET_DYN) {
  1744. if (s1->output_type == TCC_OUTPUT_MEMORY) {
  1745. #ifdef TCC_TARGET_PE
  1746. ret = -1;
  1747. #else
  1748. void *h;
  1749. h = dlopen(filename, RTLD_GLOBAL | RTLD_LAZY);
  1750. if (h)
  1751. ret = 0;
  1752. else
  1753. ret = -1;
  1754. #endif
  1755. } else {
  1756. ret = tcc_load_dll(s1, fd, filename,
  1757. (flags & AFF_REFERENCED_DLL) != 0);
  1758. }
  1759. } else {
  1760. error_noabort("unrecognized ELF file");
  1761. goto fail;
  1762. }
  1763. } else if (memcmp((char *)&ehdr, ARMAG, 8) == 0) {
  1764. file->line_num = 0; /* do not display line number if error */
  1765. ret = tcc_load_archive(s1, fd);
  1766. } else
  1767. #ifdef TCC_TARGET_COFF
  1768. if (*(uint16_t *)(&ehdr) == COFF_C67_MAGIC) {
  1769. ret = tcc_load_coff(s1, fd);
  1770. } else
  1771. #endif
  1772. #ifdef TCC_TARGET_PE
  1773. if (pe_test_res_file(&ehdr, ret)) {
  1774. ret = pe_load_res_file(s1, fd);
  1775. } else
  1776. #endif
  1777. {
  1778. /* as GNU ld, consider it is an ld script if not recognized */
  1779. try_load_script:
  1780. ret = tcc_load_ldscript(s1);
  1781. if (ret < 0) {
  1782. error_noabort("unrecognized file type");
  1783. goto fail;
  1784. }
  1785. }
  1786. }
  1787. the_end:
  1788. tcc_close(file);
  1789. fail1:
  1790. file = saved_file;
  1791. return ret;
  1792. fail:
  1793. ret = -1;
  1794. goto the_end;
  1795. }
  1796. int tcc_add_file(TCCState *s, const char *filename)
  1797. {
  1798. if (s->output_type == TCC_OUTPUT_PREPROCESS)
  1799. return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR | AFF_PREPROCESS);
  1800. else
  1801. return tcc_add_file_internal(s, filename, AFF_PRINT_ERROR);
  1802. }
  1803. int tcc_add_library_path(TCCState *s, const char *pathname)
  1804. {
  1805. char *pathname1;
  1806. pathname1 = tcc_strdup(pathname);
  1807. dynarray_add((void ***)&s->library_paths, &s->nb_library_paths, pathname1);
  1808. return 0;
  1809. }
  1810. /* find and load a dll. Return non zero if not found */
  1811. /* XXX: add '-rpath' option support ? */
  1812. static int tcc_add_dll(TCCState *s, const char *filename, int flags)
  1813. {
  1814. char buf[1024];
  1815. int i;
  1816. for(i = 0; i < s->nb_library_paths; i++) {
  1817. snprintf(buf, sizeof(buf), "%s/%s",
  1818. s->library_paths[i], filename);
  1819. if (tcc_add_file_internal(s, buf, flags) == 0)
  1820. return 0;
  1821. }
  1822. return -1;
  1823. }
  1824. /* the library name is the same as the argument of the '-l' option */
  1825. int tcc_add_library(TCCState *s, const char *libraryname)
  1826. {
  1827. char buf[1024];
  1828. int i;
  1829. /* first we look for the dynamic library if not static linking */
  1830. if (!s->static_link) {
  1831. #ifdef TCC_TARGET_PE
  1832. snprintf(buf, sizeof(buf), "%s.def", libraryname);
  1833. #else
  1834. snprintf(buf, sizeof(buf), "lib%s.so", libraryname);
  1835. #endif
  1836. if (tcc_add_dll(s, buf, 0) == 0)
  1837. return 0;
  1838. }
  1839. /* then we look for the static library */
  1840. for(i = 0; i < s->nb_library_paths; i++) {
  1841. snprintf(buf, sizeof(buf), "%s/lib%s.a",
  1842. s->library_paths[i], libraryname);
  1843. if (tcc_add_file_internal(s, buf, 0) == 0)
  1844. return 0;
  1845. }
  1846. return -1;
  1847. }
  1848. int tcc_add_symbol(TCCState *s, const char *name, void *val)
  1849. {
  1850. add_elf_sym(symtab_section, (unsigned long)val, 0,
  1851. ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
  1852. SHN_ABS, name);
  1853. return 0;
  1854. }
  1855. int tcc_set_output_type(TCCState *s, int output_type)
  1856. {
  1857. char buf[1024];
  1858. s->output_type = output_type;
  1859. if (!s->nostdinc) {
  1860. /* default include paths */
  1861. /* XXX: reverse order needed if -isystem support */
  1862. #ifndef TCC_TARGET_PE
  1863. tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/local/include");
  1864. tcc_add_sysinclude_path(s, CONFIG_SYSROOT "/usr/include");
  1865. #endif
  1866. snprintf(buf, sizeof(buf), "%s/include", s->tcc_lib_path);
  1867. tcc_add_sysinclude_path(s, buf);
  1868. #ifdef TCC_TARGET_PE
  1869. snprintf(buf, sizeof(buf), "%s/include/winapi", s->tcc_lib_path);
  1870. tcc_add_sysinclude_path(s, buf);
  1871. #endif
  1872. }
  1873. /* if bound checking, then add corresponding sections */
  1874. #ifdef CONFIG_TCC_BCHECK
  1875. if (s->do_bounds_check) {
  1876. /* define symbol */
  1877. tcc_define_symbol(s, "__BOUNDS_CHECKING_ON", NULL);
  1878. /* create bounds sections */
  1879. bounds_section = new_section(s, ".bounds",
  1880. SHT_PROGBITS, SHF_ALLOC);
  1881. lbounds_section = new_section(s, ".lbounds",
  1882. SHT_PROGBITS, SHF_ALLOC);
  1883. }
  1884. #endif
  1885. if (s->char_is_unsigned) {
  1886. tcc_define_symbol(s, "__CHAR_UNSIGNED__", NULL);
  1887. }
  1888. /* add debug sections */
  1889. if (s->do_debug) {
  1890. /* stab symbols */
  1891. stab_section = new_section(s, ".stab", SHT_PROGBITS, 0);
  1892. stab_section->sh_entsize = sizeof(Stab_Sym);
  1893. stabstr_section = new_section(s, ".stabstr", SHT_STRTAB, 0);
  1894. put_elf_str(stabstr_section, "");
  1895. stab_section->link = stabstr_section;
  1896. /* put first entry */
  1897. put_stabs("", 0, 0, 0, 0);
  1898. }
  1899. /* add libc crt1/crti objects */
  1900. #ifndef TCC_TARGET_PE
  1901. if ((output_type == TCC_OUTPUT_EXE || output_type == TCC_OUTPUT_DLL) &&
  1902. !s->nostdlib) {
  1903. if (output_type != TCC_OUTPUT_DLL)
  1904. tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crt1.o");
  1905. tcc_add_file(s, CONFIG_TCC_CRT_PREFIX "/crti.o");
  1906. }
  1907. #endif
  1908. #ifdef TCC_TARGET_PE
  1909. snprintf(buf, sizeof(buf), "%s/lib", s->tcc_lib_path);
  1910. tcc_add_library_path(s, buf);
  1911. #endif
  1912. return 0;
  1913. }
  1914. #define WD_ALL 0x0001 /* warning is activated when using -Wall */
  1915. #define FD_INVERT 0x0002 /* invert value before storing */
  1916. typedef struct FlagDef {
  1917. uint16_t offset;
  1918. uint16_t flags;
  1919. const char *name;
  1920. } FlagDef;
  1921. static const FlagDef warning_defs[] = {
  1922. { offsetof(TCCState, warn_unsupported), 0, "unsupported" },
  1923. { offsetof(TCCState, warn_write_strings), 0, "write-strings" },
  1924. { offsetof(TCCState, warn_error), 0, "error" },
  1925. { offsetof(TCCState, warn_implicit_function_declaration), WD_ALL,
  1926. "implicit-function-declaration" },
  1927. };
  1928. static int set_flag(TCCState *s, const FlagDef *flags, int nb_flags,
  1929. const char *name, int value)
  1930. {
  1931. int i;
  1932. const FlagDef *p;
  1933. const char *r;
  1934. r = name;
  1935. if (r[0] == 'n' && r[1] == 'o' && r[2] == '-') {
  1936. r += 3;
  1937. value = !value;
  1938. }
  1939. for(i = 0, p = flags; i < nb_flags; i++, p++) {
  1940. if (!strcmp(r, p->name))
  1941. goto found;
  1942. }
  1943. return -1;
  1944. found:
  1945. if (p->flags & FD_INVERT)
  1946. value = !value;
  1947. *(int *)((uint8_t *)s + p->offset) = value;
  1948. return 0;
  1949. }
  1950. /* set/reset a warning */
  1951. int tcc_set_warning(TCCState *s, const char *warning_name, int value)
  1952. {
  1953. int i;
  1954. const FlagDef *p;
  1955. if (!strcmp(warning_name, "all")) {
  1956. for(i = 0, p = warning_defs; i < countof(warning_defs); i++, p++) {
  1957. if (p->flags & WD_ALL)
  1958. *(int *)((uint8_t *)s + p->offset) = 1;
  1959. }
  1960. return 0;
  1961. } else {
  1962. return set_flag(s, warning_defs, countof(warning_defs),
  1963. warning_name, value);
  1964. }
  1965. }
  1966. static const FlagDef flag_defs[] = {
  1967. { offsetof(TCCState, char_is_unsigned), 0, "unsigned-char" },
  1968. { offsetof(TCCState, char_is_unsigned), FD_INVERT, "signed-char" },
  1969. { offsetof(TCCState, nocommon), FD_INVERT, "common" },
  1970. { offsetof(TCCState, leading_underscore), 0, "leading-underscore" },
  1971. };
  1972. /* set/reset a flag */
  1973. int tcc_set_flag(TCCState *s, const char *flag_name, int value)
  1974. {
  1975. return set_flag(s, flag_defs, countof(flag_defs),
  1976. flag_name, value);
  1977. }
  1978. /* set CONFIG_TCCDIR at runtime */
  1979. void tcc_set_lib_path(TCCState *s, const char *path)
  1980. {
  1981. s->tcc_lib_path = tcc_strdup(path);
  1982. }
  1983. void tcc_print_stats(TCCState *s, int64_t total_time)
  1984. {
  1985. double tt;
  1986. tt = (double)total_time / 1000000.0;
  1987. if (tt < 0.001)
  1988. tt = 0.001;
  1989. if (total_bytes < 1)
  1990. total_bytes = 1;
  1991. printf("%d idents, %d lines, %d bytes, %0.3f s, %d lines/s, %0.1f MB/s\n",
  1992. tok_ident - TOK_IDENT, total_lines, total_bytes,
  1993. tt, (int)(total_lines / tt),
  1994. total_bytes / tt / 1000000.0);
  1995. }