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