randomize_layout_plugin.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993
  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 hlist_head */
  47. { "security/security.c", "hlist_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. for (field = TYPE_FIELDS(node); field; field = TREE_CHAIN(field)) {
  360. const_tree fieldtype = get_field_type(field);
  361. enum tree_code code = TREE_CODE(fieldtype);
  362. if (node == fieldtype)
  363. continue;
  364. if (code == RECORD_TYPE || code == UNION_TYPE) {
  365. if (!is_pure_ops_struct(fieldtype))
  366. return 0;
  367. continue;
  368. }
  369. if (!is_fptr(fieldtype))
  370. return 0;
  371. }
  372. return 1;
  373. }
  374. static void randomize_type(tree type)
  375. {
  376. tree variant;
  377. gcc_assert(TREE_CODE(type) == RECORD_TYPE);
  378. if (lookup_attribute("randomize_considered", TYPE_ATTRIBUTES(type)))
  379. return;
  380. if (lookup_attribute("randomize_layout", TYPE_ATTRIBUTES(TYPE_MAIN_VARIANT(type))) || is_pure_ops_struct(type))
  381. relayout_struct(type);
  382. for (variant = TYPE_MAIN_VARIANT(type); variant; variant = TYPE_NEXT_VARIANT(variant)) {
  383. TYPE_ATTRIBUTES(type) = copy_list(TYPE_ATTRIBUTES(type));
  384. TYPE_ATTRIBUTES(type) = tree_cons(get_identifier("randomize_considered"), NULL_TREE, TYPE_ATTRIBUTES(type));
  385. }
  386. #ifdef __DEBUG_PLUGIN
  387. fprintf(stderr, "Marking randomize_considered on struct %s\n", ORIG_TYPE_NAME(type));
  388. #ifdef __DEBUG_VERBOSE
  389. debug_tree(type);
  390. #endif
  391. #endif
  392. }
  393. static void update_decl_size(tree decl)
  394. {
  395. tree lastval, lastidx, field, init, type, flexsize;
  396. unsigned HOST_WIDE_INT len;
  397. type = TREE_TYPE(decl);
  398. if (!lookup_attribute("has_flexarray", TYPE_ATTRIBUTES(type)))
  399. return;
  400. init = DECL_INITIAL(decl);
  401. if (init == NULL_TREE || init == error_mark_node)
  402. return;
  403. if (TREE_CODE(init) != CONSTRUCTOR)
  404. return;
  405. len = CONSTRUCTOR_NELTS(init);
  406. if (!len)
  407. return;
  408. lastval = CONSTRUCTOR_ELT(init, CONSTRUCTOR_NELTS(init) - 1)->value;
  409. lastidx = CONSTRUCTOR_ELT(init, CONSTRUCTOR_NELTS(init) - 1)->index;
  410. for (field = TYPE_FIELDS(TREE_TYPE(decl)); TREE_CHAIN(field); field = TREE_CHAIN(field))
  411. ;
  412. if (lastidx != field)
  413. return;
  414. if (TREE_CODE(lastval) != STRING_CST) {
  415. error("Only string constants are supported as initializers "
  416. "for randomized structures with flexible arrays");
  417. return;
  418. }
  419. flexsize = bitsize_int(TREE_STRING_LENGTH(lastval) *
  420. tree_to_uhwi(TYPE_SIZE(TREE_TYPE(TREE_TYPE(lastval)))));
  421. DECL_SIZE(decl) = size_binop(PLUS_EXPR, TYPE_SIZE(type), flexsize);
  422. return;
  423. }
  424. static void randomize_layout_finish_decl(void *event_data, void *data)
  425. {
  426. tree decl = (tree)event_data;
  427. tree type;
  428. if (decl == NULL_TREE || decl == error_mark_node)
  429. return;
  430. type = TREE_TYPE(decl);
  431. if (TREE_CODE(decl) != VAR_DECL)
  432. return;
  433. if (TREE_CODE(type) != RECORD_TYPE && TREE_CODE(type) != UNION_TYPE)
  434. return;
  435. if (!lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(type)))
  436. return;
  437. DECL_SIZE(decl) = 0;
  438. DECL_SIZE_UNIT(decl) = 0;
  439. SET_DECL_ALIGN(decl, 0);
  440. SET_DECL_MODE (decl, VOIDmode);
  441. SET_DECL_RTL(decl, 0);
  442. update_decl_size(decl);
  443. layout_decl(decl, 0);
  444. }
  445. static void finish_type(void *event_data, void *data)
  446. {
  447. tree type = (tree)event_data;
  448. if (type == NULL_TREE || type == error_mark_node)
  449. return;
  450. if (TREE_CODE(type) != RECORD_TYPE)
  451. return;
  452. if (TYPE_FIELDS(type) == NULL_TREE)
  453. return;
  454. if (lookup_attribute("randomize_considered", TYPE_ATTRIBUTES(type)))
  455. return;
  456. #ifdef __DEBUG_PLUGIN
  457. fprintf(stderr, "Calling randomize_type on %s\n", ORIG_TYPE_NAME(type));
  458. #endif
  459. #ifdef __DEBUG_VERBOSE
  460. debug_tree(type);
  461. #endif
  462. randomize_type(type);
  463. return;
  464. }
  465. static struct attribute_spec randomize_layout_attr = { };
  466. static struct attribute_spec no_randomize_layout_attr = { };
  467. static struct attribute_spec randomize_considered_attr = { };
  468. static struct attribute_spec randomize_performed_attr = { };
  469. static void register_attributes(void *event_data, void *data)
  470. {
  471. randomize_layout_attr.name = "randomize_layout";
  472. randomize_layout_attr.type_required = true;
  473. randomize_layout_attr.handler = handle_randomize_layout_attr;
  474. #if BUILDING_GCC_VERSION >= 4007
  475. randomize_layout_attr.affects_type_identity = true;
  476. #endif
  477. no_randomize_layout_attr.name = "no_randomize_layout";
  478. no_randomize_layout_attr.type_required = true;
  479. no_randomize_layout_attr.handler = handle_randomize_layout_attr;
  480. #if BUILDING_GCC_VERSION >= 4007
  481. no_randomize_layout_attr.affects_type_identity = true;
  482. #endif
  483. randomize_considered_attr.name = "randomize_considered";
  484. randomize_considered_attr.type_required = true;
  485. randomize_considered_attr.handler = handle_randomize_considered_attr;
  486. randomize_performed_attr.name = "randomize_performed";
  487. randomize_performed_attr.type_required = true;
  488. randomize_performed_attr.handler = handle_randomize_performed_attr;
  489. register_attribute(&randomize_layout_attr);
  490. register_attribute(&no_randomize_layout_attr);
  491. register_attribute(&randomize_considered_attr);
  492. register_attribute(&randomize_performed_attr);
  493. }
  494. static void check_bad_casts_in_constructor(tree var, tree init)
  495. {
  496. unsigned HOST_WIDE_INT idx;
  497. tree field, val;
  498. tree field_type, val_type;
  499. FOR_EACH_CONSTRUCTOR_ELT(CONSTRUCTOR_ELTS(init), idx, field, val) {
  500. if (TREE_CODE(val) == CONSTRUCTOR) {
  501. check_bad_casts_in_constructor(var, val);
  502. continue;
  503. }
  504. /* pipacs' plugin creates franken-arrays that differ from those produced by
  505. normal code which all have valid 'field' trees. work around this */
  506. if (field == NULL_TREE)
  507. continue;
  508. field_type = TREE_TYPE(field);
  509. val_type = TREE_TYPE(val);
  510. if (TREE_CODE(field_type) != POINTER_TYPE || TREE_CODE(val_type) != POINTER_TYPE)
  511. continue;
  512. if (field_type == val_type)
  513. continue;
  514. field_type = TYPE_MAIN_VARIANT(strip_array_types(TYPE_MAIN_VARIANT(TREE_TYPE(field_type))));
  515. val_type = TYPE_MAIN_VARIANT(strip_array_types(TYPE_MAIN_VARIANT(TREE_TYPE(val_type))));
  516. if (field_type == void_type_node)
  517. continue;
  518. if (field_type == val_type)
  519. continue;
  520. if (TREE_CODE(val_type) != RECORD_TYPE)
  521. continue;
  522. if (!lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(val_type)))
  523. continue;
  524. MISMATCH(DECL_SOURCE_LOCATION(var), "constructor\n", TYPE_MAIN_VARIANT(field_type), TYPE_MAIN_VARIANT(val_type));
  525. }
  526. }
  527. /* derived from the constify plugin */
  528. static void check_global_variables(void *event_data, void *data)
  529. {
  530. struct varpool_node *node;
  531. tree init;
  532. FOR_EACH_VARIABLE(node) {
  533. tree var = NODE_DECL(node);
  534. init = DECL_INITIAL(var);
  535. if (init == NULL_TREE)
  536. continue;
  537. if (TREE_CODE(init) != CONSTRUCTOR)
  538. continue;
  539. check_bad_casts_in_constructor(var, init);
  540. }
  541. }
  542. static bool dominated_by_is_err(const_tree rhs, basic_block bb)
  543. {
  544. basic_block dom;
  545. gimple dom_stmt;
  546. gimple call_stmt;
  547. const_tree dom_lhs;
  548. const_tree poss_is_err_cond;
  549. const_tree poss_is_err_func;
  550. const_tree is_err_arg;
  551. dom = get_immediate_dominator(CDI_DOMINATORS, bb);
  552. if (!dom)
  553. return false;
  554. dom_stmt = last_stmt(dom);
  555. if (!dom_stmt)
  556. return false;
  557. if (gimple_code(dom_stmt) != GIMPLE_COND)
  558. return false;
  559. if (gimple_cond_code(dom_stmt) != NE_EXPR)
  560. return false;
  561. if (!integer_zerop(gimple_cond_rhs(dom_stmt)))
  562. return false;
  563. poss_is_err_cond = gimple_cond_lhs(dom_stmt);
  564. if (TREE_CODE(poss_is_err_cond) != SSA_NAME)
  565. return false;
  566. call_stmt = SSA_NAME_DEF_STMT(poss_is_err_cond);
  567. if (gimple_code(call_stmt) != GIMPLE_CALL)
  568. return false;
  569. dom_lhs = gimple_get_lhs(call_stmt);
  570. poss_is_err_func = gimple_call_fndecl(call_stmt);
  571. if (!poss_is_err_func)
  572. return false;
  573. if (dom_lhs != poss_is_err_cond)
  574. return false;
  575. if (strcmp(DECL_NAME_POINTER(poss_is_err_func), "IS_ERR"))
  576. return false;
  577. is_err_arg = gimple_call_arg(call_stmt, 0);
  578. if (!is_err_arg)
  579. return false;
  580. if (is_err_arg != rhs)
  581. return false;
  582. return true;
  583. }
  584. static void handle_local_var_initializers(void)
  585. {
  586. tree var;
  587. unsigned int i;
  588. FOR_EACH_LOCAL_DECL(cfun, i, var) {
  589. tree init = DECL_INITIAL(var);
  590. if (!init)
  591. continue;
  592. if (TREE_CODE(init) != CONSTRUCTOR)
  593. continue;
  594. check_bad_casts_in_constructor(var, init);
  595. }
  596. }
  597. static bool type_name_eq(gimple stmt, const_tree type_tree, const char *wanted_name)
  598. {
  599. const char *type_name;
  600. if (type_tree == NULL_TREE)
  601. return false;
  602. switch (TREE_CODE(type_tree)) {
  603. case RECORD_TYPE:
  604. type_name = TYPE_NAME_POINTER(type_tree);
  605. break;
  606. case INTEGER_TYPE:
  607. if (TYPE_PRECISION(type_tree) == CHAR_TYPE_SIZE)
  608. type_name = "char";
  609. else {
  610. INFORM(gimple_location(stmt), "found non-char INTEGER_TYPE cast comparison: %qT\n", type_tree);
  611. debug_tree(type_tree);
  612. return false;
  613. }
  614. break;
  615. case POINTER_TYPE:
  616. if (TREE_CODE(TREE_TYPE(type_tree)) == VOID_TYPE) {
  617. type_name = "void *";
  618. break;
  619. } else {
  620. INFORM(gimple_location(stmt), "found non-void POINTER_TYPE cast comparison %qT\n", type_tree);
  621. debug_tree(type_tree);
  622. return false;
  623. }
  624. default:
  625. INFORM(gimple_location(stmt), "unhandled cast comparison: %qT\n", type_tree);
  626. debug_tree(type_tree);
  627. return false;
  628. }
  629. return strcmp(type_name, wanted_name) == 0;
  630. }
  631. static bool whitelisted_cast(gimple stmt, const_tree lhs_tree, const_tree rhs_tree)
  632. {
  633. const struct whitelist_entry *entry;
  634. expanded_location xloc = expand_location(gimple_location(stmt));
  635. for (entry = whitelist; entry->pathname; entry++) {
  636. if (!strstr(xloc.file, entry->pathname))
  637. continue;
  638. if (type_name_eq(stmt, lhs_tree, entry->lhs) && type_name_eq(stmt, rhs_tree, entry->rhs))
  639. return true;
  640. }
  641. return false;
  642. }
  643. /*
  644. * iterate over all statements to find "bad" casts:
  645. * those where the address of the start of a structure is cast
  646. * to a pointer of a structure of a different type, or a
  647. * structure pointer type is cast to a different structure pointer type
  648. */
  649. static unsigned int find_bad_casts_execute(void)
  650. {
  651. basic_block bb;
  652. handle_local_var_initializers();
  653. FOR_EACH_BB_FN(bb, cfun) {
  654. gimple_stmt_iterator gsi;
  655. for (gsi = gsi_start_bb(bb); !gsi_end_p(gsi); gsi_next(&gsi)) {
  656. gimple stmt;
  657. const_tree lhs;
  658. const_tree lhs_type;
  659. const_tree rhs1;
  660. const_tree rhs_type;
  661. const_tree ptr_lhs_type;
  662. const_tree ptr_rhs_type;
  663. const_tree op0;
  664. const_tree op0_type;
  665. enum tree_code rhs_code;
  666. stmt = gsi_stmt(gsi);
  667. #ifdef __DEBUG_PLUGIN
  668. #ifdef __DEBUG_VERBOSE
  669. debug_gimple_stmt(stmt);
  670. debug_tree(gimple_get_lhs(stmt));
  671. #endif
  672. #endif
  673. if (gimple_code(stmt) != GIMPLE_ASSIGN)
  674. continue;
  675. #ifdef __DEBUG_PLUGIN
  676. #ifdef __DEBUG_VERBOSE
  677. debug_tree(gimple_assign_rhs1(stmt));
  678. #endif
  679. #endif
  680. rhs_code = gimple_assign_rhs_code(stmt);
  681. if (rhs_code != ADDR_EXPR && rhs_code != SSA_NAME)
  682. continue;
  683. lhs = gimple_get_lhs(stmt);
  684. lhs_type = TREE_TYPE(lhs);
  685. rhs1 = gimple_assign_rhs1(stmt);
  686. rhs_type = TREE_TYPE(rhs1);
  687. if (TREE_CODE(rhs_type) != POINTER_TYPE ||
  688. TREE_CODE(lhs_type) != POINTER_TYPE)
  689. continue;
  690. ptr_lhs_type = TYPE_MAIN_VARIANT(strip_array_types(TYPE_MAIN_VARIANT(TREE_TYPE(lhs_type))));
  691. ptr_rhs_type = TYPE_MAIN_VARIANT(strip_array_types(TYPE_MAIN_VARIANT(TREE_TYPE(rhs_type))));
  692. if (ptr_rhs_type == void_type_node)
  693. continue;
  694. if (ptr_lhs_type == void_type_node)
  695. continue;
  696. if (dominated_by_is_err(rhs1, bb))
  697. continue;
  698. if (TREE_CODE(ptr_rhs_type) != RECORD_TYPE) {
  699. #ifndef __DEBUG_PLUGIN
  700. if (lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(ptr_lhs_type)))
  701. #endif
  702. {
  703. if (!whitelisted_cast(stmt, ptr_lhs_type, ptr_rhs_type))
  704. MISMATCH(gimple_location(stmt), "rhs", ptr_lhs_type, ptr_rhs_type);
  705. }
  706. continue;
  707. }
  708. if (rhs_code == SSA_NAME && ptr_lhs_type == ptr_rhs_type)
  709. continue;
  710. if (rhs_code == ADDR_EXPR) {
  711. op0 = TREE_OPERAND(rhs1, 0);
  712. if (op0 == NULL_TREE)
  713. continue;
  714. if (TREE_CODE(op0) != VAR_DECL)
  715. continue;
  716. op0_type = TYPE_MAIN_VARIANT(strip_array_types(TYPE_MAIN_VARIANT(TREE_TYPE(op0))));
  717. if (op0_type == ptr_lhs_type)
  718. continue;
  719. #ifndef __DEBUG_PLUGIN
  720. if (lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(op0_type)))
  721. #endif
  722. {
  723. if (!whitelisted_cast(stmt, ptr_lhs_type, op0_type))
  724. MISMATCH(gimple_location(stmt), "op0", ptr_lhs_type, op0_type);
  725. }
  726. } else {
  727. const_tree ssa_name_var = SSA_NAME_VAR(rhs1);
  728. /* skip bogus type casts introduced by container_of */
  729. if (ssa_name_var != NULL_TREE && DECL_NAME(ssa_name_var) &&
  730. !strcmp((const char *)DECL_NAME_POINTER(ssa_name_var), "__mptr"))
  731. continue;
  732. #ifndef __DEBUG_PLUGIN
  733. if (lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(ptr_rhs_type)))
  734. #endif
  735. {
  736. if (!whitelisted_cast(stmt, ptr_lhs_type, ptr_rhs_type))
  737. MISMATCH(gimple_location(stmt), "ssa", ptr_lhs_type, ptr_rhs_type);
  738. }
  739. }
  740. }
  741. }
  742. return 0;
  743. }
  744. #define PASS_NAME find_bad_casts
  745. #define NO_GATE
  746. #define TODO_FLAGS_FINISH TODO_dump_func
  747. #include "gcc-generate-gimple-pass.h"
  748. __visible int plugin_init(struct plugin_name_args *plugin_info, struct plugin_gcc_version *version)
  749. {
  750. int i;
  751. const char * const plugin_name = plugin_info->base_name;
  752. const int argc = plugin_info->argc;
  753. const struct plugin_argument * const argv = plugin_info->argv;
  754. bool enable = true;
  755. int obtained_seed = 0;
  756. struct register_pass_info find_bad_casts_pass_info;
  757. find_bad_casts_pass_info.pass = make_find_bad_casts_pass();
  758. find_bad_casts_pass_info.reference_pass_name = "ssa";
  759. find_bad_casts_pass_info.ref_pass_instance_number = 1;
  760. find_bad_casts_pass_info.pos_op = PASS_POS_INSERT_AFTER;
  761. if (!plugin_default_version_check(version, &gcc_version)) {
  762. error(G_("incompatible gcc/plugin versions"));
  763. return 1;
  764. }
  765. if (strncmp(lang_hooks.name, "GNU C", 5) && !strncmp(lang_hooks.name, "GNU C+", 6)) {
  766. inform(UNKNOWN_LOCATION, G_("%s supports C only, not %s"), plugin_name, lang_hooks.name);
  767. enable = false;
  768. }
  769. for (i = 0; i < argc; ++i) {
  770. if (!strcmp(argv[i].key, "disable")) {
  771. enable = false;
  772. continue;
  773. }
  774. if (!strcmp(argv[i].key, "performance-mode")) {
  775. performance_mode = 1;
  776. continue;
  777. }
  778. error(G_("unknown option '-fplugin-arg-%s-%s'"), plugin_name, argv[i].key);
  779. }
  780. if (strlen(randstruct_seed) != 64) {
  781. error(G_("invalid seed value supplied for %s plugin"), plugin_name);
  782. return 1;
  783. }
  784. obtained_seed = sscanf(randstruct_seed, "%016llx%016llx%016llx%016llx",
  785. &shuffle_seed[0], &shuffle_seed[1], &shuffle_seed[2], &shuffle_seed[3]);
  786. if (obtained_seed != 4) {
  787. error(G_("Invalid seed supplied for %s plugin"), plugin_name);
  788. return 1;
  789. }
  790. register_callback(plugin_name, PLUGIN_INFO, NULL, &randomize_layout_plugin_info);
  791. if (enable) {
  792. register_callback(plugin_name, PLUGIN_ALL_IPA_PASSES_START, check_global_variables, NULL);
  793. register_callback(plugin_name, PLUGIN_PASS_MANAGER_SETUP, NULL, &find_bad_casts_pass_info);
  794. register_callback(plugin_name, PLUGIN_FINISH_TYPE, finish_type, NULL);
  795. register_callback(plugin_name, PLUGIN_FINISH_DECL, randomize_layout_finish_decl, NULL);
  796. }
  797. register_callback(plugin_name, PLUGIN_ATTRIBUTES, register_attributes, NULL);
  798. return 0;
  799. }