scsi: csiostor: enable PCIe relaxed ordering if supported
[linux/fpc-iii.git] / scripts / gcc-plugins / randomize_layout_plugin.c
blob0073af326449864b4da5f7a64677c0de2d5eafa2
1 /*
2 * Copyright 2014-2016 by Open Source Security, Inc., Brad Spengler <spender@grsecurity.net>
3 * and PaX Team <pageexec@freemail.hu>
4 * Licensed under the GPL v2
6 * Note: the choice of the license means that the compilation process is
7 * NOT 'eligible' as defined by gcc's library exception to the GPL v3,
8 * but for the kernel it doesn't matter since it doesn't link against
9 * any of the gcc libraries
11 * Usage:
12 * $ # for 4.5/4.6/C based 4.7
13 * $ gcc -I`gcc -print-file-name=plugin`/include -I`gcc -print-file-name=plugin`/include/c-family -fPIC -shared -O2 -o randomize_layout_plugin.so randomize_layout_plugin.c
14 * $ # for C++ based 4.7/4.8+
15 * $ g++ -I`g++ -print-file-name=plugin`/include -I`g++ -print-file-name=plugin`/include/c-family -fPIC -shared -O2 -o randomize_layout_plugin.so randomize_layout_plugin.c
16 * $ gcc -fplugin=./randomize_layout_plugin.so test.c -O2
19 #include "gcc-common.h"
20 #include "randomize_layout_seed.h"
22 #if BUILDING_GCC_MAJOR < 4 || (BUILDING_GCC_MAJOR == 4 && BUILDING_GCC_MINOR < 7)
23 #error "The RANDSTRUCT plugin requires GCC 4.7 or newer."
24 #endif
26 #define ORIG_TYPE_NAME(node) \
27 (TYPE_NAME(TYPE_MAIN_VARIANT(node)) != NULL_TREE ? ((const unsigned char *)IDENTIFIER_POINTER(TYPE_NAME(TYPE_MAIN_VARIANT(node)))) : (const unsigned char *)"anonymous")
29 #define INFORM(loc, msg, ...) inform(loc, "randstruct: " msg, ##__VA_ARGS__)
30 #define MISMATCH(loc, how, ...) INFORM(loc, "casting between randomized structure pointer types (" how "): %qT and %qT\n", __VA_ARGS__)
32 __visible int plugin_is_GPL_compatible;
34 static int performance_mode;
36 static struct plugin_info randomize_layout_plugin_info = {
37 .version = "201402201816vanilla",
38 .help = "disable\t\t\tdo not activate plugin\n"
39 "performance-mode\tenable cacheline-aware layout randomization\n"
42 struct whitelist_entry {
43 const char *pathname;
44 const char *lhs;
45 const char *rhs;
48 static const struct whitelist_entry whitelist[] = {
49 /* NIU overloads mapping with page struct */
50 { "drivers/net/ethernet/sun/niu.c", "page", "address_space" },
51 /* unix_skb_parms via UNIXCB() buffer */
52 { "net/unix/af_unix.c", "unix_skb_parms", "char" },
53 /* big_key payload.data struct splashing */
54 { "security/keys/big_key.c", "path", "void *" },
55 /* walk struct security_hook_heads as an array of struct list_head */
56 { "security/security.c", "list_head", "security_hook_heads" },
57 { }
60 /* from old Linux dcache.h */
61 static inline unsigned long
62 partial_name_hash(unsigned long c, unsigned long prevhash)
64 return (prevhash + (c << 4) + (c >> 4)) * 11;
66 static inline unsigned int
67 name_hash(const unsigned char *name)
69 unsigned long hash = 0;
70 unsigned int len = strlen((const char *)name);
71 while (len--)
72 hash = partial_name_hash(*name++, hash);
73 return (unsigned int)hash;
76 static tree handle_randomize_layout_attr(tree *node, tree name, tree args, int flags, bool *no_add_attrs)
78 tree type;
80 *no_add_attrs = true;
81 if (TREE_CODE(*node) == FUNCTION_DECL) {
82 error("%qE attribute does not apply to functions (%qF)", name, *node);
83 return NULL_TREE;
86 if (TREE_CODE(*node) == PARM_DECL) {
87 error("%qE attribute does not apply to function parameters (%qD)", name, *node);
88 return NULL_TREE;
91 if (TREE_CODE(*node) == VAR_DECL) {
92 error("%qE attribute does not apply to variables (%qD)", name, *node);
93 return NULL_TREE;
96 if (TYPE_P(*node)) {
97 type = *node;
98 } else {
99 gcc_assert(TREE_CODE(*node) == TYPE_DECL);
100 type = TREE_TYPE(*node);
103 if (TREE_CODE(type) != RECORD_TYPE) {
104 error("%qE attribute used on %qT applies to struct types only", name, type);
105 return NULL_TREE;
108 if (lookup_attribute(IDENTIFIER_POINTER(name), TYPE_ATTRIBUTES(type))) {
109 error("%qE attribute is already applied to the type %qT", name, type);
110 return NULL_TREE;
113 *no_add_attrs = false;
115 return NULL_TREE;
118 /* set on complete types that we don't need to inspect further at all */
119 static tree handle_randomize_considered_attr(tree *node, tree name, tree args, int flags, bool *no_add_attrs)
121 *no_add_attrs = false;
122 return NULL_TREE;
126 * set on types that we've performed a shuffle on, to prevent re-shuffling
127 * this does not preclude us from inspecting its fields for potential shuffles
129 static tree handle_randomize_performed_attr(tree *node, tree name, tree args, int flags, bool *no_add_attrs)
131 *no_add_attrs = false;
132 return NULL_TREE;
136 * 64bit variant of Bob Jenkins' public domain PRNG
137 * 256 bits of internal state
140 typedef unsigned long long u64;
142 typedef struct ranctx { u64 a; u64 b; u64 c; u64 d; } ranctx;
144 #define rot(x,k) (((x)<<(k))|((x)>>(64-(k))))
145 static u64 ranval(ranctx *x) {
146 u64 e = x->a - rot(x->b, 7);
147 x->a = x->b ^ rot(x->c, 13);
148 x->b = x->c + rot(x->d, 37);
149 x->c = x->d + e;
150 x->d = e + x->a;
151 return x->d;
154 static void raninit(ranctx *x, u64 *seed) {
155 int i;
157 x->a = seed[0];
158 x->b = seed[1];
159 x->c = seed[2];
160 x->d = seed[3];
162 for (i=0; i < 30; ++i)
163 (void)ranval(x);
166 static u64 shuffle_seed[4];
168 struct partition_group {
169 tree tree_start;
170 unsigned long start;
171 unsigned long length;
174 static void partition_struct(tree *fields, unsigned long length, struct partition_group *size_groups, unsigned long *num_groups)
176 unsigned long i;
177 unsigned long accum_size = 0;
178 unsigned long accum_length = 0;
179 unsigned long group_idx = 0;
181 gcc_assert(length < INT_MAX);
183 memset(size_groups, 0, sizeof(struct partition_group) * length);
185 for (i = 0; i < length; i++) {
186 if (size_groups[group_idx].tree_start == NULL_TREE) {
187 size_groups[group_idx].tree_start = fields[i];
188 size_groups[group_idx].start = i;
189 accum_length = 0;
190 accum_size = 0;
192 accum_size += (unsigned long)int_size_in_bytes(TREE_TYPE(fields[i]));
193 accum_length++;
194 if (accum_size >= 64) {
195 size_groups[group_idx].length = accum_length;
196 accum_length = 0;
197 group_idx++;
201 if (size_groups[group_idx].tree_start != NULL_TREE &&
202 !size_groups[group_idx].length) {
203 size_groups[group_idx].length = accum_length;
204 group_idx++;
207 *num_groups = group_idx;
210 static void performance_shuffle(tree *newtree, unsigned long length, ranctx *prng_state)
212 unsigned long i, x;
213 struct partition_group size_group[length];
214 unsigned long num_groups = 0;
215 unsigned long randnum;
217 partition_struct(newtree, length, (struct partition_group *)&size_group, &num_groups);
218 for (i = num_groups - 1; i > 0; i--) {
219 struct partition_group tmp;
220 randnum = ranval(prng_state) % (i + 1);
221 tmp = size_group[i];
222 size_group[i] = size_group[randnum];
223 size_group[randnum] = tmp;
226 for (x = 0; x < num_groups; x++) {
227 for (i = size_group[x].start + size_group[x].length - 1; i > size_group[x].start; i--) {
228 tree tmp;
229 if (DECL_BIT_FIELD_TYPE(newtree[i]))
230 continue;
231 randnum = ranval(prng_state) % (i + 1);
232 // we could handle this case differently if desired
233 if (DECL_BIT_FIELD_TYPE(newtree[randnum]))
234 continue;
235 tmp = newtree[i];
236 newtree[i] = newtree[randnum];
237 newtree[randnum] = tmp;
242 static void full_shuffle(tree *newtree, unsigned long length, ranctx *prng_state)
244 unsigned long i, randnum;
246 for (i = length - 1; i > 0; i--) {
247 tree tmp;
248 randnum = ranval(prng_state) % (i + 1);
249 tmp = newtree[i];
250 newtree[i] = newtree[randnum];
251 newtree[randnum] = tmp;
255 /* modern in-place Fisher-Yates shuffle */
256 static void shuffle(const_tree type, tree *newtree, unsigned long length)
258 unsigned long i;
259 u64 seed[4];
260 ranctx prng_state;
261 const unsigned char *structname;
263 if (length == 0)
264 return;
266 gcc_assert(TREE_CODE(type) == RECORD_TYPE);
268 structname = ORIG_TYPE_NAME(type);
270 #ifdef __DEBUG_PLUGIN
271 fprintf(stderr, "Shuffling struct %s %p\n", (const char *)structname, type);
272 #ifdef __DEBUG_VERBOSE
273 debug_tree((tree)type);
274 #endif
275 #endif
277 for (i = 0; i < 4; i++) {
278 seed[i] = shuffle_seed[i];
279 seed[i] ^= name_hash(structname);
282 raninit(&prng_state, (u64 *)&seed);
284 if (performance_mode)
285 performance_shuffle(newtree, length, &prng_state);
286 else
287 full_shuffle(newtree, length, &prng_state);
290 static bool is_flexible_array(const_tree field)
292 const_tree fieldtype;
293 const_tree typesize;
294 const_tree elemtype;
295 const_tree elemsize;
297 fieldtype = TREE_TYPE(field);
298 typesize = TYPE_SIZE(fieldtype);
300 if (TREE_CODE(fieldtype) != ARRAY_TYPE)
301 return false;
303 elemtype = TREE_TYPE(fieldtype);
304 elemsize = TYPE_SIZE(elemtype);
306 /* size of type is represented in bits */
308 if (typesize == NULL_TREE && TYPE_DOMAIN(fieldtype) != NULL_TREE &&
309 TYPE_MAX_VALUE(TYPE_DOMAIN(fieldtype)) == NULL_TREE)
310 return true;
312 if (typesize != NULL_TREE &&
313 (TREE_CONSTANT(typesize) && (!tree_to_uhwi(typesize) ||
314 tree_to_uhwi(typesize) == tree_to_uhwi(elemsize))))
315 return true;
317 return false;
320 static int relayout_struct(tree type)
322 unsigned long num_fields = (unsigned long)list_length(TYPE_FIELDS(type));
323 unsigned long shuffle_length = num_fields;
324 tree field;
325 tree newtree[num_fields];
326 unsigned long i;
327 tree list;
328 tree variant;
329 tree main_variant;
330 expanded_location xloc;
331 bool has_flexarray = false;
333 if (TYPE_FIELDS(type) == NULL_TREE)
334 return 0;
336 if (num_fields < 2)
337 return 0;
339 gcc_assert(TREE_CODE(type) == RECORD_TYPE);
341 gcc_assert(num_fields < INT_MAX);
343 if (lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(type)) ||
344 lookup_attribute("no_randomize_layout", TYPE_ATTRIBUTES(TYPE_MAIN_VARIANT(type))))
345 return 0;
347 /* Workaround for 3rd-party VirtualBox source that we can't modify ourselves */
348 if (!strcmp((const char *)ORIG_TYPE_NAME(type), "INTNETTRUNKFACTORY") ||
349 !strcmp((const char *)ORIG_TYPE_NAME(type), "RAWPCIFACTORY"))
350 return 0;
352 /* throw out any structs in uapi */
353 xloc = expand_location(DECL_SOURCE_LOCATION(TYPE_FIELDS(type)));
355 if (strstr(xloc.file, "/uapi/"))
356 error(G_("attempted to randomize userland API struct %s"), ORIG_TYPE_NAME(type));
358 for (field = TYPE_FIELDS(type), i = 0; field; field = TREE_CHAIN(field), i++) {
359 gcc_assert(TREE_CODE(field) == FIELD_DECL);
360 newtree[i] = field;
364 * enforce that we don't randomize the layout of the last
365 * element of a struct if it's a 0 or 1-length array
366 * or a proper flexible array
368 if (is_flexible_array(newtree[num_fields - 1])) {
369 has_flexarray = true;
370 shuffle_length--;
373 shuffle(type, (tree *)newtree, shuffle_length);
376 * set up a bogus anonymous struct field designed to error out on unnamed struct initializers
377 * as gcc provides no other way to detect such code
379 list = make_node(FIELD_DECL);
380 TREE_CHAIN(list) = newtree[0];
381 TREE_TYPE(list) = void_type_node;
382 DECL_SIZE(list) = bitsize_zero_node;
383 DECL_NONADDRESSABLE_P(list) = 1;
384 DECL_FIELD_BIT_OFFSET(list) = bitsize_zero_node;
385 DECL_SIZE_UNIT(list) = size_zero_node;
386 DECL_FIELD_OFFSET(list) = size_zero_node;
387 DECL_CONTEXT(list) = type;
388 // to satisfy the constify plugin
389 TREE_READONLY(list) = 1;
391 for (i = 0; i < num_fields - 1; i++)
392 TREE_CHAIN(newtree[i]) = newtree[i+1];
393 TREE_CHAIN(newtree[num_fields - 1]) = NULL_TREE;
395 main_variant = TYPE_MAIN_VARIANT(type);
396 for (variant = main_variant; variant; variant = TYPE_NEXT_VARIANT(variant)) {
397 TYPE_FIELDS(variant) = list;
398 TYPE_ATTRIBUTES(variant) = copy_list(TYPE_ATTRIBUTES(variant));
399 TYPE_ATTRIBUTES(variant) = tree_cons(get_identifier("randomize_performed"), NULL_TREE, TYPE_ATTRIBUTES(variant));
400 TYPE_ATTRIBUTES(variant) = tree_cons(get_identifier("designated_init"), NULL_TREE, TYPE_ATTRIBUTES(variant));
401 if (has_flexarray)
402 TYPE_ATTRIBUTES(type) = tree_cons(get_identifier("has_flexarray"), NULL_TREE, TYPE_ATTRIBUTES(type));
406 * force a re-layout of the main variant
407 * the TYPE_SIZE for all variants will be recomputed
408 * by finalize_type_size()
410 TYPE_SIZE(main_variant) = NULL_TREE;
411 layout_type(main_variant);
412 gcc_assert(TYPE_SIZE(main_variant) != NULL_TREE);
414 return 1;
417 /* from constify plugin */
418 static const_tree get_field_type(const_tree field)
420 return strip_array_types(TREE_TYPE(field));
423 /* from constify plugin */
424 static bool is_fptr(const_tree fieldtype)
426 if (TREE_CODE(fieldtype) != POINTER_TYPE)
427 return false;
429 return TREE_CODE(TREE_TYPE(fieldtype)) == FUNCTION_TYPE;
432 /* derived from constify plugin */
433 static int is_pure_ops_struct(const_tree node)
435 const_tree field;
437 gcc_assert(TREE_CODE(node) == RECORD_TYPE || TREE_CODE(node) == UNION_TYPE);
439 for (field = TYPE_FIELDS(node); field; field = TREE_CHAIN(field)) {
440 const_tree fieldtype = get_field_type(field);
441 enum tree_code code = TREE_CODE(fieldtype);
443 if (node == fieldtype)
444 continue;
446 if (!is_fptr(fieldtype))
447 return 0;
449 if (code != RECORD_TYPE && code != UNION_TYPE)
450 continue;
452 if (!is_pure_ops_struct(fieldtype))
453 return 0;
456 return 1;
459 static void randomize_type(tree type)
461 tree variant;
463 gcc_assert(TREE_CODE(type) == RECORD_TYPE);
465 if (lookup_attribute("randomize_considered", TYPE_ATTRIBUTES(type)))
466 return;
468 if (lookup_attribute("randomize_layout", TYPE_ATTRIBUTES(TYPE_MAIN_VARIANT(type))) || is_pure_ops_struct(type))
469 relayout_struct(type);
471 for (variant = TYPE_MAIN_VARIANT(type); variant; variant = TYPE_NEXT_VARIANT(variant)) {
472 TYPE_ATTRIBUTES(type) = copy_list(TYPE_ATTRIBUTES(type));
473 TYPE_ATTRIBUTES(type) = tree_cons(get_identifier("randomize_considered"), NULL_TREE, TYPE_ATTRIBUTES(type));
475 #ifdef __DEBUG_PLUGIN
476 fprintf(stderr, "Marking randomize_considered on struct %s\n", ORIG_TYPE_NAME(type));
477 #ifdef __DEBUG_VERBOSE
478 debug_tree(type);
479 #endif
480 #endif
483 static void update_decl_size(tree decl)
485 tree lastval, lastidx, field, init, type, flexsize;
486 unsigned HOST_WIDE_INT len;
488 type = TREE_TYPE(decl);
490 if (!lookup_attribute("has_flexarray", TYPE_ATTRIBUTES(type)))
491 return;
493 init = DECL_INITIAL(decl);
494 if (init == NULL_TREE || init == error_mark_node)
495 return;
497 if (TREE_CODE(init) != CONSTRUCTOR)
498 return;
500 len = CONSTRUCTOR_NELTS(init);
501 if (!len)
502 return;
504 lastval = CONSTRUCTOR_ELT(init, CONSTRUCTOR_NELTS(init) - 1)->value;
505 lastidx = CONSTRUCTOR_ELT(init, CONSTRUCTOR_NELTS(init) - 1)->index;
507 for (field = TYPE_FIELDS(TREE_TYPE(decl)); TREE_CHAIN(field); field = TREE_CHAIN(field))
510 if (lastidx != field)
511 return;
513 if (TREE_CODE(lastval) != STRING_CST) {
514 error("Only string constants are supported as initializers "
515 "for randomized structures with flexible arrays");
516 return;
519 flexsize = bitsize_int(TREE_STRING_LENGTH(lastval) *
520 tree_to_uhwi(TYPE_SIZE(TREE_TYPE(TREE_TYPE(lastval)))));
522 DECL_SIZE(decl) = size_binop(PLUS_EXPR, TYPE_SIZE(type), flexsize);
524 return;
528 static void randomize_layout_finish_decl(void *event_data, void *data)
530 tree decl = (tree)event_data;
531 tree type;
533 if (decl == NULL_TREE || decl == error_mark_node)
534 return;
536 type = TREE_TYPE(decl);
538 if (TREE_CODE(decl) != VAR_DECL)
539 return;
541 if (TREE_CODE(type) != RECORD_TYPE && TREE_CODE(type) != UNION_TYPE)
542 return;
544 if (!lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(type)))
545 return;
547 DECL_SIZE(decl) = 0;
548 DECL_SIZE_UNIT(decl) = 0;
549 SET_DECL_ALIGN(decl, 0);
550 SET_DECL_MODE (decl, VOIDmode);
551 SET_DECL_RTL(decl, 0);
552 update_decl_size(decl);
553 layout_decl(decl, 0);
556 static void finish_type(void *event_data, void *data)
558 tree type = (tree)event_data;
560 if (type == NULL_TREE || type == error_mark_node)
561 return;
563 if (TREE_CODE(type) != RECORD_TYPE)
564 return;
566 if (TYPE_FIELDS(type) == NULL_TREE)
567 return;
569 if (lookup_attribute("randomize_considered", TYPE_ATTRIBUTES(type)))
570 return;
572 #ifdef __DEBUG_PLUGIN
573 fprintf(stderr, "Calling randomize_type on %s\n", ORIG_TYPE_NAME(type));
574 #endif
575 #ifdef __DEBUG_VERBOSE
576 debug_tree(type);
577 #endif
578 randomize_type(type);
580 return;
583 static struct attribute_spec randomize_layout_attr = {
584 .name = "randomize_layout",
585 // related to args
586 .min_length = 0,
587 .max_length = 0,
588 .decl_required = false,
589 // need type declaration
590 .type_required = true,
591 .function_type_required = false,
592 .handler = handle_randomize_layout_attr,
593 #if BUILDING_GCC_VERSION >= 4007
594 .affects_type_identity = true
595 #endif
598 static struct attribute_spec no_randomize_layout_attr = {
599 .name = "no_randomize_layout",
600 // related to args
601 .min_length = 0,
602 .max_length = 0,
603 .decl_required = false,
604 // need type declaration
605 .type_required = true,
606 .function_type_required = false,
607 .handler = handle_randomize_layout_attr,
608 #if BUILDING_GCC_VERSION >= 4007
609 .affects_type_identity = true
610 #endif
613 static struct attribute_spec randomize_considered_attr = {
614 .name = "randomize_considered",
615 // related to args
616 .min_length = 0,
617 .max_length = 0,
618 .decl_required = false,
619 // need type declaration
620 .type_required = true,
621 .function_type_required = false,
622 .handler = handle_randomize_considered_attr,
623 #if BUILDING_GCC_VERSION >= 4007
624 .affects_type_identity = false
625 #endif
628 static struct attribute_spec randomize_performed_attr = {
629 .name = "randomize_performed",
630 // related to args
631 .min_length = 0,
632 .max_length = 0,
633 .decl_required = false,
634 // need type declaration
635 .type_required = true,
636 .function_type_required = false,
637 .handler = handle_randomize_performed_attr,
638 #if BUILDING_GCC_VERSION >= 4007
639 .affects_type_identity = false
640 #endif
643 static void register_attributes(void *event_data, void *data)
645 register_attribute(&randomize_layout_attr);
646 register_attribute(&no_randomize_layout_attr);
647 register_attribute(&randomize_considered_attr);
648 register_attribute(&randomize_performed_attr);
651 static void check_bad_casts_in_constructor(tree var, tree init)
653 unsigned HOST_WIDE_INT idx;
654 tree field, val;
655 tree field_type, val_type;
657 FOR_EACH_CONSTRUCTOR_ELT(CONSTRUCTOR_ELTS(init), idx, field, val) {
658 if (TREE_CODE(val) == CONSTRUCTOR) {
659 check_bad_casts_in_constructor(var, val);
660 continue;
663 /* pipacs' plugin creates franken-arrays that differ from those produced by
664 normal code which all have valid 'field' trees. work around this */
665 if (field == NULL_TREE)
666 continue;
667 field_type = TREE_TYPE(field);
668 val_type = TREE_TYPE(val);
670 if (TREE_CODE(field_type) != POINTER_TYPE || TREE_CODE(val_type) != POINTER_TYPE)
671 continue;
673 if (field_type == val_type)
674 continue;
676 field_type = TYPE_MAIN_VARIANT(strip_array_types(TYPE_MAIN_VARIANT(TREE_TYPE(field_type))));
677 val_type = TYPE_MAIN_VARIANT(strip_array_types(TYPE_MAIN_VARIANT(TREE_TYPE(val_type))));
679 if (field_type == void_type_node)
680 continue;
681 if (field_type == val_type)
682 continue;
683 if (TREE_CODE(val_type) != RECORD_TYPE)
684 continue;
686 if (!lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(val_type)))
687 continue;
688 MISMATCH(DECL_SOURCE_LOCATION(var), "constructor\n", TYPE_MAIN_VARIANT(field_type), TYPE_MAIN_VARIANT(val_type));
692 /* derived from the constify plugin */
693 static void check_global_variables(void *event_data, void *data)
695 struct varpool_node *node;
696 tree init;
698 FOR_EACH_VARIABLE(node) {
699 tree var = NODE_DECL(node);
700 init = DECL_INITIAL(var);
701 if (init == NULL_TREE)
702 continue;
704 if (TREE_CODE(init) != CONSTRUCTOR)
705 continue;
707 check_bad_casts_in_constructor(var, init);
711 static bool dominated_by_is_err(const_tree rhs, basic_block bb)
713 basic_block dom;
714 gimple dom_stmt;
715 gimple call_stmt;
716 const_tree dom_lhs;
717 const_tree poss_is_err_cond;
718 const_tree poss_is_err_func;
719 const_tree is_err_arg;
721 dom = get_immediate_dominator(CDI_DOMINATORS, bb);
722 if (!dom)
723 return false;
725 dom_stmt = last_stmt(dom);
726 if (!dom_stmt)
727 return false;
729 if (gimple_code(dom_stmt) != GIMPLE_COND)
730 return false;
732 if (gimple_cond_code(dom_stmt) != NE_EXPR)
733 return false;
735 if (!integer_zerop(gimple_cond_rhs(dom_stmt)))
736 return false;
738 poss_is_err_cond = gimple_cond_lhs(dom_stmt);
740 if (TREE_CODE(poss_is_err_cond) != SSA_NAME)
741 return false;
743 call_stmt = SSA_NAME_DEF_STMT(poss_is_err_cond);
745 if (gimple_code(call_stmt) != GIMPLE_CALL)
746 return false;
748 dom_lhs = gimple_get_lhs(call_stmt);
749 poss_is_err_func = gimple_call_fndecl(call_stmt);
750 if (!poss_is_err_func)
751 return false;
752 if (dom_lhs != poss_is_err_cond)
753 return false;
754 if (strcmp(DECL_NAME_POINTER(poss_is_err_func), "IS_ERR"))
755 return false;
757 is_err_arg = gimple_call_arg(call_stmt, 0);
758 if (!is_err_arg)
759 return false;
761 if (is_err_arg != rhs)
762 return false;
764 return true;
767 static void handle_local_var_initializers(void)
769 tree var;
770 unsigned int i;
772 FOR_EACH_LOCAL_DECL(cfun, i, var) {
773 tree init = DECL_INITIAL(var);
774 if (!init)
775 continue;
776 if (TREE_CODE(init) != CONSTRUCTOR)
777 continue;
778 check_bad_casts_in_constructor(var, init);
782 static bool type_name_eq(gimple stmt, const_tree type_tree, const char *wanted_name)
784 const char *type_name;
786 if (type_tree == NULL_TREE)
787 return false;
789 switch (TREE_CODE(type_tree)) {
790 case RECORD_TYPE:
791 type_name = TYPE_NAME_POINTER(type_tree);
792 break;
793 case INTEGER_TYPE:
794 if (TYPE_PRECISION(type_tree) == CHAR_TYPE_SIZE)
795 type_name = "char";
796 else {
797 INFORM(gimple_location(stmt), "found non-char INTEGER_TYPE cast comparison: %qT\n", type_tree);
798 debug_tree(type_tree);
799 return false;
801 break;
802 case POINTER_TYPE:
803 if (TREE_CODE(TREE_TYPE(type_tree)) == VOID_TYPE) {
804 type_name = "void *";
805 break;
806 } else {
807 INFORM(gimple_location(stmt), "found non-void POINTER_TYPE cast comparison %qT\n", type_tree);
808 debug_tree(type_tree);
809 return false;
811 default:
812 INFORM(gimple_location(stmt), "unhandled cast comparison: %qT\n", type_tree);
813 debug_tree(type_tree);
814 return false;
817 return strcmp(type_name, wanted_name) == 0;
820 static bool whitelisted_cast(gimple stmt, const_tree lhs_tree, const_tree rhs_tree)
822 const struct whitelist_entry *entry;
823 expanded_location xloc = expand_location(gimple_location(stmt));
825 for (entry = whitelist; entry->pathname; entry++) {
826 if (!strstr(xloc.file, entry->pathname))
827 continue;
829 if (type_name_eq(stmt, lhs_tree, entry->lhs) && type_name_eq(stmt, rhs_tree, entry->rhs))
830 return true;
833 return false;
837 * iterate over all statements to find "bad" casts:
838 * those where the address of the start of a structure is cast
839 * to a pointer of a structure of a different type, or a
840 * structure pointer type is cast to a different structure pointer type
842 static unsigned int find_bad_casts_execute(void)
844 basic_block bb;
846 handle_local_var_initializers();
848 FOR_EACH_BB_FN(bb, cfun) {
849 gimple_stmt_iterator gsi;
851 for (gsi = gsi_start_bb(bb); !gsi_end_p(gsi); gsi_next(&gsi)) {
852 gimple stmt;
853 const_tree lhs;
854 const_tree lhs_type;
855 const_tree rhs1;
856 const_tree rhs_type;
857 const_tree ptr_lhs_type;
858 const_tree ptr_rhs_type;
859 const_tree op0;
860 const_tree op0_type;
861 enum tree_code rhs_code;
863 stmt = gsi_stmt(gsi);
865 #ifdef __DEBUG_PLUGIN
866 #ifdef __DEBUG_VERBOSE
867 debug_gimple_stmt(stmt);
868 debug_tree(gimple_get_lhs(stmt));
869 #endif
870 #endif
872 if (gimple_code(stmt) != GIMPLE_ASSIGN)
873 continue;
875 #ifdef __DEBUG_PLUGIN
876 #ifdef __DEBUG_VERBOSE
877 debug_tree(gimple_assign_rhs1(stmt));
878 #endif
879 #endif
882 rhs_code = gimple_assign_rhs_code(stmt);
884 if (rhs_code != ADDR_EXPR && rhs_code != SSA_NAME)
885 continue;
887 lhs = gimple_get_lhs(stmt);
888 lhs_type = TREE_TYPE(lhs);
889 rhs1 = gimple_assign_rhs1(stmt);
890 rhs_type = TREE_TYPE(rhs1);
892 if (TREE_CODE(rhs_type) != POINTER_TYPE ||
893 TREE_CODE(lhs_type) != POINTER_TYPE)
894 continue;
896 ptr_lhs_type = TYPE_MAIN_VARIANT(strip_array_types(TYPE_MAIN_VARIANT(TREE_TYPE(lhs_type))));
897 ptr_rhs_type = TYPE_MAIN_VARIANT(strip_array_types(TYPE_MAIN_VARIANT(TREE_TYPE(rhs_type))));
899 if (ptr_rhs_type == void_type_node)
900 continue;
902 if (ptr_lhs_type == void_type_node)
903 continue;
905 if (dominated_by_is_err(rhs1, bb))
906 continue;
908 if (TREE_CODE(ptr_rhs_type) != RECORD_TYPE) {
909 #ifndef __DEBUG_PLUGIN
910 if (lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(ptr_lhs_type)))
911 #endif
913 if (!whitelisted_cast(stmt, ptr_lhs_type, ptr_rhs_type))
914 MISMATCH(gimple_location(stmt), "rhs", ptr_lhs_type, ptr_rhs_type);
916 continue;
919 if (rhs_code == SSA_NAME && ptr_lhs_type == ptr_rhs_type)
920 continue;
922 if (rhs_code == ADDR_EXPR) {
923 op0 = TREE_OPERAND(rhs1, 0);
925 if (op0 == NULL_TREE)
926 continue;
928 if (TREE_CODE(op0) != VAR_DECL)
929 continue;
931 op0_type = TYPE_MAIN_VARIANT(strip_array_types(TYPE_MAIN_VARIANT(TREE_TYPE(op0))));
932 if (op0_type == ptr_lhs_type)
933 continue;
935 #ifndef __DEBUG_PLUGIN
936 if (lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(op0_type)))
937 #endif
939 if (!whitelisted_cast(stmt, ptr_lhs_type, op0_type))
940 MISMATCH(gimple_location(stmt), "op0", ptr_lhs_type, op0_type);
942 } else {
943 const_tree ssa_name_var = SSA_NAME_VAR(rhs1);
944 /* skip bogus type casts introduced by container_of */
945 if (ssa_name_var != NULL_TREE && DECL_NAME(ssa_name_var) &&
946 !strcmp((const char *)DECL_NAME_POINTER(ssa_name_var), "__mptr"))
947 continue;
948 #ifndef __DEBUG_PLUGIN
949 if (lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(ptr_rhs_type)))
950 #endif
952 if (!whitelisted_cast(stmt, ptr_lhs_type, ptr_rhs_type))
953 MISMATCH(gimple_location(stmt), "ssa", ptr_lhs_type, ptr_rhs_type);
959 return 0;
962 #define PASS_NAME find_bad_casts
963 #define NO_GATE
964 #define TODO_FLAGS_FINISH TODO_dump_func
965 #include "gcc-generate-gimple-pass.h"
967 __visible int plugin_init(struct plugin_name_args *plugin_info, struct plugin_gcc_version *version)
969 int i;
970 const char * const plugin_name = plugin_info->base_name;
971 const int argc = plugin_info->argc;
972 const struct plugin_argument * const argv = plugin_info->argv;
973 bool enable = true;
974 int obtained_seed = 0;
975 struct register_pass_info find_bad_casts_pass_info;
977 find_bad_casts_pass_info.pass = make_find_bad_casts_pass();
978 find_bad_casts_pass_info.reference_pass_name = "ssa";
979 find_bad_casts_pass_info.ref_pass_instance_number = 1;
980 find_bad_casts_pass_info.pos_op = PASS_POS_INSERT_AFTER;
982 if (!plugin_default_version_check(version, &gcc_version)) {
983 error(G_("incompatible gcc/plugin versions"));
984 return 1;
987 if (strncmp(lang_hooks.name, "GNU C", 5) && !strncmp(lang_hooks.name, "GNU C+", 6)) {
988 inform(UNKNOWN_LOCATION, G_("%s supports C only, not %s"), plugin_name, lang_hooks.name);
989 enable = false;
992 for (i = 0; i < argc; ++i) {
993 if (!strcmp(argv[i].key, "disable")) {
994 enable = false;
995 continue;
997 if (!strcmp(argv[i].key, "performance-mode")) {
998 performance_mode = 1;
999 continue;
1001 error(G_("unknown option '-fplugin-arg-%s-%s'"), plugin_name, argv[i].key);
1004 if (strlen(randstruct_seed) != 64) {
1005 error(G_("invalid seed value supplied for %s plugin"), plugin_name);
1006 return 1;
1008 obtained_seed = sscanf(randstruct_seed, "%016llx%016llx%016llx%016llx",
1009 &shuffle_seed[0], &shuffle_seed[1], &shuffle_seed[2], &shuffle_seed[3]);
1010 if (obtained_seed != 4) {
1011 error(G_("Invalid seed supplied for %s plugin"), plugin_name);
1012 return 1;
1015 register_callback(plugin_name, PLUGIN_INFO, NULL, &randomize_layout_plugin_info);
1016 if (enable) {
1017 register_callback(plugin_name, PLUGIN_ALL_IPA_PASSES_START, check_global_variables, NULL);
1018 register_callback(plugin_name, PLUGIN_PASS_MANAGER_SETUP, NULL, &find_bad_casts_pass_info);
1019 register_callback(plugin_name, PLUGIN_FINISH_TYPE, finish_type, NULL);
1020 register_callback(plugin_name, PLUGIN_FINISH_DECL, randomize_layout_finish_decl, NULL);
1022 register_callback(plugin_name, PLUGIN_ATTRIBUTES, register_attributes, NULL);
1024 return 0;