randomize_layout_plugin.c 26 KB

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