kcov.rst 11 KB

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