check_public_headers.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. #!/usr/bin/env python
  2. #
  3. # Checks all public headers in IDF in the ci
  4. #
  5. # Copyright 2020 Espressif Systems (Shanghai) PTE LTD
  6. #
  7. # Licensed under the Apache License, Version 2.0 (the "License");
  8. # you may not use this file except in compliance with the License.
  9. # You may obtain a copy of the License at
  10. #
  11. # http://www.apache.org/licenses/LICENSE-2.0
  12. #
  13. # Unless required by applicable law or agreed to in writing, software
  14. # distributed under the License is distributed on an "AS IS" BASIS,
  15. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. # See the License for the specific language governing permissions and
  17. # limitations under the License.
  18. #
  19. from __future__ import print_function
  20. from __future__ import unicode_literals
  21. import re
  22. import os
  23. import subprocess
  24. import json
  25. import fnmatch
  26. import argparse
  27. import queue
  28. from threading import Thread, Event
  29. import tempfile
  30. class HeaderFailed(Exception):
  31. """Base header failure exeption"""
  32. pass
  33. class HeaderFailedSdkconfig(HeaderFailed):
  34. def __str__(self):
  35. return "Sdkconfig Error"
  36. class HeaderFailedBuildError(HeaderFailed):
  37. def __str__(self):
  38. return "Header Build Error"
  39. class HeaderFailedCppGuardMissing(HeaderFailed):
  40. def __str__(self):
  41. return "Header Missing C++ Guard"
  42. class HeaderFailedContainsCode(HeaderFailed):
  43. def __str__(self):
  44. return "Header Produced non-zero object"
  45. # Creates a temp file and returns both output as a string and a file name
  46. #
  47. def exec_cmd_to_temp_file(what, suffix=""):
  48. out_file = tempfile.NamedTemporaryFile(suffix=suffix, delete=False)
  49. rc, out, err = exec_cmd(what, out_file)
  50. with open(out_file.name, "r") as f:
  51. out = f.read()
  52. return rc, out, err, out_file.name
  53. def exec_cmd(what, out_file=subprocess.PIPE):
  54. p = subprocess.Popen(what, stdin=subprocess.PIPE, stdout=out_file, stderr=subprocess.PIPE)
  55. output, err = p.communicate()
  56. rc = p.returncode
  57. output = output.decode('utf-8') if output is not None else None
  58. err = err.decode('utf-8') if err is not None else None
  59. return rc, output, err
  60. class PublicHeaderChecker:
  61. # Intermediate results
  62. COMPILE_ERR_REF_CONFIG_HDR_FAILED = 1 # -> Cannot compile and failed with injected SDKCONFIG #error (header FAILs)
  63. COMPILE_ERR_ERROR_MACRO_HDR_OK = 2 # -> Cannot compile, but failed with "#error" directive (header seems OK)
  64. COMPILE_ERR_HDR_FAILED = 3 # -> Cannot compile with another issue, logged if verbose (header FAILs)
  65. PREPROC_OUT_ZERO_HDR_OK = 4 # -> Both preprocessors produce zero out (header file is OK)
  66. PREPROC_OUT_SAME_HRD_FAILED = 5 # -> Both preprocessors produce the same, non-zero output (header file FAILs)
  67. PREPROC_OUT_DIFFERENT_WITH_EXT_C_HDR_OK = 6 # -> Both preprocessors produce different, non-zero output with extern "C" (header seems OK)
  68. PREPROC_OUT_DIFFERENT_NO_EXT_C_HDR_FAILED = 7 # -> Both preprocessors produce different, non-zero output without extern "C" (header fails)
  69. def log(self, message):
  70. if self.verbose:
  71. print(message)
  72. def __init__(self, verbose=False, jobs=1, prefix=None):
  73. self.gcc = "{}gcc".format(prefix)
  74. self.gpp = "{}g++".format(prefix)
  75. self.verbose = verbose
  76. self.jobs = jobs
  77. self.prefix = prefix
  78. self.extern_c = re.compile(r'extern "C"')
  79. self.error_macro = re.compile(r'#error')
  80. self.error_orphan_kconfig = re.compile(r"#error CONFIG_VARS_USED_WHILE_SDKCONFIG_NOT_INCLUDED")
  81. self.kconfig_macro = re.compile(r'\bCONFIG_[A-Z0-9_]+')
  82. self.assembly_nocode = r'^\s*(\.file|\.text|\.ident).*$'
  83. self.check_threads = []
  84. self.job_queue = queue.Queue()
  85. self.failed_queue = queue.Queue()
  86. self.terminate = Event()
  87. def __enter__(self):
  88. for i in range(self.jobs):
  89. t = Thread(target=self.check_headers, args=(i, ))
  90. self.check_threads.append(t)
  91. t.start()
  92. return self
  93. def __exit__(self, exc_type, exc_value, traceback):
  94. self.terminate.set()
  95. for t in self.check_threads:
  96. t.join()
  97. # thread function process incoming header file from a queue
  98. def check_headers(self, num):
  99. while not self.terminate.is_set():
  100. if not self.job_queue.empty():
  101. task = self.job_queue.get()
  102. if task is None:
  103. self.terminate.set()
  104. else:
  105. try:
  106. self.check_one_header(task, num)
  107. except HeaderFailed as e:
  108. self.failed_queue.put("{}: Failed! {}".format(task, e))
  109. def get_failed(self):
  110. return list(self.failed_queue.queue)
  111. def join(self):
  112. for t in self.check_threads:
  113. while t.isAlive and not self.terminate.is_set():
  114. t.join(1) # joins with timeout to respond to keyboard interrupt
  115. # Checks one header calling:
  116. # - preprocess_one_header() to test and compare preprocessor outputs
  117. # - check_no_code() to test if header contains some executable code
  118. # Procedure
  119. # 1) Preprocess the include file with C preprocessor and with CPP preprocessor
  120. # - Pass the test if the preprocessor outputs are the same and whitespaces only (#define only header)
  121. # - Fail the test if the preprocessor outputs are the same (but with some code)
  122. # - If outputs different, continue with 2)
  123. # 2) Strip out all include directives to generate "temp.h"
  124. # 3) Preprocess the temp.h the same way in (1)
  125. # - Pass the test if the preprocessor outputs are the same and whitespaces only (#include only header)
  126. # - Fail the test if the preprocessor outputs are the same (but with some code)
  127. # - If outputs different, pass the test
  128. # 4) If header passed the steps 1) and 3) test that it produced zero assembly code
  129. def check_one_header(self, header, num):
  130. res = self.preprocess_one_header(header, num)
  131. if res == self.COMPILE_ERR_REF_CONFIG_HDR_FAILED:
  132. raise HeaderFailedSdkconfig()
  133. elif res == self.COMPILE_ERR_ERROR_MACRO_HDR_OK:
  134. return self.compile_one_header(header)
  135. elif res == self.COMPILE_ERR_HDR_FAILED:
  136. raise HeaderFailedBuildError()
  137. elif res == self.PREPROC_OUT_ZERO_HDR_OK:
  138. return self.compile_one_header(header)
  139. elif res == self.PREPROC_OUT_SAME_HRD_FAILED:
  140. raise HeaderFailedCppGuardMissing()
  141. else:
  142. self.compile_one_header(header)
  143. try:
  144. _, _, _, temp_header = exec_cmd_to_temp_file(["sed", "/#include/d; /#error/d", header], suffix=".h")
  145. res = self.preprocess_one_header(temp_header, num, ignore_sdkconfig_issue=True)
  146. if res == self.PREPROC_OUT_SAME_HRD_FAILED:
  147. raise HeaderFailedCppGuardMissing()
  148. elif res == self.PREPROC_OUT_DIFFERENT_NO_EXT_C_HDR_FAILED:
  149. raise HeaderFailedCppGuardMissing()
  150. finally:
  151. os.unlink(temp_header)
  152. def compile_one_header(self, header):
  153. rc, out, err = exec_cmd([self.gcc, "-S", "-o-", "-include", header, self.main_c] + self.include_dir_flags)
  154. if rc == 0:
  155. if not re.sub(self.assembly_nocode, '', out, flags=re.M).isspace():
  156. raise HeaderFailedContainsCode()
  157. return # Header OK: produced zero code
  158. raise HeaderFailedBuildError()
  159. def preprocess_one_header(self, header, num, ignore_sdkconfig_issue=False):
  160. all_compilation_flags = ["-w", "-P", "-E", "-include", header, self.main_c] + self.include_dir_flags
  161. if not ignore_sdkconfig_issue:
  162. # just strip commnets to check for CONFIG_... macros
  163. rc, out, err = exec_cmd([self.gcc, "-fpreprocessed", "-dD", "-P", "-E", header] + self.include_dir_flags)
  164. if re.search(self.kconfig_macro, out):
  165. # enable defined #error if sdkconfig.h not included
  166. all_compilation_flags.append("-DIDF_CHECK_SDKCONFIG_INCLUDED")
  167. try:
  168. # compile with C++, check for errors, outputs for a temp file
  169. rc, cpp_out, err, cpp_out_file = exec_cmd_to_temp_file([self.gpp, "--std=c++17"] + all_compilation_flags)
  170. if rc != 0:
  171. if re.search(self.error_macro, err):
  172. if re.search(self.error_orphan_kconfig, err):
  173. self.log("{}: CONFIG_VARS_USED_WHILE_SDKCONFIG_NOT_INCLUDED".format(header))
  174. return self.COMPILE_ERR_REF_CONFIG_HDR_FAILED
  175. self.log("{}: Error directive failure: OK".format(header))
  176. return self.COMPILE_ERR_ERROR_MACRO_HDR_OK
  177. self.log("{}: FAILED: compilation issue".format(header))
  178. self.log(err)
  179. return self.COMPILE_ERR_HDR_FAILED
  180. # compile with C compiler, outputs to another temp file
  181. rc, c99_out, 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 It is the same!".format(header))
  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))
  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):
  206. idf_path = os.getenv('IDF_PATH')
  207. project_dir = os.path.join(idf_path, "examples", "get-started", "blink")
  208. subprocess.check_call(["idf.py", "reconfigure"], cwd=project_dir)
  209. build_commands_json = os.path.join(project_dir, "build", "compile_commands.json")
  210. with open(build_commands_json, "r") as f:
  211. build_command = json.load(f)[0]["command"].split()
  212. include_dir_flags = []
  213. include_dirs = []
  214. # process compilation flags (includes and defines)
  215. for item in build_command:
  216. if item.startswith("-I"):
  217. include_dir_flags.append(item)
  218. if "components" in item:
  219. include_dirs.append(item[2:]) # Removing the leading "-I"
  220. if item.startswith("-D"):
  221. include_dir_flags.append(item.replace('\\','')) # removes escaped quotes, eg: -DMBEDTLS_CONFIG_FILE=\\\"mbedtls/esp_config.h\\\"
  222. include_dir_flags.append("-I" + os.path.join(project_dir, "build", "config"))
  223. sdkconfig_h = os.path.join(project_dir, "build", "config", "sdkconfig.h")
  224. # prepares a main_c file for easier sdkconfig checks and avoid compilers warning when compiling headers directly
  225. with open(sdkconfig_h, "a") as f:
  226. f.write("#define IDF_SDKCONFIG_INCLUDED")
  227. main_c = os.path.join(project_dir, "build", "compile.c")
  228. with open(main_c, "w") as f:
  229. f.write("#if defined(IDF_CHECK_SDKCONFIG_INCLUDED) && ! defined(IDF_SDKCONFIG_INCLUDED)\n"
  230. "#error CONFIG_VARS_USED_WHILE_SDKCONFIG_NOT_INCLUDED\n"
  231. "#endif")
  232. # processes public include dirs, removing ignored files
  233. all_include_files = []
  234. files_to_check = []
  235. for d in include_dirs:
  236. if os.path.relpath(d, idf_path).startswith(tuple(ignore_dirs)):
  237. self.log("{} - directory ignored".format(d))
  238. continue
  239. for root, dirnames, filenames in os.walk(d):
  240. for filename in fnmatch.filter(filenames, '*.h'):
  241. all_include_files.append(os.path.join(root, filename))
  242. self.main_c = main_c
  243. self.include_dir_flags = include_dir_flags
  244. ignore_files = set(ignore_files)
  245. # processes public include files, removing ignored files
  246. for f in all_include_files:
  247. rel_path_file = os.path.relpath(f, idf_path)
  248. if any([os.path.commonprefix([d, rel_path_file]) == d for d in ignore_dirs]):
  249. self.log("{} - file ignored (inside ignore dir)".format(f))
  250. continue
  251. if rel_path_file in ignore_files:
  252. self.log("{} - file ignored".format(f))
  253. continue
  254. files_to_check.append(f)
  255. # removes duplicates and places headers to a work queue
  256. for f in set(files_to_check):
  257. self.job_queue.put(f)
  258. self.job_queue.put(None) # to indicate the last job
  259. def check_all_headers():
  260. parser = argparse.ArgumentParser("Public header checker file")
  261. parser.add_argument("--verbose", "-v", help="enables verbose mode", action="store_true")
  262. parser.add_argument("--jobs", "-j", help="number of jobs to run checker", default=1, type=int)
  263. parser.add_argument("--prefix", "-p", help="compiler prefix", default="xtensa-esp32-elf-", type=str)
  264. parser.add_argument("--exclude-file", "-e", help="exception file", default="check_public_headers_exceptions.txt", type=str)
  265. args = parser.parse_args()
  266. # process excluded files and dirs
  267. exclude_file = os.path.join(os.path.dirname(__file__), args.exclude_file)
  268. with open(exclude_file, "r") as f:
  269. lines = [line.rstrip() for line in f]
  270. ignore_files = []
  271. ignore_dirs = []
  272. for line in lines:
  273. if not line or line.isspace() or line.startswith("#"):
  274. continue
  275. if os.path.isdir(line):
  276. ignore_dirs.append(line)
  277. else:
  278. ignore_files.append(line)
  279. # start header check
  280. with PublicHeaderChecker(args.verbose, args.jobs, args.prefix) as header_check:
  281. header_check.list_public_headers(ignore_dirs, ignore_files)
  282. try:
  283. header_check.join()
  284. failures = header_check.get_failed()
  285. if len(failures) > 0:
  286. for failed in failures:
  287. print(failed)
  288. exit(1)
  289. print("No errors found")
  290. except KeyboardInterrupt:
  291. print("Keyboard interrupt")
  292. if __name__ == '__main__':
  293. check_all_headers()