check_cfc.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. #!/usr/bin/env python
  2. """Check CFC - Check Compile Flow Consistency
  3. This is a compiler wrapper for testing that code generation is consistent with
  4. different compilation processes. It checks that code is not unduly affected by
  5. compiler options or other changes which should not have side effects.
  6. To use:
  7. -Ensure that the compiler under test (i.e. clang, clang++) is on the PATH
  8. -On Linux copy this script to the name of the compiler
  9. e.g. cp check_cfc.py clang && cp check_cfc.py clang++
  10. -On Windows use setup.py to generate check_cfc.exe and copy that to clang.exe
  11. and clang++.exe
  12. -Enable the desired checks in check_cfc.cfg (in the same directory as the
  13. wrapper)
  14. e.g.
  15. [Checks]
  16. dash_g_no_change = true
  17. dash_s_no_change = false
  18. -The wrapper can be run using its absolute path or added to PATH before the
  19. compiler under test
  20. e.g. export PATH=<path to check_cfc>:$PATH
  21. -Compile as normal. The wrapper intercepts normal -c compiles and will return
  22. non-zero if the check fails.
  23. e.g.
  24. $ clang -c test.cpp
  25. Code difference detected with -g
  26. --- /tmp/tmp5nv893.o
  27. +++ /tmp/tmp6Vwjnc.o
  28. @@ -1 +1 @@
  29. - 0: 48 8b 05 51 0b 20 00 mov 0x200b51(%rip),%rax
  30. + 0: 48 39 3d 51 0b 20 00 cmp %rdi,0x200b51(%rip)
  31. -To run LNT with Check CFC specify the absolute path to the wrapper to the --cc
  32. and --cxx options
  33. e.g.
  34. lnt runtest nt --cc <path to check_cfc>/clang \\
  35. --cxx <path to check_cfc>/clang++ ...
  36. To add a new check:
  37. -Create a new subclass of WrapperCheck
  38. -Implement the perform_check() method. This should perform the alternate compile
  39. and do the comparison.
  40. -Add the new check to check_cfc.cfg. The check has the same name as the
  41. subclass.
  42. """
  43. from __future__ import absolute_import, division, print_function
  44. import imp
  45. import os
  46. import platform
  47. import shutil
  48. import subprocess
  49. import sys
  50. import tempfile
  51. try:
  52. import configparser
  53. except ImportError:
  54. import ConfigParser as configparser
  55. import io
  56. import obj_diff
  57. def is_windows():
  58. """Returns True if running on Windows."""
  59. return platform.system() == 'Windows'
  60. class WrapperStepException(Exception):
  61. """Exception type to be used when a step other than the original compile
  62. fails."""
  63. def __init__(self, msg, stdout, stderr):
  64. self.msg = msg
  65. self.stdout = stdout
  66. self.stderr = stderr
  67. class WrapperCheckException(Exception):
  68. """Exception type to be used when a comparison check fails."""
  69. def __init__(self, msg):
  70. self.msg = msg
  71. def main_is_frozen():
  72. """Returns True when running as a py2exe executable."""
  73. return (hasattr(sys, "frozen") or # new py2exe
  74. hasattr(sys, "importers") or # old py2exe
  75. imp.is_frozen("__main__")) # tools/freeze
  76. def get_main_dir():
  77. """Get the directory that the script or executable is located in."""
  78. if main_is_frozen():
  79. return os.path.dirname(sys.executable)
  80. return os.path.dirname(sys.argv[0])
  81. def remove_dir_from_path(path_var, directory):
  82. """Remove the specified directory from path_var, a string representing
  83. PATH"""
  84. pathlist = path_var.split(os.pathsep)
  85. norm_directory = os.path.normpath(os.path.normcase(directory))
  86. pathlist = [x for x in pathlist if os.path.normpath(
  87. os.path.normcase(x)) != norm_directory]
  88. return os.pathsep.join(pathlist)
  89. def path_without_wrapper():
  90. """Returns the PATH variable modified to remove the path to this program."""
  91. scriptdir = get_main_dir()
  92. path = os.environ['PATH']
  93. return remove_dir_from_path(path, scriptdir)
  94. def flip_dash_g(args):
  95. """Search for -g in args. If it exists then return args without. If not then
  96. add it."""
  97. if '-g' in args:
  98. # Return args without any -g
  99. return [x for x in args if x != '-g']
  100. else:
  101. # No -g, add one
  102. return args + ['-g']
  103. def derive_output_file(args):
  104. """Derive output file from the input file (if just one) or None
  105. otherwise."""
  106. infile = get_input_file(args)
  107. if infile is None:
  108. return None
  109. else:
  110. return '{}.o'.format(os.path.splitext(infile)[0])
  111. def get_output_file(args):
  112. """Return the output file specified by this command or None if not
  113. specified."""
  114. grabnext = False
  115. for arg in args:
  116. if grabnext:
  117. return arg
  118. if arg == '-o':
  119. # Specified as a separate arg
  120. grabnext = True
  121. elif arg.startswith('-o'):
  122. # Specified conjoined with -o
  123. return arg[2:]
  124. assert grabnext == False
  125. return None
  126. def is_output_specified(args):
  127. """Return true is output file is specified in args."""
  128. return get_output_file(args) is not None
  129. def replace_output_file(args, new_name):
  130. """Replaces the specified name of an output file with the specified name.
  131. Assumes that the output file name is specified in the command line args."""
  132. replaceidx = None
  133. attached = False
  134. for idx, val in enumerate(args):
  135. if val == '-o':
  136. replaceidx = idx + 1
  137. attached = False
  138. elif val.startswith('-o'):
  139. replaceidx = idx
  140. attached = True
  141. if replaceidx is None:
  142. raise Exception
  143. replacement = new_name
  144. if attached == True:
  145. replacement = '-o' + new_name
  146. args[replaceidx] = replacement
  147. return args
  148. def add_output_file(args, output_file):
  149. """Append an output file to args, presuming not already specified."""
  150. return args + ['-o', output_file]
  151. def set_output_file(args, output_file):
  152. """Set the output file within the arguments. Appends or replaces as
  153. appropriate."""
  154. if is_output_specified(args):
  155. args = replace_output_file(args, output_file)
  156. else:
  157. args = add_output_file(args, output_file)
  158. return args
  159. gSrcFileSuffixes = ('.c', '.cpp', '.cxx', '.c++', '.cp', '.cc')
  160. def get_input_file(args):
  161. """Return the input file string if it can be found (and there is only
  162. one)."""
  163. inputFiles = list()
  164. for arg in args:
  165. testarg = arg
  166. quotes = ('"', "'")
  167. while testarg.endswith(quotes):
  168. testarg = testarg[:-1]
  169. testarg = os.path.normcase(testarg)
  170. # Test if it is a source file
  171. if testarg.endswith(gSrcFileSuffixes):
  172. inputFiles.append(arg)
  173. if len(inputFiles) == 1:
  174. return inputFiles[0]
  175. else:
  176. return None
  177. def set_input_file(args, input_file):
  178. """Replaces the input file with that specified."""
  179. infile = get_input_file(args)
  180. if infile:
  181. infile_idx = args.index(infile)
  182. args[infile_idx] = input_file
  183. return args
  184. else:
  185. # Could not find input file
  186. assert False
  187. def is_normal_compile(args):
  188. """Check if this is a normal compile which will output an object file rather
  189. than a preprocess or link. args is a list of command line arguments."""
  190. compile_step = '-c' in args
  191. # Bitcode cannot be disassembled in the same way
  192. bitcode = '-flto' in args or '-emit-llvm' in args
  193. # Version and help are queries of the compiler and override -c if specified
  194. query = '--version' in args or '--help' in args
  195. # Options to output dependency files for make
  196. dependency = '-M' in args or '-MM' in args
  197. # Check if the input is recognised as a source file (this may be too
  198. # strong a restriction)
  199. input_is_valid = bool(get_input_file(args))
  200. return compile_step and not bitcode and not query and not dependency and input_is_valid
  201. def run_step(command, my_env, error_on_failure):
  202. """Runs a step of the compilation. Reports failure as exception."""
  203. # Need to use shell=True on Windows as Popen won't use PATH otherwise.
  204. p = subprocess.Popen(command, stdout=subprocess.PIPE,
  205. stderr=subprocess.PIPE, env=my_env, shell=is_windows())
  206. (stdout, stderr) = p.communicate()
  207. if p.returncode != 0:
  208. raise WrapperStepException(error_on_failure, stdout, stderr)
  209. def get_temp_file_name(suffix):
  210. """Get a temporary file name with a particular suffix. Let the caller be
  211. responsible for deleting it."""
  212. tf = tempfile.NamedTemporaryFile(suffix=suffix, delete=False)
  213. tf.close()
  214. return tf.name
  215. class WrapperCheck(object):
  216. """Base class for a check. Subclass this to add a check."""
  217. def __init__(self, output_file_a):
  218. """Record the base output file that will be compared against."""
  219. self._output_file_a = output_file_a
  220. def perform_check(self, arguments, my_env):
  221. """Override this to perform the modified compilation and required
  222. checks."""
  223. raise NotImplementedError("Please Implement this method")
  224. class dash_g_no_change(WrapperCheck):
  225. def perform_check(self, arguments, my_env):
  226. """Check if different code is generated with/without the -g flag."""
  227. output_file_b = get_temp_file_name('.o')
  228. alternate_command = list(arguments)
  229. alternate_command = flip_dash_g(alternate_command)
  230. alternate_command = set_output_file(alternate_command, output_file_b)
  231. run_step(alternate_command, my_env, "Error compiling with -g")
  232. # Compare disassembly (returns first diff if differs)
  233. difference = obj_diff.compare_object_files(self._output_file_a,
  234. output_file_b)
  235. if difference:
  236. raise WrapperCheckException(
  237. "Code difference detected with -g\n{}".format(difference))
  238. # Clean up temp file if comparison okay
  239. os.remove(output_file_b)
  240. class dash_s_no_change(WrapperCheck):
  241. def perform_check(self, arguments, my_env):
  242. """Check if compiling to asm then assembling in separate steps results
  243. in different code than compiling to object directly."""
  244. output_file_b = get_temp_file_name('.o')
  245. alternate_command = arguments + ['-via-file-asm']
  246. alternate_command = set_output_file(alternate_command, output_file_b)
  247. run_step(alternate_command, my_env,
  248. "Error compiling with -via-file-asm")
  249. # Compare if object files are exactly the same
  250. exactly_equal = obj_diff.compare_exact(self._output_file_a, output_file_b)
  251. if not exactly_equal:
  252. # Compare disassembly (returns first diff if differs)
  253. difference = obj_diff.compare_object_files(self._output_file_a,
  254. output_file_b)
  255. if difference:
  256. raise WrapperCheckException(
  257. "Code difference detected with -S\n{}".format(difference))
  258. # Code is identical, compare debug info
  259. dbgdifference = obj_diff.compare_debug_info(self._output_file_a,
  260. output_file_b)
  261. if dbgdifference:
  262. raise WrapperCheckException(
  263. "Debug info difference detected with -S\n{}".format(dbgdifference))
  264. raise WrapperCheckException("Object files not identical with -S\n")
  265. # Clean up temp file if comparison okay
  266. os.remove(output_file_b)
  267. if __name__ == '__main__':
  268. # Create configuration defaults from list of checks
  269. default_config = """
  270. [Checks]
  271. """
  272. # Find all subclasses of WrapperCheck
  273. checks = [cls.__name__ for cls in vars()['WrapperCheck'].__subclasses__()]
  274. for c in checks:
  275. default_config += "{} = false\n".format(c)
  276. config = configparser.RawConfigParser()
  277. config.readfp(io.BytesIO(default_config))
  278. scriptdir = get_main_dir()
  279. config_path = os.path.join(scriptdir, 'check_cfc.cfg')
  280. try:
  281. config.read(os.path.join(config_path))
  282. except:
  283. print("Could not read config from {}, "
  284. "using defaults.".format(config_path))
  285. my_env = os.environ.copy()
  286. my_env['PATH'] = path_without_wrapper()
  287. arguments_a = list(sys.argv)
  288. # Prevent infinite loop if called with absolute path.
  289. arguments_a[0] = os.path.basename(arguments_a[0])
  290. # Sanity check
  291. enabled_checks = [check_name
  292. for check_name in checks
  293. if config.getboolean('Checks', check_name)]
  294. checks_comma_separated = ', '.join(enabled_checks)
  295. print("Check CFC, checking: {}".format(checks_comma_separated))
  296. # A - original compilation
  297. output_file_orig = get_output_file(arguments_a)
  298. if output_file_orig is None:
  299. output_file_orig = derive_output_file(arguments_a)
  300. p = subprocess.Popen(arguments_a, env=my_env, shell=is_windows())
  301. p.communicate()
  302. if p.returncode != 0:
  303. sys.exit(p.returncode)
  304. if not is_normal_compile(arguments_a) or output_file_orig is None:
  305. # Bail out here if we can't apply checks in this case.
  306. # Does not indicate an error.
  307. # Maybe not straight compilation (e.g. -S or --version or -flto)
  308. # or maybe > 1 input files.
  309. sys.exit(0)
  310. # Sometimes we generate files which have very long names which can't be
  311. # read/disassembled. This will exit early if we can't find the file we
  312. # expected to be output.
  313. if not os.path.isfile(output_file_orig):
  314. sys.exit(0)
  315. # Copy output file to a temp file
  316. temp_output_file_orig = get_temp_file_name('.o')
  317. shutil.copyfile(output_file_orig, temp_output_file_orig)
  318. # Run checks, if they are enabled in config and if they are appropriate for
  319. # this command line.
  320. current_module = sys.modules[__name__]
  321. for check_name in checks:
  322. if config.getboolean('Checks', check_name):
  323. class_ = getattr(current_module, check_name)
  324. checker = class_(temp_output_file_orig)
  325. try:
  326. checker.perform_check(arguments_a, my_env)
  327. except WrapperCheckException as e:
  328. # Check failure
  329. print("{} {}".format(get_input_file(arguments_a), e.msg), file=sys.stderr)
  330. # Remove file to comply with build system expectations (no
  331. # output file if failed)
  332. os.remove(output_file_orig)
  333. sys.exit(1)
  334. except WrapperStepException as e:
  335. # Compile step failure
  336. print(e.msg, file=sys.stderr)
  337. print("*** stdout ***", file=sys.stderr)
  338. print(e.stdout, file=sys.stderr)
  339. print("*** stderr ***", file=sys.stderr)
  340. print(e.stderr, file=sys.stderr)
  341. # Remove file to comply with build system expectations (no
  342. # output file if failed)
  343. os.remove(output_file_orig)
  344. sys.exit(1)