jack2 codebase
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1054 lines
25KB

  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. # Thomas Nagy, 2005-2018 (ita)
  4. """
  5. Utilities and platform-specific fixes
  6. The portability fixes try to provide a consistent behavior of the Waf API
  7. through Python versions 2.5 to 3.X and across different platforms (win32, linux, etc)
  8. """
  9. from __future__ import with_statement
  10. import atexit, os, sys, errno, inspect, re, datetime, platform, base64, signal, functools, time, shlex
  11. try:
  12. import cPickle
  13. except ImportError:
  14. import pickle as cPickle
  15. # leave this
  16. if os.name == 'posix' and sys.version_info[0] < 3:
  17. try:
  18. import subprocess32 as subprocess
  19. except ImportError:
  20. import subprocess
  21. else:
  22. import subprocess
  23. try:
  24. TimeoutExpired = subprocess.TimeoutExpired
  25. except AttributeError:
  26. class TimeoutExpired(Exception):
  27. pass
  28. from collections import deque, defaultdict
  29. try:
  30. import _winreg as winreg
  31. except ImportError:
  32. try:
  33. import winreg
  34. except ImportError:
  35. winreg = None
  36. from waflib import Errors
  37. try:
  38. from hashlib import md5
  39. except ImportError:
  40. try:
  41. from hashlib import sha1 as md5
  42. except ImportError:
  43. # never fail to enable potential fixes from another module
  44. pass
  45. else:
  46. try:
  47. md5().digest()
  48. except ValueError:
  49. # Fips? #2213
  50. from hashlib import sha1 as md5
  51. try:
  52. import threading
  53. except ImportError:
  54. if not 'JOBS' in os.environ:
  55. # no threading :-(
  56. os.environ['JOBS'] = '1'
  57. class threading(object):
  58. """
  59. A fake threading class for platforms lacking the threading module.
  60. Use ``waf -j1`` on those platforms
  61. """
  62. pass
  63. class Lock(object):
  64. """Fake Lock class"""
  65. def acquire(self):
  66. pass
  67. def release(self):
  68. pass
  69. threading.Lock = threading.Thread = Lock
  70. SIG_NIL = 'SIG_NIL_SIG_NIL_'.encode()
  71. """Arbitrary null value for hashes. Modify this value according to the hash function in use"""
  72. O644 = 420
  73. """Constant representing the permissions for regular files (0644 raises a syntax error on python 3)"""
  74. O755 = 493
  75. """Constant representing the permissions for executable files (0755 raises a syntax error on python 3)"""
  76. rot_chr = ['\\', '|', '/', '-']
  77. "List of characters to use when displaying the throbber (progress bar)"
  78. rot_idx = 0
  79. "Index of the current throbber character (progress bar)"
  80. class ordered_iter_dict(dict):
  81. """Ordered dictionary that provides iteration from the most recently inserted keys first"""
  82. def __init__(self, *k, **kw):
  83. self.lst = deque()
  84. dict.__init__(self, *k, **kw)
  85. def clear(self):
  86. dict.clear(self)
  87. self.lst = deque()
  88. def __setitem__(self, key, value):
  89. if key in dict.keys(self):
  90. self.lst.remove(key)
  91. dict.__setitem__(self, key, value)
  92. self.lst.append(key)
  93. def __delitem__(self, key):
  94. dict.__delitem__(self, key)
  95. try:
  96. self.lst.remove(key)
  97. except ValueError:
  98. pass
  99. def __iter__(self):
  100. return reversed(self.lst)
  101. def keys(self):
  102. return reversed(self.lst)
  103. class lru_node(object):
  104. """
  105. Used by :py:class:`waflib.Utils.lru_cache`
  106. """
  107. __slots__ = ('next', 'prev', 'key', 'val')
  108. def __init__(self):
  109. self.next = self
  110. self.prev = self
  111. self.key = None
  112. self.val = None
  113. class lru_cache(object):
  114. """
  115. A simple least-recently used cache with lazy allocation
  116. """
  117. __slots__ = ('maxlen', 'table', 'head')
  118. def __init__(self, maxlen=100):
  119. self.maxlen = maxlen
  120. """
  121. Maximum amount of elements in the cache
  122. """
  123. self.table = {}
  124. """
  125. Mapping key-value
  126. """
  127. self.head = lru_node()
  128. self.head.next = self.head
  129. self.head.prev = self.head
  130. def __getitem__(self, key):
  131. node = self.table[key]
  132. # assert(key==node.key)
  133. if node is self.head:
  134. return node.val
  135. # detach the node found
  136. node.prev.next = node.next
  137. node.next.prev = node.prev
  138. # replace the head
  139. node.next = self.head.next
  140. node.prev = self.head
  141. self.head = node.next.prev = node.prev.next = node
  142. return node.val
  143. def __setitem__(self, key, val):
  144. if key in self.table:
  145. # update the value for an existing key
  146. node = self.table[key]
  147. node.val = val
  148. self.__getitem__(key)
  149. else:
  150. if len(self.table) < self.maxlen:
  151. # the very first item is unused until the maximum is reached
  152. node = lru_node()
  153. node.prev = self.head
  154. node.next = self.head.next
  155. node.prev.next = node.next.prev = node
  156. else:
  157. node = self.head = self.head.next
  158. try:
  159. # that's another key
  160. del self.table[node.key]
  161. except KeyError:
  162. pass
  163. node.key = key
  164. node.val = val
  165. self.table[key] = node
  166. class lazy_generator(object):
  167. def __init__(self, fun, params):
  168. self.fun = fun
  169. self.params = params
  170. def __iter__(self):
  171. return self
  172. def __next__(self):
  173. try:
  174. it = self.it
  175. except AttributeError:
  176. it = self.it = self.fun(*self.params)
  177. return next(it)
  178. next = __next__
  179. is_win32 = os.sep == '\\' or sys.platform == 'win32' or os.name == 'nt' # msys2
  180. """
  181. Whether this system is a Windows series
  182. """
  183. def readf(fname, m='r', encoding='latin-1'):
  184. """
  185. Reads an entire file into a string. See also :py:meth:`waflib.Node.Node.readf`::
  186. def build(ctx):
  187. from waflib import Utils
  188. txt = Utils.readf(self.path.find_node('wscript').abspath())
  189. txt = ctx.path.find_node('wscript').read()
  190. :type fname: string
  191. :param fname: Path to file
  192. :type m: string
  193. :param m: Open mode
  194. :type encoding: string
  195. :param encoding: encoding value, only used for python 3
  196. :rtype: string
  197. :return: Content of the file
  198. """
  199. if sys.hexversion > 0x3000000 and not 'b' in m:
  200. m += 'b'
  201. with open(fname, m) as f:
  202. txt = f.read()
  203. if encoding:
  204. txt = txt.decode(encoding)
  205. else:
  206. txt = txt.decode()
  207. else:
  208. with open(fname, m) as f:
  209. txt = f.read()
  210. return txt
  211. def writef(fname, data, m='w', encoding='latin-1'):
  212. """
  213. Writes an entire file from a string.
  214. See also :py:meth:`waflib.Node.Node.writef`::
  215. def build(ctx):
  216. from waflib import Utils
  217. txt = Utils.writef(self.path.make_node('i_like_kittens').abspath(), 'some data')
  218. self.path.make_node('i_like_kittens').write('some data')
  219. :type fname: string
  220. :param fname: Path to file
  221. :type data: string
  222. :param data: The contents to write to the file
  223. :type m: string
  224. :param m: Open mode
  225. :type encoding: string
  226. :param encoding: encoding value, only used for python 3
  227. """
  228. if sys.hexversion > 0x3000000 and not 'b' in m:
  229. data = data.encode(encoding)
  230. m += 'b'
  231. with open(fname, m) as f:
  232. f.write(data)
  233. def h_file(fname):
  234. """
  235. Computes a hash value for a file by using md5. Use the md5_tstamp
  236. extension to get faster build hashes if necessary.
  237. :type fname: string
  238. :param fname: path to the file to hash
  239. :return: hash of the file contents
  240. :rtype: string or bytes
  241. """
  242. m = md5()
  243. with open(fname, 'rb') as f:
  244. while fname:
  245. fname = f.read(200000)
  246. m.update(fname)
  247. return m.digest()
  248. def readf_win32(f, m='r', encoding='latin-1'):
  249. flags = os.O_NOINHERIT | os.O_RDONLY
  250. if 'b' in m:
  251. flags |= os.O_BINARY
  252. if '+' in m:
  253. flags |= os.O_RDWR
  254. try:
  255. fd = os.open(f, flags)
  256. except OSError:
  257. raise IOError('Cannot read from %r' % f)
  258. if sys.hexversion > 0x3000000 and not 'b' in m:
  259. m += 'b'
  260. with os.fdopen(fd, m) as f:
  261. txt = f.read()
  262. if encoding:
  263. txt = txt.decode(encoding)
  264. else:
  265. txt = txt.decode()
  266. else:
  267. with os.fdopen(fd, m) as f:
  268. txt = f.read()
  269. return txt
  270. def writef_win32(f, data, m='w', encoding='latin-1'):
  271. if sys.hexversion > 0x3000000 and not 'b' in m:
  272. data = data.encode(encoding)
  273. m += 'b'
  274. flags = os.O_CREAT | os.O_TRUNC | os.O_WRONLY | os.O_NOINHERIT
  275. if 'b' in m:
  276. flags |= os.O_BINARY
  277. if '+' in m:
  278. flags |= os.O_RDWR
  279. try:
  280. fd = os.open(f, flags)
  281. except OSError:
  282. raise OSError('Cannot write to %r' % f)
  283. with os.fdopen(fd, m) as f:
  284. f.write(data)
  285. def h_file_win32(fname):
  286. try:
  287. fd = os.open(fname, os.O_BINARY | os.O_RDONLY | os.O_NOINHERIT)
  288. except OSError:
  289. raise OSError('Cannot read from %r' % fname)
  290. m = md5()
  291. with os.fdopen(fd, 'rb') as f:
  292. while fname:
  293. fname = f.read(200000)
  294. m.update(fname)
  295. return m.digest()
  296. # always save these
  297. readf_unix = readf
  298. writef_unix = writef
  299. h_file_unix = h_file
  300. if hasattr(os, 'O_NOINHERIT') and sys.hexversion < 0x3040000:
  301. # replace the default functions
  302. readf = readf_win32
  303. writef = writef_win32
  304. h_file = h_file_win32
  305. try:
  306. x = ''.encode('hex')
  307. except LookupError:
  308. import binascii
  309. def to_hex(s):
  310. ret = binascii.hexlify(s)
  311. if not isinstance(ret, str):
  312. ret = ret.decode('utf-8')
  313. return ret
  314. else:
  315. def to_hex(s):
  316. return s.encode('hex')
  317. to_hex.__doc__ = """
  318. Return the hexadecimal representation of a string
  319. :param s: string to convert
  320. :type s: string
  321. """
  322. def listdir_win32(s):
  323. """
  324. Lists the contents of a folder in a portable manner.
  325. On Win32, returns the list of drive letters: ['C:', 'X:', 'Z:'] when an empty string is given.
  326. :type s: string
  327. :param s: a string, which can be empty on Windows
  328. """
  329. if not s:
  330. try:
  331. import ctypes
  332. except ImportError:
  333. # there is nothing much we can do
  334. return [x + ':\\' for x in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ']
  335. else:
  336. dlen = 4 # length of "?:\\x00"
  337. maxdrives = 26
  338. buf = ctypes.create_string_buffer(maxdrives * dlen)
  339. ndrives = ctypes.windll.kernel32.GetLogicalDriveStringsA(maxdrives*dlen, ctypes.byref(buf))
  340. return [ str(buf.raw[4*i:4*i+2].decode('ascii')) for i in range(int(ndrives/dlen)) ]
  341. if len(s) == 2 and s[1] == ":":
  342. s += os.sep
  343. if not os.path.isdir(s):
  344. e = OSError('%s is not a directory' % s)
  345. e.errno = errno.ENOENT
  346. raise e
  347. return os.listdir(s)
  348. listdir = os.listdir
  349. if is_win32:
  350. listdir = listdir_win32
  351. def num2ver(ver):
  352. """
  353. Converts a string, tuple or version number into an integer. The number is supposed to have at most 4 digits::
  354. from waflib.Utils import num2ver
  355. num2ver('1.3.2') == num2ver((1,3,2)) == num2ver((1,3,2,0))
  356. :type ver: string or tuple of numbers
  357. :param ver: a version number
  358. """
  359. if isinstance(ver, str):
  360. ver = tuple(ver.split('.'))
  361. if isinstance(ver, tuple):
  362. ret = 0
  363. for i in range(4):
  364. if i < len(ver):
  365. ret += 256**(3 - i) * int(ver[i])
  366. return ret
  367. return ver
  368. def to_list(val):
  369. """
  370. Converts a string argument to a list by splitting it by spaces.
  371. Returns the object if not a string::
  372. from waflib.Utils import to_list
  373. lst = to_list('a b c d')
  374. :param val: list of string or space-separated string
  375. :rtype: list
  376. :return: Argument converted to list
  377. """
  378. if isinstance(val, str):
  379. return val.split()
  380. else:
  381. return val
  382. def console_encoding():
  383. try:
  384. import ctypes
  385. except ImportError:
  386. pass
  387. else:
  388. try:
  389. codepage = ctypes.windll.kernel32.GetConsoleCP()
  390. except AttributeError:
  391. pass
  392. else:
  393. if codepage:
  394. if 65001 == codepage and sys.version_info < (3, 3):
  395. return 'utf-8'
  396. return 'cp%d' % codepage
  397. return sys.stdout.encoding or ('cp1252' if is_win32 else 'latin-1')
  398. def split_path_unix(path):
  399. return path.split('/')
  400. def split_path_cygwin(path):
  401. if path.startswith('//'):
  402. ret = path.split('/')[2:]
  403. ret[0] = '/' + ret[0]
  404. return ret
  405. return path.split('/')
  406. re_sp = re.compile('[/\\\\]+')
  407. def split_path_win32(path):
  408. if path.startswith('\\\\'):
  409. ret = re_sp.split(path)[1:]
  410. ret[0] = '\\\\' + ret[0]
  411. if ret[0] == '\\\\?':
  412. return ret[1:]
  413. return ret
  414. return re_sp.split(path)
  415. msysroot = None
  416. def split_path_msys(path):
  417. if path.startswith(('/', '\\')) and not path.startswith(('//', '\\\\')):
  418. # msys paths can be in the form /usr/bin
  419. global msysroot
  420. if not msysroot:
  421. # msys has python 2.7 or 3, so we can use this
  422. msysroot = subprocess.check_output(['cygpath', '-w', '/']).decode(sys.stdout.encoding or 'latin-1')
  423. msysroot = msysroot.strip()
  424. path = os.path.normpath(msysroot + os.sep + path)
  425. return split_path_win32(path)
  426. if sys.platform == 'cygwin':
  427. split_path = split_path_cygwin
  428. elif is_win32:
  429. # Consider this an MSYSTEM environment if $MSYSTEM is set and python
  430. # reports is executable from a unix like path on a windows host.
  431. if os.environ.get('MSYSTEM') and sys.executable.startswith('/'):
  432. split_path = split_path_msys
  433. else:
  434. split_path = split_path_win32
  435. else:
  436. split_path = split_path_unix
  437. split_path.__doc__ = """
  438. Splits a path by / or \\; do not confuse this function with with ``os.path.split``
  439. :type path: string
  440. :param path: path to split
  441. :return: list of string
  442. """
  443. def check_dir(path):
  444. """
  445. Ensures that a directory exists (similar to ``mkdir -p``).
  446. :type path: string
  447. :param path: Path to directory
  448. :raises: :py:class:`waflib.Errors.WafError` if the folder cannot be added.
  449. """
  450. if not os.path.isdir(path):
  451. try:
  452. os.makedirs(path)
  453. except OSError as e:
  454. if not os.path.isdir(path):
  455. raise Errors.WafError('Cannot create the folder %r' % path, ex=e)
  456. def check_exe(name, env=None):
  457. """
  458. Ensures that a program exists
  459. :type name: string
  460. :param name: path to the program
  461. :param env: configuration object
  462. :type env: :py:class:`waflib.ConfigSet.ConfigSet`
  463. :return: path of the program or None
  464. :raises: :py:class:`waflib.Errors.WafError` if the folder cannot be added.
  465. """
  466. if not name:
  467. raise ValueError('Cannot execute an empty string!')
  468. def is_exe(fpath):
  469. return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
  470. fpath, fname = os.path.split(name)
  471. if fpath and is_exe(name):
  472. return os.path.abspath(name)
  473. else:
  474. env = env or os.environ
  475. for path in env['PATH'].split(os.pathsep):
  476. path = path.strip('"')
  477. exe_file = os.path.join(path, name)
  478. if is_exe(exe_file):
  479. return os.path.abspath(exe_file)
  480. return None
  481. def def_attrs(cls, **kw):
  482. """
  483. Sets default attributes on a class instance
  484. :type cls: class
  485. :param cls: the class to update the given attributes in.
  486. :type kw: dict
  487. :param kw: dictionary of attributes names and values.
  488. """
  489. for k, v in kw.items():
  490. if not hasattr(cls, k):
  491. setattr(cls, k, v)
  492. def quote_define_name(s):
  493. """
  494. Converts a string into an identifier suitable for C defines.
  495. :type s: string
  496. :param s: String to convert
  497. :rtype: string
  498. :return: Identifier suitable for C defines
  499. """
  500. fu = re.sub('[^a-zA-Z0-9]', '_', s)
  501. fu = re.sub('_+', '_', fu)
  502. fu = fu.upper()
  503. return fu
  504. # shlex.quote didn't exist until python 3.3. Prior to that it was a non-documented
  505. # function in pipes.
  506. try:
  507. shell_quote = shlex.quote
  508. except AttributeError:
  509. import pipes
  510. shell_quote = pipes.quote
  511. def shell_escape(cmd):
  512. """
  513. Escapes a command:
  514. ['ls', '-l', 'arg space'] -> ls -l 'arg space'
  515. """
  516. if isinstance(cmd, str):
  517. return cmd
  518. return ' '.join(shell_quote(x) for x in cmd)
  519. def h_list(lst):
  520. """
  521. Hashes lists of ordered data.
  522. Using hash(tup) for tuples would be much more efficient,
  523. but Python now enforces hash randomization
  524. :param lst: list to hash
  525. :type lst: list of strings
  526. :return: hash of the list
  527. """
  528. return md5(repr(lst).encode()).digest()
  529. if sys.hexversion < 0x3000000:
  530. def h_list_python2(lst):
  531. return md5(repr(lst)).digest()
  532. h_list_python2.__doc__ = h_list.__doc__
  533. h_list = h_list_python2
  534. def h_fun(fun):
  535. """
  536. Hash functions
  537. :param fun: function to hash
  538. :type fun: function
  539. :return: hash of the function
  540. :rtype: string or bytes
  541. """
  542. try:
  543. return fun.code
  544. except AttributeError:
  545. if isinstance(fun, functools.partial):
  546. code = list(fun.args)
  547. # The method items() provides a sequence of tuples where the first element
  548. # represents an optional argument of the partial function application
  549. #
  550. # The sorting result outcome will be consistent because:
  551. # 1. tuples are compared in order of their elements
  552. # 2. optional argument namess are unique
  553. code.extend(sorted(fun.keywords.items()))
  554. code.append(h_fun(fun.func))
  555. fun.code = h_list(code)
  556. return fun.code
  557. try:
  558. h = inspect.getsource(fun)
  559. except EnvironmentError:
  560. h = 'nocode'
  561. try:
  562. fun.code = h
  563. except AttributeError:
  564. pass
  565. return h
  566. def h_cmd(ins):
  567. """
  568. Hashes objects recursively
  569. :param ins: input object
  570. :type ins: string or list or tuple or function
  571. :rtype: string or bytes
  572. """
  573. # this function is not meant to be particularly fast
  574. if isinstance(ins, str):
  575. # a command is either a string
  576. ret = ins
  577. elif isinstance(ins, list) or isinstance(ins, tuple):
  578. # or a list of functions/strings
  579. ret = str([h_cmd(x) for x in ins])
  580. else:
  581. # or just a python function
  582. ret = str(h_fun(ins))
  583. if sys.hexversion > 0x3000000:
  584. ret = ret.encode('latin-1', 'xmlcharrefreplace')
  585. return ret
  586. reg_subst = re.compile(r"(\\\\)|(\$\$)|\$\{([^}]+)\}")
  587. def subst_vars(expr, params):
  588. """
  589. Replaces ${VAR} with the value of VAR taken from a dict or a config set::
  590. from waflib import Utils
  591. s = Utils.subst_vars('${PREFIX}/bin', env)
  592. :type expr: string
  593. :param expr: String to perform substitution on
  594. :param params: Dictionary or config set to look up variable values.
  595. """
  596. def repl_var(m):
  597. if m.group(1):
  598. return '\\'
  599. if m.group(2):
  600. return '$'
  601. try:
  602. # ConfigSet instances may contain lists
  603. return params.get_flat(m.group(3))
  604. except AttributeError:
  605. return params[m.group(3)]
  606. # if you get a TypeError, it means that 'expr' is not a string...
  607. # Utils.subst_vars(None, env) will not work
  608. return reg_subst.sub(repl_var, expr)
  609. def destos_to_binfmt(key):
  610. """
  611. Returns the binary format based on the unversioned platform name,
  612. and defaults to ``elf`` if nothing is found.
  613. :param key: platform name
  614. :type key: string
  615. :return: string representing the binary format
  616. """
  617. if key == 'darwin':
  618. return 'mac-o'
  619. elif key in ('win32', 'cygwin', 'uwin', 'msys'):
  620. return 'pe'
  621. return 'elf'
  622. def unversioned_sys_platform():
  623. """
  624. Returns the unversioned platform name.
  625. Some Python platform names contain versions, that depend on
  626. the build environment, e.g. linux2, freebsd6, etc.
  627. This returns the name without the version number. Exceptions are
  628. os2 and win32, which are returned verbatim.
  629. :rtype: string
  630. :return: Unversioned platform name
  631. """
  632. s = sys.platform
  633. if s.startswith('java'):
  634. # The real OS is hidden under the JVM.
  635. from java.lang import System
  636. s = System.getProperty('os.name')
  637. # see http://lopica.sourceforge.net/os.html for a list of possible values
  638. if s == 'Mac OS X':
  639. return 'darwin'
  640. elif s.startswith('Windows '):
  641. return 'win32'
  642. elif s == 'OS/2':
  643. return 'os2'
  644. elif s == 'HP-UX':
  645. return 'hp-ux'
  646. elif s in ('SunOS', 'Solaris'):
  647. return 'sunos'
  648. else: s = s.lower()
  649. # powerpc == darwin for our purposes
  650. if s == 'powerpc':
  651. return 'darwin'
  652. if s == 'win32' or s == 'os2':
  653. return s
  654. if s == 'cli' and os.name == 'nt':
  655. # ironpython is only on windows as far as we know
  656. return 'win32'
  657. return re.split(r'\d+$', s)[0]
  658. def nada(*k, **kw):
  659. """
  660. Does nothing
  661. :return: None
  662. """
  663. pass
  664. class Timer(object):
  665. """
  666. Simple object for timing the execution of commands.
  667. Its string representation is the duration::
  668. from waflib.Utils import Timer
  669. timer = Timer()
  670. a_few_operations()
  671. s = str(timer)
  672. """
  673. def __init__(self):
  674. self.start_time = self.now()
  675. def __str__(self):
  676. delta = self.now() - self.start_time
  677. if not isinstance(delta, datetime.timedelta):
  678. delta = datetime.timedelta(seconds=delta)
  679. days = delta.days
  680. hours, rem = divmod(delta.seconds, 3600)
  681. minutes, seconds = divmod(rem, 60)
  682. seconds += delta.microseconds * 1e-6
  683. result = ''
  684. if days:
  685. result += '%dd' % days
  686. if days or hours:
  687. result += '%dh' % hours
  688. if days or hours or minutes:
  689. result += '%dm' % minutes
  690. return '%s%.3fs' % (result, seconds)
  691. def now(self):
  692. return datetime.datetime.utcnow()
  693. if hasattr(time, 'perf_counter'):
  694. def now(self):
  695. return time.perf_counter()
  696. def read_la_file(path):
  697. """
  698. Reads property files, used by msvc.py
  699. :param path: file to read
  700. :type path: string
  701. """
  702. sp = re.compile(r'^([^=]+)=\'(.*)\'$')
  703. dc = {}
  704. for line in readf(path).splitlines():
  705. try:
  706. _, left, right, _ = sp.split(line.strip())
  707. dc[left] = right
  708. except ValueError:
  709. pass
  710. return dc
  711. def run_once(fun):
  712. """
  713. Decorator: let a function cache its results, use like this::
  714. @run_once
  715. def foo(k):
  716. return 345*2343
  717. .. note:: in practice this can cause memory leaks, prefer a :py:class:`waflib.Utils.lru_cache`
  718. :param fun: function to execute
  719. :type fun: function
  720. :return: the return value of the function executed
  721. """
  722. cache = {}
  723. def wrap(*k):
  724. try:
  725. return cache[k]
  726. except KeyError:
  727. ret = fun(*k)
  728. cache[k] = ret
  729. return ret
  730. wrap.__cache__ = cache
  731. wrap.__name__ = fun.__name__
  732. return wrap
  733. def get_registry_app_path(key, filename):
  734. """
  735. Returns the value of a registry key for an executable
  736. :type key: string
  737. :type filename: list of string
  738. """
  739. if not winreg:
  740. return None
  741. try:
  742. result = winreg.QueryValue(key, "Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\%s.exe" % filename[0])
  743. except OSError:
  744. pass
  745. else:
  746. if os.path.isfile(result):
  747. return result
  748. def lib64():
  749. """
  750. Guess the default ``/usr/lib`` extension for 64-bit applications
  751. :return: '64' or ''
  752. :rtype: string
  753. """
  754. # default settings for /usr/lib
  755. if os.sep == '/':
  756. if platform.architecture()[0] == '64bit':
  757. if os.path.exists('/usr/lib64') and not os.path.exists('/usr/lib32'):
  758. return '64'
  759. return ''
  760. def loose_version(ver_str):
  761. # private for the time being!
  762. # see #2402
  763. lst = re.split(r'([.]|\\d+|[a-zA-Z])', ver_str)
  764. ver = []
  765. for i, val in enumerate(lst):
  766. try:
  767. ver.append(int(val))
  768. except ValueError:
  769. if val != '.':
  770. ver.append(val)
  771. return ver
  772. def sane_path(p):
  773. # private function for the time being!
  774. return os.path.abspath(os.path.expanduser(p))
  775. process_pool = []
  776. """
  777. List of processes started to execute sub-process commands
  778. """
  779. def get_process():
  780. """
  781. Returns a process object that can execute commands as sub-processes
  782. :rtype: subprocess.Popen
  783. """
  784. try:
  785. return process_pool.pop()
  786. except IndexError:
  787. filepath = os.path.dirname(os.path.abspath(__file__)) + os.sep + 'processor.py'
  788. cmd = [sys.executable, '-c', readf(filepath)]
  789. return subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, bufsize=0, close_fds=not is_win32)
  790. def run_prefork_process(cmd, kwargs, cargs):
  791. """
  792. Delegates process execution to a pre-forked process instance.
  793. """
  794. if not kwargs.get('env'):
  795. kwargs['env'] = dict(os.environ)
  796. try:
  797. obj = base64.b64encode(cPickle.dumps([cmd, kwargs, cargs]))
  798. except (TypeError, AttributeError):
  799. return run_regular_process(cmd, kwargs, cargs)
  800. proc = get_process()
  801. if not proc:
  802. return run_regular_process(cmd, kwargs, cargs)
  803. proc.stdin.write(obj)
  804. proc.stdin.write('\n'.encode())
  805. proc.stdin.flush()
  806. obj = proc.stdout.readline()
  807. if not obj:
  808. raise OSError('Preforked sub-process %r died' % proc.pid)
  809. process_pool.append(proc)
  810. lst = cPickle.loads(base64.b64decode(obj))
  811. # Jython wrapper failures (bash/execvp)
  812. assert len(lst) == 5
  813. ret, out, err, ex, trace = lst
  814. if ex:
  815. if ex == 'OSError':
  816. raise OSError(trace)
  817. elif ex == 'ValueError':
  818. raise ValueError(trace)
  819. elif ex == 'TimeoutExpired':
  820. exc = TimeoutExpired(cmd, timeout=cargs['timeout'], output=out)
  821. exc.stderr = err
  822. raise exc
  823. else:
  824. raise Exception(trace)
  825. return ret, out, err
  826. def lchown(path, user=-1, group=-1):
  827. """
  828. Change the owner/group of a path, raises an OSError if the
  829. ownership change fails.
  830. :param user: user to change
  831. :type user: int or str
  832. :param group: group to change
  833. :type group: int or str
  834. """
  835. if isinstance(user, str):
  836. import pwd
  837. entry = pwd.getpwnam(user)
  838. if not entry:
  839. raise OSError('Unknown user %r' % user)
  840. user = entry[2]
  841. if isinstance(group, str):
  842. import grp
  843. entry = grp.getgrnam(group)
  844. if not entry:
  845. raise OSError('Unknown group %r' % group)
  846. group = entry[2]
  847. return os.lchown(path, user, group)
  848. def run_regular_process(cmd, kwargs, cargs={}):
  849. """
  850. Executes a subprocess command by using subprocess.Popen
  851. """
  852. proc = subprocess.Popen(cmd, **kwargs)
  853. if kwargs.get('stdout') or kwargs.get('stderr'):
  854. try:
  855. out, err = proc.communicate(**cargs)
  856. except TimeoutExpired:
  857. if kwargs.get('start_new_session') and hasattr(os, 'killpg'):
  858. os.killpg(proc.pid, signal.SIGKILL)
  859. else:
  860. proc.kill()
  861. out, err = proc.communicate()
  862. exc = TimeoutExpired(proc.args, timeout=cargs['timeout'], output=out)
  863. exc.stderr = err
  864. raise exc
  865. status = proc.returncode
  866. else:
  867. out, err = (None, None)
  868. try:
  869. status = proc.wait(**cargs)
  870. except TimeoutExpired as e:
  871. if kwargs.get('start_new_session') and hasattr(os, 'killpg'):
  872. os.killpg(proc.pid, signal.SIGKILL)
  873. else:
  874. proc.kill()
  875. proc.wait()
  876. raise e
  877. return status, out, err
  878. def run_process(cmd, kwargs, cargs={}):
  879. """
  880. Executes a subprocess by using a pre-forked process when possible
  881. or falling back to subprocess.Popen. See :py:func:`waflib.Utils.run_prefork_process`
  882. and :py:func:`waflib.Utils.run_regular_process`
  883. """
  884. if kwargs.get('stdout') and kwargs.get('stderr'):
  885. return run_prefork_process(cmd, kwargs, cargs)
  886. else:
  887. return run_regular_process(cmd, kwargs, cargs)
  888. def alloc_process_pool(n, force=False):
  889. """
  890. Allocates an amount of processes to the default pool so its size is at least *n*.
  891. It is useful to call this function early so that the pre-forked
  892. processes use as little memory as possible.
  893. :param n: pool size
  894. :type n: integer
  895. :param force: if True then *n* more processes are added to the existing pool
  896. :type force: bool
  897. """
  898. # mandatory on python2, unnecessary on python >= 3.2
  899. global run_process, get_process, alloc_process_pool
  900. if not force:
  901. n = max(n - len(process_pool), 0)
  902. try:
  903. lst = [get_process() for x in range(n)]
  904. except OSError:
  905. run_process = run_regular_process
  906. get_process = alloc_process_pool = nada
  907. else:
  908. for x in lst:
  909. process_pool.append(x)
  910. def atexit_pool():
  911. for k in process_pool:
  912. try:
  913. os.kill(k.pid, 9)
  914. except OSError:
  915. pass
  916. else:
  917. k.wait()
  918. # see #1889
  919. if (sys.hexversion<0x207000f and not is_win32) or sys.hexversion>=0x306000f:
  920. atexit.register(atexit_pool)
  921. if os.environ.get('WAF_NO_PREFORK') or sys.platform == 'cli' or not sys.executable:
  922. run_process = run_regular_process
  923. get_process = alloc_process_pool = nada