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