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