1 /*
2  * Copyright 2013-2017 by PaX Team <pageexec@freemail.hu>
3  * Licensed under the GPL v2
4  *
5  * Note: the choice of the license means that the compilation process is
6  *       NOT 'eligible' as defined by gcc's library exception to the GPL v3,
7  *       but for the kernel it doesn't matter since it doesn't link against
8  *       any of the gcc libraries
9  *
10  * gcc plugin to forcibly initialize certain local variables that could
11  * otherwise leak kernel stack to userland if they aren't properly initialized
12  * by later code
13  *
14  * Homepage: https://pax.grsecurity.net/
15  *
16  * Options:
17  * -fplugin-arg-structleak_plugin-disable
18  * -fplugin-arg-structleak_plugin-verbose
19  * -fplugin-arg-structleak_plugin-byref
20  * -fplugin-arg-structleak_plugin-byref-all
21  *
22  * Usage:
23  * $ # for 4.5/4.6/C based 4.7
24  * $ gcc -I`gcc -print-file-name=plugin`/include -I`gcc -print-file-name=plugin`/include/c-family -fPIC -shared -O2 -o structleak_plugin.so structleak_plugin.c
25  * $ # for C++ based 4.7/4.8+
26  * $ g++ -I`g++ -print-file-name=plugin`/include -I`g++ -print-file-name=plugin`/include/c-family -fPIC -shared -O2 -o structleak_plugin.so structleak_plugin.c
27  * $ gcc -fplugin=./structleak_plugin.so test.c -O2
28  *
29  * TODO: eliminate redundant initializers
30  */
31 
32 #include "gcc-common.h"
33 
34 /* unused C type flag in all versions 4.5-6 */
35 #define TYPE_USERSPACE(TYPE) TYPE_LANG_FLAG_5(TYPE)
36 
37 __visible int plugin_is_GPL_compatible;
38 
39 static struct plugin_info structleak_plugin_info = {
40 	.version	= "20190125vanilla",
41 	.help		= "disable\tdo not activate plugin\n"
42 			  "byref\tinit structs passed by reference\n"
43 			  "byref-all\tinit anything passed by reference\n"
44 			  "verbose\tprint all initialized variables\n",
45 };
46 
47 #define BYREF_STRUCT	1
48 #define BYREF_ALL	2
49 
50 static bool verbose;
51 static int byref;
52 
53 static tree handle_user_attribute(tree *node, tree name, tree args, int flags, bool *no_add_attrs)
54 {
55 	*no_add_attrs = true;
56 
57 	/* check for types? for now accept everything linux has to offer */
58 	if (TREE_CODE(*node) != FIELD_DECL)
59 		return NULL_TREE;
60 
61 	*no_add_attrs = false;
62 	return NULL_TREE;
63 }
64 
65 static struct attribute_spec user_attr = { };
66 
67 static void register_attributes(void *event_data, void *data)
68 {
69 	user_attr.name			= "user";
70 	user_attr.handler		= handle_user_attribute;
71 #if BUILDING_GCC_VERSION >= 4007
72 	user_attr.affects_type_identity	= true;
73 #endif
74 
75 	register_attribute(&user_attr);
76 }
77 
78 static tree get_field_type(tree field)
79 {
80 	return strip_array_types(TREE_TYPE(field));
81 }
82 
83 static bool is_userspace_type(tree type)
84 {
85 	tree field;
86 
87 	for (field = TYPE_FIELDS(type); field; field = TREE_CHAIN(field)) {
88 		tree fieldtype = get_field_type(field);
89 		enum tree_code code = TREE_CODE(fieldtype);
90 
91 		if (code == RECORD_TYPE || code == UNION_TYPE)
92 			if (is_userspace_type(fieldtype))
93 				return true;
94 
95 		if (lookup_attribute("user", DECL_ATTRIBUTES(field)))
96 			return true;
97 	}
98 	return false;
99 }
100 
101 static void finish_type(void *event_data, void *data)
102 {
103 	tree type = (tree)event_data;
104 
105 	if (type == NULL_TREE || type == error_mark_node)
106 		return;
107 
108 #if BUILDING_GCC_VERSION >= 5000
109 	if (TREE_CODE(type) == ENUMERAL_TYPE)
110 		return;
111 #endif
112 
113 	if (TYPE_USERSPACE(type))
114 		return;
115 
116 	if (is_userspace_type(type))
117 		TYPE_USERSPACE(type) = 1;
118 }
119 
120 static void initialize(tree var)
121 {
122 	basic_block bb;
123 	gimple_stmt_iterator gsi;
124 	tree initializer;
125 	gimple init_stmt;
126 	tree type;
127 
128 	/* this is the original entry bb before the forced split */
129 	bb = single_succ(ENTRY_BLOCK_PTR_FOR_FN(cfun));
130 
131 	/* first check if variable is already initialized, warn otherwise */
132 	for (gsi = gsi_start_bb(bb); !gsi_end_p(gsi); gsi_next(&gsi)) {
133 		gimple stmt = gsi_stmt(gsi);
134 		tree rhs1;
135 
136 		/* we're looking for an assignment of a single rhs... */
137 		if (!gimple_assign_single_p(stmt))
138 			continue;
139 		rhs1 = gimple_assign_rhs1(stmt);
140 #if BUILDING_GCC_VERSION >= 4007
141 		/* ... of a non-clobbering expression... */
142 		if (TREE_CLOBBER_P(rhs1))
143 			continue;
144 #endif
145 		/* ... to our variable... */
146 		if (gimple_get_lhs(stmt) != var)
147 			continue;
148 		/* if it's an initializer then we're good */
149 		if (TREE_CODE(rhs1) == CONSTRUCTOR)
150 			return;
151 	}
152 
153 	/* these aren't the 0days you're looking for */
154 	if (verbose)
155 		inform(DECL_SOURCE_LOCATION(var),
156 			"%s variable will be forcibly initialized",
157 			(byref && TREE_ADDRESSABLE(var)) ? "byref"
158 							 : "userspace");
159 
160 	/* build the initializer expression */
161 	type = TREE_TYPE(var);
162 	if (AGGREGATE_TYPE_P(type))
163 		initializer = build_constructor(type, NULL);
164 	else
165 		initializer = fold_convert(type, integer_zero_node);
166 
167 	/* build the initializer stmt */
168 	init_stmt = gimple_build_assign(var, initializer);
169 	gsi = gsi_after_labels(single_succ(ENTRY_BLOCK_PTR_FOR_FN(cfun)));
170 	gsi_insert_before(&gsi, init_stmt, GSI_NEW_STMT);
171 	update_stmt(init_stmt);
172 }
173 
174 static unsigned int structleak_execute(void)
175 {
176 	basic_block bb;
177 	unsigned int ret = 0;
178 	tree var;
179 	unsigned int i;
180 
181 	/* split the first bb where we can put the forced initializers */
182 	gcc_assert(single_succ_p(ENTRY_BLOCK_PTR_FOR_FN(cfun)));
183 	bb = single_succ(ENTRY_BLOCK_PTR_FOR_FN(cfun));
184 	if (!single_pred_p(bb)) {
185 		split_edge(single_succ_edge(ENTRY_BLOCK_PTR_FOR_FN(cfun)));
186 		gcc_assert(single_succ_p(ENTRY_BLOCK_PTR_FOR_FN(cfun)));
187 	}
188 
189 	/* enumerate all local variables and forcibly initialize our targets */
190 	FOR_EACH_LOCAL_DECL(cfun, i, var) {
191 		tree type = TREE_TYPE(var);
192 
193 		gcc_assert(DECL_P(var));
194 		if (!auto_var_in_fn_p(var, current_function_decl))
195 			continue;
196 
197 		/* only care about structure types unless byref-all */
198 		if (byref != BYREF_ALL && TREE_CODE(type) != RECORD_TYPE && TREE_CODE(type) != UNION_TYPE)
199 			continue;
200 
201 		/* if the type is of interest, examine the variable */
202 		if (TYPE_USERSPACE(type) ||
203 		    (byref && TREE_ADDRESSABLE(var)))
204 			initialize(var);
205 	}
206 
207 	return ret;
208 }
209 
210 #define PASS_NAME structleak
211 #define NO_GATE
212 #define PROPERTIES_REQUIRED PROP_cfg
213 #define TODO_FLAGS_FINISH TODO_verify_il | TODO_verify_ssa | TODO_verify_stmts | TODO_dump_func | TODO_remove_unused_locals | TODO_update_ssa | TODO_ggc_collect | TODO_verify_flow
214 #include "gcc-generate-gimple-pass.h"
215 
216 __visible int plugin_init(struct plugin_name_args *plugin_info, struct plugin_gcc_version *version)
217 {
218 	int i;
219 	const char * const plugin_name = plugin_info->base_name;
220 	const int argc = plugin_info->argc;
221 	const struct plugin_argument * const argv = plugin_info->argv;
222 	bool enable = true;
223 
224 	PASS_INFO(structleak, "early_optimizations", 1, PASS_POS_INSERT_BEFORE);
225 
226 	if (!plugin_default_version_check(version, &gcc_version)) {
227 		error(G_("incompatible gcc/plugin versions"));
228 		return 1;
229 	}
230 
231 	if (strncmp(lang_hooks.name, "GNU C", 5) && !strncmp(lang_hooks.name, "GNU C+", 6)) {
232 		inform(UNKNOWN_LOCATION, G_("%s supports C only, not %s"), plugin_name, lang_hooks.name);
233 		enable = false;
234 	}
235 
236 	for (i = 0; i < argc; ++i) {
237 		if (!strcmp(argv[i].key, "disable")) {
238 			enable = false;
239 			continue;
240 		}
241 		if (!strcmp(argv[i].key, "verbose")) {
242 			verbose = true;
243 			continue;
244 		}
245 		if (!strcmp(argv[i].key, "byref")) {
246 			byref = BYREF_STRUCT;
247 			continue;
248 		}
249 		if (!strcmp(argv[i].key, "byref-all")) {
250 			byref = BYREF_ALL;
251 			continue;
252 		}
253 		error(G_("unknown option '-fplugin-arg-%s-%s'"), plugin_name, argv[i].key);
254 	}
255 
256 	register_callback(plugin_name, PLUGIN_INFO, NULL, &structleak_plugin_info);
257 	if (enable) {
258 		register_callback(plugin_name, PLUGIN_PASS_MANAGER_SETUP, NULL, &structleak_pass_info);
259 		register_callback(plugin_name, PLUGIN_FINISH_TYPE, finish_type, NULL);
260 	}
261 	register_callback(plugin_name, PLUGIN_ATTRIBUTES, register_attributes, NULL);
262 
263 	return 0;
264 }
265