array_size.cocci 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /// Use ARRAY_SIZE instead of dividing sizeof array with sizeof an element
  2. ///
  3. //# This makes an effort to find cases where ARRAY_SIZE can be used such as
  4. //# where there is a division of sizeof the array by the sizeof its first
  5. //# element or by any indexed element or the element type. It replaces the
  6. //# division of the two sizeofs by ARRAY_SIZE.
  7. //
  8. // Confidence: High
  9. // Copyright: (C) 2014 Himangi Saraogi. GPLv2.
  10. // Comments:
  11. // Options: --no-includes --include-headers
  12. virtual patch
  13. virtual context
  14. virtual org
  15. virtual report
  16. @i@
  17. @@
  18. #include <linux/kernel.h>
  19. //----------------------------------------------------------
  20. // For context mode
  21. //----------------------------------------------------------
  22. @depends on i&&context@
  23. type T;
  24. T[] E;
  25. @@
  26. (
  27. * (sizeof(E)/sizeof(*E))
  28. |
  29. * (sizeof(E)/sizeof(E[...]))
  30. |
  31. * (sizeof(E)/sizeof(T))
  32. )
  33. //----------------------------------------------------------
  34. // For patch mode
  35. //----------------------------------------------------------
  36. @depends on i&&patch@
  37. type T;
  38. T[] E;
  39. @@
  40. (
  41. - (sizeof(E)/sizeof(*E))
  42. + ARRAY_SIZE(E)
  43. |
  44. - (sizeof(E)/sizeof(E[...]))
  45. + ARRAY_SIZE(E)
  46. |
  47. - (sizeof(E)/sizeof(T))
  48. + ARRAY_SIZE(E)
  49. )
  50. //----------------------------------------------------------
  51. // For org and report mode
  52. //----------------------------------------------------------
  53. @r@
  54. type T;
  55. T[] E;
  56. position p;
  57. @@
  58. (
  59. (sizeof(E)@p /sizeof(*E))
  60. |
  61. (sizeof(E)@p /sizeof(E[...]))
  62. |
  63. (sizeof(E)@p /sizeof(T))
  64. )
  65. @script:python depends on i&&org@
  66. p << r.p;
  67. @@
  68. coccilib.org.print_todo(p[0], "WARNING should use ARRAY_SIZE")
  69. @script:python depends on i&&report@
  70. p << r.p;
  71. @@
  72. msg="WARNING: Use ARRAY_SIZE"
  73. coccilib.report.print_report(p[0], msg)