kcov.rst 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. KCOV: code coverage for fuzzing
  2. ===============================
  3. KCOV collects and exposes kernel code coverage information in a form suitable
  4. for coverage-guided fuzzing. Coverage data of a running kernel is exported via
  5. the ``kcov`` debugfs file. Coverage collection is enabled on a task basis, and
  6. thus KCOV can capture precise coverage of a single system call.
  7. Note that KCOV does not aim to collect as much coverage as possible. It aims
  8. to collect more or less stable coverage that is a function of syscall inputs.
  9. To achieve this goal, it does not collect coverage in soft/hard interrupts
  10. (unless remove coverage collection is enabled, see below) and from some
  11. inherently non-deterministic parts of the kernel (e.g. scheduler, locking).
  12. Besides collecting code coverage, KCOV can also collect comparison operands.
  13. See the "Comparison operands collection" section for details.
  14. Besides collecting coverage data from syscall handlers, KCOV can also collect
  15. coverage for annotated parts of the kernel executing in background kernel
  16. tasks or soft interrupts. See the "Remote coverage collection" section for
  17. details.
  18. Prerequisites
  19. -------------
  20. KCOV relies on compiler instrumentation and requires GCC 6.1.0 or later
  21. or any Clang version supported by the kernel.
  22. Collecting comparison operands is supported with GCC 8+ or with Clang.
  23. To enable KCOV, configure the kernel with::
  24. CONFIG_KCOV=y
  25. To enable comparison operands collection, set::
  26. CONFIG_KCOV_ENABLE_COMPARISONS=y
  27. Coverage data only becomes accessible once debugfs has been mounted::
  28. mount -t debugfs none /sys/kernel/debug
  29. Coverage collection
  30. -------------------
  31. The following program demonstrates how to use KCOV to collect coverage for a
  32. single syscall from within a test program:
  33. .. code-block:: c
  34. #include <stdio.h>
  35. #include <stddef.h>
  36. #include <stdint.h>
  37. #include <stdlib.h>
  38. #include <sys/types.h>
  39. #include <sys/stat.h>
  40. #include <sys/ioctl.h>
  41. #include <sys/mman.h>
  42. #include <unistd.h>
  43. #include <fcntl.h>
  44. #include <linux/types.h>
  45. #define KCOV_INIT_TRACE _IOR('c', 1, unsigned long)
  46. #define KCOV_ENABLE _IO('c', 100)
  47. #define KCOV_DISABLE _IO('c', 101)
  48. #define COVER_SIZE (64<<10)
  49. #define KCOV_TRACE_PC 0
  50. #define KCOV_TRACE_CMP 1
  51. int main(int argc, char **argv)
  52. {
  53. int fd;
  54. unsigned long *cover, n, i;
  55. /* A single fd descriptor allows coverage collection on a single
  56. * thread.
  57. */
  58. fd = open("/sys/kernel/debug/kcov", O_RDWR);
  59. if (fd == -1)
  60. perror("open"), exit(1);
  61. /* Setup trace mode and trace size. */
  62. if (ioctl(fd, KCOV_INIT_TRACE, COVER_SIZE))
  63. perror("ioctl"), exit(1);
  64. /* Mmap buffer shared between kernel- and user-space. */
  65. cover = (unsigned long*)mmap(NULL, COVER_SIZE * sizeof(unsigned long),
  66. PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
  67. if ((void*)cover == MAP_FAILED)
  68. perror("mmap"), exit(1);
  69. /* Enable coverage collection on the current thread. */
  70. if (ioctl(fd, KCOV_ENABLE, KCOV_TRACE_PC))
  71. perror("ioctl"), exit(1);
  72. /* Reset coverage from the tail of the ioctl() call. */
  73. __atomic_store_n(&cover[0], 0, __ATOMIC_RELAXED);
  74. /* Call the target syscall call. */
  75. read(-1, NULL, 0);
  76. /* Read number of PCs collected. */
  77. n = __atomic_load_n(&cover[0], __ATOMIC_RELAXED);
  78. for (i = 0; i < n; i++)
  79. printf("0x%lx\n", cover[i + 1]);
  80. /* Disable coverage collection for the current thread. After this call
  81. * coverage can be enabled for a different thread.
  82. */
  83. if (ioctl(fd, KCOV_DISABLE, 0))
  84. perror("ioctl"), exit(1);
  85. /* Free resources. */
  86. if (munmap(cover, COVER_SIZE * sizeof(unsigned long)))
  87. perror("munmap"), exit(1);
  88. if (close(fd))
  89. perror("close"), exit(1);
  90. return 0;
  91. }
  92. After piping through ``addr2line`` the output of the program looks as follows::
  93. SyS_read
  94. fs/read_write.c:562
  95. __fdget_pos
  96. fs/file.c:774
  97. __fget_light
  98. fs/file.c:746
  99. __fget_light
  100. fs/file.c:750
  101. __fget_light
  102. fs/file.c:760
  103. __fdget_pos
  104. fs/file.c:784
  105. SyS_read
  106. fs/read_write.c:562
  107. If a program needs to collect coverage from several threads (independently),
  108. it needs to open ``/sys/kernel/debug/kcov`` in each thread separately.
  109. The interface is fine-grained to allow efficient forking of test processes.
  110. That is, a parent process opens ``/sys/kernel/debug/kcov``, enables trace mode,
  111. mmaps coverage buffer, and then forks child processes in a loop. The child
  112. processes only need to enable coverage (it gets disabled automatically when
  113. a thread exits).
  114. Comparison operands collection
  115. ------------------------------
  116. Comparison operands collection is similar to coverage collection:
  117. .. code-block:: c
  118. /* Same includes and defines as above. */
  119. /* Number of 64-bit words per record. */
  120. #define KCOV_WORDS_PER_CMP 4
  121. /*
  122. * The format for the types of collected comparisons.
  123. *
  124. * Bit 0 shows whether one of the arguments is a compile-time constant.
  125. * Bits 1 & 2 contain log2 of the argument size, up to 8 bytes.
  126. */
  127. #define KCOV_CMP_CONST (1 << 0)
  128. #define KCOV_CMP_SIZE(n) ((n) << 1)
  129. #define KCOV_CMP_MASK KCOV_CMP_SIZE(3)
  130. int main(int argc, char **argv)
  131. {
  132. int fd;
  133. uint64_t *cover, type, arg1, arg2, is_const, size;
  134. unsigned long n, i;
  135. fd = open("/sys/kernel/debug/kcov", O_RDWR);
  136. if (fd == -1)
  137. perror("open"), exit(1);
  138. if (ioctl(fd, KCOV_INIT_TRACE, COVER_SIZE))
  139. perror("ioctl"), exit(1);
  140. /*
  141. * Note that the buffer pointer is of type uint64_t*, because all
  142. * the comparison operands are promoted to uint64_t.
  143. */
  144. cover = (uint64_t *)mmap(NULL, COVER_SIZE * sizeof(unsigned long),
  145. PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
  146. if ((void*)cover == MAP_FAILED)
  147. perror("mmap"), exit(1);
  148. /* Note KCOV_TRACE_CMP instead of KCOV_TRACE_PC. */
  149. if (ioctl(fd, KCOV_ENABLE, KCOV_TRACE_CMP))
  150. perror("ioctl"), exit(1);
  151. __atomic_store_n(&cover[0], 0, __ATOMIC_RELAXED);
  152. read(-1, NULL, 0);
  153. /* Read number of comparisons collected. */
  154. n = __atomic_load_n(&cover[0], __ATOMIC_RELAXED);
  155. for (i = 0; i < n; i++) {
  156. uint64_t ip;
  157. type = cover[i * KCOV_WORDS_PER_CMP + 1];
  158. /* arg1 and arg2 - operands of the comparison. */
  159. arg1 = cover[i * KCOV_WORDS_PER_CMP + 2];
  160. arg2 = cover[i * KCOV_WORDS_PER_CMP + 3];
  161. /* ip - caller address. */
  162. ip = cover[i * KCOV_WORDS_PER_CMP + 4];
  163. /* size of the operands. */
  164. size = 1 << ((type & KCOV_CMP_MASK) >> 1);
  165. /* is_const - true if either operand is a compile-time constant.*/
  166. is_const = type & KCOV_CMP_CONST;
  167. printf("ip: 0x%lx type: 0x%lx, arg1: 0x%lx, arg2: 0x%lx, "
  168. "size: %lu, %s\n",
  169. ip, type, arg1, arg2, size,
  170. is_const ? "const" : "non-const");
  171. }
  172. if (ioctl(fd, KCOV_DISABLE, 0))
  173. perror("ioctl"), exit(1);
  174. /* Free resources. */
  175. if (munmap(cover, COVER_SIZE * sizeof(unsigned long)))
  176. perror("munmap"), exit(1);
  177. if (close(fd))
  178. perror("close"), exit(1);
  179. return 0;
  180. }
  181. Note that the KCOV modes (collection of code coverage or comparison operands)
  182. are mutually exclusive.
  183. Remote coverage collection
  184. --------------------------
  185. Besides collecting coverage data from handlers of syscalls issued from a
  186. userspace process, KCOV can also collect coverage for parts of the kernel
  187. executing in other contexts - so-called "remote" coverage.
  188. Using KCOV to collect remote coverage requires:
  189. 1. Modifying kernel code to annotate the code section from where coverage
  190. should be collected with ``kcov_remote_start`` and ``kcov_remote_stop``.
  191. 2. Using ``KCOV_REMOTE_ENABLE`` instead of ``KCOV_ENABLE`` in the userspace
  192. process that collects coverage.
  193. Both ``kcov_remote_start`` and ``kcov_remote_stop`` annotations and the
  194. ``KCOV_REMOTE_ENABLE`` ioctl accept handles that identify particular coverage
  195. collection sections. The way a handle is used depends on the context where the
  196. matching code section executes.
  197. KCOV supports collecting remote coverage from the following contexts:
  198. 1. Global kernel background tasks. These are the tasks that are spawned during
  199. kernel boot in a limited number of instances (e.g. one USB ``hub_event``
  200. worker is spawned per one USB HCD).
  201. 2. Local kernel background tasks. These are spawned when a userspace process
  202. interacts with some kernel interface and are usually killed when the process
  203. exits (e.g. vhost workers).
  204. 3. Soft interrupts.
  205. For #1 and #3, a unique global handle must be chosen and passed to the
  206. corresponding ``kcov_remote_start`` call. Then a userspace process must pass
  207. this handle to ``KCOV_REMOTE_ENABLE`` in the ``handles`` array field of the
  208. ``kcov_remote_arg`` struct. This will attach the used KCOV device to the code
  209. section referenced by this handle. Multiple global handles identifying
  210. different code sections can be passed at once.
  211. For #2, the userspace process instead must pass a non-zero handle through the
  212. ``common_handle`` field of the ``kcov_remote_arg`` struct. This common handle
  213. gets saved to the ``kcov_handle`` field in the current ``task_struct`` and
  214. needs to be passed to the newly spawned local tasks via custom kernel code
  215. modifications. Those tasks should in turn use the passed handle in their
  216. ``kcov_remote_start`` and ``kcov_remote_stop`` annotations.
  217. KCOV follows a predefined format for both global and common handles. Each
  218. handle is a ``u64`` integer. Currently, only the one top and the lower 4 bytes
  219. are used. Bytes 4-7 are reserved and must be zero.
  220. For global handles, the top byte of the handle denotes the id of a subsystem
  221. this handle belongs to. For example, KCOV uses ``1`` as the USB subsystem id.
  222. The lower 4 bytes of a global handle denote the id of a task instance within
  223. that subsystem. For example, each ``hub_event`` worker uses the USB bus number
  224. as the task instance id.
  225. For common handles, a reserved value ``0`` is used as a subsystem id, as such
  226. handles don't belong to a particular subsystem. The lower 4 bytes of a common
  227. handle identify a collective instance of all local tasks spawned by the
  228. userspace process that passed a common handle to ``KCOV_REMOTE_ENABLE``.
  229. In practice, any value can be used for common handle instance id if coverage
  230. is only collected from a single userspace process on the system. However, if
  231. common handles are used by multiple processes, unique instance ids must be
  232. used for each process. One option is to use the process id as the common
  233. handle instance id.
  234. The following program demonstrates using KCOV to collect coverage from both
  235. local tasks spawned by the process and the global task that handles USB bus #1:
  236. .. code-block:: c
  237. /* Same includes and defines as above. */
  238. struct kcov_remote_arg {
  239. __u32 trace_mode;
  240. __u32 area_size;
  241. __u32 num_handles;
  242. __aligned_u64 common_handle;
  243. __aligned_u64 handles[0];
  244. };
  245. #define KCOV_INIT_TRACE _IOR('c', 1, unsigned long)
  246. #define KCOV_DISABLE _IO('c', 101)
  247. #define KCOV_REMOTE_ENABLE _IOW('c', 102, struct kcov_remote_arg)
  248. #define COVER_SIZE (64 << 10)
  249. #define KCOV_TRACE_PC 0
  250. #define KCOV_SUBSYSTEM_COMMON (0x00ull << 56)
  251. #define KCOV_SUBSYSTEM_USB (0x01ull << 56)
  252. #define KCOV_SUBSYSTEM_MASK (0xffull << 56)
  253. #define KCOV_INSTANCE_MASK (0xffffffffull)
  254. static inline __u64 kcov_remote_handle(__u64 subsys, __u64 inst)
  255. {
  256. if (subsys & ~KCOV_SUBSYSTEM_MASK || inst & ~KCOV_INSTANCE_MASK)
  257. return 0;
  258. return subsys | inst;
  259. }
  260. #define KCOV_COMMON_ID 0x42
  261. #define KCOV_USB_BUS_NUM 1
  262. int main(int argc, char **argv)
  263. {
  264. int fd;
  265. unsigned long *cover, n, i;
  266. struct kcov_remote_arg *arg;
  267. fd = open("/sys/kernel/debug/kcov", O_RDWR);
  268. if (fd == -1)
  269. perror("open"), exit(1);
  270. if (ioctl(fd, KCOV_INIT_TRACE, COVER_SIZE))
  271. perror("ioctl"), exit(1);
  272. cover = (unsigned long*)mmap(NULL, COVER_SIZE * sizeof(unsigned long),
  273. PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
  274. if ((void*)cover == MAP_FAILED)
  275. perror("mmap"), exit(1);
  276. /* Enable coverage collection via common handle and from USB bus #1. */
  277. arg = calloc(1, sizeof(*arg) + sizeof(uint64_t));
  278. if (!arg)
  279. perror("calloc"), exit(1);
  280. arg->trace_mode = KCOV_TRACE_PC;
  281. arg->area_size = COVER_SIZE;
  282. arg->num_handles = 1;
  283. arg->common_handle = kcov_remote_handle(KCOV_SUBSYSTEM_COMMON,
  284. KCOV_COMMON_ID);
  285. arg->handles[0] = kcov_remote_handle(KCOV_SUBSYSTEM_USB,
  286. KCOV_USB_BUS_NUM);
  287. if (ioctl(fd, KCOV_REMOTE_ENABLE, arg))
  288. perror("ioctl"), free(arg), exit(1);
  289. free(arg);
  290. /*
  291. * Here the user needs to trigger execution of a kernel code section
  292. * that is either annotated with the common handle, or to trigger some
  293. * activity on USB bus #1.
  294. */
  295. sleep(2);
  296. n = __atomic_load_n(&cover[0], __ATOMIC_RELAXED);
  297. for (i = 0; i < n; i++)
  298. printf("0x%lx\n", cover[i + 1]);
  299. if (ioctl(fd, KCOV_DISABLE, 0))
  300. perror("ioctl"), exit(1);
  301. if (munmap(cover, COVER_SIZE * sizeof(unsigned long)))
  302. perror("munmap"), exit(1);
  303. if (close(fd))
  304. perror("close"), exit(1);
  305. return 0;
  306. }