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