tccelf.c 99 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061
  1. /*
  2. * ELF file handling for TCC
  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. /* Define this to get some debug output during relocation processing. */
  22. #undef DEBUG_RELOC
  23. /********************************************************/
  24. /* global variables */
  25. ST_DATA Section *text_section, *data_section, *bss_section; /* predefined sections */
  26. ST_DATA Section *common_section;
  27. ST_DATA Section *cur_text_section; /* current section where function code is generated */
  28. #ifdef CONFIG_TCC_ASM
  29. ST_DATA Section *last_text_section; /* to handle .previous asm directive */
  30. #endif
  31. #ifdef CONFIG_TCC_BCHECK
  32. /* bound check related sections */
  33. ST_DATA Section *bounds_section; /* contains global data bound description */
  34. ST_DATA Section *lbounds_section; /* contains local data bound description */
  35. #endif
  36. /* symbol sections */
  37. ST_DATA Section *symtab_section;
  38. /* debug sections */
  39. ST_DATA Section *stab_section, *stabstr_section;
  40. /* XXX: avoid static variable */
  41. static int new_undef_sym = 0; /* Is there a new undefined sym since last new_undef_sym() */
  42. /* special flag to indicate that the section should not be linked to the other ones */
  43. #define SHF_PRIVATE 0x80000000
  44. /* section is dynsymtab_section */
  45. #define SHF_DYNSYM 0x40000000
  46. /* ------------------------------------------------------------------------- */
  47. ST_FUNC void tccelf_new(TCCState *s)
  48. {
  49. /* no section zero */
  50. dynarray_add(&s->sections, &s->nb_sections, NULL);
  51. /* create standard sections */
  52. text_section = new_section(s, ".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
  53. data_section = new_section(s, ".data", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
  54. bss_section = new_section(s, ".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
  55. common_section = new_section(s, ".common", SHT_NOBITS, SHF_PRIVATE);
  56. common_section->sh_num = SHN_COMMON;
  57. /* symbols are always generated for linking stage */
  58. symtab_section = new_symtab(s, ".symtab", SHT_SYMTAB, 0,
  59. ".strtab",
  60. ".hashtab", SHF_PRIVATE);
  61. s->symtab = symtab_section;
  62. /* private symbol table for dynamic symbols */
  63. s->dynsymtab_section = new_symtab(s, ".dynsymtab", SHT_SYMTAB, SHF_PRIVATE|SHF_DYNSYM,
  64. ".dynstrtab",
  65. ".dynhashtab", SHF_PRIVATE);
  66. get_sym_attr(s, 0, 1);
  67. }
  68. #ifdef CONFIG_TCC_BCHECK
  69. ST_FUNC void tccelf_bounds_new(TCCState *s)
  70. {
  71. /* create bounds sections */
  72. bounds_section = new_section(s, ".bounds",
  73. SHT_PROGBITS, SHF_ALLOC);
  74. lbounds_section = new_section(s, ".lbounds",
  75. SHT_PROGBITS, SHF_ALLOC);
  76. }
  77. #endif
  78. ST_FUNC void tccelf_stab_new(TCCState *s)
  79. {
  80. stab_section = new_section(s, ".stab", SHT_PROGBITS, 0);
  81. stab_section->sh_entsize = sizeof(Stab_Sym);
  82. stabstr_section = new_section(s, ".stabstr", SHT_STRTAB, 0);
  83. put_elf_str(stabstr_section, "");
  84. stab_section->link = stabstr_section;
  85. /* put first entry */
  86. put_stabs("", 0, 0, 0, 0);
  87. }
  88. static void free_section(Section *s)
  89. {
  90. tcc_free(s->data);
  91. }
  92. ST_FUNC void tccelf_delete(TCCState *s1)
  93. {
  94. int i;
  95. /* free all sections */
  96. for(i = 1; i < s1->nb_sections; i++)
  97. free_section(s1->sections[i]);
  98. dynarray_reset(&s1->sections, &s1->nb_sections);
  99. for(i = 0; i < s1->nb_priv_sections; i++)
  100. free_section(s1->priv_sections[i]);
  101. dynarray_reset(&s1->priv_sections, &s1->nb_priv_sections);
  102. /* free any loaded DLLs */
  103. #ifdef TCC_IS_NATIVE
  104. for ( i = 0; i < s1->nb_loaded_dlls; i++) {
  105. DLLReference *ref = s1->loaded_dlls[i];
  106. if ( ref->handle )
  107. # ifdef _WIN32
  108. FreeLibrary((HMODULE)ref->handle);
  109. # else
  110. dlclose(ref->handle);
  111. # endif
  112. }
  113. #endif
  114. /* free loaded dlls array */
  115. dynarray_reset(&s1->loaded_dlls, &s1->nb_loaded_dlls);
  116. tcc_free(s1->sym_attrs);
  117. symtab_section = NULL; /* for tccrun.c:rt_printline() */
  118. }
  119. /* save section data state */
  120. ST_FUNC void tccelf_begin_file(TCCState *s1)
  121. {
  122. Section *s; int i;
  123. for (i = 1; i < s1->nb_sections; i++) {
  124. s = s1->sections[i];
  125. s->sh_offset = s->data_offset;
  126. }
  127. /* disable symbol hashing during compilation */
  128. s = s1->symtab, s->reloc = s->hash, s->hash = NULL;
  129. #if defined TCC_TARGET_X86_64 && defined TCC_TARGET_PE
  130. s1->uw_sym = 0;
  131. #endif
  132. }
  133. /* At the end of compilation, convert any UNDEF syms to global, and merge
  134. with previously existing symbols */
  135. ST_FUNC void tccelf_end_file(TCCState *s1)
  136. {
  137. Section *s = s1->symtab;
  138. int first_sym, nb_syms, *tr, i;
  139. first_sym = s->sh_offset / sizeof (ElfSym);
  140. nb_syms = s->data_offset / sizeof (ElfSym) - first_sym;
  141. s->data_offset = s->sh_offset;
  142. s->link->data_offset = s->link->sh_offset;
  143. s->hash = s->reloc, s->reloc = NULL;
  144. tr = tcc_mallocz(nb_syms * sizeof *tr);
  145. for (i = 0; i < nb_syms; ++i) {
  146. ElfSym *sym = (ElfSym*)s->data + first_sym + i;
  147. if (sym->st_shndx == SHN_UNDEF
  148. && ELFW(ST_BIND)(sym->st_info) == STB_LOCAL)
  149. sym->st_info = ELFW(ST_INFO)(STB_GLOBAL, ELFW(ST_TYPE)(sym->st_info));
  150. tr[i] = set_elf_sym(s, sym->st_value, sym->st_size, sym->st_info,
  151. sym->st_other, sym->st_shndx, s->link->data + sym->st_name);
  152. }
  153. /* now update relocations */
  154. for (i = 1; i < s1->nb_sections; i++) {
  155. Section *sr = s1->sections[i];
  156. if (sr->sh_type == SHT_RELX && sr->link == s) {
  157. ElfW_Rel *rel = (ElfW_Rel*)(sr->data + sr->sh_offset);
  158. ElfW_Rel *rel_end = (ElfW_Rel*)(sr->data + sr->data_offset);
  159. for (; rel < rel_end; ++rel) {
  160. int n = ELFW(R_SYM)(rel->r_info) - first_sym;
  161. //if (n < 0) tcc_error("internal: invalid symbol index in relocation");
  162. rel->r_info = ELFW(R_INFO)(tr[n], ELFW(R_TYPE)(rel->r_info));
  163. }
  164. }
  165. }
  166. tcc_free(tr);
  167. }
  168. ST_FUNC Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags)
  169. {
  170. Section *sec;
  171. sec = tcc_mallocz(sizeof(Section) + strlen(name));
  172. strcpy(sec->name, name);
  173. sec->sh_type = sh_type;
  174. sec->sh_flags = sh_flags;
  175. switch(sh_type) {
  176. case SHT_HASH:
  177. case SHT_REL:
  178. case SHT_RELA:
  179. case SHT_DYNSYM:
  180. case SHT_SYMTAB:
  181. case SHT_DYNAMIC:
  182. sec->sh_addralign = 4;
  183. break;
  184. case SHT_STRTAB:
  185. sec->sh_addralign = 1;
  186. break;
  187. default:
  188. sec->sh_addralign = PTR_SIZE; /* gcc/pcc default alignment */
  189. break;
  190. }
  191. if (sh_flags & SHF_PRIVATE) {
  192. dynarray_add(&s1->priv_sections, &s1->nb_priv_sections, sec);
  193. } else {
  194. sec->sh_num = s1->nb_sections;
  195. dynarray_add(&s1->sections, &s1->nb_sections, sec);
  196. }
  197. return sec;
  198. }
  199. ST_FUNC Section *new_symtab(TCCState *s1,
  200. const char *symtab_name, int sh_type, int sh_flags,
  201. const char *strtab_name,
  202. const char *hash_name, int hash_sh_flags)
  203. {
  204. Section *symtab, *strtab, *hash;
  205. int *ptr, nb_buckets;
  206. symtab = new_section(s1, symtab_name, sh_type, sh_flags);
  207. symtab->sh_entsize = sizeof(ElfW(Sym));
  208. strtab = new_section(s1, strtab_name, SHT_STRTAB, sh_flags);
  209. put_elf_str(strtab, "");
  210. symtab->link = strtab;
  211. put_elf_sym(symtab, 0, 0, 0, 0, 0, NULL);
  212. nb_buckets = 1;
  213. hash = new_section(s1, hash_name, SHT_HASH, hash_sh_flags);
  214. hash->sh_entsize = sizeof(int);
  215. symtab->hash = hash;
  216. hash->link = symtab;
  217. ptr = section_ptr_add(hash, (2 + nb_buckets + 1) * sizeof(int));
  218. ptr[0] = nb_buckets;
  219. ptr[1] = 1;
  220. memset(ptr + 2, 0, (nb_buckets + 1) * sizeof(int));
  221. return symtab;
  222. }
  223. /* realloc section and set its content to zero */
  224. ST_FUNC void section_realloc(Section *sec, unsigned long new_size)
  225. {
  226. unsigned long size;
  227. unsigned char *data;
  228. size = sec->data_allocated;
  229. if (size == 0)
  230. size = 1;
  231. while (size < new_size)
  232. size = size * 2;
  233. data = tcc_realloc(sec->data, size);
  234. memset(data + sec->data_allocated, 0, size - sec->data_allocated);
  235. sec->data = data;
  236. sec->data_allocated = size;
  237. }
  238. /* reserve at least 'size' bytes aligned per 'align' in section
  239. 'sec' from current offset, and return the aligned offset */
  240. ST_FUNC size_t section_add(Section *sec, addr_t size, int align)
  241. {
  242. size_t offset, offset1;
  243. offset = (sec->data_offset + align - 1) & -align;
  244. offset1 = offset + size;
  245. if (sec->sh_type != SHT_NOBITS && offset1 > sec->data_allocated)
  246. section_realloc(sec, offset1);
  247. sec->data_offset = offset1;
  248. if (align > sec->sh_addralign)
  249. sec->sh_addralign = align;
  250. return offset;
  251. }
  252. /* reserve at least 'size' bytes in section 'sec' from
  253. sec->data_offset. */
  254. ST_FUNC void *section_ptr_add(Section *sec, addr_t size)
  255. {
  256. size_t offset = section_add(sec, size, 1);
  257. return sec->data + offset;
  258. }
  259. /* reserve at least 'size' bytes from section start */
  260. ST_FUNC void section_reserve(Section *sec, unsigned long size)
  261. {
  262. if (size > sec->data_allocated)
  263. section_realloc(sec, size);
  264. if (size > sec->data_offset)
  265. sec->data_offset = size;
  266. }
  267. /* return a reference to a section, and create it if it does not
  268. exists */
  269. ST_FUNC Section *find_section(TCCState *s1, const char *name)
  270. {
  271. Section *sec;
  272. int i;
  273. for(i = 1; i < s1->nb_sections; i++) {
  274. sec = s1->sections[i];
  275. if (!strcmp(name, sec->name))
  276. return sec;
  277. }
  278. /* sections are created as PROGBITS */
  279. return new_section(s1, name, SHT_PROGBITS, SHF_ALLOC);
  280. }
  281. /* ------------------------------------------------------------------------- */
  282. ST_FUNC int put_elf_str(Section *s, const char *sym)
  283. {
  284. int offset, len;
  285. char *ptr;
  286. len = strlen(sym) + 1;
  287. offset = s->data_offset;
  288. ptr = section_ptr_add(s, len);
  289. memmove(ptr, sym, len);
  290. return offset;
  291. }
  292. /* elf symbol hashing function */
  293. static unsigned long elf_hash(const unsigned char *name)
  294. {
  295. unsigned long h = 0, g;
  296. while (*name) {
  297. h = (h << 4) + *name++;
  298. g = h & 0xf0000000;
  299. if (g)
  300. h ^= g >> 24;
  301. h &= ~g;
  302. }
  303. return h;
  304. }
  305. /* rebuild hash table of section s */
  306. /* NOTE: we do factorize the hash table code to go faster */
  307. static void rebuild_hash(Section *s, unsigned int nb_buckets)
  308. {
  309. ElfW(Sym) *sym;
  310. int *ptr, *hash, nb_syms, sym_index, h;
  311. unsigned char *strtab;
  312. strtab = s->link->data;
  313. nb_syms = s->data_offset / sizeof(ElfW(Sym));
  314. if (!nb_buckets)
  315. nb_buckets = ((int*)s->hash->data)[0];
  316. s->hash->data_offset = 0;
  317. ptr = section_ptr_add(s->hash, (2 + nb_buckets + nb_syms) * sizeof(int));
  318. ptr[0] = nb_buckets;
  319. ptr[1] = nb_syms;
  320. ptr += 2;
  321. hash = ptr;
  322. memset(hash, 0, (nb_buckets + 1) * sizeof(int));
  323. ptr += nb_buckets + 1;
  324. sym = (ElfW(Sym) *)s->data + 1;
  325. for(sym_index = 1; sym_index < nb_syms; sym_index++) {
  326. if (ELFW(ST_BIND)(sym->st_info) != STB_LOCAL) {
  327. h = elf_hash(strtab + sym->st_name) % nb_buckets;
  328. *ptr = hash[h];
  329. hash[h] = sym_index;
  330. } else {
  331. *ptr = 0;
  332. }
  333. ptr++;
  334. sym++;
  335. }
  336. }
  337. /* return the symbol number */
  338. ST_FUNC int put_elf_sym(Section *s, addr_t value, unsigned long size,
  339. int info, int other, int shndx, const char *name)
  340. {
  341. int name_offset, sym_index;
  342. int nbuckets, h;
  343. ElfW(Sym) *sym;
  344. Section *hs;
  345. sym = section_ptr_add(s, sizeof(ElfW(Sym)));
  346. if (name && name[0])
  347. name_offset = put_elf_str(s->link, name);
  348. else
  349. name_offset = 0;
  350. /* XXX: endianness */
  351. sym->st_name = name_offset;
  352. sym->st_value = value;
  353. sym->st_size = size;
  354. sym->st_info = info;
  355. sym->st_other = other;
  356. sym->st_shndx = shndx;
  357. sym_index = sym - (ElfW(Sym) *)s->data;
  358. hs = s->hash;
  359. if (hs) {
  360. int *ptr, *base;
  361. ptr = section_ptr_add(hs, sizeof(int));
  362. base = (int *)hs->data;
  363. /* only add global or weak symbols. */
  364. if (ELFW(ST_BIND)(info) != STB_LOCAL) {
  365. /* add another hashing entry */
  366. nbuckets = base[0];
  367. h = elf_hash((unsigned char *)s->link->data + name_offset) % nbuckets;
  368. *ptr = base[2 + h];
  369. base[2 + h] = sym_index;
  370. base[1]++;
  371. /* we resize the hash table */
  372. hs->nb_hashed_syms++;
  373. if (hs->nb_hashed_syms > 2 * nbuckets) {
  374. rebuild_hash(s, 2 * nbuckets);
  375. }
  376. } else {
  377. *ptr = 0;
  378. base[1]++;
  379. }
  380. }
  381. return sym_index;
  382. }
  383. ST_FUNC int find_elf_sym(Section *s, const char *name)
  384. {
  385. ElfW(Sym) *sym;
  386. Section *hs;
  387. int nbuckets, sym_index, h;
  388. const char *name1;
  389. hs = s->hash;
  390. if (!hs)
  391. return 0;
  392. nbuckets = ((int *)hs->data)[0];
  393. h = elf_hash((unsigned char *) name) % nbuckets;
  394. sym_index = ((int *)hs->data)[2 + h];
  395. while (sym_index != 0) {
  396. sym = &((ElfW(Sym) *)s->data)[sym_index];
  397. name1 = (char *) s->link->data + sym->st_name;
  398. if (!strcmp(name, name1))
  399. return sym_index;
  400. sym_index = ((int *)hs->data)[2 + nbuckets + sym_index];
  401. }
  402. return 0;
  403. }
  404. /* return elf symbol value, signal error if 'err' is nonzero */
  405. ST_FUNC addr_t get_elf_sym_addr(TCCState *s, const char *name, int err)
  406. {
  407. int sym_index;
  408. ElfW(Sym) *sym;
  409. sym_index = find_elf_sym(s->symtab, name);
  410. sym = &((ElfW(Sym) *)s->symtab->data)[sym_index];
  411. if (!sym_index || sym->st_shndx == SHN_UNDEF) {
  412. if (err)
  413. tcc_error("%s not defined", name);
  414. return 0;
  415. }
  416. return sym->st_value;
  417. }
  418. /* return elf symbol value */
  419. LIBTCCAPI void *tcc_get_symbol(TCCState *s, const char *name)
  420. {
  421. return (void*)(uintptr_t)get_elf_sym_addr(s, name, 0);
  422. }
  423. #if defined TCC_IS_NATIVE || defined TCC_TARGET_PE
  424. /* return elf symbol value or error */
  425. ST_FUNC void* tcc_get_symbol_err(TCCState *s, const char *name)
  426. {
  427. return (void*)(uintptr_t)get_elf_sym_addr(s, name, 1);
  428. }
  429. #endif
  430. /* add an elf symbol : check if it is already defined and patch
  431. it. Return symbol index. NOTE that sh_num can be SHN_UNDEF. */
  432. ST_FUNC int set_elf_sym(Section *s, addr_t value, unsigned long size,
  433. int info, int other, int shndx, const char *name)
  434. {
  435. ElfW(Sym) *esym;
  436. int sym_bind, sym_index, sym_type, esym_bind;
  437. unsigned char sym_vis, esym_vis, new_vis;
  438. sym_bind = ELFW(ST_BIND)(info);
  439. sym_type = ELFW(ST_TYPE)(info);
  440. sym_vis = ELFW(ST_VISIBILITY)(other);
  441. if (sym_bind != STB_LOCAL) {
  442. /* we search global or weak symbols */
  443. sym_index = find_elf_sym(s, name);
  444. if (!sym_index)
  445. goto do_def;
  446. esym = &((ElfW(Sym) *)s->data)[sym_index];
  447. if (esym->st_value == value && esym->st_size == size && esym->st_info == info
  448. && esym->st_other == other && esym->st_shndx == shndx)
  449. return sym_index;
  450. if (esym->st_shndx != SHN_UNDEF) {
  451. esym_bind = ELFW(ST_BIND)(esym->st_info);
  452. /* propagate the most constraining visibility */
  453. /* STV_DEFAULT(0)<STV_PROTECTED(3)<STV_HIDDEN(2)<STV_INTERNAL(1) */
  454. esym_vis = ELFW(ST_VISIBILITY)(esym->st_other);
  455. if (esym_vis == STV_DEFAULT) {
  456. new_vis = sym_vis;
  457. } else if (sym_vis == STV_DEFAULT) {
  458. new_vis = esym_vis;
  459. } else {
  460. new_vis = (esym_vis < sym_vis) ? esym_vis : sym_vis;
  461. }
  462. esym->st_other = (esym->st_other & ~ELFW(ST_VISIBILITY)(-1))
  463. | new_vis;
  464. other = esym->st_other; /* in case we have to patch esym */
  465. if (shndx == SHN_UNDEF) {
  466. /* ignore adding of undefined symbol if the
  467. corresponding symbol is already defined */
  468. } else if (sym_bind == STB_GLOBAL && esym_bind == STB_WEAK) {
  469. /* global overrides weak, so patch */
  470. goto do_patch;
  471. } else if (sym_bind == STB_WEAK && esym_bind == STB_GLOBAL) {
  472. /* weak is ignored if already global */
  473. } else if (sym_bind == STB_WEAK && esym_bind == STB_WEAK) {
  474. /* keep first-found weak definition, ignore subsequents */
  475. } else if (sym_vis == STV_HIDDEN || sym_vis == STV_INTERNAL) {
  476. /* ignore hidden symbols after */
  477. } else if ((esym->st_shndx == SHN_COMMON
  478. || esym->st_shndx == bss_section->sh_num)
  479. && (shndx < SHN_LORESERVE
  480. && shndx != bss_section->sh_num)) {
  481. /* data symbol gets precedence over common/bss */
  482. goto do_patch;
  483. } else if (shndx == SHN_COMMON || shndx == bss_section->sh_num) {
  484. /* data symbol keeps precedence over common/bss */
  485. } else if (s->sh_flags & SHF_DYNSYM) {
  486. /* we accept that two DLL define the same symbol */
  487. } else if (esym->st_other & ST_ASM_SET) {
  488. /* If the existing symbol came from an asm .set
  489. we can override. */
  490. goto do_patch;
  491. } else {
  492. #if 0
  493. printf("new_bind=%x new_shndx=%x new_vis=%x old_bind=%x old_shndx=%x old_vis=%x\n",
  494. sym_bind, shndx, new_vis, esym_bind, esym->st_shndx, esym_vis);
  495. #endif
  496. tcc_error_noabort("'%s' defined twice", name);
  497. }
  498. } else {
  499. do_patch:
  500. esym->st_info = ELFW(ST_INFO)(sym_bind, sym_type);
  501. esym->st_shndx = shndx;
  502. new_undef_sym = 1;
  503. esym->st_value = value;
  504. esym->st_size = size;
  505. esym->st_other = other;
  506. }
  507. } else {
  508. do_def:
  509. sym_index = put_elf_sym(s, value, size,
  510. ELFW(ST_INFO)(sym_bind, sym_type), other,
  511. shndx, name);
  512. }
  513. return sym_index;
  514. }
  515. /* put relocation */
  516. ST_FUNC void put_elf_reloca(Section *symtab, Section *s, unsigned long offset,
  517. int type, int symbol, addr_t addend)
  518. {
  519. char buf[256];
  520. Section *sr;
  521. ElfW_Rel *rel;
  522. sr = s->reloc;
  523. if (!sr) {
  524. /* if no relocation section, create it */
  525. snprintf(buf, sizeof(buf), REL_SECTION_FMT, s->name);
  526. /* if the symtab is allocated, then we consider the relocation
  527. are also */
  528. sr = new_section(tcc_state, buf, SHT_RELX, symtab->sh_flags);
  529. sr->sh_entsize = sizeof(ElfW_Rel);
  530. sr->link = symtab;
  531. sr->sh_info = s->sh_num;
  532. s->reloc = sr;
  533. }
  534. rel = section_ptr_add(sr, sizeof(ElfW_Rel));
  535. rel->r_offset = offset;
  536. rel->r_info = ELFW(R_INFO)(symbol, type);
  537. #if SHT_RELX == SHT_RELA
  538. rel->r_addend = addend;
  539. #else
  540. if (addend)
  541. tcc_error("non-zero addend on REL architecture");
  542. #endif
  543. }
  544. ST_FUNC void put_elf_reloc(Section *symtab, Section *s, unsigned long offset,
  545. int type, int symbol)
  546. {
  547. put_elf_reloca(symtab, s, offset, type, symbol, 0);
  548. }
  549. /* Remove relocations for section S->reloc starting at oldrelocoffset
  550. that are to the same place, retaining the last of them. As side effect
  551. the relocations are sorted. Possibly reduces the number of relocs. */
  552. ST_FUNC void squeeze_multi_relocs(Section *s, size_t oldrelocoffset)
  553. {
  554. Section *sr = s->reloc;
  555. ElfW_Rel *r, *dest;
  556. ssize_t a;
  557. ElfW(Addr) addr;
  558. if (oldrelocoffset + sizeof(*r) >= sr->data_offset)
  559. return;
  560. /* The relocs we're dealing with are the result of initializer parsing.
  561. So they will be mostly in order and there aren't many of them.
  562. Secondly we need a stable sort (which qsort isn't). We use
  563. a simple insertion sort. */
  564. for (a = oldrelocoffset + sizeof(*r); a < sr->data_offset; a += sizeof(*r)) {
  565. ssize_t i = a - sizeof(*r);
  566. addr = ((ElfW_Rel*)(sr->data + a))->r_offset;
  567. for (; i >= (ssize_t)oldrelocoffset &&
  568. ((ElfW_Rel*)(sr->data + i))->r_offset > addr; i -= sizeof(*r)) {
  569. ElfW_Rel tmp = *(ElfW_Rel*)(sr->data + a);
  570. *(ElfW_Rel*)(sr->data + a) = *(ElfW_Rel*)(sr->data + i);
  571. *(ElfW_Rel*)(sr->data + i) = tmp;
  572. }
  573. }
  574. r = (ElfW_Rel*)(sr->data + oldrelocoffset);
  575. dest = r;
  576. for (; r < (ElfW_Rel*)(sr->data + sr->data_offset); r++) {
  577. if (dest->r_offset != r->r_offset)
  578. dest++;
  579. *dest = *r;
  580. }
  581. sr->data_offset = (unsigned char*)dest - sr->data + sizeof(*r);
  582. }
  583. /* put stab debug information */
  584. ST_FUNC void put_stabs(const char *str, int type, int other, int desc,
  585. unsigned long value)
  586. {
  587. Stab_Sym *sym;
  588. sym = section_ptr_add(stab_section, sizeof(Stab_Sym));
  589. if (str) {
  590. sym->n_strx = put_elf_str(stabstr_section, str);
  591. } else {
  592. sym->n_strx = 0;
  593. }
  594. sym->n_type = type;
  595. sym->n_other = other;
  596. sym->n_desc = desc;
  597. sym->n_value = value;
  598. }
  599. ST_FUNC void put_stabs_r(const char *str, int type, int other, int desc,
  600. unsigned long value, Section *sec, int sym_index)
  601. {
  602. put_stabs(str, type, other, desc, value);
  603. put_elf_reloc(symtab_section, stab_section,
  604. stab_section->data_offset - sizeof(unsigned int),
  605. R_DATA_32, sym_index);
  606. }
  607. ST_FUNC void put_stabn(int type, int other, int desc, int value)
  608. {
  609. put_stabs(NULL, type, other, desc, value);
  610. }
  611. ST_FUNC void put_stabd(int type, int other, int desc)
  612. {
  613. put_stabs(NULL, type, other, desc, 0);
  614. }
  615. ST_FUNC struct sym_attr *get_sym_attr(TCCState *s1, int index, int alloc)
  616. {
  617. int n;
  618. struct sym_attr *tab;
  619. if (index >= s1->nb_sym_attrs) {
  620. if (!alloc)
  621. return s1->sym_attrs;
  622. /* find immediately bigger power of 2 and reallocate array */
  623. n = 1;
  624. while (index >= n)
  625. n *= 2;
  626. tab = tcc_realloc(s1->sym_attrs, n * sizeof(*s1->sym_attrs));
  627. s1->sym_attrs = tab;
  628. memset(s1->sym_attrs + s1->nb_sym_attrs, 0,
  629. (n - s1->nb_sym_attrs) * sizeof(*s1->sym_attrs));
  630. s1->nb_sym_attrs = n;
  631. }
  632. return &s1->sym_attrs[index];
  633. }
  634. /* Browse each elem of type <type> in section <sec> starting at elem <startoff>
  635. using variable <elem> */
  636. #define for_each_elem(sec, startoff, elem, type) \
  637. for (elem = (type *) sec->data + startoff; \
  638. elem < (type *) (sec->data + sec->data_offset); elem++)
  639. /* In an ELF file symbol table, the local symbols must appear below
  640. the global and weak ones. Since TCC cannot sort it while generating
  641. the code, we must do it after. All the relocation tables are also
  642. modified to take into account the symbol table sorting */
  643. static void sort_syms(TCCState *s1, Section *s)
  644. {
  645. int *old_to_new_syms;
  646. ElfW(Sym) *new_syms;
  647. int nb_syms, i;
  648. ElfW(Sym) *p, *q;
  649. ElfW_Rel *rel;
  650. Section *sr;
  651. int type, sym_index;
  652. nb_syms = s->data_offset / sizeof(ElfW(Sym));
  653. new_syms = tcc_malloc(nb_syms * sizeof(ElfW(Sym)));
  654. old_to_new_syms = tcc_malloc(nb_syms * sizeof(int));
  655. /* first pass for local symbols */
  656. p = (ElfW(Sym) *)s->data;
  657. q = new_syms;
  658. for(i = 0; i < nb_syms; i++) {
  659. if (ELFW(ST_BIND)(p->st_info) == STB_LOCAL) {
  660. old_to_new_syms[i] = q - new_syms;
  661. *q++ = *p;
  662. }
  663. p++;
  664. }
  665. /* save the number of local symbols in section header */
  666. if( s->sh_size ) /* this 'if' makes IDA happy */
  667. s->sh_info = q - new_syms;
  668. /* then second pass for non local symbols */
  669. p = (ElfW(Sym) *)s->data;
  670. for(i = 0; i < nb_syms; i++) {
  671. if (ELFW(ST_BIND)(p->st_info) != STB_LOCAL) {
  672. old_to_new_syms[i] = q - new_syms;
  673. *q++ = *p;
  674. }
  675. p++;
  676. }
  677. /* we copy the new symbols to the old */
  678. memcpy(s->data, new_syms, nb_syms * sizeof(ElfW(Sym)));
  679. tcc_free(new_syms);
  680. /* now we modify all the relocations */
  681. for(i = 1; i < s1->nb_sections; i++) {
  682. sr = s1->sections[i];
  683. if (sr->sh_type == SHT_RELX && sr->link == s) {
  684. for_each_elem(sr, 0, rel, ElfW_Rel) {
  685. sym_index = ELFW(R_SYM)(rel->r_info);
  686. type = ELFW(R_TYPE)(rel->r_info);
  687. sym_index = old_to_new_syms[sym_index];
  688. rel->r_info = ELFW(R_INFO)(sym_index, type);
  689. }
  690. }
  691. }
  692. tcc_free(old_to_new_syms);
  693. }
  694. /* relocate symbol table, resolve undefined symbols if do_resolve is
  695. true and output error if undefined symbol. */
  696. ST_FUNC void relocate_syms(TCCState *s1, Section *symtab, int do_resolve)
  697. {
  698. ElfW(Sym) *sym;
  699. int sym_bind, sh_num;
  700. const char *name;
  701. for_each_elem(symtab, 1, sym, ElfW(Sym)) {
  702. sh_num = sym->st_shndx;
  703. if (sh_num == SHN_UNDEF) {
  704. name = (char *) s1->symtab->link->data + sym->st_name;
  705. /* Use ld.so to resolve symbol for us (for tcc -run) */
  706. if (do_resolve) {
  707. #if defined TCC_IS_NATIVE && !defined TCC_TARGET_PE
  708. void *addr = dlsym(RTLD_DEFAULT, name);
  709. if (addr) {
  710. sym->st_value = (addr_t) addr;
  711. #ifdef DEBUG_RELOC
  712. printf ("relocate_sym: %s -> 0x%lx\n", name, sym->st_value);
  713. #endif
  714. goto found;
  715. }
  716. #endif
  717. /* if dynamic symbol exist, it will be used in relocate_section */
  718. } else if (s1->dynsym && find_elf_sym(s1->dynsym, name))
  719. goto found;
  720. /* XXX: _fp_hw seems to be part of the ABI, so we ignore
  721. it */
  722. if (!strcmp(name, "_fp_hw"))
  723. goto found;
  724. /* only weak symbols are accepted to be undefined. Their
  725. value is zero */
  726. sym_bind = ELFW(ST_BIND)(sym->st_info);
  727. if (sym_bind == STB_WEAK)
  728. sym->st_value = 0;
  729. else
  730. tcc_error_noabort("undefined symbol '%s'", name);
  731. } else if (sh_num < SHN_LORESERVE) {
  732. /* add section base */
  733. sym->st_value += s1->sections[sym->st_shndx]->sh_addr;
  734. }
  735. found: ;
  736. }
  737. }
  738. /* relocate a given section (CPU dependent) by applying the relocations
  739. in the associated relocation section */
  740. ST_FUNC void relocate_section(TCCState *s1, Section *s)
  741. {
  742. Section *sr = s->reloc;
  743. ElfW_Rel *rel;
  744. ElfW(Sym) *sym;
  745. int type, sym_index;
  746. unsigned char *ptr;
  747. addr_t tgt, addr;
  748. relocate_init(sr);
  749. for_each_elem(sr, 0, rel, ElfW_Rel) {
  750. ptr = s->data + rel->r_offset;
  751. sym_index = ELFW(R_SYM)(rel->r_info);
  752. sym = &((ElfW(Sym) *)symtab_section->data)[sym_index];
  753. type = ELFW(R_TYPE)(rel->r_info);
  754. tgt = sym->st_value;
  755. #if SHT_RELX == SHT_RELA
  756. tgt += rel->r_addend;
  757. #endif
  758. addr = s->sh_addr + rel->r_offset;
  759. relocate(s1, rel, type, ptr, addr, tgt);
  760. }
  761. /* if the relocation is allocated, we change its symbol table */
  762. if (sr->sh_flags & SHF_ALLOC)
  763. sr->link = s1->dynsym;
  764. }
  765. /* relocate relocation table in 'sr' */
  766. static void relocate_rel(TCCState *s1, Section *sr)
  767. {
  768. Section *s;
  769. ElfW_Rel *rel;
  770. s = s1->sections[sr->sh_info];
  771. for_each_elem(sr, 0, rel, ElfW_Rel)
  772. rel->r_offset += s->sh_addr;
  773. }
  774. /* count the number of dynamic relocations so that we can reserve
  775. their space */
  776. static int prepare_dynamic_rel(TCCState *s1, Section *sr)
  777. {
  778. ElfW_Rel *rel;
  779. int sym_index, type, count;
  780. count = 0;
  781. for_each_elem(sr, 0, rel, ElfW_Rel) {
  782. sym_index = ELFW(R_SYM)(rel->r_info);
  783. type = ELFW(R_TYPE)(rel->r_info);
  784. switch(type) {
  785. #if defined(TCC_TARGET_I386) || defined(TCC_TARGET_X86_64)
  786. #if defined(TCC_TARGET_I386)
  787. case R_386_32:
  788. if (!get_sym_attr(s1, sym_index, 0)->dyn_index
  789. && ((ElfW(Sym)*)symtab_section->data + sym_index)->st_shndx == SHN_UNDEF) {
  790. /* don't fixup unresolved (weak) symbols */
  791. rel->r_info = ELFW(R_INFO)(sym_index, R_386_RELATIVE);
  792. break;
  793. }
  794. #elif defined(TCC_TARGET_X86_64)
  795. case R_X86_64_32:
  796. case R_X86_64_32S:
  797. case R_X86_64_64:
  798. #endif
  799. count++;
  800. break;
  801. #if defined(TCC_TARGET_I386)
  802. case R_386_PC32:
  803. #elif defined(TCC_TARGET_X86_64)
  804. case R_X86_64_PC32:
  805. #endif
  806. if (get_sym_attr(s1, sym_index, 0)->dyn_index)
  807. count++;
  808. break;
  809. #endif
  810. default:
  811. break;
  812. }
  813. }
  814. if (count) {
  815. /* allocate the section */
  816. sr->sh_flags |= SHF_ALLOC;
  817. sr->sh_size = count * sizeof(ElfW_Rel);
  818. }
  819. return count;
  820. }
  821. static void build_got(TCCState *s1)
  822. {
  823. /* if no got, then create it */
  824. s1->got = new_section(s1, ".got", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
  825. s1->got->sh_entsize = 4;
  826. set_elf_sym(symtab_section, 0, 4, ELFW(ST_INFO)(STB_GLOBAL, STT_OBJECT),
  827. 0, s1->got->sh_num, "_GLOBAL_OFFSET_TABLE_");
  828. /* keep space for _DYNAMIC pointer and two dummy got entries */
  829. section_ptr_add(s1->got, 3 * PTR_SIZE);
  830. }
  831. /* Create a GOT and (for function call) a PLT entry corresponding to a symbol
  832. in s1->symtab. When creating the dynamic symbol table entry for the GOT
  833. relocation, use 'size' and 'info' for the corresponding symbol metadata.
  834. Returns the offset of the GOT or (if any) PLT entry. */
  835. static struct sym_attr * put_got_entry(TCCState *s1, int dyn_reloc_type,
  836. unsigned long size,
  837. int info, int sym_index)
  838. {
  839. int need_plt_entry;
  840. const char *name;
  841. ElfW(Sym) *sym;
  842. struct sym_attr *attr;
  843. unsigned got_offset;
  844. char plt_name[100];
  845. int len;
  846. need_plt_entry = (dyn_reloc_type == R_JMP_SLOT);
  847. attr = get_sym_attr(s1, sym_index, 1);
  848. /* In case a function is both called and its address taken 2 GOT entries
  849. are created, one for taking the address (GOT) and the other for the PLT
  850. entry (PLTGOT). */
  851. if (need_plt_entry ? attr->plt_offset : attr->got_offset)
  852. return attr;
  853. /* create the GOT entry */
  854. got_offset = s1->got->data_offset;
  855. section_ptr_add(s1->got, PTR_SIZE);
  856. /* Create the GOT relocation that will insert the address of the object or
  857. function of interest in the GOT entry. This is a static relocation for
  858. memory output (dlsym will give us the address of symbols) and dynamic
  859. relocation otherwise (executable and DLLs). The relocation should be
  860. done lazily for GOT entry with *_JUMP_SLOT relocation type (the one
  861. associated to a PLT entry) but is currently done at load time for an
  862. unknown reason. */
  863. sym = &((ElfW(Sym) *) symtab_section->data)[sym_index];
  864. name = (char *) symtab_section->link->data + sym->st_name;
  865. if (s1->dynsym) {
  866. if (ELFW(ST_BIND)(sym->st_info) == STB_LOCAL) {
  867. /* Hack alarm. We don't want to emit dynamic symbols
  868. and symbol based relocs for STB_LOCAL symbols, but rather
  869. want to resolve them directly. At this point the symbol
  870. values aren't final yet, so we must defer this. We will later
  871. have to create a RELATIVE reloc anyway, so we misuse the
  872. relocation slot to smuggle the symbol reference until
  873. fill_local_got_entries. Not that the sym_index is
  874. relative to symtab_section, not s1->dynsym! Nevertheless
  875. we use s1->dyn_sym so that if this is the first call
  876. that got->reloc is correctly created. Also note that
  877. RELATIVE relocs are not normally created for the .got,
  878. so the types serves as a marker for later (and is retained
  879. also for the final output, which is okay because then the
  880. got is just normal data). */
  881. put_elf_reloc(s1->dynsym, s1->got, got_offset, R_RELATIVE,
  882. sym_index);
  883. } else {
  884. if (0 == attr->dyn_index)
  885. attr->dyn_index = set_elf_sym(s1->dynsym, sym->st_value, size,
  886. info, 0, sym->st_shndx, name);
  887. put_elf_reloc(s1->dynsym, s1->got, got_offset, dyn_reloc_type,
  888. attr->dyn_index);
  889. }
  890. } else {
  891. put_elf_reloc(symtab_section, s1->got, got_offset, dyn_reloc_type,
  892. sym_index);
  893. }
  894. if (need_plt_entry) {
  895. if (!s1->plt) {
  896. s1->plt = new_section(s1, ".plt", SHT_PROGBITS,
  897. SHF_ALLOC | SHF_EXECINSTR);
  898. s1->plt->sh_entsize = 4;
  899. }
  900. attr->plt_offset = create_plt_entry(s1, got_offset, attr);
  901. /* create a symbol 'sym@plt' for the PLT jump vector */
  902. len = strlen(name);
  903. if (len > sizeof plt_name - 5)
  904. len = sizeof plt_name - 5;
  905. memcpy(plt_name, name, len);
  906. strcpy(plt_name + len, "@plt");
  907. attr->plt_sym = put_elf_sym(s1->symtab, attr->plt_offset, sym->st_size,
  908. ELFW(ST_INFO)(STB_GLOBAL, STT_FUNC), 0, s1->plt->sh_num, plt_name);
  909. } else {
  910. attr->got_offset = got_offset;
  911. }
  912. return attr;
  913. }
  914. /* build GOT and PLT entries */
  915. ST_FUNC void build_got_entries(TCCState *s1)
  916. {
  917. Section *s;
  918. ElfW_Rel *rel;
  919. ElfW(Sym) *sym;
  920. int i, type, gotplt_entry, reloc_type, sym_index;
  921. struct sym_attr *attr;
  922. for(i = 1; i < s1->nb_sections; i++) {
  923. s = s1->sections[i];
  924. if (s->sh_type != SHT_RELX)
  925. continue;
  926. /* no need to handle got relocations */
  927. if (s->link != symtab_section)
  928. continue;
  929. for_each_elem(s, 0, rel, ElfW_Rel) {
  930. type = ELFW(R_TYPE)(rel->r_info);
  931. gotplt_entry = gotplt_entry_type(type);
  932. sym_index = ELFW(R_SYM)(rel->r_info);
  933. sym = &((ElfW(Sym) *)symtab_section->data)[sym_index];
  934. if (gotplt_entry == NO_GOTPLT_ENTRY) {
  935. continue;
  936. }
  937. /* Automatically create PLT/GOT [entry] if it is an undefined
  938. reference (resolved at runtime), or the symbol is absolute,
  939. probably created by tcc_add_symbol, and thus on 64-bit
  940. targets might be too far from application code. */
  941. if (gotplt_entry == AUTO_GOTPLT_ENTRY) {
  942. if (sym->st_shndx == SHN_UNDEF) {
  943. ElfW(Sym) *esym;
  944. int dynindex;
  945. if (s1->output_type == TCC_OUTPUT_DLL && ! PCRELATIVE_DLLPLT)
  946. continue;
  947. /* Relocations for UNDEF symbols would normally need
  948. to be transferred into the executable or shared object.
  949. If that were done AUTO_GOTPLT_ENTRY wouldn't exist.
  950. But TCC doesn't do that (at least for exes), so we
  951. need to resolve all such relocs locally. And that
  952. means PLT slots for functions in DLLs and COPY relocs for
  953. data symbols. COPY relocs were generated in
  954. bind_exe_dynsyms (and the symbol adjusted to be defined),
  955. and for functions we were generated a dynamic symbol
  956. of function type. */
  957. if (s1->dynsym) {
  958. /* dynsym isn't set for -run :-/ */
  959. dynindex = get_sym_attr(s1, sym_index, 0)->dyn_index;
  960. esym = (ElfW(Sym) *)s1->dynsym->data + dynindex;
  961. if (dynindex
  962. && (ELFW(ST_TYPE)(esym->st_info) == STT_FUNC
  963. || (ELFW(ST_TYPE)(esym->st_info) == STT_NOTYPE
  964. && ELFW(ST_TYPE)(sym->st_info) == STT_FUNC)))
  965. goto jmp_slot;
  966. }
  967. } else if (!(sym->st_shndx == SHN_ABS
  968. #ifndef TCC_TARGET_ARM
  969. && PTR_SIZE == 8
  970. #endif
  971. ))
  972. continue;
  973. }
  974. #ifdef TCC_TARGET_X86_64
  975. if ((type == R_X86_64_PLT32 || type == R_X86_64_PC32) &&
  976. (ELFW(ST_VISIBILITY)(sym->st_other) != STV_DEFAULT ||
  977. ELFW(ST_BIND)(sym->st_info) == STB_LOCAL)) {
  978. rel->r_info = ELFW(R_INFO)(sym_index, R_X86_64_PC32);
  979. continue;
  980. }
  981. #endif
  982. if (code_reloc(type)) {
  983. jmp_slot:
  984. reloc_type = R_JMP_SLOT;
  985. } else
  986. reloc_type = R_GLOB_DAT;
  987. if (!s1->got)
  988. build_got(s1);
  989. if (gotplt_entry == BUILD_GOT_ONLY)
  990. continue;
  991. attr = put_got_entry(s1, reloc_type, sym->st_size, sym->st_info,
  992. sym_index);
  993. if (reloc_type == R_JMP_SLOT)
  994. rel->r_info = ELFW(R_INFO)(attr->plt_sym, type);
  995. }
  996. }
  997. }
  998. /* put dynamic tag */
  999. static void put_dt(Section *dynamic, int dt, addr_t val)
  1000. {
  1001. ElfW(Dyn) *dyn;
  1002. dyn = section_ptr_add(dynamic, sizeof(ElfW(Dyn)));
  1003. dyn->d_tag = dt;
  1004. dyn->d_un.d_val = val;
  1005. }
  1006. #ifndef TCC_TARGET_PE
  1007. static void add_init_array_defines(TCCState *s1, const char *section_name)
  1008. {
  1009. Section *s;
  1010. long end_offset;
  1011. char sym_start[1024];
  1012. char sym_end[1024];
  1013. snprintf(sym_start, sizeof(sym_start), "__%s_start", section_name + 1);
  1014. snprintf(sym_end, sizeof(sym_end), "__%s_end", section_name + 1);
  1015. s = find_section(s1, section_name);
  1016. if (!s) {
  1017. end_offset = 0;
  1018. s = data_section;
  1019. } else {
  1020. end_offset = s->data_offset;
  1021. }
  1022. set_elf_sym(symtab_section,
  1023. 0, 0,
  1024. ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
  1025. s->sh_num, sym_start);
  1026. set_elf_sym(symtab_section,
  1027. end_offset, 0,
  1028. ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
  1029. s->sh_num, sym_end);
  1030. }
  1031. static int tcc_add_support(TCCState *s1, const char *filename)
  1032. {
  1033. char buf[1024];
  1034. snprintf(buf, sizeof(buf), "%s/%s", s1->tcc_lib_path, filename);
  1035. return tcc_add_file(s1, buf);
  1036. }
  1037. #endif
  1038. ST_FUNC void tcc_add_bcheck(TCCState *s1)
  1039. {
  1040. #ifdef CONFIG_TCC_BCHECK
  1041. addr_t *ptr;
  1042. int sym_index;
  1043. if (0 == s1->do_bounds_check)
  1044. return;
  1045. /* XXX: add an object file to do that */
  1046. ptr = section_ptr_add(bounds_section, sizeof(*ptr));
  1047. *ptr = 0;
  1048. set_elf_sym(symtab_section, 0, 0,
  1049. ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
  1050. bounds_section->sh_num, "__bounds_start");
  1051. /* pull bcheck.o from libtcc1.a */
  1052. sym_index = set_elf_sym(symtab_section, 0, 0,
  1053. ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
  1054. SHN_UNDEF, "__bound_init");
  1055. if (s1->output_type != TCC_OUTPUT_MEMORY) {
  1056. /* add 'call __bound_init()' in .init section */
  1057. Section *init_section = find_section(s1, ".init");
  1058. unsigned char *pinit = section_ptr_add(init_section, 5);
  1059. pinit[0] = 0xe8;
  1060. write32le(pinit + 1, -4);
  1061. put_elf_reloc(symtab_section, init_section,
  1062. init_section->data_offset - 4, R_386_PC32, sym_index);
  1063. /* R_386_PC32 = R_X86_64_PC32 = 2 */
  1064. }
  1065. #endif
  1066. }
  1067. /* add tcc runtime libraries */
  1068. ST_FUNC void tcc_add_runtime(TCCState *s1)
  1069. {
  1070. s1->filetype = 0;
  1071. tcc_add_bcheck(s1);
  1072. tcc_add_pragma_libs(s1);
  1073. #ifndef TCC_TARGET_PE
  1074. /* add libc */
  1075. if (!s1->nostdlib) {
  1076. tcc_add_library_err(s1, "c");
  1077. #ifdef TCC_LIBGCC
  1078. if (!s1->static_link) {
  1079. if (TCC_LIBGCC[0] == '/')
  1080. tcc_add_file(s1, TCC_LIBGCC);
  1081. else
  1082. tcc_add_dll(s1, TCC_LIBGCC, 0);
  1083. }
  1084. #endif
  1085. tcc_add_support(s1, TCC_LIBTCC1);
  1086. /* add crt end if not memory output */
  1087. if (s1->output_type != TCC_OUTPUT_MEMORY)
  1088. tcc_add_crt(s1, "crtn.o");
  1089. }
  1090. #endif
  1091. }
  1092. /* add various standard linker symbols (must be done after the
  1093. sections are filled (for example after allocating common
  1094. symbols)) */
  1095. static void tcc_add_linker_symbols(TCCState *s1)
  1096. {
  1097. char buf[1024];
  1098. int i;
  1099. Section *s;
  1100. set_elf_sym(symtab_section,
  1101. text_section->data_offset, 0,
  1102. ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
  1103. text_section->sh_num, "_etext");
  1104. set_elf_sym(symtab_section,
  1105. data_section->data_offset, 0,
  1106. ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
  1107. data_section->sh_num, "_edata");
  1108. set_elf_sym(symtab_section,
  1109. bss_section->data_offset, 0,
  1110. ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
  1111. bss_section->sh_num, "_end");
  1112. #ifndef TCC_TARGET_PE
  1113. /* horrible new standard ldscript defines */
  1114. add_init_array_defines(s1, ".preinit_array");
  1115. add_init_array_defines(s1, ".init_array");
  1116. add_init_array_defines(s1, ".fini_array");
  1117. #endif
  1118. /* add start and stop symbols for sections whose name can be
  1119. expressed in C */
  1120. for(i = 1; i < s1->nb_sections; i++) {
  1121. s = s1->sections[i];
  1122. if (s->sh_type == SHT_PROGBITS &&
  1123. (s->sh_flags & SHF_ALLOC)) {
  1124. const char *p;
  1125. int ch;
  1126. /* check if section name can be expressed in C */
  1127. p = s->name;
  1128. for(;;) {
  1129. ch = *p;
  1130. if (!ch)
  1131. break;
  1132. if (!isid(ch) && !isnum(ch))
  1133. goto next_sec;
  1134. p++;
  1135. }
  1136. snprintf(buf, sizeof(buf), "__start_%s", s->name);
  1137. set_elf_sym(symtab_section,
  1138. 0, 0,
  1139. ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
  1140. s->sh_num, buf);
  1141. snprintf(buf, sizeof(buf), "__stop_%s", s->name);
  1142. set_elf_sym(symtab_section,
  1143. s->data_offset, 0,
  1144. ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0,
  1145. s->sh_num, buf);
  1146. }
  1147. next_sec: ;
  1148. }
  1149. }
  1150. ST_FUNC void resolve_common_syms(TCCState *s1)
  1151. {
  1152. ElfW(Sym) *sym;
  1153. /* Allocate common symbols in BSS. */
  1154. for_each_elem(symtab_section, 1, sym, ElfW(Sym)) {
  1155. if (sym->st_shndx == SHN_COMMON) {
  1156. /* symbol alignment is in st_value for SHN_COMMONs */
  1157. sym->st_value = section_add(bss_section, sym->st_size,
  1158. sym->st_value);
  1159. sym->st_shndx = bss_section->sh_num;
  1160. }
  1161. }
  1162. /* Now assign linker provided symbols their value. */
  1163. tcc_add_linker_symbols(s1);
  1164. }
  1165. static void tcc_output_binary(TCCState *s1, FILE *f,
  1166. const int *sec_order)
  1167. {
  1168. Section *s;
  1169. int i, offset, size;
  1170. offset = 0;
  1171. for(i=1;i<s1->nb_sections;i++) {
  1172. s = s1->sections[sec_order[i]];
  1173. if (s->sh_type != SHT_NOBITS &&
  1174. (s->sh_flags & SHF_ALLOC)) {
  1175. while (offset < s->sh_offset) {
  1176. fputc(0, f);
  1177. offset++;
  1178. }
  1179. size = s->sh_size;
  1180. fwrite(s->data, 1, size, f);
  1181. offset += size;
  1182. }
  1183. }
  1184. }
  1185. ST_FUNC void fill_got_entry(TCCState *s1, ElfW_Rel *rel)
  1186. {
  1187. int sym_index = ELFW(R_SYM) (rel->r_info);
  1188. ElfW(Sym) *sym = &((ElfW(Sym) *) symtab_section->data)[sym_index];
  1189. struct sym_attr *attr = get_sym_attr(s1, sym_index, 0);
  1190. unsigned offset = attr->got_offset;
  1191. if (0 == offset)
  1192. return;
  1193. section_reserve(s1->got, offset + PTR_SIZE);
  1194. #ifdef TCC_TARGET_X86_64
  1195. write64le(s1->got->data + offset, sym->st_value);
  1196. #else
  1197. write32le(s1->got->data + offset, sym->st_value);
  1198. #endif
  1199. }
  1200. /* Perform relocation to GOT or PLT entries */
  1201. ST_FUNC void fill_got(TCCState *s1)
  1202. {
  1203. Section *s;
  1204. ElfW_Rel *rel;
  1205. int i;
  1206. for(i = 1; i < s1->nb_sections; i++) {
  1207. s = s1->sections[i];
  1208. if (s->sh_type != SHT_RELX)
  1209. continue;
  1210. /* no need to handle got relocations */
  1211. if (s->link != symtab_section)
  1212. continue;
  1213. for_each_elem(s, 0, rel, ElfW_Rel) {
  1214. switch (ELFW(R_TYPE) (rel->r_info)) {
  1215. case R_X86_64_GOT32:
  1216. case R_X86_64_GOTPCREL:
  1217. case R_X86_64_GOTPCRELX:
  1218. case R_X86_64_REX_GOTPCRELX:
  1219. case R_X86_64_PLT32:
  1220. fill_got_entry(s1, rel);
  1221. break;
  1222. }
  1223. }
  1224. }
  1225. }
  1226. /* See put_got_entry for a description. This is the second stage
  1227. where GOT references to local defined symbols are rewritten. */
  1228. static void fill_local_got_entries(TCCState *s1)
  1229. {
  1230. ElfW_Rel *rel;
  1231. if (!s1->got->reloc)
  1232. return;
  1233. for_each_elem(s1->got->reloc, 0, rel, ElfW_Rel) {
  1234. if (ELFW(R_TYPE)(rel->r_info) == R_RELATIVE) {
  1235. int sym_index = ELFW(R_SYM) (rel->r_info);
  1236. ElfW(Sym) *sym = &((ElfW(Sym) *) symtab_section->data)[sym_index];
  1237. struct sym_attr *attr = get_sym_attr(s1, sym_index, 0);
  1238. unsigned offset = attr->got_offset;
  1239. if (offset != rel->r_offset - s1->got->sh_addr)
  1240. tcc_error_noabort("huh");
  1241. rel->r_info = ELFW(R_INFO)(0, R_RELATIVE);
  1242. #if SHT_RELX == SHT_RELA
  1243. rel->r_addend = sym->st_value;
  1244. #else
  1245. /* All our REL architectures also happen to be 32bit LE. */
  1246. write32le(s1->got->data + offset, sym->st_value);
  1247. #endif
  1248. }
  1249. }
  1250. }
  1251. /* Bind symbols of executable: resolve undefined symbols from exported symbols
  1252. in shared libraries and export non local defined symbols to shared libraries
  1253. if -rdynamic switch was given on command line */
  1254. static void bind_exe_dynsyms(TCCState *s1)
  1255. {
  1256. const char *name;
  1257. int sym_index, index;
  1258. ElfW(Sym) *sym, *esym;
  1259. int type;
  1260. /* Resolve undefined symbols from dynamic symbols. When there is a match:
  1261. - if STT_FUNC or STT_GNU_IFUNC symbol -> add it in PLT
  1262. - if STT_OBJECT symbol -> add it in .bss section with suitable reloc */
  1263. for_each_elem(symtab_section, 1, sym, ElfW(Sym)) {
  1264. if (sym->st_shndx == SHN_UNDEF) {
  1265. name = (char *) symtab_section->link->data + sym->st_name;
  1266. sym_index = find_elf_sym(s1->dynsymtab_section, name);
  1267. if (sym_index) {
  1268. esym = &((ElfW(Sym) *)s1->dynsymtab_section->data)[sym_index];
  1269. type = ELFW(ST_TYPE)(esym->st_info);
  1270. if ((type == STT_FUNC) || (type == STT_GNU_IFUNC)) {
  1271. /* Indirect functions shall have STT_FUNC type in executable
  1272. * dynsym section. Indeed, a dlsym call following a lazy
  1273. * resolution would pick the symbol value from the
  1274. * executable dynsym entry which would contain the address
  1275. * of the function wanted by the caller of dlsym instead of
  1276. * the address of the function that would return that
  1277. * address */
  1278. int dynindex
  1279. = put_elf_sym(s1->dynsym, 0, esym->st_size,
  1280. ELFW(ST_INFO)(STB_GLOBAL,STT_FUNC), 0, 0,
  1281. name);
  1282. int index = sym - (ElfW(Sym) *) symtab_section->data;
  1283. get_sym_attr(s1, index, 1)->dyn_index = dynindex;
  1284. } else if (type == STT_OBJECT) {
  1285. unsigned long offset;
  1286. ElfW(Sym) *dynsym;
  1287. offset = bss_section->data_offset;
  1288. /* XXX: which alignment ? */
  1289. offset = (offset + 16 - 1) & -16;
  1290. set_elf_sym (s1->symtab, offset, esym->st_size,
  1291. esym->st_info, 0, bss_section->sh_num, name);
  1292. index = put_elf_sym(s1->dynsym, offset, esym->st_size,
  1293. esym->st_info, 0, bss_section->sh_num,
  1294. name);
  1295. /* Ensure R_COPY works for weak symbol aliases */
  1296. if (ELFW(ST_BIND)(esym->st_info) == STB_WEAK) {
  1297. for_each_elem(s1->dynsymtab_section, 1, dynsym, ElfW(Sym)) {
  1298. if ((dynsym->st_value == esym->st_value)
  1299. && (ELFW(ST_BIND)(dynsym->st_info) == STB_GLOBAL)) {
  1300. char *dynname = (char *) s1->dynsymtab_section->link->data
  1301. + dynsym->st_name;
  1302. put_elf_sym(s1->dynsym, offset, dynsym->st_size,
  1303. dynsym->st_info, 0,
  1304. bss_section->sh_num, dynname);
  1305. break;
  1306. }
  1307. }
  1308. }
  1309. put_elf_reloc(s1->dynsym, bss_section,
  1310. offset, R_COPY, index);
  1311. offset += esym->st_size;
  1312. bss_section->data_offset = offset;
  1313. }
  1314. } else {
  1315. /* STB_WEAK undefined symbols are accepted */
  1316. /* XXX: _fp_hw seems to be part of the ABI, so we ignore it */
  1317. if (ELFW(ST_BIND)(sym->st_info) == STB_WEAK ||
  1318. !strcmp(name, "_fp_hw")) {
  1319. } else {
  1320. tcc_error_noabort("undefined symbol '%s'", name);
  1321. }
  1322. }
  1323. } else if (s1->rdynamic && ELFW(ST_BIND)(sym->st_info) != STB_LOCAL) {
  1324. /* if -rdynamic option, then export all non local symbols */
  1325. name = (char *) symtab_section->link->data + sym->st_name;
  1326. set_elf_sym(s1->dynsym, sym->st_value, sym->st_size, sym->st_info,
  1327. 0, sym->st_shndx, name);
  1328. }
  1329. }
  1330. }
  1331. /* Bind symbols of libraries: export all non local symbols of executable that
  1332. are referenced by shared libraries. The reason is that the dynamic loader
  1333. search symbol first in executable and then in libraries. Therefore a
  1334. reference to a symbol already defined by a library can still be resolved by
  1335. a symbol in the executable. */
  1336. static void bind_libs_dynsyms(TCCState *s1)
  1337. {
  1338. const char *name;
  1339. int sym_index;
  1340. ElfW(Sym) *sym, *esym;
  1341. for_each_elem(s1->dynsymtab_section, 1, esym, ElfW(Sym)) {
  1342. name = (char *) s1->dynsymtab_section->link->data + esym->st_name;
  1343. sym_index = find_elf_sym(symtab_section, name);
  1344. sym = &((ElfW(Sym) *)symtab_section->data)[sym_index];
  1345. if (sym_index && sym->st_shndx != SHN_UNDEF
  1346. && ELFW(ST_BIND)(sym->st_info) != STB_LOCAL) {
  1347. set_elf_sym(s1->dynsym, sym->st_value, sym->st_size,
  1348. sym->st_info, 0, sym->st_shndx, name);
  1349. } else if (esym->st_shndx == SHN_UNDEF) {
  1350. /* weak symbols can stay undefined */
  1351. if (ELFW(ST_BIND)(esym->st_info) != STB_WEAK)
  1352. tcc_warning("undefined dynamic symbol '%s'", name);
  1353. }
  1354. }
  1355. }
  1356. /* Export all non local symbols. This is used by shared libraries so that the
  1357. non local symbols they define can resolve a reference in another shared
  1358. library or in the executable. Correspondingly, it allows undefined local
  1359. symbols to be resolved by other shared libraries or by the executable. */
  1360. static void export_global_syms(TCCState *s1)
  1361. {
  1362. int dynindex, index;
  1363. const char *name;
  1364. ElfW(Sym) *sym;
  1365. for_each_elem(symtab_section, 1, sym, ElfW(Sym)) {
  1366. if (ELFW(ST_BIND)(sym->st_info) != STB_LOCAL) {
  1367. name = (char *) symtab_section->link->data + sym->st_name;
  1368. dynindex = put_elf_sym(s1->dynsym, sym->st_value, sym->st_size,
  1369. sym->st_info, 0, sym->st_shndx, name);
  1370. index = sym - (ElfW(Sym) *) symtab_section->data;
  1371. get_sym_attr(s1, index, 1)->dyn_index = dynindex;
  1372. }
  1373. }
  1374. }
  1375. /* Allocate strings for section names and decide if an unallocated section
  1376. should be output.
  1377. NOTE: the strsec section comes last, so its size is also correct ! */
  1378. static int alloc_sec_names(TCCState *s1, int file_type, Section *strsec)
  1379. {
  1380. int i;
  1381. Section *s;
  1382. int textrel = 0;
  1383. /* Allocate strings for section names */
  1384. for(i = 1; i < s1->nb_sections; i++) {
  1385. s = s1->sections[i];
  1386. /* when generating a DLL, we include relocations but we may
  1387. patch them */
  1388. if (file_type == TCC_OUTPUT_DLL &&
  1389. s->sh_type == SHT_RELX &&
  1390. !(s->sh_flags & SHF_ALLOC) &&
  1391. (s1->sections[s->sh_info]->sh_flags & SHF_ALLOC) &&
  1392. prepare_dynamic_rel(s1, s)) {
  1393. if (s1->sections[s->sh_info]->sh_flags & SHF_EXECINSTR)
  1394. textrel = 1;
  1395. } else if ((s1->do_debug && s->sh_type != SHT_RELX) ||
  1396. file_type == TCC_OUTPUT_OBJ ||
  1397. (s->sh_flags & SHF_ALLOC) ||
  1398. i == (s1->nb_sections - 1)) {
  1399. /* we output all sections if debug or object file */
  1400. s->sh_size = s->data_offset;
  1401. }
  1402. if (s->sh_size || (s->sh_flags & SHF_ALLOC))
  1403. s->sh_name = put_elf_str(strsec, s->name);
  1404. }
  1405. strsec->sh_size = strsec->data_offset;
  1406. return textrel;
  1407. }
  1408. /* Info to be copied in dynamic section */
  1409. struct dyn_inf {
  1410. Section *dynamic;
  1411. Section *dynstr;
  1412. unsigned long data_offset;
  1413. addr_t rel_addr;
  1414. addr_t rel_size;
  1415. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
  1416. addr_t bss_addr;
  1417. addr_t bss_size;
  1418. #endif
  1419. };
  1420. /* Assign sections to segments and decide how are sections laid out when loaded
  1421. in memory. This function also fills corresponding program headers. */
  1422. static int layout_sections(TCCState *s1, ElfW(Phdr) *phdr, int phnum,
  1423. Section *interp, Section* strsec,
  1424. struct dyn_inf *dyninf, int *sec_order)
  1425. {
  1426. int i, j, k, file_type, sh_order_index, file_offset;
  1427. unsigned long s_align;
  1428. long long tmp;
  1429. addr_t addr;
  1430. ElfW(Phdr) *ph;
  1431. Section *s;
  1432. file_type = s1->output_type;
  1433. sh_order_index = 1;
  1434. file_offset = 0;
  1435. if (s1->output_format == TCC_OUTPUT_FORMAT_ELF)
  1436. file_offset = sizeof(ElfW(Ehdr)) + phnum * sizeof(ElfW(Phdr));
  1437. s_align = ELF_PAGE_SIZE;
  1438. if (s1->section_align)
  1439. s_align = s1->section_align;
  1440. if (phnum > 0) {
  1441. if (s1->has_text_addr) {
  1442. int a_offset, p_offset;
  1443. addr = s1->text_addr;
  1444. /* we ensure that (addr % ELF_PAGE_SIZE) == file_offset %
  1445. ELF_PAGE_SIZE */
  1446. a_offset = (int) (addr & (s_align - 1));
  1447. p_offset = file_offset & (s_align - 1);
  1448. if (a_offset < p_offset)
  1449. a_offset += s_align;
  1450. file_offset += (a_offset - p_offset);
  1451. } else {
  1452. if (file_type == TCC_OUTPUT_DLL)
  1453. addr = 0;
  1454. else
  1455. addr = ELF_START_ADDR;
  1456. /* compute address after headers */
  1457. addr += (file_offset & (s_align - 1));
  1458. }
  1459. ph = &phdr[0];
  1460. /* Leave one program headers for the program interpreter and one for
  1461. the program header table itself if needed. These are done later as
  1462. they require section layout to be done first. */
  1463. if (interp)
  1464. ph += 2;
  1465. /* dynamic relocation table information, for .dynamic section */
  1466. dyninf->rel_addr = dyninf->rel_size = 0;
  1467. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
  1468. dyninf->bss_addr = dyninf->bss_size = 0;
  1469. #endif
  1470. for(j = 0; j < 2; j++) {
  1471. ph->p_type = PT_LOAD;
  1472. if (j == 0)
  1473. ph->p_flags = PF_R | PF_X;
  1474. else
  1475. ph->p_flags = PF_R | PF_W;
  1476. ph->p_align = s_align;
  1477. /* Decide the layout of sections loaded in memory. This must
  1478. be done before program headers are filled since they contain
  1479. info about the layout. We do the following ordering: interp,
  1480. symbol tables, relocations, progbits, nobits */
  1481. /* XXX: do faster and simpler sorting */
  1482. for(k = 0; k < 5; k++) {
  1483. for(i = 1; i < s1->nb_sections; i++) {
  1484. s = s1->sections[i];
  1485. /* compute if section should be included */
  1486. if (j == 0) {
  1487. if ((s->sh_flags & (SHF_ALLOC | SHF_WRITE)) !=
  1488. SHF_ALLOC)
  1489. continue;
  1490. } else {
  1491. if ((s->sh_flags & (SHF_ALLOC | SHF_WRITE)) !=
  1492. (SHF_ALLOC | SHF_WRITE))
  1493. continue;
  1494. }
  1495. if (s == interp) {
  1496. if (k != 0)
  1497. continue;
  1498. } else if (s->sh_type == SHT_DYNSYM ||
  1499. s->sh_type == SHT_STRTAB ||
  1500. s->sh_type == SHT_HASH) {
  1501. if (k != 1)
  1502. continue;
  1503. } else if (s->sh_type == SHT_RELX) {
  1504. if (k != 2)
  1505. continue;
  1506. } else if (s->sh_type == SHT_NOBITS) {
  1507. if (k != 4)
  1508. continue;
  1509. } else {
  1510. if (k != 3)
  1511. continue;
  1512. }
  1513. sec_order[sh_order_index++] = i;
  1514. /* section matches: we align it and add its size */
  1515. tmp = addr;
  1516. addr = (addr + s->sh_addralign - 1) &
  1517. ~(s->sh_addralign - 1);
  1518. file_offset += (int) ( addr - tmp );
  1519. s->sh_offset = file_offset;
  1520. s->sh_addr = addr;
  1521. /* update program header infos */
  1522. if (ph->p_offset == 0) {
  1523. ph->p_offset = file_offset;
  1524. ph->p_vaddr = addr;
  1525. ph->p_paddr = ph->p_vaddr;
  1526. }
  1527. /* update dynamic relocation infos */
  1528. if (s->sh_type == SHT_RELX) {
  1529. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
  1530. if (!strcmp(strsec->data + s->sh_name, ".rel.got")) {
  1531. dyninf->rel_addr = addr;
  1532. dyninf->rel_size += s->sh_size; /* XXX only first rel. */
  1533. }
  1534. if (!strcmp(strsec->data + s->sh_name, ".rel.bss")) {
  1535. dyninf->bss_addr = addr;
  1536. dyninf->bss_size = s->sh_size; /* XXX only first rel. */
  1537. }
  1538. #else
  1539. if (dyninf->rel_size == 0)
  1540. dyninf->rel_addr = addr;
  1541. dyninf->rel_size += s->sh_size;
  1542. #endif
  1543. }
  1544. addr += s->sh_size;
  1545. if (s->sh_type != SHT_NOBITS)
  1546. file_offset += s->sh_size;
  1547. }
  1548. }
  1549. if (j == 0) {
  1550. /* Make the first PT_LOAD segment include the program
  1551. headers itself (and the ELF header as well), it'll
  1552. come out with same memory use but will make various
  1553. tools like binutils strip work better. */
  1554. ph->p_offset &= ~(ph->p_align - 1);
  1555. ph->p_vaddr &= ~(ph->p_align - 1);
  1556. ph->p_paddr &= ~(ph->p_align - 1);
  1557. }
  1558. ph->p_filesz = file_offset - ph->p_offset;
  1559. ph->p_memsz = addr - ph->p_vaddr;
  1560. ph++;
  1561. if (j == 0) {
  1562. if (s1->output_format == TCC_OUTPUT_FORMAT_ELF) {
  1563. /* if in the middle of a page, we duplicate the page in
  1564. memory so that one copy is RX and the other is RW */
  1565. if ((addr & (s_align - 1)) != 0)
  1566. addr += s_align;
  1567. } else {
  1568. addr = (addr + s_align - 1) & ~(s_align - 1);
  1569. file_offset = (file_offset + s_align - 1) & ~(s_align - 1);
  1570. }
  1571. }
  1572. }
  1573. }
  1574. /* all other sections come after */
  1575. for(i = 1; i < s1->nb_sections; i++) {
  1576. s = s1->sections[i];
  1577. if (phnum > 0 && (s->sh_flags & SHF_ALLOC))
  1578. continue;
  1579. sec_order[sh_order_index++] = i;
  1580. file_offset = (file_offset + s->sh_addralign - 1) &
  1581. ~(s->sh_addralign - 1);
  1582. s->sh_offset = file_offset;
  1583. if (s->sh_type != SHT_NOBITS)
  1584. file_offset += s->sh_size;
  1585. }
  1586. return file_offset;
  1587. }
  1588. static void fill_unloadable_phdr(ElfW(Phdr) *phdr, int phnum, Section *interp,
  1589. Section *dynamic)
  1590. {
  1591. ElfW(Phdr) *ph;
  1592. /* if interpreter, then add corresponding program header */
  1593. if (interp) {
  1594. ph = &phdr[0];
  1595. ph->p_type = PT_PHDR;
  1596. ph->p_offset = sizeof(ElfW(Ehdr));
  1597. ph->p_filesz = ph->p_memsz = phnum * sizeof(ElfW(Phdr));
  1598. ph->p_vaddr = interp->sh_addr - ph->p_filesz;
  1599. ph->p_paddr = ph->p_vaddr;
  1600. ph->p_flags = PF_R | PF_X;
  1601. ph->p_align = 4; /* interp->sh_addralign; */
  1602. ph++;
  1603. ph->p_type = PT_INTERP;
  1604. ph->p_offset = interp->sh_offset;
  1605. ph->p_vaddr = interp->sh_addr;
  1606. ph->p_paddr = ph->p_vaddr;
  1607. ph->p_filesz = interp->sh_size;
  1608. ph->p_memsz = interp->sh_size;
  1609. ph->p_flags = PF_R;
  1610. ph->p_align = interp->sh_addralign;
  1611. }
  1612. /* if dynamic section, then add corresponding program header */
  1613. if (dynamic) {
  1614. ph = &phdr[phnum - 1];
  1615. ph->p_type = PT_DYNAMIC;
  1616. ph->p_offset = dynamic->sh_offset;
  1617. ph->p_vaddr = dynamic->sh_addr;
  1618. ph->p_paddr = ph->p_vaddr;
  1619. ph->p_filesz = dynamic->sh_size;
  1620. ph->p_memsz = dynamic->sh_size;
  1621. ph->p_flags = PF_R | PF_W;
  1622. ph->p_align = dynamic->sh_addralign;
  1623. }
  1624. }
  1625. /* Fill the dynamic section with tags describing the address and size of
  1626. sections */
  1627. static void fill_dynamic(TCCState *s1, struct dyn_inf *dyninf)
  1628. {
  1629. Section *dynamic = dyninf->dynamic;
  1630. /* put dynamic section entries */
  1631. put_dt(dynamic, DT_HASH, s1->dynsym->hash->sh_addr);
  1632. put_dt(dynamic, DT_STRTAB, dyninf->dynstr->sh_addr);
  1633. put_dt(dynamic, DT_SYMTAB, s1->dynsym->sh_addr);
  1634. put_dt(dynamic, DT_STRSZ, dyninf->dynstr->data_offset);
  1635. put_dt(dynamic, DT_SYMENT, sizeof(ElfW(Sym)));
  1636. #if PTR_SIZE == 8
  1637. put_dt(dynamic, DT_RELA, dyninf->rel_addr);
  1638. put_dt(dynamic, DT_RELASZ, dyninf->rel_size);
  1639. put_dt(dynamic, DT_RELAENT, sizeof(ElfW_Rel));
  1640. #else
  1641. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
  1642. put_dt(dynamic, DT_PLTGOT, s1->got->sh_addr);
  1643. put_dt(dynamic, DT_PLTRELSZ, dyninf->rel_size);
  1644. put_dt(dynamic, DT_JMPREL, dyninf->rel_addr);
  1645. put_dt(dynamic, DT_PLTREL, DT_REL);
  1646. put_dt(dynamic, DT_REL, dyninf->bss_addr);
  1647. put_dt(dynamic, DT_RELSZ, dyninf->bss_size);
  1648. #else
  1649. put_dt(dynamic, DT_REL, dyninf->rel_addr);
  1650. put_dt(dynamic, DT_RELSZ, dyninf->rel_size);
  1651. put_dt(dynamic, DT_RELENT, sizeof(ElfW_Rel));
  1652. #endif
  1653. #endif
  1654. if (s1->do_debug)
  1655. put_dt(dynamic, DT_DEBUG, 0);
  1656. put_dt(dynamic, DT_NULL, 0);
  1657. }
  1658. /* Relocate remaining sections and symbols (that is those not related to
  1659. dynamic linking) */
  1660. static int final_sections_reloc(TCCState *s1)
  1661. {
  1662. int i;
  1663. Section *s;
  1664. relocate_syms(s1, s1->symtab, 0);
  1665. if (s1->nb_errors != 0)
  1666. return -1;
  1667. /* relocate sections */
  1668. /* XXX: ignore sections with allocated relocations ? */
  1669. for(i = 1; i < s1->nb_sections; i++) {
  1670. s = s1->sections[i];
  1671. if (s->reloc && s != s1->got)
  1672. relocate_section(s1, s);
  1673. }
  1674. /* relocate relocation entries if the relocation tables are
  1675. allocated in the executable */
  1676. for(i = 1; i < s1->nb_sections; i++) {
  1677. s = s1->sections[i];
  1678. if ((s->sh_flags & SHF_ALLOC) &&
  1679. s->sh_type == SHT_RELX) {
  1680. relocate_rel(s1, s);
  1681. }
  1682. }
  1683. return 0;
  1684. }
  1685. /* Create an ELF file on disk.
  1686. This function handle ELF specific layout requirements */
  1687. static void tcc_output_elf(TCCState *s1, FILE *f, int phnum, ElfW(Phdr) *phdr,
  1688. int file_offset, int *sec_order)
  1689. {
  1690. int i, shnum, offset, size, file_type;
  1691. Section *s;
  1692. ElfW(Ehdr) ehdr;
  1693. ElfW(Shdr) shdr, *sh;
  1694. file_type = s1->output_type;
  1695. shnum = s1->nb_sections;
  1696. memset(&ehdr, 0, sizeof(ehdr));
  1697. if (phnum > 0) {
  1698. ehdr.e_phentsize = sizeof(ElfW(Phdr));
  1699. ehdr.e_phnum = phnum;
  1700. ehdr.e_phoff = sizeof(ElfW(Ehdr));
  1701. }
  1702. /* align to 4 */
  1703. file_offset = (file_offset + 3) & -4;
  1704. /* fill header */
  1705. ehdr.e_ident[0] = ELFMAG0;
  1706. ehdr.e_ident[1] = ELFMAG1;
  1707. ehdr.e_ident[2] = ELFMAG2;
  1708. ehdr.e_ident[3] = ELFMAG3;
  1709. ehdr.e_ident[4] = ELFCLASSW;
  1710. ehdr.e_ident[5] = ELFDATA2LSB;
  1711. ehdr.e_ident[6] = EV_CURRENT;
  1712. #if !defined(TCC_TARGET_PE) && (defined(__FreeBSD__) || defined(__FreeBSD_kernel__))
  1713. /* FIXME: should set only for freebsd _target_, but we exclude only PE target */
  1714. ehdr.e_ident[EI_OSABI] = ELFOSABI_FREEBSD;
  1715. #endif
  1716. #ifdef TCC_TARGET_ARM
  1717. #ifdef TCC_ARM_EABI
  1718. ehdr.e_ident[EI_OSABI] = 0;
  1719. ehdr.e_flags = EF_ARM_EABI_VER4;
  1720. if (file_type == TCC_OUTPUT_EXE || file_type == TCC_OUTPUT_DLL)
  1721. ehdr.e_flags |= EF_ARM_HASENTRY;
  1722. if (s1->float_abi == ARM_HARD_FLOAT)
  1723. ehdr.e_flags |= EF_ARM_VFP_FLOAT;
  1724. else
  1725. ehdr.e_flags |= EF_ARM_SOFT_FLOAT;
  1726. #else
  1727. ehdr.e_ident[EI_OSABI] = ELFOSABI_ARM;
  1728. #endif
  1729. #endif
  1730. switch(file_type) {
  1731. default:
  1732. case TCC_OUTPUT_EXE:
  1733. ehdr.e_type = ET_EXEC;
  1734. ehdr.e_entry = get_elf_sym_addr(s1, "_start", 1);
  1735. break;
  1736. case TCC_OUTPUT_DLL:
  1737. ehdr.e_type = ET_DYN;
  1738. ehdr.e_entry = text_section->sh_addr; /* XXX: is it correct ? */
  1739. break;
  1740. case TCC_OUTPUT_OBJ:
  1741. ehdr.e_type = ET_REL;
  1742. break;
  1743. }
  1744. ehdr.e_machine = EM_TCC_TARGET;
  1745. ehdr.e_version = EV_CURRENT;
  1746. ehdr.e_shoff = file_offset;
  1747. ehdr.e_ehsize = sizeof(ElfW(Ehdr));
  1748. ehdr.e_shentsize = sizeof(ElfW(Shdr));
  1749. ehdr.e_shnum = shnum;
  1750. ehdr.e_shstrndx = shnum - 1;
  1751. fwrite(&ehdr, 1, sizeof(ElfW(Ehdr)), f);
  1752. fwrite(phdr, 1, phnum * sizeof(ElfW(Phdr)), f);
  1753. offset = sizeof(ElfW(Ehdr)) + phnum * sizeof(ElfW(Phdr));
  1754. sort_syms(s1, symtab_section);
  1755. for(i = 1; i < s1->nb_sections; i++) {
  1756. s = s1->sections[sec_order[i]];
  1757. if (s->sh_type != SHT_NOBITS) {
  1758. while (offset < s->sh_offset) {
  1759. fputc(0, f);
  1760. offset++;
  1761. }
  1762. size = s->sh_size;
  1763. if (size)
  1764. fwrite(s->data, 1, size, f);
  1765. offset += size;
  1766. }
  1767. }
  1768. /* output section headers */
  1769. while (offset < ehdr.e_shoff) {
  1770. fputc(0, f);
  1771. offset++;
  1772. }
  1773. for(i = 0; i < s1->nb_sections; i++) {
  1774. sh = &shdr;
  1775. memset(sh, 0, sizeof(ElfW(Shdr)));
  1776. s = s1->sections[i];
  1777. if (s) {
  1778. sh->sh_name = s->sh_name;
  1779. sh->sh_type = s->sh_type;
  1780. sh->sh_flags = s->sh_flags;
  1781. sh->sh_entsize = s->sh_entsize;
  1782. sh->sh_info = s->sh_info;
  1783. if (s->link)
  1784. sh->sh_link = s->link->sh_num;
  1785. sh->sh_addralign = s->sh_addralign;
  1786. sh->sh_addr = s->sh_addr;
  1787. sh->sh_offset = s->sh_offset;
  1788. sh->sh_size = s->sh_size;
  1789. }
  1790. fwrite(sh, 1, sizeof(ElfW(Shdr)), f);
  1791. }
  1792. }
  1793. /* Write an elf, coff or "binary" file */
  1794. static int tcc_write_elf_file(TCCState *s1, const char *filename, int phnum,
  1795. ElfW(Phdr) *phdr, int file_offset, int *sec_order)
  1796. {
  1797. int fd, mode, file_type;
  1798. FILE *f;
  1799. file_type = s1->output_type;
  1800. if (file_type == TCC_OUTPUT_OBJ)
  1801. mode = 0666;
  1802. else
  1803. mode = 0777;
  1804. unlink(filename);
  1805. fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, mode);
  1806. if (fd < 0) {
  1807. tcc_error_noabort("could not write '%s'", filename);
  1808. return -1;
  1809. }
  1810. f = fdopen(fd, "wb");
  1811. if (s1->verbose)
  1812. printf("<- %s\n", filename);
  1813. #ifdef TCC_TARGET_COFF
  1814. if (s1->output_format == TCC_OUTPUT_FORMAT_COFF)
  1815. tcc_output_coff(s1, f);
  1816. else
  1817. #endif
  1818. if (s1->output_format == TCC_OUTPUT_FORMAT_ELF)
  1819. tcc_output_elf(s1, f, phnum, phdr, file_offset, sec_order);
  1820. else
  1821. tcc_output_binary(s1, f, sec_order);
  1822. fclose(f);
  1823. return 0;
  1824. }
  1825. /* Sort section headers by assigned sh_addr, remove sections
  1826. that we aren't going to output. */
  1827. static void tidy_section_headers(TCCState *s1, int *sec_order)
  1828. {
  1829. int i, nnew, l, *backmap;
  1830. Section **snew, *s;
  1831. ElfW(Sym) *sym;
  1832. snew = tcc_malloc(s1->nb_sections * sizeof(snew[0]));
  1833. backmap = tcc_malloc(s1->nb_sections * sizeof(backmap[0]));
  1834. for (i = 0, nnew = 0, l = s1->nb_sections; i < s1->nb_sections; i++) {
  1835. s = s1->sections[sec_order[i]];
  1836. if (!i || s->sh_name) {
  1837. backmap[sec_order[i]] = nnew;
  1838. snew[nnew] = s;
  1839. ++nnew;
  1840. } else {
  1841. backmap[sec_order[i]] = 0;
  1842. snew[--l] = s;
  1843. }
  1844. }
  1845. for (i = 0; i < nnew; i++) {
  1846. s = snew[i];
  1847. if (s) {
  1848. s->sh_num = i;
  1849. if (s->sh_type == SHT_RELX)
  1850. s->sh_info = backmap[s->sh_info];
  1851. }
  1852. }
  1853. for_each_elem(symtab_section, 1, sym, ElfW(Sym))
  1854. if (sym->st_shndx != SHN_UNDEF && sym->st_shndx < SHN_LORESERVE)
  1855. sym->st_shndx = backmap[sym->st_shndx];
  1856. if( !s1->static_link ) {
  1857. for_each_elem(s1->dynsym, 1, sym, ElfW(Sym))
  1858. if (sym->st_shndx != SHN_UNDEF && sym->st_shndx < SHN_LORESERVE)
  1859. sym->st_shndx = backmap[sym->st_shndx];
  1860. }
  1861. for (i = 0; i < s1->nb_sections; i++)
  1862. sec_order[i] = i;
  1863. tcc_free(s1->sections);
  1864. s1->sections = snew;
  1865. s1->nb_sections = nnew;
  1866. tcc_free(backmap);
  1867. }
  1868. /* Output an elf, coff or binary file */
  1869. /* XXX: suppress unneeded sections */
  1870. static int elf_output_file(TCCState *s1, const char *filename)
  1871. {
  1872. int i, ret, phnum, shnum, file_type, file_offset, *sec_order;
  1873. struct dyn_inf dyninf = {0};
  1874. ElfW(Phdr) *phdr;
  1875. ElfW(Sym) *sym;
  1876. Section *strsec, *interp, *dynamic, *dynstr;
  1877. int textrel;
  1878. file_type = s1->output_type;
  1879. s1->nb_errors = 0;
  1880. ret = -1;
  1881. phdr = NULL;
  1882. sec_order = NULL;
  1883. interp = dynamic = dynstr = NULL; /* avoid warning */
  1884. textrel = 0;
  1885. if (file_type != TCC_OUTPUT_OBJ) {
  1886. /* if linking, also link in runtime libraries (libc, libgcc, etc.) */
  1887. tcc_add_runtime(s1);
  1888. resolve_common_syms(s1);
  1889. if (!s1->static_link) {
  1890. if (file_type == TCC_OUTPUT_EXE) {
  1891. char *ptr;
  1892. /* allow override the dynamic loader */
  1893. const char *elfint = getenv("LD_SO");
  1894. if (elfint == NULL)
  1895. elfint = DEFAULT_ELFINTERP(s1);
  1896. /* add interpreter section only if executable */
  1897. interp = new_section(s1, ".interp", SHT_PROGBITS, SHF_ALLOC);
  1898. interp->sh_addralign = 1;
  1899. ptr = section_ptr_add(interp, 1 + strlen(elfint));
  1900. strcpy(ptr, elfint);
  1901. }
  1902. /* add dynamic symbol table */
  1903. s1->dynsym = new_symtab(s1, ".dynsym", SHT_DYNSYM, SHF_ALLOC,
  1904. ".dynstr",
  1905. ".hash", SHF_ALLOC);
  1906. dynstr = s1->dynsym->link;
  1907. /* add dynamic section */
  1908. dynamic = new_section(s1, ".dynamic", SHT_DYNAMIC,
  1909. SHF_ALLOC | SHF_WRITE);
  1910. dynamic->link = dynstr;
  1911. dynamic->sh_entsize = sizeof(ElfW(Dyn));
  1912. build_got(s1);
  1913. if (file_type == TCC_OUTPUT_EXE) {
  1914. bind_exe_dynsyms(s1);
  1915. if (s1->nb_errors)
  1916. goto the_end;
  1917. bind_libs_dynsyms(s1);
  1918. } else {
  1919. /* shared library case: simply export all global symbols */
  1920. export_global_syms(s1);
  1921. }
  1922. }
  1923. build_got_entries(s1);
  1924. }
  1925. /* we add a section for symbols */
  1926. strsec = new_section(s1, ".shstrtab", SHT_STRTAB, 0);
  1927. put_elf_str(strsec, "");
  1928. /* Allocate strings for section names */
  1929. textrel = alloc_sec_names(s1, file_type, strsec);
  1930. if (dynamic) {
  1931. /* add a list of needed dlls */
  1932. for(i = 0; i < s1->nb_loaded_dlls; i++) {
  1933. DLLReference *dllref = s1->loaded_dlls[i];
  1934. if (dllref->level == 0)
  1935. put_dt(dynamic, DT_NEEDED, put_elf_str(dynstr, dllref->name));
  1936. }
  1937. if (s1->rpath)
  1938. put_dt(dynamic, s1->enable_new_dtags ? DT_RUNPATH : DT_RPATH,
  1939. put_elf_str(dynstr, s1->rpath));
  1940. if (file_type == TCC_OUTPUT_DLL) {
  1941. if (s1->soname)
  1942. put_dt(dynamic, DT_SONAME, put_elf_str(dynstr, s1->soname));
  1943. /* XXX: currently, since we do not handle PIC code, we
  1944. must relocate the readonly segments */
  1945. if (textrel)
  1946. put_dt(dynamic, DT_TEXTREL, 0);
  1947. }
  1948. if (s1->symbolic)
  1949. put_dt(dynamic, DT_SYMBOLIC, 0);
  1950. dyninf.dynamic = dynamic;
  1951. dyninf.dynstr = dynstr;
  1952. /* remember offset and reserve space for 2nd call below */
  1953. dyninf.data_offset = dynamic->data_offset;
  1954. fill_dynamic(s1, &dyninf);
  1955. dynamic->sh_size = dynamic->data_offset;
  1956. dynstr->sh_size = dynstr->data_offset;
  1957. }
  1958. /* compute number of program headers */
  1959. if (file_type == TCC_OUTPUT_OBJ)
  1960. phnum = 0;
  1961. else if (file_type == TCC_OUTPUT_DLL)
  1962. phnum = 3;
  1963. else if (s1->static_link)
  1964. phnum = 2;
  1965. else
  1966. phnum = 5;
  1967. /* allocate program segment headers */
  1968. phdr = tcc_mallocz(phnum * sizeof(ElfW(Phdr)));
  1969. /* compute number of sections */
  1970. shnum = s1->nb_sections;
  1971. /* this array is used to reorder sections in the output file */
  1972. sec_order = tcc_malloc(sizeof(int) * shnum);
  1973. sec_order[0] = 0;
  1974. /* compute section to program header mapping */
  1975. file_offset = layout_sections(s1, phdr, phnum, interp, strsec, &dyninf,
  1976. sec_order);
  1977. /* Fill remaining program header and finalize relocation related to dynamic
  1978. linking. */
  1979. if (file_type != TCC_OUTPUT_OBJ) {
  1980. fill_unloadable_phdr(phdr, phnum, interp, dynamic);
  1981. if (dynamic) {
  1982. dynamic->data_offset = dyninf.data_offset;
  1983. fill_dynamic(s1, &dyninf);
  1984. /* put in GOT the dynamic section address and relocate PLT */
  1985. write32le(s1->got->data, dynamic->sh_addr);
  1986. if (file_type == TCC_OUTPUT_EXE
  1987. || (RELOCATE_DLLPLT && file_type == TCC_OUTPUT_DLL))
  1988. relocate_plt(s1);
  1989. /* relocate symbols in .dynsym now that final addresses are known */
  1990. for_each_elem(s1->dynsym, 1, sym, ElfW(Sym)) {
  1991. if (sym->st_shndx != SHN_UNDEF && sym->st_shndx < SHN_LORESERVE) {
  1992. /* do symbol relocation */
  1993. sym->st_value += s1->sections[sym->st_shndx]->sh_addr;
  1994. }
  1995. }
  1996. }
  1997. /* if building executable or DLL, then relocate each section
  1998. except the GOT which is already relocated */
  1999. ret = final_sections_reloc(s1);
  2000. if (ret)
  2001. goto the_end;
  2002. tidy_section_headers(s1, sec_order);
  2003. /* Perform relocation to GOT or PLT entries */
  2004. if (file_type == TCC_OUTPUT_EXE && s1->static_link)
  2005. fill_got(s1);
  2006. else if (s1->got)
  2007. fill_local_got_entries(s1);
  2008. }
  2009. /* Create the ELF file with name 'filename' */
  2010. ret = tcc_write_elf_file(s1, filename, phnum, phdr, file_offset, sec_order);
  2011. s1->nb_sections = shnum;
  2012. the_end:
  2013. tcc_free(sec_order);
  2014. tcc_free(phdr);
  2015. return ret;
  2016. }
  2017. LIBTCCAPI int tcc_output_file(TCCState *s, const char *filename)
  2018. {
  2019. int ret;
  2020. #ifdef TCC_TARGET_PE
  2021. if (s->output_type != TCC_OUTPUT_OBJ) {
  2022. ret = pe_output_file(s, filename);
  2023. } else
  2024. #endif
  2025. ret = elf_output_file(s, filename);
  2026. return ret;
  2027. }
  2028. static void *load_data(int fd, unsigned long file_offset, unsigned long size)
  2029. {
  2030. void *data;
  2031. data = tcc_malloc(size);
  2032. lseek(fd, file_offset, SEEK_SET);
  2033. read(fd, data, size);
  2034. return data;
  2035. }
  2036. typedef struct SectionMergeInfo {
  2037. Section *s; /* corresponding existing section */
  2038. unsigned long offset; /* offset of the new section in the existing section */
  2039. uint8_t new_section; /* true if section 's' was added */
  2040. uint8_t link_once; /* true if link once section */
  2041. } SectionMergeInfo;
  2042. ST_FUNC int tcc_object_type(int fd, ElfW(Ehdr) *h)
  2043. {
  2044. int size = read(fd, h, sizeof *h);
  2045. if (size == sizeof *h && 0 == memcmp(h, ELFMAG, 4)) {
  2046. if (h->e_type == ET_REL)
  2047. return AFF_BINTYPE_REL;
  2048. if (h->e_type == ET_DYN)
  2049. return AFF_BINTYPE_DYN;
  2050. } else if (size >= 8) {
  2051. if (0 == memcmp(h, ARMAG, 8))
  2052. return AFF_BINTYPE_AR;
  2053. #ifdef TCC_TARGET_COFF
  2054. if (((struct filehdr*)h)->f_magic == COFF_C67_MAGIC)
  2055. return AFF_BINTYPE_C67;
  2056. #endif
  2057. }
  2058. return 0;
  2059. }
  2060. /* load an object file and merge it with current files */
  2061. /* XXX: handle correctly stab (debug) info */
  2062. ST_FUNC int tcc_load_object_file(TCCState *s1,
  2063. int fd, unsigned long file_offset)
  2064. {
  2065. ElfW(Ehdr) ehdr;
  2066. ElfW(Shdr) *shdr, *sh;
  2067. int size, i, j, offset, offseti, nb_syms, sym_index, ret, seencompressed;
  2068. unsigned char *strsec, *strtab;
  2069. int *old_to_new_syms;
  2070. char *sh_name, *name;
  2071. SectionMergeInfo *sm_table, *sm;
  2072. ElfW(Sym) *sym, *symtab;
  2073. ElfW_Rel *rel;
  2074. Section *s;
  2075. int stab_index;
  2076. int stabstr_index;
  2077. stab_index = stabstr_index = 0;
  2078. lseek(fd, file_offset, SEEK_SET);
  2079. if (tcc_object_type(fd, &ehdr) != AFF_BINTYPE_REL)
  2080. goto fail1;
  2081. /* test CPU specific stuff */
  2082. if (ehdr.e_ident[5] != ELFDATA2LSB ||
  2083. ehdr.e_machine != EM_TCC_TARGET) {
  2084. fail1:
  2085. tcc_error_noabort("invalid object file");
  2086. return -1;
  2087. }
  2088. /* read sections */
  2089. shdr = load_data(fd, file_offset + ehdr.e_shoff,
  2090. sizeof(ElfW(Shdr)) * ehdr.e_shnum);
  2091. sm_table = tcc_mallocz(sizeof(SectionMergeInfo) * ehdr.e_shnum);
  2092. /* load section names */
  2093. sh = &shdr[ehdr.e_shstrndx];
  2094. strsec = load_data(fd, file_offset + sh->sh_offset, sh->sh_size);
  2095. /* load symtab and strtab */
  2096. old_to_new_syms = NULL;
  2097. symtab = NULL;
  2098. strtab = NULL;
  2099. nb_syms = 0;
  2100. seencompressed = 0;
  2101. for(i = 1; i < ehdr.e_shnum; i++) {
  2102. sh = &shdr[i];
  2103. if (sh->sh_type == SHT_SYMTAB) {
  2104. if (symtab) {
  2105. tcc_error_noabort("object must contain only one symtab");
  2106. fail:
  2107. ret = -1;
  2108. goto the_end;
  2109. }
  2110. nb_syms = sh->sh_size / sizeof(ElfW(Sym));
  2111. symtab = load_data(fd, file_offset + sh->sh_offset, sh->sh_size);
  2112. sm_table[i].s = symtab_section;
  2113. /* now load strtab */
  2114. sh = &shdr[sh->sh_link];
  2115. strtab = load_data(fd, file_offset + sh->sh_offset, sh->sh_size);
  2116. }
  2117. if (sh->sh_flags & SHF_COMPRESSED)
  2118. seencompressed = 1;
  2119. }
  2120. /* now examine each section and try to merge its content with the
  2121. ones in memory */
  2122. for(i = 1; i < ehdr.e_shnum; i++) {
  2123. /* no need to examine section name strtab */
  2124. if (i == ehdr.e_shstrndx)
  2125. continue;
  2126. sh = &shdr[i];
  2127. sh_name = (char *) strsec + sh->sh_name;
  2128. /* ignore sections types we do not handle */
  2129. if (sh->sh_type != SHT_PROGBITS &&
  2130. sh->sh_type != SHT_RELX &&
  2131. #ifdef TCC_ARM_EABI
  2132. sh->sh_type != SHT_ARM_EXIDX &&
  2133. #endif
  2134. sh->sh_type != SHT_NOBITS &&
  2135. sh->sh_type != SHT_PREINIT_ARRAY &&
  2136. sh->sh_type != SHT_INIT_ARRAY &&
  2137. sh->sh_type != SHT_FINI_ARRAY &&
  2138. strcmp(sh_name, ".stabstr")
  2139. )
  2140. continue;
  2141. if (seencompressed
  2142. && (!strncmp(sh_name, ".debug_", sizeof(".debug_")-1)
  2143. || (sh->sh_type == SHT_RELX
  2144. && !strncmp((char*)strsec + shdr[sh->sh_info].sh_name,
  2145. ".debug_", sizeof(".debug_")-1))))
  2146. continue;
  2147. if (sh->sh_addralign < 1)
  2148. sh->sh_addralign = 1;
  2149. /* find corresponding section, if any */
  2150. for(j = 1; j < s1->nb_sections;j++) {
  2151. s = s1->sections[j];
  2152. if (!strcmp(s->name, sh_name)) {
  2153. if (!strncmp(sh_name, ".gnu.linkonce",
  2154. sizeof(".gnu.linkonce") - 1)) {
  2155. /* if a 'linkonce' section is already present, we
  2156. do not add it again. It is a little tricky as
  2157. symbols can still be defined in
  2158. it. */
  2159. sm_table[i].link_once = 1;
  2160. goto next;
  2161. } else {
  2162. goto found;
  2163. }
  2164. }
  2165. }
  2166. /* not found: create new section */
  2167. s = new_section(s1, sh_name, sh->sh_type, sh->sh_flags & ~SHF_GROUP);
  2168. /* take as much info as possible from the section. sh_link and
  2169. sh_info will be updated later */
  2170. s->sh_addralign = sh->sh_addralign;
  2171. s->sh_entsize = sh->sh_entsize;
  2172. sm_table[i].new_section = 1;
  2173. found:
  2174. if (sh->sh_type != s->sh_type) {
  2175. tcc_error_noabort("invalid section type");
  2176. goto fail;
  2177. }
  2178. /* align start of section */
  2179. offset = s->data_offset;
  2180. if (0 == strcmp(sh_name, ".stab")) {
  2181. stab_index = i;
  2182. goto no_align;
  2183. }
  2184. if (0 == strcmp(sh_name, ".stabstr")) {
  2185. stabstr_index = i;
  2186. goto no_align;
  2187. }
  2188. size = sh->sh_addralign - 1;
  2189. offset = (offset + size) & ~size;
  2190. if (sh->sh_addralign > s->sh_addralign)
  2191. s->sh_addralign = sh->sh_addralign;
  2192. s->data_offset = offset;
  2193. no_align:
  2194. sm_table[i].offset = offset;
  2195. sm_table[i].s = s;
  2196. /* concatenate sections */
  2197. size = sh->sh_size;
  2198. if (sh->sh_type != SHT_NOBITS) {
  2199. unsigned char *ptr;
  2200. lseek(fd, file_offset + sh->sh_offset, SEEK_SET);
  2201. ptr = section_ptr_add(s, size);
  2202. read(fd, ptr, size);
  2203. } else {
  2204. s->data_offset += size;
  2205. }
  2206. next: ;
  2207. }
  2208. /* gr relocate stab strings */
  2209. if (stab_index && stabstr_index) {
  2210. Stab_Sym *a, *b;
  2211. unsigned o;
  2212. s = sm_table[stab_index].s;
  2213. a = (Stab_Sym *)(s->data + sm_table[stab_index].offset);
  2214. b = (Stab_Sym *)(s->data + s->data_offset);
  2215. o = sm_table[stabstr_index].offset;
  2216. while (a < b) {
  2217. if (a->n_strx)
  2218. a->n_strx += o;
  2219. a++;
  2220. }
  2221. }
  2222. /* second short pass to update sh_link and sh_info fields of new
  2223. sections */
  2224. for(i = 1; i < ehdr.e_shnum; i++) {
  2225. s = sm_table[i].s;
  2226. if (!s || !sm_table[i].new_section)
  2227. continue;
  2228. sh = &shdr[i];
  2229. if (sh->sh_link > 0)
  2230. s->link = sm_table[sh->sh_link].s;
  2231. if (sh->sh_type == SHT_RELX) {
  2232. s->sh_info = sm_table[sh->sh_info].s->sh_num;
  2233. /* update backward link */
  2234. s1->sections[s->sh_info]->reloc = s;
  2235. }
  2236. }
  2237. sm = sm_table;
  2238. /* resolve symbols */
  2239. old_to_new_syms = tcc_mallocz(nb_syms * sizeof(int));
  2240. sym = symtab + 1;
  2241. for(i = 1; i < nb_syms; i++, sym++) {
  2242. if (sym->st_shndx != SHN_UNDEF &&
  2243. sym->st_shndx < SHN_LORESERVE) {
  2244. sm = &sm_table[sym->st_shndx];
  2245. if (sm->link_once) {
  2246. /* if a symbol is in a link once section, we use the
  2247. already defined symbol. It is very important to get
  2248. correct relocations */
  2249. if (ELFW(ST_BIND)(sym->st_info) != STB_LOCAL) {
  2250. name = (char *) strtab + sym->st_name;
  2251. sym_index = find_elf_sym(symtab_section, name);
  2252. if (sym_index)
  2253. old_to_new_syms[i] = sym_index;
  2254. }
  2255. continue;
  2256. }
  2257. /* if no corresponding section added, no need to add symbol */
  2258. if (!sm->s)
  2259. continue;
  2260. /* convert section number */
  2261. sym->st_shndx = sm->s->sh_num;
  2262. /* offset value */
  2263. sym->st_value += sm->offset;
  2264. }
  2265. /* add symbol */
  2266. name = (char *) strtab + sym->st_name;
  2267. sym_index = set_elf_sym(symtab_section, sym->st_value, sym->st_size,
  2268. sym->st_info, sym->st_other,
  2269. sym->st_shndx, name);
  2270. old_to_new_syms[i] = sym_index;
  2271. }
  2272. /* third pass to patch relocation entries */
  2273. for(i = 1; i < ehdr.e_shnum; i++) {
  2274. s = sm_table[i].s;
  2275. if (!s)
  2276. continue;
  2277. sh = &shdr[i];
  2278. offset = sm_table[i].offset;
  2279. switch(s->sh_type) {
  2280. case SHT_RELX:
  2281. /* take relocation offset information */
  2282. offseti = sm_table[sh->sh_info].offset;
  2283. for_each_elem(s, (offset / sizeof(*rel)), rel, ElfW_Rel) {
  2284. int type;
  2285. unsigned sym_index;
  2286. /* convert symbol index */
  2287. type = ELFW(R_TYPE)(rel->r_info);
  2288. sym_index = ELFW(R_SYM)(rel->r_info);
  2289. /* NOTE: only one symtab assumed */
  2290. if (sym_index >= nb_syms)
  2291. goto invalid_reloc;
  2292. sym_index = old_to_new_syms[sym_index];
  2293. /* ignore link_once in rel section. */
  2294. if (!sym_index && !sm->link_once
  2295. #ifdef TCC_TARGET_ARM
  2296. && type != R_ARM_V4BX
  2297. #endif
  2298. ) {
  2299. invalid_reloc:
  2300. tcc_error_noabort("Invalid relocation entry [%2d] '%s' @ %.8x",
  2301. i, strsec + sh->sh_name, rel->r_offset);
  2302. goto fail;
  2303. }
  2304. rel->r_info = ELFW(R_INFO)(sym_index, type);
  2305. /* offset the relocation offset */
  2306. rel->r_offset += offseti;
  2307. #ifdef TCC_TARGET_ARM
  2308. /* Jumps and branches from a Thumb code to a PLT entry need
  2309. special handling since PLT entries are ARM code.
  2310. Unconditional bl instructions referencing PLT entries are
  2311. handled by converting these instructions into blx
  2312. instructions. Other case of instructions referencing a PLT
  2313. entry require to add a Thumb stub before the PLT entry to
  2314. switch to ARM mode. We set bit plt_thumb_stub of the
  2315. attribute of a symbol to indicate such a case. */
  2316. if (type == R_ARM_THM_JUMP24)
  2317. get_sym_attr(s1, sym_index, 1)->plt_thumb_stub = 1;
  2318. #endif
  2319. }
  2320. break;
  2321. default:
  2322. break;
  2323. }
  2324. }
  2325. ret = 0;
  2326. the_end:
  2327. tcc_free(symtab);
  2328. tcc_free(strtab);
  2329. tcc_free(old_to_new_syms);
  2330. tcc_free(sm_table);
  2331. tcc_free(strsec);
  2332. tcc_free(shdr);
  2333. return ret;
  2334. }
  2335. typedef struct ArchiveHeader {
  2336. char ar_name[16]; /* name of this member */
  2337. char ar_date[12]; /* file mtime */
  2338. char ar_uid[6]; /* owner uid; printed as decimal */
  2339. char ar_gid[6]; /* owner gid; printed as decimal */
  2340. char ar_mode[8]; /* file mode, printed as octal */
  2341. char ar_size[10]; /* file size, printed as decimal */
  2342. char ar_fmag[2]; /* should contain ARFMAG */
  2343. } ArchiveHeader;
  2344. static int get_be32(const uint8_t *b)
  2345. {
  2346. return b[3] | (b[2] << 8) | (b[1] << 16) | (b[0] << 24);
  2347. }
  2348. static long get_be64(const uint8_t *b)
  2349. {
  2350. long long ret = get_be32(b);
  2351. ret = (ret << 32) | (unsigned)get_be32(b+4);
  2352. return (long)ret;
  2353. }
  2354. /* load only the objects which resolve undefined symbols */
  2355. static int tcc_load_alacarte(TCCState *s1, int fd, int size, int entrysize)
  2356. {
  2357. long i, bound, nsyms, sym_index, off, ret;
  2358. uint8_t *data;
  2359. const char *ar_names, *p;
  2360. const uint8_t *ar_index;
  2361. ElfW(Sym) *sym;
  2362. data = tcc_malloc(size);
  2363. if (read(fd, data, size) != size)
  2364. goto fail;
  2365. nsyms = entrysize == 4 ? get_be32(data) : get_be64(data);
  2366. ar_index = data + entrysize;
  2367. ar_names = (char *) ar_index + nsyms * entrysize;
  2368. do {
  2369. bound = 0;
  2370. for(p = ar_names, i = 0; i < nsyms; i++, p += strlen(p)+1) {
  2371. sym_index = find_elf_sym(symtab_section, p);
  2372. if(sym_index) {
  2373. sym = &((ElfW(Sym) *)symtab_section->data)[sym_index];
  2374. if(sym->st_shndx == SHN_UNDEF) {
  2375. off = (entrysize == 4
  2376. ? get_be32(ar_index + i * 4)
  2377. : get_be64(ar_index + i * 8))
  2378. + sizeof(ArchiveHeader);
  2379. ++bound;
  2380. if(tcc_load_object_file(s1, fd, off) < 0) {
  2381. fail:
  2382. ret = -1;
  2383. goto the_end;
  2384. }
  2385. }
  2386. }
  2387. }
  2388. } while(bound);
  2389. ret = 0;
  2390. the_end:
  2391. tcc_free(data);
  2392. return ret;
  2393. }
  2394. /* load a '.a' file */
  2395. ST_FUNC int tcc_load_archive(TCCState *s1, int fd, int alacarte)
  2396. {
  2397. ArchiveHeader hdr;
  2398. char ar_size[11];
  2399. char ar_name[17];
  2400. char magic[8];
  2401. int size, len, i;
  2402. unsigned long file_offset;
  2403. /* skip magic which was already checked */
  2404. read(fd, magic, sizeof(magic));
  2405. for(;;) {
  2406. len = read(fd, &hdr, sizeof(hdr));
  2407. if (len == 0)
  2408. break;
  2409. if (len != sizeof(hdr)) {
  2410. tcc_error_noabort("invalid archive");
  2411. return -1;
  2412. }
  2413. memcpy(ar_size, hdr.ar_size, sizeof(hdr.ar_size));
  2414. ar_size[sizeof(hdr.ar_size)] = '\0';
  2415. size = strtol(ar_size, NULL, 0);
  2416. memcpy(ar_name, hdr.ar_name, sizeof(hdr.ar_name));
  2417. for(i = sizeof(hdr.ar_name) - 1; i >= 0; i--) {
  2418. if (ar_name[i] != ' ')
  2419. break;
  2420. }
  2421. ar_name[i + 1] = '\0';
  2422. file_offset = lseek(fd, 0, SEEK_CUR);
  2423. /* align to even */
  2424. size = (size + 1) & ~1;
  2425. if (!strcmp(ar_name, "/")) {
  2426. /* coff symbol table : we handle it */
  2427. if (alacarte)
  2428. return tcc_load_alacarte(s1, fd, size, 4);
  2429. } else if (!strcmp(ar_name, "/SYM64/")) {
  2430. if (alacarte)
  2431. return tcc_load_alacarte(s1, fd, size, 8);
  2432. } else {
  2433. ElfW(Ehdr) ehdr;
  2434. if (tcc_object_type(fd, &ehdr) == AFF_BINTYPE_REL) {
  2435. if (tcc_load_object_file(s1, fd, file_offset) < 0)
  2436. return -1;
  2437. }
  2438. }
  2439. lseek(fd, file_offset + size, SEEK_SET);
  2440. }
  2441. return 0;
  2442. }
  2443. #ifndef TCC_TARGET_PE
  2444. /* load a DLL and all referenced DLLs. 'level = 0' means that the DLL
  2445. is referenced by the user (so it should be added as DT_NEEDED in
  2446. the generated ELF file) */
  2447. ST_FUNC int tcc_load_dll(TCCState *s1, int fd, const char *filename, int level)
  2448. {
  2449. ElfW(Ehdr) ehdr;
  2450. ElfW(Shdr) *shdr, *sh, *sh1;
  2451. int i, j, nb_syms, nb_dts, sym_bind, ret;
  2452. ElfW(Sym) *sym, *dynsym;
  2453. ElfW(Dyn) *dt, *dynamic;
  2454. unsigned char *dynstr;
  2455. const char *name, *soname;
  2456. DLLReference *dllref;
  2457. read(fd, &ehdr, sizeof(ehdr));
  2458. /* test CPU specific stuff */
  2459. if (ehdr.e_ident[5] != ELFDATA2LSB ||
  2460. ehdr.e_machine != EM_TCC_TARGET) {
  2461. tcc_error_noabort("bad architecture");
  2462. return -1;
  2463. }
  2464. /* read sections */
  2465. shdr = load_data(fd, ehdr.e_shoff, sizeof(ElfW(Shdr)) * ehdr.e_shnum);
  2466. /* load dynamic section and dynamic symbols */
  2467. nb_syms = 0;
  2468. nb_dts = 0;
  2469. dynamic = NULL;
  2470. dynsym = NULL; /* avoid warning */
  2471. dynstr = NULL; /* avoid warning */
  2472. for(i = 0, sh = shdr; i < ehdr.e_shnum; i++, sh++) {
  2473. switch(sh->sh_type) {
  2474. case SHT_DYNAMIC:
  2475. nb_dts = sh->sh_size / sizeof(ElfW(Dyn));
  2476. dynamic = load_data(fd, sh->sh_offset, sh->sh_size);
  2477. break;
  2478. case SHT_DYNSYM:
  2479. nb_syms = sh->sh_size / sizeof(ElfW(Sym));
  2480. dynsym = load_data(fd, sh->sh_offset, sh->sh_size);
  2481. sh1 = &shdr[sh->sh_link];
  2482. dynstr = load_data(fd, sh1->sh_offset, sh1->sh_size);
  2483. break;
  2484. default:
  2485. break;
  2486. }
  2487. }
  2488. /* compute the real library name */
  2489. soname = tcc_basename(filename);
  2490. for(i = 0, dt = dynamic; i < nb_dts; i++, dt++) {
  2491. if (dt->d_tag == DT_SONAME) {
  2492. soname = (char *) dynstr + dt->d_un.d_val;
  2493. }
  2494. }
  2495. /* if the dll is already loaded, do not load it */
  2496. for(i = 0; i < s1->nb_loaded_dlls; i++) {
  2497. dllref = s1->loaded_dlls[i];
  2498. if (!strcmp(soname, dllref->name)) {
  2499. /* but update level if needed */
  2500. if (level < dllref->level)
  2501. dllref->level = level;
  2502. ret = 0;
  2503. goto the_end;
  2504. }
  2505. }
  2506. /* add the dll and its level */
  2507. dllref = tcc_mallocz(sizeof(DLLReference) + strlen(soname));
  2508. dllref->level = level;
  2509. strcpy(dllref->name, soname);
  2510. dynarray_add(&s1->loaded_dlls, &s1->nb_loaded_dlls, dllref);
  2511. /* add dynamic symbols in dynsym_section */
  2512. for(i = 1, sym = dynsym + 1; i < nb_syms; i++, sym++) {
  2513. sym_bind = ELFW(ST_BIND)(sym->st_info);
  2514. if (sym_bind == STB_LOCAL)
  2515. continue;
  2516. name = (char *) dynstr + sym->st_name;
  2517. set_elf_sym(s1->dynsymtab_section, sym->st_value, sym->st_size,
  2518. sym->st_info, sym->st_other, sym->st_shndx, name);
  2519. }
  2520. /* load all referenced DLLs */
  2521. for(i = 0, dt = dynamic; i < nb_dts; i++, dt++) {
  2522. switch(dt->d_tag) {
  2523. case DT_NEEDED:
  2524. name = (char *) dynstr + dt->d_un.d_val;
  2525. for(j = 0; j < s1->nb_loaded_dlls; j++) {
  2526. dllref = s1->loaded_dlls[j];
  2527. if (!strcmp(name, dllref->name))
  2528. goto already_loaded;
  2529. }
  2530. if (tcc_add_dll(s1, name, AFF_REFERENCED_DLL) < 0) {
  2531. tcc_error_noabort("referenced dll '%s' not found", name);
  2532. ret = -1;
  2533. goto the_end;
  2534. }
  2535. already_loaded:
  2536. break;
  2537. }
  2538. }
  2539. ret = 0;
  2540. the_end:
  2541. tcc_free(dynstr);
  2542. tcc_free(dynsym);
  2543. tcc_free(dynamic);
  2544. tcc_free(shdr);
  2545. return ret;
  2546. }
  2547. #define LD_TOK_NAME 256
  2548. #define LD_TOK_EOF (-1)
  2549. /* return next ld script token */
  2550. static int ld_next(TCCState *s1, char *name, int name_size)
  2551. {
  2552. int c;
  2553. char *q;
  2554. redo:
  2555. switch(ch) {
  2556. case ' ':
  2557. case '\t':
  2558. case '\f':
  2559. case '\v':
  2560. case '\r':
  2561. case '\n':
  2562. inp();
  2563. goto redo;
  2564. case '/':
  2565. minp();
  2566. if (ch == '*') {
  2567. file->buf_ptr = parse_comment(file->buf_ptr);
  2568. ch = file->buf_ptr[0];
  2569. goto redo;
  2570. } else {
  2571. q = name;
  2572. *q++ = '/';
  2573. goto parse_name;
  2574. }
  2575. break;
  2576. case '\\':
  2577. ch = handle_eob();
  2578. if (ch != '\\')
  2579. goto redo;
  2580. /* fall through */
  2581. /* case 'a' ... 'z': */
  2582. case 'a':
  2583. case 'b':
  2584. case 'c':
  2585. case 'd':
  2586. case 'e':
  2587. case 'f':
  2588. case 'g':
  2589. case 'h':
  2590. case 'i':
  2591. case 'j':
  2592. case 'k':
  2593. case 'l':
  2594. case 'm':
  2595. case 'n':
  2596. case 'o':
  2597. case 'p':
  2598. case 'q':
  2599. case 'r':
  2600. case 's':
  2601. case 't':
  2602. case 'u':
  2603. case 'v':
  2604. case 'w':
  2605. case 'x':
  2606. case 'y':
  2607. case 'z':
  2608. /* case 'A' ... 'z': */
  2609. case 'A':
  2610. case 'B':
  2611. case 'C':
  2612. case 'D':
  2613. case 'E':
  2614. case 'F':
  2615. case 'G':
  2616. case 'H':
  2617. case 'I':
  2618. case 'J':
  2619. case 'K':
  2620. case 'L':
  2621. case 'M':
  2622. case 'N':
  2623. case 'O':
  2624. case 'P':
  2625. case 'Q':
  2626. case 'R':
  2627. case 'S':
  2628. case 'T':
  2629. case 'U':
  2630. case 'V':
  2631. case 'W':
  2632. case 'X':
  2633. case 'Y':
  2634. case 'Z':
  2635. case '_':
  2636. case '.':
  2637. case '$':
  2638. case '~':
  2639. q = name;
  2640. parse_name:
  2641. for(;;) {
  2642. if (!((ch >= 'a' && ch <= 'z') ||
  2643. (ch >= 'A' && ch <= 'Z') ||
  2644. (ch >= '0' && ch <= '9') ||
  2645. strchr("/.-_+=$:\\,~", ch)))
  2646. break;
  2647. if ((q - name) < name_size - 1) {
  2648. *q++ = ch;
  2649. }
  2650. minp();
  2651. }
  2652. *q = '\0';
  2653. c = LD_TOK_NAME;
  2654. break;
  2655. case CH_EOF:
  2656. c = LD_TOK_EOF;
  2657. break;
  2658. default:
  2659. c = ch;
  2660. inp();
  2661. break;
  2662. }
  2663. return c;
  2664. }
  2665. static int ld_add_file(TCCState *s1, const char filename[])
  2666. {
  2667. if (filename[0] == '/') {
  2668. if (CONFIG_SYSROOT[0] == '\0'
  2669. && tcc_add_file_internal(s1, filename, AFF_TYPE_BIN) == 0)
  2670. return 0;
  2671. filename = tcc_basename(filename);
  2672. }
  2673. return tcc_add_dll(s1, filename, 0);
  2674. }
  2675. static inline int new_undef_syms(void)
  2676. {
  2677. int ret = 0;
  2678. ret = new_undef_sym;
  2679. new_undef_sym = 0;
  2680. return ret;
  2681. }
  2682. static int ld_add_file_list(TCCState *s1, const char *cmd, int as_needed)
  2683. {
  2684. char filename[1024], libname[1024];
  2685. int t, group, nblibs = 0, ret = 0;
  2686. char **libs = NULL;
  2687. group = !strcmp(cmd, "GROUP");
  2688. if (!as_needed)
  2689. new_undef_syms();
  2690. t = ld_next(s1, filename, sizeof(filename));
  2691. if (t != '(')
  2692. expect("(");
  2693. t = ld_next(s1, filename, sizeof(filename));
  2694. for(;;) {
  2695. libname[0] = '\0';
  2696. if (t == LD_TOK_EOF) {
  2697. tcc_error_noabort("unexpected end of file");
  2698. ret = -1;
  2699. goto lib_parse_error;
  2700. } else if (t == ')') {
  2701. break;
  2702. } else if (t == '-') {
  2703. t = ld_next(s1, filename, sizeof(filename));
  2704. if ((t != LD_TOK_NAME) || (filename[0] != 'l')) {
  2705. tcc_error_noabort("library name expected");
  2706. ret = -1;
  2707. goto lib_parse_error;
  2708. }
  2709. pstrcpy(libname, sizeof libname, &filename[1]);
  2710. if (s1->static_link) {
  2711. snprintf(filename, sizeof filename, "lib%s.a", libname);
  2712. } else {
  2713. snprintf(filename, sizeof filename, "lib%s.so", libname);
  2714. }
  2715. } else if (t != LD_TOK_NAME) {
  2716. tcc_error_noabort("filename expected");
  2717. ret = -1;
  2718. goto lib_parse_error;
  2719. }
  2720. if (!strcmp(filename, "AS_NEEDED")) {
  2721. ret = ld_add_file_list(s1, cmd, 1);
  2722. if (ret)
  2723. goto lib_parse_error;
  2724. } else {
  2725. /* TODO: Implement AS_NEEDED support. Ignore it for now */
  2726. if (!as_needed) {
  2727. ret = ld_add_file(s1, filename);
  2728. if (ret)
  2729. goto lib_parse_error;
  2730. if (group) {
  2731. /* Add the filename *and* the libname to avoid future conversions */
  2732. dynarray_add(&libs, &nblibs, tcc_strdup(filename));
  2733. if (libname[0] != '\0')
  2734. dynarray_add(&libs, &nblibs, tcc_strdup(libname));
  2735. }
  2736. }
  2737. }
  2738. t = ld_next(s1, filename, sizeof(filename));
  2739. if (t == ',') {
  2740. t = ld_next(s1, filename, sizeof(filename));
  2741. }
  2742. }
  2743. if (group && !as_needed) {
  2744. while (new_undef_syms()) {
  2745. int i;
  2746. for (i = 0; i < nblibs; i ++)
  2747. ld_add_file(s1, libs[i]);
  2748. }
  2749. }
  2750. lib_parse_error:
  2751. dynarray_reset(&libs, &nblibs);
  2752. return ret;
  2753. }
  2754. /* interpret a subset of GNU ldscripts to handle the dummy libc.so
  2755. files */
  2756. ST_FUNC int tcc_load_ldscript(TCCState *s1)
  2757. {
  2758. char cmd[64];
  2759. char filename[1024];
  2760. int t, ret;
  2761. ch = handle_eob();
  2762. for(;;) {
  2763. t = ld_next(s1, cmd, sizeof(cmd));
  2764. if (t == LD_TOK_EOF)
  2765. return 0;
  2766. else if (t != LD_TOK_NAME)
  2767. return -1;
  2768. if (!strcmp(cmd, "INPUT") ||
  2769. !strcmp(cmd, "GROUP")) {
  2770. ret = ld_add_file_list(s1, cmd, 0);
  2771. if (ret)
  2772. return ret;
  2773. } else if (!strcmp(cmd, "OUTPUT_FORMAT") ||
  2774. !strcmp(cmd, "TARGET")) {
  2775. /* ignore some commands */
  2776. t = ld_next(s1, cmd, sizeof(cmd));
  2777. if (t != '(')
  2778. expect("(");
  2779. for(;;) {
  2780. t = ld_next(s1, filename, sizeof(filename));
  2781. if (t == LD_TOK_EOF) {
  2782. tcc_error_noabort("unexpected end of file");
  2783. return -1;
  2784. } else if (t == ')') {
  2785. break;
  2786. }
  2787. }
  2788. } else {
  2789. return -1;
  2790. }
  2791. }
  2792. return 0;
  2793. }
  2794. #endif /* !TCC_TARGET_PE */