暫無描述
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580
  1. /*
  2. * Copyright (c) 1991-1994 by Xerox Corporation. All rights reserved.
  3. * Copyright (c) 1997 by Silicon Graphics. All rights reserved.
  4. *
  5. * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
  6. * OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
  7. *
  8. * Permission is hereby granted to use or copy this program
  9. * for any purpose, provided the above notices are retained on all copies.
  10. * Permission to modify the code and to distribute modified code is granted,
  11. * provided the above notices are retained, and a notice that the code was
  12. * modified is included with the above copyright notice.
  13. */
  14. #include "private/gc_priv.h"
  15. /*
  16. * This is incredibly OS specific code for tracking down data sections in
  17. * dynamic libraries. There appears to be no way of doing this quickly
  18. * without groveling through undocumented data structures. We would argue
  19. * that this is a bug in the design of the dlopen interface. THIS CODE
  20. * MAY BREAK IN FUTURE OS RELEASES. If this matters to you, don't hesitate
  21. * to let your vendor know ...
  22. *
  23. * None of this is safe with dlclose and incremental collection.
  24. * But then not much of anything is safe in the presence of dlclose.
  25. */
  26. #if !defined(MACOS) && !defined(GC_NO_TYPES) && !defined(SN_TARGET_PSP2) \
  27. && !defined(_WIN32_WCE) && !defined(__CC_ARM)
  28. # include <sys/types.h>
  29. #endif
  30. /* BTL: avoid circular redefinition of dlopen if GC_SOLARIS_THREADS defined */
  31. #undef GC_MUST_RESTORE_REDEFINED_DLOPEN
  32. #if defined(GC_PTHREADS) && !defined(GC_NO_DLOPEN) \
  33. && !defined(GC_NO_THREAD_REDIRECTS) && !defined(GC_USE_LD_WRAP)
  34. /* To support threads in Solaris, gc.h interposes on dlopen by */
  35. /* defining "dlopen" to be "GC_dlopen", which is implemented below. */
  36. /* However, both GC_FirstDLOpenedLinkMap() and GC_dlopen() use the */
  37. /* real system dlopen() in their implementation. We first remove */
  38. /* gc.h's dlopen definition and restore it later, after GC_dlopen(). */
  39. # undef dlopen
  40. # define GC_MUST_RESTORE_REDEFINED_DLOPEN
  41. #endif /* !GC_NO_DLOPEN */
  42. /* A user-supplied routine (custom filter) that might be called to */
  43. /* determine whether a DSO really needs to be scanned by the GC. */
  44. /* 0 means no filter installed. May be unused on some platforms. */
  45. /* FIXME: Add filter support for more platforms. */
  46. STATIC GC_has_static_roots_func GC_has_static_roots = 0;
  47. #if (defined(DYNAMIC_LOADING) || defined(MSWIN32) || defined(MSWINCE) \
  48. || defined(CYGWIN32)) && !defined(PCR)
  49. #if !defined(DARWIN) && !defined(SCO_ELF) && !defined(SOLARISDL) \
  50. && !defined(AIX) && !defined(DGUX) && !defined(IRIX5) && !defined(HPUX) \
  51. && !defined(CYGWIN32) && !defined(MSWIN32) && !defined(MSWINCE) \
  52. && !(defined(ALPHA) && defined(OSF1)) \
  53. && !(defined(FREEBSD) && defined(__ELF__)) \
  54. && !((defined(LINUX) || defined(NACL)) && defined(__ELF__)) \
  55. && !(defined(NETBSD) && defined(__ELF__)) \
  56. && !defined(HAIKU) && !defined(HURD) \
  57. && !(defined(OPENBSD) && (defined(__ELF__) || defined(M68K))) \
  58. && !defined(CPPCHECK)
  59. # error We only know how to find data segments of dynamic libraries for above.
  60. # error Additional SVR4 variants might not be too hard to add.
  61. #endif
  62. #include <stdio.h>
  63. #ifdef SOLARISDL
  64. # include <sys/elf.h>
  65. # include <dlfcn.h>
  66. # include <link.h>
  67. #endif
  68. #if defined(NETBSD)
  69. # include <sys/param.h>
  70. # include <dlfcn.h>
  71. # include <machine/elf_machdep.h>
  72. # define ELFSIZE ARCH_ELFSIZE
  73. #endif
  74. #if defined(OPENBSD)
  75. # include <sys/param.h>
  76. # if (OpenBSD >= 200519) && !defined(HAVE_DL_ITERATE_PHDR)
  77. # define HAVE_DL_ITERATE_PHDR
  78. # endif
  79. #endif /* OPENBSD */
  80. #if defined(SCO_ELF) || defined(DGUX) || defined(HURD) \
  81. || (defined(__ELF__) && (defined(LINUX) || defined(FREEBSD) \
  82. || defined(NACL) || defined(NETBSD) \
  83. || defined(OPENBSD)))
  84. # include <stddef.h>
  85. # if !defined(OPENBSD) && !defined(HOST_ANDROID)
  86. /* OpenBSD does not have elf.h file; link.h below is sufficient. */
  87. /* Exclude Android because linker.h below includes its own version. */
  88. # include <elf.h>
  89. # endif
  90. # ifdef HOST_ANDROID
  91. /* If you don't need the "dynamic loading" feature, you may build */
  92. /* the collector with -D IGNORE_DYNAMIC_LOADING. */
  93. # ifdef BIONIC_ELFDATA_REDEF_BUG
  94. /* Workaround a problem in Bionic (as of Android 4.2) which has */
  95. /* mismatching ELF_DATA definitions in sys/exec_elf.h and */
  96. /* asm/elf.h included from linker.h file (similar to EM_ALPHA). */
  97. # include <asm/elf.h>
  98. # include <linux/elf-em.h>
  99. # undef ELF_DATA
  100. # undef EM_ALPHA
  101. # endif
  102. # include <link.h>
  103. # if !defined(GC_DONT_DEFINE_LINK_MAP) && !(__ANDROID_API__ >= 21)
  104. /* link_map and r_debug are defined in link.h of NDK r10+. */
  105. /* bionic/linker/linker.h defines them too but the header */
  106. /* itself is a C++ one starting from Android 4.3. */
  107. struct link_map {
  108. uintptr_t l_addr;
  109. char* l_name;
  110. uintptr_t l_ld;
  111. struct link_map* l_next;
  112. struct link_map* l_prev;
  113. };
  114. struct r_debug {
  115. int32_t r_version;
  116. struct link_map* r_map;
  117. void (*r_brk)(void);
  118. int32_t r_state;
  119. uintptr_t r_ldbase;
  120. };
  121. # endif
  122. # else
  123. EXTERN_C_BEGIN /* Workaround missing extern "C" around _DYNAMIC */
  124. /* symbol in link.h of some Linux hosts. */
  125. # include <link.h>
  126. EXTERN_C_END
  127. # endif
  128. #endif
  129. /* Newer versions of GNU/Linux define this macro. We
  130. * define it similarly for any ELF systems that don't. */
  131. # ifndef ElfW
  132. # if defined(FREEBSD)
  133. # if __ELF_WORD_SIZE == 32
  134. # define ElfW(type) Elf32_##type
  135. # else
  136. # define ElfW(type) Elf64_##type
  137. # endif
  138. # elif defined(NETBSD) || defined(OPENBSD)
  139. # if ELFSIZE == 32
  140. # define ElfW(type) Elf32_##type
  141. # else
  142. # define ElfW(type) Elf64_##type
  143. # endif
  144. # else
  145. # if !defined(ELF_CLASS) || ELF_CLASS == ELFCLASS32
  146. # define ElfW(type) Elf32_##type
  147. # else
  148. # define ElfW(type) Elf64_##type
  149. # endif
  150. # endif
  151. # endif
  152. #if defined(SOLARISDL) && !defined(USE_PROC_FOR_LIBRARIES)
  153. EXTERN_C_BEGIN
  154. extern ElfW(Dyn) _DYNAMIC;
  155. EXTERN_C_END
  156. STATIC struct link_map *
  157. GC_FirstDLOpenedLinkMap(void)
  158. {
  159. ElfW(Dyn) *dp;
  160. static struct link_map * cachedResult = 0;
  161. static ElfW(Dyn) *dynStructureAddr = 0;
  162. /* BTL: added to avoid Solaris 5.3 ld.so _DYNAMIC bug */
  163. # ifdef SUNOS53_SHARED_LIB
  164. /* BTL: Avoid the Solaris 5.3 bug that _DYNAMIC isn't being set */
  165. /* up properly in dynamically linked .so's. This means we have */
  166. /* to use its value in the set of original object files loaded */
  167. /* at program startup. */
  168. if( dynStructureAddr == 0 ) {
  169. void* startupSyms = dlopen(0, RTLD_LAZY);
  170. dynStructureAddr = (ElfW(Dyn)*)(word)dlsym(startupSyms, "_DYNAMIC");
  171. }
  172. # else
  173. dynStructureAddr = &_DYNAMIC;
  174. # endif
  175. if (0 == COVERT_DATAFLOW(dynStructureAddr)) {
  176. /* _DYNAMIC symbol not resolved. */
  177. return(0);
  178. }
  179. if (cachedResult == 0) {
  180. int tag;
  181. for( dp = ((ElfW(Dyn) *)(&_DYNAMIC)); (tag = dp->d_tag) != 0; dp++ ) {
  182. if (tag == DT_DEBUG) {
  183. struct r_debug *rd = (struct r_debug *)dp->d_un.d_ptr;
  184. if (rd != NULL) {
  185. struct link_map *lm = rd->r_map;
  186. if (lm != NULL)
  187. cachedResult = lm->l_next; /* might be NULL */
  188. }
  189. break;
  190. }
  191. }
  192. }
  193. return cachedResult;
  194. }
  195. #endif /* SOLARISDL ... */
  196. /* BTL: added to fix circular dlopen definition if GC_SOLARIS_THREADS defined */
  197. # ifdef GC_MUST_RESTORE_REDEFINED_DLOPEN
  198. # define dlopen GC_dlopen
  199. # endif
  200. # if defined(SOLARISDL)
  201. /* Add dynamic library data sections to the root set. */
  202. # if !defined(PCR) && !defined(GC_SOLARIS_THREADS) && defined(THREADS) \
  203. && !defined(CPPCHECK)
  204. # error Fix mutual exclusion with dlopen
  205. # endif
  206. # ifndef USE_PROC_FOR_LIBRARIES
  207. GC_INNER void GC_register_dynamic_libraries(void)
  208. {
  209. struct link_map *lm;
  210. for (lm = GC_FirstDLOpenedLinkMap(); lm != 0; lm = lm->l_next) {
  211. ElfW(Ehdr) * e;
  212. ElfW(Phdr) * p;
  213. unsigned long offset;
  214. char * start;
  215. int i;
  216. e = (ElfW(Ehdr) *) lm->l_addr;
  217. p = ((ElfW(Phdr) *)(((char *)(e)) + e->e_phoff));
  218. offset = ((unsigned long)(lm->l_addr));
  219. for( i = 0; i < (int)e->e_phnum; i++, p++ ) {
  220. switch( p->p_type ) {
  221. case PT_LOAD:
  222. {
  223. if( !(p->p_flags & PF_W) ) break;
  224. start = ((char *)(p->p_vaddr)) + offset;
  225. GC_add_roots_inner(start, start + p->p_memsz, TRUE);
  226. }
  227. break;
  228. default:
  229. break;
  230. }
  231. }
  232. }
  233. }
  234. # endif /* !USE_PROC ... */
  235. # endif /* SOLARISDL */
  236. #if defined(SCO_ELF) || defined(DGUX) || defined(HURD) \
  237. || (defined(__ELF__) && (defined(LINUX) || defined(FREEBSD) \
  238. || defined(NACL) || defined(NETBSD) \
  239. || defined(OPENBSD)))
  240. #ifdef USE_PROC_FOR_LIBRARIES
  241. #include <string.h>
  242. #include <sys/stat.h>
  243. #include <fcntl.h>
  244. #include <unistd.h>
  245. #define MAPS_BUF_SIZE (32*1024)
  246. /* Sort an array of HeapSects by start address. */
  247. /* Unfortunately at least some versions of */
  248. /* Linux qsort end up calling malloc by way of sysconf, and hence can't */
  249. /* be used in the collector. Hence we roll our own. Should be */
  250. /* reasonably fast if the array is already mostly sorted, as we expect */
  251. /* it to be. */
  252. static void sort_heap_sects(struct HeapSect *base, size_t number_of_elements)
  253. {
  254. signed_word n = (signed_word)number_of_elements;
  255. signed_word nsorted = 1;
  256. while (nsorted < n) {
  257. signed_word i;
  258. while (nsorted < n &&
  259. (word)base[nsorted-1].hs_start < (word)base[nsorted].hs_start)
  260. ++nsorted;
  261. if (nsorted == n) break;
  262. GC_ASSERT((word)base[nsorted-1].hs_start > (word)base[nsorted].hs_start);
  263. i = nsorted - 1;
  264. while (i >= 0 && (word)base[i].hs_start > (word)base[i+1].hs_start) {
  265. struct HeapSect tmp = base[i];
  266. base[i] = base[i+1];
  267. base[i+1] = tmp;
  268. --i;
  269. }
  270. GC_ASSERT((word)base[nsorted-1].hs_start < (word)base[nsorted].hs_start);
  271. ++nsorted;
  272. }
  273. }
  274. STATIC void GC_register_map_entries(char *maps)
  275. {
  276. char *prot;
  277. char *buf_ptr = maps;
  278. ptr_t start, end;
  279. unsigned int maj_dev;
  280. ptr_t least_ha, greatest_ha;
  281. unsigned i;
  282. GC_ASSERT(I_HOLD_LOCK());
  283. sort_heap_sects(GC_our_memory, GC_n_memory);
  284. least_ha = GC_our_memory[0].hs_start;
  285. greatest_ha = GC_our_memory[GC_n_memory-1].hs_start
  286. + GC_our_memory[GC_n_memory-1].hs_bytes;
  287. for (;;) {
  288. buf_ptr = GC_parse_map_entry(buf_ptr, &start, &end, &prot,
  289. &maj_dev, 0);
  290. if (NULL == buf_ptr)
  291. break;
  292. if (prot[1] == 'w') {
  293. /* This is a writable mapping. Add it to */
  294. /* the root set unless it is already otherwise */
  295. /* accounted for. */
  296. if ((word)start <= (word)GC_stackbottom
  297. && (word)end >= (word)GC_stackbottom) {
  298. /* Stack mapping; discard */
  299. continue;
  300. }
  301. # ifdef THREADS
  302. /* This may fail, since a thread may already be */
  303. /* unregistered, but its thread stack may still be there. */
  304. /* That can fail because the stack may disappear while */
  305. /* we're marking. Thus the marker is, and has to be */
  306. /* prepared to recover from segmentation faults. */
  307. if (GC_segment_is_thread_stack(start, end)) continue;
  308. /* FIXME: NPTL squirrels */
  309. /* away pointers in pieces of the stack segment that we */
  310. /* don't scan. We work around this */
  311. /* by treating anything allocated by libpthread as */
  312. /* uncollectible, as we do in some other cases. */
  313. /* A specifically identified problem is that */
  314. /* thread stacks contain pointers to dynamic thread */
  315. /* vectors, which may be reused due to thread caching. */
  316. /* They may not be marked if the thread is still live. */
  317. /* This specific instance should be addressed by */
  318. /* INCLUDE_LINUX_THREAD_DESCR, but that doesn't quite */
  319. /* seem to suffice. */
  320. /* We currently trace entire thread stacks, if they are */
  321. /* are currently cached but unused. This is */
  322. /* very suboptimal for performance reasons. */
  323. # endif
  324. /* We no longer exclude the main data segment. */
  325. if ((word)end <= (word)least_ha
  326. || (word)start >= (word)greatest_ha) {
  327. /* The easy case; just trace entire segment */
  328. GC_add_roots_inner(start, end, TRUE);
  329. continue;
  330. }
  331. /* Add sections that don't belong to us. */
  332. i = 0;
  333. while ((word)(GC_our_memory[i].hs_start
  334. + GC_our_memory[i].hs_bytes) < (word)start)
  335. ++i;
  336. GC_ASSERT(i < GC_n_memory);
  337. if ((word)GC_our_memory[i].hs_start <= (word)start) {
  338. start = GC_our_memory[i].hs_start
  339. + GC_our_memory[i].hs_bytes;
  340. ++i;
  341. }
  342. while (i < GC_n_memory
  343. && (word)GC_our_memory[i].hs_start < (word)end
  344. && (word)start < (word)end) {
  345. if ((word)start < (word)GC_our_memory[i].hs_start)
  346. GC_add_roots_inner(start,
  347. GC_our_memory[i].hs_start, TRUE);
  348. start = GC_our_memory[i].hs_start
  349. + GC_our_memory[i].hs_bytes;
  350. ++i;
  351. }
  352. if ((word)start < (word)end)
  353. GC_add_roots_inner(start, end, TRUE);
  354. } else if (prot[0] == '-' && prot[1] == '-' && prot[2] == '-') {
  355. /* Even roots added statically might disappear partially */
  356. /* (e.g. the roots added by INCLUDE_LINUX_THREAD_DESCR). */
  357. GC_remove_roots_subregion(start, end);
  358. }
  359. }
  360. }
  361. GC_INNER void GC_register_dynamic_libraries(void)
  362. {
  363. char *maps = GC_get_maps();
  364. if (NULL == maps)
  365. ABORT("Failed to read /proc for library registration");
  366. GC_register_map_entries(maps);
  367. }
  368. /* We now take care of the main data segment ourselves: */
  369. GC_INNER GC_bool GC_register_main_static_data(void)
  370. {
  371. return FALSE;
  372. }
  373. # define HAVE_REGISTER_MAIN_STATIC_DATA
  374. #else /* !USE_PROC_FOR_LIBRARIES */
  375. /* The following is the preferred way to walk dynamic libraries */
  376. /* for glibc 2.2.4+. Unfortunately, it doesn't work for older */
  377. /* versions. Thanks to Jakub Jelinek for most of the code. */
  378. #if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ > 2) \
  379. || (__GLIBC__ == 2 && __GLIBC_MINOR__ == 2 && defined(DT_CONFIG)) \
  380. || defined(HOST_ANDROID) /* Are others OK here, too? */
  381. # ifndef HAVE_DL_ITERATE_PHDR
  382. # define HAVE_DL_ITERATE_PHDR
  383. # endif
  384. # ifdef HOST_ANDROID
  385. /* Android headers might have no such definition for some targets. */
  386. EXTERN_C_BEGIN
  387. extern int dl_iterate_phdr(int (*cb)(struct dl_phdr_info *,
  388. size_t, void *),
  389. void *data);
  390. EXTERN_C_END
  391. # endif
  392. #endif /* __GLIBC__ >= 2 || HOST_ANDROID */
  393. #if defined(__DragonFly__) || defined(__FreeBSD_kernel__) \
  394. || (defined(FREEBSD) && __FreeBSD__ >= 7)
  395. /* On the FreeBSD system, any target system at major version 7 shall */
  396. /* have dl_iterate_phdr; therefore, we need not make it weak as below. */
  397. # ifndef HAVE_DL_ITERATE_PHDR
  398. # define HAVE_DL_ITERATE_PHDR
  399. # endif
  400. # define DL_ITERATE_PHDR_STRONG
  401. #elif defined(HAVE_DL_ITERATE_PHDR)
  402. /* We have the header files for a glibc that includes dl_iterate_phdr.*/
  403. /* It may still not be available in the library on the target system. */
  404. /* Thus we also treat it as a weak symbol. */
  405. EXTERN_C_BEGIN
  406. # pragma weak dl_iterate_phdr
  407. EXTERN_C_END
  408. #endif
  409. #if defined(HAVE_DL_ITERATE_PHDR)
  410. # ifdef PT_GNU_RELRO
  411. /* Instead of registering PT_LOAD sections directly, we keep them */
  412. /* in a temporary list, and filter them by excluding PT_GNU_RELRO */
  413. /* segments. Processing PT_GNU_RELRO sections with */
  414. /* GC_exclude_static_roots instead would be superficially cleaner. But */
  415. /* it runs into trouble if a client registers an overlapping segment, */
  416. /* which unfortunately seems quite possible. */
  417. # define MAX_LOAD_SEGS MAX_ROOT_SETS
  418. static struct load_segment {
  419. ptr_t start;
  420. ptr_t end;
  421. /* Room for a second segment if we remove a RELRO segment */
  422. /* from the middle. */
  423. ptr_t start2;
  424. ptr_t end2;
  425. } load_segs[MAX_LOAD_SEGS];
  426. static int n_load_segs;
  427. static GC_bool load_segs_overflow;
  428. # endif /* PT_GNU_RELRO */
  429. STATIC int GC_register_dynlib_callback(struct dl_phdr_info * info,
  430. size_t size, void * ptr)
  431. {
  432. const ElfW(Phdr) * p;
  433. ptr_t start, end;
  434. int i;
  435. /* Make sure struct dl_phdr_info is at least as big as we need. */
  436. if (size < offsetof (struct dl_phdr_info, dlpi_phnum)
  437. + sizeof (info->dlpi_phnum))
  438. return -1;
  439. p = info->dlpi_phdr;
  440. for (i = 0; i < (int)info->dlpi_phnum; i++, p++) {
  441. if (p->p_type == PT_LOAD) {
  442. GC_has_static_roots_func callback = GC_has_static_roots;
  443. if ((p->p_flags & PF_W) == 0) continue;
  444. start = (ptr_t)p->p_vaddr + info->dlpi_addr;
  445. end = start + p->p_memsz;
  446. if (callback != 0 && !callback(info->dlpi_name, start, p->p_memsz))
  447. continue;
  448. # ifdef PT_GNU_RELRO
  449. # if CPP_WORDSZ == 64
  450. /* TODO: GC_push_all eventually does the correct */
  451. /* rounding to the next multiple of ALIGNMENT, so, most */
  452. /* probably, we should remove the corresponding assertion */
  453. /* check in GC_add_roots_inner along with this code line. */
  454. /* start pointer value may require aligning. */
  455. start = (ptr_t)((word)start & ~(word)(sizeof(word) - 1));
  456. # endif
  457. if (n_load_segs >= MAX_LOAD_SEGS) {
  458. if (!load_segs_overflow) {
  459. WARN("Too many PT_LOAD segments;"
  460. " registering as roots directly...\n", 0);
  461. load_segs_overflow = TRUE;
  462. }
  463. GC_add_roots_inner(start, end, TRUE);
  464. } else {
  465. load_segs[n_load_segs].start = start;
  466. load_segs[n_load_segs].end = end;
  467. load_segs[n_load_segs].start2 = 0;
  468. load_segs[n_load_segs].end2 = 0;
  469. ++n_load_segs;
  470. }
  471. # else
  472. GC_add_roots_inner(start, end, TRUE);
  473. # endif /* !PT_GNU_RELRO */
  474. }
  475. }
  476. # ifdef PT_GNU_RELRO
  477. p = info->dlpi_phdr;
  478. for (i = 0; i < (int)info->dlpi_phnum; i++, p++) {
  479. if (p->p_type == PT_GNU_RELRO) {
  480. /* This entry is known to be constant and will eventually be */
  481. /* remapped as read-only. However, the address range covered */
  482. /* by this entry is typically a subset of a previously */
  483. /* encountered "LOAD" segment, so we need to exclude it. */
  484. int j;
  485. start = (ptr_t)p->p_vaddr + info->dlpi_addr;
  486. end = start + p->p_memsz;
  487. for (j = n_load_segs; --j >= 0; ) {
  488. if ((word)start >= (word)load_segs[j].start
  489. && (word)start < (word)load_segs[j].end) {
  490. if (load_segs[j].start2 != 0) {
  491. WARN("More than one GNU_RELRO segment per load one\n",0);
  492. } else {
  493. GC_ASSERT((word)end <= (word)load_segs[j].end);
  494. /* Remove from the existing load segment */
  495. load_segs[j].end2 = load_segs[j].end;
  496. load_segs[j].end = start;
  497. load_segs[j].start2 = end;
  498. }
  499. break;
  500. }
  501. if (0 == j && 0 == GC_has_static_roots)
  502. WARN("Failed to find PT_GNU_RELRO segment"
  503. " inside PT_LOAD region\n", 0);
  504. /* No warning reported in case of the callback is present */
  505. /* because most likely the segment has been excluded. */
  506. }
  507. }
  508. }
  509. # endif
  510. *(int *)ptr = 1; /* Signal that we were called */
  511. return 0;
  512. }
  513. /* Do we need to separately register the main static data segment? */
  514. GC_INNER GC_bool GC_register_main_static_data(void)
  515. {
  516. # ifdef DL_ITERATE_PHDR_STRONG
  517. /* If dl_iterate_phdr is not a weak symbol then don't test against */
  518. /* zero (otherwise a compiler might issue a warning). */
  519. return FALSE;
  520. # else
  521. return 0 == COVERT_DATAFLOW(dl_iterate_phdr);
  522. # endif
  523. }
  524. /* Return TRUE if we succeed, FALSE if dl_iterate_phdr wasn't there. */
  525. STATIC GC_bool GC_register_dynamic_libraries_dl_iterate_phdr(void)
  526. {
  527. int did_something;
  528. if (GC_register_main_static_data())
  529. return FALSE;
  530. # ifdef PT_GNU_RELRO
  531. {
  532. static GC_bool excluded_segs = FALSE;
  533. n_load_segs = 0;
  534. load_segs_overflow = FALSE;
  535. if (!EXPECT(excluded_segs, TRUE)) {
  536. GC_exclude_static_roots_inner((ptr_t)load_segs,
  537. (ptr_t)load_segs + sizeof(load_segs));
  538. excluded_segs = TRUE;
  539. }
  540. }
  541. # endif
  542. did_something = 0;
  543. dl_iterate_phdr(GC_register_dynlib_callback, &did_something);
  544. if (did_something) {
  545. # ifdef PT_GNU_RELRO
  546. int i;
  547. for (i = 0; i < n_load_segs; ++i) {
  548. if ((word)load_segs[i].end > (word)load_segs[i].start) {
  549. GC_add_roots_inner(load_segs[i].start, load_segs[i].end, TRUE);
  550. }
  551. if ((word)load_segs[i].end2 > (word)load_segs[i].start2) {
  552. GC_add_roots_inner(load_segs[i].start2, load_segs[i].end2, TRUE);
  553. }
  554. }
  555. # endif
  556. } else {
  557. ptr_t datastart, dataend;
  558. # ifdef DATASTART_IS_FUNC
  559. static ptr_t datastart_cached = (ptr_t)(word)-1;
  560. /* Evaluate DATASTART only once. */
  561. if (datastart_cached == (ptr_t)(word)-1) {
  562. datastart_cached = DATASTART;
  563. }
  564. datastart = datastart_cached;
  565. # else
  566. datastart = DATASTART;
  567. # endif
  568. # ifdef DATAEND_IS_FUNC
  569. {
  570. static ptr_t dataend_cached = 0;
  571. /* Evaluate DATAEND only once. */
  572. if (dataend_cached == 0) {
  573. dataend_cached = DATAEND;
  574. }
  575. dataend = dataend_cached;
  576. }
  577. # else
  578. dataend = DATAEND;
  579. # endif
  580. if (NULL == *(char * volatile *)&datastart
  581. || (word)datastart > (word)dataend)
  582. ABORT_ARG2("Wrong DATASTART/END pair",
  583. ": %p .. %p", (void *)datastart, (void *)dataend);
  584. /* dl_iterate_phdr may forget the static data segment in */
  585. /* statically linked executables. */
  586. GC_add_roots_inner(datastart, dataend, TRUE);
  587. # ifdef GC_HAVE_DATAREGION2
  588. if ((word)DATASTART2 - 1U >= (word)DATAEND2) {
  589. /* Subtract one to check also for NULL */
  590. /* without a compiler warning. */
  591. ABORT_ARG2("Wrong DATASTART/END2 pair",
  592. ": %p .. %p", (void *)DATASTART2, (void *)DATAEND2);
  593. }
  594. GC_add_roots_inner(DATASTART2, DATAEND2, TRUE);
  595. # endif
  596. }
  597. return TRUE;
  598. }
  599. # define HAVE_REGISTER_MAIN_STATIC_DATA
  600. #else /* !HAVE_DL_ITERATE_PHDR */
  601. /* Dynamic loading code for Linux running ELF. Somewhat tested on
  602. * Linux/x86, untested but hopefully should work on Linux/Alpha.
  603. * This code was derived from the Solaris/ELF support. Thanks to
  604. * whatever kind soul wrote that. - Patrick Bridges */
  605. /* This doesn't necessarily work in all cases, e.g. with preloaded
  606. * dynamic libraries. */
  607. # if defined(NETBSD) || defined(OPENBSD)
  608. # include <sys/exec_elf.h>
  609. /* for compatibility with 1.4.x */
  610. # ifndef DT_DEBUG
  611. # define DT_DEBUG 21
  612. # endif
  613. # ifndef PT_LOAD
  614. # define PT_LOAD 1
  615. # endif
  616. # ifndef PF_W
  617. # define PF_W 2
  618. # endif
  619. # elif !defined(HOST_ANDROID)
  620. # include <elf.h>
  621. # endif
  622. # ifndef HOST_ANDROID
  623. # include <link.h>
  624. # endif
  625. #endif /* !HAVE_DL_ITERATE_PHDR */
  626. EXTERN_C_BEGIN
  627. #ifdef __GNUC__
  628. # pragma weak _DYNAMIC
  629. #endif
  630. extern ElfW(Dyn) _DYNAMIC[];
  631. EXTERN_C_END
  632. STATIC struct link_map *
  633. GC_FirstDLOpenedLinkMap(void)
  634. {
  635. static struct link_map *cachedResult = 0;
  636. if (0 == COVERT_DATAFLOW(_DYNAMIC)) {
  637. /* _DYNAMIC symbol not resolved. */
  638. return(0);
  639. }
  640. if( cachedResult == 0 ) {
  641. # if defined(NETBSD) && defined(RTLD_DI_LINKMAP)
  642. # if defined(CPPCHECK)
  643. # define GC_RTLD_DI_LINKMAP 2
  644. # else
  645. # define GC_RTLD_DI_LINKMAP RTLD_DI_LINKMAP
  646. # endif
  647. struct link_map *lm = NULL;
  648. if (!dlinfo(RTLD_SELF, GC_RTLD_DI_LINKMAP, &lm) && lm != NULL) {
  649. /* Now lm points link_map object of libgc. Since it */
  650. /* might not be the first dynamically linked object, */
  651. /* try to find it (object next to the main object). */
  652. while (lm->l_prev != NULL) {
  653. lm = lm->l_prev;
  654. }
  655. cachedResult = lm->l_next;
  656. }
  657. # else
  658. ElfW(Dyn) *dp;
  659. int tag;
  660. for( dp = _DYNAMIC; (tag = dp->d_tag) != 0; dp++ ) {
  661. if (tag == DT_DEBUG) {
  662. struct r_debug *rd = (struct r_debug *)dp->d_un.d_ptr;
  663. /* d_ptr could be null if libs are linked statically. */
  664. if (rd != NULL) {
  665. struct link_map *lm = rd->r_map;
  666. if (lm != NULL)
  667. cachedResult = lm->l_next; /* might be NULL */
  668. }
  669. break;
  670. }
  671. }
  672. # endif /* !NETBSD || !RTLD_DI_LINKMAP */
  673. }
  674. return cachedResult;
  675. }
  676. GC_INNER void GC_register_dynamic_libraries(void)
  677. {
  678. struct link_map *lm;
  679. # ifdef HAVE_DL_ITERATE_PHDR
  680. if (GC_register_dynamic_libraries_dl_iterate_phdr()) {
  681. return;
  682. }
  683. # endif
  684. for (lm = GC_FirstDLOpenedLinkMap(); lm != 0; lm = lm->l_next)
  685. {
  686. ElfW(Ehdr) * e;
  687. ElfW(Phdr) * p;
  688. unsigned long offset;
  689. char * start;
  690. int i;
  691. e = (ElfW(Ehdr) *) lm->l_addr;
  692. # ifdef HOST_ANDROID
  693. if (e == NULL)
  694. continue;
  695. # endif
  696. p = ((ElfW(Phdr) *)(((char *)(e)) + e->e_phoff));
  697. offset = ((unsigned long)(lm->l_addr));
  698. for( i = 0; i < (int)e->e_phnum; i++, p++ ) {
  699. switch( p->p_type ) {
  700. case PT_LOAD:
  701. {
  702. if( !(p->p_flags & PF_W) ) break;
  703. start = ((char *)(p->p_vaddr)) + offset;
  704. GC_add_roots_inner(start, start + p->p_memsz, TRUE);
  705. }
  706. break;
  707. default:
  708. break;
  709. }
  710. }
  711. }
  712. }
  713. #endif /* !USE_PROC_FOR_LIBRARIES */
  714. #endif /* LINUX */
  715. #if defined(IRIX5) || (defined(USE_PROC_FOR_LIBRARIES) && !defined(LINUX))
  716. #include <sys/procfs.h>
  717. #include <sys/stat.h>
  718. #include <fcntl.h>
  719. #include <elf.h>
  720. #include <errno.h>
  721. #include <signal.h> /* Only for the following test. */
  722. #ifndef _sigargs
  723. # define IRIX6
  724. #endif
  725. /* We use /proc to track down all parts of the address space that are */
  726. /* mapped by the process, and throw out regions we know we shouldn't */
  727. /* worry about. This may also work under other SVR4 variants. */
  728. GC_INNER void GC_register_dynamic_libraries(void)
  729. {
  730. static int fd = -1;
  731. char buf[30];
  732. static prmap_t * addr_map = 0;
  733. static int current_sz = 0; /* Number of records currently in addr_map */
  734. int needed_sz = 0; /* Required size of addr_map */
  735. int i;
  736. long flags;
  737. ptr_t start;
  738. ptr_t limit;
  739. ptr_t heap_start = HEAP_START;
  740. ptr_t heap_end = heap_start;
  741. # ifdef SOLARISDL
  742. # define MA_PHYS 0
  743. # endif /* SOLARISDL */
  744. if (fd < 0) {
  745. (void)snprintf(buf, sizeof(buf), "/proc/%ld", (long)getpid());
  746. buf[sizeof(buf) - 1] = '\0';
  747. fd = open(buf, O_RDONLY);
  748. if (fd < 0) {
  749. ABORT("/proc open failed");
  750. }
  751. }
  752. if (ioctl(fd, PIOCNMAP, &needed_sz) < 0) {
  753. ABORT_ARG2("/proc PIOCNMAP ioctl failed",
  754. ": fd = %d, errno = %d", fd, errno);
  755. }
  756. if (needed_sz >= current_sz) {
  757. GC_scratch_recycle_no_gww(addr_map,
  758. (size_t)current_sz * sizeof(prmap_t));
  759. current_sz = needed_sz * 2 + 1;
  760. /* Expansion, plus room for 0 record */
  761. addr_map = (prmap_t *)GC_scratch_alloc(
  762. (size_t)current_sz * sizeof(prmap_t));
  763. if (addr_map == NULL)
  764. ABORT("Insufficient memory for address map");
  765. }
  766. if (ioctl(fd, PIOCMAP, addr_map) < 0) {
  767. ABORT_ARG3("/proc PIOCMAP ioctl failed",
  768. ": errcode= %d, needed_sz= %d, addr_map= %p",
  769. errno, needed_sz, (void *)addr_map);
  770. };
  771. if (GC_n_heap_sects > 0) {
  772. heap_end = GC_heap_sects[GC_n_heap_sects-1].hs_start
  773. + GC_heap_sects[GC_n_heap_sects-1].hs_bytes;
  774. if ((word)heap_end < (word)GC_scratch_last_end_ptr)
  775. heap_end = GC_scratch_last_end_ptr;
  776. }
  777. for (i = 0; i < needed_sz; i++) {
  778. flags = addr_map[i].pr_mflags;
  779. if ((flags & (MA_BREAK | MA_STACK | MA_PHYS
  780. | MA_FETCHOP | MA_NOTCACHED)) != 0) goto irrelevant;
  781. if ((flags & (MA_READ | MA_WRITE)) != (MA_READ | MA_WRITE))
  782. goto irrelevant;
  783. /* The latter test is empirically useless in very old Irix */
  784. /* versions. Other than the */
  785. /* main data and stack segments, everything appears to be */
  786. /* mapped readable, writable, executable, and shared(!!). */
  787. /* This makes no sense to me. - HB */
  788. start = (ptr_t)(addr_map[i].pr_vaddr);
  789. if (GC_roots_present(start)) goto irrelevant;
  790. if ((word)start < (word)heap_end && (word)start >= (word)heap_start)
  791. goto irrelevant;
  792. limit = start + addr_map[i].pr_size;
  793. /* The following seemed to be necessary for very old versions */
  794. /* of Irix, but it has been reported to discard relevant */
  795. /* segments under Irix 6.5. */
  796. # ifndef IRIX6
  797. if (addr_map[i].pr_off == 0 && strncmp(start, ELFMAG, 4) == 0) {
  798. /* Discard text segments, i.e. 0-offset mappings against */
  799. /* executable files which appear to have ELF headers. */
  800. caddr_t arg;
  801. int obj;
  802. # define MAP_IRR_SZ 10
  803. static ptr_t map_irr[MAP_IRR_SZ];
  804. /* Known irrelevant map entries */
  805. static int n_irr = 0;
  806. struct stat buf;
  807. int j;
  808. for (j = 0; j < n_irr; j++) {
  809. if (map_irr[j] == start) goto irrelevant;
  810. }
  811. arg = (caddr_t)start;
  812. obj = ioctl(fd, PIOCOPENM, &arg);
  813. if (obj >= 0) {
  814. fstat(obj, &buf);
  815. close(obj);
  816. if ((buf.st_mode & 0111) != 0) {
  817. if (n_irr < MAP_IRR_SZ) {
  818. map_irr[n_irr++] = start;
  819. }
  820. goto irrelevant;
  821. }
  822. }
  823. }
  824. # endif /* !IRIX6 */
  825. GC_add_roots_inner(start, limit, TRUE);
  826. irrelevant: ;
  827. }
  828. /* Don't keep cached descriptor, for now. Some kernels don't like us */
  829. /* to keep a /proc file descriptor around during kill -9. */
  830. if (close(fd) < 0) ABORT("Couldn't close /proc file");
  831. fd = -1;
  832. }
  833. # endif /* USE_PROC || IRIX5 */
  834. # if defined(MSWIN32) || defined(MSWINCE) || defined(CYGWIN32)
  835. # ifndef WIN32_LEAN_AND_MEAN
  836. # define WIN32_LEAN_AND_MEAN 1
  837. # endif
  838. # define NOSERVICE
  839. # include <windows.h>
  840. # include <stdlib.h>
  841. /* We traverse the entire address space and register all segments */
  842. /* that could possibly have been written to. */
  843. STATIC void GC_cond_add_roots(char *base, char * limit)
  844. {
  845. # ifdef GC_WIN32_THREADS
  846. char * curr_base = base;
  847. char * next_stack_lo;
  848. char * next_stack_hi;
  849. if (base == limit) return;
  850. for(;;) {
  851. GC_get_next_stack(curr_base, limit, &next_stack_lo, &next_stack_hi);
  852. if ((word)next_stack_lo >= (word)limit) break;
  853. if ((word)next_stack_lo > (word)curr_base)
  854. GC_add_roots_inner(curr_base, next_stack_lo, TRUE);
  855. curr_base = next_stack_hi;
  856. }
  857. if ((word)curr_base < (word)limit)
  858. GC_add_roots_inner(curr_base, limit, TRUE);
  859. # else
  860. char * stack_top
  861. = (char *)((word)GC_approx_sp() &
  862. ~(word)(GC_sysinfo.dwAllocationGranularity - 1));
  863. if (base == limit) return;
  864. if ((word)limit > (word)stack_top
  865. && (word)base < (word)GC_stackbottom) {
  866. /* Part of the stack; ignore it. */
  867. return;
  868. }
  869. GC_add_roots_inner(base, limit, TRUE);
  870. # endif
  871. }
  872. #ifdef DYNAMIC_LOADING
  873. /* GC_register_main_static_data is not needed unless DYNAMIC_LOADING. */
  874. GC_INNER GC_bool GC_register_main_static_data(void)
  875. {
  876. # if defined(MSWINCE) || defined(CYGWIN32)
  877. /* Do we need to separately register the main static data segment? */
  878. return FALSE;
  879. # else
  880. return GC_no_win32_dlls;
  881. # endif
  882. }
  883. # define HAVE_REGISTER_MAIN_STATIC_DATA
  884. #endif /* DYNAMIC_LOADING */
  885. # ifdef DEBUG_VIRTUALQUERY
  886. void GC_dump_meminfo(MEMORY_BASIC_INFORMATION *buf)
  887. {
  888. GC_printf("BaseAddress = 0x%lx, AllocationBase = 0x%lx,"
  889. " RegionSize = 0x%lx(%lu)\n", buf -> BaseAddress,
  890. buf -> AllocationBase, buf -> RegionSize, buf -> RegionSize);
  891. GC_printf("\tAllocationProtect = 0x%lx, State = 0x%lx, Protect = 0x%lx, "
  892. "Type = 0x%lx\n", buf -> AllocationProtect, buf -> State,
  893. buf -> Protect, buf -> Type);
  894. }
  895. # endif /* DEBUG_VIRTUALQUERY */
  896. # if defined(MSWINCE) || defined(CYGWIN32)
  897. /* FIXME: Should we really need to scan MEM_PRIVATE sections? */
  898. /* For now, we don't add MEM_PRIVATE sections to the data roots for */
  899. /* WinCE because otherwise SEGV fault sometimes happens to occur in */
  900. /* GC_mark_from() (and, even if we use WRAP_MARK_SOME, WinCE prints */
  901. /* a "Data Abort" message to the debugging console). */
  902. /* To workaround that, use -DGC_REGISTER_MEM_PRIVATE. */
  903. # define GC_wnt TRUE
  904. # endif
  905. GC_INNER void GC_register_dynamic_libraries(void)
  906. {
  907. MEMORY_BASIC_INFORMATION buf;
  908. DWORD protect;
  909. LPVOID p;
  910. char * base;
  911. char * limit, * new_limit;
  912. # ifdef MSWIN32
  913. if (GC_no_win32_dlls) return;
  914. # endif
  915. p = GC_sysinfo.lpMinimumApplicationAddress;
  916. base = limit = (char *)p;
  917. while ((word)p < (word)GC_sysinfo.lpMaximumApplicationAddress) {
  918. size_t result = VirtualQuery(p, &buf, sizeof(buf));
  919. # ifdef MSWINCE
  920. if (result == 0) {
  921. /* Page is free; advance to the next possible allocation base */
  922. new_limit = (char *)
  923. (((DWORD) p + GC_sysinfo.dwAllocationGranularity)
  924. & ~(GC_sysinfo.dwAllocationGranularity-1));
  925. } else
  926. # endif
  927. /* else */ {
  928. if (result != sizeof(buf)) {
  929. ABORT("Weird VirtualQuery result");
  930. }
  931. new_limit = (char *)p + buf.RegionSize;
  932. protect = buf.Protect;
  933. if (buf.State == MEM_COMMIT
  934. && (protect == PAGE_EXECUTE_READWRITE
  935. || protect == PAGE_EXECUTE_WRITECOPY
  936. || protect == PAGE_READWRITE
  937. || protect == PAGE_WRITECOPY)
  938. && (buf.Type == MEM_IMAGE
  939. # ifdef GC_REGISTER_MEM_PRIVATE
  940. || (protect == PAGE_READWRITE && buf.Type == MEM_PRIVATE)
  941. # else
  942. /* There is some evidence that we cannot always */
  943. /* ignore MEM_PRIVATE sections under Windows ME */
  944. /* and predecessors. Hence we now also check for */
  945. /* that case. */
  946. || (!GC_wnt && buf.Type == MEM_PRIVATE)
  947. # endif
  948. )
  949. && !GC_is_heap_base(buf.AllocationBase)) {
  950. # ifdef DEBUG_VIRTUALQUERY
  951. GC_dump_meminfo(&buf);
  952. # endif
  953. if ((char *)p != limit) {
  954. GC_cond_add_roots(base, limit);
  955. base = (char *)p;
  956. }
  957. limit = new_limit;
  958. }
  959. }
  960. if ((word)p > (word)new_limit /* overflow */) break;
  961. p = (LPVOID)new_limit;
  962. }
  963. GC_cond_add_roots(base, limit);
  964. }
  965. #endif /* MSWIN32 || MSWINCE || CYGWIN32 */
  966. #if defined(ALPHA) && defined(OSF1)
  967. #include <loader.h>
  968. EXTERN_C_BEGIN
  969. extern char *sys_errlist[];
  970. extern int sys_nerr;
  971. extern int errno;
  972. EXTERN_C_END
  973. GC_INNER void GC_register_dynamic_libraries(void)
  974. {
  975. ldr_module_t moduleid = LDR_NULL_MODULE;
  976. ldr_process_t mypid = ldr_my_process(); /* obtain id of this process */
  977. /* For each module */
  978. while (TRUE) {
  979. ldr_module_info_t moduleinfo;
  980. size_t modulereturnsize;
  981. ldr_region_t region;
  982. ldr_region_info_t regioninfo;
  983. size_t regionreturnsize;
  984. int status = ldr_next_module(mypid, &moduleid);
  985. /* Get the next (first) module */
  986. /* Any more modules? */
  987. if (moduleid == LDR_NULL_MODULE)
  988. break; /* No more modules */
  989. /* Check status AFTER checking moduleid because */
  990. /* of a bug in the non-shared ldr_next_module stub. */
  991. if (status != 0) {
  992. ABORT_ARG3("ldr_next_module failed",
  993. ": status= %d, errcode= %d (%s)", status, errno,
  994. errno < sys_nerr ? sys_errlist[errno] : "");
  995. }
  996. /* Get the module information */
  997. status = ldr_inq_module(mypid, moduleid, &moduleinfo,
  998. sizeof(moduleinfo), &modulereturnsize);
  999. if (status != 0 )
  1000. ABORT("ldr_inq_module failed");
  1001. /* is module for the main program (i.e. nonshared portion)? */
  1002. if (moduleinfo.lmi_flags & LDR_MAIN)
  1003. continue; /* skip the main module */
  1004. # ifdef DL_VERBOSE
  1005. GC_log_printf("---Module---\n");
  1006. GC_log_printf("Module ID\t = %16ld\n", moduleinfo.lmi_modid);
  1007. GC_log_printf("Count of regions = %16d\n", moduleinfo.lmi_nregion);
  1008. GC_log_printf("flags for module = %16lx\n", moduleinfo.lmi_flags);
  1009. GC_log_printf("module pathname\t = \"%s\"\n", moduleinfo.lmi_name);
  1010. # endif
  1011. /* For each region in this module */
  1012. for (region = 0; region < moduleinfo.lmi_nregion; region++) {
  1013. /* Get the region information */
  1014. status = ldr_inq_region(mypid, moduleid, region, &regioninfo,
  1015. sizeof(regioninfo), &regionreturnsize);
  1016. if (status != 0 )
  1017. ABORT("ldr_inq_region failed");
  1018. /* only process writable (data) regions */
  1019. if (! (regioninfo.lri_prot & LDR_W))
  1020. continue;
  1021. # ifdef DL_VERBOSE
  1022. GC_log_printf("--- Region ---\n");
  1023. GC_log_printf("Region number\t = %16ld\n",
  1024. regioninfo.lri_region_no);
  1025. GC_log_printf("Protection flags = %016x\n", regioninfo.lri_prot);
  1026. GC_log_printf("Virtual address\t = %16p\n", regioninfo.lri_vaddr);
  1027. GC_log_printf("Mapped address\t = %16p\n",
  1028. regioninfo.lri_mapaddr);
  1029. GC_log_printf("Region size\t = %16ld\n", regioninfo.lri_size);
  1030. GC_log_printf("Region name\t = \"%s\"\n", regioninfo.lri_name);
  1031. # endif
  1032. /* register region as a garbage collection root */
  1033. GC_add_roots_inner((char *)regioninfo.lri_mapaddr,
  1034. (char *)regioninfo.lri_mapaddr + regioninfo.lri_size,
  1035. TRUE);
  1036. }
  1037. }
  1038. }
  1039. #endif
  1040. #if defined(HPUX)
  1041. #include <errno.h>
  1042. #include <dl.h>
  1043. EXTERN_C_BEGIN
  1044. extern char *sys_errlist[];
  1045. extern int sys_nerr;
  1046. EXTERN_C_END
  1047. GC_INNER void GC_register_dynamic_libraries(void)
  1048. {
  1049. int index = 1; /* Ordinal position in shared library search list */
  1050. /* For each dynamic library loaded */
  1051. while (TRUE) {
  1052. struct shl_descriptor *shl_desc; /* Shared library info, see dl.h */
  1053. int status = shl_get(index, &shl_desc);
  1054. /* Get info about next shared library */
  1055. /* Check if this is the end of the list or if some error occurred */
  1056. if (status != 0) {
  1057. # ifdef GC_HPUX_THREADS
  1058. /* I've seen errno values of 0. The man page is not clear */
  1059. /* as to whether errno should get set on a -1 return. */
  1060. break;
  1061. # else
  1062. if (errno == EINVAL) {
  1063. break; /* Moved past end of shared library list --> finished */
  1064. } else {
  1065. ABORT_ARG3("shl_get failed",
  1066. ": status= %d, errcode= %d (%s)", status, errno,
  1067. errno < sys_nerr ? sys_errlist[errno] : "");
  1068. }
  1069. # endif
  1070. }
  1071. # ifdef DL_VERBOSE
  1072. GC_log_printf("---Shared library---\n");
  1073. GC_log_printf("\tfilename\t= \"%s\"\n", shl_desc->filename);
  1074. GC_log_printf("\tindex\t\t= %d\n", index);
  1075. GC_log_printf("\thandle\t\t= %08x\n",
  1076. (unsigned long) shl_desc->handle);
  1077. GC_log_printf("\ttext seg.start\t= %08x\n", shl_desc->tstart);
  1078. GC_log_printf("\ttext seg.end\t= %08x\n", shl_desc->tend);
  1079. GC_log_printf("\tdata seg.start\t= %08x\n", shl_desc->dstart);
  1080. GC_log_printf("\tdata seg.end\t= %08x\n", shl_desc->dend);
  1081. GC_log_printf("\tref.count\t= %lu\n", shl_desc->ref_count);
  1082. # endif
  1083. /* register shared library's data segment as a garbage collection root */
  1084. GC_add_roots_inner((char *) shl_desc->dstart,
  1085. (char *) shl_desc->dend, TRUE);
  1086. index++;
  1087. }
  1088. }
  1089. #endif /* HPUX */
  1090. #ifdef AIX
  1091. # pragma alloca
  1092. # include <sys/ldr.h>
  1093. # include <sys/errno.h>
  1094. GC_INNER void GC_register_dynamic_libraries(void)
  1095. {
  1096. int ldibuflen = 8192;
  1097. for (;;) {
  1098. int len;
  1099. struct ld_info *ldi;
  1100. # if defined(CPPCHECK)
  1101. char ldibuf[ldibuflen];
  1102. # else
  1103. char *ldibuf = alloca(ldibuflen);
  1104. # endif
  1105. len = loadquery(L_GETINFO, ldibuf, ldibuflen);
  1106. if (len < 0) {
  1107. if (errno != ENOMEM) {
  1108. ABORT("loadquery failed");
  1109. }
  1110. ldibuflen *= 2;
  1111. continue;
  1112. }
  1113. ldi = (struct ld_info *)ldibuf;
  1114. while (ldi) {
  1115. len = ldi->ldinfo_next;
  1116. GC_add_roots_inner(
  1117. ldi->ldinfo_dataorg,
  1118. (ptr_t)(unsigned long)ldi->ldinfo_dataorg
  1119. + ldi->ldinfo_datasize,
  1120. TRUE);
  1121. ldi = len ? (struct ld_info *)((char *)ldi + len) : 0;
  1122. }
  1123. break;
  1124. }
  1125. }
  1126. #endif /* AIX */
  1127. #ifdef DARWIN
  1128. /* __private_extern__ hack required for pre-3.4 gcc versions. */
  1129. #ifndef __private_extern__
  1130. # define __private_extern__ extern
  1131. # include <mach-o/dyld.h>
  1132. # undef __private_extern__
  1133. #else
  1134. # include <mach-o/dyld.h>
  1135. #endif
  1136. #include <mach-o/getsect.h>
  1137. /*#define DARWIN_DEBUG*/
  1138. /* Writable sections generally available on Darwin. */
  1139. STATIC const struct dyld_sections_s {
  1140. const char *seg;
  1141. const char *sect;
  1142. } GC_dyld_sections[] = {
  1143. { SEG_DATA, SECT_DATA },
  1144. /* Used by FSF GCC, but not by OS X system tools, so far. */
  1145. { SEG_DATA, "__static_data" },
  1146. { SEG_DATA, SECT_BSS },
  1147. { SEG_DATA, SECT_COMMON },
  1148. /* FSF GCC - zero-sized object sections for targets */
  1149. /*supporting section anchors. */
  1150. { SEG_DATA, "__zobj_data" },
  1151. { SEG_DATA, "__zobj_bss" }
  1152. };
  1153. /* Additional writable sections: */
  1154. /* GCC on Darwin constructs aligned sections "on demand", where */
  1155. /* the alignment size is embedded in the section name. */
  1156. /* Furthermore, there are distinctions between sections */
  1157. /* containing private vs. public symbols. It also constructs */
  1158. /* sections specifically for zero-sized objects, when the */
  1159. /* target supports section anchors. */
  1160. STATIC const char * const GC_dyld_add_sect_fmts[] = {
  1161. "__bss%u",
  1162. "__pu_bss%u",
  1163. "__zo_bss%u",
  1164. "__zo_pu_bss%u"
  1165. };
  1166. /* Currently, mach-o will allow up to the max of 2^15 alignment */
  1167. /* in an object file. */
  1168. #ifndef L2_MAX_OFILE_ALIGNMENT
  1169. # define L2_MAX_OFILE_ALIGNMENT 15
  1170. #endif
  1171. STATIC const char *GC_dyld_name_for_hdr(const struct GC_MACH_HEADER *hdr)
  1172. {
  1173. unsigned long i, c;
  1174. c = _dyld_image_count();
  1175. for (i = 0; i < c; i++)
  1176. if ((const struct GC_MACH_HEADER *)_dyld_get_image_header(i) == hdr)
  1177. return _dyld_get_image_name(i);
  1178. return NULL;
  1179. }
  1180. /* This should never be called by a thread holding the lock. */
  1181. STATIC void GC_dyld_image_add(const struct GC_MACH_HEADER *hdr,
  1182. intptr_t slide)
  1183. {
  1184. unsigned long start, end;
  1185. unsigned i, j;
  1186. const struct GC_MACH_SECTION *sec;
  1187. const char *name;
  1188. GC_has_static_roots_func callback = GC_has_static_roots;
  1189. DCL_LOCK_STATE;
  1190. if (GC_no_dls) return;
  1191. # ifdef DARWIN_DEBUG
  1192. name = GC_dyld_name_for_hdr(hdr);
  1193. # else
  1194. name = callback != 0 ? GC_dyld_name_for_hdr(hdr) : NULL;
  1195. # endif
  1196. for (i = 0; i < sizeof(GC_dyld_sections)/sizeof(GC_dyld_sections[0]); i++) {
  1197. sec = GC_GETSECTBYNAME(hdr, GC_dyld_sections[i].seg,
  1198. GC_dyld_sections[i].sect);
  1199. if (sec == NULL || sec->size < sizeof(word))
  1200. continue;
  1201. start = slide + sec->addr;
  1202. end = start + sec->size;
  1203. LOCK();
  1204. /* The user callback is called holding the lock. */
  1205. if (callback == 0 || callback(name, (void*)start, (size_t)sec->size)) {
  1206. # ifdef DARWIN_DEBUG
  1207. GC_log_printf(
  1208. "Adding section __DATA,%s at %p-%p (%lu bytes) from image %s\n",
  1209. GC_dyld_sections[i].sect, (void*)start, (void*)end,
  1210. (unsigned long)sec->size, name);
  1211. # endif
  1212. GC_add_roots_inner((ptr_t)start, (ptr_t)end, FALSE);
  1213. }
  1214. UNLOCK();
  1215. }
  1216. /* Sections constructed on demand. */
  1217. for (j = 0; j < sizeof(GC_dyld_add_sect_fmts) / sizeof(char *); j++) {
  1218. const char *fmt = GC_dyld_add_sect_fmts[j];
  1219. /* Add our manufactured aligned BSS sections. */
  1220. for (i = 0; i <= L2_MAX_OFILE_ALIGNMENT; i++) {
  1221. char secnam[16];
  1222. (void)snprintf(secnam, sizeof(secnam), fmt, (unsigned)i);
  1223. secnam[sizeof(secnam) - 1] = '\0';
  1224. sec = GC_GETSECTBYNAME(hdr, SEG_DATA, secnam);
  1225. if (sec == NULL || sec->size == 0)
  1226. continue;
  1227. start = slide + sec->addr;
  1228. end = start + sec->size;
  1229. # ifdef DARWIN_DEBUG
  1230. GC_log_printf("Adding on-demand section __DATA,%s at"
  1231. " %p-%p (%lu bytes) from image %s\n",
  1232. secnam, (void*)start, (void*)end,
  1233. (unsigned long)sec->size, name);
  1234. # endif
  1235. GC_add_roots((char*)start, (char*)end);
  1236. }
  1237. }
  1238. # if defined(DARWIN_DEBUG) && !defined(NO_DEBUGGING)
  1239. LOCK();
  1240. GC_print_static_roots();
  1241. UNLOCK();
  1242. # endif
  1243. }
  1244. /* This should never be called by a thread holding the lock. */
  1245. STATIC void GC_dyld_image_remove(const struct GC_MACH_HEADER *hdr,
  1246. intptr_t slide)
  1247. {
  1248. unsigned long start, end;
  1249. unsigned i, j;
  1250. const struct GC_MACH_SECTION *sec;
  1251. # if defined(DARWIN_DEBUG) && !defined(NO_DEBUGGING)
  1252. DCL_LOCK_STATE;
  1253. # endif
  1254. for (i = 0; i < sizeof(GC_dyld_sections)/sizeof(GC_dyld_sections[0]); i++) {
  1255. sec = GC_GETSECTBYNAME(hdr, GC_dyld_sections[i].seg,
  1256. GC_dyld_sections[i].sect);
  1257. if (sec == NULL || sec->size == 0)
  1258. continue;
  1259. start = slide + sec->addr;
  1260. end = start + sec->size;
  1261. # ifdef DARWIN_DEBUG
  1262. GC_log_printf(
  1263. "Removing section __DATA,%s at %p-%p (%lu bytes) from image %s\n",
  1264. GC_dyld_sections[i].sect, (void*)start, (void*)end,
  1265. (unsigned long)sec->size, GC_dyld_name_for_hdr(hdr));
  1266. # endif
  1267. GC_remove_roots((char*)start, (char*)end);
  1268. }
  1269. /* Remove our on-demand sections. */
  1270. for (j = 0; j < sizeof(GC_dyld_add_sect_fmts) / sizeof(char *); j++) {
  1271. const char *fmt = GC_dyld_add_sect_fmts[j];
  1272. for (i = 0; i <= L2_MAX_OFILE_ALIGNMENT; i++) {
  1273. char secnam[16];
  1274. (void)snprintf(secnam, sizeof(secnam), fmt, (unsigned)i);
  1275. secnam[sizeof(secnam) - 1] = '\0';
  1276. sec = GC_GETSECTBYNAME(hdr, SEG_DATA, secnam);
  1277. if (sec == NULL || sec->size == 0)
  1278. continue;
  1279. start = slide + sec->addr;
  1280. end = start + sec->size;
  1281. # ifdef DARWIN_DEBUG
  1282. GC_log_printf("Removing on-demand section __DATA,%s at"
  1283. " %p-%p (%lu bytes) from image %s\n", secnam,
  1284. (void*)start, (void*)end, (unsigned long)sec->size,
  1285. GC_dyld_name_for_hdr(hdr));
  1286. # endif
  1287. GC_remove_roots((char*)start, (char*)end);
  1288. }
  1289. }
  1290. # if defined(DARWIN_DEBUG) && !defined(NO_DEBUGGING)
  1291. LOCK();
  1292. GC_print_static_roots();
  1293. UNLOCK();
  1294. # endif
  1295. }
  1296. GC_INNER void GC_register_dynamic_libraries(void)
  1297. {
  1298. /* Currently does nothing. The callbacks are setup by GC_init_dyld()
  1299. The dyld library takes it from there. */
  1300. }
  1301. /* The _dyld_* functions have an internal lock so no _dyld functions
  1302. can be called while the world is stopped without the risk of a deadlock.
  1303. Because of this we MUST setup callbacks BEFORE we ever stop the world.
  1304. This should be called BEFORE any thread in created and WITHOUT the
  1305. allocation lock held. */
  1306. GC_INNER void GC_init_dyld(void)
  1307. {
  1308. static GC_bool initialized = FALSE;
  1309. if (initialized) return;
  1310. # ifdef DARWIN_DEBUG
  1311. GC_log_printf("Registering dyld callbacks...\n");
  1312. # endif
  1313. /* Apple's Documentation:
  1314. When you call _dyld_register_func_for_add_image, the dynamic linker
  1315. runtime calls the specified callback (func) once for each of the images
  1316. that is currently loaded into the program. When a new image is added to
  1317. the program, your callback is called again with the mach_header for the
  1318. new image, and the virtual memory slide amount of the new image.
  1319. This WILL properly register already linked libraries and libraries
  1320. linked in the future.
  1321. */
  1322. _dyld_register_func_for_add_image(
  1323. (void (*)(const struct mach_header*, intptr_t))GC_dyld_image_add);
  1324. _dyld_register_func_for_remove_image(
  1325. (void (*)(const struct mach_header*, intptr_t))GC_dyld_image_remove);
  1326. /* Structure mach_header64 has the same fields */
  1327. /* as mach_header except for the reserved one */
  1328. /* at the end, so these casts are OK. */
  1329. /* Set this early to avoid reentrancy issues. */
  1330. initialized = TRUE;
  1331. # ifdef NO_DYLD_BIND_FULLY_IMAGE
  1332. /* FIXME: What should we do in this case? */
  1333. # else
  1334. if (GC_no_dls) return; /* skip main data segment registration */
  1335. /* When the environment variable is set, the dynamic linker binds */
  1336. /* all undefined symbols the application needs at launch time. */
  1337. /* This includes function symbols that are normally bound lazily at */
  1338. /* the time of their first invocation. */
  1339. if (GETENV("DYLD_BIND_AT_LAUNCH") == 0) {
  1340. /* The environment variable is unset, so we should bind manually. */
  1341. # ifdef DARWIN_DEBUG
  1342. GC_log_printf("Forcing full bind of GC code...\n");
  1343. # endif
  1344. /* FIXME: '_dyld_bind_fully_image_containing_address' is deprecated. */
  1345. if (!_dyld_bind_fully_image_containing_address(
  1346. (unsigned long *)GC_malloc))
  1347. ABORT("_dyld_bind_fully_image_containing_address failed");
  1348. }
  1349. # endif
  1350. }
  1351. #define HAVE_REGISTER_MAIN_STATIC_DATA
  1352. GC_INNER GC_bool GC_register_main_static_data(void)
  1353. {
  1354. /* Already done through dyld callbacks */
  1355. return FALSE;
  1356. }
  1357. #endif /* DARWIN */
  1358. #if defined(HAIKU)
  1359. # include <kernel/image.h>
  1360. GC_INNER void GC_register_dynamic_libraries(void)
  1361. {
  1362. image_info info;
  1363. int32 cookie = 0;
  1364. while (get_next_image_info(0, &cookie, &info) == B_OK) {
  1365. ptr_t data = (ptr_t)info.data;
  1366. GC_add_roots_inner(data, data + info.data_size, TRUE);
  1367. }
  1368. }
  1369. #endif /* HAIKU */
  1370. #elif defined(PCR)
  1371. # include "il/PCR_IL.h"
  1372. # include "th/PCR_ThCtl.h"
  1373. # include "mm/PCR_MM.h"
  1374. GC_INNER void GC_register_dynamic_libraries(void)
  1375. {
  1376. /* Add new static data areas of dynamically loaded modules. */
  1377. PCR_IL_LoadedFile * p = PCR_IL_GetLastLoadedFile();
  1378. PCR_IL_LoadedSegment * q;
  1379. /* Skip uncommitted files */
  1380. while (p != NIL && !(p -> lf_commitPoint)) {
  1381. /* The loading of this file has not yet been committed */
  1382. /* Hence its description could be inconsistent. */
  1383. /* Furthermore, it hasn't yet been run. Hence its data */
  1384. /* segments can't possibly reference heap allocated */
  1385. /* objects. */
  1386. p = p -> lf_prev;
  1387. }
  1388. for (; p != NIL; p = p -> lf_prev) {
  1389. for (q = p -> lf_ls; q != NIL; q = q -> ls_next) {
  1390. if ((q -> ls_flags & PCR_IL_SegFlags_Traced_MASK)
  1391. == PCR_IL_SegFlags_Traced_on) {
  1392. GC_add_roots_inner((ptr_t)q->ls_addr,
  1393. (ptr_t)q->ls_addr + q->ls_bytes, TRUE);
  1394. }
  1395. }
  1396. }
  1397. }
  1398. #endif /* PCR && !DYNAMIC_LOADING && !MSWIN32 */
  1399. #if !defined(HAVE_REGISTER_MAIN_STATIC_DATA) && defined(DYNAMIC_LOADING)
  1400. /* Do we need to separately register the main static data segment? */
  1401. GC_INNER GC_bool GC_register_main_static_data(void)
  1402. {
  1403. return TRUE;
  1404. }
  1405. #endif /* HAVE_REGISTER_MAIN_STATIC_DATA */
  1406. /* Register a routine to filter dynamic library registration. */
  1407. GC_API void GC_CALL GC_register_has_static_roots_callback(
  1408. GC_has_static_roots_func callback)
  1409. {
  1410. GC_has_static_roots = callback;
  1411. }