vtv_rts.cc 66 KB

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