Debian Codegraph @

unittests/linuxliketests.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2016-2022 The Meson development team
3
4 import stat
5 import subprocess
6 import re
7 import tempfile
8 import textwrap
9 import os
10 import shutil
11 import hashlib
12 from unittest import mock, skipUnless, SkipTest
13 from glob import glob
14 from pathlib import Path
15 import typing as T
16
17 import mesonbuild.mlog
18 import mesonbuild.depfile
19 import mesonbuild.dependencies.base
20 import mesonbuild.dependencies.factory
21 import mesonbuild.envconfig
22 import mesonbuild.environment
23 import mesonbuild.coredata
24 import mesonbuild.modules.gnome
25 from mesonbuild.mesonlib import (
26 MachineChoice, is_windows, is_osx, is_cygwin, is_openbsd, is_haiku,
27 is_sunos, windows_proof_rmtree, version_compare, is_linux,
28 EnvironmentException
29 )
30 from mesonbuild.options import OptionKey
31 from mesonbuild.compilers import (
32 detect_c_compiler, detect_cpp_compiler, compiler_from_language,
33 )
34 from mesonbuild.compilers.c import AppleClangCCompiler, ElbrusCompiler
35 from mesonbuild.compilers.cpp import AppleClangCPPCompiler
36 from mesonbuild.compilers.objc import AppleClangObjCCompiler
37 from mesonbuild.compilers.objcpp import AppleClangObjCPPCompiler
38 from mesonbuild.dependencies.pkgconfig import PkgConfigDependency, PkgConfigCLI, PkgConfigInterface
39 from mesonbuild.programs import NonExistingExternalProgram
40 import mesonbuild.modules.pkgconfig
41
42 PKG_CONFIG = os.environ.get('PKG_CONFIG', 'pkg-config')
43
44
45 from run_tests import (
46 get_fake_env, Backend,
47 )
48
49 from .baseplatformtests import BasePlatformTests
50 from .helpers import *
51
52 def _prepend_pkg_config_path(path: str) -> str:
53 """Prepend a string value to pkg_config_path
54
55 :param path: The path to prepend
56 :return: The path, followed by any PKG_CONFIG_PATH already in the environment
57 """
58 pkgconf = os.environ.get('PKG_CONFIG_PATH')
59 if pkgconf:
60 return f'{path}{os.path.pathsep}{pkgconf}'
61 return path
62
63
64 def _clang_at_least(compiler: 'Compiler', minver: str, apple_minver: T.Optional[str]) -> bool:
65 """
66 check that Clang compiler is at least a specified version, whether AppleClang or regular Clang
67
68 Parameters
69 ----------
70 compiler:
71 Meson compiler object
72 minver: str
73 Clang minimum version
74 apple_minver: str
75 AppleCLang minimum version
76
77 Returns
78 -------
79 at_least: bool
80 Clang is at least the specified version
81 """
82 if isinstance(compiler, (AppleClangCCompiler, AppleClangCPPCompiler)):
83 if apple_minver is None:
84 return False
85 return version_compare(compiler.version, apple_minver)
86 return version_compare(compiler.version, minver)
87
88 @skipUnless(not is_windows(), "requires something Unix-like")
89 class LinuxlikeTests(BasePlatformTests):
90 '''
91 Tests that should run on Linux, macOS, and *BSD
92 '''
93
94 def test_basic_soname(self):
95 '''
96 Test that the soname is set correctly for shared libraries. This can't
97 be an ordinary test case because we need to run `readelf` and actually
98 check the soname.
99 https://github.com/mesonbuild/meson/issues/785
100 '''
101 testdir = os.path.join(self.common_test_dir, '4 shared')
102 self.init(testdir)
103 self.build()
104 lib1 = os.path.join(self.builddir, 'libmylib.so')
105 soname = get_soname(lib1)
106 self.assertEqual(soname, 'libmylib.so')
107
108 @skip_if_not_language('rust')
109 def test_rust_soname(self):
110 '''
111 Test that the soname is set correctly for shared libraries. This can't
112 be an ordinary test case because we need to run `readelf` and actually
113 check the soname.
114 https://github.com/mesonbuild/meson/issues/785
115 '''
116 testdir = os.path.join(self.rust_test_dir, '2 sharedlib')
117 self.init(testdir)
118 self.build()
119 lib1 = os.path.join(self.builddir, 'cdylib/libnot_so_rusty.so')
120 soname = get_soname(lib1)
121 self.assertEqual(soname, 'libnot_so_rusty.so')
122
123 def test_custom_soname(self):
124 '''
125 Test that the soname is set correctly for shared libraries when
126 a custom prefix and/or suffix is used. This can't be an ordinary test
127 case because we need to run `readelf` and actually check the soname.
128 https://github.com/mesonbuild/meson/issues/785
129 '''
130 testdir = os.path.join(self.common_test_dir, '24 library versions')
131 self.init(testdir)
132 self.build()
133 lib1 = os.path.join(self.builddir, 'prefixsomelib.suffix')
134 soname = get_soname(lib1)
135 self.assertEqual(soname, 'prefixsomelib.suffix')
136
137 def test_pic(self):
138 '''
139 Test that -fPIC is correctly added to static libraries when b_staticpic
140 is true and not when it is false. This can't be an ordinary test case
141 because we need to inspect the compiler database.
142 '''
143 if is_windows() or is_cygwin() or is_osx():
144 raise SkipTest('PIC not relevant')
145
146 testdir = os.path.join(self.common_test_dir, '3 static')
147 self.init(testdir)
148 compdb = self.get_compdb()
149 self.assertIn('-fPIC', compdb[0]['command'])
150 self.setconf('-Db_staticpic=false')
151 # Regenerate build
152 self.build()
153 compdb = self.get_compdb()
154 self.assertNotIn('-fPIC', compdb[0]['command'])
155
156 @mock.patch.dict(os.environ)
157 def test_pkgconfig_gen(self):
158 '''
159 Test that generated pkg-config files can be found and have the correct
160 version and link args. This can't be an ordinary test case because we
161 need to run pkg-config outside of a Meson build file.
162 https://github.com/mesonbuild/meson/issues/889
163 '''
164 testdir = os.path.join(self.common_test_dir, '44 pkgconfig-gen')
165 self.init(testdir)
166 env = get_fake_env(testdir, self.builddir, self.prefix)
167 kwargs = {'required': True, 'silent': True, 'native': MachineChoice.HOST}
168 os.environ['PKG_CONFIG_LIBDIR'] = self.privatedir
169 foo_dep = PkgConfigDependency('libfoo', env, kwargs)
170 self.assertTrue(foo_dep.found())
171 self.assertEqual(foo_dep.get_version(), '1.0')
172 self.assertIn('-lfoo', foo_dep.get_link_args())
173 self.assertEqual(foo_dep.get_variable(pkgconfig='foo'), 'bar')
174 self.assertPathEqual(foo_dep.get_variable(pkgconfig='datadir'), '/usr/data')
175
176 libhello_nolib = PkgConfigDependency('libhello_nolib', env, kwargs)
177 self.assertTrue(libhello_nolib.found())
178 self.assertEqual(libhello_nolib.get_link_args(), [])
179 self.assertEqual(libhello_nolib.get_compile_args(), [])
180 self.assertEqual(libhello_nolib.get_variable(pkgconfig='foo'), 'bar')
181 self.assertEqual(libhello_nolib.get_variable(pkgconfig='prefix'), self.prefix)
182 impl = libhello_nolib.pkgconfig
183 if not isinstance(impl, PkgConfigCLI) or version_compare(impl.pkgbin_version, ">=0.29.1"):
184 self.assertEqual(libhello_nolib.get_variable(pkgconfig='escaped_var'), r'hello\ world')
185 self.assertEqual(libhello_nolib.get_variable(pkgconfig='unescaped_var'), 'hello world')
186
187 cc = detect_c_compiler(env, MachineChoice.HOST)
188 if cc.get_id() in {'gcc', 'clang'}:
189 for name in {'ct', 'ct0'}:
190 ct_dep = PkgConfigDependency(name, env, kwargs)
191 self.assertTrue(ct_dep.found())
192 self.assertIn('-lct', ct_dep.get_link_args(raw=True))
193
194 def test_pkgconfig_gen_deps(self):
195 '''
196 Test that generated pkg-config files correctly handle dependencies
197 '''
198 testdir = os.path.join(self.common_test_dir, '44 pkgconfig-gen')
199 self.init(testdir)
200 privatedir1 = self.privatedir
201
202 self.new_builddir()
203 testdir = os.path.join(self.common_test_dir, '44 pkgconfig-gen', 'dependencies')
204 self.init(testdir, override_envvars={'PKG_CONFIG_LIBDIR': privatedir1})
205 privatedir2 = self.privatedir
206
207 env = {
208 'PKG_CONFIG_LIBDIR': os.pathsep.join([privatedir1, privatedir2]),
209 'PKG_CONFIG_SYSTEM_LIBRARY_PATH': '/usr/lib',
210 }
211 self._run([PKG_CONFIG, 'dependency-test', '--validate'], override_envvars=env)
212
213 # pkg-config strips some duplicated flags so we have to parse the
214 # generated file ourself.
215 expected = {
216 'Requires': 'libexposed',
217 'Requires.private': 'libfoo >= 1.0',
218 'Libs': '-L${libdir} -llibmain -pthread -lcustom',
219 'Libs.private': '-lcustom2 -L${libdir} -llibinternal',
220 'Cflags': '-I${includedir} -pthread -DCUSTOM',
221 }
222 if is_osx() or is_haiku():
223 expected['Cflags'] = expected['Cflags'].replace('-pthread ', '')
224 with open(os.path.join(privatedir2, 'dependency-test.pc'), encoding='utf-8') as f:
225 matched_lines = 0
226 for line in f:
227 parts = line.split(':', 1)
228 if parts[0] in expected:
229 key = parts[0]
230 val = parts[1].strip()
231 expected_val = expected[key]
232 self.assertEqual(expected_val, val)
233 matched_lines += 1
234 self.assertEqual(len(expected), matched_lines)
235
236 cmd = [PKG_CONFIG, 'requires-test']
237 out = self._run(cmd + ['--print-requires'], override_envvars=env).strip().split('\n')
238 if not is_openbsd():
239 self.assertEqual(sorted(out), sorted(['libexposed', 'libfoo >= 1.0', 'libhello']))
240 else:
241 self.assertEqual(sorted(out), sorted(['libexposed', 'libfoo>=1.0', 'libhello']))
242
243 cmd = [PKG_CONFIG, 'requires-private-test']
244 out = self._run(cmd + ['--print-requires-private'], override_envvars=env).strip().split('\n')
245 if not is_openbsd():
246 self.assertEqual(sorted(out), sorted(['libexposed', 'libfoo >= 1.0', 'libhello']))
247 else:
248 self.assertEqual(sorted(out), sorted(['libexposed', 'libfoo>=1.0', 'libhello']))
249
250 cmd = [PKG_CONFIG, 'pub-lib-order']
251 out = self._run(cmd + ['--libs'], override_envvars=env).strip().split()
252 self.assertEqual(out, ['-llibmain2', '-llibinternal'])
253
254 # See common/44 pkgconfig-gen/meson.build for description of the case this test
255 with open(os.path.join(privatedir1, 'simple2.pc'), encoding='utf-8') as f:
256 content = f.read()
257 self.assertIn('Libs: -L${libdir} -lsimple2 -lsimple1', content)
258 self.assertIn('Libs.private: -lz', content)
259
260 with open(os.path.join(privatedir1, 'simple3.pc'), encoding='utf-8') as f:
261 content = f.read()
262 self.assertEqual(1, content.count('-lsimple3'))
263
264 with open(os.path.join(privatedir1, 'simple5.pc'), encoding='utf-8') as f:
265 content = f.read()
266 self.assertNotIn('-lstat2', content)
267
268 @mock.patch.dict(os.environ)
269 def test_pkgconfig_uninstalled(self):
270 testdir = os.path.join(self.common_test_dir, '44 pkgconfig-gen')
271 self.init(testdir)
272 self.build()
273
274 os.environ['PKG_CONFIG_LIBDIR'] = os.path.join(self.builddir, 'meson-uninstalled')
275 if is_cygwin():
276 os.environ['PATH'] += os.pathsep + self.builddir
277
278 self.new_builddir()
279 testdir = os.path.join(self.common_test_dir, '44 pkgconfig-gen', 'dependencies')
280 self.init(testdir)
281 self.build()
282 self.run_tests()
283
284 def test_pkg_unfound(self):
285 testdir = os.path.join(self.unit_test_dir, '23 unfound pkgconfig')
286 self.init(testdir)
287 with open(os.path.join(self.privatedir, 'somename.pc'), encoding='utf-8') as f:
288 pcfile = f.read()
289 self.assertNotIn('blub_blob_blib', pcfile)
290
291 def test_symlink_builddir(self) -> None:
292 '''
293 Test using a symlink as either the builddir for "setup" or
294 the argument for "-C".
295 '''
296 testdir = os.path.join(self.common_test_dir, '1 trivial')
297
298 symdir = f'{self.builddir}-symlink'
299 os.symlink(self.builddir, symdir)
300 self.change_builddir(symdir)
301
302 self.init(testdir)
303 self.build()
304 self._run(self.mtest_command)
305
306 @skipIfNoPkgconfig
307 def test_qtdependency_pkgconfig_detection(self):
308 '''
309 Test that qt4 and qt5 detection with pkgconfig works.
310 '''
311 # Verify Qt4 or Qt5 can be found with pkg-config
312 qt4 = subprocess.call([PKG_CONFIG, '--exists', 'QtCore'])
313 qt5 = subprocess.call([PKG_CONFIG, '--exists', 'Qt5Core'])
314 testdir = os.path.join(self.framework_test_dir, '4 qt')
315 self.init(testdir, extra_args=['-Dmethod=pkg-config'])
316 # Confirm that the dependency was found with pkg-config
317 mesonlog = self.get_meson_log_raw()
318 if qt4 == 0:
319 self.assertRegex(mesonlog,
320 r'Run-time dependency qt4 \(modules: Core\) found: YES 4.* \(pkg-config\)')
321 if qt5 == 0:
322 self.assertRegex(mesonlog,
323 r'Run-time dependency qt5 \(modules: Core\) found: YES 5.* \(pkg-config\)')
324
325 @skip_if_not_base_option('b_sanitize')
326 def test_generate_gir_with_address_sanitizer(self):
327 if is_cygwin():
328 raise SkipTest('asan not available on Cygwin')
329 if is_openbsd():
330 raise SkipTest('-fsanitize=address is not supported on OpenBSD')
331
332 testdir = os.path.join(self.framework_test_dir, '7 gnome')
333 self.init(testdir, extra_args=['-Db_sanitize=address', '-Db_lundef=false'])
334 self.build()
335
336 def test_qt5dependency_no_lrelease(self):
337 '''
338 Test that qt5 detection with qmake works. This can't be an ordinary
339 test case because it involves setting the environment.
340 '''
341 testdir = os.path.join(self.framework_test_dir, '4 qt')
342 def _no_lrelease(self, prog, *args, **kwargs):
343 if 'lrelease' in prog:
344 return NonExistingExternalProgram(prog)
345 return self._interpreter.find_program_impl(prog, *args, **kwargs)
346 with mock.patch.object(mesonbuild.modules.ModuleState, 'find_program', _no_lrelease):
347 self.init(testdir, inprocess=True, extra_args=['-Dmethod=qmake', '-Dexpect_lrelease=false'])
348
349 def test_qt5dependency_qmake_detection(self):
350 '''
351 Test that qt5 detection with qmake works. This can't be an ordinary
352 test case because it involves setting the environment.
353 '''
354 # Verify that qmake is for Qt5
355 if not shutil.which('qmake-qt5'):
356 if not shutil.which('qmake'):
357 raise SkipTest('QMake not found')
358 output = subprocess.getoutput('qmake --version')
359 if 'Qt version 5' not in output:
360 raise SkipTest('Qmake found, but it is not for Qt 5.')
361 # Disable pkg-config codepath and force searching with qmake/qmake-qt5
362 testdir = os.path.join(self.framework_test_dir, '4 qt')
363 self.init(testdir, extra_args=['-Dmethod=qmake'])
364 # Confirm that the dependency was found with qmake
365 mesonlog = self.get_meson_log_raw()
366 self.assertRegex(mesonlog,
367 r'Run-time dependency qt5 \(modules: Core\) found: YES .* \(qmake\)\n')
368
369 def test_qt6dependency_qmake_detection(self):
370 '''
371 Test that qt6 detection with qmake works. This can't be an ordinary
372 test case because it involves setting the environment.
373 '''
374 # Verify that qmake is for Qt6
375 if not shutil.which('qmake6'):
376 if not shutil.which('qmake'):
377 raise SkipTest('QMake not found')
378 output = subprocess.getoutput('qmake --version')
379 if 'Qt version 6' not in output:
380 raise SkipTest('Qmake found, but it is not for Qt 6.')
381 # Disable pkg-config codepath and force searching with qmake/qmake-qt6
382 testdir = os.path.join(self.framework_test_dir, '4 qt')
383 self.init(testdir, extra_args=['-Dmethod=qmake'])
384 # Confirm that the dependency was found with qmake
385 mesonlog = self.get_meson_log_raw()
386 self.assertRegex(mesonlog,
387 r'Run-time dependency qt6 \(modules: Core\) found: YES .* \(qmake\)\n')
388
389 def glob_sofiles_without_privdir(self, g):
390 files = glob(g)
391 return [f for f in files if not f.endswith('.p')]
392
393 def _test_soname_impl(self, libpath, install):
394 if is_cygwin() or is_osx():
395 raise SkipTest('Test only applicable to ELF and linuxlike sonames')
396
397 testdir = os.path.join(self.unit_test_dir, '1 soname')
398 self.init(testdir)
399 self.build()
400 if install:
401 self.install()
402
403 # File without aliases set.
404 nover = os.path.join(libpath, 'libnover.so')
405 self.assertPathExists(nover)
406 self.assertFalse(os.path.islink(nover))
407 self.assertEqual(get_soname(nover), 'libnover.so')
408 self.assertEqual(len(self.glob_sofiles_without_privdir(nover[:-3] + '*')), 1)
409
410 # File with version set
411 verset = os.path.join(libpath, 'libverset.so')
412 self.assertPathExists(verset + '.4.5.6')
413 self.assertEqual(os.readlink(verset), 'libverset.so.4')
414 self.assertEqual(get_soname(verset), 'libverset.so.4')
415 self.assertEqual(len(self.glob_sofiles_without_privdir(verset[:-3] + '*')), 3)
416
417 # File with soversion set
418 soverset = os.path.join(libpath, 'libsoverset.so')
419 self.assertPathExists(soverset + '.1.2.3')
420 self.assertEqual(os.readlink(soverset), 'libsoverset.so.1.2.3')
421 self.assertEqual(get_soname(soverset), 'libsoverset.so.1.2.3')
422 self.assertEqual(len(self.glob_sofiles_without_privdir(soverset[:-3] + '*')), 2)
423
424 # File with version and soversion set to same values
425 settosame = os.path.join(libpath, 'libsettosame.so')
426 self.assertPathExists(settosame + '.7.8.9')
427 self.assertEqual(os.readlink(settosame), 'libsettosame.so.7.8.9')
428 self.assertEqual(get_soname(settosame), 'libsettosame.so.7.8.9')
429 self.assertEqual(len(self.glob_sofiles_without_privdir(settosame[:-3] + '*')), 2)
430
431 # File with version and soversion set to different values
432 bothset = os.path.join(libpath, 'libbothset.so')
433 self.assertPathExists(bothset + '.1.2.3')
434 self.assertEqual(os.readlink(bothset), 'libbothset.so.1.2.3')
435 self.assertEqual(os.readlink(bothset + '.1.2.3'), 'libbothset.so.4.5.6')
436 self.assertEqual(get_soname(bothset), 'libbothset.so.1.2.3')
437 self.assertEqual(len(self.glob_sofiles_without_privdir(bothset[:-3] + '*')), 3)
438
439 # A shared_module that is not linked to anything
440 module = os.path.join(libpath, 'libsome_module.so')
441 self.assertPathExists(module)
442 self.assertFalse(os.path.islink(module))
443 self.assertEqual(get_soname(module), None)
444
445 # A shared_module that is not linked to an executable with link_with:
446 module = os.path.join(libpath, 'liblinked_module1.so')
447 self.assertPathExists(module)
448 self.assertFalse(os.path.islink(module))
449 self.assertEqual(get_soname(module), 'liblinked_module1.so')
450
451 # A shared_module that is not linked to an executable with dependencies:
452 module = os.path.join(libpath, 'liblinked_module2.so')
453 self.assertPathExists(module)
454 self.assertFalse(os.path.islink(module))
455 self.assertEqual(get_soname(module), 'liblinked_module2.so')
456
457 def test_soname(self):
458 self._test_soname_impl(self.builddir, False)
459
460 def test_installed_soname(self):
461 libdir = self.installdir + os.path.join(self.prefix, self.libdir)
462 self._test_soname_impl(libdir, True)
463
464 @skip_if_not_base_option('b_sanitize')
465 def test_c_link_args_and_env(self):
466 '''
467 Test that the CFLAGS / CXXFLAGS environment variables are
468 included on the linker command line when c_link_args is
469 set but c_args is not.
470 '''
471 if is_cygwin():
472 raise SkipTest('asan not available on Cygwin')
473 if is_openbsd():
474 raise SkipTest('-fsanitize=address is not supported on OpenBSD')
475 if is_sunos():
476 raise SkipTest('-fsanitize=address is not supported on illumos')
477
478 testdir = os.path.join(self.common_test_dir, '1 trivial')
479 env = {'CFLAGS': '-fsanitize=address'}
480 self.init(testdir, extra_args=['-Dc_link_args="-L/usr/lib"'],
481 override_envvars=env)
482 self.build()
483
484 def test_compiler_check_flags_order(self):
485 '''
486 Test that compiler check flags override all other flags. This can't be
487 an ordinary test case because it needs the environment to be set.
488 '''
489 testdir = os.path.join(self.common_test_dir, '36 has function')
490 env = get_fake_env(testdir, self.builddir, self.prefix)
491 cpp = detect_cpp_compiler(env, MachineChoice.HOST)
492 Oflag = '-O3'
493 OflagCPP = Oflag
494 if cpp.get_id() in ('clang', 'gcc'):
495 # prevent developers from adding "int main(int argc, char **argv)"
496 # to small Meson checks unless these parameters are actually used
497 OflagCPP += ' -Werror=unused-parameter'
498 env = {'CFLAGS': Oflag,
499 'CXXFLAGS': OflagCPP}
500 self.init(testdir, override_envvars=env)
501 cmds = self.get_meson_log_compiler_checks()
502 for cmd in cmds:
503 if cmd[0] == 'ccache':
504 cmd = cmd[1:]
505 # Verify that -I flags from the `args` kwarg are first
506 # This is set in the '36 has function' test case
507 self.assertEqual(cmd[1], '-I/tmp')
508 # Verify that -O3 set via the environment is overridden by -O0
509 Oargs = [arg for arg in cmd if arg.startswith('-O')]
510 self.assertEqual(Oargs, [Oflag, '-O0'])
511
512 def _test_stds_impl(self, testdir: str, compiler: 'Compiler') -> None:
513 has_cpp17 = (compiler.get_id() not in {'clang', 'gcc'} or
514 compiler.get_id() == 'clang' and _clang_at_least(compiler, '>=5.0.0', '>=9.1') or
515 compiler.get_id() == 'gcc' and version_compare(compiler.version, '>=5.0.0'))
516 has_cpp2a_c17 = (compiler.get_id() not in {'clang', 'gcc'} or
517 compiler.get_id() == 'clang' and _clang_at_least(compiler, '>=6.0.0', '>=10.0') or
518 compiler.get_id() == 'gcc' and version_compare(compiler.version, '>=8.0.0'))
519 has_cpp20 = (compiler.get_id() not in {'clang', 'gcc'} or
520 compiler.get_id() == 'clang' and _clang_at_least(compiler, '>=10.0.0', None) or
521 compiler.get_id() == 'gcc' and version_compare(compiler.version, '>=10.0.0'))
522 has_cpp2b = (compiler.get_id() not in {'clang', 'gcc'} or
523 compiler.get_id() == 'clang' and _clang_at_least(compiler, '>=12.0.0', None) or
524 compiler.get_id() == 'gcc' and version_compare(compiler.version, '>=11.0.0'))
525 has_cpp23 = (compiler.get_id() not in {'clang', 'gcc'} or
526 compiler.get_id() == 'clang' and _clang_at_least(compiler, '>=17.0.0', None) or
527 compiler.get_id() == 'gcc' and version_compare(compiler.version, '>=11.0.0'))
528 has_cpp26 = (compiler.get_id() not in {'clang', 'gcc'} or
529 compiler.get_id() == 'clang' and _clang_at_least(compiler, '>=17.0.0', None) or
530 compiler.get_id() == 'gcc' and version_compare(compiler.version, '>=14.0.0'))
531 has_c18 = (compiler.get_id() not in {'clang', 'gcc'} or
532 compiler.get_id() == 'clang' and _clang_at_least(compiler, '>=8.0.0', '>=11.0') or
533 compiler.get_id() == 'gcc' and version_compare(compiler.version, '>=8.0.0'))
534 # Check that all the listed -std=xxx options for this compiler work just fine when used
535 # https://en.wikipedia.org/wiki/Xcode#Latest_versions
536 # https://www.gnu.org/software/gcc/projects/cxx-status.html
537 key = OptionKey(f'{compiler.language}_std')
538 for v in compiler.get_options()[key].choices:
539 # we do it like this to handle gnu++17,c++17 and gnu17,c17 cleanly
540 # thus, C++ first
541 if '++17' in v and not has_cpp17:
542 continue
543 elif '++2a' in v and not has_cpp2a_c17: # https://en.cppreference.com/w/cpp/compiler_support
544 continue
545 elif '++20' in v and not has_cpp20:
546 continue
547 elif '++2b' in v and not has_cpp2b:
548 continue
549 elif '++23' in v and not has_cpp23:
550 continue
551 elif ('++26' in v or '++2c' in v) and not has_cpp26:
552 continue
553 # now C
554 elif '17' in v and not has_cpp2a_c17:
555 continue
556 elif '18' in v and not has_c18:
557 continue
558 self.init(testdir, extra_args=[f'-D{key!s}={v}'])
559 cmd = self.get_compdb()[0]['command']
560 # c++03 and gnu++03 are not understood by ICC, don't try to look for them
561 skiplist = frozenset([
562 ('intel', 'c++03'),
563 ('intel', 'gnu++03')])
564 if v != 'none' and not (compiler.get_id(), v) in skiplist:
565 cmd_std = f" -std={v} "
566 self.assertIn(cmd_std, cmd)
567 try:
568 self.build()
569 except Exception:
570 print(f'{key!s} was {v!r}')
571 raise
572 self.wipe()
573 # Check that an invalid std option in CFLAGS/CPPFLAGS fails
574 # Needed because by default ICC ignores invalid options
575 cmd_std = '-std=FAIL'
576 if compiler.language == 'c':
577 env_flag_name = 'CFLAGS'
578 elif compiler.language == 'cpp':
579 env_flag_name = 'CXXFLAGS'
580 else:
581 raise NotImplementedError(f'Language {compiler.language} not defined.')
582 env = {}
583 env[env_flag_name] = cmd_std
584 with self.assertRaises((subprocess.CalledProcessError, EnvironmentException),
585 msg='C compiler should have failed with -std=FAIL'):
586 self.init(testdir, override_envvars = env)
587 # ICC won't fail in the above because additional flags are needed to
588 # make unknown -std=... options errors.
589 self.build()
590
591 def test_compiler_c_stds(self):
592 '''
593 Test that C stds specified for this compiler can all be used. Can't be
594 an ordinary test because it requires passing options to meson.
595 '''
596 testdir = os.path.join(self.common_test_dir, '1 trivial')
597 env = get_fake_env(testdir, self.builddir, self.prefix)
598 cc = detect_c_compiler(env, MachineChoice.HOST)
599 self._test_stds_impl(testdir, cc)
600
601 def test_compiler_cpp_stds(self):
602 '''
603 Test that C++ stds specified for this compiler can all be used. Can't
604 be an ordinary test because it requires passing options to meson.
605 '''
606 testdir = os.path.join(self.common_test_dir, '2 cpp')
607 env = get_fake_env(testdir, self.builddir, self.prefix)
608 cpp = detect_cpp_compiler(env, MachineChoice.HOST)
609 self._test_stds_impl(testdir, cpp)
610
611 def test_unity_subproj(self):
612 testdir = os.path.join(self.common_test_dir, '42 subproject')
613 self.init(testdir, extra_args='--unity=subprojects')
614 pdirs = glob(os.path.join(self.builddir, 'subprojects/sublib/simpletest*.p'))
615 self.assertEqual(len(pdirs), 1)
616 self.assertPathExists(os.path.join(pdirs[0], 'simpletest-unity0.c'))
617 sdirs = glob(os.path.join(self.builddir, 'subprojects/sublib/*sublib*.p'))
618 self.assertEqual(len(sdirs), 1)
619 self.assertPathExists(os.path.join(sdirs[0], 'sublib-unity0.c'))
620 self.assertPathDoesNotExist(os.path.join(self.builddir, 'user@exe/user-unity.c'))
621 self.build()
622
623 def test_installed_modes(self):
624 '''
625 Test that files installed by these tests have the correct permissions.
626 Can't be an ordinary test because our installed_files.txt is very basic.
627 '''
628 # Test file modes
629 testdir = os.path.join(self.common_test_dir, '12 data')
630 self.init(testdir)
631 self.install()
632
633 f = os.path.join(self.installdir, 'etc', 'etcfile.dat')
634 found_mode = stat.filemode(os.stat(f).st_mode)
635 want_mode = 'rw-------'
636 self.assertEqual(want_mode, found_mode[1:])
637
638 f = os.path.join(self.installdir, 'usr', 'bin', 'runscript.sh')
639 statf = os.stat(f)
640 found_mode = stat.filemode(statf.st_mode)
641 want_mode = 'rwxr-sr-x'
642 self.assertEqual(want_mode, found_mode[1:])
643 if os.getuid() == 0:
644 # The chown failed nonfatally if we're not root
645 self.assertEqual(0, statf.st_uid)
646 self.assertEqual(0, statf.st_gid)
647
648 f = os.path.join(self.installdir, 'usr', 'share', 'progname',
649 'fileobject_datafile.dat')
650 orig = os.path.join(testdir, 'fileobject_datafile.dat')
651 statf = os.stat(f)
652 statorig = os.stat(orig)
653 found_mode = stat.filemode(statf.st_mode)
654 orig_mode = stat.filemode(statorig.st_mode)
655 self.assertEqual(orig_mode[1:], found_mode[1:])
656 self.assertEqual(os.getuid(), statf.st_uid)
657 if os.getuid() == 0:
658 # The chown failed nonfatally if we're not root
659 self.assertEqual(0, statf.st_gid)
660
661 self.wipe()
662 # Test directory modes
663 testdir = os.path.join(self.common_test_dir, '59 install subdir')
664 self.init(testdir)
665 self.install()
666
667 f = os.path.join(self.installdir, 'usr', 'share', 'sub1', 'second.dat')
668 statf = os.stat(f)
669 found_mode = stat.filemode(statf.st_mode)
670 want_mode = 'rwxr-x--x'
671 self.assertEqual(want_mode, found_mode[1:])
672 if os.getuid() == 0:
673 # The chown failed nonfatally if we're not root
674 self.assertEqual(0, statf.st_uid)
675
676 def test_installed_modes_extended(self):
677 '''
678 Test that files are installed with correct permissions using install_mode.
679 '''
680 testdir = os.path.join(self.common_test_dir, '190 install_mode')
681 self.init(testdir)
682 self.build()
683 self.install()
684
685 for fsobj, want_mode in [
686 ('bin', 'drwxr-x---'),
687 ('bin/runscript.sh', '-rwxr-sr-x'),
688 ('bin/trivialprog', '-rwxr-sr-x'),
689 ('include', 'drwxr-x---'),
690 ('include/config.h', '-rw-rwSr--'),
691 ('include/rootdir.h', '-r--r--r--'),
692 ('lib', 'drwxr-x---'),
693 ('lib/libstat.a', '-rw---Sr--'),
694 ('share', 'drwxr-x---'),
695 ('share/man', 'drwxr-x---'),
696 ('share/man/man1', 'drwxr-x---'),
697 ('share/man/man1/foo.1', '-r--r--r--'),
698 ('share/sub1', 'drwxr-x---'),
699 ('share/sub1/second.dat', '-rwxr-x--x'),
700 ('subdir', 'drwxr-x---'),
701 ('subdir/data.dat', '-rw-rwSr--'),
702 ]:
703 f = os.path.join(self.installdir, 'usr', *fsobj.split('/'))
704 found_mode = stat.filemode(os.stat(f).st_mode)
705 self.assertEqual(want_mode, found_mode,
706 msg=('Expected file %s to have mode %s but found %s instead.' %
707 (fsobj, want_mode, found_mode)))
708 # Ensure that introspect --installed works on all types of files
709 # FIXME: also verify the files list
710 self.introspect('--installed')
711
712 def test_install_umask(self):
713 '''
714 Test that files are installed with correct permissions using default
715 install umask of 022, regardless of the umask at time the worktree
716 was checked out or the build was executed.
717 '''
718 # Copy source tree to a temporary directory and change permissions
719 # there to simulate a checkout with umask 002.
720 orig_testdir = os.path.join(self.unit_test_dir, '26 install umask')
721 # Create a new testdir under tmpdir.
722 tmpdir = os.path.realpath(tempfile.mkdtemp())
723 self.addCleanup(windows_proof_rmtree, tmpdir)
724 testdir = os.path.join(tmpdir, '26 install umask')
725 # Copy the tree using shutil.copyfile, which will use the current umask
726 # instead of preserving permissions of the old tree.
727 save_umask = os.umask(0o002)
728 self.addCleanup(os.umask, save_umask)
729 shutil.copytree(orig_testdir, testdir, copy_function=shutil.copyfile)
730 # Preserve the executable status of subdir/sayhello though.
731 os.chmod(os.path.join(testdir, 'subdir', 'sayhello'), 0o775)
732 self.init(testdir)
733 # Run the build under a 027 umask now.
734 os.umask(0o027)
735 self.build()
736 # And keep umask 027 for the install step too.
737 self.install()
738
739 for executable in [
740 'bin/prog',
741 'share/subdir/sayhello',
742 ]:
743 f = os.path.join(self.installdir, 'usr', *executable.split('/'))
744 found_mode = stat.filemode(os.stat(f).st_mode)
745 want_mode = '-rwxr-xr-x'
746 self.assertEqual(want_mode, found_mode,
747 msg=('Expected file %s to have mode %s but found %s instead.' %
748 (executable, want_mode, found_mode)))
749
750 for directory in [
751 'usr',
752 'usr/bin',
753 'usr/include',
754 'usr/share',
755 'usr/share/man',
756 'usr/share/man/man1',
757 'usr/share/subdir',
758 ]:
759 f = os.path.join(self.installdir, *directory.split('/'))
760 found_mode = stat.filemode(os.stat(f).st_mode)
761 want_mode = 'drwxr-xr-x'
762 self.assertEqual(want_mode, found_mode,
763 msg=('Expected directory %s to have mode %s but found %s instead.' %
764 (directory, want_mode, found_mode)))
765
766 for datafile in [
767 'include/sample.h',
768 'share/datafile.cat',
769 'share/file.dat',
770 'share/man/man1/prog.1',
771 'share/subdir/datafile.dog',
772 ]:
773 f = os.path.join(self.installdir, 'usr', *datafile.split('/'))
774 found_mode = stat.filemode(os.stat(f).st_mode)
775 want_mode = '-rw-r--r--'
776 self.assertEqual(want_mode, found_mode,
777 msg=('Expected file %s to have mode %s but found %s instead.' %
778 (datafile, want_mode, found_mode)))
779
780 def test_cpp_std_override(self):
781 testdir = os.path.join(self.unit_test_dir, '6 std override')
782 self.init(testdir)
783 compdb = self.get_compdb()
784 # Don't try to use -std=c++03 as a check for the
785 # presence of a compiler flag, as ICC does not
786 # support it.
787 for i in compdb:
788 if 'prog98' in i['file']:
789 c98_comp = i['command']
790 if 'prog11' in i['file']:
791 c11_comp = i['command']
792 if 'progp' in i['file']:
793 plain_comp = i['command']
794 self.assertNotEqual(len(plain_comp), 0)
795 self.assertIn('-std=c++98', c98_comp)
796 self.assertNotIn('-std=c++11', c98_comp)
797 self.assertIn('-std=c++11', c11_comp)
798 self.assertNotIn('-std=c++98', c11_comp)
799 self.assertNotIn('-std=c++98', plain_comp)
800 self.assertNotIn('-std=c++11', plain_comp)
801 # Now werror
802 self.assertIn('-Werror', plain_comp)
803 self.assertNotIn('-Werror', c98_comp)
804
805 def test_run_installed(self):
806 if is_cygwin() or is_osx():
807 raise SkipTest('LD_LIBRARY_PATH and RPATH not applicable')
808
809 testdir = os.path.join(self.unit_test_dir, '7 run installed')
810 self.init(testdir)
811 self.build()
812 self.install()
813 installed_exe = os.path.join(self.installdir, 'usr/bin/prog')
814 installed_libdir = os.path.join(self.installdir, 'usr/foo')
815 installed_lib = os.path.join(installed_libdir, 'libfoo.so')
816 self.assertTrue(os.path.isfile(installed_exe))
817 self.assertTrue(os.path.isdir(installed_libdir))
818 self.assertTrue(os.path.isfile(installed_lib))
819 # Must fail when run without LD_LIBRARY_PATH to ensure that
820 # rpath has been properly stripped rather than pointing to the builddir.
821 self.assertNotEqual(subprocess.call(installed_exe, stderr=subprocess.DEVNULL), 0)
822 # When LD_LIBRARY_PATH is set it should start working.
823 # For some reason setting LD_LIBRARY_PATH in os.environ fails
824 # when all tests are run (but works when only this test is run),
825 # but doing this explicitly works.
826 env = os.environ.copy()
827 env['LD_LIBRARY_PATH'] = ':'.join([installed_libdir, env.get('LD_LIBRARY_PATH', '')])
828 self.assertEqual(subprocess.call(installed_exe, env=env), 0)
829 # Ensure that introspect --installed works
830 installed = self.introspect('--installed')
831 for v in installed.values():
832 self.assertTrue('prog' in v or 'foo' in v)
833
834 @skipIfNoPkgconfig
835 def test_order_of_l_arguments(self):
836 testdir = os.path.join(self.unit_test_dir, '8 -L -l order')
837 self.init(testdir, override_envvars={'PKG_CONFIG_PATH': testdir})
838 # NOTE: .pc file has -Lfoo -lfoo -Lbar -lbar but pkg-config reorders
839 # the flags before returning them to -Lfoo -Lbar -lfoo -lbar
840 # but pkgconf seems to not do that. Sigh. Support both.
841 expected_order = [('-L/me/first', '-lfoo1'),
842 ('-L/me/second', '-lfoo2'),
843 ('-L/me/first', '-L/me/second'),
844 ('-lfoo1', '-lfoo2'),
845 ('-L/me/second', '-L/me/third'),
846 ('-L/me/third', '-L/me/fourth',),
847 ('-L/me/third', '-lfoo3'),
848 ('-L/me/fourth', '-lfoo4'),
849 ('-lfoo3', '-lfoo4'),
850 ]
851 with open(os.path.join(self.builddir, 'build.ninja'), encoding='utf-8') as ifile:
852 for line in ifile:
853 if expected_order[0][0] in line:
854 for first, second in expected_order:
855 self.assertLess(line.index(first), line.index(second))
856 return
857 raise RuntimeError('Linker entries not found in the Ninja file.')
858
859 def test_introspect_dependencies(self):
860 '''
861 Tests that mesonintrospect --dependencies returns expected output.
862 '''
863 testdir = os.path.join(self.framework_test_dir, '7 gnome')
864 self.init(testdir)
865 glib_found = False
866 gobject_found = False
867 deps = self.introspect('--dependencies')
868 self.assertIsInstance(deps, list)
869 for dep in deps:
870 self.assertIsInstance(dep, dict)
871 self.assertIn('name', dep)
872 self.assertIn('compile_args', dep)
873 self.assertIn('link_args', dep)
874 if dep['name'] == 'glib-2.0':
875 glib_found = True
876 elif dep['name'] == 'gobject-2.0':
877 gobject_found = True
878 self.assertTrue(glib_found)
879 self.assertTrue(gobject_found)
880 if subprocess.call([PKG_CONFIG, '--exists', 'glib-2.0 >= 2.56.2']) != 0:
881 raise SkipTest('glib >= 2.56.2 needed for the rest')
882 targets = self.introspect('--targets')
883 docbook_target = None
884 for t in targets:
885 if t['name'] == 'generated-gdbus-docbook':
886 docbook_target = t
887 break
888 self.assertIsInstance(docbook_target, dict)
889 self.assertEqual(os.path.basename(t['filename'][0]), 'generated-gdbus-doc-' + os.path.basename(t['target_sources'][0]['sources'][0]))
890
891 def test_introspect_installed(self):
892 testdir = os.path.join(self.linuxlike_test_dir, '7 library versions')
893 self.init(testdir)
894
895 install = self.introspect('--installed')
896 install = {os.path.basename(k): v for k, v in install.items()}
897 print(install)
898 if is_osx():
899 the_truth = {
900 'libmodule.dylib': '/usr/lib/libmodule.dylib',
901 'libnoversion.dylib': '/usr/lib/libnoversion.dylib',
902 'libonlysoversion.5.dylib': '/usr/lib/libonlysoversion.5.dylib',
903 'libonlysoversion.dylib': '/usr/lib/libonlysoversion.dylib',
904 'libonlyversion.1.dylib': '/usr/lib/libonlyversion.1.dylib',
905 'libonlyversion.dylib': '/usr/lib/libonlyversion.dylib',
906 'libsome.0.dylib': '/usr/lib/libsome.0.dylib',
907 'libsome.dylib': '/usr/lib/libsome.dylib',
908 }
909 the_truth_2 = {'/usr/lib/libsome.dylib',
910 '/usr/lib/libsome.0.dylib',
911 }
912 else:
913 the_truth = {
914 'libmodule.so': '/usr/lib/libmodule.so',
915 'libnoversion.so': '/usr/lib/libnoversion.so',
916 'libonlysoversion.so': '/usr/lib/libonlysoversion.so',
917 'libonlysoversion.so.5': '/usr/lib/libonlysoversion.so.5',
918 'libonlyversion.so': '/usr/lib/libonlyversion.so',
919 'libonlyversion.so.1': '/usr/lib/libonlyversion.so.1',
920 'libonlyversion.so.1.4.5': '/usr/lib/libonlyversion.so.1.4.5',
921 'libsome.so': '/usr/lib/libsome.so',
922 'libsome.so.0': '/usr/lib/libsome.so.0',
923 'libsome.so.1.2.3': '/usr/lib/libsome.so.1.2.3',
924 }
925 the_truth_2 = {'/usr/lib/libsome.so',
926 '/usr/lib/libsome.so.0',
927 '/usr/lib/libsome.so.1.2.3'}
928 self.assertDictEqual(install, the_truth)
929
930 targets = self.introspect('--targets')
931 for t in targets:
932 if t['name'] != 'some':
933 continue
934 self.assertSetEqual(the_truth_2, set(t['install_filename']))
935
936 def test_build_rpath(self):
937 if is_cygwin():
938 raise SkipTest('Windows PE/COFF binaries do not use RPATH')
939 testdir = os.path.join(self.unit_test_dir, '10 build_rpath')
940 self.init(testdir)
941 self.build()
942 build_rpath = get_rpath(os.path.join(self.builddir, 'prog'))
943 self.assertEqual(build_rpath, '$ORIGIN/sub:/foo/bar')
944 build_rpath = get_rpath(os.path.join(self.builddir, 'progcxx'))
945 self.assertEqual(build_rpath, '$ORIGIN/sub:/foo/bar')
946 self.install()
947 install_rpath = get_rpath(os.path.join(self.installdir, 'usr/bin/prog'))
948 self.assertEqual(install_rpath, '/baz')
949 install_rpath = get_rpath(os.path.join(self.installdir, 'usr/bin/progcxx'))
950 self.assertEqual(install_rpath, 'baz')
951
952 @skipIfNoPkgconfig
953 def test_build_rpath_pkgconfig(self):
954 '''
955 Test that current build artefacts (libs) are found first on the rpath,
956 manually specified rpath comes second and additional rpath elements (from
957 pkg-config files) come last
958 '''
959 if is_cygwin():
960 raise SkipTest('Windows PE/COFF binaries do not use RPATH')
961 testdir = os.path.join(self.unit_test_dir, '89 pkgconfig build rpath order')
962 self.init(testdir, override_envvars={'PKG_CONFIG_PATH': testdir})
963 self.build()
964 build_rpath = get_rpath(os.path.join(self.builddir, 'prog'))
965 self.assertEqual(build_rpath, '$ORIGIN/sub:/foo/bar:/foo/dummy')
966 build_rpath = get_rpath(os.path.join(self.builddir, 'progcxx'))
967 self.assertEqual(build_rpath, '$ORIGIN/sub:/foo/bar:/foo/dummy')
968 self.install()
969 install_rpath = get_rpath(os.path.join(self.installdir, 'usr/bin/prog'))
970 self.assertEqual(install_rpath, '/baz:/foo/dummy')
971 install_rpath = get_rpath(os.path.join(self.installdir, 'usr/bin/progcxx'))
972 self.assertEqual(install_rpath, 'baz:/foo/dummy')
973
974 @skipIfNoPkgconfig
975 def test_global_rpath(self):
976 if is_cygwin():
977 raise SkipTest('Windows PE/COFF binaries do not use RPATH')
978 if is_osx():
979 raise SkipTest('Global RPATHs via LDFLAGS not yet supported on MacOS (does anybody need it?)')
980
981 testdir = os.path.join(self.unit_test_dir, '79 global-rpath')
982 oldinstalldir = self.installdir
983
984 # Build and install an external library without DESTDIR.
985 # The external library generates a .pc file without an rpath.
986 yonder_dir = os.path.join(testdir, 'yonder')
987 yonder_prefix = os.path.join(oldinstalldir, 'yonder')
988 yonder_libdir = os.path.join(yonder_prefix, self.libdir)
989 self.prefix = yonder_prefix
990 self.installdir = yonder_prefix
991 self.init(yonder_dir)
992 self.build()
993 self.install(use_destdir=False)
994
995 # Since rpath has multiple valid formats we need to
996 # test that they are all properly used.
997 rpath_formats = [
998 ('-Wl,-rpath=', False),
999 ('-Wl,-rpath,', False),
1000 ('-Wl,--just-symbols=', True),
1001 ('-Wl,--just-symbols,', True),
1002 ('-Wl,-R', False),
1003 ('-Wl,-R,', False)
1004 ]
1005 for rpath_format, exception in rpath_formats:
1006 # Build an app that uses that installed library.
1007 # Supply the rpath to the installed library via LDFLAGS
1008 # (as systems like buildroot and guix are wont to do)
1009 # and verify install preserves that rpath.
1010 self.new_builddir()
1011 env = {'LDFLAGS': rpath_format + yonder_libdir,
1012 'PKG_CONFIG_PATH': os.path.join(yonder_libdir, 'pkgconfig')}
1013 if exception:
1014 with self.assertRaises(subprocess.CalledProcessError):
1015 self.init(testdir, override_envvars=env)
1016 continue
1017 self.init(testdir, override_envvars=env)
1018 self.build()
1019 self.install(use_destdir=False)
1020 got_rpath = get_rpath(os.path.join(yonder_prefix, 'bin/rpathified'))
1021 self.assertEqual(got_rpath, yonder_libdir, rpath_format)
1022
1023 @skip_if_not_base_option('b_sanitize')
1024 def test_env_cflags_ldflags(self):
1025 if is_cygwin():
1026 raise SkipTest('asan not available on Cygwin')
1027 if is_openbsd():
1028 raise SkipTest('-fsanitize=address is not supported on OpenBSD')
1029 if is_sunos():
1030 raise SkipTest('-fsanitize=address is not supported on illumos')
1031
1032 testdir = os.path.join(self.common_test_dir, '1 trivial')
1033 env = {'CFLAGS': '-fsanitize=address', 'LDFLAGS': '-I.'}
1034 self.init(testdir, override_envvars=env)
1035 self.build()
1036 compdb = self.get_compdb()
1037 for i in compdb:
1038 self.assertIn("-fsanitize=address", i["command"])
1039 self.wipe()
1040
1041 @skip_if_not_base_option('b_sanitize')
1042 def test_pch_with_address_sanitizer(self):
1043 if is_cygwin():
1044 raise SkipTest('asan not available on Cygwin')
1045 if is_openbsd():
1046 raise SkipTest('-fsanitize=address is not supported on OpenBSD')
1047
1048 testdir = os.path.join(self.common_test_dir, '13 pch')
1049 self.init(testdir, extra_args=['-Db_sanitize=address', '-Db_lundef=false'])
1050 self.build()
1051 compdb = self.get_compdb()
1052 for i in compdb:
1053 self.assertIn("-fsanitize=address", i["command"])
1054
1055 def test_cross_find_program(self):
1056 testdir = os.path.join(self.unit_test_dir, '11 cross prog')
1057 crossfile = tempfile.NamedTemporaryFile(mode='w', encoding='utf-8')
1058 print(os.path.join(testdir, 'some_cross_tool.py'))
1059
1060 tool_path = os.path.join(testdir, 'some_cross_tool.py')
1061
1062 crossfile.write(textwrap.dedent(f'''\
1063 [binaries]
1064 c = '{shutil.which('gcc' if is_sunos() else 'cc')}'
1065 ar = '{shutil.which('ar')}'
1066 strip = '{shutil.which('strip')}'
1067 sometool.py = ['{tool_path}']
1068 someothertool.py = '{tool_path}'
1069
1070 [properties]
1071
1072 [host_machine]
1073 system = 'linux'
1074 cpu_family = 'arm'
1075 cpu = 'armv7' # Not sure if correct.
1076 endian = 'little'
1077 '''))
1078 crossfile.flush()
1079 self.meson_cross_files = [crossfile.name]
1080 self.init(testdir)
1081
1082 def test_reconfigure(self):
1083 testdir = os.path.join(self.unit_test_dir, '13 reconfigure')
1084 self.init(testdir, extra_args=['-Db_coverage=true'], default_args=False)
1085 self.build('reconfigure')
1086
1087 @skip_if_not_language('vala')
1088 def test_vala_generated_source_buildir_inside_source_tree(self):
1089 '''
1090 Test that valac outputs generated C files in the expected location when
1091 the builddir is a subdir of the source tree.
1092 '''
1093 testdir = os.path.join(self.vala_test_dir, '8 generated sources')
1094 newdir = os.path.join(self.builddir, 'srctree')
1095 shutil.copytree(testdir, newdir)
1096 testdir = newdir
1097 # New builddir
1098 builddir = os.path.join(testdir, 'subdir/_build')
1099 os.makedirs(builddir, exist_ok=True)
1100 self.change_builddir(builddir)
1101 self.init(testdir)
1102 self.build()
1103
1104 def test_old_gnome_module_codepaths(self):
1105 '''
1106 A lot of code in the GNOME module is conditional on the version of the
1107 glib tools that are installed, and breakages in the old code can slip
1108 by once the CI has a newer glib version. So we force the GNOME module
1109 to pretend that it's running on an ancient glib so the fallback code is
1110 also tested.
1111 '''
1112 testdir = os.path.join(self.framework_test_dir, '7 gnome')
1113 with mock.patch('mesonbuild.modules.gnome.GnomeModule._get_native_glib_version', mock.Mock(return_value='2.20')):
1114 env = {'MESON_UNIT_TEST_PRETEND_GLIB_OLD': "1"}
1115 self.init(testdir,
1116 inprocess=True,
1117 override_envvars=env)
1118 self.build(override_envvars=env)
1119
1120 @skipIfNoPkgconfig
1121 def test_pkgconfig_usage(self):
1122 testdir1 = os.path.join(self.unit_test_dir, '27 pkgconfig usage/dependency')
1123 testdir2 = os.path.join(self.unit_test_dir, '27 pkgconfig usage/dependee')
1124 if subprocess.call([PKG_CONFIG, '--cflags', 'glib-2.0'],
1125 stdout=subprocess.DEVNULL,
1126 stderr=subprocess.DEVNULL) != 0:
1127 raise SkipTest('Glib 2.0 dependency not available.')
1128 with tempfile.TemporaryDirectory() as tempdirname:
1129 self.init(testdir1, extra_args=['--prefix=' + tempdirname, '--libdir=lib'], default_args=False)
1130 self.install(use_destdir=False)
1131 shutil.rmtree(self.builddir)
1132 os.mkdir(self.builddir)
1133 pkg_dir = os.path.join(tempdirname, 'lib/pkgconfig')
1134 self.assertTrue(os.path.exists(os.path.join(pkg_dir, 'libpkgdep.pc')))
1135 lib_dir = os.path.join(tempdirname, 'lib')
1136 myenv = os.environ.copy()
1137 myenv['PKG_CONFIG_PATH'] = pkg_dir
1138 # Private internal libraries must not leak out.
1139 pkg_out = subprocess.check_output([PKG_CONFIG, '--static', '--libs', 'libpkgdep'], env=myenv)
1140 self.assertNotIn(b'libpkgdep-int', pkg_out, 'Internal library leaked out.')
1141 # Dependencies must not leak to cflags when building only a shared library.
1142 pkg_out = subprocess.check_output([PKG_CONFIG, '--cflags', 'libpkgdep'], env=myenv)
1143 self.assertNotIn(b'glib', pkg_out, 'Internal dependency leaked to headers.')
1144 # Test that the result is usable.
1145 self.init(testdir2, override_envvars=myenv)
1146 self.build(override_envvars=myenv)
1147 myenv = os.environ.copy()
1148 myenv['LD_LIBRARY_PATH'] = ':'.join([lib_dir, myenv.get('LD_LIBRARY_PATH', '')])
1149 if is_cygwin():
1150 bin_dir = os.path.join(tempdirname, 'bin')
1151 myenv['PATH'] = bin_dir + os.pathsep + myenv['PATH']
1152 self.assertTrue(os.path.isdir(lib_dir))
1153 test_exe = os.path.join(self.builddir, 'pkguser')
1154 self.assertTrue(os.path.isfile(test_exe))
1155 subprocess.check_call(test_exe, env=myenv)
1156
1157 @skipIfNoPkgconfig
1158 def test_pkgconfig_relative_paths(self):
1159 testdir = os.path.join(self.unit_test_dir, '61 pkgconfig relative paths')
1160 pkg_dir = os.path.join(testdir, 'pkgconfig')
1161 self.assertPathExists(os.path.join(pkg_dir, 'librelativepath.pc'))
1162
1163 env = get_fake_env(testdir, self.builddir, self.prefix)
1164 env.coredata.optstore.set_option(OptionKey('pkg_config_path'), pkg_dir)
1165 kwargs = {'required': True, 'silent': True, 'native': MachineChoice.HOST}
1166 relative_path_dep = PkgConfigDependency('librelativepath', env, kwargs)
1167 self.assertTrue(relative_path_dep.found())
1168
1169 # Ensure link_args are properly quoted
1170 libpath = Path(self.builddir) / '../relativepath/lib'
1171 link_args = ['-L' + libpath.as_posix(), '-lrelativepath']
1172 self.assertEqual(relative_path_dep.get_link_args(), link_args)
1173
1174 @skipIfNoPkgconfig
1175 def test_pkgconfig_duplicate_path_entries(self):
1176 testdir = os.path.join(self.unit_test_dir, '111 pkgconfig duplicate path entries')
1177 pkg_dir = os.path.join(testdir, 'pkgconfig')
1178
1179 env = get_fake_env(testdir, self.builddir, self.prefix)
1180 env.coredata.optstore.set_option(OptionKey('pkg_config_path'), pkg_dir)
1181
1182 # Regression test: This used to modify the value of `pkg_config_path`
1183 # option, adding the meson-uninstalled directory to it.
1184 PkgConfigInterface.setup_env({}, env, MachineChoice.HOST, uninstalled=True)
1185
1186 pkg_config_path = env.coredata.optstore.get_value_for('pkg_config_path')
1187 self.assertEqual(pkg_config_path, [pkg_dir])
1188
1189 def test_pkgconfig_uninstalled_env_added(self):
1190 '''
1191 Checks that the meson-uninstalled dir is added to PKG_CONFIG_PATH
1192 '''
1193 testdir = os.path.join(self.unit_test_dir, '111 pkgconfig duplicate path entries')
1194 meson_uninstalled_dir = os.path.join(self.builddir, 'meson-uninstalled')
1195
1196 env = get_fake_env(testdir, self.builddir, self.prefix)
1197
1198 newEnv = PkgConfigInterface.setup_env({}, env, MachineChoice.HOST, uninstalled=True)
1199
1200 pkg_config_path_dirs = newEnv['PKG_CONFIG_PATH'].split(os.pathsep)
1201
1202 self.assertEqual(len(pkg_config_path_dirs), 1)
1203 self.assertEqual(pkg_config_path_dirs[0], meson_uninstalled_dir)
1204
1205 def test_pkgconfig_uninstalled_env_prepended(self):
1206 '''
1207 Checks that the meson-uninstalled dir is prepended to PKG_CONFIG_PATH
1208 '''
1209 testdir = os.path.join(self.unit_test_dir, '111 pkgconfig duplicate path entries')
1210 meson_uninstalled_dir = os.path.join(self.builddir, 'meson-uninstalled')
1211 external_pkg_config_path_dir = os.path.join('usr', 'local', 'lib', 'pkgconfig')
1212
1213 env = get_fake_env(testdir, self.builddir, self.prefix)
1214
1215 env.coredata.optstore.set_option(OptionKey('pkg_config_path'), external_pkg_config_path_dir)
1216
1217 newEnv = PkgConfigInterface.setup_env({}, env, MachineChoice.HOST, uninstalled=True)
1218
1219 pkg_config_path_dirs = newEnv['PKG_CONFIG_PATH'].split(os.pathsep)
1220
1221 self.assertEqual(pkg_config_path_dirs[0], meson_uninstalled_dir)
1222 self.assertEqual(pkg_config_path_dirs[1], external_pkg_config_path_dir)
1223
1224 @skipIfNoPkgconfig
1225 def test_pkgconfig_internal_libraries(self):
1226 '''
1227 '''
1228 with tempfile.TemporaryDirectory() as tempdirname:
1229 # build library
1230 testdirbase = os.path.join(self.unit_test_dir, '32 pkgconfig use libraries')
1231 testdirlib = os.path.join(testdirbase, 'lib')
1232 self.init(testdirlib, extra_args=['--prefix=' + tempdirname,
1233 '--libdir=lib',
1234 '--default-library=static'], default_args=False)
1235 self.build()
1236 self.install(use_destdir=False)
1237
1238 # build user of library
1239 pkg_dir = os.path.join(tempdirname, 'lib/pkgconfig')
1240 self.new_builddir()
1241 self.init(os.path.join(testdirbase, 'app'),
1242 override_envvars={'PKG_CONFIG_PATH': pkg_dir})
1243 self.build()
1244
1245 @skipIfNoPkgconfig
1246 def test_static_archive_stripping(self):
1247 '''
1248 Check that Meson produces valid static archives with --strip enabled
1249 '''
1250 with tempfile.TemporaryDirectory() as tempdirname:
1251 testdirbase = os.path.join(self.unit_test_dir, '65 static archive stripping')
1252
1253 # build lib
1254 self.new_builddir()
1255 testdirlib = os.path.join(testdirbase, 'lib')
1256 testlibprefix = os.path.join(tempdirname, 'libprefix')
1257 self.init(testdirlib, extra_args=['--prefix=' + testlibprefix,
1258 '--libdir=lib',
1259 '--default-library=static',
1260 '--buildtype=debug',
1261 '--strip'], default_args=False)
1262 self.build()
1263 self.install(use_destdir=False)
1264
1265 # build executable (uses lib, fails if static archive has been stripped incorrectly)
1266 pkg_dir = os.path.join(testlibprefix, 'lib/pkgconfig')
1267 self.new_builddir()
1268 self.init(os.path.join(testdirbase, 'app'),
1269 override_envvars={'PKG_CONFIG_PATH': pkg_dir})
1270 self.build()
1271
1272 @skipIfNoPkgconfig
1273 def test_pkgconfig_formatting(self):
1274 testdir = os.path.join(self.unit_test_dir, '38 pkgconfig format')
1275 self.init(testdir)
1276 myenv = os.environ.copy()
1277 myenv['PKG_CONFIG_PATH'] = _prepend_pkg_config_path(self.privatedir)
1278 stdo = subprocess.check_output([PKG_CONFIG, '--libs-only-l', 'libsomething'], env=myenv)
1279 deps = [b'-lgobject-2.0', b'-lgio-2.0', b'-lglib-2.0', b'-lsomething']
1280 if is_windows() or is_osx() or is_openbsd():
1281 # On Windows, libintl is a separate library
1282 # It used to be on Cygwin as well, but no longer is.
1283 deps.append(b'-lintl')
1284 self.assertEqual(set(deps), set(stdo.split()))
1285
1286 @skipIfNoPkgconfig
1287 @skip_if_not_language('cs')
1288 def test_pkgconfig_csharp_library(self):
1289 testdir = os.path.join(self.unit_test_dir, '49 pkgconfig csharp library')
1290 self.init(testdir)
1291 myenv = os.environ.copy()
1292 myenv['PKG_CONFIG_PATH'] = _prepend_pkg_config_path(self.privatedir)
1293 stdo = subprocess.check_output([PKG_CONFIG, '--libs', 'libsomething'], env=myenv)
1294
1295 self.assertEqual("-r/usr/lib/libsomething.dll", str(stdo.decode('ascii')).strip())
1296
1297 @skipIfNoPkgconfig
1298 def test_pkgconfig_link_order(self):
1299 '''
1300 Test that libraries are listed before their dependencies.
1301 '''
1302 testdir = os.path.join(self.unit_test_dir, '52 pkgconfig static link order')
1303 self.init(testdir)
1304 myenv = os.environ.copy()
1305 myenv['PKG_CONFIG_PATH'] = _prepend_pkg_config_path(self.privatedir)
1306 stdo = subprocess.check_output([PKG_CONFIG, '--libs', 'libsomething'], env=myenv)
1307 deps = stdo.split()
1308 self.assertLess(deps.index(b'-lsomething'), deps.index(b'-ldependency'))
1309
1310 def test_deterministic_dep_order(self):
1311 '''
1312 Test that the dependencies are always listed in a deterministic order.
1313 '''
1314 testdir = os.path.join(self.unit_test_dir, '42 dep order')
1315 self.init(testdir)
1316 with open(os.path.join(self.builddir, 'build.ninja'), encoding='utf-8') as bfile:
1317 for line in bfile:
1318 if 'build myexe:' in line or 'build myexe.exe:' in line:
1319 self.assertIn('liblib1.a liblib2.a', line)
1320 return
1321 raise RuntimeError('Could not find the build rule')
1322
1323 def test_deterministic_rpath_order(self):
1324 '''
1325 Test that the rpaths are always listed in a deterministic order.
1326 '''
1327 if is_cygwin():
1328 raise SkipTest('rpath are not used on Cygwin')
1329 testdir = os.path.join(self.unit_test_dir, '41 rpath order')
1330 self.init(testdir)
1331 if is_osx():
1332 rpathre = re.compile(r'-rpath,.*/subprojects/sub1.*-rpath,.*/subprojects/sub2')
1333 else:
1334 rpathre = re.compile(r'-rpath,\$\$ORIGIN/subprojects/sub1:\$\$ORIGIN/subprojects/sub2')
1335 with open(os.path.join(self.builddir, 'build.ninja'), encoding='utf-8') as bfile:
1336 for line in bfile:
1337 if '-rpath' in line:
1338 self.assertRegex(line, rpathre)
1339 return
1340 raise RuntimeError('Could not find the rpath')
1341
1342 def test_override_with_exe_dep(self):
1343 '''
1344 Test that we produce the correct dependencies when a program is overridden with an executable.
1345 '''
1346 testdir = os.path.join(self.src_root, 'test cases', 'native', '9 override with exe')
1347 self.init(testdir)
1348 with open(os.path.join(self.builddir, 'build.ninja'), encoding='utf-8') as bfile:
1349 for line in bfile:
1350 if 'main1.c:' in line or 'main2.c:' in line:
1351 self.assertIn('| subprojects/sub/foobar', line)
1352
1353 @skipIfNoPkgconfig
1354 def test_usage_external_library(self):
1355 '''
1356 Test that uninstalled usage of an external library (from the system or
1357 PkgConfigDependency) works. On macOS, this workflow works out of the
1358 box. On Linux, BSDs, Windows, etc, you need to set extra arguments such
1359 as LD_LIBRARY_PATH, etc, so this test is skipped.
1360
1361 The system library is found with cc.find_library() and pkg-config deps.
1362 '''
1363 oldprefix = self.prefix
1364 # Install external library so we can find it
1365 testdir = os.path.join(self.unit_test_dir, '39 external, internal library rpath', 'external library')
1366 # install into installdir without using DESTDIR
1367 installdir = self.installdir
1368 self.prefix = installdir
1369 self.init(testdir)
1370 self.prefix = oldprefix
1371 self.build()
1372 self.install(use_destdir=False)
1373 ## New builddir for the consumer
1374 self.new_builddir()
1375 env = {'LIBRARY_PATH': os.path.join(installdir, self.libdir),
1376 'PKG_CONFIG_PATH': _prepend_pkg_config_path(os.path.join(installdir, self.libdir, 'pkgconfig'))}
1377 testdir = os.path.join(self.unit_test_dir, '39 external, internal library rpath', 'built library')
1378 # install into installdir without using DESTDIR
1379 self.prefix = self.installdir
1380 self.init(testdir, override_envvars=env)
1381 self.prefix = oldprefix
1382 self.build(override_envvars=env)
1383 # test uninstalled
1384 self.run_tests(override_envvars=env)
1385 if not (is_osx() or is_linux()):
1386 return
1387 # test running after installation
1388 self.install(use_destdir=False)
1389 prog = os.path.join(self.installdir, 'bin', 'prog')
1390 self._run([prog])
1391 if not is_osx():
1392 # Rest of the workflow only works on macOS
1393 return
1394 out = self._run(['otool', '-L', prog])
1395 self.assertNotIn('@rpath', out)
1396 ## New builddir for testing that DESTDIR is not added to install_name
1397 self.new_builddir()
1398 # install into installdir with DESTDIR
1399 self.init(testdir, override_envvars=env)
1400 self.build(override_envvars=env)
1401 # test running after installation
1402 self.install(override_envvars=env)
1403 prog = self.installdir + os.path.join(self.prefix, 'bin', 'prog')
1404 lib = self.installdir + os.path.join(self.prefix, 'lib', 'libbar_built.dylib')
1405 for f in prog, lib:
1406 out = self._run(['otool', '-L', f])
1407 # Ensure that the otool output does not contain self.installdir
1408 self.assertNotRegex(out, self.installdir + '.*dylib ')
1409
1410 @skipIfNoPkgconfig
1411 def test_link_arg_fullname(self):
1412 '''
1413 Test for support of -l:libfullname.a
1414 see: https://github.com/mesonbuild/meson/issues/9000
1415 https://stackoverflow.com/questions/48532868/gcc-library-option-with-a-colon-llibevent-a
1416 '''
1417 testdir = os.path.join(self.unit_test_dir, '97 link full name','libtestprovider')
1418 oldprefix = self.prefix
1419 # install into installdir without using DESTDIR
1420 installdir = self.installdir
1421 self.prefix = installdir
1422 self.init(testdir)
1423 self.prefix=oldprefix
1424 self.build()
1425 self.install(use_destdir=False)
1426
1427 self.new_builddir()
1428 env = {'LIBRARY_PATH': os.path.join(installdir, self.libdir),
1429 'PKG_CONFIG_PATH': _prepend_pkg_config_path(os.path.join(installdir, self.libdir, 'pkgconfig'))}
1430 testdir = os.path.join(self.unit_test_dir, '97 link full name','proguser')
1431 self.init(testdir,override_envvars=env)
1432
1433 # test for link with full path
1434 with open(os.path.join(self.builddir, 'build.ninja'), encoding='utf-8') as bfile:
1435 for line in bfile:
1436 if 'build dprovidertest:' in line:
1437 self.assertIn('/libtestprovider.a', line)
1438
1439 if is_osx():
1440 # macOS's ld do not supports `--whole-archive`, skip build & run
1441 return
1442
1443 self.build(override_envvars=env)
1444
1445 # skip test if pkg-config is too old.
1446 # before v0.28, Libs flags like -Wl will not kept in context order with -l flags.
1447 # see https://gitlab.freedesktop.org/pkg-config/pkg-config/-/blob/master/NEWS
1448 pkgconfigver = subprocess.check_output([PKG_CONFIG, '--version'])
1449 if b'0.28' > pkgconfigver:
1450 raise SkipTest('pkg-config is too old to be correctly done this.')
1451 self.run_tests()
1452
1453 @skipIfNoPkgconfig
1454 def test_usage_pkgconfig_prefixes(self):
1455 '''
1456 Build and install two external libraries, to different prefixes,
1457 then build and install a client program that finds them via pkgconfig,
1458 and verify the installed client program runs.
1459 '''
1460 oldinstalldir = self.installdir
1461
1462 # Build and install both external libraries without DESTDIR
1463 val1dir = os.path.join(self.unit_test_dir, '74 pkgconfig prefixes', 'val1')
1464 val1prefix = os.path.join(oldinstalldir, 'val1')
1465 self.prefix = val1prefix
1466 self.installdir = val1prefix
1467 self.init(val1dir)
1468 self.build()
1469 self.install(use_destdir=False)
1470 self.new_builddir()
1471
1472 env1 = {}
1473 env1['PKG_CONFIG_PATH'] = os.path.join(val1prefix, self.libdir, 'pkgconfig')
1474 val2dir = os.path.join(self.unit_test_dir, '74 pkgconfig prefixes', 'val2')
1475 val2prefix = os.path.join(oldinstalldir, 'val2')
1476 self.prefix = val2prefix
1477 self.installdir = val2prefix
1478 self.init(val2dir, override_envvars=env1)
1479 self.build()
1480 self.install(use_destdir=False)
1481 self.new_builddir()
1482
1483 # Build, install, and run the client program
1484 env2 = {}
1485 env2['PKG_CONFIG_PATH'] = os.path.join(val2prefix, self.libdir, 'pkgconfig')
1486 testdir = os.path.join(self.unit_test_dir, '74 pkgconfig prefixes', 'client')
1487 testprefix = os.path.join(oldinstalldir, 'client')
1488 self.prefix = testprefix
1489 self.installdir = testprefix
1490 self.init(testdir, override_envvars=env2)
1491 self.build()
1492 self.install(use_destdir=False)
1493 prog = os.path.join(self.installdir, 'bin', 'client')
1494 env3 = {}
1495 if is_cygwin():
1496 env3['PATH'] = os.path.join(val1prefix, 'bin') + \
1497 os.pathsep + \
1498 os.path.join(val2prefix, 'bin') + \
1499 os.pathsep + os.environ['PATH']
1500 out = self._run([prog], override_envvars=env3).strip()
1501 # Expected output is val1 + val2 = 3
1502 self.assertEqual(out, '3')
1503
1504 def install_subdir_invalid_symlinks(self, testdir, subdir_path):
1505 '''
1506 Test that installation of broken symlinks works fine.
1507 https://github.com/mesonbuild/meson/issues/3914
1508 '''
1509 testdir = self.copy_srcdir(os.path.join(self.common_test_dir, testdir))
1510 subdir = os.path.join(testdir, subdir_path)
1511 with chdir(subdir):
1512 # Can't distribute broken symlinks in the source tree because it breaks
1513 # the creation of zipapps. Create it dynamically and run the test by
1514 # hand.
1515 src = '../../nonexistent.txt'
1516 os.symlink(src, 'invalid-symlink.txt')
1517 self.init(testdir)
1518 self.build()
1519 self.install()
1520 install_path = subdir_path.split(os.path.sep)[-1]
1521 link = os.path.join(self.installdir, 'usr', 'share', install_path, 'invalid-symlink.txt')
1522 self.assertTrue(os.path.islink(link), msg=link)
1523 self.assertEqual(src, os.readlink(link))
1524 self.assertFalse(os.path.isfile(link), msg=link)
1525
1526 def test_install_subdir_symlinks(self):
1527 self.install_subdir_invalid_symlinks('59 install subdir', os.path.join('sub', 'sub1'))
1528
1529 def test_install_subdir_symlinks_with_default_umask(self):
1530 self.install_subdir_invalid_symlinks('190 install_mode', 'sub2')
1531
1532 def test_install_subdir_symlinks_with_default_umask_and_mode(self):
1533 self.install_subdir_invalid_symlinks('190 install_mode', 'sub1')
1534
1535 @skipIfNoPkgconfigDep('gmodule-2.0')
1536 def test_ldflag_dedup(self):
1537 testdir = os.path.join(self.unit_test_dir, '51 ldflagdedup')
1538 if is_cygwin() or is_osx():
1539 raise SkipTest('Not applicable on Cygwin or OSX.')
1540 env = get_fake_env()
1541 cc = detect_c_compiler(env, MachineChoice.HOST)
1542 linker = cc.linker
1543 if not linker.export_dynamic_args():
1544 raise SkipTest('Not applicable for linkers without --export-dynamic')
1545 self.init(testdir)
1546 build_ninja = os.path.join(self.builddir, 'build.ninja')
1547 max_count = 0
1548 search_term = '-Wl,--export-dynamic'
1549 with open(build_ninja, encoding='utf-8') as f:
1550 for line in f:
1551 max_count = max(max_count, line.count(search_term))
1552 self.assertEqual(max_count, 1, 'Export dynamic incorrectly deduplicated.')
1553
1554 def test_compiler_libs_static_dedup(self):
1555 testdir = os.path.join(self.unit_test_dir, '55 dedup compiler libs')
1556 self.init(testdir)
1557 build_ninja = os.path.join(self.builddir, 'build.ninja')
1558 with open(build_ninja, encoding='utf-8') as f:
1559 lines = f.readlines()
1560 for lib in ('-ldl', '-lm', '-lc', '-lrt'):
1561 for line in lines:
1562 if lib not in line:
1563 continue
1564 # Assert that
1565 self.assertEqual(len(line.split(lib)), 2, msg=(lib, line))
1566
1567 @skipIfNoPkgconfig
1568 def test_noncross_options(self):
1569 # C_std defined in project options must be in effect also when native compiling.
1570 testdir = os.path.join(self.unit_test_dir, '50 noncross options')
1571 self.init(testdir, extra_args=['-Dpkg_config_path=' + testdir])
1572 compdb = self.get_compdb()
1573 self.assertEqual(len(compdb), 2)
1574 self.assertRegex(compdb[0]['command'], '-std=c99')
1575 self.assertRegex(compdb[1]['command'], '-std=c99')
1576 self.build()
1577
1578 def test_identity_cross(self):
1579 testdir = os.path.join(self.unit_test_dir, '60 identity cross')
1580
1581 constantsfile = tempfile.NamedTemporaryFile(mode='w', encoding='utf-8')
1582 constantsfile.write(textwrap.dedent('''\
1583 [constants]
1584 py_ext = '.py'
1585 '''))
1586 constantsfile.flush()
1587
1588 nativefile = tempfile.NamedTemporaryFile(mode='w', encoding='utf-8')
1589 nativefile.write(textwrap.dedent('''\
1590 [binaries]
1591 c = ['{}' + py_ext]
1592 '''.format(os.path.join(testdir, 'build_wrapper'))))
1593 nativefile.flush()
1594 self.meson_native_files = [constantsfile.name, nativefile.name]
1595
1596 crossfile = tempfile.NamedTemporaryFile(mode='w', encoding='utf-8')
1597 crossfile.write(textwrap.dedent('''\
1598 [binaries]
1599 c = ['{}' + py_ext]
1600 '''.format(os.path.join(testdir, 'host_wrapper'))))
1601 crossfile.flush()
1602 self.meson_cross_files = [constantsfile.name, crossfile.name]
1603
1604 # TODO should someday be explicit about build platform only here
1605 self.init(testdir)
1606
1607 def test_identity_cross_env(self):
1608 testdir = os.path.join(self.unit_test_dir, '60 identity cross')
1609 env = {
1610 'CC_FOR_BUILD': '"' + os.path.join(testdir, 'build_wrapper.py') + '"',
1611 'CC': '"' + os.path.join(testdir, 'host_wrapper.py') + '"',
1612 }
1613 crossfile = tempfile.NamedTemporaryFile(mode='w', encoding='utf-8')
1614 crossfile.write('')
1615 crossfile.flush()
1616 self.meson_cross_files = [crossfile.name]
1617 # TODO should someday be explicit about build platform only here
1618 self.init(testdir, override_envvars=env)
1619
1620 @skipIfNoPkgconfig
1621 def test_static_link(self):
1622 if is_cygwin():
1623 raise SkipTest("Cygwin doesn't support LD_LIBRARY_PATH.")
1624
1625 # Build some libraries and install them
1626 testdir = os.path.join(self.unit_test_dir, '66 static link/lib')
1627 libdir = os.path.join(self.installdir, self.libdir)
1628 oldprefix = self.prefix
1629 self.prefix = self.installdir
1630 self.init(testdir)
1631 self.install(use_destdir=False)
1632
1633 # Test that installed libraries works
1634 self.new_builddir()
1635 self.prefix = oldprefix
1636 meson_args = [f'-Dc_link_args=-L{libdir}',
1637 '--fatal-meson-warnings']
1638 testdir = os.path.join(self.unit_test_dir, '66 static link')
1639 env = {'PKG_CONFIG_LIBDIR': os.path.join(libdir, 'pkgconfig')}
1640 self.init(testdir, extra_args=meson_args, override_envvars=env)
1641 self.build()
1642 self.run_tests()
1643
1644 def _check_ld(self, check: str, name: str, lang: str, expected: str) -> None:
1645 if is_sunos():
1646 raise SkipTest('Solaris currently cannot override the linker.')
1647 if not shutil.which(check):
1648 raise SkipTest(f'Could not find {check}.')
1649 envvars = mesonbuild.envconfig.ENV_VAR_PROG_MAP[f'{lang}_ld'].copy()
1650
1651 # Also test a deprecated variable if there is one.
1652 if f'{lang}_ld' in mesonbuild.envconfig.DEPRECATED_ENV_PROG_MAP:
1653 envvars.extend(
1654 mesonbuild.envconfig.DEPRECATED_ENV_PROG_MAP[f'{lang}_ld'])
1655
1656 for envvar in envvars:
1657 with mock.patch.dict(os.environ, {envvar: name}):
1658 env = get_fake_env()
1659 comp = compiler_from_language(env, lang, MachineChoice.HOST)
1660 if isinstance(comp, (AppleClangCCompiler, AppleClangCPPCompiler,
1661 AppleClangObjCCompiler, AppleClangObjCPPCompiler)):
1662 raise SkipTest('AppleClang is currently only supported with ld64')
1663 if isinstance(comp, ElbrusCompiler):
1664 raise SkipTest('ElbrusCompiler currently cannot override the linker.')
1665 if lang != 'rust' and comp.use_linker_args('bfd', '') == []:
1666 raise SkipTest(
1667 f'Compiler {comp.id} does not support using alternative linkers')
1668 self.assertEqual(comp.linker.id, expected)
1669
1670 def test_ld_environment_variable_bfd(self):
1671 self._check_ld('ld.bfd', 'bfd', 'c', 'ld.bfd')
1672
1673 def test_ld_environment_variable_gold(self):
1674 self._check_ld('ld.gold', 'gold', 'c', 'ld.gold')
1675
1676 def test_ld_environment_variable_lld(self):
1677 self._check_ld('ld.lld', 'lld', 'c', 'ld.lld')
1678
1679 @skip_if_not_language('rust')
1680 @skipIfNoExecutable('ld.gold') # need an additional check here because _check_ld checks for gcc
1681 def test_ld_environment_variable_rust(self):
1682 self._check_ld('gcc', 'gcc -fuse-ld=gold', 'rust', 'ld.gold')
1683
1684 def test_ld_environment_variable_cpp(self):
1685 self._check_ld('ld.gold', 'gold', 'cpp', 'ld.gold')
1686
1687 @skip_if_not_language('objc')
1688 def test_ld_environment_variable_objc(self):
1689 self._check_ld('ld.gold', 'gold', 'objc', 'ld.gold')
1690
1691 @skip_if_not_language('objcpp')
1692 def test_ld_environment_variable_objcpp(self):
1693 self._check_ld('ld.gold', 'gold', 'objcpp', 'ld.gold')
1694
1695 @skip_if_not_language('fortran')
1696 def test_ld_environment_variable_fortran(self):
1697 self._check_ld('ld.gold', 'gold', 'fortran', 'ld.gold')
1698
1699 @skip_if_not_language('d')
1700 def test_ld_environment_variable_d(self):
1701 # At least for me, ldc defaults to gold, and gdc defaults to bfd, so
1702 # let's pick lld, which isn't the default for either (currently)
1703 if is_osx():
1704 expected = 'ld64'
1705 else:
1706 expected = 'ld.lld'
1707 self._check_ld('ld.lld', 'lld', 'd', expected)
1708
1709 def compute_sha256(self, filename):
1710 with open(filename, 'rb') as f:
1711 return hashlib.sha256(f.read()).hexdigest()
1712
1713 def test_wrap_with_file_url(self):
1714 testdir = os.path.join(self.unit_test_dir, '72 wrap file url')
1715 source_filename = os.path.join(testdir, 'subprojects', 'foo.tar.xz')
1716 patch_filename = os.path.join(testdir, 'subprojects', 'foo-patch.tar.xz')
1717 wrap_filename = os.path.join(testdir, 'subprojects', 'foo.wrap')
1718 source_hash = self.compute_sha256(source_filename)
1719 patch_hash = self.compute_sha256(patch_filename)
1720 wrap = textwrap.dedent("""\
1721 [wrap-file]
1722 directory = foo
1723
1724 source_url = http://server.invalid/foo
1725 source_fallback_url = file://{}
1726 source_filename = foo.tar.xz
1727 source_hash = {}
1728
1729 patch_url = http://server.invalid/foo
1730 patch_fallback_url = file://{}
1731 patch_filename = foo-patch.tar.xz
1732 patch_hash = {}
1733 """.format(source_filename, source_hash, patch_filename, patch_hash))
1734 with open(wrap_filename, 'w', encoding='utf-8') as f:
1735 f.write(wrap)
1736 self.init(testdir)
1737 self.build()
1738 self.run_tests()
1739
1740 windows_proof_rmtree(os.path.join(testdir, 'subprojects', 'packagecache'))
1741 windows_proof_rmtree(os.path.join(testdir, 'subprojects', 'foo'))
1742 os.unlink(wrap_filename)
1743
1744 def test_no_rpath_for_static(self):
1745 testdir = os.path.join(self.common_test_dir, '5 linkstatic')
1746 self.init(testdir)
1747 self.build()
1748 build_rpath = get_rpath(os.path.join(self.builddir, 'prog'))
1749 self.assertIsNone(build_rpath)
1750
1751 def test_lookup_system_after_broken_fallback(self):
1752 # Just to generate libfoo.pc so we can test system dependency lookup.
1753 testdir = os.path.join(self.common_test_dir, '44 pkgconfig-gen')
1754 self.init(testdir)
1755 privatedir = self.privatedir
1756
1757 # Write test project where the first dependency() returns not-found
1758 # because 'broken' subproject does not exit, but that should not prevent
1759 # the 2nd dependency() to lookup on system.
1760 self.new_builddir()
1761 with tempfile.TemporaryDirectory() as d:
1762 with open(os.path.join(d, 'meson.build'), 'w', encoding='utf-8') as f:
1763 f.write(textwrap.dedent('''\
1764 project('test')
1765 dependency('notfound', fallback: 'broken', required: false)
1766 dependency('libfoo', fallback: 'broken', required: true)
1767 '''))
1768 self.init(d, override_envvars={'PKG_CONFIG_LIBDIR': privatedir})
1769
1770 def test_as_link_whole(self):
1771 testdir = os.path.join(self.unit_test_dir, '76 as link whole')
1772 self.init(testdir)
1773 with open(os.path.join(self.privatedir, 'bar1.pc'), encoding='utf-8') as f:
1774 content = f.read()
1775 self.assertIn('-lfoo', content)
1776 with open(os.path.join(self.privatedir, 'bar2.pc'), encoding='utf-8') as f:
1777 content = f.read()
1778 self.assertNotIn('-lfoo', content)
1779
1780 def test_prelinking(self):
1781 testdir = os.path.join(self.unit_test_dir, '86 prelinking')
1782 env = get_fake_env(testdir, self.builddir, self.prefix)
1783 cc = detect_c_compiler(env, MachineChoice.HOST)
1784 if cc.id == "gcc" and not version_compare(cc.version, '>=9'):
1785 raise SkipTest('Prelinking not supported with gcc 8 or older.')
1786 if cc.id == 'clang' and not version_compare(cc.version, '>=14'):
1787 raise SkipTest('Prelinking not supported with Clang 13 or older.')
1788 self.init(testdir)
1789 self.build()
1790 outlib = os.path.join(self.builddir, 'libprelinked.a')
1791 ar = shutil.which('ar')
1792 self.assertPathExists(outlib)
1793 self.assertIsNotNone(ar)
1794 p = subprocess.run([ar, 't', outlib],
1795 stdout=subprocess.PIPE,
1796 stderr=subprocess.DEVNULL,
1797 encoding='utf-8', text=True, timeout=1)
1798 obj_files = p.stdout.strip().split('\n')
1799 self.assertTrue(any(o.endswith('-prelink.o') for o in obj_files))
1800
1801 def do_one_test_with_nativefile(self, testdir, args):
1802 testdir = os.path.join(self.common_test_dir, testdir)
1803 with tempfile.TemporaryDirectory() as d:
1804 p = Path(d) / 'nativefile'
1805 with p.open('wt', encoding='utf-8') as f:
1806 f.write(f'''[binaries]
1807 c = {args}
1808 ''')
1809 self.init(testdir, extra_args=['--native-file=' + str(p)])
1810 self.build()
1811
1812 def test_cmake_multilib(self):
1813 '''
1814 Test that the cmake module handles multilib paths correctly.
1815 '''
1816 # Verify that "gcc -m32" works
1817 try:
1818 self.do_one_test_with_nativefile('1 trivial', "['gcc', '-m32']")
1819 except subprocess.CalledProcessError as e:
1820 raise SkipTest('Not GCC, or GCC does not have the -m32 option')
1821 self.wipe()
1822
1823 # Verify that cmake works
1824 try:
1825 self.do_one_test_with_nativefile('../cmake/1 basic', "['gcc']")
1826 except subprocess.CalledProcessError as e:
1827 raise SkipTest('Could not build basic cmake project')
1828 self.wipe()
1829
1830 # If so, we can test that cmake works with "gcc -m32"
1831 self.do_one_test_with_nativefile('../cmake/1 basic', "['gcc', '-m32']")
1832
1833 @skipUnless(is_linux() or is_osx(), 'Test only applicable to Linux and macOS')
1834 def test_install_strip(self):
1835 testdir = os.path.join(self.unit_test_dir, '103 strip')
1836 self.init(testdir)
1837 self.build()
1838
1839 destdir = self.installdir + self.prefix
1840 if is_linux():
1841 lib = os.path.join(destdir, self.libdir, 'liba.so')
1842 else:
1843 lib = os.path.join(destdir, self.libdir, 'liba.dylib')
1844 install_cmd = self.meson_command + ['install', '--destdir', self.installdir]
1845
1846 # Check we have debug symbols by default
1847 self._run(install_cmd, workdir=self.builddir)
1848 if is_linux():
1849 # file can detect stripped libraries on linux
1850 stdout = self._run(['file', '-b', lib])
1851 self.assertIn('not stripped', stdout)
1852 else:
1853 # on macOS we need to query dsymutil instead.
1854 # Alternatively, check if __dyld_private is defined
1855 # in the output of nm liba.dylib, but that is not
1856 # 100% reliable, it needs linking to an external library
1857 stdout = self._run(['dsymutil', '--dump-debug-map', lib])
1858 self.assertIn('symbols:', stdout)
1859
1860 # Check debug symbols got removed with --strip
1861 self._run(install_cmd + ['--strip'], workdir=self.builddir)
1862 if is_linux():
1863 stdout = self._run(['file', '-b', lib])
1864 self.assertNotIn('not stripped', stdout)
1865 else:
1866 stdout = self._run(['dsymutil', '--dump-debug-map', lib])
1867 self.assertNotIn('symbols:', stdout)
1868
1869 def test_isystem_default_removal_with_symlink(self):
1870 env = get_fake_env()
1871 cpp = detect_cpp_compiler(env, MachineChoice.HOST)
1872 default_dirs = cpp.get_default_include_dirs()
1873 default_symlinks = []
1874 with tempfile.TemporaryDirectory() as tmpdir:
1875 for i in range(len(default_dirs)):
1876 symlink = f'{tmpdir}/default_dir{i}'
1877 default_symlinks.append(symlink)
1878 os.symlink(default_dirs[i], symlink)
1879 self.assertFalse(cpp.compiler_args([f'-isystem{symlink}' for symlink in default_symlinks]).to_native())
1880
1881 def test_freezing(self):
1882 testdir = os.path.join(self.unit_test_dir, '110 freeze')
1883 self.init(testdir)
1884 self.build()
1885 with self.assertRaises(subprocess.CalledProcessError) as e:
1886 self.run_tests()
1887 self.assertNotIn('Traceback', e.exception.output)
1888
1889 @skipUnless(is_linux(), "Ninja file differs on different platforms")
1890 def test_complex_link_cases(self):
1891 testdir = os.path.join(self.unit_test_dir, '114 complex link cases')
1892 self.init(testdir)
1893 self.build()
1894 with open(os.path.join(self.builddir, 'build.ninja'), encoding='utf-8') as f:
1895 content = f.read()
1896 # Verify link dependencies, see comments in meson.build.
1897 self.assertIn('build libt1-s3.a: STATIC_LINKER libt1-s2.a.p/s2.c.o libt1-s3.a.p/s3.c.o\n', content)
1898 self.assertIn('build t1-e1: c_LINKER t1-e1.p/main.c.o | libt1-s1.a libt1-s3.a\n', content)
1899 self.assertIn('build libt2-s3.a: STATIC_LINKER libt2-s2.a.p/s2.c.o libt2-s1.a.p/s1.c.o libt2-s3.a.p/s3.c.o\n', content)
1900 self.assertIn('build t2-e1: c_LINKER t2-e1.p/main.c.o | libt2-s3.a\n', content)
1901 self.assertIn('build t3-e1: c_LINKER t3-e1.p/main.c.o | libt3-s3.so.p/libt3-s3.so.symbols\n', content)
1902 self.assertIn('build t4-e1: c_LINKER t4-e1.p/main.c.o | libt4-s2.so.p/libt4-s2.so.symbols libt4-s3.a\n', content)
1903 self.assertIn('build t5-e1: c_LINKER t5-e1.p/main.c.o | libt5-s1.so.p/libt5-s1.so.symbols libt5-s3.a\n', content)
1904 self.assertIn('build t6-e1: c_LINKER t6-e1.p/main.c.o | libt6-s2.a libt6-s3.a\n', content)
1905 self.assertIn('build t7-e1: c_LINKER t7-e1.p/main.c.o | libt7-s3.a\n', content)
1906 self.assertIn('build t8-e1: c_LINKER t8-e1.p/main.c.o | libt8-s1.a libt8-s2.a libt8-s3.a\n', content)
1907 self.assertIn('build t9-e1: c_LINKER t9-e1.p/main.c.o | libt9-s1.a libt9-s2.a libt9-s3.a\n', content)
1908 self.assertIn('build t12-e1: c_LINKER t12-e1.p/main.c.o | libt12-s1.a libt12-s2.a libt12-s3.a\n', content)
1909 self.assertIn('build t13-e1: c_LINKER t13-e1.p/main.c.o | libt12-s1.a libt13-s3.a\n', content)
1910
1911 def test_top_options_in_sp(self):
1912 testdir = os.path.join(self.unit_test_dir, '127 pkgsubproj')
1913 self.init(testdir)
1914
1915 def test_unreadable_dir_in_declare_dep(self):
1916 testdir = os.path.join(self.unit_test_dir, '125 declare_dep var')
1917 tmpdir = Path(tempfile.mkdtemp())
1918 self.addCleanup(windows_proof_rmtree, tmpdir)
1919 declaredepdir = tmpdir / 'test'
1920 declaredepdir.mkdir()
1921 try:
1922 tmpdir.chmod(0o444)
1923 self.init(testdir, extra_args=f'-Ddir={declaredepdir}')
1924 finally:
1925 tmpdir.chmod(0o755)
1926
1927 def check_has_flag(self, compdb, src, argument):
1928 for i in compdb:
1929 if src in i['file']:
1930 self.assertIn(argument, i['command'])
1931 return
1932 self.assertTrue(False, f'Source {src} not found in compdb')
1933
1934 def test_persp_options(self):
1935 if self.backend is not Backend.ninja:
1936 raise SkipTest(f'{self.backend.name!r} backend can\'t install files')
1937
1938 testdir = os.path.join(self.unit_test_dir, '122 persp options')
1939
1940 with self.subTest('init'):
1941 self.init(testdir, extra_args='-Doptimization=1')
1942 compdb = self.get_compdb()
1943 mainsrc = 'toplevel.c'
1944 sub1src = 'sub1.c'
1945 sub2src = 'sub2.c'
1946 self.check_has_flag(compdb, mainsrc, '-O1')
1947 self.check_has_flag(compdb, sub1src, '-O1')
1948 self.check_has_flag(compdb, sub2src, '-O1')
1949
1950 # Set subproject option to O2
1951 with self.subTest('set subproject option'):
1952 self.setconf(['-Dround=2', '-D', 'sub2:optimization=3'])
1953 compdb = self.get_compdb()
1954 self.check_has_flag(compdb, mainsrc, '-O1')
1955 self.check_has_flag(compdb, sub1src, '-O1')
1956 self.check_has_flag(compdb, sub2src, '-O3')
1957
1958 # Change an already set override.
1959 with self.subTest('change subproject option'):
1960 self.setconf(['-Dround=3', '-D', 'sub2:optimization=2'])
1961 compdb = self.get_compdb()
1962 self.check_has_flag(compdb, mainsrc, '-O1')
1963 self.check_has_flag(compdb, sub1src, '-O1')
1964 self.check_has_flag(compdb, sub2src, '-O2')
1965
1966 # Set top level option to O3
1967 with self.subTest('change main project option'):
1968 self.setconf(['-Dround=4', '-D:optimization=3'])
1969 compdb = self.get_compdb()
1970 self.check_has_flag(compdb, mainsrc, '-O3')
1971 self.check_has_flag(compdb, sub1src, '-O1')
1972 self.check_has_flag(compdb, sub2src, '-O2')
1973
1974 # Unset subproject
1975 with self.subTest('unset subproject option'):
1976 self.setconf(['-Dround=5', '-U', 'sub2:optimization'])
1977 compdb = self.get_compdb()
1978 self.check_has_flag(compdb, mainsrc, '-O3')
1979 self.check_has_flag(compdb, sub1src, '-O1')
1980 self.check_has_flag(compdb, sub2src, '-O1')
1981
1982 # Set global value
1983 with self.subTest('set global option'):
1984 self.setconf(['-Dround=6', '-D', 'optimization=2'])
1985 compdb = self.get_compdb()
1986 self.check_has_flag(compdb, mainsrc, '-O3')
1987 self.check_has_flag(compdb, sub1src, '-O2')
1988 self.check_has_flag(compdb, sub2src, '-O2')
1989
1990 @skip_if_not_language('rust')
1991 @skip_if_not_base_option('b_sanitize')
1992 def test_rust_sanitizers(self):
1993 args = ['-Drust_nightly=disabled', '-Db_lundef=false']
1994 testdir = os.path.join(self.rust_test_dir, '28 mixed')
1995 tests = ['address']
1996
1997 env = get_fake_env(testdir, self.builddir, self.prefix)
1998 cpp = detect_cpp_compiler(env, MachineChoice.HOST)
1999 if cpp.find_library('ubsan', []):
2000 tests += ['address,undefined']
2001
2002 for value in tests:
2003 self.init(testdir, extra_args=args + ['-Db_sanitize=' + value])
2004 self.build()
2005 self.wipe()
2006
2007 @skip_if_not_language('rust')
2008 def test_rust_staticlib_rlib_deps(self):
2009 '''
2010 Test that when a C executable links with a Rust staticlib, the rlib
2011 dependencies of the staticlib are not passed to the C linker.
2012 See: https://github.com/mesonbuild/meson/issues/11721
2013 '''
2014 testdir = os.path.join(self.rust_test_dir, '36 staticlib rlib deps')
2015 self.init(testdir)
2016 targets = self.introspect('--targets')
2017 executable = next(t for t in targets if t['type'] == 'executable')
2018 linker = next(src for src in executable['target_sources'] if 'linker' in src)
2019 for param in linker['parameters']:
2020 self.assertNotIn('liblib.rlib', param)
2021
2022 def test_sanitizers(self):
2023 testdir = os.path.join(self.unit_test_dir, '129 sanitizers')
2024
2025 with self.subTest('no b_sanitize value'):
2026 try:
2027 out = self.init(testdir)
2028 self.assertRegex(out, 'value *: *none')
2029 finally:
2030 self.wipe()
2031
2032 for value, expected in { '': 'none',
2033 'none': 'none',
2034 'address': 'address',
2035 'undefined,address': 'address,undefined',
2036 'address,undefined': 'address,undefined' }.items():
2037 with self.subTest('b_sanitize=' + value):
2038 try:
2039 out = self.init(testdir, extra_args=['-Db_sanitize=' + value])
2040 self.assertRegex(out, 'value *: *' + expected)
2041 finally:
2042 self.wipe()