Debian Codegraph @

mesonbuild/envconfig.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2012-2016 The Meson development team
3
4 from __future__ import annotations
5
6 from dataclasses import dataclass
7 import typing as T
8 from enum import Enum
9 import os
10 import platform
11 import sys
12
13 from . import mesonlib
14 from .mesonlib import EnvironmentException, HoldableObject, lazy_property, Popen_safe
15 from .programs import ExternalProgram
16 from . import mlog
17 from pathlib import Path, PurePath, PurePosixPath, PureWindowsPath
18
19 if T.TYPE_CHECKING:
20 from .options import ElementaryOptionValues
21 from .compilers.compilers import CompilerDict
22 from .compilers.mixins.visualstudio import VisualStudioLikeCompiler
23 from ._typing import ImmutableListProtocol
24
25
26 # These classes contains all the data pulled from configuration files (native
27 # and cross file currently), and also assists with the reading environment
28 # variables.
29 #
30 # At this time there isn't an ironclad difference between this and other sources
31 # of state like `coredata`. But one rough guide is much what is in `coredata` is
32 # the *output* of the configuration process: the final decisions after tests.
33 # This, on the other hand has *inputs*. The config files are parsed, but
34 # otherwise minimally transformed. When more complex fallbacks (environment
35 # detection) exist, they are defined elsewhere as functions that construct
36 # instances of these classes.
37
38
39 known_cpu_families = (
40 'aarch64',
41 'alpha',
42 'arc',
43 'arm',
44 'avr',
45 'c2000',
46 'c6000',
47 'csky',
48 'dspic',
49 'e2k',
50 'ft32',
51 'ia64',
52 'loongarch64',
53 'm68k',
54 'microblaze',
55 'mips',
56 'mips64',
57 'msp430',
58 'parisc',
59 'pic24',
60 'pic32',
61 'ppc',
62 'ppc64',
63 'riscv32',
64 'riscv64',
65 'rl78',
66 'rx',
67 's390',
68 's390x',
69 'sh4',
70 'sparc',
71 'sparc64',
72 'sw_64',
73 'wasm32',
74 'wasm64',
75 'x86',
76 'x86_64',
77 'tricore'
78 )
79
80 # It would feel more natural to call this "64_BIT_CPU_FAMILIES", but
81 # python identifiers cannot start with numbers
82 CPU_FAMILIES_64_BIT = [
83 'aarch64',
84 'alpha',
85 'ia64',
86 'loongarch64',
87 'mips64',
88 'ppc64',
89 'riscv64',
90 's390x',
91 'sparc64',
92 'sw_64',
93 'wasm64',
94 'x86_64',
95 ]
96
97 # Map from language identifiers to environment variables.
98 ENV_VAR_COMPILER_MAP: T.Mapping[str, ImmutableListProtocol[str]] = {
99 # Compilers
100 'c': ['CC'],
101 'cpp': ['CXX'],
102 'cs': ['CSC'],
103 'cython': ['CYTHON'],
104 'd': ['DC'],
105 'fortran': ['FC'],
106 'objc': ['OBJC'],
107 'objcpp': ['OBJCXX'],
108 'rust': ['RUSTC'],
109 'vala': ['VALAC'],
110 'nasm': ['NASM'],
111
112 # Linkers
113 'c_ld': ['CC_LD'],
114 'cpp_ld': ['CXX_LD'],
115 'd_ld': ['DC_LD'],
116 'fortran_ld': ['FC_LD'],
117 'objc_ld': ['OBJC_LD'],
118 'objcpp_ld': ['OBJCXX_LD'],
119 'rust_ld': ['RUSTC_LD'],
120 }
121
122 # Map from utility names to environment variables.
123 ENV_VAR_TOOL_MAP: T.Mapping[str, ImmutableListProtocol[str]] = {
124 # Binutils
125 'ar': ['AR'],
126 'as': ['AS'],
127 'ld': ['LD'],
128 'nm': ['NM'],
129 'objcopy': ['OBJCOPY'],
130 'objdump': ['OBJDUMP'],
131 'ranlib': ['RANLIB'],
132 'readelf': ['READELF'],
133 'size': ['SIZE'],
134 'strings': ['STRINGS'],
135 'strip': ['STRIP'],
136 'windres': ['RC', 'WINDRES'],
137
138 # Other tools
139 'cmake': ['CMAKE'],
140 'qmake': ['QMAKE'],
141 'pkg-config': ['PKG_CONFIG'],
142 'make': ['MAKE'],
143 'vapigen': ['VAPIGEN'],
144 'llvm-config': ['LLVM_CONFIG'],
145 }
146
147 ENV_VAR_PROG_MAP = {**ENV_VAR_COMPILER_MAP, **ENV_VAR_TOOL_MAP}
148
149 # Deprecated environment variables mapped from the new variable to the old one
150 # Deprecated in 0.54.0
151 DEPRECATED_ENV_PROG_MAP: T.Mapping[str, ImmutableListProtocol[str]] = {
152 'd_ld': ['D_LD'],
153 'fortran_ld': ['F_LD'],
154 'rust_ld': ['RUST_LD'],
155 'objcpp_ld': ['OBJCPP_LD'],
156 }
157
158 class CMakeSkipCompilerTest(Enum):
159 ALWAYS = 'always'
160 NEVER = 'never'
161 DEP_ONLY = 'dep_only'
162
163 class Properties:
164 def __init__(
165 self,
166 properties: T.Optional[T.Dict[str, ElementaryOptionValues]] = None,
167 ):
168 self.properties = properties or {}
169
170 def has_stdlib(self, language: str) -> bool:
171 return language + '_stdlib' in self.properties
172
173 # Some of get_stdlib, get_root, get_sys_root are wider than is actually
174 # true, but without heterogeneous dict annotations it's not practical to
175 # narrow them
176 def get_stdlib(self, language: str) -> T.Union[str, T.List[str]]:
177 stdlib = self.properties[language + '_stdlib']
178 if isinstance(stdlib, str):
179 return stdlib
180 assert isinstance(stdlib, list)
181 for i in stdlib:
182 assert isinstance(i, str)
183 return stdlib
184
185 def get_root(self) -> T.Optional[str]:
186 root = self.properties.get('root', None)
187 assert root is None or isinstance(root, str)
188 return root
189
190 def get_sys_root(self) -> T.Optional[str]:
191 sys_root = self.properties.get('sys_root', None)
192 assert sys_root is None or isinstance(sys_root, str)
193 return sys_root
194
195 def get_pkg_config_libdir(self) -> T.Optional[T.List[str]]:
196 p = self.properties.get('pkg_config_libdir', None)
197 if p is None:
198 return p
199 res = mesonlib.listify(p)
200 for i in res:
201 assert isinstance(i, str)
202 return res
203
204 def get_cmake_defaults(self) -> bool:
205 if 'cmake_defaults' not in self.properties:
206 return True
207 res = self.properties['cmake_defaults']
208 assert isinstance(res, bool)
209 return res
210
211 def get_cmake_toolchain_file(self) -> T.Optional[Path]:
212 if 'cmake_toolchain_file' not in self.properties:
213 return None
214 raw = self.properties['cmake_toolchain_file']
215 assert isinstance(raw, str)
216 cmake_toolchain_file = Path(raw)
217 if not cmake_toolchain_file.is_absolute():
218 raise EnvironmentException(f'cmake_toolchain_file ({raw}) is not absolute')
219 return cmake_toolchain_file
220
221 def get_cmake_skip_compiler_test(self) -> CMakeSkipCompilerTest:
222 if 'cmake_skip_compiler_test' not in self.properties:
223 return CMakeSkipCompilerTest.DEP_ONLY
224 raw = self.properties['cmake_skip_compiler_test']
225 try:
226 return CMakeSkipCompilerTest(raw)
227 except ValueError:
228 raise EnvironmentException(
229 '"{}" is not a valid value for cmake_skip_compiler_test. Supported values are {}'
230 .format(raw, [e.value for e in CMakeSkipCompilerTest]))
231
232 def get_cmake_use_exe_wrapper(self) -> bool:
233 if 'cmake_use_exe_wrapper' not in self.properties:
234 return True
235 res = self.properties['cmake_use_exe_wrapper']
236 assert isinstance(res, bool)
237 return res
238
239 def get_java_home(self) -> T.Optional[Path]:
240 value = T.cast('T.Optional[str]', self.properties.get('java_home'))
241 return Path(value) if value else None
242
243 def get_bindgen_clang_args(self) -> T.List[str]:
244 value = mesonlib.listify(self.properties.get('bindgen_clang_arguments', []))
245 if not all(isinstance(v, str) for v in value):
246 raise EnvironmentException('bindgen_clang_arguments must be a string or an array of strings')
247 return T.cast('T.List[str]', value)
248
249 def __eq__(self, other: object) -> bool:
250 if isinstance(other, type(self)):
251 return self.properties == other.properties
252 return NotImplemented
253
254 # TODO consider removing so Properties is less freeform
255 def __getitem__(self, key: str) -> T.Optional[T.Union[str, bool, int, T.List[str]]]:
256 return self.properties[key]
257
258 # TODO consider removing so Properties is less freeform
259 def __contains__(self, item: T.Union[str, bool, int, T.List[str]]) -> bool:
260 return item in self.properties
261
262 # TODO consider removing, for same reasons as above
263 def get(self, key: str, default: T.Optional[T.Union[str, bool, int, T.List[str]]] = None) -> T.Optional[T.Union[str, bool, int, T.List[str]]]:
264 return self.properties.get(key, default)
265
266 @dataclass(unsafe_hash=True)
267 class MachineInfo(HoldableObject):
268 system: str
269 cpu_family: str | None
270 cpu: str | None
271 endian: str
272 kernel: T.Optional[str]
273 subsystem: T.Optional[str]
274
275 def __post_init__(self) -> None:
276 self.is_64_bit: bool = self.cpu_family in CPU_FAMILIES_64_BIT
277
278 def __repr__(self) -> str:
279 return f'<MachineInfo: {self.system} {self.cpu_family} ({self.cpu})>'
280
281 @classmethod
282 def from_literal(cls, raw: T.Dict[str, ElementaryOptionValues]) -> 'MachineInfo':
283 # We don't have enough type information to be sure of what we loaded
284 # So we need to accept that this might have ElementaryOptionValues, but
285 # then ensure that it's actually strings, since that's what the
286 # [*_machine] section should have.
287 assert all(isinstance(v, str) for v in raw.values()), 'for mypy'
288 literal = T.cast('T.Dict[str, str]', raw)
289 minimum_literal = {'cpu', 'cpu_family', 'endian', 'system'}
290 if minimum_literal - set(literal):
291 raise EnvironmentException(
292 f'Machine info is currently {literal}\n' +
293 'but is missing {}.'.format(minimum_literal - set(literal)))
294
295 cpu_family = literal['cpu_family']
296 if cpu_family not in known_cpu_families:
297 mlog.warning(f'Unknown CPU family {cpu_family}, please report this at https://github.com/mesonbuild/meson/issues/new')
298
299 endian = literal['endian']
300 if endian not in ('little', 'big'):
301 mlog.warning(f'Unknown endian {endian}')
302
303 system = literal['system']
304 kernel = literal.get('kernel', None)
305 subsystem = literal.get('subsystem', None)
306
307 return cls(system, cpu_family, literal['cpu'], endian, kernel, subsystem)
308
309 def is_windows(self) -> bool:
310 """
311 Machine is windows?
312 """
313 return self.system == 'windows'
314
315 def is_cygwin(self) -> bool:
316 """
317 Machine is cygwin?
318 """
319 return self.system == 'cygwin'
320
321 @lazy_property
322 def pure_path_class(self) -> T.Type[PurePath]:
323 """Get the appropriate PurePath class for this machine."""
324 if self.is_windows():
325 return PureWindowsPath
326 return PurePosixPath
327
328 def is_linux(self) -> bool:
329 """
330 Machine is linux?
331 """
332 return self.system == 'linux'
333
334 def is_darwin(self) -> bool:
335 """
336 Machine is Darwin (macOS/iOS/tvOS/visionOS/watchOS)?
337 """
338 return self.system in {'darwin', 'ios', 'tvos', 'visionos', 'watchos'}
339
340 def is_android(self) -> bool:
341 """
342 Machine is Android?
343 """
344 return self.system == 'android'
345
346 def is_ohos(self) -> bool:
347 """
348 Machine is OpenHarmony (OHOS)?
349
350 OHOS is modelled as an Android subsystem: it behaves like Android
351 (apps are shared libraries, no versioned sonames, ...) but uses musl
352 instead of Bionic. Machine files select it with system = 'android'
353 and subsystem = 'ohos'.
354 """
355 return self.is_android() and self.subsystem == 'ohos'
356
357 def is_haiku(self) -> bool:
358 """
359 Machine is Haiku?
360 """
361 return self.system == 'haiku'
362
363 def is_netbsd(self) -> bool:
364 """
365 Machine is NetBSD?
366 """
367 return self.system == 'netbsd'
368
369 def is_openbsd(self) -> bool:
370 """
371 Machine is OpenBSD?
372 """
373 return self.system == 'openbsd'
374
375 def is_dragonflybsd(self) -> bool:
376 """Machine is DragonFly BSD?"""
377 return self.system == 'dragonfly'
378
379 def is_freebsd(self) -> bool:
380 """Machine is FreeBSD?"""
381 return self.system == 'freebsd'
382
383 def is_sunos(self) -> bool:
384 """Machine is illumos or Solaris?"""
385 return self.system == 'sunos'
386
387 def is_hurd(self) -> bool:
388 """
389 Machine is GNU/Hurd?
390 """
391 return self.system == 'gnu'
392
393 def is_aix(self) -> bool:
394 """
395 Machine is aix?
396 """
397 return self.system == 'aix'
398
399 def is_irix(self) -> bool:
400 """Machine is IRIX?"""
401 return self.system.startswith('irix')
402
403 def is_os2(self) -> bool:
404 """
405 Machine is OS/2?
406 """
407 return self.system == 'os/2'
408
409 def is_fuchsia(self) -> bool:
410 return self.system == 'fuchsia'
411
412 # Various prefixes and suffixes for import libraries, shared libraries,
413 # static libraries, and executables.
414 # Versioning is added to these names in the backends as-needed.
415 def get_exe_suffix(self) -> str:
416 if self.is_windows() or self.is_cygwin() or self.is_os2():
417 return 'exe'
418 else:
419 return ''
420
421 def get_object_suffix(self) -> str:
422 if self.is_windows():
423 return 'obj'
424 else:
425 return 'o'
426
427 def libdir_layout_is_win(self) -> bool:
428 return self.is_windows() or self.is_cygwin()
429
430 class BinaryTable:
431
432 def __init__(
433 self,
434 binaries: T.Optional[T.Mapping[str, ElementaryOptionValues]] = None,
435 ):
436 self.binaries: T.Dict[str, T.List[str]] = {}
437 if binaries:
438 for name, command in binaries.items():
439 if not isinstance(command, (list, str)):
440 raise mesonlib.MesonException(
441 f'Invalid type {command!r} for entry {name!r} in cross file')
442 self.binaries[name] = mesonlib.listify(command)
443 if 'pkgconfig' in self.binaries:
444 if 'pkg-config' not in self.binaries:
445 mlog.deprecation('"pkgconfig" entry is deprecated and should be replaced by "pkg-config"', fatal=False)
446 self.binaries['pkg-config'] = self.binaries['pkgconfig']
447 elif self.binaries['pkgconfig'] != self.binaries['pkg-config']:
448 raise mesonlib.MesonException('Mismatched pkgconfig and pkg-config binaries in the machine file.')
449 else:
450 # Both are defined with the same value, this is allowed
451 # for backward compatibility.
452 # FIXME: We should still print deprecation warning if the
453 # project targets Meson >= 1.3.0, but we have no way to know
454 # that here.
455 pass
456 del self.binaries['pkgconfig']
457
458 @staticmethod
459 def detect_ccache() -> ExternalProgram:
460 return ExternalProgram('ccache', silent=True)
461
462 @staticmethod
463 def detect_sccache() -> ExternalProgram:
464 return ExternalProgram('sccache', silent=True)
465
466 @staticmethod
467 def detect_compiler_cache() -> ExternalProgram:
468 # Sccache is "newer" so it is assumed that people would prefer it by default.
469 cache = BinaryTable.detect_sccache()
470 if cache.found():
471 return cache
472 return BinaryTable.detect_ccache()
473
474 @classmethod
475 def parse_entry(cls, entry: T.Union[str, T.List[str]]) -> T.Tuple[T.List[str], T.Union[None, ExternalProgram]]:
476 parts = mesonlib.stringlistify(entry)
477 # Ensure ccache exists and remove it if it doesn't
478 if parts[0] == 'ccache':
479 compiler = parts[1:]
480 ccache = cls.detect_ccache()
481 elif parts[0] == 'sccache':
482 compiler = parts[1:]
483 ccache = cls.detect_sccache()
484 else:
485 compiler = parts
486 ccache = None
487 if not compiler:
488 raise EnvironmentException(f'Compiler cache specified without compiler: {parts[0]}')
489 # Return value has to be a list of compiler 'choices'
490 return compiler, ccache
491
492 def lookup_entry(self, name: str) -> T.Optional[T.List[str]]:
493 """Lookup binary in cross/native file and fallback to environment.
494
495 Returns command with args as list if found, Returns `None` if nothing is
496 found.
497 """
498 command = self.binaries.get(name)
499 if not command:
500 return None
501 elif not command[0].strip():
502 return None
503 return command
504
505 class CMakeVariables:
506 def __init__(self, variables: T.Optional[T.Dict[str, T.Any]] = None) -> None:
507 variables = variables or {}
508 self.variables: T.Dict[str, T.List[str]] = {}
509
510 for key, value in variables.items():
511 value = mesonlib.listify(value)
512 for i in value:
513 if not isinstance(i, str):
514 raise EnvironmentException(f"Value '{i}' of CMake variable '{key}' defined in a machine file is a {type(i).__name__} and not a str")
515 self.variables[key] = value
516
517 def get_variables(self) -> T.Dict[str, T.List[str]]:
518 return self.variables
519
520
521 # Machine and platform detection functions
522 # ========================================
523
524 KERNEL_MAPPINGS: T.Mapping[str, str] = {'freebsd': 'freebsd',
525 'openbsd': 'openbsd',
526 'netbsd': 'netbsd',
527 'windows': 'nt',
528 'android': 'linux',
529 'linux': 'linux',
530 'cygwin': 'nt',
531 'darwin': 'xnu',
532 'ios': 'xnu',
533 'tvos': 'xnu',
534 'visionos': 'xnu',
535 'watchos': 'xnu',
536 'dragonfly': 'dragonfly',
537 'haiku': 'haiku',
538 'gnu': 'gnu',
539 'fuchsia': 'fuchsia',
540 }
541
542 def detect_windows_arch(compilers: CompilerDict) -> str:
543 """
544 Detecting the 'native' architecture of Windows is not a trivial task. We
545 cannot trust that the architecture that Python is built for is the 'native'
546 one because you can run 32-bit apps on 64-bit Windows using WOW64 and
547 people sometimes install 32-bit Python on 64-bit Windows.
548
549 We also can't rely on the architecture of the OS itself, since it's
550 perfectly normal to compile and run 32-bit applications on Windows as if
551 they were native applications. It's a terrible experience to require the
552 user to supply a cross-info file to compile 32-bit applications on 64-bit
553 Windows. Thankfully, the only way to compile things with Visual Studio on
554 Windows is by entering the 'msvc toolchain' environment, which can be
555 easily detected.
556
557 In the end, the sanest method is as follows:
558 1. Check environment variables that are set by Windows and WOW64 to find out
559 if this is x86 (possibly in WOW64), if so use that as our 'native'
560 architecture.
561 2. If the compiler toolchain target architecture is x86, use that as our
562 'native' architecture.
563 3. Otherwise, use the actual Windows architecture
564
565 """
566 os_arch = mesonlib.windows_detect_native_arch()
567 if os_arch == 'x86':
568 return os_arch
569 # If we're on 64-bit Windows, 32-bit apps can be compiled without
570 # cross-compilation. So if we're doing that, just set the native arch as
571 # 32-bit and pretend like we're running under WOW64. Else, return the
572 # actual Windows architecture that we deduced above.
573 for compiler in compilers.values():
574 compiler = T.cast('VisualStudioLikeCompiler', compiler)
575 if compiler.id == 'msvc' and (compiler.target in {'x86', '80x86'}):
576 return 'x86'
577 if compiler.id == 'clang-cl' and (compiler.target in {'x86', 'i686'}):
578 return 'x86'
579 if compiler.id == 'gcc' and compiler.has_builtin_define('__i386__'):
580 return 'x86'
581 return os_arch
582
583 def any_compiler_has_define(compilers: CompilerDict, define: str) -> bool:
584 for c in compilers.values():
585 try:
586 if c.has_builtin_define(define):
587 return True
588 except mesonlib.MesonException:
589 # Ignore compilers that do not support has_builtin_define.
590 pass
591 return False
592
593 def detect_cpu_family(compilers: CompilerDict) -> str:
594 """
595 Python is inconsistent in its platform module.
596 It returns different values for the same cpu.
597 For x86 it might return 'x86', 'i686' or some such.
598 Do some canonicalization.
599 """
600 if mesonlib.is_windows():
601 trial = detect_windows_arch(compilers)
602 elif mesonlib.is_freebsd() or mesonlib.is_netbsd() or mesonlib.is_openbsd() or mesonlib.is_qnx() or mesonlib.is_aix():
603 trial = platform.processor().lower()
604 else:
605 trial = platform.machine().lower()
606 if trial.startswith('i') and trial.endswith('86'):
607 trial = 'x86'
608 elif trial == 'bepc':
609 trial = 'x86'
610 elif trial == 'arm64':
611 trial = 'aarch64'
612 elif trial.startswith('aarch64'):
613 # This can be `aarch64_be`
614 trial = 'aarch64'
615 elif trial.startswith('arm') or trial.startswith('earm'):
616 trial = 'arm'
617 elif trial.startswith(('powerpc64', 'ppc64')):
618 trial = 'ppc64'
619 elif trial.startswith(('powerpc', 'ppc')) or trial in {'macppc', 'power macintosh'}:
620 trial = 'ppc'
621 elif trial in {'amd64', 'x64', 'i86pc'}:
622 trial = 'x86_64'
623 elif trial in {'sun4u', 'sun4v'}:
624 trial = 'sparc64'
625 elif trial.startswith('mips'):
626 if '64' not in trial:
627 trial = 'mips'
628 else:
629 trial = 'mips64'
630 elif trial in {'ip30', 'ip35'}:
631 trial = 'mips64'
632
633 # On Linux (and maybe others) there can be any mixture of 32/64 bit code in
634 # the kernel, Python, system, 32-bit chroot on 64-bit host, etc. The only
635 # reliable way to know is to check the compiler defines.
636 if trial == 'x86_64':
637 if any_compiler_has_define(compilers, '__i386__'):
638 trial = 'x86'
639 elif trial == 'aarch64':
640 if any_compiler_has_define(compilers, '__arm__'):
641 trial = 'arm'
642 # Add more quirks here as bugs are reported. Keep in sync with detect_cpu()
643 # below.
644 elif trial == 'parisc64':
645 # ATM there is no 64 bit userland for PA-RISC. Thus always
646 # report it as 32 bit for simplicity.
647 trial = 'parisc'
648 elif trial == 'ppc':
649 # AIX always returns powerpc, check here for 64-bit
650 if any_compiler_has_define(compilers, '__64BIT__'):
651 trial = 'ppc64'
652 # MIPS64 is able to run MIPS32 code natively, so there is a chance that
653 # such mixture mentioned above exists.
654 elif trial == 'mips64':
655 if compilers and not any_compiler_has_define(compilers, '__mips64'):
656 trial = 'mips'
657
658 if trial not in known_cpu_families:
659 mlog.warning(f'Unknown CPU family {trial!r}, please report this at '
660 'https://github.com/mesonbuild/meson/issues/new with the '
661 'output of `uname -a` and `cat /proc/cpuinfo`')
662
663 return trial
664
665 def detect_cpu(compilers: CompilerDict) -> str:
666 if mesonlib.is_windows():
667 trial = detect_windows_arch(compilers)
668 elif mesonlib.is_freebsd() or mesonlib.is_netbsd() or mesonlib.is_openbsd() or mesonlib.is_aix():
669 trial = platform.processor().lower()
670 else:
671 trial = platform.machine().lower()
672
673 if trial in {'amd64', 'x64', 'i86pc'}:
674 trial = 'x86_64'
675 if trial == 'x86_64':
676 # Same check as above for cpu_family
677 if any_compiler_has_define(compilers, '__i386__'):
678 trial = 'i686' # All 64 bit cpus have at least this level of x86 support.
679 elif trial.startswith('aarch64') or trial.startswith('arm64'):
680 # Same check as above for cpu_family
681 if any_compiler_has_define(compilers, '__arm__'):
682 trial = 'arm'
683 else:
684 # for aarch64_be
685 trial = 'aarch64'
686 elif trial.startswith('earm'):
687 trial = 'arm'
688 elif trial == 'e2k':
689 # Make more precise CPU detection for Elbrus platform.
690 trial = platform.processor().lower()
691 elif trial.startswith('mips'):
692 if '64' not in trial:
693 trial = 'mips'
694 else:
695 if compilers and not any_compiler_has_define(compilers, '__mips64'):
696 trial = 'mips'
697 else:
698 trial = 'mips64'
699 elif trial == 'ppc':
700 # AIX always returns powerpc, check here for 64-bit
701 if any_compiler_has_define(compilers, '__64BIT__'):
702 trial = 'ppc64'
703
704 # Add more quirks here as bugs are reported. Keep in sync with
705 # detect_cpu_family() above.
706 return trial
707
708 def detect_kernel(system: str) -> T.Optional[str]:
709 if system == 'sunos':
710 # Solaris 5.10 uname doesn't support the -o switch, and illumos started
711 # with version 5.11 so shortcut the logic to report 'solaris' in such
712 # cases where the version is 5.10 or below.
713 if mesonlib.version_compare(platform.uname().release, '<=5.10'):
714 return 'solaris'
715 # This needs to be /usr/bin/uname because gnu-uname could be installed and
716 # won't provide the necessary information
717 p, out, _ = Popen_safe(['/usr/bin/uname', '-o'])
718 if p.returncode != 0:
719 raise mesonlib.MesonException('Failed to run "/usr/bin/uname -o"')
720 out = out.lower().strip()
721 if out not in {'illumos', 'solaris'}:
722 mlog.warning(f'Got an unexpected value for kernel on a SunOS derived platform, expected either "illumos" or "solaris", but got "{out}".'
723 "Please open a Meson issue with the OS you're running and the value detected for your kernel.")
724 return None
725 return out
726 return KERNEL_MAPPINGS.get(system, None)
727
728 def detect_subsystem(system: str) -> T.Optional[str]:
729 if system == 'darwin':
730 return 'macos'
731 return system
732
733 def detect_system() -> str:
734 if sys.platform == 'cygwin':
735 return 'cygwin'
736 return platform.system().lower()
737
738 def detect_msys2_arch() -> T.Optional[str]:
739 return os.environ.get('MSYSTEM_CARCH', None)
740
741 def detect_machine_info(compilers: T.Optional[CompilerDict] = None) -> MachineInfo:
742 """Detect the machine we're running on
743
744 If compilers are not provided, we cannot know as much. None out those
745 fields to avoid accidentally depending on partial knowledge. The
746 underlying ''detect_*'' method can be called to explicitly use the
747 partial information.
748 """
749 system = detect_system()
750 return MachineInfo(
751 system,
752 detect_cpu_family(compilers) if compilers is not None else None,
753 detect_cpu(compilers) if compilers is not None else None,
754 sys.byteorder,
755 detect_kernel(system),
756 detect_subsystem(system))
757
758 # TODO make this compare two `MachineInfo`s purely. How important is the
759 # `detect_cpu_family({})` distinction? It is the one impediment to that.
760 def machine_info_can_run(machine_info: MachineInfo) -> bool:
761 """Whether we can run binaries for this machine on the current machine.
762
763 Can almost always run 32-bit binaries on 64-bit natively if the host
764 and build systems are the same. We don't pass any compilers to
765 detect_cpu_family() here because we always want to know the OS
766 architecture, not what the compiler environment tells us.
767 """
768 system = detect_system()
769 if machine_info.system != system:
770 return False
771 if machine_info.subsystem and machine_info.subsystem != detect_subsystem(system):
772 return False
773 true_build_cpu_family = detect_cpu_family({})
774 assert machine_info.cpu_family is not None, 'called on incomplete machine_info'
775 return \
776 (machine_info.cpu_family == true_build_cpu_family) or \
777 ((true_build_cpu_family == 'x86_64') and (machine_info.cpu_family == 'x86')) or \
778 ((true_build_cpu_family == 'mips64') and (machine_info.cpu_family == 'mips'))