symbol.c (check_conflict): Add codimension conflict with pointer; fix cray-pointee...
[official-gcc.git] / libvtv / vtv_rts.cc
blob1af000d8eb59301b41601898cb2363daf3bffcc0
1 /* Copyright (C) 2012-2013
2 Free Software Foundation
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3, or (at your option)
9 any later version.
11 GCC 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
14 GNU General Public License for more details.
16 Under Section 7 of GPL version 3, you are granted additional
17 permissions described in the GCC Runtime Library Exception, version
18 3.1, as published by the Free Software Foundation.
20 You should have received a copy of the GNU General Public License and
21 a copy of the GCC Runtime Library Exception along with this program;
22 see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23 <http://www.gnu.org/licenses/>. */
25 /* This file is part of the vtable security feature implementation.
26 The vtable security feature is designed to detect when a virtual
27 call is about to be made through an invalid vtable pointer
28 (possibly due to data corruption or malicious attacks). The
29 compiler finds every virtual call, and inserts a verification call
30 before the virtual call. The verification call takes the actual
31 vtable pointer value in the object through which the virtual call
32 is being made, and compares the vtable pointer against a set of all
33 valid vtable pointers that the object could contain (this set is
34 based on the declared type of the object). If the pointer is in
35 the valid set, execution is allowed to continue; otherwise the
36 program is halted.
38 There are several pieces needed in order to make this work: 1. For
39 every virtual class in the program (i.e. a class that contains
40 virtual methods), we need to build the set of all possible valid
41 vtables that an object of that class could point to. This includes
42 vtables for any class(es) that inherit from the class under
43 consideration. 2. For every such data set we build up, we need a
44 way to find and reference the data set. This is complicated by the
45 fact that the real vtable addresses are not known until runtime,
46 when the program is loaded into memory, but we need to reference the
47 sets at compile time when we are inserting verification calls into
48 the program. 3. We need to find every virtual call in the program,
49 and insert the verification call (with the appropriate arguments)
50 before the virtual call. 4. We need some runtime library pieces:
51 the code to build up the data sets at runtime; the code to actually
52 perform the verification using the data sets; and some code to set
53 protections on the data sets, so they themselves do not become
54 hacker targets.
56 To find and reference the set of valid vtable pointers for any given
57 virtual class, we create a special global varible for each virtual
58 class. We refer to this as the "vtable map variable" for that
59 class. The vtable map variable has the type "void *", and is
60 initialized by the compiler to NULL. At runtime when the set of
61 valid vtable pointers for a virtual class, e.g. class Foo, is built,
62 the vtable map variable for class Foo is made to point to the set.
63 During compile time, when the compiler is inserting verification
64 calls into the program, it passes the vtable map variable for the
65 appropriate class to the verification call, so that at runtime the
66 verification call can find the appropriate data set.
68 The actual set of valid vtable pointers for a polymorphic class,
69 e.g. class Foo, cannot be built until runtime, when the vtables get
70 loaded into memory and their addresses are known. But the knowledge
71 about which vtables belong in which class' hierarchy is only known
72 at compile time. Therefore at compile time we collect class
73 hierarchy and vtable information about every virtual class, and we
74 generate calls to build up the data sets at runtime. To build the
75 data sets, we call one of the functions we add to the runtime
76 library, __VLTRegisterPair. __VLTRegisterPair takes two arguments,
77 a vtable map variable and the address of a vtable. If the vtable
78 map variable is currently NULL, it creates a new data set (hash
79 table), makes the vtable map variable point to the new data set, and
80 inserts the vtable address into the data set. If the vtable map
81 variable is not NULL, it just inserts the vtable address into the
82 data set. In order to make sure that our data sets are built before
83 any verification calls happen, we create a special constructor
84 initialization function for each compilation unit, give it a very
85 high initialization priority, and insert all of our calls to
86 __VLTRegisterPair into our special constructor initialization
87 function. */
89 /* This file contains the main externally visible runtime library
90 functions for vtable verification: __VLTChangePermission,
91 __VLTRegisterPair, and __VLTVerifyVtablePointer. It also contains
92 debug versions __VLTRegisterPairDebug and
93 __VLTVerifyVtablePointerDebug, which have extra parameters in order
94 to make it easier to debug verification failures.
96 The final piece of functionality implemented in this file is symbol
97 resolution for multiple instances of the same vtable map variable.
98 If the same virtual class is used in two different compilation
99 units, then each compilation unit will create a vtable map variable
100 for the class. We need all instances of the same vtable map
101 variable to point to the same (single) set of valid vtable
102 pointers for the class, so we wrote our own hashtable-based symbol
103 resolution for vtable map variables (with a tiny optimization in
104 the case where there is only one instance of the variable).
106 There are two other important pieces to the runtime for vtable
107 verification besides the main pieces that go into libstdc++.so: two
108 special tiny shared libraries, libvtv_init.so and libvtv_stubs.so.
109 libvtv_init.so is built from vtv_init.cc. It is designed to help
110 minimize the calls made to mprotect (see the comments in
111 vtv_init.cc for more details). Anything compiled with
112 "-fvtable-verify=std" must be linked with libvtv_init.so (the gcc
113 driver has been modified to do this). vtv_stubs.so is built from
114 vtv_stubs.cc. It replaces the main runtime functions
115 (__VLTChangePermissino, __VLTRegisterPair and
116 __VLTVerifyVtablePointer) with stub functions that do nothing. If
117 a programmer has a library that was built with verification, but
118 wishes to not have verification turned on, the programmer can link
119 in the vtv_stubs.so library. */
121 #include <stdlib.h>
122 #include <stdio.h>
123 #include <string.h>
124 #include <execinfo.h>
126 #include <unistd.h>
127 #include <sys/mman.h>
128 #include <errno.h>
129 #include <link.h>
130 #include <fcntl.h>
131 #include <limits.h>
133 /* For gthreads suppport */
134 #include <bits/c++config.h>
135 #include <ext/concurrence.h>
137 #include "vtv_utils.h"
138 #include "vtv_malloc.h"
139 #include "vtv_set.h"
140 #include "vtv_map.h"
141 #include "vtv_rts.h"
142 #include "vtv_fail.h"
144 #include "vtv-change-permission.h"
146 extern "C" {
148 /* __fortify_fail is a function in glibc that calls __libc_message,
149 causing it to print out a program termination error message
150 (including the name of the binary being terminated), a stack
151 trace where the error occurred, and a memory map dump. Ideally
152 we would have called __libc_message directly, but that function
153 does not appear to be accessible to functions outside glibc,
154 whereas __fortify_fail is. We call __fortify_fail from
155 __vtv_really_fail. We looked at calling __libc_fatal, which is
156 externally accessible, but it does not do the back trace and
157 memory dump. */
159 extern void __fortify_fail (const char *) __attribute__((noreturn));
161 } /* extern "C" */
163 /* The following variables are used only for debugging and performance
164 tuning purposes. Therefore they do not need to be "protected".
165 They cannot be used to attack the vtable verification system and if
166 they become corrupted it will not affect the correctness or
167 security of any of the rest of the vtable verification feature. */
169 unsigned int num_calls_to_regset = 0;
170 unsigned int num_calls_to_regpair = 0;
171 unsigned int num_calls_to_verify_vtable = 0;
172 unsigned long long regset_cycles = 0;
173 unsigned long long regpair_cycles = 0;
174 unsigned long long verify_vtable_cycles = 0;
176 /* Be careful about initialization of statics in this file. Some of
177 the routines below are called before any runtime initialization for
178 statics in this file will be done. For example, dont try to
179 initialize any of these statics with a runtime call (for ex:
180 sysconf). The initialization will happen after calls to the routines
181 to protect/unprotec the vtabla_map variables */
183 /* No need to mark the following variables with VTV_PROTECTED_VAR.
184 These are either const or are only used for debugging/tracing.
185 debugging/tracing will not be ON on production environments */
187 static const bool debug_hash = HASHTABLE_STATS;
188 static const int debug_functions = 0;
189 static const int debug_init = 0;
190 static const int debug_verify_vtable = 0;
192 #ifdef VTV_DEBUG
193 static const int debug_functions = 1;
194 static const int debug_init = 1;
195 static const int debug_verify_vtable = 1;
196 #endif
198 /* Global file descriptor variables for logging, tracing and debugging. */
200 static int init_log_fd = -1;
201 static int verify_vtable_log_fd = -1;
203 /* This holds a formatted error logging message, to be written to the
204 vtable verify failures log. */
205 static char debug_log_message[1024];
208 #ifdef __GTHREAD_MUTEX_INIT
209 static __gthread_mutex_t change_permissions_lock = __GTHREAD_MUTEX_INIT;
210 #else
211 static __gthread_mutex_t change_permissions_lock;
212 #endif
215 #ifndef VTV_STATS
216 #define VTV_STATS 0
217 #endif
219 #if VTV_STATS
221 static inline unsigned long long
222 get_cycle_count (void)
224 return rdtsc();
227 static inline void
228 accumulate_cycle_count (unsigned long long *sum, unsigned long long start)
230 unsigned long long end = rdtsc();
231 *sum = *sum + (end - start);
234 static inline void
235 increment_num_calls (unsigned int *num_calls)
237 *num_calls = *num_calls + 1;
240 #else
242 static inline unsigned long long
243 get_cycle_count (void)
245 return (unsigned long long) 0;
248 static inline void
249 accumulate_cycle_count (unsigned long long *sum __attribute__((__unused__)),
250 unsigned long long start __attribute__((__unused__)))
252 /* Do nothing. */
255 static inline void
256 increment_num_calls (unsigned int *num_calls __attribute__((__unused__)))
258 /* Do nothing. */
261 #endif
263 /* Types needed by insert_only_hash_sets. */
264 typedef uintptr_t int_vptr;
266 /* The set of valid vtable pointers for each virtual class is stored
267 in a hash table. This is the hashing function used for the hash
268 table. For more information on the implementation of the hash
269 table, see the class insert_only_hash_sets in vtv_set.h. */
271 struct vptr_hash
273 /* Hash function, used to convert vtable pointer, V, (a memory
274 address) into an index into the hash table. */
275 size_t
276 operator() (int_vptr v) const
278 const uint32_t x = 0x7a35e4d9;
279 const int shift = (sizeof (v) == 8) ? 23 : 21;
280 v = x * v;
281 return v ^ (v >> shift);
285 /* This is the memory allocator used to create the hash table data
286 sets of valid vtable pointers. We use VTV_malloc in order to keep
287 track of which pages have been allocated, so we can update the
288 protections on those pages appropriately. See the class
289 insert_only_hash_sets in vtv_set.h for more information. */
291 struct vptr_set_alloc
293 /* Memory allocator operator. N is the number of bytes to be
294 allocated. */
295 void *
296 operator() (size_t n) const
298 return __vtv_malloc (n);
302 /* Instantiate the template classes (in vtv_set.h) for our particular
303 hash table needs. */
304 typedef insert_only_hash_sets<int_vptr, vptr_hash, vptr_set_alloc> vtv_sets;
305 typedef vtv_sets::insert_only_hash_set vtv_set;
306 typedef vtv_set * vtv_set_handle;
307 typedef vtv_set_handle * vtv_set_handle_handle;
309 /* Records for caching the section header information that we have
310 read out of the file(s) on disk (in dl_iterate_phdr_callback), to
311 avoid having to re-open and re-read the same file multiple
312 times. */
314 struct sect_hdr_data
316 ElfW (Addr) dlpi_addr; /* The header address in the INFO record,
317 passed in from dl_iterate_phdr. */
318 ElfW (Addr) mp_low; /* Start address of the .vtable_map_vars
319 section in memory. */
320 size_t mp_size; /* Size of the .vtable_map_vars section in
321 memory. */
324 /* Array for caching the section header information, read from file,
325 to avoid re-opening and re-reading the same file over-and-over
326 again. */
328 #define MAX_ENTRIES 250
329 static struct sect_hdr_data vtv_sect_info_cache[MAX_ENTRIES] VTV_PROTECTED_VAR;
331 unsigned int num_cache_entries VTV_PROTECTED_VAR = 0;
333 /* This function takes the LOAD_ADDR for an object opened by the
334 dynamic loader, and checks the array of cached file data to see if
335 there is an entry with the same addres. If it finds such an entry,
336 it returns the record for that entry; otherwise it returns
337 NULL. */
339 struct sect_hdr_data *
340 search_cached_file_data (ElfW (Addr) load_addr)
342 unsigned int i;
343 for (i = 0; i < num_cache_entries; ++i)
345 if (vtv_sect_info_cache[i].dlpi_addr == load_addr)
346 return &(vtv_sect_info_cache[i]);
349 return NULL;
352 /* This function tries to read COUNT bytes out of the file referred to
353 by FD into the buffer BUF. It returns the actual number of bytes
354 it succeeded in reading. */
356 static size_t
357 ReadPersistent (int fd, void *buf, size_t count)
359 char *buf0 = (char *) buf;
360 size_t num_bytes = 0;
361 while (num_bytes < count)
363 int len;
364 len = read (fd, buf0 + num_bytes, count - num_bytes);
365 if (len < 0)
366 return -1;
367 if (len == 0)
368 break;
369 num_bytes += len;
372 return num_bytes;
375 /* This function tries to read COUNT bytes, starting at OFFSET from
376 the file referred to by FD, and put them into BUF. It calls
377 ReadPersistent to help it do so. It returns the actual number of
378 bytes read, or -1 if it fails altogether. */
380 static size_t
381 ReadFromOffset (int fd, void *buf, const size_t count, const off_t offset)
383 off_t off = lseek (fd, offset, SEEK_SET);
384 if (off != (off_t) -1)
385 return ReadPersistent (fd, buf, count);
386 return -1;
389 /* The function takes a MESSAGE and attempts to write it to the vtable
390 memory protection log (for debugging purposes). If the file is not
391 open, it attempts to open the file first. */
393 static void
394 log_memory_protection_data (char *message)
396 static int log_fd = -1;
398 if (log_fd == -1)
399 log_fd = __vtv_open_log ("vtv_memory_protection_data.log");
401 __vtv_add_to_log (log_fd, "%s", message);
404 static void
405 read_section_offset_and_length (struct dl_phdr_info *info,
406 const char *sect_name,
407 int mprotect_flags,
408 off_t *sect_offset,
409 ElfW (Word) *sect_len)
411 char program_name[PATH_MAX];
412 char *cptr;
413 bool found = false;
414 struct sect_hdr_data *cached_data = NULL;
415 const ElfW (Phdr) *phdr_info = info->dlpi_phdr;
416 const ElfW (Ehdr) *ehdr_info =
417 (const ElfW (Ehdr) *) (info->dlpi_addr + info->dlpi_phdr[0].p_vaddr
418 - info->dlpi_phdr[0].p_offset);
421 /* Get the name of the main executable. This may or may not include
422 arguments passed to the program. Find the first space, assume it
423 is the start of the argument list, and change it to a '\0'. */
424 snprintf (program_name, sizeof (program_name), program_invocation_name);
426 /* Check to see if we already have the data for this file. */
427 cached_data = search_cached_file_data (info->dlpi_addr);
429 if (cached_data)
431 *sect_offset = cached_data->mp_low;
432 *sect_len = cached_data->mp_size;
433 return;
436 /* Find the first non-escaped space in the program name and make it
437 the end of the string. */
438 cptr = strchr (program_name, ' ');
439 if (cptr != NULL && cptr[-1] != '\\')
440 cptr[0] = '\0';
442 if ((phdr_info->p_type == PT_PHDR || phdr_info->p_type == PT_LOAD)
443 && (ehdr_info->e_shoff && ehdr_info->e_shnum))
445 int name_len = strlen (sect_name);
446 int fd = -1;
448 /* Attempt to open the binary file on disk. */
449 if (strlen (info->dlpi_name) == 0)
451 /* If the constructor initialization function was put into
452 the preinit array, then this function will get called
453 while handling preinit array stuff, in which case
454 program_invocation_name has not been initialized. In
455 that case we can get the filename of the executable from
456 "/proc/self/exe". */
457 if (strlen (program_name) > 0)
459 if (phdr_info->p_type == PT_PHDR)
460 fd = open (program_name, O_RDONLY);
462 else
463 fd = open ("/proc/self/exe", O_RDONLY);
465 else
466 fd = open (info->dlpi_name, O_RDONLY);
468 if (fd != -1)
470 /* Find the section header information in the file. */
471 ElfW (Half) strtab_idx = ehdr_info->e_shstrndx;
472 ElfW (Shdr) shstrtab;
473 off_t shstrtab_offset = ehdr_info->e_shoff +
474 (ehdr_info->e_shentsize * strtab_idx);
475 size_t bytes_read = ReadFromOffset (fd, &shstrtab, sizeof (shstrtab),
476 shstrtab_offset);
477 VTV_ASSERT (bytes_read == sizeof (shstrtab));
479 ElfW (Shdr) sect_hdr;
481 /* This code will be needed once we have crated libvtv.so. */
482 bool is_libvtv = false;
485 if (strstr (info->dlpi_name, "libvtv.so"))
486 is_libvtv = true;
489 /* Loop through all the section headers, looking for one whose
490 name is ".vtable_map_vars". */
492 for (int i = 0; i < ehdr_info->e_shnum && !found; ++i)
494 off_t offset = ehdr_info->e_shoff + (ehdr_info->e_shentsize * i);
496 bytes_read = ReadFromOffset (fd, &sect_hdr, sizeof (sect_hdr),
497 offset);
499 VTV_ASSERT (bytes_read == sizeof (sect_hdr));
501 char header_name[64];
502 off_t name_offset = shstrtab.sh_offset + sect_hdr.sh_name;
504 bytes_read = ReadFromOffset (fd, &header_name, 64, name_offset);
506 VTV_ASSERT (bytes_read > 0);
508 if (memcmp (header_name, sect_name, name_len) == 0)
510 /* We found the section; get its load offset and
511 size. */
512 *sect_offset = sect_hdr.sh_addr;
513 if (!is_libvtv)
514 *sect_len = sect_hdr.sh_size - VTV_PAGE_SIZE;
515 else
516 *sect_len = sect_hdr.sh_size;
517 found = true;
520 close (fd);
524 if (*sect_offset != 0 && *sect_len != 0)
526 /* Calculate the page location in memory, making sure the
527 address is page-aligned. */
528 ElfW (Addr) start_addr = (const ElfW (Addr)) info->dlpi_addr
529 + *sect_offset;
530 *sect_offset = start_addr & ~(VTV_PAGE_SIZE - 1);
531 *sect_len = *sect_len - 1;
533 /* Since we got this far, we must not have found these pages in
534 the cache, so add them to it. NOTE: We could get here either
535 while making everything read-only or while making everything
536 read-write. We will only update the cache if we get here on
537 a read-write (to make absolutely sure the cache is writable
538 -- also the read-write pass should come before the read-only
539 pass). */
540 if ((mprotect_flags & PROT_WRITE)
541 && num_cache_entries < MAX_ENTRIES)
543 vtv_sect_info_cache[num_cache_entries].dlpi_addr = info->dlpi_addr;
544 vtv_sect_info_cache[num_cache_entries].mp_low = *sect_offset;
545 vtv_sect_info_cache[num_cache_entries].mp_size = *sect_len;
546 num_cache_entries++;
551 /* This is the callback function used by dl_iterate_phdr (which is
552 called from vtv_unprotect_vtable_vars and vtv_protect_vtable_vars).
553 It attempts to find the binary file on disk for the INFO record
554 that dl_iterate_phdr passes in; open the binary file, and read its
555 section header information. If the file contains a
556 ".vtable_map_vars" section, read the section offset and size. Use
557 the section offset and size, in conjunction with the data in INFO
558 to locate the pages in memory where the section is. Call
559 'mprotect' on those pages, setting the protection either to
560 read-only or read-write, depending on what's in DATA. */
562 static int
563 dl_iterate_phdr_callback (struct dl_phdr_info *info, size_t, void *data)
565 int * mprotect_flags = (int *) data;
566 off_t map_sect_offset = 0;
567 ElfW (Word) map_sect_len = 0;
568 char buffer[1024];
569 char program_name[1024];
570 const char *map_sect_name = VTV_PROTECTED_VARS_SECTION;
572 /* Check to see if this is the record for the Linux Virtual Dynamic
573 Shared Object (linux-vdso.so.1), which exists only in memory (and
574 therefore cannot be read from disk). */
576 if (strcmp (info->dlpi_name, "linux-vdso.so.1") == 0)
577 return 0;
579 if (strlen (info->dlpi_name) == 0
580 && info->dlpi_addr != 0)
581 return 0;
583 /* Get the name of the main executable. This may or may not include
584 arguments passed to the program. Find the first space, assume it
585 is the start of the argument list, and change it to a '\0'. */
586 snprintf (program_name, sizeof (program_name), program_invocation_name);
588 read_section_offset_and_length (info, map_sect_name, *mprotect_flags,
589 &map_sect_offset, &map_sect_len);
591 if (debug_functions)
593 snprintf (buffer, sizeof(buffer),
594 " Looking at load module %s to change permissions to %s\n",
595 ((strlen (info->dlpi_name) == 0) ? program_name
596 : info->dlpi_name),
597 (*mprotect_flags & PROT_WRITE) ? "READ/WRITE" : "READ-ONLY");
598 log_memory_protection_data (buffer);
601 /* See if we actually found the section. */
602 if (map_sect_offset && map_sect_len)
604 unsigned long long start;
605 int result;
607 if (debug_functions)
609 snprintf (buffer, sizeof (buffer),
610 " (%s): Protecting %p to %p\n",
611 ((strlen (info->dlpi_name) == 0) ? program_name
612 : info->dlpi_name),
613 (void *) map_sect_offset,
614 (void *) (map_sect_offset + map_sect_len));
615 log_memory_protection_data (buffer);
618 /* Change the protections on the pages for the section. */
620 start = get_cycle_count ();
621 result = mprotect ((void *) map_sect_offset, map_sect_len,
622 *mprotect_flags);
623 accumulate_cycle_count (&mprotect_cycles, start);
624 if (result == -1)
626 if (debug_functions)
628 snprintf (buffer, sizeof (buffer),
629 "Failed called to mprotect for %s error: ",
630 (*mprotect_flags & PROT_WRITE) ?
631 "READ/WRITE" : "READ-ONLY");
632 log_memory_protection_data (buffer);
633 perror(NULL);
635 VTV_error();
637 else
639 if (debug_functions)
641 snprintf (buffer, sizeof (buffer),
642 "mprotect'ed range [%p, %p]\n",
643 (void *) map_sect_offset,
644 (char *) map_sect_offset + map_sect_len);
645 log_memory_protection_data (buffer);
648 increment_num_calls (&num_calls_to_mprotect);
649 /* num_pages_protected += (map_sect_len + VTV_PAGE_SIZE - 1) / VTV_PAGE_SIZE; */
650 num_pages_protected += (map_sect_len + 4096 - 1) / 4096;
653 return 0;
656 /* This function explicitly changes the protection (read-only or read-write)
657 on the vtv_sect_info_cache, which is used for speeding up look ups in the
658 function dl_iterate_phdr_callback. This data structure needs to be
659 explicitly made read-write before any calls to dl_iterate_phdr_callback,
660 because otherwise it may still be read-only when dl_iterate_phdr_callback
661 attempts to write to it.
663 More detailed explanation: dl_iterate_phdr_callback finds all the
664 .vtable_map_vars sections in all loaded objects (including the main program)
665 and (depending on where it was called from) either makes all the pages in the
666 sections read-write or read-only. The vtv_sect_info_cache should be in the
667 .vtable_map_vars section for libstdc++.so, which means that normally it would
668 be read-only until libstdc++.so is processed by dl_iterate_phdr_callback
669 (on the read-write pass), after which it will be writable. But if any loaded
670 object gets processed before libstdc++.so, it will attempt to update the
671 data cache, which will still be read-only, and cause a seg fault. Hence
672 we need a special function, called before dl_iterate_phdr_callback, that
673 will make the data cache writable. */
675 static void
676 change_protections_on_phdr_cache (int protection_flag)
678 char * low_address = (char *) &(vtv_sect_info_cache);
679 size_t cache_size = MAX_ENTRIES * sizeof (struct sect_hdr_data);
681 low_address = (char *) ((unsigned long) low_address & ~(VTV_PAGE_SIZE - 1));
683 if (mprotect ((void *) low_address, cache_size, protection_flag) == -1)
684 VTV_error ();
687 /* Unprotect all the vtable map vars and other side data that is used
688 to keep the core hash_map data. All of these data have been put
689 into relro sections */
691 static void
692 vtv_unprotect_vtable_vars (void)
694 int mprotect_flags;
696 mprotect_flags = PROT_READ | PROT_WRITE;
697 change_protections_on_phdr_cache (mprotect_flags);
698 dl_iterate_phdr (dl_iterate_phdr_callback, (void *) &mprotect_flags);
701 /* Protect all the vtable map vars and other side data that is used
702 to keep the core hash_map data. All of these data have been put
703 into relro sections */
705 static void
706 vtv_protect_vtable_vars (void)
708 int mprotect_flags;
710 mprotect_flags = PROT_READ;
711 dl_iterate_phdr (dl_iterate_phdr_callback, (void *) &mprotect_flags);
712 change_protections_on_phdr_cache (mprotect_flags);
715 #ifndef __GTHREAD_MUTEX_INIT
716 static void
717 initialize_change_permissions_mutexes ()
719 __GTHREAD_MUTEX_INIT_FUNCTION (&change_permissions_lock);
721 #endif
723 /* Variables needed for getting the statistics about the hashtable set. */
724 #if HASHTABLE_STATS
725 _AtomicStatCounter stat_contains = 0;
726 _AtomicStatCounter stat_insert = 0;
727 _AtomicStatCounter stat_resize = 0;
728 _AtomicStatCounter stat_create = 0;
729 _AtomicStatCounter stat_probes_in_non_trivial_set = 0;
730 _AtomicStatCounter stat_contains_size0 = 0;
731 _AtomicStatCounter stat_contains_size1 = 0;
732 _AtomicStatCounter stat_contains_size2 = 0;
733 _AtomicStatCounter stat_contains_size3 = 0;
734 _AtomicStatCounter stat_contains_size4 = 0;
735 _AtomicStatCounter stat_contains_size5 = 0;
736 _AtomicStatCounter stat_contains_size6 = 0;
737 _AtomicStatCounter stat_contains_size7 = 0;
738 _AtomicStatCounter stat_contains_size8 = 0;
739 _AtomicStatCounter stat_contains_size9 = 0;
740 _AtomicStatCounter stat_contains_size10 = 0;
741 _AtomicStatCounter stat_contains_size11 = 0;
742 _AtomicStatCounter stat_contains_size12 = 0;
743 _AtomicStatCounter stat_contains_size13_or_more = 0;
744 _AtomicStatCounter stat_contains_sizes = 0;
745 _AtomicStatCounter stat_grow_from_size0_to_1 = 0;
746 _AtomicStatCounter stat_grow_from_size1_to_2 = 0;
747 _AtomicStatCounter stat_double_the_number_of_buckets = 0;
748 _AtomicStatCounter stat_insert_found_hash_collision = 0;
749 _AtomicStatCounter stat_contains_in_non_trivial_set = 0;
750 _AtomicStatCounter stat_insert_key_that_was_already_present = 0;
751 #endif
752 /* Record statistics about the hash table sets, for debugging. */
754 static void
755 log_set_stats (void)
757 #if HASHTABLE_STATS
758 if (set_log_fd == -1)
759 set_log_fd = __vtv_open_log ("vtv_set_stats.log");
761 __vtv_add_to_log (set_log_fd, "---\n%s\n",
762 insert_only_hash_tables_stats().c_str());
763 #endif
766 /* Change the permissions on all the pages we have allocated for the
767 data sets and all the ".vtable_map_var" sections in memory (which
768 contain our vtable map variables). PERM indicates whether to make
769 the permissions read-only or read-write. */
771 extern "C" /* This is only being applied to __VLTChangePermission*/
772 void
773 __VLTChangePermission (int perm)
775 if (debug_functions)
777 if (perm == __VLTP_READ_WRITE)
778 fprintf (stdout, "Changing VLT permisisons to Read-Write.\n");
779 else if (perm == __VLTP_READ_ONLY)
780 fprintf (stdout, "Changing VLT permissions to Read-only.\n");
782 else
783 fprintf (stdout, "Unrecognized permissions value: %d\n", perm);
786 #ifndef __GTHREAD_MUTEX_INIT
787 static __gthread_once_t mutex_once VTV_PROTECTED_VAR = __GTHREAD_ONCE_INIT;
789 __gthread_once (&mutex_once, initialize_change_permissions_mutexes);
790 #endif
792 /* Ordering of these unprotect/protect calls is very important.
793 You first need to unprotect all the map vars and side
794 structures before you do anything with the core data
795 structures (hash_maps) */
797 if (perm == __VLTP_READ_WRITE)
799 /* TODO: Need to revisit this code for dlopen. It most probably
800 is not unlocking the protected vtable vars after for load
801 module that is not the first load module. */
802 __gthread_mutex_lock (&change_permissions_lock);
804 vtv_unprotect_vtable_vars ();
805 __vtv_malloc_init ();
806 __vtv_malloc_unprotect ();
809 else if (perm == __VLTP_READ_ONLY)
811 if (debug_hash)
812 log_set_stats();
814 __vtv_malloc_protect ();
815 vtv_protect_vtable_vars ();
817 __gthread_mutex_unlock (&change_permissions_lock);
821 /* This is the memory allocator used to create the hash table that
822 maps from vtable map variable name to the data set that vtable map
823 variable should point to. This is part of our vtable map variable
824 symbol resolution, which is necessary because the same vtable map
825 variable may be created by multiple compilation units and we need a
826 method to make sure that all vtable map variables for a particular
827 class point to the same data set at runtime. */
829 struct insert_only_hash_map_allocator
831 /* N is the number of bytes to allocate. */
832 void *
833 alloc (size_t n) const
835 return __vtv_malloc (n);
838 /* P points to the memory to be deallocated; N is the number of
839 bytes to deallocate. */
840 void
841 dealloc (void *p, size_t) const
843 __vtv_free (p);
847 /* Explicitly instantiate this class since this file is compiled with
848 -fno-implicit-templates. These are for the hash table that is used
849 to do vtable map variable symbol resolution. */
850 template class insert_only_hash_map <vtv_set_handle *,
851 insert_only_hash_map_allocator >;
852 typedef insert_only_hash_map <vtv_set_handle *,
853 insert_only_hash_map_allocator > s2s;
854 typedef const s2s::key_type vtv_symbol_key;
856 static s2s * vtv_symbol_unification_map VTV_PROTECTED_VAR = NULL;
858 const unsigned long SET_HANDLE_HANDLE_BIT = 0x2;
860 /* In the case where a vtable map variable is the only instance of the
861 variable we have seen, it points directly to the set of valid
862 vtable pointers. All subsequent instances of the 'same' vtable map
863 variable point to the first vtable map variable. This function,
864 given a vtable map variable PTR, checks a bit to see whether it's
865 pointing directly to the data set or to the first vtable map
866 variable. */
868 static inline bool
869 is_set_handle_handle (void * ptr)
871 return ((unsigned long) ptr & SET_HANDLE_HANDLE_BIT)
872 == SET_HANDLE_HANDLE_BIT;
875 /* Returns the actual pointer value of a vtable map variable, PTR (see
876 comments for is_set_handle_handle for more details). */
878 static inline vtv_set_handle *
879 ptr_from_set_handle_handle (void * ptr)
881 return (vtv_set_handle *) ((unsigned long) ptr & ~SET_HANDLE_HANDLE_BIT);
884 /* Given a vtable map variable, PTR, this function sets the bit that
885 says this is the second (or later) instance of a vtable map
886 variable. */
888 static inline vtv_set_handle_handle
889 set_handle_handle (vtv_set_handle * ptr)
891 return (vtv_set_handle_handle) ((unsigned long) ptr | SET_HANDLE_HANDLE_BIT);
894 static inline void
895 register_set_common (void **set_handle_ptr, size_t num_args,
896 void **vtable_ptr_array, bool debug)
898 /* Now figure out what pointer to use for the set pointer, for the
899 inserts. */
900 vtv_set_handle *handle_ptr = (vtv_set_handle *) set_handle_ptr;
902 if (debug)
903 VTV_DEBUG_ASSERT (vtv_symbol_unification_map != NULL);
905 if (!is_set_handle_handle (*set_handle_ptr))
906 handle_ptr = (vtv_set_handle *) set_handle_ptr;
907 else
908 handle_ptr = ptr_from_set_handle_handle (*set_handle_ptr);
910 /* Now we've got the set and it's initialized, add the vtable
911 pointers. */
912 for (size_t index = 0; index < num_args; ++index)
914 int_vptr vtbl_ptr = (int_vptr) vtable_ptr_array[index];
915 vtv_sets::insert (vtbl_ptr, handle_ptr);
919 static inline void
920 register_pair_common (void **set_handle_ptr, const void *vtable_ptr,
921 const char *set_symbol_name, const char *vtable_name,
922 bool debug)
924 /* Now we've got the set and it's initialized, add the vtable
925 pointer (assuming that it's not NULL...It may be NULL, as we may
926 have called this function merely to initialize the set
927 pointer). */
928 int_vptr vtbl_ptr = (int_vptr) vtable_ptr;
929 if (vtbl_ptr)
931 vtv_set_handle *handle_ptr = (vtv_set_handle *) set_handle_ptr;
932 if (debug)
933 VTV_DEBUG_ASSERT (vtv_symbol_unification_map != NULL);
934 if (!is_set_handle_handle (*set_handle_ptr))
935 handle_ptr = (vtv_set_handle *) set_handle_ptr;
936 else
937 handle_ptr = ptr_from_set_handle_handle (*set_handle_ptr);
939 vtv_sets::insert (vtbl_ptr, handle_ptr);
942 if (debug && debug_init)
944 if (init_log_fd == -1)
945 init_log_fd = __vtv_open_log("vtv_init.log");
947 __vtv_add_to_log(init_log_fd,
948 "Registered %s : %s (%p) 2 level deref = %s\n",
949 set_symbol_name, vtable_name, vtbl_ptr,
950 is_set_handle_handle(*set_handle_ptr) ? "yes" : "no" );
954 /* This routine initializes a set handle to a vtable set. It makes
955 sure that there is only one set handle for a particular set by
956 using a map from set name to pointer to set handle. Since there
957 will be multiple copies of the pointer to the set handle (one per
958 compilation unit that uses it), it makes sure to initialize all the
959 pointers to the set handle so that the set handle is unique. To
960 make this a little more efficient and avoid a level of indirection
961 in some cases, the first pointer to handle for a particular handle
962 becomes the handle itself and the other pointers will point to the
963 set handle. This is the debug version of this function, so it
964 outputs extra debugging messages and logging. SET_HANDLE_PTR is
965 the address of the vtable map variable, SET_SYMBOL_KEY is the hash
966 table key (containing the name of the map variable and the hash
967 value) and SIZE_HINT is a guess for the best initial size for the
968 set of vtable pointers that SET_HANDLE_POINTER will point to. */
970 static inline void
971 init_set_symbol_debug (void **set_handle_ptr, const void *set_symbol_key,
972 size_t size_hint)
974 VTV_DEBUG_ASSERT (set_handle_ptr);
976 if (vtv_symbol_unification_map == NULL)
978 /* TODO: For now we have chosen 1024, but we need to come up with a
979 better initial size for this. */
980 vtv_symbol_unification_map = s2s::create (1024);
981 VTV_DEBUG_ASSERT(vtv_symbol_unification_map);
984 vtv_set_handle *handle_ptr = (vtv_set_handle *) set_handle_ptr;
985 vtv_symbol_key *symbol_key_ptr = (vtv_symbol_key *) set_symbol_key;
987 const s2s::value_type * map_value_ptr =
988 vtv_symbol_unification_map->get (symbol_key_ptr);
989 char buffer[200];
990 if (map_value_ptr == NULL)
992 if (*handle_ptr != NULL)
994 snprintf (buffer, sizeof (buffer),
995 "*** Found non-NULL local set ptr %p missing for symbol"
996 " %.*s",
997 *handle_ptr, symbol_key_ptr->n, symbol_key_ptr->bytes);
998 __vtv_log_verification_failure (buffer, true);
999 VTV_DEBUG_ASSERT (0);
1002 else if (*handle_ptr != NULL &&
1003 (handle_ptr != *map_value_ptr &&
1004 ptr_from_set_handle_handle (*handle_ptr) != *map_value_ptr))
1006 VTV_DEBUG_ASSERT (*map_value_ptr != NULL);
1007 snprintf (buffer, sizeof(buffer),
1008 "*** Found diffence between local set ptr %p and set ptr %p"
1009 "for symbol %.*s",
1010 *handle_ptr, *map_value_ptr,
1011 symbol_key_ptr->n, symbol_key_ptr->bytes);
1012 __vtv_log_verification_failure (buffer, true);
1013 VTV_DEBUG_ASSERT (0);
1015 else if (*handle_ptr == NULL)
1017 /* Execution should not reach this point. */
1020 if (*handle_ptr != NULL)
1022 if (!is_set_handle_handle (*set_handle_ptr))
1023 handle_ptr = (vtv_set_handle *) set_handle_ptr;
1024 else
1025 handle_ptr = ptr_from_set_handle_handle (*set_handle_ptr);
1026 vtv_sets::resize (size_hint, handle_ptr);
1027 return;
1030 VTV_DEBUG_ASSERT (*handle_ptr == NULL);
1031 if (map_value_ptr != NULL)
1033 if (*map_value_ptr == handle_ptr)
1034 vtv_sets::resize (size_hint, *map_value_ptr);
1035 else
1037 /* The one level handle to the set already exists. So, we
1038 are adding one level of indirection here and we will
1039 store a pointer to the one level handle here. */
1041 vtv_set_handle_handle * handle_handle_ptr =
1042 (vtv_set_handle_handle *)handle_ptr;
1043 *handle_handle_ptr = set_handle_handle(*map_value_ptr);
1044 VTV_DEBUG_ASSERT(*handle_handle_ptr != NULL);
1046 /* The handle can itself be NULL if the set has only
1047 been initiazlied with size hint == 1. */
1048 vtv_sets::resize (size_hint, *map_value_ptr);
1051 else
1053 /* We will create a new set. So, in this case handle_ptr is the
1054 one level pointer to the set handle. Create copy of map name
1055 in case the memory where this comes from gets unmapped by
1056 dlclose. */
1057 size_t map_key_len = symbol_key_ptr->n + sizeof (vtv_symbol_key);
1058 void *map_key = __vtv_malloc (map_key_len);
1060 memcpy (map_key, symbol_key_ptr, map_key_len);
1062 s2s::value_type *value_ptr;
1063 vtv_symbol_unification_map =
1064 vtv_symbol_unification_map->find_or_add_key ((vtv_symbol_key *)map_key,
1065 &value_ptr);
1066 *value_ptr = handle_ptr;
1068 /* TODO: We should verify the return value. */
1069 vtv_sets::create (size_hint, handle_ptr);
1070 VTV_DEBUG_ASSERT (size_hint <= 1 || *handle_ptr != NULL);
1073 if (debug_init)
1075 if (init_log_fd == -1)
1076 init_log_fd = __vtv_open_log ("vtv_init.log");
1078 __vtv_add_to_log (init_log_fd,
1079 "Init handle:%p for symbol:%.*s hash:%u size_hint:%lu"
1080 "number of symbols:%lu \n",
1081 set_handle_ptr, symbol_key_ptr->n,
1082 symbol_key_ptr->bytes, symbol_key_ptr->hash, size_hint,
1083 vtv_symbol_unification_map->size ());
1088 /* This routine initializes a set handle to a vtable set. It makes
1089 sure that there is only one set handle for a particular set by
1090 using a map from set name to pointer to set handle. Since there
1091 will be multiple copies of the pointer to the set handle (one per
1092 compilation unit that uses it), it makes sure to initialize all the
1093 pointers to the set handle so that the set handle is unique. To
1094 make this a little more efficient and avoid a level of indirection
1095 in some cases, the first pointer to handle for a particular handle
1096 becomes the handle itself and the other pointers will point to the
1097 set handle. This is the debug version of this function, so it
1098 outputs extra debugging messages and logging. SET_HANDLE_PTR is
1099 the address of the vtable map variable, SET_SYMBOL_KEY is the hash
1100 table key (containing the name of the map variable and the hash
1101 value) and SIZE_HINT is a guess for the best initial size for the
1102 set of vtable pointers that SET_HANDLE_POINTER will point to. */
1104 void
1105 __VLTRegisterSetDebug (void **set_handle_ptr, const void *set_symbol_key,
1106 size_t size_hint, size_t num_args,
1107 void **vtable_ptr_array)
1109 unsigned long long start = get_cycle_count ();
1110 increment_num_calls (&num_calls_to_regset);
1112 VTV_DEBUG_ASSERT(set_handle_ptr != NULL);
1113 init_set_symbol_debug (set_handle_ptr, set_symbol_key, size_hint);
1115 register_set_common (set_handle_ptr, num_args, vtable_ptr_array, true);
1117 accumulate_cycle_count (&regset_cycles, start);
1120 /* This function takes a the address of a vtable map variable
1121 (SET_HANDLE_PTR), a VTABLE_PTR to add to the data set, the name of
1122 the vtable map variable (SET_SYMBOL_NAME) and the name of the
1123 vtable (VTABLE_NAME) being pointed to. If the vtable map variable
1124 is NULL it creates a new data set and initializes the variable,
1125 otherwise it uses our symbol unification to find the right data
1126 set; in either case it then adds the vtable pointer to the set.
1127 The other two parameters are used for debugging information. */
1129 void
1130 __VLTRegisterPairDebug (void **set_handle_ptr, const void *set_symbol_key,
1131 size_t size_hint, const void *vtable_ptr,
1132 const char *set_symbol_name, const char *vtable_name)
1134 unsigned long long start = get_cycle_count ();
1135 increment_num_calls (&num_calls_to_regpair);
1137 VTV_DEBUG_ASSERT(set_handle_ptr != NULL);
1138 init_set_symbol_debug (set_handle_ptr, set_symbol_key, size_hint);
1140 register_pair_common (set_handle_ptr, vtable_ptr, set_symbol_name, vtable_name,
1141 true);
1143 accumulate_cycle_count (&regpair_cycles, start);
1147 /* This is the debug version of the verification function. It takes
1148 the address of a vtable map variable (SET_HANDLE_PTR) and a
1149 VTABLE_PTR to validate, as well as the name of the vtable map
1150 variable (SET_SYMBOL_NAME) and VTABLE_NAME, which are used for
1151 debugging messages. It checks to see if VTABLE_PTR is in the set
1152 pointed to by SET_HANDLE_PTR. If so, it returns VTABLE_PTR,
1153 otherwise it calls __vtv_verify_fail, which usually logs error
1154 messages and calls abort. */
1156 const void *
1157 __VLTVerifyVtablePointerDebug (void **set_handle_ptr, const void *vtable_ptr,
1158 const char *set_symbol_name,
1159 const char *vtable_name)
1161 unsigned long long start = get_cycle_count ();
1162 VTV_DEBUG_ASSERT (set_handle_ptr != NULL && *set_handle_ptr != NULL);
1163 int_vptr vtbl_ptr = (int_vptr) vtable_ptr;
1165 increment_num_calls (&num_calls_to_verify_vtable);
1166 vtv_set_handle *handle_ptr;
1167 if (!is_set_handle_handle (*set_handle_ptr))
1168 handle_ptr = (vtv_set_handle *) set_handle_ptr;
1169 else
1170 handle_ptr = ptr_from_set_handle_handle (*set_handle_ptr);
1172 if (vtv_sets::contains (vtbl_ptr, handle_ptr))
1174 if (debug_verify_vtable)
1176 if (verify_vtable_log_fd == -1)
1177 __vtv_open_log ("vtv_verify_vtable.log");
1178 __vtv_add_to_log (verify_vtable_log_fd,
1179 "Verified %s %s value = %p\n",
1180 set_symbol_name, vtable_name, vtable_ptr);
1183 else
1185 /* We failed to find the vtable pointer in the set of valid
1186 pointers. Log the error data and call the failure
1187 function. */
1188 snprintf (debug_log_message, sizeof (debug_log_message),
1189 "Looking for %s in %s\n", vtable_name, set_symbol_name);
1190 __vtv_verify_fail_debug (set_handle_ptr, vtable_ptr, debug_log_message);
1192 /* Normally __vtv_verify_fail_debug will call abort, so we won't
1193 execute the return below. If we get this far, the assumption
1194 is that the programmer has replaced __vtv_verify_fail_debug
1195 with some kind of secondary verification AND this secondary
1196 verification succeeded, so the vtable pointer is valid. */
1198 accumulate_cycle_count (&verify_vtable_cycles, start);
1200 return vtable_ptr;
1203 /* This routine initializes a set handle to a vtable set. It makes
1204 sure that there is only one set handle for a particular set by
1205 using a map from set name to pointer to set handle. Since there
1206 will be multiple copies of the pointer to the set handle (one per
1207 compilation unit that uses it), it makes sure to initialize all the
1208 pointers to the set handle so that the set handle is unique. To
1209 make this a little more efficient and avoid a level of indirection
1210 in some cases, the first pointer to handle for a particular handle
1211 becomes the handle itself and the other pointers will point to the
1212 set handle. SET_HANDLE_PTR is the address of the vtable map
1213 variable, SET_SYMBOL_KEY is the hash table key (containing the name
1214 of the map variable and the hash value) and SIZE_HINT is a guess
1215 for the best initial size for the set of vtable pointers that
1216 SET_HANDLE_POINTER will point to.*/
1218 static inline void
1219 init_set_symbol (void **set_handle_ptr, const void *set_symbol_key,
1220 size_t size_hint)
1222 vtv_set_handle *handle_ptr = (vtv_set_handle *) set_handle_ptr;
1224 if (*handle_ptr != NULL)
1226 if (!is_set_handle_handle (*set_handle_ptr))
1227 handle_ptr = (vtv_set_handle *) set_handle_ptr;
1228 else
1229 handle_ptr = ptr_from_set_handle_handle (*set_handle_ptr);
1230 vtv_sets::resize (size_hint, handle_ptr);
1231 return;
1234 if (vtv_symbol_unification_map == NULL)
1235 vtv_symbol_unification_map = s2s::create (1024);
1237 vtv_symbol_key *symbol_key_ptr = (vtv_symbol_key *) set_symbol_key;
1238 const s2s::value_type *map_value_ptr =
1239 vtv_symbol_unification_map->get (symbol_key_ptr);
1241 if (map_value_ptr != NULL)
1243 if (*map_value_ptr == handle_ptr)
1244 vtv_sets::resize (size_hint, *map_value_ptr);
1245 else
1247 /* The one level handle to the set already exists. So, we
1248 are adding one level of indirection here and we will
1249 store a pointer to the one level pointer here. */
1250 vtv_set_handle_handle *handle_handle_ptr =
1251 (vtv_set_handle_handle *) handle_ptr;
1252 *handle_handle_ptr = set_handle_handle (*map_value_ptr);
1253 vtv_sets::resize (size_hint, *map_value_ptr);
1256 else
1258 /* We will create a new set. So, in this case handle_ptr is the
1259 one level pointer to the set handle. Create copy of map name
1260 in case the memory where this comes from gets unmapped by
1261 dlclose. */
1262 size_t map_key_len = symbol_key_ptr->n + sizeof (vtv_symbol_key);
1263 void * map_key = __vtv_malloc (map_key_len);
1264 memcpy (map_key, symbol_key_ptr, map_key_len);
1266 s2s::value_type * value_ptr;
1267 vtv_symbol_unification_map =
1268 vtv_symbol_unification_map->find_or_add_key ((vtv_symbol_key *)map_key,
1269 &value_ptr);
1271 *value_ptr = handle_ptr;
1273 /* TODO: We should verify the return value. */
1274 vtv_sets::create (size_hint, handle_ptr);
1278 /* This routine initializes a set handle to a vtable set. It makes
1279 sure that there is only one set handle for a particular set by
1280 using a map from set name to pointer to set handle. Since there
1281 will be multiple copies of the pointer to the set handle (one per
1282 compilation unit that uses it), it makes sure to initialize all the
1283 pointers to the set handle so that the set handle is unique. To
1284 make this a little more efficient and avoid a level of indirection
1285 in some cases, the first pointer to handle for a particular handle
1286 becomes the handle itself and the other pointers will point to the
1287 set handle. SET_HANDLE_PTR is the address of the vtable map
1288 variable, SET_SYMBOL_KEY is the hash table key (containing the name
1289 of the map variable and the hash value) and SIZE_HINT is a guess
1290 for the best initial size for the set of vtable pointers that
1291 SET_HANDLE_POINTER will point to.*/
1294 void
1295 __VLTRegisterSet (void **set_handle_ptr, const void *set_symbol_key,
1296 size_t size_hint, size_t num_args, void **vtable_ptr_array)
1298 unsigned long long start = get_cycle_count ();
1299 increment_num_calls (&num_calls_to_regset);
1301 init_set_symbol (set_handle_ptr, set_symbol_key, size_hint);
1302 register_set_common (set_handle_ptr, num_args, vtable_ptr_array, false);
1304 accumulate_cycle_count (&regset_cycles, start);
1309 /* This function takes a the address of a vtable map variable
1310 (SET_HANDLE_PTR) and a VTABLE_PTR. If the vtable map variable is
1311 NULL it creates a new data set and initializes the variable,
1312 otherwise it uses our symbol unification to find the right data
1313 set; in either case it then adds the vtable pointer to the set. */
1315 void
1316 __VLTRegisterPair (void **set_handle_ptr, const void *set_symbol_key,
1317 size_t size_hint, const void *vtable_ptr)
1319 unsigned long long start = get_cycle_count ();
1320 increment_num_calls (&num_calls_to_regpair);
1322 init_set_symbol (set_handle_ptr, set_symbol_key, size_hint);
1323 register_pair_common (set_handle_ptr, vtable_ptr, NULL, NULL, false);
1325 accumulate_cycle_count (&regpair_cycles, start);
1328 /* This is the main verification function. It takes the address of a
1329 vtable map variable (SET_HANDLE_PTR) and a VTABLE_PTR to validate.
1330 It checks to see if VTABLE_PTR is in the set pointed to by
1331 SET_HANDLE_PTR. If so, it returns VTABLE_PTR, otherwise it calls
1332 __vtv_verify_fail, which usually logs error messages and calls
1333 abort. Since this function gets called VERY frequently, it is
1334 important for it to be as efficient as possible. */
1336 const void *
1337 __VLTVerifyVtablePointer (void ** set_handle_ptr, const void * vtable_ptr)
1339 unsigned long long start = get_cycle_count ();
1340 int_vptr vtbl_ptr = (int_vptr) vtable_ptr;
1342 vtv_set_handle *handle_ptr;
1343 increment_num_calls (&num_calls_to_verify_vtable);
1344 if (!is_set_handle_handle (*set_handle_ptr))
1345 handle_ptr = (vtv_set_handle *) set_handle_ptr;
1346 else
1347 handle_ptr = ptr_from_set_handle_handle (*set_handle_ptr);
1349 if (!vtv_sets::contains (vtbl_ptr, handle_ptr))
1351 __vtv_verify_fail ((void **) handle_ptr, vtable_ptr);
1352 /* Normally __vtv_verify_fail will call abort, so we won't
1353 execute the return below. If we get this far, the assumption
1354 is that the programmer has replaced __vtv_verify_fail with
1355 some kind of secondary verification AND this secondary
1356 verification succeeded, so the vtable pointer is valid. */
1358 accumulate_cycle_count (&verify_vtable_cycles, start);
1360 return vtable_ptr;
1363 static int page_count_2 = 0;
1365 static int
1366 dl_iterate_phdr_count_pages (struct dl_phdr_info *info,
1367 size_t unused __attribute__ ((__unused__)),
1368 void *data)
1370 int *mprotect_flags = (int *) data;
1371 off_t map_sect_offset = 0;
1372 ElfW (Word) map_sect_len = 0;
1373 const char *map_sect_name = VTV_PROTECTED_VARS_SECTION;
1375 /* Check to see if this is the record for the Linux Virtual Dynamic
1376 Shared Object (linux-vdso.so.1), which exists only in memory (and
1377 therefore cannot be read from disk). */
1379 if (strcmp (info->dlpi_name, "linux-vdso.so.1") == 0)
1380 return 0;
1382 if (strlen (info->dlpi_name) == 0
1383 && info->dlpi_addr != 0)
1384 return 0;
1386 read_section_offset_and_length (info, map_sect_name, *mprotect_flags,
1387 &map_sect_offset, &map_sect_len);
1389 /* See if we actually found the section. */
1390 if (map_sect_len)
1391 page_count_2 += (map_sect_len + VTV_PAGE_SIZE - 1) / VTV_PAGE_SIZE;
1393 return 0;
1396 static void
1397 count_all_pages (void)
1399 int mprotect_flags;
1401 mprotect_flags = PROT_READ;
1402 page_count_2 = 0;
1404 dl_iterate_phdr (dl_iterate_phdr_count_pages, (void *) &mprotect_flags);
1405 page_count_2 += __vtv_count_mmapped_pages ();
1408 void
1409 __VLTDumpStats (void)
1411 int log_fd = __vtv_open_log ("vtv-runtime-stats.log");
1413 if (log_fd != -1)
1415 count_all_pages ();
1416 __vtv_add_to_log (log_fd,
1417 "Calls: mprotect (%d) regset (%d) regpair (%d)"
1418 " verify_vtable (%d)\n",
1419 num_calls_to_mprotect, num_calls_to_regset,
1420 num_calls_to_regpair, num_calls_to_verify_vtable);
1421 __vtv_add_to_log (log_fd,
1422 "Cycles: mprotect (%lld) regset (%lld) "
1423 "regpair (%lld) verify_vtable (%lld)\n",
1424 mprotect_cycles, regset_cycles, regpair_cycles,
1425 verify_vtable_cycles);
1426 __vtv_add_to_log (log_fd,
1427 "Pages protected (1): %d\n", num_pages_protected);
1428 __vtv_add_to_log (log_fd, "Pages protected (2): %d\n", page_count_2);
1430 close (log_fd);
1434 /* This function is called from __VLTVerifyVtablePointerDebug; it
1435 sends as much debugging information as it can to the error log
1436 file, then calls __vtv_verify_fail. SET_HANDLE_PTR is the pointer
1437 to the set of valid vtable pointers, VTBL_PTR is the pointer that
1438 was not found in the set, and DEBUG_MSG is the message to be
1439 written to the log file before failing. n */
1441 void
1442 __vtv_verify_fail_debug (void **set_handle_ptr, const void *vtbl_ptr,
1443 const char *debug_msg)
1445 __vtv_log_verification_failure (debug_msg, false);
1447 /* Call the public interface in case it has been overwritten by
1448 user. */
1449 __vtv_verify_fail (set_handle_ptr, vtbl_ptr);
1451 __vtv_log_verification_failure ("Returned from __vtv_verify_fail."
1452 " Secondary verification succeeded.\n", false);
1455 /* This function calls __fortify_fail with a FAILURE_MSG and then
1456 calls abort. */
1458 void
1459 __vtv_really_fail (const char *failure_msg)
1461 __fortify_fail (failure_msg);
1463 /* We should never get this far; __fortify_fail calls __libc_message
1464 which prints out a back trace and a memory dump and then is
1465 supposed to call abort, but let's play it safe anyway and call abort
1466 ourselves. */
1467 abort ();
1470 /* This function takes an error MSG, a vtable map variable
1471 (DATA_SET_PTR) and a vtable pointer (VTBL_PTR). It is called when
1472 an attempt to verify VTBL_PTR with the set pointed to by
1473 DATA_SET_PTR failed. It outputs a failure message with the
1474 addresses involved, and calls __vtv_really_fail. */
1476 static void
1477 vtv_fail (const char *msg, void **data_set_ptr, const void *vtbl_ptr)
1479 char buffer[128];
1480 int buf_len;
1481 const char *format_str =
1482 "*** Unable to verify vtable pointer (%p) in set (%p) *** \n";
1484 snprintf (buffer, sizeof (buffer), format_str, vtbl_ptr,
1485 is_set_handle_handle(*data_set_ptr) ?
1486 ptr_from_set_handle_handle (*data_set_ptr) :
1487 *data_set_ptr);
1488 buf_len = strlen (buffer);
1489 /* Send this to to stderr. */
1490 write (2, buffer, buf_len);
1492 #ifndef VTV_NO_ABORT
1493 __vtv_really_fail (msg);
1494 #endif
1497 /* Send information about what we were trying to do when verification
1498 failed to the error log, then call vtv_fail. This function can be
1499 overwritten/replaced by the user, to implement a secondary
1500 verification function instead. DATA_SET_PTR is the vtable map
1501 variable used for the failed verification, and VTBL_PTR is the
1502 vtable pointer that was not found in the set. */
1504 void
1505 __vtv_verify_fail (void **data_set_ptr, const void *vtbl_ptr)
1507 char log_msg[256];
1508 snprintf (log_msg, sizeof (log_msg), "Looking for vtable %p in set %p.\n",
1509 vtbl_ptr,
1510 is_set_handle_handle (*data_set_ptr) ?
1511 ptr_from_set_handle_handle (*data_set_ptr) :
1512 *data_set_ptr);
1513 __vtv_log_verification_failure (log_msg, false);
1515 const char *format_str =
1516 "*** Unable to verify vtable pointer (%p) in set (%p) *** \n";
1517 snprintf (log_msg, sizeof (log_msg), format_str, vtbl_ptr, *data_set_ptr);
1518 __vtv_log_verification_failure (log_msg, false);
1519 __vtv_log_verification_failure (" Backtrace: \n", true);
1521 const char *fail_msg = "Potential vtable pointer corruption detected!!\n";
1522 vtv_fail (fail_msg, data_set_ptr, vtbl_ptr);