Sparse


Sparse is a computer software tool designed to find possible coding faults in the Linux kernel. Unlike other such tools, this static analysis tool was initially designed to only flag constructs that were likely to be of interest to kernel developers, such as the mixing of pointers to user and kernel address spaces.
Sparse checks for known problems and allows the developer to include annotations in the code that convey information about data types, such as the address space that pointers point to and the locks that a function acquires or releases.
Linus Torvalds started writing Sparse in 2003. Josh Triplett was its maintainer from 2006, a role taken over by Christopher Li in 2009
and by Luc Van Oostenryck in November 2018.
Sparse is released under the MIT License.

Annotations

Some of the checks performed by Sparse require annotating the source code using the __attribute__ GCC extension, or the Sparse-specific __context__ specifier. Sparse defines the following list of attributes:
When an API is defined with a macro, the specifier __attribute__ can be replaced by __context__.

Linux kernel definitions

The Linux kernel defines the following short forms as pre-processor macros in files and :

  1. ifdef __CHECKER__
  2. define __user __attribute__
  3. define __kernel __attribute__
  4. define __safe __attribute__)
  5. define __force __attribute__)
  6. define __nocast __attribute__)
  7. define __iomem __attribute__
  8. define __must_hold __attribute__
  9. define __acquires __attribute__
  10. define __releases __attribute__
  11. define __acquire __context__
  12. define __release __context__
  13. define __cond_lock ? : 0)
  14. define __percpu __attribute__
  15. ifdef CONFIG_SPARSE_RCU_POINTER
  16. define __rcu __attribute__
  17. else
  18. define __rcu
  19. endif
extern void __chk_user_ptr;
extern void __chk_io_ptr;
  1. else
  2. define __user
  3. define __kernel
  4. define __safe
  5. define __force
  6. define __nocast
  7. define __iomem
  8. define __chk_user_ptr 0
  9. define __chk_io_ptr 0
  10. define __builtin_warning
  11. define __must_hold
  12. define __acquires
  13. define __releases
  14. define __acquire 0
  15. define __release 0
  16. define __cond_lock
  17. define __percpu
  18. define __rcu
  19. endif


  1. ifdef __CHECKER__
  2. define __bitwise __attribute__)
  3. else
  4. define __bitwise
  5. endif

Examples

The types __le32 and __be32 represent 32-bit integer types with different endianness. However, the C language does not allow to specify that variables of these types should not be mixed. The bitwise attribute is used to mark these types as restricted, so Sparse will give a warning if variables of these types or other integer variables are mixed:

typedef __u32 __bitwise __le32;
typedef __u32 __bitwise __be32;

To mark valid conversions between restricted types, a casting with the force attribute is used to avoid Sparse giving a warning.