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