report.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * KFENCE reporting.
  4. *
  5. * Copyright (C) 2020, Google LLC.
  6. */
  7. #include <linux/stdarg.h>
  8. #include <linux/kernel.h>
  9. #include <linux/lockdep.h>
  10. #include <linux/math.h>
  11. #include <linux/printk.h>
  12. #include <linux/sched/debug.h>
  13. #include <linux/seq_file.h>
  14. #include <linux/sprintf.h>
  15. #include <linux/stacktrace.h>
  16. #include <linux/string.h>
  17. #include <linux/string_choices.h>
  18. #include <linux/sched/clock.h>
  19. #include <trace/events/error_report.h>
  20. #include <asm/kfence.h>
  21. #include "kfence.h"
  22. /* May be overridden by <asm/kfence.h>. */
  23. #ifndef ARCH_FUNC_PREFIX
  24. #define ARCH_FUNC_PREFIX ""
  25. #endif
  26. /* Helper function to either print to a seq_file or to console. */
  27. __printf(2, 3)
  28. static void seq_con_printf(struct seq_file *seq, const char *fmt, ...)
  29. {
  30. va_list args;
  31. va_start(args, fmt);
  32. if (seq)
  33. seq_vprintf(seq, fmt, args);
  34. else
  35. vprintk(fmt, args);
  36. va_end(args);
  37. }
  38. /*
  39. * Get the number of stack entries to skip to get out of MM internals. @type is
  40. * optional, and if set to NULL, assumes an allocation or free stack.
  41. */
  42. static int get_stack_skipnr(const unsigned long stack_entries[], int num_entries,
  43. const enum kfence_error_type *type)
  44. {
  45. char buf[64];
  46. int skipnr, fallback = 0;
  47. if (type) {
  48. /* Depending on error type, find different stack entries. */
  49. switch (*type) {
  50. case KFENCE_ERROR_UAF:
  51. case KFENCE_ERROR_OOB:
  52. case KFENCE_ERROR_INVALID:
  53. /*
  54. * kfence_handle_page_fault() may be called with pt_regs
  55. * set to NULL; in that case we'll simply show the full
  56. * stack trace.
  57. */
  58. return 0;
  59. case KFENCE_ERROR_CORRUPTION:
  60. case KFENCE_ERROR_INVALID_FREE:
  61. break;
  62. }
  63. }
  64. for (skipnr = 0; skipnr < num_entries; skipnr++) {
  65. int len = scnprintf(buf, sizeof(buf), "%ps", (void *)stack_entries[skipnr]);
  66. if (str_has_prefix(buf, ARCH_FUNC_PREFIX "kfence_") ||
  67. str_has_prefix(buf, ARCH_FUNC_PREFIX "__kfence_") ||
  68. str_has_prefix(buf, ARCH_FUNC_PREFIX "__kmem_cache_free") ||
  69. !strncmp(buf, ARCH_FUNC_PREFIX "__slab_free", len)) {
  70. /*
  71. * In case of tail calls from any of the below to any of
  72. * the above, optimized by the compiler such that the
  73. * stack trace would omit the initial entry point below.
  74. */
  75. fallback = skipnr + 1;
  76. }
  77. /*
  78. * The below list should only include the initial entry points
  79. * into the slab allocators. Includes the *_bulk() variants by
  80. * checking prefixes.
  81. */
  82. if (str_has_prefix(buf, ARCH_FUNC_PREFIX "kfree") ||
  83. str_has_prefix(buf, ARCH_FUNC_PREFIX "kmem_cache_free") ||
  84. str_has_prefix(buf, ARCH_FUNC_PREFIX "__kmalloc") ||
  85. str_has_prefix(buf, ARCH_FUNC_PREFIX "kmem_cache_alloc"))
  86. goto found;
  87. }
  88. if (fallback < num_entries)
  89. return fallback;
  90. found:
  91. skipnr++;
  92. return skipnr < num_entries ? skipnr : 0;
  93. }
  94. static void kfence_print_stack(struct seq_file *seq, const struct kfence_metadata *meta,
  95. bool show_alloc)
  96. __must_hold(&meta->lock)
  97. {
  98. const struct kfence_track *track = show_alloc ? &meta->alloc_track : &meta->free_track;
  99. u64 ts_sec = track->ts_nsec;
  100. unsigned long rem_nsec = do_div(ts_sec, NSEC_PER_SEC);
  101. u64 interval_nsec = local_clock() - track->ts_nsec;
  102. unsigned long rem_interval_nsec = do_div(interval_nsec, NSEC_PER_SEC);
  103. /* Timestamp matches printk timestamp format. */
  104. seq_con_printf(seq, "%s by task %d on cpu %d at %lu.%06lus (%lu.%06lus ago):\n",
  105. show_alloc ? "allocated" : meta->state == KFENCE_OBJECT_RCU_FREEING ?
  106. "rcu freeing" : "freed", track->pid,
  107. track->cpu, (unsigned long)ts_sec, rem_nsec / 1000,
  108. (unsigned long)interval_nsec, rem_interval_nsec / 1000);
  109. if (track->num_stack_entries) {
  110. /* Skip allocation/free internals stack. */
  111. int i = get_stack_skipnr(track->stack_entries, track->num_stack_entries, NULL);
  112. /* stack_trace_seq_print() does not exist; open code our own. */
  113. for (; i < track->num_stack_entries; i++)
  114. seq_con_printf(seq, " %pS\n", (void *)track->stack_entries[i]);
  115. } else {
  116. seq_con_printf(seq, " no %s stack\n", show_alloc ? "allocation" : "deallocation");
  117. }
  118. }
  119. void kfence_print_object(struct seq_file *seq, const struct kfence_metadata *meta)
  120. {
  121. const int size = abs(meta->size);
  122. const unsigned long start = meta->addr;
  123. const struct kmem_cache *const cache = meta->cache;
  124. lockdep_assert_held(&meta->lock);
  125. if (meta->state == KFENCE_OBJECT_UNUSED) {
  126. seq_con_printf(seq, "kfence-#%td unused\n", meta - kfence_metadata);
  127. return;
  128. }
  129. seq_con_printf(seq, "kfence-#%td: 0x%p-0x%p, size=%d, cache=%s\n\n",
  130. meta - kfence_metadata, (void *)start, (void *)(start + size - 1),
  131. size, (cache && cache->name) ? cache->name : "<destroyed>");
  132. kfence_print_stack(seq, meta, true);
  133. if (meta->state == KFENCE_OBJECT_FREED || meta->state == KFENCE_OBJECT_RCU_FREEING) {
  134. seq_con_printf(seq, "\n");
  135. kfence_print_stack(seq, meta, false);
  136. }
  137. }
  138. /*
  139. * Show bytes at @addr that are different from the expected canary values, up to
  140. * @max_bytes.
  141. */
  142. static void print_diff_canary(unsigned long address, size_t bytes_to_show,
  143. const struct kfence_metadata *meta)
  144. {
  145. const unsigned long show_until_addr = address + bytes_to_show;
  146. const u8 *cur, *end;
  147. /* Do not show contents of object nor read into following guard page. */
  148. end = (const u8 *)(address < meta->addr ? min(show_until_addr, meta->addr)
  149. : min(show_until_addr, PAGE_ALIGN(address)));
  150. pr_cont("[");
  151. for (cur = (const u8 *)address; cur < end; cur++) {
  152. if (*cur == KFENCE_CANARY_PATTERN_U8(cur))
  153. pr_cont(" .");
  154. else if (no_hash_pointers)
  155. pr_cont(" 0x%02x", *cur);
  156. else /* Do not leak kernel memory in non-debug builds. */
  157. pr_cont(" !");
  158. }
  159. pr_cont(" ]");
  160. }
  161. static const char *get_access_type(bool is_write)
  162. {
  163. return str_write_read(is_write);
  164. }
  165. void kfence_report_error(unsigned long address, bool is_write, struct pt_regs *regs,
  166. const struct kfence_metadata *meta, enum kfence_error_type type)
  167. {
  168. unsigned long stack_entries[KFENCE_STACK_DEPTH] = { 0 };
  169. const ptrdiff_t object_index = meta ? meta - kfence_metadata : -1;
  170. int num_stack_entries;
  171. int skipnr = 0;
  172. if (regs) {
  173. num_stack_entries = stack_trace_save_regs(regs, stack_entries, KFENCE_STACK_DEPTH, 0);
  174. } else {
  175. num_stack_entries = stack_trace_save(stack_entries, KFENCE_STACK_DEPTH, 1);
  176. skipnr = get_stack_skipnr(stack_entries, num_stack_entries, &type);
  177. }
  178. /* Require non-NULL meta, except if KFENCE_ERROR_INVALID. */
  179. if (WARN_ON(type != KFENCE_ERROR_INVALID && !meta))
  180. return;
  181. /*
  182. * Because we may generate reports in printk-unfriendly parts of the
  183. * kernel, such as scheduler code, the use of printk() could deadlock.
  184. * Until such time that all printing code here is safe in all parts of
  185. * the kernel, accept the risk, and just get our message out (given the
  186. * system might already behave unpredictably due to the memory error).
  187. * As such, also disable lockdep to hide warnings, and avoid disabling
  188. * lockdep for the rest of the kernel.
  189. */
  190. lockdep_off();
  191. pr_err("==================================================================\n");
  192. /* Print report header. */
  193. switch (type) {
  194. case KFENCE_ERROR_OOB: {
  195. const bool left_of_object = address < meta->addr;
  196. pr_err("BUG: KFENCE: out-of-bounds %s in %pS\n\n", get_access_type(is_write),
  197. (void *)stack_entries[skipnr]);
  198. pr_err("Out-of-bounds %s at 0x%p (%luB %s of kfence-#%td):\n",
  199. get_access_type(is_write), (void *)address,
  200. left_of_object ? meta->addr - address : address - meta->addr,
  201. left_of_object ? "left" : "right", object_index);
  202. break;
  203. }
  204. case KFENCE_ERROR_UAF:
  205. pr_err("BUG: KFENCE: use-after-free %s in %pS\n\n", get_access_type(is_write),
  206. (void *)stack_entries[skipnr]);
  207. pr_err("Use-after-free %s at 0x%p (in kfence-#%td):\n",
  208. get_access_type(is_write), (void *)address, object_index);
  209. break;
  210. case KFENCE_ERROR_CORRUPTION:
  211. pr_err("BUG: KFENCE: memory corruption in %pS\n\n", (void *)stack_entries[skipnr]);
  212. pr_err("Corrupted memory at 0x%p ", (void *)address);
  213. print_diff_canary(address, 16, meta);
  214. pr_cont(" (in kfence-#%td):\n", object_index);
  215. break;
  216. case KFENCE_ERROR_INVALID:
  217. pr_err("BUG: KFENCE: invalid %s in %pS\n\n", get_access_type(is_write),
  218. (void *)stack_entries[skipnr]);
  219. pr_err("Invalid %s at 0x%p:\n", get_access_type(is_write),
  220. (void *)address);
  221. break;
  222. case KFENCE_ERROR_INVALID_FREE:
  223. pr_err("BUG: KFENCE: invalid free in %pS\n\n", (void *)stack_entries[skipnr]);
  224. pr_err("Invalid free of 0x%p (in kfence-#%td):\n", (void *)address,
  225. object_index);
  226. break;
  227. }
  228. /* Print stack trace and object info. */
  229. stack_trace_print(stack_entries + skipnr, num_stack_entries - skipnr, 0);
  230. if (meta) {
  231. lockdep_assert_held(&meta->lock);
  232. pr_err("\n");
  233. kfence_print_object(NULL, meta);
  234. }
  235. /* Print report footer. */
  236. pr_err("\n");
  237. if (no_hash_pointers && regs)
  238. show_regs(regs);
  239. else
  240. dump_stack_print_info(KERN_ERR);
  241. trace_error_report_end(ERROR_DETECTOR_KFENCE, address);
  242. pr_err("==================================================================\n");
  243. lockdep_on();
  244. check_panic_on_warn("KFENCE");
  245. /* We encountered a memory safety error, taint the kernel! */
  246. add_taint(TAINT_BAD_PAGE, LOCKDEP_STILL_OK);
  247. }
  248. #ifdef CONFIG_PRINTK
  249. static void kfence_to_kp_stack(const struct kfence_track *track, void **kp_stack)
  250. {
  251. int i, j;
  252. i = get_stack_skipnr(track->stack_entries, track->num_stack_entries, NULL);
  253. for (j = 0; i < track->num_stack_entries && j < KS_ADDRS_COUNT; ++i, ++j)
  254. kp_stack[j] = (void *)track->stack_entries[i];
  255. if (j < KS_ADDRS_COUNT)
  256. kp_stack[j] = NULL;
  257. }
  258. bool __kfence_obj_info(struct kmem_obj_info *kpp, void *object, struct slab *slab)
  259. {
  260. struct kfence_metadata *meta = addr_to_metadata((unsigned long)object);
  261. unsigned long flags;
  262. if (!meta)
  263. return false;
  264. /*
  265. * If state is UNUSED at least show the pointer requested; the rest
  266. * would be garbage data.
  267. */
  268. kpp->kp_ptr = object;
  269. /* Requesting info an a never-used object is almost certainly a bug. */
  270. if (WARN_ON(meta->state == KFENCE_OBJECT_UNUSED))
  271. return true;
  272. raw_spin_lock_irqsave(&meta->lock, flags);
  273. kpp->kp_slab = slab;
  274. kpp->kp_slab_cache = meta->cache;
  275. kpp->kp_objp = (void *)meta->addr;
  276. kfence_to_kp_stack(&meta->alloc_track, kpp->kp_stack);
  277. if (meta->state == KFENCE_OBJECT_FREED || meta->state == KFENCE_OBJECT_RCU_FREEING)
  278. kfence_to_kp_stack(&meta->free_track, kpp->kp_free_stack);
  279. /* get_stack_skipnr() ensures the first entry is outside allocator. */
  280. kpp->kp_ret = kpp->kp_stack[0];
  281. raw_spin_unlock_irqrestore(&meta->lock, flags);
  282. return true;
  283. }
  284. #endif