* elf/dl-open.c (add_to_global): Introduce variable ns to help gcc
[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-2004, 2005, 2006, 2007 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 <caller.h>
34 #include <sysdep-cancel.h>
35
36 #include <dl-dst.h>
37
38
39 extern ElfW(Addr) _dl_sysdep_start (void **start_argptr,
40                                     void (*dl_main) (const ElfW(Phdr) *phdr,
41                                                      ElfW(Word) phnum,
42                                                      ElfW(Addr) *user_entry));
43 weak_extern (BP_SYM (_dl_sysdep_start))
44
45 extern int __libc_multiple_libcs;       /* Defined in init-first.c.  */
46
47 /* Undefine the following for debugging.  */
48 /* #define SCOPE_DEBUG 1 */
49 #ifdef SCOPE_DEBUG
50 static void show_scope (struct link_map *new);
51 #endif
52
53 /* We must be carefull not to leave us in an inconsistent state.  Thus we
54    catch any error and re-raise it after cleaning up.  */
55
56 struct dl_open_args
57 {
58   const char *file;
59   int mode;
60   /* This is the caller of the dlopen() function.  */
61   const void *caller_dlopen;
62   /* This is the caller if _dl_open().  */
63   const void *caller_dl_open;
64   struct link_map *map;
65   /* Namespace ID.  */
66   Lmid_t nsid;
67   /* Original parameters to the program and the current environment.  */
68   int argc;
69   char **argv;
70   char **env;
71 };
72
73
74 static int
75 add_to_global (struct link_map *new)
76 {
77   struct link_map **new_global;
78   unsigned int to_add = 0;
79   unsigned int cnt;
80
81   /* Count the objects we have to put in the global scope.  */
82   for (cnt = 0; cnt < new->l_searchlist.r_nlist; ++cnt)
83     if (new->l_searchlist.r_list[cnt]->l_global == 0)
84       ++to_add;
85
86   /* The symbols of the new objects and its dependencies are to be
87      introduced into the global scope that will be used to resolve
88      references from other dynamically-loaded objects.
89
90      The global scope is the searchlist in the main link map.  We
91      extend this list if necessary.  There is one problem though:
92      since this structure was allocated very early (before the libc
93      is loaded) the memory it uses is allocated by the malloc()-stub
94      in the ld.so.  When we come here these functions are not used
95      anymore.  Instead the malloc() implementation of the libc is
96      used.  But this means the block from the main map cannot be used
97      in an realloc() call.  Therefore we allocate a completely new
98      array the first time we have to add something to the locale scope.  */
99
100   struct link_namespaces *ns = &GL(dl_ns)[new->l_ns];
101   if (ns->_ns_global_scope_alloc == 0)
102     {
103       /* This is the first dynamic object given global scope.  */
104       ns->_ns_global_scope_alloc
105         = ns->_ns_main_searchlist->r_nlist + to_add + 8;
106       new_global = (struct link_map **)
107         malloc (ns->_ns_global_scope_alloc * sizeof (struct link_map *));
108       if (new_global == NULL)
109         {
110           ns->_ns_global_scope_alloc = 0;
111         nomem:
112           _dl_signal_error (ENOMEM, new->l_libname->name, NULL,
113                             N_("cannot extend global scope"));
114           return 1;
115         }
116
117       /* Copy over the old entries.  */
118       ns->_ns_main_searchlist->r_list
119         = memcpy (new_global, ns->_ns_main_searchlist->r_list,
120                   (ns->_ns_main_searchlist->r_nlist
121                    * sizeof (struct link_map *)));
122     }
123   else if (ns->_ns_main_searchlist->r_nlist + to_add
124            > ns->_ns_global_scope_alloc)
125     {
126       /* We have to extend the existing array of link maps in the
127          main map.  */
128       new_global = (struct link_map **)
129         realloc (ns->_ns_main_searchlist->r_list,
130                  ((ns->_ns_global_scope_alloc + to_add + 8)
131                   * sizeof (struct link_map *)));
132       if (new_global == NULL)
133         goto nomem;
134
135       ns->_ns_global_scope_alloc += to_add + 8;
136       ns->_ns_main_searchlist->r_list = new_global;
137     }
138
139   /* Now add the new entries.  */
140   unsigned int added = 0;
141   for (cnt = 0; cnt < new->l_searchlist.r_nlist; ++cnt)
142     {
143       struct link_map *map = new->l_searchlist.r_list[cnt];
144
145       if (map->l_global == 0)
146         {
147           map->l_global = 1;
148           ns->_ns_main_searchlist->r_list[ns->_ns_main_searchlist->r_nlist
149                                           + added]
150             = map;
151           ++added;
152         }
153     }
154   atomic_write_barrier ();
155   ns->_ns_main_searchlist->r_nlist += added;
156
157   return 0;
158 }
159
160
161 static void
162 dl_open_worker (void *a)
163 {
164   struct dl_open_args *args = a;
165   const char *file = args->file;
166   int mode = args->mode;
167   struct link_map *new;
168   int lazy;
169   unsigned int i;
170   bool any_tls = false;
171   struct link_map *call_map = NULL;
172
173   /* Check whether _dl_open() has been called from a valid DSO.  */
174   if (__check_caller (args->caller_dl_open,
175                       allow_libc|allow_libdl|allow_ldso) != 0)
176     _dl_signal_error (0, "dlopen", NULL, N_("invalid caller"));
177
178   /* Determine the caller's map if necessary.  This is needed in case
179      we have a DST, when we don't know the namespace ID we have to put
180      the new object in, or when the file name has no path in which
181      case we need to look along the RUNPATH/RPATH of the caller.  */
182   const char *dst = strchr (file, '$');
183   if (dst != NULL || args->nsid == __LM_ID_CALLER
184       || strchr (file, '/') == NULL)
185     {
186       const void *caller_dlopen = args->caller_dlopen;
187
188       /* We have to find out from which object the caller is calling.
189          By default we assume this is the main application.  */
190       call_map = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
191
192       struct link_map *l;
193       for (Lmid_t ns = 0; ns < DL_NNS; ++ns)
194         for (l = GL(dl_ns)[ns]._ns_loaded; l != NULL; l = l->l_next)
195           if (caller_dlopen >= (const void *) l->l_map_start
196               && caller_dlopen < (const void *) l->l_map_end)
197             {
198               /* There must be exactly one DSO for the range of the virtual
199                  memory.  Otherwise something is really broken.  */
200               assert (ns == l->l_ns);
201               call_map = l;
202               goto found_caller;
203             }
204
205     found_caller:
206       if (args->nsid == __LM_ID_CALLER)
207         {
208 #ifndef SHARED
209           /* In statically linked apps there might be no loaded object.  */
210           if (call_map == NULL)
211             args->nsid = LM_ID_BASE;
212           else
213 #endif
214             args->nsid = call_map->l_ns;
215         }
216     }
217
218   assert (_dl_debug_initialize (0, args->nsid)->r_state == RT_CONSISTENT);
219
220   /* Maybe we have to expand a DST.  */
221   if (__builtin_expect (dst != NULL, 0))
222     {
223       size_t len = strlen (file);
224       size_t required;
225       char *new_file;
226
227       /* Determine how much space we need.  We have to allocate the
228          memory locally.  */
229       required = DL_DST_REQUIRED (call_map, file, len, _dl_dst_count (dst, 0));
230
231       /* Get space for the new file name.  */
232       new_file = (char *) alloca (required + 1);
233
234       /* Generate the new file name.  */
235       _dl_dst_substitute (call_map, file, new_file, 0);
236
237       /* If the substitution failed don't try to load.  */
238       if (*new_file == '\0')
239         _dl_signal_error (0, "dlopen", NULL,
240                           N_("empty dynamic string token substitution"));
241
242       /* Now we have a new file name.  */
243       file = new_file;
244
245       /* It does not matter whether call_map is set even if we
246          computed it only because of the DST.  Since the path contains
247          a slash the value is not used.  See dl-load.c.  */
248     }
249
250   /* Load the named object.  */
251   args->map = new = _dl_map_object (call_map, file, 0, lt_loaded, 0,
252                                     mode | __RTLD_CALLMAP, args->nsid);
253
254   /* If the pointer returned is NULL this means the RTLD_NOLOAD flag is
255      set and the object is not already loaded.  */
256   if (new == NULL)
257     {
258       assert (mode & RTLD_NOLOAD);
259       return;
260     }
261
262   if (__builtin_expect (mode & __RTLD_SPROF, 0))
263     /* This happens only if we load a DSO for 'sprof'.  */
264     return;
265
266   /* This object is directly loaded.  */
267   ++new->l_direct_opencount;
268
269   /* It was already open.  */
270   if (__builtin_expect (new->l_searchlist.r_list != NULL, 0))
271     {
272       /* Let the user know about the opencount.  */
273       if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_FILES, 0))
274         _dl_debug_printf ("opening file=%s [%lu]; direct_opencount=%u\n\n",
275                           new->l_name, new->l_ns, new->l_direct_opencount);
276
277       /* If the user requested the object to be in the global namespace
278          but it is not so far, add it now.  */
279       if ((mode & RTLD_GLOBAL) && new->l_global == 0)
280         (void) add_to_global (new);
281
282       assert (_dl_debug_initialize (0, args->nsid)->r_state == RT_CONSISTENT);
283
284       return;
285     }
286
287   /* Load that object's dependencies.  */
288   _dl_map_object_deps (new, NULL, 0, 0,
289                        mode & (__RTLD_DLOPEN | RTLD_DEEPBIND | __RTLD_AUDIT));
290
291   /* So far, so good.  Now check the versions.  */
292   for (i = 0; i < new->l_searchlist.r_nlist; ++i)
293     if (new->l_searchlist.r_list[i]->l_real->l_versions == NULL)
294       (void) _dl_check_map_versions (new->l_searchlist.r_list[i]->l_real,
295                                      0, 0);
296
297 #ifdef SCOPE_DEBUG
298   show_scope (new);
299 #endif
300
301 #ifdef SHARED
302   /* Auditing checkpoint: we have added all objects.  */
303   if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
304     {
305       struct link_map *head = GL(dl_ns)[new->l_ns]._ns_loaded;
306       /* Do not call the functions for any auditing object.  */
307       if (head->l_auditing == 0)
308         {
309           struct audit_ifaces *afct = GLRO(dl_audit);
310           for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
311             {
312               if (afct->activity != NULL)
313                 afct->activity (&head->l_audit[cnt].cookie, LA_ACT_CONSISTENT);
314
315               afct = afct->next;
316             }
317         }
318     }
319 #endif
320
321   /* Notify the debugger all new objects are now ready to go.  */
322   struct r_debug *r = _dl_debug_initialize (0, args->nsid);
323   r->r_state = RT_CONSISTENT;
324   _dl_debug_state ();
325
326   /* Only do lazy relocation if `LD_BIND_NOW' is not set.  */
327   lazy = (mode & RTLD_BINDING_MASK) == RTLD_LAZY && GLRO(dl_lazy);
328
329   /* Relocate the objects loaded.  We do this in reverse order so that copy
330      relocs of earlier objects overwrite the data written by later objects.  */
331
332   struct link_map *l = new;
333   while (l->l_next)
334     l = l->l_next;
335   while (1)
336     {
337       if (! l->l_real->l_relocated)
338         {
339 #ifdef SHARED
340           if (__builtin_expect (GLRO(dl_profile) != NULL, 0))
341             {
342               /* If this here is the shared object which we want to profile
343                  make sure the profile is started.  We can find out whether
344                  this is necessary or not by observing the `_dl_profile_map'
345                  variable.  If was NULL but is not NULL afterwars we must
346                  start the profiling.  */
347               struct link_map *old_profile_map = GL(dl_profile_map);
348
349               _dl_relocate_object (l, l->l_scope, 1, 1);
350
351               if (old_profile_map == NULL && GL(dl_profile_map) != NULL)
352                 {
353                   /* We must prepare the profiling.  */
354                   _dl_start_profile ();
355
356                   /* Prevent unloading the object.  */
357                   GL(dl_profile_map)->l_flags_1 |= DF_1_NODELETE;
358                 }
359             }
360           else
361 #endif
362             _dl_relocate_object (l, l->l_scope, lazy, 0);
363         }
364
365       if (l == new)
366         break;
367       l = l->l_prev;
368     }
369
370   /* If the file is not loaded now as a dependency, add the search
371      list of the newly loaded object to the scope.  */
372   for (i = 0; i < new->l_searchlist.r_nlist; ++i)
373     {
374       struct link_map *imap = new->l_searchlist.r_list[i];
375
376       /* If the initializer has been called already, the object has
377          not been loaded here and now.  */
378       if (imap->l_init_called && imap->l_type == lt_loaded)
379         {
380           struct r_scope_elem **runp = imap->l_scope;
381           size_t cnt = 0;
382
383           while (*runp != NULL)
384             {
385               if (*runp == &new->l_searchlist)
386                 break;
387               ++cnt;
388               ++runp;
389             }
390
391           if (*runp != NULL)
392             /* Avoid duplicates.  */
393             continue;
394
395           if (__builtin_expect (cnt + 1 >= imap->l_scope_max, 0))
396             {
397               /* The 'r_scope' array is too small.  Allocate a new one
398                  dynamically.  */
399               size_t new_size;
400               struct r_scope_elem **newp;
401
402 #define SCOPE_ELEMS(imap) \
403   (sizeof (imap->l_scope_mem) / sizeof (imap->l_scope_mem[0]))
404
405               if (imap->l_scope != imap->l_scope_mem
406                   && imap->l_scope_max < SCOPE_ELEMS (imap))
407                 {
408                   new_size = SCOPE_ELEMS (imap);
409                   newp = imap->l_scope_mem;
410                 }
411               else
412                 {
413                   new_size = imap->l_scope_max * 2;
414                   newp = (struct r_scope_elem **)
415                     malloc (new_size * sizeof (struct r_scope_elem *));
416                   if (newp == NULL)
417                     _dl_signal_error (ENOMEM, "dlopen", NULL,
418                                       N_("cannot create scope list"));
419                 }
420
421               memcpy (newp, imap->l_scope, cnt * sizeof (imap->l_scope[0]));
422               struct r_scope_elem **old = imap->l_scope;
423
424               if (RTLD_SINGLE_THREAD_P)
425                 imap->l_scope = newp;
426               else
427                 {
428                   __rtld_mrlock_change (imap->l_scope_lock);
429                   imap->l_scope = newp;
430                   __rtld_mrlock_done (imap->l_scope_lock);
431                 }
432
433               if (old != imap->l_scope_mem)
434                 free (old);
435
436               imap->l_scope_max = new_size;
437             }
438
439           /* First terminate the extended list.  Otherwise a thread
440              might use the new last element and then use the garbage
441              at offset IDX+1.  */
442           imap->l_scope[cnt + 1] = NULL;
443           atomic_write_barrier ();
444           imap->l_scope[cnt] = &new->l_searchlist;
445         }
446       /* Only add TLS memory if this object is loaded now and
447          therefore is not yet initialized.  */
448       else if (! imap->l_init_called
449                /* Only if the module defines thread local data.  */
450                && __builtin_expect (imap->l_tls_blocksize > 0, 0))
451         {
452           /* Now that we know the object is loaded successfully add
453              modules containing TLS data to the slot info table.  We
454              might have to increase its size.  */
455           _dl_add_to_slotinfo (imap);
456
457           if (imap->l_need_tls_init)
458             {
459               imap->l_need_tls_init = 0;
460 #ifdef SHARED
461               /* Update the slot information data for at least the
462                  generation of the DSO we are allocating data for.  */
463               _dl_update_slotinfo (imap->l_tls_modid);
464 #endif
465
466               GL(dl_init_static_tls) (imap);
467               assert (imap->l_need_tls_init == 0);
468             }
469
470           /* We have to bump the generation counter.  */
471           any_tls = true;
472         }
473     }
474
475   /* Bump the generation number if necessary.  */
476   if (any_tls && __builtin_expect (++GL(dl_tls_generation) == 0, 0))
477     _dl_fatal_printf (N_("\
478 TLS generation counter wrapped!  Please report this."));
479
480   /* Run the initializer functions of new objects.  */
481   _dl_init (new, args->argc, args->argv, args->env);
482
483   /* Now we can make the new map available in the global scope.  */
484   if (mode & RTLD_GLOBAL)
485     /* Move the object in the global namespace.  */
486     if (add_to_global (new) != 0)
487       /* It failed.  */
488       return;
489
490   /* Mark the object as not deletable if the RTLD_NODELETE flags was
491      passed.  */
492   if (__builtin_expect (mode & RTLD_NODELETE, 0))
493     new->l_flags_1 |= DF_1_NODELETE;
494
495 #ifndef SHARED
496   /* We must be the static _dl_open in libc.a.  A static program that
497      has loaded a dynamic object now has competition.  */
498   __libc_multiple_libcs = 1;
499 #endif
500
501   /* Let the user know about the opencount.  */
502   if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_FILES, 0))
503     _dl_debug_printf ("opening file=%s [%lu]; direct_opencount=%u\n\n",
504                       new->l_name, new->l_ns, new->l_direct_opencount);
505 }
506
507
508 void *
509 _dl_open (const char *file, int mode, const void *caller_dlopen, Lmid_t nsid,
510           int argc, char *argv[], char *env[])
511 {
512   if ((mode & RTLD_BINDING_MASK) == 0)
513     /* One of the flags must be set.  */
514     _dl_signal_error (EINVAL, file, NULL, N_("invalid mode for dlopen()"));
515
516   /* Make sure we are alone.  */
517   __rtld_lock_lock_recursive (GL(dl_load_lock));
518
519   if (nsid == LM_ID_NEWLM)
520     {
521       /* Find a new namespace.  */
522       for (nsid = 1; nsid < DL_NNS; ++nsid)
523         if (GL(dl_ns)[nsid]._ns_loaded == NULL)
524           break;
525
526       if (nsid == DL_NNS)
527         {
528           /* No more namespace available.  */
529           __rtld_lock_unlock_recursive (GL(dl_load_lock));
530
531           _dl_signal_error (EINVAL, file, NULL, N_("\
532 no more namespaces available for dlmopen()"));
533         }
534
535       _dl_debug_initialize (0, nsid)->r_state = RT_CONSISTENT;
536     }
537   /* Never allow loading a DSO in a namespace which is empty.  Such
538      direct placements is only causing problems.  Also don't allow
539      loading into a namespace used for auditing.  */
540   else if (nsid != LM_ID_BASE && nsid != __LM_ID_CALLER
541            && (GL(dl_ns)[nsid]._ns_nloaded == 0
542                || GL(dl_ns)[nsid]._ns_loaded->l_auditing))
543     _dl_signal_error (EINVAL, file, NULL,
544                       N_("invalid target namespace in dlmopen()"));
545
546   struct dl_open_args args;
547   args.file = file;
548   args.mode = mode;
549   args.caller_dlopen = caller_dlopen;
550   args.caller_dl_open = RETURN_ADDRESS (0);
551   args.map = NULL;
552   args.nsid = nsid;
553   args.argc = argc;
554   args.argv = argv;
555   args.env = env;
556
557   const char *objname;
558   const char *errstring;
559   bool malloced;
560   int errcode = _dl_catch_error (&objname, &errstring, &malloced,
561                                  dl_open_worker, &args);
562
563 #ifndef MAP_COPY
564   /* We must munmap() the cache file.  */
565   _dl_unload_cache ();
566 #endif
567
568   /* See if an error occurred during loading.  */
569   if (__builtin_expect (errstring != NULL, 0))
570     {
571       /* Remove the object from memory.  It may be in an inconsistent
572          state if relocation failed, for example.  */
573       if (args.map)
574         {
575           /* Maybe some of the modules which were loaded use TLS.
576              Since it will be removed in the following _dl_close call
577              we have to mark the dtv array as having gaps to fill the
578              holes.  This is a pessimistic assumption which won't hurt
579              if not true.  There is no need to do this when we are
580              loading the auditing DSOs since TLS has not yet been set
581              up.  */
582           if ((mode & __RTLD_AUDIT) == 0)
583             GL(dl_tls_dtv_gaps) = true;
584
585           _dl_close_worker (args.map);
586         }
587
588       assert (_dl_debug_initialize (0, args.nsid)->r_state == RT_CONSISTENT);
589
590       /* Release the lock.  */
591       __rtld_lock_unlock_recursive (GL(dl_load_lock));
592
593       /* Make a local copy of the error string so that we can release the
594          memory allocated for it.  */
595       size_t len_errstring = strlen (errstring) + 1;
596       char *local_errstring;
597       if (objname == errstring + len_errstring)
598         {
599           size_t total_len = len_errstring + strlen (objname) + 1;
600           local_errstring = alloca (total_len);
601           memcpy (local_errstring, errstring, total_len);
602           objname = local_errstring + len_errstring;
603         }
604       else
605         {
606           local_errstring = alloca (len_errstring);
607           memcpy (local_errstring, errstring, len_errstring);
608         }
609
610       if (malloced)
611         free ((char *) errstring);
612
613       /* Reraise the error.  */
614       _dl_signal_error (errcode, objname, NULL, local_errstring);
615     }
616
617   assert (_dl_debug_initialize (0, args.nsid)->r_state == RT_CONSISTENT);
618
619   /* Release the lock.  */
620   __rtld_lock_unlock_recursive (GL(dl_load_lock));
621
622 #ifndef SHARED
623   DL_STATIC_INIT (args.map);
624 #endif
625
626   return args.map;
627 }
628
629
630 #ifdef SCOPE_DEBUG
631 #include <unistd.h>
632
633 static void
634 show_scope (struct link_map *new)
635 {
636   int scope_cnt;
637
638   for (scope_cnt = 0; new->l_scope[scope_cnt] != NULL; ++scope_cnt)
639     {
640       char numbuf[2];
641       unsigned int cnt;
642
643       numbuf[0] = '0' + scope_cnt;
644       numbuf[1] = '\0';
645       _dl_printf ("scope %s:", numbuf);
646
647       for (cnt = 0; cnt < new->l_scope[scope_cnt]->r_nlist; ++cnt)
648         if (*new->l_scope[scope_cnt]->r_list[cnt]->l_name)
649           _dl_printf (" %s", new->l_scope[scope_cnt]->r_list[cnt]->l_name);
650         else
651           _dl_printf (" <main>");
652
653       _dl_printf ("\n");
654     }
655 }
656 #endif