environment.py 39 KB

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