mesonlib.py 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  1. # Copyright 2012-2015 The Meson development team
  2. # Licensed under the Apache License, Version 2.0 (the "License");
  3. # you may not use this file except in compliance with the License.
  4. # You may obtain a copy of the License at
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. # Unless required by applicable law or agreed to in writing, software
  7. # distributed under the License is distributed on an "AS IS" BASIS,
  8. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. # See the License for the specific language governing permissions and
  10. # limitations under the License.
  11. """A library of random helper functionality."""
  12. import sys
  13. import stat
  14. import time
  15. import platform, subprocess, operator, os, shutil, re
  16. import collections
  17. from mesonbuild import mlog
  18. have_fcntl = False
  19. have_msvcrt = False
  20. # Used to report conflicts between meson_version and new features used
  21. target_version = ''
  22. try:
  23. import fcntl
  24. have_fcntl = True
  25. except Exception:
  26. pass
  27. try:
  28. import msvcrt
  29. have_msvcrt = True
  30. except Exception:
  31. pass
  32. from glob import glob
  33. if os.path.basename(sys.executable) == 'meson.exe':
  34. # In Windows and using the MSI installed executable.
  35. python_command = [sys.executable, 'runpython']
  36. else:
  37. python_command = [sys.executable]
  38. meson_command = None
  39. def is_ascii_string(astring):
  40. try:
  41. if isinstance(astring, str):
  42. astring.encode('ascii')
  43. if isinstance(astring, bytes):
  44. astring.decode('ascii')
  45. except UnicodeDecodeError:
  46. return False
  47. return True
  48. def check_direntry_issues(direntry_array):
  49. import locale
  50. # Warn if the locale is not UTF-8. This can cause various unfixable issues
  51. # such as os.stat not being able to decode filenames with unicode in them.
  52. # There is no way to reset both the preferred encoding and the filesystem
  53. # encoding, so we can just warn about it.
  54. e = locale.getpreferredencoding()
  55. if e.upper() != 'UTF-8' and not is_windows():
  56. if not isinstance(direntry_array, list):
  57. direntry_array = [direntry_array]
  58. for de in direntry_array:
  59. if is_ascii_string(de):
  60. continue
  61. mlog.warning('''You are using {!r} which is not a Unicode-compatible '
  62. locale but you are trying to access a file system entry called {!r} which is
  63. not pure ASCII. This may cause problems.
  64. '''.format(e, de), file=sys.stderr)
  65. # Put this in objects that should not get dumped to pickle files
  66. # by accident.
  67. import threading
  68. an_unpicklable_object = threading.Lock()
  69. class MesonException(Exception):
  70. '''Exceptions thrown by Meson'''
  71. class EnvironmentException(MesonException):
  72. '''Exceptions thrown while processing and creating the build environment'''
  73. class FileMode:
  74. # The first triad is for owner permissions, the second for group permissions,
  75. # and the third for others (everyone else).
  76. # For the 1st character:
  77. # 'r' means can read
  78. # '-' means not allowed
  79. # For the 2nd character:
  80. # 'w' means can write
  81. # '-' means not allowed
  82. # For the 3rd character:
  83. # 'x' means can execute
  84. # 's' means can execute and setuid/setgid is set (owner/group triads only)
  85. # 'S' means cannot execute and setuid/setgid is set (owner/group triads only)
  86. # 't' means can execute and sticky bit is set ("others" triads only)
  87. # 'T' means cannot execute and sticky bit is set ("others" triads only)
  88. # '-' means none of these are allowed
  89. #
  90. # The meanings of 'rwx' perms is not obvious for directories; see:
  91. # https://www.hackinglinuxexposed.com/articles/20030424.html
  92. #
  93. # For information on this notation such as setuid/setgid/sticky bits, see:
  94. # https://en.wikipedia.org/wiki/File_system_permissions#Symbolic_notation
  95. symbolic_perms_regex = re.compile('[r-][w-][xsS-]' # Owner perms
  96. '[r-][w-][xsS-]' # Group perms
  97. '[r-][w-][xtT-]') # Others perms
  98. def __init__(self, perms=None, owner=None, group=None):
  99. self.perms_s = perms
  100. self.perms = self.perms_s_to_bits(perms)
  101. self.owner = owner
  102. self.group = group
  103. def __repr__(self):
  104. ret = '<FileMode: {!r} owner={} group={}'
  105. return ret.format(self.perms_s, self.owner, self.group)
  106. @classmethod
  107. def perms_s_to_bits(cls, perms_s):
  108. '''
  109. Does the opposite of stat.filemode(), converts strings of the form
  110. 'rwxr-xr-x' to st_mode enums which can be passed to os.chmod()
  111. '''
  112. if perms_s is None:
  113. # No perms specified, we will not touch the permissions
  114. return -1
  115. eg = 'rwxr-xr-x'
  116. if not isinstance(perms_s, str):
  117. msg = 'Install perms must be a string. For example, {!r}'
  118. raise MesonException(msg.format(eg))
  119. if len(perms_s) != 9 or not cls.symbolic_perms_regex.match(perms_s):
  120. msg = 'File perms {!r} must be exactly 9 chars. For example, {!r}'
  121. raise MesonException(msg.format(perms_s, eg))
  122. perms = 0
  123. # Owner perms
  124. if perms_s[0] == 'r':
  125. perms |= stat.S_IRUSR
  126. if perms_s[1] == 'w':
  127. perms |= stat.S_IWUSR
  128. if perms_s[2] == 'x':
  129. perms |= stat.S_IXUSR
  130. elif perms_s[2] == 'S':
  131. perms |= stat.S_ISUID
  132. elif perms_s[2] == 's':
  133. perms |= stat.S_IXUSR
  134. perms |= stat.S_ISUID
  135. # Group perms
  136. if perms_s[3] == 'r':
  137. perms |= stat.S_IRGRP
  138. if perms_s[4] == 'w':
  139. perms |= stat.S_IWGRP
  140. if perms_s[5] == 'x':
  141. perms |= stat.S_IXGRP
  142. elif perms_s[5] == 'S':
  143. perms |= stat.S_ISGID
  144. elif perms_s[5] == 's':
  145. perms |= stat.S_IXGRP
  146. perms |= stat.S_ISGID
  147. # Others perms
  148. if perms_s[6] == 'r':
  149. perms |= stat.S_IROTH
  150. if perms_s[7] == 'w':
  151. perms |= stat.S_IWOTH
  152. if perms_s[8] == 'x':
  153. perms |= stat.S_IXOTH
  154. elif perms_s[8] == 'T':
  155. perms |= stat.S_ISVTX
  156. elif perms_s[8] == 't':
  157. perms |= stat.S_IXOTH
  158. perms |= stat.S_ISVTX
  159. return perms
  160. class File:
  161. def __init__(self, is_built, subdir, fname):
  162. self.is_built = is_built
  163. self.subdir = subdir
  164. self.fname = fname
  165. assert(isinstance(self.subdir, str))
  166. assert(isinstance(self.fname, str))
  167. def __str__(self):
  168. return self.relative_name()
  169. def __repr__(self):
  170. ret = '<File: {0}'
  171. if not self.is_built:
  172. ret += ' (not built)'
  173. ret += '>'
  174. return ret.format(self.relative_name())
  175. @staticmethod
  176. def from_source_file(source_root, subdir, fname):
  177. if not os.path.isfile(os.path.join(source_root, subdir, fname)):
  178. raise MesonException('File %s does not exist.' % fname)
  179. return File(False, subdir, fname)
  180. @staticmethod
  181. def from_built_file(subdir, fname):
  182. return File(True, subdir, fname)
  183. @staticmethod
  184. def from_absolute_file(fname):
  185. return File(False, '', fname)
  186. def rel_to_builddir(self, build_to_src):
  187. if self.is_built:
  188. return self.relative_name()
  189. else:
  190. return os.path.join(build_to_src, self.subdir, self.fname)
  191. def absolute_path(self, srcdir, builddir):
  192. absdir = srcdir
  193. if self.is_built:
  194. absdir = builddir
  195. return os.path.join(absdir, self.relative_name())
  196. def endswith(self, ending):
  197. return self.fname.endswith(ending)
  198. def split(self, s):
  199. return self.fname.split(s)
  200. def __eq__(self, other):
  201. return (self.fname, self.subdir, self.is_built) == (other.fname, other.subdir, other.is_built)
  202. def __hash__(self):
  203. return hash((self.fname, self.subdir, self.is_built))
  204. def relative_name(self):
  205. return os.path.join(self.subdir, self.fname)
  206. def get_compiler_for_source(compilers, src):
  207. for comp in compilers:
  208. if comp.can_compile(src):
  209. return comp
  210. raise RuntimeError('No specified compiler can handle file {!s}'.format(src))
  211. def classify_unity_sources(compilers, sources):
  212. compsrclist = {}
  213. for src in sources:
  214. comp = get_compiler_for_source(compilers, src)
  215. if comp not in compsrclist:
  216. compsrclist[comp] = [src]
  217. else:
  218. compsrclist[comp].append(src)
  219. return compsrclist
  220. def is_osx():
  221. return platform.system().lower() == 'darwin'
  222. def is_linux():
  223. return platform.system().lower() == 'linux'
  224. def is_android():
  225. return platform.system().lower() == 'android'
  226. def is_haiku():
  227. return platform.system().lower() == 'haiku'
  228. def is_openbsd():
  229. return platform.system().lower() == 'openbsd'
  230. def is_windows():
  231. platname = platform.system().lower()
  232. return platname == 'windows' or 'mingw' in platname
  233. def is_cygwin():
  234. platname = platform.system().lower()
  235. return platname.startswith('cygwin')
  236. def is_debianlike():
  237. return os.path.isfile('/etc/debian_version')
  238. def is_dragonflybsd():
  239. return platform.system().lower() == 'dragonfly'
  240. def is_freebsd():
  241. return platform.system().lower() == 'freebsd'
  242. def for_windows(is_cross, env):
  243. """
  244. Host machine is windows?
  245. Note: 'host' is the machine on which compiled binaries will run
  246. """
  247. if not is_cross:
  248. return is_windows()
  249. elif env.cross_info.has_host():
  250. return env.cross_info.config['host_machine']['system'] == 'windows'
  251. return False
  252. def for_cygwin(is_cross, env):
  253. """
  254. Host machine is cygwin?
  255. Note: 'host' is the machine on which compiled binaries will run
  256. """
  257. if not is_cross:
  258. return is_cygwin()
  259. elif env.cross_info.has_host():
  260. return env.cross_info.config['host_machine']['system'] == 'cygwin'
  261. return False
  262. def for_linux(is_cross, env):
  263. """
  264. Host machine is linux?
  265. Note: 'host' is the machine on which compiled binaries will run
  266. """
  267. if not is_cross:
  268. return is_linux()
  269. elif env.cross_info.has_host():
  270. return env.cross_info.config['host_machine']['system'] == 'linux'
  271. return False
  272. def for_darwin(is_cross, env):
  273. """
  274. Host machine is Darwin (iOS/OS X)?
  275. Note: 'host' is the machine on which compiled binaries will run
  276. """
  277. if not is_cross:
  278. return is_osx()
  279. elif env.cross_info.has_host():
  280. return env.cross_info.config['host_machine']['system'] in ('darwin', 'ios')
  281. return False
  282. def for_android(is_cross, env):
  283. """
  284. Host machine is Android?
  285. Note: 'host' is the machine on which compiled binaries will run
  286. """
  287. if not is_cross:
  288. return is_android()
  289. elif env.cross_info.has_host():
  290. return env.cross_info.config['host_machine']['system'] == 'android'
  291. return False
  292. def for_haiku(is_cross, env):
  293. """
  294. Host machine is Haiku?
  295. Note: 'host' is the machine on which compiled binaries will run
  296. """
  297. if not is_cross:
  298. return is_haiku()
  299. elif env.cross_info.has_host():
  300. return env.cross_info.config['host_machine']['system'] == 'haiku'
  301. return False
  302. def exe_exists(arglist):
  303. try:
  304. p = subprocess.Popen(arglist, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  305. p.communicate()
  306. if p.returncode == 0:
  307. return True
  308. except FileNotFoundError:
  309. pass
  310. return False
  311. def detect_vcs(source_dir):
  312. vcs_systems = [
  313. dict(name = 'git', cmd = 'git', repo_dir = '.git', get_rev = 'git describe --dirty=+', rev_regex = '(.*)', dep = '.git/logs/HEAD'),
  314. dict(name = 'mercurial', cmd = 'hg', repo_dir = '.hg', get_rev = 'hg id -i', rev_regex = '(.*)', dep = '.hg/dirstate'),
  315. dict(name = 'subversion', cmd = 'svn', repo_dir = '.svn', get_rev = 'svn info', rev_regex = 'Revision: (.*)', dep = '.svn/wc.db'),
  316. dict(name = 'bazaar', cmd = 'bzr', repo_dir = '.bzr', get_rev = 'bzr revno', rev_regex = '(.*)', dep = '.bzr'),
  317. ]
  318. segs = source_dir.replace('\\', '/').split('/')
  319. for i in range(len(segs), -1, -1):
  320. curdir = '/'.join(segs[:i])
  321. for vcs in vcs_systems:
  322. if os.path.isdir(os.path.join(curdir, vcs['repo_dir'])) and shutil.which(vcs['cmd']):
  323. vcs['wc_dir'] = curdir
  324. return vcs
  325. return None
  326. def grab_leading_numbers(vstr, strict=False):
  327. result = []
  328. for x in vstr.rstrip('.').split('.'):
  329. try:
  330. result.append(int(x))
  331. except ValueError as e:
  332. if strict:
  333. msg = 'Invalid version to compare against: {!r}; only ' \
  334. 'numeric digits separated by "." are allowed: ' + str(e)
  335. raise MesonException(msg.format(vstr))
  336. break
  337. return result
  338. numpart = re.compile('[0-9.]+')
  339. def version_compare(vstr1, vstr2, strict=False):
  340. match = numpart.match(vstr1.strip())
  341. if match is None:
  342. msg = 'Uncomparable version string {!r}.'
  343. raise MesonException(msg.format(vstr1))
  344. vstr1 = match.group(0)
  345. if vstr2.startswith('>='):
  346. cmpop = operator.ge
  347. vstr2 = vstr2[2:]
  348. elif vstr2.startswith('<='):
  349. cmpop = operator.le
  350. vstr2 = vstr2[2:]
  351. elif vstr2.startswith('!='):
  352. cmpop = operator.ne
  353. vstr2 = vstr2[2:]
  354. elif vstr2.startswith('=='):
  355. cmpop = operator.eq
  356. vstr2 = vstr2[2:]
  357. elif vstr2.startswith('='):
  358. cmpop = operator.eq
  359. vstr2 = vstr2[1:]
  360. elif vstr2.startswith('>'):
  361. cmpop = operator.gt
  362. vstr2 = vstr2[1:]
  363. elif vstr2.startswith('<'):
  364. cmpop = operator.lt
  365. vstr2 = vstr2[1:]
  366. else:
  367. cmpop = operator.eq
  368. varr1 = grab_leading_numbers(vstr1, strict)
  369. varr2 = grab_leading_numbers(vstr2, strict)
  370. return cmpop(varr1, varr2)
  371. def version_compare_many(vstr1, conditions):
  372. if not isinstance(conditions, (list, tuple, frozenset)):
  373. conditions = [conditions]
  374. found = []
  375. not_found = []
  376. for req in conditions:
  377. if not version_compare(vstr1, req, strict=True):
  378. not_found.append(req)
  379. else:
  380. found.append(req)
  381. return not_found == [], not_found, found
  382. def version_compare_condition_with_min(condition, minimum):
  383. match = numpart.match(minimum.strip())
  384. if match is None:
  385. msg = 'Uncomparable version string {!r}.'
  386. raise MesonException(msg.format(minimum))
  387. minimum = match.group(0)
  388. if condition.startswith('>='):
  389. cmpop = operator.lt
  390. condition = condition[2:]
  391. elif condition.startswith('<='):
  392. return True
  393. condition = condition[2:]
  394. elif condition.startswith('!='):
  395. return True
  396. condition = condition[2:]
  397. elif condition.startswith('=='):
  398. cmpop = operator.lt
  399. condition = condition[2:]
  400. elif condition.startswith('='):
  401. cmpop = operator.lt
  402. condition = condition[1:]
  403. elif condition.startswith('>'):
  404. cmpop = operator.lt
  405. condition = condition[1:]
  406. elif condition.startswith('<'):
  407. return True
  408. condition = condition[2:]
  409. else:
  410. cmpop = operator.eq
  411. varr1 = grab_leading_numbers(minimum, True)
  412. varr2 = grab_leading_numbers(condition, True)
  413. return cmpop(varr1, varr2)
  414. def version_compare_condition_with_max(condition, maximum):
  415. match = numpart.match(maximum.strip())
  416. if match is None:
  417. msg = 'Uncomparable version string {!r}.'
  418. raise MesonException(msg.format(maximum))
  419. maximum = match.group(0)
  420. if condition.startswith('>='):
  421. return False
  422. condition = condition[2:]
  423. elif condition.startswith('<='):
  424. cmpop = operator.lt
  425. condition = condition[2:]
  426. elif condition.startswith('!='):
  427. return False
  428. condition = condition[2:]
  429. elif condition.startswith('=='):
  430. cmpop = operator.lt
  431. condition = condition[2:]
  432. elif condition.startswith('='):
  433. cmpop = operator.lt
  434. condition = condition[1:]
  435. elif condition.startswith('>'):
  436. return False
  437. condition = condition[1:]
  438. elif condition.startswith('<'):
  439. cmpop = operator.lt
  440. condition = condition[2:]
  441. else:
  442. cmpop = operator.eq
  443. varr1 = grab_leading_numbers(maximum, True)
  444. varr2 = grab_leading_numbers(condition, True)
  445. return cmpop(varr1, varr2)
  446. def default_libdir():
  447. if is_debianlike():
  448. try:
  449. pc = subprocess.Popen(['dpkg-architecture', '-qDEB_HOST_MULTIARCH'],
  450. stdout=subprocess.PIPE,
  451. stderr=subprocess.DEVNULL)
  452. (stdo, _) = pc.communicate()
  453. if pc.returncode == 0:
  454. archpath = stdo.decode().strip()
  455. return 'lib/' + archpath
  456. except Exception:
  457. pass
  458. if os.path.isdir('/usr/lib64') and not os.path.islink('/usr/lib64'):
  459. return 'lib64'
  460. return 'lib'
  461. def default_libexecdir():
  462. # There is no way to auto-detect this, so it must be set at build time
  463. return 'libexec'
  464. def default_prefix():
  465. return 'c:/' if is_windows() else '/usr/local'
  466. def get_library_dirs():
  467. if is_windows():
  468. return ['C:/mingw/lib'] # Fixme
  469. if is_osx():
  470. return ['/usr/lib'] # Fix me as well.
  471. # The following is probably Debian/Ubuntu specific.
  472. # /usr/local/lib is first because it contains stuff
  473. # installed by the sysadmin and is probably more up-to-date
  474. # than /usr/lib. If you feel that this search order is
  475. # problematic, please raise the issue on the mailing list.
  476. unixdirs = ['/usr/local/lib', '/usr/lib', '/lib']
  477. plat = subprocess.check_output(['uname', '-m']).decode().strip()
  478. # This is a terrible hack. I admit it and I'm really sorry.
  479. # I just don't know what the correct solution is.
  480. if plat == 'i686':
  481. plat = 'i386'
  482. if plat.startswith('arm'):
  483. plat = 'arm'
  484. unixdirs += glob('/usr/lib/' + plat + '*')
  485. if os.path.exists('/usr/lib64'):
  486. unixdirs.append('/usr/lib64')
  487. unixdirs += glob('/lib/' + plat + '*')
  488. if os.path.exists('/lib64'):
  489. unixdirs.append('/lib64')
  490. unixdirs += glob('/lib/' + plat + '*')
  491. return unixdirs
  492. def has_path_sep(name, sep='/\\'):
  493. 'Checks if any of the specified @sep path separators are in @name'
  494. for each in sep:
  495. if each in name:
  496. return True
  497. return False
  498. def do_replacement(regex, line, format, confdata):
  499. missing_variables = set()
  500. start_tag = '@'
  501. backslash_tag = '\\@'
  502. if format == 'cmake':
  503. start_tag = '${'
  504. backslash_tag = '\\${'
  505. def variable_replace(match):
  506. # Pairs of escape characters before '@' or '\@'
  507. if match.group(0).endswith('\\'):
  508. num_escapes = match.end(0) - match.start(0)
  509. return '\\' * (num_escapes // 2)
  510. # Single escape character and '@'
  511. elif match.group(0) == backslash_tag:
  512. return start_tag
  513. # Template variable to be replaced
  514. else:
  515. varname = match.group(1)
  516. if varname in confdata:
  517. (var, desc) = confdata.get(varname)
  518. if isinstance(var, str):
  519. pass
  520. elif isinstance(var, int):
  521. var = str(var)
  522. else:
  523. raise RuntimeError('Tried to replace a variable with something other than a string or int.')
  524. else:
  525. missing_variables.add(varname)
  526. var = ''
  527. return var
  528. return re.sub(regex, variable_replace, line), missing_variables
  529. def do_mesondefine(line, confdata):
  530. arr = line.split()
  531. if len(arr) != 2:
  532. raise MesonException('#mesondefine does not contain exactly two tokens: %s' % line.strip())
  533. varname = arr[1]
  534. try:
  535. (v, desc) = confdata.get(varname)
  536. except KeyError:
  537. return '/* #undef %s */\n' % varname
  538. if isinstance(v, bool):
  539. if v:
  540. return '#define %s\n' % varname
  541. else:
  542. return '#undef %s\n' % varname
  543. elif isinstance(v, int):
  544. return '#define %s %d\n' % (varname, v)
  545. elif isinstance(v, str):
  546. return '#define %s %s\n' % (varname, v)
  547. else:
  548. raise MesonException('#mesondefine argument "%s" is of unknown type.' % varname)
  549. def do_conf_file(src, dst, confdata, format, encoding='utf-8'):
  550. try:
  551. with open(src, encoding=encoding) as f:
  552. data = f.readlines()
  553. except Exception as e:
  554. raise MesonException('Could not read input file %s: %s' % (src, str(e)))
  555. # Only allow (a-z, A-Z, 0-9, _, -) as valid characters for a define
  556. # Also allow escaping '@' with '\@'
  557. if format in ['meson', 'cmake@']:
  558. regex = re.compile(r'(?:\\\\)+(?=\\?@)|\\@|@([-a-zA-Z0-9_]+)@')
  559. elif format == 'cmake':
  560. regex = re.compile(r'(?:\\\\)+(?=\\?\$)|\\\${|\${([-a-zA-Z0-9_]+)}')
  561. else:
  562. raise MesonException('Format "{}" not handled'.format(format))
  563. search_token = '#mesondefine'
  564. if format != 'meson':
  565. search_token = '#cmakedefine'
  566. result = []
  567. missing_variables = set()
  568. for line in data:
  569. if line.startswith(search_token):
  570. line = do_mesondefine(line, confdata)
  571. else:
  572. line, missing = do_replacement(regex, line, format, confdata)
  573. missing_variables.update(missing)
  574. result.append(line)
  575. dst_tmp = dst + '~'
  576. try:
  577. with open(dst_tmp, 'w', encoding=encoding) as f:
  578. f.writelines(result)
  579. except Exception as e:
  580. raise MesonException('Could not write output file %s: %s' % (dst, str(e)))
  581. shutil.copymode(src, dst_tmp)
  582. replace_if_different(dst, dst_tmp)
  583. return missing_variables
  584. CONF_C_PRELUDE = '''/*
  585. * Autogenerated by the Meson build system.
  586. * Do not edit, your changes will be lost.
  587. */
  588. #pragma once
  589. '''
  590. CONF_NASM_PRELUDE = '''; Autogenerated by the Meson build system.
  591. ; Do not edit, your changes will be lost.
  592. '''
  593. def dump_conf_header(ofilename, cdata, output_format):
  594. if output_format == 'c':
  595. prelude = CONF_C_PRELUDE
  596. prefix = '#'
  597. elif output_format == 'nasm':
  598. prelude = CONF_NASM_PRELUDE
  599. prefix = '%'
  600. ofilename_tmp = ofilename + '~'
  601. with open(ofilename_tmp, 'w', encoding='utf-8') as ofile:
  602. ofile.write(prelude)
  603. for k in sorted(cdata.keys()):
  604. (v, desc) = cdata.get(k)
  605. if desc:
  606. if output_format == 'c':
  607. ofile.write('/* %s */\n' % desc)
  608. elif output_format == 'nasm':
  609. for line in desc.split('\n'):
  610. ofile.write('; %s\n' % line)
  611. if isinstance(v, bool):
  612. if v:
  613. ofile.write('%sdefine %s\n\n' % (prefix, k))
  614. else:
  615. ofile.write('%sundef %s\n\n' % (prefix, k))
  616. elif isinstance(v, (int, str)):
  617. ofile.write('%sdefine %s %s\n\n' % (prefix, k, v))
  618. else:
  619. raise MesonException('Unknown data type in configuration file entry: ' + k)
  620. replace_if_different(ofilename, ofilename_tmp)
  621. def replace_if_different(dst, dst_tmp):
  622. # If contents are identical, don't touch the file to prevent
  623. # unnecessary rebuilds.
  624. different = True
  625. try:
  626. with open(dst, 'rb') as f1, open(dst_tmp, 'rb') as f2:
  627. if f1.read() == f2.read():
  628. different = False
  629. except FileNotFoundError:
  630. pass
  631. if different:
  632. os.replace(dst_tmp, dst)
  633. else:
  634. os.unlink(dst_tmp)
  635. def listify(item, flatten=True, unholder=False):
  636. '''
  637. Returns a list with all args embedded in a list if they are not a list.
  638. This function preserves order.
  639. @flatten: Convert lists of lists to a flat list
  640. @unholder: Replace each item with the object it holds, if required
  641. Note: unholding only works recursively when flattening
  642. '''
  643. if not isinstance(item, list):
  644. if unholder and hasattr(item, 'held_object'):
  645. item = item.held_object
  646. return [item]
  647. result = []
  648. for i in item:
  649. if unholder and hasattr(i, 'held_object'):
  650. i = i.held_object
  651. if flatten and isinstance(i, list):
  652. result += listify(i, flatten=True, unholder=unholder)
  653. else:
  654. result.append(i)
  655. return result
  656. def extract_as_list(dict_object, *keys, pop=False, **kwargs):
  657. '''
  658. Extracts all values from given dict_object and listifies them.
  659. '''
  660. result = []
  661. fetch = dict_object.get
  662. if pop:
  663. fetch = dict_object.pop
  664. # If there's only one key, we don't return a list with one element
  665. if len(keys) == 1:
  666. return listify(fetch(keys[0], []), **kwargs)
  667. # Return a list of values corresponding to *keys
  668. for key in keys:
  669. result.append(listify(fetch(key, []), **kwargs))
  670. return result
  671. def typeslistify(item, types):
  672. '''
  673. Ensure that type(@item) is one of @types or a
  674. list of items all of which are of type @types
  675. '''
  676. if isinstance(item, types):
  677. item = [item]
  678. if not isinstance(item, list):
  679. raise MesonException('Item must be a list or one of {!r}'.format(types))
  680. for i in item:
  681. if i is not None and not isinstance(i, types):
  682. raise MesonException('List item must be one of {!r}'.format(types))
  683. return item
  684. def stringlistify(item):
  685. return typeslistify(item, str)
  686. def expand_arguments(args):
  687. expended_args = []
  688. for arg in args:
  689. if not arg.startswith('@'):
  690. expended_args.append(arg)
  691. continue
  692. args_file = arg[1:]
  693. try:
  694. with open(args_file) as f:
  695. extended_args = f.read().split()
  696. expended_args += extended_args
  697. except Exception as e:
  698. print('Error expanding command line arguments, %s not found' % args_file)
  699. print(e)
  700. return None
  701. return expended_args
  702. def Popen_safe(args, write=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs):
  703. import locale
  704. encoding = locale.getpreferredencoding()
  705. if sys.version_info < (3, 6) or not sys.stdout.encoding or encoding.upper() != 'UTF-8':
  706. return Popen_safe_legacy(args, write=write, stdout=stdout, stderr=stderr, **kwargs)
  707. p = subprocess.Popen(args, universal_newlines=True, close_fds=False,
  708. stdout=stdout, stderr=stderr, **kwargs)
  709. o, e = p.communicate(write)
  710. return p, o, e
  711. def Popen_safe_legacy(args, write=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs):
  712. p = subprocess.Popen(args, universal_newlines=False,
  713. stdout=stdout, stderr=stderr, **kwargs)
  714. if write is not None:
  715. write = write.encode('utf-8')
  716. o, e = p.communicate(write)
  717. if o is not None:
  718. if sys.stdout.encoding:
  719. o = o.decode(encoding=sys.stdout.encoding, errors='replace').replace('\r\n', '\n')
  720. else:
  721. o = o.decode(errors='replace').replace('\r\n', '\n')
  722. if e is not None:
  723. if sys.stderr.encoding:
  724. e = e.decode(encoding=sys.stderr.encoding, errors='replace').replace('\r\n', '\n')
  725. else:
  726. e = e.decode(errors='replace').replace('\r\n', '\n')
  727. return p, o, e
  728. def iter_regexin_iter(regexiter, initer):
  729. '''
  730. Takes each regular expression in @regexiter and tries to search for it in
  731. every item in @initer. If there is a match, returns that match.
  732. Else returns False.
  733. '''
  734. for regex in regexiter:
  735. for ii in initer:
  736. if not isinstance(ii, str):
  737. continue
  738. match = re.search(regex, ii)
  739. if match:
  740. return match.group()
  741. return False
  742. def _substitute_values_check_errors(command, values):
  743. # Error checking
  744. inregex = ('@INPUT([0-9]+)?@', '@PLAINNAME@', '@BASENAME@')
  745. outregex = ('@OUTPUT([0-9]+)?@', '@OUTDIR@')
  746. if '@INPUT@' not in values:
  747. # Error out if any input-derived templates are present in the command
  748. match = iter_regexin_iter(inregex, command)
  749. if match:
  750. m = 'Command cannot have {!r}, since no input files were specified'
  751. raise MesonException(m.format(match))
  752. else:
  753. if len(values['@INPUT@']) > 1:
  754. # Error out if @PLAINNAME@ or @BASENAME@ is present in the command
  755. match = iter_regexin_iter(inregex[1:], command)
  756. if match:
  757. raise MesonException('Command cannot have {!r} when there is '
  758. 'more than one input file'.format(match))
  759. # Error out if an invalid @INPUTnn@ template was specified
  760. for each in command:
  761. if not isinstance(each, str):
  762. continue
  763. match = re.search(inregex[0], each)
  764. if match and match.group() not in values:
  765. m = 'Command cannot have {!r} since there are only {!r} inputs'
  766. raise MesonException(m.format(match.group(), len(values['@INPUT@'])))
  767. if '@OUTPUT@' not in values:
  768. # Error out if any output-derived templates are present in the command
  769. match = iter_regexin_iter(outregex, command)
  770. if match:
  771. m = 'Command cannot have {!r} since there are no outputs'
  772. raise MesonException(m.format(match))
  773. else:
  774. # Error out if an invalid @OUTPUTnn@ template was specified
  775. for each in command:
  776. if not isinstance(each, str):
  777. continue
  778. match = re.search(outregex[0], each)
  779. if match and match.group() not in values:
  780. m = 'Command cannot have {!r} since there are only {!r} outputs'
  781. raise MesonException(m.format(match.group(), len(values['@OUTPUT@'])))
  782. def substitute_values(command, values):
  783. '''
  784. Substitute the template strings in the @values dict into the list of
  785. strings @command and return a new list. For a full list of the templates,
  786. see get_filenames_templates_dict()
  787. If multiple inputs/outputs are given in the @values dictionary, we
  788. substitute @INPUT@ and @OUTPUT@ only if they are the entire string, not
  789. just a part of it, and in that case we substitute *all* of them.
  790. '''
  791. # Error checking
  792. _substitute_values_check_errors(command, values)
  793. # Substitution
  794. outcmd = []
  795. rx_keys = [re.escape(key) for key in values if key not in ('@INPUT@', '@OUTPUT@')]
  796. value_rx = re.compile('|'.join(rx_keys)) if rx_keys else None
  797. for vv in command:
  798. if not isinstance(vv, str):
  799. outcmd.append(vv)
  800. elif '@INPUT@' in vv:
  801. inputs = values['@INPUT@']
  802. if vv == '@INPUT@':
  803. outcmd += inputs
  804. elif len(inputs) == 1:
  805. outcmd.append(vv.replace('@INPUT@', inputs[0]))
  806. else:
  807. raise MesonException("Command has '@INPUT@' as part of a "
  808. "string and more than one input file")
  809. elif '@OUTPUT@' in vv:
  810. outputs = values['@OUTPUT@']
  811. if vv == '@OUTPUT@':
  812. outcmd += outputs
  813. elif len(outputs) == 1:
  814. outcmd.append(vv.replace('@OUTPUT@', outputs[0]))
  815. else:
  816. raise MesonException("Command has '@OUTPUT@' as part of a "
  817. "string and more than one output file")
  818. # Append values that are exactly a template string.
  819. # This is faster than a string replace.
  820. elif vv in values:
  821. outcmd.append(values[vv])
  822. # Substitute everything else with replacement
  823. elif value_rx:
  824. outcmd.append(value_rx.sub(lambda m: values[m.group(0)], vv))
  825. else:
  826. outcmd.append(vv)
  827. return outcmd
  828. def get_filenames_templates_dict(inputs, outputs):
  829. '''
  830. Create a dictionary with template strings as keys and values as values for
  831. the following templates:
  832. @INPUT@ - the full path to one or more input files, from @inputs
  833. @OUTPUT@ - the full path to one or more output files, from @outputs
  834. @OUTDIR@ - the full path to the directory containing the output files
  835. If there is only one input file, the following keys are also created:
  836. @PLAINNAME@ - the filename of the input file
  837. @BASENAME@ - the filename of the input file with the extension removed
  838. If there is more than one input file, the following keys are also created:
  839. @INPUT0@, @INPUT1@, ... one for each input file
  840. If there is more than one output file, the following keys are also created:
  841. @OUTPUT0@, @OUTPUT1@, ... one for each output file
  842. '''
  843. values = {}
  844. # Gather values derived from the input
  845. if inputs:
  846. # We want to substitute all the inputs.
  847. values['@INPUT@'] = inputs
  848. for (ii, vv) in enumerate(inputs):
  849. # Write out @INPUT0@, @INPUT1@, ...
  850. values['@INPUT{}@'.format(ii)] = vv
  851. if len(inputs) == 1:
  852. # Just one value, substitute @PLAINNAME@ and @BASENAME@
  853. values['@PLAINNAME@'] = plain = os.path.basename(inputs[0])
  854. values['@BASENAME@'] = os.path.splitext(plain)[0]
  855. if outputs:
  856. # Gather values derived from the outputs, similar to above.
  857. values['@OUTPUT@'] = outputs
  858. for (ii, vv) in enumerate(outputs):
  859. values['@OUTPUT{}@'.format(ii)] = vv
  860. # Outdir should be the same for all outputs
  861. values['@OUTDIR@'] = os.path.dirname(outputs[0])
  862. # Many external programs fail on empty arguments.
  863. if values['@OUTDIR@'] == '':
  864. values['@OUTDIR@'] = '.'
  865. return values
  866. def _make_tree_writable(topdir):
  867. # Ensure all files and directories under topdir are writable
  868. # (and readable) by owner.
  869. for d, _, files in os.walk(topdir):
  870. os.chmod(d, os.stat(d).st_mode | stat.S_IWRITE | stat.S_IREAD)
  871. for fname in files:
  872. fpath = os.path.join(d, fname)
  873. if os.path.isfile(fpath):
  874. os.chmod(fpath, os.stat(fpath).st_mode | stat.S_IWRITE | stat.S_IREAD)
  875. def windows_proof_rmtree(f):
  876. # On Windows if anyone is holding a file open you can't
  877. # delete it. As an example an anti virus scanner might
  878. # be scanning files you are trying to delete. The only
  879. # way to fix this is to try again and again.
  880. delays = [0.1, 0.1, 0.2, 0.2, 0.2, 0.5, 0.5, 1, 1, 1, 1, 2]
  881. # Start by making the tree wriable.
  882. _make_tree_writable(f)
  883. for d in delays:
  884. try:
  885. shutil.rmtree(f)
  886. return
  887. except FileNotFoundError:
  888. return
  889. except (OSError, PermissionError):
  890. time.sleep(d)
  891. # Try one last time and throw if it fails.
  892. shutil.rmtree(f)
  893. def detect_subprojects(spdir_name, current_dir='', result=None):
  894. if result is None:
  895. result = {}
  896. spdir = os.path.join(current_dir, spdir_name)
  897. if not os.path.exists(spdir):
  898. return result
  899. for trial in glob(os.path.join(spdir, '*')):
  900. basename = os.path.basename(trial)
  901. if trial == 'packagecache':
  902. continue
  903. append_this = True
  904. if os.path.isdir(trial):
  905. detect_subprojects(spdir_name, trial, result)
  906. elif trial.endswith('.wrap') and os.path.isfile(trial):
  907. basename = os.path.splitext(basename)[0]
  908. else:
  909. append_this = False
  910. if append_this:
  911. if basename in result:
  912. result[basename].append(trial)
  913. else:
  914. result[basename] = [trial]
  915. return result
  916. class OrderedSet(collections.MutableSet):
  917. """A set that preserves the order in which items are added, by first
  918. insertion.
  919. """
  920. def __init__(self, iterable=None):
  921. self.__container = collections.OrderedDict()
  922. if iterable:
  923. self.update(iterable)
  924. def __contains__(self, value):
  925. return value in self.__container
  926. def __iter__(self):
  927. return iter(self.__container.keys())
  928. def __len__(self):
  929. return len(self.__container)
  930. def __repr__(self):
  931. # Don't print 'OrderedSet("")' for an empty set.
  932. if self.__container:
  933. return 'OrderedSet("{}")'.format(
  934. '", "'.join(repr(e) for e in self.__container.keys()))
  935. return 'OrderedSet()'
  936. def add(self, value):
  937. self.__container[value] = None
  938. def discard(self, value):
  939. if value in self.__container:
  940. del self.__container[value]
  941. def update(self, iterable):
  942. for item in iterable:
  943. self.__container[item] = None
  944. def difference(self, set_):
  945. return type(self)(e for e in self if e not in set_)
  946. class BuildDirLock:
  947. def __init__(self, builddir):
  948. self.lockfilename = os.path.join(builddir, 'meson-private/meson.lock')
  949. def __enter__(self):
  950. self.lockfile = open(self.lockfilename, 'w')
  951. try:
  952. if have_fcntl:
  953. fcntl.flock(self.lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)
  954. elif have_msvcrt:
  955. msvcrt.locking(self.lockfile.fileno(), msvcrt.LK_NBLCK, 1)
  956. except (BlockingIOError, PermissionError):
  957. self.lockfile.close()
  958. raise MesonException('Some other Meson process is already using this build directory. Exiting.')
  959. def __exit__(self, *args):
  960. if have_fcntl:
  961. fcntl.flock(self.lockfile, fcntl.LOCK_UN)
  962. elif have_msvcrt:
  963. msvcrt.locking(self.lockfile.fileno(), msvcrt.LK_UNLCK, 1)
  964. self.lockfile.close()