Move shared umount.c from hppa to mips.
[jlayton/glibc.git] / ports / sysdeps / mips / dl-lookup.c
1 /* Look up a symbol in the loaded objects.
2    MIPS/Linux version - special handling of non-PIC undefined symbol rules.
3    Copyright (C) 1995-2014 Free Software Foundation, Inc.
4    This file is part of the GNU C Library.
5
6    The GNU C Library is free software; you can redistribute it and/or
7    modify it under the terms of the GNU Lesser General Public
8    License as published by the Free Software Foundation; either
9    version 2.1 of the License, or (at your option) any later version.
10
11    The GNU C Library is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14    Lesser General Public License for more details.
15
16    You should have received a copy of the GNU Lesser General Public
17    License along with the GNU C Library; if not, see
18    <http://www.gnu.org/licenses/>.  */
19
20 #include <alloca.h>
21 #include <libintl.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <unistd.h>
25 #include <ldsodefs.h>
26 #include <dl-hash.h>
27 #include <dl-machine.h>
28 #include <sysdep-cancel.h>
29 #include <bits/libc-lock.h>
30 #include <tls.h>
31 #include <atomic.h>
32
33 #include <assert.h>
34
35 #define VERSTAG(tag)    (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX (tag))
36
37 /* We need this string more than once.  */
38 static const char undefined_msg[] = "undefined symbol: ";
39
40
41 struct sym_val
42   {
43     const ElfW(Sym) *s;
44     struct link_map *m;
45   };
46
47
48 #define make_string(string, rest...) \
49   ({                                                                          \
50     const char *all[] = { string, ## rest };                                  \
51     size_t len, cnt;                                                          \
52     char *result, *cp;                                                        \
53                                                                               \
54     len = 1;                                                                  \
55     for (cnt = 0; cnt < sizeof (all) / sizeof (all[0]); ++cnt)                \
56       len += strlen (all[cnt]);                                               \
57                                                                               \
58     cp = result = alloca (len);                                               \
59     for (cnt = 0; cnt < sizeof (all) / sizeof (all[0]); ++cnt)                \
60       cp = __stpcpy (cp, all[cnt]);                                           \
61                                                                               \
62     result;                                                                   \
63   })
64
65 /* Statistics function.  */
66 #ifdef SHARED
67 # define bump_num_relocations() ++GL(dl_num_relocations)
68 #else
69 # define bump_num_relocations() ((void) 0)
70 #endif
71
72
73 /* Inner part of the lookup functions.  We return a value > 0 if we
74    found the symbol, the value 0 if nothing is found and < 0 if
75    something bad happened.  */
76 static int
77 __attribute_noinline__
78 do_lookup_x (const char *undef_name, uint_fast32_t new_hash,
79              unsigned long int *old_hash, const ElfW(Sym) *ref,
80              struct sym_val *result, struct r_scope_elem *scope, size_t i,
81              const struct r_found_version *const version, int flags,
82              struct link_map *skip, int type_class, struct link_map *undef_map)
83 {
84   size_t n = scope->r_nlist;
85   /* Make sure we read the value before proceeding.  Otherwise we
86      might use r_list pointing to the initial scope and r_nlist being
87      the value after a resize.  That is the only path in dl-open.c not
88      protected by GSCOPE.  A read barrier here might be to expensive.  */
89   __asm volatile ("" : "+r" (n), "+m" (scope->r_list));
90   struct link_map **list = scope->r_list;
91
92   do
93     {
94       /* These variables are used in the nested function.  */
95       Elf_Symndx symidx;
96       int num_versions = 0;
97       const ElfW(Sym) *versioned_sym = NULL;
98
99       const struct link_map *map = list[i]->l_real;
100
101       /* Here come the extra test needed for `_dl_lookup_symbol_skip'.  */
102       if (map == skip)
103         continue;
104
105       /* Don't search the executable when resolving a copy reloc.  */
106       if ((type_class & ELF_RTYPE_CLASS_COPY) && map->l_type == lt_executable)
107         continue;
108
109       /* Do not look into objects which are going to be removed.  */
110       if (map->l_removed)
111         continue;
112
113       /* Print some debugging info if wanted.  */
114       if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_SYMBOLS, 0))
115         _dl_debug_printf ("symbol=%s;  lookup in file=%s [%lu]\n",
116                           undef_name, DSO_FILENAME (map->l_name),
117                           map->l_ns);
118
119       /* If the hash table is empty there is nothing to do here.  */
120       if (map->l_nbuckets == 0)
121         continue;
122
123       /* The tables for this map.  */
124       const ElfW(Sym) *symtab = (const void *) D_PTR (map, l_info[DT_SYMTAB]);
125       const char *strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]);
126
127
128       /* Nested routine to check whether the symbol matches.  */
129       const ElfW(Sym) *
130       __attribute_noinline__
131       check_match (const ElfW(Sym) *sym)
132       {
133         unsigned int stt = ELFW(ST_TYPE) (sym->st_info);
134         assert (ELF_RTYPE_CLASS_PLT == 1);
135         /* The semantics of zero/non-zero values of undefined symbols
136            differs depending on whether the non-PIC ABI is in use.
137            Under the non-PIC ABI, a non-zero value indicates that
138            there is an address reference to the symbol and thus it
139            must always be resolved (except when resolving a jump slot
140            relocation) to the PLT entry whose address is provided as
141            the symbol's value; a zero value indicates that this
142            canonical-address behaviour is not required.  Yet under the
143            classic MIPS psABI, a zero value indicates that there is an
144            address reference to the function and the dynamic linker
145            must resolve the symbol immediately upon loading.  To avoid
146            conflict, symbols for which the dynamic linker must assume
147            the non-PIC ABI semantics are marked with the STO_MIPS_PLT
148            flag.  */
149         if (__builtin_expect ((sym->st_value == 0 /* No value.  */
150                                && stt != STT_TLS)
151                               || (sym->st_shndx == SHN_UNDEF
152                                   && !(sym->st_other & STO_MIPS_PLT))
153                               || (type_class & (sym->st_shndx == SHN_UNDEF)),
154                               0))
155           return NULL;
156
157         /* Ignore all but STT_NOTYPE, STT_OBJECT, STT_FUNC,
158            STT_COMMON, STT_TLS, and STT_GNU_IFUNC since these are no
159            code/data definitions.  */
160 #define ALLOWED_STT \
161         ((1 << STT_NOTYPE) | (1 << STT_OBJECT) | (1 << STT_FUNC) \
162          | (1 << STT_COMMON) | (1 << STT_TLS) | (1 << STT_GNU_IFUNC))
163         if (__builtin_expect (((1 << stt) & ALLOWED_STT) == 0, 0))
164           return NULL;
165
166         if (sym != ref && strcmp (strtab + sym->st_name, undef_name))
167           /* Not the symbol we are looking for.  */
168           return NULL;
169
170         const ElfW(Half) *verstab = map->l_versyms;
171         if (version != NULL)
172           {
173             if (__builtin_expect (verstab == NULL, 0))
174               {
175                 /* We need a versioned symbol but haven't found any.  If
176                    this is the object which is referenced in the verneed
177                    entry it is a bug in the library since a symbol must
178                    not simply disappear.
179
180                    It would also be a bug in the object since it means that
181                    the list of required versions is incomplete and so the
182                    tests in dl-version.c haven't found a problem.*/
183                 assert (version->filename == NULL
184                         || ! _dl_name_match_p (version->filename, map));
185
186                 /* Otherwise we accept the symbol.  */
187               }
188             else
189               {
190                 /* We can match the version information or use the
191                    default one if it is not hidden.  */
192                 ElfW(Half) ndx = verstab[symidx] & 0x7fff;
193                 if ((map->l_versions[ndx].hash != version->hash
194                      || strcmp (map->l_versions[ndx].name, version->name))
195                     && (version->hidden || map->l_versions[ndx].hash
196                         || (verstab[symidx] & 0x8000)))
197                   /* It's not the version we want.  */
198                   return NULL;
199               }
200           }
201         else
202           {
203             /* No specific version is selected.  There are two ways we
204                can got here:
205
206                - a binary which does not include versioning information
207                is loaded
208
209                - dlsym() instead of dlvsym() is used to get a symbol which
210                might exist in more than one form
211
212                If the library does not provide symbol version information
213                there is no problem at all: we simply use the symbol if it
214                is defined.
215
216                These two lookups need to be handled differently if the
217                library defines versions.  In the case of the old
218                unversioned application the oldest (default) version
219                should be used.  In case of a dlsym() call the latest and
220                public interface should be returned.  */
221             if (verstab != NULL)
222               {
223                 if ((verstab[symidx] & 0x7fff)
224                     >= ((flags & DL_LOOKUP_RETURN_NEWEST) ? 2 : 3))
225                   {
226                     /* Don't accept hidden symbols.  */
227                     if ((verstab[symidx] & 0x8000) == 0
228                         && num_versions++ == 0)
229                       /* No version so far.  */
230                       versioned_sym = sym;
231
232                     return NULL;
233                   }
234               }
235           }
236
237         /* There cannot be another entry for this symbol so stop here.  */
238         return sym;
239       }
240
241       const ElfW(Sym) *sym;
242       const ElfW(Addr) *bitmask = map->l_gnu_bitmask;
243       if (__builtin_expect (bitmask != NULL, 1))
244         {
245           ElfW(Addr) bitmask_word
246             = bitmask[(new_hash / __ELF_NATIVE_CLASS)
247                       & map->l_gnu_bitmask_idxbits];
248
249           unsigned int hashbit1 = new_hash & (__ELF_NATIVE_CLASS - 1);
250           unsigned int hashbit2 = ((new_hash >> map->l_gnu_shift)
251                                    & (__ELF_NATIVE_CLASS - 1));
252
253           if (__builtin_expect ((bitmask_word >> hashbit1)
254                                 & (bitmask_word >> hashbit2) & 1, 0))
255             {
256               Elf32_Word bucket = map->l_gnu_buckets[new_hash
257                                                      % map->l_nbuckets];
258               if (bucket != 0)
259                 {
260                   const Elf32_Word *hasharr = &map->l_gnu_chain_zero[bucket];
261
262                   do
263                     if (((*hasharr ^ new_hash) >> 1) == 0)
264                       {
265                         symidx = hasharr - map->l_gnu_chain_zero;
266                         sym = check_match (&symtab[symidx]);
267                         if (sym != NULL)
268                           goto found_it;
269                       }
270                   while ((*hasharr++ & 1u) == 0);
271                 }
272             }
273           /* No symbol found.  */
274           symidx = SHN_UNDEF;
275         }
276       else
277         {
278           if (*old_hash == 0xffffffff)
279             *old_hash = _dl_elf_hash (undef_name);
280
281           /* Use the old SysV-style hash table.  Search the appropriate
282              hash bucket in this object's symbol table for a definition
283              for the same symbol name.  */
284           for (symidx = map->l_buckets[*old_hash % map->l_nbuckets];
285                symidx != STN_UNDEF;
286                symidx = map->l_chain[symidx])
287             {
288               sym = check_match (&symtab[symidx]);
289               if (sym != NULL)
290                 goto found_it;
291             }
292         }
293
294       /* If we have seen exactly one versioned symbol while we are
295          looking for an unversioned symbol and the version is not the
296          default version we still accept this symbol since there are
297          no possible ambiguities.  */
298       sym = num_versions == 1 ? versioned_sym : NULL;
299
300       if (sym != NULL)
301         {
302         found_it:
303           switch (__builtin_expect (ELFW(ST_BIND) (sym->st_info), STB_GLOBAL))
304             {
305             case STB_WEAK:
306               /* Weak definition.  Use this value if we don't find another.  */
307               if (__builtin_expect (GLRO(dl_dynamic_weak), 0))
308                 {
309                   if (! result->s)
310                     {
311                       result->s = sym;
312                       result->m = (struct link_map *) map;
313                     }
314                   break;
315                 }
316               /* FALLTHROUGH */
317             case STB_GLOBAL:
318             success:
319               /* Global definition.  Just what we need.  */
320               result->s = sym;
321               result->m = (struct link_map *) map;
322               return 1;
323
324             case STB_GNU_UNIQUE:;
325               /* We have to determine whether we already found a
326                  symbol with this name before.  If not then we have to
327                  add it to the search table.  If we already found a
328                  definition we have to use it.  */
329               void enter (struct unique_sym *table, size_t size,
330                           unsigned int hash, const char *name,
331                           const ElfW(Sym) *sym, const struct link_map *map)
332               {
333                 size_t idx = hash % size;
334                 size_t hash2 = 1 + hash % (size - 2);
335                 while (table[idx].name != NULL)
336                   {
337                     idx += hash2;
338                     if (idx >= size)
339                       idx -= size;
340                   }
341
342                 table[idx].hashval = hash;
343                 table[idx].name = name;
344                 table[idx].sym = sym;
345                 table[idx].map = map;
346               }
347
348               struct unique_sym_table *tab
349                 = &GL(dl_ns)[map->l_ns]._ns_unique_sym_table;
350
351               __rtld_lock_lock_recursive (tab->lock);
352
353               struct unique_sym *entries = tab->entries;
354               size_t size = tab->size;
355               if (entries != NULL)
356                 {
357                   size_t idx = new_hash % size;
358                   size_t hash2 = 1 + new_hash % (size - 2);
359                   while (1)
360                     {
361                       if (entries[idx].hashval == new_hash
362                           && strcmp (entries[idx].name, undef_name) == 0)
363                         {
364                           if ((type_class & ELF_RTYPE_CLASS_COPY) != 0)
365                             {
366                               /* We possibly have to initialize the central
367                                  copy from the copy addressed through the
368                                  relocation.  */
369                               result->s = sym;
370                               result->m = (struct link_map *) map;
371                             }
372                           else
373                             {
374                               result->s = entries[idx].sym;
375                               result->m = (struct link_map *) entries[idx].map;
376                             }
377                           __rtld_lock_unlock_recursive (tab->lock);
378                           return 1;
379                         }
380
381                       if (entries[idx].name == NULL)
382                         break;
383
384                       idx += hash2;
385                       if (idx >= size)
386                         idx -= size;
387                     }
388
389                   if (size * 3 <= tab->n_elements * 4)
390                     {
391                       /* Expand the table.  */
392 #ifdef RTLD_CHECK_FOREIGN_CALL
393                       /* This must not happen during runtime relocations.  */
394                       assert (!RTLD_CHECK_FOREIGN_CALL);
395 #endif
396                       size_t newsize = _dl_higher_prime_number (size + 1);
397                       struct unique_sym *newentries
398                         = calloc (sizeof (struct unique_sym), newsize);
399                       if (newentries == NULL)
400                         {
401                         nomem:
402                           __rtld_lock_unlock_recursive (tab->lock);
403                           _dl_fatal_printf ("out of memory\n");
404                         }
405
406                       for (idx = 0; idx < size; ++idx)
407                         if (entries[idx].name != NULL)
408                           enter (newentries, newsize, entries[idx].hashval,
409                                  entries[idx].name, entries[idx].sym,
410                                  entries[idx].map);
411
412                       tab->free (entries);
413                       tab->size = newsize;
414                       size = newsize;
415                       entries = tab->entries = newentries;
416                       tab->free = free;
417                     }
418                 }
419               else
420                 {
421 #ifdef RTLD_CHECK_FOREIGN_CALL
422                   /* This must not happen during runtime relocations.  */
423                   assert (!RTLD_CHECK_FOREIGN_CALL);
424 #endif
425
426 #ifdef SHARED
427                   /* If tab->entries is NULL, but tab->size is not, it means
428                      this is the second, conflict finding, lookup for
429                      LD_TRACE_PRELINKING in _dl_debug_bindings.  Don't
430                      allocate anything and don't enter anything into the
431                      hash table.  */
432                   if (__builtin_expect (tab->size, 0))
433                     {
434                       assert (GLRO(dl_debug_mask) & DL_DEBUG_PRELINK);
435                       __rtld_lock_unlock_recursive (tab->lock);
436                       goto success;
437                     }
438 #endif
439
440 #define INITIAL_NUNIQUE_SYM_TABLE 31
441                   size = INITIAL_NUNIQUE_SYM_TABLE;
442                   entries = calloc (sizeof (struct unique_sym), size);
443                   if (entries == NULL)
444                     goto nomem;
445
446                   tab->entries = entries;
447                   tab->size = size;
448                   tab->free = free;
449                 }
450
451               if ((type_class & ELF_RTYPE_CLASS_COPY) != 0)
452                 enter (entries, size, new_hash, strtab + sym->st_name, ref,
453                        undef_map);
454               else
455                 {
456                   enter (entries, size, new_hash, strtab + sym->st_name, sym,
457                          map);
458
459                   if (map->l_type == lt_loaded)
460                     /* Make sure we don't unload this object by
461                        setting the appropriate flag.  */
462                     ((struct link_map *) map)->l_flags_1 |= DF_1_NODELETE;
463                 }
464               ++tab->n_elements;
465
466               __rtld_lock_unlock_recursive (tab->lock);
467
468               goto success;
469
470             default:
471               /* Local symbols are ignored.  */
472               break;
473             }
474         }
475
476       /* If this current map is the one mentioned in the verneed entry
477          and we have not found a weak entry, it is a bug.  */
478       if (symidx == STN_UNDEF && version != NULL && version->filename != NULL
479           && __builtin_expect (_dl_name_match_p (version->filename, map), 0))
480         return -1;
481     }
482   while (++i < n);
483
484   /* We have not found anything until now.  */
485   return 0;
486 }
487
488
489 static uint_fast32_t
490 dl_new_hash (const char *s)
491 {
492   uint_fast32_t h = 5381;
493   for (unsigned char c = *s; c != '\0'; c = *++s)
494     h = h * 33 + c;
495   return h & 0xffffffff;
496 }
497
498
499 /* Add extra dependency on MAP to UNDEF_MAP.  */
500 static int
501 internal_function
502 add_dependency (struct link_map *undef_map, struct link_map *map, int flags)
503 {
504   struct link_map *runp;
505   unsigned int i;
506   int result = 0;
507
508   /* Avoid self-references and references to objects which cannot be
509      unloaded anyway.  */
510   if (undef_map == map)
511     return 0;
512
513   /* Avoid references to objects which cannot be unloaded anyway.  */
514   assert (map->l_type == lt_loaded);
515   if ((map->l_flags_1 & DF_1_NODELETE) != 0)
516     return 0;
517
518   struct link_map_reldeps *l_reldeps
519     = atomic_forced_read (undef_map->l_reldeps);
520
521   /* Make sure l_reldeps is read before l_initfini.  */
522   atomic_read_barrier ();
523
524   /* Determine whether UNDEF_MAP already has a reference to MAP.  First
525      look in the normal dependencies.  */
526   struct link_map **l_initfini = atomic_forced_read (undef_map->l_initfini);
527   if (l_initfini != NULL)
528     {
529       for (i = 0; l_initfini[i] != NULL; ++i)
530         if (l_initfini[i] == map)
531           return 0;
532     }
533
534   /* No normal dependency.  See whether we already had to add it
535      to the special list of dynamic dependencies.  */
536   unsigned int l_reldepsact = 0;
537   if (l_reldeps != NULL)
538     {
539       struct link_map **list = &l_reldeps->list[0];
540       l_reldepsact = l_reldeps->act;
541       for (i = 0; i < l_reldepsact; ++i)
542         if (list[i] == map)
543           return 0;
544     }
545
546   /* Save serial number of the target MAP.  */
547   unsigned long long serial = map->l_serial;
548
549   /* Make sure nobody can unload the object while we are at it.  */
550   if (__builtin_expect (flags & DL_LOOKUP_GSCOPE_LOCK, 0))
551     {
552       /* We can't just call __rtld_lock_lock_recursive (GL(dl_load_lock))
553          here, that can result in ABBA deadlock.  */
554       THREAD_GSCOPE_RESET_FLAG ();
555       __rtld_lock_lock_recursive (GL(dl_load_lock));
556       /* While MAP value won't change, after THREAD_GSCOPE_RESET_FLAG ()
557          it can e.g. point to unallocated memory.  So avoid the optimizer
558          treating the above read from MAP->l_serial as ensurance it
559          can safely dereference it.  */
560       map = atomic_forced_read (map);
561
562       /* From this point on it is unsafe to dereference MAP, until it
563          has been found in one of the lists.  */
564
565       /* Redo the l_initfini check in case undef_map's l_initfini
566          changed in the mean time.  */
567       if (undef_map->l_initfini != l_initfini
568           && undef_map->l_initfini != NULL)
569         {
570           l_initfini = undef_map->l_initfini;
571           for (i = 0; l_initfini[i] != NULL; ++i)
572             if (l_initfini[i] == map)
573               goto out_check;
574         }
575
576       /* Redo the l_reldeps check if undef_map's l_reldeps changed in
577          the mean time.  */
578       if (undef_map->l_reldeps != NULL)
579         {
580           if (undef_map->l_reldeps != l_reldeps)
581             {
582               struct link_map **list = &undef_map->l_reldeps->list[0];
583               l_reldepsact = undef_map->l_reldeps->act;
584               for (i = 0; i < l_reldepsact; ++i)
585                 if (list[i] == map)
586                   goto out_check;
587             }
588           else if (undef_map->l_reldeps->act > l_reldepsact)
589             {
590               struct link_map **list
591                 = &undef_map->l_reldeps->list[0];
592               i = l_reldepsact;
593               l_reldepsact = undef_map->l_reldeps->act;
594               for (; i < l_reldepsact; ++i)
595                 if (list[i] == map)
596                   goto out_check;
597             }
598         }
599     }
600   else
601     __rtld_lock_lock_recursive (GL(dl_load_lock));
602
603   /* The object is not yet in the dependency list.  Before we add
604      it make sure just one more time the object we are about to
605      reference is still available.  There is a brief period in
606      which the object could have been removed since we found the
607      definition.  */
608   runp = GL(dl_ns)[undef_map->l_ns]._ns_loaded;
609   while (runp != NULL && runp != map)
610     runp = runp->l_next;
611
612   if (runp != NULL)
613     {
614       /* The object is still available.  */
615
616       /* MAP could have been dlclosed, freed and then some other dlopened
617          library could have the same link_map pointer.  */
618       if (map->l_serial != serial)
619         goto out_check;
620
621       /* Redo the NODELETE check, as when dl_load_lock wasn't held
622          yet this could have changed.  */
623       if ((map->l_flags_1 & DF_1_NODELETE) != 0)
624         goto out;
625
626       /* If the object with the undefined reference cannot be removed ever
627          just make sure the same is true for the object which contains the
628          definition.  */
629       if (undef_map->l_type != lt_loaded
630           || (undef_map->l_flags_1 & DF_1_NODELETE) != 0)
631         {
632           map->l_flags_1 |= DF_1_NODELETE;
633           goto out;
634         }
635
636       /* Add the reference now.  */
637       if (__builtin_expect (l_reldepsact >= undef_map->l_reldepsmax, 0))
638         {
639           /* Allocate more memory for the dependency list.  Since this
640              can never happen during the startup phase we can use
641              `realloc'.  */
642           struct link_map_reldeps *newp;
643           unsigned int max
644             = undef_map->l_reldepsmax ? undef_map->l_reldepsmax * 2 : 10;
645
646 #ifdef RTLD_PREPARE_FOREIGN_CALL
647           RTLD_PREPARE_FOREIGN_CALL;
648 #endif
649
650           newp = malloc (sizeof (*newp) + max * sizeof (struct link_map *));
651           if (newp == NULL)
652             {
653               /* If we didn't manage to allocate memory for the list this is
654                  no fatal problem.  We simply make sure the referenced object
655                  cannot be unloaded.  This is semantically the correct
656                  behavior.  */
657               map->l_flags_1 |= DF_1_NODELETE;
658               goto out;
659             }
660           else
661             {
662               if (l_reldepsact)
663                 memcpy (&newp->list[0], &undef_map->l_reldeps->list[0],
664                         l_reldepsact * sizeof (struct link_map *));
665               newp->list[l_reldepsact] = map;
666               newp->act = l_reldepsact + 1;
667               atomic_write_barrier ();
668               void *old = undef_map->l_reldeps;
669               undef_map->l_reldeps = newp;
670               undef_map->l_reldepsmax = max;
671               if (old)
672                 _dl_scope_free (old);
673             }
674         }
675       else
676         {
677           undef_map->l_reldeps->list[l_reldepsact] = map;
678           atomic_write_barrier ();
679           undef_map->l_reldeps->act = l_reldepsact + 1;
680         }
681
682       /* Display information if we are debugging.  */
683       if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_FILES, 0))
684         _dl_debug_printf ("\
685 \nfile=%s [%lu];  needed by %s [%lu] (relocation dependency)\n\n",
686                           DSO_FILENAME (map->l_name),
687                           map->l_ns,
688                           DSO_FILENAME (undef_map->l_name),
689                           undef_map->l_ns);
690     }
691   else
692     /* Whoa, that was bad luck.  We have to search again.  */
693     result = -1;
694
695  out:
696   /* Release the lock.  */
697   __rtld_lock_unlock_recursive (GL(dl_load_lock));
698
699   if (__builtin_expect (flags & DL_LOOKUP_GSCOPE_LOCK, 0))
700     THREAD_GSCOPE_SET_FLAG ();
701
702   return result;
703
704  out_check:
705   if (map->l_serial != serial)
706     result = -1;
707   goto out;
708 }
709
710 static void
711 internal_function
712 _dl_debug_bindings (const char *undef_name, struct link_map *undef_map,
713                     const ElfW(Sym) **ref, struct sym_val *value,
714                     const struct r_found_version *version, int type_class,
715                     int protected);
716
717
718 /* Search loaded objects' symbol tables for a definition of the symbol
719    UNDEF_NAME, perhaps with a requested version for the symbol.
720
721    We must never have calls to the audit functions inside this function
722    or in any function which gets called.  If this would happen the audit
723    code might create a thread which can throw off all the scope locking.  */
724 lookup_t
725 internal_function
726 _dl_lookup_symbol_x (const char *undef_name, struct link_map *undef_map,
727                      const ElfW(Sym) **ref,
728                      struct r_scope_elem *symbol_scope[],
729                      const struct r_found_version *version,
730                      int type_class, int flags, struct link_map *skip_map)
731 {
732   const uint_fast32_t new_hash = dl_new_hash (undef_name);
733   unsigned long int old_hash = 0xffffffff;
734   struct sym_val current_value = { NULL, NULL };
735   struct r_scope_elem **scope = symbol_scope;
736
737   bump_num_relocations ();
738
739   /* No other flag than DL_LOOKUP_ADD_DEPENDENCY or DL_LOOKUP_GSCOPE_LOCK
740      is allowed if we look up a versioned symbol.  */
741   assert (version == NULL
742           || (flags & ~(DL_LOOKUP_ADD_DEPENDENCY | DL_LOOKUP_GSCOPE_LOCK))
743              == 0);
744
745   size_t i = 0;
746   if (__builtin_expect (skip_map != NULL, 0))
747     /* Search the relevant loaded objects for a definition.  */
748     while ((*scope)->r_list[i] != skip_map)
749       ++i;
750
751   /* Search the relevant loaded objects for a definition.  */
752   for (size_t start = i; *scope != NULL; start = 0, ++scope)
753     {
754       int res = do_lookup_x (undef_name, new_hash, &old_hash, *ref,
755                              &current_value, *scope, start, version, flags,
756                              skip_map, type_class, undef_map);
757       if (res > 0)
758         break;
759
760       if (__builtin_expect (res, 0) < 0 && skip_map == NULL)
761         {
762           /* Oh, oh.  The file named in the relocation entry does not
763              contain the needed symbol.  This code is never reached
764              for unversioned lookups.  */
765           assert (version != NULL);
766           const char *reference_name = undef_map ? undef_map->l_name : "";
767
768           /* XXX We cannot translate the message.  */
769           _dl_signal_cerror (0, DSO_FILENAME (reference_name),
770                              N_("relocation error"),
771                              make_string ("symbol ", undef_name, ", version ",
772                                           version->name,
773                                           " not defined in file ",
774                                           version->filename,
775                                           " with link time reference",
776                                           res == -2
777                                           ? " (no version symbols)" : ""));
778           *ref = NULL;
779           return 0;
780         }
781     }
782
783   if (__builtin_expect (current_value.s == NULL, 0))
784     {
785       if ((*ref == NULL || ELFW(ST_BIND) ((*ref)->st_info) != STB_WEAK)
786           && skip_map == NULL
787           && !(GLRO(dl_debug_mask) & DL_DEBUG_UNUSED))
788         {
789           /* We could find no value for a strong reference.  */
790           const char *reference_name = undef_map ? undef_map->l_name : "";
791           const char *versionstr = version ? ", version " : "";
792           const char *versionname = (version && version->name
793                                      ? version->name : "");
794
795           /* XXX We cannot translate the message.  */
796           _dl_signal_cerror (0, DSO_FILENAME (reference_name),
797                              N_("symbol lookup error"),
798                              make_string (undefined_msg, undef_name,
799                                           versionstr, versionname));
800         }
801       *ref = NULL;
802       return 0;
803     }
804
805   int protected = (*ref
806                    && ELFW(ST_VISIBILITY) ((*ref)->st_other) == STV_PROTECTED);
807   if (__builtin_expect (protected != 0, 0))
808     {
809       /* It is very tricky.  We need to figure out what value to
810          return for the protected symbol.  */
811       if (type_class == ELF_RTYPE_CLASS_PLT)
812         {
813           if (current_value.s != NULL && current_value.m != undef_map)
814             {
815               current_value.s = *ref;
816               current_value.m = undef_map;
817             }
818         }
819       else
820         {
821           struct sym_val protected_value = { NULL, NULL };
822
823           for (scope = symbol_scope; *scope != NULL; i = 0, ++scope)
824             if (do_lookup_x (undef_name, new_hash, &old_hash, *ref,
825                              &protected_value, *scope, i, version, flags,
826                              skip_map, ELF_RTYPE_CLASS_PLT, NULL) != 0)
827               break;
828
829           if (protected_value.s != NULL && protected_value.m != undef_map)
830             {
831               current_value.s = *ref;
832               current_value.m = undef_map;
833             }
834         }
835     }
836
837   /* We have to check whether this would bind UNDEF_MAP to an object
838      in the global scope which was dynamically loaded.  In this case
839      we have to prevent the latter from being unloaded unless the
840      UNDEF_MAP object is also unloaded.  */
841   if (__builtin_expect (current_value.m->l_type == lt_loaded, 0)
842       /* Don't do this for explicit lookups as opposed to implicit
843          runtime lookups.  */
844       && (flags & DL_LOOKUP_ADD_DEPENDENCY) != 0
845       /* Add UNDEF_MAP to the dependencies.  */
846       && add_dependency (undef_map, current_value.m, flags) < 0)
847       /* Something went wrong.  Perhaps the object we tried to reference
848          was just removed.  Try finding another definition.  */
849       return _dl_lookup_symbol_x (undef_name, undef_map, ref,
850                                   (flags & DL_LOOKUP_GSCOPE_LOCK)
851                                   ? undef_map->l_scope : symbol_scope,
852                                   version, type_class, flags, skip_map);
853
854   /* The object is used.  */
855   if (__builtin_expect (current_value.m->l_used == 0, 0))
856     current_value.m->l_used = 1;
857
858   if (__builtin_expect (GLRO(dl_debug_mask)
859                         & (DL_DEBUG_BINDINGS|DL_DEBUG_PRELINK), 0))
860     _dl_debug_bindings (undef_name, undef_map, ref,
861                         &current_value, version, type_class, protected);
862
863   *ref = current_value.s;
864   return LOOKUP_VALUE (current_value.m);
865 }
866
867
868 /* Cache the location of MAP's hash table.  */
869
870 void
871 internal_function
872 _dl_setup_hash (struct link_map *map)
873 {
874   Elf_Symndx *hash;
875
876   if (__builtin_expect (map->l_info[DT_ADDRTAGIDX (DT_GNU_HASH) + DT_NUM
877                                     + DT_THISPROCNUM + DT_VERSIONTAGNUM
878                                     + DT_EXTRANUM + DT_VALNUM] != NULL, 1))
879     {
880       Elf32_Word *hash32
881         = (void *) D_PTR (map, l_info[DT_ADDRTAGIDX (DT_GNU_HASH) + DT_NUM
882                                       + DT_THISPROCNUM + DT_VERSIONTAGNUM
883                                       + DT_EXTRANUM + DT_VALNUM]);
884       map->l_nbuckets = *hash32++;
885       Elf32_Word symbias = *hash32++;
886       Elf32_Word bitmask_nwords = *hash32++;
887       /* Must be a power of two.  */
888       assert ((bitmask_nwords & (bitmask_nwords - 1)) == 0);
889       map->l_gnu_bitmask_idxbits = bitmask_nwords - 1;
890       map->l_gnu_shift = *hash32++;
891
892       map->l_gnu_bitmask = (ElfW(Addr) *) hash32;
893       hash32 += __ELF_NATIVE_CLASS / 32 * bitmask_nwords;
894
895       map->l_gnu_buckets = hash32;
896       hash32 += map->l_nbuckets;
897       map->l_gnu_chain_zero = hash32 - symbias;
898       return;
899     }
900
901   if (!map->l_info[DT_HASH])
902     return;
903   hash = (void *) D_PTR (map, l_info[DT_HASH]);
904
905   map->l_nbuckets = *hash++;
906   /* Skip nchain.  */
907   hash++;
908   map->l_buckets = hash;
909   hash += map->l_nbuckets;
910   map->l_chain = hash;
911 }
912
913
914 static void
915 internal_function
916 _dl_debug_bindings (const char *undef_name, struct link_map *undef_map,
917                     const ElfW(Sym) **ref, struct sym_val *value,
918                     const struct r_found_version *version, int type_class,
919                     int protected)
920 {
921   const char *reference_name = undef_map->l_name;
922
923   if (GLRO(dl_debug_mask) & DL_DEBUG_BINDINGS)
924     {
925       _dl_debug_printf ("binding file %s [%lu] to %s [%lu]: %s symbol `%s'",
926                         DSO_FILENAME (reference_name),
927                         undef_map->l_ns,
928                         DSO_FILENAME (value->m->l_name),
929                         value->m->l_ns,
930                         protected ? "protected" : "normal", undef_name);
931       if (version)
932         _dl_debug_printf_c (" [%s]\n", version->name);
933       else
934         _dl_debug_printf_c ("\n");
935     }
936 #ifdef SHARED
937   if (GLRO(dl_debug_mask) & DL_DEBUG_PRELINK)
938     {
939       int conflict = 0;
940       struct sym_val val = { NULL, NULL };
941
942       if ((GLRO(dl_trace_prelink_map) == NULL
943            || GLRO(dl_trace_prelink_map) == GL(dl_ns)[LM_ID_BASE]._ns_loaded)
944           && undef_map != GL(dl_ns)[LM_ID_BASE]._ns_loaded)
945         {
946           const uint_fast32_t new_hash = dl_new_hash (undef_name);
947           unsigned long int old_hash = 0xffffffff;
948           struct unique_sym *saved_entries
949             = GL(dl_ns)[LM_ID_BASE]._ns_unique_sym_table.entries;
950
951           GL(dl_ns)[LM_ID_BASE]._ns_unique_sym_table.entries = NULL;
952           do_lookup_x (undef_name, new_hash, &old_hash, *ref, &val,
953                        undef_map->l_local_scope[0], 0, version, 0, NULL,
954                        type_class, undef_map);
955           if (val.s != value->s || val.m != value->m)
956             conflict = 1;
957           else if (__builtin_expect (undef_map->l_symbolic_in_local_scope, 0)
958                    && val.s
959                    && __builtin_expect (ELFW(ST_BIND) (val.s->st_info),
960                                         STB_GLOBAL) == STB_GNU_UNIQUE)
961             {
962               /* If it is STB_GNU_UNIQUE and undef_map's l_local_scope
963                  contains any DT_SYMBOLIC libraries, unfortunately there
964                  can be conflicts even if the above is equal.  As symbol
965                  resolution goes from the last library to the first and
966                  if a STB_GNU_UNIQUE symbol is found in some late DT_SYMBOLIC
967                  library, it would be the one that is looked up.  */
968               struct sym_val val2 = { NULL, NULL };
969               size_t n;
970               struct r_scope_elem *scope = undef_map->l_local_scope[0];
971
972               for (n = 0; n < scope->r_nlist; n++)
973                 if (scope->r_list[n] == val.m)
974                   break;
975
976               for (n++; n < scope->r_nlist; n++)
977                 if (scope->r_list[n]->l_info[DT_SYMBOLIC] != NULL
978                     && do_lookup_x (undef_name, new_hash, &old_hash, *ref,
979                                     &val2,
980                                     &scope->r_list[n]->l_symbolic_searchlist,
981                                     0, version, 0, NULL, type_class,
982                                     undef_map) > 0)
983                   {
984                     conflict = 1;
985                     val = val2;
986                     break;
987                   }
988             }
989           GL(dl_ns)[LM_ID_BASE]._ns_unique_sym_table.entries = saved_entries;
990         }
991
992       if (value->s)
993         {
994           if (__builtin_expect (ELFW(ST_TYPE) (value->s->st_info)
995                                 == STT_TLS, 0))
996             type_class = 4;
997           else if (__builtin_expect (ELFW(ST_TYPE) (value->s->st_info)
998                                      == STT_GNU_IFUNC, 0))
999             type_class |= 8;
1000         }
1001
1002       if (conflict
1003           || GLRO(dl_trace_prelink_map) == undef_map
1004           || GLRO(dl_trace_prelink_map) == NULL
1005           || type_class >= 4)
1006         {
1007           _dl_printf ("%s 0x%0*Zx 0x%0*Zx -> 0x%0*Zx 0x%0*Zx ",
1008                       conflict ? "conflict" : "lookup",
1009                       (int) sizeof (ElfW(Addr)) * 2,
1010                       (size_t) undef_map->l_map_start,
1011                       (int) sizeof (ElfW(Addr)) * 2,
1012                       (size_t) (((ElfW(Addr)) *ref) - undef_map->l_map_start),
1013                       (int) sizeof (ElfW(Addr)) * 2,
1014                       (size_t) (value->s ? value->m->l_map_start : 0),
1015                       (int) sizeof (ElfW(Addr)) * 2,
1016                       (size_t) (value->s ? value->s->st_value : 0));
1017
1018           if (conflict)
1019             _dl_printf ("x 0x%0*Zx 0x%0*Zx ",
1020                         (int) sizeof (ElfW(Addr)) * 2,
1021                         (size_t) (val.s ? val.m->l_map_start : 0),
1022                         (int) sizeof (ElfW(Addr)) * 2,
1023                         (size_t) (val.s ? val.s->st_value : 0));
1024
1025           _dl_printf ("/%x %s\n", type_class, undef_name);
1026         }
1027     }
1028 #endif
1029 }