Debian Codegraph @

unittests/windowstests.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2016-2021 The Meson development team
3
4 import subprocess
5 import re
6 import os
7 import shutil
8 from unittest import mock, SkipTest, skipUnless, skipIf
9 from glob import glob
10
11 import mesonbuild.mlog
12 import mesonbuild.depfile
13 import mesonbuild.dependencies.factory
14 import mesonbuild.envconfig
15 import mesonbuild.environment
16 import mesonbuild.coredata
17 import mesonbuild.modules.gnome
18 from mesonbuild.mesonlib import (
19 MachineChoice, is_windows, is_cygwin, python_command, version_compare,
20 EnvironmentException
21 )
22 from mesonbuild.options import OptionKey
23 from mesonbuild.compilers import (
24 detect_c_compiler, detect_d_compiler, compiler_from_language,
25 )
26 from mesonbuild.programs import ExternalProgram
27 import mesonbuild.dependencies.base
28 import mesonbuild.modules.pkgconfig
29
30
31 from run_tests import (
32 Backend, get_fake_env
33 )
34
35 from .baseplatformtests import BasePlatformTests
36 from .helpers import *
37
38 @skipUnless(is_windows() or is_cygwin(), "requires Windows (or Windows via Cygwin)")
39 class WindowsTests(BasePlatformTests):
40 '''
41 Tests that should run on Cygwin, MinGW, and MSVC
42 '''
43
44 def setUp(self):
45 super().setUp()
46 self.platform_test_dir = os.path.join(self.src_root, 'test cases/windows')
47
48 @skipIf(is_cygwin(), 'Test only applicable to Windows')
49 @mock.patch.dict(os.environ)
50 def test_find_program(self):
51 '''
52 Test that Windows-specific edge-cases in find_program are functioning
53 correctly. Cannot be an ordinary test because it involves manipulating
54 PATH to point to a directory with Python scripts.
55 '''
56 testdir = os.path.join(self.platform_test_dir, '8 find program')
57 # Find `cmd` and `cmd.exe`
58 prog1 = ExternalProgram('cmd')
59 self.assertTrue(prog1.found(), msg='cmd not found')
60 prog2 = ExternalProgram('cmd.exe')
61 self.assertTrue(prog2.found(), msg='cmd.exe not found')
62 self.assertPathEqual(prog1.get_path(), prog2.get_path())
63 # Find cmd.exe with args without searching
64 prog = ExternalProgram('cmd', command=['cmd', '/C'])
65 self.assertTrue(prog.found(), msg='cmd not found with args')
66 self.assertPathEqual(prog.get_command()[0], 'cmd')
67 # Find cmd with an absolute path that's missing the extension
68 cmd_path = prog2.get_path()[:-4]
69 prog = ExternalProgram(cmd_path)
70 self.assertTrue(prog.found(), msg=f'{cmd_path!r} not found')
71 # Finding a script with no extension inside a directory works
72 prog = ExternalProgram(os.path.join(testdir, 'test-script'))
73 self.assertTrue(prog.found(), msg='test-script not found')
74 # Finding a script with an extension inside a directory works
75 prog = ExternalProgram(os.path.join(testdir, 'test-script-ext.py'))
76 self.assertTrue(prog.found(), msg='test-script-ext.py not found')
77 # Finding a script in PATH
78 os.environ['PATH'] += os.pathsep + testdir
79 # If `.PY` is in PATHEXT, scripts can be found as programs
80 if '.PY' in [ext.upper() for ext in os.environ['PATHEXT'].split(';')]:
81 # Finding a script in PATH w/o extension works and adds the interpreter
82 prog = ExternalProgram('test-script-ext')
83 self.assertTrue(prog.found(), msg='test-script-ext not found in PATH')
84 self.assertPathEqual(prog.get_command()[0], python_command[0])
85 self.assertPathBasenameEqual(prog.get_path(), 'test-script-ext.py')
86 # Finding a script in PATH with extension works and adds the interpreter
87 prog = ExternalProgram('test-script-ext.py')
88 self.assertTrue(prog.found(), msg='test-script-ext.py not found in PATH')
89 self.assertPathEqual(prog.get_command()[0], python_command[0])
90 self.assertPathBasenameEqual(prog.get_path(), 'test-script-ext.py')
91 # Using a script with an extension directly via command= works and adds the interpreter
92 prog = ExternalProgram('test-script-ext.py', command=[os.path.join(testdir, 'test-script-ext.py'), '--help'])
93 self.assertTrue(prog.found(), msg='test-script-ext.py with full path not picked up via command=')
94 self.assertPathEqual(prog.get_command()[0], python_command[0])
95 self.assertPathEqual(prog.get_command()[2], '--help')
96 self.assertPathBasenameEqual(prog.get_path(), 'test-script-ext.py')
97 # Using a script without an extension directly via command= works and adds the interpreter
98 prog = ExternalProgram('test-script', command=[os.path.join(testdir, 'test-script'), '--help'])
99 self.assertTrue(prog.found(), msg='test-script with full path not picked up via command=')
100 self.assertPathEqual(prog.get_command()[0], python_command[0])
101 self.assertPathEqual(prog.get_command()[2], '--help')
102 self.assertPathBasenameEqual(prog.get_path(), 'test-script')
103 # Ensure that WindowsApps gets removed from PATH
104 path = os.environ['PATH']
105 if 'WindowsApps' not in path:
106 username = os.environ['USERNAME']
107 appstore_dir = fr'C:\Users\{username}\AppData\Local\Microsoft\WindowsApps'
108 path = os.pathsep + appstore_dir
109 path = ExternalProgram._windows_sanitize_path(path)
110 self.assertNotIn('WindowsApps', path)
111
112 def test_ignore_libs(self):
113 '''
114 Test that find_library on libs that are to be ignored returns an empty
115 array of arguments. Must be a unit test because we cannot inspect
116 ExternalLibraryHolder from build files.
117 '''
118 testdir = os.path.join(self.platform_test_dir, '1 basic')
119 env = get_fake_env(testdir, self.builddir, self.prefix)
120 cc = detect_c_compiler(env, MachineChoice.HOST)
121 if cc.get_argument_syntax() != 'msvc':
122 raise SkipTest('Not using MSVC')
123 # To force people to update this test, and also test
124 self.assertEqual(set(cc.ignore_libs), {'c', 'm', 'pthread', 'dl', 'rt', 'execinfo'})
125 for l in cc.ignore_libs:
126 self.assertEqual(cc.find_library(l, env, []), [])
127
128 def test_rc_depends_files(self):
129 testdir = os.path.join(self.platform_test_dir, '5 resources')
130
131 # resource compiler depfile generation is not yet implemented for msvc
132 env = get_fake_env(testdir, self.builddir, self.prefix)
133 depfile_works = detect_c_compiler(env, MachineChoice.HOST).get_id() not in {'msvc', 'clang-cl', 'intel-cl'}
134
135 self.init(testdir)
136 self.build()
137 # Immediately rebuilding should not do anything
138 self.assertBuildIsNoop()
139 # Test compile_resources(depend_file:)
140 # Changing mtime of sample.ico should rebuild prog
141 self.utime(os.path.join(testdir, 'res', 'sample.ico'))
142 self.assertRebuiltTarget('prog')
143 # Test depfile generation by compile_resources
144 # Changing mtime of resource.h should rebuild myres.rc and then prog
145 if depfile_works:
146 self.utime(os.path.join(testdir, 'inc', 'resource', 'resource.h'))
147 self.assertRebuiltTarget('prog')
148 self.wipe()
149
150 if depfile_works:
151 testdir = os.path.join(self.platform_test_dir, '12 resources with custom targets')
152 self.init(testdir)
153 self.build()
154 # Immediately rebuilding should not do anything
155 self.assertBuildIsNoop()
156 # Changing mtime of resource.h should rebuild myres_1.rc and then prog_1
157 self.utime(os.path.join(testdir, 'res', 'resource.h'))
158 self.assertRebuiltTarget('prog_1')
159
160 def test_msvc_cpp17(self):
161 testdir = os.path.join(self.unit_test_dir, '44 vscpp17')
162
163 env = get_fake_env(testdir, self.builddir, self.prefix)
164 cc = detect_c_compiler(env, MachineChoice.HOST)
165 if cc.get_argument_syntax() != 'msvc':
166 raise SkipTest('Test only applies to MSVC-like compilers')
167
168 try:
169 self.init(testdir)
170 except subprocess.CalledProcessError:
171 # According to Python docs, output is only stored when
172 # using check_output. We don't use it, so we can't check
173 # that the output is correct (i.e. that it failed due
174 # to the right reason).
175 return
176 self.build()
177
178 @skipIf(is_cygwin(), 'Test only applicable to Windows')
179 def test_genvslite(self):
180 # The test framework itself might be forcing a specific, non-ninja backend across a set of tests, which
181 # includes this test. E.g. -
182 # > python.exe run_unittests.py --backend=vs WindowsTests
183 # Since that explicitly specifies a backend that's incompatible with (and essentially meaningless in
184 # conjunction with) 'genvslite', we should skip further genvslite testing.
185 if self.backend is not Backend.ninja:
186 raise SkipTest('Test only applies when using the Ninja backend')
187
188 testdir = os.path.join(self.unit_test_dir, '117 genvslite')
189
190 env = get_fake_env(testdir, self.builddir, self.prefix)
191 cc = detect_c_compiler(env, MachineChoice.HOST)
192 if cc.get_argument_syntax() != 'msvc':
193 raise SkipTest('Test only applies when MSVC tools are available.')
194
195 # We want to run the genvslite setup. I.e. -
196 # meson setup --genvslite vs2022 ...
197 # which we should expect to generate the set of _debug/_debugoptimized/_release suffixed
198 # build directories. Then we want to check that the solution/project build hooks (like clean,
199 # build, and rebuild) end up ultimately invoking the 'meson compile ...' of the appropriately
200 # suffixed build dir, for which we need to use 'msbuild.exe'
201
202 # Find 'msbuild.exe'
203 msbuildprog = ExternalProgram('msbuild.exe')
204 self.assertTrue(msbuildprog.found(), msg='msbuild.exe not found')
205
206 # Setup with '--genvslite ...'
207 self.new_builddir()
208
209 # Firstly, we'd like to check that meson errors if the user explicitly specifies a non-ninja backend
210 # during setup.
211 with self.assertRaises(subprocess.CalledProcessError) as cm:
212 self.init(testdir, extra_args=['--genvslite', 'vs2022', '--backend', 'vs'])
213 self.assertIn("specifying a non-ninja backend conflicts with a 'genvslite' setup", cm.exception.stdout)
214
215 # Wrap the following bulk of setup and msbuild invocation testing in a try-finally because any exception,
216 # failure, or success must always clean up any of the suffixed build dir folders that may have been generated.
217 try:
218 # Since this
219 self.init(testdir, extra_args=['--genvslite', 'vs2022'])
220 # We need to bear in mind that the BasePlatformTests framework creates and cleans up its own temporary
221 # build directory. However, 'genvslite' creates a set of suffixed build directories which we'll have
222 # to clean up ourselves. See 'finally' block below.
223
224 # We intentionally skip the -
225 # self.build()
226 # step because we're wanting to test compilation/building through the solution/project's interface.
227
228 # Execute the debug and release builds through the projects 'Build' hooks
229 genvslite_vcxproj_path = str(os.path.join(self.builddir+'_vs', '[email protected]'))
230 # This use-case of invoking the .sln/.vcxproj build hooks, not through Visual Studio itself, but through
231 # 'msbuild.exe', in a VS tools command prompt environment (e.g. "x64 Native Tools Command Prompt for VS 2022"), is a
232 # problem: Such an environment sets the 'VSINSTALLDIR' variable which, mysteriously, has the side-effect of causing
233 # the spawned 'meson compile' command to fail to find 'ninja' (and even when ninja can be found elsewhere, all the
234 # compiler binaries that ninja wants to run also fail to be found). The PATH environment variable in the child python
235 # (and ninja) processes are fundamentally stripped down of all the critical search paths required to run the ninja
236 # compile work ... ONLY when 'VSINSTALLDIR' is set; without 'VSINSTALLDIR' set, the meson compile command does search
237 # for and find ninja (ironically, it finds it under the path where VSINSTALLDIR pointed!).
238 # For the above reason, this testing works around this bizarre behaviour by temporarily removing any 'VSINSTALLDIR'
239 # variable, prior to invoking the builds -
240 current_env = os.environ.copy()
241 current_env.pop('VSINSTALLDIR', None)
242 subprocess.check_call(
243 ['msbuild', '-target:Build', '-property:Configuration=debug', genvslite_vcxproj_path],
244 stdout=subprocess.DEVNULL,
245 stderr=subprocess.DEVNULL,
246 env=current_env)
247 subprocess.check_call(
248 ['msbuild', '-target:Build', '-property:Configuration=release', genvslite_vcxproj_path],
249 stdout=subprocess.DEVNULL,
250 stderr=subprocess.DEVNULL,
251 env=current_env)
252
253 # Check this has actually built the appropriate exes
254 exe_path = str(os.path.join(self.builddir+'_debug', 'genvslite.exe'))
255 self.assertTrue(os.path.exists(exe_path))
256 rc = subprocess.run([exe_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
257 self.assertEqual(rc.returncode, 0, rc.stdout + rc.stderr)
258 output_debug = rc.stdout
259 self.assertEqual(output_debug, b'Debug\r\n' )
260 exe_path = str(os.path.join(self.builddir+'_release', 'genvslite.exe'))
261 self.assertTrue(os.path.exists(exe_path))
262 output_release = subprocess.check_output([exe_path])
263 self.assertEqual( output_release, b'Non-debug\r\n' )
264
265 finally:
266 # Clean up our special suffixed temporary build dirs
267 suffixed_build_dirs = glob(self.builddir+'_*', recursive=False)
268 for build_dir in suffixed_build_dirs:
269 shutil.rmtree(build_dir)
270
271 def test_install_pdb_introspection(self):
272 testdir = os.path.join(self.platform_test_dir, '1 basic')
273
274 env = get_fake_env(testdir, self.builddir, self.prefix)
275 cc = detect_c_compiler(env, MachineChoice.HOST)
276 if cc.get_argument_syntax() != 'msvc':
277 raise SkipTest('Test only applies to MSVC-like compilers')
278
279 self.init(testdir)
280 installed = self.introspect('--installed')
281 files = [os.path.basename(path) for path in installed.values()]
282
283 self.assertIn('prog.pdb', files)
284
285 def _check_ld(self, name: str, lang: str, expected: str) -> None:
286 if not shutil.which(name):
287 raise SkipTest(f'Could not find {name}.')
288 envvars = mesonbuild.envconfig.ENV_VAR_PROG_MAP[f'{lang}_ld'].copy()
289
290 # Also test a deprecated variable if there is one.
291 if f'{lang}_ld' in mesonbuild.envconfig.DEPRECATED_ENV_PROG_MAP:
292 envvars.extend(
293 mesonbuild.envconfig.DEPRECATED_ENV_PROG_MAP[f'{lang}_ld'])
294
295 for envvar in envvars:
296 with mock.patch.dict(os.environ, {envvar: name}):
297 env = get_fake_env()
298 try:
299 comp = compiler_from_language(env, lang, MachineChoice.HOST)
300 except EnvironmentException:
301 raise SkipTest(f'Could not find a compiler for {lang}')
302 self.assertEqual(comp.linker.id, expected)
303
304 def test_link_environment_variable_lld_link(self):
305 env = get_fake_env()
306 comp = detect_c_compiler(env, MachineChoice.HOST)
307 if comp.get_argument_syntax() == 'gcc':
308 raise SkipTest('GCC cannot be used with link compatible linkers.')
309 self._check_ld('lld-link', 'c', 'lld-link')
310
311 def test_link_environment_variable_link(self):
312 env = get_fake_env()
313 comp = detect_c_compiler(env, MachineChoice.HOST)
314 if comp.get_argument_syntax() == 'gcc':
315 raise SkipTest('GCC cannot be used with link compatible linkers.')
316 self._check_ld('link', 'c', 'link')
317
318 def test_link_environment_variable_optlink(self):
319 env = get_fake_env()
320 comp = detect_c_compiler(env, MachineChoice.HOST)
321 if comp.get_argument_syntax() == 'gcc':
322 raise SkipTest('GCC cannot be used with link compatible linkers.')
323 self._check_ld('optlink', 'c', 'optlink')
324
325 @skip_if_not_language('rust')
326 def test_link_environment_variable_rust(self):
327 self._check_ld('link', 'rust', 'link')
328
329 @skip_if_not_language('d')
330 def test_link_environment_variable_d(self):
331 env = get_fake_env()
332 comp = detect_d_compiler(env, MachineChoice.HOST)
333 if comp.id == 'dmd':
334 raise SkipTest('meson cannot reliably make DMD use a different linker.')
335 self._check_ld('lld-link', 'd', 'lld-link')
336
337 def test_pefile_checksum(self):
338 try:
339 import pefile
340 except ImportError:
341 if IS_CI:
342 raise
343 raise SkipTest('pefile module not found')
344 testdir = os.path.join(self.common_test_dir, '6 linkshared')
345 self.init(testdir, extra_args=['--buildtype=release'])
346 self.build()
347 # Test that binaries have a non-zero checksum
348 env = get_fake_env()
349 cc = detect_c_compiler(env, MachineChoice.HOST)
350 cc_id = cc.get_id()
351 ld_id = cc.get_linker_id()
352 dll = glob(os.path.join(self.builddir, '*mycpplib.dll'))[0]
353 exe = os.path.join(self.builddir, 'cppprog.exe')
354 for f in (dll, exe):
355 pe = pefile.PE(f)
356 msg = f'PE file: {f!r}, compiler: {cc_id!r}, linker: {ld_id!r}'
357 if cc_id == 'clang-cl':
358 # Latest clang-cl tested (7.0) does not write checksums out
359 self.assertFalse(pe.verify_checksum(), msg=msg)
360 else:
361 # Verify that a valid checksum was written by all other compilers
362 self.assertTrue(pe.verify_checksum(), msg=msg)
363
364 @skip_if_not_base_option('b_vscrt')
365 def test_qt5dependency_vscrt(self):
366 '''
367 Test that qt5 dependencies use the debug module suffix when b_vscrt is
368 set to 'mdd'
369 '''
370 # Verify that qmake is for Qt5
371 if not shutil.which('qmake-qt5'):
372 if not IS_CI and not shutil.which('qmake'):
373 raise SkipTest('QMake not found')
374 output = subprocess.getoutput('qmake --version')
375 if not IS_CI and 'Qt version 5' not in output:
376 raise SkipTest('Qmake found, but it is not for Qt 5.')
377 # Setup with /MDd
378 testdir = os.path.join(self.framework_test_dir, '4 qt')
379 self.init(testdir, extra_args=['-Db_vscrt=mdd'])
380 # Verify that we're linking to the debug versions of Qt DLLs
381 build_ninja = os.path.join(self.builddir, 'build.ninja')
382 with open(build_ninja, encoding='utf-8') as f:
383 contents = f.read()
384 m = re.search('build qt5core.exe: cpp_LINKER.*Qt5Cored.lib', contents)
385 self.assertIsNotNone(m, msg=contents)
386
387 @skip_if_not_base_option('b_vscrt')
388 def test_compiler_checks_vscrt(self):
389 '''
390 Test that the correct VS CRT is used when running compiler checks
391 '''
392 env = get_fake_env()
393 cc = detect_c_compiler(env, MachineChoice.HOST)
394
395 MSVCRT_MAP = {
396 '/MD': '-fms-runtime-lib=dll',
397 '/MDd': '-fms-runtime-lib=dll_dbg',
398 '/MT': '-fms-runtime-lib=static',
399 '/MTd': '-fms-runtime-lib=static_dbg',
400 }
401
402 def sanitycheck_vscrt(vscrt):
403 if cc.get_argument_syntax() != 'msvc':
404 vscrt = MSVCRT_MAP[vscrt]
405 checks = self.get_meson_log_sanitychecks()
406 self.assertGreater(len(checks), 0)
407 for check in checks:
408 self.assertIn(vscrt, check)
409
410 testdir = os.path.join(self.common_test_dir, '1 trivial')
411 self.init(testdir)
412 sanitycheck_vscrt('/MDd')
413
414 self.new_builddir()
415 self.init(testdir, extra_args=['-Dbuildtype=debugoptimized'])
416 sanitycheck_vscrt('/MD')
417
418 self.new_builddir()
419 self.init(testdir, extra_args=['-Dbuildtype=release'])
420 sanitycheck_vscrt('/MD')
421
422 self.new_builddir()
423 self.init(testdir, extra_args=['-Db_vscrt=md'])
424 sanitycheck_vscrt('/MD')
425
426 self.new_builddir()
427 self.init(testdir, extra_args=['-Db_vscrt=mdd'])
428 sanitycheck_vscrt('/MDd')
429
430 self.new_builddir()
431 self.init(testdir, extra_args=['-Db_vscrt=mt'])
432 sanitycheck_vscrt('/MT')
433
434 self.new_builddir()
435 self.init(testdir, extra_args=['-Db_vscrt=mtd'])
436 sanitycheck_vscrt('/MTd')
437
438 def test_modules(self):
439 if self.backend is not Backend.ninja:
440 raise SkipTest(f'C++ modules only work with the Ninja backend (not {self.backend.name}).')
441 if 'VSCMD_VER' not in os.environ:
442 raise SkipTest('C++ modules is only supported with Visual Studio.')
443 if version_compare(os.environ['VSCMD_VER'], '<16.10.0'):
444 raise SkipTest('C++ modules are only supported with VS 2019 Preview or newer.')
445 self.init(os.path.join(self.unit_test_dir, '85 cpp modules'))
446 self.build()
447
448 def test_non_utf8_fails(self):
449 # FIXME: VS backend does not use flags from compiler.get_always_args()
450 # and thus it's missing /utf-8 argument. Was that intentional? This needs
451 # to be revisited.
452 if self.backend is not Backend.ninja:
453 raise SkipTest(f'This test only pass with ninja backend (not {self.backend.name}).')
454 testdir = os.path.join(self.platform_test_dir, '18 msvc charset')
455 env = get_fake_env(testdir, self.builddir, self.prefix)
456 cc = detect_c_compiler(env, MachineChoice.HOST)
457 if cc.get_argument_syntax() != 'msvc':
458 raise SkipTest('Not using MSVC')
459 self.init(testdir, extra_args=['-Dtest-failure=true'])
460 self.assertRaises(subprocess.CalledProcessError, self.build)
461
462 @unittest.skipIf(is_cygwin(), "Needs visual studio")
463 def test_vsenv_option(self):
464 if self.backend is not Backend.ninja:
465 raise SkipTest('Only ninja backend is valid for test')
466 env = os.environ.copy()
467 env['MESON_FORCE_VSENV_FOR_UNITTEST'] = '1'
468 # Remove ninja from PATH to ensure that the one provided by Visual
469 # Studio is picked, as a regression test for
470 # https://github.com/mesonbuild/meson/issues/9774
471 env['PATH'] = get_path_without_cmd('ninja', env['PATH'])
472 # Add a multiline variable to test that it is handled correctly
473 # with a line that contains only '=' and a line that would result
474 # in an invalid variable name.
475 # see: https://github.com/mesonbuild/meson/pull/13682
476 env['MULTILINE_VAR_WITH_EQUALS'] = 'Foo\r\n=====\r\n'
477 env['MULTILINE_VAR_WITH_INVALID_NAME'] = 'Foo\n%=Bar\n'
478 testdir = os.path.join(self.common_test_dir, '1 trivial')
479 out = self.init(testdir, extra_args=['--vsenv'], override_envvars=env)
480 self.assertIn('Activating VS', out)
481 self.assertRegex(out, 'Visual Studio environment is needed to run Ninja')
482 # All these directly call ninja with the full path, so we need to patch
483 # it out to use meson subcommands
484 with mock.patch.object(self, 'build_command', self.meson_command + ['compile']):
485 out = self.build(override_envvars=env)
486 self.assertIn('Activating VS', out)
487 with mock.patch.object(self, 'test_command', self.meson_command + ['test']):
488 out = self.run_tests(override_envvars=env)
489 self.assertIn('Activating VS', out)
490 with mock.patch.object(self, 'install_command', self.meson_command + ['install']):
491 out = self.install(override_envvars=env)
492 self.assertIn('Activating VS', out)