check_cfc.py 14 KB

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