blob: a18b0d4af4560f8623e9f4185f40a2b0a5daaa30 [file] [log] [blame]
Alexander Popov10e9ae92018-08-17 01:16:59 +03001/*
2 * Copyright 2011-2017 by the PaX Team <pageexec@freemail.hu>
3 * Modified by Alexander Popov <alex.popov@linux.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 is needed for tracking the lowest border of the kernel stack.
12 * It instruments the kernel code inserting stackleak_track_stack() calls:
13 * - after alloca();
14 * - for the functions with a stack frame size greater than or equal
15 * to the "track-min-size" plugin parameter.
16 *
17 * This plugin is ported from grsecurity/PaX. For more information see:
18 * https://grsecurity.net/
19 * https://pax.grsecurity.net/
20 *
21 * Debugging:
22 * - use fprintf() to stderr, debug_generic_expr(), debug_gimple_stmt(),
Alexander Popovfeee1b82020-06-24 15:33:29 +030023 * print_rtl_single() and debug_rtx();
Alexander Popov10e9ae92018-08-17 01:16:59 +030024 * - add "-fdump-tree-all -fdump-rtl-all" to the plugin CFLAGS in
25 * Makefile.gcc-plugins to see the verbose dumps of the gcc passes;
26 * - use gcc -E to understand the preprocessing shenanigans;
27 * - use gcc with enabled CFG/GIMPLE/SSA verification (--enable-checking).
28 */
29
30#include "gcc-common.h"
31
32__visible int plugin_is_GPL_compatible;
33
34static int track_frame_size = -1;
Alexander Popovfeee1b82020-06-24 15:33:29 +030035static bool build_for_x86 = false;
Alexander Popov10e9ae92018-08-17 01:16:59 +030036static const char track_function[] = "stackleak_track_stack";
37
38/*
39 * Mark these global variables (roots) for gcc garbage collector since
40 * they point to the garbage-collected memory.
41 */
42static GTY(()) tree track_function_decl;
43
44static struct plugin_info stackleak_plugin_info = {
45 .version = "201707101337",
46 .help = "track-min-size=nn\ttrack stack for functions with a stack frame size >= nn bytes\n"
Alexander Popovfeee1b82020-06-24 15:33:29 +030047 "arch=target_arch\tspecify target build arch\n"
Alexander Popov10e9ae92018-08-17 01:16:59 +030048 "disable\t\tdo not activate the plugin\n"
49};
50
Alexander Popovfeee1b82020-06-24 15:33:29 +030051static void add_stack_tracking_gcall(gimple_stmt_iterator *gsi, bool after)
Alexander Popov10e9ae92018-08-17 01:16:59 +030052{
53 gimple stmt;
Alexander Popovfeee1b82020-06-24 15:33:29 +030054 gcall *gimple_call;
Alexander Popov10e9ae92018-08-17 01:16:59 +030055 cgraph_node_ptr node;
Alexander Popov10e9ae92018-08-17 01:16:59 +030056 basic_block bb;
57
Alexander Popovfeee1b82020-06-24 15:33:29 +030058 /* Insert calling stackleak_track_stack() */
Alexander Popov10e9ae92018-08-17 01:16:59 +030059 stmt = gimple_build_call(track_function_decl, 0);
Alexander Popovfeee1b82020-06-24 15:33:29 +030060 gimple_call = as_a_gcall(stmt);
61 if (after)
62 gsi_insert_after(gsi, gimple_call, GSI_CONTINUE_LINKING);
63 else
64 gsi_insert_before(gsi, gimple_call, GSI_SAME_STMT);
Alexander Popov10e9ae92018-08-17 01:16:59 +030065
66 /* Update the cgraph */
Alexander Popovfeee1b82020-06-24 15:33:29 +030067 bb = gimple_bb(gimple_call);
Alexander Popov10e9ae92018-08-17 01:16:59 +030068 node = cgraph_get_create_node(track_function_decl);
69 gcc_assert(node);
Alexander Popov10e9ae92018-08-17 01:16:59 +030070 cgraph_create_edge(cgraph_get_node(current_function_decl), node,
Alexander Popovfeee1b82020-06-24 15:33:29 +030071 gimple_call, bb->count,
Kees Cook8d97fb32020-04-02 00:53:47 -070072 compute_call_stmt_bb_frequency(current_function_decl, bb));
Alexander Popov10e9ae92018-08-17 01:16:59 +030073}
74
75static bool is_alloca(gimple stmt)
76{
77 if (gimple_call_builtin_p(stmt, BUILT_IN_ALLOCA))
78 return true;
79
80#if BUILDING_GCC_VERSION >= 4007
81 if (gimple_call_builtin_p(stmt, BUILT_IN_ALLOCA_WITH_ALIGN))
82 return true;
83#endif
84
85 return false;
86}
87
Alexander Popovfeee1b82020-06-24 15:33:29 +030088static tree get_current_stack_pointer_decl(void)
89{
90 varpool_node_ptr node;
91
92 FOR_EACH_VARIABLE(node) {
93 tree var = NODE_DECL(node);
94 tree name = DECL_NAME(var);
95
96 if (DECL_NAME_LENGTH(var) != sizeof("current_stack_pointer") - 1)
97 continue;
98
99 if (strcmp(IDENTIFIER_POINTER(name), "current_stack_pointer"))
100 continue;
101
102 return var;
103 }
104
105 return NULL_TREE;
106}
107
108static void add_stack_tracking_gasm(gimple_stmt_iterator *gsi, bool after)
109{
110 gasm *asm_call = NULL;
111 tree sp_decl, input;
112 vec<tree, va_gc> *inputs = NULL;
113
114 /* 'no_caller_saved_registers' is currently supported only for x86 */
115 gcc_assert(build_for_x86);
116
117 /*
118 * Insert calling stackleak_track_stack() in asm:
119 * asm volatile("call stackleak_track_stack"
120 * :: "r" (current_stack_pointer))
121 * Use ASM_CALL_CONSTRAINT trick from arch/x86/include/asm/asm.h.
122 * This constraint is taken into account during gcc shrink-wrapping
123 * optimization. It is needed to be sure that stackleak_track_stack()
124 * call is inserted after the prologue of the containing function,
125 * when the stack frame is prepared.
126 */
127 sp_decl = get_current_stack_pointer_decl();
128 if (sp_decl == NULL_TREE) {
129 add_stack_tracking_gcall(gsi, after);
130 return;
131 }
132 input = build_tree_list(NULL_TREE, build_const_char_string(2, "r"));
133 input = chainon(NULL_TREE, build_tree_list(input, sp_decl));
134 vec_safe_push(inputs, input);
135 asm_call = gimple_build_asm_vec("call stackleak_track_stack",
136 inputs, NULL, NULL, NULL);
137 gimple_asm_set_volatile(asm_call, true);
138 if (after)
139 gsi_insert_after(gsi, asm_call, GSI_CONTINUE_LINKING);
140 else
141 gsi_insert_before(gsi, asm_call, GSI_SAME_STMT);
142 update_stmt(asm_call);
143}
144
145static void add_stack_tracking(gimple_stmt_iterator *gsi, bool after)
146{
147 /*
148 * The 'no_caller_saved_registers' attribute is used for
149 * stackleak_track_stack(). If the compiler supports this attribute for
150 * the target arch, we can add calling stackleak_track_stack() in asm.
151 * That improves performance: we avoid useless operations with the
152 * caller-saved registers in the functions from which we will remove
153 * stackleak_track_stack() call during the stackleak_cleanup pass.
154 */
155 if (lookup_attribute_spec(get_identifier("no_caller_saved_registers")))
156 add_stack_tracking_gasm(gsi, after);
157 else
158 add_stack_tracking_gcall(gsi, after);
159}
160
Alexander Popov10e9ae92018-08-17 01:16:59 +0300161/*
162 * Work with the GIMPLE representation of the code. Insert the
163 * stackleak_track_stack() call after alloca() and into the beginning
164 * of the function if it is not instrumented.
165 */
166static unsigned int stackleak_instrument_execute(void)
167{
168 basic_block bb, entry_bb;
169 bool prologue_instrumented = false, is_leaf = true;
Alexander Popovfeee1b82020-06-24 15:33:29 +0300170 gimple_stmt_iterator gsi = { 0 };
Alexander Popov10e9ae92018-08-17 01:16:59 +0300171
172 /*
173 * ENTRY_BLOCK_PTR is a basic block which represents possible entry
174 * point of a function. This block does not contain any code and
175 * has a CFG edge to its successor.
176 */
177 gcc_assert(single_succ_p(ENTRY_BLOCK_PTR_FOR_FN(cfun)));
178 entry_bb = single_succ(ENTRY_BLOCK_PTR_FOR_FN(cfun));
179
180 /*
181 * Loop through the GIMPLE statements in each of cfun basic blocks.
182 * cfun is a global variable which represents the function that is
183 * currently processed.
184 */
185 FOR_EACH_BB_FN(bb, cfun) {
186 for (gsi = gsi_start_bb(bb); !gsi_end_p(gsi); gsi_next(&gsi)) {
187 gimple stmt;
188
189 stmt = gsi_stmt(gsi);
190
191 /* Leaf function is a function which makes no calls */
192 if (is_gimple_call(stmt))
193 is_leaf = false;
194
195 if (!is_alloca(stmt))
196 continue;
197
198 /* Insert stackleak_track_stack() call after alloca() */
Alexander Popovfeee1b82020-06-24 15:33:29 +0300199 add_stack_tracking(&gsi, true);
Alexander Popov10e9ae92018-08-17 01:16:59 +0300200 if (bb == entry_bb)
201 prologue_instrumented = true;
202 }
203 }
204
205 if (prologue_instrumented)
206 return 0;
207
208 /*
209 * Special cases to skip the instrumentation.
210 *
211 * Taking the address of static inline functions materializes them,
212 * but we mustn't instrument some of them as the resulting stack
213 * alignment required by the function call ABI will break other
214 * assumptions regarding the expected (but not otherwise enforced)
215 * register clobbering ABI.
216 *
217 * Case in point: native_save_fl on amd64 when optimized for size
218 * clobbers rdx if it were instrumented here.
219 *
220 * TODO: any more special cases?
221 */
222 if (is_leaf &&
223 !TREE_PUBLIC(current_function_decl) &&
224 DECL_DECLARED_INLINE_P(current_function_decl)) {
225 return 0;
226 }
227
228 if (is_leaf &&
229 !strncmp(IDENTIFIER_POINTER(DECL_NAME(current_function_decl)),
230 "_paravirt_", 10)) {
231 return 0;
232 }
233
234 /* Insert stackleak_track_stack() call at the function beginning */
235 bb = entry_bb;
236 if (!single_pred_p(bb)) {
237 /* gcc_assert(bb_loop_depth(bb) ||
238 (bb->flags & BB_IRREDUCIBLE_LOOP)); */
239 split_edge(single_succ_edge(ENTRY_BLOCK_PTR_FOR_FN(cfun)));
240 gcc_assert(single_succ_p(ENTRY_BLOCK_PTR_FOR_FN(cfun)));
241 bb = single_succ(ENTRY_BLOCK_PTR_FOR_FN(cfun));
242 }
243 gsi = gsi_after_labels(bb);
Alexander Popovfeee1b82020-06-24 15:33:29 +0300244 add_stack_tracking(&gsi, false);
Alexander Popov10e9ae92018-08-17 01:16:59 +0300245
246 return 0;
247}
248
249static bool large_stack_frame(void)
250{
251#if BUILDING_GCC_VERSION >= 8000
252 return maybe_ge(get_frame_size(), track_frame_size);
253#else
254 return (get_frame_size() >= track_frame_size);
255#endif
256}
257
Alexander Popovfeee1b82020-06-24 15:33:29 +0300258static void remove_stack_tracking_gcall(void)
Alexander Popov10e9ae92018-08-17 01:16:59 +0300259{
260 rtx_insn *insn, *next;
261
Alexander Popov10e9ae92018-08-17 01:16:59 +0300262 /*
263 * Find stackleak_track_stack() calls. Loop through the chain of insns,
264 * which is an RTL representation of the code for a function.
265 *
266 * The example of a matching insn:
267 * (call_insn 8 4 10 2 (call (mem (symbol_ref ("stackleak_track_stack")
268 * [flags 0x41] <function_decl 0x7f7cd3302a80 stackleak_track_stack>)
269 * [0 stackleak_track_stack S1 A8]) (0)) 675 {*call} (expr_list
270 * (symbol_ref ("stackleak_track_stack") [flags 0x41] <function_decl
271 * 0x7f7cd3302a80 stackleak_track_stack>) (expr_list (0) (nil))) (nil))
272 */
273 for (insn = get_insns(); insn; insn = next) {
274 rtx body;
275
276 next = NEXT_INSN(insn);
277
278 /* Check the expression code of the insn */
279 if (!CALL_P(insn))
280 continue;
281
282 /*
283 * Check the expression code of the insn body, which is an RTL
284 * Expression (RTX) describing the side effect performed by
285 * that insn.
286 */
287 body = PATTERN(insn);
288
289 if (GET_CODE(body) == PARALLEL)
290 body = XVECEXP(body, 0, 0);
291
292 if (GET_CODE(body) != CALL)
293 continue;
294
295 /*
296 * Check the first operand of the call expression. It should
297 * be a mem RTX describing the needed subroutine with a
298 * symbol_ref RTX.
299 */
300 body = XEXP(body, 0);
301 if (GET_CODE(body) != MEM)
302 continue;
303
304 body = XEXP(body, 0);
305 if (GET_CODE(body) != SYMBOL_REF)
306 continue;
307
308 if (SYMBOL_REF_DECL(body) != track_function_decl)
309 continue;
310
311 /* Delete the stackleak_track_stack() call */
312 delete_insn_and_edges(insn);
313#if BUILDING_GCC_VERSION >= 4007 && BUILDING_GCC_VERSION < 8000
314 if (GET_CODE(next) == NOTE &&
315 NOTE_KIND(next) == NOTE_INSN_CALL_ARG_LOCATION) {
316 insn = next;
317 next = NEXT_INSN(insn);
318 delete_insn_and_edges(insn);
319 }
320#endif
321 }
Alexander Popovfeee1b82020-06-24 15:33:29 +0300322}
323
324static bool remove_stack_tracking_gasm(void)
325{
326 bool removed = false;
327 rtx_insn *insn, *next;
328
329 /* 'no_caller_saved_registers' is currently supported only for x86 */
330 gcc_assert(build_for_x86);
331
332 /*
333 * Find stackleak_track_stack() asm calls. Loop through the chain of
334 * insns, which is an RTL representation of the code for a function.
335 *
336 * The example of a matching insn:
337 * (insn 11 5 12 2 (parallel [ (asm_operands/v
338 * ("call stackleak_track_stack") ("") 0
339 * [ (reg/v:DI 7 sp [ current_stack_pointer ]) ]
340 * [ (asm_input:DI ("r")) ] [])
341 * (clobber (reg:CC 17 flags)) ]) -1 (nil))
342 */
343 for (insn = get_insns(); insn; insn = next) {
344 rtx body;
345
346 next = NEXT_INSN(insn);
347
348 /* Check the expression code of the insn */
349 if (!NONJUMP_INSN_P(insn))
350 continue;
351
352 /*
353 * Check the expression code of the insn body, which is an RTL
354 * Expression (RTX) describing the side effect performed by
355 * that insn.
356 */
357 body = PATTERN(insn);
358
359 if (GET_CODE(body) != PARALLEL)
360 continue;
361
362 body = XVECEXP(body, 0, 0);
363
364 if (GET_CODE(body) != ASM_OPERANDS)
365 continue;
366
367 if (strcmp(ASM_OPERANDS_TEMPLATE(body),
368 "call stackleak_track_stack")) {
369 continue;
370 }
371
372 delete_insn_and_edges(insn);
373 gcc_assert(!removed);
374 removed = true;
375 }
376
377 return removed;
378}
379
380/*
381 * Work with the RTL representation of the code.
382 * Remove the unneeded stackleak_track_stack() calls from the functions
383 * which don't call alloca() and don't have a large enough stack frame size.
384 */
385static unsigned int stackleak_cleanup_execute(void)
386{
387 bool removed = false;
388
389 if (cfun->calls_alloca)
390 return 0;
391
392 if (large_stack_frame())
393 return 0;
394
395 if (lookup_attribute_spec(get_identifier("no_caller_saved_registers")))
396 removed = remove_stack_tracking_gasm();
397
398 if (!removed)
399 remove_stack_tracking_gcall();
Alexander Popov10e9ae92018-08-17 01:16:59 +0300400
401 return 0;
402}
403
404static bool stackleak_gate(void)
405{
406 tree section;
407
408 section = lookup_attribute("section",
409 DECL_ATTRIBUTES(current_function_decl));
410 if (section && TREE_VALUE(section)) {
411 section = TREE_VALUE(TREE_VALUE(section));
412
413 if (!strncmp(TREE_STRING_POINTER(section), ".init.text", 10))
414 return false;
415 if (!strncmp(TREE_STRING_POINTER(section), ".devinit.text", 13))
416 return false;
417 if (!strncmp(TREE_STRING_POINTER(section), ".cpuinit.text", 13))
418 return false;
419 if (!strncmp(TREE_STRING_POINTER(section), ".meminit.text", 13))
420 return false;
421 }
422
423 return track_frame_size >= 0;
424}
425
426/* Build the function declaration for stackleak_track_stack() */
427static void stackleak_start_unit(void *gcc_data __unused,
428 void *user_data __unused)
429{
430 tree fntype;
431
432 /* void stackleak_track_stack(void) */
433 fntype = build_function_type_list(void_type_node, NULL_TREE);
434 track_function_decl = build_fn_decl(track_function, fntype);
435 DECL_ASSEMBLER_NAME(track_function_decl); /* for LTO */
436 TREE_PUBLIC(track_function_decl) = 1;
437 TREE_USED(track_function_decl) = 1;
438 DECL_EXTERNAL(track_function_decl) = 1;
439 DECL_ARTIFICIAL(track_function_decl) = 1;
440 DECL_PRESERVE_P(track_function_decl) = 1;
441}
442
443/*
444 * Pass gate function is a predicate function that gets executed before the
445 * corresponding pass. If the return value is 'true' the pass gets executed,
446 * otherwise, it is skipped.
447 */
448static bool stackleak_instrument_gate(void)
449{
450 return stackleak_gate();
451}
452
453#define PASS_NAME stackleak_instrument
454#define PROPERTIES_REQUIRED PROP_gimple_leh | PROP_cfg
455#define TODO_FLAGS_START TODO_verify_ssa | TODO_verify_flow | TODO_verify_stmts
456#define TODO_FLAGS_FINISH TODO_verify_ssa | TODO_verify_stmts | TODO_dump_func \
457 | TODO_update_ssa | TODO_rebuild_cgraph_edges
458#include "gcc-generate-gimple-pass.h"
459
460static bool stackleak_cleanup_gate(void)
461{
462 return stackleak_gate();
463}
464
465#define PASS_NAME stackleak_cleanup
466#define TODO_FLAGS_FINISH TODO_dump_func
467#include "gcc-generate-rtl-pass.h"
468
469/*
470 * Every gcc plugin exports a plugin_init() function that is called right
471 * after the plugin is loaded. This function is responsible for registering
472 * the plugin callbacks and doing other required initialization.
473 */
474__visible int plugin_init(struct plugin_name_args *plugin_info,
475 struct plugin_gcc_version *version)
476{
477 const char * const plugin_name = plugin_info->base_name;
478 const int argc = plugin_info->argc;
479 const struct plugin_argument * const argv = plugin_info->argv;
480 int i = 0;
481
482 /* Extra GGC root tables describing our GTY-ed data */
483 static const struct ggc_root_tab gt_ggc_r_gt_stackleak[] = {
484 {
485 .base = &track_function_decl,
486 .nelt = 1,
487 .stride = sizeof(track_function_decl),
488 .cb = &gt_ggc_mx_tree_node,
489 .pchw = &gt_pch_nx_tree_node
490 },
491 LAST_GGC_ROOT_TAB
492 };
493
494 /*
495 * The stackleak_instrument pass should be executed before the
496 * "optimized" pass, which is the control flow graph cleanup that is
497 * performed just before expanding gcc trees to the RTL. In former
498 * versions of the plugin this new pass was inserted before the
499 * "tree_profile" pass, which is currently called "profile".
500 */
501 PASS_INFO(stackleak_instrument, "optimized", 1,
502 PASS_POS_INSERT_BEFORE);
503
504 /*
Alexander Popov8fb2dfb2018-12-06 18:13:07 +0300505 * The stackleak_cleanup pass should be executed before the "*free_cfg"
506 * pass. It's the moment when the stack frame size is already final,
507 * function prologues and epilogues are generated, and the
508 * machine-dependent code transformations are not done.
Alexander Popov10e9ae92018-08-17 01:16:59 +0300509 */
Alexander Popov8fb2dfb2018-12-06 18:13:07 +0300510 PASS_INFO(stackleak_cleanup, "*free_cfg", 1, PASS_POS_INSERT_BEFORE);
Alexander Popov10e9ae92018-08-17 01:16:59 +0300511
512 if (!plugin_default_version_check(version, &gcc_version)) {
513 error(G_("incompatible gcc/plugin versions"));
514 return 1;
515 }
516
517 /* Parse the plugin arguments */
518 for (i = 0; i < argc; i++) {
519 if (!strcmp(argv[i].key, "disable"))
520 return 0;
521
522 if (!strcmp(argv[i].key, "track-min-size")) {
523 if (!argv[i].value) {
524 error(G_("no value supplied for option '-fplugin-arg-%s-%s'"),
525 plugin_name, argv[i].key);
526 return 1;
527 }
528
529 track_frame_size = atoi(argv[i].value);
530 if (track_frame_size < 0) {
531 error(G_("invalid option argument '-fplugin-arg-%s-%s=%s'"),
532 plugin_name, argv[i].key, argv[i].value);
533 return 1;
534 }
Alexander Popovfeee1b82020-06-24 15:33:29 +0300535 } else if (!strcmp(argv[i].key, "arch")) {
536 if (!argv[i].value) {
537 error(G_("no value supplied for option '-fplugin-arg-%s-%s'"),
538 plugin_name, argv[i].key);
539 return 1;
540 }
541
542 if (!strcmp(argv[i].value, "x86"))
543 build_for_x86 = true;
Alexander Popov10e9ae92018-08-17 01:16:59 +0300544 } else {
545 error(G_("unknown option '-fplugin-arg-%s-%s'"),
546 plugin_name, argv[i].key);
547 return 1;
548 }
549 }
550
551 /* Give the information about the plugin */
552 register_callback(plugin_name, PLUGIN_INFO, NULL,
553 &stackleak_plugin_info);
554
555 /* Register to be called before processing a translation unit */
556 register_callback(plugin_name, PLUGIN_START_UNIT,
557 &stackleak_start_unit, NULL);
558
559 /* Register an extra GCC garbage collector (GGC) root table */
560 register_callback(plugin_name, PLUGIN_REGISTER_GGC_ROOTS, NULL,
561 (void *)&gt_ggc_r_gt_stackleak);
562
563 /*
564 * Hook into the Pass Manager to register new gcc passes.
565 *
566 * The stack frame size info is available only at the last RTL pass,
567 * when it's too late to insert complex code like a function call.
568 * So we register two gcc passes to instrument every function at first
569 * and remove the unneeded instrumentation later.
570 */
571 register_callback(plugin_name, PLUGIN_PASS_MANAGER_SETUP, NULL,
572 &stackleak_instrument_pass_info);
573 register_callback(plugin_name, PLUGIN_PASS_MANAGER_SETUP, NULL,
574 &stackleak_cleanup_pass_info);
575
576 return 0;
577}