randomize_layout_plugin.c 24 KB

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