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