array_size.cocci 1.7 KB

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