Update.
[platform/upstream/glibc.git] / elf / dl-open.c
1 /* Load a shared object at runtime, relocate it, and run its initializer.
2    Copyright (C) 1996-2001, 2002, 2003, 2004 Free Software Foundation, Inc.
3    This file is part of the GNU C Library.
4
5    The GNU C Library is free software; you can redistribute it and/or
6    modify it under the terms of the GNU Lesser General Public
7    License as published by the Free Software Foundation; either
8    version 2.1 of the License, or (at your option) any later version.
9
10    The GNU C Library is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    Lesser General Public License for more details.
14
15    You should have received a copy of the GNU Lesser General Public
16    License along with the GNU C Library; if not, write to the Free
17    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
18    02111-1307 USA.  */
19
20 #include <assert.h>
21 #include <dlfcn.h>
22 #include <errno.h>
23 #include <libintl.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <unistd.h>
28 #include <sys/mman.h>           /* Check whether MAP_COPY is defined.  */
29 #include <sys/param.h>
30 #include <bits/libc-lock.h>
31 #include <ldsodefs.h>
32 #include <bp-sym.h>
33 #include <gnu/lib-names.h>
34
35 #include <dl-dst.h>
36
37
38 #ifndef SHARED
39 /* Giving this initialized value preallocates some surplus bytes in the
40    static TLS area, see __libc_setup_tls (libc-tls.c).  */
41 size_t _dl_tls_static_size = 2048;
42 #endif
43
44 extern ElfW(Addr) _dl_sysdep_start (void **start_argptr,
45                                     void (*dl_main) (const ElfW(Phdr) *phdr,
46                                                      ElfW(Word) phnum,
47                                                      ElfW(Addr) *user_entry));
48 weak_extern (BP_SYM (_dl_sysdep_start))
49
50 extern int __libc_multiple_libcs;       /* Defined in init-first.c.  */
51
52 extern int __libc_argc attribute_hidden;
53 extern char **__libc_argv attribute_hidden;
54
55 extern char **__environ;
56
57 /* Undefine the following for debugging.  */
58 /* #define SCOPE_DEBUG 1 */
59 #ifdef SCOPE_DEBUG
60 static void show_scope (struct link_map *new);
61 #endif
62
63 /* We must be carefull not to leave us in an inconsistent state.  Thus we
64    catch any error and re-raise it after cleaning up.  */
65
66 struct dl_open_args
67 {
68   const char *file;
69   int mode;
70   /* This is the caller of the dlopen() function.  */
71   const void *caller_dlopen;
72   /* This is the caller if _dl_open().  */
73   const void *caller_dl_open;
74   struct link_map *map;
75 };
76
77
78 static int
79 add_to_global (struct link_map *new)
80 {
81   struct link_map **new_global;
82   unsigned int to_add = 0;
83   unsigned int cnt;
84
85   /* Count the objects we have to put in the global scope.  */
86   for (cnt = 0; cnt < new->l_searchlist.r_nlist; ++cnt)
87     if (new->l_searchlist.r_list[cnt]->l_global == 0)
88       ++to_add;
89
90   /* The symbols of the new objects and its dependencies are to be
91      introduced into the global scope that will be used to resolve
92      references from other dynamically-loaded objects.
93
94      The global scope is the searchlist in the main link map.  We
95      extend this list if necessary.  There is one problem though:
96      since this structure was allocated very early (before the libc
97      is loaded) the memory it uses is allocated by the malloc()-stub
98      in the ld.so.  When we come here these functions are not used
99      anymore.  Instead the malloc() implementation of the libc is
100      used.  But this means the block from the main map cannot be used
101      in an realloc() call.  Therefore we allocate a completely new
102      array the first time we have to add something to the locale scope.  */
103
104   if (GL(dl_global_scope_alloc) == 0)
105     {
106       /* This is the first dynamic object given global scope.  */
107       GL(dl_global_scope_alloc) = GL(dl_main_searchlist)->r_nlist + to_add + 8;
108       new_global = (struct link_map **)
109         malloc (GL(dl_global_scope_alloc) * sizeof (struct link_map *));
110       if (new_global == NULL)
111         {
112           GL(dl_global_scope_alloc) = 0;
113         nomem:
114           _dl_signal_error (ENOMEM, new->l_libname->name, NULL,
115                             N_("cannot extend global scope"));
116           return 1;
117         }
118
119       /* Copy over the old entries.  */
120       memcpy (new_global, GL(dl_main_searchlist)->r_list,
121               (GL(dl_main_searchlist)->r_nlist * sizeof (struct link_map *)));
122
123       GL(dl_main_searchlist)->r_list = new_global;
124     }
125   else if (GL(dl_main_searchlist)->r_nlist + to_add
126            > GL(dl_global_scope_alloc))
127     {
128       /* We have to extend the existing array of link maps in the
129          main map.  */
130       new_global = (struct link_map **)
131         realloc (GL(dl_main_searchlist)->r_list,
132                  ((GL(dl_global_scope_alloc) + to_add + 8)
133                   * sizeof (struct link_map *)));
134       if (new_global == NULL)
135         goto nomem;
136
137       GL(dl_global_scope_alloc) += to_add + 8;
138       GL(dl_main_searchlist)->r_list = new_global;
139     }
140
141   /* Now add the new entries.  */
142   for (cnt = 0; cnt < new->l_searchlist.r_nlist; ++cnt)
143     {
144       struct link_map *map = new->l_searchlist.r_list[cnt];
145
146       if (map->l_global == 0)
147         {
148           map->l_global = 1;
149           GL(dl_main_searchlist)->r_list[GL(dl_main_searchlist)->r_nlist]
150             = map;
151           ++GL(dl_main_searchlist)->r_nlist;
152         }
153     }
154
155   return 0;
156 }
157
158
159 #ifdef SHARED
160 static int
161 internal_function
162 check_libc_caller (const void *caller)
163 {
164   static const char expected1[] = LIBC_SO;
165   static const char expected2[] = LIBDL_SO;
166
167   /* If we already know the address ranges, just test.  */
168   static const void *expected1_from;
169   static const void *expected1_to;
170   static const void *expected2_from;
171   static const void *expected2_to;
172
173   if (expected1_from == NULL)
174     {
175       /* The only other DSO which is allowed to call these functions is
176          libdl.  Find the address range containing the caller.  */
177       struct link_map *l;
178
179       for (l = GL(dl_loaded); l != NULL; l = l->l_next)
180         if (_dl_name_match_p (expected1, l))
181           {
182             expected1_from = (const void *) l->l_map_start;
183             expected1_to = (const void *) l->l_map_end;
184           }
185         else if (_dl_name_match_p (expected2, l))
186           {
187             expected2_from = (const void *) l->l_map_start;
188             expected2_to = (const void *) l->l_map_end;
189           }
190
191       assert (expected1_from != NULL);
192     }
193
194   /* When there would be more than two expected caller we could use an
195      array for the values but for now this is cheaper.  */
196   if ((caller >= expected1_from && caller < expected1_to)
197       || (caller >= expected2_from && caller < expected2_to))
198     return 0;
199
200   return 1;
201 }
202 #endif
203
204
205 static void
206 dl_open_worker (void *a)
207 {
208   struct dl_open_args *args = a;
209   const char *file = args->file;
210   int mode = args->mode;
211   struct link_map *new, *l;
212   const char *dst;
213   int lazy;
214   unsigned int i;
215 #ifdef USE_TLS
216   bool any_tls;
217 #endif
218
219 #ifdef SHARED
220   /* Check whether _dl_open() has been called from a valid DSO.  */
221   if (check_libc_caller (args->caller_dl_open) != 0)
222     _dl_signal_error (0, "dlopen", NULL, N_("invalid caller"));
223 #endif
224
225   /* Maybe we have to expand a DST.  */
226   dst = strchr (file, '$');
227   if (__builtin_expect (dst != NULL, 0))
228     {
229       const void *caller_dlopen = args->caller_dlopen;
230       size_t len = strlen (file);
231       size_t required;
232       struct link_map *call_map;
233       char *new_file;
234
235       /* DSTs must not appear in SUID/SGID programs.  */
236       if (__libc_enable_secure)
237         /* This is an error.  */
238         _dl_signal_error (0, "dlopen", NULL,
239                           N_("DST not allowed in SUID/SGID programs"));
240
241       /* We have to find out from which object the caller is calling.  */
242       call_map = NULL;
243       for (l = GL(dl_loaded); l; l = l->l_next)
244         if (caller_dlopen >= (const void *) l->l_map_start
245             && caller_dlopen < (const void *) l->l_map_end)
246           {
247             /* There must be exactly one DSO for the range of the virtual
248                memory.  Otherwise something is really broken.  */
249             call_map = l;
250             break;
251           }
252
253       if (call_map == NULL)
254         /* In this case we assume this is the main application.  */
255         call_map = GL(dl_loaded);
256
257       /* Determine how much space we need.  We have to allocate the
258          memory locally.  */
259       required = DL_DST_REQUIRED (call_map, file, len, _dl_dst_count (dst, 0));
260
261       /* Get space for the new file name.  */
262       new_file = (char *) alloca (required + 1);
263
264       /* Generate the new file name.  */
265       _dl_dst_substitute (call_map, file, new_file, 0);
266
267       /* If the substitution failed don't try to load.  */
268       if (*new_file == '\0')
269         _dl_signal_error (0, "dlopen", NULL,
270                           N_("empty dynamic string token substitution"));
271
272       /* Now we have a new file name.  */
273       file = new_file;
274     }
275
276   /* Load the named object.  */
277   args->map = new = _dl_map_object (NULL, file, 0, lt_loaded, 0, mode);
278
279   /* If the pointer returned is NULL this means the RTLD_NOLOAD flag is
280      set and the object is not already loaded.  */
281   if (new == NULL)
282     {
283       assert (mode & RTLD_NOLOAD);
284       return;
285     }
286
287   if (__builtin_expect (mode & __RTLD_SPROF, 0))
288     /* This happens only if we load a DSO for 'sprof'.  */
289     return;
290
291   /* It was already open.  */
292   if (new->l_searchlist.r_list != NULL)
293     {
294       /* Let the user know about the opencount.  */
295       if (__builtin_expect (GL(dl_debug_mask) & DL_DEBUG_FILES, 0))
296         _dl_debug_printf ("opening file=%s; opencount == %u\n\n",
297                           new->l_name, new->l_opencount);
298
299       /* If the user requested the object to be in the global namespace
300          but it is not so far, add it now.  */
301       if ((mode & RTLD_GLOBAL) && new->l_global == 0)
302         (void) add_to_global (new);
303
304       /* Increment just the reference counter of the object.  */
305       ++new->l_opencount;
306
307       return;
308     }
309
310   /* Load that object's dependencies.  */
311   _dl_map_object_deps (new, NULL, 0, 0, mode & __RTLD_DLOPEN);
312
313   /* So far, so good.  Now check the versions.  */
314   for (i = 0; i < new->l_searchlist.r_nlist; ++i)
315     if (new->l_searchlist.r_list[i]->l_versions == NULL)
316       (void) _dl_check_map_versions (new->l_searchlist.r_list[i], 0, 0);
317
318 #ifdef SCOPE_DEBUG
319   show_scope (new);
320 #endif
321
322   /* Only do lazy relocation if `LD_BIND_NOW' is not set.  */
323   lazy = (mode & RTLD_BINDING_MASK) == RTLD_LAZY && GL(dl_lazy);
324
325   /* Relocate the objects loaded.  We do this in reverse order so that copy
326      relocs of earlier objects overwrite the data written by later objects.  */
327
328   l = new;
329   while (l->l_next)
330     l = l->l_next;
331   while (1)
332     {
333       if (! l->l_relocated)
334         {
335 #ifdef SHARED
336           if (GL(dl_profile) != NULL)
337             {
338               /* If this here is the shared object which we want to profile
339                  make sure the profile is started.  We can find out whether
340                  this is necessary or not by observing the `_dl_profile_map'
341                  variable.  If was NULL but is not NULL afterwars we must
342                  start the profiling.  */
343               struct link_map *old_profile_map = GL(dl_profile_map);
344
345               _dl_relocate_object (l, l->l_scope, 1, 1);
346
347               if (old_profile_map == NULL && GL(dl_profile_map) != NULL)
348                 /* We must prepare the profiling.  */
349                 _dl_start_profile (GL(dl_profile_map), GL(dl_profile_output));
350             }
351           else
352 #endif
353             _dl_relocate_object (l, l->l_scope, lazy, 0);
354         }
355
356       if (l == new)
357         break;
358       l = l->l_prev;
359     }
360
361 #ifdef USE_TLS
362   /* Do static TLS initialization now if it has been delayed because
363      the TLS template might not be fully relocated at _dl_allocate_static_tls
364      time.  */
365   for (l = new; l; l = l->l_next)
366     if (l->l_need_tls_init)
367       {
368         l->l_need_tls_init = 0;
369         GL(dl_init_static_tls) (l);
370       }
371
372   /* We normally don't bump the TLS generation counter.  There must be
373      actually a need to do this.  */
374   any_tls = false;
375 #endif
376
377   /* Increment the open count for all dependencies.  If the file is
378      not loaded as a dependency here add the search list of the newly
379      loaded object to the scope.  */
380   for (i = 0; i < new->l_searchlist.r_nlist; ++i)
381     if (++new->l_searchlist.r_list[i]->l_opencount > 1
382         && new->l_searchlist.r_list[i]->l_type == lt_loaded)
383       {
384         struct link_map *imap = new->l_searchlist.r_list[i];
385         struct r_scope_elem **runp = imap->l_scope;
386         size_t cnt = 0;
387
388         while (*runp != NULL)
389           {
390             /* This can happen if imap was just loaded, but during
391                relocation had l_opencount bumped because of relocation
392                dependency.  Avoid duplicates in l_scope.  */
393             if (__builtin_expect (*runp == &new->l_searchlist, 0))
394               break;
395
396             ++cnt;
397             ++runp;
398           }
399
400         if (*runp != NULL)
401           /* Avoid duplicates.  */
402           continue;
403
404         if (__builtin_expect (cnt + 1 >= imap->l_scope_max, 0))
405           {
406             /* The 'r_scope' array is too small.  Allocate a new one
407                dynamically.  */
408             struct r_scope_elem **newp;
409             size_t new_size = imap->l_scope_max * 2;
410
411             if (imap->l_scope == imap->l_scope_mem)
412               {
413                 newp = (struct r_scope_elem **)
414                   malloc (new_size * sizeof (struct r_scope_elem *));
415                 if (newp == NULL)
416                   _dl_signal_error (ENOMEM, "dlopen", NULL,
417                                     N_("cannot create scope list"));
418                 imap->l_scope = memcpy (newp, imap->l_scope,
419                                         cnt * sizeof (imap->l_scope[0]));
420               }
421             else
422               {
423                 newp = (struct r_scope_elem **)
424                   realloc (imap->l_scope,
425                            new_size * sizeof (struct r_scope_elem *));
426                 if (newp == NULL)
427                   _dl_signal_error (ENOMEM, "dlopen", NULL,
428                                     N_("cannot create scope list"));
429                 imap->l_scope = newp;
430               }
431
432             imap->l_scope_max = new_size;
433           }
434
435         imap->l_scope[cnt++] = &new->l_searchlist;
436         imap->l_scope[cnt] = NULL;
437       }
438 #if USE_TLS
439     else if (new->l_searchlist.r_list[i]->l_opencount == 1
440              /* Only if the module defines thread local data.  */
441              && __builtin_expect (new->l_searchlist.r_list[i]->l_tls_blocksize
442                                   > 0, 0))
443       {
444         /* Now that we know the object is loaded successfully add
445            modules containing TLS data to the dtv info table.  We
446            might have to increase its size.  */
447         struct dtv_slotinfo_list *listp;
448         struct dtv_slotinfo_list *prevp;
449         size_t idx = new->l_searchlist.r_list[i]->l_tls_modid;
450
451         assert (new->l_searchlist.r_list[i]->l_type == lt_loaded);
452
453         /* Find the place in the dtv slotinfo list.  */
454         listp = GL(dl_tls_dtv_slotinfo_list);
455         prevp = NULL;           /* Needed to shut up gcc.  */
456         do
457           {
458             /* Does it fit in the array of this list element?  */
459             if (idx < listp->len)
460               break;
461             idx -= listp->len;
462             prevp = listp;
463             listp = listp->next;
464           }
465         while (listp != NULL);
466
467         if (listp == NULL)
468           {
469             /* When we come here it means we have to add a new element
470                to the slotinfo list.  And the new module must be in
471                the first slot.  */
472             assert (idx == 0);
473
474             listp = prevp->next = (struct dtv_slotinfo_list *)
475               malloc (sizeof (struct dtv_slotinfo_list)
476                       + TLS_SLOTINFO_SURPLUS * sizeof (struct dtv_slotinfo));
477             if (listp == NULL)
478               {
479                 /* We ran out of memory.  We will simply fail this
480                    call but don't undo anything we did so far.  The
481                    application will crash or be terminated anyway very
482                    soon.  */
483
484                 /* We have to do this since some entries in the dtv
485                    slotinfo array might already point to this
486                    generation.  */
487                 ++GL(dl_tls_generation);
488
489                 _dl_signal_error (ENOMEM, "dlopen", NULL,
490                                   N_("cannot create TLS data structures"));
491               }
492
493             listp->len = TLS_SLOTINFO_SURPLUS;
494             listp->next = NULL;
495             memset (listp->slotinfo, '\0',
496                     TLS_SLOTINFO_SURPLUS * sizeof (struct dtv_slotinfo));
497           }
498
499         /* Add the information into the slotinfo data structure.  */
500         listp->slotinfo[idx].map = new->l_searchlist.r_list[i];
501         listp->slotinfo[idx].gen = GL(dl_tls_generation) + 1;
502
503         /* We have to bump the generation counter.  */
504         any_tls = true;
505       }
506
507   /* Bump the generation number if necessary.  */
508   if (any_tls)
509     if (__builtin_expect (++GL(dl_tls_generation) == 0, 0))
510       __libc_fatal (_("TLS generation counter wrapped!  Please send report with the 'glibcbug' script."));
511 #endif
512
513   /* Run the initializer functions of new objects.  */
514   _dl_init (new, __libc_argc, __libc_argv, __environ);
515
516   /* Now we can make the new map available in the global scope.  */
517   if (mode & RTLD_GLOBAL)
518     /* Move the object in the global namespace.  */
519     if (add_to_global (new) != 0)
520       /* It failed.  */
521       return;
522
523   /* Mark the object as not deletable if the RTLD_NODELETE flags was
524      passed.  */
525   if (__builtin_expect (mode & RTLD_NODELETE, 0))
526     new->l_flags_1 |= DF_1_NODELETE;
527
528 #ifndef SHARED
529   /* We must be the static _dl_open in libc.a.  A static program that
530      has loaded a dynamic object now has competition.  */
531   __libc_multiple_libcs = 1;
532 #endif
533
534   /* Let the user know about the opencount.  */
535   if (__builtin_expect (GL(dl_debug_mask) & DL_DEBUG_FILES, 0))
536     _dl_debug_printf ("opening file=%s; opencount == %u\n\n",
537                       new->l_name, new->l_opencount);
538 }
539
540
541 void *
542 internal_function
543 _dl_open (const char *file, int mode, const void *caller_dlopen)
544 {
545   struct dl_open_args args;
546   const char *objname;
547   const char *errstring;
548   int errcode;
549
550   if ((mode & RTLD_BINDING_MASK) == 0)
551     /* One of the flags must be set.  */
552     _dl_signal_error (EINVAL, file, NULL, N_("invalid mode for dlopen()"));
553
554   /* Make sure we are alone.  */
555   __rtld_lock_lock_recursive (GL(dl_load_lock));
556
557   args.file = file;
558   args.mode = mode;
559   args.caller_dlopen = caller_dlopen;
560   args.caller_dl_open = RETURN_ADDRESS (0);
561   args.map = NULL;
562   errcode = _dl_catch_error (&objname, &errstring, dl_open_worker, &args);
563
564 #ifndef MAP_COPY
565   /* We must munmap() the cache file.  */
566   _dl_unload_cache ();
567 #endif
568
569   /* Release the lock.  */
570   __rtld_lock_unlock_recursive (GL(dl_load_lock));
571
572   if (__builtin_expect (errstring != NULL, 0))
573     {
574       /* Some error occurred during loading.  */
575       char *local_errstring;
576       size_t len_errstring;
577
578       /* Remove the object from memory.  It may be in an inconsistent
579          state if relocation failed, for example.  */
580       if (args.map)
581         {
582           unsigned int i;
583
584           /* Increment open counters for all objects since this
585              sometimes has not happened yet.  */
586           if (args.map->l_searchlist.r_list[0]->l_opencount == 0)
587             for (i = 0; i < args.map->l_searchlist.r_nlist; ++i)
588               ++args.map->l_searchlist.r_list[i]->l_opencount;
589
590 #ifdef USE_TLS
591           /* Maybe some of the modules which were loaded uses TLS.
592              Since it will be removed in the following _dl_close call
593              we have to mark the dtv array as having gaps to fill
594              the holes.  This is a pessimistic assumption which won't
595              hurt if not true.  */
596           GL(dl_tls_dtv_gaps) = true;
597 #endif
598
599           _dl_close (args.map);
600         }
601
602       /* Make a local copy of the error string so that we can release the
603          memory allocated for it.  */
604       len_errstring = strlen (errstring) + 1;
605       if (objname == errstring + len_errstring)
606         {
607           size_t total_len = len_errstring + strlen (objname) + 1;
608           local_errstring = alloca (total_len);
609           memcpy (local_errstring, errstring, total_len);
610           objname = local_errstring + len_errstring;
611         }
612       else
613         {
614           local_errstring = alloca (len_errstring);
615           memcpy (local_errstring, errstring, len_errstring);
616         }
617
618       if (errstring != _dl_out_of_memory)
619         free ((char *) errstring);
620
621       /* Reraise the error.  */
622       _dl_signal_error (errcode, objname, NULL, local_errstring);
623     }
624
625 #ifndef SHARED
626   DL_STATIC_INIT (args.map);
627 #endif
628
629   return args.map;
630 }
631 libc_hidden_def (_dl_open)
632
633
634 #ifdef SCOPE_DEBUG
635 #include <unistd.h>
636
637 static void
638 show_scope (struct link_map *new)
639 {
640   int scope_cnt;
641
642   for (scope_cnt = 0; new->l_scope[scope_cnt] != NULL; ++scope_cnt)
643     {
644       char numbuf[2];
645       unsigned int cnt;
646
647       numbuf[0] = '0' + scope_cnt;
648       numbuf[1] = '\0';
649       _dl_printf ("scope %s:", numbuf);
650
651       for (cnt = 0; cnt < new->l_scope[scope_cnt]->r_nlist; ++cnt)
652         if (*new->l_scope[scope_cnt]->r_list[cnt]->l_name)
653           _dl_printf (" %s", new->l_scope[scope_cnt]->r_list[cnt]->l_name);
654         else
655           _dl_printf (" <main>");
656
657       _dl_printf ("\n");
658     }
659 }
660 #endif