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