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