environment.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931
  1. # Copyright 2012-2016 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. import os
  12. import platform
  13. import re
  14. from .compilers import *
  15. from .mesonlib import EnvironmentException, Popen_safe
  16. import configparser
  17. import shlex
  18. import shutil
  19. build_filename = 'meson.build'
  20. # Environment variables that each lang uses.
  21. cflags_mapping = {'c': 'CFLAGS',
  22. 'cpp': 'CXXFLAGS',
  23. 'objc': 'OBJCFLAGS',
  24. 'objcpp': 'OBJCXXFLAGS',
  25. 'fortran': 'FFLAGS',
  26. 'd': 'DFLAGS',
  27. 'vala': 'VALAFLAGS'}
  28. def find_coverage_tools():
  29. gcovr_exe = 'gcovr'
  30. lcov_exe = 'lcov'
  31. genhtml_exe = 'genhtml'
  32. if not mesonlib.exe_exists([gcovr_exe, '--version']):
  33. gcovr_exe = None
  34. if not mesonlib.exe_exists([lcov_exe, '--version']):
  35. lcov_exe = None
  36. if not mesonlib.exe_exists([genhtml_exe, '--version']):
  37. genhtml_exe = None
  38. return gcovr_exe, lcov_exe, genhtml_exe
  39. def detect_ninja(version='1.5'):
  40. for n in ['ninja', 'ninja-build']:
  41. try:
  42. p, found = Popen_safe([n, '--version'])[0:2]
  43. except (FileNotFoundError, PermissionError):
  44. # Doesn't exist in PATH or isn't executable
  45. continue
  46. # Perhaps we should add a way for the caller to know the failure mode
  47. # (not found or too old)
  48. if p.returncode == 0 and mesonlib.version_compare(found, '>=' + version):
  49. return n
  50. def detect_native_windows_arch():
  51. """
  52. The architecture of Windows itself: x86 or amd64
  53. """
  54. # These env variables are always available. See:
  55. # https://msdn.microsoft.com/en-us/library/aa384274(VS.85).aspx
  56. # https://blogs.msdn.microsoft.com/david.wang/2006/03/27/howto-detect-process-bitness/
  57. arch = os.environ.get('PROCESSOR_ARCHITEW6432', '').lower()
  58. if not arch:
  59. try:
  60. # If this doesn't exist, something is messing with the environment
  61. arch = os.environ['PROCESSOR_ARCHITECTURE'].lower()
  62. except KeyError:
  63. raise EnvironmentException('Unable to detect native OS architecture')
  64. return arch
  65. def detect_windows_arch(compilers):
  66. """
  67. Detecting the 'native' architecture of Windows is not a trivial task. We
  68. cannot trust that the architecture that Python is built for is the 'native'
  69. one because you can run 32-bit apps on 64-bit Windows using WOW64 and
  70. people sometimes install 32-bit Python on 64-bit Windows.
  71. We also can't rely on the architecture of the OS itself, since it's
  72. perfectly normal to compile and run 32-bit applications on Windows as if
  73. they were native applications. It's a terrible experience to require the
  74. user to supply a cross-info file to compile 32-bit applications on 64-bit
  75. Windows. Thankfully, the only way to compile things with Visual Studio on
  76. Windows is by entering the 'msvc toolchain' environment, which can be
  77. easily detected.
  78. In the end, the sanest method is as follows:
  79. 1. Check if we're in an MSVC toolchain environment, and if so, return the
  80. MSVC toolchain architecture as our 'native' architecture.
  81. 2. If not, check environment variables that are set by Windows and WOW64 to
  82. find out the architecture that Windows is built for, and use that as our
  83. 'native' architecture.
  84. """
  85. os_arch = detect_native_windows_arch()
  86. if os_arch != 'amd64':
  87. return os_arch
  88. # If we're on 64-bit Windows, 32-bit apps can be compiled without
  89. # cross-compilation. So if we're doing that, just set the native arch as
  90. # 32-bit and pretend like we're running under WOW64. Else, return the
  91. # actual Windows architecture that we deduced above.
  92. for compiler in compilers.values():
  93. # Check if we're using and inside an MSVC toolchain environment
  94. if compiler.id == 'msvc' and 'VCINSTALLDIR' in os.environ:
  95. # 'Platform' is only set when the target arch is not 'x86'.
  96. # It's 'x64' when targetting x86_64 and 'arm' when targetting ARM.
  97. platform = os.environ.get('Platform', 'x86').lower()
  98. if platform == 'x86':
  99. return platform
  100. if compiler.id == 'gcc' and compiler.has_builtin_define('__i386__'):
  101. return 'x86'
  102. return os_arch
  103. def detect_cpu_family(compilers):
  104. """
  105. Python is inconsistent in its platform module.
  106. It returns different values for the same cpu.
  107. For x86 it might return 'x86', 'i686' or somesuch.
  108. Do some canonicalization.
  109. """
  110. if mesonlib.is_windows():
  111. trial = detect_windows_arch(compilers)
  112. else:
  113. trial = platform.machine().lower()
  114. if trial.startswith('i') and trial.endswith('86'):
  115. return 'x86'
  116. if trial.startswith('arm'):
  117. return 'arm'
  118. if trial in ('amd64', 'x64'):
  119. trial = 'x86_64'
  120. if trial == 'x86_64':
  121. # On Linux (and maybe others) there can be any mixture of 32/64 bit
  122. # code in the kernel, Python, system etc. The only reliable way
  123. # to know is to check the compiler defines.
  124. for c in compilers.values():
  125. try:
  126. if c.has_builtin_define('__i386__'):
  127. return 'x86'
  128. except mesonlib.MesonException:
  129. # Ignore compilers that do not support has_builtin_define.
  130. pass
  131. return 'x86_64'
  132. # Add fixes here as bugs are reported.
  133. return trial
  134. def detect_cpu(compilers):
  135. if mesonlib.is_windows():
  136. trial = detect_windows_arch(compilers)
  137. else:
  138. trial = platform.machine().lower()
  139. if trial in ('amd64', 'x64'):
  140. trial = 'x86_64'
  141. if trial == 'x86_64':
  142. # Same check as above for cpu_family
  143. for c in compilers.values():
  144. try:
  145. if c.has_builtin_define('__i386__'):
  146. return 'i686' # All 64 bit cpus have at least this level of x86 support.
  147. except mesonlib.MesonException:
  148. pass
  149. return 'x86_64'
  150. # Add fixes here as bugs are reported.
  151. return trial
  152. def detect_system():
  153. system = platform.system().lower()
  154. if system.startswith('cygwin'):
  155. return 'cygwin'
  156. return system
  157. def for_windows(is_cross, env):
  158. """
  159. Host machine is windows?
  160. Note: 'host' is the machine on which compiled binaries will run
  161. """
  162. if not is_cross:
  163. return mesonlib.is_windows()
  164. elif env.cross_info.has_host():
  165. return env.cross_info.config['host_machine']['system'] == 'windows'
  166. return False
  167. def for_cygwin(is_cross, env):
  168. """
  169. Host machine is cygwin?
  170. Note: 'host' is the machine on which compiled binaries will run
  171. """
  172. if not is_cross:
  173. return mesonlib.is_cygwin()
  174. elif env.cross_info.has_host():
  175. return env.cross_info.config['host_machine']['system'] == 'cygwin'
  176. return False
  177. def for_darwin(is_cross, env):
  178. """
  179. Host machine is Darwin (iOS/OS X)?
  180. Note: 'host' is the machine on which compiled binaries will run
  181. """
  182. if not is_cross:
  183. return mesonlib.is_osx()
  184. elif env.cross_info.has_host():
  185. return env.cross_info.config['host_machine']['system'] == 'darwin'
  186. return False
  187. def search_version(text):
  188. # Usually of the type 4.1.4 but compiler output may contain
  189. # stuff like this:
  190. # (Sourcery CodeBench Lite 2014.05-29) 4.8.3 20140320 (prerelease)
  191. # Limiting major version number to two digits seems to work
  192. # thus far. When we get to GCC 100, this will break, but
  193. # if we are still relevant when that happens, it can be
  194. # considered an achievement in itself.
  195. #
  196. # This regex is reaching magic levels. If it ever needs
  197. # to be updated, do not complexify but convert to something
  198. # saner instead.
  199. version_regex = '(?<!(\d|\.))(\d{1,2}(\.\d+)+(-[a-zA-Z0-9]+)?)'
  200. match = re.search(version_regex, text)
  201. if match:
  202. return match.group(0)
  203. return 'unknown version'
  204. class Environment:
  205. private_dir = 'meson-private'
  206. log_dir = 'meson-logs'
  207. coredata_file = os.path.join(private_dir, 'coredata.dat')
  208. def __init__(self, source_dir, build_dir, main_script_launcher, options, original_cmd_line_args):
  209. self.source_dir = source_dir
  210. self.build_dir = build_dir
  211. self.meson_script_launcher = main_script_launcher
  212. self.scratch_dir = os.path.join(build_dir, Environment.private_dir)
  213. self.log_dir = os.path.join(build_dir, Environment.log_dir)
  214. os.makedirs(self.scratch_dir, exist_ok=True)
  215. os.makedirs(self.log_dir, exist_ok=True)
  216. try:
  217. cdf = os.path.join(self.get_build_dir(), Environment.coredata_file)
  218. self.coredata = coredata.load(cdf)
  219. self.first_invocation = False
  220. except FileNotFoundError:
  221. # WARNING: Don't use any values from coredata in __init__. It gets
  222. # re-initialized with project options by the interpreter during
  223. # build file parsing.
  224. self.coredata = coredata.CoreData(options)
  225. self.coredata.meson_script_launcher = self.meson_script_launcher
  226. self.first_invocation = True
  227. if self.coredata.cross_file:
  228. self.cross_info = CrossBuildInfo(self.coredata.cross_file)
  229. else:
  230. self.cross_info = None
  231. self.cmd_line_options = options
  232. self.original_cmd_line_args = original_cmd_line_args
  233. # List of potential compilers.
  234. if mesonlib.is_windows():
  235. self.default_c = ['cl', 'cc', 'gcc', 'clang']
  236. self.default_cpp = ['cl', 'c++', 'g++', 'clang++']
  237. else:
  238. self.default_c = ['cc']
  239. self.default_cpp = ['c++']
  240. self.default_objc = ['cc']
  241. self.default_objcpp = ['c++']
  242. self.default_fortran = ['gfortran', 'g95', 'f95', 'f90', 'f77', 'ifort']
  243. self.default_static_linker = ['ar']
  244. self.vs_static_linker = ['lib']
  245. self.gcc_static_linker = ['gcc-ar']
  246. self.clang_static_linker = ['llvm-ar']
  247. # Various prefixes and suffixes for import libraries, shared libraries,
  248. # static libraries, and executables.
  249. # Versioning is added to these names in the backends as-needed.
  250. cross = self.is_cross_build()
  251. if (not cross and mesonlib.is_windows()) \
  252. or (cross and self.cross_info.has_host() and self.cross_info.config['host_machine']['system'] == 'windows'):
  253. self.exe_suffix = 'exe'
  254. self.object_suffix = 'obj'
  255. self.win_libdir_layout = True
  256. elif (not cross and mesonlib.is_cygwin()) \
  257. or (cross and self.cross_info.has_host() and self.cross_info.config['host_machine']['system'] == 'cygwin'):
  258. self.exe_suffix = 'exe'
  259. self.object_suffix = 'o'
  260. self.win_libdir_layout = True
  261. else:
  262. self.exe_suffix = ''
  263. self.object_suffix = 'o'
  264. self.win_libdir_layout = False
  265. if 'STRIP' in os.environ:
  266. self.native_strip_bin = shlex.split('STRIP')
  267. else:
  268. self.native_strip_bin = ['strip']
  269. def is_cross_build(self):
  270. return self.cross_info is not None
  271. def dump_coredata(self, mtime):
  272. cdf = os.path.join(self.get_build_dir(), Environment.coredata_file)
  273. coredata.save(self.coredata, cdf)
  274. os.utime(cdf, times=(mtime, mtime))
  275. def get_script_dir(self):
  276. import mesonbuild.scripts
  277. return os.path.dirname(mesonbuild.scripts.__file__)
  278. def get_log_dir(self):
  279. return self.log_dir
  280. def get_coredata(self):
  281. return self.coredata
  282. def get_build_command(self):
  283. return self.meson_script_launcher
  284. def is_header(self, fname):
  285. return is_header(fname)
  286. def is_source(self, fname):
  287. return is_source(fname)
  288. def is_assembly(self, fname):
  289. return is_assembly(fname)
  290. def is_llvm_ir(self, fname):
  291. return is_llvm_ir(fname)
  292. def is_object(self, fname):
  293. return is_object(fname)
  294. def is_library(self, fname):
  295. return is_library(fname)
  296. def had_argument_for(self, option):
  297. trial1 = '--' + option
  298. trial2 = '-D' + option
  299. previous_is_plaind = False
  300. for i in self.original_cmd_line_args:
  301. if i.startswith(trial1) or i.startswith(trial2):
  302. return True
  303. if previous_is_plaind and i.startswith(option):
  304. return True
  305. previous_is_plaind = i == '-D'
  306. return False
  307. def merge_options(self, options):
  308. for (name, value) in options.items():
  309. if name not in self.coredata.user_options:
  310. self.coredata.user_options[name] = value
  311. else:
  312. oldval = self.coredata.user_options[name]
  313. if type(oldval) != type(value):
  314. self.coredata.user_options[name] = value
  315. @staticmethod
  316. def get_gnu_compiler_defines(compiler):
  317. """
  318. Detect GNU compiler platform type (Apple, MinGW, Unix)
  319. """
  320. # Arguments to output compiler pre-processor defines to stdout
  321. # gcc, g++, and gfortran all support these arguments
  322. args = compiler + ['-E', '-dM', '-']
  323. p, output = Popen_safe(args, write='', stdin=subprocess.PIPE)[0:2]
  324. if p.returncode != 0:
  325. raise EnvironmentException('Unable to detect GNU compiler type:\n' + output)
  326. # Parse several lines of the type:
  327. # `#define ___SOME_DEF some_value`
  328. # and extract `___SOME_DEF`
  329. defines = {}
  330. for line in output.split('\n'):
  331. if not line:
  332. continue
  333. d, *rest = line.split(' ', 2)
  334. if d != '#define':
  335. continue
  336. if len(rest) == 1:
  337. defines[rest] = True
  338. if len(rest) == 2:
  339. defines[rest[0]] = rest[1]
  340. return defines
  341. @staticmethod
  342. def get_gnu_version_from_defines(defines):
  343. dot = '.'
  344. major = defines.get('__GNUC__', '0')
  345. minor = defines.get('__GNUC_MINOR__', '0')
  346. patch = defines.get('__GNUC_PATCHLEVEL__', '0')
  347. return dot.join((major, minor, patch))
  348. @staticmethod
  349. def get_gnu_compiler_type(defines):
  350. # Detect GCC type (Apple, MinGW, Cygwin, Unix)
  351. if '__APPLE__' in defines:
  352. return GCC_OSX
  353. elif '__MINGW32__' in defines or '__MINGW64__' in defines:
  354. return GCC_MINGW
  355. elif '__CYGWIN__' in defines:
  356. return GCC_CYGWIN
  357. return GCC_STANDARD
  358. def _get_compilers(self, lang, evar, want_cross):
  359. '''
  360. The list of compilers is detected in the exact same way for
  361. C, C++, ObjC, ObjC++, Fortran so consolidate it here.
  362. '''
  363. if self.is_cross_build() and want_cross:
  364. compilers = mesonlib.stringlistify(self.cross_info.config['binaries'][lang])
  365. # Ensure ccache exists and remove it if it doesn't
  366. if compilers[0] == 'ccache':
  367. compilers = compilers[1:]
  368. ccache = self.detect_ccache()
  369. else:
  370. ccache = []
  371. # Return value has to be a list of compiler 'choices'
  372. compilers = [compilers]
  373. is_cross = True
  374. if self.cross_info.need_exe_wrapper():
  375. exe_wrap = self.cross_info.config['binaries'].get('exe_wrapper', None)
  376. else:
  377. exe_wrap = []
  378. elif evar in os.environ:
  379. compilers = shlex.split(os.environ[evar])
  380. # Ensure ccache exists and remove it if it doesn't
  381. if compilers[0] == 'ccache':
  382. compilers = compilers[1:]
  383. ccache = self.detect_ccache()
  384. else:
  385. ccache = []
  386. # Return value has to be a list of compiler 'choices'
  387. compilers = [compilers]
  388. is_cross = False
  389. exe_wrap = None
  390. else:
  391. compilers = getattr(self, 'default_' + lang)
  392. ccache = self.detect_ccache()
  393. is_cross = False
  394. exe_wrap = None
  395. return compilers, ccache, is_cross, exe_wrap
  396. def _handle_exceptions(self, exceptions, binaries, bintype='compiler'):
  397. errmsg = 'Unknown {}(s): {}'.format(bintype, binaries)
  398. if exceptions:
  399. errmsg += '\nThe follow exceptions were encountered:'
  400. for (c, e) in exceptions.items():
  401. errmsg += '\nRunning "{0}" gave "{1}"'.format(c, e)
  402. raise EnvironmentException(errmsg)
  403. def _detect_c_or_cpp_compiler(self, lang, evar, want_cross):
  404. popen_exceptions = {}
  405. compilers, ccache, is_cross, exe_wrap = self._get_compilers(lang, evar, want_cross)
  406. for compiler in compilers:
  407. if isinstance(compiler, str):
  408. compiler = [compiler]
  409. if 'cl' in compiler or 'cl.exe' in compiler:
  410. arg = '/?'
  411. else:
  412. arg = '--version'
  413. try:
  414. p, out, err = Popen_safe(compiler + [arg])
  415. except OSError as e:
  416. popen_exceptions[' '.join(compiler + [arg])] = e
  417. continue
  418. version = search_version(out)
  419. if 'Free Software Foundation' in out:
  420. defines = self.get_gnu_compiler_defines(compiler)
  421. if not defines:
  422. popen_exceptions[compiler] = 'no pre-processor defines'
  423. continue
  424. gtype = self.get_gnu_compiler_type(defines)
  425. version = self.get_gnu_version_from_defines(defines)
  426. cls = GnuCCompiler if lang == 'c' else GnuCPPCompiler
  427. return cls(ccache + compiler, version, gtype, is_cross, exe_wrap, defines)
  428. if 'clang' in out:
  429. if 'Apple' in out or for_darwin(want_cross, self):
  430. cltype = CLANG_OSX
  431. elif 'windows' in out or for_windows(want_cross, self):
  432. cltype = CLANG_WIN
  433. else:
  434. cltype = CLANG_STANDARD
  435. cls = ClangCCompiler if lang == 'c' else ClangCPPCompiler
  436. return cls(ccache + compiler, version, cltype, is_cross, exe_wrap)
  437. if 'Microsoft' in out or 'Microsoft' in err:
  438. # Visual Studio prints version number to stderr but
  439. # everything else to stdout. Why? Lord only knows.
  440. version = search_version(err)
  441. cls = VisualStudioCCompiler if lang == 'c' else VisualStudioCPPCompiler
  442. return cls(compiler, version, is_cross, exe_wrap)
  443. if '(ICC)' in out:
  444. # TODO: add microsoft add check OSX
  445. inteltype = ICC_STANDARD
  446. cls = IntelCCompiler if lang == 'c' else IntelCPPCompiler
  447. return cls(ccache + compiler, version, inteltype, is_cross, exe_wrap)
  448. self._handle_exceptions(popen_exceptions, compilers)
  449. def detect_c_compiler(self, want_cross):
  450. return self._detect_c_or_cpp_compiler('c', 'CC', want_cross)
  451. def detect_cpp_compiler(self, want_cross):
  452. return self._detect_c_or_cpp_compiler('cpp', 'CXX', want_cross)
  453. def detect_fortran_compiler(self, want_cross):
  454. popen_exceptions = {}
  455. compilers, ccache, is_cross, exe_wrap = self._get_compilers('fortran', 'FC', want_cross)
  456. for compiler in compilers:
  457. if isinstance(compiler, str):
  458. compiler = [compiler]
  459. for arg in ['--version', '-V']:
  460. try:
  461. p, out, err = Popen_safe(compiler + [arg])
  462. except OSError as e:
  463. popen_exceptions[' '.join(compiler + [arg])] = e
  464. continue
  465. version = search_version(out)
  466. if 'GNU Fortran' in out:
  467. defines = self.get_gnu_compiler_defines(compiler)
  468. if not defines:
  469. popen_exceptions[compiler] = 'no pre-processor defines'
  470. continue
  471. gtype = self.get_gnu_compiler_type(defines)
  472. version = self.get_gnu_version_from_defines(defines)
  473. return GnuFortranCompiler(compiler, version, gtype, is_cross, exe_wrap, defines)
  474. if 'G95' in out:
  475. return G95FortranCompiler(compiler, version, is_cross, exe_wrap)
  476. if 'Sun Fortran' in err:
  477. version = search_version(err)
  478. return SunFortranCompiler(compiler, version, is_cross, exe_wrap)
  479. if 'ifort (IFORT)' in out:
  480. return IntelFortranCompiler(compiler, version, is_cross, exe_wrap)
  481. if 'PathScale EKOPath(tm)' in err:
  482. return PathScaleFortranCompiler(compiler, version, is_cross, exe_wrap)
  483. if 'PGI Compilers' in out:
  484. return PGIFortranCompiler(compiler, version, is_cross, exe_wrap)
  485. if 'Open64 Compiler Suite' in err:
  486. return Open64FortranCompiler(compiler, version, is_cross, exe_wrap)
  487. if 'NAG Fortran' in err:
  488. return NAGFortranCompiler(compiler, version, is_cross, exe_wrap)
  489. self._handle_exceptions(popen_exceptions, compilers)
  490. def get_scratch_dir(self):
  491. return self.scratch_dir
  492. def get_depfixer(self):
  493. path = os.path.split(__file__)[0]
  494. return os.path.join(path, 'depfixer.py')
  495. def detect_objc_compiler(self, want_cross):
  496. popen_exceptions = {}
  497. compilers, ccache, is_cross, exe_wrap = self._get_compilers('objc', 'OBJC', want_cross)
  498. for compiler in compilers:
  499. if isinstance(compiler, str):
  500. compiler = [compiler]
  501. arg = ['--version']
  502. try:
  503. p, out, err = Popen_safe(compiler + arg)
  504. except OSError as e:
  505. popen_exceptions[' '.join(compiler + arg)] = e
  506. version = search_version(out)
  507. if 'Free Software Foundation' in out:
  508. defines = self.get_gnu_compiler_defines(compiler)
  509. if not defines:
  510. popen_exceptions[compiler] = 'no pre-processor defines'
  511. continue
  512. gtype = self.get_gnu_compiler_type(defines)
  513. version = self.get_gnu_version_from_defines(defines)
  514. return GnuObjCCompiler(ccache + compiler, version, gtype, is_cross, exe_wrap, defines)
  515. if out.startswith('Apple LLVM'):
  516. return ClangObjCCompiler(ccache + compiler, version, CLANG_OSX, is_cross, exe_wrap)
  517. if out.startswith('clang'):
  518. return ClangObjCCompiler(ccache + compiler, version, CLANG_STANDARD, is_cross, exe_wrap)
  519. self._handle_exceptions(popen_exceptions, compilers)
  520. def detect_objcpp_compiler(self, want_cross):
  521. popen_exceptions = {}
  522. compilers, ccache, is_cross, exe_wrap = self._get_compilers('objcpp', 'OBJCXX', want_cross)
  523. for compiler in compilers:
  524. if isinstance(compiler, str):
  525. compiler = [compiler]
  526. arg = ['--version']
  527. try:
  528. p, out, err = Popen_safe(compiler + arg)
  529. except OSError as e:
  530. popen_exceptions[' '.join(compiler + arg)] = e
  531. version = search_version(out)
  532. if 'Free Software Foundation' in out:
  533. defines = self.get_gnu_compiler_defines(compiler)
  534. if not defines:
  535. popen_exceptions[compiler] = 'no pre-processor defines'
  536. continue
  537. gtype = self.get_gnu_compiler_type(defines)
  538. version = self.get_gnu_version_from_defines(defines)
  539. return GnuObjCPPCompiler(ccache + compiler, version, gtype, is_cross, exe_wrap, defines)
  540. if out.startswith('Apple LLVM'):
  541. return ClangObjCPPCompiler(ccache + compiler, version, CLANG_OSX, is_cross, exe_wrap)
  542. if out.startswith('clang'):
  543. return ClangObjCPPCompiler(ccache + compiler, version, CLANG_STANDARD, is_cross, exe_wrap)
  544. self._handle_exceptions(popen_exceptions, compilers)
  545. def detect_java_compiler(self):
  546. exelist = ['javac']
  547. try:
  548. p, out, err = Popen_safe(exelist + ['-version'])
  549. except OSError:
  550. raise EnvironmentException('Could not execute Java compiler "%s"' % ' '.join(exelist))
  551. version = search_version(err)
  552. if 'javac' in err:
  553. return JavaCompiler(exelist, version)
  554. raise EnvironmentException('Unknown compiler "' + ' '.join(exelist) + '"')
  555. def detect_cs_compiler(self):
  556. exelist = ['mcs']
  557. try:
  558. p, out, err = Popen_safe(exelist + ['--version'])
  559. except OSError:
  560. raise EnvironmentException('Could not execute C# compiler "%s"' % ' '.join(exelist))
  561. version = search_version(out)
  562. if 'Mono' in out:
  563. return MonoCompiler(exelist, version)
  564. raise EnvironmentException('Unknown compiler "' + ' '.join(exelist) + '"')
  565. def detect_vala_compiler(self):
  566. exelist = ['valac']
  567. try:
  568. p, out = Popen_safe(exelist + ['--version'])[0:2]
  569. except OSError:
  570. raise EnvironmentException('Could not execute Vala compiler "%s"' % ' '.join(exelist))
  571. version = search_version(out)
  572. if 'Vala' in out:
  573. return ValaCompiler(exelist, version)
  574. raise EnvironmentException('Unknown compiler "' + ' '.join(exelist) + '"')
  575. def detect_rust_compiler(self):
  576. exelist = ['rustc']
  577. try:
  578. p, out = Popen_safe(exelist + ['--version'])[0:2]
  579. except OSError:
  580. raise EnvironmentException('Could not execute Rust compiler "%s"' % ' '.join(exelist))
  581. version = search_version(out)
  582. if 'rustc' in out:
  583. return RustCompiler(exelist, version)
  584. raise EnvironmentException('Unknown compiler "' + ' '.join(exelist) + '"')
  585. def detect_d_compiler(self, want_cross):
  586. is_cross = False
  587. # Search for a D compiler.
  588. # We prefer LDC over GDC unless overridden with the DC
  589. # environment variable because LDC has a much more
  590. # up to date language version at time (2016).
  591. if 'DC' in os.environ:
  592. exelist = shlex.split(os.environ['DC'])
  593. elif self.is_cross_build() and want_cross:
  594. exelist = mesonlib.stringlistify(self.cross_info.config['binaries']['d'])
  595. is_cross = True
  596. elif shutil.which("ldc2"):
  597. exelist = ['ldc2']
  598. elif shutil.which("ldc"):
  599. exelist = ['ldc']
  600. elif shutil.which("gdc"):
  601. exelist = ['gdc']
  602. elif shutil.which("dmd"):
  603. exelist = ['dmd']
  604. else:
  605. raise EnvironmentException('Could not find any supported D compiler.')
  606. try:
  607. p, out = Popen_safe(exelist + ['--version'])[0:2]
  608. except OSError:
  609. raise EnvironmentException('Could not execute D compiler "%s"' % ' '.join(exelist))
  610. version = search_version(out)
  611. if 'LLVM D compiler' in out:
  612. return LLVMDCompiler(exelist, version, is_cross)
  613. elif 'gdc' in out:
  614. return GnuDCompiler(exelist, version, is_cross)
  615. elif 'Digital Mars' in out:
  616. return DmdDCompiler(exelist, version, is_cross)
  617. raise EnvironmentException('Unknown compiler "' + ' '.join(exelist) + '"')
  618. def detect_swift_compiler(self):
  619. exelist = ['swiftc']
  620. try:
  621. p, _, err = Popen_safe(exelist + ['-v'])
  622. except OSError:
  623. raise EnvironmentException('Could not execute Swift compiler "%s"' % ' '.join(exelist))
  624. version = search_version(err)
  625. if 'Swift' in err:
  626. return SwiftCompiler(exelist, version)
  627. raise EnvironmentException('Unknown compiler "' + ' '.join(exelist) + '"')
  628. def detect_static_linker(self, compiler):
  629. if compiler.is_cross:
  630. linker = self.cross_info.config['binaries']['ar']
  631. if isinstance(linker, str):
  632. linker = [linker]
  633. linkers = [linker]
  634. else:
  635. evar = 'AR'
  636. if evar in os.environ:
  637. linkers = [shlex.split(os.environ[evar])]
  638. elif isinstance(compiler, VisualStudioCCompiler):
  639. linkers = [self.vs_static_linker]
  640. elif isinstance(compiler, GnuCompiler):
  641. # Use gcc-ar if available; needed for LTO
  642. linkers = [self.gcc_static_linker, self.default_static_linker]
  643. elif isinstance(compiler, ClangCompiler):
  644. # Use llvm-ar if available; needed for LTO
  645. linkers = [self.clang_static_linker, self.default_static_linker]
  646. else:
  647. linkers = [self.default_static_linker]
  648. popen_exceptions = {}
  649. for linker in linkers:
  650. if 'lib' in linker or 'lib.exe' in linker:
  651. arg = '/?'
  652. else:
  653. arg = '--version'
  654. try:
  655. p, out, err = Popen_safe(linker + [arg])
  656. except OSError as e:
  657. popen_exceptions[' '.join(linker + [arg])] = e
  658. continue
  659. if '/OUT:' in out or '/OUT:' in err:
  660. return VisualStudioLinker(linker)
  661. if p.returncode == 0:
  662. return ArLinker(linker)
  663. if p.returncode == 1 and err.startswith('usage'): # OSX
  664. return ArLinker(linker)
  665. self._handle_exceptions(popen_exceptions, linkers, 'linker')
  666. raise EnvironmentException('Unknown static linker "%s"' % ' '.join(linkers))
  667. def detect_ccache(self):
  668. try:
  669. has_ccache = subprocess.call(['ccache', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  670. except OSError:
  671. has_ccache = 1
  672. if has_ccache == 0:
  673. cmdlist = ['ccache']
  674. else:
  675. cmdlist = []
  676. return cmdlist
  677. def get_source_dir(self):
  678. return self.source_dir
  679. def get_build_dir(self):
  680. return self.build_dir
  681. def get_exe_suffix(self):
  682. return self.exe_suffix
  683. def get_import_lib_dir(self):
  684. "Install dir for the import library (library used for linking)"
  685. return self.get_libdir()
  686. def get_shared_module_dir(self):
  687. "Install dir for shared modules that are loaded at runtime"
  688. return self.get_libdir()
  689. def get_shared_lib_dir(self):
  690. "Install dir for the shared library"
  691. if self.win_libdir_layout:
  692. return self.get_bindir()
  693. return self.get_libdir()
  694. def get_static_lib_dir(self):
  695. "Install dir for the static library"
  696. return self.get_libdir()
  697. def get_object_suffix(self):
  698. return self.object_suffix
  699. def get_prefix(self):
  700. return self.coredata.get_builtin_option('prefix')
  701. def get_libdir(self):
  702. return self.coredata.get_builtin_option('libdir')
  703. def get_libexecdir(self):
  704. return self.coredata.get_builtin_option('libexecdir')
  705. def get_bindir(self):
  706. return self.coredata.get_builtin_option('bindir')
  707. def get_includedir(self):
  708. return self.coredata.get_builtin_option('includedir')
  709. def get_mandir(self):
  710. return self.coredata.get_builtin_option('mandir')
  711. def get_datadir(self):
  712. return self.coredata.get_builtin_option('datadir')
  713. def get_args_from_envvars(compiler):
  714. """
  715. @compiler: Compiler to fetch environment flags for
  716. Returns a tuple of (compile_flags, link_flags) for the specified language
  717. from the inherited environment
  718. """
  719. def log_var(var, val):
  720. if val:
  721. mlog.log('Appending {} from environment: {!r}'.format(var, val))
  722. lang = compiler.get_language()
  723. compiler_is_linker = False
  724. if hasattr(compiler, 'get_linker_exelist'):
  725. compiler_is_linker = (compiler.get_exelist() == compiler.get_linker_exelist())
  726. if lang not in cflags_mapping:
  727. return [], [], []
  728. compile_flags = os.environ.get(cflags_mapping[lang], '')
  729. log_var(cflags_mapping[lang], compile_flags)
  730. compile_flags = shlex.split(compile_flags)
  731. # Link flags (same for all languages)
  732. link_flags = os.environ.get('LDFLAGS', '')
  733. log_var('LDFLAGS', link_flags)
  734. link_flags = shlex.split(link_flags)
  735. if compiler_is_linker:
  736. # When the compiler is used as a wrapper around the linker (such as
  737. # with GCC and Clang), the compile flags can be needed while linking
  738. # too. This is also what Autotools does. However, we don't want to do
  739. # this when the linker is stand-alone such as with MSVC C/C++, etc.
  740. link_flags = compile_flags + link_flags
  741. # Pre-processor flags (not for fortran or D)
  742. preproc_flags = ''
  743. if lang in ('c', 'cpp', 'objc', 'objcpp'):
  744. preproc_flags = os.environ.get('CPPFLAGS', '')
  745. log_var('CPPFLAGS', preproc_flags)
  746. preproc_flags = shlex.split(preproc_flags)
  747. compile_flags += preproc_flags
  748. return preproc_flags, compile_flags, link_flags
  749. class CrossBuildInfo:
  750. def __init__(self, filename):
  751. self.config = {'properties': {}}
  752. self.parse_datafile(filename)
  753. if 'target_machine' in self.config:
  754. return
  755. if 'host_machine' not in self.config:
  756. raise mesonlib.MesonException('Cross info file must have either host or a target machine.')
  757. if 'binaries' not in self.config:
  758. raise mesonlib.MesonException('Cross file is missing "binaries".')
  759. def ok_type(self, i):
  760. return isinstance(i, (str, int, bool))
  761. def parse_datafile(self, filename):
  762. config = configparser.ConfigParser()
  763. config.read(filename)
  764. # This is a bit hackish at the moment.
  765. for s in config.sections():
  766. self.config[s] = {}
  767. for entry in config[s]:
  768. value = config[s][entry]
  769. if ' ' in entry or '\t' in entry or "'" in entry or '"' in entry:
  770. raise EnvironmentException('Malformed variable name %s in cross file..' % entry)
  771. try:
  772. res = eval(value, {'__builtins__': None}, {'true': True, 'false': False})
  773. except Exception:
  774. raise EnvironmentException('Malformed value in cross file variable %s.' % entry)
  775. if self.ok_type(res):
  776. self.config[s][entry] = res
  777. elif isinstance(res, list):
  778. for i in res:
  779. if not self.ok_type(i):
  780. raise EnvironmentException('Malformed value in cross file variable %s.' % entry)
  781. self.config[s][entry] = res
  782. else:
  783. raise EnvironmentException('Malformed value in cross file variable %s.' % entry)
  784. def has_host(self):
  785. return 'host_machine' in self.config
  786. def has_target(self):
  787. return 'target_machine' in self.config
  788. def has_stdlib(self, language):
  789. return language + '_stdlib' in self.config['properties']
  790. def get_stdlib(self, language):
  791. return self.config['properties'][language + '_stdlib']
  792. def get_properties(self):
  793. return self.config['properties']
  794. # Wehn compiling a cross compiler we use the native compiler for everything.
  795. # But not when cross compiling a cross compiler.
  796. def need_cross_compiler(self):
  797. return 'host_machine' in self.config
  798. def need_exe_wrapper(self):
  799. value = self.config['properties'].get('needs_exe_wrapper', None)
  800. if value is not None:
  801. return value
  802. # Can almost always run 32-bit binaries on 64-bit natively if the host
  803. # and build systems are the same. We don't pass any compilers to
  804. # detect_cpu_family() here because we always want to know the OS
  805. # architecture, not what the compiler environment tells us.
  806. if self.has_host() and detect_cpu_family({}) == 'x86_64' and \
  807. self.config['host_machine']['cpu_family'] == 'x86' and \
  808. self.config['host_machine']['system'] == detect_system():
  809. return False
  810. return True
  811. class MachineInfo:
  812. def __init__(self, system, cpu_family, cpu, endian):
  813. self.system = system
  814. self.cpu_family = cpu_family
  815. self.cpu = cpu
  816. self.endian = endian