alloc_cast.cocci 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /// Remove casting the values returned by memory allocation functions
  3. /// like kmalloc, kzalloc, kmem_cache_alloc, kmem_cache_zalloc etc.
  4. ///
  5. //# This makes an effort to find cases of casting of values returned by
  6. //# malloc, calloc, kmalloc, kmalloc_array, kmalloc_node and removes
  7. //# the casting as it is not required. The result in the patch case may
  8. //# need some reformatting.
  9. //
  10. // Confidence: High
  11. // Copyright: (C) 2014 Himangi Saraogi
  12. // Copyright: (C) 2017 Himanshu Jha
  13. // Comments:
  14. // Options: --no-includes --include-headers
  15. //
  16. virtual context
  17. virtual patch
  18. virtual org
  19. virtual report
  20. @initialize:python@
  21. @@
  22. import re
  23. pattern = '__'
  24. m = re.compile(pattern)
  25. @r1 depends on context || patch@
  26. type T;
  27. @@
  28. (T *)
  29. \(malloc\|calloc\|kmalloc\|kmalloc_array\|kmalloc_node\)(...)
  30. //----------------------------------------------------------
  31. // For context mode
  32. //----------------------------------------------------------
  33. @script:python depends on context@
  34. t << r1.T;
  35. @@
  36. if m.search(t) != None:
  37. cocci.include_match(False)
  38. @depends on context && r1@
  39. type r1.T;
  40. @@
  41. * (T *)
  42. \(malloc\|calloc\|kmalloc\|kmalloc_array\|kmalloc_node\)(...)
  43. //----------------------------------------------------------
  44. // For patch mode
  45. //----------------------------------------------------------
  46. @script:python depends on patch@
  47. t << r1.T;
  48. @@
  49. if m.search(t) != None:
  50. cocci.include_match(False)
  51. @depends on patch && r1@
  52. type r1.T;
  53. @@
  54. - (T *)
  55. \(malloc\|calloc\|kmalloc\|kmalloc_array\|kmalloc_node\)(...)
  56. //----------------------------------------------------------
  57. // For org and report mode
  58. //----------------------------------------------------------
  59. @r2 depends on org || report@
  60. type T;
  61. position p;
  62. @@
  63. (T@p *)
  64. \(malloc\|calloc\|kmalloc\|kmalloc_array\|kmalloc_node\)(...)
  65. @script:python depends on org@
  66. p << r2.p;
  67. t << r2.T;
  68. @@
  69. if m.search(t) != None:
  70. cocci.include_match(False)
  71. else:
  72. coccilib.org.print_safe_todo(p[0], t)
  73. @script:python depends on report@
  74. p << r2.p;
  75. t << r2.T;
  76. @@
  77. if m.search(t) != None:
  78. cocci.include_match(False)
  79. else:
  80. msg="WARNING: casting value returned by memory allocation function to (%s *) is useless." % (t)
  81. coccilib.report.print_report(p[0], msg)