gcc-plugins: Use dynamic initializers
[muen/linux.git] / scripts / gcc-plugins / latent_entropy_plugin.c
1 /*
2  * Copyright 2012-2016 by the PaX Team <pageexec@freemail.hu>
3  * Copyright 2016 by Emese Revfy <re.emese@gmail.com>
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  * This gcc plugin helps generate a little bit of entropy from program state,
12  * used throughout the uptime of the kernel. Here is an instrumentation example:
13  *
14  * before:
15  * void __latent_entropy test(int argc, char *argv[])
16  * {
17  *      if (argc <= 1)
18  *              printf("%s: no command arguments :(\n", *argv);
19  *      else
20  *              printf("%s: %d command arguments!\n", *argv, args - 1);
21  * }
22  *
23  * after:
24  * void __latent_entropy test(int argc, char *argv[])
25  * {
26  *      // latent_entropy_execute() 1.
27  *      unsigned long local_entropy;
28  *      // init_local_entropy() 1.
29  *      void *local_entropy_frameaddr;
30  *      // init_local_entropy() 3.
31  *      unsigned long tmp_latent_entropy;
32  *
33  *      // init_local_entropy() 2.
34  *      local_entropy_frameaddr = __builtin_frame_address(0);
35  *      local_entropy = (unsigned long) local_entropy_frameaddr;
36  *
37  *      // init_local_entropy() 4.
38  *      tmp_latent_entropy = latent_entropy;
39  *      // init_local_entropy() 5.
40  *      local_entropy ^= tmp_latent_entropy;
41  *
42  *      // latent_entropy_execute() 3.
43  *      if (argc <= 1) {
44  *              // perturb_local_entropy()
45  *              local_entropy += 4623067384293424948;
46  *              printf("%s: no command arguments :(\n", *argv);
47  *              // perturb_local_entropy()
48  *      } else {
49  *              local_entropy ^= 3896280633962944730;
50  *              printf("%s: %d command arguments!\n", *argv, args - 1);
51  *      }
52  *
53  *      // latent_entropy_execute() 4.
54  *      tmp_latent_entropy = rol(tmp_latent_entropy, local_entropy);
55  *      latent_entropy = tmp_latent_entropy;
56  * }
57  *
58  * TODO:
59  * - add ipa pass to identify not explicitly marked candidate functions
60  * - mix in more program state (function arguments/return values,
61  *   loop variables, etc)
62  * - more instrumentation control via attribute parameters
63  *
64  * BUGS:
65  * - none known
66  *
67  * Options:
68  * -fplugin-arg-latent_entropy_plugin-disable
69  *
70  * Attribute: __attribute__((latent_entropy))
71  *  The latent_entropy gcc attribute can be only on functions and variables.
72  *  If it is on a function then the plugin will instrument it. If the attribute
73  *  is on a variable then the plugin will initialize it with a random value.
74  *  The variable must be an integer, an integer array type or a structure
75  *  with integer fields.
76  */
77
78 #include "gcc-common.h"
79
80 __visible int plugin_is_GPL_compatible;
81
82 static GTY(()) tree latent_entropy_decl;
83
84 static struct plugin_info latent_entropy_plugin_info = {
85         .version        = "201606141920vanilla",
86         .help           = "disable\tturn off latent entropy instrumentation\n",
87 };
88
89 static unsigned HOST_WIDE_INT seed;
90 /*
91  * get_random_seed() (this is a GCC function) generates the seed.
92  * This is a simple random generator without any cryptographic security because
93  * the entropy doesn't come from here.
94  */
95 static unsigned HOST_WIDE_INT get_random_const(void)
96 {
97         unsigned int i;
98         unsigned HOST_WIDE_INT ret = 0;
99
100         for (i = 0; i < 8 * sizeof(ret); i++) {
101                 ret = (ret << 1) | (seed & 1);
102                 seed >>= 1;
103                 if (ret & 1)
104                         seed ^= 0xD800000000000000ULL;
105         }
106
107         return ret;
108 }
109
110 static tree tree_get_random_const(tree type)
111 {
112         unsigned long long mask;
113
114         mask = 1ULL << (TREE_INT_CST_LOW(TYPE_SIZE(type)) - 1);
115         mask = 2 * (mask - 1) + 1;
116
117         if (TYPE_UNSIGNED(type))
118                 return build_int_cstu(type, mask & get_random_const());
119         return build_int_cst(type, mask & get_random_const());
120 }
121
122 static tree handle_latent_entropy_attribute(tree *node, tree name,
123                                                 tree args __unused,
124                                                 int flags __unused,
125                                                 bool *no_add_attrs)
126 {
127         tree type;
128 #if BUILDING_GCC_VERSION <= 4007
129         VEC(constructor_elt, gc) *vals;
130 #else
131         vec<constructor_elt, va_gc> *vals;
132 #endif
133
134         switch (TREE_CODE(*node)) {
135         default:
136                 *no_add_attrs = true;
137                 error("%qE attribute only applies to functions and variables",
138                         name);
139                 break;
140
141         case VAR_DECL:
142                 if (DECL_INITIAL(*node)) {
143                         *no_add_attrs = true;
144                         error("variable %qD with %qE attribute must not be initialized",
145                                 *node, name);
146                         break;
147                 }
148
149                 if (!TREE_STATIC(*node)) {
150                         *no_add_attrs = true;
151                         error("variable %qD with %qE attribute must not be local",
152                                 *node, name);
153                         break;
154                 }
155
156                 type = TREE_TYPE(*node);
157                 switch (TREE_CODE(type)) {
158                 default:
159                         *no_add_attrs = true;
160                         error("variable %qD with %qE attribute must be an integer or a fixed length integer array type or a fixed sized structure with integer fields",
161                                 *node, name);
162                         break;
163
164                 case RECORD_TYPE: {
165                         tree fld, lst = TYPE_FIELDS(type);
166                         unsigned int nelt = 0;
167
168                         for (fld = lst; fld; nelt++, fld = TREE_CHAIN(fld)) {
169                                 tree fieldtype;
170
171                                 fieldtype = TREE_TYPE(fld);
172                                 if (TREE_CODE(fieldtype) == INTEGER_TYPE)
173                                         continue;
174
175                                 *no_add_attrs = true;
176                                 error("structure variable %qD with %qE attribute has a non-integer field %qE",
177                                         *node, name, fld);
178                                 break;
179                         }
180
181                         if (fld)
182                                 break;
183
184 #if BUILDING_GCC_VERSION <= 4007
185                         vals = VEC_alloc(constructor_elt, gc, nelt);
186 #else
187                         vec_alloc(vals, nelt);
188 #endif
189
190                         for (fld = lst; fld; fld = TREE_CHAIN(fld)) {
191                                 tree random_const, fld_t = TREE_TYPE(fld);
192
193                                 random_const = tree_get_random_const(fld_t);
194                                 CONSTRUCTOR_APPEND_ELT(vals, fld, random_const);
195                         }
196
197                         /* Initialize the fields with random constants */
198                         DECL_INITIAL(*node) = build_constructor(type, vals);
199                         break;
200                 }
201
202                 /* Initialize the variable with a random constant */
203                 case INTEGER_TYPE:
204                         DECL_INITIAL(*node) = tree_get_random_const(type);
205                         break;
206
207                 case ARRAY_TYPE: {
208                         tree elt_type, array_size, elt_size;
209                         unsigned int i, nelt;
210                         HOST_WIDE_INT array_size_int, elt_size_int;
211
212                         elt_type = TREE_TYPE(type);
213                         elt_size = TYPE_SIZE_UNIT(TREE_TYPE(type));
214                         array_size = TYPE_SIZE_UNIT(type);
215
216                         if (TREE_CODE(elt_type) != INTEGER_TYPE || !array_size
217                                 || TREE_CODE(array_size) != INTEGER_CST) {
218                                 *no_add_attrs = true;
219                                 error("array variable %qD with %qE attribute must be a fixed length integer array type",
220                                         *node, name);
221                                 break;
222                         }
223
224                         array_size_int = TREE_INT_CST_LOW(array_size);
225                         elt_size_int = TREE_INT_CST_LOW(elt_size);
226                         nelt = array_size_int / elt_size_int;
227
228 #if BUILDING_GCC_VERSION <= 4007
229                         vals = VEC_alloc(constructor_elt, gc, nelt);
230 #else
231                         vec_alloc(vals, nelt);
232 #endif
233
234                         for (i = 0; i < nelt; i++) {
235                                 tree cst = size_int(i);
236                                 tree rand_cst = tree_get_random_const(elt_type);
237
238                                 CONSTRUCTOR_APPEND_ELT(vals, cst, rand_cst);
239                         }
240
241                         /*
242                          * Initialize the elements of the array with random
243                          * constants
244                          */
245                         DECL_INITIAL(*node) = build_constructor(type, vals);
246                         break;
247                 }
248                 }
249                 break;
250
251         case FUNCTION_DECL:
252                 break;
253         }
254
255         return NULL_TREE;
256 }
257
258 static struct attribute_spec latent_entropy_attr = { };
259
260 static void register_attributes(void *event_data __unused, void *data __unused)
261 {
262         latent_entropy_attr.name                = "latent_entropy";
263         latent_entropy_attr.decl_required       = true;
264         latent_entropy_attr.handler             = handle_latent_entropy_attribute;
265
266         register_attribute(&latent_entropy_attr);
267 }
268
269 static bool latent_entropy_gate(void)
270 {
271         tree list;
272
273         /* don't bother with noreturn functions for now */
274         if (TREE_THIS_VOLATILE(current_function_decl))
275                 return false;
276
277         /* gcc-4.5 doesn't discover some trivial noreturn functions */
278         if (EDGE_COUNT(EXIT_BLOCK_PTR_FOR_FN(cfun)->preds) == 0)
279                 return false;
280
281         list = DECL_ATTRIBUTES(current_function_decl);
282         return lookup_attribute("latent_entropy", list) != NULL_TREE;
283 }
284
285 static tree create_var(tree type, const char *name)
286 {
287         tree var;
288
289         var = create_tmp_var(type, name);
290         add_referenced_var(var);
291         mark_sym_for_renaming(var);
292         return var;
293 }
294
295 /*
296  * Set up the next operation and its constant operand to use in the latent
297  * entropy PRNG. When RHS is specified, the request is for perturbing the
298  * local latent entropy variable, otherwise it is for perturbing the global
299  * latent entropy variable where the two operands are already given by the
300  * local and global latent entropy variables themselves.
301  *
302  * The operation is one of add/xor/rol when instrumenting the local entropy
303  * variable and one of add/xor when perturbing the global entropy variable.
304  * Rotation is not used for the latter case because it would transmit less
305  * entropy to the global variable than the other two operations.
306  */
307 static enum tree_code get_op(tree *rhs)
308 {
309         static enum tree_code op;
310         unsigned HOST_WIDE_INT random_const;
311
312         random_const = get_random_const();
313
314         switch (op) {
315         case BIT_XOR_EXPR:
316                 op = PLUS_EXPR;
317                 break;
318
319         case PLUS_EXPR:
320                 if (rhs) {
321                         op = LROTATE_EXPR;
322                         /*
323                          * This code limits the value of random_const to
324                          * the size of a long for the rotation
325                          */
326                         random_const %= TYPE_PRECISION(long_unsigned_type_node);
327                         break;
328                 }
329
330         case LROTATE_EXPR:
331         default:
332                 op = BIT_XOR_EXPR;
333                 break;
334         }
335         if (rhs)
336                 *rhs = build_int_cstu(long_unsigned_type_node, random_const);
337         return op;
338 }
339
340 static gimple create_assign(enum tree_code code, tree lhs, tree op1,
341                                 tree op2)
342 {
343         return gimple_build_assign_with_ops(code, lhs, op1, op2);
344 }
345
346 static void perturb_local_entropy(basic_block bb, tree local_entropy)
347 {
348         gimple_stmt_iterator gsi;
349         gimple assign;
350         tree rhs;
351         enum tree_code op;
352
353         op = get_op(&rhs);
354         assign = create_assign(op, local_entropy, local_entropy, rhs);
355         gsi = gsi_after_labels(bb);
356         gsi_insert_before(&gsi, assign, GSI_NEW_STMT);
357         update_stmt(assign);
358 }
359
360 static void __perturb_latent_entropy(gimple_stmt_iterator *gsi,
361                                         tree local_entropy)
362 {
363         gimple assign;
364         tree temp;
365         enum tree_code op;
366
367         /* 1. create temporary copy of latent_entropy */
368         temp = create_var(long_unsigned_type_node, "temp_latent_entropy");
369
370         /* 2. read... */
371         add_referenced_var(latent_entropy_decl);
372         mark_sym_for_renaming(latent_entropy_decl);
373         assign = gimple_build_assign(temp, latent_entropy_decl);
374         gsi_insert_before(gsi, assign, GSI_NEW_STMT);
375         update_stmt(assign);
376
377         /* 3. ...modify... */
378         op = get_op(NULL);
379         assign = create_assign(op, temp, temp, local_entropy);
380         gsi_insert_after(gsi, assign, GSI_NEW_STMT);
381         update_stmt(assign);
382
383         /* 4. ...write latent_entropy */
384         assign = gimple_build_assign(latent_entropy_decl, temp);
385         gsi_insert_after(gsi, assign, GSI_NEW_STMT);
386         update_stmt(assign);
387 }
388
389 static bool handle_tail_calls(basic_block bb, tree local_entropy)
390 {
391         gimple_stmt_iterator gsi;
392
393         for (gsi = gsi_start_bb(bb); !gsi_end_p(gsi); gsi_next(&gsi)) {
394                 gcall *call;
395                 gimple stmt = gsi_stmt(gsi);
396
397                 if (!is_gimple_call(stmt))
398                         continue;
399
400                 call = as_a_gcall(stmt);
401                 if (!gimple_call_tail_p(call))
402                         continue;
403
404                 __perturb_latent_entropy(&gsi, local_entropy);
405                 return true;
406         }
407
408         return false;
409 }
410
411 static void perturb_latent_entropy(tree local_entropy)
412 {
413         edge_iterator ei;
414         edge e, last_bb_e;
415         basic_block last_bb;
416
417         gcc_assert(single_pred_p(EXIT_BLOCK_PTR_FOR_FN(cfun)));
418         last_bb_e = single_pred_edge(EXIT_BLOCK_PTR_FOR_FN(cfun));
419
420         FOR_EACH_EDGE(e, ei, last_bb_e->src->preds) {
421                 if (ENTRY_BLOCK_PTR_FOR_FN(cfun) == e->src)
422                         continue;
423                 if (EXIT_BLOCK_PTR_FOR_FN(cfun) == e->src)
424                         continue;
425
426                 handle_tail_calls(e->src, local_entropy);
427         }
428
429         last_bb = single_pred(EXIT_BLOCK_PTR_FOR_FN(cfun));
430         if (!handle_tail_calls(last_bb, local_entropy)) {
431                 gimple_stmt_iterator gsi = gsi_last_bb(last_bb);
432
433                 __perturb_latent_entropy(&gsi, local_entropy);
434         }
435 }
436
437 static void init_local_entropy(basic_block bb, tree local_entropy)
438 {
439         gimple assign, call;
440         tree frame_addr, rand_const, tmp, fndecl, udi_frame_addr;
441         enum tree_code op;
442         unsigned HOST_WIDE_INT rand_cst;
443         gimple_stmt_iterator gsi = gsi_after_labels(bb);
444
445         /* 1. create local_entropy_frameaddr */
446         frame_addr = create_var(ptr_type_node, "local_entropy_frameaddr");
447
448         /* 2. local_entropy_frameaddr = __builtin_frame_address() */
449         fndecl = builtin_decl_implicit(BUILT_IN_FRAME_ADDRESS);
450         call = gimple_build_call(fndecl, 1, integer_zero_node);
451         gimple_call_set_lhs(call, frame_addr);
452         gsi_insert_before(&gsi, call, GSI_NEW_STMT);
453         update_stmt(call);
454
455         udi_frame_addr = fold_convert(long_unsigned_type_node, frame_addr);
456         assign = gimple_build_assign(local_entropy, udi_frame_addr);
457         gsi_insert_after(&gsi, assign, GSI_NEW_STMT);
458         update_stmt(assign);
459
460         /* 3. create temporary copy of latent_entropy */
461         tmp = create_var(long_unsigned_type_node, "temp_latent_entropy");
462
463         /* 4. read the global entropy variable into local entropy */
464         add_referenced_var(latent_entropy_decl);
465         mark_sym_for_renaming(latent_entropy_decl);
466         assign = gimple_build_assign(tmp, latent_entropy_decl);
467         gsi_insert_after(&gsi, assign, GSI_NEW_STMT);
468         update_stmt(assign);
469
470         /* 5. mix local_entropy_frameaddr into local entropy */
471         assign = create_assign(BIT_XOR_EXPR, local_entropy, local_entropy, tmp);
472         gsi_insert_after(&gsi, assign, GSI_NEW_STMT);
473         update_stmt(assign);
474
475         rand_cst = get_random_const();
476         rand_const = build_int_cstu(long_unsigned_type_node, rand_cst);
477         op = get_op(NULL);
478         assign = create_assign(op, local_entropy, local_entropy, rand_const);
479         gsi_insert_after(&gsi, assign, GSI_NEW_STMT);
480         update_stmt(assign);
481 }
482
483 static bool create_latent_entropy_decl(void)
484 {
485         varpool_node_ptr node;
486
487         if (latent_entropy_decl != NULL_TREE)
488                 return true;
489
490         FOR_EACH_VARIABLE(node) {
491                 tree name, var = NODE_DECL(node);
492
493                 if (DECL_NAME_LENGTH(var) < sizeof("latent_entropy") - 1)
494                         continue;
495
496                 name = DECL_NAME(var);
497                 if (strcmp(IDENTIFIER_POINTER(name), "latent_entropy"))
498                         continue;
499
500                 latent_entropy_decl = var;
501                 break;
502         }
503
504         return latent_entropy_decl != NULL_TREE;
505 }
506
507 static unsigned int latent_entropy_execute(void)
508 {
509         basic_block bb;
510         tree local_entropy;
511
512         if (!create_latent_entropy_decl())
513                 return 0;
514
515         /* prepare for step 2 below */
516         gcc_assert(single_succ_p(ENTRY_BLOCK_PTR_FOR_FN(cfun)));
517         bb = single_succ(ENTRY_BLOCK_PTR_FOR_FN(cfun));
518         if (!single_pred_p(bb)) {
519                 split_edge(single_succ_edge(ENTRY_BLOCK_PTR_FOR_FN(cfun)));
520                 gcc_assert(single_succ_p(ENTRY_BLOCK_PTR_FOR_FN(cfun)));
521                 bb = single_succ(ENTRY_BLOCK_PTR_FOR_FN(cfun));
522         }
523
524         /* 1. create the local entropy variable */
525         local_entropy = create_var(long_unsigned_type_node, "local_entropy");
526
527         /* 2. initialize the local entropy variable */
528         init_local_entropy(bb, local_entropy);
529
530         bb = bb->next_bb;
531
532         /*
533          * 3. instrument each BB with an operation on the
534          *    local entropy variable
535          */
536         while (bb != EXIT_BLOCK_PTR_FOR_FN(cfun)) {
537                 perturb_local_entropy(bb, local_entropy);
538                 bb = bb->next_bb;
539         };
540
541         /* 4. mix local entropy into the global entropy variable */
542         perturb_latent_entropy(local_entropy);
543         return 0;
544 }
545
546 static void latent_entropy_start_unit(void *gcc_data __unused,
547                                         void *user_data __unused)
548 {
549         tree type, id;
550         int quals;
551
552         seed = get_random_seed(false);
553
554         if (in_lto_p)
555                 return;
556
557         /* extern volatile unsigned long latent_entropy */
558         quals = TYPE_QUALS(long_unsigned_type_node) | TYPE_QUAL_VOLATILE;
559         type = build_qualified_type(long_unsigned_type_node, quals);
560         id = get_identifier("latent_entropy");
561         latent_entropy_decl = build_decl(UNKNOWN_LOCATION, VAR_DECL, id, type);
562
563         TREE_STATIC(latent_entropy_decl) = 1;
564         TREE_PUBLIC(latent_entropy_decl) = 1;
565         TREE_USED(latent_entropy_decl) = 1;
566         DECL_PRESERVE_P(latent_entropy_decl) = 1;
567         TREE_THIS_VOLATILE(latent_entropy_decl) = 1;
568         DECL_EXTERNAL(latent_entropy_decl) = 1;
569         DECL_ARTIFICIAL(latent_entropy_decl) = 1;
570         lang_hooks.decls.pushdecl(latent_entropy_decl);
571 }
572
573 #define PASS_NAME latent_entropy
574 #define PROPERTIES_REQUIRED PROP_gimple_leh | PROP_cfg
575 #define TODO_FLAGS_FINISH TODO_verify_ssa | TODO_verify_stmts | TODO_dump_func \
576         | TODO_update_ssa
577 #include "gcc-generate-gimple-pass.h"
578
579 __visible int plugin_init(struct plugin_name_args *plugin_info,
580                           struct plugin_gcc_version *version)
581 {
582         bool enabled = true;
583         const char * const plugin_name = plugin_info->base_name;
584         const int argc = plugin_info->argc;
585         const struct plugin_argument * const argv = plugin_info->argv;
586         int i;
587
588         static const struct ggc_root_tab gt_ggc_r_gt_latent_entropy[] = {
589                 {
590                         .base = &latent_entropy_decl,
591                         .nelt = 1,
592                         .stride = sizeof(latent_entropy_decl),
593                         .cb = &gt_ggc_mx_tree_node,
594                         .pchw = &gt_pch_nx_tree_node
595                 },
596                 LAST_GGC_ROOT_TAB
597         };
598
599         PASS_INFO(latent_entropy, "optimized", 1, PASS_POS_INSERT_BEFORE);
600
601         if (!plugin_default_version_check(version, &gcc_version)) {
602                 error(G_("incompatible gcc/plugin versions"));
603                 return 1;
604         }
605
606         for (i = 0; i < argc; ++i) {
607                 if (!(strcmp(argv[i].key, "disable"))) {
608                         enabled = false;
609                         continue;
610                 }
611                 error(G_("unknown option '-fplugin-arg-%s-%s'"), plugin_name, argv[i].key);
612         }
613
614         register_callback(plugin_name, PLUGIN_INFO, NULL,
615                                 &latent_entropy_plugin_info);
616         if (enabled) {
617                 register_callback(plugin_name, PLUGIN_START_UNIT,
618                                         &latent_entropy_start_unit, NULL);
619                 register_callback(plugin_name, PLUGIN_REGISTER_GGC_ROOTS,
620                                   NULL, (void *)&gt_ggc_r_gt_latent_entropy);
621                 register_callback(plugin_name, PLUGIN_PASS_MANAGER_SETUP, NULL,
622                                         &latent_entropy_pass_info);
623         }
624         register_callback(plugin_name, PLUGIN_ATTRIBUTES, register_attributes,
625                                 NULL);
626
627         return 0;
628 }