util.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. from __future__ import print_function
  2. import errno
  3. import itertools
  4. import math
  5. import numbers
  6. import os
  7. import platform
  8. import signal
  9. import subprocess
  10. import sys
  11. import threading
  12. def norm_path(path):
  13. path = os.path.realpath(path)
  14. path = os.path.normpath(path)
  15. path = os.path.normcase(path)
  16. return path
  17. def is_string(value):
  18. try:
  19. # Python 2 and Python 3 are different here.
  20. return isinstance(value, basestring)
  21. except NameError:
  22. return isinstance(value, str)
  23. def pythonize_bool(value):
  24. if value is None:
  25. return False
  26. if type(value) is bool:
  27. return value
  28. if isinstance(value, numbers.Number):
  29. return value != 0
  30. if is_string(value):
  31. if value.lower() in ('1', 'true', 'on', 'yes'):
  32. return True
  33. if value.lower() in ('', '0', 'false', 'off', 'no'):
  34. return False
  35. raise ValueError('"{}" is not a valid boolean'.format(value))
  36. def make_word_regex(word):
  37. return r'\b' + word + r'\b'
  38. def to_bytes(s):
  39. """Return the parameter as type 'bytes', possibly encoding it.
  40. In Python2, the 'bytes' type is the same as 'str'. In Python3, they
  41. are distinct.
  42. """
  43. if isinstance(s, bytes):
  44. # In Python2, this branch is taken for both 'str' and 'bytes'.
  45. # In Python3, this branch is taken only for 'bytes'.
  46. return s
  47. # In Python2, 's' is a 'unicode' object.
  48. # In Python3, 's' is a 'str' object.
  49. # Encode to UTF-8 to get 'bytes' data.
  50. return s.encode('utf-8')
  51. def to_string(b):
  52. """Return the parameter as type 'str', possibly encoding it.
  53. In Python2, the 'str' type is the same as 'bytes'. In Python3, the
  54. 'str' type is (essentially) Python2's 'unicode' type, and 'bytes' is
  55. distinct.
  56. """
  57. if isinstance(b, str):
  58. # In Python2, this branch is taken for types 'str' and 'bytes'.
  59. # In Python3, this branch is taken only for 'str'.
  60. return b
  61. if isinstance(b, bytes):
  62. # In Python2, this branch is never taken ('bytes' is handled as 'str').
  63. # In Python3, this is true only for 'bytes'.
  64. try:
  65. return b.decode('utf-8')
  66. except UnicodeDecodeError:
  67. # If the value is not valid Unicode, return the default
  68. # repr-line encoding.
  69. return str(b)
  70. # By this point, here's what we *don't* have:
  71. #
  72. # - In Python2:
  73. # - 'str' or 'bytes' (1st branch above)
  74. # - In Python3:
  75. # - 'str' (1st branch above)
  76. # - 'bytes' (2nd branch above)
  77. #
  78. # The last type we might expect is the Python2 'unicode' type. There is no
  79. # 'unicode' type in Python3 (all the Python3 cases were already handled). In
  80. # order to get a 'str' object, we need to encode the 'unicode' object.
  81. try:
  82. return b.encode('utf-8')
  83. except AttributeError:
  84. raise TypeError('not sure how to convert %s to %s' % (type(b), str))
  85. def detectCPUs():
  86. """Detects the number of CPUs on a system.
  87. Cribbed from pp.
  88. """
  89. # Linux, Unix and MacOS:
  90. if hasattr(os, 'sysconf'):
  91. if 'SC_NPROCESSORS_ONLN' in os.sysconf_names:
  92. # Linux & Unix:
  93. ncpus = os.sysconf('SC_NPROCESSORS_ONLN')
  94. if isinstance(ncpus, int) and ncpus > 0:
  95. return ncpus
  96. else: # OSX:
  97. return int(subprocess.check_output(['sysctl', '-n', 'hw.ncpu'],
  98. stderr=subprocess.STDOUT))
  99. # Windows:
  100. if 'NUMBER_OF_PROCESSORS' in os.environ:
  101. ncpus = int(os.environ['NUMBER_OF_PROCESSORS'])
  102. if ncpus > 0:
  103. # With more than 32 processes, process creation often fails with
  104. # "Too many open files". FIXME: Check if there's a better fix.
  105. return min(ncpus, 32)
  106. return 1 # Default
  107. def mkdir_p(path):
  108. """mkdir_p(path) - Make the "path" directory, if it does not exist; this
  109. will also make directories for any missing parent directories."""
  110. if not path or os.path.exists(path):
  111. return
  112. parent = os.path.dirname(path)
  113. if parent != path:
  114. mkdir_p(parent)
  115. try:
  116. os.mkdir(path)
  117. except OSError:
  118. e = sys.exc_info()[1]
  119. # Ignore EEXIST, which may occur during a race condition.
  120. if e.errno != errno.EEXIST:
  121. raise
  122. def listdir_files(dirname, suffixes=None, exclude_filenames=None):
  123. """Yields files in a directory.
  124. Filenames that are not excluded by rules below are yielded one at a time, as
  125. basenames (i.e., without dirname).
  126. Files starting with '.' are always skipped.
  127. If 'suffixes' is not None, then only filenames ending with one of its
  128. members will be yielded. These can be extensions, like '.exe', or strings,
  129. like 'Test'. (It is a lexicographic check; so an empty sequence will yield
  130. nothing, but a single empty string will yield all filenames.)
  131. If 'exclude_filenames' is not None, then none of the file basenames in it
  132. will be yielded.
  133. If specified, the containers for 'suffixes' and 'exclude_filenames' must
  134. support membership checking for strs.
  135. Args:
  136. dirname: a directory path.
  137. suffixes: (optional) a sequence of strings (set, list, etc.).
  138. exclude_filenames: (optional) a sequence of strings.
  139. Yields:
  140. Filenames as returned by os.listdir (generally, str).
  141. """
  142. if exclude_filenames is None:
  143. exclude_filenames = set()
  144. if suffixes is None:
  145. suffixes = {''}
  146. for filename in os.listdir(dirname):
  147. if (os.path.isdir(os.path.join(dirname, filename)) or
  148. filename.startswith('.') or
  149. filename in exclude_filenames or
  150. not any(filename.endswith(sfx) for sfx in suffixes)):
  151. continue
  152. yield filename
  153. def which(command, paths=None):
  154. """which(command, [paths]) - Look up the given command in the paths string
  155. (or the PATH environment variable, if unspecified)."""
  156. if paths is None:
  157. paths = os.environ.get('PATH', '')
  158. # Check for absolute match first.
  159. if os.path.isabs(command) and os.path.isfile(command):
  160. return os.path.normcase(os.path.normpath(command))
  161. # Would be nice if Python had a lib function for this.
  162. if not paths:
  163. paths = os.defpath
  164. # Get suffixes to search.
  165. # On Cygwin, 'PATHEXT' may exist but it should not be used.
  166. if os.pathsep == ';':
  167. pathext = os.environ.get('PATHEXT', '').split(';')
  168. else:
  169. pathext = ['']
  170. # Search the paths...
  171. for path in paths.split(os.pathsep):
  172. for ext in pathext:
  173. p = os.path.join(path, command + ext)
  174. if os.path.exists(p) and not os.path.isdir(p):
  175. return os.path.normcase(os.path.normpath(p))
  176. return None
  177. def checkToolsPath(dir, tools):
  178. for tool in tools:
  179. if not os.path.exists(os.path.join(dir, tool)):
  180. return False
  181. return True
  182. def whichTools(tools, paths):
  183. for path in paths.split(os.pathsep):
  184. if checkToolsPath(path, tools):
  185. return path
  186. return None
  187. def printHistogram(items, title='Items'):
  188. items.sort(key=lambda item: item[1])
  189. maxValue = max([v for _, v in items])
  190. # Select first "nice" bar height that produces more than 10 bars.
  191. power = int(math.ceil(math.log(maxValue, 10)))
  192. for inc in itertools.cycle((5, 2, 2.5, 1)):
  193. barH = inc * 10**power
  194. N = int(math.ceil(maxValue / barH))
  195. if N > 10:
  196. break
  197. elif inc == 1:
  198. power -= 1
  199. histo = [set() for i in range(N)]
  200. for name, v in items:
  201. bin = min(int(N * v / maxValue), N - 1)
  202. histo[bin].add(name)
  203. barW = 40
  204. hr = '-' * (barW + 34)
  205. print('\nSlowest %s:' % title)
  206. print(hr)
  207. for name, value in items[-20:]:
  208. print('%.2fs: %s' % (value, name))
  209. print('\n%s Times:' % title)
  210. print(hr)
  211. pDigits = int(math.ceil(math.log(maxValue, 10)))
  212. pfDigits = max(0, 3 - pDigits)
  213. if pfDigits:
  214. pDigits += pfDigits + 1
  215. cDigits = int(math.ceil(math.log(len(items), 10)))
  216. print('[%s] :: [%s] :: [%s]' % ('Range'.center((pDigits + 1) * 2 + 3),
  217. 'Percentage'.center(barW),
  218. 'Count'.center(cDigits * 2 + 1)))
  219. print(hr)
  220. for i, row in enumerate(histo):
  221. pct = float(len(row)) / len(items)
  222. w = int(barW * pct)
  223. print('[%*.*fs,%*.*fs) :: [%s%s] :: [%*d/%*d]' % (
  224. pDigits, pfDigits, i * barH, pDigits, pfDigits, (i + 1) * barH,
  225. '*' * w, ' ' * (barW - w), cDigits, len(row), cDigits, len(items)))
  226. class ExecuteCommandTimeoutException(Exception):
  227. def __init__(self, msg, out, err, exitCode):
  228. assert isinstance(msg, str)
  229. assert isinstance(out, str)
  230. assert isinstance(err, str)
  231. assert isinstance(exitCode, int)
  232. self.msg = msg
  233. self.out = out
  234. self.err = err
  235. self.exitCode = exitCode
  236. # Close extra file handles on UNIX (on Windows this cannot be done while
  237. # also redirecting input).
  238. kUseCloseFDs = not (platform.system() == 'Windows')
  239. def executeCommand(command, cwd=None, env=None, input=None, timeout=0):
  240. """Execute command ``command`` (list of arguments or string) with.
  241. * working directory ``cwd`` (str), use None to use the current
  242. working directory
  243. * environment ``env`` (dict), use None for none
  244. * Input to the command ``input`` (str), use string to pass
  245. no input.
  246. * Max execution time ``timeout`` (int) seconds. Use 0 for no timeout.
  247. Returns a tuple (out, err, exitCode) where
  248. * ``out`` (str) is the standard output of running the command
  249. * ``err`` (str) is the standard error of running the command
  250. * ``exitCode`` (int) is the exitCode of running the command
  251. If the timeout is hit an ``ExecuteCommandTimeoutException``
  252. is raised.
  253. """
  254. if input is not None:
  255. input = to_bytes(input)
  256. p = subprocess.Popen(command, cwd=cwd,
  257. stdin=subprocess.PIPE,
  258. stdout=subprocess.PIPE,
  259. stderr=subprocess.PIPE,
  260. env=env, close_fds=kUseCloseFDs)
  261. timerObject = None
  262. # FIXME: Because of the way nested function scopes work in Python 2.x we
  263. # need to use a reference to a mutable object rather than a plain
  264. # bool. In Python 3 we could use the "nonlocal" keyword but we need
  265. # to support Python 2 as well.
  266. hitTimeOut = [False]
  267. try:
  268. if timeout > 0:
  269. def killProcess():
  270. # We may be invoking a shell so we need to kill the
  271. # process and all its children.
  272. hitTimeOut[0] = True
  273. killProcessAndChildren(p.pid)
  274. timerObject = threading.Timer(timeout, killProcess)
  275. timerObject.start()
  276. out, err = p.communicate(input=input)
  277. exitCode = p.wait()
  278. finally:
  279. if timerObject != None:
  280. timerObject.cancel()
  281. # Ensure the resulting output is always of string type.
  282. out = to_string(out)
  283. err = to_string(err)
  284. if hitTimeOut[0]:
  285. raise ExecuteCommandTimeoutException(
  286. msg='Reached timeout of {} seconds'.format(timeout),
  287. out=out,
  288. err=err,
  289. exitCode=exitCode
  290. )
  291. # Detect Ctrl-C in subprocess.
  292. if exitCode == -signal.SIGINT:
  293. raise KeyboardInterrupt
  294. return out, err, exitCode
  295. def usePlatformSdkOnDarwin(config, lit_config):
  296. # On Darwin, support relocatable SDKs by providing Clang with a
  297. # default system root path.
  298. if 'darwin' in config.target_triple:
  299. try:
  300. cmd = subprocess.Popen(['xcrun', '--show-sdk-path', '--sdk', 'macosx'],
  301. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  302. out, err = cmd.communicate()
  303. out = out.strip()
  304. res = cmd.wait()
  305. except OSError:
  306. res = -1
  307. if res == 0 and out:
  308. sdk_path = out
  309. lit_config.note('using SDKROOT: %r' % sdk_path)
  310. config.environment['SDKROOT'] = sdk_path
  311. def findPlatformSdkVersionOnMacOS(config, lit_config):
  312. if 'darwin' in config.target_triple:
  313. try:
  314. cmd = subprocess.Popen(['xcrun', '--show-sdk-version', '--sdk', 'macosx'],
  315. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  316. out, err = cmd.communicate()
  317. out = out.strip()
  318. res = cmd.wait()
  319. except OSError:
  320. res = -1
  321. if res == 0 and out:
  322. return out
  323. return None
  324. def killProcessAndChildren(pid):
  325. """This function kills a process with ``pid`` and all its running children
  326. (recursively). It is currently implemented using the psutil module which
  327. provides a simple platform neutral implementation.
  328. TODO: Reimplement this without using psutil so we can remove
  329. our dependency on it.
  330. """
  331. import psutil
  332. try:
  333. psutilProc = psutil.Process(pid)
  334. # Handle the different psutil API versions
  335. try:
  336. # psutil >= 2.x
  337. children_iterator = psutilProc.children(recursive=True)
  338. except AttributeError:
  339. # psutil 1.x
  340. children_iterator = psutilProc.get_children(recursive=True)
  341. for child in children_iterator:
  342. try:
  343. child.kill()
  344. except psutil.NoSuchProcess:
  345. pass
  346. psutilProc.kill()
  347. except psutil.NoSuchProcess:
  348. pass
  349. try:
  350. import win32api
  351. except ImportError:
  352. win32api = None
  353. def abort_now():
  354. """Abort the current process without doing any exception teardown"""
  355. sys.stdout.flush()
  356. if win32api:
  357. win32api.TerminateProcess(win32api.GetCurrentProcess(), 3)
  358. else:
  359. os.kill(0, 9)