vtv_rts.cc 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827
  1. /* Copyright (C) 2012-2022 Free Software Foundation, Inc.
  2. This file is part of GCC.
  3. GCC is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 3, or (at your option)
  6. any later version.
  7. GCC is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. Under Section 7 of GPL version 3, you are granted additional
  12. permissions described in the GCC Runtime Library Exception, version
  13. 3.1, as published by the Free Software Foundation.
  14. You should have received a copy of the GNU General Public License and
  15. a copy of the GCC Runtime Library Exception along with this program;
  16. see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
  17. <http://www.gnu.org/licenses/>. */
  18. /* This file is part of the vtable security feature implementation.
  19. The vtable security feature is designed to detect when a virtual
  20. call is about to be made through an invalid vtable pointer
  21. (possibly due to data corruption or malicious attacks). The
  22. compiler finds every virtual call, and inserts a verification call
  23. before the virtual call. The verification call takes the actual
  24. vtable pointer value in the object through which the virtual call
  25. is being made, and compares the vtable pointer against a set of all
  26. valid vtable pointers that the object could contain (this set is
  27. based on the declared type of the object). If the pointer is in
  28. the valid set, execution is allowed to continue; otherwise the
  29. program is halted.
  30. There are several pieces needed in order to make this work: 1. For
  31. every virtual class in the program (i.e. a class that contains
  32. virtual methods), we need to build the set of all possible valid
  33. vtables that an object of that class could point to. This includes
  34. vtables for any class(es) that inherit from the class under
  35. consideration. 2. For every such data set we build up, we need a
  36. way to find and reference the data set. This is complicated by the
  37. fact that the real vtable addresses are not known until runtime,
  38. when the program is loaded into memory, but we need to reference the
  39. sets at compile time when we are inserting verification calls into
  40. the program. 3. We need to find every virtual call in the program,
  41. and insert the verification call (with the appropriate arguments)
  42. before the virtual call. 4. We need some runtime library pieces:
  43. the code to build up the data sets at runtime; the code to actually
  44. perform the verification using the data sets; and some code to set
  45. protections on the data sets, so they themselves do not become
  46. hacker targets.
  47. To find and reference the set of valid vtable pointers for any given
  48. virtual class, we create a special global varible for each virtual
  49. class. We refer to this as the "vtable map variable" for that
  50. class. The vtable map variable has the type "void *", and is
  51. initialized by the compiler to NULL. At runtime when the set of
  52. valid vtable pointers for a virtual class, e.g. class Foo, is built,
  53. the vtable map variable for class Foo is made to point to the set.
  54. During compile time, when the compiler is inserting verification
  55. calls into the program, it passes the vtable map variable for the
  56. appropriate class to the verification call, so that at runtime the
  57. verification call can find the appropriate data set.
  58. The actual set of valid vtable pointers for a polymorphic class,
  59. e.g. class Foo, cannot be built until runtime, when the vtables get
  60. loaded into memory and their addresses are known. But the knowledge
  61. about which vtables belong in which class' hierarchy is only known
  62. at compile time. Therefore at compile time we collect class
  63. hierarchy and vtable information about every virtual class, and we
  64. generate calls to build up the data sets at runtime. To build the
  65. data sets, we call one of the functions we add to the runtime
  66. library, __VLTRegisterPair. __VLTRegisterPair takes two arguments,
  67. a vtable map variable and the address of a vtable. If the vtable
  68. map variable is currently NULL, it creates a new data set (hash
  69. table), makes the vtable map variable point to the new data set, and
  70. inserts the vtable address into the data set. If the vtable map
  71. variable is not NULL, it just inserts the vtable address into the
  72. data set. In order to make sure that our data sets are built before
  73. any verification calls happen, we create a special constructor
  74. initialization function for each compilation unit, give it a very
  75. high initialization priority, and insert all of our calls to
  76. __VLTRegisterPair into our special constructor initialization
  77. function. */
  78. /* This file contains the main externally visible runtime library
  79. functions for vtable verification: __VLTChangePermission,
  80. __VLTRegisterPair, and __VLTVerifyVtablePointer. It also contains
  81. debug versions __VLTRegisterPairDebug and
  82. __VLTVerifyVtablePointerDebug, which have extra parameters in order
  83. to make it easier to debug verification failures.
  84. The final piece of functionality implemented in this file is symbol
  85. resolution for multiple instances of the same vtable map variable.
  86. If the same virtual class is used in two different compilation
  87. units, then each compilation unit will create a vtable map variable
  88. for the class. We need all instances of the same vtable map
  89. variable to point to the same (single) set of valid vtable
  90. pointers for the class, so we wrote our own hashtable-based symbol
  91. resolution for vtable map variables (with a tiny optimization in
  92. the case where there is only one instance of the variable).
  93. There are two other important pieces to the runtime for vtable
  94. verification besides the main pieces that go into libstdc++.so: two
  95. special tiny shared libraries, libvtv_init.so and libvtv_stubs.so.
  96. libvtv_init.so is built from vtv_init.cc. It is designed to help
  97. minimize the calls made to mprotect (see the comments in
  98. vtv_init.cc for more details). Anything compiled with
  99. "-fvtable-verify=std" must be linked with libvtv_init.so (the gcc
  100. driver has been modified to do this). vtv_stubs.so is built from
  101. vtv_stubs.cc. It replaces the main runtime functions
  102. (__VLTChangePermissino, __VLTRegisterPair and
  103. __VLTVerifyVtablePointer) with stub functions that do nothing. If
  104. a programmer has a library that was built with verification, but
  105. wishes to not have verification turned on, the programmer can link
  106. in the vtv_stubs.so library. */
  107. #include <stdlib.h>
  108. #include <stdio.h>
  109. #include <string.h>
  110. #if defined (__CYGWIN__) || defined (__MINGW32__)
  111. #include <windows.h>
  112. #include <winternl.h>
  113. #include <psapi.h>
  114. #else
  115. #include <execinfo.h>
  116. #endif
  117. #include <unistd.h>
  118. #if !defined (__CYGWIN__) && !defined (__MINGW32__)
  119. #include <sys/mman.h>
  120. #include <link.h>
  121. #endif
  122. #include <errno.h>
  123. #include <fcntl.h>
  124. #include <limits.h>
  125. /* For gthreads suppport */
  126. #include <bits/c++config.h>
  127. #include <ext/concurrence.h>
  128. #include "vtv_utils.h"
  129. #include "vtv_malloc.h"
  130. #include "vtv_set.h"
  131. #include "vtv_map.h"
  132. #include "vtv_rts.h"
  133. #include "vtv_fail.h"
  134. #include "vtv-change-permission.h"
  135. #ifdef HAVE_GETEXECNAME
  136. const char *program_invocation_name;
  137. #endif
  138. #ifdef HAVE___FORTIFY_FAIL
  139. extern "C" {
  140. /* __fortify_fail is a function in glibc that calls __libc_message,
  141. causing it to print out a program termination error message
  142. (including the name of the binary being terminated), a stack
  143. trace where the error occurred, and a memory map dump. Ideally
  144. we would have called __libc_message directly, but that function
  145. does not appear to be accessible to functions outside glibc,
  146. whereas __fortify_fail is. We call __fortify_fail from
  147. __vtv_really_fail. We looked at calling __libc_fatal, which is
  148. externally accessible, but it does not do the back trace and
  149. memory dump. */
  150. extern void __fortify_fail (const char *) __attribute__((noreturn));
  151. } /* extern "C" */
  152. #else
  153. #if defined (__CYGWIN__) || defined (__MINGW32__)
  154. // porting: fix link error to libc
  155. void __fortify_fail (const char * msg){
  156. OutputDebugString(msg);
  157. abort();
  158. }
  159. #else
  160. // FIXME: Provide backtrace via libbacktrace?
  161. void __fortify_fail (const char *msg) {
  162. write (2, msg, strlen (msg));
  163. abort ();
  164. }
  165. #endif
  166. #endif
  167. /* The following variables are used only for debugging and performance
  168. tuning purposes. Therefore they do not need to be "protected".
  169. They cannot be used to attack the vtable verification system and if
  170. they become corrupted it will not affect the correctness or
  171. security of any of the rest of the vtable verification feature. */
  172. unsigned int num_calls_to_regset = 0;
  173. unsigned int num_calls_to_regpair = 0;
  174. unsigned int num_calls_to_verify_vtable = 0;
  175. unsigned long long regset_cycles = 0;
  176. unsigned long long regpair_cycles = 0;
  177. unsigned long long verify_vtable_cycles = 0;
  178. /* Be careful about initialization of statics in this file. Some of
  179. the routines below are called before any runtime initialization for
  180. statics in this file will be done. For example, dont try to
  181. initialize any of these statics with a runtime call (for ex:
  182. sysconf). The initialization will happen after calls to the routines
  183. to protect/unprotec the vtabla_map variables */
  184. /* No need to mark the following variables with VTV_PROTECTED_VAR.
  185. These are either const or are only used for debugging/tracing.
  186. debugging/tracing will not be ON on production environments */
  187. static const bool debug_hash = HASHTABLE_STATS;
  188. #ifdef VTV_DEBUG
  189. static const int debug_functions = 1;
  190. static const int debug_init = 1;
  191. static const int debug_verify_vtable = 1;
  192. #else
  193. static const int debug_functions = 0;
  194. static const int debug_init = 0;
  195. static const int debug_verify_vtable = 0;
  196. #endif
  197. /* Global file descriptor variables for logging, tracing and debugging. */
  198. static int init_log_fd = -1;
  199. static int verify_vtable_log_fd = -1;
  200. /* This holds a formatted error logging message, to be written to the
  201. vtable verify failures log. */
  202. static char debug_log_message[1024];
  203. #ifdef __GTHREAD_MUTEX_INIT
  204. static __gthread_mutex_t change_permissions_lock = __GTHREAD_MUTEX_INIT;
  205. #else
  206. static __gthread_mutex_t change_permissions_lock;
  207. #endif
  208. #ifndef VTV_STATS
  209. #define VTV_STATS 0
  210. #endif
  211. #if VTV_STATS
  212. static inline unsigned long long
  213. get_cycle_count (void)
  214. {
  215. return rdtsc();
  216. }
  217. static inline void
  218. accumulate_cycle_count (unsigned long long *sum, unsigned long long start)
  219. {
  220. unsigned long long end = rdtsc();
  221. *sum = *sum + (end - start);
  222. }
  223. static inline void
  224. increment_num_calls (unsigned int *num_calls)
  225. {
  226. *num_calls = *num_calls + 1;
  227. }
  228. #else
  229. static inline unsigned long long
  230. get_cycle_count (void)
  231. {
  232. return (unsigned long long) 0;
  233. }
  234. static inline void
  235. accumulate_cycle_count (unsigned long long *sum __attribute__((__unused__)),
  236. unsigned long long start __attribute__((__unused__)))
  237. {
  238. /* Do nothing. */
  239. }
  240. static inline void
  241. increment_num_calls (unsigned int *num_calls __attribute__((__unused__)))
  242. {
  243. /* Do nothing. */
  244. }
  245. #endif
  246. /* Types needed by insert_only_hash_sets. */
  247. typedef uintptr_t int_vptr;
  248. /* The set of valid vtable pointers for each virtual class is stored
  249. in a hash table. This is the hashing function used for the hash
  250. table. For more information on the implementation of the hash
  251. table, see the class insert_only_hash_sets in vtv_set.h. */
  252. struct vptr_hash
  253. {
  254. /* Hash function, used to convert vtable pointer, V, (a memory
  255. address) into an index into the hash table. */
  256. size_t
  257. operator() (int_vptr v) const
  258. {
  259. const uint32_t x = 0x7a35e4d9;
  260. const int shift = (sizeof (v) == 8) ? 23 : 21;
  261. v = x * v;
  262. return v ^ (v >> shift);
  263. }
  264. };
  265. /* This is the memory allocator used to create the hash table data
  266. sets of valid vtable pointers. We use VTV_malloc in order to keep
  267. track of which pages have been allocated, so we can update the
  268. protections on those pages appropriately. See the class
  269. insert_only_hash_sets in vtv_set.h for more information. */
  270. struct vptr_set_alloc
  271. {
  272. /* Memory allocator operator. N is the number of bytes to be
  273. allocated. */
  274. void *
  275. operator() (size_t n) const
  276. {
  277. return __vtv_malloc (n);
  278. }
  279. };
  280. /* Instantiate the template classes (in vtv_set.h) for our particular
  281. hash table needs. */
  282. typedef insert_only_hash_sets<int_vptr, vptr_hash, vptr_set_alloc> vtv_sets;
  283. typedef vtv_sets::insert_only_hash_set vtv_set;
  284. typedef vtv_set * vtv_set_handle;
  285. typedef vtv_set_handle * vtv_set_handle_handle;
  286. /* Records for caching the section header information that we have
  287. read out of the file(s) on disk (in dl_iterate_phdr_callback), to
  288. avoid having to re-open and re-read the same file multiple
  289. times. */
  290. struct sect_hdr_data
  291. {
  292. #if defined (__CYGWIN__) || defined (__MINGW32__)
  293. uintptr_t dlpi_addr; /* The header address in the INFO record,
  294. passed in from dl_iterate_phdr. */
  295. uintptr_t mp_low; /* Start address of the .vtable_map_vars
  296. section in memory. */
  297. #else
  298. ElfW (Addr) dlpi_addr; /* The header address in the INFO record,
  299. passed in from dl_iterate_phdr. */
  300. ElfW (Addr) mp_low; /* Start address of the .vtable_map_vars
  301. section in memory. */
  302. #endif
  303. size_t mp_size; /* Size of the .vtable_map_vars section in
  304. memory. */
  305. };
  306. /* Array for caching the section header information, read from file,
  307. to avoid re-opening and re-reading the same file over-and-over
  308. again. */
  309. #define MAX_ENTRIES 250
  310. static struct sect_hdr_data vtv_sect_info_cache[MAX_ENTRIES] VTV_PROTECTED_VAR;
  311. unsigned int num_cache_entries VTV_PROTECTED_VAR = 0;
  312. /* This function takes the LOAD_ADDR for an object opened by the
  313. dynamic loader, and checks the array of cached file data to see if
  314. there is an entry with the same addres. If it finds such an entry,
  315. it returns the record for that entry; otherwise it returns
  316. NULL. */
  317. #if defined (__CYGWIN__) || defined (__MINGW32__)
  318. struct sect_hdr_data *
  319. search_cached_file_data (uintptr_t load_addr)
  320. #else
  321. struct sect_hdr_data *
  322. search_cached_file_data (ElfW (Addr) load_addr)
  323. #endif
  324. {
  325. unsigned int i;
  326. for (i = 0; i < num_cache_entries; ++i)
  327. {
  328. if (vtv_sect_info_cache[i].dlpi_addr == load_addr)
  329. return &(vtv_sect_info_cache[i]);
  330. }
  331. return NULL;
  332. }
  333. /* This function tries to read COUNT bytes out of the file referred to
  334. by FD into the buffer BUF. It returns the actual number of bytes
  335. it succeeded in reading. */
  336. static size_t
  337. ReadPersistent (int fd, void *buf, size_t count)
  338. {
  339. char *buf0 = (char *) buf;
  340. size_t num_bytes = 0;
  341. while (num_bytes < count)
  342. {
  343. int len;
  344. len = read (fd, buf0 + num_bytes, count - num_bytes);
  345. if (len < 0)
  346. return -1;
  347. if (len == 0)
  348. break;
  349. num_bytes += len;
  350. }
  351. return num_bytes;
  352. }
  353. /* This function tries to read COUNT bytes, starting at OFFSET from
  354. the file referred to by FD, and put them into BUF. It calls
  355. ReadPersistent to help it do so. It returns the actual number of
  356. bytes read, or -1 if it fails altogether. */
  357. static size_t
  358. ReadFromOffset (int fd, void *buf, const size_t count, const off_t offset)
  359. {
  360. off_t off = lseek (fd, offset, SEEK_SET);
  361. if (off != (off_t) -1)
  362. return ReadPersistent (fd, buf, count);
  363. return -1;
  364. }
  365. /* The function takes a MESSAGE and attempts to write it to the vtable
  366. memory protection log (for debugging purposes). If the file is not
  367. open, it attempts to open the file first. */
  368. static void
  369. log_memory_protection_data (char *message)
  370. {
  371. static int log_fd = -1;
  372. if (log_fd == -1)
  373. log_fd = __vtv_open_log ("vtv_memory_protection_data.log");
  374. __vtv_add_to_log (log_fd, "%s", message);
  375. }
  376. #if defined (__CYGWIN__) || defined (__MINGW32__)
  377. static void
  378. read_section_offset_and_length (char *name,
  379. uintptr_t addr,
  380. const char *sect_name,
  381. int mprotect_flags,
  382. off_t *sect_offset,
  383. WORD *sect_len)
  384. {
  385. bool found = false;
  386. struct sect_hdr_data *cached_data = NULL;
  387. /* Check to see if we already have the data for this file. */
  388. cached_data = search_cached_file_data (addr);
  389. if (cached_data)
  390. {
  391. *sect_offset = cached_data->mp_low;
  392. *sect_len = cached_data->mp_size;
  393. return;
  394. }
  395. // check for DOS Header magic bytes
  396. if (*(WORD *)addr == 0x5A4D)
  397. {
  398. int name_len = strlen (sect_name);
  399. int fd = -1;
  400. /* Attempt to open the binary file on disk. */
  401. if (strlen (name) == 0)
  402. {
  403. return;
  404. }
  405. else
  406. fd = open (name, O_RDONLY | O_BINARY);
  407. if (fd != -1)
  408. {
  409. /* Find the section header information in memory. */
  410. PIMAGE_DOS_HEADER pDosHeader = (PIMAGE_DOS_HEADER)addr;
  411. PIMAGE_NT_HEADERS pNtHeaders = (PIMAGE_NT_HEADERS)((char *)addr
  412. + pDosHeader->e_lfanew);
  413. PIMAGE_FILE_HEADER pFileHeader = &pNtHeaders->FileHeader;
  414. DWORD PointerToStringTable = pFileHeader->PointerToSymbolTable
  415. + (pFileHeader->NumberOfSymbols*0x12);
  416. PIMAGE_SECTION_HEADER sect_hdr =
  417. (PIMAGE_SECTION_HEADER)((char *)&pNtHeaders->OptionalHeader
  418. + pFileHeader->SizeOfOptionalHeader);
  419. /* Loop through all the section headers, looking for one whose
  420. name is ".vtable_map_vars". */
  421. for (int i = 0; i < pFileHeader->NumberOfSections && !found; ++i)
  422. {
  423. char header_name[64];
  424. /* Check if we have to get the section name from the COFF string
  425. table. */
  426. if (sect_hdr[i].Name[0] == '/')
  427. {
  428. if (atoi((const char*)sect_hdr[i].Name+1) == 0)
  429. {
  430. continue;
  431. }
  432. off_t name_offset = PointerToStringTable
  433. + atoi((const char*)sect_hdr[i].Name+1);
  434. size_t bytes_read = ReadFromOffset (fd, &header_name, 64,
  435. name_offset);
  436. VTV_ASSERT (bytes_read > 0);
  437. }
  438. else
  439. {
  440. memcpy (&header_name, sect_hdr[i].Name,
  441. sizeof (sect_hdr[i].Name));
  442. }
  443. if (memcmp (header_name, sect_name, name_len) == 0)
  444. {
  445. /* We found the section; get its load offset and
  446. size. */
  447. *sect_offset = sect_hdr[i].VirtualAddress;
  448. if (sect_hdr[i].Misc.VirtualSize % VTV_PAGE_SIZE != 0)
  449. *sect_len = sect_hdr[i].Misc.VirtualSize + VTV_PAGE_SIZE
  450. - (sect_hdr[i].Misc.VirtualSize % VTV_PAGE_SIZE);
  451. else
  452. *sect_len = sect_hdr[i].Misc.VirtualSize;
  453. found = true;
  454. }
  455. }
  456. close (fd);
  457. }
  458. }
  459. if (*sect_offset != 0 && *sect_len != 0)
  460. {
  461. /* Calculate the page location in memory, making sure the
  462. address is page-aligned. */
  463. uintptr_t start_addr = addr + *sect_offset;
  464. *sect_offset = start_addr & ~(VTV_PAGE_SIZE - 1);
  465. *sect_len = *sect_len - 1;
  466. /* Since we got this far, we must not have found these pages in
  467. the cache, so add them to it. NOTE: We could get here either
  468. while making everything read-only or while making everything
  469. read-write. We will only update the cache if we get here on
  470. a read-write (to make absolutely sure the cache is writable
  471. -- also the read-write pass should come before the read-only
  472. pass). */
  473. if ((mprotect_flags & PROT_WRITE)
  474. && num_cache_entries < MAX_ENTRIES)
  475. {
  476. vtv_sect_info_cache[num_cache_entries].dlpi_addr = addr;
  477. vtv_sect_info_cache[num_cache_entries].mp_low = *sect_offset;
  478. vtv_sect_info_cache[num_cache_entries].mp_size = *sect_len;
  479. num_cache_entries++;
  480. }
  481. }
  482. }
  483. #else
  484. static void
  485. read_section_offset_and_length (struct dl_phdr_info *info,
  486. const char *sect_name,
  487. int mprotect_flags,
  488. off_t *sect_offset,
  489. ElfW (Word) *sect_len)
  490. {
  491. char program_name[PATH_MAX];
  492. char *cptr;
  493. bool found = false;
  494. struct sect_hdr_data *cached_data = NULL;
  495. const ElfW (Phdr) *phdr_info = info->dlpi_phdr;
  496. const ElfW (Ehdr) *ehdr_info =
  497. (const ElfW (Ehdr) *) (info->dlpi_addr + info->dlpi_phdr[0].p_vaddr
  498. - info->dlpi_phdr[0].p_offset);
  499. /* Get the name of the main executable. This may or may not include
  500. arguments passed to the program. Find the first space, assume it
  501. is the start of the argument list, and change it to a '\0'. */
  502. #ifdef HAVE_GETEXECNAME
  503. program_invocation_name = getexecname ();
  504. #endif
  505. snprintf (program_name, sizeof (program_name), program_invocation_name);
  506. /* Check to see if we already have the data for this file. */
  507. cached_data = search_cached_file_data (info->dlpi_addr);
  508. if (cached_data)
  509. {
  510. *sect_offset = cached_data->mp_low;
  511. *sect_len = cached_data->mp_size;
  512. return;
  513. }
  514. /* Find the first non-escaped space in the program name and make it
  515. the end of the string. */
  516. cptr = strchr (program_name, ' ');
  517. if (cptr != NULL && cptr[-1] != '\\')
  518. cptr[0] = '\0';
  519. if ((phdr_info->p_type == PT_PHDR || phdr_info->p_type == PT_LOAD)
  520. && (ehdr_info->e_shoff && ehdr_info->e_shnum))
  521. {
  522. int name_len = strlen (sect_name);
  523. int fd = -1;
  524. /* Attempt to open the binary file on disk. */
  525. if (strlen (info->dlpi_name) == 0)
  526. {
  527. /* If the constructor initialization function was put into
  528. the preinit array, then this function will get called
  529. while handling preinit array stuff, in which case
  530. program_invocation_name has not been initialized. In
  531. that case we can get the filename of the executable from
  532. "/proc/self/exe". */
  533. if (strlen (program_name) > 0)
  534. {
  535. if (phdr_info->p_type == PT_PHDR)
  536. fd = open (program_name, O_RDONLY);
  537. }
  538. else
  539. fd = open ("/proc/self/exe", O_RDONLY);
  540. }
  541. else
  542. fd = open (info->dlpi_name, O_RDONLY);
  543. if (fd != -1)
  544. {
  545. /* Find the section header information in the file. */
  546. ElfW (Half) strtab_idx = ehdr_info->e_shstrndx;
  547. ElfW (Shdr) shstrtab;
  548. off_t shstrtab_offset = ehdr_info->e_shoff +
  549. (ehdr_info->e_shentsize * strtab_idx);
  550. size_t bytes_read = ReadFromOffset (fd, &shstrtab, sizeof (shstrtab),
  551. shstrtab_offset);
  552. VTV_ASSERT (bytes_read == sizeof (shstrtab));
  553. ElfW (Shdr) sect_hdr;
  554. /* This code will be needed once we have crated libvtv.so. */
  555. bool is_libvtv = false;
  556. /*
  557. if (strstr (info->dlpi_name, "libvtv.so"))
  558. is_libvtv = true;
  559. */
  560. /* Loop through all the section headers, looking for one whose
  561. name is ".vtable_map_vars". */
  562. for (int i = 0; i < ehdr_info->e_shnum && !found; ++i)
  563. {
  564. off_t offset = ehdr_info->e_shoff + (ehdr_info->e_shentsize * i);
  565. bytes_read = ReadFromOffset (fd, &sect_hdr, sizeof (sect_hdr),
  566. offset);
  567. VTV_ASSERT (bytes_read == sizeof (sect_hdr));
  568. char header_name[64];
  569. off_t name_offset = shstrtab.sh_offset + sect_hdr.sh_name;
  570. bytes_read = ReadFromOffset (fd, &header_name, 64, name_offset);
  571. VTV_ASSERT (bytes_read > 0);
  572. if (memcmp (header_name, sect_name, name_len) == 0)
  573. {
  574. /* We found the section; get its load offset and
  575. size. */
  576. *sect_offset = sect_hdr.sh_addr;
  577. if (!is_libvtv)
  578. {
  579. VTV_ASSERT (sect_hdr.sh_size - VTV_PAGE_SIZE >= 0);
  580. *sect_len = sect_hdr.sh_size - VTV_PAGE_SIZE;
  581. }
  582. else
  583. *sect_len = sect_hdr.sh_size;
  584. found = true;
  585. }
  586. }
  587. close (fd);
  588. }
  589. }
  590. if (*sect_offset != 0 && *sect_len != 0)
  591. {
  592. /* Calculate the page location in memory, making sure the
  593. address is page-aligned. */
  594. ElfW (Addr) start_addr = (const ElfW (Addr)) info->dlpi_addr
  595. + *sect_offset;
  596. *sect_offset = start_addr & ~(VTV_PAGE_SIZE - 1);
  597. *sect_len = *sect_len - 1;
  598. /* Since we got this far, we must not have found these pages in
  599. the cache, so add them to it. NOTE: We could get here either
  600. while making everything read-only or while making everything
  601. read-write. We will only update the cache if we get here on
  602. a read-write (to make absolutely sure the cache is writable
  603. -- also the read-write pass should come before the read-only
  604. pass). */
  605. if ((mprotect_flags & PROT_WRITE)
  606. && num_cache_entries < MAX_ENTRIES)
  607. {
  608. vtv_sect_info_cache[num_cache_entries].dlpi_addr = info->dlpi_addr;
  609. vtv_sect_info_cache[num_cache_entries].mp_low = *sect_offset;
  610. vtv_sect_info_cache[num_cache_entries].mp_size = *sect_len;
  611. num_cache_entries++;
  612. }
  613. }
  614. }
  615. #endif
  616. #if defined (__CYGWIN__) || defined (__MINGW32__)
  617. /* This function is used to iterate over all loaded modules and searches
  618. for a section called ".vtable_map_vars". The only interaction with
  619. the binary file on disk of the module is to read section names in the
  620. COFF string table. If the module contains a ".vtable_map_vars" section,
  621. read section offset and size from the section header of the loaded module.
  622. Call 'mprotect' on those pages, setting the protection either to
  623. read-only or read-write, depending on what's in data.
  624. The calls to change the protection occur in vtv_unprotect_vtable_vars
  625. and vtv_protect_vtable_vars. */
  626. static int
  627. iterate_modules (void *data)
  628. {
  629. int * mprotect_flags = (int *) data;
  630. off_t map_sect_offset = 0;
  631. WORD map_sect_len = 0;
  632. char buffer[1024];
  633. const char *map_sect_name = VTV_PROTECTED_VARS_SECTION;
  634. HMODULE hMods[1024];
  635. HANDLE hProcess;
  636. DWORD cbNeeded;
  637. hProcess = GetCurrentProcess ();
  638. if (NULL == hProcess)
  639. return 0;
  640. if (EnumProcessModules (hProcess, hMods, sizeof (hMods), &cbNeeded))
  641. {
  642. /* Iterate over all loaded modules. */
  643. for (unsigned int i = 0; i < (cbNeeded / sizeof (HMODULE)); i++)
  644. {
  645. char szModName[MAX_PATH];
  646. if (GetModuleFileNameExA (hProcess, hMods[i], szModName,
  647. sizeof (szModName)))
  648. {
  649. map_sect_offset = 0;
  650. map_sect_len = 0;
  651. read_section_offset_and_length (szModName,
  652. (uintptr_t) hMods[i],
  653. map_sect_name,
  654. *mprotect_flags,
  655. &map_sect_offset,
  656. &map_sect_len);
  657. if (debug_functions)
  658. {
  659. snprintf (buffer, sizeof(buffer),
  660. " Looking at load module %s to change permissions to %s\n",
  661. szModName,
  662. (*mprotect_flags & PROT_WRITE) ? "READ/WRITE" : "READ-ONLY");
  663. log_memory_protection_data (buffer);
  664. }
  665. /* See if we actually found the section. */
  666. if (map_sect_offset && map_sect_len)
  667. {
  668. unsigned long long start;
  669. int result;
  670. if (debug_functions)
  671. {
  672. snprintf (buffer, sizeof (buffer),
  673. " (%s): Protecting %p to %p\n",
  674. szModName,
  675. (void *) map_sect_offset,
  676. (void *) (map_sect_offset + map_sect_len));
  677. log_memory_protection_data (buffer);
  678. }
  679. /* Change the protections on the pages for the section. */
  680. start = get_cycle_count ();
  681. result = mprotect ((void *) map_sect_offset, map_sect_len,
  682. *mprotect_flags);
  683. accumulate_cycle_count (&mprotect_cycles, start);
  684. if (result == -1)
  685. {
  686. if (debug_functions)
  687. {
  688. snprintf (buffer, sizeof (buffer),
  689. "Failed call to mprotect for %s error: ",
  690. (*mprotect_flags & PROT_WRITE) ?
  691. "READ/WRITE" : "READ-ONLY");
  692. log_memory_protection_data (buffer);
  693. perror(NULL);
  694. }
  695. VTV_error();
  696. }
  697. else
  698. {
  699. if (debug_functions)
  700. {
  701. snprintf (buffer, sizeof (buffer),
  702. "mprotect'ed range [%p, %p]\n",
  703. (void *) map_sect_offset,
  704. (char *) map_sect_offset + map_sect_len);
  705. log_memory_protection_data (buffer);
  706. }
  707. }
  708. increment_num_calls (&num_calls_to_mprotect);
  709. num_pages_protected += (map_sect_len + VTV_PAGE_SIZE - 1)
  710. / VTV_PAGE_SIZE;
  711. continue;
  712. }
  713. }
  714. }
  715. }
  716. CloseHandle(hProcess);
  717. return 0;
  718. }
  719. #else
  720. /* This is the callback function used by dl_iterate_phdr (which is
  721. called from vtv_unprotect_vtable_vars and vtv_protect_vtable_vars).
  722. It attempts to find the binary file on disk for the INFO record
  723. that dl_iterate_phdr passes in; open the binary file, and read its
  724. section header information. If the file contains a
  725. ".vtable_map_vars" section, read the section offset and size. Use
  726. the section offset and size, in conjunction with the data in INFO
  727. to locate the pages in memory where the section is. Call
  728. 'mprotect' on those pages, setting the protection either to
  729. read-only or read-write, depending on what's in DATA. */
  730. static int
  731. dl_iterate_phdr_callback (struct dl_phdr_info *info, size_t, void *data)
  732. {
  733. int * mprotect_flags = (int *) data;
  734. off_t map_sect_offset = 0;
  735. ElfW (Word) map_sect_len = 0;
  736. char buffer[1024];
  737. char program_name[1024];
  738. const char *map_sect_name = VTV_PROTECTED_VARS_SECTION;
  739. /* Check to see if this is the record for the Linux Virtual Dynamic
  740. Shared Object (linux-vdso.so.1), which exists only in memory (and
  741. therefore cannot be read from disk). */
  742. if (strcmp (info->dlpi_name, "linux-vdso.so.1") == 0)
  743. return 0;
  744. if (strlen (info->dlpi_name) == 0
  745. && info->dlpi_addr != 0)
  746. return 0;
  747. /* Get the name of the main executable. This may or may not include
  748. arguments passed to the program. Find the first space, assume it
  749. is the start of the argument list, and change it to a '\0'. */
  750. #ifdef HAVE_GETEXECNAME
  751. program_invocation_name = getexecname ();
  752. #endif
  753. snprintf (program_name, sizeof (program_name), program_invocation_name);
  754. read_section_offset_and_length (info, map_sect_name, *mprotect_flags,
  755. &map_sect_offset, &map_sect_len);
  756. if (debug_functions)
  757. {
  758. snprintf (buffer, sizeof(buffer),
  759. " Looking at load module %s to change permissions to %s\n",
  760. ((strlen (info->dlpi_name) == 0) ? program_name
  761. : info->dlpi_name),
  762. (*mprotect_flags & PROT_WRITE) ? "READ/WRITE" : "READ-ONLY");
  763. log_memory_protection_data (buffer);
  764. }
  765. /* See if we actually found the section. */
  766. if (map_sect_offset && map_sect_len)
  767. {
  768. unsigned long long start;
  769. int result;
  770. if (debug_functions)
  771. {
  772. snprintf (buffer, sizeof (buffer),
  773. " (%s): Protecting %p to %p\n",
  774. ((strlen (info->dlpi_name) == 0) ? program_name
  775. : info->dlpi_name),
  776. (void *) map_sect_offset,
  777. (void *) (map_sect_offset + map_sect_len));
  778. log_memory_protection_data (buffer);
  779. }
  780. /* Change the protections on the pages for the section. */
  781. start = get_cycle_count ();
  782. result = mprotect ((void *) map_sect_offset, map_sect_len,
  783. *mprotect_flags);
  784. accumulate_cycle_count (&mprotect_cycles, start);
  785. if (result == -1)
  786. {
  787. if (debug_functions)
  788. {
  789. snprintf (buffer, sizeof (buffer),
  790. "Failed call to mprotect for %s error: ",
  791. (*mprotect_flags & PROT_WRITE) ?
  792. "READ/WRITE" : "READ-ONLY");
  793. log_memory_protection_data (buffer);
  794. perror(NULL);
  795. }
  796. VTV_error();
  797. }
  798. else
  799. {
  800. if (debug_functions)
  801. {
  802. snprintf (buffer, sizeof (buffer),
  803. "mprotect'ed range [%p, %p]\n",
  804. (void *) map_sect_offset,
  805. (char *) map_sect_offset + map_sect_len);
  806. log_memory_protection_data (buffer);
  807. }
  808. }
  809. increment_num_calls (&num_calls_to_mprotect);
  810. num_pages_protected += (map_sect_len + VTV_PAGE_SIZE - 1) / VTV_PAGE_SIZE;
  811. }
  812. return 0;
  813. }
  814. #endif
  815. /* This function explicitly changes the protection (read-only or read-write)
  816. on the vtv_sect_info_cache, which is used for speeding up look ups in the
  817. function dl_iterate_phdr_callback. This data structure needs to be
  818. explicitly made read-write before any calls to dl_iterate_phdr_callback,
  819. because otherwise it may still be read-only when dl_iterate_phdr_callback
  820. attempts to write to it.
  821. More detailed explanation: dl_iterate_phdr_callback finds all the
  822. .vtable_map_vars sections in all loaded objects (including the main program)
  823. and (depending on where it was called from) either makes all the pages in the
  824. sections read-write or read-only. The vtv_sect_info_cache should be in the
  825. .vtable_map_vars section for libstdc++.so, which means that normally it would
  826. be read-only until libstdc++.so is processed by dl_iterate_phdr_callback
  827. (on the read-write pass), after which it will be writable. But if any loaded
  828. object gets processed before libstdc++.so, it will attempt to update the
  829. data cache, which will still be read-only, and cause a seg fault. Hence
  830. we need a special function, called before dl_iterate_phdr_callback, that
  831. will make the data cache writable. */
  832. static void
  833. change_protections_on_phdr_cache (int protection_flag)
  834. {
  835. char * low_address = (char *) &(vtv_sect_info_cache);
  836. size_t cache_size = MAX_ENTRIES * sizeof (struct sect_hdr_data);
  837. low_address = (char *) ((uintptr_t) low_address & ~(VTV_PAGE_SIZE - 1));
  838. if (mprotect ((void *) low_address, cache_size, protection_flag) == -1)
  839. VTV_error ();
  840. }
  841. /* Unprotect all the vtable map vars and other side data that is used
  842. to keep the core hash_map data. All of these data have been put
  843. into relro sections */
  844. static void
  845. vtv_unprotect_vtable_vars (void)
  846. {
  847. int mprotect_flags;
  848. mprotect_flags = PROT_READ | PROT_WRITE;
  849. change_protections_on_phdr_cache (mprotect_flags);
  850. #if defined (__CYGWIN__) || defined (__MINGW32__)
  851. iterate_modules ((void *) &mprotect_flags);
  852. #else
  853. dl_iterate_phdr (dl_iterate_phdr_callback, (void *) &mprotect_flags);
  854. #endif
  855. }
  856. /* Protect all the vtable map vars and other side data that is used
  857. to keep the core hash_map data. All of these data have been put
  858. into relro sections */
  859. static void
  860. vtv_protect_vtable_vars (void)
  861. {
  862. int mprotect_flags;
  863. mprotect_flags = PROT_READ;
  864. #if defined (__CYGWIN__) || defined (__MINGW32__)
  865. iterate_modules ((void *) &mprotect_flags);
  866. #else
  867. dl_iterate_phdr (dl_iterate_phdr_callback, (void *) &mprotect_flags);
  868. #endif
  869. change_protections_on_phdr_cache (mprotect_flags);
  870. }
  871. #ifndef __GTHREAD_MUTEX_INIT
  872. static void
  873. initialize_change_permissions_mutexes ()
  874. {
  875. __GTHREAD_MUTEX_INIT_FUNCTION (&change_permissions_lock);
  876. }
  877. #endif
  878. /* Variables needed for getting the statistics about the hashtable set. */
  879. #if HASHTABLE_STATS
  880. _AtomicStatCounter stat_contains = 0;
  881. _AtomicStatCounter stat_insert = 0;
  882. _AtomicStatCounter stat_resize = 0;
  883. _AtomicStatCounter stat_create = 0;
  884. _AtomicStatCounter stat_probes_in_non_trivial_set = 0;
  885. _AtomicStatCounter stat_contains_size0 = 0;
  886. _AtomicStatCounter stat_contains_size1 = 0;
  887. _AtomicStatCounter stat_contains_size2 = 0;
  888. _AtomicStatCounter stat_contains_size3 = 0;
  889. _AtomicStatCounter stat_contains_size4 = 0;
  890. _AtomicStatCounter stat_contains_size5 = 0;
  891. _AtomicStatCounter stat_contains_size6 = 0;
  892. _AtomicStatCounter stat_contains_size7 = 0;
  893. _AtomicStatCounter stat_contains_size8 = 0;
  894. _AtomicStatCounter stat_contains_size9 = 0;
  895. _AtomicStatCounter stat_contains_size10 = 0;
  896. _AtomicStatCounter stat_contains_size11 = 0;
  897. _AtomicStatCounter stat_contains_size12 = 0;
  898. _AtomicStatCounter stat_contains_size13_or_more = 0;
  899. _AtomicStatCounter stat_contains_sizes = 0;
  900. _AtomicStatCounter stat_grow_from_size0_to_1 = 0;
  901. _AtomicStatCounter stat_grow_from_size1_to_2 = 0;
  902. _AtomicStatCounter stat_double_the_number_of_buckets = 0;
  903. _AtomicStatCounter stat_insert_found_hash_collision = 0;
  904. _AtomicStatCounter stat_contains_in_non_trivial_set = 0;
  905. _AtomicStatCounter stat_insert_key_that_was_already_present = 0;
  906. #endif
  907. /* Record statistics about the hash table sets, for debugging. */
  908. static void
  909. log_set_stats (void)
  910. {
  911. #if HASHTABLE_STATS
  912. if (set_log_fd == -1)
  913. set_log_fd = __vtv_open_log ("vtv_set_stats.log");
  914. __vtv_add_to_log (set_log_fd, "---\n%s\n",
  915. insert_only_hash_tables_stats().c_str());
  916. #endif
  917. }
  918. /* Change the permissions on all the pages we have allocated for the
  919. data sets and all the ".vtable_map_var" sections in memory (which
  920. contain our vtable map variables). PERM indicates whether to make
  921. the permissions read-only or read-write. */
  922. extern "C" /* This is only being applied to __VLTChangePermission*/
  923. void
  924. __VLTChangePermission (int perm)
  925. {
  926. if (debug_functions)
  927. {
  928. if (perm == __VLTP_READ_WRITE)
  929. fprintf (stdout, "Changing VLT permissions to Read-Write.\n");
  930. else if (perm == __VLTP_READ_ONLY)
  931. fprintf (stdout, "Changing VLT permissions to Read-Only.\n");
  932. else
  933. fprintf (stdout, "Unrecognized permissions value: %d\n", perm);
  934. }
  935. #ifndef __GTHREAD_MUTEX_INIT
  936. static __gthread_once_t mutex_once VTV_PROTECTED_VAR = __GTHREAD_ONCE_INIT;
  937. __gthread_once (&mutex_once, initialize_change_permissions_mutexes);
  938. #endif
  939. /* Ordering of these unprotect/protect calls is very important.
  940. You first need to unprotect all the map vars and side
  941. structures before you do anything with the core data
  942. structures (hash_maps) */
  943. if (perm == __VLTP_READ_WRITE)
  944. {
  945. /* TODO: Need to revisit this code for dlopen. It most probably
  946. is not unlocking the protected vtable vars after for load
  947. module that is not the first load module. */
  948. __gthread_mutex_lock (&change_permissions_lock);
  949. vtv_unprotect_vtable_vars ();
  950. __vtv_malloc_init ();
  951. __vtv_malloc_unprotect ();
  952. }
  953. else if (perm == __VLTP_READ_ONLY)
  954. {
  955. if (debug_hash)
  956. log_set_stats();
  957. __vtv_malloc_protect ();
  958. vtv_protect_vtable_vars ();
  959. __gthread_mutex_unlock (&change_permissions_lock);
  960. }
  961. }
  962. /* This is the memory allocator used to create the hash table that
  963. maps from vtable map variable name to the data set that vtable map
  964. variable should point to. This is part of our vtable map variable
  965. symbol resolution, which is necessary because the same vtable map
  966. variable may be created by multiple compilation units and we need a
  967. method to make sure that all vtable map variables for a particular
  968. class point to the same data set at runtime. */
  969. struct insert_only_hash_map_allocator
  970. {
  971. /* N is the number of bytes to allocate. */
  972. void *
  973. alloc (size_t n) const
  974. {
  975. return __vtv_malloc (n);
  976. }
  977. /* P points to the memory to be deallocated; N is the number of
  978. bytes to deallocate. */
  979. void
  980. dealloc (void *p, size_t) const
  981. {
  982. __vtv_free (p);
  983. }
  984. };
  985. /* Explicitly instantiate this class since this file is compiled with
  986. -fno-implicit-templates. These are for the hash table that is used
  987. to do vtable map variable symbol resolution. */
  988. template class insert_only_hash_map <vtv_set_handle *,
  989. insert_only_hash_map_allocator >;
  990. typedef insert_only_hash_map <vtv_set_handle *,
  991. insert_only_hash_map_allocator > s2s;
  992. typedef const s2s::key_type vtv_symbol_key;
  993. static s2s * vtv_symbol_unification_map VTV_PROTECTED_VAR = NULL;
  994. const unsigned long SET_HANDLE_HANDLE_BIT = 0x2;
  995. /* In the case where a vtable map variable is the only instance of the
  996. variable we have seen, it points directly to the set of valid
  997. vtable pointers. All subsequent instances of the 'same' vtable map
  998. variable point to the first vtable map variable. This function,
  999. given a vtable map variable PTR, checks a bit to see whether it's
  1000. pointing directly to the data set or to the first vtable map
  1001. variable. */
  1002. static inline bool
  1003. is_set_handle_handle (void * ptr)
  1004. {
  1005. return ((uintptr_t) ptr & SET_HANDLE_HANDLE_BIT)
  1006. == SET_HANDLE_HANDLE_BIT;
  1007. }
  1008. /* Returns the actual pointer value of a vtable map variable, PTR (see
  1009. comments for is_set_handle_handle for more details). */
  1010. static inline vtv_set_handle *
  1011. ptr_from_set_handle_handle (void * ptr)
  1012. {
  1013. return (vtv_set_handle *) ((uintptr_t) ptr & ~SET_HANDLE_HANDLE_BIT);
  1014. }
  1015. /* Given a vtable map variable, PTR, this function sets the bit that
  1016. says this is the second (or later) instance of a vtable map
  1017. variable. */
  1018. static inline vtv_set_handle_handle
  1019. set_handle_handle (vtv_set_handle * ptr)
  1020. {
  1021. return (vtv_set_handle_handle) ((uintptr_t) ptr | SET_HANDLE_HANDLE_BIT);
  1022. }
  1023. static inline void
  1024. register_set_common (void **set_handle_ptr, size_t num_args,
  1025. void **vtable_ptr_array, bool debug)
  1026. {
  1027. /* Now figure out what pointer to use for the set pointer, for the
  1028. inserts. */
  1029. vtv_set_handle *handle_ptr = (vtv_set_handle *) set_handle_ptr;
  1030. if (debug)
  1031. VTV_DEBUG_ASSERT (vtv_symbol_unification_map != NULL);
  1032. if (!is_set_handle_handle (*set_handle_ptr))
  1033. handle_ptr = (vtv_set_handle *) set_handle_ptr;
  1034. else
  1035. handle_ptr = ptr_from_set_handle_handle (*set_handle_ptr);
  1036. /* Now we've got the set and it's initialized, add the vtable
  1037. pointers. */
  1038. for (size_t index = 0; index < num_args; ++index)
  1039. {
  1040. int_vptr vtbl_ptr = (int_vptr) vtable_ptr_array[index];
  1041. vtv_sets::insert (vtbl_ptr, handle_ptr);
  1042. }
  1043. }
  1044. static inline void
  1045. register_pair_common (void **set_handle_ptr, const void *vtable_ptr,
  1046. const char *set_symbol_name, const char *vtable_name,
  1047. bool debug)
  1048. {
  1049. /* Now we've got the set and it's initialized, add the vtable
  1050. pointer (assuming that it's not NULL...It may be NULL, as we may
  1051. have called this function merely to initialize the set
  1052. pointer). */
  1053. int_vptr vtbl_ptr = (int_vptr) vtable_ptr;
  1054. if (vtbl_ptr)
  1055. {
  1056. vtv_set_handle *handle_ptr = (vtv_set_handle *) set_handle_ptr;
  1057. if (debug)
  1058. VTV_DEBUG_ASSERT (vtv_symbol_unification_map != NULL);
  1059. if (!is_set_handle_handle (*set_handle_ptr))
  1060. handle_ptr = (vtv_set_handle *) set_handle_ptr;
  1061. else
  1062. handle_ptr = ptr_from_set_handle_handle (*set_handle_ptr);
  1063. vtv_sets::insert (vtbl_ptr, handle_ptr);
  1064. }
  1065. if (debug && debug_init)
  1066. {
  1067. if (init_log_fd == -1)
  1068. init_log_fd = __vtv_open_log("vtv_init.log");
  1069. __vtv_add_to_log(init_log_fd,
  1070. "Registered %s : %s (%p) 2 level deref = %s\n",
  1071. set_symbol_name, vtable_name, vtbl_ptr,
  1072. is_set_handle_handle(*set_handle_ptr) ? "yes" : "no" );
  1073. }
  1074. }
  1075. /* This routine initializes a set handle to a vtable set. It makes
  1076. sure that there is only one set handle for a particular set by
  1077. using a map from set name to pointer to set handle. Since there
  1078. will be multiple copies of the pointer to the set handle (one per
  1079. compilation unit that uses it), it makes sure to initialize all the
  1080. pointers to the set handle so that the set handle is unique. To
  1081. make this a little more efficient and avoid a level of indirection
  1082. in some cases, the first pointer to handle for a particular handle
  1083. becomes the handle itself and the other pointers will point to the
  1084. set handle. This is the debug version of this function, so it
  1085. outputs extra debugging messages and logging. SET_HANDLE_PTR is
  1086. the address of the vtable map variable, SET_SYMBOL_KEY is the hash
  1087. table key (containing the name of the map variable and the hash
  1088. value) and SIZE_HINT is a guess for the best initial size for the
  1089. set of vtable pointers that SET_HANDLE_POINTER will point to. */
  1090. static inline void
  1091. init_set_symbol_debug (void **set_handle_ptr, const void *set_symbol_key,
  1092. size_t size_hint)
  1093. {
  1094. VTV_DEBUG_ASSERT (set_handle_ptr);
  1095. if (vtv_symbol_unification_map == NULL)
  1096. {
  1097. /* TODO: For now we have chosen 1024, but we need to come up with a
  1098. better initial size for this. */
  1099. vtv_symbol_unification_map = s2s::create (1024);
  1100. VTV_DEBUG_ASSERT(vtv_symbol_unification_map);
  1101. }
  1102. vtv_set_handle *handle_ptr = (vtv_set_handle *) set_handle_ptr;
  1103. vtv_symbol_key *symbol_key_ptr = (vtv_symbol_key *) set_symbol_key;
  1104. const s2s::value_type * map_value_ptr =
  1105. vtv_symbol_unification_map->get (symbol_key_ptr);
  1106. char buffer[200];
  1107. if (map_value_ptr == NULL)
  1108. {
  1109. if (*handle_ptr != NULL)
  1110. {
  1111. snprintf (buffer, sizeof (buffer),
  1112. "*** Found non-NULL local set ptr %p missing for symbol"
  1113. " %.*s",
  1114. *handle_ptr, symbol_key_ptr->n, symbol_key_ptr->bytes);
  1115. __vtv_log_verification_failure (buffer, true);
  1116. VTV_DEBUG_ASSERT (0);
  1117. }
  1118. }
  1119. else if (*handle_ptr != NULL &&
  1120. (handle_ptr != *map_value_ptr &&
  1121. ptr_from_set_handle_handle (*handle_ptr) != *map_value_ptr))
  1122. {
  1123. VTV_DEBUG_ASSERT (*map_value_ptr != NULL);
  1124. snprintf (buffer, sizeof(buffer),
  1125. "*** Found diffence between local set ptr %p and set ptr %p"
  1126. "for symbol %.*s",
  1127. *handle_ptr, *map_value_ptr,
  1128. symbol_key_ptr->n, symbol_key_ptr->bytes);
  1129. __vtv_log_verification_failure (buffer, true);
  1130. VTV_DEBUG_ASSERT (0);
  1131. }
  1132. else if (*handle_ptr == NULL)
  1133. {
  1134. /* Execution should not reach this point. */
  1135. }
  1136. if (*handle_ptr != NULL)
  1137. {
  1138. if (!is_set_handle_handle (*set_handle_ptr))
  1139. handle_ptr = (vtv_set_handle *) set_handle_ptr;
  1140. else
  1141. handle_ptr = ptr_from_set_handle_handle (*set_handle_ptr);
  1142. vtv_sets::resize (size_hint, handle_ptr);
  1143. return;
  1144. }
  1145. VTV_DEBUG_ASSERT (*handle_ptr == NULL);
  1146. if (map_value_ptr != NULL)
  1147. {
  1148. if (*map_value_ptr == handle_ptr)
  1149. vtv_sets::resize (size_hint, *map_value_ptr);
  1150. else
  1151. {
  1152. /* The one level handle to the set already exists. So, we
  1153. are adding one level of indirection here and we will
  1154. store a pointer to the one level handle here. */
  1155. vtv_set_handle_handle * handle_handle_ptr =
  1156. (vtv_set_handle_handle *)handle_ptr;
  1157. *handle_handle_ptr = set_handle_handle(*map_value_ptr);
  1158. VTV_DEBUG_ASSERT(*handle_handle_ptr != NULL);
  1159. /* The handle can itself be NULL if the set has only
  1160. been initiazlied with size hint == 1. */
  1161. vtv_sets::resize (size_hint, *map_value_ptr);
  1162. }
  1163. }
  1164. else
  1165. {
  1166. /* We will create a new set. So, in this case handle_ptr is the
  1167. one level pointer to the set handle. Create copy of map name
  1168. in case the memory where this comes from gets unmapped by
  1169. dlclose. */
  1170. size_t map_key_len = symbol_key_ptr->n + sizeof (vtv_symbol_key);
  1171. void *map_key = __vtv_malloc (map_key_len);
  1172. memcpy (map_key, symbol_key_ptr, map_key_len);
  1173. s2s::value_type *value_ptr;
  1174. vtv_symbol_unification_map =
  1175. vtv_symbol_unification_map->find_or_add_key ((vtv_symbol_key *)map_key,
  1176. &value_ptr);
  1177. *value_ptr = handle_ptr;
  1178. /* TODO: We should verify the return value. */
  1179. vtv_sets::create (size_hint, handle_ptr);
  1180. VTV_DEBUG_ASSERT (size_hint <= 1 || *handle_ptr != NULL);
  1181. }
  1182. if (debug_init)
  1183. {
  1184. if (init_log_fd == -1)
  1185. init_log_fd = __vtv_open_log ("vtv_init.log");
  1186. __vtv_add_to_log (init_log_fd,
  1187. "Init handle:%p for symbol:%.*s hash:%u size_hint:%lu"
  1188. "number of symbols:%lu \n",
  1189. set_handle_ptr, symbol_key_ptr->n,
  1190. symbol_key_ptr->bytes, symbol_key_ptr->hash, size_hint,
  1191. vtv_symbol_unification_map->size ());
  1192. }
  1193. }
  1194. /* This routine initializes a set handle to a vtable set. It makes
  1195. sure that there is only one set handle for a particular set by
  1196. using a map from set name to pointer to set handle. Since there
  1197. will be multiple copies of the pointer to the set handle (one per
  1198. compilation unit that uses it), it makes sure to initialize all the
  1199. pointers to the set handle so that the set handle is unique. To
  1200. make this a little more efficient and avoid a level of indirection
  1201. in some cases, the first pointer to handle for a particular handle
  1202. becomes the handle itself and the other pointers will point to the
  1203. set handle. This is the debug version of this function, so it
  1204. outputs extra debugging messages and logging. SET_HANDLE_PTR is
  1205. the address of the vtable map variable, SET_SYMBOL_KEY is the hash
  1206. table key (containing the name of the map variable and the hash
  1207. value) and SIZE_HINT is a guess for the best initial size for the
  1208. set of vtable pointers that SET_HANDLE_POINTER will point to. */
  1209. void
  1210. __VLTRegisterSetDebug (void **set_handle_ptr, const void *set_symbol_key,
  1211. size_t size_hint, size_t num_args,
  1212. void **vtable_ptr_array)
  1213. {
  1214. unsigned long long start = get_cycle_count ();
  1215. increment_num_calls (&num_calls_to_regset);
  1216. VTV_DEBUG_ASSERT(set_handle_ptr != NULL);
  1217. init_set_symbol_debug (set_handle_ptr, set_symbol_key, size_hint);
  1218. register_set_common (set_handle_ptr, num_args, vtable_ptr_array, true);
  1219. accumulate_cycle_count (&regset_cycles, start);
  1220. }
  1221. /* This function takes a the address of a vtable map variable
  1222. (SET_HANDLE_PTR), a VTABLE_PTR to add to the data set, the name of
  1223. the vtable map variable (SET_SYMBOL_NAME) and the name of the
  1224. vtable (VTABLE_NAME) being pointed to. If the vtable map variable
  1225. is NULL it creates a new data set and initializes the variable,
  1226. otherwise it uses our symbol unification to find the right data
  1227. set; in either case it then adds the vtable pointer to the set.
  1228. The other two parameters are used for debugging information. */
  1229. void
  1230. __VLTRegisterPairDebug (void **set_handle_ptr, const void *set_symbol_key,
  1231. size_t size_hint, const void *vtable_ptr,
  1232. const char *set_symbol_name, const char *vtable_name)
  1233. {
  1234. unsigned long long start = get_cycle_count ();
  1235. increment_num_calls (&num_calls_to_regpair);
  1236. VTV_DEBUG_ASSERT(set_handle_ptr != NULL);
  1237. init_set_symbol_debug (set_handle_ptr, set_symbol_key, size_hint);
  1238. register_pair_common (set_handle_ptr, vtable_ptr, set_symbol_name, vtable_name,
  1239. true);
  1240. accumulate_cycle_count (&regpair_cycles, start);
  1241. }
  1242. /* This is the debug version of the verification function. It takes
  1243. the address of a vtable map variable (SET_HANDLE_PTR) and a
  1244. VTABLE_PTR to validate, as well as the name of the vtable map
  1245. variable (SET_SYMBOL_NAME) and VTABLE_NAME, which are used for
  1246. debugging messages. It checks to see if VTABLE_PTR is in the set
  1247. pointed to by SET_HANDLE_PTR. If so, it returns VTABLE_PTR,
  1248. otherwise it calls __vtv_verify_fail, which usually logs error
  1249. messages and calls abort. */
  1250. const void *
  1251. __VLTVerifyVtablePointerDebug (void **set_handle_ptr, const void *vtable_ptr,
  1252. const char *set_symbol_name,
  1253. const char *vtable_name)
  1254. {
  1255. unsigned long long start = get_cycle_count ();
  1256. VTV_DEBUG_ASSERT (set_handle_ptr != NULL && *set_handle_ptr != NULL);
  1257. int_vptr vtbl_ptr = (int_vptr) vtable_ptr;
  1258. increment_num_calls (&num_calls_to_verify_vtable);
  1259. vtv_set_handle *handle_ptr;
  1260. if (!is_set_handle_handle (*set_handle_ptr))
  1261. handle_ptr = (vtv_set_handle *) set_handle_ptr;
  1262. else
  1263. handle_ptr = ptr_from_set_handle_handle (*set_handle_ptr);
  1264. if (vtv_sets::contains (vtbl_ptr, handle_ptr))
  1265. {
  1266. if (debug_verify_vtable)
  1267. {
  1268. if (verify_vtable_log_fd == -1)
  1269. __vtv_open_log ("vtv_verify_vtable.log");
  1270. __vtv_add_to_log (verify_vtable_log_fd,
  1271. "Verified %s %s value = %p\n",
  1272. set_symbol_name, vtable_name, vtable_ptr);
  1273. }
  1274. }
  1275. else
  1276. {
  1277. /* We failed to find the vtable pointer in the set of valid
  1278. pointers. Log the error data and call the failure
  1279. function. */
  1280. snprintf (debug_log_message, sizeof (debug_log_message),
  1281. "Looking for %s in %s\n", vtable_name, set_symbol_name);
  1282. __vtv_verify_fail_debug (set_handle_ptr, vtable_ptr, debug_log_message);
  1283. /* Normally __vtv_verify_fail_debug will call abort, so we won't
  1284. execute the return below. If we get this far, the assumption
  1285. is that the programmer has replaced __vtv_verify_fail_debug
  1286. with some kind of secondary verification AND this secondary
  1287. verification succeeded, so the vtable pointer is valid. */
  1288. }
  1289. accumulate_cycle_count (&verify_vtable_cycles, start);
  1290. return vtable_ptr;
  1291. }
  1292. /* This routine initializes a set handle to a vtable set. It makes
  1293. sure that there is only one set handle for a particular set by
  1294. using a map from set name to pointer to set handle. Since there
  1295. will be multiple copies of the pointer to the set handle (one per
  1296. compilation unit that uses it), it makes sure to initialize all the
  1297. pointers to the set handle so that the set handle is unique. To
  1298. make this a little more efficient and avoid a level of indirection
  1299. in some cases, the first pointer to handle for a particular handle
  1300. becomes the handle itself and the other pointers will point to the
  1301. set handle. SET_HANDLE_PTR is the address of the vtable map
  1302. variable, SET_SYMBOL_KEY is the hash table key (containing the name
  1303. of the map variable and the hash value) and SIZE_HINT is a guess
  1304. for the best initial size for the set of vtable pointers that
  1305. SET_HANDLE_POINTER will point to.*/
  1306. static inline void
  1307. init_set_symbol (void **set_handle_ptr, const void *set_symbol_key,
  1308. size_t size_hint)
  1309. {
  1310. vtv_set_handle *handle_ptr = (vtv_set_handle *) set_handle_ptr;
  1311. if (*handle_ptr != NULL)
  1312. {
  1313. if (!is_set_handle_handle (*set_handle_ptr))
  1314. handle_ptr = (vtv_set_handle *) set_handle_ptr;
  1315. else
  1316. handle_ptr = ptr_from_set_handle_handle (*set_handle_ptr);
  1317. vtv_sets::resize (size_hint, handle_ptr);
  1318. return;
  1319. }
  1320. if (vtv_symbol_unification_map == NULL)
  1321. vtv_symbol_unification_map = s2s::create (1024);
  1322. vtv_symbol_key *symbol_key_ptr = (vtv_symbol_key *) set_symbol_key;
  1323. const s2s::value_type *map_value_ptr =
  1324. vtv_symbol_unification_map->get (symbol_key_ptr);
  1325. if (map_value_ptr != NULL)
  1326. {
  1327. if (*map_value_ptr == handle_ptr)
  1328. vtv_sets::resize (size_hint, *map_value_ptr);
  1329. else
  1330. {
  1331. /* The one level handle to the set already exists. So, we
  1332. are adding one level of indirection here and we will
  1333. store a pointer to the one level pointer here. */
  1334. vtv_set_handle_handle *handle_handle_ptr =
  1335. (vtv_set_handle_handle *) handle_ptr;
  1336. *handle_handle_ptr = set_handle_handle (*map_value_ptr);
  1337. vtv_sets::resize (size_hint, *map_value_ptr);
  1338. }
  1339. }
  1340. else
  1341. {
  1342. /* We will create a new set. So, in this case handle_ptr is the
  1343. one level pointer to the set handle. Create copy of map name
  1344. in case the memory where this comes from gets unmapped by
  1345. dlclose. */
  1346. size_t map_key_len = symbol_key_ptr->n + sizeof (vtv_symbol_key);
  1347. void * map_key = __vtv_malloc (map_key_len);
  1348. memcpy (map_key, symbol_key_ptr, map_key_len);
  1349. s2s::value_type * value_ptr;
  1350. vtv_symbol_unification_map =
  1351. vtv_symbol_unification_map->find_or_add_key ((vtv_symbol_key *)map_key,
  1352. &value_ptr);
  1353. *value_ptr = handle_ptr;
  1354. /* TODO: We should verify the return value. */
  1355. vtv_sets::create (size_hint, handle_ptr);
  1356. }
  1357. }
  1358. /* This routine initializes a set handle to a vtable set. It makes
  1359. sure that there is only one set handle for a particular set by
  1360. using a map from set name to pointer to set handle. Since there
  1361. will be multiple copies of the pointer to the set handle (one per
  1362. compilation unit that uses it), it makes sure to initialize all the
  1363. pointers to the set handle so that the set handle is unique. To
  1364. make this a little more efficient and avoid a level of indirection
  1365. in some cases, the first pointer to handle for a particular handle
  1366. becomes the handle itself and the other pointers will point to the
  1367. set handle. SET_HANDLE_PTR is the address of the vtable map
  1368. variable, SET_SYMBOL_KEY is the hash table key (containing the name
  1369. of the map variable and the hash value) and SIZE_HINT is a guess
  1370. for the best initial size for the set of vtable pointers that
  1371. SET_HANDLE_POINTER will point to.*/
  1372. void
  1373. __VLTRegisterSet (void **set_handle_ptr, const void *set_symbol_key,
  1374. size_t size_hint, size_t num_args, void **vtable_ptr_array)
  1375. {
  1376. unsigned long long start = get_cycle_count ();
  1377. increment_num_calls (&num_calls_to_regset);
  1378. init_set_symbol (set_handle_ptr, set_symbol_key, size_hint);
  1379. register_set_common (set_handle_ptr, num_args, vtable_ptr_array, false);
  1380. accumulate_cycle_count (&regset_cycles, start);
  1381. }
  1382. /* This function takes a the address of a vtable map variable
  1383. (SET_HANDLE_PTR) and a VTABLE_PTR. If the vtable map variable is
  1384. NULL it creates a new data set and initializes the variable,
  1385. otherwise it uses our symbol unification to find the right data
  1386. set; in either case it then adds the vtable pointer to the set. */
  1387. void
  1388. __VLTRegisterPair (void **set_handle_ptr, const void *set_symbol_key,
  1389. size_t size_hint, const void *vtable_ptr)
  1390. {
  1391. unsigned long long start = get_cycle_count ();
  1392. increment_num_calls (&num_calls_to_regpair);
  1393. init_set_symbol (set_handle_ptr, set_symbol_key, size_hint);
  1394. register_pair_common (set_handle_ptr, vtable_ptr, NULL, NULL, false);
  1395. accumulate_cycle_count (&regpair_cycles, start);
  1396. }
  1397. /* This is the main verification function. It takes the address of a
  1398. vtable map variable (SET_HANDLE_PTR) and a VTABLE_PTR to validate.
  1399. It checks to see if VTABLE_PTR is in the set pointed to by
  1400. SET_HANDLE_PTR. If so, it returns VTABLE_PTR, otherwise it calls
  1401. __vtv_verify_fail, which usually logs error messages and calls
  1402. abort. Since this function gets called VERY frequently, it is
  1403. important for it to be as efficient as possible. */
  1404. const void *
  1405. __VLTVerifyVtablePointer (void ** set_handle_ptr, const void * vtable_ptr)
  1406. {
  1407. unsigned long long start = get_cycle_count ();
  1408. int_vptr vtbl_ptr = (int_vptr) vtable_ptr;
  1409. vtv_set_handle *handle_ptr;
  1410. increment_num_calls (&num_calls_to_verify_vtable);
  1411. if (!is_set_handle_handle (*set_handle_ptr))
  1412. handle_ptr = (vtv_set_handle *) set_handle_ptr;
  1413. else
  1414. handle_ptr = ptr_from_set_handle_handle (*set_handle_ptr);
  1415. if (!vtv_sets::contains (vtbl_ptr, handle_ptr))
  1416. {
  1417. __vtv_verify_fail ((void **) handle_ptr, vtable_ptr);
  1418. /* Normally __vtv_verify_fail will call abort, so we won't
  1419. execute the return below. If we get this far, the assumption
  1420. is that the programmer has replaced __vtv_verify_fail with
  1421. some kind of secondary verification AND this secondary
  1422. verification succeeded, so the vtable pointer is valid. */
  1423. }
  1424. accumulate_cycle_count (&verify_vtable_cycles, start);
  1425. return vtable_ptr;
  1426. }
  1427. static int page_count_2 = 0;
  1428. #if !defined (__CYGWIN__) && !defined (__MINGW32__)
  1429. static int
  1430. dl_iterate_phdr_count_pages (struct dl_phdr_info *info,
  1431. size_t unused __attribute__ ((__unused__)),
  1432. void *data)
  1433. {
  1434. int *mprotect_flags = (int *) data;
  1435. off_t map_sect_offset = 0;
  1436. ElfW (Word) map_sect_len = 0;
  1437. const char *map_sect_name = VTV_PROTECTED_VARS_SECTION;
  1438. /* Check to see if this is the record for the Linux Virtual Dynamic
  1439. Shared Object (linux-vdso.so.1), which exists only in memory (and
  1440. therefore cannot be read from disk). */
  1441. if (strcmp (info->dlpi_name, "linux-vdso.so.1") == 0)
  1442. return 0;
  1443. if (strlen (info->dlpi_name) == 0
  1444. && info->dlpi_addr != 0)
  1445. return 0;
  1446. read_section_offset_and_length (info, map_sect_name, *mprotect_flags,
  1447. &map_sect_offset, &map_sect_len);
  1448. /* See if we actually found the section. */
  1449. if (map_sect_len)
  1450. page_count_2 += (map_sect_len + VTV_PAGE_SIZE - 1) / VTV_PAGE_SIZE;
  1451. return 0;
  1452. }
  1453. #endif
  1454. static void
  1455. count_all_pages (void)
  1456. {
  1457. int mprotect_flags;
  1458. mprotect_flags = PROT_READ;
  1459. page_count_2 = 0;
  1460. #if defined (__CYGWIN__) || defined (__MINGW32__)
  1461. iterate_modules ((void *) &mprotect_flags);
  1462. #else
  1463. dl_iterate_phdr (dl_iterate_phdr_count_pages, (void *) &mprotect_flags);
  1464. #endif
  1465. page_count_2 += __vtv_count_mmapped_pages ();
  1466. }
  1467. void
  1468. __VLTDumpStats (void)
  1469. {
  1470. int log_fd = __vtv_open_log ("vtv-runtime-stats.log");
  1471. if (log_fd != -1)
  1472. {
  1473. count_all_pages ();
  1474. __vtv_add_to_log (log_fd,
  1475. "Calls: mprotect (%d) regset (%d) regpair (%d)"
  1476. " verify_vtable (%d)\n",
  1477. num_calls_to_mprotect, num_calls_to_regset,
  1478. num_calls_to_regpair, num_calls_to_verify_vtable);
  1479. __vtv_add_to_log (log_fd,
  1480. "Cycles: mprotect (%lld) regset (%lld) "
  1481. "regpair (%lld) verify_vtable (%lld)\n",
  1482. mprotect_cycles, regset_cycles, regpair_cycles,
  1483. verify_vtable_cycles);
  1484. __vtv_add_to_log (log_fd,
  1485. "Pages protected (1): %d\n", num_pages_protected);
  1486. __vtv_add_to_log (log_fd, "Pages protected (2): %d\n", page_count_2);
  1487. close (log_fd);
  1488. }
  1489. }
  1490. /* This function is called from __VLTVerifyVtablePointerDebug; it
  1491. sends as much debugging information as it can to the error log
  1492. file, then calls __vtv_verify_fail. SET_HANDLE_PTR is the pointer
  1493. to the set of valid vtable pointers, VTBL_PTR is the pointer that
  1494. was not found in the set, and DEBUG_MSG is the message to be
  1495. written to the log file before failing. n */
  1496. void
  1497. __vtv_verify_fail_debug (void **set_handle_ptr, const void *vtbl_ptr,
  1498. const char *debug_msg)
  1499. {
  1500. __vtv_log_verification_failure (debug_msg, false);
  1501. /* Call the public interface in case it has been overwritten by
  1502. user. */
  1503. __vtv_verify_fail (set_handle_ptr, vtbl_ptr);
  1504. __vtv_log_verification_failure ("Returned from __vtv_verify_fail."
  1505. " Secondary verification succeeded.\n", false);
  1506. }
  1507. /* This function calls __fortify_fail with a FAILURE_MSG and then
  1508. calls abort. */
  1509. void
  1510. __vtv_really_fail (const char *failure_msg)
  1511. {
  1512. __fortify_fail (failure_msg);
  1513. /* We should never get this far; __fortify_fail calls __libc_message
  1514. which prints out a back trace and a memory dump and then is
  1515. supposed to call abort, but let's play it safe anyway and call abort
  1516. ourselves. */
  1517. abort ();
  1518. }
  1519. /* This function takes an error MSG, a vtable map variable
  1520. (DATA_SET_PTR) and a vtable pointer (VTBL_PTR). It is called when
  1521. an attempt to verify VTBL_PTR with the set pointed to by
  1522. DATA_SET_PTR failed. It outputs a failure message with the
  1523. addresses involved, and calls __vtv_really_fail. */
  1524. static void
  1525. vtv_fail (const char *msg, void **data_set_ptr, const void *vtbl_ptr)
  1526. {
  1527. char buffer[128];
  1528. int buf_len;
  1529. const char *format_str =
  1530. "*** Unable to verify vtable pointer (%p) in set (%p) *** \n";
  1531. snprintf (buffer, sizeof (buffer), format_str, vtbl_ptr,
  1532. is_set_handle_handle(*data_set_ptr) ?
  1533. ptr_from_set_handle_handle (*data_set_ptr) :
  1534. *data_set_ptr);
  1535. buf_len = strlen (buffer);
  1536. /* Send this to to stderr. */
  1537. write (2, buffer, buf_len);
  1538. #ifndef VTV_NO_ABORT
  1539. __vtv_really_fail (msg);
  1540. #endif
  1541. }
  1542. /* Send information about what we were trying to do when verification
  1543. failed to the error log, then call vtv_fail. This function can be
  1544. overwritten/replaced by the user, to implement a secondary
  1545. verification function instead. DATA_SET_PTR is the vtable map
  1546. variable used for the failed verification, and VTBL_PTR is the
  1547. vtable pointer that was not found in the set. */
  1548. void
  1549. __vtv_verify_fail (void **data_set_ptr, const void *vtbl_ptr)
  1550. {
  1551. char log_msg[256];
  1552. snprintf (log_msg, sizeof (log_msg), "Looking for vtable %p in set %p.\n",
  1553. vtbl_ptr,
  1554. is_set_handle_handle (*data_set_ptr) ?
  1555. ptr_from_set_handle_handle (*data_set_ptr) :
  1556. *data_set_ptr);
  1557. __vtv_log_verification_failure (log_msg, false);
  1558. const char *format_str =
  1559. "*** Unable to verify vtable pointer (%p) in set (%p) *** \n";
  1560. snprintf (log_msg, sizeof (log_msg), format_str, vtbl_ptr, *data_set_ptr);
  1561. __vtv_log_verification_failure (log_msg, false);
  1562. __vtv_log_verification_failure (" Backtrace: \n", true);
  1563. const char *fail_msg = "Potential vtable pointer corruption detected!!\n";
  1564. vtv_fail (fail_msg, data_set_ptr, vtbl_ptr);
  1565. }