randomize_layout_plugin.c 27 KB

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