* elf/dl-open.c (dl_open_worker): Print exact l_direct_opencount value,
[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-2004, 2005 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 /* Undefine the following for debugging.  */
53 /* #define SCOPE_DEBUG 1 */
54 #ifdef SCOPE_DEBUG
55 static void show_scope (struct link_map *new);
56 #endif
57
58 /* We must be carefull not to leave us in an inconsistent state.  Thus we
59    catch any error and re-raise it after cleaning up.  */
60
61 struct dl_open_args
62 {
63   const char *file;
64   int mode;
65   /* This is the caller of the dlopen() function.  */
66   const void *caller_dlopen;
67   /* This is the caller if _dl_open().  */
68   const void *caller_dl_open;
69   struct link_map *map;
70   /* Namespace ID.  */
71   Lmid_t nsid;
72   /* Original parameters to the program and the current environment.  */
73   int argc;
74   char **argv;
75   char **env;
76 };
77
78
79 static int
80 add_to_global (struct link_map *new)
81 {
82   struct link_map **new_global;
83   unsigned int to_add = 0;
84   unsigned int cnt;
85
86   /* Count the objects we have to put in the global scope.  */
87   for (cnt = 0; cnt < new->l_searchlist.r_nlist; ++cnt)
88     if (new->l_searchlist.r_list[cnt]->l_global == 0)
89       ++to_add;
90
91   /* The symbols of the new objects and its dependencies are to be
92      introduced into the global scope that will be used to resolve
93      references from other dynamically-loaded objects.
94
95      The global scope is the searchlist in the main link map.  We
96      extend this list if necessary.  There is one problem though:
97      since this structure was allocated very early (before the libc
98      is loaded) the memory it uses is allocated by the malloc()-stub
99      in the ld.so.  When we come here these functions are not used
100      anymore.  Instead the malloc() implementation of the libc is
101      used.  But this means the block from the main map cannot be used
102      in an realloc() call.  Therefore we allocate a completely new
103      array the first time we have to add something to the locale scope.  */
104
105   if (GL(dl_ns)[new->l_ns]._ns_global_scope_alloc == 0)
106     {
107       /* This is the first dynamic object given global scope.  */
108       GL(dl_ns)[new->l_ns]._ns_global_scope_alloc
109         = GL(dl_ns)[new->l_ns]._ns_main_searchlist->r_nlist + to_add + 8;
110       new_global = (struct link_map **)
111         malloc (GL(dl_ns)[new->l_ns]._ns_global_scope_alloc
112                 * sizeof (struct link_map *));
113       if (new_global == NULL)
114         {
115           GL(dl_ns)[new->l_ns]._ns_global_scope_alloc = 0;
116         nomem:
117           _dl_signal_error (ENOMEM, new->l_libname->name, NULL,
118                             N_("cannot extend global scope"));
119           return 1;
120         }
121
122       /* Copy over the old entries.  */
123       GL(dl_ns)[new->l_ns]._ns_main_searchlist->r_list
124         = memcpy (new_global,
125                   GL(dl_ns)[new->l_ns]._ns_main_searchlist->r_list,
126                   (GL(dl_ns)[new->l_ns]._ns_main_searchlist->r_nlist
127                    * sizeof (struct link_map *)));
128     }
129   else if (GL(dl_ns)[new->l_ns]._ns_main_searchlist->r_nlist + to_add
130            > GL(dl_ns)[new->l_ns]._ns_global_scope_alloc)
131     {
132       /* We have to extend the existing array of link maps in the
133          main map.  */
134       new_global = (struct link_map **)
135         realloc (GL(dl_ns)[new->l_ns]._ns_main_searchlist->r_list,
136                  ((GL(dl_ns)[new->l_ns]._ns_global_scope_alloc + to_add + 8)
137                   * sizeof (struct link_map *)));
138       if (new_global == NULL)
139         goto nomem;
140
141       GL(dl_ns)[new->l_ns]._ns_global_scope_alloc += to_add + 8;
142       GL(dl_ns)[new->l_ns]._ns_main_searchlist->r_list = new_global;
143     }
144
145   /* Now add the new entries.  */
146   for (cnt = 0; cnt < new->l_searchlist.r_nlist; ++cnt)
147     {
148       struct link_map *map = new->l_searchlist.r_list[cnt];
149
150       if (map->l_global == 0)
151         {
152           map->l_global = 1;
153           GL(dl_ns)[new->l_ns]._ns_main_searchlist->r_list[GL(dl_ns)[new->l_ns]._ns_main_searchlist->r_nlist]
154             = map;
155           ++GL(dl_ns)[new->l_ns]._ns_main_searchlist->r_nlist;
156         }
157     }
158
159   return 0;
160 }
161
162
163 static void
164 dl_open_worker (void *a)
165 {
166   struct dl_open_args *args = a;
167   const char *file = args->file;
168   int mode = args->mode;
169   struct link_map *new, *l;
170   int lazy;
171   unsigned int i;
172 #ifdef USE_TLS
173   bool any_tls = false;
174 #endif
175   struct link_map *call_map = NULL;
176
177   /* Check whether _dl_open() has been called from a valid DSO.  */
178   if (__check_caller (args->caller_dl_open,
179                       allow_libc|allow_libdl|allow_ldso) != 0)
180     _dl_signal_error (0, "dlopen", NULL, N_("invalid caller"));
181
182   /* Determine the caller's map if necessary.  This is needed in case
183      we have a DST, when we don't know the namespace ID we have to put
184      the new object in, or when the file name has no path in which
185      case we need to look along the RUNPATH/RPATH of the caller.  */
186   const char *dst = strchr (file, '$');
187   if (dst != NULL || args->nsid == __LM_ID_CALLER
188       || strchr (file, '/') == NULL)
189     {
190       const void *caller_dlopen = args->caller_dlopen;
191
192       /* We have to find out from which object the caller is calling.
193          By default we assume this is the main application.  */
194       call_map = GL(dl_ns)[LM_ID_BASE]._ns_loaded;
195
196       for (Lmid_t ns = 0; ns < DL_NNS; ++ns)
197         for (l = GL(dl_ns)[ns]._ns_loaded; l != NULL; l = l->l_next)
198           if (caller_dlopen >= (const void *) l->l_map_start
199               && caller_dlopen < (const void *) l->l_map_end)
200             {
201               /* There must be exactly one DSO for the range of the virtual
202                  memory.  Otherwise something is really broken.  */
203               assert (ns == l->l_ns);
204               call_map = l;
205               goto found_caller;
206             }
207
208     found_caller:
209       if (args->nsid == __LM_ID_CALLER)
210         {
211 #ifndef SHARED
212           /* In statically linked apps there might be no loaded object.  */
213           if (call_map == NULL)
214             args->nsid = LM_ID_BASE;
215           else
216 #endif
217             args->nsid = call_map->l_ns;
218         }
219     }
220
221   assert (_dl_debug_initialize (0, args->nsid)->r_state == RT_CONSISTENT);
222
223   /* Maybe we have to expand a DST.  */
224   if (__builtin_expect (dst != NULL, 0))
225     {
226       size_t len = strlen (file);
227       size_t required;
228       char *new_file;
229
230       /* DSTs must not appear in SUID/SGID programs.  */
231       if (INTUSE(__libc_enable_secure))
232         /* This is an error.  */
233         _dl_signal_error (0, "dlopen", NULL,
234                           N_("DST not allowed in SUID/SGID programs"));
235
236
237       /* Determine how much space we need.  We have to allocate the
238          memory locally.  */
239       required = DL_DST_REQUIRED (call_map, file, len, _dl_dst_count (dst, 0));
240
241       /* Get space for the new file name.  */
242       new_file = (char *) alloca (required + 1);
243
244       /* Generate the new file name.  */
245       _dl_dst_substitute (call_map, file, new_file, 0);
246
247       /* If the substitution failed don't try to load.  */
248       if (*new_file == '\0')
249         _dl_signal_error (0, "dlopen", NULL,
250                           N_("empty dynamic string token substitution"));
251
252       /* Now we have a new file name.  */
253       file = new_file;
254
255       /* It does not matter whether call_map is set even if we
256          computed it only because of the DST.  Since the path contains
257          a slash the value is not used.  See dl-load.c.  */
258     }
259
260   /* Load the named object.  */
261   args->map = new = _dl_map_object (call_map, file, 0, lt_loaded, 0,
262                                     mode | __RTLD_CALLMAP, args->nsid);
263
264   /* If the pointer returned is NULL this means the RTLD_NOLOAD flag is
265      set and the object is not already loaded.  */
266   if (new == NULL)
267     {
268       assert (mode & RTLD_NOLOAD);
269       return;
270     }
271
272   if (__builtin_expect (mode & __RTLD_SPROF, 0))
273     /* This happens only if we load a DSO for 'sprof'.  */
274     return;
275
276   /* This object is directly loaded.  */
277   ++new->l_direct_opencount;
278
279   /* It was already open.  */
280   if (__builtin_expect (new->l_searchlist.r_list != NULL, 0))
281     {
282       /* Let the user know about the opencount.  */
283       if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_FILES, 0))
284         _dl_debug_printf ("opening file=%s [%lu]; direct_opencount=%u\n\n",
285                           new->l_name, new->l_ns, new->l_direct_opencount);
286
287       /* If the user requested the object to be in the global namespace
288          but it is not so far, add it now.  */
289       if ((mode & RTLD_GLOBAL) && new->l_global == 0)
290         (void) add_to_global (new);
291
292       assert (_dl_debug_initialize (0, args->nsid)->r_state == RT_CONSISTENT);
293
294       return;
295     }
296
297   /* Load that object's dependencies.  */
298   _dl_map_object_deps (new, NULL, 0, 0,
299                        mode & (__RTLD_DLOPEN | RTLD_DEEPBIND | __RTLD_AUDIT));
300
301   /* So far, so good.  Now check the versions.  */
302   for (i = 0; i < new->l_searchlist.r_nlist; ++i)
303     if (new->l_searchlist.r_list[i]->l_real->l_versions == NULL)
304       (void) _dl_check_map_versions (new->l_searchlist.r_list[i]->l_real,
305                                      0, 0);
306
307 #ifdef SCOPE_DEBUG
308   show_scope (new);
309 #endif
310
311 #ifdef SHARED
312   /* Auditing checkpoint: we have added all objects.  */
313   if (__builtin_expect (GLRO(dl_naudit) > 0, 0))
314     {
315       struct link_map *head = GL(dl_ns)[new->l_ns]._ns_loaded;
316       /* Do not call the functions for any auditing object.  */
317       if (head->l_auditing == 0)
318         {
319           struct audit_ifaces *afct = GLRO(dl_audit);
320           for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt)
321             {
322               if (afct->activity != NULL)
323                 afct->activity (&head->l_audit[cnt].cookie, LA_ACT_CONSISTENT);
324
325               afct = afct->next;
326             }
327         }
328     }
329 #endif
330
331   /* Notify the debugger all new objects are now ready to go.  */
332   struct r_debug *r = _dl_debug_initialize (0, args->nsid);
333   r->r_state = RT_CONSISTENT;
334   _dl_debug_state ();
335
336   /* Only do lazy relocation if `LD_BIND_NOW' is not set.  */
337   lazy = (mode & RTLD_BINDING_MASK) == RTLD_LAZY && GLRO(dl_lazy);
338
339   /* Relocate the objects loaded.  We do this in reverse order so that copy
340      relocs of earlier objects overwrite the data written by later objects.  */
341
342   l = new;
343   while (l->l_next)
344     l = l->l_next;
345   while (1)
346     {
347       if (! l->l_real->l_relocated)
348         {
349 #ifdef SHARED
350           if (GLRO(dl_profile) != NULL)
351             {
352               /* If this here is the shared object which we want to profile
353                  make sure the profile is started.  We can find out whether
354                  this is necessary or not by observing the `_dl_profile_map'
355                  variable.  If was NULL but is not NULL afterwars we must
356                  start the profiling.  */
357               struct link_map *old_profile_map = GL(dl_profile_map);
358
359               _dl_relocate_object (l, l->l_scope, 1, 1);
360
361               if (old_profile_map == NULL && GL(dl_profile_map) != NULL)
362                 {
363                   /* We must prepare the profiling.  */
364                   _dl_start_profile ();
365
366                   /* Prevent unloading the object.  */
367                   GL(dl_profile_map)->l_flags_1 |= DF_1_NODELETE;
368                 }
369             }
370           else
371 #endif
372             _dl_relocate_object (l, l->l_scope, lazy, 0);
373         }
374
375       if (l == new)
376         break;
377       l = l->l_prev;
378     }
379
380   /* If the file is not loaded now as a dependency, add the search
381      list of the newly loaded object to the scope.  */
382   for (i = 0; i < new->l_searchlist.r_nlist; ++i)
383     {
384       struct link_map *imap = new->l_searchlist.r_list[i];
385
386       /* If the initializer has been called already, the object has
387          not been loaded here and now.  */
388       if (imap->l_init_called && imap->l_type == lt_loaded)
389         {
390           struct r_scope_elem **runp = imap->l_scope;
391           size_t cnt = 0;
392
393           while (*runp != NULL)
394             {
395               ++cnt;
396               ++runp;
397             }
398
399           if (*runp != NULL)
400             /* Avoid duplicates.  */
401             continue;
402
403           if (__builtin_expect (cnt + 1 >= imap->l_scope_max, 0))
404             {
405               /* The 'r_scope' array is too small.  Allocate a new one
406                  dynamically.  */
407               struct r_scope_elem **newp;
408               size_t new_size = imap->l_scope_max * 2;
409
410               if (imap->l_scope == imap->l_scope_mem)
411                 {
412                   newp = (struct r_scope_elem **)
413                     malloc (new_size * sizeof (struct r_scope_elem *));
414                   if (newp == NULL)
415                     _dl_signal_error (ENOMEM, "dlopen", NULL,
416                                       N_("cannot create scope list"));
417                   imap->l_scope = memcpy (newp, imap->l_scope,
418                                           cnt * sizeof (imap->l_scope[0]));
419                 }
420               else
421                 {
422                   newp = (struct r_scope_elem **)
423                     realloc (imap->l_scope,
424                              new_size * sizeof (struct r_scope_elem *));
425                   if (newp == NULL)
426                     _dl_signal_error (ENOMEM, "dlopen", NULL,
427                                       N_("cannot create scope list"));
428                   imap->l_scope = newp;
429                 }
430
431               imap->l_scope_max = new_size;
432             }
433
434           imap->l_scope[cnt++] = &new->l_searchlist;
435           imap->l_scope[cnt] = NULL;
436         }
437 #if USE_TLS
438       /* Only add TLS memory if this object is loaded now and
439          therefore is not yet initialized.  */
440       else if (! imap->l_init_called
441                /* Only if the module defines thread local data.  */
442                && __builtin_expect (imap->l_tls_blocksize > 0, 0))
443         {
444           /* Now that we know the object is loaded successfully add
445              modules containing TLS data to the slot info table.  We
446              might have to increase its size.  */
447           _dl_add_to_slotinfo (imap);
448
449           if (imap->l_need_tls_init)
450             {
451               imap->l_need_tls_init = 0;
452 # ifdef SHARED
453               /* Update the slot information data for at least the
454                  generation of the DSO we are allocating data for.  */
455               _dl_update_slotinfo (imap->l_tls_modid);
456 # endif
457
458               GL(dl_init_static_tls) (imap);
459               assert (imap->l_need_tls_init == 0);
460             }
461
462           /* We have to bump the generation counter.  */
463           any_tls = true;
464         }
465     }
466
467   /* Bump the generation number if necessary.  */
468   if (any_tls && __builtin_expect (++GL(dl_tls_generation) == 0, 0))
469     _dl_fatal_printf (N_("\
470 TLS generation counter wrapped!  Please report this."));
471 #endif
472
473   /* Run the initializer functions of new objects.  */
474   _dl_init (new, args->argc, args->argv, args->env);
475
476   /* Now we can make the new map available in the global scope.  */
477   if (mode & RTLD_GLOBAL)
478     /* Move the object in the global namespace.  */
479     if (add_to_global (new) != 0)
480       /* It failed.  */
481       return;
482
483   /* Mark the object as not deletable if the RTLD_NODELETE flags was
484      passed.  */
485   if (__builtin_expect (mode & RTLD_NODELETE, 0))
486     new->l_flags_1 |= DF_1_NODELETE;
487
488 #ifndef SHARED
489   /* We must be the static _dl_open in libc.a.  A static program that
490      has loaded a dynamic object now has competition.  */
491   __libc_multiple_libcs = 1;
492 #endif
493
494   /* Let the user know about the opencount.  */
495   if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_FILES, 0))
496     _dl_debug_printf ("opening file=%s [%lu]; direct_opencount=%u\n\n",
497                       new->l_name, new->l_ns, new->l_direct_opencount);
498 }
499
500
501 void *
502 _dl_open (const char *file, int mode, const void *caller_dlopen, Lmid_t nsid,
503           int argc, char *argv[], char *env[])
504 {
505   struct dl_open_args args;
506   const char *objname;
507   const char *errstring;
508   int errcode;
509
510   if ((mode & RTLD_BINDING_MASK) == 0)
511     /* One of the flags must be set.  */
512     _dl_signal_error (EINVAL, file, NULL, N_("invalid mode for dlopen()"));
513
514   /* Make sure we are alone.  */
515   __rtld_lock_lock_recursive (GL(dl_load_lock));
516
517   if (nsid == LM_ID_NEWLM)
518     {
519       /* Find a new namespace.  */
520       for (nsid = 1; nsid < DL_NNS; ++nsid)
521         if (GL(dl_ns)[nsid]._ns_loaded == NULL)
522           break;
523
524       if (nsid == DL_NNS)
525         {
526           /* No more namespace available.  */
527           __rtld_lock_unlock_recursive (GL(dl_load_lock));
528
529           _dl_signal_error (EINVAL, file, NULL, N_("\
530 no more namespaces available for dlmopen()"));
531         }
532
533       _dl_debug_initialize (0, nsid)->r_state = RT_CONSISTENT;
534     }
535   /* Never allow loading a DSO in a namespace which is empty.  Such
536      direct placements is only causing problems.  Also don't allow
537      loading into a namespace used for auditing.  */
538   else if (nsid != LM_ID_BASE && nsid != __LM_ID_CALLER
539            && (GL(dl_ns)[nsid]._ns_nloaded == 0
540                || GL(dl_ns)[nsid]._ns_loaded->l_auditing))
541     _dl_signal_error (EINVAL, file, NULL,
542                       N_("invalid target namespace in dlmopen()"));
543
544   args.file = file;
545   args.mode = mode;
546   args.caller_dlopen = caller_dlopen;
547   args.caller_dl_open = RETURN_ADDRESS (0);
548   args.map = NULL;
549   args.nsid = nsid;
550   args.argc = argc;
551   args.argv = argv;
552   args.env = env;
553   errcode = _dl_catch_error (&objname, &errstring, dl_open_worker, &args);
554
555 #ifndef MAP_COPY
556   /* We must munmap() the cache file.  */
557   _dl_unload_cache ();
558 #endif
559
560   /* Release the lock.  */
561   __rtld_lock_unlock_recursive (GL(dl_load_lock));
562
563   if (__builtin_expect (errstring != NULL, 0))
564     {
565       /* Some error occurred during loading.  */
566       char *local_errstring;
567       size_t len_errstring;
568
569       /* Remove the object from memory.  It may be in an inconsistent
570          state if relocation failed, for example.  */
571       if (args.map)
572         {
573 #ifdef USE_TLS
574           /* Maybe some of the modules which were loaded use TLS.
575              Since it will be removed in the following _dl_close call
576              we have to mark the dtv array as having gaps to fill the
577              holes.  This is a pessimistic assumption which won't hurt
578              if not true.  There is no need to do this when we are
579              loading the auditing DSOs since TLS has not yet been set
580              up.  */
581           if ((mode & __RTLD_AUDIT) == 0)
582             GL(dl_tls_dtv_gaps) = true;
583 #endif
584
585           _dl_close (args.map);
586         }
587
588       /* Make a local copy of the error string so that we can release the
589          memory allocated for it.  */
590       len_errstring = strlen (errstring) + 1;
591       if (objname == errstring + len_errstring)
592         {
593           size_t total_len = len_errstring + strlen (objname) + 1;
594           local_errstring = alloca (total_len);
595           memcpy (local_errstring, errstring, total_len);
596           objname = local_errstring + len_errstring;
597         }
598       else
599         {
600           local_errstring = alloca (len_errstring);
601           memcpy (local_errstring, errstring, len_errstring);
602         }
603
604       if (errstring != _dl_out_of_memory)
605         free ((char *) errstring);
606
607       assert (_dl_debug_initialize (0, args.nsid)->r_state == RT_CONSISTENT);
608
609       /* Reraise the error.  */
610       _dl_signal_error (errcode, objname, NULL, local_errstring);
611     }
612
613   assert (_dl_debug_initialize (0, args.nsid)->r_state == RT_CONSISTENT);
614
615 #ifndef SHARED
616   DL_STATIC_INIT (args.map);
617 #endif
618
619   return args.map;
620 }
621
622
623 #ifdef SCOPE_DEBUG
624 #include <unistd.h>
625
626 static void
627 show_scope (struct link_map *new)
628 {
629   int scope_cnt;
630
631   for (scope_cnt = 0; new->l_scope[scope_cnt] != NULL; ++scope_cnt)
632     {
633       char numbuf[2];
634       unsigned int cnt;
635
636       numbuf[0] = '0' + scope_cnt;
637       numbuf[1] = '\0';
638       _dl_printf ("scope %s:", numbuf);
639
640       for (cnt = 0; cnt < new->l_scope[scope_cnt]->r_nlist; ++cnt)
641         if (*new->l_scope[scope_cnt]->r_list[cnt]->l_name)
642           _dl_printf (" %s", new->l_scope[scope_cnt]->r_list[cnt]->l_name);
643         else
644           _dl_printf (" <main>");
645
646       _dl_printf ("\n");
647     }
648 }
649 #endif