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