]> git.ipfire.org Git - thirdparty/gcc.git/blame - gcc/asan.c
Re-factor inclusion of tree.h.
[thirdparty/gcc.git] / gcc / asan.c
CommitLineData
b92cccf4 1/* AddressSanitizer, a fast memory error detector.
711789cc 2 Copyright (C) 2012-2013 Free Software Foundation, Inc.
b92cccf4 3 Contributed by Kostya Serebryany <kcc@google.com>
4
5This file is part of GCC.
6
7GCC is free software; you can redistribute it and/or modify it under
8the terms of the GNU General Public License as published by the Free
9Software Foundation; either version 3, or (at your option) any later
10version.
11
12GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or
14FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15for more details.
16
17You should have received a copy of the GNU General Public License
18along with GCC; see the file COPYING3. If not see
19<http://www.gnu.org/licenses/>. */
20
21
22#include "config.h"
23#include "system.h"
24#include "coretypes.h"
41a8aa41 25#include "tree.h"
b92cccf4 26#include "gimple.h"
27#include "tree-iterator.h"
69ee5dbb 28#include "tree-ssa.h"
b92cccf4 29#include "tree-pass.h"
b92cccf4 30#include "asan.h"
31#include "gimple-pretty-print.h"
7ad5fd20 32#include "target.h"
3c919612 33#include "expr.h"
34#include "optabs.h"
92fc5c48 35#include "output.h"
a4932d0d 36#include "tm_p.h"
b45e34ed 37#include "langhooks.h"
c31c80df 38#include "hash-table.h"
39#include "alloc-pool.h"
f6568ea4 40#include "cfgloop.h"
9a4a3348 41#include "gimple-builder.h"
b92cccf4 42
eca932e6 43/* AddressSanitizer finds out-of-bounds and use-after-free bugs
44 with <2x slowdown on average.
45
46 The tool consists of two parts:
47 instrumentation module (this file) and a run-time library.
48 The instrumentation module adds a run-time check before every memory insn.
49 For a 8- or 16- byte load accessing address X:
50 ShadowAddr = (X >> 3) + Offset
51 ShadowValue = *(char*)ShadowAddr; // *(short*) for 16-byte access.
52 if (ShadowValue)
53 __asan_report_load8(X);
54 For a load of N bytes (N=1, 2 or 4) from address X:
55 ShadowAddr = (X >> 3) + Offset
56 ShadowValue = *(char*)ShadowAddr;
57 if (ShadowValue)
58 if ((X & 7) + N - 1 > ShadowValue)
59 __asan_report_loadN(X);
60 Stores are instrumented similarly, but using __asan_report_storeN functions.
61 A call too __asan_init() is inserted to the list of module CTORs.
62
63 The run-time library redefines malloc (so that redzone are inserted around
64 the allocated memory) and free (so that reuse of free-ed memory is delayed),
65 provides __asan_report* and __asan_init functions.
66
67 Read more:
68 http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
69
70 The current implementation supports detection of out-of-bounds and
71 use-after-free in the heap, on the stack and for global variables.
72
73 [Protection of stack variables]
74
75 To understand how detection of out-of-bounds and use-after-free works
76 for stack variables, lets look at this example on x86_64 where the
77 stack grows downward:
3c919612 78
79 int
80 foo ()
81 {
82 char a[23] = {0};
83 int b[2] = {0};
84
85 a[5] = 1;
86 b[1] = 2;
87
88 return a[5] + b[1];
89 }
90
eca932e6 91 For this function, the stack protected by asan will be organized as
92 follows, from the top of the stack to the bottom:
3c919612 93
eca932e6 94 Slot 1/ [red zone of 32 bytes called 'RIGHT RedZone']
3c919612 95
eca932e6 96 Slot 2/ [8 bytes of red zone, that adds up to the space of 'a' to make
97 the next slot be 32 bytes aligned; this one is called Partial
98 Redzone; this 32 bytes alignment is an asan constraint]
3c919612 99
eca932e6 100 Slot 3/ [24 bytes for variable 'a']
3c919612 101
eca932e6 102 Slot 4/ [red zone of 32 bytes called 'Middle RedZone']
3c919612 103
eca932e6 104 Slot 5/ [24 bytes of Partial Red Zone (similar to slot 2]
3c919612 105
eca932e6 106 Slot 6/ [8 bytes for variable 'b']
3c919612 107
eca932e6 108 Slot 7/ [32 bytes of Red Zone at the bottom of the stack, called
109 'LEFT RedZone']
3c919612 110
eca932e6 111 The 32 bytes of LEFT red zone at the bottom of the stack can be
112 decomposed as such:
3c919612 113
114 1/ The first 8 bytes contain a magical asan number that is always
115 0x41B58AB3.
116
117 2/ The following 8 bytes contains a pointer to a string (to be
118 parsed at runtime by the runtime asan library), which format is
119 the following:
120
121 "<function-name> <space> <num-of-variables-on-the-stack>
122 (<32-bytes-aligned-offset-in-bytes-of-variable> <space>
123 <length-of-var-in-bytes> ){n} "
124
125 where '(...){n}' means the content inside the parenthesis occurs 'n'
126 times, with 'n' being the number of variables on the stack.
127
128 3/ The following 16 bytes of the red zone have no particular
129 format.
130
eca932e6 131 The shadow memory for that stack layout is going to look like this:
3c919612 132
133 - content of shadow memory 8 bytes for slot 7: 0xF1F1F1F1.
134 The F1 byte pattern is a magic number called
135 ASAN_STACK_MAGIC_LEFT and is a way for the runtime to know that
136 the memory for that shadow byte is part of a the LEFT red zone
137 intended to seat at the bottom of the variables on the stack.
138
139 - content of shadow memory 8 bytes for slots 6 and 5:
140 0xF4F4F400. The F4 byte pattern is a magic number
141 called ASAN_STACK_MAGIC_PARTIAL. It flags the fact that the
142 memory region for this shadow byte is a PARTIAL red zone
143 intended to pad a variable A, so that the slot following
144 {A,padding} is 32 bytes aligned.
145
146 Note that the fact that the least significant byte of this
147 shadow memory content is 00 means that 8 bytes of its
148 corresponding memory (which corresponds to the memory of
149 variable 'b') is addressable.
150
151 - content of shadow memory 8 bytes for slot 4: 0xF2F2F2F2.
152 The F2 byte pattern is a magic number called
153 ASAN_STACK_MAGIC_MIDDLE. It flags the fact that the memory
154 region for this shadow byte is a MIDDLE red zone intended to
155 seat between two 32 aligned slots of {variable,padding}.
156
157 - content of shadow memory 8 bytes for slot 3 and 2:
eca932e6 158 0xF4000000. This represents is the concatenation of
3c919612 159 variable 'a' and the partial red zone following it, like what we
160 had for variable 'b'. The least significant 3 bytes being 00
161 means that the 3 bytes of variable 'a' are addressable.
162
eca932e6 163 - content of shadow memory 8 bytes for slot 1: 0xF3F3F3F3.
3c919612 164 The F3 byte pattern is a magic number called
165 ASAN_STACK_MAGIC_RIGHT. It flags the fact that the memory
166 region for this shadow byte is a RIGHT red zone intended to seat
167 at the top of the variables of the stack.
168
eca932e6 169 Note that the real variable layout is done in expand_used_vars in
170 cfgexpand.c. As far as Address Sanitizer is concerned, it lays out
171 stack variables as well as the different red zones, emits some
172 prologue code to populate the shadow memory as to poison (mark as
173 non-accessible) the regions of the red zones and mark the regions of
174 stack variables as accessible, and emit some epilogue code to
175 un-poison (mark as accessible) the regions of red zones right before
176 the function exits.
92fc5c48 177
eca932e6 178 [Protection of global variables]
92fc5c48 179
eca932e6 180 The basic idea is to insert a red zone between two global variables
181 and install a constructor function that calls the asan runtime to do
182 the populating of the relevant shadow memory regions at load time.
92fc5c48 183
eca932e6 184 So the global variables are laid out as to insert a red zone between
185 them. The size of the red zones is so that each variable starts on a
186 32 bytes boundary.
92fc5c48 187
eca932e6 188 Then a constructor function is installed so that, for each global
189 variable, it calls the runtime asan library function
190 __asan_register_globals_with an instance of this type:
92fc5c48 191
192 struct __asan_global
193 {
194 // Address of the beginning of the global variable.
195 const void *__beg;
196
197 // Initial size of the global variable.
198 uptr __size;
199
200 // Size of the global variable + size of the red zone. This
201 // size is 32 bytes aligned.
202 uptr __size_with_redzone;
203
204 // Name of the global variable.
205 const void *__name;
206
207 // This is always set to NULL for now.
208 uptr __has_dynamic_init;
209 }
210
eca932e6 211 A destructor function that calls the runtime asan library function
212 _asan_unregister_globals is also installed. */
3c919612 213
214alias_set_type asan_shadow_set = -1;
b92cccf4 215
5d5c682b 216/* Pointer types to 1 resp. 2 byte integers in shadow memory. A separate
217 alias set is used for all shadow memory accesses. */
218static GTY(()) tree shadow_ptr_types[2];
219
c31c80df 220/* Hashtable support for memory references used by gimple
221 statements. */
222
223/* This type represents a reference to a memory region. */
224struct asan_mem_ref
225{
a04e8d62 226 /* The expression of the beginning of the memory region. */
c31c80df 227 tree start;
228
229 /* The size of the access (can be 1, 2, 4, 8, 16 for now). */
230 char access_size;
231};
232
233static alloc_pool asan_mem_ref_alloc_pool;
234
235/* This creates the alloc pool used to store the instances of
236 asan_mem_ref that are stored in the hash table asan_mem_ref_ht. */
237
238static alloc_pool
239asan_mem_ref_get_alloc_pool ()
240{
241 if (asan_mem_ref_alloc_pool == NULL)
242 asan_mem_ref_alloc_pool = create_alloc_pool ("asan_mem_ref",
243 sizeof (asan_mem_ref),
244 10);
245 return asan_mem_ref_alloc_pool;
246
247}
248
249/* Initializes an instance of asan_mem_ref. */
250
251static void
252asan_mem_ref_init (asan_mem_ref *ref, tree start, char access_size)
253{
254 ref->start = start;
255 ref->access_size = access_size;
256}
257
258/* Allocates memory for an instance of asan_mem_ref into the memory
259 pool returned by asan_mem_ref_get_alloc_pool and initialize it.
260 START is the address of (or the expression pointing to) the
261 beginning of memory reference. ACCESS_SIZE is the size of the
262 access to the referenced memory. */
263
264static asan_mem_ref*
265asan_mem_ref_new (tree start, char access_size)
266{
267 asan_mem_ref *ref =
268 (asan_mem_ref *) pool_alloc (asan_mem_ref_get_alloc_pool ());
269
270 asan_mem_ref_init (ref, start, access_size);
271 return ref;
272}
273
274/* This builds and returns a pointer to the end of the memory region
275 that starts at START and of length LEN. */
276
277tree
278asan_mem_ref_get_end (tree start, tree len)
279{
280 if (len == NULL_TREE || integer_zerop (len))
281 return start;
282
283 return fold_build2 (POINTER_PLUS_EXPR, TREE_TYPE (start), start, len);
284}
285
286/* Return a tree expression that represents the end of the referenced
287 memory region. Beware that this function can actually build a new
288 tree expression. */
289
290tree
291asan_mem_ref_get_end (const asan_mem_ref *ref, tree len)
292{
293 return asan_mem_ref_get_end (ref->start, len);
294}
295
296struct asan_mem_ref_hasher
297 : typed_noop_remove <asan_mem_ref>
298{
299 typedef asan_mem_ref value_type;
300 typedef asan_mem_ref compare_type;
301
302 static inline hashval_t hash (const value_type *);
303 static inline bool equal (const value_type *, const compare_type *);
304};
305
306/* Hash a memory reference. */
307
308inline hashval_t
309asan_mem_ref_hasher::hash (const asan_mem_ref *mem_ref)
310{
311 hashval_t h = iterative_hash_expr (mem_ref->start, 0);
312 h = iterative_hash_hashval_t (h, mem_ref->access_size);
313 return h;
314}
315
316/* Compare two memory references. We accept the length of either
317 memory references to be NULL_TREE. */
318
319inline bool
320asan_mem_ref_hasher::equal (const asan_mem_ref *m1,
321 const asan_mem_ref *m2)
322{
323 return (m1->access_size == m2->access_size
324 && operand_equal_p (m1->start, m2->start, 0));
325}
326
327static hash_table <asan_mem_ref_hasher> asan_mem_ref_ht;
328
329/* Returns a reference to the hash table containing memory references.
330 This function ensures that the hash table is created. Note that
331 this hash table is updated by the function
332 update_mem_ref_hash_table. */
333
334static hash_table <asan_mem_ref_hasher> &
335get_mem_ref_hash_table ()
336{
337 if (!asan_mem_ref_ht.is_created ())
338 asan_mem_ref_ht.create (10);
339
340 return asan_mem_ref_ht;
341}
342
343/* Clear all entries from the memory references hash table. */
344
345static void
346empty_mem_ref_hash_table ()
347{
348 if (asan_mem_ref_ht.is_created ())
349 asan_mem_ref_ht.empty ();
350}
351
352/* Free the memory references hash table. */
353
354static void
355free_mem_ref_resources ()
356{
357 if (asan_mem_ref_ht.is_created ())
358 asan_mem_ref_ht.dispose ();
359
360 if (asan_mem_ref_alloc_pool)
361 {
362 free_alloc_pool (asan_mem_ref_alloc_pool);
363 asan_mem_ref_alloc_pool = NULL;
364 }
365}
366
367/* Return true iff the memory reference REF has been instrumented. */
368
369static bool
370has_mem_ref_been_instrumented (tree ref, char access_size)
371{
372 asan_mem_ref r;
373 asan_mem_ref_init (&r, ref, access_size);
374
375 return (get_mem_ref_hash_table ().find (&r) != NULL);
376}
377
378/* Return true iff the memory reference REF has been instrumented. */
379
380static bool
381has_mem_ref_been_instrumented (const asan_mem_ref *ref)
382{
383 return has_mem_ref_been_instrumented (ref->start, ref->access_size);
384}
385
386/* Return true iff access to memory region starting at REF and of
387 length LEN has been instrumented. */
388
389static bool
390has_mem_ref_been_instrumented (const asan_mem_ref *ref, tree len)
391{
392 /* First let's see if the address of the beginning of REF has been
393 instrumented. */
394 if (!has_mem_ref_been_instrumented (ref))
395 return false;
396
397 if (len != 0)
398 {
399 /* Let's see if the end of the region has been instrumented. */
400 if (!has_mem_ref_been_instrumented (asan_mem_ref_get_end (ref, len),
401 ref->access_size))
402 return false;
403 }
404 return true;
405}
406
407/* Set REF to the memory reference present in a gimple assignment
408 ASSIGNMENT. Return true upon successful completion, false
409 otherwise. */
410
411static bool
412get_mem_ref_of_assignment (const gimple assignment,
413 asan_mem_ref *ref,
414 bool *ref_is_store)
415{
416 gcc_assert (gimple_assign_single_p (assignment));
417
9f559b20 418 if (gimple_store_p (assignment)
419 && !gimple_clobber_p (assignment))
c31c80df 420 {
421 ref->start = gimple_assign_lhs (assignment);
422 *ref_is_store = true;
423 }
424 else if (gimple_assign_load_p (assignment))
425 {
426 ref->start = gimple_assign_rhs1 (assignment);
427 *ref_is_store = false;
428 }
429 else
430 return false;
431
432 ref->access_size = int_size_in_bytes (TREE_TYPE (ref->start));
433 return true;
434}
435
436/* Return the memory references contained in a gimple statement
437 representing a builtin call that has to do with memory access. */
438
439static bool
440get_mem_refs_of_builtin_call (const gimple call,
441 asan_mem_ref *src0,
442 tree *src0_len,
443 bool *src0_is_store,
444 asan_mem_ref *src1,
445 tree *src1_len,
446 bool *src1_is_store,
447 asan_mem_ref *dst,
448 tree *dst_len,
449 bool *dst_is_store,
450 bool *dest_is_deref)
451{
452 gcc_checking_assert (gimple_call_builtin_p (call, BUILT_IN_NORMAL));
453
454 tree callee = gimple_call_fndecl (call);
455 tree source0 = NULL_TREE, source1 = NULL_TREE,
456 dest = NULL_TREE, len = NULL_TREE;
457 bool is_store = true, got_reference_p = false;
458 char access_size = 1;
459
460 switch (DECL_FUNCTION_CODE (callee))
461 {
462 /* (s, s, n) style memops. */
463 case BUILT_IN_BCMP:
464 case BUILT_IN_MEMCMP:
465 source0 = gimple_call_arg (call, 0);
466 source1 = gimple_call_arg (call, 1);
467 len = gimple_call_arg (call, 2);
468 break;
469
470 /* (src, dest, n) style memops. */
471 case BUILT_IN_BCOPY:
472 source0 = gimple_call_arg (call, 0);
473 dest = gimple_call_arg (call, 1);
474 len = gimple_call_arg (call, 2);
475 break;
476
477 /* (dest, src, n) style memops. */
478 case BUILT_IN_MEMCPY:
479 case BUILT_IN_MEMCPY_CHK:
480 case BUILT_IN_MEMMOVE:
481 case BUILT_IN_MEMMOVE_CHK:
482 case BUILT_IN_MEMPCPY:
483 case BUILT_IN_MEMPCPY_CHK:
484 dest = gimple_call_arg (call, 0);
485 source0 = gimple_call_arg (call, 1);
486 len = gimple_call_arg (call, 2);
487 break;
488
489 /* (dest, n) style memops. */
490 case BUILT_IN_BZERO:
491 dest = gimple_call_arg (call, 0);
492 len = gimple_call_arg (call, 1);
493 break;
494
495 /* (dest, x, n) style memops*/
496 case BUILT_IN_MEMSET:
497 case BUILT_IN_MEMSET_CHK:
498 dest = gimple_call_arg (call, 0);
499 len = gimple_call_arg (call, 2);
500 break;
501
502 case BUILT_IN_STRLEN:
503 source0 = gimple_call_arg (call, 0);
504 len = gimple_call_lhs (call);
505 break ;
506
507 /* And now the __atomic* and __sync builtins.
508 These are handled differently from the classical memory memory
509 access builtins above. */
510
511 case BUILT_IN_ATOMIC_LOAD_1:
512 case BUILT_IN_ATOMIC_LOAD_2:
513 case BUILT_IN_ATOMIC_LOAD_4:
514 case BUILT_IN_ATOMIC_LOAD_8:
515 case BUILT_IN_ATOMIC_LOAD_16:
516 is_store = false;
517 /* fall through. */
518
519 case BUILT_IN_SYNC_FETCH_AND_ADD_1:
520 case BUILT_IN_SYNC_FETCH_AND_ADD_2:
521 case BUILT_IN_SYNC_FETCH_AND_ADD_4:
522 case BUILT_IN_SYNC_FETCH_AND_ADD_8:
523 case BUILT_IN_SYNC_FETCH_AND_ADD_16:
524
525 case BUILT_IN_SYNC_FETCH_AND_SUB_1:
526 case BUILT_IN_SYNC_FETCH_AND_SUB_2:
527 case BUILT_IN_SYNC_FETCH_AND_SUB_4:
528 case BUILT_IN_SYNC_FETCH_AND_SUB_8:
529 case BUILT_IN_SYNC_FETCH_AND_SUB_16:
530
531 case BUILT_IN_SYNC_FETCH_AND_OR_1:
532 case BUILT_IN_SYNC_FETCH_AND_OR_2:
533 case BUILT_IN_SYNC_FETCH_AND_OR_4:
534 case BUILT_IN_SYNC_FETCH_AND_OR_8:
535 case BUILT_IN_SYNC_FETCH_AND_OR_16:
536
537 case BUILT_IN_SYNC_FETCH_AND_AND_1:
538 case BUILT_IN_SYNC_FETCH_AND_AND_2:
539 case BUILT_IN_SYNC_FETCH_AND_AND_4:
540 case BUILT_IN_SYNC_FETCH_AND_AND_8:
541 case BUILT_IN_SYNC_FETCH_AND_AND_16:
542
543 case BUILT_IN_SYNC_FETCH_AND_XOR_1:
544 case BUILT_IN_SYNC_FETCH_AND_XOR_2:
545 case BUILT_IN_SYNC_FETCH_AND_XOR_4:
546 case BUILT_IN_SYNC_FETCH_AND_XOR_8:
547 case BUILT_IN_SYNC_FETCH_AND_XOR_16:
548
549 case BUILT_IN_SYNC_FETCH_AND_NAND_1:
550 case BUILT_IN_SYNC_FETCH_AND_NAND_2:
551 case BUILT_IN_SYNC_FETCH_AND_NAND_4:
552 case BUILT_IN_SYNC_FETCH_AND_NAND_8:
553
554 case BUILT_IN_SYNC_ADD_AND_FETCH_1:
555 case BUILT_IN_SYNC_ADD_AND_FETCH_2:
556 case BUILT_IN_SYNC_ADD_AND_FETCH_4:
557 case BUILT_IN_SYNC_ADD_AND_FETCH_8:
558 case BUILT_IN_SYNC_ADD_AND_FETCH_16:
559
560 case BUILT_IN_SYNC_SUB_AND_FETCH_1:
561 case BUILT_IN_SYNC_SUB_AND_FETCH_2:
562 case BUILT_IN_SYNC_SUB_AND_FETCH_4:
563 case BUILT_IN_SYNC_SUB_AND_FETCH_8:
564 case BUILT_IN_SYNC_SUB_AND_FETCH_16:
565
566 case BUILT_IN_SYNC_OR_AND_FETCH_1:
567 case BUILT_IN_SYNC_OR_AND_FETCH_2:
568 case BUILT_IN_SYNC_OR_AND_FETCH_4:
569 case BUILT_IN_SYNC_OR_AND_FETCH_8:
570 case BUILT_IN_SYNC_OR_AND_FETCH_16:
571
572 case BUILT_IN_SYNC_AND_AND_FETCH_1:
573 case BUILT_IN_SYNC_AND_AND_FETCH_2:
574 case BUILT_IN_SYNC_AND_AND_FETCH_4:
575 case BUILT_IN_SYNC_AND_AND_FETCH_8:
576 case BUILT_IN_SYNC_AND_AND_FETCH_16:
577
578 case BUILT_IN_SYNC_XOR_AND_FETCH_1:
579 case BUILT_IN_SYNC_XOR_AND_FETCH_2:
580 case BUILT_IN_SYNC_XOR_AND_FETCH_4:
581 case BUILT_IN_SYNC_XOR_AND_FETCH_8:
582 case BUILT_IN_SYNC_XOR_AND_FETCH_16:
583
584 case BUILT_IN_SYNC_NAND_AND_FETCH_1:
585 case BUILT_IN_SYNC_NAND_AND_FETCH_2:
586 case BUILT_IN_SYNC_NAND_AND_FETCH_4:
587 case BUILT_IN_SYNC_NAND_AND_FETCH_8:
588
589 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_1:
590 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_2:
591 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_4:
592 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_8:
593 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_16:
594
595 case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_1:
596 case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_2:
597 case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_4:
598 case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_8:
599 case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_16:
600
601 case BUILT_IN_SYNC_LOCK_TEST_AND_SET_1:
602 case BUILT_IN_SYNC_LOCK_TEST_AND_SET_2:
603 case BUILT_IN_SYNC_LOCK_TEST_AND_SET_4:
604 case BUILT_IN_SYNC_LOCK_TEST_AND_SET_8:
605 case BUILT_IN_SYNC_LOCK_TEST_AND_SET_16:
606
607 case BUILT_IN_SYNC_LOCK_RELEASE_1:
608 case BUILT_IN_SYNC_LOCK_RELEASE_2:
609 case BUILT_IN_SYNC_LOCK_RELEASE_4:
610 case BUILT_IN_SYNC_LOCK_RELEASE_8:
611 case BUILT_IN_SYNC_LOCK_RELEASE_16:
612
613 case BUILT_IN_ATOMIC_EXCHANGE_1:
614 case BUILT_IN_ATOMIC_EXCHANGE_2:
615 case BUILT_IN_ATOMIC_EXCHANGE_4:
616 case BUILT_IN_ATOMIC_EXCHANGE_8:
617 case BUILT_IN_ATOMIC_EXCHANGE_16:
618
619 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_1:
620 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_2:
621 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_4:
622 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_8:
623 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_16:
624
625 case BUILT_IN_ATOMIC_STORE_1:
626 case BUILT_IN_ATOMIC_STORE_2:
627 case BUILT_IN_ATOMIC_STORE_4:
628 case BUILT_IN_ATOMIC_STORE_8:
629 case BUILT_IN_ATOMIC_STORE_16:
630
631 case BUILT_IN_ATOMIC_ADD_FETCH_1:
632 case BUILT_IN_ATOMIC_ADD_FETCH_2:
633 case BUILT_IN_ATOMIC_ADD_FETCH_4:
634 case BUILT_IN_ATOMIC_ADD_FETCH_8:
635 case BUILT_IN_ATOMIC_ADD_FETCH_16:
636
637 case BUILT_IN_ATOMIC_SUB_FETCH_1:
638 case BUILT_IN_ATOMIC_SUB_FETCH_2:
639 case BUILT_IN_ATOMIC_SUB_FETCH_4:
640 case BUILT_IN_ATOMIC_SUB_FETCH_8:
641 case BUILT_IN_ATOMIC_SUB_FETCH_16:
642
643 case BUILT_IN_ATOMIC_AND_FETCH_1:
644 case BUILT_IN_ATOMIC_AND_FETCH_2:
645 case BUILT_IN_ATOMIC_AND_FETCH_4:
646 case BUILT_IN_ATOMIC_AND_FETCH_8:
647 case BUILT_IN_ATOMIC_AND_FETCH_16:
648
649 case BUILT_IN_ATOMIC_NAND_FETCH_1:
650 case BUILT_IN_ATOMIC_NAND_FETCH_2:
651 case BUILT_IN_ATOMIC_NAND_FETCH_4:
652 case BUILT_IN_ATOMIC_NAND_FETCH_8:
653 case BUILT_IN_ATOMIC_NAND_FETCH_16:
654
655 case BUILT_IN_ATOMIC_XOR_FETCH_1:
656 case BUILT_IN_ATOMIC_XOR_FETCH_2:
657 case BUILT_IN_ATOMIC_XOR_FETCH_4:
658 case BUILT_IN_ATOMIC_XOR_FETCH_8:
659 case BUILT_IN_ATOMIC_XOR_FETCH_16:
660
661 case BUILT_IN_ATOMIC_OR_FETCH_1:
662 case BUILT_IN_ATOMIC_OR_FETCH_2:
663 case BUILT_IN_ATOMIC_OR_FETCH_4:
664 case BUILT_IN_ATOMIC_OR_FETCH_8:
665 case BUILT_IN_ATOMIC_OR_FETCH_16:
666
667 case BUILT_IN_ATOMIC_FETCH_ADD_1:
668 case BUILT_IN_ATOMIC_FETCH_ADD_2:
669 case BUILT_IN_ATOMIC_FETCH_ADD_4:
670 case BUILT_IN_ATOMIC_FETCH_ADD_8:
671 case BUILT_IN_ATOMIC_FETCH_ADD_16:
672
673 case BUILT_IN_ATOMIC_FETCH_SUB_1:
674 case BUILT_IN_ATOMIC_FETCH_SUB_2:
675 case BUILT_IN_ATOMIC_FETCH_SUB_4:
676 case BUILT_IN_ATOMIC_FETCH_SUB_8:
677 case BUILT_IN_ATOMIC_FETCH_SUB_16:
678
679 case BUILT_IN_ATOMIC_FETCH_AND_1:
680 case BUILT_IN_ATOMIC_FETCH_AND_2:
681 case BUILT_IN_ATOMIC_FETCH_AND_4:
682 case BUILT_IN_ATOMIC_FETCH_AND_8:
683 case BUILT_IN_ATOMIC_FETCH_AND_16:
684
685 case BUILT_IN_ATOMIC_FETCH_NAND_1:
686 case BUILT_IN_ATOMIC_FETCH_NAND_2:
687 case BUILT_IN_ATOMIC_FETCH_NAND_4:
688 case BUILT_IN_ATOMIC_FETCH_NAND_8:
689 case BUILT_IN_ATOMIC_FETCH_NAND_16:
690
691 case BUILT_IN_ATOMIC_FETCH_XOR_1:
692 case BUILT_IN_ATOMIC_FETCH_XOR_2:
693 case BUILT_IN_ATOMIC_FETCH_XOR_4:
694 case BUILT_IN_ATOMIC_FETCH_XOR_8:
695 case BUILT_IN_ATOMIC_FETCH_XOR_16:
696
697 case BUILT_IN_ATOMIC_FETCH_OR_1:
698 case BUILT_IN_ATOMIC_FETCH_OR_2:
699 case BUILT_IN_ATOMIC_FETCH_OR_4:
700 case BUILT_IN_ATOMIC_FETCH_OR_8:
701 case BUILT_IN_ATOMIC_FETCH_OR_16:
702 {
703 dest = gimple_call_arg (call, 0);
704 /* DEST represents the address of a memory location.
705 instrument_derefs wants the memory location, so lets
706 dereference the address DEST before handing it to
707 instrument_derefs. */
708 if (TREE_CODE (dest) == ADDR_EXPR)
709 dest = TREE_OPERAND (dest, 0);
710 else if (TREE_CODE (dest) == SSA_NAME)
711 dest = build2 (MEM_REF, TREE_TYPE (TREE_TYPE (dest)),
712 dest, build_int_cst (TREE_TYPE (dest), 0));
713 else
714 gcc_unreachable ();
715
716 access_size = int_size_in_bytes (TREE_TYPE (dest));
717 }
718
719 default:
720 /* The other builtins memory access are not instrumented in this
721 function because they either don't have any length parameter,
722 or their length parameter is just a limit. */
723 break;
724 }
725
726 if (len != NULL_TREE)
727 {
728 if (source0 != NULL_TREE)
729 {
730 src0->start = source0;
731 src0->access_size = access_size;
732 *src0_len = len;
733 *src0_is_store = false;
734 }
735
736 if (source1 != NULL_TREE)
737 {
738 src1->start = source1;
739 src1->access_size = access_size;
740 *src1_len = len;
741 *src1_is_store = false;
742 }
743
744 if (dest != NULL_TREE)
745 {
746 dst->start = dest;
747 dst->access_size = access_size;
748 *dst_len = len;
749 *dst_is_store = true;
750 }
751
752 got_reference_p = true;
753 }
d9dc05a1 754 else if (dest)
755 {
756 dst->start = dest;
757 dst->access_size = access_size;
758 *dst_len = NULL_TREE;
759 *dst_is_store = is_store;
760 *dest_is_deref = true;
761 got_reference_p = true;
762 }
c31c80df 763
d9dc05a1 764 return got_reference_p;
c31c80df 765}
766
767/* Return true iff a given gimple statement has been instrumented.
768 Note that the statement is "defined" by the memory references it
769 contains. */
770
771static bool
772has_stmt_been_instrumented_p (gimple stmt)
773{
774 if (gimple_assign_single_p (stmt))
775 {
776 bool r_is_store;
777 asan_mem_ref r;
778 asan_mem_ref_init (&r, NULL, 1);
779
780 if (get_mem_ref_of_assignment (stmt, &r, &r_is_store))
781 return has_mem_ref_been_instrumented (&r);
782 }
783 else if (gimple_call_builtin_p (stmt, BUILT_IN_NORMAL))
784 {
785 asan_mem_ref src0, src1, dest;
786 asan_mem_ref_init (&src0, NULL, 1);
787 asan_mem_ref_init (&src1, NULL, 1);
788 asan_mem_ref_init (&dest, NULL, 1);
789
790 tree src0_len = NULL_TREE, src1_len = NULL_TREE, dest_len = NULL_TREE;
791 bool src0_is_store = false, src1_is_store = false,
792 dest_is_store = false, dest_is_deref = false;
793 if (get_mem_refs_of_builtin_call (stmt,
794 &src0, &src0_len, &src0_is_store,
795 &src1, &src1_len, &src1_is_store,
796 &dest, &dest_len, &dest_is_store,
797 &dest_is_deref))
798 {
799 if (src0.start != NULL_TREE
800 && !has_mem_ref_been_instrumented (&src0, src0_len))
801 return false;
802
803 if (src1.start != NULL_TREE
804 && !has_mem_ref_been_instrumented (&src1, src1_len))
805 return false;
806
807 if (dest.start != NULL_TREE
808 && !has_mem_ref_been_instrumented (&dest, dest_len))
809 return false;
810
811 return true;
812 }
813 }
814 return false;
815}
816
817/* Insert a memory reference into the hash table. */
818
819static void
820update_mem_ref_hash_table (tree ref, char access_size)
821{
822 hash_table <asan_mem_ref_hasher> ht = get_mem_ref_hash_table ();
823
824 asan_mem_ref r;
825 asan_mem_ref_init (&r, ref, access_size);
826
827 asan_mem_ref **slot = ht.find_slot (&r, INSERT);
828 if (*slot == NULL)
829 *slot = asan_mem_ref_new (ref, access_size);
830}
831
55b58027 832/* Initialize shadow_ptr_types array. */
833
834static void
835asan_init_shadow_ptr_types (void)
836{
837 asan_shadow_set = new_alias_set ();
838 shadow_ptr_types[0] = build_distinct_type_copy (signed_char_type_node);
839 TYPE_ALIAS_SET (shadow_ptr_types[0]) = asan_shadow_set;
840 shadow_ptr_types[0] = build_pointer_type (shadow_ptr_types[0]);
841 shadow_ptr_types[1] = build_distinct_type_copy (short_integer_type_node);
842 TYPE_ALIAS_SET (shadow_ptr_types[1]) = asan_shadow_set;
843 shadow_ptr_types[1] = build_pointer_type (shadow_ptr_types[1]);
844 initialize_sanitizer_builtins ();
845}
846
b75d2c15 847/* Create ADDR_EXPR of STRING_CST with the PP pretty printer text. */
92fc5c48 848
849static tree
b75d2c15 850asan_pp_string (pretty_printer *pp)
92fc5c48 851{
b75d2c15 852 const char *buf = pp_formatted_text (pp);
92fc5c48 853 size_t len = strlen (buf);
854 tree ret = build_string (len + 1, buf);
855 TREE_TYPE (ret)
55b58027 856 = build_array_type (TREE_TYPE (shadow_ptr_types[0]),
857 build_index_type (size_int (len)));
92fc5c48 858 TREE_READONLY (ret) = 1;
859 TREE_STATIC (ret) = 1;
55b58027 860 return build1 (ADDR_EXPR, shadow_ptr_types[0], ret);
92fc5c48 861}
862
3c919612 863/* Return a CONST_INT representing 4 subsequent shadow memory bytes. */
864
865static rtx
866asan_shadow_cst (unsigned char shadow_bytes[4])
867{
868 int i;
869 unsigned HOST_WIDE_INT val = 0;
870 gcc_assert (WORDS_BIG_ENDIAN == BYTES_BIG_ENDIAN);
871 for (i = 0; i < 4; i++)
872 val |= (unsigned HOST_WIDE_INT) shadow_bytes[BYTES_BIG_ENDIAN ? 3 - i : i]
873 << (BITS_PER_UNIT * i);
bc89f4e2 874 return gen_int_mode (val, SImode);
3c919612 875}
876
cc72d6e9 877/* Clear shadow memory at SHADOW_MEM, LEN bytes. Can't call a library call here
878 though. */
879
880static void
881asan_clear_shadow (rtx shadow_mem, HOST_WIDE_INT len)
882{
883 rtx insn, insns, top_label, end, addr, tmp, jump;
884
885 start_sequence ();
886 clear_storage (shadow_mem, GEN_INT (len), BLOCK_OP_NORMAL);
887 insns = get_insns ();
888 end_sequence ();
889 for (insn = insns; insn; insn = NEXT_INSN (insn))
890 if (CALL_P (insn))
891 break;
892 if (insn == NULL_RTX)
893 {
894 emit_insn (insns);
895 return;
896 }
897
898 gcc_assert ((len & 3) == 0);
899 top_label = gen_label_rtx ();
900 addr = force_reg (Pmode, XEXP (shadow_mem, 0));
901 shadow_mem = adjust_automodify_address (shadow_mem, SImode, addr, 0);
902 end = force_reg (Pmode, plus_constant (Pmode, addr, len));
903 emit_label (top_label);
904
905 emit_move_insn (shadow_mem, const0_rtx);
0359f9f5 906 tmp = expand_simple_binop (Pmode, PLUS, addr, gen_int_mode (4, Pmode), addr,
cc72d6e9 907 true, OPTAB_LIB_WIDEN);
908 if (tmp != addr)
909 emit_move_insn (addr, tmp);
910 emit_cmp_and_jump_insns (addr, end, LT, NULL_RTX, Pmode, true, top_label);
911 jump = get_last_insn ();
912 gcc_assert (JUMP_P (jump));
9eb946de 913 add_int_reg_note (jump, REG_BR_PROB, REG_BR_PROB_BASE * 80 / 100);
cc72d6e9 914}
915
3c919612 916/* Insert code to protect stack vars. The prologue sequence should be emitted
917 directly, epilogue sequence returned. BASE is the register holding the
918 stack base, against which OFFSETS array offsets are relative to, OFFSETS
919 array contains pairs of offsets in reverse order, always the end offset
920 of some gap that needs protection followed by starting offset,
921 and DECLS is an array of representative decls for each var partition.
922 LENGTH is the length of the OFFSETS array, DECLS array is LENGTH / 2 - 1
923 elements long (OFFSETS include gap before the first variable as well
924 as gaps after each stack variable). */
925
926rtx
927asan_emit_stack_protection (rtx base, HOST_WIDE_INT *offsets, tree *decls,
928 int length)
929{
930 rtx shadow_base, shadow_mem, ret, mem;
931 unsigned char shadow_bytes[4];
932 HOST_WIDE_INT base_offset = offsets[length - 1], offset, prev_offset;
933 HOST_WIDE_INT last_offset, last_size;
934 int l;
935 unsigned char cur_shadow_byte = ASAN_STACK_MAGIC_LEFT;
3c919612 936 tree str_cst;
937
55b58027 938 if (shadow_ptr_types[0] == NULL_TREE)
939 asan_init_shadow_ptr_types ();
940
3c919612 941 /* First of all, prepare the description string. */
b75d2c15 942 pretty_printer asan_pp;
eed6bc21 943
3c919612 944 if (DECL_NAME (current_function_decl))
a94db6b0 945 pp_tree_identifier (&asan_pp, DECL_NAME (current_function_decl));
3c919612 946 else
92fc5c48 947 pp_string (&asan_pp, "<unknown>");
948 pp_space (&asan_pp);
949 pp_decimal_int (&asan_pp, length / 2 - 1);
950 pp_space (&asan_pp);
3c919612 951 for (l = length - 2; l; l -= 2)
952 {
953 tree decl = decls[l / 2 - 1];
92fc5c48 954 pp_wide_integer (&asan_pp, offsets[l] - base_offset);
955 pp_space (&asan_pp);
956 pp_wide_integer (&asan_pp, offsets[l - 1] - offsets[l]);
957 pp_space (&asan_pp);
3c919612 958 if (DECL_P (decl) && DECL_NAME (decl))
959 {
92fc5c48 960 pp_decimal_int (&asan_pp, IDENTIFIER_LENGTH (DECL_NAME (decl)));
961 pp_space (&asan_pp);
a94db6b0 962 pp_tree_identifier (&asan_pp, DECL_NAME (decl));
3c919612 963 }
964 else
92fc5c48 965 pp_string (&asan_pp, "9 <unknown>");
966 pp_space (&asan_pp);
3c919612 967 }
b75d2c15 968 str_cst = asan_pp_string (&asan_pp);
3c919612 969
970 /* Emit the prologue sequence. */
0359f9f5 971 base = expand_binop (Pmode, add_optab, base,
972 gen_int_mode (base_offset, Pmode),
3c919612 973 NULL_RTX, 1, OPTAB_DIRECT);
974 mem = gen_rtx_MEM (ptr_mode, base);
d11aedc7 975 emit_move_insn (mem, gen_int_mode (ASAN_STACK_FRAME_MAGIC, ptr_mode));
3c919612 976 mem = adjust_address (mem, VOIDmode, GET_MODE_SIZE (ptr_mode));
977 emit_move_insn (mem, expand_normal (str_cst));
978 shadow_base = expand_binop (Pmode, lshr_optab, base,
979 GEN_INT (ASAN_SHADOW_SHIFT),
980 NULL_RTX, 1, OPTAB_DIRECT);
981 shadow_base = expand_binop (Pmode, add_optab, shadow_base,
0359f9f5 982 gen_int_mode (targetm.asan_shadow_offset (),
983 Pmode),
3c919612 984 NULL_RTX, 1, OPTAB_DIRECT);
985 gcc_assert (asan_shadow_set != -1
986 && (ASAN_RED_ZONE_SIZE >> ASAN_SHADOW_SHIFT) == 4);
987 shadow_mem = gen_rtx_MEM (SImode, shadow_base);
988 set_mem_alias_set (shadow_mem, asan_shadow_set);
989 prev_offset = base_offset;
990 for (l = length; l; l -= 2)
991 {
992 if (l == 2)
993 cur_shadow_byte = ASAN_STACK_MAGIC_RIGHT;
994 offset = offsets[l - 1];
995 if ((offset - base_offset) & (ASAN_RED_ZONE_SIZE - 1))
996 {
997 int i;
998 HOST_WIDE_INT aoff
999 = base_offset + ((offset - base_offset)
1000 & ~(ASAN_RED_ZONE_SIZE - HOST_WIDE_INT_1));
1001 shadow_mem = adjust_address (shadow_mem, VOIDmode,
1002 (aoff - prev_offset)
1003 >> ASAN_SHADOW_SHIFT);
1004 prev_offset = aoff;
1005 for (i = 0; i < 4; i++, aoff += (1 << ASAN_SHADOW_SHIFT))
1006 if (aoff < offset)
1007 {
1008 if (aoff < offset - (1 << ASAN_SHADOW_SHIFT) + 1)
1009 shadow_bytes[i] = 0;
1010 else
1011 shadow_bytes[i] = offset - aoff;
1012 }
1013 else
1014 shadow_bytes[i] = ASAN_STACK_MAGIC_PARTIAL;
1015 emit_move_insn (shadow_mem, asan_shadow_cst (shadow_bytes));
1016 offset = aoff;
1017 }
1018 while (offset <= offsets[l - 2] - ASAN_RED_ZONE_SIZE)
1019 {
1020 shadow_mem = adjust_address (shadow_mem, VOIDmode,
1021 (offset - prev_offset)
1022 >> ASAN_SHADOW_SHIFT);
1023 prev_offset = offset;
1024 memset (shadow_bytes, cur_shadow_byte, 4);
1025 emit_move_insn (shadow_mem, asan_shadow_cst (shadow_bytes));
1026 offset += ASAN_RED_ZONE_SIZE;
1027 }
1028 cur_shadow_byte = ASAN_STACK_MAGIC_MIDDLE;
1029 }
1030 do_pending_stack_adjust ();
1031
1032 /* Construct epilogue sequence. */
1033 start_sequence ();
1034
1035 shadow_mem = gen_rtx_MEM (BLKmode, shadow_base);
1036 set_mem_alias_set (shadow_mem, asan_shadow_set);
1037 prev_offset = base_offset;
1038 last_offset = base_offset;
1039 last_size = 0;
1040 for (l = length; l; l -= 2)
1041 {
1042 offset = base_offset + ((offsets[l - 1] - base_offset)
1043 & ~(ASAN_RED_ZONE_SIZE - HOST_WIDE_INT_1));
1044 if (last_offset + last_size != offset)
1045 {
1046 shadow_mem = adjust_address (shadow_mem, VOIDmode,
1047 (last_offset - prev_offset)
1048 >> ASAN_SHADOW_SHIFT);
1049 prev_offset = last_offset;
cc72d6e9 1050 asan_clear_shadow (shadow_mem, last_size >> ASAN_SHADOW_SHIFT);
3c919612 1051 last_offset = offset;
1052 last_size = 0;
1053 }
1054 last_size += base_offset + ((offsets[l - 2] - base_offset)
1055 & ~(ASAN_RED_ZONE_SIZE - HOST_WIDE_INT_1))
1056 - offset;
1057 }
1058 if (last_size)
1059 {
1060 shadow_mem = adjust_address (shadow_mem, VOIDmode,
1061 (last_offset - prev_offset)
1062 >> ASAN_SHADOW_SHIFT);
cc72d6e9 1063 asan_clear_shadow (shadow_mem, last_size >> ASAN_SHADOW_SHIFT);
3c919612 1064 }
1065
1066 do_pending_stack_adjust ();
1067
1068 ret = get_insns ();
1069 end_sequence ();
1070 return ret;
1071}
1072
92fc5c48 1073/* Return true if DECL, a global var, might be overridden and needs
1074 therefore a local alias. */
1075
1076static bool
1077asan_needs_local_alias (tree decl)
1078{
1079 return DECL_WEAK (decl) || !targetm.binds_local_p (decl);
1080}
1081
1082/* Return true if DECL is a VAR_DECL that should be protected
1083 by Address Sanitizer, by appending a red zone with protected
1084 shadow memory after it and aligning it to at least
1085 ASAN_RED_ZONE_SIZE bytes. */
1086
1087bool
1088asan_protect_global (tree decl)
1089{
1090 rtx rtl, symbol;
92fc5c48 1091
55b58027 1092 if (TREE_CODE (decl) == STRING_CST)
1093 {
1094 /* Instrument all STRING_CSTs except those created
1095 by asan_pp_string here. */
1096 if (shadow_ptr_types[0] != NULL_TREE
1097 && TREE_CODE (TREE_TYPE (decl)) == ARRAY_TYPE
1098 && TREE_TYPE (TREE_TYPE (decl)) == TREE_TYPE (shadow_ptr_types[0]))
1099 return false;
1100 return true;
1101 }
92fc5c48 1102 if (TREE_CODE (decl) != VAR_DECL
1103 /* TLS vars aren't statically protectable. */
1104 || DECL_THREAD_LOCAL_P (decl)
1105 /* Externs will be protected elsewhere. */
1106 || DECL_EXTERNAL (decl)
92fc5c48 1107 || !DECL_RTL_SET_P (decl)
1108 /* Comdat vars pose an ABI problem, we can't know if
1109 the var that is selected by the linker will have
1110 padding or not. */
1111 || DECL_ONE_ONLY (decl)
1112 /* Similarly for common vars. People can use -fno-common. */
1ba1559d 1113 || (DECL_COMMON (decl) && TREE_PUBLIC (decl))
92fc5c48 1114 /* Don't protect if using user section, often vars placed
1115 into user section from multiple TUs are then assumed
1116 to be an array of such vars, putting padding in there
1117 breaks this assumption. */
1118 || (DECL_SECTION_NAME (decl) != NULL_TREE
1119 && !DECL_HAS_IMPLICIT_SECTION_NAME_P (decl))
1120 || DECL_SIZE (decl) == 0
1121 || ASAN_RED_ZONE_SIZE * BITS_PER_UNIT > MAX_OFILE_ALIGNMENT
1122 || !valid_constant_size_p (DECL_SIZE_UNIT (decl))
1123 || DECL_ALIGN_UNIT (decl) > 2 * ASAN_RED_ZONE_SIZE)
1124 return false;
1125
1126 rtl = DECL_RTL (decl);
1127 if (!MEM_P (rtl) || GET_CODE (XEXP (rtl, 0)) != SYMBOL_REF)
1128 return false;
1129 symbol = XEXP (rtl, 0);
1130
1131 if (CONSTANT_POOL_ADDRESS_P (symbol)
1132 || TREE_CONSTANT_POOL_ADDRESS_P (symbol))
1133 return false;
1134
92fc5c48 1135 if (lookup_attribute ("weakref", DECL_ATTRIBUTES (decl)))
1136 return false;
1137
1138#ifndef ASM_OUTPUT_DEF
1139 if (asan_needs_local_alias (decl))
1140 return false;
1141#endif
1142
eca932e6 1143 return true;
92fc5c48 1144}
1145
b92cccf4 1146/* Construct a function tree for __asan_report_{load,store}{1,2,4,8,16}.
1147 IS_STORE is either 1 (for a store) or 0 (for a load).
1148 SIZE_IN_BYTES is one of 1, 2, 4, 8, 16. */
1149
1150static tree
5d5c682b 1151report_error_func (bool is_store, int size_in_bytes)
b92cccf4 1152{
b45e34ed 1153 static enum built_in_function report[2][5]
1154 = { { BUILT_IN_ASAN_REPORT_LOAD1, BUILT_IN_ASAN_REPORT_LOAD2,
1155 BUILT_IN_ASAN_REPORT_LOAD4, BUILT_IN_ASAN_REPORT_LOAD8,
1156 BUILT_IN_ASAN_REPORT_LOAD16 },
1157 { BUILT_IN_ASAN_REPORT_STORE1, BUILT_IN_ASAN_REPORT_STORE2,
1158 BUILT_IN_ASAN_REPORT_STORE4, BUILT_IN_ASAN_REPORT_STORE8,
1159 BUILT_IN_ASAN_REPORT_STORE16 } };
1160 return builtin_decl_implicit (report[is_store][exact_log2 (size_in_bytes)]);
b92cccf4 1161}
1162
5d5c682b 1163#define PROB_VERY_UNLIKELY (REG_BR_PROB_BASE / 2000 - 1)
1164#define PROB_ALWAYS (REG_BR_PROB_BASE)
1165
aab92688 1166/* Split the current basic block and create a condition statement
1ac3509e 1167 insertion point right before or after the statement pointed to by
1168 ITER. Return an iterator to the point at which the caller might
1169 safely insert the condition statement.
aab92688 1170
1171 THEN_BLOCK must be set to the address of an uninitialized instance
1172 of basic_block. The function will then set *THEN_BLOCK to the
1173 'then block' of the condition statement to be inserted by the
1174 caller.
1175
e8d4d8a9 1176 If CREATE_THEN_FALLTHRU_EDGE is false, no edge will be created from
1177 *THEN_BLOCK to *FALLTHROUGH_BLOCK.
1178
aab92688 1179 Similarly, the function will set *FALLTRHOUGH_BLOCK to the 'else
1180 block' of the condition statement to be inserted by the caller.
1181
1182 Note that *FALLTHROUGH_BLOCK is a new block that contains the
1183 statements starting from *ITER, and *THEN_BLOCK is a new empty
1184 block.
1185
1ac3509e 1186 *ITER is adjusted to point to always point to the first statement
1187 of the basic block * FALLTHROUGH_BLOCK. That statement is the
1188 same as what ITER was pointing to prior to calling this function,
1189 if BEFORE_P is true; otherwise, it is its following statement. */
aab92688 1190
1191static gimple_stmt_iterator
1ac3509e 1192create_cond_insert_point (gimple_stmt_iterator *iter,
1193 bool before_p,
1194 bool then_more_likely_p,
e8d4d8a9 1195 bool create_then_fallthru_edge,
1ac3509e 1196 basic_block *then_block,
1197 basic_block *fallthrough_block)
aab92688 1198{
1199 gimple_stmt_iterator gsi = *iter;
1200
1ac3509e 1201 if (!gsi_end_p (gsi) && before_p)
aab92688 1202 gsi_prev (&gsi);
1203
1204 basic_block cur_bb = gsi_bb (*iter);
1205
1206 edge e = split_block (cur_bb, gsi_stmt (gsi));
1207
1208 /* Get a hold on the 'condition block', the 'then block' and the
1209 'else block'. */
1210 basic_block cond_bb = e->src;
1211 basic_block fallthru_bb = e->dest;
1212 basic_block then_bb = create_empty_bb (cond_bb);
f6568ea4 1213 if (current_loops)
1214 {
1215 add_bb_to_loop (then_bb, cond_bb->loop_father);
1216 loops_state_set (LOOPS_NEED_FIXUP);
1217 }
aab92688 1218
1219 /* Set up the newly created 'then block'. */
1220 e = make_edge (cond_bb, then_bb, EDGE_TRUE_VALUE);
1221 int fallthrough_probability
1222 = then_more_likely_p
1223 ? PROB_VERY_UNLIKELY
1224 : PROB_ALWAYS - PROB_VERY_UNLIKELY;
1225 e->probability = PROB_ALWAYS - fallthrough_probability;
e8d4d8a9 1226 if (create_then_fallthru_edge)
1227 make_single_succ_edge (then_bb, fallthru_bb, EDGE_FALLTHRU);
aab92688 1228
1229 /* Set up the fallthrough basic block. */
1230 e = find_edge (cond_bb, fallthru_bb);
1231 e->flags = EDGE_FALSE_VALUE;
1232 e->count = cond_bb->count;
1233 e->probability = fallthrough_probability;
1234
1235 /* Update dominance info for the newly created then_bb; note that
1236 fallthru_bb's dominance info has already been updated by
1237 split_bock. */
1238 if (dom_info_available_p (CDI_DOMINATORS))
1239 set_immediate_dominator (CDI_DOMINATORS, then_bb, cond_bb);
1240
1241 *then_block = then_bb;
1242 *fallthrough_block = fallthru_bb;
1243 *iter = gsi_start_bb (fallthru_bb);
1244
1245 return gsi_last_bb (cond_bb);
1246}
1247
1ac3509e 1248/* Insert an if condition followed by a 'then block' right before the
1249 statement pointed to by ITER. The fallthrough block -- which is the
1250 else block of the condition as well as the destination of the
1251 outcoming edge of the 'then block' -- starts with the statement
1252 pointed to by ITER.
1253
eca932e6 1254 COND is the condition of the if.
1ac3509e 1255
1256 If THEN_MORE_LIKELY_P is true, the probability of the edge to the
1257 'then block' is higher than the probability of the edge to the
1258 fallthrough block.
1259
1260 Upon completion of the function, *THEN_BB is set to the newly
1261 inserted 'then block' and similarly, *FALLTHROUGH_BB is set to the
1262 fallthrough block.
1263
1264 *ITER is adjusted to still point to the same statement it was
1265 pointing to initially. */
1266
1267static void
1268insert_if_then_before_iter (gimple cond,
1269 gimple_stmt_iterator *iter,
1270 bool then_more_likely_p,
1271 basic_block *then_bb,
1272 basic_block *fallthrough_bb)
1273{
1274 gimple_stmt_iterator cond_insert_point =
1275 create_cond_insert_point (iter,
1276 /*before_p=*/true,
1277 then_more_likely_p,
e8d4d8a9 1278 /*create_then_fallthru_edge=*/true,
1ac3509e 1279 then_bb,
1280 fallthrough_bb);
1281 gsi_insert_after (&cond_insert_point, cond, GSI_NEW_STMT);
1282}
1283
c91b0fff 1284/* Instrument the memory access instruction BASE. Insert new
1ac3509e 1285 statements before or after ITER.
c91b0fff 1286
1287 Note that the memory access represented by BASE can be either an
1288 SSA_NAME, or a non-SSA expression. LOCATION is the source code
1289 location. IS_STORE is TRUE for a store, FALSE for a load.
1ac3509e 1290 BEFORE_P is TRUE for inserting the instrumentation code before
1291 ITER, FALSE for inserting it after ITER. SIZE_IN_BYTES is one of
1292 1, 2, 4, 8, 16.
1293
1294 If BEFORE_P is TRUE, *ITER is arranged to still point to the
1295 statement it was pointing to prior to calling this function,
1296 otherwise, it points to the statement logically following it. */
b92cccf4 1297
1298static void
1ac3509e 1299build_check_stmt (location_t location, tree base, gimple_stmt_iterator *iter,
1300 bool before_p, bool is_store, int size_in_bytes)
b92cccf4 1301{
1302 gimple_stmt_iterator gsi;
aab92688 1303 basic_block then_bb, else_bb;
5d5c682b 1304 tree t, base_addr, shadow;
b92cccf4 1305 gimple g;
5d5c682b 1306 tree shadow_ptr_type = shadow_ptr_types[size_in_bytes == 16 ? 1 : 0];
1307 tree shadow_type = TREE_TYPE (shadow_ptr_type);
1308 tree uintptr_type
1309 = build_nonstandard_integer_type (TYPE_PRECISION (TREE_TYPE (base)), 1);
c91b0fff 1310 tree base_ssa = base;
b92cccf4 1311
aab92688 1312 /* Get an iterator on the point where we can add the condition
1313 statement for the instrumentation. */
1ac3509e 1314 gsi = create_cond_insert_point (iter, before_p,
1315 /*then_more_likely_p=*/false,
e8d4d8a9 1316 /*create_then_fallthru_edge=*/false,
1ac3509e 1317 &then_bb,
1318 &else_bb);
b92cccf4 1319
5d5c682b 1320 base = unshare_expr (base);
b92cccf4 1321
c91b0fff 1322 /* BASE can already be an SSA_NAME; in that case, do not create a
1323 new SSA_NAME for it. */
1324 if (TREE_CODE (base) != SSA_NAME)
1325 {
1326 g = gimple_build_assign_with_ops (TREE_CODE (base),
1327 make_ssa_name (TREE_TYPE (base), NULL),
1328 base, NULL_TREE);
1329 gimple_set_location (g, location);
1330 gsi_insert_after (&gsi, g, GSI_NEW_STMT);
1331 base_ssa = gimple_assign_lhs (g);
1332 }
b92cccf4 1333
5d5c682b 1334 g = gimple_build_assign_with_ops (NOP_EXPR,
1335 make_ssa_name (uintptr_type, NULL),
c91b0fff 1336 base_ssa, NULL_TREE);
b92cccf4 1337 gimple_set_location (g, location);
5d5c682b 1338 gsi_insert_after (&gsi, g, GSI_NEW_STMT);
1339 base_addr = gimple_assign_lhs (g);
b92cccf4 1340
5d5c682b 1341 /* Build
1342 (base_addr >> ASAN_SHADOW_SHIFT) + targetm.asan_shadow_offset (). */
b92cccf4 1343
5d5c682b 1344 t = build_int_cst (uintptr_type, ASAN_SHADOW_SHIFT);
1345 g = gimple_build_assign_with_ops (RSHIFT_EXPR,
1346 make_ssa_name (uintptr_type, NULL),
1347 base_addr, t);
b92cccf4 1348 gimple_set_location (g, location);
5d5c682b 1349 gsi_insert_after (&gsi, g, GSI_NEW_STMT);
1350
1351 t = build_int_cst (uintptr_type, targetm.asan_shadow_offset ());
1352 g = gimple_build_assign_with_ops (PLUS_EXPR,
1353 make_ssa_name (uintptr_type, NULL),
1354 gimple_assign_lhs (g), t);
b92cccf4 1355 gimple_set_location (g, location);
5d5c682b 1356 gsi_insert_after (&gsi, g, GSI_NEW_STMT);
b92cccf4 1357
5d5c682b 1358 g = gimple_build_assign_with_ops (NOP_EXPR,
1359 make_ssa_name (shadow_ptr_type, NULL),
1360 gimple_assign_lhs (g), NULL_TREE);
1361 gimple_set_location (g, location);
1362 gsi_insert_after (&gsi, g, GSI_NEW_STMT);
b92cccf4 1363
5d5c682b 1364 t = build2 (MEM_REF, shadow_type, gimple_assign_lhs (g),
1365 build_int_cst (shadow_ptr_type, 0));
1366 g = gimple_build_assign_with_ops (MEM_REF,
1367 make_ssa_name (shadow_type, NULL),
1368 t, NULL_TREE);
1369 gimple_set_location (g, location);
1370 gsi_insert_after (&gsi, g, GSI_NEW_STMT);
1371 shadow = gimple_assign_lhs (g);
1372
1373 if (size_in_bytes < 8)
1374 {
1375 /* Slow path for 1, 2 and 4 byte accesses.
1376 Test (shadow != 0)
1377 & ((base_addr & 7) + (size_in_bytes - 1)) >= shadow). */
32bd7708 1378 gimple_seq seq = NULL;
1379 gimple shadow_test = build_assign (NE_EXPR, shadow, 0);
1380 gimple_seq_add_stmt (&seq, shadow_test);
1381 gimple_seq_add_stmt (&seq, build_assign (BIT_AND_EXPR, base_addr, 7));
1382 gimple_seq_add_stmt (&seq, build_type_cast (shadow_type,
1383 gimple_seq_last (seq)));
5d5c682b 1384 if (size_in_bytes > 1)
32bd7708 1385 gimple_seq_add_stmt (&seq,
1386 build_assign (PLUS_EXPR, gimple_seq_last (seq),
1387 size_in_bytes - 1));
1388 gimple_seq_add_stmt (&seq, build_assign (GE_EXPR, gimple_seq_last (seq),
1389 shadow));
1390 gimple_seq_add_stmt (&seq, build_assign (BIT_AND_EXPR, shadow_test,
1391 gimple_seq_last (seq)));
1392 t = gimple_assign_lhs (gimple_seq_last (seq));
1393 gimple_seq_set_location (seq, location);
1394 gsi_insert_seq_after (&gsi, seq, GSI_CONTINUE_LINKING);
5d5c682b 1395 }
1396 else
1397 t = shadow;
b92cccf4 1398
5d5c682b 1399 g = gimple_build_cond (NE_EXPR, t, build_int_cst (TREE_TYPE (t), 0),
1400 NULL_TREE, NULL_TREE);
1401 gimple_set_location (g, location);
1402 gsi_insert_after (&gsi, g, GSI_NEW_STMT);
b92cccf4 1403
5d5c682b 1404 /* Generate call to the run-time library (e.g. __asan_report_load8). */
b92cccf4 1405 gsi = gsi_start_bb (then_bb);
5d5c682b 1406 g = gimple_build_call (report_error_func (is_store, size_in_bytes),
1407 1, base_addr);
1408 gimple_set_location (g, location);
1409 gsi_insert_after (&gsi, g, GSI_NEW_STMT);
b92cccf4 1410
8293ee35 1411 *iter = gsi_start_bb (else_bb);
b92cccf4 1412}
1413
1414/* If T represents a memory access, add instrumentation code before ITER.
1415 LOCATION is source code location.
1ac3509e 1416 IS_STORE is either TRUE (for a store) or FALSE (for a load). */
b92cccf4 1417
1418static void
1419instrument_derefs (gimple_stmt_iterator *iter, tree t,
c31c80df 1420 location_t location, bool is_store)
b92cccf4 1421{
1422 tree type, base;
5d5c682b 1423 HOST_WIDE_INT size_in_bytes;
b92cccf4 1424
1425 type = TREE_TYPE (t);
b92cccf4 1426 switch (TREE_CODE (t))
1427 {
1428 case ARRAY_REF:
1429 case COMPONENT_REF:
1430 case INDIRECT_REF:
1431 case MEM_REF:
1432 break;
1433 default:
1434 return;
1435 }
5d5c682b 1436
1437 size_in_bytes = int_size_in_bytes (type);
1438 if ((size_in_bytes & (size_in_bytes - 1)) != 0
1439 || (unsigned HOST_WIDE_INT) size_in_bytes - 1 >= 16)
1440 return;
1441
5d5c682b 1442 HOST_WIDE_INT bitsize, bitpos;
1443 tree offset;
1444 enum machine_mode mode;
1445 int volatilep = 0, unsignedp = 0;
1446 get_inner_reference (t, &bitsize, &bitpos, &offset,
1447 &mode, &unsignedp, &volatilep, false);
1ac3509e 1448 if (bitpos % (size_in_bytes * BITS_PER_UNIT)
1449 || bitsize != size_in_bytes * BITS_PER_UNIT)
9ffeb5ce 1450 {
1451 if (TREE_CODE (t) == COMPONENT_REF
1452 && DECL_BIT_FIELD_REPRESENTATIVE (TREE_OPERAND (t, 1)) != NULL_TREE)
1453 {
1454 tree repr = DECL_BIT_FIELD_REPRESENTATIVE (TREE_OPERAND (t, 1));
1455 instrument_derefs (iter, build3 (COMPONENT_REF, TREE_TYPE (repr),
1456 TREE_OPERAND (t, 0), repr,
1457 NULL_TREE), location, is_store);
1458 }
1459 return;
1460 }
5d5c682b 1461
1462 base = build_fold_addr_expr (t);
c31c80df 1463 if (!has_mem_ref_been_instrumented (base, size_in_bytes))
1464 {
1465 build_check_stmt (location, base, iter, /*before_p=*/true,
1466 is_store, size_in_bytes);
1467 update_mem_ref_hash_table (base, size_in_bytes);
1468 update_mem_ref_hash_table (t, size_in_bytes);
1469 }
1470
1ac3509e 1471}
1472
1473/* Instrument an access to a contiguous memory region that starts at
1474 the address pointed to by BASE, over a length of LEN (expressed in
1475 the sizeof (*BASE) bytes). ITER points to the instruction before
1476 which the instrumentation instructions must be inserted. LOCATION
1477 is the source location that the instrumentation instructions must
1478 have. If IS_STORE is true, then the memory access is a store;
1479 otherwise, it's a load. */
1480
1481static void
1482instrument_mem_region_access (tree base, tree len,
1483 gimple_stmt_iterator *iter,
1484 location_t location, bool is_store)
1485{
94dbcbb6 1486 if (!POINTER_TYPE_P (TREE_TYPE (base))
1487 || !INTEGRAL_TYPE_P (TREE_TYPE (len))
1488 || integer_zerop (len))
1ac3509e 1489 return;
1490
1491 gimple_stmt_iterator gsi = *iter;
1492
1493 basic_block fallthrough_bb = NULL, then_bb = NULL;
c31c80df 1494
1495 /* If the beginning of the memory region has already been
1496 instrumented, do not instrument it. */
d9dc05a1 1497 bool start_instrumented = has_mem_ref_been_instrumented (base, 1);
1498
1499 /* If the end of the memory region has already been instrumented, do
1500 not instrument it. */
1501 tree end = asan_mem_ref_get_end (base, len);
1502 bool end_instrumented = has_mem_ref_been_instrumented (end, 1);
1503
1504 if (start_instrumented && end_instrumented)
1505 return;
c31c80df 1506
1ac3509e 1507 if (!is_gimple_constant (len))
1508 {
1509 /* So, the length of the memory area to asan-protect is
1510 non-constant. Let's guard the generated instrumentation code
1511 like:
1512
1513 if (len != 0)
1514 {
1515 //asan instrumentation code goes here.
eca932e6 1516 }
1ac3509e 1517 // falltrough instructions, starting with *ITER. */
1518
1519 gimple g = gimple_build_cond (NE_EXPR,
1520 len,
1521 build_int_cst (TREE_TYPE (len), 0),
1522 NULL_TREE, NULL_TREE);
1523 gimple_set_location (g, location);
1524 insert_if_then_before_iter (g, iter, /*then_more_likely_p=*/true,
1525 &then_bb, &fallthrough_bb);
1526 /* Note that fallthrough_bb starts with the statement that was
1527 pointed to by ITER. */
1528
1529 /* The 'then block' of the 'if (len != 0) condition is where
1530 we'll generate the asan instrumentation code now. */
d9dc05a1 1531 gsi = gsi_last_bb (then_bb);
1ac3509e 1532 }
1533
d9dc05a1 1534 if (!start_instrumented)
1535 {
1536 /* Instrument the beginning of the memory region to be accessed,
1537 and arrange for the rest of the intrumentation code to be
1538 inserted in the then block *after* the current gsi. */
1539 build_check_stmt (location, base, &gsi, /*before_p=*/true, is_store, 1);
1540
1541 if (then_bb)
1542 /* We are in the case where the length of the region is not
1543 constant; so instrumentation code is being generated in the
1544 'then block' of the 'if (len != 0) condition. Let's arrange
1545 for the subsequent instrumentation statements to go in the
1546 'then block'. */
1547 gsi = gsi_last_bb (then_bb);
1548 else
1549 {
1550 *iter = gsi;
1551 /* Don't remember this access as instrumented, if length
1552 is unknown. It might be zero and not being actually
1553 instrumented, so we can't rely on it being instrumented. */
1554 update_mem_ref_hash_table (base, 1);
1555 }
1556 }
c31c80df 1557
d9dc05a1 1558 if (end_instrumented)
1559 return;
c31c80df 1560
1ac3509e 1561 /* We want to instrument the access at the end of the memory region,
1562 which is at (base + len - 1). */
1563
1564 /* offset = len - 1; */
1565 len = unshare_expr (len);
94dbcbb6 1566 tree offset;
1567 gimple_seq seq = NULL;
1568 if (TREE_CODE (len) == INTEGER_CST)
1569 offset = fold_build2 (MINUS_EXPR, size_type_node,
1570 fold_convert (size_type_node, len),
1571 build_int_cst (size_type_node, 1));
1572 else
1573 {
1574 gimple g;
1575 tree t;
1576
1577 if (TREE_CODE (len) != SSA_NAME)
1578 {
1579 t = make_ssa_name (TREE_TYPE (len), NULL);
1580 g = gimple_build_assign_with_ops (TREE_CODE (len), t, len, NULL);
1581 gimple_set_location (g, location);
1582 gimple_seq_add_stmt_without_update (&seq, g);
1583 len = t;
1584 }
1585 if (!useless_type_conversion_p (size_type_node, TREE_TYPE (len)))
1586 {
1587 t = make_ssa_name (size_type_node, NULL);
1588 g = gimple_build_assign_with_ops (NOP_EXPR, t, len, NULL);
1589 gimple_set_location (g, location);
1590 gimple_seq_add_stmt_without_update (&seq, g);
1591 len = t;
1592 }
1593
1594 t = make_ssa_name (size_type_node, NULL);
1595 g = gimple_build_assign_with_ops (MINUS_EXPR, t, len,
1596 build_int_cst (size_type_node, 1));
1597 gimple_set_location (g, location);
c31c80df 1598 gimple_seq_add_stmt_without_update (&seq, g);
1599 offset = gimple_assign_lhs (g);
1600 }
1ac3509e 1601
c31c80df 1602 /* _1 = base; */
1603 base = unshare_expr (base);
1604 gimple region_end =
1605 gimple_build_assign_with_ops (TREE_CODE (base),
1606 make_ssa_name (TREE_TYPE (base), NULL),
1607 base, NULL);
1608 gimple_set_location (region_end, location);
1609 gimple_seq_add_stmt_without_update (&seq, region_end);
1ac3509e 1610
c31c80df 1611 /* _2 = _1 + offset; */
1612 region_end =
1613 gimple_build_assign_with_ops (POINTER_PLUS_EXPR,
1614 make_ssa_name (TREE_TYPE (base), NULL),
1615 gimple_assign_lhs (region_end),
1616 offset);
1617 gimple_set_location (region_end, location);
d9dc05a1 1618 gimple_seq_add_stmt_without_update (&seq, region_end);
1619 gsi_insert_seq_before (&gsi, seq, GSI_SAME_STMT);
1ac3509e 1620
c31c80df 1621 /* instrument access at _2; */
d9dc05a1 1622 gsi = gsi_for_stmt (region_end);
c31c80df 1623 build_check_stmt (location, gimple_assign_lhs (region_end),
1624 &gsi, /*before_p=*/false, is_store, 1);
1ac3509e 1625
d9dc05a1 1626 if (then_bb == NULL)
1627 update_mem_ref_hash_table (end, 1);
1628
1629 *iter = gsi_for_stmt (gsi_stmt (*iter));
c31c80df 1630}
1ac3509e 1631
c31c80df 1632/* Instrument the call (to the builtin strlen function) pointed to by
1633 ITER.
1ac3509e 1634
c31c80df 1635 This function instruments the access to the first byte of the
1636 argument, right before the call. After the call it instruments the
1637 access to the last byte of the argument; it uses the result of the
1638 call to deduce the offset of that last byte.
1ac3509e 1639
e4849b47 1640 Upon completion, iff the call has actually been instrumented, this
c31c80df 1641 function returns TRUE and *ITER points to the statement logically
1642 following the built-in strlen function call *ITER was initially
1643 pointing to. Otherwise, the function returns FALSE and *ITER
1644 remains unchanged. */
1ac3509e 1645
c31c80df 1646static bool
1647instrument_strlen_call (gimple_stmt_iterator *iter)
1648{
1649 gimple call = gsi_stmt (*iter);
1650 gcc_assert (is_gimple_call (call));
1ac3509e 1651
c31c80df 1652 tree callee = gimple_call_fndecl (call);
1653 gcc_assert (is_builtin_fn (callee)
1654 && DECL_BUILT_IN_CLASS (callee) == BUILT_IN_NORMAL
1655 && DECL_FUNCTION_CODE (callee) == BUILT_IN_STRLEN);
1ac3509e 1656
c31c80df 1657 tree len = gimple_call_lhs (call);
1658 if (len == NULL)
1659 /* Some passes might clear the return value of the strlen call;
1660 bail out in that case. Return FALSE as we are not advancing
1661 *ITER. */
1662 return false;
1663 gcc_assert (INTEGRAL_TYPE_P (TREE_TYPE (len)));
1ac3509e 1664
c31c80df 1665 location_t loc = gimple_location (call);
1666 tree str_arg = gimple_call_arg (call, 0);
1ac3509e 1667
c31c80df 1668 /* Instrument the access to the first byte of str_arg. i.e:
1ac3509e 1669
c31c80df 1670 _1 = str_arg; instrument (_1); */
e4849b47 1671 tree cptr_type = build_pointer_type (char_type_node);
c31c80df 1672 gimple str_arg_ssa =
1673 gimple_build_assign_with_ops (NOP_EXPR,
e4849b47 1674 make_ssa_name (cptr_type, NULL),
c31c80df 1675 str_arg, NULL);
1676 gimple_set_location (str_arg_ssa, loc);
1677 gimple_stmt_iterator gsi = *iter;
1678 gsi_insert_before (&gsi, str_arg_ssa, GSI_NEW_STMT);
1679 build_check_stmt (loc, gimple_assign_lhs (str_arg_ssa), &gsi,
1680 /*before_p=*/false, /*is_store=*/false, 1);
1ac3509e 1681
c31c80df 1682 /* If we initially had an instruction like:
1ac3509e 1683
c31c80df 1684 int n = strlen (str)
1ac3509e 1685
c31c80df 1686 we now want to instrument the access to str[n], after the
1687 instruction above.*/
1ac3509e 1688
c31c80df 1689 /* So let's build the access to str[n] that is, access through the
1690 pointer_plus expr: (_1 + len). */
1691 gimple stmt =
1692 gimple_build_assign_with_ops (POINTER_PLUS_EXPR,
e4849b47 1693 make_ssa_name (cptr_type, NULL),
c31c80df 1694 gimple_assign_lhs (str_arg_ssa),
1695 len);
1696 gimple_set_location (stmt, loc);
1697 gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
1ac3509e 1698
c31c80df 1699 build_check_stmt (loc, gimple_assign_lhs (stmt), &gsi,
1700 /*before_p=*/false, /*is_store=*/false, 1);
1ac3509e 1701
c31c80df 1702 /* Ensure that iter points to the statement logically following the
1703 one it was initially pointing to. */
1704 *iter = gsi;
1705 /* As *ITER has been advanced to point to the next statement, let's
1706 return true to inform transform_statements that it shouldn't
1707 advance *ITER anymore; otherwises it will skip that next
1708 statement, which wouldn't be instrumented. */
1709 return true;
1710}
1ac3509e 1711
c31c80df 1712/* Instrument the call to a built-in memory access function that is
1713 pointed to by the iterator ITER.
1ac3509e 1714
c31c80df 1715 Upon completion, return TRUE iff *ITER has been advanced to the
1716 statement following the one it was originally pointing to. */
1ac3509e 1717
c31c80df 1718static bool
1719instrument_builtin_call (gimple_stmt_iterator *iter)
1720{
1721 bool iter_advanced_p = false;
1722 gimple call = gsi_stmt (*iter);
1ac3509e 1723
c31c80df 1724 gcc_checking_assert (gimple_call_builtin_p (call, BUILT_IN_NORMAL));
1ac3509e 1725
c31c80df 1726 tree callee = gimple_call_fndecl (call);
1727 location_t loc = gimple_location (call);
1ac3509e 1728
c31c80df 1729 if (DECL_FUNCTION_CODE (callee) == BUILT_IN_STRLEN)
1730 iter_advanced_p = instrument_strlen_call (iter);
1731 else
1ac3509e 1732 {
c31c80df 1733 asan_mem_ref src0, src1, dest;
1734 asan_mem_ref_init (&src0, NULL, 1);
1735 asan_mem_ref_init (&src1, NULL, 1);
1736 asan_mem_ref_init (&dest, NULL, 1);
1737
1738 tree src0_len = NULL_TREE, src1_len = NULL_TREE, dest_len = NULL_TREE;
1739 bool src0_is_store = false, src1_is_store = false,
1740 dest_is_store = false, dest_is_deref = false;
1741
1742 if (get_mem_refs_of_builtin_call (call,
1743 &src0, &src0_len, &src0_is_store,
0f2b58ae 1744 &src1, &src1_len, &src1_is_store,
c31c80df 1745 &dest, &dest_len, &dest_is_store,
1746 &dest_is_deref))
1747 {
1748 if (dest_is_deref)
1749 {
1750 instrument_derefs (iter, dest.start, loc, dest_is_store);
1751 gsi_next (iter);
1752 iter_advanced_p = true;
1753 }
1754 else if (src0_len || src1_len || dest_len)
1755 {
d9dc05a1 1756 if (src0.start != NULL_TREE)
c31c80df 1757 instrument_mem_region_access (src0.start, src0_len,
1758 iter, loc, /*is_store=*/false);
1759 if (src1.start != NULL_TREE)
1760 instrument_mem_region_access (src1.start, src1_len,
1761 iter, loc, /*is_store=*/false);
1762 if (dest.start != NULL_TREE)
1763 instrument_mem_region_access (dest.start, dest_len,
1764 iter, loc, /*is_store=*/true);
1765 *iter = gsi_for_stmt (call);
1766 gsi_next (iter);
1767 iter_advanced_p = true;
1768 }
1769 }
1ac3509e 1770 }
c31c80df 1771 return iter_advanced_p;
1ac3509e 1772}
1773
1774/* Instrument the assignment statement ITER if it is subject to
c31c80df 1775 instrumentation. Return TRUE iff instrumentation actually
1776 happened. In that case, the iterator ITER is advanced to the next
1777 logical expression following the one initially pointed to by ITER,
1778 and the relevant memory reference that which access has been
1779 instrumented is added to the memory references hash table. */
1ac3509e 1780
c31c80df 1781static bool
1782maybe_instrument_assignment (gimple_stmt_iterator *iter)
1ac3509e 1783{
1784 gimple s = gsi_stmt (*iter);
1785
1786 gcc_assert (gimple_assign_single_p (s));
1787
c31c80df 1788 tree ref_expr = NULL_TREE;
1789 bool is_store, is_instrumented = false;
1790
38e9269e 1791 if (gimple_store_p (s))
c31c80df 1792 {
1793 ref_expr = gimple_assign_lhs (s);
1794 is_store = true;
1795 instrument_derefs (iter, ref_expr,
1796 gimple_location (s),
1797 is_store);
1798 is_instrumented = true;
1799 }
1800
38e9269e 1801 if (gimple_assign_load_p (s))
c31c80df 1802 {
1803 ref_expr = gimple_assign_rhs1 (s);
1804 is_store = false;
1805 instrument_derefs (iter, ref_expr,
1806 gimple_location (s),
1807 is_store);
1808 is_instrumented = true;
1809 }
1810
1811 if (is_instrumented)
1812 gsi_next (iter);
1813
1814 return is_instrumented;
1ac3509e 1815}
1816
1817/* Instrument the function call pointed to by the iterator ITER, if it
1818 is subject to instrumentation. At the moment, the only function
1819 calls that are instrumented are some built-in functions that access
1820 memory. Look at instrument_builtin_call to learn more.
1821
1822 Upon completion return TRUE iff *ITER was advanced to the statement
1823 following the one it was originally pointing to. */
1824
1825static bool
1826maybe_instrument_call (gimple_stmt_iterator *iter)
1827{
494f4883 1828 gimple stmt = gsi_stmt (*iter);
c31c80df 1829 bool is_builtin = gimple_call_builtin_p (stmt, BUILT_IN_NORMAL);
1830
1831 if (is_builtin && instrument_builtin_call (iter))
494f4883 1832 return true;
c31c80df 1833
494f4883 1834 if (gimple_call_noreturn_p (stmt))
1835 {
1836 if (is_builtin)
1837 {
1838 tree callee = gimple_call_fndecl (stmt);
1839 switch (DECL_FUNCTION_CODE (callee))
1840 {
1841 case BUILT_IN_UNREACHABLE:
1842 case BUILT_IN_TRAP:
1843 /* Don't instrument these. */
1844 return false;
1845 }
1846 }
1847 tree decl = builtin_decl_implicit (BUILT_IN_ASAN_HANDLE_NO_RETURN);
1848 gimple g = gimple_build_call (decl, 0);
1849 gimple_set_location (g, gimple_location (stmt));
1850 gsi_insert_before (iter, g, GSI_SAME_STMT);
1851 }
1ac3509e 1852 return false;
b92cccf4 1853}
1854
c31c80df 1855/* Walk each instruction of all basic block and instrument those that
1856 represent memory references: loads, stores, or function calls.
1857 In a given basic block, this function avoids instrumenting memory
1858 references that have already been instrumented. */
b92cccf4 1859
1860static void
1861transform_statements (void)
1862{
e8d4d8a9 1863 basic_block bb, last_bb = NULL;
b92cccf4 1864 gimple_stmt_iterator i;
1865 int saved_last_basic_block = last_basic_block;
b92cccf4 1866
1867 FOR_EACH_BB (bb)
1868 {
e8d4d8a9 1869 basic_block prev_bb = bb;
c31c80df 1870
b92cccf4 1871 if (bb->index >= saved_last_basic_block) continue;
e8d4d8a9 1872
1873 /* Flush the mem ref hash table, if current bb doesn't have
1874 exactly one predecessor, or if that predecessor (skipping
1875 over asan created basic blocks) isn't the last processed
1876 basic block. Thus we effectively flush on extended basic
1877 block boundaries. */
1878 while (single_pred_p (prev_bb))
1879 {
1880 prev_bb = single_pred (prev_bb);
1881 if (prev_bb->index < saved_last_basic_block)
1882 break;
1883 }
1884 if (prev_bb != last_bb)
1885 empty_mem_ref_hash_table ();
1886 last_bb = bb;
1887
1ac3509e 1888 for (i = gsi_start_bb (bb); !gsi_end_p (i);)
eca932e6 1889 {
1ac3509e 1890 gimple s = gsi_stmt (i);
1891
c31c80df 1892 if (has_stmt_been_instrumented_p (s))
1893 gsi_next (&i);
1894 else if (gimple_assign_single_p (s)
1895 && maybe_instrument_assignment (&i))
1896 /* Nothing to do as maybe_instrument_assignment advanced
1897 the iterator I. */;
1898 else if (is_gimple_call (s) && maybe_instrument_call (&i))
1899 /* Nothing to do as maybe_instrument_call
1900 advanced the iterator I. */;
1901 else
1ac3509e 1902 {
c31c80df 1903 /* No instrumentation happened.
1904
e8d4d8a9 1905 If the current instruction is a function call that
1906 might free something, let's forget about the memory
1907 references that got instrumented. Otherwise we might
1908 miss some instrumentation opportunities. */
1909 if (is_gimple_call (s) && !nonfreeing_call_p (s))
c31c80df 1910 empty_mem_ref_hash_table ();
1911
1912 gsi_next (&i);
1ac3509e 1913 }
eca932e6 1914 }
b92cccf4 1915 }
c31c80df 1916 free_mem_ref_resources ();
b92cccf4 1917}
1918
92fc5c48 1919/* Build
1920 struct __asan_global
1921 {
1922 const void *__beg;
1923 uptr __size;
1924 uptr __size_with_redzone;
1925 const void *__name;
1926 uptr __has_dynamic_init;
1927 } type. */
1928
1929static tree
1930asan_global_struct (void)
1931{
1932 static const char *field_names[5]
1933 = { "__beg", "__size", "__size_with_redzone",
1934 "__name", "__has_dynamic_init" };
1935 tree fields[5], ret;
1936 int i;
1937
1938 ret = make_node (RECORD_TYPE);
1939 for (i = 0; i < 5; i++)
1940 {
1941 fields[i]
1942 = build_decl (UNKNOWN_LOCATION, FIELD_DECL,
1943 get_identifier (field_names[i]),
1944 (i == 0 || i == 3) ? const_ptr_type_node
9e46467d 1945 : pointer_sized_int_node);
92fc5c48 1946 DECL_CONTEXT (fields[i]) = ret;
1947 if (i)
1948 DECL_CHAIN (fields[i - 1]) = fields[i];
1949 }
1950 TYPE_FIELDS (ret) = fields[0];
1951 TYPE_NAME (ret) = get_identifier ("__asan_global");
1952 layout_type (ret);
1953 return ret;
1954}
1955
1956/* Append description of a single global DECL into vector V.
1957 TYPE is __asan_global struct type as returned by asan_global_struct. */
1958
1959static void
f1f41a6c 1960asan_add_global (tree decl, tree type, vec<constructor_elt, va_gc> *v)
92fc5c48 1961{
1962 tree init, uptr = TREE_TYPE (DECL_CHAIN (TYPE_FIELDS (type)));
1963 unsigned HOST_WIDE_INT size;
1964 tree str_cst, refdecl = decl;
f1f41a6c 1965 vec<constructor_elt, va_gc> *vinner = NULL;
92fc5c48 1966
b75d2c15 1967 pretty_printer asan_pp;
92fc5c48 1968
92fc5c48 1969 if (DECL_NAME (decl))
a94db6b0 1970 pp_tree_identifier (&asan_pp, DECL_NAME (decl));
92fc5c48 1971 else
1972 pp_string (&asan_pp, "<unknown>");
1973 pp_space (&asan_pp);
1974 pp_left_paren (&asan_pp);
1975 pp_string (&asan_pp, main_input_filename);
1976 pp_right_paren (&asan_pp);
b75d2c15 1977 str_cst = asan_pp_string (&asan_pp);
92fc5c48 1978
1979 if (asan_needs_local_alias (decl))
1980 {
1981 char buf[20];
f1f41a6c 1982 ASM_GENERATE_INTERNAL_LABEL (buf, "LASAN", vec_safe_length (v) + 1);
92fc5c48 1983 refdecl = build_decl (DECL_SOURCE_LOCATION (decl),
1984 VAR_DECL, get_identifier (buf), TREE_TYPE (decl));
1985 TREE_ADDRESSABLE (refdecl) = TREE_ADDRESSABLE (decl);
1986 TREE_READONLY (refdecl) = TREE_READONLY (decl);
1987 TREE_THIS_VOLATILE (refdecl) = TREE_THIS_VOLATILE (decl);
1988 DECL_GIMPLE_REG_P (refdecl) = DECL_GIMPLE_REG_P (decl);
1989 DECL_ARTIFICIAL (refdecl) = DECL_ARTIFICIAL (decl);
1990 DECL_IGNORED_P (refdecl) = DECL_IGNORED_P (decl);
1991 TREE_STATIC (refdecl) = 1;
1992 TREE_PUBLIC (refdecl) = 0;
1993 TREE_USED (refdecl) = 1;
1994 assemble_alias (refdecl, DECL_ASSEMBLER_NAME (decl));
1995 }
1996
1997 CONSTRUCTOR_APPEND_ELT (vinner, NULL_TREE,
1998 fold_convert (const_ptr_type_node,
1999 build_fold_addr_expr (refdecl)));
2000 size = tree_low_cst (DECL_SIZE_UNIT (decl), 1);
2001 CONSTRUCTOR_APPEND_ELT (vinner, NULL_TREE, build_int_cst (uptr, size));
2002 size += asan_red_zone_size (size);
2003 CONSTRUCTOR_APPEND_ELT (vinner, NULL_TREE, build_int_cst (uptr, size));
2004 CONSTRUCTOR_APPEND_ELT (vinner, NULL_TREE,
2005 fold_convert (const_ptr_type_node, str_cst));
2006 CONSTRUCTOR_APPEND_ELT (vinner, NULL_TREE, build_int_cst (uptr, 0));
2007 init = build_constructor (type, vinner);
2008 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, init);
2009}
2010
b45e34ed 2011/* Initialize sanitizer.def builtins if the FE hasn't initialized them. */
2012void
2013initialize_sanitizer_builtins (void)
2014{
2015 tree decl;
2016
2017 if (builtin_decl_implicit_p (BUILT_IN_ASAN_INIT))
2018 return;
2019
2020 tree BT_FN_VOID = build_function_type_list (void_type_node, NULL_TREE);
2021 tree BT_FN_VOID_PTR
2022 = build_function_type_list (void_type_node, ptr_type_node, NULL_TREE);
9e46467d 2023 tree BT_FN_VOID_PTR_PTR_PTR
2024 = build_function_type_list (void_type_node, ptr_type_node,
2025 ptr_type_node, ptr_type_node, NULL_TREE);
b45e34ed 2026 tree BT_FN_VOID_PTR_PTRMODE
2027 = build_function_type_list (void_type_node, ptr_type_node,
9e46467d 2028 pointer_sized_int_node, NULL_TREE);
83392e87 2029 tree BT_FN_VOID_INT
2030 = build_function_type_list (void_type_node, integer_type_node, NULL_TREE);
2031 tree BT_FN_BOOL_VPTR_PTR_IX_INT_INT[5];
2032 tree BT_FN_IX_CONST_VPTR_INT[5];
2033 tree BT_FN_IX_VPTR_IX_INT[5];
2034 tree BT_FN_VOID_VPTR_IX_INT[5];
2035 tree vptr
2036 = build_pointer_type (build_qualified_type (void_type_node,
2037 TYPE_QUAL_VOLATILE));
2038 tree cvptr
2039 = build_pointer_type (build_qualified_type (void_type_node,
2040 TYPE_QUAL_VOLATILE
2041 |TYPE_QUAL_CONST));
2042 tree boolt
2043 = lang_hooks.types.type_for_size (BOOL_TYPE_SIZE, 1);
2044 int i;
2045 for (i = 0; i < 5; i++)
2046 {
2047 tree ix = build_nonstandard_integer_type (BITS_PER_UNIT * (1 << i), 1);
2048 BT_FN_BOOL_VPTR_PTR_IX_INT_INT[i]
2049 = build_function_type_list (boolt, vptr, ptr_type_node, ix,
2050 integer_type_node, integer_type_node,
2051 NULL_TREE);
2052 BT_FN_IX_CONST_VPTR_INT[i]
2053 = build_function_type_list (ix, cvptr, integer_type_node, NULL_TREE);
2054 BT_FN_IX_VPTR_IX_INT[i]
2055 = build_function_type_list (ix, vptr, ix, integer_type_node,
2056 NULL_TREE);
2057 BT_FN_VOID_VPTR_IX_INT[i]
2058 = build_function_type_list (void_type_node, vptr, ix,
2059 integer_type_node, NULL_TREE);
2060 }
2061#define BT_FN_BOOL_VPTR_PTR_I1_INT_INT BT_FN_BOOL_VPTR_PTR_IX_INT_INT[0]
2062#define BT_FN_I1_CONST_VPTR_INT BT_FN_IX_CONST_VPTR_INT[0]
2063#define BT_FN_I1_VPTR_I1_INT BT_FN_IX_VPTR_IX_INT[0]
2064#define BT_FN_VOID_VPTR_I1_INT BT_FN_VOID_VPTR_IX_INT[0]
2065#define BT_FN_BOOL_VPTR_PTR_I2_INT_INT BT_FN_BOOL_VPTR_PTR_IX_INT_INT[1]
2066#define BT_FN_I2_CONST_VPTR_INT BT_FN_IX_CONST_VPTR_INT[1]
2067#define BT_FN_I2_VPTR_I2_INT BT_FN_IX_VPTR_IX_INT[1]
2068#define BT_FN_VOID_VPTR_I2_INT BT_FN_VOID_VPTR_IX_INT[1]
2069#define BT_FN_BOOL_VPTR_PTR_I4_INT_INT BT_FN_BOOL_VPTR_PTR_IX_INT_INT[2]
2070#define BT_FN_I4_CONST_VPTR_INT BT_FN_IX_CONST_VPTR_INT[2]
2071#define BT_FN_I4_VPTR_I4_INT BT_FN_IX_VPTR_IX_INT[2]
2072#define BT_FN_VOID_VPTR_I4_INT BT_FN_VOID_VPTR_IX_INT[2]
2073#define BT_FN_BOOL_VPTR_PTR_I8_INT_INT BT_FN_BOOL_VPTR_PTR_IX_INT_INT[3]
2074#define BT_FN_I8_CONST_VPTR_INT BT_FN_IX_CONST_VPTR_INT[3]
2075#define BT_FN_I8_VPTR_I8_INT BT_FN_IX_VPTR_IX_INT[3]
2076#define BT_FN_VOID_VPTR_I8_INT BT_FN_VOID_VPTR_IX_INT[3]
2077#define BT_FN_BOOL_VPTR_PTR_I16_INT_INT BT_FN_BOOL_VPTR_PTR_IX_INT_INT[4]
2078#define BT_FN_I16_CONST_VPTR_INT BT_FN_IX_CONST_VPTR_INT[4]
2079#define BT_FN_I16_VPTR_I16_INT BT_FN_IX_VPTR_IX_INT[4]
2080#define BT_FN_VOID_VPTR_I16_INT BT_FN_VOID_VPTR_IX_INT[4]
b45e34ed 2081#undef ATTR_NOTHROW_LEAF_LIST
2082#define ATTR_NOTHROW_LEAF_LIST ECF_NOTHROW | ECF_LEAF
c2901651 2083#undef ATTR_TMPURE_NOTHROW_LEAF_LIST
2084#define ATTR_TMPURE_NOTHROW_LEAF_LIST ECF_TM_PURE | ATTR_NOTHROW_LEAF_LIST
b45e34ed 2085#undef ATTR_NORETURN_NOTHROW_LEAF_LIST
2086#define ATTR_NORETURN_NOTHROW_LEAF_LIST ECF_NORETURN | ATTR_NOTHROW_LEAF_LIST
c2901651 2087#undef ATTR_TMPURE_NORETURN_NOTHROW_LEAF_LIST
2088#define ATTR_TMPURE_NORETURN_NOTHROW_LEAF_LIST \
2089 ECF_TM_PURE | ATTR_NORETURN_NOTHROW_LEAF_LIST
9e46467d 2090#undef ATTR_COLD_NOTHROW_LEAF_LIST
2091#define ATTR_COLD_NOTHROW_LEAF_LIST \
2092 /* ECF_COLD missing */ ATTR_NOTHROW_LEAF_LIST
2093#undef ATTR_COLD_NORETURN_NOTHROW_LEAF_LIST
2094#define ATTR_COLD_NORETURN_NOTHROW_LEAF_LIST \
2095 /* ECF_COLD missing */ ATTR_NORETURN_NOTHROW_LEAF_LIST
b45e34ed 2096#undef DEF_SANITIZER_BUILTIN
2097#define DEF_SANITIZER_BUILTIN(ENUM, NAME, TYPE, ATTRS) \
2098 decl = add_builtin_function ("__builtin_" NAME, TYPE, ENUM, \
2099 BUILT_IN_NORMAL, NAME, NULL_TREE); \
2100 set_call_expr_flags (decl, ATTRS); \
2101 set_builtin_decl (ENUM, decl, true);
2102
2103#include "sanitizer.def"
2104
2105#undef DEF_SANITIZER_BUILTIN
2106}
2107
55b58027 2108/* Called via htab_traverse. Count number of emitted
2109 STRING_CSTs in the constant hash table. */
2110
2111static int
2112count_string_csts (void **slot, void *data)
2113{
2114 struct constant_descriptor_tree *desc
2115 = (struct constant_descriptor_tree *) *slot;
2116 if (TREE_CODE (desc->value) == STRING_CST
2117 && TREE_ASM_WRITTEN (desc->value)
2118 && asan_protect_global (desc->value))
2119 ++*((unsigned HOST_WIDE_INT *) data);
2120 return 1;
2121}
2122
2123/* Helper structure to pass two parameters to
2124 add_string_csts. */
2125
2126struct asan_add_string_csts_data
2127{
2128 tree type;
2129 vec<constructor_elt, va_gc> *v;
2130};
2131
2132/* Called via htab_traverse. Call asan_add_global
2133 on emitted STRING_CSTs from the constant hash table. */
2134
2135static int
2136add_string_csts (void **slot, void *data)
2137{
2138 struct constant_descriptor_tree *desc
2139 = (struct constant_descriptor_tree *) *slot;
2140 if (TREE_CODE (desc->value) == STRING_CST
2141 && TREE_ASM_WRITTEN (desc->value)
2142 && asan_protect_global (desc->value))
2143 {
2144 struct asan_add_string_csts_data *aascd
2145 = (struct asan_add_string_csts_data *) data;
2146 asan_add_global (SYMBOL_REF_DECL (XEXP (desc->rtl, 0)),
2147 aascd->type, aascd->v);
2148 }
2149 return 1;
2150}
2151
92fc5c48 2152/* Needs to be GTY(()), because cgraph_build_static_cdtor may
2153 invoke ggc_collect. */
2154static GTY(()) tree asan_ctor_statements;
2155
b92cccf4 2156/* Module-level instrumentation.
2157 - Insert __asan_init() into the list of CTORs.
2158 - TODO: insert redzones around globals.
2159 */
2160
2161void
2162asan_finish_file (void)
2163{
92fc5c48 2164 struct varpool_node *vnode;
2165 unsigned HOST_WIDE_INT gcount = 0;
2166
55b58027 2167 if (shadow_ptr_types[0] == NULL_TREE)
2168 asan_init_shadow_ptr_types ();
2169 /* Avoid instrumenting code in the asan ctors/dtors.
2170 We don't need to insert padding after the description strings,
2171 nor after .LASAN* array. */
9e46467d 2172 flag_sanitize &= ~SANITIZE_ADDRESS;
b45e34ed 2173
2174 tree fn = builtin_decl_implicit (BUILT_IN_ASAN_INIT);
2175 append_to_statement_list (build_call_expr (fn, 0), &asan_ctor_statements);
92fc5c48 2176 FOR_EACH_DEFINED_VARIABLE (vnode)
046a838d 2177 if (TREE_ASM_WRITTEN (vnode->symbol.decl)
2178 && asan_protect_global (vnode->symbol.decl))
92fc5c48 2179 ++gcount;
55b58027 2180 htab_t const_desc_htab = constant_pool_htab ();
2181 htab_traverse (const_desc_htab, count_string_csts, &gcount);
92fc5c48 2182 if (gcount)
2183 {
b45e34ed 2184 tree type = asan_global_struct (), var, ctor;
92fc5c48 2185 tree dtor_statements = NULL_TREE;
f1f41a6c 2186 vec<constructor_elt, va_gc> *v;
92fc5c48 2187 char buf[20];
2188
2189 type = build_array_type_nelts (type, gcount);
2190 ASM_GENERATE_INTERNAL_LABEL (buf, "LASAN", 0);
2191 var = build_decl (UNKNOWN_LOCATION, VAR_DECL, get_identifier (buf),
2192 type);
2193 TREE_STATIC (var) = 1;
2194 TREE_PUBLIC (var) = 0;
2195 DECL_ARTIFICIAL (var) = 1;
2196 DECL_IGNORED_P (var) = 1;
f1f41a6c 2197 vec_alloc (v, gcount);
92fc5c48 2198 FOR_EACH_DEFINED_VARIABLE (vnode)
046a838d 2199 if (TREE_ASM_WRITTEN (vnode->symbol.decl)
2200 && asan_protect_global (vnode->symbol.decl))
92fc5c48 2201 asan_add_global (vnode->symbol.decl, TREE_TYPE (type), v);
55b58027 2202 struct asan_add_string_csts_data aascd;
2203 aascd.type = TREE_TYPE (type);
2204 aascd.v = v;
2205 htab_traverse (const_desc_htab, add_string_csts, &aascd);
92fc5c48 2206 ctor = build_constructor (type, v);
2207 TREE_CONSTANT (ctor) = 1;
2208 TREE_STATIC (ctor) = 1;
2209 DECL_INITIAL (var) = ctor;
2210 varpool_assemble_decl (varpool_node_for_decl (var));
2211
b45e34ed 2212 fn = builtin_decl_implicit (BUILT_IN_ASAN_REGISTER_GLOBALS);
9e46467d 2213 tree gcount_tree = build_int_cst (pointer_sized_int_node, gcount);
b45e34ed 2214 append_to_statement_list (build_call_expr (fn, 2,
92fc5c48 2215 build_fold_addr_expr (var),
9e46467d 2216 gcount_tree),
92fc5c48 2217 &asan_ctor_statements);
2218
b45e34ed 2219 fn = builtin_decl_implicit (BUILT_IN_ASAN_UNREGISTER_GLOBALS);
2220 append_to_statement_list (build_call_expr (fn, 2,
92fc5c48 2221 build_fold_addr_expr (var),
9e46467d 2222 gcount_tree),
92fc5c48 2223 &dtor_statements);
2224 cgraph_build_static_cdtor ('D', dtor_statements,
2225 MAX_RESERVED_INIT_PRIORITY - 1);
2226 }
2227 cgraph_build_static_cdtor ('I', asan_ctor_statements,
2228 MAX_RESERVED_INIT_PRIORITY - 1);
9e46467d 2229 flag_sanitize |= SANITIZE_ADDRESS;
5d5c682b 2230}
2231
b92cccf4 2232/* Instrument the current function. */
2233
2234static unsigned int
2235asan_instrument (void)
2236{
5d5c682b 2237 if (shadow_ptr_types[0] == NULL_TREE)
55b58027 2238 asan_init_shadow_ptr_types ();
b92cccf4 2239 transform_statements ();
b92cccf4 2240 return 0;
2241}
2242
2243static bool
2244gate_asan (void)
2245{
9e46467d 2246 return (flag_sanitize & SANITIZE_ADDRESS) != 0
a9196da9 2247 && !lookup_attribute ("no_sanitize_address",
d413ffdd 2248 DECL_ATTRIBUTES (current_function_decl));
b92cccf4 2249}
2250
cbe8bda8 2251namespace {
2252
2253const pass_data pass_data_asan =
b92cccf4 2254{
cbe8bda8 2255 GIMPLE_PASS, /* type */
2256 "asan", /* name */
2257 OPTGROUP_NONE, /* optinfo_flags */
2258 true, /* has_gate */
2259 true, /* has_execute */
2260 TV_NONE, /* tv_id */
2261 ( PROP_ssa | PROP_cfg | PROP_gimple_leh ), /* properties_required */
2262 0, /* properties_provided */
2263 0, /* properties_destroyed */
2264 0, /* todo_flags_start */
2265 ( TODO_verify_flow | TODO_verify_stmts
2266 | TODO_update_ssa ), /* todo_flags_finish */
b92cccf4 2267};
5d5c682b 2268
cbe8bda8 2269class pass_asan : public gimple_opt_pass
2270{
2271public:
9af5ce0c 2272 pass_asan (gcc::context *ctxt)
2273 : gimple_opt_pass (pass_data_asan, ctxt)
cbe8bda8 2274 {}
2275
2276 /* opt_pass methods: */
ae84f584 2277 opt_pass * clone () { return new pass_asan (m_ctxt); }
cbe8bda8 2278 bool gate () { return gate_asan (); }
2279 unsigned int execute () { return asan_instrument (); }
2280
2281}; // class pass_asan
2282
2283} // anon namespace
2284
2285gimple_opt_pass *
2286make_pass_asan (gcc::context *ctxt)
2287{
2288 return new pass_asan (ctxt);
2289}
2290
8293ee35 2291static bool
2292gate_asan_O0 (void)
2293{
d413ffdd 2294 return !optimize && gate_asan ();
8293ee35 2295}
2296
cbe8bda8 2297namespace {
2298
2299const pass_data pass_data_asan_O0 =
8293ee35 2300{
cbe8bda8 2301 GIMPLE_PASS, /* type */
2302 "asan0", /* name */
2303 OPTGROUP_NONE, /* optinfo_flags */
2304 true, /* has_gate */
2305 true, /* has_execute */
2306 TV_NONE, /* tv_id */
2307 ( PROP_ssa | PROP_cfg | PROP_gimple_leh ), /* properties_required */
2308 0, /* properties_provided */
2309 0, /* properties_destroyed */
2310 0, /* todo_flags_start */
2311 ( TODO_verify_flow | TODO_verify_stmts
2312 | TODO_update_ssa ), /* todo_flags_finish */
8293ee35 2313};
2314
cbe8bda8 2315class pass_asan_O0 : public gimple_opt_pass
2316{
2317public:
9af5ce0c 2318 pass_asan_O0 (gcc::context *ctxt)
2319 : gimple_opt_pass (pass_data_asan_O0, ctxt)
cbe8bda8 2320 {}
2321
2322 /* opt_pass methods: */
2323 bool gate () { return gate_asan_O0 (); }
2324 unsigned int execute () { return asan_instrument (); }
2325
2326}; // class pass_asan_O0
2327
2328} // anon namespace
2329
2330gimple_opt_pass *
2331make_pass_asan_O0 (gcc::context *ctxt)
2332{
2333 return new pass_asan_O0 (ctxt);
2334}
2335
5d5c682b 2336#include "gt-asan.h"