e34ea5ccf524d38373995ffac4d0624ee07f4469
[platform/upstream/glibc.git] / elf / cache.c
1 /* Copyright (C) 1999, 2000, 2001, 2002, 2003
2         Free Software Foundation, Inc.
3    This file is part of the GNU C Library.
4    Contributed by Andreas Jaeger <aj@suse.de>, 1999.
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, write to the Free
18    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
19    02111-1307 USA.  */
20
21 #include <errno.h>
22 #include <error.h>
23 #include <dirent.h>
24 #include <inttypes.h>
25 #include <libintl.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <unistd.h>
30 #include <sys/fcntl.h>
31 #include <sys/mman.h>
32 #include <sys/stat.h>
33 #include <sys/types.h>
34
35 #include "ldconfig.h"
36 #include "dl-cache.h"
37
38 struct cache_entry
39 {
40   char *lib;                    /* Library name.  */
41   char *path;                   /* Path to find library.  */
42   int flags;                    /* Flags to indicate kind of library.  */
43   unsigned int osversion;       /* Required OS version.  */
44   uint64_t hwcap;               /* Important hardware capabilities.  */
45   int bits_hwcap;               /* Number of bits set in hwcap.  */
46   struct cache_entry *next;     /* Next entry in list.  */
47 };
48
49 /* List of all cache entries.  */
50 static struct cache_entry *entries;
51
52 static const char *flag_descr[] =
53 { "libc4", "ELF", "libc5", "libc6"};
54
55 /* Print a single entry.  */
56 static void
57 print_entry (const char *lib, int flag, unsigned int osversion,
58              uint64_t hwcap, const char *key)
59 {
60   printf ("\t%s (", lib);
61   switch (flag & FLAG_TYPE_MASK)
62     {
63     case FLAG_LIBC4:
64     case FLAG_ELF:
65     case FLAG_ELF_LIBC5:
66     case FLAG_ELF_LIBC6:
67       fputs (flag_descr[flag & FLAG_TYPE_MASK], stdout);
68       break;
69     default:
70       fputs (_("unknown"), stdout);
71       break;
72     }
73   switch (flag & FLAG_REQUIRED_MASK)
74     {
75     case FLAG_SPARC_LIB64:
76       fputs (",64bit", stdout);
77       break;
78     case FLAG_IA64_LIB64:
79       fputs (",IA-64", stdout);
80       break;
81     case FLAG_X8664_LIB64:
82       fputs (",x86-64", stdout);
83       break;
84     case FLAG_S390_LIB64:
85       fputs(",64bit", stdout);
86       break;
87     case FLAG_POWERPC_LIB64:
88       fputs(",64bit", stdout);
89       break;
90     case FLAG_MIPS64_LIBN32:
91       fputs(",N32", stdout);
92       break;
93     case FLAG_MIPS64_LIBN64:
94       fputs(",64bit", stdout);
95     case 0:
96       break;
97     default:
98       printf (",%d", flag & FLAG_REQUIRED_MASK);
99       break;
100     }
101   if (hwcap != 0)
102     printf (", hwcap: 0x%" PRIx64, hwcap);
103   if (osversion != 0)
104     {
105       static const char *const abi_tag_os[] =
106       {
107         [0] = "Linux",
108         [1] = "Hurd",
109         [2] = "Solaris",
110         [3] = "FreeBSD",
111         [4] = N_("Unknown OS")
112       };
113 #define MAXTAG (sizeof abi_tag_os / sizeof abi_tag_os[0] - 1)
114       unsigned int os = osversion >> 24;
115
116       printf (_(", OS ABI: %s %d.%d.%d"),
117               _(abi_tag_os[os > MAXTAG ? MAXTAG : os]),
118               (osversion >> 16) & 0xff,
119               (osversion >> 8) & 0xff,
120               osversion & 0xff);
121     }
122   printf (") => %s\n", key);
123 }
124
125
126 /* Print the whole cache file, if a file contains the new cache format
127    hidden in the old one, print the contents of the new format.  */
128 void
129 print_cache (const char *cache_name)
130 {
131   size_t cache_size;
132   struct stat64 st;
133   int fd;
134   unsigned int i;
135   struct cache_file *cache;
136   struct cache_file_new *cache_new = NULL;
137   const char *cache_data;
138   int format = 0;
139
140   fd = open (cache_name, O_RDONLY);
141   if (fd < 0)
142     error (EXIT_FAILURE, errno, _("Can't open cache file %s\n"), cache_name);
143
144   if (fstat64 (fd, &st) < 0
145       /* No need to map the file if it is empty.  */
146       || st.st_size == 0)
147     {
148       close (fd);
149       return;
150     }
151
152   cache = mmap (0, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
153   if (cache == MAP_FAILED)
154     error (EXIT_FAILURE, errno, _("mmap of cache file failed.\n"));
155   cache_size = st.st_size;
156
157   if (cache_size < sizeof (struct cache_file))
158     error (EXIT_FAILURE, 0, _("File is not a cache file.\n"));
159
160   if (memcmp (cache->magic, CACHEMAGIC, sizeof CACHEMAGIC - 1))
161     {
162       /* This can only be the new format without the old one.  */
163       cache_new = (struct cache_file_new *) cache;
164
165       if (memcmp (cache_new->magic, CACHEMAGIC_NEW, sizeof CACHEMAGIC_NEW - 1)
166           || memcmp (cache_new->version, CACHE_VERSION,
167                       sizeof CACHE_VERSION - 1))
168         error (EXIT_FAILURE, 0, _("File is not a cache file.\n"));
169       format = 1;
170       /* This is where the strings start.  */
171       cache_data = (const char *) cache_new;
172     }
173   else
174     {
175       size_t offset = ALIGN_CACHE (sizeof (struct cache_file)
176                                    + (cache->nlibs
177                                       * sizeof (struct file_entry)));
178       /* This is where the strings start.  */
179       cache_data = (const char *) &cache->libs[cache->nlibs];
180
181       /* Check for a new cache embedded in the old format.  */
182       if (cache_size >
183           (offset + sizeof (struct cache_file_new)))
184         {
185
186           cache_new = (struct cache_file_new *) ((void *)cache + offset);
187
188           if (memcmp (cache_new->magic, CACHEMAGIC_NEW,
189                       sizeof CACHEMAGIC_NEW - 1) == 0
190               && memcmp (cache_new->version, CACHE_VERSION,
191                          sizeof CACHE_VERSION - 1) == 0)
192             {
193               cache_data = (const char *) cache_new;
194               format = 1;
195             }
196         }
197     }
198
199   if (format == 0)
200     {
201       printf (_("%d libs found in cache `%s'\n"), cache->nlibs, cache_name);
202
203       /* Print everything.  */
204       for (i = 0; i < cache->nlibs; i++)
205         print_entry (cache_data + cache->libs[i].key,
206                      cache->libs[i].flags, 0, 0,
207                      cache_data + cache->libs[i].value);
208     }
209   else if (format == 1)
210     {
211       printf (_("%d libs found in cache `%s'\n"),
212               cache_new->nlibs, cache_name);
213
214       /* Print everything.  */
215       for (i = 0; i < cache_new->nlibs; i++)
216         print_entry (cache_data + cache_new->libs[i].key,
217                      cache_new->libs[i].flags,
218                      cache_new->libs[i].osversion,
219                      cache_new->libs[i].hwcap,
220                      cache_data + cache_new->libs[i].value);
221     }
222   /* Cleanup.  */
223   munmap (cache, cache_size);
224   close (fd);
225 }
226
227 /* Initialize cache data structures.  */
228 void
229 init_cache (void)
230 {
231   entries = NULL;
232 }
233
234
235
236 static
237 int compare (const struct cache_entry *e1, const struct cache_entry *e2)
238 {
239   int res;
240
241   /* We need to swap entries here to get the correct sort order.  */
242   res = _dl_cache_libcmp (e2->lib, e1->lib);
243   if (res == 0)
244     {
245       if (e1->flags < e2->flags)
246         return 1;
247       else if (e1->flags > e2->flags)
248         return -1;
249       /* Sort by most specific hwcap.  */
250       else if (e2->bits_hwcap > e1->bits_hwcap)
251         return 1;
252       else if (e2->bits_hwcap < e1->bits_hwcap)
253         return -1;
254       else if (e2->hwcap > e1->hwcap)
255         return 1;
256       else if (e2->hwcap < e1->hwcap)
257         return -1;
258       if (e2->osversion > e1->osversion)
259         return 1;
260       if (e2->osversion < e1->osversion)
261         return -1;
262     }
263   return res;
264 }
265
266 /* Save the contents of the cache.  */
267 void
268 save_cache (const char *cache_name)
269 {
270   struct cache_entry *entry;
271   int fd, idx_old, idx_new;
272   size_t total_strlen, len;
273   char *strings, *str, *temp_name;
274   struct cache_file *file_entries = NULL;
275   struct cache_file_new *file_entries_new = NULL;
276   size_t file_entries_size = 0;
277   size_t file_entries_new_size = 0;
278   unsigned int str_offset;
279   /* Number of cache entries.  */
280   int cache_entry_count = 0;
281   /* Number of normal cache entries.  */
282   int cache_entry_old_count = 0;
283   /* Pad for alignment of cache_file_new.  */
284   size_t pad;
285
286   /* The cache entries are sorted already, save them in this order. */
287
288   /* Count the length of all strings.  */
289   /* The old format doesn't contain hwcap entries and doesn't contain
290      libraries in subdirectories with hwcaps entries.  Count therefore
291      also all entries with hwcap == 0.  */
292   total_strlen = 0;
293   for (entry = entries; entry != NULL; entry = entry->next)
294     {
295       /* Account the final NULs.  */
296       total_strlen += strlen (entry->lib) + strlen (entry->path) + 2;
297       ++cache_entry_count;
298       if (entry->hwcap == 0)
299         ++cache_entry_old_count;
300     }
301
302   /* Create the on disk cache structure.  */
303   /* First an array for all strings.  */
304   strings = (char *)xmalloc (total_strlen);
305
306   if (opt_format != 2)
307     {
308       /* And the list of all entries in the old format.  */
309       file_entries_size = sizeof (struct cache_file)
310         + cache_entry_old_count * sizeof (struct file_entry);
311       file_entries = (struct cache_file *) xmalloc (file_entries_size);
312
313       /* Fill in the header.  */
314       memset (file_entries, 0, sizeof (struct cache_file));
315       memcpy (file_entries->magic, CACHEMAGIC, sizeof CACHEMAGIC - 1);
316
317       file_entries->nlibs = cache_entry_old_count;
318     }
319
320   if (opt_format != 0)
321     {
322       /* And the list of all entries in the new format.  */
323       file_entries_new_size = sizeof (struct cache_file_new)
324         + cache_entry_count * sizeof (struct file_entry_new);
325       file_entries_new =
326         (struct cache_file_new *) xmalloc (file_entries_new_size);
327
328       /* Fill in the header.  */
329       memset (file_entries_new, 0, sizeof (struct cache_file_new));
330       memcpy (file_entries_new->magic, CACHEMAGIC_NEW,
331               sizeof CACHEMAGIC_NEW - 1);
332       memcpy (file_entries_new->version, CACHE_VERSION,
333               sizeof CACHE_VERSION - 1);
334
335       file_entries_new->nlibs = cache_entry_count;
336       file_entries_new->len_strings = total_strlen;
337     }
338
339   pad = ALIGN_CACHE (file_entries_size) - file_entries_size;
340
341   /* If we have both formats, we hide the new format in the strings
342      table, we have to adjust all string indices for this so that
343      old libc5/glibc 2 dynamic linkers just ignore them.  */
344   if (opt_format != 0)
345     str_offset = file_entries_new_size;
346   else
347     str_offset = 0;
348
349   str = strings;
350   for (idx_old = 0, idx_new = 0, entry = entries; entry != NULL;
351        entry = entry->next, ++idx_new)
352     {
353       /* First the library.  */
354       if (opt_format != 2)
355         {
356           file_entries->libs[idx_old].flags = entry->flags;
357           /* XXX: Actually we can optimize here and remove duplicates.  */
358           file_entries->libs[idx_old].key = str_offset + pad;
359         }
360       if (opt_format != 0)
361         {
362           /* We could subtract file_entries_new_size from str_offset -
363              not doing so makes the code easier, the string table
364              always begins at the beginning of the the new cache
365              struct.  */
366           file_entries_new->libs[idx_new].flags = entry->flags;
367           file_entries_new->libs[idx_new].osversion = entry->osversion;
368           file_entries_new->libs[idx_new].hwcap = entry->hwcap;
369           file_entries_new->libs[idx_new].key = str_offset;
370         }
371       len = strlen (entry->lib);
372       str = stpcpy (str, entry->lib);
373       /* Account the final NUL.  */
374       ++str;
375       str_offset += len + 1;
376       /* Then the path.  */
377       if (opt_format != 2)
378         file_entries->libs[idx_old].value = str_offset + pad;
379       if (opt_format != 0)
380         file_entries_new->libs[idx_new].value = str_offset;
381       len = strlen (entry->path);
382       str = stpcpy (str, entry->path);
383       /* Account the final NUL.  */
384       ++str;
385       str_offset += len + 1;
386       /* Ignore entries with hwcap for old format.  */
387       if (entry->hwcap == 0)
388         ++idx_old;
389     }
390
391   /* Write out the cache.  */
392
393   /* Write cache first to a temporary file and rename it later.  */
394   temp_name = xmalloc (strlen (cache_name) + 2);
395   sprintf (temp_name, "%s~", cache_name);
396   /* First remove an old copy if it exists.  */
397   if (unlink (temp_name) && errno != ENOENT)
398     error (EXIT_FAILURE, errno, _("Can't remove old temporary cache file %s"),
399            temp_name);
400
401   /* Create file.  */
402   fd = open (temp_name, O_CREAT|O_WRONLY|O_TRUNC|O_NOFOLLOW,
403              S_IROTH|S_IRGRP|S_IRUSR|S_IWUSR);
404   if (fd < 0)
405     error (EXIT_FAILURE, errno, _("Can't create temporary cache file %s"),
406            temp_name);
407
408   /* Write contents.  */
409   if (opt_format != 2)
410     {
411       if (write (fd, file_entries, file_entries_size)
412           != (ssize_t)file_entries_size)
413         error (EXIT_FAILURE, errno, _("Writing of cache data failed"));
414     }
415   if (opt_format != 0)
416     {
417       /* Align cache.  */
418       if (opt_format != 2)
419         {
420           char zero[pad];
421           if (write (fd, zero, pad) != (ssize_t)pad)
422             error (EXIT_FAILURE, errno, _("Writing of cache data failed"));
423         }
424       if (write (fd, file_entries_new, file_entries_new_size)
425           != (ssize_t)file_entries_new_size)
426         error (EXIT_FAILURE, errno, _("Writing of cache data failed"));
427     }
428
429   if (write (fd, strings, total_strlen) != (ssize_t)total_strlen)
430     error (EXIT_FAILURE, errno, _("Writing of cache data failed."));
431
432   close (fd);
433
434   /* Make sure user can always read cache file */
435   if (chmod (temp_name, S_IROTH|S_IRGRP|S_IRUSR|S_IWUSR))
436     error (EXIT_FAILURE, errno,
437            _("Changing access rights of %s to %#o failed"), temp_name,
438            S_IROTH|S_IRGRP|S_IRUSR|S_IWUSR);
439
440   /* Move temporary to its final location.  */
441   if (rename (temp_name, cache_name))
442     error (EXIT_FAILURE, errno, _("Renaming of %s to %s failed"), temp_name,
443            cache_name);
444
445   /* Free all allocated memory.  */
446   free (file_entries);
447   free (strings);
448
449   while (entries)
450     {
451       entry = entries;
452       free (entry->path);
453       free (entry->lib);
454       entries = entries->next;
455       free (entry);
456     }
457 }
458
459
460 /* Add one library to the cache.  */
461 void
462 add_to_cache (const char *path, const char *lib, int flags,
463               unsigned int osversion, uint64_t hwcap)
464 {
465   struct cache_entry *new_entry, *ptr, *prev;
466   char *full_path;
467   int len, i;
468
469   new_entry = (struct cache_entry *) xmalloc (sizeof (struct cache_entry));
470
471   len = strlen (lib) + strlen (path) + 2;
472
473   full_path = (char *) xmalloc (len);
474   snprintf (full_path, len, "%s/%s", path, lib);
475
476   new_entry->lib = xstrdup (lib);
477   new_entry->path = full_path;
478   new_entry->flags = flags;
479   new_entry->osversion = osversion;
480   new_entry->hwcap = hwcap;
481   new_entry->bits_hwcap = 0;
482
483   /* Count the number of bits set in the masked value.  */
484   for (i = 0; (~((1ULL << i) - 1) & hwcap) != 0 && i < 8 * sizeof (hwcap); ++i)
485     if ((hwcap & (1ULL << i)) != 0)
486       ++new_entry->bits_hwcap;
487
488
489   /* Keep the list sorted - search for right place to insert.  */
490   ptr = entries;
491   prev = entries;
492   while (ptr != NULL)
493     {
494       if (compare (ptr, new_entry) > 0)
495         break;
496       prev = ptr;
497       ptr = ptr->next;
498     }
499   /* Is this the first entry?  */
500   if (ptr == entries)
501     {
502       new_entry->next = entries;
503       entries = new_entry;
504     }
505   else
506     {
507       new_entry->next = prev->next;
508       prev->next = new_entry;
509     }
510 }