check_public_headers.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. #!/usr/bin/env python
  2. #
  3. # Checks all public headers in IDF in the ci
  4. #
  5. # SPDX-FileCopyrightText: 2020-2022 Espressif Systems (Shanghai) CO LTD
  6. # SPDX-License-Identifier: Apache-2.0
  7. #
  8. from __future__ import print_function, unicode_literals
  9. import argparse
  10. import fnmatch
  11. import json
  12. import os
  13. import queue
  14. import re
  15. import subprocess
  16. import tempfile
  17. from io import open
  18. from threading import Event, Thread
  19. class HeaderFailed(Exception):
  20. """Base header failure exeption"""
  21. pass
  22. class HeaderFailedSdkconfig(HeaderFailed):
  23. def __str__(self):
  24. return 'Sdkconfig Error'
  25. class HeaderFailedBuildError(HeaderFailed):
  26. def __str__(self):
  27. return 'Header Build Error'
  28. class HeaderFailedCppGuardMissing(HeaderFailed):
  29. def __str__(self):
  30. return 'Header Missing C++ Guard'
  31. class HeaderFailedContainsCode(HeaderFailed):
  32. def __str__(self):
  33. return 'Header Produced non-zero object'
  34. # Creates a temp file and returns both output as a string and a file name
  35. #
  36. def exec_cmd_to_temp_file(what, suffix=''):
  37. out_file = tempfile.NamedTemporaryFile(suffix=suffix, delete=False)
  38. rc, out, err, cmd = exec_cmd(what, out_file)
  39. with open(out_file.name, 'r', encoding='utf-8') as f:
  40. out = f.read()
  41. return rc, out, err, out_file.name, cmd
  42. def exec_cmd(what, out_file=subprocess.PIPE):
  43. p = subprocess.Popen(what, stdin=subprocess.PIPE, stdout=out_file, stderr=subprocess.PIPE)
  44. output, err = p.communicate()
  45. rc = p.returncode
  46. output = output.decode('utf-8') if output is not None else None
  47. err = err.decode('utf-8') if err is not None else None
  48. return rc, output, err, ' '.join(what)
  49. class PublicHeaderChecker:
  50. # Intermediate results
  51. COMPILE_ERR_REF_CONFIG_HDR_FAILED = 1 # -> Cannot compile and failed with injected SDKCONFIG #error (header FAILs)
  52. COMPILE_ERR_ERROR_MACRO_HDR_OK = 2 # -> Cannot compile, but failed with "#error" directive (header seems OK)
  53. COMPILE_ERR_HDR_FAILED = 3 # -> Cannot compile with another issue, logged if verbose (header FAILs)
  54. PREPROC_OUT_ZERO_HDR_OK = 4 # -> Both preprocessors produce zero out (header file is OK)
  55. PREPROC_OUT_SAME_HRD_FAILED = 5 # -> Both preprocessors produce the same, non-zero output (header file FAILs)
  56. PREPROC_OUT_DIFFERENT_WITH_EXT_C_HDR_OK = 6 # -> Both preprocessors produce different, non-zero output with extern "C" (header seems OK)
  57. PREPROC_OUT_DIFFERENT_NO_EXT_C_HDR_FAILED = 7 # -> Both preprocessors produce different, non-zero output without extern "C" (header fails)
  58. def log(self, message, debug=False):
  59. if self.verbose or debug:
  60. print(message)
  61. def __init__(self, verbose=False, jobs=1, prefix=None):
  62. self.gcc = '{}gcc'.format(prefix)
  63. self.gpp = '{}g++'.format(prefix)
  64. self.verbose = verbose
  65. self.jobs = jobs
  66. self.prefix = prefix
  67. self.extern_c = re.compile(r'extern "C"')
  68. self.error_macro = re.compile(r'#error')
  69. self.error_orphan_kconfig = re.compile(r'#error CONFIG_VARS_USED_WHILE_SDKCONFIG_NOT_INCLUDED')
  70. self.kconfig_macro = re.compile(r'\bCONFIG_[A-Z0-9_]+')
  71. self.assembly_nocode = r'^\s*(\.file|\.text|\.ident|\.option|\.attribute).*$'
  72. self.check_threads = []
  73. self.job_queue = queue.Queue()
  74. self.failed_queue = queue.Queue()
  75. self.terminate = Event()
  76. def __enter__(self):
  77. for i in range(self.jobs):
  78. t = Thread(target=self.check_headers, args=(i, ))
  79. self.check_threads.append(t)
  80. t.start()
  81. return self
  82. def __exit__(self, exc_type, exc_value, traceback):
  83. self.terminate.set()
  84. for t in self.check_threads:
  85. t.join()
  86. # thread function process incoming header file from a queue
  87. def check_headers(self, num):
  88. while not self.terminate.is_set():
  89. if not self.job_queue.empty():
  90. task = self.job_queue.get()
  91. if task is None:
  92. self.terminate.set()
  93. else:
  94. try:
  95. self.check_one_header(task, num)
  96. except HeaderFailed as e:
  97. self.failed_queue.put('{}: Failed! {}'.format(task, e))
  98. except Exception as e:
  99. # Makes sure any unexpected exceptions causes the program to terminate
  100. self.failed_queue.put('{}: Failed! {}'.format(task, e))
  101. self.terminate.set()
  102. raise
  103. def get_failed(self):
  104. return list(self.failed_queue.queue)
  105. def join(self):
  106. for t in self.check_threads:
  107. while t.is_alive() and not self.terminate.is_set():
  108. t.join(1) # joins with timeout to respond to keyboard interrupt
  109. # Checks one header calling:
  110. # - preprocess_one_header() to test and compare preprocessor outputs
  111. # - check_no_code() to test if header contains some executable code
  112. # Procedure
  113. # 1) Preprocess the include file with C preprocessor and with CPP preprocessor
  114. # - Pass the test if the preprocessor outputs are the same and whitespaces only (#define only header)
  115. # - Fail the test if the preprocessor outputs are the same (but with some code)
  116. # - If outputs different, continue with 2)
  117. # 2) Strip out all include directives to generate "temp.h"
  118. # 3) Preprocess the temp.h the same way in (1)
  119. # - Pass the test if the preprocessor outputs are the same and whitespaces only (#include only header)
  120. # - Fail the test if the preprocessor outputs are the same (but with some code)
  121. # - If outputs different, pass the test
  122. # 4) If header passed the steps 1) and 3) test that it produced zero assembly code
  123. def check_one_header(self, header, num):
  124. res = self.preprocess_one_header(header, num)
  125. if res == self.COMPILE_ERR_REF_CONFIG_HDR_FAILED:
  126. raise HeaderFailedSdkconfig()
  127. elif res == self.COMPILE_ERR_ERROR_MACRO_HDR_OK:
  128. return self.compile_one_header(header)
  129. elif res == self.COMPILE_ERR_HDR_FAILED:
  130. raise HeaderFailedBuildError()
  131. elif res == self.PREPROC_OUT_ZERO_HDR_OK:
  132. return self.compile_one_header(header)
  133. elif res == self.PREPROC_OUT_SAME_HRD_FAILED:
  134. raise HeaderFailedCppGuardMissing()
  135. else:
  136. self.compile_one_header(header)
  137. temp_header = None
  138. try:
  139. _, _, _, temp_header, _ = exec_cmd_to_temp_file(['sed', '/#include/d; /#error/d', header], suffix='.h')
  140. res = self.preprocess_one_header(temp_header, num, ignore_sdkconfig_issue=True)
  141. if res == self.PREPROC_OUT_SAME_HRD_FAILED:
  142. raise HeaderFailedCppGuardMissing()
  143. elif res == self.PREPROC_OUT_DIFFERENT_NO_EXT_C_HDR_FAILED:
  144. raise HeaderFailedCppGuardMissing()
  145. finally:
  146. if temp_header:
  147. os.unlink(temp_header)
  148. def compile_one_header(self, header):
  149. rc, out, err, cmd = exec_cmd([self.gcc, '-S', '-o-', '-include', header, self.main_c] + self.include_dir_flags)
  150. if rc == 0:
  151. if not re.sub(self.assembly_nocode, '', out, flags=re.M).isspace():
  152. raise HeaderFailedContainsCode()
  153. return # Header OK: produced zero code
  154. self.log('{}: FAILED: compilation issue'.format(header), True)
  155. self.log(err, True)
  156. self.log('\nCompilation command failed:\n{}\n'.format(cmd), True)
  157. raise HeaderFailedBuildError()
  158. def preprocess_one_header(self, header, num, ignore_sdkconfig_issue=False):
  159. all_compilation_flags = ['-w', '-P', '-E', '-DESP_PLATFORM', '-include', header, self.main_c] + self.include_dir_flags
  160. if not ignore_sdkconfig_issue:
  161. # just strip commnets to check for CONFIG_... macros
  162. rc, out, err, _ = exec_cmd([self.gcc, '-fpreprocessed', '-dD', '-P', '-E', header] + self.include_dir_flags)
  163. if re.search(self.kconfig_macro, out):
  164. # enable defined #error if sdkconfig.h not included
  165. all_compilation_flags.append('-DIDF_CHECK_SDKCONFIG_INCLUDED')
  166. try:
  167. # compile with C++, check for errors, outputs for a temp file
  168. rc, cpp_out, err, cpp_out_file, cmd = exec_cmd_to_temp_file([self.gpp, '--std=c++17'] + all_compilation_flags)
  169. if rc != 0:
  170. if re.search(self.error_macro, err):
  171. if re.search(self.error_orphan_kconfig, err):
  172. self.log('{}: CONFIG_VARS_USED_WHILE_SDKCONFIG_NOT_INCLUDED'.format(header), True)
  173. return self.COMPILE_ERR_REF_CONFIG_HDR_FAILED
  174. self.log('{}: Error directive failure: OK'.format(header))
  175. return self.COMPILE_ERR_ERROR_MACRO_HDR_OK
  176. self.log('{}: FAILED: compilation issue'.format(header), True)
  177. self.log(err, True)
  178. self.log('\nCompilation command failed:\n{}\n'.format(cmd), True)
  179. return self.COMPILE_ERR_HDR_FAILED
  180. # compile with C compiler, outputs to another temp file
  181. rc, _, err, c99_out_file, _ = exec_cmd_to_temp_file([self.gcc, '--std=c99'] + all_compilation_flags)
  182. if rc != 0:
  183. self.log('{} FAILED should never happen'.format(header))
  184. return self.COMPILE_ERR_HDR_FAILED
  185. # diff the two outputs
  186. rc, diff, err, _ = exec_cmd(['diff', c99_out_file, cpp_out_file])
  187. if not diff or diff.isspace():
  188. if not cpp_out or cpp_out.isspace():
  189. self.log('{} The same, but empty out - OK'.format(header))
  190. return self.PREPROC_OUT_ZERO_HDR_OK
  191. self.log('{} FAILED C and C++ preprocessor output is the same!'.format(header), True)
  192. return self.PREPROC_OUT_SAME_HRD_FAILED
  193. if re.search(self.extern_c, diff):
  194. self.log('{} extern C present - OK'.format(header))
  195. return self.PREPROC_OUT_DIFFERENT_WITH_EXT_C_HDR_OK
  196. self.log('{} Different but no extern C - FAILED'.format(header), True)
  197. return self.PREPROC_OUT_DIFFERENT_NO_EXT_C_HDR_FAILED
  198. finally:
  199. os.unlink(cpp_out_file)
  200. try:
  201. os.unlink(c99_out_file)
  202. except Exception:
  203. pass
  204. # Get compilation data from an example to list all public header files
  205. def list_public_headers(self, ignore_dirs, ignore_files, only_dir=None):
  206. idf_path = os.getenv('IDF_PATH')
  207. project_dir = os.path.join(idf_path, 'examples', 'get-started', 'blink')
  208. build_dir = tempfile.mkdtemp()
  209. sdkconfig = os.path.join(build_dir, 'sdkconfig')
  210. try:
  211. os.unlink(os.path.join(project_dir, 'sdkconfig'))
  212. except FileNotFoundError:
  213. pass
  214. subprocess.check_call(['idf.py', '-B', build_dir, f'-DSDKCONFIG={sdkconfig}', 'reconfigure'], cwd=project_dir)
  215. build_commands_json = os.path.join(build_dir, 'compile_commands.json')
  216. with open(build_commands_json, 'r', encoding='utf-8') as f:
  217. build_command = json.load(f)[0]['command'].split()
  218. include_dir_flags = []
  219. include_dirs = []
  220. # process compilation flags (includes and defines)
  221. for item in build_command:
  222. if item.startswith('-I'):
  223. include_dir_flags.append(item)
  224. if 'components' in item:
  225. include_dirs.append(item[2:]) # Removing the leading "-I"
  226. if item.startswith('-D'):
  227. include_dir_flags.append(item.replace('\\','')) # removes escaped quotes, eg: -DMBEDTLS_CONFIG_FILE=\\\"mbedtls/esp_config.h\\\"
  228. include_dir_flags.append('-I' + os.path.join(build_dir, 'config'))
  229. include_dir_flags.append('-DCI_HEADER_CHECK')
  230. sdkconfig_h = os.path.join(build_dir, 'config', 'sdkconfig.h')
  231. # prepares a main_c file for easier sdkconfig checks and avoid compilers warning when compiling headers directly
  232. with open(sdkconfig_h, 'a') as f:
  233. f.write('#define IDF_SDKCONFIG_INCLUDED')
  234. main_c = os.path.join(build_dir, 'compile.c')
  235. with open(main_c, 'w') as f:
  236. f.write('#if defined(IDF_CHECK_SDKCONFIG_INCLUDED) && ! defined(IDF_SDKCONFIG_INCLUDED)\n'
  237. '#error CONFIG_VARS_USED_WHILE_SDKCONFIG_NOT_INCLUDED\n'
  238. '#endif')
  239. # processes public include dirs, removing ignored files
  240. all_include_files = []
  241. files_to_check = []
  242. for d in include_dirs:
  243. if only_dir is not None and not os.path.relpath(d, idf_path).startswith(only_dir):
  244. self.log('{} - directory ignored (not in "{}")'.format(d, only_dir))
  245. continue
  246. if os.path.relpath(d, idf_path).startswith(tuple(ignore_dirs)):
  247. self.log('{} - directory ignored'.format(d))
  248. continue
  249. for root, dirnames, filenames in os.walk(d):
  250. for filename in fnmatch.filter(filenames, '*.h'):
  251. all_include_files.append(os.path.join(root, filename))
  252. self.main_c = main_c
  253. self.include_dir_flags = include_dir_flags
  254. ignore_files = set(ignore_files)
  255. # processes public include files, removing ignored files
  256. for f in all_include_files:
  257. rel_path_file = os.path.relpath(f, idf_path)
  258. if any([os.path.commonprefix([d, rel_path_file]) == d for d in ignore_dirs]):
  259. self.log('{} - file ignored (inside ignore dir)'.format(f))
  260. continue
  261. if rel_path_file in ignore_files:
  262. self.log('{} - file ignored'.format(f))
  263. continue
  264. files_to_check.append(f)
  265. # removes duplicates and places headers to a work queue
  266. for f in set(files_to_check):
  267. self.job_queue.put(f)
  268. self.job_queue.put(None) # to indicate the last job
  269. def check_all_headers():
  270. parser = argparse.ArgumentParser('Public header checker file', formatter_class=argparse.RawDescriptionHelpFormatter, epilog='''\
  271. Tips for fixing failures reported by this script
  272. ------------------------------------------------
  273. This checker validates all public headers to detect these types of issues:
  274. 1) "Sdkconfig Error": Using SDK config macros without including "sdkconfig.h"
  275. * Check if the failing include file or any other included file uses "CONFIG_..." prefixed macros
  276. 2) "Header Build Error": Header itself is not compilable (missing includes, macros, types)
  277. * Check that all referenced macros, types are available (defined or included)
  278. * Check that all included header files are available (included in paths)
  279. * Check for possible compilation issues
  280. * Try to compile only the offending header file
  281. 3) "Header Missing C++ Guard": Preprocessing the header by C and C++ should produce different output
  282. * Check if the "#ifdef __cplusplus" header sentinels are present
  283. 4) "Header Produced non-zero object": Header contains some object, a definition
  284. * Check if no definition is present in the offending header file
  285. Notes:
  286. * The script validates *all* header files (recursively) in public folders for all components.
  287. * The script locates include paths from running a default build of "examples/get-started/blink'
  288. * The script does not support any other targets than esp32
  289. General tips:
  290. * Use "-d" argument to make the script check only the offending header file
  291. * Use "-v" argument to produce more verbose output
  292. * Copy, paste and execute the compilation commands to reproduce build errors (script prints out
  293. the entire compilation command line with absolute paths)
  294. ''')
  295. parser.add_argument('--verbose', '-v', help='enables verbose mode', action='store_true')
  296. parser.add_argument('--jobs', '-j', help='number of jobs to run checker', default=1, type=int)
  297. parser.add_argument('--prefix', '-p', help='compiler prefix', default='xtensa-esp32-elf-', type=str)
  298. parser.add_argument('--exclude-file', '-e', help='exception file', default='check_public_headers_exceptions.txt', type=str)
  299. parser.add_argument('--only-dir', '-d', help='reduce the analysis to this directory only', default=None, type=str)
  300. args = parser.parse_args()
  301. # process excluded files and dirs
  302. exclude_file = os.path.join(os.path.dirname(__file__), args.exclude_file)
  303. with open(exclude_file, 'r', encoding='utf-8') as f:
  304. lines = [line.rstrip() for line in f]
  305. ignore_files = []
  306. ignore_dirs = []
  307. for line in lines:
  308. if not line or line.isspace() or line.startswith('#'):
  309. continue
  310. if os.path.isdir(line):
  311. ignore_dirs.append(line)
  312. else:
  313. ignore_files.append(line)
  314. # start header check
  315. with PublicHeaderChecker(args.verbose, args.jobs, args.prefix) as header_check:
  316. header_check.list_public_headers(ignore_dirs, ignore_files, only_dir=args.only_dir)
  317. try:
  318. header_check.join()
  319. failures = header_check.get_failed()
  320. if len(failures) > 0:
  321. for failed in failures:
  322. print(failed)
  323. print(parser.epilog)
  324. exit(1)
  325. print('No errors found')
  326. except KeyboardInterrupt:
  327. print('Keyboard interrupt')
  328. if __name__ == '__main__':
  329. check_all_headers()