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