| 1 |
# SPDX-License-Identifier: Apache-2.0 |
| 2 |
# Copyright 2012-2022 The Meson development team |
| 3 |
# Copyright © 2023-2025 Intel Corporation |
| 4 |
|
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
import abc |
| 8 |
import contextlib, os.path, re |
| 9 |
import enum |
| 10 |
import itertools |
| 11 |
import typing as T |
| 12 |
from dataclasses import dataclass, field |
| 13 |
from functools import lru_cache |
| 14 |
|
| 15 |
from .. import mlog |
| 16 |
from .. import mesonlib |
| 17 |
from .. import options |
| 18 |
from ..mesonlib import ( |
| 19 |
HoldableObject, SimpleABC, |
| 20 |
EnvironmentException, MesonBugException, MesonException, |
| 21 |
Popen_safe_logged, LibType, TemporaryDirectoryWinProof, |
| 22 |
) |
| 23 |
from ..options import OptionKey |
| 24 |
from ..arglist import CompilerArgs |
| 25 |
|
| 26 |
if T.TYPE_CHECKING: |
| 27 |
from typing_extensions import Literal, TypeAlias |
| 28 |
|
| 29 |
from .. import build |
| 30 |
from .. import coredata |
| 31 |
from ..build import BuildTarget, DFeatures |
| 32 |
from ..options import MutableKeyedOptionDictType |
| 33 |
from ..envconfig import MachineInfo |
| 34 |
from ..environment import Environment |
| 35 |
from ..linkers import RSPFileSyntax |
| 36 |
from ..linkers.linkers import DynamicLinker |
| 37 |
from ..mesonlib import MachineChoice |
| 38 |
from ..dependencies import Dependency |
| 39 |
|
| 40 |
# See the comment on `lang_suffixes` if modifying this list. |
| 41 |
Language = Literal[ |
| 42 |
'c', 'cpp', 'cuda', 'fortran', 'd', 'objc', 'objcpp', 'rust', 'vala', |
| 43 |
'cs', 'swift', 'java', 'cython', 'nasm', 'masm', 'linearasm' |
| 44 |
] |
| 45 |
CompilerDict: TypeAlias = T.Dict[Language, 'Compiler'] |
| 46 |
|
| 47 |
_T = T.TypeVar('_T') |
| 48 |
|
| 49 |
"""This file contains the data files of all compilers Meson knows |
| 50 |
about. To support a new compiler, add its information below. |
| 51 |
Also add corresponding autodetection code in detect.py.""" |
| 52 |
|
| 53 |
header_suffixes = {'h', 'hh', 'hpp', 'hxx', 'H', 'ipp', 'moc', 'vapi', 'di', 'pxd', 'pxi'} |
| 54 |
obj_suffixes = {'o', 'obj', 'res'} |
| 55 |
# To the emscripten compiler, .js files are libraries |
| 56 |
lib_suffixes = {'a', 'lib', 'dll', 'dll.a', 'dylib', 'so', 'js'} |
| 57 |
# Mapping of language to suffixes of files that should always be in that language |
| 58 |
# This means we can't include .h headers here since they could be C, C++, ObjC, etc. |
| 59 |
# First suffix is the language's default. |
| 60 |
|
| 61 |
# Don't forget to update the Language if adding new keys, as well as |
| 62 |
# docs/yaml/functions/project.yaml |
| 63 |
lang_suffixes: T.Mapping[Language, T.Tuple[str, ...]] = { |
| 64 |
'c': ('c',), |
| 65 |
'cpp': ('cpp', 'cppm', 'cc', 'cp', 'cxx', 'c++', 'hh', 'hp', 'hpp', 'ipp', 'hxx', 'h++', 'ino', 'ixx', 'CPP', 'C', 'HPP', 'H'), |
| 66 |
'cuda': ('cu',), |
| 67 |
# f90, f95, f03, f08 are for free-form fortran ('f90' recommended) |
| 68 |
# f, for, ftn, fpp are for fixed-form fortran ('f' or 'for' recommended) |
| 69 |
'fortran': ('f90', 'f95', 'f03', 'f08', 'f', 'for', 'ftn', 'fpp'), |
| 70 |
'd': ('d', 'di'), |
| 71 |
'objc': ('m',), |
| 72 |
'objcpp': ('mm',), |
| 73 |
'rust': ('rs',), |
| 74 |
'vala': ('vala', 'vapi', 'gs'), |
| 75 |
'cs': ('cs',), |
| 76 |
'swift': ('swift',), |
| 77 |
'java': ('java',), |
| 78 |
'cython': ('pyx', ), |
| 79 |
'nasm': ('asm', 'nasm',), |
| 80 |
'masm': ('masm',), |
| 81 |
'linearasm': ('sa',), |
| 82 |
} |
| 83 |
# Some compilers only recognize files with specific suffixes. |
| 84 |
compiler_suffixes: T.Mapping[str, T.Tuple[str, ...]] = { |
| 85 |
'msvc': ('c', 'cc', 'cxx', 'cpp', 'obj', 'lib', 'def'), |
| 86 |
} |
| 87 |
all_languages: mesonlib.OrderedSet[Language] = mesonlib.OrderedSet(sorted(lang_suffixes)) |
| 88 |
c_cpp_suffixes = {'h'} |
| 89 |
cpp_suffixes = set(lang_suffixes['cpp']) | c_cpp_suffixes |
| 90 |
c_suffixes = set(lang_suffixes['c']) | c_cpp_suffixes |
| 91 |
assembler_suffixes = {'s', 'S', 'sx', 'asm', 'masm'} |
| 92 |
llvm_ir_suffixes = {'ll'} |
| 93 |
all_suffixes = set(itertools.chain(*lang_suffixes.values(), assembler_suffixes, llvm_ir_suffixes, c_cpp_suffixes)) |
| 94 |
source_suffixes = all_suffixes - header_suffixes |
| 95 |
# List of languages that by default consume and output libraries following the |
| 96 |
# C ABI; these can generally be used interchangeably |
| 97 |
# This must be sorted, see sort_clink(). |
| 98 |
clib_langs = ('objcpp', 'cpp', 'objc', 'c', 'nasm', 'fortran') |
| 99 |
# List of languages that can be linked with C code directly by the linker |
| 100 |
# used in build.py:process_compilers() and build.py:get_dynamic_linker() |
| 101 |
# This must be sorted, see sort_clink(). |
| 102 |
clink_langs = ('rust', 'd', 'cuda') + clib_langs |
| 103 |
|
| 104 |
SUFFIX_TO_LANG: T.Mapping[str, Language] = dict(itertools.chain(*( |
| 105 |
[(suffix, lang) for suffix in v] for lang, v in lang_suffixes.items()))) |
| 106 |
|
| 107 |
# Languages that should use LDFLAGS arguments when linking. |
| 108 |
LANGUAGES_USING_LDFLAGS = {'objcpp', 'cpp', 'objc', 'c', 'fortran', 'd', 'cuda'} |
| 109 |
# Languages that should use CPPFLAGS arguments when linking. |
| 110 |
LANGUAGES_USING_CPPFLAGS = {'c', 'cpp', 'objc', 'objcpp'} |
| 111 |
soregex = re.compile(r'.*\.so(\.[0-9]+)?(\.[0-9]+)?(\.[0-9]+)?$') |
| 112 |
|
| 113 |
# Environment variables that each lang uses. |
| 114 |
CFLAGS_MAPPING: T.Mapping[Language, str] = { |
| 115 |
'c': 'CFLAGS', |
| 116 |
'cpp': 'CXXFLAGS', |
| 117 |
'cuda': 'CUFLAGS', |
| 118 |
'objc': 'OBJCFLAGS', |
| 119 |
'objcpp': 'OBJCXXFLAGS', |
| 120 |
'fortran': 'FFLAGS', |
| 121 |
'd': 'DFLAGS', |
| 122 |
'vala': 'VALAFLAGS', |
| 123 |
'rust': 'RUSTFLAGS', |
| 124 |
'cython': 'CYTHONFLAGS', |
| 125 |
'cs': 'CSFLAGS', # This one might not be standard. |
| 126 |
} |
| 127 |
|
| 128 |
# All these are only for C-linkable languages; see `clink_langs` above. |
| 129 |
|
| 130 |
def sort_clink(lang: Language) -> int: |
| 131 |
''' |
| 132 |
Sorting function to sort the list of languages according to |
| 133 |
reversed(compilers.clink_langs) and append the unknown langs in the end. |
| 134 |
The purpose is to prefer C over C++ for files that can be compiled by |
| 135 |
both such as assembly, C, etc. Also applies to ObjC, ObjC++, etc. |
| 136 |
''' |
| 137 |
if lang not in clink_langs: |
| 138 |
return 1 |
| 139 |
return -clink_langs.index(lang) |
| 140 |
|
| 141 |
def is_header(fname: 'mesonlib.FileOrString') -> bool: |
| 142 |
if isinstance(fname, mesonlib.File): |
| 143 |
fname = fname.fname |
| 144 |
suffix = fname.split('.')[-1] |
| 145 |
return suffix in header_suffixes |
| 146 |
|
| 147 |
def is_source_suffix(suffix: str) -> bool: |
| 148 |
return suffix in source_suffixes |
| 149 |
|
| 150 |
@lru_cache(maxsize=None) |
| 151 |
def cached_is_source_by_name(fname: str) -> bool: |
| 152 |
suffix = fname.split('.')[-1].lower() |
| 153 |
return is_source_suffix(suffix) |
| 154 |
|
| 155 |
def is_source(fname: 'mesonlib.FileOrString') -> bool: |
| 156 |
if isinstance(fname, mesonlib.File): |
| 157 |
fname = fname.fname |
| 158 |
return cached_is_source_by_name(fname) |
| 159 |
|
| 160 |
def is_assembly(fname: 'mesonlib.FileOrString') -> bool: |
| 161 |
if isinstance(fname, mesonlib.File): |
| 162 |
fname = fname.fname |
| 163 |
suffix = fname.split('.')[-1] |
| 164 |
return suffix in assembler_suffixes |
| 165 |
|
| 166 |
def is_java(fname: mesonlib.FileOrString) -> bool: |
| 167 |
if isinstance(fname, mesonlib.File): |
| 168 |
fname = fname.fname |
| 169 |
suffix = fname.split('.')[-1] |
| 170 |
return suffix in lang_suffixes['java'] |
| 171 |
|
| 172 |
def is_separate_compile(fname: mesonlib.FileOrString) -> bool: |
| 173 |
return not fname.endswith('.rs') |
| 174 |
|
| 175 |
def is_llvm_ir(fname: 'mesonlib.FileOrString') -> bool: |
| 176 |
if isinstance(fname, mesonlib.File): |
| 177 |
fname = fname.fname |
| 178 |
suffix = fname.split('.')[-1] |
| 179 |
return suffix in llvm_ir_suffixes |
| 180 |
|
| 181 |
@lru_cache(maxsize=None) |
| 182 |
def cached_is_object_by_name(fname: str) -> bool: |
| 183 |
suffix = fname.split('.')[-1] |
| 184 |
return suffix in obj_suffixes |
| 185 |
|
| 186 |
def is_object(fname: 'mesonlib.FileOrString') -> bool: |
| 187 |
if isinstance(fname, mesonlib.File): |
| 188 |
fname = fname.fname |
| 189 |
return cached_is_object_by_name(fname) |
| 190 |
|
| 191 |
@lru_cache(maxsize=None) |
| 192 |
def cached_is_library_by_name(fname: str) -> bool: |
| 193 |
if soregex.match(fname): |
| 194 |
return True |
| 195 |
|
| 196 |
suffix = fname.split('.')[-1] |
| 197 |
return suffix in lib_suffixes |
| 198 |
|
| 199 |
def is_library(fname: 'mesonlib.FileOrString') -> bool: |
| 200 |
if isinstance(fname, mesonlib.File): |
| 201 |
fname = fname.fname |
| 202 |
return cached_is_library_by_name(fname) |
| 203 |
|
| 204 |
def is_known_suffix(fname: 'mesonlib.FileOrString') -> bool: |
| 205 |
if isinstance(fname, mesonlib.File): |
| 206 |
fname = fname.fname |
| 207 |
suffix = fname.split('.')[-1] |
| 208 |
|
| 209 |
return suffix in all_suffixes |
| 210 |
|
| 211 |
|
| 212 |
class CompileCheckMode(enum.Enum): |
| 213 |
|
| 214 |
PREPROCESS = 'preprocess' |
| 215 |
COMPILE = 'compile' |
| 216 |
LINK = 'link' |
| 217 |
|
| 218 |
|
| 219 |
gnu_winlibs = ['-lkernel32', '-luser32', '-lgdi32', '-lwinspool', '-lshell32', |
| 220 |
'-lole32', '-loleaut32', '-luuid', '-lcomdlg32', '-ladvapi32'] |
| 221 |
|
| 222 |
msvc_winlibs = ['kernel32.lib', 'user32.lib', 'gdi32.lib', |
| 223 |
'winspool.lib', 'shell32.lib', 'ole32.lib', 'oleaut32.lib', |
| 224 |
'uuid.lib', 'comdlg32.lib', 'advapi32.lib'] |
| 225 |
|
| 226 |
clike_optimization_args: T.Dict[str, T.List[str]] = { |
| 227 |
'plain': [], |
| 228 |
'0': [], |
| 229 |
'g': [], |
| 230 |
'1': ['-O1'], |
| 231 |
'2': ['-O2'], |
| 232 |
'3': ['-O3'], |
| 233 |
's': ['-Os'], |
| 234 |
} |
| 235 |
|
| 236 |
clike_debug_args: T.Dict[bool, T.List[str]] = { |
| 237 |
False: [], |
| 238 |
True: ['-g'] |
| 239 |
} |
| 240 |
|
| 241 |
|
| 242 |
def option_enabled(boptions: T.Set[OptionKey], |
| 243 |
target: 'BuildTarget', |
| 244 |
env: 'Environment', |
| 245 |
option: T.Union[str, OptionKey]) -> bool: |
| 246 |
if isinstance(option, str): |
| 247 |
option = OptionKey(option) |
| 248 |
try: |
| 249 |
if option not in boptions: |
| 250 |
return False |
| 251 |
ret = env.coredata.get_option_for_target(target, option) |
| 252 |
assert isinstance(ret, bool), 'must return bool' # could also be str |
| 253 |
return ret |
| 254 |
except KeyError: |
| 255 |
return False |
| 256 |
|
| 257 |
|
| 258 |
def get_option_value_for_target(env: 'Environment', target: 'BuildTarget', opt: OptionKey, fallback: '_T') -> '_T': |
| 259 |
"""Get the value of an option, or the fallback value.""" |
| 260 |
try: |
| 261 |
v = env.coredata.get_option_for_target(target, opt) |
| 262 |
except (KeyError, AttributeError): |
| 263 |
return fallback |
| 264 |
|
| 265 |
assert isinstance(v, type(fallback)), f'Should have {type(fallback)!r} but was {type(v)!r}' |
| 266 |
# Mypy doesn't understand that the above assert ensures that v is type _T |
| 267 |
return v |
| 268 |
|
| 269 |
|
| 270 |
def are_asserts_disabled(target: 'BuildTarget', env: 'Environment') -> bool: |
| 271 |
"""Should debug assertions be disabled |
| 272 |
|
| 273 |
:param target: a target to check for |
| 274 |
:param env: the environment |
| 275 |
:return: whether to disable assertions or not |
| 276 |
""" |
| 277 |
return (env.coredata.get_option_for_target(target, 'b_ndebug') == 'true' or |
| 278 |
(env.coredata.get_option_for_target(target, 'b_ndebug') == 'if-release' and |
| 279 |
env.coredata.get_option_for_target(target, 'buildtype') in {'release', 'plain'})) |
| 280 |
|
| 281 |
|
| 282 |
def are_asserts_disabled_for_subproject(subproject: str, env: 'Environment') -> bool: |
| 283 |
key = OptionKey('b_ndebug', subproject) |
| 284 |
return (env.coredata.optstore.get_value_for(key) == 'true' or |
| 285 |
(env.coredata.optstore.get_value_for(key) == 'if-release' and |
| 286 |
env.coredata.optstore.get_value_for(key.evolve(name='buildtype')) in {'release', 'plain'})) |
| 287 |
|
| 288 |
|
| 289 |
def get_base_compile_args(target: 'BuildTarget', compiler: 'Compiler', env: 'Environment') -> T.List[str]: |
| 290 |
args: T.List[str] = [] |
| 291 |
lto = False |
| 292 |
try: |
| 293 |
if env.coredata.get_option_for_target(target, 'b_lto'): |
| 294 |
num_threads = get_option_value_for_target(env, target, OptionKey('b_lto_threads'), 0) |
| 295 |
ltomode = get_option_value_for_target(env, target, OptionKey('b_lto_mode'), 'default') |
| 296 |
args.extend(compiler.get_lto_compile_args( |
| 297 |
target=target, |
| 298 |
threads=num_threads, |
| 299 |
mode=ltomode)) |
| 300 |
lto = True |
| 301 |
except (KeyError, AttributeError): |
| 302 |
pass |
| 303 |
try: |
| 304 |
clrout = env.coredata.get_option_for_target(target, 'b_colorout') |
| 305 |
assert isinstance(clrout, str) |
| 306 |
args += compiler.get_colorout_args(clrout) |
| 307 |
except KeyError: |
| 308 |
pass |
| 309 |
try: |
| 310 |
sanitize = env.coredata.get_option_for_target(target, 'b_sanitize') |
| 311 |
assert isinstance(sanitize, list) |
| 312 |
if sanitize == ['none']: |
| 313 |
sanitize = [] |
| 314 |
sanitize_args = compiler.sanitizer_compile_args(target, sanitize) |
| 315 |
# We consider that if there are no sanitizer arguments returned, then |
| 316 |
# the language doesn't support them. |
| 317 |
if sanitize_args: |
| 318 |
if not compiler.has_multi_arguments(sanitize_args)[0]: |
| 319 |
raise MesonException(f'Compiler {compiler.name_string()} does not support sanitizer arguments {sanitize_args}') |
| 320 |
args.extend(sanitize_args) |
| 321 |
except KeyError: |
| 322 |
pass |
| 323 |
try: |
| 324 |
pgo_val = env.coredata.get_option_for_target(target, 'b_pgo') |
| 325 |
if pgo_val == 'generate': |
| 326 |
args.extend(compiler.get_profile_generate_args()) |
| 327 |
elif pgo_val == 'use': |
| 328 |
args.extend(compiler.get_profile_use_args()) |
| 329 |
except (KeyError, AttributeError): |
| 330 |
pass |
| 331 |
try: |
| 332 |
if env.coredata.get_option_for_target(target, 'b_coverage'): |
| 333 |
args += compiler.get_coverage_args() |
| 334 |
except (KeyError, AttributeError): |
| 335 |
pass |
| 336 |
try: |
| 337 |
args += compiler.get_assert_args(are_asserts_disabled(target, env)) |
| 338 |
except KeyError: |
| 339 |
pass |
| 340 |
# This does not need a try...except |
| 341 |
bitcode = option_enabled(compiler.base_options, target, env, 'b_bitcode') |
| 342 |
args.extend(compiler.get_embed_bitcode_args(bitcode, lto)) |
| 343 |
try: |
| 344 |
crt_val = env.coredata.get_option_for_target(target, 'b_vscrt') |
| 345 |
assert isinstance(crt_val, str) |
| 346 |
try: |
| 347 |
args += compiler.get_crt_compile_args(crt_val) |
| 348 |
except EnvironmentException: |
| 349 |
pass |
| 350 |
except KeyError: |
| 351 |
pass |
| 352 |
return args |
| 353 |
|
| 354 |
def get_base_link_args(target: 'BuildTarget', |
| 355 |
linker: 'Compiler', |
| 356 |
env: 'Environment') -> T.List[str]: |
| 357 |
args: T.List[str] = [] |
| 358 |
build_dir = env.get_build_dir() |
| 359 |
if env.coredata.get_option_for_target(target, 'werror'): |
| 360 |
args.extend(linker.get_linker_fatal_warnings()) |
| 361 |
try: |
| 362 |
if env.coredata.get_option_for_target(target, 'b_lto'): |
| 363 |
if env.coredata.get_option_for_target(target, 'werror'): |
| 364 |
args.extend(linker.get_werror_args()) |
| 365 |
|
| 366 |
thinlto_cache_dir = None |
| 367 |
cachedir_key = OptionKey('b_thinlto_cache') |
| 368 |
if get_option_value_for_target(env, target, cachedir_key, False): |
| 369 |
thinlto_cache_dir = get_option_value_for_target(env, target, OptionKey('b_thinlto_cache_dir'), '') |
| 370 |
if thinlto_cache_dir == '': |
| 371 |
thinlto_cache_dir = os.path.join(build_dir, 'meson-private', 'thinlto-cache') |
| 372 |
os.makedirs(thinlto_cache_dir, exist_ok=True) |
| 373 |
num_threads = get_option_value_for_target(env, target, OptionKey('b_lto_threads'), 0) |
| 374 |
lto_mode = get_option_value_for_target(env, target, OptionKey('b_lto_mode'), 'default') |
| 375 |
args.extend(linker.get_lto_link_args( |
| 376 |
target=target, |
| 377 |
threads=num_threads, |
| 378 |
mode=lto_mode, |
| 379 |
thinlto_cache_dir=thinlto_cache_dir)) |
| 380 |
obj_cache_path = os.path.join('@PRIVATE_DIR@', "lto.o") |
| 381 |
args.extend(linker.get_lto_obj_cache_path(obj_cache_path)) |
| 382 |
except (KeyError, AttributeError): |
| 383 |
pass |
| 384 |
try: |
| 385 |
sanitizer = env.coredata.get_option_for_target(target, 'b_sanitize') |
| 386 |
assert isinstance(sanitizer, list) |
| 387 |
if sanitizer == ['none']: |
| 388 |
sanitizer = [] |
| 389 |
sanitizer_args = linker.sanitizer_link_args(target, sanitizer) |
| 390 |
# We consider that if there are no sanitizer arguments returned, then |
| 391 |
# the language doesn't support them. |
| 392 |
if sanitizer_args: |
| 393 |
if not linker.has_multi_link_arguments(sanitizer_args, False)[0]: |
| 394 |
raise MesonException(f'Linker {linker.name_string()} does not support sanitizer arguments {sanitizer_args}') |
| 395 |
args.extend(sanitizer_args) |
| 396 |
except KeyError: |
| 397 |
pass |
| 398 |
try: |
| 399 |
pgo_val = env.coredata.get_option_for_target(target, 'b_pgo') |
| 400 |
if pgo_val == 'generate': |
| 401 |
args.extend(linker.get_profile_generate_args()) |
| 402 |
elif pgo_val == 'use': |
| 403 |
args.extend(linker.get_profile_use_args()) |
| 404 |
except (KeyError, AttributeError): |
| 405 |
pass |
| 406 |
try: |
| 407 |
if env.coredata.get_option_for_target(target, 'b_coverage'): |
| 408 |
args += linker.get_coverage_link_args() |
| 409 |
except (KeyError, AttributeError): |
| 410 |
pass |
| 411 |
|
| 412 |
as_needed = option_enabled(linker.base_options, target, env, 'b_asneeded') |
| 413 |
bitcode = option_enabled(linker.base_options, target, env, 'b_bitcode') |
| 414 |
# Shared modules cannot be built with bitcode_bundle because |
| 415 |
# -bitcode_bundle is incompatible with -undefined and -bundle |
| 416 |
if bitcode and not target.typename == 'shared module': |
| 417 |
args.extend(linker.bitcode_args()) |
| 418 |
elif as_needed: |
| 419 |
# -Wl,-dead_strip_dylibs is incompatible with bitcode |
| 420 |
args.extend(linker.get_asneeded_args()) |
| 421 |
|
| 422 |
# Apple's ld (the only one that supports bitcode) does not like -undefined |
| 423 |
# arguments or -headerpad_max_install_names when bitcode is enabled |
| 424 |
if not bitcode: |
| 425 |
from ..build import SharedModule |
| 426 |
args.extend(linker.headerpad_args()) |
| 427 |
if (not isinstance(target, SharedModule) and |
| 428 |
option_enabled(linker.base_options, target, env, 'b_lundef')): |
| 429 |
args.extend(linker.no_undefined_link_args()) |
| 430 |
else: |
| 431 |
args.extend(linker.get_allow_undefined_link_args()) |
| 432 |
|
| 433 |
try: |
| 434 |
crt_val = env.coredata.get_option_for_target(target, 'b_vscrt') |
| 435 |
assert isinstance(crt_val, str) |
| 436 |
try: |
| 437 |
crtargs = linker.get_crt_link_args(crt_val) |
| 438 |
assert isinstance(crtargs, list) |
| 439 |
args += crtargs |
| 440 |
except EnvironmentException: |
| 441 |
pass |
| 442 |
except KeyError: |
| 443 |
pass |
| 444 |
return args |
| 445 |
|
| 446 |
|
| 447 |
class CrossNoRunException(MesonException): |
| 448 |
pass |
| 449 |
|
| 450 |
@dataclass |
| 451 |
class RunResult(HoldableObject): |
| 452 |
compiled: bool |
| 453 |
returncode: int = 999 |
| 454 |
stdout: str = 'UNDEFINED' |
| 455 |
stderr: str = 'UNDEFINED' |
| 456 |
cached: bool = False |
| 457 |
|
| 458 |
|
| 459 |
class LinkerOptionStyle(metaclass=abc.ABCMeta): |
| 460 |
@abc.abstractmethod |
| 461 |
def wrap(self, group: T.List[str]) -> T.List[str]: |
| 462 |
... |
| 463 |
|
| 464 |
|
| 465 |
@dataclass |
| 466 |
class PrefixArgumentLinkerOptionStyle(LinkerOptionStyle): |
| 467 |
""" |
| 468 |
Represents a linker option style where each linker argument is preceded by a separate argument representing |
| 469 |
the compiler's pass-through option, like Clang: ['-Xlinker', 'arg1', '-Xlinker', 'arg2'] passes ['arg1', 'arg2'] to the |
| 470 |
linker. |
| 471 |
""" |
| 472 |
|
| 473 |
prefix_arg: str |
| 474 |
|
| 475 |
def wrap(self, group: T.List[str]) -> T.List[str]: |
| 476 |
return [compiler_arg for linker_arg in group for compiler_arg in [self.prefix_arg, linker_arg]] |
| 477 |
|
| 478 |
|
| 479 |
@dataclass |
| 480 |
class SimplePrefixLinkerOptionStyle(LinkerOptionStyle): |
| 481 |
""" |
| 482 |
Represents a linker option style where each linker argument is prefixed with the compiler's pass-through |
| 483 |
option as part of the same argument, like DMD: ['-L=arg1', '-L=arg2'] passes ['arg1', 'arg2'] to the linker. |
| 484 |
""" |
| 485 |
|
| 486 |
prefix: str |
| 487 |
|
| 488 |
def wrap(self, group: T.List[str]) -> T.List[str]: |
| 489 |
return [self.prefix + linker_arg for linker_arg in group] |
| 490 |
|
| 491 |
|
| 492 |
class LinkerArgumentWrapException(MesonException): |
| 493 |
pass |
| 494 |
|
| 495 |
|
| 496 |
@dataclass |
| 497 |
class ManyInOneLinkerOptionStyle(LinkerOptionStyle): |
| 498 |
""" |
| 499 |
Represents a linker option style where multiple linker arguments are passed as a single argument to the |
| 500 |
compiler combined with a prefix, like GCC: ['-Wl,arg1,arg2'] passes ['arg1', 'arg2'] to the linker. |
| 501 |
""" |
| 502 |
|
| 503 |
prefix: str |
| 504 |
separator: str |
| 505 |
|
| 506 |
fallback: T.Optional[LinkerOptionStyle] = None |
| 507 |
|
| 508 |
def wrap(self, group: T.List[str]) -> T.List[str]: |
| 509 |
for el in group: |
| 510 |
if self.separator not in el: |
| 511 |
continue |
| 512 |
|
| 513 |
if self.fallback is not None: |
| 514 |
return self.fallback.wrap(group) |
| 515 |
|
| 516 |
full = '' |
| 517 |
if len(group) > 1: |
| 518 |
full = f' (part of arguments list {group!r})' |
| 519 |
stripped = f'{self.prefix}{el}' |
| 520 |
raise LinkerArgumentWrapException(f'Cannot wrap linker argument {el!r}{full} for compiler interface: ' |
| 521 |
f'would result in {stripped!r}, which the compiler would interpret as ' |
| 522 |
f'multiple linker arguments since it treats {self.separator!r} as the ' |
| 523 |
'separator.') |
| 524 |
|
| 525 |
return [self.prefix + self.separator.join(group)] |
| 526 |
|
| 527 |
|
| 528 |
@dataclass |
| 529 |
class CompileResult(HoldableObject): |
| 530 |
|
| 531 |
"""The result of Compiler.compiles (and friends).""" |
| 532 |
|
| 533 |
stdout: str |
| 534 |
stderr: str |
| 535 |
command: T.List[str] |
| 536 |
returncode: int |
| 537 |
input_name: str |
| 538 |
output_name: T.Optional[str] = field(default=None, init=False) |
| 539 |
cached: bool = field(default=False, init=False) |
| 540 |
|
| 541 |
class Compiler(HoldableObject, metaclass=SimpleABC): |
| 542 |
|
| 543 |
# Libraries to ignore in find_library() since they are provided by the |
| 544 |
# compiler or the C library. Currently only used for MSVC. |
| 545 |
ignore_libs: T.List[str] = [] |
| 546 |
# Libraries that are internal compiler implementations, and must not be |
| 547 |
# manually searched. |
| 548 |
internal_libs: T.List[str] = [] |
| 549 |
|
| 550 |
LINKER_OPTION_STYLE: T.Optional[LinkerOptionStyle] = None |
| 551 |
|
| 552 |
# If the compiler is used to fire a separate linking step, environment |
| 553 |
# variables like CFLAGS have to be passed to the linking step as well. |
| 554 |
# They do not have to be passed if the linker is invoked directly (such |
| 555 |
# as for Visual Studio's LINK.EXE) or if the compilation and linking |
| 556 |
# steps are one and the same (such as for Rust). |
| 557 |
USED_FOR_SEPARATE_LINKING_STEP = True |
| 558 |
|
| 559 |
language: Language |
| 560 |
id: str |
| 561 |
warn_args: T.Dict[str, T.List[str]] |
| 562 |
mode = 'COMPILER' |
| 563 |
|
| 564 |
def __init__(self, ccache: T.List[str], exelist: T.List[str], version: str, |
| 565 |
for_machine: MachineChoice, environment: Environment, |
| 566 |
linker: T.Optional['DynamicLinker'] = None, |
| 567 |
full_version: T.Optional[str] = None): |
| 568 |
self.exelist = ccache + exelist |
| 569 |
self.exelist_no_ccache = exelist |
| 570 |
self.file_suffixes = lang_suffixes[self.language] |
| 571 |
self.can_compile_suffixes = set(self.file_suffixes) |
| 572 |
self.default_suffix = self.file_suffixes[0] |
| 573 |
self.version = version |
| 574 |
self.full_version = full_version |
| 575 |
self.for_machine = for_machine |
| 576 |
self.base_options: T.Set[OptionKey] = set() |
| 577 |
self.linker = linker |
| 578 |
self.environment = environment |
| 579 |
self.is_cross = environment.is_cross_build(for_machine) |
| 580 |
self.modes: T.List[Compiler] = [] |
| 581 |
|
| 582 |
@property |
| 583 |
def info(self) -> MachineInfo: |
| 584 |
# This must be fetched dynamically because it may be re-evaluated later, |
| 585 |
# and we could end up with a stale copy |
| 586 |
# see :class:`Interpreter._redetect_machines()` |
| 587 |
return self.environment.machines[self.for_machine] |
| 588 |
|
| 589 |
def init_from_options(self) -> None: |
| 590 |
"""Initializer compiler attributes that require options to be set.""" |
| 591 |
|
| 592 |
def __repr__(self) -> str: |
| 593 |
repr_str = "<{0}: v{1} `{2}`>" |
| 594 |
return repr_str.format(self.__class__.__name__, self.version, |
| 595 |
' '.join(self.exelist)) |
| 596 |
|
| 597 |
@lru_cache(maxsize=None) |
| 598 |
def can_compile(self, src: 'mesonlib.FileOrString') -> bool: |
| 599 |
if isinstance(src, mesonlib.File): |
| 600 |
src = src.fname |
| 601 |
suffix = os.path.splitext(src)[1] |
| 602 |
if suffix != '.C': |
| 603 |
suffix = suffix.lower() |
| 604 |
return bool(suffix) and suffix[1:] in self.can_compile_suffixes |
| 605 |
|
| 606 |
def get_id(self) -> str: |
| 607 |
return self.id |
| 608 |
|
| 609 |
def get_modes(self) -> T.List[Compiler]: |
| 610 |
return self.modes |
| 611 |
|
| 612 |
def get_exe(self) -> str: |
| 613 |
return self.exelist[0] |
| 614 |
|
| 615 |
def get_exe_args(self) -> T.List[str]: |
| 616 |
return self.exelist[1:] |
| 617 |
|
| 618 |
def get_linker_id(self) -> str: |
| 619 |
# There is not guarantee that we have a dynamic linker instance, as |
| 620 |
# some languages don't have separate linkers and compilers. In those |
| 621 |
# cases return the compiler id |
| 622 |
try: |
| 623 |
return self.linker.id |
| 624 |
except AttributeError: |
| 625 |
return self.id |
| 626 |
|
| 627 |
def get_version_string(self) -> str: |
| 628 |
details = [self.id, self.version] |
| 629 |
if self.full_version: |
| 630 |
details += ['"%s"' % (self.full_version)] |
| 631 |
return '(%s)' % (' '.join(details)) |
| 632 |
|
| 633 |
def get_language(self) -> Language: |
| 634 |
return self.language |
| 635 |
|
| 636 |
@classmethod |
| 637 |
def get_display_language(cls) -> str: |
| 638 |
return cls.language.capitalize() |
| 639 |
|
| 640 |
def get_default_suffix(self) -> str: |
| 641 |
return self.default_suffix |
| 642 |
|
| 643 |
def get_define(self, dname: str, prefix: str, |
| 644 |
extra_args: T.Union[T.List[str], T.Callable[[CompileCheckMode], T.List[str]]], |
| 645 |
dependencies: T.List['Dependency'], |
| 646 |
disable_cache: bool = False) -> T.Tuple[str, bool]: |
| 647 |
raise EnvironmentException('%s does not support get_define ' % self.get_id()) |
| 648 |
|
| 649 |
def compute_int(self, expression: str, low: T.Optional[int], high: T.Optional[int], |
| 650 |
guess: T.Optional[int], prefix: str, *, |
| 651 |
extra_args: T.Union[None, T.List[str], T.Callable[[CompileCheckMode], T.List[str]]], |
| 652 |
dependencies: T.Optional[T.List['Dependency']]) -> int: |
| 653 |
raise EnvironmentException('%s does not support compute_int ' % self.get_id()) |
| 654 |
|
| 655 |
def compute_parameters_with_absolute_paths(self, parameter_list: T.List[str], |
| 656 |
build_dir: str) -> T.List[str]: |
| 657 |
raise EnvironmentException('%s does not support compute_parameters_with_absolute_paths ' % self.get_id()) |
| 658 |
|
| 659 |
def has_members(self, typename: str, membernames: T.List[str], prefix: str, *, |
| 660 |
extra_args: T.Union[None, T.List[str], T.Callable[[CompileCheckMode], T.List[str]]] = None, |
| 661 |
dependencies: T.Optional[T.List['Dependency']] = None) -> T.Tuple[bool, bool]: |
| 662 |
raise EnvironmentException('%s does not support has_member(s) ' % self.get_id()) |
| 663 |
|
| 664 |
def has_type(self, typename: str, prefix: str, |
| 665 |
extra_args: T.Union[T.List[str], T.Callable[[CompileCheckMode], T.List[str]]], *, |
| 666 |
dependencies: T.Optional[T.List['Dependency']] = None) -> T.Tuple[bool, bool]: |
| 667 |
raise EnvironmentException('%s does not support has_type ' % self.get_id()) |
| 668 |
|
| 669 |
def symbols_have_underscore_prefix(self) -> bool: |
| 670 |
raise EnvironmentException('%s does not support symbols_have_underscore_prefix ' % self.get_id()) |
| 671 |
|
| 672 |
def get_exelist(self, ccache: bool = True) -> T.List[str]: |
| 673 |
return self.exelist.copy() if ccache else self.exelist_no_ccache.copy() |
| 674 |
|
| 675 |
def get_linker_exelist(self) -> T.List[str]: |
| 676 |
return self.linker.get_exelist() if self.linker else self.get_exelist() |
| 677 |
|
| 678 |
@abc.abstractmethod |
| 679 |
def get_output_args(self, outputname: str) -> T.List[str]: |
| 680 |
pass |
| 681 |
|
| 682 |
def get_linker_output_args(self, outputname: str) -> T.List[str]: |
| 683 |
return self.linker.get_output_args(outputname) |
| 684 |
|
| 685 |
def get_linker_search_args(self, dirname: str) -> T.List[str]: |
| 686 |
return self.linker.get_search_args(dirname) |
| 687 |
|
| 688 |
def get_builtin_define(self, define: str) -> T.Optional[str]: |
| 689 |
raise EnvironmentException('%s does not support get_builtin_define.' % self.id) |
| 690 |
|
| 691 |
def has_builtin_define(self, define: str) -> bool: |
| 692 |
raise EnvironmentException('%s does not support has_builtin_define.' % self.id) |
| 693 |
|
| 694 |
def get_always_args(self) -> T.List[str]: |
| 695 |
return [] |
| 696 |
|
| 697 |
def can_linker_accept_rsp(self) -> bool: |
| 698 |
""" |
| 699 |
Determines whether the linker can accept arguments using the @rsp syntax. |
| 700 |
""" |
| 701 |
return self.linker.get_accepts_rsp() |
| 702 |
|
| 703 |
def get_linker_always_args(self) -> T.List[str]: |
| 704 |
return self.linker.get_always_args() if self.linker else [] |
| 705 |
|
| 706 |
def get_linker_lib_prefix(self) -> str: |
| 707 |
return self.linker.get_lib_prefix() |
| 708 |
|
| 709 |
def gen_import_library_args(self, implibname: str) -> T.List[str]: |
| 710 |
""" |
| 711 |
Used only on Windows for libraries that need an import library. |
| 712 |
This currently means C, C++, Fortran. |
| 713 |
""" |
| 714 |
return [] |
| 715 |
|
| 716 |
def gen_export_dynamic_link_args(self) -> T.List[str]: |
| 717 |
raise MesonException('Language %s does not support export_dynamic.' % self.get_display_language()) |
| 718 |
|
| 719 |
def make_option_name(self, key: OptionKey) -> str: |
| 720 |
return f'{self.language}_{key.name}' |
| 721 |
|
| 722 |
def get_options(self) -> 'MutableKeyedOptionDictType': |
| 723 |
return {} |
| 724 |
|
| 725 |
def get_option_compile_args(self, target: 'BuildTarget', subproject: T.Optional[str] = None) -> T.List[str]: |
| 726 |
return [] |
| 727 |
|
| 728 |
def get_option_std_args(self, target: BuildTarget, subproject: T.Optional[str] = None) -> T.List[str]: |
| 729 |
return [] |
| 730 |
|
| 731 |
def get_option_link_args(self, target: 'BuildTarget', subproject: T.Optional[str] = None) -> T.List[str]: |
| 732 |
return self.linker.get_option_link_args(target, subproject) |
| 733 |
|
| 734 |
def check_header(self, hname: str, prefix: str, *, |
| 735 |
extra_args: T.Union[None, T.List[str], T.Callable[[CompileCheckMode], T.List[str]]] = None, |
| 736 |
dependencies: T.Optional[T.List['Dependency']] = None) -> T.Tuple[bool, bool]: |
| 737 |
"""Check that header is usable. |
| 738 |
|
| 739 |
Returns a two item tuple of bools. The first bool is whether the |
| 740 |
check succeeded, the second is whether the result was cached (True) |
| 741 |
or run fresh (False). |
| 742 |
""" |
| 743 |
raise EnvironmentException('Language %s does not support header checks.' % self.get_display_language()) |
| 744 |
|
| 745 |
def has_header(self, hname: str, prefix: str, *, |
| 746 |
extra_args: T.Union[None, T.List[str], T.Callable[[CompileCheckMode], T.List[str]]] = None, |
| 747 |
dependencies: T.Optional[T.List['Dependency']] = None, |
| 748 |
disable_cache: bool = False) -> T.Tuple[bool, bool]: |
| 749 |
"""Check that header is exists. |
| 750 |
|
| 751 |
This check will return true if the file exists, even if it contains: |
| 752 |
|
| 753 |
```c |
| 754 |
# error "You thought you could use this, LOLZ!" |
| 755 |
``` |
| 756 |
|
| 757 |
Use check_header if your header only works in some cases. |
| 758 |
|
| 759 |
Returns a two item tuple of bools. The first bool is whether the |
| 760 |
check succeeded, the second is whether the result was cached (True) |
| 761 |
or run fresh (False). |
| 762 |
""" |
| 763 |
raise EnvironmentException('Language %s does not support header checks.' % self.get_display_language()) |
| 764 |
|
| 765 |
def has_header_symbol(self, hname: str, symbol: str, prefix: str, *, |
| 766 |
extra_args: T.Union[None, T.List[str], T.Callable[[CompileCheckMode], T.List[str]]] = None, |
| 767 |
dependencies: T.Optional[T.List['Dependency']] = None) -> T.Tuple[bool, bool]: |
| 768 |
raise EnvironmentException('Language %s does not support header symbol checks.' % self.get_display_language()) |
| 769 |
|
| 770 |
def run(self, code: 'mesonlib.FileOrString', |
| 771 |
extra_args: T.Union[T.List[str], T.Callable[[CompileCheckMode], T.List[str]], None] = None, |
| 772 |
dependencies: T.Optional[T.List['Dependency']] = None, |
| 773 |
run_env: T.Optional[T.Dict[str, str]] = None, |
| 774 |
run_cwd: T.Optional[str] = None) -> RunResult: |
| 775 |
need_exe_wrapper = self.environment.need_exe_wrapper(self.for_machine) |
| 776 |
if need_exe_wrapper and not self.environment.has_exe_wrapper(): |
| 777 |
raise CrossNoRunException('Can not run test applications in this cross environment.') |
| 778 |
with self._build_wrapper(code, extra_args, dependencies, mode=CompileCheckMode.LINK, want_output=True) as p: |
| 779 |
if p.returncode != 0: |
| 780 |
mlog.debug(f'Could not compile test file {p.input_name}: {p.returncode}\n') |
| 781 |
return RunResult(False) |
| 782 |
if need_exe_wrapper: |
| 783 |
cmdlist = self.environment.exe_wrapper.get_command() + [p.output_name] |
| 784 |
else: |
| 785 |
cmdlist = [p.output_name] |
| 786 |
try: |
| 787 |
pe, so, se = mesonlib.Popen_safe(cmdlist, env=run_env, cwd=run_cwd) |
| 788 |
except Exception as e: |
| 789 |
mlog.debug(f'Could not run: {cmdlist} (error: {e})\n') |
| 790 |
return RunResult(False) |
| 791 |
|
| 792 |
mlog.debug('Program stdout:\n') |
| 793 |
mlog.debug(so) |
| 794 |
mlog.debug('Program stderr:\n') |
| 795 |
mlog.debug(se) |
| 796 |
return RunResult(True, pe.returncode, so, se) |
| 797 |
|
| 798 |
# Caching run() in general seems too risky (no way to know what the program |
| 799 |
# depends on), but some callers know more about the programs they intend to |
| 800 |
# run. |
| 801 |
# For now we just accept code as a string, as that's what internal callers |
| 802 |
# need anyway. If we wanted to accept files, the cache key would need to |
| 803 |
# include mtime. |
| 804 |
def cached_run(self, code: str, *, |
| 805 |
extra_args: T.Union[T.List[str], T.Callable[[CompileCheckMode], T.List[str]], None] = None, |
| 806 |
dependencies: T.Optional[T.List['Dependency']] = None) -> RunResult: |
| 807 |
run_check_cache = self.environment.coredata.run_check_cache |
| 808 |
args = self.build_wrapper_args(extra_args, dependencies, CompileCheckMode('link')) |
| 809 |
key = (code, tuple(args)) |
| 810 |
if key in run_check_cache: |
| 811 |
p = run_check_cache[key] |
| 812 |
p.cached = True |
| 813 |
mlog.debug('Using cached run result:') |
| 814 |
mlog.debug('Code:\n', code) |
| 815 |
mlog.debug('Args:\n', extra_args) |
| 816 |
mlog.debug('Cached run returncode:\n', p.returncode) |
| 817 |
mlog.debug('Cached run stdout:\n', p.stdout) |
| 818 |
mlog.debug('Cached run stderr:\n', p.stderr) |
| 819 |
else: |
| 820 |
p = self.run(code, extra_args=extra_args, dependencies=dependencies) |
| 821 |
run_check_cache[key] = p |
| 822 |
return p |
| 823 |
|
| 824 |
def sizeof(self, typename: str, prefix: str, *, |
| 825 |
extra_args: T.Union[None, T.List[str], T.Callable[[CompileCheckMode], T.List[str]]] = None, |
| 826 |
dependencies: T.Optional[T.List['Dependency']] = None) -> T.Tuple[int, bool]: |
| 827 |
raise EnvironmentException('Language %s does not support sizeof checks.' % self.get_display_language()) |
| 828 |
|
| 829 |
def alignment(self, typename: str, prefix: str, *, |
| 830 |
extra_args: T.Optional[T.List[str]] = None, |
| 831 |
dependencies: T.Optional[T.List['Dependency']] = None) -> T.Tuple[int, bool]: |
| 832 |
raise EnvironmentException('Language %s does not support alignment checks.' % self.get_display_language()) |
| 833 |
|
| 834 |
def has_function(self, funcname: str, prefix: str, *, |
| 835 |
extra_args: T.Optional[T.List[str]] = None, |
| 836 |
dependencies: T.Optional[T.List['Dependency']] = None) -> T.Tuple[bool, bool]: |
| 837 |
"""See if a function exists. |
| 838 |
|
| 839 |
Returns a two item tuple of bools. The first bool is whether the |
| 840 |
check succeeded, the second is whether the result was cached (True) |
| 841 |
or run fresh (False). |
| 842 |
""" |
| 843 |
raise EnvironmentException('Language %s does not support function checks.' % self.get_display_language()) |
| 844 |
|
| 845 |
@classmethod |
| 846 |
def _unix_args_to_native(cls, args: T.List[str], info: MachineInfo) -> T.List[str]: |
| 847 |
"Always returns a copy that can be independently mutated" |
| 848 |
return args.copy() |
| 849 |
|
| 850 |
def unix_args_to_native(self, args: T.List[str]) -> T.List[str]: |
| 851 |
return self._unix_args_to_native(args, self.info) |
| 852 |
|
| 853 |
@classmethod |
| 854 |
def native_args_to_unix(cls, args: T.List[str]) -> T.List[str]: |
| 855 |
"Always returns a copy that can be independently mutated" |
| 856 |
return args.copy() |
| 857 |
|
| 858 |
def find_library(self, libname: str, extra_dirs: T.List[str], libtype: LibType = LibType.PREFER_SHARED, |
| 859 |
lib_prefix_warning: bool = True, ignore_system_dirs: bool = False, |
| 860 |
skip_link_check: bool = False) -> T.Optional[T.List[str]]: |
| 861 |
raise EnvironmentException(f'Language {self.get_display_language()} does not support library finding.') |
| 862 |
|
| 863 |
def get_library_naming(self, libtype: LibType, strict: bool = False) -> T.Optional[T.Tuple[str, ...]]: |
| 864 |
raise EnvironmentException( |
| 865 |
'Language {} does not support get_library_naming.'.format( |
| 866 |
self.get_display_language())) |
| 867 |
|
| 868 |
def get_program_dirs(self) -> T.List[str]: |
| 869 |
return [] |
| 870 |
|
| 871 |
def has_multi_arguments(self, args: T.List[str]) -> T.Tuple[bool, bool]: |
| 872 |
"""Checks if the compiler has all of the arguments. |
| 873 |
|
| 874 |
:returns: |
| 875 |
A tuple of (bool, bool). The first value is whether the check |
| 876 |
succeeded, and the second is whether it was retrieved from a cache |
| 877 |
""" |
| 878 |
raise EnvironmentException( |
| 879 |
'Language {} does not support has_multi_arguments.'.format( |
| 880 |
self.get_display_language())) |
| 881 |
|
| 882 |
def has_multi_link_arguments(self, args: T.List[str], to_host_args: bool = True) -> T.Tuple[bool, bool]: |
| 883 |
"""Checks if the linker has all of the arguments. |
| 884 |
|
| 885 |
to_host_args is False if the arguments were returned by this same Compiler object. |
| 886 |
|
| 887 |
:returns: |
| 888 |
A tuple of (bool, bool). The first value is whether the check |
| 889 |
succeeded, and the second is whether it was retrieved from a cache |
| 890 |
""" |
| 891 |
return self.linker.has_multi_arguments(args) |
| 892 |
|
| 893 |
def _get_compile_output(self, dirname: str, mode: CompileCheckMode) -> str: |
| 894 |
assert mode != CompileCheckMode.PREPROCESS, 'In pre-processor mode, the output is sent to stdout and discarded' |
| 895 |
# Extension only matters if running results; '.exe' is |
| 896 |
# guaranteed to be executable on every platform. |
| 897 |
if mode == CompileCheckMode.LINK: |
| 898 |
suffix = 'exe' |
| 899 |
else: |
| 900 |
suffix = 'obj' |
| 901 |
return os.path.join(dirname, 'output.' + suffix) |
| 902 |
|
| 903 |
def get_compiler_args_for_mode(self, mode: CompileCheckMode) -> T.List[str]: |
| 904 |
args: T.List[str] = [] |
| 905 |
args += self.get_always_args() |
| 906 |
if mode is CompileCheckMode.COMPILE: |
| 907 |
args += self.get_compile_only_args() |
| 908 |
elif mode is CompileCheckMode.PREPROCESS: |
| 909 |
args += self.get_preprocess_only_args() |
| 910 |
else: |
| 911 |
assert mode is CompileCheckMode.LINK |
| 912 |
return args |
| 913 |
|
| 914 |
def compiler_args(self, args: T.Optional[T.Iterable[str]] = None) -> CompilerArgs: |
| 915 |
"""Return an appropriate CompilerArgs instance for this class.""" |
| 916 |
return CompilerArgs(self, args) |
| 917 |
|
| 918 |
@contextlib.contextmanager |
| 919 |
def compile(self, code: 'mesonlib.FileOrString', |
| 920 |
extra_args: T.Union[None, CompilerArgs, T.List[str]] = None, |
| 921 |
*, mode: CompileCheckMode = CompileCheckMode.LINK, want_output: bool = False, |
| 922 |
temp_dir: T.Optional[str] = None) -> T.Iterator[CompileResult]: |
| 923 |
# TODO: there isn't really any reason for this to be a contextmanager |
| 924 |
|
| 925 |
if mode == CompileCheckMode.PREPROCESS: |
| 926 |
assert not want_output, 'In pre-processor mode, the output is sent to stdout and discarded' |
| 927 |
|
| 928 |
if extra_args is None: |
| 929 |
extra_args = [] |
| 930 |
|
| 931 |
with TemporaryDirectoryWinProof(dir=temp_dir if temp_dir else None) as tmpdirname: |
| 932 |
no_ccache = False |
| 933 |
if isinstance(code, str): |
| 934 |
srcname = os.path.join(tmpdirname, |
| 935 |
'testfile.' + self.default_suffix) |
| 936 |
with open(srcname, 'w', encoding='utf-8') as ofile: |
| 937 |
ofile.write(code) |
| 938 |
if not code.endswith('\n'): |
| 939 |
ofile.write('\n') |
| 940 |
# ccache would result in a cache miss |
| 941 |
no_ccache = True |
| 942 |
code_debug = f'Code:\n{code}' |
| 943 |
else: |
| 944 |
srcname = code.fname |
| 945 |
code_debug = f'Source file: {srcname}' |
| 946 |
|
| 947 |
compiler_id = self.get_id() |
| 948 |
suffixes = compiler_suffixes.get(compiler_id) |
| 949 |
if suffixes: |
| 950 |
suffix = os.path.splitext(srcname)[1] |
| 951 |
if suffix and suffix[1:] not in suffixes: |
| 952 |
err = f'Unrecognized filename suffix for "{srcname}", will be ignored by {compiler_id}' |
| 953 |
mlog.error(err) |
| 954 |
yield CompileResult('', err, [], 1, srcname) |
| 955 |
return |
| 956 |
|
| 957 |
# Construct the compiler command-line |
| 958 |
commands = self.compiler_args() |
| 959 |
commands.append(srcname) |
| 960 |
|
| 961 |
# Preprocess mode outputs to stdout, so no output args |
| 962 |
if mode != CompileCheckMode.PREPROCESS: |
| 963 |
output = self._get_compile_output(tmpdirname, mode) |
| 964 |
commands += self.get_output_args(output) |
| 965 |
commands.extend(self.get_compiler_args_for_mode(CompileCheckMode(mode))) |
| 966 |
|
| 967 |
# extra_args must be last because it could contain '/link' to |
| 968 |
# pass args to VisualStudio's linker. In that case everything |
| 969 |
# in the command line after '/link' is given to the linker. |
| 970 |
if extra_args: |
| 971 |
commands += extra_args |
| 972 |
# Generate full command-line with the exelist |
| 973 |
command_list = self.get_exelist(ccache=not no_ccache) + commands.to_native() |
| 974 |
mlog.debug('Running compile:') |
| 975 |
mlog.debug('Working directory: ', tmpdirname) |
| 976 |
mlog.debug(code_debug) |
| 977 |
os_env = os.environ.copy() |
| 978 |
os_env['LC_ALL'] = 'C' |
| 979 |
if no_ccache: |
| 980 |
os_env['CCACHE_DISABLE'] = '1' |
| 981 |
p, stdo, stde = Popen_safe_logged(command_list, msg='Command line', cwd=tmpdirname, env=os_env) |
| 982 |
|
| 983 |
result = CompileResult(stdo, stde, command_list, p.returncode, input_name=srcname) |
| 984 |
if want_output: |
| 985 |
result.output_name = output |
| 986 |
yield result |
| 987 |
|
| 988 |
@contextlib.contextmanager |
| 989 |
def cached_compile(self, code: 'mesonlib.FileOrString', *, |
| 990 |
extra_args: T.Union[None, T.List[str], CompilerArgs] = None, |
| 991 |
mode: CompileCheckMode = CompileCheckMode.LINK, |
| 992 |
temp_dir: T.Optional[str] = None) -> T.Iterator[CompileResult]: |
| 993 |
# TODO: There's isn't really any reason for this to be a context manager |
| 994 |
|
| 995 |
# Calculate the key |
| 996 |
textra_args: T.Tuple[str, ...] = tuple(extra_args) if extra_args is not None else tuple() |
| 997 |
key: coredata.CompilerCheckCacheKey = (tuple(self.exelist), self.version, code, textra_args, mode) |
| 998 |
|
| 999 |
# Check if not cached, and generate, otherwise get from the cache |
| 1000 |
cache = self.environment.coredata.compiler_check_cache |
| 1001 |
if key in cache: |
| 1002 |
p = cache[key] |
| 1003 |
p.cached = True |
| 1004 |
mlog.debug('Using cached compile:') |
| 1005 |
mlog.debug('Cached command line: ', ' '.join(p.command), '\n') |
| 1006 |
mlog.debug('Code:\n', code) |
| 1007 |
mlog.debug('Cached compiler stdout:\n', p.stdout) |
| 1008 |
mlog.debug('Cached compiler stderr:\n', p.stderr) |
| 1009 |
yield p |
| 1010 |
else: |
| 1011 |
with self.compile(code, extra_args=extra_args, mode=mode, want_output=False, temp_dir=temp_dir) as p: |
| 1012 |
cache[key] = p |
| 1013 |
yield p |
| 1014 |
|
| 1015 |
def get_colorout_args(self, colortype: str) -> T.List[str]: |
| 1016 |
# TODO: colortype can probably be an emum |
| 1017 |
return [] |
| 1018 |
|
| 1019 |
# Some compilers (msvc) write debug info to a separate file. |
| 1020 |
# These args specify where it should be written. |
| 1021 |
def get_compile_debugfile_args(self, rel_obj: str, pch: bool = False) -> T.List[str]: |
| 1022 |
return [] |
| 1023 |
|
| 1024 |
def should_link_pch_object(self) -> bool: |
| 1025 |
return False |
| 1026 |
|
| 1027 |
def get_link_debugfile_name(self, targetfile: str) -> T.Optional[str]: |
| 1028 |
return self.linker.get_debugfile_name(targetfile) |
| 1029 |
|
| 1030 |
def get_link_debugfile_args(self, targetfile: str) -> T.List[str]: |
| 1031 |
return self.linker.get_debugfile_args(targetfile) |
| 1032 |
|
| 1033 |
def get_std_link_args(self, env: Environment, is_thin: bool) -> T.List[str]: |
| 1034 |
raise MesonBugException("get_std_link_args() not implemented; if needs_static_linker() is False it needs to be") |
| 1035 |
|
| 1036 |
def get_std_shared_lib_link_args(self) -> T.List[str]: |
| 1037 |
return self.linker.get_std_shared_lib_args() |
| 1038 |
|
| 1039 |
def get_std_shared_module_link_args(self, target: 'BuildTarget') -> T.List[str]: |
| 1040 |
return self.linker.get_std_shared_module_args(target) |
| 1041 |
|
| 1042 |
def get_link_whole_for(self, args: T.List[str]) -> T.List[str]: |
| 1043 |
return self.linker.get_link_whole_for(args) |
| 1044 |
|
| 1045 |
def get_allow_undefined_link_args(self) -> T.List[str]: |
| 1046 |
return self.linker.get_allow_undefined_args() |
| 1047 |
|
| 1048 |
def no_undefined_link_args(self) -> T.List[str]: |
| 1049 |
return self.linker.no_undefined_args() |
| 1050 |
|
| 1051 |
def get_instruction_set_args(self, instruction_set: str) -> T.Optional[T.List[str]]: |
| 1052 |
"""Compiler arguments needed to enable the given instruction set. |
| 1053 |
|
| 1054 |
Return type ay be an empty list meaning nothing needed or None |
| 1055 |
meaning the given set is not supported. |
| 1056 |
""" |
| 1057 |
return None |
| 1058 |
|
| 1059 |
def build_rpath_args(self, build_dir: str, from_dir: str, target: BuildTarget, |
| 1060 |
extra_paths: T.Optional[T.List[str]] = None |
| 1061 |
) -> T.Tuple[T.List[str], T.Set[bytes]]: |
| 1062 |
return self.linker.build_rpath_args(build_dir, from_dir, target, extra_paths) |
| 1063 |
|
| 1064 |
def get_archive_name(self, filename: str) -> str: |
| 1065 |
return self.linker.get_archive_name(filename) |
| 1066 |
|
| 1067 |
def get_command_to_archive_shlib(self) -> T.List[str]: |
| 1068 |
if not self.linker: |
| 1069 |
return [] |
| 1070 |
return self.linker.get_command_to_archive_shlib() |
| 1071 |
|
| 1072 |
def thread_flags(self) -> T.List[str]: |
| 1073 |
return [] |
| 1074 |
|
| 1075 |
def thread_link_flags(self) -> T.List[str]: |
| 1076 |
return self.linker.thread_flags() |
| 1077 |
|
| 1078 |
def openmp_flags(self) -> T.List[str]: |
| 1079 |
raise EnvironmentException('Language %s does not support OpenMP flags.' % self.get_display_language()) |
| 1080 |
|
| 1081 |
def openmp_link_flags(self) -> T.List[str]: |
| 1082 |
return self.openmp_flags() |
| 1083 |
|
| 1084 |
def language_stdlib_only_link_flags(self) -> T.List[str]: |
| 1085 |
return [] |
| 1086 |
|
| 1087 |
def gnu_symbol_visibility_args(self, vistype: str) -> T.List[str]: |
| 1088 |
return [] |
| 1089 |
|
| 1090 |
def get_win_subsystem_args(self, value: str) -> T.List[str]: |
| 1091 |
# By default the dynamic linker is going to return an empty |
| 1092 |
# array in case it either doesn't support Windows subsystems |
| 1093 |
# or does not target Windows |
| 1094 |
return self.linker.get_win_subsystem_args(value) |
| 1095 |
|
| 1096 |
def has_func_attribute(self, name: str) -> T.Tuple[bool, bool]: |
| 1097 |
raise EnvironmentException( |
| 1098 |
f'Language {self.get_display_language()} does not support function attributes.') |
| 1099 |
|
| 1100 |
def get_pic_args(self) -> T.List[str]: |
| 1101 |
m = 'Language {} does not support position-independent code' |
| 1102 |
raise EnvironmentException(m.format(self.get_display_language())) |
| 1103 |
|
| 1104 |
def get_pie_args(self) -> T.List[str]: |
| 1105 |
m = 'Language {} does not support position-independent executable' |
| 1106 |
raise EnvironmentException(m.format(self.get_display_language())) |
| 1107 |
|
| 1108 |
def get_pie_link_args(self) -> T.List[str]: |
| 1109 |
return self.linker.get_pie_args() |
| 1110 |
|
| 1111 |
@staticmethod |
| 1112 |
def get_argument_syntax() -> str: |
| 1113 |
"""Returns the argument family type. |
| 1114 |
|
| 1115 |
Compilers fall into families if they try to emulate the command line |
| 1116 |
interface of another compiler. For example, clang is in the GCC family |
| 1117 |
since it accepts most of the same arguments as GCC. ICL (ICC on |
| 1118 |
windows) is in the MSVC family since it accepts most of the same |
| 1119 |
arguments as MSVC. |
| 1120 |
""" |
| 1121 |
return 'other' |
| 1122 |
|
| 1123 |
def get_profile_generate_args(self) -> T.List[str]: |
| 1124 |
raise EnvironmentException( |
| 1125 |
'%s does not support get_profile_generate_args ' % self.get_id()) |
| 1126 |
|
| 1127 |
def get_profile_use_args(self) -> T.List[str]: |
| 1128 |
raise EnvironmentException( |
| 1129 |
'%s does not support get_profile_use_args ' % self.get_id()) |
| 1130 |
|
| 1131 |
def remove_linkerlike_args(self, args: T.List[str]) -> T.List[str]: |
| 1132 |
rm_exact = ('-headerpad_max_install_names',) |
| 1133 |
rm_prefixes = ('-Wl,', '-L',) |
| 1134 |
rm_next = ('-L', '-framework',) |
| 1135 |
ret: T.List[str] = [] |
| 1136 |
iargs = iter(args) |
| 1137 |
for arg in iargs: |
| 1138 |
# Remove this argument |
| 1139 |
if arg in rm_exact: |
| 1140 |
continue |
| 1141 |
# If the argument starts with this, but is not *exactly* this |
| 1142 |
# f.ex., '-L' should match ['-Lfoo'] but not ['-L', 'foo'] |
| 1143 |
if arg.startswith(rm_prefixes) and arg not in rm_prefixes: |
| 1144 |
continue |
| 1145 |
# Ignore this argument and the one after it |
| 1146 |
if arg in rm_next: |
| 1147 |
next(iargs) |
| 1148 |
continue |
| 1149 |
ret.append(arg) |
| 1150 |
return ret |
| 1151 |
|
| 1152 |
def get_embed_bitcode_args(self, bitcode: bool, lto: bool) -> T.List[str]: |
| 1153 |
return [] |
| 1154 |
|
| 1155 |
def get_lto_compile_args(self, *, target: T.Optional[BuildTarget] = None, threads: int = 0, |
| 1156 |
mode: str = 'default') -> T.List[str]: |
| 1157 |
return [] |
| 1158 |
|
| 1159 |
def get_lto_link_args(self, *, target: T.Optional[BuildTarget] = None, threads: int = 0, |
| 1160 |
mode: str = 'default', thinlto_cache_dir: T.Optional[str] = None) -> T.List[str]: |
| 1161 |
return self.linker.get_lto_args() |
| 1162 |
|
| 1163 |
def get_lto_obj_cache_path(self, path: str) -> T.List[str]: |
| 1164 |
return self.linker.get_lto_obj_cache_path(path) |
| 1165 |
|
| 1166 |
def sanitizer_compile_args(self, target: T.Optional[BuildTarget], value: T.List[str]) -> T.List[str]: |
| 1167 |
return [] |
| 1168 |
|
| 1169 |
def sanitizer_link_args(self, target: T.Optional[BuildTarget], value: T.List[str]) -> T.List[str]: |
| 1170 |
return self.linker.sanitizer_args(value) |
| 1171 |
|
| 1172 |
def get_asneeded_args(self) -> T.List[str]: |
| 1173 |
return self.linker.get_asneeded_args() |
| 1174 |
|
| 1175 |
def headerpad_args(self) -> T.List[str]: |
| 1176 |
return self.linker.headerpad_args() |
| 1177 |
|
| 1178 |
def bitcode_args(self) -> T.List[str]: |
| 1179 |
return self.linker.bitcode_args() |
| 1180 |
|
| 1181 |
def get_optimization_link_args(self, optimization_level: str) -> T.List[str]: |
| 1182 |
return self.linker.get_optimization_link_args(optimization_level) |
| 1183 |
|
| 1184 |
def get_linker_fatal_warnings(self) -> T.List[str]: |
| 1185 |
return self.linker.fatal_warnings() |
| 1186 |
|
| 1187 |
def get_soname_args(self, prefix: str, shlib_name: str, suffix: str, soversion: str, |
| 1188 |
darwin_versions: T.Tuple[str, str]) -> T.List[str]: |
| 1189 |
return self.linker.get_soname_args( |
| 1190 |
prefix, shlib_name, suffix, soversion, |
| 1191 |
darwin_versions) |
| 1192 |
|
| 1193 |
def get_build_link_args(self, target: BuildTarget, build: build.Build) -> T.List[str]: |
| 1194 |
# Link args added using add_global_link_arguments() override |
| 1195 |
# per-project link arguments. Link args added from the env (LDFLAGS) |
| 1196 |
# override all the defaults but not the per-target link args. |
| 1197 |
return build.get_project_link_args(self, target) \ |
| 1198 |
+ build.get_global_link_args(self, target) \ |
| 1199 |
+ self.environment.coredata.get_external_link_args(self.for_machine, self.get_language()) |
| 1200 |
|
| 1201 |
def get_target_link_args(self, target: 'BuildTarget') -> T.List[str]: |
| 1202 |
return target.link_args |
| 1203 |
|
| 1204 |
def get_target_link_early_args(self, target: 'BuildTarget') -> T.List[str]: |
| 1205 |
return target.link_early_args |
| 1206 |
|
| 1207 |
def get_dependency_compile_args(self, dep: 'Dependency') -> T.List[str]: |
| 1208 |
return dep.get_compile_args() |
| 1209 |
|
| 1210 |
def get_dependency_link_args(self, dep: 'Dependency') -> T.List[str]: |
| 1211 |
return dep.get_link_args(self.get_language()) |
| 1212 |
|
| 1213 |
@classmethod |
| 1214 |
def use_linker_args(cls, linker: str, version: str) -> T.List[str]: |
| 1215 |
"""Get a list of arguments to pass to the compiler to set the linker. |
| 1216 |
""" |
| 1217 |
return [] |
| 1218 |
|
| 1219 |
def get_coverage_args(self) -> T.List[str]: |
| 1220 |
return [] |
| 1221 |
|
| 1222 |
def get_coverage_link_args(self) -> T.List[str]: |
| 1223 |
return self.linker.get_coverage_args() |
| 1224 |
|
| 1225 |
def gen_vs_module_defs_args(self, defsfile: str) -> T.List[str]: |
| 1226 |
return self.linker.gen_vs_module_defs_args(defsfile) |
| 1227 |
|
| 1228 |
def get_assert_args(self, disable: bool) -> T.List[str]: |
| 1229 |
"""Get arguments to enable or disable assertion. |
| 1230 |
|
| 1231 |
:param disable: Whether to disable assertions |
| 1232 |
:return: A list of string arguments for this compiler |
| 1233 |
""" |
| 1234 |
return [] |
| 1235 |
|
| 1236 |
def get_crt_val(self, crt_val: str) -> str: |
| 1237 |
if crt_val in options.MSCRT_VALS: |
| 1238 |
return crt_val |
| 1239 |
assert crt_val in {'from_buildtype', 'static_from_buildtype'} |
| 1240 |
|
| 1241 |
dbg = 'mdd' |
| 1242 |
rel = 'md' |
| 1243 |
if crt_val == 'static_from_buildtype': |
| 1244 |
dbg = 'mtd' |
| 1245 |
rel = 'mt' |
| 1246 |
|
| 1247 |
# Match what build type flags used to do. |
| 1248 |
buildtype = self.environment.coredata.optstore.get_value_for('buildtype') |
| 1249 |
assert isinstance(buildtype, str), 'for mypy' |
| 1250 |
if buildtype == 'plain': |
| 1251 |
return 'none' |
| 1252 |
elif buildtype == 'debug': |
| 1253 |
return dbg |
| 1254 |
elif buildtype in {'debugoptimized', 'release', 'minsize'}: |
| 1255 |
return rel |
| 1256 |
else: |
| 1257 |
assert buildtype == 'custom' |
| 1258 |
raise EnvironmentException('Requested C runtime based on buildtype, but buildtype is "custom".') |
| 1259 |
|
| 1260 |
def get_crt_compile_args(self, crt_val: str) -> T.List[str]: |
| 1261 |
raise EnvironmentException('This compiler does not support Windows CRT selection') |
| 1262 |
|
| 1263 |
def get_crt_link_args(self, crt_val: str) -> T.List[str]: |
| 1264 |
raise EnvironmentException('This compiler does not support Windows CRT selection') |
| 1265 |
|
| 1266 |
def get_compile_only_args(self) -> T.List[str]: |
| 1267 |
return [] |
| 1268 |
|
| 1269 |
def get_preprocess_only_args(self) -> T.List[str]: |
| 1270 |
raise EnvironmentException('This compiler does not have a preprocessor') |
| 1271 |
|
| 1272 |
def get_preprocess_to_file_args(self) -> T.List[str]: |
| 1273 |
return self.get_preprocess_only_args() |
| 1274 |
|
| 1275 |
def get_default_include_dirs(self) -> T.List[str]: |
| 1276 |
# TODO: This is a candidate for returning an immutable list |
| 1277 |
return [] |
| 1278 |
|
| 1279 |
def get_largefile_args(self) -> T.List[str]: |
| 1280 |
'''Enable transparent large-file-support for 32-bit UNIX systems''' |
| 1281 |
if not (self.get_argument_syntax() == 'msvc' or self.info.is_darwin()): |
| 1282 |
# Enable large-file support unconditionally on all platforms other |
| 1283 |
# than macOS and MSVC. macOS is now 64-bit-only so it doesn't |
| 1284 |
# need anything special, and MSVC doesn't have automatic LFS. |
| 1285 |
# You must use the 64-bit counterparts explicitly. |
| 1286 |
# glibc, musl, and uclibc, and all BSD libcs support this. On Android, |
| 1287 |
# support for transparent LFS is available depending on the version of |
| 1288 |
# Bionic: https://github.com/android/platform_bionic#32-bit-abi-bugs |
| 1289 |
# https://code.google.com/p/android/issues/detail?id=64613 |
| 1290 |
# |
| 1291 |
# If this breaks your code, fix it! It's been 20+ years! |
| 1292 |
return ['-D_FILE_OFFSET_BITS=64'] |
| 1293 |
# We don't enable -D_LARGEFILE64_SOURCE since that enables |
| 1294 |
# transitionary features and must be enabled by programs that use |
| 1295 |
# those features explicitly. |
| 1296 |
return [] |
| 1297 |
|
| 1298 |
def get_library_dirs(self, elf_class: T.Optional[int] = None) -> T.List[str]: |
| 1299 |
return [] |
| 1300 |
|
| 1301 |
def get_return_value(self, |
| 1302 |
fname: str, |
| 1303 |
rtype: str, |
| 1304 |
prefix: str, |
| 1305 |
extra_args: T.Optional[T.List[str]], |
| 1306 |
dependencies: T.Optional[T.List['Dependency']]) -> T.Union[str, int]: |
| 1307 |
raise EnvironmentException(f'{self.id} does not support get_return_value') |
| 1308 |
|
| 1309 |
def find_framework(self, |
| 1310 |
name: str, |
| 1311 |
extra_dirs: T.List[str], |
| 1312 |
allow_system: bool = True) -> T.Optional[T.List[str]]: |
| 1313 |
raise EnvironmentException(f'{self.id} does not support find_framework') |
| 1314 |
|
| 1315 |
def find_framework_paths(self) -> T.List[str]: |
| 1316 |
raise EnvironmentException(f'{self.id} does not support find_framework_paths') |
| 1317 |
|
| 1318 |
def attribute_check_func(self, name: str) -> str: |
| 1319 |
raise EnvironmentException(f'{self.id} does not support attribute checks') |
| 1320 |
|
| 1321 |
def get_pch_suffix(self) -> str: |
| 1322 |
raise EnvironmentException(f'{self.id} does not support pre compiled headers') |
| 1323 |
|
| 1324 |
def get_pch_name(self, name: str) -> str: |
| 1325 |
raise EnvironmentException(f'{self.id} does not support pre compiled headers') |
| 1326 |
|
| 1327 |
def get_pch_use_args(self, pch_dir: str, header: str) -> T.List[str]: |
| 1328 |
raise EnvironmentException(f'{self.id} does not support pre compiled headers') |
| 1329 |
|
| 1330 |
def get_has_func_attribute_extra_args(self, name: str) -> T.List[str]: |
| 1331 |
raise EnvironmentException(f'{self.id} does not support function attributes') |
| 1332 |
|
| 1333 |
def name_string(self) -> str: |
| 1334 |
return ' '.join(self.exelist) |
| 1335 |
|
| 1336 |
def sanity_check(self, work_dir: str) -> None: |
| 1337 |
"""Check that this compiler actually works. |
| 1338 |
|
| 1339 |
This should provide a simple compile/link test. Something as simple as: |
| 1340 |
```python |
| 1341 |
main(): return 0 |
| 1342 |
``` |
| 1343 |
is good enough here. |
| 1344 |
|
| 1345 |
:param work_dir: A directory to put temporary artifacts |
| 1346 |
:raises mesonlib.EnvironmentException: If building the binary fails |
| 1347 |
:raises mesonlib.EnvironmentException: If running the binary is attempted and fails |
| 1348 |
""" |
| 1349 |
sourcename, transpiled, binname = self._sanity_check_filenames() |
| 1350 |
|
| 1351 |
with open(os.path.join(work_dir, sourcename), 'w', encoding='utf-8') as f: |
| 1352 |
f.write(self._sanity_check_source_code()) |
| 1353 |
|
| 1354 |
if transpiled: |
| 1355 |
cmdlist, linker_args = self._sanity_check_compile_args(sourcename, transpiled) |
| 1356 |
cmdlist.extend(linker_args) |
| 1357 |
pc, stdo, stde = mesonlib.Popen_safe(cmdlist, cwd=work_dir) |
| 1358 |
mlog.debug('Sanity check transpiler command line:', mesonlib.join_args(cmdlist)) |
| 1359 |
mlog.debug('Sanity check transpiler stdout:') |
| 1360 |
mlog.debug(stdo) |
| 1361 |
mlog.debug('-----\nSanity check transpiler stderr:') |
| 1362 |
mlog.debug(stde) |
| 1363 |
mlog.debug('-----') |
| 1364 |
if pc.returncode != 0: |
| 1365 |
raise mesonlib.EnvironmentException(f'Compiler {self.name_string()} cannot transpile programs.') |
| 1366 |
|
| 1367 |
comp_lang = SUFFIX_TO_LANG[transpiled.rsplit('.', maxsplit=1)[1]] |
| 1368 |
comp = self.environment.coredata.compilers[self.for_machine].get(comp_lang) |
| 1369 |
if not comp: |
| 1370 |
raise mesonlib.MesonBugException(f'Need a {comp_lang} compiler for {self.language} compiler test, but one doesnt exist') |
| 1371 |
|
| 1372 |
cmdlist, linker_args = self._transpiled_sanity_check_compile_args(comp, transpiled, binname) |
| 1373 |
|
| 1374 |
mlog.debug('checking compilation of transpiled source:') |
| 1375 |
else: |
| 1376 |
cmdlist, linker_args = self._sanity_check_compile_args(sourcename, binname) |
| 1377 |
|
| 1378 |
cmdlist.extend(linker_args) |
| 1379 |
pc, stdo, stde = mesonlib.Popen_safe(cmdlist, cwd=work_dir) |
| 1380 |
mlog.debug('Sanity check compiler command line:', mesonlib.join_args(cmdlist)) |
| 1381 |
mlog.debug('Sanity check compile stdout:') |
| 1382 |
mlog.debug(stdo) |
| 1383 |
mlog.debug('-----\nSanity check compile stderr:') |
| 1384 |
mlog.debug(stde) |
| 1385 |
mlog.debug('-----') |
| 1386 |
if pc.returncode != 0: |
| 1387 |
raise mesonlib.EnvironmentException(f'Compiler {self.name_string()} cannot compile programs.') |
| 1388 |
|
| 1389 |
self._run_sanity_check([os.path.join(work_dir, binname)], work_dir) |
| 1390 |
|
| 1391 |
def _sanity_check_filenames(self) -> T.Tuple[str, T.Optional[str], str]: |
| 1392 |
"""Generate the name of the source and binary file for the sanity check. |
| 1393 |
|
| 1394 |
The returned names should be just the names of the files with |
| 1395 |
extensions, but no paths. |
| 1396 |
|
| 1397 |
The return value consists of a source name, a transpiled source name (if |
| 1398 |
there is one), and the final binary name. |
| 1399 |
|
| 1400 |
:return: A tuple of (sourcename, transpiled, binaryname) |
| 1401 |
""" |
| 1402 |
default_ext = lang_suffixes[self.language][0] |
| 1403 |
template = f'sanity_check_for_{self.language}' |
| 1404 |
sourcename = f'{template}.{default_ext}' |
| 1405 |
cross_or_not = "_cross" if self.is_cross else "" |
| 1406 |
binaryname = f'{template}{cross_or_not}.exe' |
| 1407 |
return sourcename, None, binaryname |
| 1408 |
|
| 1409 |
def _transpiled_sanity_check_compile_args( |
| 1410 |
self, compiler: Compiler, sourcename: str, binname: str |
| 1411 |
) -> T.Tuple[T.List[str], T.List[str]]: |
| 1412 |
"""Get arguments to run compiler for sanity check. |
| 1413 |
|
| 1414 |
By default this will just return the compile arguments for the compiler in question. |
| 1415 |
|
| 1416 |
Linker arguments are separated from compiler arguments because some |
| 1417 |
compilers do not allow linker and compiler arguments to be mixed together |
| 1418 |
|
| 1419 |
Overriding this is useful when needing to change the kind of output |
| 1420 |
produced, or adding extra arguments. |
| 1421 |
|
| 1422 |
:param compiler: The :class:`Compiler` that is used for compiling the transpiled sources |
| 1423 |
:param sourcename: the name of the source file to generate |
| 1424 |
:param binname: the name of the binary file to generate |
| 1425 |
:return: a tuple of arguments, the first is the executable and compiler |
| 1426 |
arguments, the second is linker arguments |
| 1427 |
""" |
| 1428 |
return compiler._sanity_check_compile_args(sourcename, binname) |
| 1429 |
|
| 1430 |
def _sanity_check_mode(self) -> CompileCheckMode: |
| 1431 |
"""Whether the sanity check links a binary, or only compiles one.""" |
| 1432 |
return CompileCheckMode.LINK |
| 1433 |
|
| 1434 |
def get_external_compile_args(self) -> T.List[str]: |
| 1435 |
return list(self.environment.coredata.get_external_args(self.for_machine, self.language)) |
| 1436 |
|
| 1437 |
def get_external_link_args(self) -> T.List[str]: |
| 1438 |
return list(self.environment.coredata.get_external_link_args(self.for_machine, self.language)) |
| 1439 |
|
| 1440 |
def _sanity_check_compile_args(self, sourcename: str, binname: str |
| 1441 |
) -> T.Tuple[T.List[str], T.List[str]]: |
| 1442 |
"""Get arguments to run compiler for sanity check. |
| 1443 |
|
| 1444 |
Linker arguments are separated from compiler arguments because some |
| 1445 |
compilers do not allow linker and compiler arguments to be mixed together |
| 1446 |
|
| 1447 |
:param sourcename: the name of the source file to generate |
| 1448 |
:param binname: the name of the binary file to generate |
| 1449 |
:return: a tuple of arguments, the first is the executable and compiler |
| 1450 |
arguments, the second is linker arguments |
| 1451 |
""" |
| 1452 |
mode = self._sanity_check_mode() |
| 1453 |
cargs = self.exelist_no_ccache + self.get_always_args() + self.get_output_args(binname) + [sourcename] + \ |
| 1454 |
self.get_external_compile_args() |
| 1455 |
if mode is CompileCheckMode.COMPILE: |
| 1456 |
return cargs, [] |
| 1457 |
largs = self.get_external_link_args() |
| 1458 |
return cargs, largs |
| 1459 |
|
| 1460 |
@abc.abstractmethod |
| 1461 |
def _sanity_check_source_code(self) -> str: |
| 1462 |
"""Get the source code to run for a sanity check |
| 1463 |
|
| 1464 |
:return: A string to be written into a file and ran. |
| 1465 |
""" |
| 1466 |
|
| 1467 |
def _sanity_check_run_with_exe_wrapper(self, command: T.List[str]) -> T.List[str]: |
| 1468 |
"""Wrap the binary to run in the test with the exe_wrapper if necessary |
| 1469 |
|
| 1470 |
Languages that do no want to use an exe_wrapper (or always want to use |
| 1471 |
some kind of wrapper) should override this method |
| 1472 |
|
| 1473 |
:param command: The string list of commands to run |
| 1474 |
:return: The list of commands wrapped by the exe_wrapper if it is needed, otherwise the original commands |
| 1475 |
""" |
| 1476 |
if self.is_cross and (exe_wrapper := self.environment.get_exe_wrapper()): |
| 1477 |
return exe_wrapper.get_command() + command |
| 1478 |
return command |
| 1479 |
|
| 1480 |
def _run_sanity_check(self, cmdlist: T.List[str], work_dir: str) -> None: |
| 1481 |
"""Run a sanity test binary |
| 1482 |
|
| 1483 |
:param cmdlist: A list of strings to pass to :func:`subprocess.run` or equivalent to run the test |
| 1484 |
:param work_dir: A directory to place temporary artifacts |
| 1485 |
:raises mesonlib.EnvironmentException: If the binary cannot be run or if it returns a non-zero exit code |
| 1486 |
""" |
| 1487 |
# Can't check binaries, so we have to assume they work |
| 1488 |
if self.is_cross and not self.environment.has_exe_wrapper(): |
| 1489 |
mlog.debug('Cannot run cross check') |
| 1490 |
return |
| 1491 |
|
| 1492 |
cmdlist = self._sanity_check_run_with_exe_wrapper(cmdlist) |
| 1493 |
mlog.debug('Sanity check built target output for', self.for_machine, self.language, 'compiler') |
| 1494 |
mlog.debug(' -- Running test binary command: ', mesonlib.join_args(cmdlist)) |
| 1495 |
try: |
| 1496 |
pe, stdo, stde = Popen_safe_logged(cmdlist, 'Sanity check', cwd=work_dir) |
| 1497 |
mlog.debug(' -- stdout:\n', stdo) |
| 1498 |
mlog.debug(' -- stderr:\n', stde) |
| 1499 |
mlog.debug(' -- returncode:', pe.returncode) |
| 1500 |
except Exception as e: |
| 1501 |
raise mesonlib.EnvironmentException(f'Could not invoke sanity check executable: {e!s}.') |
| 1502 |
|
| 1503 |
if pe.returncode != 0: |
| 1504 |
raise mesonlib.EnvironmentException(f'Executables created by {self.language} compiler {self.name_string()} are not runnable.') |
| 1505 |
|
| 1506 |
def split_shlib_to_parts(self, fname: str) -> T.Tuple[T.Optional[str], str]: |
| 1507 |
return None, fname |
| 1508 |
|
| 1509 |
def get_dependency_gen_args(self, outtarget: str, outfile: str) -> T.List[str]: |
| 1510 |
return [] |
| 1511 |
|
| 1512 |
def get_std_exe_link_args(self) -> T.List[str]: |
| 1513 |
# TODO: is this a linker property? |
| 1514 |
return [] |
| 1515 |
|
| 1516 |
def get_include_args(self, path: str, is_system: bool) -> T.List[str]: |
| 1517 |
return [] |
| 1518 |
|
| 1519 |
def get_depfile_format(self) -> str: |
| 1520 |
return 'msvc' if self.get_argument_syntax() == 'msvc' else 'gcc' |
| 1521 |
|
| 1522 |
def depfile_for_object(self, objfile: str) -> T.Optional[str]: |
| 1523 |
return objfile + '.' + self.get_depfile_suffix() |
| 1524 |
|
| 1525 |
def get_depfile_suffix(self) -> str: |
| 1526 |
raise EnvironmentException(f'{self.id} does not implement get_depfile_suffix') |
| 1527 |
|
| 1528 |
def get_no_stdinc_args(self) -> T.List[str]: |
| 1529 |
"""Arguments to turn off default inclusion of standard libraries.""" |
| 1530 |
return [] |
| 1531 |
|
| 1532 |
def get_no_stdlib_link_args(self) -> T.List[str]: |
| 1533 |
"""Arguments to turn off default linking to standard libraries.""" |
| 1534 |
return [] |
| 1535 |
|
| 1536 |
def get_warn_args(self, level: str) -> T.List[str]: |
| 1537 |
return [] |
| 1538 |
|
| 1539 |
def get_werror_args(self) -> T.List[str]: |
| 1540 |
return [] |
| 1541 |
|
| 1542 |
def get_cpp_modules_args(self) -> T.List[str]: |
| 1543 |
return [] |
| 1544 |
|
| 1545 |
@abc.abstractmethod |
| 1546 |
def get_optimization_args(self, optimization_level: str) -> T.List[str]: |
| 1547 |
pass |
| 1548 |
|
| 1549 |
def get_module_incdir_args(self) -> T.Tuple[str, ...]: |
| 1550 |
raise EnvironmentException(f'{self.id} does not implement get_module_incdir_args') |
| 1551 |
|
| 1552 |
def get_module_outdir_args(self, path: str) -> T.List[str]: |
| 1553 |
raise EnvironmentException(f'{self.id} does not implement get_module_outdir_args') |
| 1554 |
|
| 1555 |
def module_name_to_filename(self, module_name: str) -> str: |
| 1556 |
raise EnvironmentException(f'{self.id} does not implement module_name_to_filename') |
| 1557 |
|
| 1558 |
def get_compiler_check_args(self, mode: CompileCheckMode) -> T.List[str]: |
| 1559 |
"""Arguments to pass the compiler and/or linker for checks. |
| 1560 |
|
| 1561 |
The default implementation turns off optimizations. |
| 1562 |
|
| 1563 |
Examples of things that go here: |
| 1564 |
- extra arguments for error checking |
| 1565 |
- Arguments required to make the compiler exit with a non-zero status |
| 1566 |
when something is wrong. |
| 1567 |
""" |
| 1568 |
return self.get_no_optimization_args() |
| 1569 |
|
| 1570 |
def get_no_optimization_args(self) -> T.List[str]: |
| 1571 |
"""Arguments to the compiler to turn off all optimizations.""" |
| 1572 |
return [] |
| 1573 |
|
| 1574 |
def build_wrapper_args(self, |
| 1575 |
extra_args: T.Union[None, CompilerArgs, T.List[str], T.Callable[[CompileCheckMode], T.List[str]]], |
| 1576 |
dependencies: T.Optional[T.List['Dependency']], |
| 1577 |
mode: CompileCheckMode = CompileCheckMode.COMPILE) -> CompilerArgs: |
| 1578 |
"""Arguments to pass the build_wrapper helper. |
| 1579 |
|
| 1580 |
This generally needs to be set on a per-language basis. It provides |
| 1581 |
a hook for languages to handle dependencies and extra args. The base |
| 1582 |
implementation handles the most common cases, namely adding the |
| 1583 |
check_arguments, unwrapping dependencies, and appending extra args. |
| 1584 |
""" |
| 1585 |
if callable(extra_args): |
| 1586 |
extra_args = extra_args(mode) |
| 1587 |
if extra_args is None: |
| 1588 |
extra_args = [] |
| 1589 |
if dependencies is None: |
| 1590 |
dependencies = [] |
| 1591 |
|
| 1592 |
# Collect compiler arguments |
| 1593 |
args = self.compiler_args(self.get_compiler_check_args(mode)) |
| 1594 |
for d in dependencies: |
| 1595 |
# Add compile flags needed by dependencies |
| 1596 |
args += d.get_compile_args() |
| 1597 |
if mode is CompileCheckMode.LINK: |
| 1598 |
# Add link flags needed to find dependencies |
| 1599 |
args += d.get_link_args() |
| 1600 |
|
| 1601 |
if mode is CompileCheckMode.COMPILE: |
| 1602 |
# Add DFLAGS from the env |
| 1603 |
args += self.get_external_compile_args() |
| 1604 |
elif mode is CompileCheckMode.LINK: |
| 1605 |
args += self.get_linker_always_args() |
| 1606 |
# Add LDFLAGS from the env |
| 1607 |
args += self.get_external_link_args() |
| 1608 |
# extra_args must override all other arguments, so we add them last |
| 1609 |
args += extra_args |
| 1610 |
return args |
| 1611 |
|
| 1612 |
@contextlib.contextmanager |
| 1613 |
def _build_wrapper(self, code: 'mesonlib.FileOrString', |
| 1614 |
extra_args: T.Union[None, CompilerArgs, T.List[str], T.Callable[[CompileCheckMode], T.List[str]]] = None, |
| 1615 |
dependencies: T.Optional[T.List['Dependency']] = None, |
| 1616 |
mode: CompileCheckMode = CompileCheckMode.COMPILE, want_output: bool = False, |
| 1617 |
disable_cache: bool = False) -> T.Iterator[CompileResult]: |
| 1618 |
"""Helper for getting a cached value when possible. |
| 1619 |
|
| 1620 |
This method isn't meant to be called externally, it's mean to be |
| 1621 |
wrapped by other methods like compiles() and links(). |
| 1622 |
""" |
| 1623 |
args = self.build_wrapper_args(extra_args, dependencies, mode) |
| 1624 |
if disable_cache or want_output: |
| 1625 |
with self.compile(code, extra_args=args, mode=mode, want_output=want_output, temp_dir=self.environment.scratch_dir) as r: |
| 1626 |
yield r |
| 1627 |
else: |
| 1628 |
with self.cached_compile(code, extra_args=args, mode=mode, temp_dir=self.environment.scratch_dir) as r: |
| 1629 |
yield r |
| 1630 |
|
| 1631 |
def compiles(self, code: 'mesonlib.FileOrString', *, |
| 1632 |
extra_args: T.Union[None, T.List[str], CompilerArgs, T.Callable[[CompileCheckMode], T.List[str]]] = None, |
| 1633 |
dependencies: T.Optional[T.List['Dependency']] = None, |
| 1634 |
mode: CompileCheckMode = CompileCheckMode.COMPILE, |
| 1635 |
disable_cache: bool = False) -> T.Tuple[bool, bool]: |
| 1636 |
"""Run a compilation or link test to see if code can be compiled/linked. |
| 1637 |
|
| 1638 |
:returns: |
| 1639 |
A tuple of (bool, bool). The first value is whether the check |
| 1640 |
succeeded, and the second is whether it was retrieved from a cache |
| 1641 |
""" |
| 1642 |
with self._build_wrapper(code, extra_args, dependencies, mode, disable_cache=disable_cache) as p: |
| 1643 |
return p.returncode == 0, p.cached |
| 1644 |
|
| 1645 |
def links(self, code: 'mesonlib.FileOrString', *, |
| 1646 |
compiler: T.Optional['Compiler'] = None, |
| 1647 |
extra_args: T.Union[None, T.List[str], CompilerArgs, T.Callable[[CompileCheckMode], T.List[str]]] = None, |
| 1648 |
dependencies: T.Optional[T.List['Dependency']] = None, |
| 1649 |
disable_cache: bool = False) -> T.Tuple[bool, bool]: |
| 1650 |
if compiler: |
| 1651 |
with compiler._build_wrapper(code, dependencies=dependencies, want_output=True) as r: |
| 1652 |
objfile = mesonlib.File.from_absolute_file(r.output_name) |
| 1653 |
return self.compiles(objfile, extra_args=extra_args, |
| 1654 |
dependencies=dependencies, mode=CompileCheckMode.LINK, disable_cache=True) |
| 1655 |
|
| 1656 |
return self.compiles(code, extra_args=extra_args, |
| 1657 |
dependencies=dependencies, mode=CompileCheckMode.LINK, disable_cache=disable_cache) |
| 1658 |
|
| 1659 |
def get_feature_args(self, kwargs: DFeatures, build_to_src: str) -> T.List[str]: |
| 1660 |
"""Used by D for extra language features.""" |
| 1661 |
# TODO: using a TypeDict here would improve this |
| 1662 |
raise EnvironmentException(f'{self.id} does not implement get_feature_args') |
| 1663 |
|
| 1664 |
def get_prelink_args(self, prelink_name: str, obj_list: T.List[str]) -> T.Tuple[T.List[str], T.List[str]]: |
| 1665 |
raise EnvironmentException(f'{self.id} does not know how to do prelinking.') |
| 1666 |
|
| 1667 |
def get_prelink_append_compile_args(self) -> bool: |
| 1668 |
"""Controls whether compile args have to be used for prelinking or not""" |
| 1669 |
return False |
| 1670 |
|
| 1671 |
def rsp_file_syntax(self) -> 'RSPFileSyntax': |
| 1672 |
"""The format of the RSP file that this compiler supports. |
| 1673 |
|
| 1674 |
If `self.can_linker_accept_rsp()` returns True, then this needs to |
| 1675 |
be implemented |
| 1676 |
""" |
| 1677 |
return self.linker.rsp_file_syntax() |
| 1678 |
|
| 1679 |
def get_debug_args(self, is_debug: bool) -> T.List[str]: |
| 1680 |
"""Arguments required for a debug build.""" |
| 1681 |
return [] |
| 1682 |
|
| 1683 |
def needs_static_linker(self) -> bool: |
| 1684 |
raise NotImplementedError(f'There is no static linker for {self.language}') |
| 1685 |
|
| 1686 |
def get_preprocessor(self) -> Compiler: |
| 1687 |
"""Get compiler's preprocessor. |
| 1688 |
""" |
| 1689 |
raise EnvironmentException(f'{self.get_id()} does not support preprocessor') |
| 1690 |
|
| 1691 |
def form_compileropt_key(self, basename: str) -> OptionKey: |
| 1692 |
return OptionKey(f'{self.language}_{basename}', machine=self.for_machine) |
| 1693 |
|
| 1694 |
def get_compileropt_value(self, |
| 1695 |
key: T.Union[str, OptionKey], |
| 1696 |
target: T.Optional[BuildTarget], |
| 1697 |
subproject: T.Optional[str] = None |
| 1698 |
) -> options.ElementaryOptionValues: |
| 1699 |
if isinstance(key, str): |
| 1700 |
key = self.form_compileropt_key(key) |
| 1701 |
if target: |
| 1702 |
return self.environment.coredata.get_option_for_target(target, key) |
| 1703 |
else: |
| 1704 |
return self.environment.coredata.optstore.get_value_for(key.evolve(subproject=subproject)) |
| 1705 |
|
| 1706 |
def _update_language_stds(self, opts: MutableKeyedOptionDictType, value: T.List[str]) -> None: |
| 1707 |
key = self.form_compileropt_key('std') |
| 1708 |
std = opts[key] |
| 1709 |
assert isinstance(std, (options.UserStdOption, options.UserComboOption)), 'for mypy' |
| 1710 |
if 'none' not in value: |
| 1711 |
value = ['none'] + value |
| 1712 |
std.choices = value |
| 1713 |
|
| 1714 |
def get_crt_static(self) -> bool: |
| 1715 |
"""Is this target using static CRT?""" |
| 1716 |
raise EnvironmentException(f'{self.get_id()} does not support static CRT') |
| 1717 |
|
| 1718 |
def get_target_libdir(self) -> str: |
| 1719 |
"""Where is the libdir for the current machine located""" |
| 1720 |
raise EnvironmentException(f'{self.get_id()} does not support Rust target libdir') |
| 1721 |
|
| 1722 |
def get_show_dep_args(self) -> T.List[str]: |
| 1723 |
"""Arguments for printing depfile information in MSVC compatible format""" |
| 1724 |
return [] |