kmemcheck.rst 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  1. Getting started with kmemcheck
  2. ==============================
  3. Vegard Nossum <vegardno@ifi.uio.no>
  4. Introduction
  5. ------------
  6. kmemcheck is a debugging feature for the Linux Kernel. More specifically, it
  7. is a dynamic checker that detects and warns about some uses of uninitialized
  8. memory.
  9. Userspace programmers might be familiar with Valgrind's memcheck. The main
  10. difference between memcheck and kmemcheck is that memcheck works for userspace
  11. programs only, and kmemcheck works for the kernel only. The implementations
  12. are of course vastly different. Because of this, kmemcheck is not as accurate
  13. as memcheck, but it turns out to be good enough in practice to discover real
  14. programmer errors that the compiler is not able to find through static
  15. analysis.
  16. Enabling kmemcheck on a kernel will probably slow it down to the extent that
  17. the machine will not be usable for normal workloads such as e.g. an
  18. interactive desktop. kmemcheck will also cause the kernel to use about twice
  19. as much memory as normal. For this reason, kmemcheck is strictly a debugging
  20. feature.
  21. Downloading
  22. -----------
  23. As of version 2.6.31-rc1, kmemcheck is included in the mainline kernel.
  24. Configuring and compiling
  25. -------------------------
  26. kmemcheck only works for the x86 (both 32- and 64-bit) platform. A number of
  27. configuration variables must have specific settings in order for the kmemcheck
  28. menu to even appear in "menuconfig". These are:
  29. - ``CONFIG_CC_OPTIMIZE_FOR_SIZE=n``
  30. This option is located under "General setup" / "Optimize for size".
  31. Without this, gcc will use certain optimizations that usually lead to
  32. false positive warnings from kmemcheck. An example of this is a 16-bit
  33. field in a struct, where gcc may load 32 bits, then discard the upper
  34. 16 bits. kmemcheck sees only the 32-bit load, and may trigger a
  35. warning for the upper 16 bits (if they're uninitialized).
  36. - ``CONFIG_SLAB=y`` or ``CONFIG_SLUB=y``
  37. This option is located under "General setup" / "Choose SLAB
  38. allocator".
  39. - ``CONFIG_FUNCTION_TRACER=n``
  40. This option is located under "Kernel hacking" / "Tracers" / "Kernel
  41. Function Tracer"
  42. When function tracing is compiled in, gcc emits a call to another
  43. function at the beginning of every function. This means that when the
  44. page fault handler is called, the ftrace framework will be called
  45. before kmemcheck has had a chance to handle the fault. If ftrace then
  46. modifies memory that was tracked by kmemcheck, the result is an
  47. endless recursive page fault.
  48. - ``CONFIG_DEBUG_PAGEALLOC=n``
  49. This option is located under "Kernel hacking" / "Memory Debugging"
  50. / "Debug page memory allocations".
  51. In addition, I highly recommend turning on ``CONFIG_DEBUG_INFO=y``. This is also
  52. located under "Kernel hacking". With this, you will be able to get line number
  53. information from the kmemcheck warnings, which is extremely valuable in
  54. debugging a problem. This option is not mandatory, however, because it slows
  55. down the compilation process and produces a much bigger kernel image.
  56. Now the kmemcheck menu should be visible (under "Kernel hacking" / "Memory
  57. Debugging" / "kmemcheck: trap use of uninitialized memory"). Here follows
  58. a description of the kmemcheck configuration variables:
  59. - ``CONFIG_KMEMCHECK``
  60. This must be enabled in order to use kmemcheck at all...
  61. - ``CONFIG_KMEMCHECK_``[``DISABLED`` | ``ENABLED`` | ``ONESHOT``]``_BY_DEFAULT``
  62. This option controls the status of kmemcheck at boot-time. "Enabled"
  63. will enable kmemcheck right from the start, "disabled" will boot the
  64. kernel as normal (but with the kmemcheck code compiled in, so it can
  65. be enabled at run-time after the kernel has booted), and "one-shot" is
  66. a special mode which will turn kmemcheck off automatically after
  67. detecting the first use of uninitialized memory.
  68. If you are using kmemcheck to actively debug a problem, then you
  69. probably want to choose "enabled" here.
  70. The one-shot mode is mostly useful in automated test setups because it
  71. can prevent floods of warnings and increase the chances of the machine
  72. surviving in case something is really wrong. In other cases, the one-
  73. shot mode could actually be counter-productive because it would turn
  74. itself off at the very first error -- in the case of a false positive
  75. too -- and this would come in the way of debugging the specific
  76. problem you were interested in.
  77. If you would like to use your kernel as normal, but with a chance to
  78. enable kmemcheck in case of some problem, it might be a good idea to
  79. choose "disabled" here. When kmemcheck is disabled, most of the run-
  80. time overhead is not incurred, and the kernel will be almost as fast
  81. as normal.
  82. - ``CONFIG_KMEMCHECK_QUEUE_SIZE``
  83. Select the maximum number of error reports to store in an internal
  84. (fixed-size) buffer. Since errors can occur virtually anywhere and in
  85. any context, we need a temporary storage area which is guaranteed not
  86. to generate any other page faults when accessed. The queue will be
  87. emptied as soon as a tasklet may be scheduled. If the queue is full,
  88. new error reports will be lost.
  89. The default value of 64 is probably fine. If some code produces more
  90. than 64 errors within an irqs-off section, then the code is likely to
  91. produce many, many more, too, and these additional reports seldom give
  92. any more information (the first report is usually the most valuable
  93. anyway).
  94. This number might have to be adjusted if you are not using serial
  95. console or similar to capture the kernel log. If you are using the
  96. "dmesg" command to save the log, then getting a lot of kmemcheck
  97. warnings might overflow the kernel log itself, and the earlier reports
  98. will get lost in that way instead. Try setting this to 10 or so on
  99. such a setup.
  100. - ``CONFIG_KMEMCHECK_SHADOW_COPY_SHIFT``
  101. Select the number of shadow bytes to save along with each entry of the
  102. error-report queue. These bytes indicate what parts of an allocation
  103. are initialized, uninitialized, etc. and will be displayed when an
  104. error is detected to help the debugging of a particular problem.
  105. The number entered here is actually the logarithm of the number of
  106. bytes that will be saved. So if you pick for example 5 here, kmemcheck
  107. will save 2^5 = 32 bytes.
  108. The default value should be fine for debugging most problems. It also
  109. fits nicely within 80 columns.
  110. - ``CONFIG_KMEMCHECK_PARTIAL_OK``
  111. This option (when enabled) works around certain GCC optimizations that
  112. produce 32-bit reads from 16-bit variables where the upper 16 bits are
  113. thrown away afterwards.
  114. The default value (enabled) is recommended. This may of course hide
  115. some real errors, but disabling it would probably produce a lot of
  116. false positives.
  117. - ``CONFIG_KMEMCHECK_BITOPS_OK``
  118. This option silences warnings that would be generated for bit-field
  119. accesses where not all the bits are initialized at the same time. This
  120. may also hide some real bugs.
  121. This option is probably obsolete, or it should be replaced with
  122. the kmemcheck-/bitfield-annotations for the code in question. The
  123. default value is therefore fine.
  124. Now compile the kernel as usual.
  125. How to use
  126. ----------
  127. Booting
  128. ~~~~~~~
  129. First some information about the command-line options. There is only one
  130. option specific to kmemcheck, and this is called "kmemcheck". It can be used
  131. to override the default mode as chosen by the ``CONFIG_KMEMCHECK_*_BY_DEFAULT``
  132. option. Its possible settings are:
  133. - ``kmemcheck=0`` (disabled)
  134. - ``kmemcheck=1`` (enabled)
  135. - ``kmemcheck=2`` (one-shot mode)
  136. If SLUB debugging has been enabled in the kernel, it may take precedence over
  137. kmemcheck in such a way that the slab caches which are under SLUB debugging
  138. will not be tracked by kmemcheck. In order to ensure that this doesn't happen
  139. (even though it shouldn't by default), use SLUB's boot option ``slub_debug``,
  140. like this: ``slub_debug=-``
  141. In fact, this option may also be used for fine-grained control over SLUB vs.
  142. kmemcheck. For example, if the command line includes
  143. ``kmemcheck=1 slub_debug=,dentry``, then SLUB debugging will be used only
  144. for the "dentry" slab cache, and with kmemcheck tracking all the other
  145. caches. This is advanced usage, however, and is not generally recommended.
  146. Run-time enable/disable
  147. ~~~~~~~~~~~~~~~~~~~~~~~
  148. When the kernel has booted, it is possible to enable or disable kmemcheck at
  149. run-time. WARNING: This feature is still experimental and may cause false
  150. positive warnings to appear. Therefore, try not to use this. If you find that
  151. it doesn't work properly (e.g. you see an unreasonable amount of warnings), I
  152. will be happy to take bug reports.
  153. Use the file ``/proc/sys/kernel/kmemcheck`` for this purpose, e.g.::
  154. $ echo 0 > /proc/sys/kernel/kmemcheck # disables kmemcheck
  155. The numbers are the same as for the ``kmemcheck=`` command-line option.
  156. Debugging
  157. ~~~~~~~~~
  158. A typical report will look something like this::
  159. WARNING: kmemcheck: Caught 32-bit read from uninitialized memory (ffff88003e4a2024)
  160. 80000000000000000000000000000000000000000088ffff0000000000000000
  161. i i i i u u u u i i i i i i i i u u u u u u u u u u u u u u u u
  162. ^
  163. Pid: 1856, comm: ntpdate Not tainted 2.6.29-rc5 #264 945P-A
  164. RIP: 0010:[<ffffffff8104ede8>] [<ffffffff8104ede8>] __dequeue_signal+0xc8/0x190
  165. RSP: 0018:ffff88003cdf7d98 EFLAGS: 00210002
  166. RAX: 0000000000000030 RBX: ffff88003d4ea968 RCX: 0000000000000009
  167. RDX: ffff88003e5d6018 RSI: ffff88003e5d6024 RDI: ffff88003cdf7e84
  168. RBP: ffff88003cdf7db8 R08: ffff88003e5d6000 R09: 0000000000000000
  169. R10: 0000000000000080 R11: 0000000000000000 R12: 000000000000000e
  170. R13: ffff88003cdf7e78 R14: ffff88003d530710 R15: ffff88003d5a98c8
  171. FS: 0000000000000000(0000) GS:ffff880001982000(0063) knlGS:00000
  172. CS: 0010 DS: 002b ES: 002b CR0: 0000000080050033
  173. CR2: ffff88003f806ea0 CR3: 000000003c036000 CR4: 00000000000006a0
  174. DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
  175. DR3: 0000000000000000 DR6: 00000000ffff4ff0 DR7: 0000000000000400
  176. [<ffffffff8104f04e>] dequeue_signal+0x8e/0x170
  177. [<ffffffff81050bd8>] get_signal_to_deliver+0x98/0x390
  178. [<ffffffff8100b87d>] do_notify_resume+0xad/0x7d0
  179. [<ffffffff8100c7b5>] int_signal+0x12/0x17
  180. [<ffffffffffffffff>] 0xffffffffffffffff
  181. The single most valuable information in this report is the RIP (or EIP on 32-
  182. bit) value. This will help us pinpoint exactly which instruction that caused
  183. the warning.
  184. If your kernel was compiled with ``CONFIG_DEBUG_INFO=y``, then all we have to do
  185. is give this address to the addr2line program, like this::
  186. $ addr2line -e vmlinux -i ffffffff8104ede8
  187. arch/x86/include/asm/string_64.h:12
  188. include/asm-generic/siginfo.h:287
  189. kernel/signal.c:380
  190. kernel/signal.c:410
  191. The "``-e vmlinux``" tells addr2line which file to look in. **IMPORTANT:**
  192. This must be the vmlinux of the kernel that produced the warning in the
  193. first place! If not, the line number information will almost certainly be
  194. wrong.
  195. The "``-i``" tells addr2line to also print the line numbers of inlined
  196. functions. In this case, the flag was very important, because otherwise,
  197. it would only have printed the first line, which is just a call to
  198. ``memcpy()``, which could be called from a thousand places in the kernel, and
  199. is therefore not very useful. These inlined functions would not show up in
  200. the stack trace above, simply because the kernel doesn't load the extra
  201. debugging information. This technique can of course be used with ordinary
  202. kernel oopses as well.
  203. In this case, it's the caller of ``memcpy()`` that is interesting, and it can be
  204. found in ``include/asm-generic/siginfo.h``, line 287::
  205. 281 static inline void copy_siginfo(struct siginfo *to, struct siginfo *from)
  206. 282 {
  207. 283 if (from->si_code < 0)
  208. 284 memcpy(to, from, sizeof(*to));
  209. 285 else
  210. 286 /* _sigchld is currently the largest know union member */
  211. 287 memcpy(to, from, __ARCH_SI_PREAMBLE_SIZE + sizeof(from->_sifields._sigchld));
  212. 288 }
  213. Since this was a read (kmemcheck usually warns about reads only, though it can
  214. warn about writes to unallocated or freed memory as well), it was probably the
  215. "from" argument which contained some uninitialized bytes. Following the chain
  216. of calls, we move upwards to see where "from" was allocated or initialized,
  217. ``kernel/signal.c``, line 380::
  218. 359 static void collect_signal(int sig, struct sigpending *list, siginfo_t *info)
  219. 360 {
  220. ...
  221. 367 list_for_each_entry(q, &list->list, list) {
  222. 368 if (q->info.si_signo == sig) {
  223. 369 if (first)
  224. 370 goto still_pending;
  225. 371 first = q;
  226. ...
  227. 377 if (first) {
  228. 378 still_pending:
  229. 379 list_del_init(&first->list);
  230. 380 copy_siginfo(info, &first->info);
  231. 381 __sigqueue_free(first);
  232. ...
  233. 392 }
  234. 393 }
  235. Here, it is ``&first->info`` that is being passed on to ``copy_siginfo()``. The
  236. variable ``first`` was found on a list -- passed in as the second argument to
  237. ``collect_signal()``. We continue our journey through the stack, to figure out
  238. where the item on "list" was allocated or initialized. We move to line 410::
  239. 395 static int __dequeue_signal(struct sigpending *pending, sigset_t *mask,
  240. 396 siginfo_t *info)
  241. 397 {
  242. ...
  243. 410 collect_signal(sig, pending, info);
  244. ...
  245. 414 }
  246. Now we need to follow the ``pending`` pointer, since that is being passed on to
  247. ``collect_signal()`` as ``list``. At this point, we've run out of lines from the
  248. "addr2line" output. Not to worry, we just paste the next addresses from the
  249. kmemcheck stack dump, i.e.::
  250. [<ffffffff8104f04e>] dequeue_signal+0x8e/0x170
  251. [<ffffffff81050bd8>] get_signal_to_deliver+0x98/0x390
  252. [<ffffffff8100b87d>] do_notify_resume+0xad/0x7d0
  253. [<ffffffff8100c7b5>] int_signal+0x12/0x17
  254. $ addr2line -e vmlinux -i ffffffff8104f04e ffffffff81050bd8 \
  255. ffffffff8100b87d ffffffff8100c7b5
  256. kernel/signal.c:446
  257. kernel/signal.c:1806
  258. arch/x86/kernel/signal.c:805
  259. arch/x86/kernel/signal.c:871
  260. arch/x86/kernel/entry_64.S:694
  261. Remember that since these addresses were found on the stack and not as the
  262. RIP value, they actually point to the _next_ instruction (they are return
  263. addresses). This becomes obvious when we look at the code for line 446::
  264. 422 int dequeue_signal(struct task_struct *tsk, sigset_t *mask, siginfo_t *info)
  265. 423 {
  266. ...
  267. 431 signr = __dequeue_signal(&tsk->signal->shared_pending,
  268. 432 mask, info);
  269. 433 /*
  270. 434 * itimer signal ?
  271. 435 *
  272. 436 * itimers are process shared and we restart periodic
  273. 437 * itimers in the signal delivery path to prevent DoS
  274. 438 * attacks in the high resolution timer case. This is
  275. 439 * compliant with the old way of self restarting
  276. 440 * itimers, as the SIGALRM is a legacy signal and only
  277. 441 * queued once. Changing the restart behaviour to
  278. 442 * restart the timer in the signal dequeue path is
  279. 443 * reducing the timer noise on heavy loaded !highres
  280. 444 * systems too.
  281. 445 */
  282. 446 if (unlikely(signr == SIGALRM)) {
  283. ...
  284. 489 }
  285. So instead of looking at 446, we should be looking at 431, which is the line
  286. that executes just before 446. Here we see that what we are looking for is
  287. ``&tsk->signal->shared_pending``.
  288. Our next task is now to figure out which function that puts items on this
  289. ``shared_pending`` list. A crude, but efficient tool, is ``git grep``::
  290. $ git grep -n 'shared_pending' kernel/
  291. ...
  292. kernel/signal.c:828: pending = group ? &t->signal->shared_pending : &t->pending;
  293. kernel/signal.c:1339: pending = group ? &t->signal->shared_pending : &t->pending;
  294. ...
  295. There were more results, but none of them were related to list operations,
  296. and these were the only assignments. We inspect the line numbers more closely
  297. and find that this is indeed where items are being added to the list::
  298. 816 static int send_signal(int sig, struct siginfo *info, struct task_struct *t,
  299. 817 int group)
  300. 818 {
  301. ...
  302. 828 pending = group ? &t->signal->shared_pending : &t->pending;
  303. ...
  304. 851 q = __sigqueue_alloc(t, GFP_ATOMIC, (sig < SIGRTMIN &&
  305. 852 (is_si_special(info) ||
  306. 853 info->si_code >= 0)));
  307. 854 if (q) {
  308. 855 list_add_tail(&q->list, &pending->list);
  309. ...
  310. 890 }
  311. and::
  312. 1309 int send_sigqueue(struct sigqueue *q, struct task_struct *t, int group)
  313. 1310 {
  314. ....
  315. 1339 pending = group ? &t->signal->shared_pending : &t->pending;
  316. 1340 list_add_tail(&q->list, &pending->list);
  317. ....
  318. 1347 }
  319. In the first case, the list element we are looking for, ``q``, is being
  320. returned from the function ``__sigqueue_alloc()``, which looks like an
  321. allocation function. Let's take a look at it::
  322. 187 static struct sigqueue *__sigqueue_alloc(struct task_struct *t, gfp_t flags,
  323. 188 int override_rlimit)
  324. 189 {
  325. 190 struct sigqueue *q = NULL;
  326. 191 struct user_struct *user;
  327. 192
  328. 193 /*
  329. 194 * We won't get problems with the target's UID changing under us
  330. 195 * because changing it requires RCU be used, and if t != current, the
  331. 196 * caller must be holding the RCU readlock (by way of a spinlock) and
  332. 197 * we use RCU protection here
  333. 198 */
  334. 199 user = get_uid(__task_cred(t)->user);
  335. 200 atomic_inc(&user->sigpending);
  336. 201 if (override_rlimit ||
  337. 202 atomic_read(&user->sigpending) <=
  338. 203 t->signal->rlim[RLIMIT_SIGPENDING].rlim_cur)
  339. 204 q = kmem_cache_alloc(sigqueue_cachep, flags);
  340. 205 if (unlikely(q == NULL)) {
  341. 206 atomic_dec(&user->sigpending);
  342. 207 free_uid(user);
  343. 208 } else {
  344. 209 INIT_LIST_HEAD(&q->list);
  345. 210 q->flags = 0;
  346. 211 q->user = user;
  347. 212 }
  348. 213
  349. 214 return q;
  350. 215 }
  351. We see that this function initializes ``q->list``, ``q->flags``, and
  352. ``q->user``. It seems that now is the time to look at the definition of
  353. ``struct sigqueue``, e.g.::
  354. 14 struct sigqueue {
  355. 15 struct list_head list;
  356. 16 int flags;
  357. 17 siginfo_t info;
  358. 18 struct user_struct *user;
  359. 19 };
  360. And, you might remember, it was a ``memcpy()`` on ``&first->info`` that
  361. caused the warning, so this makes perfect sense. It also seems reasonable
  362. to assume that it is the caller of ``__sigqueue_alloc()`` that has the
  363. responsibility of filling out (initializing) this member.
  364. But just which fields of the struct were uninitialized? Let's look at
  365. kmemcheck's report again::
  366. WARNING: kmemcheck: Caught 32-bit read from uninitialized memory (ffff88003e4a2024)
  367. 80000000000000000000000000000000000000000088ffff0000000000000000
  368. i i i i u u u u i i i i i i i i u u u u u u u u u u u u u u u u
  369. ^
  370. These first two lines are the memory dump of the memory object itself, and
  371. the shadow bytemap, respectively. The memory object itself is in this case
  372. ``&first->info``. Just beware that the start of this dump is NOT the start
  373. of the object itself! The position of the caret (^) corresponds with the
  374. address of the read (ffff88003e4a2024).
  375. The shadow bytemap dump legend is as follows:
  376. - i: initialized
  377. - u: uninitialized
  378. - a: unallocated (memory has been allocated by the slab layer, but has not
  379. yet been handed off to anybody)
  380. - f: freed (memory has been allocated by the slab layer, but has been freed
  381. by the previous owner)
  382. In order to figure out where (relative to the start of the object) the
  383. uninitialized memory was located, we have to look at the disassembly. For
  384. that, we'll need the RIP address again::
  385. RIP: 0010:[<ffffffff8104ede8>] [<ffffffff8104ede8>] __dequeue_signal+0xc8/0x190
  386. $ objdump -d --no-show-raw-insn vmlinux | grep -C 8 ffffffff8104ede8:
  387. ffffffff8104edc8: mov %r8,0x8(%r8)
  388. ffffffff8104edcc: test %r10d,%r10d
  389. ffffffff8104edcf: js ffffffff8104ee88 <__dequeue_signal+0x168>
  390. ffffffff8104edd5: mov %rax,%rdx
  391. ffffffff8104edd8: mov $0xc,%ecx
  392. ffffffff8104eddd: mov %r13,%rdi
  393. ffffffff8104ede0: mov $0x30,%eax
  394. ffffffff8104ede5: mov %rdx,%rsi
  395. ffffffff8104ede8: rep movsl %ds:(%rsi),%es:(%rdi)
  396. ffffffff8104edea: test $0x2,%al
  397. ffffffff8104edec: je ffffffff8104edf0 <__dequeue_signal+0xd0>
  398. ffffffff8104edee: movsw %ds:(%rsi),%es:(%rdi)
  399. ffffffff8104edf0: test $0x1,%al
  400. ffffffff8104edf2: je ffffffff8104edf5 <__dequeue_signal+0xd5>
  401. ffffffff8104edf4: movsb %ds:(%rsi),%es:(%rdi)
  402. ffffffff8104edf5: mov %r8,%rdi
  403. ffffffff8104edf8: callq ffffffff8104de60 <__sigqueue_free>
  404. As expected, it's the "``rep movsl``" instruction from the ``memcpy()``
  405. that causes the warning. We know about ``REP MOVSL`` that it uses the register
  406. ``RCX`` to count the number of remaining iterations. By taking a look at the
  407. register dump again (from the kmemcheck report), we can figure out how many
  408. bytes were left to copy::
  409. RAX: 0000000000000030 RBX: ffff88003d4ea968 RCX: 0000000000000009
  410. By looking at the disassembly, we also see that ``%ecx`` is being loaded
  411. with the value ``$0xc`` just before (ffffffff8104edd8), so we are very
  412. lucky. Keep in mind that this is the number of iterations, not bytes. And
  413. since this is a "long" operation, we need to multiply by 4 to get the
  414. number of bytes. So this means that the uninitialized value was encountered
  415. at 4 * (0xc - 0x9) = 12 bytes from the start of the object.
  416. We can now try to figure out which field of the "``struct siginfo``" that
  417. was not initialized. This is the beginning of the struct::
  418. 40 typedef struct siginfo {
  419. 41 int si_signo;
  420. 42 int si_errno;
  421. 43 int si_code;
  422. 44
  423. 45 union {
  424. ..
  425. 92 } _sifields;
  426. 93 } siginfo_t;
  427. On 64-bit, the int is 4 bytes long, so it must the union member that has
  428. not been initialized. We can verify this using gdb::
  429. $ gdb vmlinux
  430. ...
  431. (gdb) p &((struct siginfo *) 0)->_sifields
  432. $1 = (union {...} *) 0x10
  433. Actually, it seems that the union member is located at offset 0x10 -- which
  434. means that gcc has inserted 4 bytes of padding between the members ``si_code``
  435. and ``_sifields``. We can now get a fuller picture of the memory dump::
  436. _----------------------------=> si_code
  437. / _--------------------=> (padding)
  438. | / _------------=> _sifields(._kill._pid)
  439. | | / _----=> _sifields(._kill._uid)
  440. | | | /
  441. -------|-------|-------|-------|
  442. 80000000000000000000000000000000000000000088ffff0000000000000000
  443. i i i i u u u u i i i i i i i i u u u u u u u u u u u u u u u u
  444. This allows us to realize another important fact: ``si_code`` contains the
  445. value 0x80. Remember that x86 is little endian, so the first 4 bytes
  446. "80000000" are really the number 0x00000080. With a bit of research, we
  447. find that this is actually the constant ``SI_KERNEL`` defined in
  448. ``include/asm-generic/siginfo.h``::
  449. 144 #define SI_KERNEL 0x80 /* sent by the kernel from somewhere */
  450. This macro is used in exactly one place in the x86 kernel: In ``send_signal()``
  451. in ``kernel/signal.c``::
  452. 816 static int send_signal(int sig, struct siginfo *info, struct task_struct *t,
  453. 817 int group)
  454. 818 {
  455. ...
  456. 828 pending = group ? &t->signal->shared_pending : &t->pending;
  457. ...
  458. 851 q = __sigqueue_alloc(t, GFP_ATOMIC, (sig < SIGRTMIN &&
  459. 852 (is_si_special(info) ||
  460. 853 info->si_code >= 0)));
  461. 854 if (q) {
  462. 855 list_add_tail(&q->list, &pending->list);
  463. 856 switch ((unsigned long) info) {
  464. ...
  465. 865 case (unsigned long) SEND_SIG_PRIV:
  466. 866 q->info.si_signo = sig;
  467. 867 q->info.si_errno = 0;
  468. 868 q->info.si_code = SI_KERNEL;
  469. 869 q->info.si_pid = 0;
  470. 870 q->info.si_uid = 0;
  471. 871 break;
  472. ...
  473. 890 }
  474. Not only does this match with the ``.si_code`` member, it also matches the place
  475. we found earlier when looking for where siginfo_t objects are enqueued on the
  476. ``shared_pending`` list.
  477. So to sum up: It seems that it is the padding introduced by the compiler
  478. between two struct fields that is uninitialized, and this gets reported when
  479. we do a ``memcpy()`` on the struct. This means that we have identified a false
  480. positive warning.
  481. Normally, kmemcheck will not report uninitialized accesses in ``memcpy()`` calls
  482. when both the source and destination addresses are tracked. (Instead, we copy
  483. the shadow bytemap as well). In this case, the destination address clearly
  484. was not tracked. We can dig a little deeper into the stack trace from above::
  485. arch/x86/kernel/signal.c:805
  486. arch/x86/kernel/signal.c:871
  487. arch/x86/kernel/entry_64.S:694
  488. And we clearly see that the destination siginfo object is located on the
  489. stack::
  490. 782 static void do_signal(struct pt_regs *regs)
  491. 783 {
  492. 784 struct k_sigaction ka;
  493. 785 siginfo_t info;
  494. ...
  495. 804 signr = get_signal_to_deliver(&info, &ka, regs, NULL);
  496. ...
  497. 854 }
  498. And this ``&info`` is what eventually gets passed to ``copy_siginfo()`` as the
  499. destination argument.
  500. Now, even though we didn't find an actual error here, the example is still a
  501. good one, because it shows how one would go about to find out what the report
  502. was all about.
  503. Annotating false positives
  504. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  505. There are a few different ways to make annotations in the source code that
  506. will keep kmemcheck from checking and reporting certain allocations. Here
  507. they are:
  508. - ``__GFP_NOTRACK_FALSE_POSITIVE``
  509. This flag can be passed to ``kmalloc()`` or ``kmem_cache_alloc()``
  510. (therefore also to other functions that end up calling one of
  511. these) to indicate that the allocation should not be tracked
  512. because it would lead to a false positive report. This is a "big
  513. hammer" way of silencing kmemcheck; after all, even if the false
  514. positive pertains to particular field in a struct, for example, we
  515. will now lose the ability to find (real) errors in other parts of
  516. the same struct.
  517. Example::
  518. /* No warnings will ever trigger on accessing any part of x */
  519. x = kmalloc(sizeof *x, GFP_KERNEL | __GFP_NOTRACK_FALSE_POSITIVE);
  520. - ``kmemcheck_bitfield_begin(name)``/``kmemcheck_bitfield_end(name)`` and
  521. ``kmemcheck_annotate_bitfield(ptr, name)``
  522. The first two of these three macros can be used inside struct
  523. definitions to signal, respectively, the beginning and end of a
  524. bitfield. Additionally, this will assign the bitfield a name, which
  525. is given as an argument to the macros.
  526. Having used these markers, one can later use
  527. kmemcheck_annotate_bitfield() at the point of allocation, to indicate
  528. which parts of the allocation is part of a bitfield.
  529. Example::
  530. struct foo {
  531. int x;
  532. kmemcheck_bitfield_begin(flags);
  533. int flag_a:1;
  534. int flag_b:1;
  535. kmemcheck_bitfield_end(flags);
  536. int y;
  537. };
  538. struct foo *x = kmalloc(sizeof *x);
  539. /* No warnings will trigger on accessing the bitfield of x */
  540. kmemcheck_annotate_bitfield(x, flags);
  541. Note that ``kmemcheck_annotate_bitfield()`` can be used even before the
  542. return value of ``kmalloc()`` is checked -- in other words, passing NULL
  543. as the first argument is legal (and will do nothing).
  544. Reporting errors
  545. ----------------
  546. As we have seen, kmemcheck will produce false positive reports. Therefore, it
  547. is not very wise to blindly post kmemcheck warnings to mailing lists and
  548. maintainers. Instead, I encourage maintainers and developers to find errors
  549. in their own code. If you get a warning, you can try to work around it, try
  550. to figure out if it's a real error or not, or simply ignore it. Most
  551. developers know their own code and will quickly and efficiently determine the
  552. root cause of a kmemcheck report. This is therefore also the most efficient
  553. way to work with kmemcheck.
  554. That said, we (the kmemcheck maintainers) will always be on the lookout for
  555. false positives that we can annotate and silence. So whatever you find,
  556. please drop us a note privately! Kernel configs and steps to reproduce (if
  557. available) are of course a great help too.
  558. Happy hacking!
  559. Technical description
  560. ---------------------
  561. kmemcheck works by marking memory pages non-present. This means that whenever
  562. somebody attempts to access the page, a page fault is generated. The page
  563. fault handler notices that the page was in fact only hidden, and so it calls
  564. on the kmemcheck code to make further investigations.
  565. When the investigations are completed, kmemcheck "shows" the page by marking
  566. it present (as it would be under normal circumstances). This way, the
  567. interrupted code can continue as usual.
  568. But after the instruction has been executed, we should hide the page again, so
  569. that we can catch the next access too! Now kmemcheck makes use of a debugging
  570. feature of the processor, namely single-stepping. When the processor has
  571. finished the one instruction that generated the memory access, a debug
  572. exception is raised. From here, we simply hide the page again and continue
  573. execution, this time with the single-stepping feature turned off.
  574. kmemcheck requires some assistance from the memory allocator in order to work.
  575. The memory allocator needs to
  576. 1. Tell kmemcheck about newly allocated pages and pages that are about to
  577. be freed. This allows kmemcheck to set up and tear down the shadow memory
  578. for the pages in question. The shadow memory stores the status of each
  579. byte in the allocation proper, e.g. whether it is initialized or
  580. uninitialized.
  581. 2. Tell kmemcheck which parts of memory should be marked uninitialized.
  582. There are actually a few more states, such as "not yet allocated" and
  583. "recently freed".
  584. If a slab cache is set up using the SLAB_NOTRACK flag, it will never return
  585. memory that can take page faults because of kmemcheck.
  586. If a slab cache is NOT set up using the SLAB_NOTRACK flag, callers can still
  587. request memory with the __GFP_NOTRACK or __GFP_NOTRACK_FALSE_POSITIVE flags.
  588. This does not prevent the page faults from occurring, however, but marks the
  589. object in question as being initialized so that no warnings will ever be
  590. produced for this object.
  591. Currently, the SLAB and SLUB allocators are supported by kmemcheck.