]> git.ipfire.org Git - thirdparty/gcc.git/blame - gcc/asan.c
* asan.c (handle_builtin_alloca): Deal with all alloca variants.
[thirdparty/gcc.git] / gcc / asan.c
CommitLineData
b92cccf4 1/* AddressSanitizer, a fast memory error detector.
aad93da1 2 Copyright (C) 2012-2017 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"
9ef16211 25#include "backend.h"
7c29e30e 26#include "target.h"
27#include "rtl.h"
41a8aa41 28#include "tree.h"
9ef16211 29#include "gimple.h"
7c29e30e 30#include "cfghooks.h"
31#include "alloc-pool.h"
32#include "tree-pass.h"
ad7b10a2 33#include "memmodel.h"
7c29e30e 34#include "tm_p.h"
c51887c5 35#include "ssa.h"
7c29e30e 36#include "stringpool.h"
37#include "tree-ssanames.h"
7c29e30e 38#include "optabs.h"
39#include "emit-rtl.h"
40#include "cgraph.h"
41#include "gimple-pretty-print.h"
42#include "alias.h"
b20a8bb4 43#include "fold-const.h"
94ea8568 44#include "cfganal.h"
a8783bee 45#include "gimplify.h"
dcf1a1ec 46#include "gimple-iterator.h"
9ed99284 47#include "varasm.h"
48#include "stor-layout.h"
b92cccf4 49#include "tree-iterator.h"
30a86690 50#include "stringpool.h"
51#include "attribs.h"
b92cccf4 52#include "asan.h"
d53441c8 53#include "dojump.h"
54#include "explow.h"
3c919612 55#include "expr.h"
92fc5c48 56#include "output.h"
b45e34ed 57#include "langhooks.h"
f6568ea4 58#include "cfgloop.h"
9a4a3348 59#include "gimple-builder.h"
d08919a7 60#include "gimple-fold.h"
19b928d9 61#include "ubsan.h"
bf2b7c22 62#include "params.h"
f7715905 63#include "builtins.h"
5cd86e48 64#include "fnmatch.h"
c51887c5 65#include "tree-inline.h"
b92cccf4 66
eca932e6 67/* AddressSanitizer finds out-of-bounds and use-after-free bugs
68 with <2x slowdown on average.
69
70 The tool consists of two parts:
71 instrumentation module (this file) and a run-time library.
72 The instrumentation module adds a run-time check before every memory insn.
73 For a 8- or 16- byte load accessing address X:
74 ShadowAddr = (X >> 3) + Offset
75 ShadowValue = *(char*)ShadowAddr; // *(short*) for 16-byte access.
76 if (ShadowValue)
77 __asan_report_load8(X);
78 For a load of N bytes (N=1, 2 or 4) from address X:
79 ShadowAddr = (X >> 3) + Offset
80 ShadowValue = *(char*)ShadowAddr;
81 if (ShadowValue)
82 if ((X & 7) + N - 1 > ShadowValue)
83 __asan_report_loadN(X);
84 Stores are instrumented similarly, but using __asan_report_storeN functions.
1e80ce41 85 A call too __asan_init_vN() is inserted to the list of module CTORs.
86 N is the version number of the AddressSanitizer API. The changes between the
87 API versions are listed in libsanitizer/asan/asan_interface_internal.h.
eca932e6 88
89 The run-time library redefines malloc (so that redzone are inserted around
90 the allocated memory) and free (so that reuse of free-ed memory is delayed),
1e80ce41 91 provides __asan_report* and __asan_init_vN functions.
eca932e6 92
93 Read more:
94 http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
95
96 The current implementation supports detection of out-of-bounds and
97 use-after-free in the heap, on the stack and for global variables.
98
99 [Protection of stack variables]
100
101 To understand how detection of out-of-bounds and use-after-free works
102 for stack variables, lets look at this example on x86_64 where the
103 stack grows downward:
3c919612 104
105 int
106 foo ()
107 {
108 char a[23] = {0};
109 int b[2] = {0};
110
111 a[5] = 1;
112 b[1] = 2;
113
114 return a[5] + b[1];
115 }
116
eca932e6 117 For this function, the stack protected by asan will be organized as
118 follows, from the top of the stack to the bottom:
3c919612 119
eca932e6 120 Slot 1/ [red zone of 32 bytes called 'RIGHT RedZone']
3c919612 121
eca932e6 122 Slot 2/ [8 bytes of red zone, that adds up to the space of 'a' to make
123 the next slot be 32 bytes aligned; this one is called Partial
124 Redzone; this 32 bytes alignment is an asan constraint]
3c919612 125
eca932e6 126 Slot 3/ [24 bytes for variable 'a']
3c919612 127
eca932e6 128 Slot 4/ [red zone of 32 bytes called 'Middle RedZone']
3c919612 129
eca932e6 130 Slot 5/ [24 bytes of Partial Red Zone (similar to slot 2]
3c919612 131
eca932e6 132 Slot 6/ [8 bytes for variable 'b']
3c919612 133
eca932e6 134 Slot 7/ [32 bytes of Red Zone at the bottom of the stack, called
135 'LEFT RedZone']
3c919612 136
eca932e6 137 The 32 bytes of LEFT red zone at the bottom of the stack can be
138 decomposed as such:
3c919612 139
140 1/ The first 8 bytes contain a magical asan number that is always
141 0x41B58AB3.
142
143 2/ The following 8 bytes contains a pointer to a string (to be
144 parsed at runtime by the runtime asan library), which format is
145 the following:
146
147 "<function-name> <space> <num-of-variables-on-the-stack>
148 (<32-bytes-aligned-offset-in-bytes-of-variable> <space>
149 <length-of-var-in-bytes> ){n} "
150
151 where '(...){n}' means the content inside the parenthesis occurs 'n'
152 times, with 'n' being the number of variables on the stack.
e815c2c5 153
1e80ce41 154 3/ The following 8 bytes contain the PC of the current function which
155 will be used by the run-time library to print an error message.
3c919612 156
1e80ce41 157 4/ The following 8 bytes are reserved for internal use by the run-time.
3c919612 158
eca932e6 159 The shadow memory for that stack layout is going to look like this:
3c919612 160
161 - content of shadow memory 8 bytes for slot 7: 0xF1F1F1F1.
162 The F1 byte pattern is a magic number called
163 ASAN_STACK_MAGIC_LEFT and is a way for the runtime to know that
164 the memory for that shadow byte is part of a the LEFT red zone
165 intended to seat at the bottom of the variables on the stack.
166
167 - content of shadow memory 8 bytes for slots 6 and 5:
168 0xF4F4F400. The F4 byte pattern is a magic number
169 called ASAN_STACK_MAGIC_PARTIAL. It flags the fact that the
170 memory region for this shadow byte is a PARTIAL red zone
171 intended to pad a variable A, so that the slot following
172 {A,padding} is 32 bytes aligned.
173
174 Note that the fact that the least significant byte of this
175 shadow memory content is 00 means that 8 bytes of its
176 corresponding memory (which corresponds to the memory of
177 variable 'b') is addressable.
178
179 - content of shadow memory 8 bytes for slot 4: 0xF2F2F2F2.
180 The F2 byte pattern is a magic number called
181 ASAN_STACK_MAGIC_MIDDLE. It flags the fact that the memory
182 region for this shadow byte is a MIDDLE red zone intended to
183 seat between two 32 aligned slots of {variable,padding}.
184
185 - content of shadow memory 8 bytes for slot 3 and 2:
eca932e6 186 0xF4000000. This represents is the concatenation of
3c919612 187 variable 'a' and the partial red zone following it, like what we
188 had for variable 'b'. The least significant 3 bytes being 00
189 means that the 3 bytes of variable 'a' are addressable.
190
eca932e6 191 - content of shadow memory 8 bytes for slot 1: 0xF3F3F3F3.
3c919612 192 The F3 byte pattern is a magic number called
193 ASAN_STACK_MAGIC_RIGHT. It flags the fact that the memory
194 region for this shadow byte is a RIGHT red zone intended to seat
195 at the top of the variables of the stack.
196
eca932e6 197 Note that the real variable layout is done in expand_used_vars in
198 cfgexpand.c. As far as Address Sanitizer is concerned, it lays out
199 stack variables as well as the different red zones, emits some
200 prologue code to populate the shadow memory as to poison (mark as
201 non-accessible) the regions of the red zones and mark the regions of
202 stack variables as accessible, and emit some epilogue code to
203 un-poison (mark as accessible) the regions of red zones right before
204 the function exits.
92fc5c48 205
eca932e6 206 [Protection of global variables]
92fc5c48 207
eca932e6 208 The basic idea is to insert a red zone between two global variables
209 and install a constructor function that calls the asan runtime to do
210 the populating of the relevant shadow memory regions at load time.
92fc5c48 211
eca932e6 212 So the global variables are laid out as to insert a red zone between
213 them. The size of the red zones is so that each variable starts on a
214 32 bytes boundary.
92fc5c48 215
eca932e6 216 Then a constructor function is installed so that, for each global
217 variable, it calls the runtime asan library function
218 __asan_register_globals_with an instance of this type:
92fc5c48 219
220 struct __asan_global
221 {
222 // Address of the beginning of the global variable.
223 const void *__beg;
224
225 // Initial size of the global variable.
226 uptr __size;
227
228 // Size of the global variable + size of the red zone. This
229 // size is 32 bytes aligned.
230 uptr __size_with_redzone;
231
232 // Name of the global variable.
233 const void *__name;
234
1e80ce41 235 // Name of the module where the global variable is declared.
236 const void *__module_name;
237
085f6ebf 238 // 1 if it has dynamic initialization, 0 otherwise.
92fc5c48 239 uptr __has_dynamic_init;
a9586c9c 240
241 // A pointer to struct that contains source location, could be NULL.
242 __asan_global_source_location *__location;
92fc5c48 243 }
244
eca932e6 245 A destructor function that calls the runtime asan library function
246 _asan_unregister_globals is also installed. */
3c919612 247
cf357977 248static unsigned HOST_WIDE_INT asan_shadow_offset_value;
249static bool asan_shadow_offset_computed;
5cd86e48 250static vec<char *> sanitized_sections;
d08919a7 251static tree last_alloca_addr;
cf357977 252
629b6abc 253/* Set of variable declarations that are going to be guarded by
254 use-after-scope sanitizer. */
255
256static hash_set<tree> *asan_handled_variables = NULL;
257
258hash_set <tree> *asan_used_labels = NULL;
259
cf357977 260/* Sets shadow offset to value in string VAL. */
261
262bool
263set_asan_shadow_offset (const char *val)
264{
265 char *endp;
e815c2c5 266
cf357977 267 errno = 0;
268#ifdef HAVE_LONG_LONG
269 asan_shadow_offset_value = strtoull (val, &endp, 0);
270#else
271 asan_shadow_offset_value = strtoul (val, &endp, 0);
272#endif
273 if (!(*val != '\0' && *endp == '\0' && errno == 0))
274 return false;
275
276 asan_shadow_offset_computed = true;
277
278 return true;
279}
280
4d3c996b 281/* Set list of user-defined sections that need to be sanitized. */
282
283void
5cd86e48 284set_sanitized_sections (const char *sections)
4d3c996b 285{
5cd86e48 286 char *pat;
287 unsigned i;
288 FOR_EACH_VEC_ELT (sanitized_sections, i, pat)
289 free (pat);
290 sanitized_sections.truncate (0);
291
292 for (const char *s = sections; *s; )
293 {
294 const char *end;
295 for (end = s; *end && *end != ','; ++end);
296 size_t len = end - s;
297 sanitized_sections.safe_push (xstrndup (s, len));
298 s = *end ? end + 1 : end;
299 }
4d3c996b 300}
301
a30589d5 302bool
303asan_mark_p (gimple *stmt, enum asan_mark_flags flag)
304{
305 return (gimple_call_internal_p (stmt, IFN_ASAN_MARK)
306 && tree_to_uhwi (gimple_call_arg (stmt, 0)) == flag);
307}
308
629b6abc 309bool
310asan_sanitize_stack_p (void)
311{
9917317a 312 return (sanitize_flags_p (SANITIZE_ADDRESS) && ASAN_STACK);
629b6abc 313}
314
77c44489 315bool
316asan_sanitize_allocas_p (void)
317{
318 return (asan_sanitize_stack_p () && ASAN_PROTECT_ALLOCAS);
319}
320
4d3c996b 321/* Checks whether section SEC should be sanitized. */
322
323static bool
324section_sanitized_p (const char *sec)
325{
5cd86e48 326 char *pat;
327 unsigned i;
328 FOR_EACH_VEC_ELT (sanitized_sections, i, pat)
329 if (fnmatch (pat, sec, FNM_PERIOD) == 0)
330 return true;
4d3c996b 331 return false;
332}
333
cf357977 334/* Returns Asan shadow offset. */
335
336static unsigned HOST_WIDE_INT
337asan_shadow_offset ()
338{
339 if (!asan_shadow_offset_computed)
340 {
341 asan_shadow_offset_computed = true;
342 asan_shadow_offset_value = targetm.asan_shadow_offset ();
343 }
344 return asan_shadow_offset_value;
345}
346
3c919612 347alias_set_type asan_shadow_set = -1;
b92cccf4 348
629b6abc 349/* Pointer types to 1, 2 or 4 byte integers in shadow memory. A separate
5d5c682b 350 alias set is used for all shadow memory accesses. */
629b6abc 351static GTY(()) tree shadow_ptr_types[3];
5d5c682b 352
683539f6 353/* Decl for __asan_option_detect_stack_use_after_return. */
354static GTY(()) tree asan_detect_stack_use_after_return;
355
c31c80df 356/* Hashtable support for memory references used by gimple
357 statements. */
358
359/* This type represents a reference to a memory region. */
360struct asan_mem_ref
361{
a04e8d62 362 /* The expression of the beginning of the memory region. */
c31c80df 363 tree start;
364
86d3a572 365 /* The size of the access. */
366 HOST_WIDE_INT access_size;
e815c2c5 367};
368
1dc6c44d 369object_allocator <asan_mem_ref> asan_mem_ref_pool ("asan_mem_ref");
c31c80df 370
371/* Initializes an instance of asan_mem_ref. */
372
373static void
86d3a572 374asan_mem_ref_init (asan_mem_ref *ref, tree start, HOST_WIDE_INT access_size)
c31c80df 375{
376 ref->start = start;
377 ref->access_size = access_size;
378}
379
380/* Allocates memory for an instance of asan_mem_ref into the memory
381 pool returned by asan_mem_ref_get_alloc_pool and initialize it.
382 START is the address of (or the expression pointing to) the
383 beginning of memory reference. ACCESS_SIZE is the size of the
384 access to the referenced memory. */
385
386static asan_mem_ref*
86d3a572 387asan_mem_ref_new (tree start, HOST_WIDE_INT access_size)
c31c80df 388{
e16712b1 389 asan_mem_ref *ref = asan_mem_ref_pool.allocate ();
c31c80df 390
391 asan_mem_ref_init (ref, start, access_size);
392 return ref;
393}
394
395/* This builds and returns a pointer to the end of the memory region
396 that starts at START and of length LEN. */
397
398tree
399asan_mem_ref_get_end (tree start, tree len)
400{
401 if (len == NULL_TREE || integer_zerop (len))
402 return start;
403
0a9f72cf 404 if (!ptrofftype_p (len))
405 len = convert_to_ptrofftype (len);
406
c31c80df 407 return fold_build2 (POINTER_PLUS_EXPR, TREE_TYPE (start), start, len);
408}
409
410/* Return a tree expression that represents the end of the referenced
411 memory region. Beware that this function can actually build a new
412 tree expression. */
413
414tree
415asan_mem_ref_get_end (const asan_mem_ref *ref, tree len)
416{
417 return asan_mem_ref_get_end (ref->start, len);
418}
419
770ff93b 420struct asan_mem_ref_hasher : nofree_ptr_hash <asan_mem_ref>
c31c80df 421{
9969c043 422 static inline hashval_t hash (const asan_mem_ref *);
423 static inline bool equal (const asan_mem_ref *, const asan_mem_ref *);
c31c80df 424};
425
426/* Hash a memory reference. */
427
428inline hashval_t
429asan_mem_ref_hasher::hash (const asan_mem_ref *mem_ref)
430{
f9acf11a 431 return iterative_hash_expr (mem_ref->start, 0);
c31c80df 432}
433
434/* Compare two memory references. We accept the length of either
435 memory references to be NULL_TREE. */
436
437inline bool
438asan_mem_ref_hasher::equal (const asan_mem_ref *m1,
439 const asan_mem_ref *m2)
440{
f9acf11a 441 return operand_equal_p (m1->start, m2->start, 0);
c31c80df 442}
443
c1f445d2 444static hash_table<asan_mem_ref_hasher> *asan_mem_ref_ht;
c31c80df 445
446/* Returns a reference to the hash table containing memory references.
447 This function ensures that the hash table is created. Note that
448 this hash table is updated by the function
449 update_mem_ref_hash_table. */
450
c1f445d2 451static hash_table<asan_mem_ref_hasher> *
c31c80df 452get_mem_ref_hash_table ()
453{
c1f445d2 454 if (!asan_mem_ref_ht)
455 asan_mem_ref_ht = new hash_table<asan_mem_ref_hasher> (10);
c31c80df 456
457 return asan_mem_ref_ht;
458}
459
460/* Clear all entries from the memory references hash table. */
461
462static void
463empty_mem_ref_hash_table ()
464{
c1f445d2 465 if (asan_mem_ref_ht)
466 asan_mem_ref_ht->empty ();
c31c80df 467}
468
469/* Free the memory references hash table. */
470
471static void
472free_mem_ref_resources ()
473{
c1f445d2 474 delete asan_mem_ref_ht;
475 asan_mem_ref_ht = NULL;
c31c80df 476
e16712b1 477 asan_mem_ref_pool.release ();
c31c80df 478}
479
480/* Return true iff the memory reference REF has been instrumented. */
481
482static bool
86d3a572 483has_mem_ref_been_instrumented (tree ref, HOST_WIDE_INT access_size)
c31c80df 484{
485 asan_mem_ref r;
486 asan_mem_ref_init (&r, ref, access_size);
487
f9acf11a 488 asan_mem_ref *saved_ref = get_mem_ref_hash_table ()->find (&r);
489 return saved_ref && saved_ref->access_size >= access_size;
c31c80df 490}
491
492/* Return true iff the memory reference REF has been instrumented. */
493
494static bool
495has_mem_ref_been_instrumented (const asan_mem_ref *ref)
496{
497 return has_mem_ref_been_instrumented (ref->start, ref->access_size);
498}
499
500/* Return true iff access to memory region starting at REF and of
501 length LEN has been instrumented. */
502
503static bool
504has_mem_ref_been_instrumented (const asan_mem_ref *ref, tree len)
505{
f9acf11a 506 HOST_WIDE_INT size_in_bytes
507 = tree_fits_shwi_p (len) ? tree_to_shwi (len) : -1;
c31c80df 508
f9acf11a 509 return size_in_bytes != -1
510 && has_mem_ref_been_instrumented (ref->start, size_in_bytes);
c31c80df 511}
512
513/* Set REF to the memory reference present in a gimple assignment
514 ASSIGNMENT. Return true upon successful completion, false
515 otherwise. */
516
517static bool
1a91d914 518get_mem_ref_of_assignment (const gassign *assignment,
c31c80df 519 asan_mem_ref *ref,
520 bool *ref_is_store)
521{
522 gcc_assert (gimple_assign_single_p (assignment));
523
9f559b20 524 if (gimple_store_p (assignment)
525 && !gimple_clobber_p (assignment))
c31c80df 526 {
527 ref->start = gimple_assign_lhs (assignment);
528 *ref_is_store = true;
529 }
530 else if (gimple_assign_load_p (assignment))
531 {
532 ref->start = gimple_assign_rhs1 (assignment);
533 *ref_is_store = false;
534 }
535 else
536 return false;
537
538 ref->access_size = int_size_in_bytes (TREE_TYPE (ref->start));
539 return true;
540}
541
d08919a7 542/* Return address of last allocated dynamic alloca. */
543
544static tree
545get_last_alloca_addr ()
546{
547 if (last_alloca_addr)
548 return last_alloca_addr;
549
550 last_alloca_addr = create_tmp_reg (ptr_type_node, "last_alloca_addr");
551 gassign *g = gimple_build_assign (last_alloca_addr, null_pointer_node);
552 edge e = single_succ_edge (ENTRY_BLOCK_PTR_FOR_FN (cfun));
553 gsi_insert_on_edge_immediate (e, g);
554 return last_alloca_addr;
555}
556
557/* Insert __asan_allocas_unpoison (top, bottom) call after
558 __builtin_stack_restore (new_sp) call.
559 The pseudocode of this routine should look like this:
560 __builtin_stack_restore (new_sp);
561 top = last_alloca_addr;
562 bot = new_sp;
563 __asan_allocas_unpoison (top, bot);
564 last_alloca_addr = new_sp;
565 In general, we can't use new_sp as bot parameter because on some
566 architectures SP has non zero offset from dynamic stack area. Moreover, on
567 some architectures this offset (STACK_DYNAMIC_OFFSET) becomes known for each
568 particular function only after all callees were expanded to rtl.
569 The most noticeable example is PowerPC{,64}, see
570 http://refspecs.linuxfoundation.org/ELF/ppc64/PPC-elf64abi.html#DYNAM-STACK.
571 To overcome the issue we use following trick: pass new_sp as a second
572 parameter to __asan_allocas_unpoison and rewrite it during expansion with
573 virtual_dynamic_stack_rtx later in expand_asan_emit_allocas_unpoison
574 function.
575*/
576
577static void
578handle_builtin_stack_restore (gcall *call, gimple_stmt_iterator *iter)
579{
77c44489 580 if (!iter || !asan_sanitize_allocas_p ())
d08919a7 581 return;
582
583 tree last_alloca = get_last_alloca_addr ();
584 tree restored_stack = gimple_call_arg (call, 0);
585 tree fn = builtin_decl_implicit (BUILT_IN_ASAN_ALLOCAS_UNPOISON);
586 gimple *g = gimple_build_call (fn, 2, last_alloca, restored_stack);
587 gsi_insert_after (iter, g, GSI_NEW_STMT);
588 g = gimple_build_assign (last_alloca, restored_stack);
589 gsi_insert_after (iter, g, GSI_NEW_STMT);
590}
591
592/* Deploy and poison redzones around __builtin_alloca call. To do this, we
593 should replace this call with another one with changed parameters and
594 replace all its uses with new address, so
595 addr = __builtin_alloca (old_size, align);
596 is replaced by
597 left_redzone_size = max (align, ASAN_RED_ZONE_SIZE);
598 Following two statements are optimized out if we know that
599 old_size & (ASAN_RED_ZONE_SIZE - 1) == 0, i.e. alloca doesn't need partial
600 redzone.
601 misalign = old_size & (ASAN_RED_ZONE_SIZE - 1);
602 partial_redzone_size = ASAN_RED_ZONE_SIZE - misalign;
603 right_redzone_size = ASAN_RED_ZONE_SIZE;
604 additional_size = left_redzone_size + partial_redzone_size +
605 right_redzone_size;
606 new_size = old_size + additional_size;
607 new_alloca = __builtin_alloca (new_size, max (align, 32))
608 __asan_alloca_poison (new_alloca, old_size)
609 addr = new_alloca + max (align, ASAN_RED_ZONE_SIZE);
610 last_alloca_addr = new_alloca;
611 ADDITIONAL_SIZE is added to make new memory allocation contain not only
612 requested memory, but also left, partial and right redzones as well as some
613 additional space, required by alignment. */
614
615static void
616handle_builtin_alloca (gcall *call, gimple_stmt_iterator *iter)
617{
77c44489 618 if (!iter || !asan_sanitize_allocas_p ())
d08919a7 619 return;
620
621 gassign *g;
622 gcall *gg;
623 const HOST_WIDE_INT redzone_mask = ASAN_RED_ZONE_SIZE - 1;
624
625 tree last_alloca = get_last_alloca_addr ();
626 tree callee = gimple_call_fndecl (call);
627 tree old_size = gimple_call_arg (call, 0);
628 tree ptr_type = gimple_call_lhs (call) ? TREE_TYPE (gimple_call_lhs (call))
629 : ptr_type_node;
630 tree partial_size = NULL_TREE;
d08919a7 631 unsigned int align
2b34677f 632 = DECL_FUNCTION_CODE (callee) == BUILT_IN_ALLOCA
633 ? 0 : tree_to_uhwi (gimple_call_arg (call, 1));
d08919a7 634
635 /* If ALIGN > ASAN_RED_ZONE_SIZE, we embed left redzone into first ALIGN
636 bytes of allocated space. Otherwise, align alloca to ASAN_RED_ZONE_SIZE
637 manually. */
638 align = MAX (align, ASAN_RED_ZONE_SIZE * BITS_PER_UNIT);
639
640 tree alloca_rz_mask = build_int_cst (size_type_node, redzone_mask);
641 tree redzone_size = build_int_cst (size_type_node, ASAN_RED_ZONE_SIZE);
642
643 /* Extract lower bits from old_size. */
644 wide_int size_nonzero_bits = get_nonzero_bits (old_size);
645 wide_int rz_mask
646 = wi::uhwi (redzone_mask, wi::get_precision (size_nonzero_bits));
647 wide_int old_size_lower_bits = wi::bit_and (size_nonzero_bits, rz_mask);
648
649 /* If alloca size is aligned to ASAN_RED_ZONE_SIZE, we don't need partial
650 redzone. Otherwise, compute its size here. */
651 if (wi::ne_p (old_size_lower_bits, 0))
652 {
653 /* misalign = size & (ASAN_RED_ZONE_SIZE - 1)
654 partial_size = ASAN_RED_ZONE_SIZE - misalign. */
655 g = gimple_build_assign (make_ssa_name (size_type_node, NULL),
656 BIT_AND_EXPR, old_size, alloca_rz_mask);
657 gsi_insert_before (iter, g, GSI_SAME_STMT);
658 tree misalign = gimple_assign_lhs (g);
659 g = gimple_build_assign (make_ssa_name (size_type_node, NULL), MINUS_EXPR,
660 redzone_size, misalign);
661 gsi_insert_before (iter, g, GSI_SAME_STMT);
662 partial_size = gimple_assign_lhs (g);
663 }
664
665 /* additional_size = align + ASAN_RED_ZONE_SIZE. */
666 tree additional_size = build_int_cst (size_type_node, align / BITS_PER_UNIT
667 + ASAN_RED_ZONE_SIZE);
668 /* If alloca has partial redzone, include it to additional_size too. */
669 if (partial_size)
670 {
671 /* additional_size += partial_size. */
672 g = gimple_build_assign (make_ssa_name (size_type_node), PLUS_EXPR,
673 partial_size, additional_size);
674 gsi_insert_before (iter, g, GSI_SAME_STMT);
675 additional_size = gimple_assign_lhs (g);
676 }
677
678 /* new_size = old_size + additional_size. */
679 g = gimple_build_assign (make_ssa_name (size_type_node), PLUS_EXPR, old_size,
680 additional_size);
681 gsi_insert_before (iter, g, GSI_SAME_STMT);
682 tree new_size = gimple_assign_lhs (g);
683
684 /* Build new __builtin_alloca call:
685 new_alloca_with_rz = __builtin_alloca (new_size, align). */
686 tree fn = builtin_decl_implicit (BUILT_IN_ALLOCA_WITH_ALIGN);
687 gg = gimple_build_call (fn, 2, new_size,
688 build_int_cst (size_type_node, align));
689 tree new_alloca_with_rz = make_ssa_name (ptr_type, gg);
690 gimple_call_set_lhs (gg, new_alloca_with_rz);
691 gsi_insert_before (iter, gg, GSI_SAME_STMT);
692
693 /* new_alloca = new_alloca_with_rz + align. */
694 g = gimple_build_assign (make_ssa_name (ptr_type), POINTER_PLUS_EXPR,
695 new_alloca_with_rz,
696 build_int_cst (size_type_node,
697 align / BITS_PER_UNIT));
698 gsi_insert_before (iter, g, GSI_SAME_STMT);
699 tree new_alloca = gimple_assign_lhs (g);
700
701 /* Poison newly created alloca redzones:
702 __asan_alloca_poison (new_alloca, old_size). */
703 fn = builtin_decl_implicit (BUILT_IN_ASAN_ALLOCA_POISON);
704 gg = gimple_build_call (fn, 2, new_alloca, old_size);
705 gsi_insert_before (iter, gg, GSI_SAME_STMT);
706
707 /* Save new_alloca_with_rz value into last_alloca to use it during
708 allocas unpoisoning. */
709 g = gimple_build_assign (last_alloca, new_alloca_with_rz);
710 gsi_insert_before (iter, g, GSI_SAME_STMT);
711
712 /* Finally, replace old alloca ptr with NEW_ALLOCA. */
713 replace_call_with_value (iter, new_alloca);
714}
715
c31c80df 716/* Return the memory references contained in a gimple statement
717 representing a builtin call that has to do with memory access. */
718
719static bool
d08919a7 720get_mem_refs_of_builtin_call (gcall *call,
c31c80df 721 asan_mem_ref *src0,
722 tree *src0_len,
723 bool *src0_is_store,
724 asan_mem_ref *src1,
725 tree *src1_len,
726 bool *src1_is_store,
727 asan_mem_ref *dst,
728 tree *dst_len,
729 bool *dst_is_store,
f9acf11a 730 bool *dest_is_deref,
d08919a7 731 bool *intercepted_p,
732 gimple_stmt_iterator *iter = NULL)
c31c80df 733{
734 gcc_checking_assert (gimple_call_builtin_p (call, BUILT_IN_NORMAL));
735
736 tree callee = gimple_call_fndecl (call);
737 tree source0 = NULL_TREE, source1 = NULL_TREE,
738 dest = NULL_TREE, len = NULL_TREE;
739 bool is_store = true, got_reference_p = false;
86d3a572 740 HOST_WIDE_INT access_size = 1;
c31c80df 741
f9acf11a 742 *intercepted_p = asan_intercepted_p ((DECL_FUNCTION_CODE (callee)));
743
c31c80df 744 switch (DECL_FUNCTION_CODE (callee))
745 {
746 /* (s, s, n) style memops. */
747 case BUILT_IN_BCMP:
748 case BUILT_IN_MEMCMP:
749 source0 = gimple_call_arg (call, 0);
750 source1 = gimple_call_arg (call, 1);
751 len = gimple_call_arg (call, 2);
752 break;
753
754 /* (src, dest, n) style memops. */
755 case BUILT_IN_BCOPY:
756 source0 = gimple_call_arg (call, 0);
757 dest = gimple_call_arg (call, 1);
758 len = gimple_call_arg (call, 2);
759 break;
760
761 /* (dest, src, n) style memops. */
762 case BUILT_IN_MEMCPY:
763 case BUILT_IN_MEMCPY_CHK:
764 case BUILT_IN_MEMMOVE:
765 case BUILT_IN_MEMMOVE_CHK:
766 case BUILT_IN_MEMPCPY:
767 case BUILT_IN_MEMPCPY_CHK:
768 dest = gimple_call_arg (call, 0);
769 source0 = gimple_call_arg (call, 1);
770 len = gimple_call_arg (call, 2);
771 break;
772
773 /* (dest, n) style memops. */
774 case BUILT_IN_BZERO:
775 dest = gimple_call_arg (call, 0);
776 len = gimple_call_arg (call, 1);
777 break;
778
779 /* (dest, x, n) style memops*/
780 case BUILT_IN_MEMSET:
781 case BUILT_IN_MEMSET_CHK:
782 dest = gimple_call_arg (call, 0);
783 len = gimple_call_arg (call, 2);
784 break;
785
786 case BUILT_IN_STRLEN:
787 source0 = gimple_call_arg (call, 0);
788 len = gimple_call_lhs (call);
6e48ee8f 789 break;
c31c80df 790
d08919a7 791 case BUILT_IN_STACK_RESTORE:
792 handle_builtin_stack_restore (call, iter);
793 break;
794
2b34677f 795 CASE_BUILT_IN_ALLOCA:
d08919a7 796 handle_builtin_alloca (call, iter);
797 break;
c31c80df 798 /* And now the __atomic* and __sync builtins.
799 These are handled differently from the classical memory memory
800 access builtins above. */
801
802 case BUILT_IN_ATOMIC_LOAD_1:
c31c80df 803 is_store = false;
6e48ee8f 804 /* FALLTHRU */
c31c80df 805 case BUILT_IN_SYNC_FETCH_AND_ADD_1:
c31c80df 806 case BUILT_IN_SYNC_FETCH_AND_SUB_1:
c31c80df 807 case BUILT_IN_SYNC_FETCH_AND_OR_1:
c31c80df 808 case BUILT_IN_SYNC_FETCH_AND_AND_1:
c31c80df 809 case BUILT_IN_SYNC_FETCH_AND_XOR_1:
c31c80df 810 case BUILT_IN_SYNC_FETCH_AND_NAND_1:
c31c80df 811 case BUILT_IN_SYNC_ADD_AND_FETCH_1:
c31c80df 812 case BUILT_IN_SYNC_SUB_AND_FETCH_1:
c31c80df 813 case BUILT_IN_SYNC_OR_AND_FETCH_1:
c31c80df 814 case BUILT_IN_SYNC_AND_AND_FETCH_1:
c31c80df 815 case BUILT_IN_SYNC_XOR_AND_FETCH_1:
c31c80df 816 case BUILT_IN_SYNC_NAND_AND_FETCH_1:
c31c80df 817 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_1:
c31c80df 818 case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_1:
c31c80df 819 case BUILT_IN_SYNC_LOCK_TEST_AND_SET_1:
c31c80df 820 case BUILT_IN_SYNC_LOCK_RELEASE_1:
c31c80df 821 case BUILT_IN_ATOMIC_EXCHANGE_1:
c31c80df 822 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_1:
c31c80df 823 case BUILT_IN_ATOMIC_STORE_1:
c31c80df 824 case BUILT_IN_ATOMIC_ADD_FETCH_1:
c31c80df 825 case BUILT_IN_ATOMIC_SUB_FETCH_1:
c31c80df 826 case BUILT_IN_ATOMIC_AND_FETCH_1:
c31c80df 827 case BUILT_IN_ATOMIC_NAND_FETCH_1:
c31c80df 828 case BUILT_IN_ATOMIC_XOR_FETCH_1:
c31c80df 829 case BUILT_IN_ATOMIC_OR_FETCH_1:
c31c80df 830 case BUILT_IN_ATOMIC_FETCH_ADD_1:
c31c80df 831 case BUILT_IN_ATOMIC_FETCH_SUB_1:
c31c80df 832 case BUILT_IN_ATOMIC_FETCH_AND_1:
c31c80df 833 case BUILT_IN_ATOMIC_FETCH_NAND_1:
c31c80df 834 case BUILT_IN_ATOMIC_FETCH_XOR_1:
c31c80df 835 case BUILT_IN_ATOMIC_FETCH_OR_1:
6e48ee8f 836 access_size = 1;
837 goto do_atomic;
838
839 case BUILT_IN_ATOMIC_LOAD_2:
840 is_store = false;
841 /* FALLTHRU */
842 case BUILT_IN_SYNC_FETCH_AND_ADD_2:
843 case BUILT_IN_SYNC_FETCH_AND_SUB_2:
844 case BUILT_IN_SYNC_FETCH_AND_OR_2:
845 case BUILT_IN_SYNC_FETCH_AND_AND_2:
846 case BUILT_IN_SYNC_FETCH_AND_XOR_2:
847 case BUILT_IN_SYNC_FETCH_AND_NAND_2:
848 case BUILT_IN_SYNC_ADD_AND_FETCH_2:
849 case BUILT_IN_SYNC_SUB_AND_FETCH_2:
850 case BUILT_IN_SYNC_OR_AND_FETCH_2:
851 case BUILT_IN_SYNC_AND_AND_FETCH_2:
852 case BUILT_IN_SYNC_XOR_AND_FETCH_2:
853 case BUILT_IN_SYNC_NAND_AND_FETCH_2:
854 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_2:
855 case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_2:
856 case BUILT_IN_SYNC_LOCK_TEST_AND_SET_2:
857 case BUILT_IN_SYNC_LOCK_RELEASE_2:
858 case BUILT_IN_ATOMIC_EXCHANGE_2:
859 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_2:
860 case BUILT_IN_ATOMIC_STORE_2:
861 case BUILT_IN_ATOMIC_ADD_FETCH_2:
862 case BUILT_IN_ATOMIC_SUB_FETCH_2:
863 case BUILT_IN_ATOMIC_AND_FETCH_2:
864 case BUILT_IN_ATOMIC_NAND_FETCH_2:
865 case BUILT_IN_ATOMIC_XOR_FETCH_2:
866 case BUILT_IN_ATOMIC_OR_FETCH_2:
867 case BUILT_IN_ATOMIC_FETCH_ADD_2:
868 case BUILT_IN_ATOMIC_FETCH_SUB_2:
869 case BUILT_IN_ATOMIC_FETCH_AND_2:
870 case BUILT_IN_ATOMIC_FETCH_NAND_2:
871 case BUILT_IN_ATOMIC_FETCH_XOR_2:
c31c80df 872 case BUILT_IN_ATOMIC_FETCH_OR_2:
6e48ee8f 873 access_size = 2;
874 goto do_atomic;
875
876 case BUILT_IN_ATOMIC_LOAD_4:
877 is_store = false;
878 /* FALLTHRU */
879 case BUILT_IN_SYNC_FETCH_AND_ADD_4:
880 case BUILT_IN_SYNC_FETCH_AND_SUB_4:
881 case BUILT_IN_SYNC_FETCH_AND_OR_4:
882 case BUILT_IN_SYNC_FETCH_AND_AND_4:
883 case BUILT_IN_SYNC_FETCH_AND_XOR_4:
884 case BUILT_IN_SYNC_FETCH_AND_NAND_4:
885 case BUILT_IN_SYNC_ADD_AND_FETCH_4:
886 case BUILT_IN_SYNC_SUB_AND_FETCH_4:
887 case BUILT_IN_SYNC_OR_AND_FETCH_4:
888 case BUILT_IN_SYNC_AND_AND_FETCH_4:
889 case BUILT_IN_SYNC_XOR_AND_FETCH_4:
890 case BUILT_IN_SYNC_NAND_AND_FETCH_4:
891 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_4:
892 case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_4:
893 case BUILT_IN_SYNC_LOCK_TEST_AND_SET_4:
894 case BUILT_IN_SYNC_LOCK_RELEASE_4:
895 case BUILT_IN_ATOMIC_EXCHANGE_4:
896 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_4:
897 case BUILT_IN_ATOMIC_STORE_4:
898 case BUILT_IN_ATOMIC_ADD_FETCH_4:
899 case BUILT_IN_ATOMIC_SUB_FETCH_4:
900 case BUILT_IN_ATOMIC_AND_FETCH_4:
901 case BUILT_IN_ATOMIC_NAND_FETCH_4:
902 case BUILT_IN_ATOMIC_XOR_FETCH_4:
903 case BUILT_IN_ATOMIC_OR_FETCH_4:
904 case BUILT_IN_ATOMIC_FETCH_ADD_4:
905 case BUILT_IN_ATOMIC_FETCH_SUB_4:
906 case BUILT_IN_ATOMIC_FETCH_AND_4:
907 case BUILT_IN_ATOMIC_FETCH_NAND_4:
908 case BUILT_IN_ATOMIC_FETCH_XOR_4:
c31c80df 909 case BUILT_IN_ATOMIC_FETCH_OR_4:
6e48ee8f 910 access_size = 4;
911 goto do_atomic;
912
913 case BUILT_IN_ATOMIC_LOAD_8:
914 is_store = false;
915 /* FALLTHRU */
916 case BUILT_IN_SYNC_FETCH_AND_ADD_8:
917 case BUILT_IN_SYNC_FETCH_AND_SUB_8:
918 case BUILT_IN_SYNC_FETCH_AND_OR_8:
919 case BUILT_IN_SYNC_FETCH_AND_AND_8:
920 case BUILT_IN_SYNC_FETCH_AND_XOR_8:
921 case BUILT_IN_SYNC_FETCH_AND_NAND_8:
922 case BUILT_IN_SYNC_ADD_AND_FETCH_8:
923 case BUILT_IN_SYNC_SUB_AND_FETCH_8:
924 case BUILT_IN_SYNC_OR_AND_FETCH_8:
925 case BUILT_IN_SYNC_AND_AND_FETCH_8:
926 case BUILT_IN_SYNC_XOR_AND_FETCH_8:
927 case BUILT_IN_SYNC_NAND_AND_FETCH_8:
928 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_8:
929 case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_8:
930 case BUILT_IN_SYNC_LOCK_TEST_AND_SET_8:
931 case BUILT_IN_SYNC_LOCK_RELEASE_8:
932 case BUILT_IN_ATOMIC_EXCHANGE_8:
933 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_8:
934 case BUILT_IN_ATOMIC_STORE_8:
935 case BUILT_IN_ATOMIC_ADD_FETCH_8:
936 case BUILT_IN_ATOMIC_SUB_FETCH_8:
937 case BUILT_IN_ATOMIC_AND_FETCH_8:
938 case BUILT_IN_ATOMIC_NAND_FETCH_8:
939 case BUILT_IN_ATOMIC_XOR_FETCH_8:
940 case BUILT_IN_ATOMIC_OR_FETCH_8:
941 case BUILT_IN_ATOMIC_FETCH_ADD_8:
942 case BUILT_IN_ATOMIC_FETCH_SUB_8:
943 case BUILT_IN_ATOMIC_FETCH_AND_8:
944 case BUILT_IN_ATOMIC_FETCH_NAND_8:
945 case BUILT_IN_ATOMIC_FETCH_XOR_8:
c31c80df 946 case BUILT_IN_ATOMIC_FETCH_OR_8:
6e48ee8f 947 access_size = 8;
948 goto do_atomic;
949
950 case BUILT_IN_ATOMIC_LOAD_16:
951 is_store = false;
952 /* FALLTHRU */
953 case BUILT_IN_SYNC_FETCH_AND_ADD_16:
954 case BUILT_IN_SYNC_FETCH_AND_SUB_16:
955 case BUILT_IN_SYNC_FETCH_AND_OR_16:
956 case BUILT_IN_SYNC_FETCH_AND_AND_16:
957 case BUILT_IN_SYNC_FETCH_AND_XOR_16:
958 case BUILT_IN_SYNC_FETCH_AND_NAND_16:
959 case BUILT_IN_SYNC_ADD_AND_FETCH_16:
960 case BUILT_IN_SYNC_SUB_AND_FETCH_16:
961 case BUILT_IN_SYNC_OR_AND_FETCH_16:
962 case BUILT_IN_SYNC_AND_AND_FETCH_16:
963 case BUILT_IN_SYNC_XOR_AND_FETCH_16:
964 case BUILT_IN_SYNC_NAND_AND_FETCH_16:
965 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_16:
966 case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_16:
967 case BUILT_IN_SYNC_LOCK_TEST_AND_SET_16:
968 case BUILT_IN_SYNC_LOCK_RELEASE_16:
969 case BUILT_IN_ATOMIC_EXCHANGE_16:
970 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_16:
971 case BUILT_IN_ATOMIC_STORE_16:
972 case BUILT_IN_ATOMIC_ADD_FETCH_16:
973 case BUILT_IN_ATOMIC_SUB_FETCH_16:
974 case BUILT_IN_ATOMIC_AND_FETCH_16:
975 case BUILT_IN_ATOMIC_NAND_FETCH_16:
976 case BUILT_IN_ATOMIC_XOR_FETCH_16:
977 case BUILT_IN_ATOMIC_OR_FETCH_16:
978 case BUILT_IN_ATOMIC_FETCH_ADD_16:
979 case BUILT_IN_ATOMIC_FETCH_SUB_16:
980 case BUILT_IN_ATOMIC_FETCH_AND_16:
981 case BUILT_IN_ATOMIC_FETCH_NAND_16:
982 case BUILT_IN_ATOMIC_FETCH_XOR_16:
c31c80df 983 case BUILT_IN_ATOMIC_FETCH_OR_16:
6e48ee8f 984 access_size = 16;
985 /* FALLTHRU */
986 do_atomic:
c31c80df 987 {
988 dest = gimple_call_arg (call, 0);
989 /* DEST represents the address of a memory location.
990 instrument_derefs wants the memory location, so lets
991 dereference the address DEST before handing it to
992 instrument_derefs. */
6e48ee8f 993 tree type = build_nonstandard_integer_type (access_size
994 * BITS_PER_UNIT, 1);
995 dest = build2 (MEM_REF, type, dest,
996 build_int_cst (build_pointer_type (char_type_node), 0));
997 break;
c31c80df 998 }
999
1000 default:
1001 /* The other builtins memory access are not instrumented in this
1002 function because they either don't have any length parameter,
1003 or their length parameter is just a limit. */
1004 break;
1005 }
1006
1007 if (len != NULL_TREE)
1008 {
1009 if (source0 != NULL_TREE)
1010 {
1011 src0->start = source0;
1012 src0->access_size = access_size;
1013 *src0_len = len;
1014 *src0_is_store = false;
1015 }
1016
1017 if (source1 != NULL_TREE)
1018 {
1019 src1->start = source1;
1020 src1->access_size = access_size;
1021 *src1_len = len;
1022 *src1_is_store = false;
1023 }
1024
1025 if (dest != NULL_TREE)
1026 {
1027 dst->start = dest;
1028 dst->access_size = access_size;
1029 *dst_len = len;
1030 *dst_is_store = true;
1031 }
1032
1033 got_reference_p = true;
1034 }
d9dc05a1 1035 else if (dest)
1036 {
1037 dst->start = dest;
1038 dst->access_size = access_size;
1039 *dst_len = NULL_TREE;
1040 *dst_is_store = is_store;
1041 *dest_is_deref = true;
1042 got_reference_p = true;
1043 }
c31c80df 1044
d9dc05a1 1045 return got_reference_p;
c31c80df 1046}
1047
1048/* Return true iff a given gimple statement has been instrumented.
1049 Note that the statement is "defined" by the memory references it
1050 contains. */
1051
1052static bool
42acab1c 1053has_stmt_been_instrumented_p (gimple *stmt)
c31c80df 1054{
1055 if (gimple_assign_single_p (stmt))
1056 {
1057 bool r_is_store;
1058 asan_mem_ref r;
1059 asan_mem_ref_init (&r, NULL, 1);
1060
1a91d914 1061 if (get_mem_ref_of_assignment (as_a <gassign *> (stmt), &r,
1062 &r_is_store))
c31c80df 1063 return has_mem_ref_been_instrumented (&r);
1064 }
1065 else if (gimple_call_builtin_p (stmt, BUILT_IN_NORMAL))
1066 {
1067 asan_mem_ref src0, src1, dest;
1068 asan_mem_ref_init (&src0, NULL, 1);
1069 asan_mem_ref_init (&src1, NULL, 1);
1070 asan_mem_ref_init (&dest, NULL, 1);
1071
1072 tree src0_len = NULL_TREE, src1_len = NULL_TREE, dest_len = NULL_TREE;
1073 bool src0_is_store = false, src1_is_store = false,
f9acf11a 1074 dest_is_store = false, dest_is_deref = false, intercepted_p = true;
1a91d914 1075 if (get_mem_refs_of_builtin_call (as_a <gcall *> (stmt),
c31c80df 1076 &src0, &src0_len, &src0_is_store,
1077 &src1, &src1_len, &src1_is_store,
1078 &dest, &dest_len, &dest_is_store,
f9acf11a 1079 &dest_is_deref, &intercepted_p))
c31c80df 1080 {
1081 if (src0.start != NULL_TREE
1082 && !has_mem_ref_been_instrumented (&src0, src0_len))
1083 return false;
1084
1085 if (src1.start != NULL_TREE
1086 && !has_mem_ref_been_instrumented (&src1, src1_len))
1087 return false;
1088
1089 if (dest.start != NULL_TREE
1090 && !has_mem_ref_been_instrumented (&dest, dest_len))
1091 return false;
1092
1093 return true;
1094 }
1095 }
774068a0 1096 else if (is_gimple_call (stmt) && gimple_store_p (stmt))
1097 {
1098 asan_mem_ref r;
1099 asan_mem_ref_init (&r, NULL, 1);
1100
1101 r.start = gimple_call_lhs (stmt);
1102 r.access_size = int_size_in_bytes (TREE_TYPE (r.start));
1103 return has_mem_ref_been_instrumented (&r);
1104 }
1105
c31c80df 1106 return false;
1107}
1108
1109/* Insert a memory reference into the hash table. */
1110
1111static void
86d3a572 1112update_mem_ref_hash_table (tree ref, HOST_WIDE_INT access_size)
c31c80df 1113{
c1f445d2 1114 hash_table<asan_mem_ref_hasher> *ht = get_mem_ref_hash_table ();
c31c80df 1115
1116 asan_mem_ref r;
1117 asan_mem_ref_init (&r, ref, access_size);
1118
c1f445d2 1119 asan_mem_ref **slot = ht->find_slot (&r, INSERT);
f9acf11a 1120 if (*slot == NULL || (*slot)->access_size < access_size)
c31c80df 1121 *slot = asan_mem_ref_new (ref, access_size);
1122}
1123
55b58027 1124/* Initialize shadow_ptr_types array. */
1125
1126static void
1127asan_init_shadow_ptr_types (void)
1128{
1129 asan_shadow_set = new_alias_set ();
629b6abc 1130 tree types[3] = { signed_char_type_node, short_integer_type_node,
1131 integer_type_node };
1132
1133 for (unsigned i = 0; i < 3; i++)
1134 {
1135 shadow_ptr_types[i] = build_distinct_type_copy (types[i]);
1136 TYPE_ALIAS_SET (shadow_ptr_types[i]) = asan_shadow_set;
1137 shadow_ptr_types[i] = build_pointer_type (shadow_ptr_types[i]);
1138 }
1139
55b58027 1140 initialize_sanitizer_builtins ();
1141}
1142
b75d2c15 1143/* Create ADDR_EXPR of STRING_CST with the PP pretty printer text. */
92fc5c48 1144
1145static tree
b75d2c15 1146asan_pp_string (pretty_printer *pp)
92fc5c48 1147{
b75d2c15 1148 const char *buf = pp_formatted_text (pp);
92fc5c48 1149 size_t len = strlen (buf);
1150 tree ret = build_string (len + 1, buf);
1151 TREE_TYPE (ret)
55b58027 1152 = build_array_type (TREE_TYPE (shadow_ptr_types[0]),
1153 build_index_type (size_int (len)));
92fc5c48 1154 TREE_READONLY (ret) = 1;
1155 TREE_STATIC (ret) = 1;
55b58027 1156 return build1 (ADDR_EXPR, shadow_ptr_types[0], ret);
92fc5c48 1157}
1158
3c919612 1159/* Return a CONST_INT representing 4 subsequent shadow memory bytes. */
1160
1161static rtx
1162asan_shadow_cst (unsigned char shadow_bytes[4])
1163{
1164 int i;
1165 unsigned HOST_WIDE_INT val = 0;
1166 gcc_assert (WORDS_BIG_ENDIAN == BYTES_BIG_ENDIAN);
1167 for (i = 0; i < 4; i++)
1168 val |= (unsigned HOST_WIDE_INT) shadow_bytes[BYTES_BIG_ENDIAN ? 3 - i : i]
1169 << (BITS_PER_UNIT * i);
bc89f4e2 1170 return gen_int_mode (val, SImode);
3c919612 1171}
1172
cc72d6e9 1173/* Clear shadow memory at SHADOW_MEM, LEN bytes. Can't call a library call here
1174 though. */
1175
1176static void
1177asan_clear_shadow (rtx shadow_mem, HOST_WIDE_INT len)
1178{
dbf944e5 1179 rtx_insn *insn, *insns, *jump;
1180 rtx_code_label *top_label;
1181 rtx end, addr, tmp;
cc72d6e9 1182
1183 start_sequence ();
1184 clear_storage (shadow_mem, GEN_INT (len), BLOCK_OP_NORMAL);
1185 insns = get_insns ();
1186 end_sequence ();
1187 for (insn = insns; insn; insn = NEXT_INSN (insn))
1188 if (CALL_P (insn))
1189 break;
1190 if (insn == NULL_RTX)
1191 {
1192 emit_insn (insns);
1193 return;
1194 }
1195
1196 gcc_assert ((len & 3) == 0);
1197 top_label = gen_label_rtx ();
a15fa55a 1198 addr = copy_to_mode_reg (Pmode, XEXP (shadow_mem, 0));
cc72d6e9 1199 shadow_mem = adjust_automodify_address (shadow_mem, SImode, addr, 0);
1200 end = force_reg (Pmode, plus_constant (Pmode, addr, len));
1201 emit_label (top_label);
1202
1203 emit_move_insn (shadow_mem, const0_rtx);
0359f9f5 1204 tmp = expand_simple_binop (Pmode, PLUS, addr, gen_int_mode (4, Pmode), addr,
ff326078 1205 true, OPTAB_LIB_WIDEN);
cc72d6e9 1206 if (tmp != addr)
1207 emit_move_insn (addr, tmp);
1208 emit_cmp_and_jump_insns (addr, end, LT, NULL_RTX, Pmode, true, top_label);
1209 jump = get_last_insn ();
1210 gcc_assert (JUMP_P (jump));
61cb1816 1211 add_reg_br_prob_note (jump,
1212 profile_probability::guessed_always ()
1213 .apply_scale (80, 100));
cc72d6e9 1214}
1215
1e80ce41 1216void
1217asan_function_start (void)
1218{
1219 section *fnsec = function_section (current_function_decl);
1220 switch_to_section (fnsec);
1221 ASM_OUTPUT_DEBUG_LABEL (asm_out_file, "LASANPC",
ff326078 1222 current_function_funcdef_no);
1e80ce41 1223}
1224
629b6abc 1225/* Return number of shadow bytes that are occupied by a local variable
1226 of SIZE bytes. */
1227
1228static unsigned HOST_WIDE_INT
1229shadow_mem_size (unsigned HOST_WIDE_INT size)
1230{
1231 return ROUND_UP (size, ASAN_SHADOW_GRANULARITY) / ASAN_SHADOW_GRANULARITY;
1232}
1233
3c919612 1234/* Insert code to protect stack vars. The prologue sequence should be emitted
1235 directly, epilogue sequence returned. BASE is the register holding the
1236 stack base, against which OFFSETS array offsets are relative to, OFFSETS
1237 array contains pairs of offsets in reverse order, always the end offset
1238 of some gap that needs protection followed by starting offset,
1239 and DECLS is an array of representative decls for each var partition.
1240 LENGTH is the length of the OFFSETS array, DECLS array is LENGTH / 2 - 1
1241 elements long (OFFSETS include gap before the first variable as well
683539f6 1242 as gaps after each stack variable). PBASE is, if non-NULL, some pseudo
1243 register which stack vars DECL_RTLs are based on. Either BASE should be
1244 assigned to PBASE, when not doing use after return protection, or
1245 corresponding address based on __asan_stack_malloc* return value. */
3c919612 1246
67ab16d9 1247rtx_insn *
683539f6 1248asan_emit_stack_protection (rtx base, rtx pbase, unsigned int alignb,
1249 HOST_WIDE_INT *offsets, tree *decls, int length)
3c919612 1250{
79f6a8ed 1251 rtx shadow_base, shadow_mem, ret, mem, orig_base;
1252 rtx_code_label *lab;
67ab16d9 1253 rtx_insn *insns;
f25b3fef 1254 char buf[32];
3c919612 1255 unsigned char shadow_bytes[4];
683539f6 1256 HOST_WIDE_INT base_offset = offsets[length - 1];
1257 HOST_WIDE_INT base_align_bias = 0, offset, prev_offset;
1258 HOST_WIDE_INT asan_frame_size = offsets[0] - base_offset;
355c1762 1259 HOST_WIDE_INT last_offset, last_size;
3c919612 1260 int l;
1261 unsigned char cur_shadow_byte = ASAN_STACK_MAGIC_LEFT;
1e80ce41 1262 tree str_cst, decl, id;
683539f6 1263 int use_after_return_class = -1;
3c919612 1264
55b58027 1265 if (shadow_ptr_types[0] == NULL_TREE)
1266 asan_init_shadow_ptr_types ();
1267
3c919612 1268 /* First of all, prepare the description string. */
b75d2c15 1269 pretty_printer asan_pp;
eed6bc21 1270
92fc5c48 1271 pp_decimal_int (&asan_pp, length / 2 - 1);
1272 pp_space (&asan_pp);
3c919612 1273 for (l = length - 2; l; l -= 2)
1274 {
1275 tree decl = decls[l / 2 - 1];
92fc5c48 1276 pp_wide_integer (&asan_pp, offsets[l] - base_offset);
1277 pp_space (&asan_pp);
1278 pp_wide_integer (&asan_pp, offsets[l - 1] - offsets[l]);
1279 pp_space (&asan_pp);
3c919612 1280 if (DECL_P (decl) && DECL_NAME (decl))
1281 {
92fc5c48 1282 pp_decimal_int (&asan_pp, IDENTIFIER_LENGTH (DECL_NAME (decl)));
1283 pp_space (&asan_pp);
a94db6b0 1284 pp_tree_identifier (&asan_pp, DECL_NAME (decl));
3c919612 1285 }
1286 else
92fc5c48 1287 pp_string (&asan_pp, "9 <unknown>");
1288 pp_space (&asan_pp);
3c919612 1289 }
b75d2c15 1290 str_cst = asan_pp_string (&asan_pp);
3c919612 1291
1292 /* Emit the prologue sequence. */
bf2b7c22 1293 if (asan_frame_size > 32 && asan_frame_size <= 65536 && pbase
1294 && ASAN_USE_AFTER_RETURN)
683539f6 1295 {
1296 use_after_return_class = floor_log2 (asan_frame_size - 1) - 5;
1297 /* __asan_stack_malloc_N guarantees alignment
ff326078 1298 N < 6 ? (64 << N) : 4096 bytes. */
683539f6 1299 if (alignb > (use_after_return_class < 6
1300 ? (64U << use_after_return_class) : 4096U))
1301 use_after_return_class = -1;
1302 else if (alignb > ASAN_RED_ZONE_SIZE && (asan_frame_size & (alignb - 1)))
1303 base_align_bias = ((asan_frame_size + alignb - 1)
1304 & ~(alignb - HOST_WIDE_INT_1)) - asan_frame_size;
1305 }
f89175bb 1306 /* Align base if target is STRICT_ALIGNMENT. */
1307 if (STRICT_ALIGNMENT)
1308 base = expand_binop (Pmode, and_optab, base,
1309 gen_int_mode (-((GET_MODE_ALIGNMENT (SImode)
1310 << ASAN_SHADOW_SHIFT)
1311 / BITS_PER_UNIT), Pmode), NULL_RTX,
1312 1, OPTAB_DIRECT);
1313
683539f6 1314 if (use_after_return_class == -1 && pbase)
1315 emit_move_insn (pbase, base);
f89175bb 1316
0359f9f5 1317 base = expand_binop (Pmode, add_optab, base,
683539f6 1318 gen_int_mode (base_offset - base_align_bias, Pmode),
3c919612 1319 NULL_RTX, 1, OPTAB_DIRECT);
683539f6 1320 orig_base = NULL_RTX;
1321 if (use_after_return_class != -1)
1322 {
1323 if (asan_detect_stack_use_after_return == NULL_TREE)
1324 {
1325 id = get_identifier ("__asan_option_detect_stack_use_after_return");
1326 decl = build_decl (BUILTINS_LOCATION, VAR_DECL, id,
1327 integer_type_node);
1328 SET_DECL_ASSEMBLER_NAME (decl, id);
1329 TREE_ADDRESSABLE (decl) = 1;
1330 DECL_ARTIFICIAL (decl) = 1;
1331 DECL_IGNORED_P (decl) = 1;
1332 DECL_EXTERNAL (decl) = 1;
1333 TREE_STATIC (decl) = 1;
1334 TREE_PUBLIC (decl) = 1;
1335 TREE_USED (decl) = 1;
1336 asan_detect_stack_use_after_return = decl;
1337 }
1338 orig_base = gen_reg_rtx (Pmode);
1339 emit_move_insn (orig_base, base);
1340 ret = expand_normal (asan_detect_stack_use_after_return);
1341 lab = gen_label_rtx ();
683539f6 1342 emit_cmp_and_jump_insns (ret, const0_rtx, EQ, NULL_RTX,
720cfc43 1343 VOIDmode, 0, lab,
1344 profile_probability::very_likely ());
683539f6 1345 snprintf (buf, sizeof buf, "__asan_stack_malloc_%d",
1346 use_after_return_class);
1347 ret = init_one_libfunc (buf);
9e9e5c15 1348 ret = emit_library_call_value (ret, NULL_RTX, LCT_NORMAL, ptr_mode,
683539f6 1349 GEN_INT (asan_frame_size
1350 + base_align_bias),
7966ce00 1351 TYPE_MODE (pointer_sized_int_node));
1352 /* __asan_stack_malloc_[n] returns a pointer to fake stack if succeeded
1353 and NULL otherwise. Check RET value is NULL here and jump over the
1354 BASE reassignment in this case. Otherwise, reassign BASE to RET. */
7966ce00 1355 emit_cmp_and_jump_insns (ret, const0_rtx, EQ, NULL_RTX,
720cfc43 1356 VOIDmode, 0, lab,
1357 profile_probability:: very_unlikely ());
683539f6 1358 ret = convert_memory_address (Pmode, ret);
1359 emit_move_insn (base, ret);
1360 emit_label (lab);
1361 emit_move_insn (pbase, expand_binop (Pmode, add_optab, base,
1362 gen_int_mode (base_align_bias
1363 - base_offset, Pmode),
1364 NULL_RTX, 1, OPTAB_DIRECT));
1365 }
3c919612 1366 mem = gen_rtx_MEM (ptr_mode, base);
683539f6 1367 mem = adjust_address (mem, VOIDmode, base_align_bias);
d11aedc7 1368 emit_move_insn (mem, gen_int_mode (ASAN_STACK_FRAME_MAGIC, ptr_mode));
3c919612 1369 mem = adjust_address (mem, VOIDmode, GET_MODE_SIZE (ptr_mode));
1370 emit_move_insn (mem, expand_normal (str_cst));
1e80ce41 1371 mem = adjust_address (mem, VOIDmode, GET_MODE_SIZE (ptr_mode));
1372 ASM_GENERATE_INTERNAL_LABEL (buf, "LASANPC", current_function_funcdef_no);
1373 id = get_identifier (buf);
1374 decl = build_decl (DECL_SOURCE_LOCATION (current_function_decl),
ff326078 1375 VAR_DECL, id, char_type_node);
1e80ce41 1376 SET_DECL_ASSEMBLER_NAME (decl, id);
1377 TREE_ADDRESSABLE (decl) = 1;
1378 TREE_READONLY (decl) = 1;
1379 DECL_ARTIFICIAL (decl) = 1;
1380 DECL_IGNORED_P (decl) = 1;
1381 TREE_STATIC (decl) = 1;
1382 TREE_PUBLIC (decl) = 0;
1383 TREE_USED (decl) = 1;
7c4fae98 1384 DECL_INITIAL (decl) = decl;
1385 TREE_ASM_WRITTEN (decl) = 1;
1386 TREE_ASM_WRITTEN (id) = 1;
1e80ce41 1387 emit_move_insn (mem, expand_normal (build_fold_addr_expr (decl)));
3c919612 1388 shadow_base = expand_binop (Pmode, lshr_optab, base,
1389 GEN_INT (ASAN_SHADOW_SHIFT),
1390 NULL_RTX, 1, OPTAB_DIRECT);
683539f6 1391 shadow_base
1392 = plus_constant (Pmode, shadow_base,
cf357977 1393 asan_shadow_offset ()
683539f6 1394 + (base_align_bias >> ASAN_SHADOW_SHIFT));
3c919612 1395 gcc_assert (asan_shadow_set != -1
1396 && (ASAN_RED_ZONE_SIZE >> ASAN_SHADOW_SHIFT) == 4);
1397 shadow_mem = gen_rtx_MEM (SImode, shadow_base);
1398 set_mem_alias_set (shadow_mem, asan_shadow_set);
f89175bb 1399 if (STRICT_ALIGNMENT)
1400 set_mem_align (shadow_mem, (GET_MODE_ALIGNMENT (SImode)));
3c919612 1401 prev_offset = base_offset;
1402 for (l = length; l; l -= 2)
1403 {
1404 if (l == 2)
1405 cur_shadow_byte = ASAN_STACK_MAGIC_RIGHT;
1406 offset = offsets[l - 1];
1407 if ((offset - base_offset) & (ASAN_RED_ZONE_SIZE - 1))
1408 {
1409 int i;
1410 HOST_WIDE_INT aoff
1411 = base_offset + ((offset - base_offset)
1412 & ~(ASAN_RED_ZONE_SIZE - HOST_WIDE_INT_1));
1413 shadow_mem = adjust_address (shadow_mem, VOIDmode,
1414 (aoff - prev_offset)
1415 >> ASAN_SHADOW_SHIFT);
1416 prev_offset = aoff;
629b6abc 1417 for (i = 0; i < 4; i++, aoff += ASAN_SHADOW_GRANULARITY)
3c919612 1418 if (aoff < offset)
1419 {
629b6abc 1420 if (aoff < offset - (HOST_WIDE_INT)ASAN_SHADOW_GRANULARITY + 1)
3c919612 1421 shadow_bytes[i] = 0;
1422 else
1423 shadow_bytes[i] = offset - aoff;
1424 }
1425 else
1350ad47 1426 shadow_bytes[i] = ASAN_STACK_MAGIC_MIDDLE;
3c919612 1427 emit_move_insn (shadow_mem, asan_shadow_cst (shadow_bytes));
1428 offset = aoff;
1429 }
1430 while (offset <= offsets[l - 2] - ASAN_RED_ZONE_SIZE)
1431 {
1432 shadow_mem = adjust_address (shadow_mem, VOIDmode,
1433 (offset - prev_offset)
1434 >> ASAN_SHADOW_SHIFT);
1435 prev_offset = offset;
1436 memset (shadow_bytes, cur_shadow_byte, 4);
1437 emit_move_insn (shadow_mem, asan_shadow_cst (shadow_bytes));
1438 offset += ASAN_RED_ZONE_SIZE;
1439 }
1440 cur_shadow_byte = ASAN_STACK_MAGIC_MIDDLE;
1441 }
1442 do_pending_stack_adjust ();
1443
1444 /* Construct epilogue sequence. */
1445 start_sequence ();
1446
79f6a8ed 1447 lab = NULL;
683539f6 1448 if (use_after_return_class != -1)
1449 {
79f6a8ed 1450 rtx_code_label *lab2 = gen_label_rtx ();
683539f6 1451 char c = (char) ASAN_STACK_MAGIC_USE_AFTER_RET;
683539f6 1452 emit_cmp_and_jump_insns (orig_base, base, EQ, NULL_RTX,
720cfc43 1453 VOIDmode, 0, lab2,
1454 profile_probability::very_likely ());
683539f6 1455 shadow_mem = gen_rtx_MEM (BLKmode, shadow_base);
1456 set_mem_alias_set (shadow_mem, asan_shadow_set);
1457 mem = gen_rtx_MEM (ptr_mode, base);
1458 mem = adjust_address (mem, VOIDmode, base_align_bias);
1459 emit_move_insn (mem, gen_int_mode (ASAN_STACK_RETIRED_MAGIC, ptr_mode));
1460 unsigned HOST_WIDE_INT sz = asan_frame_size >> ASAN_SHADOW_SHIFT;
1461 if (use_after_return_class < 5
1462 && can_store_by_pieces (sz, builtin_memset_read_str, &c,
1463 BITS_PER_UNIT, true))
1464 store_by_pieces (shadow_mem, sz, builtin_memset_read_str, &c,
1465 BITS_PER_UNIT, true, 0);
1466 else if (use_after_return_class >= 5
1467 || !set_storage_via_setmem (shadow_mem,
1468 GEN_INT (sz),
1469 gen_int_mode (c, QImode),
1470 BITS_PER_UNIT, BITS_PER_UNIT,
1471 -1, sz, sz, sz))
1472 {
1473 snprintf (buf, sizeof buf, "__asan_stack_free_%d",
1474 use_after_return_class);
1475 ret = init_one_libfunc (buf);
1476 rtx addr = convert_memory_address (ptr_mode, base);
1477 rtx orig_addr = convert_memory_address (ptr_mode, orig_base);
9e9e5c15 1478 emit_library_call (ret, LCT_NORMAL, ptr_mode, addr, ptr_mode,
683539f6 1479 GEN_INT (asan_frame_size + base_align_bias),
1480 TYPE_MODE (pointer_sized_int_node),
1481 orig_addr, ptr_mode);
1482 }
1483 lab = gen_label_rtx ();
1484 emit_jump (lab);
1485 emit_label (lab2);
1486 }
1487
3c919612 1488 shadow_mem = gen_rtx_MEM (BLKmode, shadow_base);
1489 set_mem_alias_set (shadow_mem, asan_shadow_set);
f89175bb 1490
1491 if (STRICT_ALIGNMENT)
1492 set_mem_align (shadow_mem, (GET_MODE_ALIGNMENT (SImode)));
1493
355c1762 1494 prev_offset = base_offset;
3c919612 1495 last_offset = base_offset;
355c1762 1496 last_size = 0;
1497 for (l = length; l; l -= 2)
3c919612 1498 {
355c1762 1499 offset = base_offset + ((offsets[l - 1] - base_offset)
1500 & ~(ASAN_RED_ZONE_SIZE - HOST_WIDE_INT_1));
1501 if (last_offset + last_size != offset)
3c919612 1502 {
355c1762 1503 shadow_mem = adjust_address (shadow_mem, VOIDmode,
1504 (last_offset - prev_offset)
1505 >> ASAN_SHADOW_SHIFT);
1506 prev_offset = last_offset;
1507 asan_clear_shadow (shadow_mem, last_size >> ASAN_SHADOW_SHIFT);
1508 last_offset = offset;
1509 last_size = 0;
1510 }
1511 last_size += base_offset + ((offsets[l - 2] - base_offset)
1512 & ~(ASAN_RED_ZONE_SIZE - HOST_WIDE_INT_1))
1513 - offset;
629b6abc 1514
355c1762 1515 /* Unpoison shadow memory that corresponds to a variable that is
1516 is subject of use-after-return sanitization. */
1517 if (l > 2)
1518 {
1519 decl = decls[l / 2 - 2];
629b6abc 1520 if (asan_handled_variables != NULL
1521 && asan_handled_variables->contains (decl))
1522 {
355c1762 1523 HOST_WIDE_INT size = offsets[l - 3] - offsets[l - 2];
629b6abc 1524 if (dump_file && (dump_flags & TDF_DETAILS))
1525 {
1526 const char *n = (DECL_NAME (decl)
1527 ? IDENTIFIER_POINTER (DECL_NAME (decl))
1528 : "<unknown>");
1529 fprintf (dump_file, "Unpoisoning shadow stack for variable: "
355c1762 1530 "%s (%" PRId64 " B)\n", n, size);
629b6abc 1531 }
1532
355c1762 1533 last_size += size & ~(ASAN_RED_ZONE_SIZE - HOST_WIDE_INT_1);
629b6abc 1534 }
3c919612 1535 }
355c1762 1536 }
1537 if (last_size)
1538 {
1539 shadow_mem = adjust_address (shadow_mem, VOIDmode,
1540 (last_offset - prev_offset)
1541 >> ASAN_SHADOW_SHIFT);
1542 asan_clear_shadow (shadow_mem, last_size >> ASAN_SHADOW_SHIFT);
3c919612 1543 }
1544
629b6abc 1545 /* Clean-up set with instrumented stack variables. */
1546 delete asan_handled_variables;
1547 asan_handled_variables = NULL;
1548 delete asan_used_labels;
1549 asan_used_labels = NULL;
1550
3c919612 1551 do_pending_stack_adjust ();
683539f6 1552 if (lab)
1553 emit_label (lab);
3c919612 1554
67ab16d9 1555 insns = get_insns ();
3c919612 1556 end_sequence ();
67ab16d9 1557 return insns;
3c919612 1558}
1559
d08919a7 1560/* Emit __asan_allocas_unpoison (top, bot) call. The BASE parameter corresponds
1561 to BOT argument, for TOP virtual_stack_dynamic_rtx is used. NEW_SEQUENCE
1562 indicates whether we're emitting new instructions sequence or not. */
1563
1564rtx_insn *
1565asan_emit_allocas_unpoison (rtx top, rtx bot, rtx_insn *before)
1566{
1567 if (before)
1568 push_to_sequence (before);
1569 else
1570 start_sequence ();
1571 rtx ret = init_one_libfunc ("__asan_allocas_unpoison");
cd2ee6ee 1572 top = convert_memory_address (ptr_mode, top);
1573 bot = convert_memory_address (ptr_mode, bot);
9e9e5c15 1574 ret = emit_library_call_value (ret, NULL_RTX, LCT_NORMAL, ptr_mode,
1575 top, ptr_mode, bot, ptr_mode);
d08919a7 1576
1577 do_pending_stack_adjust ();
1578 rtx_insn *insns = get_insns ();
1579 end_sequence ();
1580 return insns;
1581}
1582
92fc5c48 1583/* Return true if DECL, a global var, might be overridden and needs
1584 therefore a local alias. */
1585
1586static bool
1587asan_needs_local_alias (tree decl)
1588{
1589 return DECL_WEAK (decl) || !targetm.binds_local_p (decl);
1590}
1591
47c3d0de 1592/* Return true if DECL, a global var, is an artificial ODR indicator symbol
1593 therefore doesn't need protection. */
1594
1595static bool
1596is_odr_indicator (tree decl)
1597{
1598 return (DECL_ARTIFICIAL (decl)
1599 && lookup_attribute ("asan odr indicator", DECL_ATTRIBUTES (decl)));
1600}
1601
92fc5c48 1602/* Return true if DECL is a VAR_DECL that should be protected
1603 by Address Sanitizer, by appending a red zone with protected
1604 shadow memory after it and aligning it to at least
1605 ASAN_RED_ZONE_SIZE bytes. */
1606
1607bool
1608asan_protect_global (tree decl)
1609{
bf2b7c22 1610 if (!ASAN_GLOBALS)
1611 return false;
1612
92fc5c48 1613 rtx rtl, symbol;
92fc5c48 1614
55b58027 1615 if (TREE_CODE (decl) == STRING_CST)
1616 {
1617 /* Instrument all STRING_CSTs except those created
1618 by asan_pp_string here. */
1619 if (shadow_ptr_types[0] != NULL_TREE
1620 && TREE_CODE (TREE_TYPE (decl)) == ARRAY_TYPE
1621 && TREE_TYPE (TREE_TYPE (decl)) == TREE_TYPE (shadow_ptr_types[0]))
1622 return false;
1623 return true;
1624 }
53e9c5c4 1625 if (!VAR_P (decl)
92fc5c48 1626 /* TLS vars aren't statically protectable. */
1627 || DECL_THREAD_LOCAL_P (decl)
1628 /* Externs will be protected elsewhere. */
1629 || DECL_EXTERNAL (decl)
92fc5c48 1630 || !DECL_RTL_SET_P (decl)
1631 /* Comdat vars pose an ABI problem, we can't know if
1632 the var that is selected by the linker will have
1633 padding or not. */
1634 || DECL_ONE_ONLY (decl)
aa1dfc5f 1635 /* Similarly for common vars. People can use -fno-common.
1636 Note: Linux kernel is built with -fno-common, so we do instrument
1637 globals there even if it is C. */
1ba1559d 1638 || (DECL_COMMON (decl) && TREE_PUBLIC (decl))
92fc5c48 1639 /* Don't protect if using user section, often vars placed
1640 into user section from multiple TUs are then assumed
1641 to be an array of such vars, putting padding in there
1642 breaks this assumption. */
738a6bda 1643 || (DECL_SECTION_NAME (decl) != NULL
4d3c996b 1644 && !symtab_node::get (decl)->implicit_section
1645 && !section_sanitized_p (DECL_SECTION_NAME (decl)))
92fc5c48 1646 || DECL_SIZE (decl) == 0
1647 || ASAN_RED_ZONE_SIZE * BITS_PER_UNIT > MAX_OFILE_ALIGNMENT
1648 || !valid_constant_size_p (DECL_SIZE_UNIT (decl))
11d00a0b 1649 || DECL_ALIGN_UNIT (decl) > 2 * ASAN_RED_ZONE_SIZE
47c3d0de 1650 || TREE_TYPE (decl) == ubsan_get_source_location_type ()
1651 || is_odr_indicator (decl))
92fc5c48 1652 return false;
1653
1654 rtl = DECL_RTL (decl);
1655 if (!MEM_P (rtl) || GET_CODE (XEXP (rtl, 0)) != SYMBOL_REF)
1656 return false;
1657 symbol = XEXP (rtl, 0);
1658
1659 if (CONSTANT_POOL_ADDRESS_P (symbol)
1660 || TREE_CONSTANT_POOL_ADDRESS_P (symbol))
1661 return false;
1662
92fc5c48 1663 if (lookup_attribute ("weakref", DECL_ATTRIBUTES (decl)))
1664 return false;
1665
07b8a412 1666 if (!TARGET_SUPPORTS_ALIASES && asan_needs_local_alias (decl))
92fc5c48 1667 return false;
92fc5c48 1668
eca932e6 1669 return true;
92fc5c48 1670}
1671
86d3a572 1672/* Construct a function tree for __asan_report_{load,store}{1,2,4,8,16,_n}.
1673 IS_STORE is either 1 (for a store) or 0 (for a load). */
b92cccf4 1674
1675static tree
f4d482a6 1676report_error_func (bool is_store, bool recover_p, HOST_WIDE_INT size_in_bytes,
1677 int *nargs)
b92cccf4 1678{
f4d482a6 1679 static enum built_in_function report[2][2][6]
1680 = { { { BUILT_IN_ASAN_REPORT_LOAD1, BUILT_IN_ASAN_REPORT_LOAD2,
1681 BUILT_IN_ASAN_REPORT_LOAD4, BUILT_IN_ASAN_REPORT_LOAD8,
1682 BUILT_IN_ASAN_REPORT_LOAD16, BUILT_IN_ASAN_REPORT_LOAD_N },
1683 { BUILT_IN_ASAN_REPORT_STORE1, BUILT_IN_ASAN_REPORT_STORE2,
1684 BUILT_IN_ASAN_REPORT_STORE4, BUILT_IN_ASAN_REPORT_STORE8,
1685 BUILT_IN_ASAN_REPORT_STORE16, BUILT_IN_ASAN_REPORT_STORE_N } },
1686 { { BUILT_IN_ASAN_REPORT_LOAD1_NOABORT,
1687 BUILT_IN_ASAN_REPORT_LOAD2_NOABORT,
1688 BUILT_IN_ASAN_REPORT_LOAD4_NOABORT,
1689 BUILT_IN_ASAN_REPORT_LOAD8_NOABORT,
1690 BUILT_IN_ASAN_REPORT_LOAD16_NOABORT,
1691 BUILT_IN_ASAN_REPORT_LOAD_N_NOABORT },
1692 { BUILT_IN_ASAN_REPORT_STORE1_NOABORT,
1693 BUILT_IN_ASAN_REPORT_STORE2_NOABORT,
1694 BUILT_IN_ASAN_REPORT_STORE4_NOABORT,
1695 BUILT_IN_ASAN_REPORT_STORE8_NOABORT,
1696 BUILT_IN_ASAN_REPORT_STORE16_NOABORT,
1697 BUILT_IN_ASAN_REPORT_STORE_N_NOABORT } } };
4f86f720 1698 if (size_in_bytes == -1)
1699 {
1700 *nargs = 2;
f4d482a6 1701 return builtin_decl_implicit (report[recover_p][is_store][5]);
4f86f720 1702 }
1703 *nargs = 1;
f4d482a6 1704 int size_log2 = exact_log2 (size_in_bytes);
1705 return builtin_decl_implicit (report[recover_p][is_store][size_log2]);
b92cccf4 1706}
1707
4f86f720 1708/* Construct a function tree for __asan_{load,store}{1,2,4,8,16,_n}.
1709 IS_STORE is either 1 (for a store) or 0 (for a load). */
1710
1711static tree
f4d482a6 1712check_func (bool is_store, bool recover_p, HOST_WIDE_INT size_in_bytes,
1713 int *nargs)
4f86f720 1714{
f4d482a6 1715 static enum built_in_function check[2][2][6]
1716 = { { { BUILT_IN_ASAN_LOAD1, BUILT_IN_ASAN_LOAD2,
1717 BUILT_IN_ASAN_LOAD4, BUILT_IN_ASAN_LOAD8,
1718 BUILT_IN_ASAN_LOAD16, BUILT_IN_ASAN_LOADN },
1719 { BUILT_IN_ASAN_STORE1, BUILT_IN_ASAN_STORE2,
1720 BUILT_IN_ASAN_STORE4, BUILT_IN_ASAN_STORE8,
1721 BUILT_IN_ASAN_STORE16, BUILT_IN_ASAN_STOREN } },
1722 { { BUILT_IN_ASAN_LOAD1_NOABORT,
1723 BUILT_IN_ASAN_LOAD2_NOABORT,
1724 BUILT_IN_ASAN_LOAD4_NOABORT,
1725 BUILT_IN_ASAN_LOAD8_NOABORT,
1726 BUILT_IN_ASAN_LOAD16_NOABORT,
1727 BUILT_IN_ASAN_LOADN_NOABORT },
1728 { BUILT_IN_ASAN_STORE1_NOABORT,
1729 BUILT_IN_ASAN_STORE2_NOABORT,
1730 BUILT_IN_ASAN_STORE4_NOABORT,
1731 BUILT_IN_ASAN_STORE8_NOABORT,
1732 BUILT_IN_ASAN_STORE16_NOABORT,
1733 BUILT_IN_ASAN_STOREN_NOABORT } } };
4f86f720 1734 if (size_in_bytes == -1)
1735 {
1736 *nargs = 2;
f4d482a6 1737 return builtin_decl_implicit (check[recover_p][is_store][5]);
4f86f720 1738 }
1739 *nargs = 1;
f4d482a6 1740 int size_log2 = exact_log2 (size_in_bytes);
1741 return builtin_decl_implicit (check[recover_p][is_store][size_log2]);
4f86f720 1742}
1743
aab92688 1744/* Split the current basic block and create a condition statement
1ac3509e 1745 insertion point right before or after the statement pointed to by
1746 ITER. Return an iterator to the point at which the caller might
1747 safely insert the condition statement.
aab92688 1748
1749 THEN_BLOCK must be set to the address of an uninitialized instance
1750 of basic_block. The function will then set *THEN_BLOCK to the
1751 'then block' of the condition statement to be inserted by the
1752 caller.
1753
e8d4d8a9 1754 If CREATE_THEN_FALLTHRU_EDGE is false, no edge will be created from
1755 *THEN_BLOCK to *FALLTHROUGH_BLOCK.
1756
aab92688 1757 Similarly, the function will set *FALLTRHOUGH_BLOCK to the 'else
1758 block' of the condition statement to be inserted by the caller.
1759
1760 Note that *FALLTHROUGH_BLOCK is a new block that contains the
1761 statements starting from *ITER, and *THEN_BLOCK is a new empty
1762 block.
1763
1ac3509e 1764 *ITER is adjusted to point to always point to the first statement
1765 of the basic block * FALLTHROUGH_BLOCK. That statement is the
1766 same as what ITER was pointing to prior to calling this function,
1767 if BEFORE_P is true; otherwise, it is its following statement. */
aab92688 1768
ec08f7b0 1769gimple_stmt_iterator
1ac3509e 1770create_cond_insert_point (gimple_stmt_iterator *iter,
1771 bool before_p,
1772 bool then_more_likely_p,
e8d4d8a9 1773 bool create_then_fallthru_edge,
1ac3509e 1774 basic_block *then_block,
1775 basic_block *fallthrough_block)
aab92688 1776{
1777 gimple_stmt_iterator gsi = *iter;
1778
1ac3509e 1779 if (!gsi_end_p (gsi) && before_p)
aab92688 1780 gsi_prev (&gsi);
1781
1782 basic_block cur_bb = gsi_bb (*iter);
1783
1784 edge e = split_block (cur_bb, gsi_stmt (gsi));
1785
1786 /* Get a hold on the 'condition block', the 'then block' and the
1787 'else block'. */
1788 basic_block cond_bb = e->src;
1789 basic_block fallthru_bb = e->dest;
1790 basic_block then_bb = create_empty_bb (cond_bb);
f6568ea4 1791 if (current_loops)
1792 {
1793 add_bb_to_loop (then_bb, cond_bb->loop_father);
1794 loops_state_set (LOOPS_NEED_FIXUP);
1795 }
aab92688 1796
1797 /* Set up the newly created 'then block'. */
1798 e = make_edge (cond_bb, then_bb, EDGE_TRUE_VALUE);
7dc9e270 1799 profile_probability fallthrough_probability
aab92688 1800 = then_more_likely_p
7dc9e270 1801 ? profile_probability::very_unlikely ()
1802 : profile_probability::very_likely ();
1803 e->probability = fallthrough_probability.invert ();
e8d4d8a9 1804 if (create_then_fallthru_edge)
1805 make_single_succ_edge (then_bb, fallthru_bb, EDGE_FALLTHRU);
aab92688 1806
1807 /* Set up the fallthrough basic block. */
1808 e = find_edge (cond_bb, fallthru_bb);
1809 e->flags = EDGE_FALSE_VALUE;
1810 e->count = cond_bb->count;
7dc9e270 1811 e->probability = fallthrough_probability;
aab92688 1812
1813 /* Update dominance info for the newly created then_bb; note that
1814 fallthru_bb's dominance info has already been updated by
1815 split_bock. */
1816 if (dom_info_available_p (CDI_DOMINATORS))
1817 set_immediate_dominator (CDI_DOMINATORS, then_bb, cond_bb);
1818
1819 *then_block = then_bb;
1820 *fallthrough_block = fallthru_bb;
1821 *iter = gsi_start_bb (fallthru_bb);
1822
1823 return gsi_last_bb (cond_bb);
1824}
1825
1ac3509e 1826/* Insert an if condition followed by a 'then block' right before the
1827 statement pointed to by ITER. The fallthrough block -- which is the
1828 else block of the condition as well as the destination of the
1829 outcoming edge of the 'then block' -- starts with the statement
1830 pointed to by ITER.
1831
eca932e6 1832 COND is the condition of the if.
1ac3509e 1833
1834 If THEN_MORE_LIKELY_P is true, the probability of the edge to the
1835 'then block' is higher than the probability of the edge to the
1836 fallthrough block.
1837
1838 Upon completion of the function, *THEN_BB is set to the newly
1839 inserted 'then block' and similarly, *FALLTHROUGH_BB is set to the
1840 fallthrough block.
1841
1842 *ITER is adjusted to still point to the same statement it was
1843 pointing to initially. */
1844
1845static void
1a91d914 1846insert_if_then_before_iter (gcond *cond,
1ac3509e 1847 gimple_stmt_iterator *iter,
1848 bool then_more_likely_p,
1849 basic_block *then_bb,
1850 basic_block *fallthrough_bb)
1851{
1852 gimple_stmt_iterator cond_insert_point =
1853 create_cond_insert_point (iter,
1854 /*before_p=*/true,
1855 then_more_likely_p,
e8d4d8a9 1856 /*create_then_fallthru_edge=*/true,
1ac3509e 1857 then_bb,
1858 fallthrough_bb);
1859 gsi_insert_after (&cond_insert_point, cond, GSI_NEW_STMT);
1860}
1861
629b6abc 1862/* Build (base_addr >> ASAN_SHADOW_SHIFT) + asan_shadow_offset ().
1863 If RETURN_ADDRESS is set to true, return memory location instread
1864 of a value in the shadow memory. */
86d3a572 1865
1866static tree
1867build_shadow_mem_access (gimple_stmt_iterator *gsi, location_t location,
629b6abc 1868 tree base_addr, tree shadow_ptr_type,
1869 bool return_address = false)
86d3a572 1870{
1871 tree t, uintptr_type = TREE_TYPE (base_addr);
1872 tree shadow_type = TREE_TYPE (shadow_ptr_type);
42acab1c 1873 gimple *g;
86d3a572 1874
1875 t = build_int_cst (uintptr_type, ASAN_SHADOW_SHIFT);
e9cf809e 1876 g = gimple_build_assign (make_ssa_name (uintptr_type), RSHIFT_EXPR,
1877 base_addr, t);
86d3a572 1878 gimple_set_location (g, location);
1879 gsi_insert_after (gsi, g, GSI_NEW_STMT);
1880
cf357977 1881 t = build_int_cst (uintptr_type, asan_shadow_offset ());
e9cf809e 1882 g = gimple_build_assign (make_ssa_name (uintptr_type), PLUS_EXPR,
1883 gimple_assign_lhs (g), t);
86d3a572 1884 gimple_set_location (g, location);
1885 gsi_insert_after (gsi, g, GSI_NEW_STMT);
1886
e9cf809e 1887 g = gimple_build_assign (make_ssa_name (shadow_ptr_type), NOP_EXPR,
1888 gimple_assign_lhs (g));
86d3a572 1889 gimple_set_location (g, location);
1890 gsi_insert_after (gsi, g, GSI_NEW_STMT);
1891
629b6abc 1892 if (!return_address)
1893 {
1894 t = build2 (MEM_REF, shadow_type, gimple_assign_lhs (g),
1895 build_int_cst (shadow_ptr_type, 0));
1896 g = gimple_build_assign (make_ssa_name (shadow_type), MEM_REF, t);
1897 gimple_set_location (g, location);
1898 gsi_insert_after (gsi, g, GSI_NEW_STMT);
1899 }
1900
86d3a572 1901 return gimple_assign_lhs (g);
1902}
1903
4f86f720 1904/* BASE can already be an SSA_NAME; in that case, do not create a
1905 new SSA_NAME for it. */
1906
1907static tree
1908maybe_create_ssa_name (location_t loc, tree base, gimple_stmt_iterator *iter,
1909 bool before_p)
1910{
1911 if (TREE_CODE (base) == SSA_NAME)
1912 return base;
42acab1c 1913 gimple *g = gimple_build_assign (make_ssa_name (TREE_TYPE (base)),
e9cf809e 1914 TREE_CODE (base), base);
4f86f720 1915 gimple_set_location (g, loc);
1916 if (before_p)
1917 gsi_insert_before (iter, g, GSI_SAME_STMT);
1918 else
1919 gsi_insert_after (iter, g, GSI_NEW_STMT);
1920 return gimple_assign_lhs (g);
1921}
1922
0a9f72cf 1923/* LEN can already have necessary size and precision;
1924 in that case, do not create a new variable. */
1925
1926tree
1927maybe_cast_to_ptrmode (location_t loc, tree len, gimple_stmt_iterator *iter,
1928 bool before_p)
1929{
1930 if (ptrofftype_p (len))
1931 return len;
42acab1c 1932 gimple *g = gimple_build_assign (make_ssa_name (pointer_sized_int_node),
e9cf809e 1933 NOP_EXPR, len);
0a9f72cf 1934 gimple_set_location (g, loc);
1935 if (before_p)
1936 gsi_insert_before (iter, g, GSI_SAME_STMT);
1937 else
1938 gsi_insert_after (iter, g, GSI_NEW_STMT);
1939 return gimple_assign_lhs (g);
1940}
1941
c91b0fff 1942/* Instrument the memory access instruction BASE. Insert new
1ac3509e 1943 statements before or after ITER.
c91b0fff 1944
1945 Note that the memory access represented by BASE can be either an
1946 SSA_NAME, or a non-SSA expression. LOCATION is the source code
1947 location. IS_STORE is TRUE for a store, FALSE for a load.
1ac3509e 1948 BEFORE_P is TRUE for inserting the instrumentation code before
4f86f720 1949 ITER, FALSE for inserting it after ITER. IS_SCALAR_ACCESS is TRUE
1950 for a scalar memory access and FALSE for memory region access.
1951 NON_ZERO_P is TRUE if memory region is guaranteed to have non-zero
1952 length. ALIGN tells alignment of accessed memory object.
1953
1954 START_INSTRUMENTED and END_INSTRUMENTED are TRUE if start/end of
1955 memory region have already been instrumented.
1ac3509e 1956
1957 If BEFORE_P is TRUE, *ITER is arranged to still point to the
1958 statement it was pointing to prior to calling this function,
1959 otherwise, it points to the statement logically following it. */
b92cccf4 1960
1961static void
ff326078 1962build_check_stmt (location_t loc, tree base, tree len,
4f86f720 1963 HOST_WIDE_INT size_in_bytes, gimple_stmt_iterator *iter,
ff326078 1964 bool is_non_zero_len, bool before_p, bool is_store,
f9acf11a 1965 bool is_scalar_access, unsigned int align = 0)
b92cccf4 1966{
4f86f720 1967 gimple_stmt_iterator gsi = *iter;
42acab1c 1968 gimple *g;
4f86f720 1969
ff326078 1970 gcc_assert (!(size_in_bytes > 0 && !is_non_zero_len));
4f86f720 1971
ff326078 1972 gsi = *iter;
1973
1974 base = unshare_expr (base);
1975 base = maybe_create_ssa_name (loc, base, &gsi, before_p);
1976
4f86f720 1977 if (len)
0a9f72cf 1978 {
1979 len = unshare_expr (len);
1980 len = maybe_cast_to_ptrmode (loc, len, iter, before_p);
1981 }
4f86f720 1982 else
1983 {
1984 gcc_assert (size_in_bytes != -1);
1985 len = build_int_cst (pointer_sized_int_node, size_in_bytes);
1986 }
1987
1988 if (size_in_bytes > 1)
93e990a3 1989 {
4f86f720 1990 if ((size_in_bytes & (size_in_bytes - 1)) != 0
1991 || size_in_bytes > 16)
ff326078 1992 is_scalar_access = false;
4f86f720 1993 else if (align && align < size_in_bytes * BITS_PER_UNIT)
1994 {
1995 /* On non-strict alignment targets, if
1996 16-byte access is just 8-byte aligned,
1997 this will result in misaligned shadow
1998 memory 2 byte load, but otherwise can
1999 be handled using one read. */
2000 if (size_in_bytes != 16
2001 || STRICT_ALIGNMENT
2002 || align < 8 * BITS_PER_UNIT)
ff326078 2003 is_scalar_access = false;
86d3a572 2004 }
5d5c682b 2005 }
b92cccf4 2006
ff326078 2007 HOST_WIDE_INT flags = 0;
2008 if (is_store)
2009 flags |= ASAN_CHECK_STORE;
2010 if (is_non_zero_len)
2011 flags |= ASAN_CHECK_NON_ZERO_LEN;
2012 if (is_scalar_access)
2013 flags |= ASAN_CHECK_SCALAR_ACCESS;
ff326078 2014
da81fb00 2015 g = gimple_build_call_internal (IFN_ASAN_CHECK, 4,
ff326078 2016 build_int_cst (integer_type_node, flags),
da81fb00 2017 base, len,
2018 build_int_cst (integer_type_node,
2019 align / BITS_PER_UNIT));
ff326078 2020 gimple_set_location (g, loc);
2021 if (before_p)
2022 gsi_insert_before (&gsi, g, GSI_SAME_STMT);
4f86f720 2023 else
2024 {
4f86f720 2025 gsi_insert_after (&gsi, g, GSI_NEW_STMT);
ff326078 2026 gsi_next (&gsi);
2027 *iter = gsi;
4f86f720 2028 }
b92cccf4 2029}
2030
2031/* If T represents a memory access, add instrumentation code before ITER.
2032 LOCATION is source code location.
1ac3509e 2033 IS_STORE is either TRUE (for a store) or FALSE (for a load). */
b92cccf4 2034
2035static void
2036instrument_derefs (gimple_stmt_iterator *iter, tree t,
c31c80df 2037 location_t location, bool is_store)
b92cccf4 2038{
bf2b7c22 2039 if (is_store && !ASAN_INSTRUMENT_WRITES)
2040 return;
2041 if (!is_store && !ASAN_INSTRUMENT_READS)
2042 return;
2043
b92cccf4 2044 tree type, base;
5d5c682b 2045 HOST_WIDE_INT size_in_bytes;
fcfbb129 2046 if (location == UNKNOWN_LOCATION)
2047 location = EXPR_LOCATION (t);
b92cccf4 2048
2049 type = TREE_TYPE (t);
b92cccf4 2050 switch (TREE_CODE (t))
2051 {
2052 case ARRAY_REF:
2053 case COMPONENT_REF:
2054 case INDIRECT_REF:
2055 case MEM_REF:
085f6ebf 2056 case VAR_DECL:
433da5c4 2057 case BIT_FIELD_REF:
b92cccf4 2058 break;
085f6ebf 2059 /* FALLTHRU */
b92cccf4 2060 default:
2061 return;
2062 }
5d5c682b 2063
2064 size_in_bytes = int_size_in_bytes (type);
86d3a572 2065 if (size_in_bytes <= 0)
5d5c682b 2066 return;
2067
5d5c682b 2068 HOST_WIDE_INT bitsize, bitpos;
2069 tree offset;
3754d046 2070 machine_mode mode;
292237f3 2071 int unsignedp, reversep, volatilep = 0;
2072 tree inner = get_inner_reference (t, &bitsize, &bitpos, &offset, &mode,
b3b6e4b5 2073 &unsignedp, &reversep, &volatilep);
828ab337 2074
2075 if (TREE_CODE (t) == COMPONENT_REF
2076 && DECL_BIT_FIELD_REPRESENTATIVE (TREE_OPERAND (t, 1)) != NULL_TREE)
9ffeb5ce 2077 {
828ab337 2078 tree repr = DECL_BIT_FIELD_REPRESENTATIVE (TREE_OPERAND (t, 1));
2079 instrument_derefs (iter, build3 (COMPONENT_REF, TREE_TYPE (repr),
2080 TREE_OPERAND (t, 0), repr,
f4685159 2081 TREE_OPERAND (t, 2)),
2082 location, is_store);
9ffeb5ce 2083 return;
2084 }
828ab337 2085
2086 if (bitpos % BITS_PER_UNIT
2087 || bitsize != size_in_bytes * BITS_PER_UNIT)
86d3a572 2088 return;
5d5c682b 2089
fa9cb955 2090 if (VAR_P (inner) && DECL_HARD_REGISTER (inner))
2091 return;
2092
53e9c5c4 2093 if (VAR_P (inner)
085f6ebf 2094 && offset == NULL_TREE
2095 && bitpos >= 0
2096 && DECL_SIZE (inner)
2097 && tree_fits_shwi_p (DECL_SIZE (inner))
2098 && bitpos + bitsize <= tree_to_shwi (DECL_SIZE (inner)))
2099 {
2100 if (DECL_THREAD_LOCAL_P (inner))
2101 return;
a99c832c 2102 if (!ASAN_GLOBALS && is_global_var (inner))
2103 return;
085f6ebf 2104 if (!TREE_STATIC (inner))
2105 {
2106 /* Automatic vars in the current function will be always
2107 accessible. */
629b6abc 2108 if (decl_function_context (inner) == current_function_decl
2109 && (!asan_sanitize_use_after_scope ()
2110 || !TREE_ADDRESSABLE (inner)))
085f6ebf 2111 return;
2112 }
2113 /* Always instrument external vars, they might be dynamically
2114 initialized. */
2115 else if (!DECL_EXTERNAL (inner))
2116 {
2117 /* For static vars if they are known not to be dynamically
2118 initialized, they will be always accessible. */
97221fd7 2119 varpool_node *vnode = varpool_node::get (inner);
085f6ebf 2120 if (vnode && !vnode->dynamically_initialized)
2121 return;
2122 }
2123 }
2124
5d5c682b 2125 base = build_fold_addr_expr (t);
c31c80df 2126 if (!has_mem_ref_been_instrumented (base, size_in_bytes))
2127 {
4f86f720 2128 unsigned int align = get_object_alignment (t);
2129 build_check_stmt (location, base, NULL_TREE, size_in_bytes, iter,
ff326078 2130 /*is_non_zero_len*/size_in_bytes > 0, /*before_p=*/true,
4f86f720 2131 is_store, /*is_scalar_access*/true, align);
c31c80df 2132 update_mem_ref_hash_table (base, size_in_bytes);
2133 update_mem_ref_hash_table (t, size_in_bytes);
2134 }
2135
1ac3509e 2136}
2137
f9acf11a 2138/* Insert a memory reference into the hash table if access length
2139 can be determined in compile time. */
2140
2141static void
2142maybe_update_mem_ref_hash_table (tree base, tree len)
2143{
2144 if (!POINTER_TYPE_P (TREE_TYPE (base))
2145 || !INTEGRAL_TYPE_P (TREE_TYPE (len)))
2146 return;
2147
2148 HOST_WIDE_INT size_in_bytes = tree_fits_shwi_p (len) ? tree_to_shwi (len) : -1;
2149
2150 if (size_in_bytes != -1)
2151 update_mem_ref_hash_table (base, size_in_bytes);
2152}
2153
1ac3509e 2154/* Instrument an access to a contiguous memory region that starts at
2155 the address pointed to by BASE, over a length of LEN (expressed in
2156 the sizeof (*BASE) bytes). ITER points to the instruction before
2157 which the instrumentation instructions must be inserted. LOCATION
2158 is the source location that the instrumentation instructions must
2159 have. If IS_STORE is true, then the memory access is a store;
2160 otherwise, it's a load. */
2161
2162static void
2163instrument_mem_region_access (tree base, tree len,
2164 gimple_stmt_iterator *iter,
2165 location_t location, bool is_store)
2166{
94dbcbb6 2167 if (!POINTER_TYPE_P (TREE_TYPE (base))
2168 || !INTEGRAL_TYPE_P (TREE_TYPE (len))
2169 || integer_zerop (len))
1ac3509e 2170 return;
2171
4f86f720 2172 HOST_WIDE_INT size_in_bytes = tree_fits_shwi_p (len) ? tree_to_shwi (len) : -1;
c31c80df 2173
f9acf11a 2174 if ((size_in_bytes == -1)
2175 || !has_mem_ref_been_instrumented (base, size_in_bytes))
2176 {
2177 build_check_stmt (location, base, len, size_in_bytes, iter,
2178 /*is_non_zero_len*/size_in_bytes > 0, /*before_p*/true,
2179 is_store, /*is_scalar_access*/false, /*align*/0);
2180 }
d9dc05a1 2181
f9acf11a 2182 maybe_update_mem_ref_hash_table (base, len);
d9dc05a1 2183 *iter = gsi_for_stmt (gsi_stmt (*iter));
c31c80df 2184}
1ac3509e 2185
c31c80df 2186/* Instrument the call to a built-in memory access function that is
2187 pointed to by the iterator ITER.
1ac3509e 2188
c31c80df 2189 Upon completion, return TRUE iff *ITER has been advanced to the
2190 statement following the one it was originally pointing to. */
1ac3509e 2191
c31c80df 2192static bool
2193instrument_builtin_call (gimple_stmt_iterator *iter)
2194{
bf2b7c22 2195 if (!ASAN_MEMINTRIN)
2196 return false;
2197
c31c80df 2198 bool iter_advanced_p = false;
1a91d914 2199 gcall *call = as_a <gcall *> (gsi_stmt (*iter));
1ac3509e 2200
c31c80df 2201 gcc_checking_assert (gimple_call_builtin_p (call, BUILT_IN_NORMAL));
1ac3509e 2202
c31c80df 2203 location_t loc = gimple_location (call);
1ac3509e 2204
f9acf11a 2205 asan_mem_ref src0, src1, dest;
2206 asan_mem_ref_init (&src0, NULL, 1);
2207 asan_mem_ref_init (&src1, NULL, 1);
2208 asan_mem_ref_init (&dest, NULL, 1);
c31c80df 2209
f9acf11a 2210 tree src0_len = NULL_TREE, src1_len = NULL_TREE, dest_len = NULL_TREE;
2211 bool src0_is_store = false, src1_is_store = false, dest_is_store = false,
2212 dest_is_deref = false, intercepted_p = true;
c31c80df 2213
f9acf11a 2214 if (get_mem_refs_of_builtin_call (call,
2215 &src0, &src0_len, &src0_is_store,
2216 &src1, &src1_len, &src1_is_store,
2217 &dest, &dest_len, &dest_is_store,
d08919a7 2218 &dest_is_deref, &intercepted_p, iter))
f9acf11a 2219 {
2220 if (dest_is_deref)
c31c80df 2221 {
f9acf11a 2222 instrument_derefs (iter, dest.start, loc, dest_is_store);
2223 gsi_next (iter);
2224 iter_advanced_p = true;
2225 }
2226 else if (!intercepted_p
2227 && (src0_len || src1_len || dest_len))
2228 {
2229 if (src0.start != NULL_TREE)
2230 instrument_mem_region_access (src0.start, src0_len,
2231 iter, loc, /*is_store=*/false);
2232 if (src1.start != NULL_TREE)
2233 instrument_mem_region_access (src1.start, src1_len,
2234 iter, loc, /*is_store=*/false);
2235 if (dest.start != NULL_TREE)
2236 instrument_mem_region_access (dest.start, dest_len,
2237 iter, loc, /*is_store=*/true);
2238
2239 *iter = gsi_for_stmt (call);
2240 gsi_next (iter);
2241 iter_advanced_p = true;
2242 }
2243 else
2244 {
2245 if (src0.start != NULL_TREE)
2246 maybe_update_mem_ref_hash_table (src0.start, src0_len);
2247 if (src1.start != NULL_TREE)
2248 maybe_update_mem_ref_hash_table (src1.start, src1_len);
2249 if (dest.start != NULL_TREE)
2250 maybe_update_mem_ref_hash_table (dest.start, dest_len);
c31c80df 2251 }
1ac3509e 2252 }
c31c80df 2253 return iter_advanced_p;
1ac3509e 2254}
2255
2256/* Instrument the assignment statement ITER if it is subject to
c31c80df 2257 instrumentation. Return TRUE iff instrumentation actually
2258 happened. In that case, the iterator ITER is advanced to the next
2259 logical expression following the one initially pointed to by ITER,
2260 and the relevant memory reference that which access has been
2261 instrumented is added to the memory references hash table. */
1ac3509e 2262
c31c80df 2263static bool
2264maybe_instrument_assignment (gimple_stmt_iterator *iter)
1ac3509e 2265{
42acab1c 2266 gimple *s = gsi_stmt (*iter);
1ac3509e 2267
2268 gcc_assert (gimple_assign_single_p (s));
2269
c31c80df 2270 tree ref_expr = NULL_TREE;
2271 bool is_store, is_instrumented = false;
2272
38e9269e 2273 if (gimple_store_p (s))
c31c80df 2274 {
2275 ref_expr = gimple_assign_lhs (s);
2276 is_store = true;
2277 instrument_derefs (iter, ref_expr,
2278 gimple_location (s),
2279 is_store);
2280 is_instrumented = true;
2281 }
e815c2c5 2282
38e9269e 2283 if (gimple_assign_load_p (s))
c31c80df 2284 {
2285 ref_expr = gimple_assign_rhs1 (s);
2286 is_store = false;
2287 instrument_derefs (iter, ref_expr,
2288 gimple_location (s),
2289 is_store);
2290 is_instrumented = true;
2291 }
2292
2293 if (is_instrumented)
2294 gsi_next (iter);
2295
2296 return is_instrumented;
1ac3509e 2297}
2298
2299/* Instrument the function call pointed to by the iterator ITER, if it
2300 is subject to instrumentation. At the moment, the only function
2301 calls that are instrumented are some built-in functions that access
2302 memory. Look at instrument_builtin_call to learn more.
2303
2304 Upon completion return TRUE iff *ITER was advanced to the statement
2305 following the one it was originally pointing to. */
2306
2307static bool
2308maybe_instrument_call (gimple_stmt_iterator *iter)
2309{
42acab1c 2310 gimple *stmt = gsi_stmt (*iter);
c31c80df 2311 bool is_builtin = gimple_call_builtin_p (stmt, BUILT_IN_NORMAL);
2312
2313 if (is_builtin && instrument_builtin_call (iter))
494f4883 2314 return true;
c31c80df 2315
494f4883 2316 if (gimple_call_noreturn_p (stmt))
2317 {
2318 if (is_builtin)
2319 {
2320 tree callee = gimple_call_fndecl (stmt);
2321 switch (DECL_FUNCTION_CODE (callee))
2322 {
2323 case BUILT_IN_UNREACHABLE:
2324 case BUILT_IN_TRAP:
2325 /* Don't instrument these. */
2326 return false;
5213d6c9 2327 default:
2328 break;
494f4883 2329 }
2330 }
2331 tree decl = builtin_decl_implicit (BUILT_IN_ASAN_HANDLE_NO_RETURN);
42acab1c 2332 gimple *g = gimple_build_call (decl, 0);
494f4883 2333 gimple_set_location (g, gimple_location (stmt));
2334 gsi_insert_before (iter, g, GSI_SAME_STMT);
2335 }
774068a0 2336
fcfbb129 2337 bool instrumented = false;
774068a0 2338 if (gimple_store_p (stmt))
2339 {
2340 tree ref_expr = gimple_call_lhs (stmt);
2341 instrument_derefs (iter, ref_expr,
2342 gimple_location (stmt),
2343 /*is_store=*/true);
2344
fcfbb129 2345 instrumented = true;
774068a0 2346 }
2347
fcfbb129 2348 /* Walk through gimple_call arguments and check them id needed. */
2349 unsigned args_num = gimple_call_num_args (stmt);
2350 for (unsigned i = 0; i < args_num; ++i)
2351 {
2352 tree arg = gimple_call_arg (stmt, i);
2353 /* If ARG is not a non-aggregate register variable, compiler in general
2354 creates temporary for it and pass it as argument to gimple call.
2355 But in some cases, e.g. when we pass by value a small structure that
2356 fits to register, compiler can avoid extra overhead by pulling out
2357 these temporaries. In this case, we should check the argument. */
2358 if (!is_gimple_reg (arg) && !is_gimple_min_invariant (arg))
2359 {
2360 instrument_derefs (iter, arg,
2361 gimple_location (stmt),
2362 /*is_store=*/false);
2363 instrumented = true;
2364 }
2365 }
2366 if (instrumented)
2367 gsi_next (iter);
2368 return instrumented;
b92cccf4 2369}
2370
c31c80df 2371/* Walk each instruction of all basic block and instrument those that
2372 represent memory references: loads, stores, or function calls.
2373 In a given basic block, this function avoids instrumenting memory
2374 references that have already been instrumented. */
b92cccf4 2375
2376static void
2377transform_statements (void)
2378{
e8d4d8a9 2379 basic_block bb, last_bb = NULL;
b92cccf4 2380 gimple_stmt_iterator i;
fe672ac0 2381 int saved_last_basic_block = last_basic_block_for_fn (cfun);
b92cccf4 2382
fc00614f 2383 FOR_EACH_BB_FN (bb, cfun)
b92cccf4 2384 {
e8d4d8a9 2385 basic_block prev_bb = bb;
c31c80df 2386
b92cccf4 2387 if (bb->index >= saved_last_basic_block) continue;
e8d4d8a9 2388
2389 /* Flush the mem ref hash table, if current bb doesn't have
2390 exactly one predecessor, or if that predecessor (skipping
2391 over asan created basic blocks) isn't the last processed
2392 basic block. Thus we effectively flush on extended basic
2393 block boundaries. */
2394 while (single_pred_p (prev_bb))
2395 {
2396 prev_bb = single_pred (prev_bb);
2397 if (prev_bb->index < saved_last_basic_block)
2398 break;
2399 }
2400 if (prev_bb != last_bb)
2401 empty_mem_ref_hash_table ();
2402 last_bb = bb;
2403
1ac3509e 2404 for (i = gsi_start_bb (bb); !gsi_end_p (i);)
eca932e6 2405 {
42acab1c 2406 gimple *s = gsi_stmt (i);
1ac3509e 2407
c31c80df 2408 if (has_stmt_been_instrumented_p (s))
2409 gsi_next (&i);
2410 else if (gimple_assign_single_p (s)
e99409a5 2411 && !gimple_clobber_p (s)
c31c80df 2412 && maybe_instrument_assignment (&i))
2413 /* Nothing to do as maybe_instrument_assignment advanced
2414 the iterator I. */;
2415 else if (is_gimple_call (s) && maybe_instrument_call (&i))
2416 /* Nothing to do as maybe_instrument_call
2417 advanced the iterator I. */;
2418 else
1ac3509e 2419 {
c31c80df 2420 /* No instrumentation happened.
2421
e8d4d8a9 2422 If the current instruction is a function call that
2423 might free something, let's forget about the memory
2424 references that got instrumented. Otherwise we might
629b6abc 2425 miss some instrumentation opportunities. Do the same
2426 for a ASAN_MARK poisoning internal function. */
2427 if (is_gimple_call (s)
a30589d5 2428 && (!nonfreeing_call_p (s)
2429 || asan_mark_p (s, ASAN_MARK_POISON)))
c31c80df 2430 empty_mem_ref_hash_table ();
2431
2432 gsi_next (&i);
1ac3509e 2433 }
eca932e6 2434 }
b92cccf4 2435 }
c31c80df 2436 free_mem_ref_resources ();
b92cccf4 2437}
2438
085f6ebf 2439/* Build
2440 __asan_before_dynamic_init (module_name)
2441 or
2442 __asan_after_dynamic_init ()
2443 call. */
2444
2445tree
2446asan_dynamic_init_call (bool after_p)
2447{
bcab7035 2448 if (shadow_ptr_types[0] == NULL_TREE)
2449 asan_init_shadow_ptr_types ();
2450
085f6ebf 2451 tree fn = builtin_decl_implicit (after_p
2452 ? BUILT_IN_ASAN_AFTER_DYNAMIC_INIT
2453 : BUILT_IN_ASAN_BEFORE_DYNAMIC_INIT);
2454 tree module_name_cst = NULL_TREE;
2455 if (!after_p)
2456 {
2457 pretty_printer module_name_pp;
2458 pp_string (&module_name_pp, main_input_filename);
2459
085f6ebf 2460 module_name_cst = asan_pp_string (&module_name_pp);
2461 module_name_cst = fold_convert (const_ptr_type_node,
2462 module_name_cst);
2463 }
2464
2465 return build_call_expr (fn, after_p ? 0 : 1, module_name_cst);
2466}
2467
92fc5c48 2468/* Build
2469 struct __asan_global
2470 {
2471 const void *__beg;
2472 uptr __size;
2473 uptr __size_with_redzone;
2474 const void *__name;
1e80ce41 2475 const void *__module_name;
92fc5c48 2476 uptr __has_dynamic_init;
a9586c9c 2477 __asan_global_source_location *__location;
1350ad47 2478 char *__odr_indicator;
92fc5c48 2479 } type. */
2480
2481static tree
2482asan_global_struct (void)
2483{
47c3d0de 2484 static const char *field_names[]
92fc5c48 2485 = { "__beg", "__size", "__size_with_redzone",
47c3d0de 2486 "__name", "__module_name", "__has_dynamic_init", "__location",
2487 "__odr_indicator" };
2488 tree fields[ARRAY_SIZE (field_names)], ret;
2489 unsigned i;
92fc5c48 2490
2491 ret = make_node (RECORD_TYPE);
47c3d0de 2492 for (i = 0; i < ARRAY_SIZE (field_names); i++)
92fc5c48 2493 {
2494 fields[i]
2495 = build_decl (UNKNOWN_LOCATION, FIELD_DECL,
2496 get_identifier (field_names[i]),
2497 (i == 0 || i == 3) ? const_ptr_type_node
9e46467d 2498 : pointer_sized_int_node);
92fc5c48 2499 DECL_CONTEXT (fields[i]) = ret;
2500 if (i)
2501 DECL_CHAIN (fields[i - 1]) = fields[i];
2502 }
530273ed 2503 tree type_decl = build_decl (input_location, TYPE_DECL,
2504 get_identifier ("__asan_global"), ret);
2505 DECL_IGNORED_P (type_decl) = 1;
2506 DECL_ARTIFICIAL (type_decl) = 1;
92fc5c48 2507 TYPE_FIELDS (ret) = fields[0];
530273ed 2508 TYPE_NAME (ret) = type_decl;
2509 TYPE_STUB_DECL (ret) = type_decl;
92fc5c48 2510 layout_type (ret);
2511 return ret;
2512}
2513
47c3d0de 2514/* Create and return odr indicator symbol for DECL.
2515 TYPE is __asan_global struct type as returned by asan_global_struct. */
2516
2517static tree
2518create_odr_indicator (tree decl, tree type)
2519{
2520 char *name;
2521 tree uptr = TREE_TYPE (DECL_CHAIN (TYPE_FIELDS (type)));
2522 tree decl_name
2523 = (HAS_DECL_ASSEMBLER_NAME_P (decl) ? DECL_ASSEMBLER_NAME (decl)
2524 : DECL_NAME (decl));
2525 /* DECL_NAME theoretically might be NULL. Bail out with 0 in this case. */
2526 if (decl_name == NULL_TREE)
2527 return build_int_cst (uptr, 0);
377dc1bd 2528 const char *dname = IDENTIFIER_POINTER (decl_name);
2529 if (HAS_DECL_ASSEMBLER_NAME_P (decl))
2530 dname = targetm.strip_name_encoding (dname);
2531 size_t len = strlen (dname) + sizeof ("__odr_asan_");
47c3d0de 2532 name = XALLOCAVEC (char, len);
377dc1bd 2533 snprintf (name, len, "__odr_asan_%s", dname);
47c3d0de 2534#ifndef NO_DOT_IN_LABEL
2535 name[sizeof ("__odr_asan") - 1] = '.';
2536#elif !defined(NO_DOLLAR_IN_LABEL)
2537 name[sizeof ("__odr_asan") - 1] = '$';
2538#endif
2539 tree var = build_decl (UNKNOWN_LOCATION, VAR_DECL, get_identifier (name),
2540 char_type_node);
2541 TREE_ADDRESSABLE (var) = 1;
2542 TREE_READONLY (var) = 0;
2543 TREE_THIS_VOLATILE (var) = 1;
2544 DECL_GIMPLE_REG_P (var) = 0;
2545 DECL_ARTIFICIAL (var) = 1;
2546 DECL_IGNORED_P (var) = 1;
2547 TREE_STATIC (var) = 1;
2548 TREE_PUBLIC (var) = 1;
2549 DECL_VISIBILITY (var) = DECL_VISIBILITY (decl);
2550 DECL_VISIBILITY_SPECIFIED (var) = DECL_VISIBILITY_SPECIFIED (decl);
2551
2552 TREE_USED (var) = 1;
2553 tree ctor = build_constructor_va (TREE_TYPE (var), 1, NULL_TREE,
2554 build_int_cst (unsigned_type_node, 0));
2555 TREE_CONSTANT (ctor) = 1;
2556 TREE_STATIC (ctor) = 1;
2557 DECL_INITIAL (var) = ctor;
2558 DECL_ATTRIBUTES (var) = tree_cons (get_identifier ("asan odr indicator"),
2559 NULL, DECL_ATTRIBUTES (var));
2560 make_decl_rtl (var);
2561 varpool_node::finalize_decl (var);
2562 return fold_convert (uptr, build_fold_addr_expr (var));
2563}
2564
2565/* Return true if DECL, a global var, might be overridden and needs
2566 an additional odr indicator symbol. */
2567
2568static bool
2569asan_needs_odr_indicator_p (tree decl)
2570{
76af476d 2571 /* Don't emit ODR indicators for kernel because:
2572 a) Kernel is written in C thus doesn't need ODR indicators.
2573 b) Some kernel code may have assumptions about symbols containing specific
2574 patterns in their names. Since ODR indicators contain original names
2575 of symbols they are emitted for, these assumptions would be broken for
2576 ODR indicator symbols. */
2577 return (!(flag_sanitize & SANITIZE_KERNEL_ADDRESS)
2578 && !DECL_ARTIFICIAL (decl)
2579 && !DECL_WEAK (decl)
2580 && TREE_PUBLIC (decl));
47c3d0de 2581}
2582
92fc5c48 2583/* Append description of a single global DECL into vector V.
2584 TYPE is __asan_global struct type as returned by asan_global_struct. */
2585
2586static void
f1f41a6c 2587asan_add_global (tree decl, tree type, vec<constructor_elt, va_gc> *v)
92fc5c48 2588{
2589 tree init, uptr = TREE_TYPE (DECL_CHAIN (TYPE_FIELDS (type)));
2590 unsigned HOST_WIDE_INT size;
1e80ce41 2591 tree str_cst, module_name_cst, refdecl = decl;
f1f41a6c 2592 vec<constructor_elt, va_gc> *vinner = NULL;
92fc5c48 2593
1e80ce41 2594 pretty_printer asan_pp, module_name_pp;
92fc5c48 2595
92fc5c48 2596 if (DECL_NAME (decl))
a94db6b0 2597 pp_tree_identifier (&asan_pp, DECL_NAME (decl));
92fc5c48 2598 else
2599 pp_string (&asan_pp, "<unknown>");
b75d2c15 2600 str_cst = asan_pp_string (&asan_pp);
92fc5c48 2601
9b2d20e4 2602 pp_string (&module_name_pp, main_input_filename);
1e80ce41 2603 module_name_cst = asan_pp_string (&module_name_pp);
2604
92fc5c48 2605 if (asan_needs_local_alias (decl))
2606 {
2607 char buf[20];
f1f41a6c 2608 ASM_GENERATE_INTERNAL_LABEL (buf, "LASAN", vec_safe_length (v) + 1);
92fc5c48 2609 refdecl = build_decl (DECL_SOURCE_LOCATION (decl),
2610 VAR_DECL, get_identifier (buf), TREE_TYPE (decl));
2611 TREE_ADDRESSABLE (refdecl) = TREE_ADDRESSABLE (decl);
2612 TREE_READONLY (refdecl) = TREE_READONLY (decl);
2613 TREE_THIS_VOLATILE (refdecl) = TREE_THIS_VOLATILE (decl);
2614 DECL_GIMPLE_REG_P (refdecl) = DECL_GIMPLE_REG_P (decl);
2615 DECL_ARTIFICIAL (refdecl) = DECL_ARTIFICIAL (decl);
2616 DECL_IGNORED_P (refdecl) = DECL_IGNORED_P (decl);
2617 TREE_STATIC (refdecl) = 1;
2618 TREE_PUBLIC (refdecl) = 0;
2619 TREE_USED (refdecl) = 1;
2620 assemble_alias (refdecl, DECL_ASSEMBLER_NAME (decl));
2621 }
2622
47c3d0de 2623 tree odr_indicator_ptr
2624 = (asan_needs_odr_indicator_p (decl) ? create_odr_indicator (decl, type)
2625 : build_int_cst (uptr, 0));
92fc5c48 2626 CONSTRUCTOR_APPEND_ELT (vinner, NULL_TREE,
2627 fold_convert (const_ptr_type_node,
2628 build_fold_addr_expr (refdecl)));
6a0712d4 2629 size = tree_to_uhwi (DECL_SIZE_UNIT (decl));
92fc5c48 2630 CONSTRUCTOR_APPEND_ELT (vinner, NULL_TREE, build_int_cst (uptr, size));
2631 size += asan_red_zone_size (size);
2632 CONSTRUCTOR_APPEND_ELT (vinner, NULL_TREE, build_int_cst (uptr, size));
2633 CONSTRUCTOR_APPEND_ELT (vinner, NULL_TREE,
2634 fold_convert (const_ptr_type_node, str_cst));
1e80ce41 2635 CONSTRUCTOR_APPEND_ELT (vinner, NULL_TREE,
2636 fold_convert (const_ptr_type_node, module_name_cst));
97221fd7 2637 varpool_node *vnode = varpool_node::get (decl);
9b2d20e4 2638 int has_dynamic_init = 0;
2639 /* FIXME: Enable initialization order fiasco detection in LTO mode once
2640 proper fix for PR 79061 will be applied. */
2641 if (!in_lto_p)
2642 has_dynamic_init = vnode ? vnode->dynamically_initialized : 0;
085f6ebf 2643 CONSTRUCTOR_APPEND_ELT (vinner, NULL_TREE,
2644 build_int_cst (uptr, has_dynamic_init));
11d00a0b 2645 tree locptr = NULL_TREE;
2646 location_t loc = DECL_SOURCE_LOCATION (decl);
2647 expanded_location xloc = expand_location (loc);
2648 if (xloc.file != NULL)
2649 {
2650 static int lasanloccnt = 0;
2651 char buf[25];
2652 ASM_GENERATE_INTERNAL_LABEL (buf, "LASANLOC", ++lasanloccnt);
2653 tree var = build_decl (UNKNOWN_LOCATION, VAR_DECL, get_identifier (buf),
2654 ubsan_get_source_location_type ());
2655 TREE_STATIC (var) = 1;
2656 TREE_PUBLIC (var) = 0;
2657 DECL_ARTIFICIAL (var) = 1;
2658 DECL_IGNORED_P (var) = 1;
2659 pretty_printer filename_pp;
2660 pp_string (&filename_pp, xloc.file);
2661 tree str = asan_pp_string (&filename_pp);
2662 tree ctor = build_constructor_va (TREE_TYPE (var), 3,
2663 NULL_TREE, str, NULL_TREE,
2664 build_int_cst (unsigned_type_node,
2665 xloc.line), NULL_TREE,
2666 build_int_cst (unsigned_type_node,
2667 xloc.column));
2668 TREE_CONSTANT (ctor) = 1;
2669 TREE_STATIC (ctor) = 1;
2670 DECL_INITIAL (var) = ctor;
2671 varpool_node::finalize_decl (var);
2672 locptr = fold_convert (uptr, build_fold_addr_expr (var));
2673 }
2674 else
2675 locptr = build_int_cst (uptr, 0);
2676 CONSTRUCTOR_APPEND_ELT (vinner, NULL_TREE, locptr);
47c3d0de 2677 CONSTRUCTOR_APPEND_ELT (vinner, NULL_TREE, odr_indicator_ptr);
92fc5c48 2678 init = build_constructor (type, vinner);
2679 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, init);
2680}
2681
b45e34ed 2682/* Initialize sanitizer.def builtins if the FE hasn't initialized them. */
2683void
2684initialize_sanitizer_builtins (void)
2685{
2686 tree decl;
2687
2688 if (builtin_decl_implicit_p (BUILT_IN_ASAN_INIT))
2689 return;
2690
2691 tree BT_FN_VOID = build_function_type_list (void_type_node, NULL_TREE);
2692 tree BT_FN_VOID_PTR
2693 = build_function_type_list (void_type_node, ptr_type_node, NULL_TREE);
085f6ebf 2694 tree BT_FN_VOID_CONST_PTR
2695 = build_function_type_list (void_type_node, const_ptr_type_node, NULL_TREE);
2c4c3477 2696 tree BT_FN_VOID_PTR_PTR
2697 = build_function_type_list (void_type_node, ptr_type_node,
2698 ptr_type_node, NULL_TREE);
9e46467d 2699 tree BT_FN_VOID_PTR_PTR_PTR
2700 = build_function_type_list (void_type_node, ptr_type_node,
2701 ptr_type_node, ptr_type_node, NULL_TREE);
b45e34ed 2702 tree BT_FN_VOID_PTR_PTRMODE
2703 = build_function_type_list (void_type_node, ptr_type_node,
9e46467d 2704 pointer_sized_int_node, NULL_TREE);
83392e87 2705 tree BT_FN_VOID_INT
2706 = build_function_type_list (void_type_node, integer_type_node, NULL_TREE);
d14d27c6 2707 tree BT_FN_SIZE_CONST_PTR_INT
2708 = build_function_type_list (size_type_node, const_ptr_type_node,
2709 integer_type_node, NULL_TREE);
ccec7674 2710
2711 tree BT_FN_VOID_UINT8_UINT8
2712 = build_function_type_list (void_type_node, unsigned_char_type_node,
2713 unsigned_char_type_node, NULL_TREE);
2714 tree BT_FN_VOID_UINT16_UINT16
2715 = build_function_type_list (void_type_node, uint16_type_node,
2716 uint16_type_node, NULL_TREE);
2717 tree BT_FN_VOID_UINT32_UINT32
2718 = build_function_type_list (void_type_node, uint32_type_node,
2719 uint32_type_node, NULL_TREE);
2720 tree BT_FN_VOID_UINT64_UINT64
2721 = build_function_type_list (void_type_node, uint64_type_node,
2722 uint64_type_node, NULL_TREE);
2723 tree BT_FN_VOID_FLOAT_FLOAT
2724 = build_function_type_list (void_type_node, float_type_node,
2725 float_type_node, NULL_TREE);
2726 tree BT_FN_VOID_DOUBLE_DOUBLE
2727 = build_function_type_list (void_type_node, double_type_node,
2728 double_type_node, NULL_TREE);
2729 tree BT_FN_VOID_UINT64_PTR
2730 = build_function_type_list (void_type_node, uint64_type_node,
2731 ptr_type_node, NULL_TREE);
2732
83392e87 2733 tree BT_FN_BOOL_VPTR_PTR_IX_INT_INT[5];
2734 tree BT_FN_IX_CONST_VPTR_INT[5];
2735 tree BT_FN_IX_VPTR_IX_INT[5];
2736 tree BT_FN_VOID_VPTR_IX_INT[5];
2737 tree vptr
2738 = build_pointer_type (build_qualified_type (void_type_node,
2739 TYPE_QUAL_VOLATILE));
2740 tree cvptr
2741 = build_pointer_type (build_qualified_type (void_type_node,
2742 TYPE_QUAL_VOLATILE
2743 |TYPE_QUAL_CONST));
2744 tree boolt
2745 = lang_hooks.types.type_for_size (BOOL_TYPE_SIZE, 1);
2746 int i;
2747 for (i = 0; i < 5; i++)
2748 {
2749 tree ix = build_nonstandard_integer_type (BITS_PER_UNIT * (1 << i), 1);
2750 BT_FN_BOOL_VPTR_PTR_IX_INT_INT[i]
2751 = build_function_type_list (boolt, vptr, ptr_type_node, ix,
2752 integer_type_node, integer_type_node,
2753 NULL_TREE);
2754 BT_FN_IX_CONST_VPTR_INT[i]
2755 = build_function_type_list (ix, cvptr, integer_type_node, NULL_TREE);
2756 BT_FN_IX_VPTR_IX_INT[i]
2757 = build_function_type_list (ix, vptr, ix, integer_type_node,
2758 NULL_TREE);
2759 BT_FN_VOID_VPTR_IX_INT[i]
2760 = build_function_type_list (void_type_node, vptr, ix,
2761 integer_type_node, NULL_TREE);
2762 }
2763#define BT_FN_BOOL_VPTR_PTR_I1_INT_INT BT_FN_BOOL_VPTR_PTR_IX_INT_INT[0]
2764#define BT_FN_I1_CONST_VPTR_INT BT_FN_IX_CONST_VPTR_INT[0]
2765#define BT_FN_I1_VPTR_I1_INT BT_FN_IX_VPTR_IX_INT[0]
2766#define BT_FN_VOID_VPTR_I1_INT BT_FN_VOID_VPTR_IX_INT[0]
2767#define BT_FN_BOOL_VPTR_PTR_I2_INT_INT BT_FN_BOOL_VPTR_PTR_IX_INT_INT[1]
2768#define BT_FN_I2_CONST_VPTR_INT BT_FN_IX_CONST_VPTR_INT[1]
2769#define BT_FN_I2_VPTR_I2_INT BT_FN_IX_VPTR_IX_INT[1]
2770#define BT_FN_VOID_VPTR_I2_INT BT_FN_VOID_VPTR_IX_INT[1]
2771#define BT_FN_BOOL_VPTR_PTR_I4_INT_INT BT_FN_BOOL_VPTR_PTR_IX_INT_INT[2]
2772#define BT_FN_I4_CONST_VPTR_INT BT_FN_IX_CONST_VPTR_INT[2]
2773#define BT_FN_I4_VPTR_I4_INT BT_FN_IX_VPTR_IX_INT[2]
2774#define BT_FN_VOID_VPTR_I4_INT BT_FN_VOID_VPTR_IX_INT[2]
2775#define BT_FN_BOOL_VPTR_PTR_I8_INT_INT BT_FN_BOOL_VPTR_PTR_IX_INT_INT[3]
2776#define BT_FN_I8_CONST_VPTR_INT BT_FN_IX_CONST_VPTR_INT[3]
2777#define BT_FN_I8_VPTR_I8_INT BT_FN_IX_VPTR_IX_INT[3]
2778#define BT_FN_VOID_VPTR_I8_INT BT_FN_VOID_VPTR_IX_INT[3]
2779#define BT_FN_BOOL_VPTR_PTR_I16_INT_INT BT_FN_BOOL_VPTR_PTR_IX_INT_INT[4]
2780#define BT_FN_I16_CONST_VPTR_INT BT_FN_IX_CONST_VPTR_INT[4]
2781#define BT_FN_I16_VPTR_I16_INT BT_FN_IX_VPTR_IX_INT[4]
2782#define BT_FN_VOID_VPTR_I16_INT BT_FN_VOID_VPTR_IX_INT[4]
b45e34ed 2783#undef ATTR_NOTHROW_LEAF_LIST
2784#define ATTR_NOTHROW_LEAF_LIST ECF_NOTHROW | ECF_LEAF
c2901651 2785#undef ATTR_TMPURE_NOTHROW_LEAF_LIST
2786#define ATTR_TMPURE_NOTHROW_LEAF_LIST ECF_TM_PURE | ATTR_NOTHROW_LEAF_LIST
b45e34ed 2787#undef ATTR_NORETURN_NOTHROW_LEAF_LIST
2788#define ATTR_NORETURN_NOTHROW_LEAF_LIST ECF_NORETURN | ATTR_NOTHROW_LEAF_LIST
f6b540af 2789#undef ATTR_CONST_NORETURN_NOTHROW_LEAF_LIST
2790#define ATTR_CONST_NORETURN_NOTHROW_LEAF_LIST \
2791 ECF_CONST | ATTR_NORETURN_NOTHROW_LEAF_LIST
c2901651 2792#undef ATTR_TMPURE_NORETURN_NOTHROW_LEAF_LIST
2793#define ATTR_TMPURE_NORETURN_NOTHROW_LEAF_LIST \
2794 ECF_TM_PURE | ATTR_NORETURN_NOTHROW_LEAF_LIST
9e46467d 2795#undef ATTR_COLD_NOTHROW_LEAF_LIST
2796#define ATTR_COLD_NOTHROW_LEAF_LIST \
2797 /* ECF_COLD missing */ ATTR_NOTHROW_LEAF_LIST
2798#undef ATTR_COLD_NORETURN_NOTHROW_LEAF_LIST
2799#define ATTR_COLD_NORETURN_NOTHROW_LEAF_LIST \
2800 /* ECF_COLD missing */ ATTR_NORETURN_NOTHROW_LEAF_LIST
f6b540af 2801#undef ATTR_COLD_CONST_NORETURN_NOTHROW_LEAF_LIST
2802#define ATTR_COLD_CONST_NORETURN_NOTHROW_LEAF_LIST \
2803 /* ECF_COLD missing */ ATTR_CONST_NORETURN_NOTHROW_LEAF_LIST
d14d27c6 2804#undef ATTR_PURE_NOTHROW_LEAF_LIST
2805#define ATTR_PURE_NOTHROW_LEAF_LIST ECF_PURE | ATTR_NOTHROW_LEAF_LIST
ee49ca6a 2806#undef DEF_BUILTIN_STUB
2807#define DEF_BUILTIN_STUB(ENUM, NAME)
b45e34ed 2808#undef DEF_SANITIZER_BUILTIN
2809#define DEF_SANITIZER_BUILTIN(ENUM, NAME, TYPE, ATTRS) \
cf5531b5 2810 do { \
2811 decl = add_builtin_function ("__builtin_" NAME, TYPE, ENUM, \
2812 BUILT_IN_NORMAL, NAME, NULL_TREE); \
2813 set_call_expr_flags (decl, ATTRS); \
2814 set_builtin_decl (ENUM, decl, true); \
2815 } while (0);
b45e34ed 2816
2817#include "sanitizer.def"
2818
d14d27c6 2819 /* -fsanitize=object-size uses __builtin_object_size, but that might
2820 not be available for e.g. Fortran at this point. We use
2821 DEF_SANITIZER_BUILTIN here only as a convenience macro. */
2822 if ((flag_sanitize & SANITIZE_OBJECT_SIZE)
2823 && !builtin_decl_implicit_p (BUILT_IN_OBJECT_SIZE))
2824 DEF_SANITIZER_BUILTIN (BUILT_IN_OBJECT_SIZE, "object_size",
2825 BT_FN_SIZE_CONST_PTR_INT,
2826 ATTR_PURE_NOTHROW_LEAF_LIST)
2827
b45e34ed 2828#undef DEF_SANITIZER_BUILTIN
ee49ca6a 2829#undef DEF_BUILTIN_STUB
b45e34ed 2830}
2831
55b58027 2832/* Called via htab_traverse. Count number of emitted
2833 STRING_CSTs in the constant hash table. */
2834
2ef51f0e 2835int
2836count_string_csts (constant_descriptor_tree **slot,
2837 unsigned HOST_WIDE_INT *data)
55b58027 2838{
2ef51f0e 2839 struct constant_descriptor_tree *desc = *slot;
55b58027 2840 if (TREE_CODE (desc->value) == STRING_CST
2841 && TREE_ASM_WRITTEN (desc->value)
2842 && asan_protect_global (desc->value))
2ef51f0e 2843 ++*data;
55b58027 2844 return 1;
2845}
2846
2847/* Helper structure to pass two parameters to
2848 add_string_csts. */
2849
2850struct asan_add_string_csts_data
2851{
2852 tree type;
2853 vec<constructor_elt, va_gc> *v;
2854};
2855
2ef51f0e 2856/* Called via hash_table::traverse. Call asan_add_global
55b58027 2857 on emitted STRING_CSTs from the constant hash table. */
2858
2ef51f0e 2859int
2860add_string_csts (constant_descriptor_tree **slot,
2861 asan_add_string_csts_data *aascd)
55b58027 2862{
2ef51f0e 2863 struct constant_descriptor_tree *desc = *slot;
55b58027 2864 if (TREE_CODE (desc->value) == STRING_CST
2865 && TREE_ASM_WRITTEN (desc->value)
2866 && asan_protect_global (desc->value))
2867 {
55b58027 2868 asan_add_global (SYMBOL_REF_DECL (XEXP (desc->rtl, 0)),
2869 aascd->type, aascd->v);
2870 }
2871 return 1;
2872}
2873
92fc5c48 2874/* Needs to be GTY(()), because cgraph_build_static_cdtor may
2875 invoke ggc_collect. */
2876static GTY(()) tree asan_ctor_statements;
2877
b92cccf4 2878/* Module-level instrumentation.
1e80ce41 2879 - Insert __asan_init_vN() into the list of CTORs.
b92cccf4 2880 - TODO: insert redzones around globals.
2881 */
2882
2883void
2884asan_finish_file (void)
2885{
098f44bc 2886 varpool_node *vnode;
92fc5c48 2887 unsigned HOST_WIDE_INT gcount = 0;
2888
55b58027 2889 if (shadow_ptr_types[0] == NULL_TREE)
2890 asan_init_shadow_ptr_types ();
2891 /* Avoid instrumenting code in the asan ctors/dtors.
2892 We don't need to insert padding after the description strings,
2893 nor after .LASAN* array. */
9e46467d 2894 flag_sanitize &= ~SANITIZE_ADDRESS;
b45e34ed 2895
aa1dfc5f 2896 /* For user-space we want asan constructors to run first.
2897 Linux kernel does not support priorities other than default, and the only
2898 other user of constructors is coverage. So we run with the default
2899 priority. */
2900 int priority = flag_sanitize & SANITIZE_USER_ADDRESS
2901 ? MAX_RESERVED_INIT_PRIORITY - 1 : DEFAULT_INIT_PRIORITY;
2902
647918a4 2903 if (flag_sanitize & SANITIZE_USER_ADDRESS)
2904 {
2905 tree fn = builtin_decl_implicit (BUILT_IN_ASAN_INIT);
2906 append_to_statement_list (build_call_expr (fn, 0), &asan_ctor_statements);
7966ce00 2907 fn = builtin_decl_implicit (BUILT_IN_ASAN_VERSION_MISMATCH_CHECK);
2908 append_to_statement_list (build_call_expr (fn, 0), &asan_ctor_statements);
647918a4 2909 }
92fc5c48 2910 FOR_EACH_DEFINED_VARIABLE (vnode)
02774f2d 2911 if (TREE_ASM_WRITTEN (vnode->decl)
2912 && asan_protect_global (vnode->decl))
92fc5c48 2913 ++gcount;
2ef51f0e 2914 hash_table<tree_descriptor_hasher> *const_desc_htab = constant_pool_htab ();
2915 const_desc_htab->traverse<unsigned HOST_WIDE_INT *, count_string_csts>
2916 (&gcount);
92fc5c48 2917 if (gcount)
2918 {
b45e34ed 2919 tree type = asan_global_struct (), var, ctor;
92fc5c48 2920 tree dtor_statements = NULL_TREE;
f1f41a6c 2921 vec<constructor_elt, va_gc> *v;
92fc5c48 2922 char buf[20];
2923
2924 type = build_array_type_nelts (type, gcount);
2925 ASM_GENERATE_INTERNAL_LABEL (buf, "LASAN", 0);
2926 var = build_decl (UNKNOWN_LOCATION, VAR_DECL, get_identifier (buf),
2927 type);
2928 TREE_STATIC (var) = 1;
2929 TREE_PUBLIC (var) = 0;
2930 DECL_ARTIFICIAL (var) = 1;
2931 DECL_IGNORED_P (var) = 1;
f1f41a6c 2932 vec_alloc (v, gcount);
92fc5c48 2933 FOR_EACH_DEFINED_VARIABLE (vnode)
02774f2d 2934 if (TREE_ASM_WRITTEN (vnode->decl)
2935 && asan_protect_global (vnode->decl))
2936 asan_add_global (vnode->decl, TREE_TYPE (type), v);
55b58027 2937 struct asan_add_string_csts_data aascd;
2938 aascd.type = TREE_TYPE (type);
2939 aascd.v = v;
2ef51f0e 2940 const_desc_htab->traverse<asan_add_string_csts_data *, add_string_csts>
2941 (&aascd);
92fc5c48 2942 ctor = build_constructor (type, v);
2943 TREE_CONSTANT (ctor) = 1;
2944 TREE_STATIC (ctor) = 1;
2945 DECL_INITIAL (var) = ctor;
97221fd7 2946 varpool_node::finalize_decl (var);
92fc5c48 2947
647918a4 2948 tree fn = builtin_decl_implicit (BUILT_IN_ASAN_REGISTER_GLOBALS);
9e46467d 2949 tree gcount_tree = build_int_cst (pointer_sized_int_node, gcount);
b45e34ed 2950 append_to_statement_list (build_call_expr (fn, 2,
92fc5c48 2951 build_fold_addr_expr (var),
9e46467d 2952 gcount_tree),
92fc5c48 2953 &asan_ctor_statements);
2954
b45e34ed 2955 fn = builtin_decl_implicit (BUILT_IN_ASAN_UNREGISTER_GLOBALS);
2956 append_to_statement_list (build_call_expr (fn, 2,
92fc5c48 2957 build_fold_addr_expr (var),
9e46467d 2958 gcount_tree),
92fc5c48 2959 &dtor_statements);
aa1dfc5f 2960 cgraph_build_static_cdtor ('D', dtor_statements, priority);
92fc5c48 2961 }
647918a4 2962 if (asan_ctor_statements)
aa1dfc5f 2963 cgraph_build_static_cdtor ('I', asan_ctor_statements, priority);
9e46467d 2964 flag_sanitize |= SANITIZE_ADDRESS;
5d5c682b 2965}
2966
629b6abc 2967/* Poison or unpoison (depending on IS_CLOBBER variable) shadow memory based
2968 on SHADOW address. Newly added statements will be added to ITER with
2969 given location LOC. We mark SIZE bytes in shadow memory, where
2970 LAST_CHUNK_SIZE is greater than zero in situation where we are at the
2971 end of a variable. */
2972
2973static void
2974asan_store_shadow_bytes (gimple_stmt_iterator *iter, location_t loc,
2975 tree shadow,
2976 unsigned HOST_WIDE_INT base_addr_offset,
2977 bool is_clobber, unsigned size,
2978 unsigned last_chunk_size)
2979{
2980 tree shadow_ptr_type;
2981
2982 switch (size)
2983 {
2984 case 1:
2985 shadow_ptr_type = shadow_ptr_types[0];
2986 break;
2987 case 2:
2988 shadow_ptr_type = shadow_ptr_types[1];
2989 break;
2990 case 4:
2991 shadow_ptr_type = shadow_ptr_types[2];
2992 break;
2993 default:
2994 gcc_unreachable ();
2995 }
2996
2997 unsigned char c = (char) is_clobber ? ASAN_STACK_MAGIC_USE_AFTER_SCOPE : 0;
2998 unsigned HOST_WIDE_INT val = 0;
6dc83378 2999 unsigned last_pos = size;
3000 if (last_chunk_size && !is_clobber)
3001 last_pos = BYTES_BIG_ENDIAN ? 0 : size - 1;
629b6abc 3002 for (unsigned i = 0; i < size; ++i)
3003 {
3004 unsigned char shadow_c = c;
6dc83378 3005 if (i == last_pos)
629b6abc 3006 shadow_c = last_chunk_size;
3007 val |= (unsigned HOST_WIDE_INT) shadow_c << (BITS_PER_UNIT * i);
3008 }
3009
3010 /* Handle last chunk in unpoisoning. */
3011 tree magic = build_int_cst (TREE_TYPE (shadow_ptr_type), val);
3012
3013 tree dest = build2 (MEM_REF, TREE_TYPE (shadow_ptr_type), shadow,
3014 build_int_cst (shadow_ptr_type, base_addr_offset));
3015
3016 gimple *g = gimple_build_assign (dest, magic);
3017 gimple_set_location (g, loc);
3018 gsi_insert_after (iter, g, GSI_NEW_STMT);
3019}
3020
3021/* Expand the ASAN_MARK builtins. */
3022
3023bool
3024asan_expand_mark_ifn (gimple_stmt_iterator *iter)
3025{
3026 gimple *g = gsi_stmt (*iter);
3027 location_t loc = gimple_location (g);
a30589d5 3028 HOST_WIDE_INT flag = tree_to_shwi (gimple_call_arg (g, 0));
3029 bool is_poison = ((asan_mark_flags)flag) == ASAN_MARK_POISON;
629b6abc 3030
3031 tree base = gimple_call_arg (g, 1);
3032 gcc_checking_assert (TREE_CODE (base) == ADDR_EXPR);
3033 tree decl = TREE_OPERAND (base, 0);
9b51ac50 3034
3035 /* For a nested function, we can have: ASAN_MARK (2, &FRAME.2.fp_input, 4) */
3036 if (TREE_CODE (decl) == COMPONENT_REF
3037 && DECL_NONLOCAL_FRAME (TREE_OPERAND (decl, 0)))
3038 decl = TREE_OPERAND (decl, 0);
3039
629b6abc 3040 gcc_checking_assert (TREE_CODE (decl) == VAR_DECL);
355c1762 3041
3042 if (is_poison)
3043 {
3044 if (asan_handled_variables == NULL)
3045 asan_handled_variables = new hash_set<tree> (16);
3046 asan_handled_variables->add (decl);
3047 }
629b6abc 3048 tree len = gimple_call_arg (g, 2);
3049
3050 gcc_assert (tree_fits_shwi_p (len));
3051 unsigned HOST_WIDE_INT size_in_bytes = tree_to_shwi (len);
3052 gcc_assert (size_in_bytes);
3053
3054 g = gimple_build_assign (make_ssa_name (pointer_sized_int_node),
3055 NOP_EXPR, base);
3056 gimple_set_location (g, loc);
3057 gsi_replace (iter, g, false);
3058 tree base_addr = gimple_assign_lhs (g);
3059
3060 /* Generate direct emission if size_in_bytes is small. */
3061 if (size_in_bytes <= ASAN_PARAM_USE_AFTER_SCOPE_DIRECT_EMISSION_THRESHOLD)
3062 {
3063 unsigned HOST_WIDE_INT shadow_size = shadow_mem_size (size_in_bytes);
3064
3065 tree shadow = build_shadow_mem_access (iter, loc, base_addr,
3066 shadow_ptr_types[0], true);
3067
3068 for (unsigned HOST_WIDE_INT offset = 0; offset < shadow_size;)
3069 {
3070 unsigned size = 1;
3071 if (shadow_size - offset >= 4)
3072 size = 4;
3073 else if (shadow_size - offset >= 2)
3074 size = 2;
3075
3076 unsigned HOST_WIDE_INT last_chunk_size = 0;
3077 unsigned HOST_WIDE_INT s = (offset + size) * ASAN_SHADOW_GRANULARITY;
3078 if (s > size_in_bytes)
3079 last_chunk_size = ASAN_SHADOW_GRANULARITY - (s - size_in_bytes);
3080
a30589d5 3081 asan_store_shadow_bytes (iter, loc, shadow, offset, is_poison,
629b6abc 3082 size, last_chunk_size);
3083 offset += size;
3084 }
3085 }
3086 else
3087 {
3088 g = gimple_build_assign (make_ssa_name (pointer_sized_int_node),
3089 NOP_EXPR, len);
3090 gimple_set_location (g, loc);
3091 gsi_insert_before (iter, g, GSI_SAME_STMT);
3092 tree sz_arg = gimple_assign_lhs (g);
3093
c6c892c5 3094 tree fun
3095 = builtin_decl_implicit (is_poison ? BUILT_IN_ASAN_POISON_STACK_MEMORY
3096 : BUILT_IN_ASAN_UNPOISON_STACK_MEMORY);
629b6abc 3097 g = gimple_build_call (fun, 2, base_addr, sz_arg);
3098 gimple_set_location (g, loc);
3099 gsi_insert_after (iter, g, GSI_NEW_STMT);
3100 }
3101
3102 return false;
3103}
3104
ff326078 3105/* Expand the ASAN_{LOAD,STORE} builtins. */
3106
6b5813f5 3107bool
ff326078 3108asan_expand_check_ifn (gimple_stmt_iterator *iter, bool use_calls)
3109{
42acab1c 3110 gimple *g = gsi_stmt (*iter);
ff326078 3111 location_t loc = gimple_location (g);
21017ecb 3112 bool recover_p;
3113 if (flag_sanitize & SANITIZE_USER_ADDRESS)
3114 recover_p = (flag_sanitize_recover & SANITIZE_USER_ADDRESS) != 0;
3115 else
3116 recover_p = (flag_sanitize_recover & SANITIZE_KERNEL_ADDRESS) != 0;
f4d482a6 3117
ff326078 3118 HOST_WIDE_INT flags = tree_to_shwi (gimple_call_arg (g, 0));
3119 gcc_assert (flags < ASAN_CHECK_LAST);
3120 bool is_scalar_access = (flags & ASAN_CHECK_SCALAR_ACCESS) != 0;
3121 bool is_store = (flags & ASAN_CHECK_STORE) != 0;
3122 bool is_non_zero_len = (flags & ASAN_CHECK_NON_ZERO_LEN) != 0;
ff326078 3123
3124 tree base = gimple_call_arg (g, 1);
3125 tree len = gimple_call_arg (g, 2);
da81fb00 3126 HOST_WIDE_INT align = tree_to_shwi (gimple_call_arg (g, 3));
ff326078 3127
3128 HOST_WIDE_INT size_in_bytes
3129 = is_scalar_access && tree_fits_shwi_p (len) ? tree_to_shwi (len) : -1;
3130
3131 if (use_calls)
3132 {
3133 /* Instrument using callbacks. */
42acab1c 3134 gimple *g = gimple_build_assign (make_ssa_name (pointer_sized_int_node),
e9cf809e 3135 NOP_EXPR, base);
ff326078 3136 gimple_set_location (g, loc);
3137 gsi_insert_before (iter, g, GSI_SAME_STMT);
3138 tree base_addr = gimple_assign_lhs (g);
3139
3140 int nargs;
f4d482a6 3141 tree fun = check_func (is_store, recover_p, size_in_bytes, &nargs);
ff326078 3142 if (nargs == 1)
3143 g = gimple_build_call (fun, 1, base_addr);
3144 else
3145 {
3146 gcc_assert (nargs == 2);
e9cf809e 3147 g = gimple_build_assign (make_ssa_name (pointer_sized_int_node),
3148 NOP_EXPR, len);
ff326078 3149 gimple_set_location (g, loc);
3150 gsi_insert_before (iter, g, GSI_SAME_STMT);
3151 tree sz_arg = gimple_assign_lhs (g);
3152 g = gimple_build_call (fun, nargs, base_addr, sz_arg);
3153 }
3154 gimple_set_location (g, loc);
3155 gsi_replace (iter, g, false);
3156 return false;
3157 }
3158
3159 HOST_WIDE_INT real_size_in_bytes = size_in_bytes == -1 ? 1 : size_in_bytes;
3160
ff326078 3161 tree shadow_ptr_type = shadow_ptr_types[real_size_in_bytes == 16 ? 1 : 0];
3162 tree shadow_type = TREE_TYPE (shadow_ptr_type);
3163
3164 gimple_stmt_iterator gsi = *iter;
3165
3166 if (!is_non_zero_len)
3167 {
3168 /* So, the length of the memory area to asan-protect is
3169 non-constant. Let's guard the generated instrumentation code
3170 like:
3171
3172 if (len != 0)
3173 {
3174 //asan instrumentation code goes here.
3175 }
3176 // falltrough instructions, starting with *ITER. */
3177
3178 g = gimple_build_cond (NE_EXPR,
3179 len,
3180 build_int_cst (TREE_TYPE (len), 0),
3181 NULL_TREE, NULL_TREE);
3182 gimple_set_location (g, loc);
3183
3184 basic_block then_bb, fallthrough_bb;
1a91d914 3185 insert_if_then_before_iter (as_a <gcond *> (g), iter,
3186 /*then_more_likely_p=*/true,
3187 &then_bb, &fallthrough_bb);
ff326078 3188 /* Note that fallthrough_bb starts with the statement that was
3189 pointed to by ITER. */
3190
3191 /* The 'then block' of the 'if (len != 0) condition is where
3192 we'll generate the asan instrumentation code now. */
3193 gsi = gsi_last_bb (then_bb);
3194 }
3195
3196 /* Get an iterator on the point where we can add the condition
3197 statement for the instrumentation. */
3198 basic_block then_bb, else_bb;
3199 gsi = create_cond_insert_point (&gsi, /*before_p*/false,
3200 /*then_more_likely_p=*/false,
f4d482a6 3201 /*create_then_fallthru_edge*/recover_p,
ff326078 3202 &then_bb,
3203 &else_bb);
3204
e9cf809e 3205 g = gimple_build_assign (make_ssa_name (pointer_sized_int_node),
3206 NOP_EXPR, base);
ff326078 3207 gimple_set_location (g, loc);
3208 gsi_insert_before (&gsi, g, GSI_NEW_STMT);
3209 tree base_addr = gimple_assign_lhs (g);
3210
3211 tree t = NULL_TREE;
3212 if (real_size_in_bytes >= 8)
3213 {
3214 tree shadow = build_shadow_mem_access (&gsi, loc, base_addr,
3215 shadow_ptr_type);
3216 t = shadow;
3217 }
3218 else
3219 {
3220 /* Slow path for 1, 2 and 4 byte accesses. */
f9acf11a 3221 /* Test (shadow != 0)
3222 & ((base_addr & 7) + (real_size_in_bytes - 1)) >= shadow). */
3223 tree shadow = build_shadow_mem_access (&gsi, loc, base_addr,
3224 shadow_ptr_type);
42acab1c 3225 gimple *shadow_test = build_assign (NE_EXPR, shadow, 0);
f9acf11a 3226 gimple_seq seq = NULL;
3227 gimple_seq_add_stmt (&seq, shadow_test);
3228 /* Aligned (>= 8 bytes) can test just
3229 (real_size_in_bytes - 1 >= shadow), as base_addr & 7 is known
3230 to be 0. */
3231 if (align < 8)
ff326078 3232 {
f9acf11a 3233 gimple_seq_add_stmt (&seq, build_assign (BIT_AND_EXPR,
3234 base_addr, 7));
3235 gimple_seq_add_stmt (&seq,
3236 build_type_cast (shadow_type,
3237 gimple_seq_last (seq)));
3238 if (real_size_in_bytes > 1)
3239 gimple_seq_add_stmt (&seq,
3240 build_assign (PLUS_EXPR,
3241 gimple_seq_last (seq),
3242 real_size_in_bytes - 1));
3243 t = gimple_assign_lhs (gimple_seq_last_stmt (seq));
ff326078 3244 }
f9acf11a 3245 else
3246 t = build_int_cst (shadow_type, real_size_in_bytes - 1);
3247 gimple_seq_add_stmt (&seq, build_assign (GE_EXPR, t, shadow));
3248 gimple_seq_add_stmt (&seq, build_assign (BIT_AND_EXPR, shadow_test,
3249 gimple_seq_last (seq)));
3250 t = gimple_assign_lhs (gimple_seq_last (seq));
3251 gimple_seq_set_location (seq, loc);
3252 gsi_insert_seq_after (&gsi, seq, GSI_CONTINUE_LINKING);
ff326078 3253
3254 /* For non-constant, misaligned or otherwise weird access sizes,
f9acf11a 3255 check first and last byte. */
3256 if (size_in_bytes == -1)
ff326078 3257 {
e9cf809e 3258 g = gimple_build_assign (make_ssa_name (pointer_sized_int_node),
3259 MINUS_EXPR, len,
3260 build_int_cst (pointer_sized_int_node, 1));
ff326078 3261 gimple_set_location (g, loc);
3262 gsi_insert_after (&gsi, g, GSI_NEW_STMT);
3263 tree last = gimple_assign_lhs (g);
e9cf809e 3264 g = gimple_build_assign (make_ssa_name (pointer_sized_int_node),
3265 PLUS_EXPR, base_addr, last);
ff326078 3266 gimple_set_location (g, loc);
3267 gsi_insert_after (&gsi, g, GSI_NEW_STMT);
3268 tree base_end_addr = gimple_assign_lhs (g);
3269
3270 tree shadow = build_shadow_mem_access (&gsi, loc, base_end_addr,
3271 shadow_ptr_type);
42acab1c 3272 gimple *shadow_test = build_assign (NE_EXPR, shadow, 0);
ff326078 3273 gimple_seq seq = NULL;
3274 gimple_seq_add_stmt (&seq, shadow_test);
3275 gimple_seq_add_stmt (&seq, build_assign (BIT_AND_EXPR,
3276 base_end_addr, 7));
3277 gimple_seq_add_stmt (&seq, build_type_cast (shadow_type,
3278 gimple_seq_last (seq)));
3279 gimple_seq_add_stmt (&seq, build_assign (GE_EXPR,
3280 gimple_seq_last (seq),
3281 shadow));
3282 gimple_seq_add_stmt (&seq, build_assign (BIT_AND_EXPR, shadow_test,
3283 gimple_seq_last (seq)));
f9acf11a 3284 gimple_seq_add_stmt (&seq, build_assign (BIT_IOR_EXPR, t,
3285 gimple_seq_last (seq)));
ff326078 3286 t = gimple_assign_lhs (gimple_seq_last (seq));
3287 gimple_seq_set_location (seq, loc);
3288 gsi_insert_seq_after (&gsi, seq, GSI_CONTINUE_LINKING);
3289 }
3290 }
3291
3292 g = gimple_build_cond (NE_EXPR, t, build_int_cst (TREE_TYPE (t), 0),
3293 NULL_TREE, NULL_TREE);
3294 gimple_set_location (g, loc);
3295 gsi_insert_after (&gsi, g, GSI_NEW_STMT);
3296
3297 /* Generate call to the run-time library (e.g. __asan_report_load8). */
3298 gsi = gsi_start_bb (then_bb);
3299 int nargs;
f4d482a6 3300 tree fun = report_error_func (is_store, recover_p, size_in_bytes, &nargs);
ff326078 3301 g = gimple_build_call (fun, nargs, base_addr, len);
3302 gimple_set_location (g, loc);
3303 gsi_insert_after (&gsi, g, GSI_NEW_STMT);
3304
3305 gsi_remove (iter, true);
3306 *iter = gsi_start_bb (else_bb);
3307
3308 return true;
3309}
3310
c51887c5 3311/* Create ASAN shadow variable for a VAR_DECL which has been rewritten
3312 into SSA. Already seen VAR_DECLs are stored in SHADOW_VARS_MAPPING. */
3313
3314static tree
3315create_asan_shadow_var (tree var_decl,
3316 hash_map<tree, tree> &shadow_vars_mapping)
3317{
3318 tree *slot = shadow_vars_mapping.get (var_decl);
3319 if (slot == NULL)
3320 {
3321 tree shadow_var = copy_node (var_decl);
3322
3323 copy_body_data id;
3324 memset (&id, 0, sizeof (copy_body_data));
3325 id.src_fn = id.dst_fn = current_function_decl;
3326 copy_decl_for_dup_finish (&id, var_decl, shadow_var);
3327
3328 DECL_ARTIFICIAL (shadow_var) = 1;
3329 DECL_IGNORED_P (shadow_var) = 1;
3330 DECL_SEEN_IN_BIND_EXPR_P (shadow_var) = 0;
3331 gimple_add_tmp_var (shadow_var);
3332
3333 shadow_vars_mapping.put (var_decl, shadow_var);
3334 return shadow_var;
3335 }
3336 else
3337 return *slot;
3338}
3339
ba39c1d4 3340/* Expand ASAN_POISON ifn. */
3341
c51887c5 3342bool
3343asan_expand_poison_ifn (gimple_stmt_iterator *iter,
3344 bool *need_commit_edge_insert,
3345 hash_map<tree, tree> &shadow_vars_mapping)
3346{
3347 gimple *g = gsi_stmt (*iter);
3348 tree poisoned_var = gimple_call_lhs (g);
947c0c36 3349 if (!poisoned_var || has_zero_uses (poisoned_var))
c51887c5 3350 {
3351 gsi_remove (iter, true);
3352 return true;
3353 }
3354
947c0c36 3355 if (SSA_NAME_VAR (poisoned_var) == NULL_TREE)
3356 SET_SSA_NAME_VAR_OR_IDENTIFIER (poisoned_var,
3357 create_tmp_var (TREE_TYPE (poisoned_var)));
3358
ba39c1d4 3359 tree shadow_var = create_asan_shadow_var (SSA_NAME_VAR (poisoned_var),
3360 shadow_vars_mapping);
c51887c5 3361
3362 bool recover_p;
3363 if (flag_sanitize & SANITIZE_USER_ADDRESS)
3364 recover_p = (flag_sanitize_recover & SANITIZE_USER_ADDRESS) != 0;
3365 else
3366 recover_p = (flag_sanitize_recover & SANITIZE_KERNEL_ADDRESS) != 0;
3367 tree size = DECL_SIZE_UNIT (shadow_var);
3368 gimple *poison_call
3369 = gimple_build_call_internal (IFN_ASAN_MARK, 3,
3370 build_int_cst (integer_type_node,
3371 ASAN_MARK_POISON),
3372 build_fold_addr_expr (shadow_var), size);
3373
ba39c1d4 3374 gimple *use;
c51887c5 3375 imm_use_iterator imm_iter;
ba39c1d4 3376 FOR_EACH_IMM_USE_STMT (use, imm_iter, poisoned_var)
c51887c5 3377 {
c51887c5 3378 if (is_gimple_debug (use))
3379 continue;
3380
3381 int nargs;
ba39c1d4 3382 bool store_p = gimple_call_internal_p (use, IFN_ASAN_POISON_USE);
3383 tree fun = report_error_func (store_p, recover_p, tree_to_uhwi (size),
c51887c5 3384 &nargs);
3385
3386 gcall *call = gimple_build_call (fun, 1,
3387 build_fold_addr_expr (shadow_var));
3388 gimple_set_location (call, gimple_location (use));
3389 gimple *call_to_insert = call;
3390
3391 /* The USE can be a gimple PHI node. If so, insert the call on
3392 all edges leading to the PHI node. */
3393 if (is_a <gphi *> (use))
3394 {
3395 gphi *phi = dyn_cast<gphi *> (use);
3396 for (unsigned i = 0; i < gimple_phi_num_args (phi); ++i)
3397 if (gimple_phi_arg_def (phi, i) == poisoned_var)
3398 {
3399 edge e = gimple_phi_arg_edge (phi, i);
3400
dad472c2 3401 /* Do not insert on an edge we can't split. */
3402 if (e->flags & EDGE_ABNORMAL)
3403 continue;
3404
c51887c5 3405 if (call_to_insert == NULL)
3406 call_to_insert = gimple_copy (call);
3407
3408 gsi_insert_seq_on_edge (e, call_to_insert);
3409 *need_commit_edge_insert = true;
3410 call_to_insert = NULL;
3411 }
3412 }
3413 else
3414 {
3415 gimple_stmt_iterator gsi = gsi_for_stmt (use);
ba39c1d4 3416 if (store_p)
3417 gsi_replace (&gsi, call, true);
3418 else
3419 gsi_insert_before (&gsi, call, GSI_NEW_STMT);
c51887c5 3420 }
3421 }
3422
3423 SSA_NAME_IS_DEFAULT_DEF (poisoned_var) = true;
3424 SSA_NAME_DEF_STMT (poisoned_var) = gimple_build_nop ();
3425 gsi_replace (iter, poison_call, false);
3426
3427 return true;
3428}
3429
b92cccf4 3430/* Instrument the current function. */
3431
3432static unsigned int
3433asan_instrument (void)
3434{
5d5c682b 3435 if (shadow_ptr_types[0] == NULL_TREE)
55b58027 3436 asan_init_shadow_ptr_types ();
b92cccf4 3437 transform_statements ();
d08919a7 3438 last_alloca_addr = NULL_TREE;
b92cccf4 3439 return 0;
3440}
3441
3442static bool
3443gate_asan (void)
3444{
9917317a 3445 return sanitize_flags_p (SANITIZE_ADDRESS);
b92cccf4 3446}
3447
cbe8bda8 3448namespace {
3449
3450const pass_data pass_data_asan =
b92cccf4 3451{
cbe8bda8 3452 GIMPLE_PASS, /* type */
3453 "asan", /* name */
3454 OPTGROUP_NONE, /* optinfo_flags */
cbe8bda8 3455 TV_NONE, /* tv_id */
3456 ( PROP_ssa | PROP_cfg | PROP_gimple_leh ), /* properties_required */
3457 0, /* properties_provided */
3458 0, /* properties_destroyed */
3459 0, /* todo_flags_start */
8b88439e 3460 TODO_update_ssa, /* todo_flags_finish */
b92cccf4 3461};
5d5c682b 3462
cbe8bda8 3463class pass_asan : public gimple_opt_pass
3464{
3465public:
9af5ce0c 3466 pass_asan (gcc::context *ctxt)
3467 : gimple_opt_pass (pass_data_asan, ctxt)
cbe8bda8 3468 {}
3469
3470 /* opt_pass methods: */
ae84f584 3471 opt_pass * clone () { return new pass_asan (m_ctxt); }
31315c24 3472 virtual bool gate (function *) { return gate_asan (); }
65b0537f 3473 virtual unsigned int execute (function *) { return asan_instrument (); }
cbe8bda8 3474
3475}; // class pass_asan
3476
3477} // anon namespace
3478
3479gimple_opt_pass *
3480make_pass_asan (gcc::context *ctxt)
3481{
3482 return new pass_asan (ctxt);
3483}
3484
cbe8bda8 3485namespace {
3486
3487const pass_data pass_data_asan_O0 =
8293ee35 3488{
cbe8bda8 3489 GIMPLE_PASS, /* type */
3490 "asan0", /* name */
3491 OPTGROUP_NONE, /* optinfo_flags */
cbe8bda8 3492 TV_NONE, /* tv_id */
3493 ( PROP_ssa | PROP_cfg | PROP_gimple_leh ), /* properties_required */
3494 0, /* properties_provided */
3495 0, /* properties_destroyed */
3496 0, /* todo_flags_start */
8b88439e 3497 TODO_update_ssa, /* todo_flags_finish */
8293ee35 3498};
3499
cbe8bda8 3500class pass_asan_O0 : public gimple_opt_pass
3501{
3502public:
9af5ce0c 3503 pass_asan_O0 (gcc::context *ctxt)
3504 : gimple_opt_pass (pass_data_asan_O0, ctxt)
cbe8bda8 3505 {}
3506
3507 /* opt_pass methods: */
31315c24 3508 virtual bool gate (function *) { return !optimize && gate_asan (); }
65b0537f 3509 virtual unsigned int execute (function *) { return asan_instrument (); }
cbe8bda8 3510
3511}; // class pass_asan_O0
3512
3513} // anon namespace
3514
3515gimple_opt_pass *
3516make_pass_asan_O0 (gcc::context *ctxt)
3517{
3518 return new pass_asan_O0 (ctxt);
3519}
3520
5d5c682b 3521#include "gt-asan.h"