Back to home page

OSCL-LXR

 
 

    


0001 /*
0002  * Copyright 2014-2016 by Open Source Security, Inc., Brad Spengler <spender@grsecurity.net>
0003  *                   and PaX Team <pageexec@freemail.hu>
0004  * Licensed under the GPL v2
0005  *
0006  * Note: the choice of the license means that the compilation process is
0007  *       NOT 'eligible' as defined by gcc's library exception to the GPL v3,
0008  *       but for the kernel it doesn't matter since it doesn't link against
0009  *       any of the gcc libraries
0010  *
0011  * Usage:
0012  * $ # for 4.5/4.6/C based 4.7
0013  * $ 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
0014  * $ # for C++ based 4.7/4.8+
0015  * $ 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
0016  * $ gcc -fplugin=./randomize_layout_plugin.so test.c -O2
0017  */
0018 
0019 #include "gcc-common.h"
0020 #include "randomize_layout_seed.h"
0021 
0022 #if BUILDING_GCC_MAJOR < 4 || (BUILDING_GCC_MAJOR == 4 && BUILDING_GCC_MINOR < 7)
0023 #error "The RANDSTRUCT plugin requires GCC 4.7 or newer."
0024 #endif
0025 
0026 #define ORIG_TYPE_NAME(node) \
0027     (TYPE_NAME(TYPE_MAIN_VARIANT(node)) != NULL_TREE ? ((const unsigned char *)IDENTIFIER_POINTER(TYPE_NAME(TYPE_MAIN_VARIANT(node)))) : (const unsigned char *)"anonymous")
0028 
0029 #define INFORM(loc, msg, ...)   inform(loc, "randstruct: " msg, ##__VA_ARGS__)
0030 #define MISMATCH(loc, how, ...) INFORM(loc, "casting between randomized structure pointer types (" how "): %qT and %qT\n", __VA_ARGS__)
0031 
0032 __visible int plugin_is_GPL_compatible;
0033 
0034 static int performance_mode;
0035 
0036 static struct plugin_info randomize_layout_plugin_info = {
0037     .version    = PLUGIN_VERSION,
0038     .help       = "disable\t\t\tdo not activate plugin\n"
0039               "performance-mode\tenable cacheline-aware layout randomization\n"
0040 };
0041 
0042 /* from old Linux dcache.h */
0043 static inline unsigned long
0044 partial_name_hash(unsigned long c, unsigned long prevhash)
0045 {
0046     return (prevhash + (c << 4) + (c >> 4)) * 11;
0047 }
0048 static inline unsigned int
0049 name_hash(const unsigned char *name)
0050 {
0051     unsigned long hash = 0;
0052     unsigned int len = strlen((const char *)name);
0053     while (len--)
0054         hash = partial_name_hash(*name++, hash);
0055     return (unsigned int)hash;
0056 }
0057 
0058 static tree handle_randomize_layout_attr(tree *node, tree name, tree args, int flags, bool *no_add_attrs)
0059 {
0060     tree type;
0061 
0062     *no_add_attrs = true;
0063     if (TREE_CODE(*node) == FUNCTION_DECL) {
0064         error("%qE attribute does not apply to functions (%qF)", name, *node);
0065         return NULL_TREE;
0066     }
0067 
0068     if (TREE_CODE(*node) == PARM_DECL) {
0069         error("%qE attribute does not apply to function parameters (%qD)", name, *node);
0070         return NULL_TREE;
0071     }
0072 
0073     if (TREE_CODE(*node) == VAR_DECL) {
0074         error("%qE attribute does not apply to variables (%qD)", name, *node);
0075         return NULL_TREE;
0076     }
0077 
0078     if (TYPE_P(*node)) {
0079         type = *node;
0080     } else {
0081         gcc_assert(TREE_CODE(*node) == TYPE_DECL);
0082         type = TREE_TYPE(*node);
0083     }
0084 
0085     if (TREE_CODE(type) != RECORD_TYPE) {
0086         error("%qE attribute used on %qT applies to struct types only", name, type);
0087         return NULL_TREE;
0088     }
0089 
0090     if (lookup_attribute(IDENTIFIER_POINTER(name), TYPE_ATTRIBUTES(type))) {
0091         error("%qE attribute is already applied to the type %qT", name, type);
0092         return NULL_TREE;
0093     }
0094 
0095     *no_add_attrs = false;
0096 
0097     return NULL_TREE;
0098 }
0099 
0100 /* set on complete types that we don't need to inspect further at all */
0101 static tree handle_randomize_considered_attr(tree *node, tree name, tree args, int flags, bool *no_add_attrs)
0102 {
0103     *no_add_attrs = false;
0104     return NULL_TREE;
0105 }
0106 
0107 /*
0108  * set on types that we've performed a shuffle on, to prevent re-shuffling
0109  * this does not preclude us from inspecting its fields for potential shuffles
0110  */
0111 static tree handle_randomize_performed_attr(tree *node, tree name, tree args, int flags, bool *no_add_attrs)
0112 {
0113     *no_add_attrs = false;
0114     return NULL_TREE;
0115 }
0116 
0117 /*
0118  * 64bit variant of Bob Jenkins' public domain PRNG
0119  * 256 bits of internal state
0120  */
0121 
0122 typedef unsigned long long u64;
0123 
0124 typedef struct ranctx { u64 a; u64 b; u64 c; u64 d; } ranctx;
0125 
0126 #define rot(x,k) (((x)<<(k))|((x)>>(64-(k))))
0127 static u64 ranval(ranctx *x) {
0128     u64 e = x->a - rot(x->b, 7);
0129     x->a = x->b ^ rot(x->c, 13);
0130     x->b = x->c + rot(x->d, 37);
0131     x->c = x->d + e;
0132     x->d = e + x->a;
0133     return x->d;
0134 }
0135 
0136 static void raninit(ranctx *x, u64 *seed) {
0137     int i;
0138 
0139     x->a = seed[0];
0140     x->b = seed[1];
0141     x->c = seed[2];
0142     x->d = seed[3];
0143 
0144     for (i=0; i < 30; ++i)
0145         (void)ranval(x);
0146 }
0147 
0148 static u64 shuffle_seed[4];
0149 
0150 struct partition_group {
0151     tree tree_start;
0152     unsigned long start;
0153     unsigned long length;
0154 };
0155 
0156 static void partition_struct(tree *fields, unsigned long length, struct partition_group *size_groups, unsigned long *num_groups)
0157 {
0158     unsigned long i;
0159     unsigned long accum_size = 0;
0160     unsigned long accum_length = 0;
0161     unsigned long group_idx = 0;
0162 
0163     gcc_assert(length < INT_MAX);
0164 
0165     memset(size_groups, 0, sizeof(struct partition_group) * length);
0166 
0167     for (i = 0; i < length; i++) {
0168         if (size_groups[group_idx].tree_start == NULL_TREE) {
0169             size_groups[group_idx].tree_start = fields[i];
0170             size_groups[group_idx].start = i;
0171             accum_length = 0;
0172             accum_size = 0;
0173         }
0174         accum_size += (unsigned long)int_size_in_bytes(TREE_TYPE(fields[i]));
0175         accum_length++;
0176         if (accum_size >= 64) {
0177             size_groups[group_idx].length = accum_length;
0178             accum_length = 0;
0179             group_idx++;
0180         }
0181     }
0182 
0183     if (size_groups[group_idx].tree_start != NULL_TREE &&
0184         !size_groups[group_idx].length) {
0185         size_groups[group_idx].length = accum_length;
0186         group_idx++;
0187     }
0188 
0189     *num_groups = group_idx;
0190 }
0191 
0192 static void performance_shuffle(tree *newtree, unsigned long length, ranctx *prng_state)
0193 {
0194     unsigned long i, x;
0195     struct partition_group size_group[length];
0196     unsigned long num_groups = 0;
0197     unsigned long randnum;
0198 
0199     partition_struct(newtree, length, (struct partition_group *)&size_group, &num_groups);
0200     for (i = num_groups - 1; i > 0; i--) {
0201         struct partition_group tmp;
0202         randnum = ranval(prng_state) % (i + 1);
0203         tmp = size_group[i];
0204         size_group[i] = size_group[randnum];
0205         size_group[randnum] = tmp;
0206     }
0207 
0208     for (x = 0; x < num_groups; x++) {
0209         for (i = size_group[x].start + size_group[x].length - 1; i > size_group[x].start; i--) {
0210             tree tmp;
0211             if (DECL_BIT_FIELD_TYPE(newtree[i]))
0212                 continue;
0213             randnum = ranval(prng_state) % (i + 1);
0214             // we could handle this case differently if desired
0215             if (DECL_BIT_FIELD_TYPE(newtree[randnum]))
0216                 continue;
0217             tmp = newtree[i];
0218             newtree[i] = newtree[randnum];
0219             newtree[randnum] = tmp;
0220         }
0221     }
0222 }
0223 
0224 static void full_shuffle(tree *newtree, unsigned long length, ranctx *prng_state)
0225 {
0226     unsigned long i, randnum;
0227 
0228     for (i = length - 1; i > 0; i--) {
0229         tree tmp;
0230         randnum = ranval(prng_state) % (i + 1);
0231         tmp = newtree[i];
0232         newtree[i] = newtree[randnum];
0233         newtree[randnum] = tmp;
0234     }
0235 }
0236 
0237 /* modern in-place Fisher-Yates shuffle */
0238 static void shuffle(const_tree type, tree *newtree, unsigned long length)
0239 {
0240     unsigned long i;
0241     u64 seed[4];
0242     ranctx prng_state;
0243     const unsigned char *structname;
0244 
0245     if (length == 0)
0246         return;
0247 
0248     gcc_assert(TREE_CODE(type) == RECORD_TYPE);
0249 
0250     structname = ORIG_TYPE_NAME(type);
0251 
0252 #ifdef __DEBUG_PLUGIN
0253     fprintf(stderr, "Shuffling struct %s %p\n", (const char *)structname, type);
0254 #ifdef __DEBUG_VERBOSE
0255     debug_tree((tree)type);
0256 #endif
0257 #endif
0258 
0259     for (i = 0; i < 4; i++) {
0260         seed[i] = shuffle_seed[i];
0261         seed[i] ^= name_hash(structname);
0262     }
0263 
0264     raninit(&prng_state, (u64 *)&seed);
0265 
0266     if (performance_mode)
0267         performance_shuffle(newtree, length, &prng_state);
0268     else
0269         full_shuffle(newtree, length, &prng_state);
0270 }
0271 
0272 static bool is_flexible_array(const_tree field)
0273 {
0274     const_tree fieldtype;
0275     const_tree typesize;
0276     const_tree elemtype;
0277     const_tree elemsize;
0278 
0279     fieldtype = TREE_TYPE(field);
0280     typesize = TYPE_SIZE(fieldtype);
0281 
0282     if (TREE_CODE(fieldtype) != ARRAY_TYPE)
0283         return false;
0284 
0285     elemtype = TREE_TYPE(fieldtype);
0286     elemsize = TYPE_SIZE(elemtype);
0287 
0288     /* size of type is represented in bits */
0289 
0290     if (typesize == NULL_TREE && TYPE_DOMAIN(fieldtype) != NULL_TREE &&
0291         TYPE_MAX_VALUE(TYPE_DOMAIN(fieldtype)) == NULL_TREE)
0292         return true;
0293 
0294     if (typesize != NULL_TREE &&
0295         (TREE_CONSTANT(typesize) && (!tree_to_uhwi(typesize) ||
0296          tree_to_uhwi(typesize) == tree_to_uhwi(elemsize))))
0297         return true;
0298 
0299     return false;
0300 }
0301 
0302 static int relayout_struct(tree type)
0303 {
0304     unsigned long num_fields = (unsigned long)list_length(TYPE_FIELDS(type));
0305     unsigned long shuffle_length = num_fields;
0306     tree field;
0307     tree newtree[num_fields];
0308     unsigned long i;
0309     tree list;
0310     tree variant;
0311     tree main_variant;
0312     expanded_location xloc;
0313     bool has_flexarray = false;
0314 
0315     if (TYPE_FIELDS(type) == NULL_TREE)
0316         return 0;
0317 
0318     if (num_fields < 2)
0319         return 0;
0320 
0321     gcc_assert(TREE_CODE(type) == RECORD_TYPE);
0322 
0323     gcc_assert(num_fields < INT_MAX);
0324 
0325     if (lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(type)) ||
0326         lookup_attribute("no_randomize_layout", TYPE_ATTRIBUTES(TYPE_MAIN_VARIANT(type))))
0327         return 0;
0328 
0329     /* Workaround for 3rd-party VirtualBox source that we can't modify ourselves */
0330     if (!strcmp((const char *)ORIG_TYPE_NAME(type), "INTNETTRUNKFACTORY") ||
0331         !strcmp((const char *)ORIG_TYPE_NAME(type), "RAWPCIFACTORY"))
0332         return 0;
0333 
0334     /* throw out any structs in uapi */
0335     xloc = expand_location(DECL_SOURCE_LOCATION(TYPE_FIELDS(type)));
0336 
0337     if (strstr(xloc.file, "/uapi/"))
0338         error(G_("attempted to randomize userland API struct %s"), ORIG_TYPE_NAME(type));
0339 
0340     for (field = TYPE_FIELDS(type), i = 0; field; field = TREE_CHAIN(field), i++) {
0341         gcc_assert(TREE_CODE(field) == FIELD_DECL);
0342         newtree[i] = field;
0343     }
0344 
0345     /*
0346      * enforce that we don't randomize the layout of the last
0347      * element of a struct if it's a 0 or 1-length array
0348      * or a proper flexible array
0349      */
0350     if (is_flexible_array(newtree[num_fields - 1])) {
0351         has_flexarray = true;
0352         shuffle_length--;
0353     }
0354 
0355     shuffle(type, (tree *)newtree, shuffle_length);
0356 
0357     /*
0358      * set up a bogus anonymous struct field designed to error out on unnamed struct initializers
0359      * as gcc provides no other way to detect such code
0360      */
0361     list = make_node(FIELD_DECL);
0362     TREE_CHAIN(list) = newtree[0];
0363     TREE_TYPE(list) = void_type_node;
0364     DECL_SIZE(list) = bitsize_zero_node;
0365     DECL_NONADDRESSABLE_P(list) = 1;
0366     DECL_FIELD_BIT_OFFSET(list) = bitsize_zero_node;
0367     DECL_SIZE_UNIT(list) = size_zero_node;
0368     DECL_FIELD_OFFSET(list) = size_zero_node;
0369     DECL_CONTEXT(list) = type;
0370     // to satisfy the constify plugin
0371     TREE_READONLY(list) = 1;
0372 
0373     for (i = 0; i < num_fields - 1; i++)
0374         TREE_CHAIN(newtree[i]) = newtree[i+1];
0375     TREE_CHAIN(newtree[num_fields - 1]) = NULL_TREE;
0376 
0377     main_variant = TYPE_MAIN_VARIANT(type);
0378     for (variant = main_variant; variant; variant = TYPE_NEXT_VARIANT(variant)) {
0379         TYPE_FIELDS(variant) = list;
0380         TYPE_ATTRIBUTES(variant) = copy_list(TYPE_ATTRIBUTES(variant));
0381         TYPE_ATTRIBUTES(variant) = tree_cons(get_identifier("randomize_performed"), NULL_TREE, TYPE_ATTRIBUTES(variant));
0382         TYPE_ATTRIBUTES(variant) = tree_cons(get_identifier("designated_init"), NULL_TREE, TYPE_ATTRIBUTES(variant));
0383         if (has_flexarray)
0384             TYPE_ATTRIBUTES(type) = tree_cons(get_identifier("has_flexarray"), NULL_TREE, TYPE_ATTRIBUTES(type));
0385     }
0386 
0387     /*
0388      * force a re-layout of the main variant
0389      * the TYPE_SIZE for all variants will be recomputed
0390      * by finalize_type_size()
0391      */
0392     TYPE_SIZE(main_variant) = NULL_TREE;
0393     layout_type(main_variant);
0394     gcc_assert(TYPE_SIZE(main_variant) != NULL_TREE);
0395 
0396     return 1;
0397 }
0398 
0399 /* from constify plugin */
0400 static const_tree get_field_type(const_tree field)
0401 {
0402     return strip_array_types(TREE_TYPE(field));
0403 }
0404 
0405 /* from constify plugin */
0406 static bool is_fptr(const_tree fieldtype)
0407 {
0408     if (TREE_CODE(fieldtype) != POINTER_TYPE)
0409         return false;
0410 
0411     return TREE_CODE(TREE_TYPE(fieldtype)) == FUNCTION_TYPE;
0412 }
0413 
0414 /* derived from constify plugin */
0415 static int is_pure_ops_struct(const_tree node)
0416 {
0417     const_tree field;
0418 
0419     gcc_assert(TREE_CODE(node) == RECORD_TYPE || TREE_CODE(node) == UNION_TYPE);
0420 
0421     for (field = TYPE_FIELDS(node); field; field = TREE_CHAIN(field)) {
0422         const_tree fieldtype = get_field_type(field);
0423         enum tree_code code = TREE_CODE(fieldtype);
0424 
0425         if (node == fieldtype)
0426             continue;
0427 
0428         if (code == RECORD_TYPE || code == UNION_TYPE) {
0429             if (!is_pure_ops_struct(fieldtype))
0430                 return 0;
0431             continue;
0432         }
0433 
0434         if (!is_fptr(fieldtype))
0435             return 0;
0436     }
0437 
0438     return 1;
0439 }
0440 
0441 static void randomize_type(tree type)
0442 {
0443     tree variant;
0444 
0445     gcc_assert(TREE_CODE(type) == RECORD_TYPE);
0446 
0447     if (lookup_attribute("randomize_considered", TYPE_ATTRIBUTES(type)))
0448         return;
0449 
0450     if (lookup_attribute("randomize_layout", TYPE_ATTRIBUTES(TYPE_MAIN_VARIANT(type))) || is_pure_ops_struct(type))
0451         relayout_struct(type);
0452 
0453     for (variant = TYPE_MAIN_VARIANT(type); variant; variant = TYPE_NEXT_VARIANT(variant)) {
0454         TYPE_ATTRIBUTES(type) = copy_list(TYPE_ATTRIBUTES(type));
0455         TYPE_ATTRIBUTES(type) = tree_cons(get_identifier("randomize_considered"), NULL_TREE, TYPE_ATTRIBUTES(type));
0456     }
0457 #ifdef __DEBUG_PLUGIN
0458     fprintf(stderr, "Marking randomize_considered on struct %s\n", ORIG_TYPE_NAME(type));
0459 #ifdef __DEBUG_VERBOSE
0460     debug_tree(type);
0461 #endif
0462 #endif
0463 }
0464 
0465 static void update_decl_size(tree decl)
0466 {
0467     tree lastval, lastidx, field, init, type, flexsize;
0468     unsigned HOST_WIDE_INT len;
0469 
0470     type = TREE_TYPE(decl);
0471 
0472     if (!lookup_attribute("has_flexarray", TYPE_ATTRIBUTES(type)))
0473         return;
0474 
0475     init = DECL_INITIAL(decl);
0476     if (init == NULL_TREE || init == error_mark_node)
0477         return;
0478 
0479     if (TREE_CODE(init) != CONSTRUCTOR)
0480         return;
0481 
0482     len = CONSTRUCTOR_NELTS(init);
0483         if (!len)
0484         return;
0485 
0486     lastval = CONSTRUCTOR_ELT(init, CONSTRUCTOR_NELTS(init) - 1)->value;
0487     lastidx = CONSTRUCTOR_ELT(init, CONSTRUCTOR_NELTS(init) - 1)->index;
0488 
0489     for (field = TYPE_FIELDS(TREE_TYPE(decl)); TREE_CHAIN(field); field = TREE_CHAIN(field))
0490         ;
0491 
0492     if (lastidx != field)
0493         return;
0494 
0495     if (TREE_CODE(lastval) != STRING_CST) {
0496         error("Only string constants are supported as initializers "
0497               "for randomized structures with flexible arrays");
0498         return;
0499     }
0500 
0501     flexsize = bitsize_int(TREE_STRING_LENGTH(lastval) *
0502         tree_to_uhwi(TYPE_SIZE(TREE_TYPE(TREE_TYPE(lastval)))));
0503 
0504     DECL_SIZE(decl) = size_binop(PLUS_EXPR, TYPE_SIZE(type), flexsize);
0505 
0506     return;
0507 }
0508 
0509 
0510 static void randomize_layout_finish_decl(void *event_data, void *data)
0511 {
0512     tree decl = (tree)event_data;
0513     tree type;
0514 
0515     if (decl == NULL_TREE || decl == error_mark_node)
0516         return;
0517 
0518     type = TREE_TYPE(decl);
0519 
0520     if (TREE_CODE(decl) != VAR_DECL)
0521         return;
0522 
0523     if (TREE_CODE(type) != RECORD_TYPE && TREE_CODE(type) != UNION_TYPE)
0524         return;
0525 
0526     if (!lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(type)))
0527         return;
0528 
0529     DECL_SIZE(decl) = 0;
0530     DECL_SIZE_UNIT(decl) = 0;
0531     SET_DECL_ALIGN(decl, 0);
0532     SET_DECL_MODE (decl, VOIDmode);
0533     SET_DECL_RTL(decl, 0);
0534     update_decl_size(decl);
0535     layout_decl(decl, 0);
0536 }
0537 
0538 static void finish_type(void *event_data, void *data)
0539 {
0540     tree type = (tree)event_data;
0541 
0542     if (type == NULL_TREE || type == error_mark_node)
0543         return;
0544 
0545     if (TREE_CODE(type) != RECORD_TYPE)
0546         return;
0547 
0548     if (TYPE_FIELDS(type) == NULL_TREE)
0549         return;
0550 
0551     if (lookup_attribute("randomize_considered", TYPE_ATTRIBUTES(type)))
0552         return;
0553 
0554 #ifdef __DEBUG_PLUGIN
0555     fprintf(stderr, "Calling randomize_type on %s\n", ORIG_TYPE_NAME(type));
0556 #endif
0557 #ifdef __DEBUG_VERBOSE
0558     debug_tree(type);
0559 #endif
0560     randomize_type(type);
0561 
0562     return;
0563 }
0564 
0565 static struct attribute_spec randomize_layout_attr = { };
0566 static struct attribute_spec no_randomize_layout_attr = { };
0567 static struct attribute_spec randomize_considered_attr = { };
0568 static struct attribute_spec randomize_performed_attr = { };
0569 
0570 static void register_attributes(void *event_data, void *data)
0571 {
0572     randomize_layout_attr.name      = "randomize_layout";
0573     randomize_layout_attr.type_required = true;
0574     randomize_layout_attr.handler       = handle_randomize_layout_attr;
0575     randomize_layout_attr.affects_type_identity = true;
0576 
0577     no_randomize_layout_attr.name       = "no_randomize_layout";
0578     no_randomize_layout_attr.type_required  = true;
0579     no_randomize_layout_attr.handler    = handle_randomize_layout_attr;
0580     no_randomize_layout_attr.affects_type_identity = true;
0581 
0582     randomize_considered_attr.name      = "randomize_considered";
0583     randomize_considered_attr.type_required = true;
0584     randomize_considered_attr.handler   = handle_randomize_considered_attr;
0585 
0586     randomize_performed_attr.name       = "randomize_performed";
0587     randomize_performed_attr.type_required  = true;
0588     randomize_performed_attr.handler    = handle_randomize_performed_attr;
0589 
0590     register_attribute(&randomize_layout_attr);
0591     register_attribute(&no_randomize_layout_attr);
0592     register_attribute(&randomize_considered_attr);
0593     register_attribute(&randomize_performed_attr);
0594 }
0595 
0596 static void check_bad_casts_in_constructor(tree var, tree init)
0597 {
0598     unsigned HOST_WIDE_INT idx;
0599     tree field, val;
0600     tree field_type, val_type;
0601 
0602     FOR_EACH_CONSTRUCTOR_ELT(CONSTRUCTOR_ELTS(init), idx, field, val) {
0603         if (TREE_CODE(val) == CONSTRUCTOR) {
0604             check_bad_casts_in_constructor(var, val);
0605             continue;
0606         }
0607 
0608         /* pipacs' plugin creates franken-arrays that differ from those produced by
0609            normal code which all have valid 'field' trees. work around this */
0610         if (field == NULL_TREE)
0611             continue;
0612         field_type = TREE_TYPE(field);
0613         val_type = TREE_TYPE(val);
0614 
0615         if (TREE_CODE(field_type) != POINTER_TYPE || TREE_CODE(val_type) != POINTER_TYPE)
0616             continue;
0617 
0618         if (field_type == val_type)
0619             continue;
0620 
0621         field_type = TYPE_MAIN_VARIANT(strip_array_types(TYPE_MAIN_VARIANT(TREE_TYPE(field_type))));
0622         val_type = TYPE_MAIN_VARIANT(strip_array_types(TYPE_MAIN_VARIANT(TREE_TYPE(val_type))));
0623 
0624         if (field_type == void_type_node)
0625             continue;
0626         if (field_type == val_type)
0627             continue;
0628         if (TREE_CODE(val_type) != RECORD_TYPE)
0629             continue;
0630 
0631         if (!lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(val_type)))
0632             continue;
0633         MISMATCH(DECL_SOURCE_LOCATION(var), "constructor\n", TYPE_MAIN_VARIANT(field_type), TYPE_MAIN_VARIANT(val_type));
0634     }
0635 }
0636 
0637 /* derived from the constify plugin */
0638 static void check_global_variables(void *event_data, void *data)
0639 {
0640     struct varpool_node *node;
0641     tree init;
0642 
0643     FOR_EACH_VARIABLE(node) {
0644         tree var = NODE_DECL(node);
0645         init = DECL_INITIAL(var);
0646         if (init == NULL_TREE)
0647             continue;
0648 
0649         if (TREE_CODE(init) != CONSTRUCTOR)
0650             continue;
0651 
0652         check_bad_casts_in_constructor(var, init);
0653     }
0654 }
0655 
0656 static bool dominated_by_is_err(const_tree rhs, basic_block bb)
0657 {
0658     basic_block dom;
0659     gimple dom_stmt;
0660     gimple call_stmt;
0661     const_tree dom_lhs;
0662     const_tree poss_is_err_cond;
0663     const_tree poss_is_err_func;
0664     const_tree is_err_arg;
0665 
0666     dom = get_immediate_dominator(CDI_DOMINATORS, bb);
0667     if (!dom)
0668         return false;
0669 
0670     dom_stmt = last_stmt(dom);
0671     if (!dom_stmt)
0672         return false;
0673 
0674     if (gimple_code(dom_stmt) != GIMPLE_COND)
0675         return false;
0676 
0677     if (gimple_cond_code(dom_stmt) != NE_EXPR)
0678         return false;
0679 
0680     if (!integer_zerop(gimple_cond_rhs(dom_stmt)))
0681         return false;
0682 
0683     poss_is_err_cond = gimple_cond_lhs(dom_stmt);
0684 
0685     if (TREE_CODE(poss_is_err_cond) != SSA_NAME)
0686         return false;
0687 
0688     call_stmt = SSA_NAME_DEF_STMT(poss_is_err_cond);
0689 
0690     if (gimple_code(call_stmt) != GIMPLE_CALL)
0691         return false;
0692 
0693     dom_lhs = gimple_get_lhs(call_stmt);
0694     poss_is_err_func = gimple_call_fndecl(call_stmt);
0695     if (!poss_is_err_func)
0696         return false;
0697     if (dom_lhs != poss_is_err_cond)
0698         return false;
0699     if (strcmp(DECL_NAME_POINTER(poss_is_err_func), "IS_ERR"))
0700         return false;
0701 
0702     is_err_arg = gimple_call_arg(call_stmt, 0);
0703     if (!is_err_arg)
0704         return false;
0705 
0706     if (is_err_arg != rhs)
0707         return false;
0708 
0709     return true;
0710 }
0711 
0712 static void handle_local_var_initializers(void)
0713 {
0714     tree var;
0715     unsigned int i;
0716 
0717     FOR_EACH_LOCAL_DECL(cfun, i, var) {
0718         tree init = DECL_INITIAL(var);
0719         if (!init)
0720             continue;
0721         if (TREE_CODE(init) != CONSTRUCTOR)
0722             continue;
0723         check_bad_casts_in_constructor(var, init);
0724     }
0725 }
0726 
0727 /*
0728  * iterate over all statements to find "bad" casts:
0729  * those where the address of the start of a structure is cast
0730  * to a pointer of a structure of a different type, or a
0731  * structure pointer type is cast to a different structure pointer type
0732  */
0733 static unsigned int find_bad_casts_execute(void)
0734 {
0735     basic_block bb;
0736 
0737     handle_local_var_initializers();
0738 
0739     FOR_EACH_BB_FN(bb, cfun) {
0740         gimple_stmt_iterator gsi;
0741 
0742         for (gsi = gsi_start_bb(bb); !gsi_end_p(gsi); gsi_next(&gsi)) {
0743             gimple stmt;
0744             const_tree lhs;
0745             const_tree lhs_type;
0746             const_tree rhs1;
0747             const_tree rhs_type;
0748             const_tree ptr_lhs_type;
0749             const_tree ptr_rhs_type;
0750             const_tree op0;
0751             const_tree op0_type;
0752             enum tree_code rhs_code;
0753 
0754             stmt = gsi_stmt(gsi);
0755 
0756 #ifdef __DEBUG_PLUGIN
0757 #ifdef __DEBUG_VERBOSE
0758             debug_gimple_stmt(stmt);
0759             debug_tree(gimple_get_lhs(stmt));
0760 #endif
0761 #endif
0762 
0763             if (gimple_code(stmt) != GIMPLE_ASSIGN)
0764                 continue;
0765 
0766 #ifdef __DEBUG_PLUGIN
0767 #ifdef __DEBUG_VERBOSE
0768             debug_tree(gimple_assign_rhs1(stmt));
0769 #endif
0770 #endif
0771 
0772 
0773             rhs_code = gimple_assign_rhs_code(stmt);
0774 
0775             if (rhs_code != ADDR_EXPR && rhs_code != SSA_NAME)
0776                 continue;
0777 
0778             lhs = gimple_get_lhs(stmt);
0779             lhs_type = TREE_TYPE(lhs);
0780             rhs1 = gimple_assign_rhs1(stmt);
0781             rhs_type = TREE_TYPE(rhs1);
0782 
0783             if (TREE_CODE(rhs_type) != POINTER_TYPE ||
0784                 TREE_CODE(lhs_type) != POINTER_TYPE)
0785                 continue;
0786 
0787             ptr_lhs_type = TYPE_MAIN_VARIANT(strip_array_types(TYPE_MAIN_VARIANT(TREE_TYPE(lhs_type))));
0788             ptr_rhs_type = TYPE_MAIN_VARIANT(strip_array_types(TYPE_MAIN_VARIANT(TREE_TYPE(rhs_type))));
0789 
0790             if (ptr_rhs_type == void_type_node)
0791                 continue;
0792 
0793             if (ptr_lhs_type == void_type_node)
0794                 continue;
0795 
0796             if (dominated_by_is_err(rhs1, bb))
0797                 continue;
0798 
0799             if (TREE_CODE(ptr_rhs_type) != RECORD_TYPE) {
0800 #ifndef __DEBUG_PLUGIN
0801                 if (lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(ptr_lhs_type)))
0802 #endif
0803                 MISMATCH(gimple_location(stmt), "rhs", ptr_lhs_type, ptr_rhs_type);
0804                 continue;
0805             }
0806 
0807             if (rhs_code == SSA_NAME && ptr_lhs_type == ptr_rhs_type)
0808                 continue;
0809 
0810             if (rhs_code == ADDR_EXPR) {
0811                 op0 = TREE_OPERAND(rhs1, 0);
0812 
0813                 if (op0 == NULL_TREE)
0814                     continue;
0815 
0816                 if (TREE_CODE(op0) != VAR_DECL)
0817                     continue;
0818 
0819                 op0_type = TYPE_MAIN_VARIANT(strip_array_types(TYPE_MAIN_VARIANT(TREE_TYPE(op0))));
0820                 if (op0_type == ptr_lhs_type)
0821                     continue;
0822 
0823 #ifndef __DEBUG_PLUGIN
0824                 if (lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(op0_type)))
0825 #endif
0826                 MISMATCH(gimple_location(stmt), "op0", ptr_lhs_type, op0_type);
0827             } else {
0828                 const_tree ssa_name_var = SSA_NAME_VAR(rhs1);
0829                 /* skip bogus type casts introduced by container_of */
0830                 if (ssa_name_var != NULL_TREE && DECL_NAME(ssa_name_var) && 
0831                     !strcmp((const char *)DECL_NAME_POINTER(ssa_name_var), "__mptr"))
0832                     continue;
0833 #ifndef __DEBUG_PLUGIN
0834                 if (lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(ptr_rhs_type)))
0835 #endif
0836                 MISMATCH(gimple_location(stmt), "ssa", ptr_lhs_type, ptr_rhs_type);
0837             }
0838 
0839         }
0840     }
0841     return 0;
0842 }
0843 
0844 #define PASS_NAME find_bad_casts
0845 #define NO_GATE
0846 #define TODO_FLAGS_FINISH TODO_dump_func
0847 #include "gcc-generate-gimple-pass.h"
0848 
0849 __visible int plugin_init(struct plugin_name_args *plugin_info, struct plugin_gcc_version *version)
0850 {
0851     int i;
0852     const char * const plugin_name = plugin_info->base_name;
0853     const int argc = plugin_info->argc;
0854     const struct plugin_argument * const argv = plugin_info->argv;
0855     bool enable = true;
0856     int obtained_seed = 0;
0857     struct register_pass_info find_bad_casts_pass_info;
0858 
0859     find_bad_casts_pass_info.pass           = make_find_bad_casts_pass();
0860     find_bad_casts_pass_info.reference_pass_name    = "ssa";
0861     find_bad_casts_pass_info.ref_pass_instance_number   = 1;
0862     find_bad_casts_pass_info.pos_op         = PASS_POS_INSERT_AFTER;
0863 
0864     if (!plugin_default_version_check(version, &gcc_version)) {
0865         error(G_("incompatible gcc/plugin versions"));
0866         return 1;
0867     }
0868 
0869     if (strncmp(lang_hooks.name, "GNU C", 5) && !strncmp(lang_hooks.name, "GNU C+", 6)) {
0870         inform(UNKNOWN_LOCATION, G_("%s supports C only, not %s"), plugin_name, lang_hooks.name);
0871         enable = false;
0872     }
0873 
0874     for (i = 0; i < argc; ++i) {
0875         if (!strcmp(argv[i].key, "disable")) {
0876             enable = false;
0877             continue;
0878         }
0879         if (!strcmp(argv[i].key, "performance-mode")) {
0880             performance_mode = 1;
0881             continue;
0882         }
0883         error(G_("unknown option '-fplugin-arg-%s-%s'"), plugin_name, argv[i].key);
0884     }
0885 
0886     if (strlen(randstruct_seed) != 64) {
0887         error(G_("invalid seed value supplied for %s plugin"), plugin_name);
0888         return 1;
0889     }
0890     obtained_seed = sscanf(randstruct_seed, "%016llx%016llx%016llx%016llx",
0891         &shuffle_seed[0], &shuffle_seed[1], &shuffle_seed[2], &shuffle_seed[3]);
0892     if (obtained_seed != 4) {
0893         error(G_("Invalid seed supplied for %s plugin"), plugin_name);
0894         return 1;
0895     }
0896 
0897     register_callback(plugin_name, PLUGIN_INFO, NULL, &randomize_layout_plugin_info);
0898     if (enable) {
0899         register_callback(plugin_name, PLUGIN_ALL_IPA_PASSES_START, check_global_variables, NULL);
0900         register_callback(plugin_name, PLUGIN_PASS_MANAGER_SETUP, NULL, &find_bad_casts_pass_info);
0901         register_callback(plugin_name, PLUGIN_FINISH_TYPE, finish_type, NULL);
0902         register_callback(plugin_name, PLUGIN_FINISH_DECL, randomize_layout_finish_decl, NULL);
0903     }
0904     register_callback(plugin_name, PLUGIN_ATTRIBUTES, register_attributes, NULL);
0905 
0906     return 0;
0907 }