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 <caller.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           GLRO(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 static void
160 dl_open_worker (void *a)
161 {
162   struct dl_open_args *args = a;
163   const char *file = args->file;
164   int mode = args->mode;
165   struct link_map *new, *l;
166   const char *dst;
167   int lazy;
168   unsigned int i;
169 #ifdef USE_TLS
170   bool any_tls;
171 #endif
172
173   /* Check whether _dl_open() has been called from a valid DSO.  */
174   if (__check_caller (args->caller_dl_open, allow_libc|allow_libdl) != 0)
175     GLRO(dl_signal_error) (0, "dlopen", NULL, N_("invalid caller"));
176
177   /* Maybe we have to expand a DST.  */
178   dst = strchr (file, '$');
179   if (__builtin_expect (dst != NULL, 0))
180     {
181       const void *caller_dlopen = args->caller_dlopen;
182       size_t len = strlen (file);
183       size_t required;
184       struct link_map *call_map;
185       char *new_file;
186
187       /* DSTs must not appear in SUID/SGID programs.  */
188       if (__libc_enable_secure)
189         /* This is an error.  */
190         GLRO(dl_signal_error) (0, "dlopen", NULL,
191                                N_("DST not allowed in SUID/SGID programs"));
192
193       /* We have to find out from which object the caller is calling.  */
194       call_map = NULL;
195       for (l = GL(dl_loaded); l; l = l->l_next)
196         if (caller_dlopen >= (const void *) l->l_map_start
197             && caller_dlopen < (const void *) l->l_map_end)
198           {
199             /* There must be exactly one DSO for the range of the virtual
200                memory.  Otherwise something is really broken.  */
201             call_map = l;
202             break;
203           }
204
205       if (call_map == NULL)
206         /* In this case we assume this is the main application.  */
207         call_map = GL(dl_loaded);
208
209       /* Determine how much space we need.  We have to allocate the
210          memory locally.  */
211       required = DL_DST_REQUIRED (call_map, file, len, _dl_dst_count (dst, 0));
212
213       /* Get space for the new file name.  */
214       new_file = (char *) alloca (required + 1);
215
216       /* Generate the new file name.  */
217       _dl_dst_substitute (call_map, file, new_file, 0);
218
219       /* If the substitution failed don't try to load.  */
220       if (*new_file == '\0')
221         GLRO(dl_signal_error) (0, "dlopen", NULL,
222                                N_("empty dynamic string token substitution"));
223
224       /* Now we have a new file name.  */
225       file = new_file;
226     }
227
228   /* Load the named object.  */
229   args->map = new = GLRO(dl_map_object) (NULL, file, 0, lt_loaded, 0, mode);
230
231   /* If the pointer returned is NULL this means the RTLD_NOLOAD flag is
232      set and the object is not already loaded.  */
233   if (new == NULL)
234     {
235       assert (mode & RTLD_NOLOAD);
236       return;
237     }
238
239   if (__builtin_expect (mode & __RTLD_SPROF, 0))
240     /* This happens only if we load a DSO for 'sprof'.  */
241     return;
242
243   /* It was already open.  */
244   if (__builtin_expect (new->l_searchlist.r_list != NULL, 0))
245     {
246       /* Let the user know about the opencount.  */
247       if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_FILES, 0))
248         GLRO(dl_debug_printf) ("opening file=%s; opencount == %u\n\n",
249                                new->l_name, new->l_opencount);
250
251       /* If the user requested the object to be in the global namespace
252          but it is not so far, add it now.  */
253       if ((mode & RTLD_GLOBAL) && new->l_global == 0)
254         (void) add_to_global (new);
255
256       /* Increment just the reference counter of the object.  */
257       ++new->l_opencount;
258
259       return;
260     }
261
262   /* Load that object's dependencies.  */
263   GLRO(dl_map_object_deps) (new, NULL, 0, 0, mode & __RTLD_DLOPEN);
264
265   /* So far, so good.  Now check the versions.  */
266   for (i = 0; i < new->l_searchlist.r_nlist; ++i)
267     if (new->l_searchlist.r_list[i]->l_versions == NULL)
268       (void) GLRO(dl_check_map_versions) (new->l_searchlist.r_list[i], 0, 0);
269
270 #ifdef SCOPE_DEBUG
271   show_scope (new);
272 #endif
273
274   /* Only do lazy relocation if `LD_BIND_NOW' is not set.  */
275   lazy = (mode & RTLD_BINDING_MASK) == RTLD_LAZY && GLRO(dl_lazy);
276
277   /* Relocate the objects loaded.  We do this in reverse order so that copy
278      relocs of earlier objects overwrite the data written by later objects.  */
279
280   l = new;
281   while (l->l_next)
282     l = l->l_next;
283   while (1)
284     {
285       if (! l->l_relocated)
286         {
287 #ifdef SHARED
288           if (GLRO(dl_profile) != NULL)
289             {
290               /* If this here is the shared object which we want to profile
291                  make sure the profile is started.  We can find out whether
292                  this is necessary or not by observing the `_dl_profile_map'
293                  variable.  If was NULL but is not NULL afterwars we must
294                  start the profiling.  */
295               struct link_map *old_profile_map = GL(dl_profile_map);
296
297               GLRO(dl_relocate_object) (l, l->l_scope, 1, 1);
298
299               if (old_profile_map == NULL && GL(dl_profile_map) != NULL)
300                 {
301                   /* We must prepare the profiling.  */
302                   GLRO(dl_start_profile) ();
303
304                   /* Prevent unloading the object.  */
305                   GL(dl_profile_map)->l_flags_1 |= DF_1_NODELETE;
306                 }
307             }
308           else
309 #endif
310             GLRO(dl_relocate_object) (l, l->l_scope, lazy, 0);
311         }
312
313       if (l == new)
314         break;
315       l = l->l_prev;
316     }
317
318 #ifdef USE_TLS
319   /* Do static TLS initialization now if it has been delayed because
320      the TLS template might not be fully relocated at _dl_allocate_static_tls
321      time.  */
322   for (l = new; l; l = l->l_next)
323     if (l->l_need_tls_init)
324       {
325         l->l_need_tls_init = 0;
326         GL(dl_init_static_tls) (l);
327       }
328
329   /* We normally don't bump the TLS generation counter.  There must be
330      actually a need to do this.  */
331   any_tls = false;
332 #endif
333
334   /* Increment the open count for all dependencies.  If the file is
335      not loaded as a dependency here add the search list of the newly
336      loaded object to the scope.  */
337   for (i = 0; i < new->l_searchlist.r_nlist; ++i)
338     if (++new->l_searchlist.r_list[i]->l_opencount > 1
339         && new->l_searchlist.r_list[i]->l_type == lt_loaded)
340       {
341         struct link_map *imap = new->l_searchlist.r_list[i];
342         struct r_scope_elem **runp = imap->l_scope;
343         size_t cnt = 0;
344
345         while (*runp != NULL)
346           {
347             /* This can happen if imap was just loaded, but during
348                relocation had l_opencount bumped because of relocation
349                dependency.  Avoid duplicates in l_scope.  */
350             if (__builtin_expect (*runp == &new->l_searchlist, 0))
351               break;
352
353             ++cnt;
354             ++runp;
355           }
356
357         if (*runp != NULL)
358           /* Avoid duplicates.  */
359           continue;
360
361         if (__builtin_expect (cnt + 1 >= imap->l_scope_max, 0))
362           {
363             /* The 'r_scope' array is too small.  Allocate a new one
364                dynamically.  */
365             struct r_scope_elem **newp;
366             size_t new_size = imap->l_scope_max * 2;
367
368             if (imap->l_scope == imap->l_scope_mem)
369               {
370                 newp = (struct r_scope_elem **)
371                   malloc (new_size * sizeof (struct r_scope_elem *));
372                 if (newp == NULL)
373                   GLRO(dl_signal_error) (ENOMEM, "dlopen", NULL,
374                                          N_("cannot create scope list"));
375                 imap->l_scope = memcpy (newp, imap->l_scope,
376                                         cnt * sizeof (imap->l_scope[0]));
377               }
378             else
379               {
380                 newp = (struct r_scope_elem **)
381                   realloc (imap->l_scope,
382                            new_size * sizeof (struct r_scope_elem *));
383                 if (newp == NULL)
384                   GLRO(dl_signal_error) (ENOMEM, "dlopen", NULL,
385                                          N_("cannot create scope list"));
386                 imap->l_scope = newp;
387               }
388
389             imap->l_scope_max = new_size;
390           }
391
392         imap->l_scope[cnt++] = &new->l_searchlist;
393         imap->l_scope[cnt] = NULL;
394       }
395 #if USE_TLS
396     else if (new->l_searchlist.r_list[i]->l_opencount == 1
397              /* Only if the module defines thread local data.  */
398              && __builtin_expect (new->l_searchlist.r_list[i]->l_tls_blocksize
399                                   > 0, 0))
400       {
401         /* Now that we know the object is loaded successfully add
402            modules containing TLS data to the dtv info table.  We
403            might have to increase its size.  */
404         struct dtv_slotinfo_list *listp;
405         struct dtv_slotinfo_list *prevp;
406         size_t idx = new->l_searchlist.r_list[i]->l_tls_modid;
407
408         assert (new->l_searchlist.r_list[i]->l_type == lt_loaded);
409
410         /* Find the place in the dtv slotinfo list.  */
411         listp = GL(dl_tls_dtv_slotinfo_list);
412         prevp = NULL;           /* Needed to shut up gcc.  */
413         do
414           {
415             /* Does it fit in the array of this list element?  */
416             if (idx < listp->len)
417               break;
418             idx -= listp->len;
419             prevp = listp;
420             listp = listp->next;
421           }
422         while (listp != NULL);
423
424         if (listp == NULL)
425           {
426             /* When we come here it means we have to add a new element
427                to the slotinfo list.  And the new module must be in
428                the first slot.  */
429             assert (idx == 0);
430
431             listp = prevp->next = (struct dtv_slotinfo_list *)
432               malloc (sizeof (struct dtv_slotinfo_list)
433                       + TLS_SLOTINFO_SURPLUS * sizeof (struct dtv_slotinfo));
434             if (listp == NULL)
435               {
436                 /* We ran out of memory.  We will simply fail this
437                    call but don't undo anything we did so far.  The
438                    application will crash or be terminated anyway very
439                    soon.  */
440
441                 /* We have to do this since some entries in the dtv
442                    slotinfo array might already point to this
443                    generation.  */
444                 ++GL(dl_tls_generation);
445
446                 GLRO(dl_signal_error) (ENOMEM, "dlopen", NULL, N_("\
447 cannot create TLS data structures"));
448               }
449
450             listp->len = TLS_SLOTINFO_SURPLUS;
451             listp->next = NULL;
452             memset (listp->slotinfo, '\0',
453                     TLS_SLOTINFO_SURPLUS * sizeof (struct dtv_slotinfo));
454           }
455
456         /* Add the information into the slotinfo data structure.  */
457         listp->slotinfo[idx].map = new->l_searchlist.r_list[i];
458         listp->slotinfo[idx].gen = GL(dl_tls_generation) + 1;
459
460         /* We have to bump the generation counter.  */
461         any_tls = true;
462       }
463
464   /* Bump the generation number if necessary.  */
465   if (any_tls)
466     if (__builtin_expect (++GL(dl_tls_generation) == 0, 0))
467       __libc_fatal (_("TLS generation counter wrapped!  Please send report with the 'glibcbug' script."));
468 #endif
469
470   /* Run the initializer functions of new objects.  */
471   GLRO(dl_init) (new, __libc_argc, __libc_argv, __environ);
472
473   /* Now we can make the new map available in the global scope.  */
474   if (mode & RTLD_GLOBAL)
475     /* Move the object in the global namespace.  */
476     if (add_to_global (new) != 0)
477       /* It failed.  */
478       return;
479
480   /* Mark the object as not deletable if the RTLD_NODELETE flags was
481      passed.  */
482   if (__builtin_expect (mode & RTLD_NODELETE, 0))
483     new->l_flags_1 |= DF_1_NODELETE;
484
485 #ifndef SHARED
486   /* We must be the static _dl_open in libc.a.  A static program that
487      has loaded a dynamic object now has competition.  */
488   __libc_multiple_libcs = 1;
489 #endif
490
491   /* Let the user know about the opencount.  */
492   if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_FILES, 0))
493     GLRO(dl_debug_printf) ("opening file=%s; opencount == %u\n\n",
494                            new->l_name, new->l_opencount);
495 }
496
497
498 void *
499 internal_function
500 _dl_open (const char *file, int mode, const void *caller_dlopen)
501 {
502   struct dl_open_args args;
503   const char *objname;
504   const char *errstring;
505   int errcode;
506
507   if ((mode & RTLD_BINDING_MASK) == 0)
508     /* One of the flags must be set.  */
509     GLRO(dl_signal_error) (EINVAL, file, NULL,
510                            N_("invalid mode for dlopen()"));
511
512   /* Make sure we are alone.  */
513   __rtld_lock_lock_recursive (GL(dl_load_lock));
514
515   args.file = file;
516   args.mode = mode;
517   args.caller_dlopen = caller_dlopen;
518   args.caller_dl_open = RETURN_ADDRESS (0);
519   args.map = NULL;
520   errcode = GLRO(dl_catch_error) (&objname, &errstring, dl_open_worker, &args);
521
522 #ifndef MAP_COPY
523   /* We must munmap() the cache file.  */
524   GLRO(dl_unload_cache) ();
525 #endif
526
527   /* Release the lock.  */
528   __rtld_lock_unlock_recursive (GL(dl_load_lock));
529
530   if (__builtin_expect (errstring != NULL, 0))
531     {
532       /* Some error occurred during loading.  */
533       char *local_errstring;
534       size_t len_errstring;
535
536       /* Remove the object from memory.  It may be in an inconsistent
537          state if relocation failed, for example.  */
538       if (args.map)
539         {
540           unsigned int i;
541
542           /* Increment open counters for all objects since this
543              sometimes has not happened yet.  */
544           if (args.map->l_searchlist.r_list[0]->l_opencount == 0)
545             for (i = 0; i < args.map->l_searchlist.r_nlist; ++i)
546               ++args.map->l_searchlist.r_list[i]->l_opencount;
547
548 #ifdef USE_TLS
549           /* Maybe some of the modules which were loaded uses TLS.
550              Since it will be removed in the following _dl_close call
551              we have to mark the dtv array as having gaps to fill
552              the holes.  This is a pessimistic assumption which won't
553              hurt if not true.  */
554           GL(dl_tls_dtv_gaps) = true;
555 #endif
556
557           _dl_close (args.map);
558         }
559
560       /* Make a local copy of the error string so that we can release the
561          memory allocated for it.  */
562       len_errstring = strlen (errstring) + 1;
563       if (objname == errstring + len_errstring)
564         {
565           size_t total_len = len_errstring + strlen (objname) + 1;
566           local_errstring = alloca (total_len);
567           memcpy (local_errstring, errstring, total_len);
568           objname = local_errstring + len_errstring;
569         }
570       else
571         {
572           local_errstring = alloca (len_errstring);
573           memcpy (local_errstring, errstring, len_errstring);
574         }
575
576       if (errstring != _dl_out_of_memory)
577         free ((char *) errstring);
578
579       /* Reraise the error.  */
580       GLRO(dl_signal_error) (errcode, objname, NULL, local_errstring);
581     }
582
583 #ifndef SHARED
584   DL_STATIC_INIT (args.map);
585 #endif
586
587   return args.map;
588 }
589 libc_hidden_def (_dl_open)
590
591
592 #ifdef SCOPE_DEBUG
593 #include <unistd.h>
594
595 static void
596 show_scope (struct link_map *new)
597 {
598   int scope_cnt;
599
600   for (scope_cnt = 0; new->l_scope[scope_cnt] != NULL; ++scope_cnt)
601     {
602       char numbuf[2];
603       unsigned int cnt;
604
605       numbuf[0] = '0' + scope_cnt;
606       numbuf[1] = '\0';
607       _dl_printf ("scope %s:", numbuf);
608
609       for (cnt = 0; cnt < new->l_scope[scope_cnt]->r_nlist; ++cnt)
610         if (*new->l_scope[scope_cnt]->r_list[cnt]->l_name)
611           _dl_printf (" %s", new->l_scope[scope_cnt]->r_list[cnt]->l_name);
612         else
613           _dl_printf (" <main>");
614
615       _dl_printf ("\n");
616     }
617 }
618 #endif