Debian Codegraph @

unittests/machinefiletests.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2016-2021 The Meson development team
3
4 from __future__ import annotations
5
6 import subprocess
7 import tempfile
8 import textwrap
9 import os
10 import shutil
11 import functools
12 import threading
13 import sys
14 from itertools import chain
15 from unittest import mock, skipIf, SkipTest, TestCase
16 from pathlib import Path, PurePath
17 import typing as T
18
19 import mesonbuild.mlog
20 import mesonbuild.depfile
21 import mesonbuild.dependencies.factory
22 import mesonbuild.envconfig
23 import mesonbuild.environment
24 import mesonbuild.coredata
25 import mesonbuild.modules.gnome
26 from mesonbuild import mesonlib
27 from mesonbuild import machinefile
28
29 from mesonbuild.mesonlib import (
30 MachineChoice, is_windows, is_osx, is_cygwin, is_haiku, is_sunos
31 )
32 from mesonbuild.compilers import (
33 detect_swift_compiler, compiler_from_language
34 )
35 import mesonbuild.modules.pkgconfig
36
37
38 from run_tests import (
39 Backend,
40 get_fake_env
41 )
42
43 from .baseplatformtests import BasePlatformTests
44 from .helpers import *
45
46 @functools.lru_cache()
47 def is_real_gnu_compiler(path):
48 '''
49 Check if the gcc we have is a real gcc and not a macOS wrapper around clang
50 '''
51 if not path:
52 return False
53 out = subprocess.check_output([path, '--version'], encoding='utf-8', universal_newlines=True, stderr=subprocess.STDOUT)
54 return 'Free Software Foundation' in out
55
56 cross_dir = Path(__file__).parent.parent / 'cross'
57
58 class MachineFileStoreTests(TestCase):
59
60 def test_loading(self):
61 store = machinefile.MachineFileStore([cross_dir / 'ubuntu-armhf.txt'], [], str(cross_dir))
62 self.assertIsNotNone(store)
63
64 def test_home_variable(self):
65 """Test that ~ expands to the user's home directory."""
66 with tempfile.NamedTemporaryFile(mode='w', suffix='.ini', delete=False) as f:
67 f.write(textwrap.dedent('''\
68 [constants]
69 toolchain = ~ / 'sdk'
70
71 [binaries]
72 c = ~ / 'bin' / 'gcc'
73 cpp = toolchain / 'bin' / 'g++'
74 '''))
75 fname = f.name
76
77 try:
78 parser = machinefile.MachineFileParser([fname], '/tmp')
79 if sys.platform in ('linux', 'darwin'):
80 home = PurePath(os.environ['HOME'])
81 elif sys.platform in ('win32', 'cygwin'):
82 # Even with MSYS2 and Cygwin, we must use the windows-native homedir
83 # https://github.com/mesonbuild/meson/pull/15524#issuecomment-3864016608
84 if 'USER' not in os.environ:
85 raise SkipTest('No USER in env')
86 home = PurePath('C:\\', 'Users', os.environ['USER'])
87 else:
88 raise SkipTest('Don\'t know how to get homedir')
89
90 # Check that ~ expands correctly in binaries section
91 self.assertEqual(parser.sections['binaries']['c'], str(home / 'bin' / 'gcc'))
92 self.assertEqual(parser.sections['binaries']['cpp'], str(home / 'sdk' / 'bin' / 'g++'))
93 finally:
94 os.unlink(fname)
95
96 class NativeFileTests(BasePlatformTests):
97
98 def setUp(self):
99 super().setUp()
100 self.testcase = os.path.join(self.unit_test_dir, '46 native file binary')
101 self.current_config = 0
102 self.current_wrapper = 0
103
104 def helper_create_native_file(self, values: T.Dict[str, T.Dict[str, T.Union[str, int, float, bool, T.Sequence[T.Union[str, int, float, bool]]]]]) -> str:
105 """Create a config file as a temporary file.
106
107 values should be a nested dictionary structure of {section: {key:
108 value}}
109 """
110 filename = os.path.join(self.builddir, f'generated{self.current_config}.config')
111 self.current_config += 1
112 with open(filename, 'wt', encoding='utf-8') as f:
113 for section, entries in values.items():
114 f.write(f'[{section}]\n')
115 for k, v in entries.items():
116 if isinstance(v, (bool, int, float)):
117 f.write(f"{k}={v}\n")
118 elif isinstance(v, str):
119 f.write(f"{k}='{v}'\n")
120 else:
121 f.write("{}=[{}]\n".format(k, ', '.join([f"'{w}'" for w in v])))
122 return filename
123
124 def helper_create_binary_wrapper(self, binary, dir_=None, extra_args=None, **kwargs):
125 """Creates a wrapper around a binary that overrides specific values."""
126 filename = os.path.join(dir_ or self.builddir, f'binary_wrapper{self.current_wrapper}.py')
127 extra_args = extra_args or {}
128 self.current_wrapper += 1
129 if is_haiku():
130 chbang = '#!/bin/env python3'
131 else:
132 chbang = '#!/usr/bin/env python3'
133
134 with open(filename, 'wt', encoding='utf-8') as f:
135 f.write(textwrap.dedent('''\
136 {}
137 import argparse
138 import subprocess
139 import sys
140
141 def main():
142 parser = argparse.ArgumentParser()
143 '''.format(chbang)))
144 for name in chain(extra_args, kwargs):
145 f.write(' parser.add_argument("-{0}", "--{0}", action="store_true")\n'.format(name))
146 f.write(' args, extra_args = parser.parse_known_args()\n')
147 for name, value in chain(extra_args.items(), kwargs.items()):
148 f.write(f' if args.{name}:\n')
149 f.write(' print("{}", file=sys.{})\n'.format(value, kwargs.get('outfile', 'stdout')))
150 f.write(' sys.exit(0)\n')
151 f.write(textwrap.dedent('''
152 ret = subprocess.run(
153 ["{}"] + extra_args,
154 stdout=subprocess.PIPE,
155 stderr=subprocess.PIPE)
156 print(ret.stdout.decode('utf-8'))
157 print(ret.stderr.decode('utf-8'), file=sys.stderr)
158 sys.exit(ret.returncode)
159
160 if __name__ == '__main__':
161 main()
162 '''.format(binary)))
163
164 if not is_windows():
165 os.chmod(filename, 0o755)
166 return filename
167
168 # On windows we need yet another level of indirection, as cmd cannot
169 # invoke python files itself, so instead we generate a .bat file, which
170 # invokes our python wrapper
171 batfile = os.path.join(self.builddir, f'binary_wrapper{self.current_wrapper}.bat')
172 with open(batfile, 'wt', encoding='utf-8') as f:
173 f.write(fr'@{sys.executable} {filename} %*')
174 return batfile
175
176 def helper_for_compiler(self, lang, cb, for_machine = MachineChoice.HOST):
177 """Helper for generating tests for overriding compilers for languages
178 with more than one implementation, such as C, C++, ObjC, ObjC++, and D.
179 """
180 env = get_fake_env()
181 getter = lambda: compiler_from_language(env, lang, for_machine)
182 cc = getter()
183 binary, newid = cb(cc)
184 env.binaries[for_machine].binaries[lang] = binary
185 compiler = getter()
186 self.assertEqual(compiler.id, newid)
187
188 def test_multiple_native_files_override(self):
189 wrapper = self.helper_create_binary_wrapper('bash', version='foo')
190 config = self.helper_create_native_file({'binaries': {'bash': wrapper}})
191 wrapper = self.helper_create_binary_wrapper('bash', version='12345')
192 config2 = self.helper_create_native_file({'binaries': {'bash': wrapper}})
193 self.init(self.testcase, extra_args=[
194 '--native-file', config, '--native-file', config2,
195 '-Dcase=find_program'])
196
197 # This test hangs on cygwin.
198 @skipIf(os.name != 'posix' or is_cygwin(), 'Uses fifos, which are not available on non Unix OSes.')
199 def test_native_file_is_pipe(self):
200 fifo = os.path.join(self.builddir, 'native.file')
201 os.mkfifo(fifo)
202 with tempfile.TemporaryDirectory() as d:
203 wrapper = self.helper_create_binary_wrapper('bash', d, version='12345')
204
205 def filler():
206 with open(fifo, 'w', encoding='utf-8') as f:
207 f.write('[binaries]\n')
208 f.write(f"bash = '{wrapper}'\n")
209
210 thread = threading.Thread(target=filler)
211 thread.start()
212
213 self.init(self.testcase, extra_args=['--native-file', fifo, '-Dcase=find_program'])
214
215 thread.join()
216 os.unlink(fifo)
217
218 self.init(self.testcase, extra_args=['--wipe'])
219
220 def test_multiple_native_files(self):
221 wrapper = self.helper_create_binary_wrapper('bash', version='12345')
222 config = self.helper_create_native_file({'binaries': {'bash': wrapper}})
223 wrapper = self.helper_create_binary_wrapper('python')
224 config2 = self.helper_create_native_file({'binaries': {'python': wrapper}})
225 self.init(self.testcase, extra_args=[
226 '--native-file', config, '--native-file', config2,
227 '-Dcase=find_program'])
228
229 def _simple_test(self, case, binary, entry=None):
230 wrapper = self.helper_create_binary_wrapper(binary, version='12345')
231 config = self.helper_create_native_file({'binaries': {entry or binary: wrapper}})
232 self.init(self.testcase, extra_args=['--native-file', config, f'-Dcase={case}'])
233
234 def test_find_program(self):
235 self._simple_test('find_program', 'bash')
236
237 @skipIfNoExecutable('llvm-config')
238 def test_config_tool_dep(self):
239 # Do the skip at this level to avoid screwing up the cache
240 if mesonbuild.envconfig.detect_msys2_arch():
241 raise SkipTest('Skipped due to problems with LLVM on MSYS2')
242 self._simple_test('config_dep', 'llvm-config')
243
244 def test_python3_module(self):
245 self._simple_test('python3', 'python3')
246
247 def test_python_module(self):
248 if is_windows():
249 # Bat adds extra crap to stdout, so the version check logic in the
250 # python module breaks. This is fine on other OSes because they
251 # don't need the extra indirection.
252 raise SkipTest('bat indirection breaks internal sanity checks.')
253 elif is_osx():
254 binary = 'python'
255 if not shutil.which(binary):
256 raise SkipTest('Not running Python2 tests because it was not found.')
257 else:
258 binary = 'python2'
259 if not shutil.which(binary):
260 raise SkipTest('Not running Python2 tests because it was not found.')
261
262 # We not have python2, check for it
263 for v in ['2', '2.7', '-2.7']:
264 try:
265 rc = subprocess.call(['pkg-config', '--cflags', f'python{v}'],
266 stdout=subprocess.DEVNULL,
267 stderr=subprocess.DEVNULL)
268 except FileNotFoundError:
269 raise SkipTest('Not running Python 2 tests because pkg-config not found.')
270 if rc == 0:
271 break
272 else:
273 raise SkipTest('Not running Python 2 tests because dev packages not installed.')
274 self._simple_test('python', binary, entry='python')
275
276 @skipIf(is_windows(), 'Setting up multiple compilers on windows is hard')
277 @skip_if_env_set('CC')
278 def test_c_compiler(self):
279 def cb(comp):
280 if comp.id == 'gcc':
281 if not shutil.which('clang'):
282 raise SkipTest('Only one compiler found, cannot test.')
283 return 'clang', 'clang'
284 if not is_real_gnu_compiler(shutil.which('gcc')):
285 raise SkipTest('Only one compiler found, cannot test.')
286 return 'gcc', 'gcc'
287 self.helper_for_compiler('c', cb)
288
289 @skipIf(is_windows(), 'Setting up multiple compilers on windows is hard')
290 @skip_if_env_set('CXX')
291 def test_cpp_compiler(self):
292 def cb(comp):
293 if comp.id == 'gcc':
294 if not shutil.which('clang++'):
295 raise SkipTest('Only one compiler found, cannot test.')
296 return 'clang++', 'clang'
297 if not is_real_gnu_compiler(shutil.which('g++')):
298 raise SkipTest('Only one compiler found, cannot test.')
299 return 'g++', 'gcc'
300 self.helper_for_compiler('cpp', cb)
301
302 @skip_if_not_language('objc')
303 @skip_if_env_set('OBJC')
304 def test_objc_compiler(self):
305 def cb(comp):
306 if comp.id == 'gcc':
307 if not shutil.which('clang'):
308 raise SkipTest('Only one compiler found, cannot test.')
309 return 'clang', 'clang'
310 if not is_real_gnu_compiler(shutil.which('gcc')):
311 raise SkipTest('Only one compiler found, cannot test.')
312 return 'gcc', 'gcc'
313 try:
314 self.helper_for_compiler('objc', cb)
315 except mesonlib.EnvironmentException as e:
316 if 'GCC was not built with support for objective-c' in str(e):
317 raise unittest.SkipTest("GCC doesn't support objective-c, test cannot run")
318 raise
319
320 @skip_if_not_language('objcpp')
321 @skip_if_env_set('OBJCXX')
322 def test_objcpp_compiler(self):
323 def cb(comp):
324 if comp.id == 'gcc':
325 if not shutil.which('clang++'):
326 raise SkipTest('Only one compiler found, cannot test.')
327 return 'clang++', 'clang'
328 if not is_real_gnu_compiler(shutil.which('g++')):
329 raise SkipTest('Only one compiler found, cannot test.')
330 return 'g++', 'gcc'
331 try:
332 self.helper_for_compiler('objcpp', cb)
333 except mesonlib.EnvironmentException as e:
334 if 'GCC was not built with support for objective-c++' in str(e):
335 raise unittest.SkipTest("G++ doesn't support objective-c++, test cannot run")
336 raise
337
338 @skip_if_not_language('d')
339 @skip_if_env_set('DC')
340 def test_d_compiler(self):
341 def cb(comp):
342 if comp.id == 'dmd':
343 if shutil.which('ldc'):
344 return 'ldc', 'ldc'
345 elif shutil.which('gdc'):
346 return 'gdc', 'gdc'
347 else:
348 raise SkipTest('No alternative dlang compiler found.')
349 if shutil.which('dmd'):
350 return 'dmd', 'dmd'
351 raise SkipTest('No alternative dlang compiler found.')
352 self.helper_for_compiler('d', cb)
353
354 @skip_if_not_language('cs')
355 @skip_if_env_set('CSC')
356 def test_cs_compiler(self):
357 def cb(comp):
358 if comp.id == 'csc':
359 if not shutil.which('mcs'):
360 raise SkipTest('No alternate C# implementation.')
361 return 'mcs', 'mcs'
362 if not shutil.which('csc'):
363 raise SkipTest('No alternate C# implementation.')
364 return 'csc', 'csc'
365 self.helper_for_compiler('cs', cb)
366
367 @skip_if_not_language('fortran')
368 @skip_if_env_set('FC')
369 def test_fortran_compiler(self):
370 def cb(comp):
371 if comp.id == 'lcc':
372 if shutil.which('lfortran'):
373 return 'lfortran', 'lcc'
374 raise SkipTest('No alternate Fortran implementation.')
375 elif comp.id == 'gcc':
376 if shutil.which('ifort'):
377 # There is an ICC for windows (windows build, linux host),
378 # but we don't support that ATM so let's not worry about it.
379 if is_windows():
380 return 'ifort', 'intel-cl'
381 return 'ifort', 'intel'
382 elif shutil.which('flang'):
383 return 'flang', 'flang'
384 elif shutil.which('pgfortran'):
385 return 'pgfortran', 'pgi'
386 # XXX: there are several other fortran compilers meson
387 # supports, but I don't have any of them to test with
388 raise SkipTest('No alternate Fortran implementation.')
389 if not shutil.which('gfortran'):
390 raise SkipTest('No alternate Fortran implementation.')
391 return 'gfortran', 'gcc'
392 self.helper_for_compiler('fortran', cb)
393
394 def _single_implementation_compiler(self, lang: str, binary: str, version_str: str, version: str) -> None:
395 """Helper for languages with a single (supported) implementation.
396
397 Builds a wrapper around the compiler to override the version.
398 """
399 wrapper = self.helper_create_binary_wrapper(binary, version=version_str)
400 env = get_fake_env()
401 env.binaries.host.binaries[lang] = [wrapper]
402 compiler = compiler_from_language(env, lang, MachineChoice.HOST)
403 self.assertEqual(compiler.version, version)
404
405 @skip_if_not_language('vala')
406 @skip_if_env_set('VALAC')
407 def test_vala_compiler(self):
408 self._single_implementation_compiler(
409 'vala', 'valac', 'Vala 1.2345', '1.2345')
410
411 @skip_if_not_language('rust')
412 @skip_if_env_set('RUSTC')
413 def test_rust_compiler(self):
414 self._single_implementation_compiler(
415 'rust', 'rustc', 'rustc 1.2345', '1.2345')
416
417 @skip_if_not_language('java')
418 def test_java_compiler(self):
419 self._single_implementation_compiler(
420 'java', 'javac', 'javac 9.99.77', '9.99.77')
421
422 @skip_if_not_language('java')
423 def test_java_classpath(self):
424 if self.backend is not Backend.ninja:
425 raise SkipTest('Jar is only supported with Ninja')
426 testdir = os.path.join(self.unit_test_dir, '112 classpath')
427 self.init(testdir)
428 self.build()
429 one_build_path = get_classpath(os.path.join(self.builddir, 'one.jar'))
430 self.assertIsNone(one_build_path)
431 two_build_path = get_classpath(os.path.join(self.builddir, 'two.jar'))
432 self.assertEqual(two_build_path, 'one.jar')
433 self.install()
434 one_install_path = get_classpath(os.path.join(self.installdir, 'usr/bin/one.jar'))
435 self.assertIsNone(one_install_path)
436 two_install_path = get_classpath(os.path.join(self.installdir, 'usr/bin/two.jar'))
437 self.assertIsNone(two_install_path)
438
439 @skip_if_not_language('swift')
440 def test_swift_compiler(self):
441 wrapper = self.helper_create_binary_wrapper(
442 'swiftc', version='Swift 1.2345', outfile='stderr',
443 extra_args={'Xlinker': 'macosx_version. PROJECT:ld - 1.2.3'})
444 env = get_fake_env()
445 env.binaries.host.binaries['swift'] = [wrapper]
446 compiler = detect_swift_compiler(env, MachineChoice.HOST)
447 self.assertEqual(compiler.version, '1.2345')
448
449 def test_native_file_dirs(self):
450 testcase = os.path.join(self.unit_test_dir, '59 native file override')
451 self.init(testcase, default_args=False,
452 extra_args=['--native-file', os.path.join(testcase, 'nativefile')])
453
454 def test_native_file_dirs_overridden(self):
455 testcase = os.path.join(self.unit_test_dir, '59 native file override')
456 self.init(testcase, default_args=False,
457 extra_args=['--native-file', os.path.join(testcase, 'nativefile'),
458 '-Ddef_libdir=liblib', '-Dlibdir=liblib'])
459
460 def test_compile_sys_path(self):
461 """Compiling with a native file stored in a system path works.
462
463 There was a bug which caused the paths to be stored incorrectly and
464 would result in ninja invoking meson in an infinite loop. This tests
465 for that by actually invoking ninja.
466 """
467 testcase = os.path.join(self.common_test_dir, '1 trivial')
468
469 # It really doesn't matter what's in the native file, just that it exists
470 config = self.helper_create_native_file({'binaries': {'bash': 'false'}})
471
472 self.init(testcase, extra_args=['--native-file', config])
473 self.build()
474
475 def test_user_options(self):
476 testcase = os.path.join(self.common_test_dir, '40 options')
477 for opt, value in [('testoption', 'some other val'), ('other_one', True),
478 ('combo_opt', 'one'), ('array_opt', ['two']),
479 ('integer_opt', 0),
480 ('CaseSenSiTivE', 'SOME other Value'),
481 ('CASESENSITIVE', 'some other Value')]:
482 config = self.helper_create_native_file({'project options': {opt: value}})
483 with self.assertRaises(subprocess.CalledProcessError) as cm:
484 self.init(testcase, extra_args=['--native-file', config])
485 self.assertRegex(cm.exception.stdout, r'Incorrect value to [a-z]+ option')
486
487 def test_user_options_command_line_overrides(self):
488 testcase = os.path.join(self.common_test_dir, '40 options')
489 config = self.helper_create_native_file({'project options': {'other_one': True}})
490 self.init(testcase, extra_args=['--native-file', config, '-Dother_one=false'])
491
492 def test_user_options_subproject(self):
493 testcase = os.path.join(self.unit_test_dir, '78 user options for subproject')
494
495 s = os.path.join(testcase, 'subprojects')
496 if not os.path.exists(s):
497 os.mkdir(s)
498 s = os.path.join(s, 'sub')
499 if not os.path.exists(s):
500 sub = os.path.join(self.common_test_dir, '40 options')
501 shutil.copytree(sub, s)
502
503 for opt, value in [('testoption', 'some other val'), ('other_one', True),
504 ('combo_opt', 'one'), ('array_opt', ['two']),
505 ('integer_opt', 0)]:
506 config = self.helper_create_native_file({'sub:project options': {opt: value}})
507 with self.assertRaises(subprocess.CalledProcessError) as cm:
508 self.init(testcase, extra_args=['--native-file', config])
509 self.assertRegex(cm.exception.stdout, r'Incorrect value to [a-z]+ option')
510
511 def test_option_bool(self):
512 # Bools are allowed to be unquoted
513 testcase = os.path.join(self.common_test_dir, '1 trivial')
514 config = self.helper_create_native_file({'built-in options': {'werror': True}})
515 self.init(testcase, extra_args=['--native-file', config])
516 configuration = self.introspect('--buildoptions')
517 for each in configuration:
518 # Test that no-per subproject options are inherited from the parent
519 if 'werror' in each['name']:
520 self.assertEqual(each['value'], True)
521 break
522 else:
523 self.fail('Did not find werror in build options?')
524
525 def test_option_integer(self):
526 # Bools are allowed to be unquoted
527 testcase = os.path.join(self.common_test_dir, '1 trivial')
528 config = self.helper_create_native_file({'built-in options': {'unity_size': 100}})
529 self.init(testcase, extra_args=['--native-file', config])
530 configuration = self.introspect('--buildoptions')
531 for each in configuration:
532 # Test that no-per subproject options are inherited from the parent
533 if 'unity_size' in each['name']:
534 self.assertEqual(each['value'], 100)
535 break
536 else:
537 self.fail('Did not find unity_size in build options?')
538
539 def test_builtin_options(self):
540 testcase = os.path.join(self.common_test_dir, '2 cpp')
541 config = self.helper_create_native_file({'built-in options': {'cpp_std': 'c++14'}})
542
543 self.init(testcase, extra_args=['--native-file', config])
544 configuration = self.introspect('--buildoptions')
545 for each in configuration:
546 if each['name'] == 'cpp_std':
547 self.assertEqual(each['value'], 'c++14')
548 break
549 else:
550 self.fail('Did not find werror in build options?')
551
552 def test_builtin_options_conf_overrides_env(self):
553 testcase = os.path.join(self.common_test_dir, '2 cpp')
554 config = self.helper_create_native_file({'built-in options': {'pkg_config_path': '/foo'}})
555
556 self.init(testcase, extra_args=['--native-file', config], override_envvars={'PKG_CONFIG_PATH': '/bar'})
557 configuration = self.introspect('--buildoptions')
558 for each in configuration:
559 if each['name'] == 'pkg_config_path':
560 self.assertEqual(each['value'], ['/foo'])
561 break
562 else:
563 self.fail('Did not find pkg_config_path in build options?')
564
565 def test_builtin_options_subprojects(self):
566 testcase = os.path.join(self.common_test_dir, '98 subproject subdir')
567 config = self.helper_create_native_file({'built-in options': {'default_library': 'both', 'c_args': ['-Dfoo']}, 'sub:built-in options': {'default_library': 'static'}})
568
569 self.init(testcase, extra_args=['--native-file', config])
570 configuration = self.introspect('--buildoptions')
571 found = 0
572 for each in configuration:
573 # Test that no-per subproject options are inherited from the parent
574 if 'c_args' in each['name']:
575 # This path will be hit twice, once for build and once for host,
576 self.assertEqual(each['value'], ['-Dfoo'])
577 found += 1
578 elif each['name'] == 'default_library':
579 self.assertEqual(each['value'], 'both')
580 found += 1
581 elif each['name'] == 'sub:default_library':
582 self.assertEqual(each['value'], 'static')
583 found += 1
584 # FIXME: check that the subproject option has beeb added
585 # into augments.
586 self.assertEqual(found, 2, 'Did not find all two sections')
587
588 def test_builtin_options_machinefile_overrides_subproject(self):
589 # The buildfile says subproject(... default_library: static), the machinefile overrides it
590 testcase = os.path.join(self.common_test_dir, '223 persubproject options')
591 config = self.helper_create_native_file({'sub2:built-in options': {'default_library': 'shared'}})
592
593 with self.assertRaises((RuntimeError, subprocess.CalledProcessError)) as cm:
594 self.init(testcase, extra_args=['--native-file', config])
595 if isinstance(cm, RuntimeError):
596 check = str(cm.exception)
597 else:
598 check = cm.exception.stdout
599 self.assertIn(check, 'Parent should override default_library')
600
601 def test_builtin_options_machinefile_global_loses_over_subproject(self):
602 # The buildfile says subproject(... default_library: static), ensure that it overrides the machinefile
603 testcase = os.path.join(self.common_test_dir, '223 persubproject options')
604 config = self.helper_create_native_file({'built-in options': {'default_library': 'both'}})
605 self.init(testcase, extra_args=['--native-file', config])
606
607 def test_builtin_options_compiler_properties(self):
608 # the properties section can have lang_args, and those need to be
609 # overwritten by the built-in options
610 testcase = os.path.join(self.common_test_dir, '1 trivial')
611 config = self.helper_create_native_file({
612 'built-in options': {'c_args': ['-DFOO']},
613 'properties': {'c_args': ['-DBAR']},
614 })
615
616 self.init(testcase, extra_args=['--native-file', config])
617 configuration = self.introspect('--buildoptions')
618 for each in configuration:
619 if each['name'] == 'c_args':
620 self.assertEqual(each['value'], ['-DFOO'])
621 break
622 else:
623 self.fail('Did not find c_args in build options?')
624
625 def test_builtin_options_compiler_properties_legacy(self):
626 # The legacy placement in properties is still valid if a 'built-in
627 # options' setting is present, but doesn't have the lang_args
628 testcase = os.path.join(self.common_test_dir, '1 trivial')
629 config = self.helper_create_native_file({
630 'built-in options': {'default_library': 'static'},
631 'properties': {'c_args': ['-DBAR']},
632 })
633
634 self.init(testcase, extra_args=['--native-file', config])
635 configuration = self.introspect('--buildoptions')
636 for each in configuration:
637 if each['name'] == 'c_args':
638 self.assertEqual(each['value'], ['-DBAR'])
639 break
640 else:
641 self.fail('Did not find c_args in build options?')
642
643 def test_builtin_options_paths(self):
644 # the properties section can have lang_args, and those need to be
645 # overwritten by the built-in options
646 testcase = os.path.join(self.common_test_dir, '1 trivial')
647 config = self.helper_create_native_file({
648 'built-in options': {'bindir': 'foo'},
649 'paths': {'bindir': 'bar'},
650 })
651
652 self.init(testcase, extra_args=['--native-file', config])
653 configuration = self.introspect('--buildoptions')
654 for each in configuration:
655 if each['name'] == 'bindir':
656 self.assertEqual(each['value'], 'foo')
657 break
658 else:
659 self.fail('Did not find bindir in build options?')
660
661 def test_builtin_options_paths_legacy(self):
662 testcase = os.path.join(self.common_test_dir, '1 trivial')
663 config = self.helper_create_native_file({
664 'built-in options': {'default_library': 'static'},
665 'paths': {'bindir': 'bar'},
666 })
667
668 self.init(testcase, extra_args=['--native-file', config])
669 configuration = self.introspect('--buildoptions')
670 for each in configuration:
671 if each['name'] == 'bindir':
672 self.assertEqual(each['value'], 'bar')
673 break
674 else:
675 self.fail('Did not find bindir in build options?')
676
677 @skip_if_not_language('rust')
678 def test_bindgen_clang_arguments(self) -> None:
679 if self.backend is not Backend.ninja:
680 raise SkipTest('Rust is only supported with Ninja')
681
682 testcase = os.path.join(self.rust_test_dir, '12 bindgen')
683 config = self.helper_create_native_file({
684 'properties': {'bindgen_clang_arguments': 'sentinel'}
685 })
686
687 self.init(testcase, extra_args=['--native-file', config])
688 targets: T.List[T.Dict[str, T.Any]] = self.introspect('--targets')
689 for t in targets:
690 if t['id'].startswith('rustmod-bindgen'):
691 args: T.List[str] = t['target_sources'][0]['compiler']
692 self.assertIn('sentinel', args, msg="Did not find machine file value")
693 cargs_start = args.index('--')
694 sent_arg = args.index('sentinel')
695 self.assertLess(cargs_start, sent_arg, msg='sentinel argument does not come after "--"')
696 break
697 else:
698 self.fail('Did not find a bindgen target')
699
700
701 class CrossFileTests(BasePlatformTests):
702
703 """Tests for cross file functionality not directly related to
704 cross compiling.
705
706 This is mainly aimed to testing overrides from cross files.
707 """
708
709 def setUp(self):
710 super().setUp()
711 self.current_config = 0
712 self.current_wrapper = 0
713
714 def _cross_file_generator(self, *, needs_exe_wrapper: bool = False,
715 exe_wrapper: T.Optional[T.List[str]] = None) -> str:
716 if is_windows():
717 raise SkipTest('Cannot run this test on non-mingw/non-cygwin windows')
718
719 return textwrap.dedent(f"""\
720 [binaries]
721 c = '{shutil.which('gcc' if is_sunos() else 'cc')}'
722 ar = '{shutil.which('ar')}'
723 strip = '{shutil.which('strip')}'
724 exe_wrapper = {str(exe_wrapper) if exe_wrapper is not None else '[]'}
725
726 [properties]
727 needs_exe_wrapper = {needs_exe_wrapper}
728
729 [host_machine]
730 system = 'linux'
731 cpu_family = 'x86'
732 cpu = 'i686'
733 endian = 'little'
734 """)
735
736 def _stub_exe_wrapper(self) -> str:
737 return textwrap.dedent('''\
738 #!/usr/bin/env python3
739 import subprocess
740 import sys
741
742 sys.exit(subprocess.run(sys.argv[1:]).returncode)
743 ''')
744
745 def test_needs_exe_wrapper_true(self):
746 testdir = os.path.join(self.unit_test_dir, '70 cross test passed')
747 with tempfile.TemporaryDirectory() as d:
748 p = Path(d) / 'crossfile'
749 with p.open('wt', encoding='utf-8') as f:
750 f.write(self._cross_file_generator(needs_exe_wrapper=True))
751 self.init(testdir, extra_args=['--cross-file=' + str(p)])
752 out = self.run_target('test')
753 self.assertRegex(out, r'Skipped:\s*1\s*\n')
754
755 def test_needs_exe_wrapper_false(self):
756 testdir = os.path.join(self.unit_test_dir, '70 cross test passed')
757 with tempfile.TemporaryDirectory() as d:
758 p = Path(d) / 'crossfile'
759 with p.open('wt', encoding='utf-8') as f:
760 f.write(self._cross_file_generator(needs_exe_wrapper=False))
761 self.init(testdir, extra_args=['--cross-file=' + str(p)])
762 out = self.run_target('test')
763 self.assertNotRegex(out, r'Skipped:\s*1\n')
764
765 def test_needs_exe_wrapper_true_wrapper(self):
766 testdir = os.path.join(self.unit_test_dir, '70 cross test passed')
767 with tempfile.TemporaryDirectory() as d:
768 s = Path(d) / 'wrapper.py'
769 with s.open('wt', encoding='utf-8') as f:
770 f.write(self._stub_exe_wrapper())
771 s.chmod(0o774)
772 p = Path(d) / 'crossfile'
773 with p.open('wt', encoding='utf-8') as f:
774 f.write(self._cross_file_generator(
775 needs_exe_wrapper=True,
776 exe_wrapper=[str(s)]))
777
778 self.init(testdir, extra_args=['--cross-file=' + str(p), '-Dexpect=true'])
779 out = self.run_target('test')
780 self.assertRegex(out, r'Ok:\s*3\s*\n')
781
782 def test_cross_exe_passed_no_wrapper(self):
783 testdir = os.path.join(self.unit_test_dir, '70 cross test passed')
784 with tempfile.TemporaryDirectory() as d:
785 p = Path(d) / 'crossfile'
786 with p.open('wt', encoding='utf-8') as f:
787 f.write(self._cross_file_generator(needs_exe_wrapper=True))
788
789 self.init(testdir, extra_args=['--cross-file=' + str(p)])
790 self.build()
791 out = self.run_target('test')
792 self.assertRegex(out, r'Skipped:\s*1\s*\n')
793
794 # The test uses mocking and thus requires that the current process is the
795 # one to run the Meson steps. If we are using an external test executable
796 # (most commonly in Debian autopkgtests) then the mocking won't work.
797 @skipIf('MESON_EXE' in os.environ, 'MESON_EXE is defined, cannot use mocking.')
798 def test_cross_file_system_paths(self):
799 if is_windows():
800 raise SkipTest('system crossfile paths not defined for Windows (yet)')
801
802 testdir = os.path.join(self.common_test_dir, '1 trivial')
803 cross_content = self._cross_file_generator()
804 with tempfile.TemporaryDirectory() as d:
805 dir_ = os.path.join(d, 'meson', 'cross')
806 os.makedirs(dir_)
807 with tempfile.NamedTemporaryFile('w', dir=dir_, delete=False, encoding='utf-8') as f:
808 f.write(cross_content)
809 name = os.path.basename(f.name)
810
811 with self.subTest('using XDG_DATA_HOME'):
812 with mock.patch.dict(os.environ, {'XDG_DATA_HOME': d}):
813 self.init(testdir, extra_args=['--cross-file=' + name], inprocess=True)
814 self.wipe()
815
816 with self.subTest('using XDG_DATA_DIRS'):
817 with mock.patch.dict(os.environ, {'XDG_DATA_DIRS': d}):
818 os.environ.pop('XDG_DATA_HOME', None)
819 self.init(testdir, extra_args=['--cross-file=' + name], inprocess=True)
820 self.wipe()
821
822 with tempfile.TemporaryDirectory() as d:
823 dir_ = os.path.join(d, '.local', 'share', 'meson', 'cross')
824 os.makedirs(dir_)
825 with tempfile.NamedTemporaryFile('w', dir=dir_, delete=False, encoding='utf-8') as f:
826 f.write(cross_content)
827 name = os.path.basename(f.name)
828
829 # If XDG_DATA_HOME is set in the environment running the
830 # tests this test will fail, os mock the environment, pop
831 # it, then test
832 with self.subTest('env vars unset'):
833 with mock.patch.dict(os.environ):
834 os.environ.pop('XDG_DATA_HOME', None)
835 with mock.patch('mesonbuild.coredata.os.path.expanduser', lambda x: x.replace('~', d)):
836 self.init(testdir, extra_args=['--cross-file=' + name], inprocess=True)
837 self.wipe()
838
839 def helper_create_cross_file(self, values: T.Dict[str, T.Dict[str, T.Any]]) -> str:
840 """Create a config file as a temporary file.
841
842 values should be a nested dictionary structure of {section: {key:
843 value}}
844 """
845 filename = os.path.join(self.builddir, f'generated{self.current_config}.config')
846 self.current_config += 1
847 with open(filename, 'wt', encoding='utf-8') as f:
848 for section, entries in values.items():
849 f.write(f'[{section}]\n')
850 for k, v in entries.items():
851 f.write(f"{k}={v!r}\n")
852 return filename
853
854 def test_cross_file_dirs(self):
855 testcase = os.path.join(self.unit_test_dir, '59 native file override')
856 self.init(testcase, default_args=False,
857 extra_args=['--native-file', os.path.join(testcase, 'nativefile'),
858 '--cross-file', os.path.join(testcase, 'crossfile'),
859 '-Ddef_bindir=binbar',
860 '-Ddef_datadir=databar',
861 '-Ddef_includedir=includebar',
862 '-Ddef_infodir=infobar',
863 '-Ddef_libdir=libbar',
864 '-Ddef_libexecdir=libexecbar',
865 '-Ddef_localedir=localebar',
866 '-Ddef_localstatedir=localstatebar',
867 '-Ddef_mandir=manbar',
868 '-Ddef_sbindir=sbinbar',
869 '-Ddef_sharedstatedir=sharedstatebar',
870 '-Ddef_sysconfdir=sysconfbar'])
871
872 def test_cross_file_dirs_overridden(self):
873 testcase = os.path.join(self.unit_test_dir, '59 native file override')
874 self.init(testcase, default_args=False,
875 extra_args=['--native-file', os.path.join(testcase, 'nativefile'),
876 '--cross-file', os.path.join(testcase, 'crossfile'),
877 '-Ddef_libdir=liblib', '-Dlibdir=liblib',
878 '-Ddef_bindir=binbar',
879 '-Ddef_datadir=databar',
880 '-Ddef_includedir=includebar',
881 '-Ddef_infodir=infobar',
882 '-Ddef_libexecdir=libexecbar',
883 '-Ddef_localedir=localebar',
884 '-Ddef_localstatedir=localstatebar',
885 '-Ddef_mandir=manbar',
886 '-Ddef_sbindir=sbinbar',
887 '-Ddef_sharedstatedir=sharedstatebar',
888 '-Ddef_sysconfdir=sysconfbar'])
889
890 def test_cross_file_dirs_chain(self):
891 # crossfile2 overrides crossfile overrides nativefile
892 testcase = os.path.join(self.unit_test_dir, '59 native file override')
893 self.init(testcase, default_args=False,
894 extra_args=['--native-file', os.path.join(testcase, 'nativefile'),
895 '--cross-file', os.path.join(testcase, 'crossfile'),
896 '--cross-file', os.path.join(testcase, 'crossfile2'),
897 '-Ddef_bindir=binbar2',
898 '-Ddef_datadir=databar',
899 '-Ddef_includedir=includebar',
900 '-Ddef_infodir=infobar',
901 '-Ddef_libdir=libbar',
902 '-Ddef_libexecdir=libexecbar',
903 '-Ddef_localedir=localebar',
904 '-Ddef_localstatedir=localstatebar',
905 '-Ddef_mandir=manbar',
906 '-Ddef_sbindir=sbinbar',
907 '-Ddef_sharedstatedir=sharedstatebar',
908 '-Ddef_sysconfdir=sysconfbar'])
909
910 def test_user_options(self):
911 # This is just a touch test for cross file, since the implementation
912 # shares code after loading from the files
913 testcase = os.path.join(self.common_test_dir, '40 options')
914 config = self.helper_create_cross_file({'project options': {'testoption': 'some other value'}})
915 with self.assertRaises(subprocess.CalledProcessError) as cm:
916 self.init(testcase, extra_args=['--cross-file', config])
917 self.assertRegex(cm.exception.stdout, r'Incorrect value to [a-z]+ option')
918
919 def test_builtin_options(self):
920 testcase = os.path.join(self.common_test_dir, '2 cpp')
921 config = self.helper_create_cross_file({'built-in options': {'cpp_std': 'c++14'}})
922
923 self.init(testcase, extra_args=['--cross-file', config])
924 configuration = self.introspect('--buildoptions')
925 for each in configuration:
926 if each['name'] == 'cpp_std':
927 self.assertEqual(each['value'], 'c++14')
928 break
929 else:
930 self.fail('No c++ standard set?')
931
932 def test_builtin_options_per_machine(self):
933 """Test options that are allowed to be set on a per-machine basis.
934
935 Such options could be passed twice, once for the build machine, and
936 once for the host machine. I've picked pkg-config path, but any would
937 do that can be set for both.
938 """
939 testcase = os.path.join(self.common_test_dir, '2 cpp')
940 cross = self.helper_create_cross_file({'built-in options': {'pkg_config_path': '/cross/path', 'cpp_std': 'c++17'}})
941 native = self.helper_create_cross_file({'built-in options': {'pkg_config_path': '/native/path', 'cpp_std': 'c++14'}})
942
943 # Ensure that PKG_CONFIG_PATH is not set in the environment
944 with mock.patch.dict('os.environ'):
945 for k in ['PKG_CONFIG_PATH', 'PKG_CONFIG_PATH_FOR_BUILD']:
946 try:
947 del os.environ[k]
948 except KeyError:
949 pass
950 self.init(testcase, extra_args=['--cross-file', cross, '--native-file', native])
951
952 configuration = self.introspect('--buildoptions')
953 found = 0
954 for each in configuration:
955 if each['name'] == 'pkg_config_path':
956 self.assertEqual(each['value'], ['/cross/path'])
957 found += 1
958 elif each['name'] == 'cpp_std':
959 self.assertEqual(each['value'], 'c++17')
960 found += 1
961 elif each['name'] == 'build.pkg_config_path':
962 self.assertEqual(each['value'], ['/native/path'])
963 found += 1
964 elif each['name'] == 'build.cpp_std':
965 self.assertEqual(each['value'], 'c++14')
966 found += 1
967
968 if found == 4:
969 break
970 self.assertEqual(found, 4, 'Did not find all sections.')
971
972 def test_builtin_options_conf_overrides_env(self):
973 testcase = os.path.join(self.common_test_dir, '2 cpp')
974 config = self.helper_create_cross_file({'built-in options': {'pkg_config_path': '/native', 'cpp_args': '-DFILE'}})
975 cross = self.helper_create_cross_file({'built-in options': {'pkg_config_path': '/cross', 'cpp_args': '-DFILE'}})
976
977 self.init(testcase, extra_args=['--native-file', config, '--cross-file', cross],
978 override_envvars={'PKG_CONFIG_PATH': '/bar', 'PKG_CONFIG_PATH_FOR_BUILD': '/dir',
979 'CXXFLAGS': '-DENV', 'CXXFLAGS_FOR_BUILD': '-DENV'})
980 configuration = self.introspect('--buildoptions')
981 found = 0
982 expected = 4
983 for each in configuration:
984 if each['name'] == 'pkg_config_path':
985 self.assertEqual(each['value'], ['/cross'])
986 found += 1
987 elif each['name'] == 'build.pkg_config_path':
988 self.assertEqual(each['value'], ['/native'])
989 found += 1
990 elif each['name'].endswith('cpp_args'):
991 self.assertEqual(each['value'], ['-DFILE'])
992 found += 1
993 if found == expected:
994 break
995 self.assertEqual(found, expected, 'Did not find all sections.')
996
997 def test_for_build_env_vars(self) -> None:
998 testcase = os.path.join(self.common_test_dir, '2 cpp')
999 config = self.helper_create_cross_file({'built-in options': {}})
1000 cross = self.helper_create_cross_file({'built-in options': {}})
1001
1002 self.init(testcase, extra_args=['--native-file', config, '--cross-file', cross],
1003 override_envvars={'PKG_CONFIG_PATH': '/bar', 'PKG_CONFIG_PATH_FOR_BUILD': '/dir'})
1004 configuration = self.introspect('--buildoptions')
1005 found = 0
1006 for each in configuration:
1007 if each['name'] == 'pkg_config_path':
1008 self.assertEqual(each['value'], ['/bar'])
1009 found += 1
1010 elif each['name'] == 'build.pkg_config_path':
1011 self.assertEqual(each['value'], ['/dir'])
1012 found += 1
1013 if found == 2:
1014 break
1015 self.assertEqual(found, 2, 'Did not find all sections.')
1016
1017 def test_external_property_build_machine_native(self):
1018 testdir = os.path.join(self.unit_test_dir, '137 external property nonexisting')
1019 self.meson_native_files = [os.path.join(testdir, "propfile")]
1020 out = self.init(testdir, allow_fail=True, extra_args=['-Dnative=true'])
1021 self.assertIn('Unknown property for host machine: nonexisting', out)
1022
1023 def test_external_property_host_machine_native(self):
1024 testdir = os.path.join(self.unit_test_dir, '137 external property nonexisting')
1025 self.meson_native_files = [os.path.join(testdir, "propfile")]
1026 out = self.init(testdir, allow_fail=True, extra_args=['-Dnative=false'])
1027 self.assertIn('Unknown property for host machine: nonexisting', out)
1028
1029 def test_external_property_build_machine_cross(self):
1030 # meson.get_external_property(..., native : true) refers to the build
1031 # machine. In a cross build the build and host machines are distinct, so
1032 # the error for a missing property must refer to the build machine.
1033 crossdir = os.path.join(self.unit_test_dir, '69 cross')
1034 # Reuse the cross test project to generate a native and a cross file
1035 # describing this machine, so the configuration below is treated as a
1036 # cross build (see test_identity_cross).
1037 self.init(crossdir, extra_args=['-Dgenerate=true'])
1038
1039 nativefile = os.path.join(self.builddir, "nativefile")
1040 crossfile = os.path.join(self.builddir, "crossfile")
1041
1042 self.new_builddir()
1043 testdir = os.path.join(self.unit_test_dir, '137 external property nonexisting')
1044 self.meson_native_files = [nativefile, os.path.join(testdir, "propfile")]
1045 self.meson_cross_files = [crossfile]
1046 out = self.init(testdir, allow_fail=True, extra_args=['-Dnative=true'])
1047 self.assertIn('Unknown property for build machine: nonexisting', out)
1048
1049 self.new_builddir()
1050 testdir = os.path.join(self.unit_test_dir, '137 external property nonexisting')
1051 self.meson_native_files = [nativefile]
1052 self.meson_cross_files = [crossfile, os.path.join(testdir, "propfile")]
1053 out = self.init(testdir, allow_fail=True, extra_args=['-Dnative=false'])
1054 self.assertIn('Unknown property for host machine: nonexisting', out)
1055
1056 def test_project_options_native_only(self) -> None:
1057 # Do not load project options from a native file when doing a cross
1058 # build
1059 testcase = os.path.join(self.unit_test_dir, '19 array option')
1060 config = self.helper_create_cross_file({'project options': {'list': ['bar', 'foo']}})
1061 cross = self.helper_create_cross_file({'binaries': {}})
1062
1063 self.init(testcase, extra_args=['--native-file', config, '--cross-file', cross])
1064 configuration = self.introspect('--buildoptions')
1065 for each in configuration:
1066 if each['name'] == 'list':
1067 self.assertEqual(each['value'], ['foo', 'bar'])
1068 break
1069 else:
1070 self.fail('Did not find expected option.')
1071
1072 @skip_if_not_language('rust')
1073 @skipIfNoExecutable('bindgen')
1074 def test_bindgen_finds_target_in_clang_options(self) -> None:
1075 testcase = os.path.join(self.unit_test_dir, '135 minimal bindgen')
1076
1077 def check_target(include: T.Optional[str], exclude: T.Optional[str] = None) -> None:
1078 configuration = self.introspect('--targets')
1079 for each in configuration:
1080 if each['name'].startswith('rustmod-bindgen'):
1081 if include:
1082 self.assertIn(f'--target={include}', each['target_sources'][0]['compiler'])
1083 if exclude:
1084 self.assertNotIn(f'--target={exclude}', each['target_sources'][0]['compiler'])
1085 if not (include or exclude):
1086 self.assertFalse(any(x.startswith('--target') for x in each['target_sources'][0]['compiler']))
1087 break
1088 else:
1089 self.fail('--target was not set')
1090
1091 with self.subTest('none set'):
1092 self.init(testcase)
1093 check_target(None)
1094
1095 rustc = shutil.which('rustc')
1096 assert rustc is not None, 'Should have skipped'
1097 build_tuple = subprocess.run([rustc, '--print', 'host-tuple'], universal_newlines=True, check=True, capture_output=True).stdout.strip()
1098 host_tuple = 'aarch64-unknown-linux-gnu'
1099
1100 with self.subTest('properties only'):
1101 self.new_builddir()
1102 config = self.helper_create_cross_file({'properties': {'bindgen_clang_arguments': [f'--target={build_tuple}']}})
1103 self.init(testcase, extra_args=['--native-file', config])
1104 check_target(build_tuple)
1105
1106 with self.subTest('compiler only'):
1107 self.new_builddir()
1108 config = self.helper_create_cross_file({'binaries': {'rust': [rustc, f'--target={build_tuple}']}})
1109 self.init(testcase, extra_args=['-Dadd_rust_language=true', '--cross-file', config])
1110 check_target(build_tuple)
1111
1112 with self.subTest('properties and compiler'):
1113 # https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=1132495
1114 if build_tuple == host_tuple:
1115 raise SkipTest('Do not run aarch64 cross compilation test on aarch64 itself.')
1116 self.new_builddir()
1117 config = self.helper_create_cross_file({
1118 'binaries': {'rust': [rustc, f'--target={build_tuple}']},
1119 'properties': {'bindgen_clang_arguments': [f'--target={host_tuple}']},
1120 })
1121 self.init(testcase, extra_args=['-Dadd_rust_language=true', '--cross-file', config])
1122 check_target(host_tuple, build_tuple)
1123
1124 with self.subTest('unused compiler'):
1125 self.new_builddir()
1126 config = self.helper_create_cross_file({
1127 'binaries': {'rust': [rustc, f'--target={build_tuple}']},
1128 })
1129 self.init(testcase, extra_args=['--cross-file', config])
1130 check_target(None, build_tuple)