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