1 /*
2  * Copyright 2014-2016 by Open Source Security, Inc., Brad Spengler <[email protected]>
3  *                   and PaX Team <[email protected]>
4  * Licensed under the GPL v2
5  *
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
10  *
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
17  */
18 
19 #include "gcc-common.h"
20 #include "randomize_layout_seed.h"
21 
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
25 
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")
28 
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__)
31 
32 __visible int plugin_is_GPL_compatible;
33 
34 static int performance_mode;
35 
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"
40 };
41 
42 struct whitelist_entry {
43 	const char *pathname;
44 	const char *lhs;
45 	const char *rhs;
46 };
47 
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 	{ }
56 };
57 
58 /* from old Linux dcache.h */
59 static inline unsigned long
60 partial_name_hash(unsigned long c, unsigned long prevhash)
61 {
62 	return (prevhash + (c << 4) + (c >> 4)) * 11;
63 }
64 static inline unsigned int
65 name_hash(const unsigned char *name)
66 {
67 	unsigned long hash = 0;
68 	unsigned int len = strlen((const char *)name);
69 	while (len--)
70 		hash = partial_name_hash(*name++, hash);
71 	return (unsigned int)hash;
72 }
73 
74 static tree handle_randomize_layout_attr(tree *node, tree name, tree args, int flags, bool *no_add_attrs)
75 {
76 	tree type;
77 
78 	*no_add_attrs = true;
79 	if (TREE_CODE(*node) == FUNCTION_DECL) {
80 		error("%qE attribute does not apply to functions (%qF)", name, *node);
81 		return NULL_TREE;
82 	}
83 
84 	if (TREE_CODE(*node) == PARM_DECL) {
85 		error("%qE attribute does not apply to function parameters (%qD)", name, *node);
86 		return NULL_TREE;
87 	}
88 
89 	if (TREE_CODE(*node) == VAR_DECL) {
90 		error("%qE attribute does not apply to variables (%qD)", name, *node);
91 		return NULL_TREE;
92 	}
93 
94 	if (TYPE_P(*node)) {
95 		type = *node;
96 	} else {
97 		gcc_assert(TREE_CODE(*node) == TYPE_DECL);
98 		type = TREE_TYPE(*node);
99 	}
100 
101 	if (TREE_CODE(type) != RECORD_TYPE) {
102 		error("%qE attribute used on %qT applies to struct types only", name, type);
103 		return NULL_TREE;
104 	}
105 
106 	if (lookup_attribute(IDENTIFIER_POINTER(name), TYPE_ATTRIBUTES(type))) {
107 		error("%qE attribute is already applied to the type %qT", name, type);
108 		return NULL_TREE;
109 	}
110 
111 	*no_add_attrs = false;
112 
113 	return NULL_TREE;
114 }
115 
116 /* set on complete types that we don't need to inspect further at all */
117 static tree handle_randomize_considered_attr(tree *node, tree name, tree args, int flags, bool *no_add_attrs)
118 {
119 	*no_add_attrs = false;
120 	return NULL_TREE;
121 }
122 
123 /*
124  * set on types that we've performed a shuffle on, to prevent re-shuffling
125  * this does not preclude us from inspecting its fields for potential shuffles
126  */
127 static tree handle_randomize_performed_attr(tree *node, tree name, tree args, int flags, bool *no_add_attrs)
128 {
129 	*no_add_attrs = false;
130 	return NULL_TREE;
131 }
132 
133 /*
134  * 64bit variant of Bob Jenkins' public domain PRNG
135  * 256 bits of internal state
136  */
137 
138 typedef unsigned long long u64;
139 
140 typedef struct ranctx { u64 a; u64 b; u64 c; u64 d; } ranctx;
141 
142 #define rot(x,k) (((x)<<(k))|((x)>>(64-(k))))
143 static u64 ranval(ranctx *x) {
144 	u64 e = x->a - rot(x->b, 7);
145 	x->a = x->b ^ rot(x->c, 13);
146 	x->b = x->c + rot(x->d, 37);
147 	x->c = x->d + e;
148 	x->d = e + x->a;
149 	return x->d;
150 }
151 
152 static void raninit(ranctx *x, u64 *seed) {
153 	int i;
154 
155 	x->a = seed[0];
156 	x->b = seed[1];
157 	x->c = seed[2];
158 	x->d = seed[3];
159 
160 	for (i=0; i < 30; ++i)
161 		(void)ranval(x);
162 }
163 
164 static u64 shuffle_seed[4];
165 
166 struct partition_group {
167 	tree tree_start;
168 	unsigned long start;
169 	unsigned long length;
170 };
171 
172 static void partition_struct(tree *fields, unsigned long length, struct partition_group *size_groups, unsigned long *num_groups)
173 {
174 	unsigned long i;
175 	unsigned long accum_size = 0;
176 	unsigned long accum_length = 0;
177 	unsigned long group_idx = 0;
178 
179 	gcc_assert(length < INT_MAX);
180 
181 	memset(size_groups, 0, sizeof(struct partition_group) * length);
182 
183 	for (i = 0; i < length; i++) {
184 		if (size_groups[group_idx].tree_start == NULL_TREE) {
185 			size_groups[group_idx].tree_start = fields[i];
186 			size_groups[group_idx].start = i;
187 			accum_length = 0;
188 			accum_size = 0;
189 		}
190 		accum_size += (unsigned long)int_size_in_bytes(TREE_TYPE(fields[i]));
191 		accum_length++;
192 		if (accum_size >= 64) {
193 			size_groups[group_idx].length = accum_length;
194 			accum_length = 0;
195 			group_idx++;
196 		}
197 	}
198 
199 	if (size_groups[group_idx].tree_start != NULL_TREE &&
200 	    !size_groups[group_idx].length) {
201 		size_groups[group_idx].length = accum_length;
202 		group_idx++;
203 	}
204 
205 	*num_groups = group_idx;
206 }
207 
208 static void performance_shuffle(tree *newtree, unsigned long length, ranctx *prng_state)
209 {
210 	unsigned long i, x;
211 	struct partition_group size_group[length];
212 	unsigned long num_groups = 0;
213 	unsigned long randnum;
214 
215 	partition_struct(newtree, length, (struct partition_group *)&size_group, &num_groups);
216 	for (i = num_groups - 1; i > 0; i--) {
217 		struct partition_group tmp;
218 		randnum = ranval(prng_state) % (i + 1);
219 		tmp = size_group[i];
220 		size_group[i] = size_group[randnum];
221 		size_group[randnum] = tmp;
222 	}
223 
224 	for (x = 0; x < num_groups; x++) {
225 		for (i = size_group[x].start + size_group[x].length - 1; i > size_group[x].start; i--) {
226 			tree tmp;
227 			if (DECL_BIT_FIELD_TYPE(newtree[i]))
228 				continue;
229 			randnum = ranval(prng_state) % (i + 1);
230 			// we could handle this case differently if desired
231 			if (DECL_BIT_FIELD_TYPE(newtree[randnum]))
232 				continue;
233 			tmp = newtree[i];
234 			newtree[i] = newtree[randnum];
235 			newtree[randnum] = tmp;
236 		}
237 	}
238 }
239 
240 static void full_shuffle(tree *newtree, unsigned long length, ranctx *prng_state)
241 {
242 	unsigned long i, randnum;
243 
244 	for (i = length - 1; i > 0; i--) {
245 		tree tmp;
246 		randnum = ranval(prng_state) % (i + 1);
247 		tmp = newtree[i];
248 		newtree[i] = newtree[randnum];
249 		newtree[randnum] = tmp;
250 	}
251 }
252 
253 /* modern in-place Fisher-Yates shuffle */
254 static void shuffle(const_tree type, tree *newtree, unsigned long length)
255 {
256 	unsigned long i;
257 	u64 seed[4];
258 	ranctx prng_state;
259 	const unsigned char *structname;
260 
261 	if (length == 0)
262 		return;
263 
264 	gcc_assert(TREE_CODE(type) == RECORD_TYPE);
265 
266 	structname = ORIG_TYPE_NAME(type);
267 
268 #ifdef __DEBUG_PLUGIN
269 	fprintf(stderr, "Shuffling struct %s %p\n", (const char *)structname, type);
270 #ifdef __DEBUG_VERBOSE
271 	debug_tree((tree)type);
272 #endif
273 #endif
274 
275 	for (i = 0; i < 4; i++) {
276 		seed[i] = shuffle_seed[i];
277 		seed[i] ^= name_hash(structname);
278 	}
279 
280 	raninit(&prng_state, (u64 *)&seed);
281 
282 	if (performance_mode)
283 		performance_shuffle(newtree, length, &prng_state);
284 	else
285 		full_shuffle(newtree, length, &prng_state);
286 }
287 
288 static bool is_flexible_array(const_tree field)
289 {
290 	const_tree fieldtype;
291 	const_tree typesize;
292 	const_tree elemtype;
293 	const_tree elemsize;
294 
295 	fieldtype = TREE_TYPE(field);
296 	typesize = TYPE_SIZE(fieldtype);
297 
298 	if (TREE_CODE(fieldtype) != ARRAY_TYPE)
299 		return false;
300 
301 	elemtype = TREE_TYPE(fieldtype);
302 	elemsize = TYPE_SIZE(elemtype);
303 
304 	/* size of type is represented in bits */
305 
306 	if (typesize == NULL_TREE && TYPE_DOMAIN(fieldtype) != NULL_TREE &&
307 	    TYPE_MAX_VALUE(TYPE_DOMAIN(fieldtype)) == NULL_TREE)
308 		return true;
309 
310 	if (typesize != NULL_TREE &&
311 	    (TREE_CONSTANT(typesize) && (!tree_to_uhwi(typesize) ||
312 	     tree_to_uhwi(typesize) == tree_to_uhwi(elemsize))))
313 		return true;
314 
315 	return false;
316 }
317 
318 static int relayout_struct(tree type)
319 {
320 	unsigned long num_fields = (unsigned long)list_length(TYPE_FIELDS(type));
321 	unsigned long shuffle_length = num_fields;
322 	tree field;
323 	tree newtree[num_fields];
324 	unsigned long i;
325 	tree list;
326 	tree variant;
327 	tree main_variant;
328 	expanded_location xloc;
329 	bool has_flexarray = false;
330 
331 	if (TYPE_FIELDS(type) == NULL_TREE)
332 		return 0;
333 
334 	if (num_fields < 2)
335 		return 0;
336 
337 	gcc_assert(TREE_CODE(type) == RECORD_TYPE);
338 
339 	gcc_assert(num_fields < INT_MAX);
340 
341 	if (lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(type)) ||
342 	    lookup_attribute("no_randomize_layout", TYPE_ATTRIBUTES(TYPE_MAIN_VARIANT(type))))
343 		return 0;
344 
345 	/* Workaround for 3rd-party VirtualBox source that we can't modify ourselves */
346 	if (!strcmp((const char *)ORIG_TYPE_NAME(type), "INTNETTRUNKFACTORY") ||
347 	    !strcmp((const char *)ORIG_TYPE_NAME(type), "RAWPCIFACTORY"))
348 		return 0;
349 
350 	/* throw out any structs in uapi */
351 	xloc = expand_location(DECL_SOURCE_LOCATION(TYPE_FIELDS(type)));
352 
353 	if (strstr(xloc.file, "/uapi/"))
354 		error(G_("attempted to randomize userland API struct %s"), ORIG_TYPE_NAME(type));
355 
356 	for (field = TYPE_FIELDS(type), i = 0; field; field = TREE_CHAIN(field), i++) {
357 		gcc_assert(TREE_CODE(field) == FIELD_DECL);
358 		newtree[i] = field;
359 	}
360 
361 	/*
362 	 * enforce that we don't randomize the layout of the last
363 	 * element of a struct if it's a 0 or 1-length array
364 	 * or a proper flexible array
365 	 */
366 	if (is_flexible_array(newtree[num_fields - 1])) {
367 		has_flexarray = true;
368 		shuffle_length--;
369 	}
370 
371 	shuffle(type, (tree *)newtree, shuffle_length);
372 
373 	/*
374 	 * set up a bogus anonymous struct field designed to error out on unnamed struct initializers
375 	 * as gcc provides no other way to detect such code
376 	 */
377 	list = make_node(FIELD_DECL);
378 	TREE_CHAIN(list) = newtree[0];
379 	TREE_TYPE(list) = void_type_node;
380 	DECL_SIZE(list) = bitsize_zero_node;
381 	DECL_NONADDRESSABLE_P(list) = 1;
382 	DECL_FIELD_BIT_OFFSET(list) = bitsize_zero_node;
383 	DECL_SIZE_UNIT(list) = size_zero_node;
384 	DECL_FIELD_OFFSET(list) = size_zero_node;
385 	DECL_CONTEXT(list) = type;
386 	// to satisfy the constify plugin
387 	TREE_READONLY(list) = 1;
388 
389 	for (i = 0; i < num_fields - 1; i++)
390 		TREE_CHAIN(newtree[i]) = newtree[i+1];
391 	TREE_CHAIN(newtree[num_fields - 1]) = NULL_TREE;
392 
393 	main_variant = TYPE_MAIN_VARIANT(type);
394 	for (variant = main_variant; variant; variant = TYPE_NEXT_VARIANT(variant)) {
395 		TYPE_FIELDS(variant) = list;
396 		TYPE_ATTRIBUTES(variant) = copy_list(TYPE_ATTRIBUTES(variant));
397 		TYPE_ATTRIBUTES(variant) = tree_cons(get_identifier("randomize_performed"), NULL_TREE, TYPE_ATTRIBUTES(variant));
398 		TYPE_ATTRIBUTES(variant) = tree_cons(get_identifier("designated_init"), NULL_TREE, TYPE_ATTRIBUTES(variant));
399 		if (has_flexarray)
400 			TYPE_ATTRIBUTES(type) = tree_cons(get_identifier("has_flexarray"), NULL_TREE, TYPE_ATTRIBUTES(type));
401 	}
402 
403 	/*
404 	 * force a re-layout of the main variant
405 	 * the TYPE_SIZE for all variants will be recomputed
406 	 * by finalize_type_size()
407 	 */
408 	TYPE_SIZE(main_variant) = NULL_TREE;
409 	layout_type(main_variant);
410 	gcc_assert(TYPE_SIZE(main_variant) != NULL_TREE);
411 
412 	return 1;
413 }
414 
415 /* from constify plugin */
416 static const_tree get_field_type(const_tree field)
417 {
418 	return strip_array_types(TREE_TYPE(field));
419 }
420 
421 /* from constify plugin */
422 static bool is_fptr(const_tree fieldtype)
423 {
424 	if (TREE_CODE(fieldtype) != POINTER_TYPE)
425 		return false;
426 
427 	return TREE_CODE(TREE_TYPE(fieldtype)) == FUNCTION_TYPE;
428 }
429 
430 /* derived from constify plugin */
431 static int is_pure_ops_struct(const_tree node)
432 {
433 	const_tree field;
434 
435 	gcc_assert(TREE_CODE(node) == RECORD_TYPE || TREE_CODE(node) == UNION_TYPE);
436 
437 	for (field = TYPE_FIELDS(node); field; field = TREE_CHAIN(field)) {
438 		const_tree fieldtype = get_field_type(field);
439 		enum tree_code code = TREE_CODE(fieldtype);
440 
441 		if (node == fieldtype)
442 			continue;
443 
444 		if (code == RECORD_TYPE || code == UNION_TYPE) {
445 			if (!is_pure_ops_struct(fieldtype))
446 				return 0;
447 			continue;
448 		}
449 
450 		if (!is_fptr(fieldtype))
451 			return 0;
452 	}
453 
454 	return 1;
455 }
456 
457 static void randomize_type(tree type)
458 {
459 	tree variant;
460 
461 	gcc_assert(TREE_CODE(type) == RECORD_TYPE);
462 
463 	if (lookup_attribute("randomize_considered", TYPE_ATTRIBUTES(type)))
464 		return;
465 
466 	if (lookup_attribute("randomize_layout", TYPE_ATTRIBUTES(TYPE_MAIN_VARIANT(type))) || is_pure_ops_struct(type))
467 		relayout_struct(type);
468 
469 	for (variant = TYPE_MAIN_VARIANT(type); variant; variant = TYPE_NEXT_VARIANT(variant)) {
470 		TYPE_ATTRIBUTES(type) = copy_list(TYPE_ATTRIBUTES(type));
471 		TYPE_ATTRIBUTES(type) = tree_cons(get_identifier("randomize_considered"), NULL_TREE, TYPE_ATTRIBUTES(type));
472 	}
473 #ifdef __DEBUG_PLUGIN
474 	fprintf(stderr, "Marking randomize_considered on struct %s\n", ORIG_TYPE_NAME(type));
475 #ifdef __DEBUG_VERBOSE
476 	debug_tree(type);
477 #endif
478 #endif
479 }
480 
481 static void update_decl_size(tree decl)
482 {
483 	tree lastval, lastidx, field, init, type, flexsize;
484 	unsigned HOST_WIDE_INT len;
485 
486 	type = TREE_TYPE(decl);
487 
488 	if (!lookup_attribute("has_flexarray", TYPE_ATTRIBUTES(type)))
489 		return;
490 
491 	init = DECL_INITIAL(decl);
492 	if (init == NULL_TREE || init == error_mark_node)
493 		return;
494 
495 	if (TREE_CODE(init) != CONSTRUCTOR)
496 		return;
497 
498 	len = CONSTRUCTOR_NELTS(init);
499         if (!len)
500 		return;
501 
502 	lastval = CONSTRUCTOR_ELT(init, CONSTRUCTOR_NELTS(init) - 1)->value;
503 	lastidx = CONSTRUCTOR_ELT(init, CONSTRUCTOR_NELTS(init) - 1)->index;
504 
505 	for (field = TYPE_FIELDS(TREE_TYPE(decl)); TREE_CHAIN(field); field = TREE_CHAIN(field))
506 		;
507 
508 	if (lastidx != field)
509 		return;
510 
511 	if (TREE_CODE(lastval) != STRING_CST) {
512 		error("Only string constants are supported as initializers "
513 		      "for randomized structures with flexible arrays");
514 		return;
515 	}
516 
517 	flexsize = bitsize_int(TREE_STRING_LENGTH(lastval) *
518 		tree_to_uhwi(TYPE_SIZE(TREE_TYPE(TREE_TYPE(lastval)))));
519 
520 	DECL_SIZE(decl) = size_binop(PLUS_EXPR, TYPE_SIZE(type), flexsize);
521 
522 	return;
523 }
524 
525 
526 static void randomize_layout_finish_decl(void *event_data, void *data)
527 {
528 	tree decl = (tree)event_data;
529 	tree type;
530 
531 	if (decl == NULL_TREE || decl == error_mark_node)
532 		return;
533 
534 	type = TREE_TYPE(decl);
535 
536 	if (TREE_CODE(decl) != VAR_DECL)
537 		return;
538 
539 	if (TREE_CODE(type) != RECORD_TYPE && TREE_CODE(type) != UNION_TYPE)
540 		return;
541 
542 	if (!lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(type)))
543 		return;
544 
545 	DECL_SIZE(decl) = 0;
546 	DECL_SIZE_UNIT(decl) = 0;
547 	SET_DECL_ALIGN(decl, 0);
548 	SET_DECL_MODE (decl, VOIDmode);
549 	SET_DECL_RTL(decl, 0);
550 	update_decl_size(decl);
551 	layout_decl(decl, 0);
552 }
553 
554 static void finish_type(void *event_data, void *data)
555 {
556 	tree type = (tree)event_data;
557 
558 	if (type == NULL_TREE || type == error_mark_node)
559 		return;
560 
561 	if (TREE_CODE(type) != RECORD_TYPE)
562 		return;
563 
564 	if (TYPE_FIELDS(type) == NULL_TREE)
565 		return;
566 
567 	if (lookup_attribute("randomize_considered", TYPE_ATTRIBUTES(type)))
568 		return;
569 
570 #ifdef __DEBUG_PLUGIN
571 	fprintf(stderr, "Calling randomize_type on %s\n", ORIG_TYPE_NAME(type));
572 #endif
573 #ifdef __DEBUG_VERBOSE
574 	debug_tree(type);
575 #endif
576 	randomize_type(type);
577 
578 	return;
579 }
580 
581 static struct attribute_spec randomize_layout_attr = { };
582 static struct attribute_spec no_randomize_layout_attr = { };
583 static struct attribute_spec randomize_considered_attr = { };
584 static struct attribute_spec randomize_performed_attr = { };
585 
586 static void register_attributes(void *event_data, void *data)
587 {
588 	randomize_layout_attr.name		= "randomize_layout";
589 	randomize_layout_attr.type_required	= true;
590 	randomize_layout_attr.handler		= handle_randomize_layout_attr;
591 	randomize_layout_attr.affects_type_identity = true;
592 
593 	no_randomize_layout_attr.name		= "no_randomize_layout";
594 	no_randomize_layout_attr.type_required	= true;
595 	no_randomize_layout_attr.handler	= handle_randomize_layout_attr;
596 	no_randomize_layout_attr.affects_type_identity = true;
597 
598 	randomize_considered_attr.name		= "randomize_considered";
599 	randomize_considered_attr.type_required	= true;
600 	randomize_considered_attr.handler	= handle_randomize_considered_attr;
601 
602 	randomize_performed_attr.name		= "randomize_performed";
603 	randomize_performed_attr.type_required	= true;
604 	randomize_performed_attr.handler	= handle_randomize_performed_attr;
605 
606 	register_attribute(&randomize_layout_attr);
607 	register_attribute(&no_randomize_layout_attr);
608 	register_attribute(&randomize_considered_attr);
609 	register_attribute(&randomize_performed_attr);
610 }
611 
612 static void check_bad_casts_in_constructor(tree var, tree init)
613 {
614 	unsigned HOST_WIDE_INT idx;
615 	tree field, val;
616 	tree field_type, val_type;
617 
618 	FOR_EACH_CONSTRUCTOR_ELT(CONSTRUCTOR_ELTS(init), idx, field, val) {
619 		if (TREE_CODE(val) == CONSTRUCTOR) {
620 			check_bad_casts_in_constructor(var, val);
621 			continue;
622 		}
623 
624 		/* pipacs' plugin creates franken-arrays that differ from those produced by
625 		   normal code which all have valid 'field' trees. work around this */
626 		if (field == NULL_TREE)
627 			continue;
628 		field_type = TREE_TYPE(field);
629 		val_type = TREE_TYPE(val);
630 
631 		if (TREE_CODE(field_type) != POINTER_TYPE || TREE_CODE(val_type) != POINTER_TYPE)
632 			continue;
633 
634 		if (field_type == val_type)
635 			continue;
636 
637 		field_type = TYPE_MAIN_VARIANT(strip_array_types(TYPE_MAIN_VARIANT(TREE_TYPE(field_type))));
638 		val_type = TYPE_MAIN_VARIANT(strip_array_types(TYPE_MAIN_VARIANT(TREE_TYPE(val_type))));
639 
640 		if (field_type == void_type_node)
641 			continue;
642 		if (field_type == val_type)
643 			continue;
644 		if (TREE_CODE(val_type) != RECORD_TYPE)
645 			continue;
646 
647 		if (!lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(val_type)))
648 			continue;
649 		MISMATCH(DECL_SOURCE_LOCATION(var), "constructor\n", TYPE_MAIN_VARIANT(field_type), TYPE_MAIN_VARIANT(val_type));
650 	}
651 }
652 
653 /* derived from the constify plugin */
654 static void check_global_variables(void *event_data, void *data)
655 {
656 	struct varpool_node *node;
657 	tree init;
658 
659 	FOR_EACH_VARIABLE(node) {
660 		tree var = NODE_DECL(node);
661 		init = DECL_INITIAL(var);
662 		if (init == NULL_TREE)
663 			continue;
664 
665 		if (TREE_CODE(init) != CONSTRUCTOR)
666 			continue;
667 
668 		check_bad_casts_in_constructor(var, init);
669 	}
670 }
671 
672 static bool dominated_by_is_err(const_tree rhs, basic_block bb)
673 {
674 	basic_block dom;
675 	gimple dom_stmt;
676 	gimple call_stmt;
677 	const_tree dom_lhs;
678 	const_tree poss_is_err_cond;
679 	const_tree poss_is_err_func;
680 	const_tree is_err_arg;
681 
682 	dom = get_immediate_dominator(CDI_DOMINATORS, bb);
683 	if (!dom)
684 		return false;
685 
686 	dom_stmt = last_stmt(dom);
687 	if (!dom_stmt)
688 		return false;
689 
690 	if (gimple_code(dom_stmt) != GIMPLE_COND)
691 		return false;
692 
693 	if (gimple_cond_code(dom_stmt) != NE_EXPR)
694 		return false;
695 
696 	if (!integer_zerop(gimple_cond_rhs(dom_stmt)))
697 		return false;
698 
699 	poss_is_err_cond = gimple_cond_lhs(dom_stmt);
700 
701 	if (TREE_CODE(poss_is_err_cond) != SSA_NAME)
702 		return false;
703 
704 	call_stmt = SSA_NAME_DEF_STMT(poss_is_err_cond);
705 
706 	if (gimple_code(call_stmt) != GIMPLE_CALL)
707 		return false;
708 
709 	dom_lhs = gimple_get_lhs(call_stmt);
710 	poss_is_err_func = gimple_call_fndecl(call_stmt);
711 	if (!poss_is_err_func)
712 		return false;
713 	if (dom_lhs != poss_is_err_cond)
714 		return false;
715 	if (strcmp(DECL_NAME_POINTER(poss_is_err_func), "IS_ERR"))
716 		return false;
717 
718 	is_err_arg = gimple_call_arg(call_stmt, 0);
719 	if (!is_err_arg)
720 		return false;
721 
722 	if (is_err_arg != rhs)
723 		return false;
724 
725 	return true;
726 }
727 
728 static void handle_local_var_initializers(void)
729 {
730 	tree var;
731 	unsigned int i;
732 
733 	FOR_EACH_LOCAL_DECL(cfun, i, var) {
734 		tree init = DECL_INITIAL(var);
735 		if (!init)
736 			continue;
737 		if (TREE_CODE(init) != CONSTRUCTOR)
738 			continue;
739 		check_bad_casts_in_constructor(var, init);
740 	}
741 }
742 
743 static bool type_name_eq(gimple stmt, const_tree type_tree, const char *wanted_name)
744 {
745 	const char *type_name;
746 
747 	if (type_tree == NULL_TREE)
748 		return false;
749 
750 	switch (TREE_CODE(type_tree)) {
751 	case RECORD_TYPE:
752 		type_name = TYPE_NAME_POINTER(type_tree);
753 		break;
754 	case INTEGER_TYPE:
755 		if (TYPE_PRECISION(type_tree) == CHAR_TYPE_SIZE)
756 			type_name = "char";
757 		else {
758 			INFORM(gimple_location(stmt), "found non-char INTEGER_TYPE cast comparison: %qT\n", type_tree);
759 			debug_tree(type_tree);
760 			return false;
761 		}
762 		break;
763 	case POINTER_TYPE:
764 		if (TREE_CODE(TREE_TYPE(type_tree)) == VOID_TYPE) {
765 			type_name = "void *";
766 			break;
767 		} else {
768 			INFORM(gimple_location(stmt), "found non-void POINTER_TYPE cast comparison %qT\n", type_tree);
769 			debug_tree(type_tree);
770 			return false;
771 		}
772 	default:
773 		INFORM(gimple_location(stmt), "unhandled cast comparison: %qT\n", type_tree);
774 		debug_tree(type_tree);
775 		return false;
776 	}
777 
778 	return strcmp(type_name, wanted_name) == 0;
779 }
780 
781 static bool whitelisted_cast(gimple stmt, const_tree lhs_tree, const_tree rhs_tree)
782 {
783 	const struct whitelist_entry *entry;
784 	expanded_location xloc = expand_location(gimple_location(stmt));
785 
786 	for (entry = whitelist; entry->pathname; entry++) {
787 		if (!strstr(xloc.file, entry->pathname))
788 			continue;
789 
790 		if (type_name_eq(stmt, lhs_tree, entry->lhs) && type_name_eq(stmt, rhs_tree, entry->rhs))
791 			return true;
792 	}
793 
794 	return false;
795 }
796 
797 /*
798  * iterate over all statements to find "bad" casts:
799  * those where the address of the start of a structure is cast
800  * to a pointer of a structure of a different type, or a
801  * structure pointer type is cast to a different structure pointer type
802  */
803 static unsigned int find_bad_casts_execute(void)
804 {
805 	basic_block bb;
806 
807 	handle_local_var_initializers();
808 
809 	FOR_EACH_BB_FN(bb, cfun) {
810 		gimple_stmt_iterator gsi;
811 
812 		for (gsi = gsi_start_bb(bb); !gsi_end_p(gsi); gsi_next(&gsi)) {
813 			gimple stmt;
814 			const_tree lhs;
815 			const_tree lhs_type;
816 			const_tree rhs1;
817 			const_tree rhs_type;
818 			const_tree ptr_lhs_type;
819 			const_tree ptr_rhs_type;
820 			const_tree op0;
821 			const_tree op0_type;
822 			enum tree_code rhs_code;
823 
824 			stmt = gsi_stmt(gsi);
825 
826 #ifdef __DEBUG_PLUGIN
827 #ifdef __DEBUG_VERBOSE
828 			debug_gimple_stmt(stmt);
829 			debug_tree(gimple_get_lhs(stmt));
830 #endif
831 #endif
832 
833 			if (gimple_code(stmt) != GIMPLE_ASSIGN)
834 				continue;
835 
836 #ifdef __DEBUG_PLUGIN
837 #ifdef __DEBUG_VERBOSE
838 			debug_tree(gimple_assign_rhs1(stmt));
839 #endif
840 #endif
841 
842 
843 			rhs_code = gimple_assign_rhs_code(stmt);
844 
845 			if (rhs_code != ADDR_EXPR && rhs_code != SSA_NAME)
846 				continue;
847 
848 			lhs = gimple_get_lhs(stmt);
849 			lhs_type = TREE_TYPE(lhs);
850 			rhs1 = gimple_assign_rhs1(stmt);
851 			rhs_type = TREE_TYPE(rhs1);
852 
853 			if (TREE_CODE(rhs_type) != POINTER_TYPE ||
854 			    TREE_CODE(lhs_type) != POINTER_TYPE)
855 				continue;
856 
857 			ptr_lhs_type = TYPE_MAIN_VARIANT(strip_array_types(TYPE_MAIN_VARIANT(TREE_TYPE(lhs_type))));
858 			ptr_rhs_type = TYPE_MAIN_VARIANT(strip_array_types(TYPE_MAIN_VARIANT(TREE_TYPE(rhs_type))));
859 
860 			if (ptr_rhs_type == void_type_node)
861 				continue;
862 
863 			if (ptr_lhs_type == void_type_node)
864 				continue;
865 
866 			if (dominated_by_is_err(rhs1, bb))
867 				continue;
868 
869 			if (TREE_CODE(ptr_rhs_type) != RECORD_TYPE) {
870 #ifndef __DEBUG_PLUGIN
871 				if (lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(ptr_lhs_type)))
872 #endif
873 				{
874 					if (!whitelisted_cast(stmt, ptr_lhs_type, ptr_rhs_type))
875 						MISMATCH(gimple_location(stmt), "rhs", ptr_lhs_type, ptr_rhs_type);
876 				}
877 				continue;
878 			}
879 
880 			if (rhs_code == SSA_NAME && ptr_lhs_type == ptr_rhs_type)
881 				continue;
882 
883 			if (rhs_code == ADDR_EXPR) {
884 				op0 = TREE_OPERAND(rhs1, 0);
885 
886 				if (op0 == NULL_TREE)
887 					continue;
888 
889 				if (TREE_CODE(op0) != VAR_DECL)
890 					continue;
891 
892 				op0_type = TYPE_MAIN_VARIANT(strip_array_types(TYPE_MAIN_VARIANT(TREE_TYPE(op0))));
893 				if (op0_type == ptr_lhs_type)
894 					continue;
895 
896 #ifndef __DEBUG_PLUGIN
897 				if (lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(op0_type)))
898 #endif
899 				{
900 					if (!whitelisted_cast(stmt, ptr_lhs_type, op0_type))
901 						MISMATCH(gimple_location(stmt), "op0", ptr_lhs_type, op0_type);
902 				}
903 			} else {
904 				const_tree ssa_name_var = SSA_NAME_VAR(rhs1);
905 				/* skip bogus type casts introduced by container_of */
906 				if (ssa_name_var != NULL_TREE && DECL_NAME(ssa_name_var) &&
907 				    !strcmp((const char *)DECL_NAME_POINTER(ssa_name_var), "__mptr"))
908 					continue;
909 #ifndef __DEBUG_PLUGIN
910 				if (lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(ptr_rhs_type)))
911 #endif
912 				{
913 					if (!whitelisted_cast(stmt, ptr_lhs_type, ptr_rhs_type))
914 						MISMATCH(gimple_location(stmt), "ssa", ptr_lhs_type, ptr_rhs_type);
915 				}
916 			}
917 
918 		}
919 	}
920 	return 0;
921 }
922 
923 #define PASS_NAME find_bad_casts
924 #define NO_GATE
925 #define TODO_FLAGS_FINISH TODO_dump_func
926 #include "gcc-generate-gimple-pass.h"
927 
928 __visible int plugin_init(struct plugin_name_args *plugin_info, struct plugin_gcc_version *version)
929 {
930 	int i;
931 	const char * const plugin_name = plugin_info->base_name;
932 	const int argc = plugin_info->argc;
933 	const struct plugin_argument * const argv = plugin_info->argv;
934 	bool enable = true;
935 	int obtained_seed = 0;
936 	struct register_pass_info find_bad_casts_pass_info;
937 
938 	find_bad_casts_pass_info.pass			= make_find_bad_casts_pass();
939 	find_bad_casts_pass_info.reference_pass_name	= "ssa";
940 	find_bad_casts_pass_info.ref_pass_instance_number	= 1;
941 	find_bad_casts_pass_info.pos_op			= PASS_POS_INSERT_AFTER;
942 
943 	if (!plugin_default_version_check(version, &gcc_version)) {
944 		error(G_("incompatible gcc/plugin versions"));
945 		return 1;
946 	}
947 
948 	if (strncmp(lang_hooks.name, "GNU C", 5) && !strncmp(lang_hooks.name, "GNU C+", 6)) {
949 		inform(UNKNOWN_LOCATION, G_("%s supports C only, not %s"), plugin_name, lang_hooks.name);
950 		enable = false;
951 	}
952 
953 	for (i = 0; i < argc; ++i) {
954 		if (!strcmp(argv[i].key, "disable")) {
955 			enable = false;
956 			continue;
957 		}
958 		if (!strcmp(argv[i].key, "performance-mode")) {
959 			performance_mode = 1;
960 			continue;
961 		}
962 		error(G_("unknown option '-fplugin-arg-%s-%s'"), plugin_name, argv[i].key);
963 	}
964 
965 	if (strlen(randstruct_seed) != 64) {
966 		error(G_("invalid seed value supplied for %s plugin"), plugin_name);
967 		return 1;
968 	}
969 	obtained_seed = sscanf(randstruct_seed, "%016llx%016llx%016llx%016llx",
970 		&shuffle_seed[0], &shuffle_seed[1], &shuffle_seed[2], &shuffle_seed[3]);
971 	if (obtained_seed != 4) {
972 		error(G_("Invalid seed supplied for %s plugin"), plugin_name);
973 		return 1;
974 	}
975 
976 	register_callback(plugin_name, PLUGIN_INFO, NULL, &randomize_layout_plugin_info);
977 	if (enable) {
978 		register_callback(plugin_name, PLUGIN_ALL_IPA_PASSES_START, check_global_variables, NULL);
979 		register_callback(plugin_name, PLUGIN_PASS_MANAGER_SETUP, NULL, &find_bad_casts_pass_info);
980 		register_callback(plugin_name, PLUGIN_FINISH_TYPE, finish_type, NULL);
981 		register_callback(plugin_name, PLUGIN_FINISH_DECL, randomize_layout_finish_decl, NULL);
982 	}
983 	register_callback(plugin_name, PLUGIN_ATTRIBUTES, register_attributes, NULL);
984 
985 	return 0;
986 }
987