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 assert isinstance(raw, str)
226 try:
227 return CMakeSkipCompilerTest(raw)
228 except ValueError:
229 raise EnvironmentException(
230 '"{}" is not a valid value for cmake_skip_compiler_test. Supported values are {}'
231 .format(raw, [e.value for e in CMakeSkipCompilerTest]))
232
233 def get_cmake_use_exe_wrapper(self) -> bool:
234 if 'cmake_use_exe_wrapper' not in self.properties:
235 return True
236 res = self.properties['cmake_use_exe_wrapper']
237 assert isinstance(res, bool)
238 return res
239
240 def get_java_home(self) -> T.Optional[Path]:
241 value = T.cast('T.Optional[str]', self.properties.get('java_home'))
242 return Path(value) if value else None
243
244 def get_bindgen_clang_args(self) -> T.List[str]:
245 value = mesonlib.listify(self.properties.get('bindgen_clang_arguments', []))
246 if not all(isinstance(v, str) for v in value):
247 raise EnvironmentException('bindgen_clang_arguments must be a string or an array of strings')
248 return T.cast('T.List[str]', value)
249
250 def __eq__(self, other: object) -> bool:
251 if isinstance(other, type(self)):
252 return self.properties == other.properties
253 return NotImplemented
254
255 # TODO consider removing so Properties is less freeform
256 def __getitem__(self, key: str) -> T.Optional[T.Union[str, bool, int, T.List[str]]]:
257 return self.properties[key]
258
259 # TODO consider removing so Properties is less freeform
260 def __contains__(self, item: T.Union[str, bool, int, T.List[str]]) -> bool:
261 return item in self.properties
262
263 # TODO consider removing, for same reasons as above
264 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]]]:
265 return self.properties.get(key, default)
266
267 @dataclass(unsafe_hash=True)
268 class MachineInfo(HoldableObject):
269 system: str
270 cpu_family: str | None
271 cpu: str | None
272 endian: str
273 kernel: T.Optional[str]
274 subsystem: T.Optional[str]
275
276 def __post_init__(self) -> None:
277 self.is_64_bit: bool = self.cpu_family in CPU_FAMILIES_64_BIT
278
279 def __repr__(self) -> str:
280 return f'<MachineInfo: {self.system} {self.cpu_family} ({self.cpu})>'
281
282 @classmethod
283 def from_literal(cls, raw: T.Dict[str, ElementaryOptionValues]) -> 'MachineInfo':
284 # We don't have enough type information to be sure of what we loaded
285 # So we need to accept that this might have ElementaryOptionValues, but
286 # then ensure that it's actually strings, since that's what the
287 # [*_machine] section should have.
288 assert all(isinstance(v, str) for v in raw.values()), 'for mypy'
289 literal = T.cast('T.Dict[str, str]', raw)
290 minimum_literal = {'cpu', 'cpu_family', 'endian', 'system'}
291 if minimum_literal - set(literal):
292 raise EnvironmentException(
293 f'Machine info is currently {literal}\n' +
294 'but is missing {}.'.format(minimum_literal - set(literal)))
295
296 cpu_family = literal['cpu_family']
297 if cpu_family not in known_cpu_families:
298 mlog.warning(f'Unknown CPU family {cpu_family}, please report this at https://github.com/mesonbuild/meson/issues/new')
299
300 endian = literal['endian']
301 if endian not in ('little', 'big'):
302 mlog.warning(f'Unknown endian {endian}')
303
304 system = literal['system']
305 kernel = literal.get('kernel', None)
306 subsystem = literal.get('subsystem', None)
307
308 return cls(system, cpu_family, literal['cpu'], endian, kernel, subsystem)
309
310 def is_windows(self) -> bool:
311 """
312 Machine is windows?
313 """
314 return self.system == 'windows'
315
316 def is_cygwin(self) -> bool:
317 """
318 Machine is cygwin?
319 """
320 return self.system == 'cygwin'
321
322 @lazy_property
323 def pure_path_class(self) -> T.Type[PurePath]:
324 """Get the appropriate PurePath class for this machine."""
325 if self.is_windows():
326 return PureWindowsPath
327 return PurePosixPath
328
329 def is_linux(self) -> bool:
330 """
331 Machine is linux?
332 """
333 return self.system == 'linux'
334
335 def is_darwin(self) -> bool:
336 """
337 Machine is Darwin (macOS/iOS/tvOS/visionOS/watchOS)?
338 """
339 return self.system in {'darwin', 'ios', 'tvos', 'visionos', 'watchos'}
340
341 def is_android(self) -> bool:
342 """
343 Machine is Android?
344 """
345 return self.system == 'android'
346
347 def is_ohos(self) -> bool:
348 """
349 Machine is OpenHarmony (OHOS)?
350
351 OHOS is modelled as an Android subsystem: it behaves like Android
352 (apps are shared libraries, no versioned sonames, ...) but uses musl
353 instead of Bionic. Machine files select it with system = 'android'
354 and subsystem = 'ohos'.
355 """
356 return self.is_android() and self.subsystem == 'ohos'
357
358 def is_haiku(self) -> bool:
359 """
360 Machine is Haiku?
361 """
362 return self.system == 'haiku'
363
364 def is_netbsd(self) -> bool:
365 """
366 Machine is NetBSD?
367 """
368 return self.system == 'netbsd'
369
370 def is_openbsd(self) -> bool:
371 """
372 Machine is OpenBSD?
373 """
374 return self.system == 'openbsd'
375
376 def is_dragonflybsd(self) -> bool:
377 """Machine is DragonFly BSD?"""
378 return self.system == 'dragonfly'
379
380 def is_freebsd(self) -> bool:
381 """Machine is FreeBSD?"""
382 return self.system == 'freebsd'
383
384 def is_sunos(self) -> bool:
385 """Machine is illumos or Solaris?"""
386 return self.system == 'sunos'
387
388 def is_hurd(self) -> bool:
389 """
390 Machine is GNU/Hurd?
391 """
392 return self.system == 'gnu'
393
394 def is_aix(self) -> bool:
395 """
396 Machine is aix?
397 """
398 return self.system == 'aix'
399
400 def is_irix(self) -> bool:
401 """Machine is IRIX?"""
402 return self.system.startswith('irix')
403
404 def is_os2(self) -> bool:
405 """
406 Machine is OS/2?
407 """
408 return self.system == 'os/2'
409
410 def is_fuchsia(self) -> bool:
411 return self.system == 'fuchsia'
412
413 # Various prefixes and suffixes for import libraries, shared libraries,
414 # static libraries, and executables.
415 # Versioning is added to these names in the backends as-needed.
416 def get_exe_suffix(self) -> str:
417 if self.is_windows() or self.is_cygwin() or self.is_os2():
418 return 'exe'
419 else:
420 return ''
421
422 def get_object_suffix(self) -> str:
423 if self.is_windows():
424 return 'obj'
425 else:
426 return 'o'
427
428 def libdir_layout_is_win(self) -> bool:
429 return self.is_windows() or self.is_cygwin()
430
431 class BinaryTable:
432
433 def __init__(
434 self,
435 binaries: T.Optional[T.Mapping[str, ElementaryOptionValues]] = None,
436 ):
437 self.binaries: T.Dict[str, T.List[str]] = {}
438 if binaries:
439 for name, command in binaries.items():
440 if not isinstance(command, (list, str)):
441 raise mesonlib.MesonException(
442 f'Invalid type {command!r} for entry {name!r} in cross file')
443 self.binaries[name] = mesonlib.listify(command)
444 if 'pkgconfig' in self.binaries:
445 if 'pkg-config' not in self.binaries:
446 mlog.deprecation('"pkgconfig" entry is deprecated and should be replaced by "pkg-config"', fatal=False)
447 self.binaries['pkg-config'] = self.binaries['pkgconfig']
448 elif self.binaries['pkgconfig'] != self.binaries['pkg-config']:
449 raise mesonlib.MesonException('Mismatched pkgconfig and pkg-config binaries in the machine file.')
450 else:
451 # Both are defined with the same value, this is allowed
452 # for backward compatibility.
453 # FIXME: We should still print deprecation warning if the
454 # project targets Meson >= 1.3.0, but we have no way to know
455 # that here.
456 pass
457 del self.binaries['pkgconfig']
458
459 @staticmethod
460 def detect_ccache() -> ExternalProgram:
461 return ExternalProgram('ccache', silent=True)
462
463 @staticmethod
464 def detect_sccache() -> ExternalProgram:
465 return ExternalProgram('sccache', silent=True)
466
467 @staticmethod
468 def detect_compiler_cache() -> ExternalProgram:
469 # Sccache is "newer" so it is assumed that people would prefer it by default.
470 cache = BinaryTable.detect_sccache()
471 if cache.found():
472 return cache
473 return BinaryTable.detect_ccache()
474
475 @classmethod
476 def parse_entry(cls, entry: T.Union[str, T.List[str]]) -> T.Tuple[T.List[str], T.Union[None, ExternalProgram]]:
477 parts = mesonlib.stringlistify(entry)
478 # Ensure ccache exists and remove it if it doesn't
479 if parts[0] == 'ccache':
480 compiler = parts[1:]
481 ccache = cls.detect_ccache()
482 elif parts[0] == 'sccache':
483 compiler = parts[1:]
484 ccache = cls.detect_sccache()
485 else:
486 compiler = parts
487 ccache = None
488 if not compiler:
489 raise EnvironmentException(f'Compiler cache specified without compiler: {parts[0]}')
490 # Return value has to be a list of compiler 'choices'
491 return compiler, ccache
492
493 def lookup_entry(self, name: str) -> T.Optional[T.List[str]]:
494 """Lookup binary in cross/native file and fallback to environment.
495
496 Returns command with args as list if found, Returns `None` if nothing is
497 found.
498 """
499 command = self.binaries.get(name)
500 if not command:
501 return None
502 elif not command[0].strip():
503 return None
504 return command
505
506 class CMakeVariables:
507 def __init__(self, variables: T.Optional[T.Dict[str, T.Any]] = None) -> None:
508 variables = variables or {}
509 self.variables: T.Dict[str, T.List[str]] = {}
510
511 for key, value in variables.items():
512 value = mesonlib.listify(value)
513 for i in value:
514 if not isinstance(i, str):
515 raise EnvironmentException(f"Value '{i}' of CMake variable '{key}' defined in a machine file is a {type(i).__name__} and not a str")
516 self.variables[key] = value
517
518 def get_variables(self) -> T.Dict[str, T.List[str]]:
519 return self.variables
520
521
522 # Machine and platform detection functions
523 # ========================================
524
525 KERNEL_MAPPINGS: T.Mapping[str, str] = {'freebsd': 'freebsd',
526 'openbsd': 'openbsd',
527 'netbsd': 'netbsd',
528 'windows': 'nt',
529 'android': 'linux',
530 'linux': 'linux',
531 'cygwin': 'nt',
532 'darwin': 'xnu',
533 'ios': 'xnu',
534 'tvos': 'xnu',
535 'visionos': 'xnu',
536 'watchos': 'xnu',
537 'dragonfly': 'dragonfly',
538 'haiku': 'haiku',
539 'gnu': 'gnu',
540 'fuchsia': 'fuchsia',
541 }
542
543 def detect_windows_arch(compilers: CompilerDict) -> str:
544 """
545 Detecting the 'native' architecture of Windows is not a trivial task. We
546 cannot trust that the architecture that Python is built for is the 'native'
547 one because you can run 32-bit apps on 64-bit Windows using WOW64 and
548 people sometimes install 32-bit Python on 64-bit Windows.
549
550 We also can't rely on the architecture of the OS itself, since it's
551 perfectly normal to compile and run 32-bit applications on Windows as if
552 they were native applications. It's a terrible experience to require the
553 user to supply a cross-info file to compile 32-bit applications on 64-bit
554 Windows. Thankfully, the only way to compile things with Visual Studio on
555 Windows is by entering the 'msvc toolchain' environment, which can be
556 easily detected.
557
558 In the end, the sanest method is as follows:
559 1. Check environment variables that are set by Windows and WOW64 to find out
560 if this is x86 (possibly in WOW64), if so use that as our 'native'
561 architecture.
562 2. If the compiler toolchain target architecture is x86, use that as our
563 'native' architecture.
564 3. Otherwise, use the actual Windows architecture
565
566 """
567 os_arch = mesonlib.windows_detect_native_arch()
568 if os_arch == 'x86':
569 return os_arch
570 # If we're on 64-bit Windows, 32-bit apps can be compiled without
571 # cross-compilation. So if we're doing that, just set the native arch as
572 # 32-bit and pretend like we're running under WOW64. Else, return the
573 # actual Windows architecture that we deduced above.
574 for compiler in compilers.values():
575 compiler = T.cast('VisualStudioLikeCompiler', compiler)
576 if compiler.id == 'msvc' and (compiler.target in {'x86', '80x86'}):
577 return 'x86'
578 if compiler.id == 'clang-cl' and (compiler.target in {'x86', 'i686'}):
579 return 'x86'
580 if compiler.id == 'gcc' and compiler.has_builtin_define('__i386__'):
581 return 'x86'
582 return os_arch
583
584 def any_compiler_has_define(compilers: CompilerDict, define: str) -> bool:
585 for c in compilers.values():
586 try:
587 if c.has_builtin_define(define):
588 return True
589 except mesonlib.MesonException:
590 # Ignore compilers that do not support has_builtin_define.
591 pass
592 return False
593
594 def detect_cpu_family(compilers: CompilerDict) -> str:
595 """
596 Python is inconsistent in its platform module.
597 It returns different values for the same cpu.
598 For x86 it might return 'x86', 'i686' or some such.
599 Do some canonicalization.
600 """
601 if mesonlib.is_windows():
602 trial = detect_windows_arch(compilers)
603 elif mesonlib.is_freebsd() or mesonlib.is_netbsd() or mesonlib.is_openbsd() or mesonlib.is_qnx() or mesonlib.is_aix():
604 trial = platform.processor().lower()
605 else:
606 trial = platform.machine().lower()
607 if trial.startswith('i') and trial.endswith('86'):
608 trial = 'x86'
609 elif trial == 'bepc':
610 trial = 'x86'
611 elif trial == 'arm64':
612 trial = 'aarch64'
613 elif trial.startswith('aarch64'):
614 # This can be `aarch64_be`
615 trial = 'aarch64'
616 elif trial.startswith('arm') or trial.startswith('earm'):
617 trial = 'arm'
618 elif trial.startswith(('powerpc64', 'ppc64')):
619 trial = 'ppc64'
620 elif trial.startswith(('powerpc', 'ppc')) or trial in {'macppc', 'power macintosh'}:
621 trial = 'ppc'
622 elif trial in {'amd64', 'x64', 'i86pc'}:
623 trial = 'x86_64'
624 elif trial in {'sun4u', 'sun4v'}:
625 trial = 'sparc64'
626 elif trial.startswith('mips'):
627 if '64' not in trial:
628 trial = 'mips'
629 else:
630 trial = 'mips64'
631 elif trial in {'ip30', 'ip35'}:
632 trial = 'mips64'
633
634 # On Linux (and maybe others) there can be any mixture of 32/64 bit code in
635 # the kernel, Python, system, 32-bit chroot on 64-bit host, etc. The only
636 # reliable way to know is to check the compiler defines.
637 if trial == 'x86_64':
638 if any_compiler_has_define(compilers, '__i386__'):
639 trial = 'x86'
640 elif trial == 'aarch64':
641 if any_compiler_has_define(compilers, '__arm__'):
642 trial = 'arm'
643 # Add more quirks here as bugs are reported. Keep in sync with detect_cpu()
644 # below.
645 elif trial == 'parisc64':
646 # ATM there is no 64 bit userland for PA-RISC. Thus always
647 # report it as 32 bit for simplicity.
648 trial = 'parisc'
649 elif trial == 'ppc':
650 # AIX always returns powerpc, check here for 64-bit
651 if any_compiler_has_define(compilers, '__64BIT__'):
652 trial = 'ppc64'
653 # MIPS64 is able to run MIPS32 code natively, so there is a chance that
654 # such mixture mentioned above exists.
655 elif trial == 'mips64':
656 if compilers and not any_compiler_has_define(compilers, '__mips64'):
657 trial = 'mips'
658
659 if trial not in known_cpu_families:
660 mlog.warning(f'Unknown CPU family {trial!r}, please report this at '
661 'https://github.com/mesonbuild/meson/issues/new with the '
662 'output of `uname -a` and `cat /proc/cpuinfo`')
663
664 return trial
665
666 def detect_cpu(compilers: CompilerDict) -> str:
667 if mesonlib.is_windows():
668 trial = detect_windows_arch(compilers)
669 elif mesonlib.is_freebsd() or mesonlib.is_netbsd() or mesonlib.is_openbsd() or mesonlib.is_aix():
670 trial = platform.processor().lower()
671 else:
672 trial = platform.machine().lower()
673
674 if trial in {'amd64', 'x64', 'i86pc'}:
675 trial = 'x86_64'
676 if trial == 'x86_64':
677 # Same check as above for cpu_family
678 if any_compiler_has_define(compilers, '__i386__'):
679 trial = 'i686' # All 64 bit cpus have at least this level of x86 support.
680 elif trial.startswith('aarch64') or trial.startswith('arm64'):
681 # Same check as above for cpu_family
682 if any_compiler_has_define(compilers, '__arm__'):
683 trial = 'arm'
684 else:
685 # for aarch64_be
686 trial = 'aarch64'
687 elif trial.startswith('earm'):
688 trial = 'arm'
689 elif trial == 'e2k':
690 # Make more precise CPU detection for Elbrus platform.
691 trial = platform.processor().lower()
692 elif trial.startswith('mips'):
693 if '64' not in trial:
694 trial = 'mips'
695 else:
696 if compilers and not any_compiler_has_define(compilers, '__mips64'):
697 trial = 'mips'
698 else:
699 trial = 'mips64'
700 elif trial == 'ppc':
701 # AIX always returns powerpc, check here for 64-bit
702 if any_compiler_has_define(compilers, '__64BIT__'):
703 trial = 'ppc64'
704
705 # Add more quirks here as bugs are reported. Keep in sync with
706 # detect_cpu_family() above.
707 return trial
708
709 def detect_kernel(system: str) -> T.Optional[str]:
710 if system == 'sunos':
711 # Solaris 5.10 uname doesn't support the -o switch, and illumos started
712 # with version 5.11 so shortcut the logic to report 'solaris' in such
713 # cases where the version is 5.10 or below.
714 if mesonlib.version_compare(platform.uname().release, '<=5.10'):
715 return 'solaris'
716 # This needs to be /usr/bin/uname because gnu-uname could be installed and
717 # won't provide the necessary information
718 p, out, _ = Popen_safe(['/usr/bin/uname', '-o'])
719 if p.returncode != 0:
720 raise mesonlib.MesonException('Failed to run "/usr/bin/uname -o"')
721 out = out.lower().strip()
722 if out not in {'illumos', 'solaris'}:
723 mlog.warning(f'Got an unexpected value for kernel on a SunOS derived platform, expected either "illumos" or "solaris", but got "{out}".'
724 "Please open a Meson issue with the OS you're running and the value detected for your kernel.")
725 return None
726 return out
727 return KERNEL_MAPPINGS.get(system, None)
728
729 def detect_subsystem(system: str) -> T.Optional[str]:
730 if system == 'darwin':
731 return 'macos'
732 return system
733
734 def detect_system() -> str:
735 if sys.platform == 'cygwin':
736 return 'cygwin'
737 return platform.system().lower()
738
739 def detect_msys2_arch() -> T.Optional[str]:
740 return os.environ.get('MSYSTEM_CARCH', None)
741
742 def detect_machine_info(compilers: T.Optional[CompilerDict] = None) -> MachineInfo:
743 """Detect the machine we're running on
744
745 If compilers are not provided, we cannot know as much. None out those
746 fields to avoid accidentally depending on partial knowledge. The
747 underlying ''detect_*'' method can be called to explicitly use the
748 partial information.
749 """
750 system = detect_system()
751 return MachineInfo(
752 system,
753 detect_cpu_family(compilers) if compilers is not None else None,
754 detect_cpu(compilers) if compilers is not None else None,
755 sys.byteorder,
756 detect_kernel(system),
757 detect_subsystem(system))
758
759 # TODO make this compare two `MachineInfo`s purely. How important is the
760 # `detect_cpu_family({})` distinction? It is the one impediment to that.
761 def machine_info_can_run(machine_info: MachineInfo) -> bool:
762 """Whether we can run binaries for this machine on the current machine.
763
764 Can almost always run 32-bit binaries on 64-bit natively if the host
765 and build systems are the same. We don't pass any compilers to
766 detect_cpu_family() here because we always want to know the OS
767 architecture, not what the compiler environment tells us.
768 """
769 system = detect_system()
770 if machine_info.system != system:
771 return False
772 if machine_info.subsystem and machine_info.subsystem != detect_subsystem(system):
773 return False
774 true_build_cpu_family = detect_cpu_family({})
775 assert machine_info.cpu_family is not None, 'called on incomplete machine_info'
776 return \
777 (machine_info.cpu_family == true_build_cpu_family) or \
778 ((true_build_cpu_family == 'x86_64') and (machine_info.cpu_family == 'x86')) or \
779 ((true_build_cpu_family == 'mips64') and (machine_info.cpu_family == 'mips'))