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