Debian Codegraph @

mesonbuild/compilers/mixins/clike.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2012-2023 The Meson development team
3
4 from __future__ import annotations
5
6
7 """Mixin classes to be shared between C and C++ compilers.
8
9 Without this we'll end up with awful diamond inheritance problems. The goal
10 of this is to have mixin's, which are classes that are designed *not* to be
11 standalone, they only work through inheritance.
12 """
13
14 import collections
15 import functools
16 import glob
17 import itertools
18 import os
19 import re
20 import subprocess
21 import copy
22 import typing as T
23 from pathlib import Path
24
25 from ... import arglist
26 from ... import mesonlib
27 from ... import mlog
28 from ...linkers.linkers import GnuLikeDynamicLinkerMixin, SolarisDynamicLinker, CompCertDynamicLinker
29 from ...mesonlib import LibType
30 from .. import compilers
31 from ..compilers import CompileCheckMode
32 from .visualstudio import VisualStudioLikeCompiler
33
34 if T.TYPE_CHECKING:
35 from ...dependencies import Dependency
36 from ..._typing import ImmutableListProtocol
37 from ...environment import Environment
38 from ...compilers.compilers import Compiler
39 else:
40 # This is a bit clever, for mypy we pretend that these mixins descend from
41 # Compiler, so we get all of the methods and attributes defined for us, but
42 # for runtime we make them descend from object (which all classes normally
43 # do). This gives up DRYer type checking, with no runtime impact
44 Compiler = object
45
46 GROUP_FLAGS = re.compile(r'''^(?!-Wl,) .*\.so (?:\.[0-9]+)? (?:\.[0-9]+)? (?:\.[0-9]+)?$ |
47 ^(?:-Wl,)?-l |
48 \.a$''', re.X)
49
50 class CLikeCompilerArgs(arglist.CompilerArgs):
51 # Note: ``-isystem`` is deliberately absent from prepend_prefixes.
52 # Because ``-isystem`` is appended by __iadd__ rather than
53 # prepended, the reversed iteration in the ninja backend causes
54 # directories listed *last* in include_directories() to appear
55 # *first* on the command line (and thus be searched first). This
56 # is the opposite convention from ``-I``, where first-listed means
57 # first-searched. Existing projects (e.g. systemd) rely on this
58 # ``-isystem`` ordering, so adding ``-isystem`` to prepend_prefixes
59 # would silently break them by reversing their include priority.
60 # See NinjaBackend._generate_single_compile_target_args().
61 prepend_prefixes = ('-I', '-L')
62 dedup2_prefixes = ('-I', '-isystem', '-L', '-D', '-U')
63
64 # NOTE: not thorough. A list of potential corner cases can be found in
65 # https://github.com/mesonbuild/meson/pull/4593#pullrequestreview-182016038
66 dedup1_prefixes = ('-l', '-Wl,-l', '-Wl,-rpath,', '-Wl,-rpath-link,')
67 dedup1_suffixes = ('.lib', '.dll', '.so', '.dylib', '.a')
68 dedup1_args = ('-c', '-S', '-E', '-pipe', '-pthread', '-Wl,--export-dynamic')
69
70 def to_native(self, copy: bool = False) -> T.List[str]:
71 # This seems to be allowed, but could never work?
72 assert isinstance(self.compiler, compilers.Compiler), 'How did you get here'
73
74 # Check if we need to add --start/end-group for circular dependencies
75 # between static libraries, and for recursively searching for symbols
76 # needed by static libraries that are provided by object files or
77 # shared libraries.
78 self.flush_pre_post()
79 if copy:
80 new = self.copy()
81 else:
82 new = self
83 # This covers all ld.bfd, ld.gold, ld.gold, and xild on Linux, which
84 # all act like (or are) gnu ld
85 # TODO: this could probably be added to the DynamicLinker instead
86 if isinstance(self.compiler.linker, (GnuLikeDynamicLinkerMixin, SolarisDynamicLinker, CompCertDynamicLinker)):
87 group_start = -1
88 group_end = -1
89 for i, each in enumerate(new):
90 if not GROUP_FLAGS.search(each):
91 continue
92 group_end = i
93 if group_start < 0:
94 # First occurrence of a library
95 group_start = i
96 # Only add groups if there are multiple libraries.
97 if group_end > group_start >= 0:
98 # Last occurrence of a library
99 new.insert(group_end + 1, '-Wl,--end-group')
100 new.insert(group_start, '-Wl,--start-group')
101 # Remove system/default include paths added with -isystem
102 default_dirs = self.compiler.get_default_include_dirs()
103 if default_dirs:
104 real_default_dirs = [self._cached_realpath(i) for i in default_dirs]
105 bad_idx_list: T.List[int] = []
106 for i, each in enumerate(new):
107 if not each.startswith('-isystem'):
108 continue
109
110 # Remove the -isystem and the path if the path is a default path
111 if each == '-isystem':
112 if i < (len(new) - 1) and self._cached_realpath(new[i + 1]) in real_default_dirs:
113 bad_idx_list += [i, i + 1]
114 elif each.startswith('-isystem='):
115 if self._cached_realpath(each[9:]) in real_default_dirs:
116 bad_idx_list += [i]
117 elif self._cached_realpath(each[8:]) in real_default_dirs:
118 bad_idx_list += [i]
119 for i in reversed(bad_idx_list):
120 new.pop(i)
121 return self.compiler.unix_args_to_native(new._container)
122
123 @staticmethod
124 @functools.lru_cache(maxsize=None)
125 def _cached_realpath(arg: str) -> str:
126 return os.path.realpath(arg)
127
128 def __repr__(self) -> str:
129 self.flush_pre_post()
130 return f'CLikeCompilerArgs({self.compiler!r}, {self._container!r})'
131
132
133 class CLikeCompiler(Compiler):
134
135 """Shared bits for the C and CPP Compilers."""
136
137 if T.TYPE_CHECKING:
138 warn_args: T.Dict[str, T.List[str]] = {}
139
140 # TODO: Replace this manual cache with functools.lru_cache
141 find_library_cache: T.Dict[T.Tuple[T.Tuple[str, ...], str, T.Tuple[str, ...], str, LibType, bool, bool], T.Optional[T.List[str]]] = {}
142 find_framework_cache: T.Dict[T.Tuple[T.Tuple[str, ...], str, T.Tuple[str, ...], bool], T.Optional[T.List[str]]] = {}
143 internal_libs = arglist.UNIXY_COMPILER_INTERNAL_LIBS
144
145 def __init__(self) -> None:
146 # If a child ObjC or CPP class has already set it, don't set it ourselves
147 self.can_compile_suffixes.add('h')
148 # Lazy initialized in get_preprocessor()
149 self.preprocessor: T.Optional[Compiler] = None
150
151 def compiler_args(self, args: T.Optional[T.Iterable[str]] = None) -> CLikeCompilerArgs:
152 # This is correct, mypy just doesn't understand co-operative inheritance
153 return CLikeCompilerArgs(self, args)
154
155 def needs_static_linker(self) -> bool:
156 return True # When compiling static libraries, so yes.
157
158 def get_always_args(self) -> T.List[str]:
159 '''
160 Args that are always-on for all C compilers other than MSVC
161 '''
162 return self.get_largefile_args()
163
164 def get_no_stdinc_args(self) -> T.List[str]:
165 return ['-nostdinc']
166
167 def get_no_stdlib_link_args(self) -> T.List[str]:
168 return ['-nostdlib']
169
170 def get_warn_args(self, level: str) -> T.List[str]:
171 # TODO: this should be an enum
172 return self.warn_args[level]
173
174 def get_depfile_suffix(self) -> str:
175 return 'd'
176
177 def get_preprocess_only_args(self) -> T.List[str]:
178 return ['-E', '-P']
179
180 def get_compile_only_args(self) -> T.List[str]:
181 return ['-c']
182
183 def get_no_optimization_args(self) -> T.List[str]:
184 return ['-O0', '-U_FORTIFY_SOURCE']
185
186 def get_output_args(self, outputname: str) -> T.List[str]:
187 return ['-o', outputname]
188
189 def get_werror_args(self) -> T.List[str]:
190 return ['-Werror']
191
192 def get_include_args(self, path: str, is_system: bool) -> T.List[str]:
193 if path == '':
194 path = '.'
195 if is_system:
196 return ['-isystem', path]
197 return ['-I' + path]
198
199 def get_compiler_dirs(self, name: str) -> T.List[str]:
200 '''
201 Get dirs from the compiler, either `libraries:` or `programs:`
202 '''
203 return []
204
205 @functools.lru_cache()
206 def _get_library_dirs(self, elf_class: T.Optional[int] = None) -> 'ImmutableListProtocol[str]':
207 # TODO: replace elf_class with enum
208 dirs = self.get_compiler_dirs('libraries')
209 if elf_class is None or elf_class == 0:
210 return dirs
211
212 # if we do have an elf class for 32-bit or 64-bit, we want to check that
213 # the directory in question contains libraries of the appropriate class. Since
214 # system directories aren't mixed, we only need to check one file for each
215 # directory and go by that. If we can't check the file for some reason, assume
216 # the compiler knows what it's doing, and accept the directory anyway.
217 retval: T.List[str] = []
218 for d in dirs:
219 files = [f for f in os.listdir(d) if f.endswith('.so') and os.path.isfile(os.path.join(d, f))]
220 # if no files, accept directory and move on
221 if not files:
222 retval.append(d)
223 continue
224
225 for f in files:
226 file_to_check = os.path.join(d, f)
227 try:
228 with open(file_to_check, 'rb') as fd:
229 header = fd.read(5)
230 # if file is not an ELF file, it's weird, but accept dir
231 # if it is elf, and the class matches, accept dir
232 if header[1:4] != b'ELF' or int(header[4]) == elf_class:
233 retval.append(d)
234 # at this point, it's an ELF file which doesn't match the
235 # appropriate elf_class, so skip this one
236 # stop scanning after the first successful read
237 break
238 except OSError:
239 # Skip the file if we can't read it
240 pass
241
242 return retval
243
244 def get_library_dirs(self, elf_class: T.Optional[int] = None) -> T.List[str]:
245 """Wrap the lru_cache so that we return a new copy and don't allow
246 mutation of the cached value.
247 """
248 return self._get_library_dirs(elf_class).copy()
249
250 @functools.lru_cache()
251 def _get_program_dirs(self) -> 'ImmutableListProtocol[str]':
252 '''
253 Programs used by the compiler. Also where toolchain DLLs such as
254 libstdc++-6.dll are found with MinGW.
255 '''
256 return self.get_compiler_dirs('programs')
257
258 def get_program_dirs(self) -> T.List[str]:
259 return self._get_program_dirs().copy()
260
261 def get_pic_args(self) -> T.List[str]:
262 return ['-fPIC']
263
264 def get_pch_use_args(self, pch_dir: str, header: str) -> T.List[str]:
265 return ['-include', os.path.basename(header)]
266
267 def get_pch_name(self, name: str) -> str:
268 return os.path.basename(name) + '.' + self.get_pch_suffix()
269
270 def get_default_include_dirs(self) -> T.List[str]:
271 return []
272
273 def gen_export_dynamic_link_args(self) -> T.List[str]:
274 return self.linker.export_dynamic_args()
275
276 def gen_import_library_args(self, implibname: str) -> T.List[str]:
277 return self.linker.import_library_args(implibname)
278
279 def _sanity_check_compile_args(self, sourcename: str, binname: str
280 ) -> T.Tuple[T.List[str], T.List[str]]:
281 # Cross-compiling is hard. For example, you might need -nostdlib, or to pass --target, etc.
282 mode = CompileCheckMode.COMPILE if self.is_cross and not self.environment.has_exe_wrapper() else CompileCheckMode.LINK
283 cargs, b_largs = self._get_basic_compiler_args(mode)
284 largs = self.linker_to_compiler_args(b_largs)
285 s_args, s_largs = super()._sanity_check_compile_args(sourcename, binname)
286 return s_args + cargs, s_largs + largs
287
288 def check_header(self, hname: str, prefix: str, *,
289 extra_args: T.Union[None, T.List[str], T.Callable[['CompileCheckMode'], T.List[str]]] = None,
290 dependencies: T.Optional[T.List['Dependency']] = None) -> T.Tuple[bool, bool]:
291 code = f'''{prefix}
292 #include <{hname}>'''
293 return self.compiles(code, extra_args=extra_args, dependencies=dependencies)
294
295 def has_header(self, hname: str, prefix: str, *,
296 extra_args: T.Union[None, T.List[str], T.Callable[['CompileCheckMode'], T.List[str]]] = None,
297 dependencies: T.Optional[T.List['Dependency']] = None,
298 disable_cache: bool = False) -> T.Tuple[bool, bool]:
299 code = f'''{prefix}
300 #ifdef __has_include
301 #if !__has_include("{hname}")
302 #error "Header '{hname}' could not be found"
303 #endif
304 #else
305 #include <{hname}>
306 #endif'''
307 return self.compiles(code, extra_args=extra_args,
308 dependencies=dependencies, mode=CompileCheckMode.PREPROCESS, disable_cache=disable_cache)
309
310 def has_header_symbol(self, hname: str, symbol: str, prefix: str, *,
311 extra_args: T.Union[None, T.List[str], T.Callable[[CompileCheckMode], T.List[str]]] = None,
312 dependencies: T.Optional[T.List['Dependency']] = None) -> T.Tuple[bool, bool]:
313 t = f'''{prefix}
314 #include <{hname}>
315 int main(void) {{
316 /* If it's not defined as a macro, try to use as a symbol */
317 #ifndef {symbol}
318 {symbol};
319 #endif
320 return 0;
321 }}'''
322 return self.compiles(t, extra_args=extra_args,
323 dependencies=dependencies)
324
325 def _get_basic_compiler_args(self, mode: CompileCheckMode) -> T.Tuple[T.List[str], T.List[str]]:
326 cargs: T.List[str] = []
327 largs: T.List[str] = []
328 if mode is CompileCheckMode.LINK:
329 # Sometimes we need to manually select the CRT to use with MSVC.
330 # One example is when trying to do a compiler check that involves
331 # linking with static libraries since MSVC won't select a CRT for
332 # us in that case and will error out asking us to pick one.
333 try:
334 crt_val = self.environment.coredata.optstore.get_value_for('b_vscrt')
335 assert isinstance(crt_val, str), 'for mypy'
336 cargs += self.get_crt_compile_args(crt_val)
337 largs += self.get_crt_link_args(crt_val)
338 except (KeyError, AttributeError):
339 pass
340
341 # Add CFLAGS/CXXFLAGS/OBJCFLAGS/OBJCXXFLAGS and CPPFLAGS from the env
342 sys_args = self.environment.coredata.get_external_args(self.for_machine, self.language)
343 if isinstance(sys_args, str):
344 sys_args = [sys_args]
345 # Apparently it is a thing to inject linker flags both
346 # via CFLAGS _and_ LDFLAGS, even though the former are
347 # also used during linking. These flags can break
348 # argument checks. Thanks, Autotools.
349 cleaned_sys_args = self.remove_linkerlike_args(sys_args)
350 cargs += cleaned_sys_args
351
352 if mode is CompileCheckMode.LINK:
353 ld_value = self.environment.lookup_binary_entry(self.for_machine, self.language + '_ld')
354 if ld_value is not None:
355 cargs += self.use_linker_args(ld_value[0], self.version)
356
357 # Add LDFLAGS from the env
358 sys_ld_args = self.environment.coredata.get_external_link_args(self.for_machine, self.language)
359 # CFLAGS and CXXFLAGS go to both linking and compiling, but we want them
360 # to only appear on the command line once. Remove dupes.
361 largs += [x for x in sys_ld_args if x not in cleaned_sys_args]
362
363 cargs += self.get_compiler_args_for_mode(mode)
364 return cargs, largs
365
366 def build_wrapper_args(self,
367 extra_args: T.Union[None, arglist.CompilerArgs, T.List[str], T.Callable[[CompileCheckMode], T.List[str]]],
368 dependencies: T.Optional[T.List['Dependency']],
369 mode: CompileCheckMode = CompileCheckMode.COMPILE) -> arglist.CompilerArgs:
370 # TODO: the caller should handle the listing of these arguments
371 if extra_args is None:
372 extra_args = []
373 else:
374 # TODO: we want to do this in the caller
375 extra_args = mesonlib.listify(extra_args)
376 extra_args = mesonlib.listify([e(mode) if callable(e) else e for e in extra_args])
377
378 if dependencies is None:
379 dependencies = []
380 elif not isinstance(dependencies, collections.abc.Iterable):
381 # TODO: we want to ensure the front end does the listifing here
382 dependencies = [dependencies]
383 # Collect compiler arguments
384 cargs: arglist.CompilerArgs = self.compiler_args()
385 largs: T.List[str] = []
386 for d in dependencies:
387 # Add compile flags needed by dependencies
388 cargs += d.get_compile_args()
389 system_incdir = d.get_include_type() == 'system'
390 for i in d.get_include_dirs():
391 for idir in i.abs_string_list(self.environment.get_source_dir(), self.environment.get_build_dir()):
392 cargs.extend(self.get_include_args(idir, system_incdir))
393 if mode is CompileCheckMode.LINK:
394 # Add link flags needed to find dependencies
395 largs += d.get_link_args()
396
397 ca, la = self._get_basic_compiler_args(mode)
398 cargs += ca
399
400 cargs += self.get_compiler_check_args(mode)
401
402 # on MSVC compiler and linker flags must be separated by the "/link" argument
403 # at this point, the '/link' argument may already be part of extra_args, otherwise, it is added here
404 largs += [l for l in self.linker_to_compiler_args(la) if l != '/link']
405
406 if self.linker_to_compiler_args([]) == ['/link']:
407 if largs != [] and '/link' not in extra_args:
408 extra_args += ['/link']
409 # all linker flags must be converted now, otherwise the reordering
410 # of arglist will apply and -L flags will be reordered into
411 # breaking form. See arglist._should_prepend
412 largs = self.unix_args_to_native(largs)
413
414 args = cargs + extra_args + largs
415 return args
416
417 def _compile_int(self, expression: str, prefix: str,
418 extra_args: T.Union[None, T.List[str], T.Callable[[CompileCheckMode], T.List[str]]],
419 dependencies: T.Optional[T.List['Dependency']]) -> bool:
420 t = f'''{prefix}
421 #include <stddef.h>
422 int main(void) {{ static int a[1-2*!({expression})]; a[0]=0; return 0; }}'''
423 return self.compiles(t, extra_args=extra_args, dependencies=dependencies)[0]
424
425 def _cross_compute_int(self, expression: str, low: T.Optional[int], high: T.Optional[int],
426 guess: T.Optional[int], prefix: str,
427 extra_args: T.Union[None, T.List[str], T.Callable[[CompileCheckMode], T.List[str]]] = None,
428 dependencies: T.Optional[T.List['Dependency']] = None) -> int:
429 # Try user's guess first
430 if isinstance(guess, int):
431 if self._compile_int(f'{expression} == {guess}', prefix, extra_args, dependencies):
432 return guess
433
434 # Try to expand the expression and evaluate it on the build machines compiler
435 if self.language in self.environment.coredata.compilers.build:
436 try:
437 expanded, _ = self.get_define(expression, prefix, extra_args, dependencies, False)
438 evaluate_expanded = f'''
439 #include <stdio.h>
440 #include <stdint.h>
441 int main(void) {{ int expression = {expanded}; printf("%d", expression); return 0; }}'''
442 run = self.environment.coredata.compilers.build[self.language].run(evaluate_expanded)
443 if run and run.compiled and run.returncode == 0:
444 if self._compile_int(f'{expression} == {run.stdout}', prefix, extra_args, dependencies):
445 return int(run.stdout)
446 except mesonlib.EnvironmentException:
447 pass
448
449 # If no bounds are given, compute them in the limit of int32
450 maxint = 0x7fffffff
451 minint = -0x80000000
452 if not isinstance(low, int) or not isinstance(high, int):
453 if self._compile_int(f'{expression} >= 0', prefix, extra_args, dependencies):
454 low = cur = 0
455 while self._compile_int(f'{expression} > {cur}', prefix, extra_args, dependencies):
456 low = cur + 1
457 if low > maxint:
458 raise mesonlib.EnvironmentException('Cross-compile check overflowed')
459 cur = min(cur * 2 + 1, maxint)
460 high = cur
461 else:
462 high = cur = -1
463 while self._compile_int(f'{expression} < {cur}', prefix, extra_args, dependencies):
464 high = cur - 1
465 if high < minint:
466 raise mesonlib.EnvironmentException('Cross-compile check overflowed')
467 cur = max(cur * 2, minint)
468 low = cur
469 else:
470 # Sanity check limits given by user
471 if high < low:
472 raise mesonlib.EnvironmentException('high limit smaller than low limit')
473 condition = f'{expression} <= {high} && {expression} >= {low}'
474 if not self._compile_int(condition, prefix, extra_args, dependencies):
475 raise mesonlib.EnvironmentException('Value out of given range')
476
477 # Binary search
478 while low != high:
479 cur = low + int((high - low) / 2)
480 if self._compile_int(f'{expression} <= {cur}', prefix, extra_args, dependencies):
481 high = cur
482 else:
483 low = cur + 1
484
485 return low
486
487 def compute_int(self, expression: str, low: T.Optional[int], high: T.Optional[int],
488 guess: T.Optional[int], prefix: str, *,
489 extra_args: T.Union[None, T.List[str], T.Callable[[CompileCheckMode], T.List[str]]],
490 dependencies: T.Optional[T.List['Dependency']] = None) -> int:
491 if extra_args is None:
492 extra_args = []
493 if self.is_cross:
494 return self._cross_compute_int(expression, low, high, guess, prefix, extra_args, dependencies)
495 t = f'''{prefix}
496 #include<stddef.h>
497 #include<stdio.h>
498 int main(void) {{
499 printf("%ld\\n", (long)({expression}));
500 return 0;
501 }}'''
502 res = self.run(t, extra_args=extra_args,
503 dependencies=dependencies)
504 if not res.compiled:
505 return -1
506 if res.returncode != 0:
507 raise mesonlib.EnvironmentException('Could not run compute_int test binary.')
508 return int(res.stdout)
509
510 def _cross_sizeof(self, typename: str, prefix: str, *,
511 extra_args: T.Union[None, T.List[str], T.Callable[[CompileCheckMode], T.List[str]]] = None,
512 dependencies: T.Optional[T.List['Dependency']] = None) -> int:
513 if extra_args is None:
514 extra_args = []
515 t = f'''{prefix}
516 #include <stddef.h>
517 int main(void) {{
518 {typename} something;
519 return 0;
520 }}'''
521 if not self.compiles(t, extra_args=extra_args,
522 dependencies=dependencies)[0]:
523 return -1
524 return self._cross_compute_int(f'sizeof({typename})', None, None, None, prefix, extra_args, dependencies)
525
526 def sizeof(self, typename: str, prefix: str, *,
527 extra_args: T.Union[None, T.List[str], T.Callable[[CompileCheckMode], T.List[str]]] = None,
528 dependencies: T.Optional[T.List['Dependency']] = None) -> T.Tuple[int, bool]:
529 if extra_args is None:
530 extra_args = []
531 if self.is_cross:
532 r = self._cross_sizeof(typename, prefix, extra_args=extra_args,
533 dependencies=dependencies)
534 return r, False
535 t = f'''{prefix}
536 #include<stddef.h>
537 #include<stdio.h>
538 int main(void) {{
539 printf("%ld\\n", (long)(sizeof({typename})));
540 return 0;
541 }}'''
542 res = self.cached_run(t, extra_args=extra_args,
543 dependencies=dependencies)
544 if not res.compiled:
545 return -1, False
546 if res.returncode != 0:
547 raise mesonlib.EnvironmentException('Could not run sizeof test binary.')
548 try:
549 return int(res.stdout), res.cached
550 except ValueError:
551 raise mesonlib.EnvironmentException(
552 f'Could not determine size of {typename}: compiler output was empty or invalid.'
553 )
554
555 def _cross_alignment(self, typename: str, prefix: str, *,
556 extra_args: T.Optional[T.List[str]] = None,
557 dependencies: T.Optional[T.List['Dependency']] = None) -> int:
558 if extra_args is None:
559 extra_args = []
560 t = f'''{prefix}
561 #include <stddef.h>
562 int main(void) {{
563 {typename} something;
564 return 0;
565 }}'''
566 if not self.compiles(t, extra_args=extra_args,
567 dependencies=dependencies)[0]:
568 return -1
569 t = f'''{prefix}
570 #include <stddef.h>
571 struct tmp {{
572 char c;
573 {typename} target;
574 }};'''
575 return self._cross_compute_int('offsetof(struct tmp, target)', None, None, None, t, extra_args, dependencies)
576
577 def alignment(self, typename: str, prefix: str, *,
578 extra_args: T.Optional[T.List[str]] = None,
579 dependencies: T.Optional[T.List['Dependency']] = None) -> T.Tuple[int, bool]:
580 if extra_args is None:
581 extra_args = []
582 if self.is_cross:
583 r = self._cross_alignment(typename, prefix, extra_args=extra_args,
584 dependencies=dependencies)
585 return r, False
586 t = f'''{prefix}
587 #include <stdio.h>
588 #include <stddef.h>
589 struct tmp {{
590 char c;
591 {typename} target;
592 }};
593 int main(void) {{
594 printf("%d", (int)offsetof(struct tmp, target));
595 return 0;
596 }}'''
597 res = self.cached_run(t, extra_args=extra_args,
598 dependencies=dependencies)
599 if not res.compiled:
600 raise mesonlib.EnvironmentException('Could not compile alignment test.')
601 if res.returncode != 0:
602 raise mesonlib.EnvironmentException('Could not run alignment test binary.')
603
604 align: int
605 try:
606 align = int(res.stdout)
607 except ValueError:
608 # If we get here, the user is most likely using a script that is
609 # pretending to be a compiler.
610 raise mesonlib.EnvironmentException('Could not run alignment test binary.')
611 if align == 0:
612 raise mesonlib.EnvironmentException(f'Could not determine alignment of {typename}. Sorry. You might want to file a bug.')
613
614 return align, res.cached
615
616 def get_define(self, dname: str, prefix: str,
617 extra_args: T.Union[T.List[str], T.Callable[[CompileCheckMode], T.List[str]]],
618 dependencies: T.Optional[T.List['Dependency']],
619 disable_cache: bool = False) -> T.Tuple[str, bool]:
620 delim_start = '"MESON_GET_DEFINE_DELIMITER_START"\n'
621 delim_end = '\n"MESON_GET_DEFINE_DELIMITER_END"'
622 sentinel_undef = '"MESON_GET_DEFINE_UNDEFINED_SENTINEL"'
623 code = f'''
624 {prefix}
625 #ifndef {dname}
626 # define {dname} {sentinel_undef}
627 #endif
628 {delim_start}{dname}{delim_end}'''
629 args = self.build_wrapper_args(extra_args, dependencies,
630 mode=CompileCheckMode.PREPROCESS).to_native()
631 func = functools.partial(self.cached_compile, code, extra_args=args, mode=CompileCheckMode.PREPROCESS)
632 if disable_cache:
633 func = functools.partial(self.compile, code, extra_args=args, mode=CompileCheckMode.PREPROCESS)
634 with func() as p:
635 cached = p.cached
636 if p.returncode != 0:
637 raise mesonlib.EnvironmentException(f'Could not get define {dname!r}')
638
639 # Get the preprocessed value between the delimiters
640 star_idx = p.stdout.find(delim_start)
641 end_idx = p.stdout.rfind(delim_end)
642 if (star_idx == -1) or (end_idx == -1) or (star_idx == end_idx):
643 raise mesonlib.MesonBugException('Delimiters not found in preprocessor output.')
644 define_value = p.stdout[star_idx + len(delim_start):end_idx]
645
646 # Due to https://developercommunity.visualstudio.com/t/Inconsistent-whitespace-with-standard-pr/11023343,
647 # MSVC can end up producing an unexpected space after the sentinel_undef
648 # string (if building with -std:c11, and if the test source is written
649 # with unix newlines). To avoid treating this as an actual predefined
650 # macro, look for the buggy value as well.
651 if define_value in {sentinel_undef, sentinel_undef + ' '}:
652 define_value = None
653 else:
654 # Merge string literals
655 define_value = self._concatenate_string_literals(define_value).strip()
656
657 return define_value, cached
658
659 def get_return_value(self, fname: str, rtype: str, prefix: str,
660 extra_args: T.Optional[T.List[str]],
661 dependencies: T.Optional[T.List['Dependency']]) -> T.Union[str, int]:
662 # TODO: rtype should be an enum.
663 # TODO: maybe we can use overload to tell mypy when this will return int vs str?
664 if rtype == 'string':
665 fmt = '%s'
666 cast = '(char*)'
667 elif rtype == 'int':
668 fmt = '%lli'
669 cast = '(long long int)'
670 else:
671 raise AssertionError(f'BUG: Unknown return type {rtype!r}')
672 code = f'''{prefix}
673 #include <stdio.h>
674 int main(void) {{
675 printf ("{fmt}", {cast} {fname}());
676 return 0;
677 }}'''
678 res = self.run(code, extra_args=extra_args, dependencies=dependencies)
679 if not res.compiled:
680 raise mesonlib.EnvironmentException(f'Could not get return value of {fname}()')
681 if rtype == 'string':
682 return res.stdout
683 elif rtype == 'int':
684 try:
685 return int(res.stdout.strip())
686 except ValueError:
687 raise mesonlib.EnvironmentException(f'Return value of {fname}() is not an int')
688 assert False, 'Unreachable'
689
690 @staticmethod
691 def _no_prototype_templ() -> T.Tuple[str, str]:
692 """
693 Try to find the function without a prototype from a header by defining
694 our own dummy prototype and trying to link with the C library (and
695 whatever else the compiler links in by default). This is very similar
696 to the check performed by Autoconf for AC_CHECK_FUNCS.
697 """
698 # Define the symbol to something else since it is defined by the
699 # includes or defines listed by the user or by the compiler. This may
700 # include, for instance _GNU_SOURCE which must be defined before
701 # limits.h, which includes features.h
702 # Then, undef the symbol to get rid of it completely.
703 head = '''
704 #define {func} meson_disable_define_of_{func}
705 {prefix}
706 #include <limits.h>
707 #undef {func}
708 '''
709 # Override any GCC internal prototype and declare our own definition for
710 # the symbol. Use char because that's unlikely to be an actual return
711 # value for a function which ensures that we override the definition.
712 head += '''
713 #ifdef __cplusplus
714 extern "C"
715 #endif
716 char {func} (void);
717 '''
718 # The actual function call
719 main = '''
720 int main(void) {{
721 return {func} ();
722 }}'''
723 return head, main
724
725 @staticmethod
726 def _have_prototype_templ() -> T.Tuple[str, str]:
727 """
728 Returns a head-er and main() call that uses the headers listed by the
729 user for the function prototype while checking if a function exists.
730 """
731 # Add the 'prefix', aka defines, includes, etc that the user provides
732 # This may include, for instance _GNU_SOURCE which must be defined
733 # before limits.h, which includes features.h
734 head = '{prefix}\n#include <limits.h>\n'
735 # We don't know what the function takes or returns, so return it as an int.
736 # Just taking the address or comparing it to void is not enough because
737 # compilers are smart enough to optimize it away. The resulting binary
738 # is not run so we don't care what the return value is.
739 main = '''\nint main(void) {{
740 void *a = (void*) &{func};
741 long long b = (long long) a;
742 return (int) b;
743 }}'''
744 return head, main
745
746 def has_function(self, funcname: str, prefix: str, *,
747 extra_args: T.Optional[T.List[str]] = None,
748 dependencies: T.Optional[T.List['Dependency']] = None) -> T.Tuple[bool, bool]:
749 """Determine if a function exists.
750
751 First, this function looks for the symbol in the default libraries
752 provided by the compiler (stdlib + a few others usually). If that
753 fails, it checks if any of the headers specified in the prefix provide
754 an implementation of the function, and if that fails, it checks if it's
755 implemented as a compiler-builtin.
756 """
757 if extra_args is None:
758 extra_args = []
759
760 # Short-circuit if the check is already provided by the cross-info file
761 varname = 'has function ' + funcname
762 varname = varname.replace(' ', '_')
763 if self.is_cross:
764 val = self.environment.properties.host.get(varname, None)
765 if val is not None:
766 if isinstance(val, bool):
767 return val, False
768 raise mesonlib.EnvironmentException(f'Cross variable {varname} is not a boolean.')
769
770 # TODO: we really need a protocol for this,
771 #
772 # class StrProto(typing.Protocol):
773 # def __str__(self) -> str: ...
774 fargs: T.Dict[str, T.Union[str, bool, int]] = {'prefix': prefix, 'func': funcname}
775
776 # glibc defines functions that are not available on Linux as stubs that
777 # fail with ENOSYS (such as e.g. lchmod). In this case we want to fail
778 # instead of detecting the stub as a valid symbol.
779 # We already included limits.h earlier to ensure that these are defined
780 # for stub functions.
781 stubs_fail = '''
782 #if defined __stub_{func} || defined __stub___{func}
783 fail fail fail this function is not going to work
784 #endif
785 '''
786
787 # If we have any includes in the prefix supplied by the user, assume
788 # that the user wants us to use the symbol prototype defined in those
789 # includes. If not, then try to do the Autoconf-style check with
790 # a dummy prototype definition of our own.
791 # This is needed when the linker determines symbol availability from an
792 # SDK based on the prototype in the header provided by the SDK.
793 # Ignoring this prototype would result in the symbol always being
794 # marked as available.
795 if '#include' in prefix:
796 head, main = self._have_prototype_templ()
797 else:
798 head, main = self._no_prototype_templ()
799 templ = head + stubs_fail + main
800
801 res, cached = self.links(templ.format(**fargs), extra_args=extra_args,
802 dependencies=dependencies)
803 if res:
804 return True, cached
805
806 # MSVC does not have compiler __builtin_-s.
807 if self.get_id() in {'msvc', 'intel-cl'}:
808 return False, False
809
810 # Detect function as a built-in
811 #
812 # Some functions like alloca() are defined as compiler built-ins which
813 # are inlined by the compiler and you can't take their address, so we
814 # need to look for them differently. On nice compilers like clang, we
815 # can just directly use the __has_builtin() macro.
816 fargs['no_includes'] = '#include' not in prefix
817 is_builtin = funcname.startswith('__builtin_')
818 fargs['is_builtin'] = is_builtin
819 fargs['__builtin_'] = '' if is_builtin else '__builtin_'
820 t = '''{prefix}
821 int main(void) {{
822
823 /* With some toolchains (MSYS2/mingw for example) the compiler
824 * provides various builtins which are not really implemented and
825 * fall back to the stdlib where they aren't provided and fail at
826 * build/link time. In case the user provides a header, including
827 * the header didn't lead to the function being defined, and the
828 * function we are checking isn't a builtin itself we assume the
829 * builtin is not functional and we just error out. */
830 #if !{no_includes:d} && !defined({func}) && !{is_builtin:d}
831 #error "No definition for {__builtin_}{func} found in the prefix"
832 #endif
833
834 #ifdef __has_builtin
835 #if !__has_builtin({__builtin_}{func})
836 #error "{__builtin_}{func} not found"
837 #endif
838 #elif ! defined({func})
839 {__builtin_}{func};
840 #endif
841 return 0;
842 }}'''
843 return self.links(t.format(**fargs), extra_args=extra_args,
844 dependencies=dependencies)
845
846 def has_members(self, typename: str, membernames: T.List[str], prefix: str, *,
847 extra_args: T.Union[None, T.List[str], T.Callable[[CompileCheckMode], T.List[str]]] = None,
848 dependencies: T.Optional[T.List['Dependency']] = None) -> T.Tuple[bool, bool]:
849 if extra_args is None:
850 extra_args = []
851 # Create code that accesses all members
852 members = ''.join(f'(void) ( foo.{member} );\n' for member in membernames)
853 t = f'''{prefix}
854 void bar(void) {{
855 {typename} foo;
856 {members}
857 (void) foo;
858 }}'''
859 return self.compiles(t, extra_args=extra_args, dependencies=dependencies)
860
861 def has_type(self, typename: str, prefix: str,
862 extra_args: T.Union[T.List[str], T.Callable[[CompileCheckMode], T.List[str]]], *,
863 dependencies: T.Optional[T.List['Dependency']] = None) -> T.Tuple[bool, bool]:
864 t = f'''{prefix}
865 void bar(void) {{
866 (void) sizeof({typename});
867 }}'''
868 return self.compiles(t, extra_args=extra_args, dependencies=dependencies)
869
870 def _symbols_have_underscore_prefix_searchbin(self) -> bool:
871 '''
872 Check if symbols have underscore prefix by compiling a small test binary
873 and then searching the binary for the string,
874 '''
875 symbol_name = b'meson_uscore_prefix'
876 code = '''#ifdef __cplusplus
877 extern "C" {
878 #endif
879 void ''' + symbol_name.decode() + ''' (void) {}
880 #ifdef __cplusplus
881 }
882 #endif
883 '''
884 args = self.get_compiler_check_args(CompileCheckMode.COMPILE)
885 n = '_symbols_have_underscore_prefix_searchbin'
886 with self._build_wrapper(code, extra_args=args, mode=CompileCheckMode.COMPILE, want_output=True) as p:
887 if p.returncode != 0:
888 raise RuntimeError(f'BUG: Unable to compile {n!r} check: {p.stderr}')
889 if not os.path.isfile(p.output_name):
890 raise RuntimeError(f'BUG: Can\'t find compiled test code for {n!r} check')
891 with open(p.output_name, 'rb') as o:
892 for line in o:
893 # Check if the underscore form of the symbol is somewhere
894 # in the output file.
895 if b'_' + symbol_name in line:
896 mlog.debug("Underscore prefix check found prefixed function in binary")
897 return True
898 # Else, check if the non-underscored form is present
899 elif symbol_name in line:
900 mlog.debug("Underscore prefix check found non-prefixed function in binary")
901 return False
902 raise RuntimeError(f'BUG: {n!r} check did not find symbol string in binary')
903
904 def _symbols_have_underscore_prefix_define(self) -> T.Optional[bool]:
905 '''
906 Check if symbols have underscore prefix by querying the
907 __USER_LABEL_PREFIX__ define that most compilers provide
908 for this. Return if functions have underscore prefix or None
909 if it was not possible to determine, like when the compiler
910 does not set the define or the define has an unexpected value.
911 '''
912 delim = '"MESON_HAVE_UNDERSCORE_DELIMITER" '
913 code = f'''
914 #ifndef __USER_LABEL_PREFIX__
915 #define MESON_UNDERSCORE_PREFIX unsupported
916 #else
917 #define MESON_UNDERSCORE_PREFIX __USER_LABEL_PREFIX__
918 #endif
919 {delim}MESON_UNDERSCORE_PREFIX
920 '''
921 with self._build_wrapper(code, mode=CompileCheckMode.PREPROCESS, want_output=False) as p:
922 if p.returncode != 0:
923 raise RuntimeError(f'BUG: Unable to preprocess _symbols_have_underscore_prefix_define check: {p.stdout}')
924 symbol_prefix = p.stdout.partition(delim)[-1].rstrip()
925
926 mlog.debug(f'Queried compiler for function prefix: __USER_LABEL_PREFIX__ is "{symbol_prefix!s}"')
927 if symbol_prefix == '_':
928 return True
929 elif symbol_prefix == '':
930 return False
931 else:
932 return None
933
934 def _symbols_have_underscore_prefix_list(self) -> T.Optional[bool]:
935 '''
936 Check if symbols have underscore prefix by consulting a hardcoded
937 list of cases where we know the results.
938 Return if functions have underscore prefix or None if unknown.
939 '''
940 # Darwin always uses the underscore prefix, not matter what
941 if self.info.is_darwin():
942 return True
943 # Windows uses the underscore prefix on x86 (32bit) only
944 if self.info.is_windows() or self.info.is_cygwin():
945 return self.info.cpu_family == 'x86'
946 return None
947
948 def symbols_have_underscore_prefix(self) -> bool:
949 '''
950 Check if the compiler prefixes an underscore to global C symbols
951 '''
952 # First, try to query the compiler directly
953 result = self._symbols_have_underscore_prefix_define()
954 if result is not None:
955 return result
956
957 # Else, try to consult a hardcoded list of cases we know
958 # absolutely have an underscore prefix
959 result = self._symbols_have_underscore_prefix_list()
960 if result is not None:
961 return result
962
963 # As a last resort, try search in a compiled binary, which is the
964 # most unreliable way of checking this, see #5482
965 return self._symbols_have_underscore_prefix_searchbin()
966
967 def _get_patterns(self, prefixes: T.List[str], suffixes: T.List[str], shared: bool = False) -> T.List[str]:
968 patterns: T.List[str] = []
969 if self.info.is_os2():
970 # On OS/2, search order for shared libs is
971 # 1. libfoo_dll.a
972 # 2. foo_dll.a
973 # 3. libfoo.a
974 # 4. foo.a
975 # 5. foo.dll
976 # For static libs, `_s' is used instead of `_dll'.
977 for s in suffixes:
978 dot = '' if s.startswith(('_dll.', '_s.')) else '.'
979 for p in prefixes:
980 patterns.append(p + '{}' + dot + s)
981 return patterns
982 for p in prefixes:
983 for s in suffixes:
984 patterns.append(p + '{}.' + s)
985 if shared and self.info.is_openbsd():
986 # Shared libraries on OpenBSD can be named libfoo.so.X.Y:
987 # https://www.openbsd.org/faq/ports/specialtopics.html#SharedLibs
988 #
989 # This globbing is probably the best matching we can do since regex
990 # is expensive. It's wrong in many edge cases, but it will match
991 # correctly-named libraries and hopefully no one on OpenBSD names
992 # their files libfoo.so.9a.7b.1.0
993 for p in prefixes:
994 patterns.append(p + '{}.so.[0-9]*.[0-9]*')
995 return patterns
996
997 def get_library_naming(self, libtype: LibType, strict: bool = False) -> T.Tuple[str, ...]:
998 '''
999 Get library prefixes and suffixes for the target platform ordered by
1000 priority
1001 '''
1002 stlibext = ['a']
1003 # We've always allowed libname to be both `foo` and `libfoo`, and now
1004 # people depend on it. Also, some people use prebuilt `foo.so` instead
1005 # of `libfoo.so` for unknown reasons, and may also want to create
1006 # `foo.so` by setting name_prefix to ''
1007 # lib prefix is not usually used with msvc and OS/2
1008 if strict and not isinstance(self, VisualStudioLikeCompiler) and not self.info.is_os2():
1009 prefixes = ['lib']
1010 else:
1011 prefixes = ['lib', '']
1012 # Library suffixes and prefixes
1013 if self.info.is_darwin():
1014 shlibext = ['dylib', 'so']
1015 elif self.info.is_windows():
1016 # FIXME: .lib files can be import or static so we should read the
1017 # file, figure out which one it is, and reject the wrong kind.
1018 if isinstance(self, VisualStudioLikeCompiler):
1019 shlibext = ['lib']
1020 else:
1021 shlibext = ['dll.a', 'lib', 'dll']
1022 # Yep, static libraries can also be foo.lib
1023 stlibext += ['lib']
1024 elif self.info.is_cygwin():
1025 shlibext = ['dll', 'dll.a']
1026 prefixes = ['cyg'] + prefixes
1027 elif self.id.lower() in {'c6000', 'c2000', 'ti'}:
1028 # TI C28x compilers can use both extensions for static or dynamic libs.
1029 stlibext = ['a', 'lib']
1030 shlibext = ['dll', 'so']
1031 elif self.info.is_os2():
1032 stlibext = ['_s.lib', '_s.a', 'lib', 'a']
1033 shlibext = ['_dll.lib', '_dll.a', 'lib', 'a', 'dll']
1034 else:
1035 # Linux/BSDs
1036 shlibext = ['so']
1037 # Search priority
1038 if libtype is LibType.PREFER_SHARED:
1039 patterns = self._get_patterns(prefixes, shlibext, True)
1040 patterns.extend([x for x in self._get_patterns(prefixes, stlibext, False) if x not in patterns])
1041 elif libtype is LibType.PREFER_STATIC:
1042 patterns = self._get_patterns(prefixes, stlibext, False)
1043 patterns.extend([x for x in self._get_patterns(prefixes, shlibext, True) if x not in patterns])
1044 elif libtype is LibType.SHARED:
1045 patterns = self._get_patterns(prefixes, shlibext, True)
1046 else:
1047 assert libtype is LibType.STATIC
1048 patterns = self._get_patterns(prefixes, stlibext, False)
1049 return tuple(patterns)
1050
1051 @staticmethod
1052 def _sort_shlibs_openbsd(libs: T.List[str]) -> T.List[str]:
1053 def tuple_key(x: str) -> T.Tuple[int, ...]:
1054 ver = x.rsplit('.so.', maxsplit=1)[1]
1055 return tuple(int(i) for i in ver.split('.'))
1056
1057 filtered: T.List[str] = []
1058 for lib in libs:
1059 # Validate file as a shared library of type libfoo.so.X.Y
1060 ret = lib.rsplit('.so.', maxsplit=1)
1061 if len(ret) != 2:
1062 continue
1063 try:
1064 tuple(int(i) for i in ret[1].split('.'))
1065 except ValueError:
1066 continue
1067 filtered.append(lib)
1068 return sorted(filtered, key=tuple_key, reverse=True)
1069
1070 @classmethod
1071 def _get_trials_from_pattern(cls, pattern: str, directory: str, libname: str) -> T.List[str]:
1072 f = os.path.join(directory, pattern.format(libname))
1073 # Globbing for OpenBSD
1074 if '*' in pattern:
1075 # NOTE: globbing matches directories and broken symlinks
1076 # so we have to do an isfile test on it later
1077 return cls._sort_shlibs_openbsd(glob.glob(f))
1078 return [f]
1079
1080 @staticmethod
1081 def _get_file_from_list(env: Environment, paths: T.List[str]) -> T.Optional[Path]:
1082 '''
1083 Check whether the library exists by filename. On macOS, we also
1084 check if the library matches our target architecture.
1085 '''
1086 for p in paths:
1087 if os.path.isfile(p):
1088
1089 if env.machines.host.is_darwin() and env.machines.build.is_darwin():
1090 # Run `lipo` and check if the library supports the arch we want
1091 archs = mesonlib.darwin_get_object_archs(p)
1092 if not archs or env.machines.host.cpu_family not in archs:
1093 mlog.debug(f'Rejected {p}, supports {archs} but need {env.machines.host.cpu_family}')
1094 continue
1095
1096 return Path(p)
1097
1098 return None
1099
1100 @functools.lru_cache()
1101 def output_is_64bit(self) -> bool:
1102 '''
1103 returns true if the output produced is 64-bit, false if 32-bit
1104 '''
1105 return self.sizeof('void *', '')[0] == 8
1106
1107 def _find_library_real(self, libname: str, extra_dirs: T.List[str], code: str, libtype: LibType,
1108 lib_prefix_warning: bool, ignore_system_dirs: bool,
1109 skip_link_check: bool = False) -> T.Optional[T.List[str]]:
1110 # First try if we can just add the library as -l.
1111 # Gcc + co seem to prefer builtin lib dirs to -L dirs.
1112 # Only try to find std libs if no extra dirs specified.
1113 # The built-in search procedure will always favour .so and then always
1114 # search for .a. This is only allowed if libtype is LibType.PREFER_SHARED
1115 if ((not extra_dirs and libtype is LibType.PREFER_SHARED) or
1116 libname in self.internal_libs):
1117 cargs = ['-l' + libname]
1118 largs = self.get_linker_always_args() + self.get_allow_undefined_link_args()
1119 extra_args = cargs + self.linker_to_compiler_args(largs)
1120
1121 if self.links(code, extra_args=extra_args, disable_cache=True)[0]:
1122 return cargs
1123 # Don't do a manual search for internal libs
1124 if libname in self.internal_libs:
1125 return None
1126 # Not found or we want to use a specific libtype? Try to find the
1127 # library file itself.
1128 patterns = self.get_library_naming(libtype)
1129 # try to detect if we are 64-bit or 32-bit. If we can't
1130 # detect, we will just skip path validity checks done in
1131 # get_library_dirs() call
1132 try:
1133 if self.output_is_64bit():
1134 elf_class = 2
1135 else:
1136 elf_class = 1
1137 except (mesonlib.MesonException, KeyError): # TODO evaluate if catching KeyError is wanted here
1138 elf_class = 0
1139 # Search in the specified dirs, and then in the system libraries
1140 largs = self.get_linker_always_args() + self.get_allow_undefined_link_args()
1141 lcargs = self.linker_to_compiler_args(largs)
1142 for d in itertools.chain(extra_dirs, [] if ignore_system_dirs else self.get_library_dirs(elf_class)):
1143 for p in patterns:
1144 trials = self._get_trials_from_pattern(p, d, libname)
1145 if not trials:
1146 continue
1147
1148 trial_result = ""
1149 for trial in trials:
1150 if not os.path.isfile(trial):
1151 continue
1152 # When skip_link_check is True (e.g. for pkg-config
1153 # libraries which are trusted to be linkable), skip the
1154 # potentially expensive link check and just verify that the
1155 # file exists.
1156 extra_args = [trial] + lcargs
1157 if skip_link_check or self.links(code, extra_args=extra_args, disable_cache=True)[0]:
1158 trial_result = trial
1159 break
1160
1161 if not trial_result:
1162 continue
1163 if libname.startswith('lib') and trial_result.startswith(libname) and lib_prefix_warning:
1164 mlog.warning(f'find_library({libname!r}) starting in "lib" only works by accident and is not portable')
1165 return [Path(trial_result).as_posix()]
1166 return None
1167
1168 def _find_library_impl(self, libname: str, extra_dirs: T.List[str], code: str, libtype: LibType,
1169 lib_prefix_warning: bool, ignore_system_dirs: bool,
1170 skip_link_check: bool = False) -> T.Optional[T.List[str]]:
1171 # These libraries are either built-in or invalid
1172 if libname in self.ignore_libs:
1173 return []
1174 if isinstance(extra_dirs, str):
1175 extra_dirs = [extra_dirs]
1176 key = (tuple(self.exelist), libname, tuple(extra_dirs), code, libtype, ignore_system_dirs, skip_link_check)
1177 if key not in self.find_library_cache:
1178 value = self._find_library_real(libname, extra_dirs, code, libtype, lib_prefix_warning, ignore_system_dirs, skip_link_check)
1179 self.find_library_cache[key] = value
1180 else:
1181 value = self.find_library_cache[key]
1182 if value is None:
1183 return None
1184 return value.copy()
1185
1186 def find_library(self, libname: str, extra_dirs: T.List[str], libtype: LibType = LibType.PREFER_SHARED,
1187 lib_prefix_warning: bool = True, ignore_system_dirs: bool = False,
1188 skip_link_check: bool = False) -> T.Optional[T.List[str]]:
1189 code = 'int main(void) { return 0; }\n'
1190 return self._find_library_impl(libname, extra_dirs, code, libtype, lib_prefix_warning, ignore_system_dirs, skip_link_check)
1191
1192 def find_framework_paths(self) -> T.List[str]:
1193 '''
1194 These are usually /Library/Frameworks and /System/Library/Frameworks,
1195 unless you select a particular macOS SDK with the -isysroot flag.
1196 You can also add to this by setting -F in CFLAGS.
1197 '''
1198 # TODO: this really needs to be *AppleClang*, not just any clang.
1199 if self.id != 'clang':
1200 raise mesonlib.MesonException('Cannot find framework path with non-clang compiler')
1201 # Construct the compiler command-line
1202 commands = self.get_exelist(ccache=False) + ['-v', '-E', '-']
1203 commands += self.get_always_args()
1204 # Add CFLAGS/CXXFLAGS/OBJCFLAGS/OBJCXXFLAGS from the env
1205 commands += self.environment.coredata.get_external_args(self.for_machine, self.language)
1206 mlog.debug('Finding framework path by running: ', ' '.join(commands), '\n')
1207 os_env = os.environ.copy()
1208 os_env['LC_ALL'] = 'C'
1209 _, _, stde = mesonlib.Popen_safe(commands, env=os_env, stdin=subprocess.PIPE)
1210 paths: T.List[str] = []
1211 for line in stde.split('\n'):
1212 if '(framework directory)' not in line:
1213 continue
1214 # line is of the form:
1215 # ` /path/to/framework (framework directory)`
1216 paths.append(line[:-21].strip())
1217 return paths
1218
1219 def _find_framework_real(self, name: str, extra_dirs: T.List[str], allow_system: bool) -> T.Optional[T.List[str]]:
1220 code = 'int main(void) { return 0; }'
1221 link_args: T.List[str] = []
1222 for d in extra_dirs:
1223 link_args += ['-F' + d]
1224 # We can pass -Z to disable searching in the system frameworks, but
1225 # then we must also pass -L/usr/lib to pick up libSystem.dylib
1226 extra_args = [] if allow_system else ['-Z', '-L/usr/lib']
1227 link_args += ['-framework', name]
1228 if self.links(code, extra_args=(extra_args + link_args), disable_cache=True)[0]:
1229 return link_args
1230 return None
1231
1232 def _find_framework_impl(self, name: str, extra_dirs: T.List[str],
1233 allow_system: bool) -> T.Optional[T.List[str]]:
1234 if isinstance(extra_dirs, str):
1235 extra_dirs = [extra_dirs]
1236 key = (tuple(self.exelist), name, tuple(extra_dirs), allow_system)
1237 if key in self.find_framework_cache:
1238 value = self.find_framework_cache[key]
1239 else:
1240 value = self._find_framework_real(name, extra_dirs, allow_system)
1241 self.find_framework_cache[key] = value
1242 if value is None:
1243 return None
1244 return value.copy()
1245
1246 def find_framework(self, name: str, extra_dirs: T.List[str],
1247 allow_system: bool = True) -> T.Optional[T.List[str]]:
1248 '''
1249 Finds the framework with the specified name, and returns link args for
1250 the same or returns None when the framework is not found.
1251 '''
1252 # TODO: should probably check for macOS?
1253 return self._find_framework_impl(name, extra_dirs, allow_system)
1254
1255 def get_crt_compile_args(self, crt_val: str) -> T.List[str]:
1256 # TODO: does this belong here or in GnuLike or maybe PosixLike?
1257 return []
1258
1259 def get_crt_link_args(self, crt_val: str) -> T.List[str]:
1260 # TODO: does this belong here or in GnuLike or maybe PosixLike?
1261 return []
1262
1263 def thread_flags(self) -> T.List[str]:
1264 # TODO: does this belong here or in GnuLike or maybe PosixLike?
1265 if self.info.is_haiku() or self.info.is_darwin():
1266 return []
1267 if self.info.is_os2():
1268 return ['-lpthread']
1269 return ['-pthread']
1270
1271 def linker_to_compiler_args(self, args: T.List[str]) -> T.List[str]:
1272 return args.copy()
1273
1274 def has_arguments(self, args: T.List[str], code: str,
1275 mode: CompileCheckMode) -> T.Tuple[bool, bool]:
1276 return self.compiles(code, extra_args=args, mode=mode)
1277
1278 def _has_multi_arguments(self, args: T.List[str], code: str) -> T.Tuple[bool, bool]:
1279 new_args: T.List[str] = []
1280 for arg in args:
1281 # some compilers, e.g. GCC, don't warn for unsupported warning-disable
1282 # flags, so when we are testing a flag like "-Wno-forgotten-towel", also
1283 # check the equivalent enable flag too "-Wforgotten-towel".
1284 if arg.startswith('-Wno-'):
1285 # Make an exception for -Wno-attributes=x as -Wattributes=x is invalid
1286 # for GCC at least. Also, the positive form of some flags require a
1287 # value to be specified, i.e. we need to pass -Wfoo=N rather than just
1288 # -Wfoo.
1289 if arg.startswith('-Wno-attributes='):
1290 pass
1291 elif arg in {'-Wno-alloc-size-larger-than',
1292 '-Wno-alloca-larger-than',
1293 '-Wno-frame-larger-than',
1294 '-Wno-stack-usage',
1295 '-Wno-vla-larger-than'}:
1296 # Pass an arbitrary value to the enabling flag; since the test program
1297 # is trivial, it is unlikely to provoke any of these warnings.
1298 new_args.append('-W' + arg[5:] + '=1000')
1299 else:
1300 new_args.append('-W' + arg[5:])
1301 if arg.startswith('-Wl,'):
1302 mlog.warning(f'{arg} looks like a linker argument, '
1303 'but has_argument and other similar methods only '
1304 'support checking compiler arguments. Using them '
1305 'to check linker arguments are never supported, '
1306 'and results are likely to be wrong regardless of '
1307 'the compiler you are using. has_link_argument or '
1308 'other similar method can be used instead.')
1309 new_args.append(arg)
1310 return self.has_arguments(new_args, code, mode=CompileCheckMode.COMPILE)
1311
1312 def has_multi_arguments(self, args: T.List[str]) -> T.Tuple[bool, bool]:
1313 return self._has_multi_arguments(args, 'extern int i;\nint i;\n')
1314
1315 def _has_multi_link_arguments(self, args: T.List[str], code: str) -> T.Tuple[bool, bool]:
1316 args = self.linker.fatal_warnings() + args
1317 args = self.linker_to_compiler_args(args)
1318 return self.has_arguments(args, code, mode=CompileCheckMode.LINK)
1319
1320 def has_multi_link_arguments(self, args: T.List[str], to_host_args: bool = True) -> T.Tuple[bool, bool]:
1321 return self._has_multi_link_arguments(args, 'int main(void) { return 0; }\n')
1322
1323 @staticmethod
1324 def _concatenate_string_literals(s: str) -> str:
1325 pattern = re.compile(r'(?P<pre>.*([^\\]")|^")(?P<str1>([^\\"]|\\.)*)"\s+"(?P<str2>([^\\"]|\\.)*)(?P<post>".*)')
1326 ret = s
1327 m = pattern.match(ret)
1328 while m:
1329 ret = ''.join(m.group('pre', 'str1', 'str2', 'post'))
1330 m = pattern.match(ret)
1331 return ret
1332
1333 def get_has_func_attribute_extra_args(self, name: str) -> T.List[str]:
1334 # Most compilers (such as GCC and Clang) only warn about unknown or
1335 # ignored attributes, so force an error. Overridden in GCC and Clang
1336 # mixins.
1337 return ['-Werror']
1338
1339 def has_func_attribute(self, name: str) -> T.Tuple[bool, bool]:
1340 # Just assume that if we're not on windows that dllimport and dllexport
1341 # don't work
1342 if not (self.info.is_windows() or self.info.is_cygwin()):
1343 if name in {'dllimport', 'dllexport'}:
1344 return False, False
1345
1346 return self.compiles(self.attribute_check_func(name),
1347 extra_args=self.get_has_func_attribute_extra_args(name))
1348
1349 def get_assert_args(self, disable: bool) -> T.List[str]:
1350 if disable:
1351 return ['-DNDEBUG']
1352 return []
1353
1354 @functools.lru_cache(maxsize=None)
1355 def can_compile(self, src: 'mesonlib.FileOrString') -> bool:
1356 # Files we preprocess can be anything, e.g. .in
1357 if self.mode == 'PREPROCESSOR':
1358 return True
1359 return super().can_compile(src)
1360
1361 def get_preprocessor(self) -> Compiler:
1362 if not self.preprocessor:
1363 self.preprocessor = copy.copy(self)
1364 self.preprocessor.exelist = self.exelist + self.get_preprocess_to_file_args()
1365 self.preprocessor.mode = 'PREPROCESSOR'
1366 self.modes.append(self.preprocessor)
1367 return self.preprocessor