environment.py 42 KB

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