stackleak_plugin.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. /*
  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(),
  23. * print_rtl() and print_simple_rtl();
  24. * - 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. #include "gcc-common.h"
  30. __visible int plugin_is_GPL_compatible;
  31. static int track_frame_size = -1;
  32. static const char track_function[] = "stackleak_track_stack";
  33. /*
  34. * Mark these global variables (roots) for gcc garbage collector since
  35. * they point to the garbage-collected memory.
  36. */
  37. static GTY(()) tree track_function_decl;
  38. static struct plugin_info stackleak_plugin_info = {
  39. .version = "201707101337",
  40. .help = "track-min-size=nn\ttrack stack for functions with a stack frame size >= nn bytes\n"
  41. "disable\t\tdo not activate the plugin\n"
  42. };
  43. static void stackleak_add_track_stack(gimple_stmt_iterator *gsi, bool after)
  44. {
  45. gimple stmt;
  46. gcall *stackleak_track_stack;
  47. cgraph_node_ptr node;
  48. int frequency;
  49. basic_block bb;
  50. /* Insert call to void stackleak_track_stack(void) */
  51. stmt = gimple_build_call(track_function_decl, 0);
  52. stackleak_track_stack = as_a_gcall(stmt);
  53. if (after) {
  54. gsi_insert_after(gsi, stackleak_track_stack,
  55. GSI_CONTINUE_LINKING);
  56. } else {
  57. gsi_insert_before(gsi, stackleak_track_stack, GSI_SAME_STMT);
  58. }
  59. /* Update the cgraph */
  60. bb = gimple_bb(stackleak_track_stack);
  61. node = cgraph_get_create_node(track_function_decl);
  62. gcc_assert(node);
  63. frequency = compute_call_stmt_bb_frequency(current_function_decl, bb);
  64. cgraph_create_edge(cgraph_get_node(current_function_decl), node,
  65. stackleak_track_stack, bb->count, frequency);
  66. }
  67. static bool is_alloca(gimple stmt)
  68. {
  69. if (gimple_call_builtin_p(stmt, BUILT_IN_ALLOCA))
  70. return true;
  71. #if BUILDING_GCC_VERSION >= 4007
  72. if (gimple_call_builtin_p(stmt, BUILT_IN_ALLOCA_WITH_ALIGN))
  73. return true;
  74. #endif
  75. return false;
  76. }
  77. /*
  78. * Work with the GIMPLE representation of the code. Insert the
  79. * stackleak_track_stack() call after alloca() and into the beginning
  80. * of the function if it is not instrumented.
  81. */
  82. static unsigned int stackleak_instrument_execute(void)
  83. {
  84. basic_block bb, entry_bb;
  85. bool prologue_instrumented = false, is_leaf = true;
  86. gimple_stmt_iterator gsi;
  87. /*
  88. * ENTRY_BLOCK_PTR is a basic block which represents possible entry
  89. * point of a function. This block does not contain any code and
  90. * has a CFG edge to its successor.
  91. */
  92. gcc_assert(single_succ_p(ENTRY_BLOCK_PTR_FOR_FN(cfun)));
  93. entry_bb = single_succ(ENTRY_BLOCK_PTR_FOR_FN(cfun));
  94. /*
  95. * Loop through the GIMPLE statements in each of cfun basic blocks.
  96. * cfun is a global variable which represents the function that is
  97. * currently processed.
  98. */
  99. FOR_EACH_BB_FN(bb, cfun) {
  100. for (gsi = gsi_start_bb(bb); !gsi_end_p(gsi); gsi_next(&gsi)) {
  101. gimple stmt;
  102. stmt = gsi_stmt(gsi);
  103. /* Leaf function is a function which makes no calls */
  104. if (is_gimple_call(stmt))
  105. is_leaf = false;
  106. if (!is_alloca(stmt))
  107. continue;
  108. /* Insert stackleak_track_stack() call after alloca() */
  109. stackleak_add_track_stack(&gsi, true);
  110. if (bb == entry_bb)
  111. prologue_instrumented = true;
  112. }
  113. }
  114. if (prologue_instrumented)
  115. return 0;
  116. /*
  117. * Special cases to skip the instrumentation.
  118. *
  119. * Taking the address of static inline functions materializes them,
  120. * but we mustn't instrument some of them as the resulting stack
  121. * alignment required by the function call ABI will break other
  122. * assumptions regarding the expected (but not otherwise enforced)
  123. * register clobbering ABI.
  124. *
  125. * Case in point: native_save_fl on amd64 when optimized for size
  126. * clobbers rdx if it were instrumented here.
  127. *
  128. * TODO: any more special cases?
  129. */
  130. if (is_leaf &&
  131. !TREE_PUBLIC(current_function_decl) &&
  132. DECL_DECLARED_INLINE_P(current_function_decl)) {
  133. return 0;
  134. }
  135. if (is_leaf &&
  136. !strncmp(IDENTIFIER_POINTER(DECL_NAME(current_function_decl)),
  137. "_paravirt_", 10)) {
  138. return 0;
  139. }
  140. /* Insert stackleak_track_stack() call at the function beginning */
  141. bb = entry_bb;
  142. if (!single_pred_p(bb)) {
  143. /* gcc_assert(bb_loop_depth(bb) ||
  144. (bb->flags & BB_IRREDUCIBLE_LOOP)); */
  145. split_edge(single_succ_edge(ENTRY_BLOCK_PTR_FOR_FN(cfun)));
  146. gcc_assert(single_succ_p(ENTRY_BLOCK_PTR_FOR_FN(cfun)));
  147. bb = single_succ(ENTRY_BLOCK_PTR_FOR_FN(cfun));
  148. }
  149. gsi = gsi_after_labels(bb);
  150. stackleak_add_track_stack(&gsi, false);
  151. return 0;
  152. }
  153. static bool large_stack_frame(void)
  154. {
  155. #if BUILDING_GCC_VERSION >= 8000
  156. return maybe_ge(get_frame_size(), track_frame_size);
  157. #else
  158. return (get_frame_size() >= track_frame_size);
  159. #endif
  160. }
  161. /*
  162. * Work with the RTL representation of the code.
  163. * Remove the unneeded stackleak_track_stack() calls from the functions
  164. * which don't call alloca() and don't have a large enough stack frame size.
  165. */
  166. static unsigned int stackleak_cleanup_execute(void)
  167. {
  168. rtx_insn *insn, *next;
  169. if (cfun->calls_alloca)
  170. return 0;
  171. if (large_stack_frame())
  172. return 0;
  173. /*
  174. * Find stackleak_track_stack() calls. Loop through the chain of insns,
  175. * which is an RTL representation of the code for a function.
  176. *
  177. * The example of a matching insn:
  178. * (call_insn 8 4 10 2 (call (mem (symbol_ref ("stackleak_track_stack")
  179. * [flags 0x41] <function_decl 0x7f7cd3302a80 stackleak_track_stack>)
  180. * [0 stackleak_track_stack S1 A8]) (0)) 675 {*call} (expr_list
  181. * (symbol_ref ("stackleak_track_stack") [flags 0x41] <function_decl
  182. * 0x7f7cd3302a80 stackleak_track_stack>) (expr_list (0) (nil))) (nil))
  183. */
  184. for (insn = get_insns(); insn; insn = next) {
  185. rtx body;
  186. next = NEXT_INSN(insn);
  187. /* Check the expression code of the insn */
  188. if (!CALL_P(insn))
  189. continue;
  190. /*
  191. * Check the expression code of the insn body, which is an RTL
  192. * Expression (RTX) describing the side effect performed by
  193. * that insn.
  194. */
  195. body = PATTERN(insn);
  196. if (GET_CODE(body) == PARALLEL)
  197. body = XVECEXP(body, 0, 0);
  198. if (GET_CODE(body) != CALL)
  199. continue;
  200. /*
  201. * Check the first operand of the call expression. It should
  202. * be a mem RTX describing the needed subroutine with a
  203. * symbol_ref RTX.
  204. */
  205. body = XEXP(body, 0);
  206. if (GET_CODE(body) != MEM)
  207. continue;
  208. body = XEXP(body, 0);
  209. if (GET_CODE(body) != SYMBOL_REF)
  210. continue;
  211. if (SYMBOL_REF_DECL(body) != track_function_decl)
  212. continue;
  213. /* Delete the stackleak_track_stack() call */
  214. delete_insn_and_edges(insn);
  215. #if BUILDING_GCC_VERSION >= 4007 && BUILDING_GCC_VERSION < 8000
  216. if (GET_CODE(next) == NOTE &&
  217. NOTE_KIND(next) == NOTE_INSN_CALL_ARG_LOCATION) {
  218. insn = next;
  219. next = NEXT_INSN(insn);
  220. delete_insn_and_edges(insn);
  221. }
  222. #endif
  223. }
  224. return 0;
  225. }
  226. static bool stackleak_gate(void)
  227. {
  228. tree section;
  229. section = lookup_attribute("section",
  230. DECL_ATTRIBUTES(current_function_decl));
  231. if (section && TREE_VALUE(section)) {
  232. section = TREE_VALUE(TREE_VALUE(section));
  233. if (!strncmp(TREE_STRING_POINTER(section), ".init.text", 10))
  234. return false;
  235. if (!strncmp(TREE_STRING_POINTER(section), ".devinit.text", 13))
  236. return false;
  237. if (!strncmp(TREE_STRING_POINTER(section), ".cpuinit.text", 13))
  238. return false;
  239. if (!strncmp(TREE_STRING_POINTER(section), ".meminit.text", 13))
  240. return false;
  241. }
  242. return track_frame_size >= 0;
  243. }
  244. /* Build the function declaration for stackleak_track_stack() */
  245. static void stackleak_start_unit(void *gcc_data __unused,
  246. void *user_data __unused)
  247. {
  248. tree fntype;
  249. /* void stackleak_track_stack(void) */
  250. fntype = build_function_type_list(void_type_node, NULL_TREE);
  251. track_function_decl = build_fn_decl(track_function, fntype);
  252. DECL_ASSEMBLER_NAME(track_function_decl); /* for LTO */
  253. TREE_PUBLIC(track_function_decl) = 1;
  254. TREE_USED(track_function_decl) = 1;
  255. DECL_EXTERNAL(track_function_decl) = 1;
  256. DECL_ARTIFICIAL(track_function_decl) = 1;
  257. DECL_PRESERVE_P(track_function_decl) = 1;
  258. }
  259. /*
  260. * Pass gate function is a predicate function that gets executed before the
  261. * corresponding pass. If the return value is 'true' the pass gets executed,
  262. * otherwise, it is skipped.
  263. */
  264. static bool stackleak_instrument_gate(void)
  265. {
  266. return stackleak_gate();
  267. }
  268. #define PASS_NAME stackleak_instrument
  269. #define PROPERTIES_REQUIRED PROP_gimple_leh | PROP_cfg
  270. #define TODO_FLAGS_START TODO_verify_ssa | TODO_verify_flow | TODO_verify_stmts
  271. #define TODO_FLAGS_FINISH TODO_verify_ssa | TODO_verify_stmts | TODO_dump_func \
  272. | TODO_update_ssa | TODO_rebuild_cgraph_edges
  273. #include "gcc-generate-gimple-pass.h"
  274. static bool stackleak_cleanup_gate(void)
  275. {
  276. return stackleak_gate();
  277. }
  278. #define PASS_NAME stackleak_cleanup
  279. #define TODO_FLAGS_FINISH TODO_dump_func
  280. #include "gcc-generate-rtl-pass.h"
  281. /*
  282. * Every gcc plugin exports a plugin_init() function that is called right
  283. * after the plugin is loaded. This function is responsible for registering
  284. * the plugin callbacks and doing other required initialization.
  285. */
  286. __visible int plugin_init(struct plugin_name_args *plugin_info,
  287. struct plugin_gcc_version *version)
  288. {
  289. const char * const plugin_name = plugin_info->base_name;
  290. const int argc = plugin_info->argc;
  291. const struct plugin_argument * const argv = plugin_info->argv;
  292. int i = 0;
  293. /* Extra GGC root tables describing our GTY-ed data */
  294. static const struct ggc_root_tab gt_ggc_r_gt_stackleak[] = {
  295. {
  296. .base = &track_function_decl,
  297. .nelt = 1,
  298. .stride = sizeof(track_function_decl),
  299. .cb = &gt_ggc_mx_tree_node,
  300. .pchw = &gt_pch_nx_tree_node
  301. },
  302. LAST_GGC_ROOT_TAB
  303. };
  304. /*
  305. * The stackleak_instrument pass should be executed before the
  306. * "optimized" pass, which is the control flow graph cleanup that is
  307. * performed just before expanding gcc trees to the RTL. In former
  308. * versions of the plugin this new pass was inserted before the
  309. * "tree_profile" pass, which is currently called "profile".
  310. */
  311. PASS_INFO(stackleak_instrument, "optimized", 1,
  312. PASS_POS_INSERT_BEFORE);
  313. /*
  314. * The stackleak_cleanup pass should be executed after the
  315. * "reload" pass, when the stack frame size is final.
  316. */
  317. PASS_INFO(stackleak_cleanup, "reload", 1, PASS_POS_INSERT_AFTER);
  318. if (!plugin_default_version_check(version, &gcc_version)) {
  319. error(G_("incompatible gcc/plugin versions"));
  320. return 1;
  321. }
  322. /* Parse the plugin arguments */
  323. for (i = 0; i < argc; i++) {
  324. if (!strcmp(argv[i].key, "disable"))
  325. return 0;
  326. if (!strcmp(argv[i].key, "track-min-size")) {
  327. if (!argv[i].value) {
  328. error(G_("no value supplied for option '-fplugin-arg-%s-%s'"),
  329. plugin_name, argv[i].key);
  330. return 1;
  331. }
  332. track_frame_size = atoi(argv[i].value);
  333. if (track_frame_size < 0) {
  334. error(G_("invalid option argument '-fplugin-arg-%s-%s=%s'"),
  335. plugin_name, argv[i].key, argv[i].value);
  336. return 1;
  337. }
  338. } else {
  339. error(G_("unknown option '-fplugin-arg-%s-%s'"),
  340. plugin_name, argv[i].key);
  341. return 1;
  342. }
  343. }
  344. /* Give the information about the plugin */
  345. register_callback(plugin_name, PLUGIN_INFO, NULL,
  346. &stackleak_plugin_info);
  347. /* Register to be called before processing a translation unit */
  348. register_callback(plugin_name, PLUGIN_START_UNIT,
  349. &stackleak_start_unit, NULL);
  350. /* Register an extra GCC garbage collector (GGC) root table */
  351. register_callback(plugin_name, PLUGIN_REGISTER_GGC_ROOTS, NULL,
  352. (void *)&gt_ggc_r_gt_stackleak);
  353. /*
  354. * Hook into the Pass Manager to register new gcc passes.
  355. *
  356. * The stack frame size info is available only at the last RTL pass,
  357. * when it's too late to insert complex code like a function call.
  358. * So we register two gcc passes to instrument every function at first
  359. * and remove the unneeded instrumentation later.
  360. */
  361. register_callback(plugin_name, PLUGIN_PASS_MANAGER_SETUP, NULL,
  362. &stackleak_instrument_pass_info);
  363. register_callback(plugin_name, PLUGIN_PASS_MANAGER_SETUP, NULL,
  364. &stackleak_cleanup_pass_info);
  365. return 0;
  366. }