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_mode(self) -> CompileCheckMode:
280 # Cross-compiling is hard. For example, you might need -nostdlib, or to pass --target, etc.
281 if self.is_cross and not self.environment.has_exe_wrapper():
282 return CompileCheckMode.COMPILE
283 return CompileCheckMode.LINK
284
285 def _sanity_check_compile_args(self, sourcename: str, binname: str
286 ) -> T.Tuple[T.List[str], T.List[str]]:
287 # _get_basic_compiler_args() already adds c_args/c_link_args (or
288 # similar). Calling super()._sanity_check_compile_args() would
289 # duplicate them and, for MSVC-like compilers, place the link
290 # arguments before the /link that linker_to_compiler_args() inserts.
291 mode = self._sanity_check_mode()
292 b_cargs, b_largs = self._get_basic_compiler_args(mode)
293 cargs = self.exelist_no_ccache + self.get_output_args(binname) + [sourcename] + b_cargs
294 if mode is CompileCheckMode.COMPILE:
295 # We aren't linking in this invocation (and can't run the result
296 # without an exe wrapper anyway), so don't pass any link-only
297 # arguments to a compile-only command. Some compilers add fixed
298 # flags (e.g. MSVC-style compilers always prepend /link) even
299 # when there is nothing to link, which would otherwise end up
300 # unused/misplaced in a compile-only invocation.
301 return cargs, []
302
303 largs = self.linker_to_compiler_args(b_largs)
304 return cargs, largs
305
306 def check_header(self, hname: str, prefix: str, *,
307 extra_args: T.Union[None, T.List[str], T.Callable[['CompileCheckMode'], T.List[str]]] = None,
308 dependencies: T.Optional[T.List['Dependency']] = None) -> T.Tuple[bool, bool]:
309 code = f'''{prefix}
310 #include <{hname}>'''
311 return self.compiles(code, extra_args=extra_args, dependencies=dependencies)
312
313 def has_header(self, hname: str, prefix: str, *,
314 extra_args: T.Union[None, T.List[str], T.Callable[['CompileCheckMode'], T.List[str]]] = None,
315 dependencies: T.Optional[T.List['Dependency']] = None,
316 disable_cache: bool = False) -> T.Tuple[bool, bool]:
317 code = f'''{prefix}
318 #ifdef __has_include
319 #if !__has_include("{hname}")
320 #error "Header '{hname}' could not be found"
321 #endif
322 #else
323 #include <{hname}>
324 #endif'''
325 return self.compiles(code, extra_args=extra_args,
326 dependencies=dependencies, mode=CompileCheckMode.PREPROCESS, disable_cache=disable_cache)
327
328 def has_header_symbol(self, hname: str, symbol: str, prefix: str, *,
329 extra_args: T.Union[None, T.List[str], T.Callable[[CompileCheckMode], T.List[str]]] = None,
330 dependencies: T.Optional[T.List['Dependency']] = None) -> T.Tuple[bool, bool]:
331 t = f'''{prefix}
332 #include <{hname}>
333 int main(void) {{
334 /* If it's not defined as a macro, try to use as a symbol */
335 #ifndef {symbol}
336 {symbol};
337 #endif
338 return 0;
339 }}'''
340 return self.compiles(t, extra_args=extra_args,
341 dependencies=dependencies)
342
343 def _get_basic_compiler_args(self, mode: CompileCheckMode) -> T.Tuple[T.List[str], T.List[str]]:
344 cargs: T.List[str] = []
345 largs: T.List[str] = []
346 if mode is CompileCheckMode.LINK:
347 # Sometimes we need to manually select the CRT to use with MSVC.
348 # One example is when trying to do a compiler check that involves
349 # linking with static libraries since MSVC won't select a CRT for
350 # us in that case and will error out asking us to pick one.
351 try:
352 crt_val = self.environment.coredata.optstore.get_value_for('b_vscrt')
353 assert isinstance(crt_val, str), 'for mypy'
354 cargs += self.get_crt_compile_args(crt_val)
355 largs += self.get_crt_link_args(crt_val)
356 except (KeyError, AttributeError):
357 pass
358
359 # Add CFLAGS/CXXFLAGS/OBJCFLAGS/OBJCXXFLAGS and CPPFLAGS from the env
360 sys_args = self.get_external_compile_args()
361 # Apparently it is a thing to inject linker flags both
362 # via CFLAGS _and_ LDFLAGS, even though the former are
363 # also used during linking. These flags can break
364 # argument checks. Thanks, Autotools.
365 cleaned_sys_args = self.remove_linkerlike_args(sys_args)
366 cargs += cleaned_sys_args
367
368 if mode is CompileCheckMode.LINK:
369 largs += self.get_linker_always_args()
370
371 ld_value = self.environment.lookup_binary_entry(self.for_machine, self.language + '_ld')
372 if ld_value is not None:
373 cargs += self.use_linker_args(ld_value[0], self.version)
374
375 # Add LDFLAGS from the env
376 sys_ld_args = self.get_external_link_args()
377 # CFLAGS and CXXFLAGS go to both linking and compiling, but we want them
378 # to only appear on the command line once. Remove dupes.
379 largs += [x for x in sys_ld_args if x not in cleaned_sys_args]
380
381 cargs += self.get_compiler_args_for_mode(mode)
382 return cargs, largs
383
384 def build_wrapper_args(self,
385 extra_args: T.Union[None, arglist.CompilerArgs, T.List[str], T.Callable[[CompileCheckMode], T.List[str]]],
386 dependencies: T.Optional[T.List['Dependency']],
387 mode: CompileCheckMode = CompileCheckMode.COMPILE) -> arglist.CompilerArgs:
388 # TODO: the caller should handle the listing of these arguments
389 if extra_args is None:
390 extra_args = []
391 else:
392 # TODO: we want to do this in the caller
393 extra_args = mesonlib.listify(extra_args)
394 extra_args = mesonlib.listify([e(mode) if callable(e) else e for e in extra_args])
395
396 if dependencies is None:
397 dependencies = []
398 elif not isinstance(dependencies, collections.abc.Iterable):
399 # TODO: we want to ensure the front end does the listifing here
400 dependencies = [dependencies]
401 # Collect compiler arguments
402 cargs: arglist.CompilerArgs = self.compiler_args()
403 largs: T.List[str] = []
404 for d in dependencies:
405 # Add compile flags needed by dependencies
406 cargs += d.get_compile_args()
407 system_incdir = d.get_include_type() == 'system'
408 for i in d.get_include_dirs():
409 for idir in i.abs_string_list(self.environment.get_source_dir(), self.environment.get_build_dir()):
410 cargs.extend(self.get_include_args(idir, system_incdir))
411 if mode is CompileCheckMode.LINK:
412 # Add link flags needed to find dependencies
413 largs += d.get_link_args()
414
415 ca, la = self._get_basic_compiler_args(mode)
416 cargs += ca
417
418 cargs += self.get_compiler_check_args(mode)
419
420 # on MSVC compiler and linker flags must be separated by the "/link" argument
421 # at this point, the '/link' argument may already be part of extra_args, otherwise, it is added here
422 largs += [l for l in self.linker_to_compiler_args(la) if l != '/link']
423
424 if self.linker_to_compiler_args([]) == ['/link']:
425 if largs != [] and '/link' not in extra_args:
426 extra_args += ['/link']
427 # all linker flags must be converted now, otherwise the reordering
428 # of arglist will apply and -L flags will be reordered into
429 # breaking form. See arglist._should_prepend
430 largs = self.unix_args_to_native(largs)
431
432 args = cargs + extra_args + largs
433 return args
434
435 def _compile_int(self, expression: str, prefix: str,
436 extra_args: T.Union[None, T.List[str], T.Callable[[CompileCheckMode], T.List[str]]],
437 dependencies: T.Optional[T.List['Dependency']]) -> bool:
438 t = f'''{prefix}
439 #include <stddef.h>
440 int main(void) {{ static int a[1-2*!({expression})]; a[0]=0; return 0; }}'''
441 return self.compiles(t, extra_args=extra_args, dependencies=dependencies)[0]
442
443 def _cross_compute_int(self, expression: str, low: T.Optional[int], high: T.Optional[int],
444 guess: T.Optional[int], prefix: str,
445 extra_args: T.Union[None, T.List[str], T.Callable[[CompileCheckMode], T.List[str]]] = None,
446 dependencies: T.Optional[T.List['Dependency']] = None) -> int:
447 # Try user's guess first
448 if isinstance(guess, int):
449 if self._compile_int(f'{expression} == {guess}', prefix, extra_args, dependencies):
450 return guess
451
452 # Try to expand the expression and evaluate it on the build machines compiler
453 if self.language in self.environment.coredata.compilers.build:
454 try:
455 expanded, _ = self.get_define(expression, prefix, extra_args, dependencies, False)
456 evaluate_expanded = f'''
457 #include <stdio.h>
458 #include <stdint.h>
459 int main(void) {{ int expression = {expanded}; printf("%d", expression); return 0; }}'''
460 run = self.environment.coredata.compilers.build[self.language].run(evaluate_expanded)
461 if run and run.compiled and run.returncode == 0:
462 if self._compile_int(f'{expression} == {run.stdout}', prefix, extra_args, dependencies):
463 return int(run.stdout)
464 except mesonlib.EnvironmentException:
465 pass
466
467 # If no bounds are given, compute them in the limit of int32
468 maxint = 0x7fffffff
469 minint = -0x80000000
470 if not isinstance(low, int) or not isinstance(high, int):
471 if self._compile_int(f'{expression} >= 0', prefix, extra_args, dependencies):
472 low = cur = 0
473 while self._compile_int(f'{expression} > {cur}', prefix, extra_args, dependencies):
474 low = cur + 1
475 if low > maxint:
476 raise mesonlib.EnvironmentException('Cross-compile check overflowed')
477 cur = min(cur * 2 + 1, maxint)
478 high = cur
479 else:
480 high = cur = -1
481 while self._compile_int(f'{expression} < {cur}', prefix, extra_args, dependencies):
482 high = cur - 1
483 if high < minint:
484 raise mesonlib.EnvironmentException('Cross-compile check overflowed')
485 cur = max(cur * 2, minint)
486 low = cur
487 else:
488 # Sanity check limits given by user
489 if high < low:
490 raise mesonlib.EnvironmentException('high limit smaller than low limit')
491 condition = f'{expression} <= {high} && {expression} >= {low}'
492 if not self._compile_int(condition, prefix, extra_args, dependencies):
493 raise mesonlib.EnvironmentException('Value out of given range')
494
495 # Binary search
496 while low != high:
497 cur = low + int((high - low) / 2)
498 if self._compile_int(f'{expression} <= {cur}', prefix, extra_args, dependencies):
499 high = cur
500 else:
501 low = cur + 1
502
503 return low
504
505 def compute_int(self, expression: str, low: T.Optional[int], high: T.Optional[int],
506 guess: T.Optional[int], prefix: str, *,
507 extra_args: T.Union[None, T.List[str], T.Callable[[CompileCheckMode], T.List[str]]],
508 dependencies: T.Optional[T.List['Dependency']] = None) -> int:
509 if extra_args is None:
510 extra_args = []
511 if self.is_cross:
512 return self._cross_compute_int(expression, low, high, guess, prefix, extra_args, dependencies)
513 t = f'''{prefix}
514 #include<stddef.h>
515 #include<stdio.h>
516 int main(void) {{
517 printf("%ld\\n", (long)({expression}));
518 return 0;
519 }}'''
520 res = self.run(t, extra_args=extra_args,
521 dependencies=dependencies)
522 if not res.compiled:
523 return -1
524 if res.returncode != 0:
525 raise mesonlib.EnvironmentException('Could not run compute_int test binary.')
526 return int(res.stdout)
527
528 def _cross_sizeof(self, typename: str, prefix: str, *,
529 extra_args: T.Union[None, T.List[str], T.Callable[[CompileCheckMode], T.List[str]]] = None,
530 dependencies: T.Optional[T.List['Dependency']] = None) -> int:
531 if extra_args is None:
532 extra_args = []
533 t = f'''{prefix}
534 #include <stddef.h>
535 int main(void) {{
536 {typename} something;
537 return 0;
538 }}'''
539 if not self.compiles(t, extra_args=extra_args,
540 dependencies=dependencies)[0]:
541 return -1
542 return self._cross_compute_int(f'sizeof({typename})', None, None, None, prefix, extra_args, dependencies)
543
544 def sizeof(self, typename: str, prefix: str, *,
545 extra_args: T.Union[None, T.List[str], T.Callable[[CompileCheckMode], T.List[str]]] = None,
546 dependencies: T.Optional[T.List['Dependency']] = None) -> T.Tuple[int, bool]:
547 if extra_args is None:
548 extra_args = []
549 if self.is_cross:
550 r = self._cross_sizeof(typename, prefix, extra_args=extra_args,
551 dependencies=dependencies)
552 return r, False
553 t = f'''{prefix}
554 #include<stddef.h>
555 #include<stdio.h>
556 int main(void) {{
557 printf("%ld\\n", (long)(sizeof({typename})));
558 return 0;
559 }}'''
560 res = self.cached_run(t, extra_args=extra_args,
561 dependencies=dependencies)
562 if not res.compiled:
563 return -1, False
564 if res.returncode != 0:
565 raise mesonlib.EnvironmentException('Could not run sizeof test binary.')
566 try:
567 return int(res.stdout), res.cached
568 except ValueError:
569 raise mesonlib.EnvironmentException(
570 f'Could not determine size of {typename}: compiler output was empty or invalid.'
571 )
572
573 def _cross_alignment(self, typename: str, prefix: str, *,
574 extra_args: T.Optional[T.List[str]] = None,
575 dependencies: T.Optional[T.List['Dependency']] = None) -> int:
576 if extra_args is None:
577 extra_args = []
578 t = f'''{prefix}
579 #include <stddef.h>
580 int main(void) {{
581 {typename} something;
582 return 0;
583 }}'''
584 if not self.compiles(t, extra_args=extra_args,
585 dependencies=dependencies)[0]:
586 return -1
587 t = f'''{prefix}
588 #include <stddef.h>
589 struct tmp {{
590 char c;
591 {typename} target;
592 }};'''
593 return self._cross_compute_int('offsetof(struct tmp, target)', None, None, None, t, extra_args, dependencies)
594
595 def alignment(self, typename: str, prefix: str, *,
596 extra_args: T.Optional[T.List[str]] = None,
597 dependencies: T.Optional[T.List['Dependency']] = None) -> T.Tuple[int, bool]:
598 if extra_args is None:
599 extra_args = []
600 if self.is_cross:
601 r = self._cross_alignment(typename, prefix, extra_args=extra_args,
602 dependencies=dependencies)
603 return r, False
604 t = f'''{prefix}
605 #include <stdio.h>
606 #include <stddef.h>
607 struct tmp {{
608 char c;
609 {typename} target;
610 }};
611 int main(void) {{
612 printf("%d", (int)offsetof(struct tmp, target));
613 return 0;
614 }}'''
615 res = self.cached_run(t, extra_args=extra_args,
616 dependencies=dependencies)
617 if not res.compiled:
618 raise mesonlib.EnvironmentException('Could not compile alignment test.')
619 if res.returncode != 0:
620 raise mesonlib.EnvironmentException('Could not run alignment test binary.')
621
622 align: int
623 try:
624 align = int(res.stdout)
625 except ValueError:
626 # If we get here, the user is most likely using a script that is
627 # pretending to be a compiler.
628 raise mesonlib.EnvironmentException('Could not run alignment test binary.')
629 if align == 0:
630 raise mesonlib.EnvironmentException(f'Could not determine alignment of {typename}. Sorry. You might want to file a bug.')
631
632 return align, res.cached
633
634 def get_define(self, dname: str, prefix: str,
635 extra_args: T.Union[T.List[str], T.Callable[[CompileCheckMode], T.List[str]]],
636 dependencies: T.Optional[T.List['Dependency']],
637 disable_cache: bool = False) -> T.Tuple[str, bool]:
638 delim_start = '"MESON_GET_DEFINE_DELIMITER_START"\n'
639 delim_end = '\n"MESON_GET_DEFINE_DELIMITER_END"'
640 sentinel_undef = '"MESON_GET_DEFINE_UNDEFINED_SENTINEL"'
641 code = f'''
642 {prefix}
643 #ifndef {dname}
644 # define {dname} {sentinel_undef}
645 #endif
646 {delim_start}{dname}{delim_end}'''
647 args = self.build_wrapper_args(extra_args, dependencies,
648 mode=CompileCheckMode.PREPROCESS).to_native()
649 func = functools.partial(self.cached_compile, code, extra_args=args, mode=CompileCheckMode.PREPROCESS)
650 if disable_cache:
651 func = functools.partial(self.compile, code, extra_args=args, mode=CompileCheckMode.PREPROCESS)
652 with func() as p:
653 cached = p.cached
654 if p.returncode != 0:
655 raise mesonlib.EnvironmentException(f'Could not get define {dname!r}')
656
657 # Get the preprocessed value between the delimiters
658 star_idx = p.stdout.find(delim_start)
659 end_idx = p.stdout.rfind(delim_end)
660 if (star_idx == -1) or (end_idx == -1) or (star_idx == end_idx):
661 raise mesonlib.MesonBugException('Delimiters not found in preprocessor output.')
662 define_value = p.stdout[star_idx + len(delim_start):end_idx]
663
664 # Due to https://developercommunity.visualstudio.com/t/Inconsistent-whitespace-with-standard-pr/11023343,
665 # MSVC can end up producing an unexpected space after the sentinel_undef
666 # string (if building with -std:c11, and if the test source is written
667 # with unix newlines). To avoid treating this as an actual predefined
668 # macro, look for the buggy value as well.
669 if define_value in {sentinel_undef, sentinel_undef + ' '}:
670 define_value = None
671 else:
672 # Merge string literals
673 define_value = self._concatenate_string_literals(define_value).strip()
674
675 return define_value, cached
676
677 def get_return_value(self, fname: str, rtype: str, prefix: str,
678 extra_args: T.Optional[T.List[str]],
679 dependencies: T.Optional[T.List['Dependency']]) -> T.Union[str, int]:
680 # TODO: rtype should be an enum.
681 # TODO: maybe we can use overload to tell mypy when this will return int vs str?
682 if rtype == 'string':
683 fmt = '%s'
684 cast = '(char*)'
685 elif rtype == 'int':
686 fmt = '%lli'
687 cast = '(long long int)'
688 else:
689 raise AssertionError(f'BUG: Unknown return type {rtype!r}')
690 code = f'''{prefix}
691 #include <stdio.h>
692 int main(void) {{
693 printf ("{fmt}", {cast} {fname}());
694 return 0;
695 }}'''
696 res = self.run(code, extra_args=extra_args, dependencies=dependencies)
697 if not res.compiled:
698 raise mesonlib.EnvironmentException(f'Could not get return value of {fname}()')
699 if rtype == 'string':
700 return res.stdout
701 elif rtype == 'int':
702 try:
703 return int(res.stdout.strip())
704 except ValueError:
705 raise mesonlib.EnvironmentException(f'Return value of {fname}() is not an int')
706 assert False, 'Unreachable'
707
708 @staticmethod
709 def _no_prototype_templ() -> T.Tuple[str, str]:
710 """
711 Try to find the function without a prototype from a header by defining
712 our own dummy prototype and trying to link with the C library (and
713 whatever else the compiler links in by default). This is very similar
714 to the check performed by Autoconf for AC_CHECK_FUNCS.
715 """
716 # Define the symbol to something else since it is defined by the
717 # includes or defines listed by the user or by the compiler. This may
718 # include, for instance _GNU_SOURCE which must be defined before
719 # limits.h, which includes features.h
720 # Then, undef the symbol to get rid of it completely.
721 head = '''
722 #define {func} meson_disable_define_of_{func}
723 {prefix}
724 #include <limits.h>
725 #undef {func}
726 '''
727 # Override any GCC internal prototype and declare our own definition for
728 # the symbol. Use char because that's unlikely to be an actual return
729 # value for a function which ensures that we override the definition.
730 head += '''
731 #ifdef __cplusplus
732 extern "C"
733 #endif
734 char {func} (void);
735 '''
736 # The actual function call
737 main = '''
738 int main(void) {{
739 return {func} ();
740 }}'''
741 return head, main
742
743 @staticmethod
744 def _have_prototype_templ() -> T.Tuple[str, str]:
745 """
746 Returns a head-er and main() call that uses the headers listed by the
747 user for the function prototype while checking if a function exists.
748 """
749 # Add the 'prefix', aka defines, includes, etc that the user provides
750 # This may include, for instance _GNU_SOURCE which must be defined
751 # before limits.h, which includes features.h
752 head = '{prefix}\n#include <limits.h>\n'
753 # We don't know what the function takes or returns, so return it as an int.
754 # Just taking the address or comparing it to void is not enough because
755 # compilers are smart enough to optimize it away. The resulting binary
756 # is not run so we don't care what the return value is.
757 main = '''\nint main(void) {{
758 void *a = (void*) &{func};
759 long long b = (long long) a;
760 return (int) b;
761 }}'''
762 return head, main
763
764 def has_function(self, funcname: str, prefix: str, *,
765 extra_args: T.Optional[T.List[str]] = None,
766 dependencies: T.Optional[T.List['Dependency']] = None) -> T.Tuple[bool, bool]:
767 """Determine if a function exists.
768
769 First, this function looks for the symbol in the default libraries
770 provided by the compiler (stdlib + a few others usually). If that
771 fails, it checks if any of the headers specified in the prefix provide
772 an implementation of the function, and if that fails, it checks if it's
773 implemented as a compiler-builtin.
774 """
775 if extra_args is None:
776 extra_args = []
777
778 # Short-circuit if the check is already provided by the cross-info file
779 varname = 'has function ' + funcname
780 varname = varname.replace(' ', '_')
781 if self.is_cross:
782 val = self.environment.properties.host.get(varname, None)
783 if val is not None:
784 if isinstance(val, bool):
785 return val, False
786 raise mesonlib.EnvironmentException(f'Cross variable {varname} is not a boolean.')
787
788 # TODO: we really need a protocol for this,
789 #
790 # class StrProto(typing.Protocol):
791 # def __str__(self) -> str: ...
792 fargs: T.Dict[str, T.Union[str, bool, int]] = {'prefix': prefix, 'func': funcname}
793
794 # glibc defines functions that are not available on Linux as stubs that
795 # fail with ENOSYS (such as e.g. lchmod). In this case we want to fail
796 # instead of detecting the stub as a valid symbol.
797 # We already included limits.h earlier to ensure that these are defined
798 # for stub functions.
799 stubs_fail = '''
800 #if defined __stub_{func} || defined __stub___{func}
801 fail fail fail this function is not going to work
802 #endif
803 '''
804
805 # If we have any includes in the prefix supplied by the user, assume
806 # that the user wants us to use the symbol prototype defined in those
807 # includes. If not, then try to do the Autoconf-style check with
808 # a dummy prototype definition of our own.
809 # This is needed when the linker determines symbol availability from an
810 # SDK based on the prototype in the header provided by the SDK.
811 # Ignoring this prototype would result in the symbol always being
812 # marked as available.
813 if '#include' in prefix:
814 head, main = self._have_prototype_templ()
815 else:
816 head, main = self._no_prototype_templ()
817 templ = head + stubs_fail + main
818
819 res, cached = self.links(templ.format(**fargs), extra_args=extra_args,
820 dependencies=dependencies)
821 if res:
822 return True, cached
823
824 # MSVC does not have compiler __builtin_-s.
825 if self.get_id() in {'msvc', 'intel-cl'}:
826 return False, False
827
828 # Detect function as a built-in
829 #
830 # Some functions like alloca() are defined as compiler built-ins which
831 # are inlined by the compiler and you can't take their address, so we
832 # need to look for them differently. On nice compilers like clang, we
833 # can just directly use the __has_builtin() macro.
834 fargs['no_includes'] = '#include' not in prefix
835 is_builtin = funcname.startswith('__builtin_')
836 fargs['is_builtin'] = is_builtin
837 fargs['__builtin_'] = '' if is_builtin else '__builtin_'
838 t = '''{prefix}
839 int main(void) {{
840
841 /* With some toolchains (MSYS2/mingw for example) the compiler
842 * provides various builtins which are not really implemented and
843 * fall back to the stdlib where they aren't provided and fail at
844 * build/link time. In case the user provides a header, including
845 * the header didn't lead to the function being defined, and the
846 * function we are checking isn't a builtin itself we assume the
847 * builtin is not functional and we just error out. */
848 #if !{no_includes:d} && !defined({func}) && !{is_builtin:d}
849 #error "No definition for {__builtin_}{func} found in the prefix"
850 #endif
851
852 #ifdef __has_builtin
853 #if !__has_builtin({__builtin_}{func})
854 #error "{__builtin_}{func} not found"
855 #endif
856 #elif ! defined({func})
857 {__builtin_}{func};
858 #endif
859 return 0;
860 }}'''
861 return self.links(t.format(**fargs), extra_args=extra_args,
862 dependencies=dependencies)
863
864 def has_members(self, typename: str, membernames: T.List[str], prefix: str, *,
865 extra_args: T.Union[None, T.List[str], T.Callable[[CompileCheckMode], T.List[str]]] = None,
866 dependencies: T.Optional[T.List['Dependency']] = None) -> T.Tuple[bool, bool]:
867 if extra_args is None:
868 extra_args = []
869 # Create code that accesses all members
870 members = ''.join(f'(void) ( foo.{member} );\n' for member in membernames)
871 t = f'''{prefix}
872 void bar(void) {{
873 {typename} foo;
874 {members}
875 (void) foo;
876 }}'''
877 return self.compiles(t, extra_args=extra_args, dependencies=dependencies)
878
879 def has_type(self, typename: str, prefix: str,
880 extra_args: T.Union[T.List[str], T.Callable[[CompileCheckMode], T.List[str]]], *,
881 dependencies: T.Optional[T.List['Dependency']] = None) -> T.Tuple[bool, bool]:
882 t = f'''{prefix}
883 void bar(void) {{
884 (void) sizeof({typename});
885 }}'''
886 return self.compiles(t, extra_args=extra_args, dependencies=dependencies)
887
888 def _symbols_have_underscore_prefix_searchbin(self) -> bool:
889 '''
890 Check if symbols have underscore prefix by compiling a small test binary
891 and then searching the binary for the string,
892 '''
893 symbol_name = b'meson_uscore_prefix'
894 code = '''#ifdef __cplusplus
895 extern "C" {
896 #endif
897 void ''' + symbol_name.decode() + ''' (void) {}
898 #ifdef __cplusplus
899 }
900 #endif
901 '''
902 args = self.get_compiler_check_args(CompileCheckMode.COMPILE)
903 n = '_symbols_have_underscore_prefix_searchbin'
904 with self._build_wrapper(code, extra_args=args, mode=CompileCheckMode.COMPILE, want_output=True) as p:
905 if p.returncode != 0:
906 raise RuntimeError(f'BUG: Unable to compile {n!r} check: {p.stderr}')
907 if not os.path.isfile(p.output_name):
908 raise RuntimeError(f'BUG: Can\'t find compiled test code for {n!r} check')
909 with open(p.output_name, 'rb') as o:
910 for line in o:
911 # Check if the underscore form of the symbol is somewhere
912 # in the output file.
913 if b'_' + symbol_name in line:
914 mlog.debug("Underscore prefix check found prefixed function in binary")
915 return True
916 # Else, check if the non-underscored form is present
917 elif symbol_name in line:
918 mlog.debug("Underscore prefix check found non-prefixed function in binary")
919 return False
920 raise RuntimeError(f'BUG: {n!r} check did not find symbol string in binary')
921
922 def _symbols_have_underscore_prefix_define(self) -> T.Optional[bool]:
923 '''
924 Check if symbols have underscore prefix by querying the
925 __USER_LABEL_PREFIX__ define that most compilers provide
926 for this. Return if functions have underscore prefix or None
927 if it was not possible to determine, like when the compiler
928 does not set the define or the define has an unexpected value.
929 '''
930 delim = '"MESON_HAVE_UNDERSCORE_DELIMITER" '
931 code = f'''
932 #ifndef __USER_LABEL_PREFIX__
933 #define MESON_UNDERSCORE_PREFIX unsupported
934 #else
935 #define MESON_UNDERSCORE_PREFIX __USER_LABEL_PREFIX__
936 #endif
937 {delim}MESON_UNDERSCORE_PREFIX
938 '''
939 with self._build_wrapper(code, mode=CompileCheckMode.PREPROCESS, want_output=False) as p:
940 if p.returncode != 0:
941 raise RuntimeError(f'BUG: Unable to preprocess _symbols_have_underscore_prefix_define check: {p.stdout}')
942 symbol_prefix = p.stdout.partition(delim)[-1].rstrip()
943
944 mlog.debug(f'Queried compiler for function prefix: __USER_LABEL_PREFIX__ is "{symbol_prefix!s}"')
945 if symbol_prefix == '_':
946 return True
947 elif symbol_prefix == '':
948 return False
949 else:
950 return None
951
952 def _symbols_have_underscore_prefix_list(self) -> T.Optional[bool]:
953 '''
954 Check if symbols have underscore prefix by consulting a hardcoded
955 list of cases where we know the results.
956 Return if functions have underscore prefix or None if unknown.
957 '''
958 # Darwin always uses the underscore prefix, not matter what
959 if self.info.is_darwin():
960 return True
961 # Windows uses the underscore prefix on x86 (32bit) only
962 if self.info.is_windows() or self.info.is_cygwin():
963 return self.info.cpu_family == 'x86'
964 return None
965
966 def symbols_have_underscore_prefix(self) -> bool:
967 '''
968 Check if the compiler prefixes an underscore to global C symbols
969 '''
970 # First, try to query the compiler directly
971 result = self._symbols_have_underscore_prefix_define()
972 if result is not None:
973 return result
974
975 # Else, try to consult a hardcoded list of cases we know
976 # absolutely have an underscore prefix
977 result = self._symbols_have_underscore_prefix_list()
978 if result is not None:
979 return result
980
981 # As a last resort, try search in a compiled binary, which is the
982 # most unreliable way of checking this, see #5482
983 return self._symbols_have_underscore_prefix_searchbin()
984
985 def _get_patterns(self, prefixes: T.List[str], suffixes: T.List[str], shared: bool = False) -> T.List[str]:
986 patterns: T.List[str] = []
987 if self.info.is_os2():
988 # On OS/2, search order for shared libs is
989 # 1. libfoo_dll.a
990 # 2. foo_dll.a
991 # 3. libfoo.a
992 # 4. foo.a
993 # 5. foo.dll
994 # For static libs, `_s' is used instead of `_dll'.
995 for s in suffixes:
996 dot = '' if s.startswith(('_dll.', '_s.')) else '.'
997 for p in prefixes:
998 patterns.append(p + '{}' + dot + s)
999 return patterns
1000 for p in prefixes:
1001 for s in suffixes:
1002 patterns.append(p + '{}.' + s)
1003 if shared and self.info.is_openbsd():
1004 # Shared libraries on OpenBSD can be named libfoo.so.X.Y:
1005 # https://www.openbsd.org/faq/ports/specialtopics.html#SharedLibs
1006 #
1007 # This globbing is probably the best matching we can do since regex
1008 # is expensive. It's wrong in many edge cases, but it will match
1009 # correctly-named libraries and hopefully no one on OpenBSD names
1010 # their files libfoo.so.9a.7b.1.0
1011 for p in prefixes:
1012 patterns.append(p + '{}.so.[0-9]*.[0-9]*')
1013 return patterns
1014
1015 def get_library_naming(self, libtype: LibType, strict: bool = False) -> T.Tuple[str, ...]:
1016 '''
1017 Get library prefixes and suffixes for the target platform ordered by
1018 priority
1019 '''
1020 stlibext = ['a']
1021 # We've always allowed libname to be both `foo` and `libfoo`, and now
1022 # people depend on it. Also, some people use prebuilt `foo.so` instead
1023 # of `libfoo.so` for unknown reasons, and may also want to create
1024 # `foo.so` by setting name_prefix to ''
1025 # lib prefix is not usually used with msvc and OS/2
1026 if strict and not isinstance(self, VisualStudioLikeCompiler) and not self.info.is_os2():
1027 prefixes = ['lib']
1028 else:
1029 prefixes = ['lib', '']
1030 # Library suffixes and prefixes
1031 if self.info.is_darwin():
1032 shlibext = ['dylib', 'so']
1033 elif self.info.is_windows():
1034 # FIXME: .lib files can be import or static so we should read the
1035 # file, figure out which one it is, and reject the wrong kind.
1036 if isinstance(self, VisualStudioLikeCompiler):
1037 shlibext = ['lib']
1038 else:
1039 shlibext = ['dll.a', 'lib', 'dll']
1040 # Yep, static libraries can also be foo.lib
1041 stlibext += ['lib']
1042 elif self.info.is_cygwin():
1043 shlibext = ['dll', 'dll.a']
1044 prefixes = ['cyg'] + prefixes
1045 elif self.id.lower() in {'c6000', 'c2000', 'ti'}:
1046 # TI C28x compilers can use both extensions for static or dynamic libs.
1047 stlibext = ['a', 'lib']
1048 shlibext = ['dll', 'so']
1049 elif self.info.is_os2():
1050 stlibext = ['_s.lib', '_s.a', 'lib', 'a']
1051 shlibext = ['_dll.lib', '_dll.a', 'lib', 'a', 'dll']
1052 else:
1053 # Linux/BSDs
1054 shlibext = ['so']
1055 # Search priority
1056 if libtype is LibType.PREFER_SHARED:
1057 patterns = self._get_patterns(prefixes, shlibext, True)
1058 patterns.extend([x for x in self._get_patterns(prefixes, stlibext, False) if x not in patterns])
1059 elif libtype is LibType.PREFER_STATIC:
1060 patterns = self._get_patterns(prefixes, stlibext, False)
1061 patterns.extend([x for x in self._get_patterns(prefixes, shlibext, True) if x not in patterns])
1062 elif libtype is LibType.SHARED:
1063 patterns = self._get_patterns(prefixes, shlibext, True)
1064 else:
1065 assert libtype is LibType.STATIC
1066 patterns = self._get_patterns(prefixes, stlibext, False)
1067 return tuple(patterns)
1068
1069 @staticmethod
1070 def _sort_shlibs_openbsd(libs: T.List[str]) -> T.List[str]:
1071 def tuple_key(x: str) -> T.Tuple[int, ...]:
1072 ver = x.rsplit('.so.', maxsplit=1)[1]
1073 return tuple(int(i) for i in ver.split('.'))
1074
1075 filtered: T.List[str] = []
1076 for lib in libs:
1077 # Validate file as a shared library of type libfoo.so.X.Y
1078 ret = lib.rsplit('.so.', maxsplit=1)
1079 if len(ret) != 2:
1080 continue
1081 try:
1082 tuple(int(i) for i in ret[1].split('.'))
1083 except ValueError:
1084 continue
1085 filtered.append(lib)
1086 return sorted(filtered, key=tuple_key, reverse=True)
1087
1088 @classmethod
1089 def _get_trials_from_pattern(cls, pattern: str, directory: str, libname: str) -> T.List[str]:
1090 f = os.path.join(directory, pattern.format(libname))
1091 # Globbing for OpenBSD
1092 if '*' in pattern:
1093 # NOTE: globbing matches directories and broken symlinks
1094 # so we have to do an isfile test on it later
1095 return cls._sort_shlibs_openbsd(glob.glob(f))
1096 return [f]
1097
1098 @staticmethod
1099 def _get_file_from_list(env: Environment, paths: T.List[str]) -> T.Optional[Path]:
1100 '''
1101 Check whether the library exists by filename. On macOS, we also
1102 check if the library matches our target architecture.
1103 '''
1104 for p in paths:
1105 if os.path.isfile(p):
1106
1107 if env.machines.host.is_darwin() and env.machines.build.is_darwin():
1108 # Run `lipo` and check if the library supports the arch we want
1109 archs = mesonlib.darwin_get_object_archs(p)
1110 if not archs or env.machines.host.cpu_family not in archs:
1111 mlog.debug(f'Rejected {p}, supports {archs} but need {env.machines.host.cpu_family}')
1112 continue
1113
1114 return Path(p)
1115
1116 return None
1117
1118 @functools.lru_cache()
1119 def output_is_64bit(self) -> bool:
1120 '''
1121 returns true if the output produced is 64-bit, false if 32-bit
1122 '''
1123 return self.sizeof('void *', '')[0] == 8
1124
1125 def _find_library_real(self, libname: str, extra_dirs: T.List[str], code: str, libtype: LibType,
1126 lib_prefix_warning: bool, ignore_system_dirs: bool,
1127 skip_link_check: bool = False) -> T.Optional[T.List[str]]:
1128 # First try if we can just add the library as -l.
1129 # Gcc + co seem to prefer builtin lib dirs to -L dirs.
1130 # Only try to find std libs if no extra dirs specified.
1131 # The built-in search procedure will always favour .so and then always
1132 # search for .a. This is only allowed if libtype is LibType.PREFER_SHARED
1133 if ((not extra_dirs and libtype is LibType.PREFER_SHARED) or
1134 libname in self.internal_libs):
1135 cargs = ['-l' + libname]
1136 largs = self.get_allow_undefined_link_args()
1137 extra_args = cargs + self.linker_to_compiler_args(largs)
1138
1139 if self.links(code, extra_args=extra_args, disable_cache=True)[0]:
1140 return cargs
1141 # Don't do a manual search for internal libs
1142 if libname in self.internal_libs:
1143 return None
1144 # Not found or we want to use a specific libtype? Try to find the
1145 # library file itself.
1146 patterns = self.get_library_naming(libtype)
1147 # try to detect if we are 64-bit or 32-bit. If we can't
1148 # detect, we will just skip path validity checks done in
1149 # get_library_dirs() call
1150 try:
1151 if self.output_is_64bit():
1152 elf_class = 2
1153 else:
1154 elf_class = 1
1155 except (mesonlib.MesonException, KeyError): # TODO evaluate if catching KeyError is wanted here
1156 elf_class = 0
1157 # Search in the specified dirs, and then in the system libraries
1158 largs = self.get_allow_undefined_link_args()
1159 lcargs = self.linker_to_compiler_args(largs)
1160 for d in itertools.chain(extra_dirs, [] if ignore_system_dirs else self.get_library_dirs(elf_class)):
1161 for p in patterns:
1162 trials = self._get_trials_from_pattern(p, d, libname)
1163 if not trials:
1164 continue
1165
1166 trial_result = ""
1167 for trial in trials:
1168 if not os.path.isfile(trial):
1169 continue
1170
1171 # Check if an argument to find_library is usable:
1172 # * user requested a static library specifically
1173 # => assume they know what they're doing, no link test
1174 # as some runtime libraries may be provided in such
1175 # a way that they must be used together with another
1176 # library, or require special options.
1177 #
1178 # * user requested a library without `static: true`
1179 # => build a shared library and link against it. Shared
1180 # libraries (on ELF platforms) can be underlinked
1181 # so it's better than an executable, as we'll only fail
1182 # if it's unusable for another reason.
1183
1184 # If we were asked specifically for a static library, don't perform
1185 # a link test, because it might be a special toolchain library.
1186 skip_link_check |= (libtype == LibType.STATIC)
1187
1188 # Don't bother fishing for arguments if we've already
1189 # been told not to perform a test.
1190 if not skip_link_check:
1191 shared_link_args = self.get_std_shared_lib_link_args()
1192 extra_args = [trial] + lcargs + shared_link_args
1193
1194 # Try to build the link test as PIC. We don't know if
1195 # the target library is itself PIC: if it's non-PIC,
1196 # PIC is fine, and if it is PIC, then PIC is needed,
1197 # so always use it.
1198 extra_args += self.get_pic_args()
1199
1200 # Don't bother with a link check if we don't know how to build
1201 # a shared library.
1202 skip_link_check |= (not shared_link_args)
1203
1204 # When skip_link_check is True (e.g. for pkg-config
1205 # libraries which are trusted to be linkable), skip the
1206 # potentially expensive link check and just verify that the
1207 # file exists.
1208 if skip_link_check or self.links(code, extra_args=extra_args, disable_cache=True)[0]:
1209 trial_result = trial
1210 break
1211
1212 if not trial_result:
1213 continue
1214 if libname.startswith('lib') and trial_result.startswith(libname) and lib_prefix_warning:
1215 mlog.warning(f'find_library({libname!r}) starting in "lib" only works by accident and is not portable')
1216 return [Path(trial_result).as_posix()]
1217 return None
1218
1219 def _find_library_impl(self, libname: str, extra_dirs: T.List[str], code: str, libtype: LibType,
1220 lib_prefix_warning: bool, ignore_system_dirs: bool,
1221 skip_link_check: bool = False) -> T.Optional[T.List[str]]:
1222 # These libraries are either built-in or invalid
1223 if libname in self.ignore_libs:
1224 return []
1225 if isinstance(extra_dirs, str):
1226 extra_dirs = [extra_dirs]
1227 key = (tuple(self.exelist), libname, tuple(extra_dirs), code, libtype, ignore_system_dirs, skip_link_check)
1228 if key not in self.find_library_cache:
1229 value = self._find_library_real(libname, extra_dirs, code, libtype, lib_prefix_warning, ignore_system_dirs, skip_link_check)
1230 self.find_library_cache[key] = value
1231 else:
1232 value = self.find_library_cache[key]
1233 if value is None:
1234 return None
1235 return value.copy()
1236
1237 def find_library(self, libname: str, extra_dirs: T.List[str], libtype: LibType = LibType.PREFER_SHARED,
1238 lib_prefix_warning: bool = True, ignore_system_dirs: bool = False,
1239 skip_link_check: bool = False) -> T.Optional[T.List[str]]:
1240 code = 'int main(void) { return 0; }\n'
1241 return self._find_library_impl(libname, extra_dirs, code, libtype, lib_prefix_warning, ignore_system_dirs, skip_link_check)
1242
1243 def find_framework_paths(self) -> T.List[str]:
1244 '''
1245 These are usually /Library/Frameworks and /System/Library/Frameworks,
1246 unless you select a particular macOS SDK with the -isysroot flag.
1247 You can also add to this by setting -F in CFLAGS.
1248 '''
1249 # TODO: this really needs to be *AppleClang*, not just any clang.
1250 if self.id != 'clang':
1251 raise mesonlib.MesonException('Cannot find framework path with non-clang compiler')
1252 # Construct the compiler command-line
1253 commands = self.get_exelist(ccache=False) + ['-v', '-E', '-']
1254 commands += self.get_always_args()
1255 # Add CFLAGS/CXXFLAGS/OBJCFLAGS/OBJCXXFLAGS from the env
1256 commands += self.get_external_compile_args()
1257 mlog.debug('Finding framework path by running: ', ' '.join(commands), '\n')
1258 os_env = os.environ.copy()
1259 os_env['LC_ALL'] = 'C'
1260 _, _, stde = mesonlib.Popen_safe(commands, env=os_env, stdin=subprocess.PIPE)
1261 paths: T.List[str] = []
1262 for line in stde.split('\n'):
1263 if '(framework directory)' not in line:
1264 continue
1265 # line is of the form:
1266 # ` /path/to/framework (framework directory)`
1267 paths.append(line[:-21].strip())
1268 return paths
1269
1270 def _find_framework_real(self, name: str, extra_dirs: T.List[str], allow_system: bool) -> T.Optional[T.List[str]]:
1271 code = 'int main(void) { return 0; }'
1272 link_args: T.List[str] = []
1273 for d in extra_dirs:
1274 link_args += ['-F' + d]
1275 # We can pass -Z to disable searching in the system frameworks, but
1276 # then we must also pass -L/usr/lib to pick up libSystem.dylib
1277 extra_args = [] if allow_system else ['-Z', '-L/usr/lib']
1278 link_args += ['-framework', name]
1279 if self.links(code, extra_args=(extra_args + link_args), disable_cache=True)[0]:
1280 return link_args
1281 return None
1282
1283 def _find_framework_impl(self, name: str, extra_dirs: T.List[str],
1284 allow_system: bool) -> T.Optional[T.List[str]]:
1285 if isinstance(extra_dirs, str):
1286 extra_dirs = [extra_dirs]
1287 key = (tuple(self.exelist), name, tuple(extra_dirs), allow_system)
1288 if key in self.find_framework_cache:
1289 value = self.find_framework_cache[key]
1290 else:
1291 value = self._find_framework_real(name, extra_dirs, allow_system)
1292 self.find_framework_cache[key] = value
1293 if value is None:
1294 return None
1295 return value.copy()
1296
1297 def find_framework(self, name: str, extra_dirs: T.List[str],
1298 allow_system: bool = True) -> T.Optional[T.List[str]]:
1299 '''
1300 Finds the framework with the specified name, and returns link args for
1301 the same or returns None when the framework is not found.
1302 '''
1303 # TODO: should probably check for macOS?
1304 return self._find_framework_impl(name, extra_dirs, allow_system)
1305
1306 def get_crt_compile_args(self, crt_val: str) -> T.List[str]:
1307 # TODO: does this belong here or in GnuLike or maybe PosixLike?
1308 return []
1309
1310 def get_crt_link_args(self, crt_val: str) -> T.List[str]:
1311 # TODO: does this belong here or in GnuLike or maybe PosixLike?
1312 return []
1313
1314 def thread_flags(self) -> T.List[str]:
1315 # TODO: does this belong here or in GnuLike or maybe PosixLike?
1316 if self.info.is_haiku() or self.info.is_darwin():
1317 return []
1318 if self.info.is_os2():
1319 return ['-lpthread']
1320 return ['-pthread']
1321
1322 def linker_to_compiler_args(self, args: T.List[str]) -> T.List[str]:
1323 return args.copy()
1324
1325 def has_arguments(self, args: T.List[str], code: str,
1326 mode: CompileCheckMode) -> T.Tuple[bool, bool]:
1327 return self.compiles(code, extra_args=args, mode=mode)
1328
1329 def _has_multi_arguments(self, args: T.List[str], code: str) -> T.Tuple[bool, bool]:
1330 new_args: T.List[str] = []
1331 for arg in args:
1332 # some compilers, e.g. GCC, don't warn for unsupported warning-disable
1333 # flags, so when we are testing a flag like "-Wno-forgotten-towel", also
1334 # check the equivalent enable flag too "-Wforgotten-towel".
1335 if arg.startswith('-Wno-'):
1336 # Make an exception for -Wno-attributes=x as -Wattributes=x is invalid
1337 # for GCC at least. Also, the positive form of some flags require a
1338 # value to be specified, i.e. we need to pass -Wfoo=N rather than just
1339 # -Wfoo.
1340 if arg.startswith('-Wno-attributes='):
1341 pass
1342 elif arg in {'-Wno-alloc-size-larger-than',
1343 '-Wno-alloca-larger-than',
1344 '-Wno-frame-larger-than',
1345 '-Wno-stack-usage',
1346 '-Wno-vla-larger-than'}:
1347 # Pass an arbitrary value to the enabling flag; since the test program
1348 # is trivial, it is unlikely to provoke any of these warnings.
1349 new_args.append('-W' + arg[5:] + '=1000')
1350 else:
1351 new_args.append('-W' + arg[5:])
1352 if arg.startswith('-Wl,'):
1353 mlog.warning(f'{arg} looks like a linker argument, '
1354 'but has_argument and other similar methods only '
1355 'support checking compiler arguments. Using them '
1356 'to check linker arguments are never supported, '
1357 'and results are likely to be wrong regardless of '
1358 'the compiler you are using. has_link_argument or '
1359 'other similar method can be used instead.')
1360 new_args.append(arg)
1361 return self.has_arguments(new_args, code, mode=CompileCheckMode.COMPILE)
1362
1363 def has_multi_arguments(self, args: T.List[str]) -> T.Tuple[bool, bool]:
1364 return self._has_multi_arguments(args, 'extern int i;\nint i;\n')
1365
1366 def _has_multi_link_arguments(self, args: T.List[str], code: str) -> T.Tuple[bool, bool]:
1367 args = self.linker.fatal_warnings() + args
1368 args = self.linker_to_compiler_args(args)
1369 return self.has_arguments(args, code, mode=CompileCheckMode.LINK)
1370
1371 def has_multi_link_arguments(self, args: T.List[str], to_host_args: bool = True) -> T.Tuple[bool, bool]:
1372 return self._has_multi_link_arguments(args, 'int main(void) { return 0; }\n')
1373
1374 @staticmethod
1375 def _concatenate_string_literals(s: str) -> str:
1376 pattern = re.compile(r'(?P<pre>.*([^\\]")|^")(?P<str1>([^\\"]|\\.)*)"\s+"(?P<str2>([^\\"]|\\.)*)(?P<post>".*)')
1377 ret = s
1378 m = pattern.match(ret)
1379 while m:
1380 ret = ''.join(m.group('pre', 'str1', 'str2', 'post'))
1381 m = pattern.match(ret)
1382 return ret
1383
1384 def get_has_func_attribute_extra_args(self, name: str) -> T.List[str]:
1385 # Most compilers (such as GCC and Clang) only warn about unknown or
1386 # ignored attributes, so force an error. Overridden in GCC and Clang
1387 # mixins.
1388 return ['-Werror']
1389
1390 def has_func_attribute(self, name: str) -> T.Tuple[bool, bool]:
1391 # Just assume that if we're not on windows that dllimport and dllexport
1392 # don't work
1393 if not (self.info.is_windows() or self.info.is_cygwin()):
1394 if name in {'dllimport', 'dllexport'}:
1395 return False, False
1396
1397 return self.compiles(self.attribute_check_func(name),
1398 extra_args=self.get_has_func_attribute_extra_args(name))
1399
1400 def get_assert_args(self, disable: bool) -> T.List[str]:
1401 if disable:
1402 return ['-DNDEBUG']
1403 return []
1404
1405 @functools.lru_cache(maxsize=None)
1406 def can_compile(self, src: 'mesonlib.FileOrString') -> bool:
1407 # Files we preprocess can be anything, e.g. .in
1408 if self.mode == 'PREPROCESSOR':
1409 return True
1410 return super().can_compile(src)
1411
1412 def get_preprocessor(self) -> Compiler:
1413 if not self.preprocessor:
1414 self.preprocessor = copy.copy(self)
1415 self.preprocessor.exelist = self.exelist + self.get_preprocess_to_file_args()
1416 self.preprocessor.mode = 'PREPROCESSOR'
1417 self.modes.append(self.preprocessor)
1418 return self.preprocessor