check_public_headers.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. #!/usr/bin/env python
  2. #
  3. # Checks all public headers in IDF in the ci
  4. #
  5. # SPDX-FileCopyrightText: 2020-2021 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 = 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
  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
  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).*$'
  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 = 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. raise HeaderFailedBuildError()
  157. def preprocess_one_header(self, header, num, ignore_sdkconfig_issue=False):
  158. all_compilation_flags = ['-w', '-P', '-E', '-DESP_PLATFORM', '-include', header, self.main_c] + self.include_dir_flags
  159. if not ignore_sdkconfig_issue:
  160. # just strip commnets to check for CONFIG_... macros
  161. rc, out, err = exec_cmd([self.gcc, '-fpreprocessed', '-dD', '-P', '-E', header] + self.include_dir_flags)
  162. if re.search(self.kconfig_macro, out):
  163. # enable defined #error if sdkconfig.h not included
  164. all_compilation_flags.append('-DIDF_CHECK_SDKCONFIG_INCLUDED')
  165. try:
  166. # compile with C++, check for errors, outputs for a temp file
  167. rc, cpp_out, err, cpp_out_file = exec_cmd_to_temp_file([self.gpp, '--std=c++17'] + all_compilation_flags)
  168. if rc != 0:
  169. if re.search(self.error_macro, err):
  170. if re.search(self.error_orphan_kconfig, err):
  171. self.log('{}: CONFIG_VARS_USED_WHILE_SDKCONFIG_NOT_INCLUDED'.format(header), True)
  172. return self.COMPILE_ERR_REF_CONFIG_HDR_FAILED
  173. self.log('{}: Error directive failure: OK'.format(header))
  174. return self.COMPILE_ERR_ERROR_MACRO_HDR_OK
  175. self.log('{}: FAILED: compilation issue'.format(header), True)
  176. self.log(err, True)
  177. return self.COMPILE_ERR_HDR_FAILED
  178. # compile with C compiler, outputs to another temp file
  179. rc, c99_out, err, c99_out_file = exec_cmd_to_temp_file([self.gcc, '--std=c99'] + all_compilation_flags)
  180. if rc != 0:
  181. self.log('{} FAILED should never happen'.format(header))
  182. return self.COMPILE_ERR_HDR_FAILED
  183. # diff the two outputs
  184. rc, diff, err = exec_cmd(['diff', c99_out_file, cpp_out_file])
  185. if not diff or diff.isspace():
  186. if not cpp_out or cpp_out.isspace():
  187. self.log('{} The same, but empty out - OK'.format(header))
  188. return self.PREPROC_OUT_ZERO_HDR_OK
  189. self.log('{} FAILED C and C++ preprocessor output is the same!'.format(header), True)
  190. return self.PREPROC_OUT_SAME_HRD_FAILED
  191. if re.search(self.extern_c, diff):
  192. self.log('{} extern C present - OK'.format(header))
  193. return self.PREPROC_OUT_DIFFERENT_WITH_EXT_C_HDR_OK
  194. self.log('{} Different but no extern C - FAILED'.format(header), True)
  195. return self.PREPROC_OUT_DIFFERENT_NO_EXT_C_HDR_FAILED
  196. finally:
  197. os.unlink(cpp_out_file)
  198. try:
  199. os.unlink(c99_out_file)
  200. except Exception:
  201. pass
  202. # Get compilation data from an example to list all public header files
  203. def list_public_headers(self, ignore_dirs, ignore_files, only_dir=None):
  204. idf_path = os.getenv('IDF_PATH')
  205. project_dir = os.path.join(idf_path, 'examples', 'get-started', 'blink')
  206. subprocess.check_call(['idf.py', 'reconfigure'], cwd=project_dir)
  207. build_commands_json = os.path.join(project_dir, 'build', 'compile_commands.json')
  208. with open(build_commands_json, 'r', encoding='utf-8') as f:
  209. build_command = json.load(f)[0]['command'].split()
  210. include_dir_flags = []
  211. include_dirs = []
  212. # process compilation flags (includes and defines)
  213. for item in build_command:
  214. if item.startswith('-I'):
  215. include_dir_flags.append(item)
  216. if 'components' in item:
  217. include_dirs.append(item[2:]) # Removing the leading "-I"
  218. if item.startswith('-D'):
  219. include_dir_flags.append(item.replace('\\','')) # removes escaped quotes, eg: -DMBEDTLS_CONFIG_FILE=\\\"mbedtls/esp_config.h\\\"
  220. include_dir_flags.append('-I' + os.path.join(project_dir, 'build', 'config'))
  221. include_dir_flags.append('-DCI_HEADER_CHECK')
  222. sdkconfig_h = os.path.join(project_dir, 'build', 'config', 'sdkconfig.h')
  223. # prepares a main_c file for easier sdkconfig checks and avoid compilers warning when compiling headers directly
  224. with open(sdkconfig_h, 'a') as f:
  225. f.write('#define IDF_SDKCONFIG_INCLUDED')
  226. main_c = os.path.join(project_dir, 'build', 'compile.c')
  227. with open(main_c, 'w') as f:
  228. f.write('#if defined(IDF_CHECK_SDKCONFIG_INCLUDED) && ! defined(IDF_SDKCONFIG_INCLUDED)\n'
  229. '#error CONFIG_VARS_USED_WHILE_SDKCONFIG_NOT_INCLUDED\n'
  230. '#endif')
  231. # processes public include dirs, removing ignored files
  232. all_include_files = []
  233. files_to_check = []
  234. for d in include_dirs:
  235. if only_dir is not None and not os.path.relpath(d, idf_path).startswith(only_dir):
  236. self.log('{} - directory ignored (not in "{}")'.format(d, only_dir))
  237. continue
  238. if os.path.relpath(d, idf_path).startswith(tuple(ignore_dirs)):
  239. self.log('{} - directory ignored'.format(d))
  240. continue
  241. for root, dirnames, filenames in os.walk(d):
  242. for filename in fnmatch.filter(filenames, '*.h'):
  243. all_include_files.append(os.path.join(root, filename))
  244. self.main_c = main_c
  245. self.include_dir_flags = include_dir_flags
  246. ignore_files = set(ignore_files)
  247. # processes public include files, removing ignored files
  248. for f in all_include_files:
  249. rel_path_file = os.path.relpath(f, idf_path)
  250. if any([os.path.commonprefix([d, rel_path_file]) == d for d in ignore_dirs]):
  251. self.log('{} - file ignored (inside ignore dir)'.format(f))
  252. continue
  253. if rel_path_file in ignore_files:
  254. self.log('{} - file ignored'.format(f))
  255. continue
  256. files_to_check.append(f)
  257. # removes duplicates and places headers to a work queue
  258. for f in set(files_to_check):
  259. self.job_queue.put(f)
  260. self.job_queue.put(None) # to indicate the last job
  261. def check_all_headers():
  262. parser = argparse.ArgumentParser('Public header checker file')
  263. parser.add_argument('--verbose', '-v', help='enables verbose mode', action='store_true')
  264. parser.add_argument('--jobs', '-j', help='number of jobs to run checker', default=1, type=int)
  265. parser.add_argument('--prefix', '-p', help='compiler prefix', default='xtensa-esp32-elf-', type=str)
  266. parser.add_argument('--exclude-file', '-e', help='exception file', default='check_public_headers_exceptions.txt', type=str)
  267. parser.add_argument('--only-dir', '-d', help='reduce the analysis to this directory only', default=None, type=str)
  268. args = parser.parse_args()
  269. # process excluded files and dirs
  270. exclude_file = os.path.join(os.path.dirname(__file__), args.exclude_file)
  271. with open(exclude_file, 'r', encoding='utf-8') as f:
  272. lines = [line.rstrip() for line in f]
  273. ignore_files = []
  274. ignore_dirs = []
  275. for line in lines:
  276. if not line or line.isspace() or line.startswith('#'):
  277. continue
  278. if os.path.isdir(line):
  279. ignore_dirs.append(line)
  280. else:
  281. ignore_files.append(line)
  282. # start header check
  283. with PublicHeaderChecker(args.verbose, args.jobs, args.prefix) as header_check:
  284. header_check.list_public_headers(ignore_dirs, ignore_files, only_dir=args.only_dir)
  285. try:
  286. header_check.join()
  287. failures = header_check.get_failed()
  288. if len(failures) > 0:
  289. for failed in failures:
  290. print(failed)
  291. exit(1)
  292. print('No errors found')
  293. except KeyboardInterrupt:
  294. print('Keyboard interrupt')
  295. if __name__ == '__main__':
  296. check_all_headers()