1
0

check_stdlib_usage.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. #!/usr/bin/env python3
  2. #
  3. # Simple DirectMedia Layer
  4. # Copyright (C) 1997-2026 Sam Lantinga <slouken@libsdl.org>
  5. #
  6. # This software is provided 'as-is', without any express or implied
  7. # warranty. In no event will the authors be held liable for any damages
  8. # arising from the use of this software.
  9. #
  10. # Permission is granted to anyone to use this software for any purpose,
  11. # including commercial applications, and to alter it and redistribute it
  12. # freely, subject to the following restrictions:
  13. #
  14. # 1. The origin of this software must not be misrepresented; you must not
  15. # claim that you wrote the original software. If you use this software
  16. # in a product, an acknowledgment in the product documentation would be
  17. # appreciated but is not required.
  18. # 2. Altered source versions must be plainly marked as such, and must not be
  19. # misrepresented as being the original software.
  20. # 3. This notice may not be removed or altered from any source distribution.
  21. #
  22. # This script detects use of stdlib function in SDL code
  23. import argparse
  24. import os
  25. import pathlib
  26. import re
  27. import sys
  28. SDL_ROOT = pathlib.Path(__file__).resolve().parents[1]
  29. STDLIB_SYMBOLS = (
  30. 'abs',
  31. 'acos',
  32. 'acosf',
  33. 'asin',
  34. 'asinf',
  35. 'asprintf',
  36. 'atan',
  37. 'atan2',
  38. 'atan2f',
  39. 'atanf',
  40. 'atof',
  41. 'atoi',
  42. 'bsearch',
  43. 'calloc',
  44. 'ceil',
  45. 'ceilf',
  46. 'copysign',
  47. 'copysignf',
  48. 'cos',
  49. 'cosf',
  50. 'crc32',
  51. 'exp',
  52. 'expf',
  53. 'fabs',
  54. 'fabsf',
  55. 'floor',
  56. 'floorf',
  57. 'fmod',
  58. 'fmodf',
  59. 'free',
  60. 'getenv',
  61. 'isalnum',
  62. 'isalpha',
  63. 'isblank',
  64. 'iscntrl',
  65. 'isdigit',
  66. 'isgraph',
  67. 'islower',
  68. 'isprint',
  69. 'ispunct',
  70. 'isspace',
  71. 'isupper',
  72. 'isxdigit',
  73. 'itoa',
  74. 'lltoa',
  75. 'log10',
  76. 'log10f',
  77. 'logf',
  78. 'lround',
  79. 'lroundf',
  80. 'ltoa',
  81. 'malloc',
  82. 'memalign',
  83. 'memcmp',
  84. 'memcpy',
  85. 'memcpy4',
  86. 'memmove',
  87. 'memset',
  88. 'pow',
  89. 'powf',
  90. 'qsort',
  91. 'qsort_r',
  92. 'qsort_s',
  93. 'realloc',
  94. 'round',
  95. 'roundf',
  96. 'scalbn',
  97. 'scalbnf',
  98. 'setenv',
  99. 'sin',
  100. 'sinf',
  101. 'snprintf',
  102. 'sqrt',
  103. 'sqrtf',
  104. 'sscanf',
  105. 'strcasecmp',
  106. 'strchr',
  107. 'strcmp',
  108. 'strdup',
  109. 'strlcat',
  110. 'strlcpy',
  111. 'strlen',
  112. 'strlwr',
  113. 'strncasecmp',
  114. 'strncmp',
  115. 'strrchr',
  116. 'strrev',
  117. 'strstr',
  118. 'strtod',
  119. 'strtokr',
  120. 'strtol',
  121. 'strtoll',
  122. 'strtoul',
  123. 'strtoull',
  124. 'strupr',
  125. 'tan',
  126. 'tanf',
  127. 'tolower',
  128. 'toupper',
  129. 'trunc',
  130. 'truncf',
  131. 'uitoa',
  132. 'ulltoa',
  133. 'ultoa',
  134. 'utf8strlcpy',
  135. 'utf8strlen',
  136. 'vasprintf',
  137. 'vsnprintf',
  138. 'vsscanf',
  139. 'wcscasecmp',
  140. 'wcscmp',
  141. 'wcsdup',
  142. 'wcslcat',
  143. 'wcslcpy',
  144. 'wcslen',
  145. 'wcsncasecmp',
  146. 'wcsncmp',
  147. 'wcsstr',
  148. 'wcstol',
  149. 'wcstoll',
  150. 'wcstoul',
  151. 'wcstoull',
  152. )
  153. RE_STDLIB_SYMBOL = re.compile(rf"(?<!->)\b(?P<symbol>{'|'.join(STDLIB_SYMBOLS)})\b\(")
  154. def find_symbols_in_file(file: pathlib.Path) -> int:
  155. match_count = 0
  156. allowed_extensions = [ ".c", ".cpp", ".m", ".h", ".hpp", ".cc" ]
  157. excluded_paths = [
  158. "src/core/windows/gameinput/gameinput.cpp",
  159. "src/stdlib",
  160. "src/libm",
  161. "src/hidapi",
  162. "src/video/khronos",
  163. "src/video/miniz.h",
  164. "src/video/stb_image.h",
  165. "include/SDL3",
  166. "build-scripts/gen_audio_resampler_filter.c",
  167. "build-scripts/gen_audio_channel_conversion.c",
  168. "test/win32/sdlprocdump.c",
  169. ]
  170. filename = pathlib.Path(file)
  171. for ep in excluded_paths:
  172. if ep in filename.as_posix():
  173. # skip
  174. return 0
  175. if filename.suffix not in allowed_extensions:
  176. # skip
  177. return 0
  178. # print("Parse %s" % file)
  179. try:
  180. with file.open("r", encoding="UTF-8", newline="") as rfp:
  181. parsing_comment = False
  182. for line_i, original_line in enumerate(rfp, start=1):
  183. line = original_line.strip()
  184. line_comment = ""
  185. # Get the comment block /* ... */ across several lines
  186. while True:
  187. if parsing_comment:
  188. pos_end_comment = line.find("*/")
  189. if pos_end_comment >= 0:
  190. line = line[pos_end_comment+2:]
  191. parsing_comment = False
  192. else:
  193. break
  194. else:
  195. pos_start_comment = line.find("/*")
  196. if pos_start_comment >= 0:
  197. pos_end_comment = line.find("*/", pos_start_comment+2)
  198. if pos_end_comment >= 0:
  199. line_comment += line[pos_start_comment:pos_end_comment+2]
  200. line = line[:pos_start_comment] + line[pos_end_comment+2:]
  201. else:
  202. line_comment += line[pos_start_comment:]
  203. line = line[:pos_start_comment]
  204. parsing_comment = True
  205. break
  206. else:
  207. break
  208. if parsing_comment:
  209. continue
  210. pos_line_comment = line.find("//")
  211. if pos_line_comment >= 0:
  212. line_comment += line[pos_line_comment:]
  213. line = line[:pos_line_comment]
  214. if matches := tuple(RE_STDLIB_SYMBOL.finditer(line)):
  215. text_string = " or ".join(f"SDL_{m.group(1)}" for m in matches)
  216. first_quote = line.find("\"")
  217. last_quote = line.rfind("\"")
  218. first_occurrence = min(m.span()[0] for m in matches)
  219. last_occurrence = max(m.span()[1] for m in matches)
  220. if first_quote == -1 or not (first_quote < first_occurrence and last_quote > last_occurrence):
  221. override_string = f"This should NOT be {text_string}"
  222. if override_string not in line_comment:
  223. print(f"{filename}:{line_i}")
  224. print(f" {line}")
  225. print(f"")
  226. match_count += 1
  227. except UnicodeDecodeError:
  228. print(f"{file} is not text, skipping", file=sys.stderr)
  229. return match_count
  230. def find_symbols_in_dir(path: pathlib.Path) -> int:
  231. match_count = 0
  232. for entry in path.iterdir():
  233. if entry.is_dir():
  234. match_count += find_symbols_in_dir(entry)
  235. else:
  236. match_count += find_symbols_in_file(entry)
  237. return match_count
  238. def main():
  239. parser = argparse.ArgumentParser(fromfile_prefix_chars="@")
  240. parser.add_argument("paths", default=[SDL_ROOT / "src", SDL_ROOT / "test"], nargs="*", type=pathlib.Path, help="Paths to look for stdlib symbols")
  241. args = parser.parse_args()
  242. print(f"Looking for stdlib usage in {', '.join(str(p) for p in args.paths)}...")
  243. match_count = 0
  244. for path in args.paths:
  245. if path.is_file():
  246. match_count = find_symbols_in_file(path)
  247. else:
  248. match_count = find_symbols_in_dir(path)
  249. if match_count:
  250. print("If the stdlib usage is intentional, add a '// This should NOT be SDL_<symbol>()' line comment.")
  251. print("")
  252. print("NOT OK")
  253. else:
  254. print("OK")
  255. return 1 if match_count else 0
  256. if __name__ == "__main__":
  257. raise SystemExit(main())