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