randomize_layout_plugin.c 27 KB

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