randomize_layout_plugin.c 27 KB

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