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	= UTS_RELEASE,
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 	/* unix_skb_parms via UNIXCB() buffer */
50 	{ "net/unix/af_unix.c", "unix_skb_parms", "char" },
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 	for (field = TYPE_FIELDS(node); field; field = TREE_CHAIN(field)) {
434 		const_tree fieldtype = get_field_type(field);
435 		enum tree_code code = TREE_CODE(fieldtype);
436 
437 		if (node == fieldtype)
438 			continue;
439 
440 		if (code == RECORD_TYPE || code == UNION_TYPE) {
441 			if (!is_pure_ops_struct(fieldtype))
442 				return 0;
443 			continue;
444 		}
445 
446 		if (!is_fptr(fieldtype))
447 			return 0;
448 	}
449 
450 	return 1;
451 }
452 
453 static void randomize_type(tree type)
454 {
455 	tree variant;
456 
457 	gcc_assert(TREE_CODE(type) == RECORD_TYPE);
458 
459 	if (lookup_attribute("randomize_considered", TYPE_ATTRIBUTES(type)))
460 		return;
461 
462 	if (lookup_attribute("randomize_layout", TYPE_ATTRIBUTES(TYPE_MAIN_VARIANT(type))) || is_pure_ops_struct(type))
463 		relayout_struct(type);
464 
465 	for (variant = TYPE_MAIN_VARIANT(type); variant; variant = TYPE_NEXT_VARIANT(variant)) {
466 		TYPE_ATTRIBUTES(type) = copy_list(TYPE_ATTRIBUTES(type));
467 		TYPE_ATTRIBUTES(type) = tree_cons(get_identifier("randomize_considered"), NULL_TREE, TYPE_ATTRIBUTES(type));
468 	}
469 #ifdef __DEBUG_PLUGIN
470 	fprintf(stderr, "Marking randomize_considered on struct %s\n", ORIG_TYPE_NAME(type));
471 #ifdef __DEBUG_VERBOSE
472 	debug_tree(type);
473 #endif
474 #endif
475 }
476 
477 static void update_decl_size(tree decl)
478 {
479 	tree lastval, lastidx, field, init, type, flexsize;
480 	unsigned HOST_WIDE_INT len;
481 
482 	type = TREE_TYPE(decl);
483 
484 	if (!lookup_attribute("has_flexarray", TYPE_ATTRIBUTES(type)))
485 		return;
486 
487 	init = DECL_INITIAL(decl);
488 	if (init == NULL_TREE || init == error_mark_node)
489 		return;
490 
491 	if (TREE_CODE(init) != CONSTRUCTOR)
492 		return;
493 
494 	len = CONSTRUCTOR_NELTS(init);
495         if (!len)
496 		return;
497 
498 	lastval = CONSTRUCTOR_ELT(init, CONSTRUCTOR_NELTS(init) - 1)->value;
499 	lastidx = CONSTRUCTOR_ELT(init, CONSTRUCTOR_NELTS(init) - 1)->index;
500 
501 	for (field = TYPE_FIELDS(TREE_TYPE(decl)); TREE_CHAIN(field); field = TREE_CHAIN(field))
502 		;
503 
504 	if (lastidx != field)
505 		return;
506 
507 	if (TREE_CODE(lastval) != STRING_CST) {
508 		error("Only string constants are supported as initializers "
509 		      "for randomized structures with flexible arrays");
510 		return;
511 	}
512 
513 	flexsize = bitsize_int(TREE_STRING_LENGTH(lastval) *
514 		tree_to_uhwi(TYPE_SIZE(TREE_TYPE(TREE_TYPE(lastval)))));
515 
516 	DECL_SIZE(decl) = size_binop(PLUS_EXPR, TYPE_SIZE(type), flexsize);
517 
518 	return;
519 }
520 
521 
522 static void randomize_layout_finish_decl(void *event_data, void *data)
523 {
524 	tree decl = (tree)event_data;
525 	tree type;
526 
527 	if (decl == NULL_TREE || decl == error_mark_node)
528 		return;
529 
530 	type = TREE_TYPE(decl);
531 
532 	if (TREE_CODE(decl) != VAR_DECL)
533 		return;
534 
535 	if (TREE_CODE(type) != RECORD_TYPE && TREE_CODE(type) != UNION_TYPE)
536 		return;
537 
538 	if (!lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(type)))
539 		return;
540 
541 	DECL_SIZE(decl) = 0;
542 	DECL_SIZE_UNIT(decl) = 0;
543 	SET_DECL_ALIGN(decl, 0);
544 	SET_DECL_MODE (decl, VOIDmode);
545 	SET_DECL_RTL(decl, 0);
546 	update_decl_size(decl);
547 	layout_decl(decl, 0);
548 }
549 
550 static void finish_type(void *event_data, void *data)
551 {
552 	tree type = (tree)event_data;
553 
554 	if (type == NULL_TREE || type == error_mark_node)
555 		return;
556 
557 	if (TREE_CODE(type) != RECORD_TYPE)
558 		return;
559 
560 	if (TYPE_FIELDS(type) == NULL_TREE)
561 		return;
562 
563 	if (lookup_attribute("randomize_considered", TYPE_ATTRIBUTES(type)))
564 		return;
565 
566 #ifdef __DEBUG_PLUGIN
567 	fprintf(stderr, "Calling randomize_type on %s\n", ORIG_TYPE_NAME(type));
568 #endif
569 #ifdef __DEBUG_VERBOSE
570 	debug_tree(type);
571 #endif
572 	randomize_type(type);
573 
574 	return;
575 }
576 
577 static struct attribute_spec randomize_layout_attr = { };
578 static struct attribute_spec no_randomize_layout_attr = { };
579 static struct attribute_spec randomize_considered_attr = { };
580 static struct attribute_spec randomize_performed_attr = { };
581 
582 static void register_attributes(void *event_data, void *data)
583 {
584 	randomize_layout_attr.name		= "randomize_layout";
585 	randomize_layout_attr.type_required	= true;
586 	randomize_layout_attr.handler		= handle_randomize_layout_attr;
587 	randomize_layout_attr.affects_type_identity = true;
588 
589 	no_randomize_layout_attr.name		= "no_randomize_layout";
590 	no_randomize_layout_attr.type_required	= true;
591 	no_randomize_layout_attr.handler	= handle_randomize_layout_attr;
592 	no_randomize_layout_attr.affects_type_identity = true;
593 
594 	randomize_considered_attr.name		= "randomize_considered";
595 	randomize_considered_attr.type_required	= true;
596 	randomize_considered_attr.handler	= handle_randomize_considered_attr;
597 
598 	randomize_performed_attr.name		= "randomize_performed";
599 	randomize_performed_attr.type_required	= true;
600 	randomize_performed_attr.handler	= handle_randomize_performed_attr;
601 
602 	register_attribute(&randomize_layout_attr);
603 	register_attribute(&no_randomize_layout_attr);
604 	register_attribute(&randomize_considered_attr);
605 	register_attribute(&randomize_performed_attr);
606 }
607 
608 static void check_bad_casts_in_constructor(tree var, tree init)
609 {
610 	unsigned HOST_WIDE_INT idx;
611 	tree field, val;
612 	tree field_type, val_type;
613 
614 	FOR_EACH_CONSTRUCTOR_ELT(CONSTRUCTOR_ELTS(init), idx, field, val) {
615 		if (TREE_CODE(val) == CONSTRUCTOR) {
616 			check_bad_casts_in_constructor(var, val);
617 			continue;
618 		}
619 
620 		/* pipacs' plugin creates franken-arrays that differ from those produced by
621 		   normal code which all have valid 'field' trees. work around this */
622 		if (field == NULL_TREE)
623 			continue;
624 		field_type = TREE_TYPE(field);
625 		val_type = TREE_TYPE(val);
626 
627 		if (TREE_CODE(field_type) != POINTER_TYPE || TREE_CODE(val_type) != POINTER_TYPE)
628 			continue;
629 
630 		if (field_type == val_type)
631 			continue;
632 
633 		field_type = TYPE_MAIN_VARIANT(strip_array_types(TYPE_MAIN_VARIANT(TREE_TYPE(field_type))));
634 		val_type = TYPE_MAIN_VARIANT(strip_array_types(TYPE_MAIN_VARIANT(TREE_TYPE(val_type))));
635 
636 		if (field_type == void_type_node)
637 			continue;
638 		if (field_type == val_type)
639 			continue;
640 		if (TREE_CODE(val_type) != RECORD_TYPE)
641 			continue;
642 
643 		if (!lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(val_type)))
644 			continue;
645 		MISMATCH(DECL_SOURCE_LOCATION(var), "constructor\n", TYPE_MAIN_VARIANT(field_type), TYPE_MAIN_VARIANT(val_type));
646 	}
647 }
648 
649 /* derived from the constify plugin */
650 static void check_global_variables(void *event_data, void *data)
651 {
652 	struct varpool_node *node;
653 	tree init;
654 
655 	FOR_EACH_VARIABLE(node) {
656 		tree var = NODE_DECL(node);
657 		init = DECL_INITIAL(var);
658 		if (init == NULL_TREE)
659 			continue;
660 
661 		if (TREE_CODE(init) != CONSTRUCTOR)
662 			continue;
663 
664 		check_bad_casts_in_constructor(var, init);
665 	}
666 }
667 
668 static bool dominated_by_is_err(const_tree rhs, basic_block bb)
669 {
670 	basic_block dom;
671 	gimple dom_stmt;
672 	gimple call_stmt;
673 	const_tree dom_lhs;
674 	const_tree poss_is_err_cond;
675 	const_tree poss_is_err_func;
676 	const_tree is_err_arg;
677 
678 	dom = get_immediate_dominator(CDI_DOMINATORS, bb);
679 	if (!dom)
680 		return false;
681 
682 	dom_stmt = last_stmt(dom);
683 	if (!dom_stmt)
684 		return false;
685 
686 	if (gimple_code(dom_stmt) != GIMPLE_COND)
687 		return false;
688 
689 	if (gimple_cond_code(dom_stmt) != NE_EXPR)
690 		return false;
691 
692 	if (!integer_zerop(gimple_cond_rhs(dom_stmt)))
693 		return false;
694 
695 	poss_is_err_cond = gimple_cond_lhs(dom_stmt);
696 
697 	if (TREE_CODE(poss_is_err_cond) != SSA_NAME)
698 		return false;
699 
700 	call_stmt = SSA_NAME_DEF_STMT(poss_is_err_cond);
701 
702 	if (gimple_code(call_stmt) != GIMPLE_CALL)
703 		return false;
704 
705 	dom_lhs = gimple_get_lhs(call_stmt);
706 	poss_is_err_func = gimple_call_fndecl(call_stmt);
707 	if (!poss_is_err_func)
708 		return false;
709 	if (dom_lhs != poss_is_err_cond)
710 		return false;
711 	if (strcmp(DECL_NAME_POINTER(poss_is_err_func), "IS_ERR"))
712 		return false;
713 
714 	is_err_arg = gimple_call_arg(call_stmt, 0);
715 	if (!is_err_arg)
716 		return false;
717 
718 	if (is_err_arg != rhs)
719 		return false;
720 
721 	return true;
722 }
723 
724 static void handle_local_var_initializers(void)
725 {
726 	tree var;
727 	unsigned int i;
728 
729 	FOR_EACH_LOCAL_DECL(cfun, i, var) {
730 		tree init = DECL_INITIAL(var);
731 		if (!init)
732 			continue;
733 		if (TREE_CODE(init) != CONSTRUCTOR)
734 			continue;
735 		check_bad_casts_in_constructor(var, init);
736 	}
737 }
738 
739 static bool type_name_eq(gimple stmt, const_tree type_tree, const char *wanted_name)
740 {
741 	const char *type_name;
742 
743 	if (type_tree == NULL_TREE)
744 		return false;
745 
746 	switch (TREE_CODE(type_tree)) {
747 	case RECORD_TYPE:
748 		type_name = TYPE_NAME_POINTER(type_tree);
749 		break;
750 	case INTEGER_TYPE:
751 		if (TYPE_PRECISION(type_tree) == CHAR_TYPE_SIZE)
752 			type_name = "char";
753 		else {
754 			INFORM(gimple_location(stmt), "found non-char INTEGER_TYPE cast comparison: %qT\n", type_tree);
755 			debug_tree(type_tree);
756 			return false;
757 		}
758 		break;
759 	case POINTER_TYPE:
760 		if (TREE_CODE(TREE_TYPE(type_tree)) == VOID_TYPE) {
761 			type_name = "void *";
762 			break;
763 		} else {
764 			INFORM(gimple_location(stmt), "found non-void POINTER_TYPE cast comparison %qT\n", type_tree);
765 			debug_tree(type_tree);
766 			return false;
767 		}
768 	default:
769 		INFORM(gimple_location(stmt), "unhandled cast comparison: %qT\n", type_tree);
770 		debug_tree(type_tree);
771 		return false;
772 	}
773 
774 	return strcmp(type_name, wanted_name) == 0;
775 }
776 
777 static bool whitelisted_cast(gimple stmt, const_tree lhs_tree, const_tree rhs_tree)
778 {
779 	const struct whitelist_entry *entry;
780 	expanded_location xloc = expand_location(gimple_location(stmt));
781 
782 	for (entry = whitelist; entry->pathname; entry++) {
783 		if (!strstr(xloc.file, entry->pathname))
784 			continue;
785 
786 		if (type_name_eq(stmt, lhs_tree, entry->lhs) && type_name_eq(stmt, rhs_tree, entry->rhs))
787 			return true;
788 	}
789 
790 	return false;
791 }
792 
793 /*
794  * iterate over all statements to find "bad" casts:
795  * those where the address of the start of a structure is cast
796  * to a pointer of a structure of a different type, or a
797  * structure pointer type is cast to a different structure pointer type
798  */
799 static unsigned int find_bad_casts_execute(void)
800 {
801 	basic_block bb;
802 
803 	handle_local_var_initializers();
804 
805 	FOR_EACH_BB_FN(bb, cfun) {
806 		gimple_stmt_iterator gsi;
807 
808 		for (gsi = gsi_start_bb(bb); !gsi_end_p(gsi); gsi_next(&gsi)) {
809 			gimple stmt;
810 			const_tree lhs;
811 			const_tree lhs_type;
812 			const_tree rhs1;
813 			const_tree rhs_type;
814 			const_tree ptr_lhs_type;
815 			const_tree ptr_rhs_type;
816 			const_tree op0;
817 			const_tree op0_type;
818 			enum tree_code rhs_code;
819 
820 			stmt = gsi_stmt(gsi);
821 
822 #ifdef __DEBUG_PLUGIN
823 #ifdef __DEBUG_VERBOSE
824 			debug_gimple_stmt(stmt);
825 			debug_tree(gimple_get_lhs(stmt));
826 #endif
827 #endif
828 
829 			if (gimple_code(stmt) != GIMPLE_ASSIGN)
830 				continue;
831 
832 #ifdef __DEBUG_PLUGIN
833 #ifdef __DEBUG_VERBOSE
834 			debug_tree(gimple_assign_rhs1(stmt));
835 #endif
836 #endif
837 
838 
839 			rhs_code = gimple_assign_rhs_code(stmt);
840 
841 			if (rhs_code != ADDR_EXPR && rhs_code != SSA_NAME)
842 				continue;
843 
844 			lhs = gimple_get_lhs(stmt);
845 			lhs_type = TREE_TYPE(lhs);
846 			rhs1 = gimple_assign_rhs1(stmt);
847 			rhs_type = TREE_TYPE(rhs1);
848 
849 			if (TREE_CODE(rhs_type) != POINTER_TYPE ||
850 			    TREE_CODE(lhs_type) != POINTER_TYPE)
851 				continue;
852 
853 			ptr_lhs_type = TYPE_MAIN_VARIANT(strip_array_types(TYPE_MAIN_VARIANT(TREE_TYPE(lhs_type))));
854 			ptr_rhs_type = TYPE_MAIN_VARIANT(strip_array_types(TYPE_MAIN_VARIANT(TREE_TYPE(rhs_type))));
855 
856 			if (ptr_rhs_type == void_type_node)
857 				continue;
858 
859 			if (ptr_lhs_type == void_type_node)
860 				continue;
861 
862 			if (dominated_by_is_err(rhs1, bb))
863 				continue;
864 
865 			if (TREE_CODE(ptr_rhs_type) != RECORD_TYPE) {
866 #ifndef __DEBUG_PLUGIN
867 				if (lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(ptr_lhs_type)))
868 #endif
869 				{
870 					if (!whitelisted_cast(stmt, ptr_lhs_type, ptr_rhs_type))
871 						MISMATCH(gimple_location(stmt), "rhs", ptr_lhs_type, ptr_rhs_type);
872 				}
873 				continue;
874 			}
875 
876 			if (rhs_code == SSA_NAME && ptr_lhs_type == ptr_rhs_type)
877 				continue;
878 
879 			if (rhs_code == ADDR_EXPR) {
880 				op0 = TREE_OPERAND(rhs1, 0);
881 
882 				if (op0 == NULL_TREE)
883 					continue;
884 
885 				if (TREE_CODE(op0) != VAR_DECL)
886 					continue;
887 
888 				op0_type = TYPE_MAIN_VARIANT(strip_array_types(TYPE_MAIN_VARIANT(TREE_TYPE(op0))));
889 				if (op0_type == ptr_lhs_type)
890 					continue;
891 
892 #ifndef __DEBUG_PLUGIN
893 				if (lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(op0_type)))
894 #endif
895 				{
896 					if (!whitelisted_cast(stmt, ptr_lhs_type, op0_type))
897 						MISMATCH(gimple_location(stmt), "op0", ptr_lhs_type, op0_type);
898 				}
899 			} else {
900 				const_tree ssa_name_var = SSA_NAME_VAR(rhs1);
901 				/* skip bogus type casts introduced by container_of */
902 				if (ssa_name_var != NULL_TREE && DECL_NAME(ssa_name_var) &&
903 				    !strcmp((const char *)DECL_NAME_POINTER(ssa_name_var), "__mptr"))
904 					continue;
905 #ifndef __DEBUG_PLUGIN
906 				if (lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(ptr_rhs_type)))
907 #endif
908 				{
909 					if (!whitelisted_cast(stmt, ptr_lhs_type, ptr_rhs_type))
910 						MISMATCH(gimple_location(stmt), "ssa", ptr_lhs_type, ptr_rhs_type);
911 				}
912 			}
913 
914 		}
915 	}
916 	return 0;
917 }
918 
919 #define PASS_NAME find_bad_casts
920 #define NO_GATE
921 #define TODO_FLAGS_FINISH TODO_dump_func
922 #include "gcc-generate-gimple-pass.h"
923 
924 __visible int plugin_init(struct plugin_name_args *plugin_info, struct plugin_gcc_version *version)
925 {
926 	int i;
927 	const char * const plugin_name = plugin_info->base_name;
928 	const int argc = plugin_info->argc;
929 	const struct plugin_argument * const argv = plugin_info->argv;
930 	bool enable = true;
931 	int obtained_seed = 0;
932 	struct register_pass_info find_bad_casts_pass_info;
933 
934 	find_bad_casts_pass_info.pass			= make_find_bad_casts_pass();
935 	find_bad_casts_pass_info.reference_pass_name	= "ssa";
936 	find_bad_casts_pass_info.ref_pass_instance_number	= 1;
937 	find_bad_casts_pass_info.pos_op			= PASS_POS_INSERT_AFTER;
938 
939 	if (!plugin_default_version_check(version, &gcc_version)) {
940 		error(G_("incompatible gcc/plugin versions"));
941 		return 1;
942 	}
943 
944 	if (strncmp(lang_hooks.name, "GNU C", 5) && !strncmp(lang_hooks.name, "GNU C+", 6)) {
945 		inform(UNKNOWN_LOCATION, G_("%s supports C only, not %s"), plugin_name, lang_hooks.name);
946 		enable = false;
947 	}
948 
949 	for (i = 0; i < argc; ++i) {
950 		if (!strcmp(argv[i].key, "disable")) {
951 			enable = false;
952 			continue;
953 		}
954 		if (!strcmp(argv[i].key, "performance-mode")) {
955 			performance_mode = 1;
956 			continue;
957 		}
958 		error(G_("unknown option '-fplugin-arg-%s-%s'"), plugin_name, argv[i].key);
959 	}
960 
961 	if (strlen(randstruct_seed) != 64) {
962 		error(G_("invalid seed value supplied for %s plugin"), plugin_name);
963 		return 1;
964 	}
965 	obtained_seed = sscanf(randstruct_seed, "%016llx%016llx%016llx%016llx",
966 		&shuffle_seed[0], &shuffle_seed[1], &shuffle_seed[2], &shuffle_seed[3]);
967 	if (obtained_seed != 4) {
968 		error(G_("Invalid seed supplied for %s plugin"), plugin_name);
969 		return 1;
970 	}
971 
972 	register_callback(plugin_name, PLUGIN_INFO, NULL, &randomize_layout_plugin_info);
973 	if (enable) {
974 		register_callback(plugin_name, PLUGIN_ALL_IPA_PASSES_START, check_global_variables, NULL);
975 		register_callback(plugin_name, PLUGIN_PASS_MANAGER_SETUP, NULL, &find_bad_casts_pass_info);
976 		register_callback(plugin_name, PLUGIN_FINISH_TYPE, finish_type, NULL);
977 		register_callback(plugin_name, PLUGIN_FINISH_DECL, randomize_layout_finish_decl, NULL);
978 	}
979 	register_callback(plugin_name, PLUGIN_ATTRIBUTES, register_attributes, NULL);
980 
981 	return 0;
982 }
983