Update.
[platform/upstream/glibc.git] / elf / dl-deps.c
1 /* Load the dependencies of a mapped object.
2    Copyright (C) 1996, 1997, 1998, 1999, 2000 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 Library General Public License as
7    published by the Free Software Foundation; either version 2 of the
8    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    Library General Public License for more details.
14
15    You should have received a copy of the GNU Library General Public
16    License along with the GNU C Library; see the file COPYING.LIB.  If not,
17    write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18    Boston, MA 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/param.h>
28 #include <ldsodefs.h>
29
30 #include <dl-dst.h>
31
32 /* Whether an shared object references one or more auxiliary objects
33    is signaled by the AUXTAG entry in l_info.  */
34 #define AUXTAG  (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
35                  + DT_EXTRATAGIDX (DT_AUXILIARY))
36 /* Whether an shared object references one or more auxiliary objects
37    is signaled by the AUXTAG entry in l_info.  */
38 #define FILTERTAG (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \
39                    + DT_EXTRATAGIDX (DT_FILTER))
40
41 /* This is zero at program start to signal that the global scope map is
42    allocated by rtld.  Later it keeps the size of the map.  It might be
43    reset if in _dl_close if the last global object is removed.  */
44 size_t _dl_global_scope_alloc;
45
46 extern size_t _dl_platformlen;
47
48 /* When loading auxiliary objects we must ignore errors.  It's ok if
49    an object is missing.  */
50 struct openaux_args
51   {
52     /* The arguments to openaux.  */
53     struct link_map *map;
54     int trace_mode;
55     const char *strtab;
56     const char *name;
57
58     /* The return value of openaux.  */
59     struct link_map *aux;
60   };
61
62 static void
63 openaux (void *a)
64 {
65   struct openaux_args *args = (struct openaux_args *) a;
66
67   args->aux = _dl_map_object (args->map, args->name, 0,
68                               (args->map->l_type == lt_executable
69                                ? lt_library : args->map->l_type),
70                               args->trace_mode, 0);
71 }
72
73
74
75 /* We use a very special kind of list to track the two kinds paths
76    through the list of loaded shared objects.  We have to
77
78    - produce a flat list with unique members of all involved objects
79
80    - produce a flat list of all shared objects.
81 */
82 struct list
83   {
84     int done;                   /* Nonzero if this map was processed.  */
85     struct link_map *map;       /* The data.  */
86
87     struct list *unique;        /* Elements for normal list.  */
88     struct list *dup;           /* Elements in complete list.  */
89   };
90
91
92 /* Macro to expand DST.  It is an macro since we use `alloca'.  */
93 #define expand_dst(l, str, fatal) \
94   ({                                                                          \
95     const char *__str = (str);                                                \
96     const char *__result = __str;                                             \
97     size_t __cnt = DL_DST_COUNT(__str, 0);                                    \
98                                                                               \
99     if (__cnt != 0)                                                           \
100       {                                                                       \
101         char *__newp;                                                         \
102                                                                               \
103         /* DST must not appear in SUID/SGID programs.  */                     \
104         if (__libc_enable_secure)                                             \
105           _dl_signal_error (0, __str,                                         \
106                             N_("DST not allowed in SUID/SGID programs"));     \
107                                                                               \
108         __newp = (char *) alloca (DL_DST_REQUIRED (l, __str, strlen (__str),  \
109                                                    __cnt));                   \
110                                                                               \
111         __result = DL_DST_SUBSTITUTE (l, __str, __newp, 0);                   \
112                                                                               \
113         if (*__result == '\0')                                                \
114           {                                                                   \
115             /* The replacement for the DST is not known.  We can't            \
116                processed.  */                                                 \
117             if (fatal)                                                        \
118               _dl_signal_error (0, __str, N_("\
119 empty dynamics string token substitution"));                                  \
120             else                                                              \
121               {                                                               \
122                 /* This is for DT_AUXILIARY.  */                              \
123                 if (__builtin_expect (_dl_debug_libs, 0))                     \
124                   _dl_debug_message (1, "cannot load auxiliary `", __str,     \
125                                      "' because of empty dynamic string"      \
126                                      " token substitution\n", NULL);          \
127                 continue;                                                     \
128               }                                                               \
129           }                                                                   \
130       }                                                                       \
131                                                                               \
132     __result; })
133
134
135 void
136 internal_function
137 _dl_map_object_deps (struct link_map *map,
138                      struct link_map **preloads, unsigned int npreloads,
139                      int trace_mode)
140 {
141   struct list known[1 + npreloads + 1];
142   struct list *runp, *utail, *dtail;
143   unsigned int nlist, nduplist, i;
144
145   inline void preload (struct link_map *map)
146     {
147       known[nlist].done = 0;
148       known[nlist].map = map;
149
150       known[nlist].unique = &known[nlist + 1];
151       known[nlist].dup = &known[nlist + 1];
152
153       ++nlist;
154       /* We use `l_reserved' as a mark bit to detect objects we have
155          already put in the search list and avoid adding duplicate
156          elements later in the list.  */
157       map->l_reserved = 1;
158     }
159
160   /* No loaded object so far.  */
161   nlist = 0;
162
163   /* First load MAP itself.  */
164   preload (map);
165
166   /* Add the preloaded items after MAP but before any of its dependencies.  */
167   for (i = 0; i < npreloads; ++i)
168     preload (preloads[i]);
169
170   /* Terminate the lists.  */
171   known[nlist - 1].unique = NULL;
172   known[nlist - 1].dup = NULL;
173
174   /* Pointer to last unique object.  */
175   utail = &known[nlist - 1];
176   /* Pointer to last loaded object.  */
177   dtail = &known[nlist - 1];
178
179   /* Until now we have the same number of libraries in the normal and
180      the list with duplicates.  */
181   nduplist = nlist;
182
183   /* Process each element of the search list, loading each of its
184      auxiliary objects and immediate dependencies.  Auxiliary objects
185      will be added in the list before the object itself and
186      dependencies will be appended to the list as we step through it.
187      This produces a flat, ordered list that represents a
188      breadth-first search of the dependency tree.
189
190      The whole process is complicated by the fact that we better
191      should use alloca for the temporary list elements.  But using
192      alloca means we cannot use recursive function calls.  */
193   for (runp = known; runp; )
194     {
195       struct link_map *l = runp->map;
196       struct link_map **needed = NULL;
197       unsigned int nneeded = 0;
198
199       /* Unless otherwise stated, this object is handled.  */
200       runp->done = 1;
201
202       /* Allocate a temporary record to contain the references to the
203          dependencies of this object.  */
204       if (l->l_searchlist.r_list == NULL && l->l_initfini == NULL
205           && l != map && l->l_ldnum > 0)
206         needed = (struct link_map **) alloca (l->l_ldnum
207                                               * sizeof (struct link_map *));
208
209       if (l->l_info[DT_NEEDED] || l->l_info[AUXTAG] || l->l_info[FILTERTAG])
210         {
211           const char *strtab = (const void *) D_PTR (l, l_info[DT_STRTAB]);
212           struct openaux_args args;
213           struct list *orig;
214           const ElfW(Dyn) *d;
215
216           args.strtab = strtab;
217           args.map = l;
218           args.trace_mode = trace_mode;
219           orig = runp;
220
221           for (d = l->l_ld; d->d_tag != DT_NULL; ++d)
222             if (__builtin_expect (d->d_tag, DT_NEEDED) == DT_NEEDED)
223               {
224                 /* Map in the needed object.  */
225                 struct link_map *dep;
226                 /* Allocate new entry.  */
227                 struct list *newp;
228                 /* Object name.  */
229                 const char *name;
230
231                 /* Recognize DSTs.  */
232                 name = expand_dst (l, strtab + d->d_un.d_val, 0);
233
234                 dep = _dl_map_object (l, name, 0,
235                                       l->l_type == lt_executable ? lt_library :
236                                       l->l_type, trace_mode, 0);
237
238                 /* Add it in any case to the duplicate list.  */
239                 newp = alloca (sizeof (struct list));
240                 newp->map = dep;
241                 newp->dup = NULL;
242                 dtail->dup = newp;
243                 dtail = newp;
244                 ++nduplist;
245
246                 if (dep->l_reserved)
247                   {
248                     /* This object is already in the search list we are
249                        building.  Don't add a duplicate pointer.
250                        Release the reference just added by
251                        _dl_map_object.  */
252                     if (dep->l_initfini != NULL)
253                       for (i = 1; dep->l_initfini[i] != NULL; ++i)
254                         --dep->l_initfini[i]->l_opencount;
255                     --dep->l_opencount;
256                   }
257                 else
258                   {
259                     /* Append DEP to the unique list.  */
260                     newp->done = 0;
261                     newp->unique = NULL;
262                     utail->unique = newp;
263                     utail = newp;
264                     ++nlist;
265                     /* Set the mark bit that says it's already in the list.  */
266                     dep->l_reserved = 1;
267                   }
268
269                 /* Remember this dependency.  */
270                 if (needed != NULL)
271                   needed[nneeded++] = dep;
272               }
273             else if (d->d_tag == DT_AUXILIARY || d->d_tag == DT_FILTER)
274               {
275                 const char *objname;
276                 const char *errstring;
277                 struct list *newp;
278                 /* Object name.  */
279                 const char *name;
280
281                 /* Recognize DSTs.  */
282                 name = expand_dst (l, strtab + d->d_un.d_val,
283                                    d->d_tag == DT_AUXILIARY);
284
285                 if (d->d_tag == DT_AUXILIARY)
286                   {
287                     /* Store the tag in the argument structure.  */
288                     args.name = name;
289
290                     /* Say that we are about to load an auxiliary library.  */
291                     if (__builtin_expect (_dl_debug_libs, 0))
292                       _dl_debug_message (1, "load auxiliary object=",
293                                          name, " requested by file=",
294                                          l->l_name[0]
295                                          ? l->l_name : _dl_argv[0],
296                                          "\n", NULL);
297
298                     /* We must be prepared that the addressed shared
299                        object is not available.  */
300                     if (_dl_catch_error (&objname, &errstring, openaux, &args))
301                       {
302                         /* We are not interested in the error message.  */
303                         assert (errstring != NULL);
304                         if (errstring != _dl_out_of_memory)
305                           free ((char *) errstring);
306
307                         /* Simply ignore this error and continue the work.  */
308                         continue;
309                       }
310                   }
311                 else
312                   {
313                     /* Say that we are about to load an auxiliary library.  */
314                     if (__builtin_expect (_dl_debug_libs, 0))
315                       _dl_debug_message (1, "load filtered object=", name,
316                                          " requested by file=",
317                                          l->l_name[0]
318                                          ? l->l_name : _dl_argv[0],
319                                          "\n", NULL);
320
321                     /* For filter objects the dependency must be available.  */
322                     args.aux = _dl_map_object (l, name, 0,
323                                                (l->l_type == lt_executable
324                                                 ? lt_library : l->l_type),
325                                                trace_mode, 0);
326                   }
327
328                 /* The auxiliary object is actually available.
329                    Incorporate the map in all the lists.  */
330
331                 /* Allocate new entry.  This always has to be done.  */
332                 newp = alloca (sizeof (struct list));
333
334                 /* We want to insert the new map before the current one,
335                    but we have no back links.  So we copy the contents of
336                    the current entry over.  Note that ORIG and NEWP now
337                    have switched their meanings.  */
338                 orig->dup = memcpy (newp, orig, sizeof (*newp));
339
340                 /* Initialize new entry.  */
341                 orig->done = 0;
342                 orig->map = args.aux;
343
344                 /* Remember this dependency.  */
345                 if (needed != NULL)
346                   needed[nneeded++] = args.aux;
347
348                 /* We must handle two situations here: the map is new,
349                    so we must add it in all three lists.  If the map
350                    is already known, we have two further possibilities:
351                    - if the object is before the current map in the
352                    search list, we do nothing.  It is already found
353                    early
354                    - if the object is after the current one, we must
355                    move it just before the current map to make sure
356                    the symbols are found early enough
357                 */
358                 if (args.aux->l_reserved)
359                   {
360                     /* The object is already somewhere in the list.
361                        Locate it first.  */
362                     struct list *late;
363
364                     /* This object is already in the search list we
365                        are building.  Don't add a duplicate pointer.
366                        Release the reference just added by
367                        _dl_map_object.  */
368                     if (args.aux->l_initfini != NULL)
369                       for (i = 1; args.aux->l_initfini[i] != NULL; ++i)
370                         --args.aux->l_initfini[i]->l_opencount;
371                     --args.aux->l_opencount;
372
373                     for (late = newp; late->unique; late = late->unique)
374                       if (late->unique->map == args.aux)
375                         break;
376
377                     if (late->unique)
378                       {
379                         /* The object is somewhere behind the current
380                            position in the search path.  We have to
381                            move it to this earlier position.  */
382                         orig->unique = newp;
383
384                         /* Now remove the later entry from the unique list
385                            and adjust the tail pointer.  */
386                         if (utail == late->unique)
387                           utail = late;
388                         late->unique = late->unique->unique;
389
390                         /* We must move the object earlier in the chain.  */
391                         if (args.aux->l_prev)
392                           args.aux->l_prev->l_next = args.aux->l_next;
393                         if (args.aux->l_next)
394                           args.aux->l_next->l_prev = args.aux->l_prev;
395
396                         args.aux->l_prev = newp->map->l_prev;
397                         newp->map->l_prev = args.aux;
398                         if (args.aux->l_prev != NULL)
399                           args.aux->l_prev->l_next = args.aux;
400                         args.aux->l_next = newp->map;
401                       }
402                     else
403                       {
404                         /* The object must be somewhere earlier in the
405                            list.  That's good, we only have to insert
406                            an entry for the duplicate list.  */
407                         orig->unique = NULL;    /* Never used.  */
408
409                         /* Now we have a problem.  The element
410                            pointing to ORIG in the unique list must
411                            point to NEWP now.  This is the only place
412                            where we need this backreference and this
413                            situation is really not that frequent.  So
414                            we don't use a double-linked list but
415                            instead search for the preceding element.  */
416                         late = known;
417                         while (late->unique != orig)
418                           late = late->unique;
419                         late->unique = newp;
420                       }
421                   }
422                 else
423                   {
424                     /* This is easy.  We just add the symbol right here.  */
425                     orig->unique = newp;
426                     ++nlist;
427                     /* Set the mark bit that says it's already in the list.  */
428                     args.aux->l_reserved = 1;
429
430                     /* The only problem is that in the double linked
431                        list of all objects we don't have this new
432                        object at the correct place.  Correct this here.  */
433                     if (args.aux->l_prev)
434                       args.aux->l_prev->l_next = args.aux->l_next;
435                     if (args.aux->l_next)
436                       args.aux->l_next->l_prev = args.aux->l_prev;
437
438                     args.aux->l_prev = newp->map->l_prev;
439                     newp->map->l_prev = args.aux;
440                     if (args.aux->l_prev != NULL)
441                       args.aux->l_prev->l_next = args.aux;
442                     args.aux->l_next = newp->map;
443                   }
444
445                 /* Move the tail pointers if necessary.  */
446                 if (orig == utail)
447                   utail = newp;
448                 if (orig == dtail)
449                   dtail = newp;
450
451                 /* Move on the insert point.  */
452                 orig = newp;
453
454                 /* We always add an entry to the duplicate list.  */
455                 ++nduplist;
456               }
457         }
458
459       /* Terminate the list of dependencies and store the array address.  */
460       if (needed != NULL)
461         {
462           needed[nneeded++] = NULL;
463
464           l->l_initfini = malloc (nneeded * sizeof needed[0]);
465           if (l->l_initfini == NULL)
466             _dl_signal_error (ENOMEM, map->l_name,
467                               N_("cannot allocate dependency list"));
468           memcpy (l->l_initfini, needed, nneeded * sizeof needed[0]);
469         }
470
471       /* If we have no auxiliary objects just go on to the next map.  */
472       if (runp->done)
473         do
474           runp = runp->unique;
475         while (runp != NULL && runp->done);
476     }
477
478   if (map->l_initfini != NULL && map->l_type == lt_loaded)
479     {
480       /* This object was previously loaded as a dependency and we have
481          a separate l_initfini list.  We don't need it anymore.  */
482       assert (map->l_searchlist.r_list == NULL);
483       free (map->l_initfini);
484     }
485
486   /* Store the search list we built in the object.  It will be used for
487      searches in the scope of this object.  */
488   map->l_searchlist.r_list = malloc ((2 * nlist + 1
489                                       + (nlist == nduplist ? 0 : nduplist))
490                                      * sizeof (struct link_map *));
491   if (map->l_searchlist.r_list == NULL)
492     _dl_signal_error (ENOMEM, map->l_name,
493                       N_("cannot allocate symbol search list"));
494   map->l_searchlist.r_nlist = nlist;
495
496   for (nlist = 0, runp = known; runp; runp = runp->unique)
497     {
498       if (trace_mode && runp->map->l_opencount == 0)
499         /* This can happen when we trace the loading.  */
500         --map->l_searchlist.r_nlist;
501       else
502         map->l_searchlist.r_list[nlist++] = runp->map;
503
504       /* Now clear all the mark bits we set in the objects on the search list
505          to avoid duplicates, so the next call starts fresh.  */
506       runp->map->l_reserved = 0;
507     }
508
509   map->l_searchlist.r_nduplist = nduplist;
510   if (nlist == nduplist)
511     map->l_searchlist.r_duplist = map->l_searchlist.r_list;
512   else
513     {
514       unsigned int cnt;
515
516       map->l_searchlist.r_duplist = map->l_searchlist.r_list + nlist;
517
518       for (cnt = 0, runp = known; runp; runp = runp->dup)
519         if (trace_mode && runp->map->l_opencount == 0)
520           /* This can happen when we trace the loading.  */
521           --map->l_searchlist.r_nduplist;
522         else
523           map->l_searchlist.r_duplist[cnt++] = runp->map;
524     }
525
526   /* Now determine the order in which the initialization has to happen.  */
527   map->l_initfini =
528     (struct link_map **) memcpy (map->l_searchlist.r_duplist + nduplist,
529                                  map->l_searchlist.r_list,
530                                  nlist * sizeof (struct link_map *));
531   /* We can skip looking for the binary itself which is at the front
532      of the search list.  Look through the list backward so that circular
533      dependencies are not changing the order.  */
534   for (i = 1; i < nlist; ++i)
535     {
536       struct link_map *l = map->l_searchlist.r_list[i];
537       unsigned int j;
538       unsigned int k;
539
540       /* Find the place in the initfini list where the map is currently
541          located.  */
542       for (j = 1; map->l_initfini[j] != l; ++j)
543         ;
544
545       /* Find all object for which the current one is a dependency and
546          move the found object (if necessary) in front.  */
547       for (k = j + 1; k < nlist; ++k)
548         {
549           struct link_map **runp;
550
551           runp = map->l_initfini[k]->l_initfini;
552           if (runp != NULL)
553             {
554               while (*runp != NULL)
555                 if (*runp == l)
556                   {
557                     struct link_map *here = map->l_initfini[k];
558
559                     /* Move it now.  */
560                     memmove (&map->l_initfini[j] + 1,
561                              &map->l_initfini[j],
562                              (k - j) * sizeof (struct link_map *));
563                     map->l_initfini[j] = here;
564
565                     break;
566                   }
567                 else
568                   ++runp;
569             }
570         }
571     }
572   /* Terminate the list of dependencies.  */
573   map->l_initfini[nlist] = NULL;
574 }