| 1 |
# SPDX-License-Identifier: Apache-2.0 |
| 2 |
# Copyright 2013-2021 The Meson development team |
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
from pathlib import Path |
| 7 |
|
| 8 |
from .base import ExternalDependency, DependencyException, sort_libpaths, DependencyTypeName |
| 9 |
from ..mesonlib import (EnvironmentVariables, OrderedSet, PerMachine, Popen_safe, Popen_safe_logged, MachineChoice, |
| 10 |
join_args, MesonException, path_has_root) |
| 11 |
from ..options import OptionKey |
| 12 |
from ..programs import find_external_program, ExternalProgram |
| 13 |
from .. import mlog |
| 14 |
from pathlib import PurePath |
| 15 |
from functools import lru_cache |
| 16 |
import re |
| 17 |
import os |
| 18 |
import shlex |
| 19 |
import typing as T |
| 20 |
|
| 21 |
if T.TYPE_CHECKING: |
| 22 |
from typing_extensions import Literal |
| 23 |
from .._typing import ImmutableListProtocol |
| 24 |
|
| 25 |
from ..environment import Environment |
| 26 |
from ..utils.core import EnvironOrDict |
| 27 |
from ..interpreter.type_checking import PkgConfigDefineType |
| 28 |
from .base import DependencyObjectKWs |
| 29 |
|
| 30 |
class PkgConfigInterface: |
| 31 |
'''Base class wrapping a pkg-config implementation''' |
| 32 |
|
| 33 |
# keyed on machine and extra_paths |
| 34 |
class_impl: PerMachine[T.Dict[T.Optional[T.Tuple[str, ...]], T.Union[Literal[False], T.Optional[PkgConfigInterface]]]] = PerMachine({}, {}) |
| 35 |
class_cli_impl: PerMachine[T.Dict[T.Optional[T.Tuple[str, ...]], T.Union[Literal[False], T.Optional[PkgConfigCLI]]]] = PerMachine({}, {}) |
| 36 |
pkg_bin_per_machine: PerMachine[T.Optional[ExternalProgram]] = PerMachine(None, None) |
| 37 |
|
| 38 |
@staticmethod |
| 39 |
def set_program_override(pkg_bin: ExternalProgram, for_machine: MachineChoice) -> None: |
| 40 |
if PkgConfigInterface.class_impl[for_machine]: |
| 41 |
raise MesonException(f'Tried to override pkg-config for machine {for_machine} but it was already initialized.\n' |
| 42 |
'pkg-config must be overridden before it\'s used.') |
| 43 |
PkgConfigInterface.pkg_bin_per_machine[for_machine] = pkg_bin |
| 44 |
|
| 45 |
@staticmethod |
| 46 |
def instance(env: Environment, for_machine: MachineChoice, silent: bool, |
| 47 |
extra_paths: T.Optional[T.List[str]] = None) -> T.Optional[PkgConfigInterface]: |
| 48 |
'''Return a pkg-config implementation singleton''' |
| 49 |
extra_paths_key = tuple(extra_paths) if extra_paths is not None else None |
| 50 |
impl = PkgConfigInterface.class_impl[for_machine].get(extra_paths_key, False) |
| 51 |
if impl is False: |
| 52 |
impl = PkgConfigCLI(env, for_machine, silent, PkgConfigInterface.pkg_bin_per_machine[for_machine], extra_paths) |
| 53 |
if not impl.found(): |
| 54 |
impl = None |
| 55 |
if not impl and not silent: |
| 56 |
mlog.log('Found pkg-config:', mlog.red('NO')) |
| 57 |
PkgConfigInterface.class_impl[for_machine][extra_paths_key] = impl |
| 58 |
return impl |
| 59 |
|
| 60 |
@staticmethod |
| 61 |
def _cli(env: Environment, for_machine: MachineChoice, |
| 62 |
extra_paths: T.Optional[T.List[str]] = None, |
| 63 |
silent: bool = False) -> T.Optional[PkgConfigCLI]: |
| 64 |
'''Return the CLI pkg-config implementation singleton |
| 65 |
Even when we use another implementation internally, external tools might |
| 66 |
still need the CLI implementation. |
| 67 |
''' |
| 68 |
impl: T.Union[Literal[False], T.Optional[PkgConfigInterface]] # Help confused mypy |
| 69 |
impl = PkgConfigInterface.instance(env, for_machine, silent) |
| 70 |
if impl and not isinstance(impl, PkgConfigCLI): |
| 71 |
extra_paths_key = tuple(extra_paths) if extra_paths is not None else None |
| 72 |
impl = PkgConfigInterface.class_cli_impl[for_machine].get(extra_paths_key, False) |
| 73 |
if impl is False: |
| 74 |
impl = PkgConfigCLI(env, for_machine, silent, PkgConfigInterface.pkg_bin_per_machine[for_machine], extra_paths) |
| 75 |
if not impl.found(): |
| 76 |
impl = None |
| 77 |
PkgConfigInterface.class_cli_impl[for_machine][extra_paths_key] = impl |
| 78 |
return T.cast('T.Optional[PkgConfigCLI]', impl) # Trust me, mypy |
| 79 |
|
| 80 |
@staticmethod |
| 81 |
def get_env(env: Environment, for_machine: MachineChoice, uninstalled: bool = False, |
| 82 |
extra_paths: T.Optional[T.List[str]] = None) -> EnvironmentVariables: |
| 83 |
cli = PkgConfigInterface._cli(env, for_machine, extra_paths) |
| 84 |
return cli._get_env(uninstalled) if cli else EnvironmentVariables() |
| 85 |
|
| 86 |
@staticmethod |
| 87 |
def setup_env(environ: EnvironOrDict, env: Environment, for_machine: MachineChoice, |
| 88 |
uninstalled: bool = False) -> EnvironOrDict: |
| 89 |
cli = PkgConfigInterface._cli(env, for_machine) |
| 90 |
return cli._setup_env(environ, uninstalled) if cli else environ |
| 91 |
|
| 92 |
def __init__(self, env: Environment, for_machine: MachineChoice) -> None: |
| 93 |
self.env = env |
| 94 |
self.for_machine = for_machine |
| 95 |
|
| 96 |
def found(self) -> bool: |
| 97 |
'''Return whether pkg-config is supported''' |
| 98 |
raise NotImplementedError |
| 99 |
|
| 100 |
def version(self, name: str) -> T.Optional[str]: |
| 101 |
'''Return module version or None if not found''' |
| 102 |
raise NotImplementedError |
| 103 |
|
| 104 |
def cflags(self, name: str, static: bool = False, allow_system: bool = False, |
| 105 |
define_variable: PkgConfigDefineType = None) -> ImmutableListProtocol[str]: |
| 106 |
'''Return module cflags |
| 107 |
@allow_system: If False, remove default system include paths |
| 108 |
''' |
| 109 |
raise NotImplementedError |
| 110 |
|
| 111 |
def libs(self, name: str, static: bool = False, allow_system: bool = False, |
| 112 |
define_variable: PkgConfigDefineType = None) -> ImmutableListProtocol[str]: |
| 113 |
'''Return module libs |
| 114 |
@static: If True, also include private libraries |
| 115 |
@allow_system: If False, remove default system libraries search paths |
| 116 |
''' |
| 117 |
raise NotImplementedError |
| 118 |
|
| 119 |
def variable(self, name: str, variable_name: str, |
| 120 |
define_variable: PkgConfigDefineType) -> T.Optional[str]: |
| 121 |
'''Return module variable or None if variable is not defined''' |
| 122 |
raise NotImplementedError |
| 123 |
|
| 124 |
def list_all(self) -> ImmutableListProtocol[str]: |
| 125 |
'''Return all available pkg-config modules''' |
| 126 |
raise NotImplementedError |
| 127 |
|
| 128 |
class PkgConfigCLI(PkgConfigInterface): |
| 129 |
'''pkg-config CLI implementation''' |
| 130 |
|
| 131 |
def __init__(self, env: Environment, for_machine: MachineChoice, silent: bool, |
| 132 |
pkgbin: T.Optional[ExternalProgram] = None, |
| 133 |
extra_paths: T.Optional[T.List[str]] = None) -> None: |
| 134 |
super().__init__(env, for_machine) |
| 135 |
self._detect_pkgbin(pkgbin) |
| 136 |
if self.pkgbin and not silent: |
| 137 |
mlog.log('Found pkg-config:', mlog.green('YES'), mlog.bold(f'({self.pkgbin.get_path()})'), mlog.blue(self.pkgbin_version)) |
| 138 |
self.extra_paths = extra_paths or [] |
| 139 |
|
| 140 |
def found(self) -> bool: |
| 141 |
return bool(self.pkgbin) |
| 142 |
|
| 143 |
@lru_cache(maxsize=None) |
| 144 |
def version(self, name: str) -> T.Optional[str]: |
| 145 |
mlog.debug(f'Determining dependency {name!r} with pkg-config executable {self.pkgbin.get_path()!r}') |
| 146 |
ret, version, _ = self._call_pkgbin(['--modversion', name]) |
| 147 |
return version if ret == 0 else None |
| 148 |
|
| 149 |
@staticmethod |
| 150 |
def _define_variable_args(define_variable: PkgConfigDefineType) -> T.List[str]: |
| 151 |
ret = [] |
| 152 |
if define_variable: |
| 153 |
for pair in define_variable: |
| 154 |
ret.append('--define-variable=' + '='.join(pair)) |
| 155 |
return ret |
| 156 |
|
| 157 |
@lru_cache(maxsize=None) |
| 158 |
def cflags(self, name: str, static: bool = False, allow_system: bool = False, |
| 159 |
define_variable: PkgConfigDefineType = None) -> ImmutableListProtocol[str]: |
| 160 |
env = None |
| 161 |
if allow_system: |
| 162 |
env = os.environ.copy() |
| 163 |
env['PKG_CONFIG_ALLOW_SYSTEM_CFLAGS'] = '1' |
| 164 |
args: T.List[str] = [] |
| 165 |
args += self._define_variable_args(define_variable) |
| 166 |
if static: |
| 167 |
args.append('--static') |
| 168 |
args += ['--cflags', name] |
| 169 |
ret, out, err = self._call_pkgbin(args, env=env) |
| 170 |
if ret != 0: |
| 171 |
raise DependencyException(f'Could not generate cflags for {name}:\n{err}\n') |
| 172 |
return self._split_args(out) |
| 173 |
|
| 174 |
@lru_cache(maxsize=None) |
| 175 |
def libs(self, name: str, static: bool = False, allow_system: bool = False, |
| 176 |
define_variable: PkgConfigDefineType = None) -> ImmutableListProtocol[str]: |
| 177 |
env = None |
| 178 |
if allow_system: |
| 179 |
env = os.environ.copy() |
| 180 |
env['PKG_CONFIG_ALLOW_SYSTEM_LIBS'] = '1' |
| 181 |
args: T.List[str] = [] |
| 182 |
args += self._define_variable_args(define_variable) |
| 183 |
if static: |
| 184 |
args.append('--static') |
| 185 |
args += ['--libs', name] |
| 186 |
ret, out, err = self._call_pkgbin(args, env=env) |
| 187 |
if ret != 0: |
| 188 |
raise DependencyException(f'Could not generate libs for {name}:\n{err}\n') |
| 189 |
return self._split_args(out) |
| 190 |
|
| 191 |
@lru_cache(maxsize=None) |
| 192 |
def variable(self, name: str, variable_name: str, |
| 193 |
define_variable: PkgConfigDefineType) -> T.Optional[str]: |
| 194 |
args: T.List[str] = [] |
| 195 |
args += self._define_variable_args(define_variable) |
| 196 |
args += ['--variable=' + variable_name, name] |
| 197 |
ret, out, err = self._call_pkgbin(args) |
| 198 |
if ret != 0: |
| 199 |
raise DependencyException(f'Could not get variable for {name}:\n{err}\n') |
| 200 |
variable = out.strip() |
| 201 |
# pkg-config doesn't distinguish between empty and nonexistent variables |
| 202 |
# use the variable list to check for variable existence |
| 203 |
if not variable: |
| 204 |
ret, out, _ = self._call_pkgbin(['--print-variables', name]) |
| 205 |
if not re.search(rf'^{variable_name}$', out, re.MULTILINE): |
| 206 |
return None |
| 207 |
mlog.debug(f'Got pkg-config variable {variable_name} : {variable}') |
| 208 |
return variable |
| 209 |
|
| 210 |
@lru_cache(maxsize=None) |
| 211 |
def list_all(self) -> ImmutableListProtocol[str]: |
| 212 |
ret, out, err = self._call_pkgbin(['--list-all']) |
| 213 |
if ret != 0: |
| 214 |
raise DependencyException(f'could not list modules:\n{err}\n') |
| 215 |
return [i.split(' ', 1)[0] for i in out.splitlines()] |
| 216 |
|
| 217 |
@staticmethod |
| 218 |
def _split_args(cmd: str) -> T.List[str]: |
| 219 |
# pkg-config paths follow Unix conventions, even on Windows; split the |
| 220 |
# output using shlex.split rather than mesonlib.split_args |
| 221 |
return shlex.split(cmd) |
| 222 |
|
| 223 |
def _detect_pkgbin(self, pkgbin: T.Optional[ExternalProgram] = None) -> None: |
| 224 |
def validate(potential_pkgbin: ExternalProgram) -> bool: |
| 225 |
version_if_ok = self._check_pkgconfig(potential_pkgbin) |
| 226 |
if version_if_ok: |
| 227 |
self.pkgbin = potential_pkgbin |
| 228 |
self.pkgbin_version = version_if_ok |
| 229 |
return True |
| 230 |
return False |
| 231 |
|
| 232 |
if pkgbin and validate(pkgbin): |
| 233 |
return |
| 234 |
|
| 235 |
for potential_pkgbin in find_external_program(self.env, self.for_machine, "pkg-config", "Pkg-config", |
| 236 |
self.env.default_pkgconfig, allow_default_for_cross=False): |
| 237 |
if validate(potential_pkgbin): |
| 238 |
return |
| 239 |
self.pkgbin = None |
| 240 |
|
| 241 |
def _check_pkgconfig(self, pkgbin: ExternalProgram) -> T.Optional[str]: |
| 242 |
if not pkgbin.found(): |
| 243 |
mlog.log(f'Did not find pkg-config by name {pkgbin.name!r}') |
| 244 |
return None |
| 245 |
command_as_string = ' '.join(pkgbin.get_command()) |
| 246 |
try: |
| 247 |
helptext = Popen_safe(pkgbin.get_command() + ['--help'])[1] |
| 248 |
if 'Pure-Perl' in helptext: |
| 249 |
mlog.log(f'Found pkg-config {command_as_string!r} but it is Strawberry Perl and thus broken. Ignoring...') |
| 250 |
return None |
| 251 |
p, out = Popen_safe(pkgbin.get_command() + ['--version'])[0:2] |
| 252 |
if p.returncode != 0: |
| 253 |
mlog.warning(f'Found pkg-config {command_as_string!r} but it failed when ran') |
| 254 |
return None |
| 255 |
except FileNotFoundError: |
| 256 |
mlog.warning(f'We thought we found pkg-config {command_as_string!r} but now it\'s not there. How odd!') |
| 257 |
return None |
| 258 |
except PermissionError: |
| 259 |
msg = f'Found pkg-config {command_as_string!r} but didn\'t have permissions to run it.' |
| 260 |
if not self.env.machines.build.is_windows(): |
| 261 |
msg += '\n\nOn Unix-like systems this is often caused by scripts that are not executable.' |
| 262 |
mlog.warning(msg) |
| 263 |
return None |
| 264 |
return out.strip() |
| 265 |
|
| 266 |
def _get_env(self, uninstalled: bool = False) -> EnvironmentVariables: |
| 267 |
env = EnvironmentVariables() |
| 268 |
key = OptionKey('pkg_config_path', machine=self.for_machine) |
| 269 |
pathlist = self.env.coredata.optstore.get_value_for(key) |
| 270 |
assert isinstance(pathlist, list) |
| 271 |
extra_paths: T.List[str] = pathlist + self.extra_paths |
| 272 |
if uninstalled: |
| 273 |
bpath = self.env.get_build_dir() |
| 274 |
if bpath is not None: |
| 275 |
# uninstalled can only be used if a build dir exists. |
| 276 |
uninstalled_path = Path(bpath, 'meson-uninstalled').as_posix() |
| 277 |
if uninstalled_path not in extra_paths: |
| 278 |
extra_paths.insert(0, uninstalled_path) |
| 279 |
env.set('PKG_CONFIG_PATH', extra_paths) |
| 280 |
sysroot = self.env.properties[self.for_machine].get_sys_root() |
| 281 |
if sysroot: |
| 282 |
env.set('PKG_CONFIG_SYSROOT_DIR', [sysroot]) |
| 283 |
pkg_config_libdir_prop = self.env.properties[self.for_machine].get_pkg_config_libdir() |
| 284 |
if pkg_config_libdir_prop: |
| 285 |
env.set('PKG_CONFIG_LIBDIR', pkg_config_libdir_prop) |
| 286 |
env.set('PKG_CONFIG', [join_args(self.pkgbin.get_command())]) |
| 287 |
return env |
| 288 |
|
| 289 |
def _setup_env(self, env: EnvironOrDict, uninstalled: bool = False) -> T.Dict[str, str]: |
| 290 |
envvars = self._get_env(uninstalled) |
| 291 |
env = envvars.get_env(env) |
| 292 |
# Dump all PKG_CONFIG environment variables |
| 293 |
for key, value in env.items(): |
| 294 |
if key.startswith('PKG_'): |
| 295 |
mlog.debug(f'env[{key}]: {value}') |
| 296 |
return env |
| 297 |
|
| 298 |
def _call_pkgbin(self, args: T.List[str], env: T.Optional[EnvironOrDict] = None) -> T.Tuple[int, str, str]: |
| 299 |
assert isinstance(self.pkgbin, ExternalProgram) |
| 300 |
env = env or os.environ |
| 301 |
env = self._setup_env(env) |
| 302 |
cmd = self.pkgbin.get_command() + args |
| 303 |
p, out, err = Popen_safe_logged(cmd, env=env) |
| 304 |
return p.returncode, out.strip(), err.strip() |
| 305 |
|
| 306 |
|
| 307 |
class PkgConfigDependency(ExternalDependency): |
| 308 |
|
| 309 |
type_name = DependencyTypeName('pkgconfig') |
| 310 |
|
| 311 |
def __init__(self, name: str, environment: Environment, kwargs: DependencyObjectKWs, |
| 312 |
extra_paths: T.Optional[T.List[str]] = None) -> None: |
| 313 |
super().__init__(name, environment, kwargs) |
| 314 |
self.is_libtool = False |
| 315 |
self.extra_paths = extra_paths or [] |
| 316 |
pkgconfig = PkgConfigInterface.instance(self.env, self.for_machine, self.silent, self.extra_paths) |
| 317 |
if not pkgconfig: |
| 318 |
msg = f'Pkg-config for machine {self.for_machine} not found. Giving up.' |
| 319 |
if self.required: |
| 320 |
raise DependencyException(msg) |
| 321 |
mlog.debug(msg) |
| 322 |
return |
| 323 |
self.pkgconfig = pkgconfig |
| 324 |
|
| 325 |
version = self.pkgconfig.version(name) |
| 326 |
if version is None: |
| 327 |
return |
| 328 |
|
| 329 |
self.version = version |
| 330 |
self.is_found = True |
| 331 |
|
| 332 |
try: |
| 333 |
# Fetch cargs to be used while using this dependency |
| 334 |
self._set_cargs() |
| 335 |
# Fetch the libraries and library paths needed for using this |
| 336 |
self._set_libs() |
| 337 |
except DependencyException as e: |
| 338 |
mlog.warning(f"Pkg-config error with '{name}': {e}") |
| 339 |
if self.required: |
| 340 |
raise |
| 341 |
else: |
| 342 |
self.compile_args = [] |
| 343 |
self.link_args = [] |
| 344 |
self.is_found = False |
| 345 |
self.reason = e |
| 346 |
|
| 347 |
def __repr__(self) -> str: |
| 348 |
s = '<{0} {1}: {2} {3}>' |
| 349 |
return s.format(self.__class__.__name__, self.name, self.is_found, |
| 350 |
self.version_reqs) |
| 351 |
|
| 352 |
def _convert_mingw_paths(self, args: ImmutableListProtocol[str]) -> T.List[str]: |
| 353 |
''' |
| 354 |
Both MSVC and native Python on Windows cannot handle MinGW-esque /c/foo |
| 355 |
paths so convert them to C:/foo. We cannot resolve other paths starting |
| 356 |
with / like /home/foo so leave them as-is so that the user gets an |
| 357 |
error/warning from the compiler/linker. |
| 358 |
''' |
| 359 |
if not self.env.machines.build.is_windows(): |
| 360 |
return args.copy() |
| 361 |
converted = [] |
| 362 |
for arg in args: |
| 363 |
pargs: T.Tuple[str, ...] = tuple() |
| 364 |
# Library search path |
| 365 |
if arg.startswith('-L/'): |
| 366 |
pargs = PurePath(arg[2:]).parts |
| 367 |
tmpl = '-L{}:/{}' |
| 368 |
elif arg.startswith('-I/'): |
| 369 |
pargs = PurePath(arg[2:]).parts |
| 370 |
tmpl = '-I{}:/{}' |
| 371 |
# Full path to library or .la file |
| 372 |
elif arg.startswith('/'): |
| 373 |
pargs = PurePath(arg).parts |
| 374 |
tmpl = '{}:/{}' |
| 375 |
elif arg.startswith(('-L', '-I')) or (len(arg) > 2 and arg[1] == ':'): |
| 376 |
# clean out improper '\\ ' as comes from some Windows pkg-config files |
| 377 |
arg = arg.replace('\\ ', ' ') |
| 378 |
if len(pargs) > 1 and len(pargs[1]) == 1: |
| 379 |
arg = tmpl.format(pargs[1], '/'.join(pargs[2:])) |
| 380 |
converted.append(arg) |
| 381 |
return converted |
| 382 |
|
| 383 |
def _set_cargs(self) -> None: |
| 384 |
allow_system = False |
| 385 |
if self.language == 'fortran': |
| 386 |
# gfortran doesn't appear to look in system paths for INCLUDE files, |
| 387 |
# so don't allow pkg-config to suppress -I flags for system paths |
| 388 |
allow_system = True |
| 389 |
cflags = self.pkgconfig.cflags(self.name, self.static, allow_system) |
| 390 |
self.compile_args = self._convert_mingw_paths(cflags) |
| 391 |
|
| 392 |
def _search_libs(self, libs_in: ImmutableListProtocol[str], raw_libs_in: ImmutableListProtocol[str]) -> T.Tuple[T.List[str], T.List[str]]: |
| 393 |
''' |
| 394 |
@libs_in: PKG_CONFIG_ALLOW_SYSTEM_LIBS=1 pkg-config --libs |
| 395 |
@raw_libs_in: pkg-config --libs |
| 396 |
|
| 397 |
We always look for the file ourselves instead of depending on the |
| 398 |
compiler to find it with -lfoo or foo.lib (if possible) because: |
| 399 |
1. We want to be able to select static or shared |
| 400 |
2. We need the full path of the library to calculate RPATH values |
| 401 |
3. De-dup of libraries is easier when we have absolute paths |
| 402 |
|
| 403 |
Libraries that are provided by the toolchain or are not found by |
| 404 |
find_library() will be added with -L -l pairs. |
| 405 |
''' |
| 406 |
# Library paths should be safe to de-dup |
| 407 |
# |
| 408 |
# First, figure out what library paths to use. Originally, we were |
| 409 |
# doing this as part of the loop, but due to differences in the order |
| 410 |
# of -L values between pkg-config and pkgconf, we need to do that as |
| 411 |
# a separate step. See: |
| 412 |
# https://github.com/mesonbuild/meson/issues/3951 |
| 413 |
# https://github.com/mesonbuild/meson/issues/4023 |
| 414 |
# |
| 415 |
# Separate system and prefix paths, and ensure that prefix paths are |
| 416 |
# always searched first. |
| 417 |
prefix_libpaths: OrderedSet[str] = OrderedSet() |
| 418 |
# We also store this raw_link_args on the object later |
| 419 |
raw_link_args = self._convert_mingw_paths(raw_libs_in) |
| 420 |
for arg in raw_link_args: |
| 421 |
if arg.startswith('-L') and not arg.startswith(('-L-l', '-L-L')): |
| 422 |
path = arg[2:] |
| 423 |
if not path_has_root(path): |
| 424 |
# Resolve the path as a compiler in the build directory would |
| 425 |
path = os.path.join(self.env.get_build_dir(), path) |
| 426 |
prefix_libpaths.add(path) |
| 427 |
# Library paths are not always ordered in a meaningful way |
| 428 |
# |
| 429 |
# Instead of relying on pkg-config or pkgconf to provide -L flags in a |
| 430 |
# specific order, we reorder library paths ourselves, according to th |
| 431 |
# order specified in PKG_CONFIG_PATH. See: |
| 432 |
# https://github.com/mesonbuild/meson/issues/4271 |
| 433 |
# |
| 434 |
# Only prefix_libpaths are reordered here because there should not be |
| 435 |
# too many system_libpaths to cause library version issues. |
| 436 |
pkg_config_path: T.List[str] = self.env.coredata.optstore.get_value_for(OptionKey('pkg_config_path', machine=self.for_machine)) # type: ignore[assignment] |
| 437 |
pkg_config_path = self._convert_mingw_paths(pkg_config_path) |
| 438 |
prefix_libpaths = OrderedSet(sort_libpaths(list(prefix_libpaths), pkg_config_path)) |
| 439 |
system_libpaths: OrderedSet[str] = OrderedSet() |
| 440 |
full_args = self._convert_mingw_paths(libs_in) |
| 441 |
for arg in full_args: |
| 442 |
if arg.startswith(('-L-l', '-L-L')): |
| 443 |
# These are D language arguments, not library paths |
| 444 |
continue |
| 445 |
if arg.startswith('-L') and arg[2:] not in prefix_libpaths: |
| 446 |
system_libpaths.add(arg[2:]) |
| 447 |
# Use this re-ordered path list for library resolution |
| 448 |
libpaths = list(prefix_libpaths) + list(system_libpaths) |
| 449 |
# Track -lfoo libraries to avoid duplicate work |
| 450 |
libs_found: OrderedSet[str] = OrderedSet() |
| 451 |
# Track not-found libraries to know whether to add library paths |
| 452 |
libs_notfound = [] |
| 453 |
# Generate link arguments for this library |
| 454 |
link_args = [] |
| 455 |
for lib in full_args: |
| 456 |
if lib.startswith(('-L-l', '-L-L')): |
| 457 |
# These are D language arguments, add them as-is |
| 458 |
pass |
| 459 |
elif lib.startswith('-L'): |
| 460 |
# We already handled library paths above |
| 461 |
continue |
| 462 |
elif lib.startswith('-l:'): |
| 463 |
# see: https://stackoverflow.com/questions/48532868/gcc-library-option-with-a-colon-llibevent-a |
| 464 |
# also : See the documentation of -lnamespec | --library=namespec in the linker manual |
| 465 |
# https://sourceware.org/binutils/docs-2.18/ld/Options.html |
| 466 |
|
| 467 |
# Don't resolve the same -l:libfoo.a argument again |
| 468 |
if lib in libs_found: |
| 469 |
continue |
| 470 |
libfilename = lib[3:] |
| 471 |
foundname = None |
| 472 |
for libdir in libpaths: |
| 473 |
target = os.path.join(libdir, libfilename) |
| 474 |
if os.path.exists(target): |
| 475 |
foundname = target |
| 476 |
break |
| 477 |
if foundname is None: |
| 478 |
if lib in libs_notfound: |
| 479 |
continue |
| 480 |
else: |
| 481 |
mlog.warning('Library {!r} not found for dependency {!r}, may ' |
| 482 |
'not be successfully linked'.format(libfilename, self.name)) |
| 483 |
libs_notfound.append(lib) |
| 484 |
else: |
| 485 |
lib = foundname |
| 486 |
elif lib.startswith('-l'): |
| 487 |
# Don't resolve the same -lfoo argument again |
| 488 |
if lib in libs_found: |
| 489 |
continue |
| 490 |
if self.clib_compiler: |
| 491 |
# Libraries from pkg-config are trusted to be linkable, so |
| 492 |
# we skip the potentially expensive link check for |
| 493 |
# performance reasons. |
| 494 |
args = self.clib_compiler.find_library( |
| 495 |
lib[2:], libpaths, self.libtype, lib_prefix_warning=False, |
| 496 |
skip_link_check=True) |
| 497 |
# If the project only uses a non-clib language such as D, Rust, |
| 498 |
# C#, Python, etc, all we can do is limp along by adding the |
| 499 |
# arguments as-is and then adding the libpaths at the end. |
| 500 |
else: |
| 501 |
args = None |
| 502 |
if args is not None: |
| 503 |
libs_found.add(lib) |
| 504 |
# Replace -l arg with full path to library if available |
| 505 |
# else, library is either to be ignored, or is provided by |
| 506 |
# the compiler, can't be resolved, and should be used as-is |
| 507 |
if args: |
| 508 |
if not args[0].startswith('-l'): |
| 509 |
lib = args[0] |
| 510 |
else: |
| 511 |
continue |
| 512 |
else: |
| 513 |
# Library wasn't found, maybe we're looking in the wrong |
| 514 |
# places or the library will be provided with LDFLAGS or |
| 515 |
# LIBRARY_PATH from the environment (on macOS), and many |
| 516 |
# other edge cases that we can't account for. |
| 517 |
# |
| 518 |
# Add all -L paths and use it as -lfoo |
| 519 |
if lib in libs_notfound: |
| 520 |
continue |
| 521 |
if self.static: |
| 522 |
mlog.warning('Static library {!r} not found for dependency {!r}, may ' |
| 523 |
'not be statically linked'.format(lib[2:], self.name)) |
| 524 |
libs_notfound.append(lib) |
| 525 |
elif lib.endswith(".la"): |
| 526 |
shared_libname = self.extract_libtool_shlib(lib) |
| 527 |
shared_lib = os.path.join(os.path.dirname(lib), shared_libname) |
| 528 |
if not os.path.exists(shared_lib): |
| 529 |
shared_lib = os.path.join(os.path.dirname(lib), ".libs", shared_libname) |
| 530 |
|
| 531 |
if not os.path.exists(shared_lib): |
| 532 |
raise DependencyException(f'Got a libtools specific "{lib}" dependencies' |
| 533 |
'but we could not compute the actual shared' |
| 534 |
'library path') |
| 535 |
self.is_libtool = True |
| 536 |
lib = shared_lib |
| 537 |
if lib in link_args: |
| 538 |
continue |
| 539 |
link_args.append(lib) |
| 540 |
# Add all -Lbar args if we have -lfoo args in link_args |
| 541 |
if libs_notfound: |
| 542 |
# Order of -L flags doesn't matter with ld, but it might with other |
| 543 |
# linkers such as MSVC, so prepend them. |
| 544 |
link_args = ['-L' + lp for lp in prefix_libpaths] + link_args |
| 545 |
return link_args, raw_link_args |
| 546 |
|
| 547 |
def _set_libs(self) -> None: |
| 548 |
# Force pkg-config to output -L fields even if they are system |
| 549 |
# paths so we can do manual searching with cc.find_library() later. |
| 550 |
libs = self.pkgconfig.libs(self.name, self.static, allow_system=True) |
| 551 |
# Also get the 'raw' output without -Lfoo system paths for adding -L |
| 552 |
# args with -lfoo when a library can't be found, and also in |
| 553 |
# gnome.generate_gir + gnome.gtkdoc which need -L -l arguments. |
| 554 |
raw_libs = self.pkgconfig.libs(self.name, self.static, allow_system=False) |
| 555 |
self.link_args, self.raw_link_args = self._search_libs(libs, raw_libs) |
| 556 |
|
| 557 |
def extract_field(self, la_file: str, fieldname: str) -> T.Optional[str]: |
| 558 |
with open(la_file, encoding='utf-8') as f: |
| 559 |
for line in f: |
| 560 |
arr = line.strip().split('=', 1) |
| 561 |
if arr[0] == fieldname: |
| 562 |
return arr[1][1:-1] |
| 563 |
return None |
| 564 |
|
| 565 |
def extract_dlname_field(self, la_file: str) -> T.Optional[str]: |
| 566 |
return self.extract_field(la_file, 'dlname') |
| 567 |
|
| 568 |
def extract_libdir_field(self, la_file: str) -> T.Optional[str]: |
| 569 |
return self.extract_field(la_file, 'libdir') |
| 570 |
|
| 571 |
def extract_libtool_shlib(self, la_file: str) -> T.Optional[str]: |
| 572 |
''' |
| 573 |
Returns the path to the shared library |
| 574 |
corresponding to this .la file |
| 575 |
''' |
| 576 |
dlname = self.extract_dlname_field(la_file) |
| 577 |
if dlname is None: |
| 578 |
return None |
| 579 |
|
| 580 |
# Darwin uses absolute paths where possible; since the libtool files never |
| 581 |
# contain absolute paths, use the libdir field |
| 582 |
if self.env.machines[self.for_machine].is_darwin(): |
| 583 |
dlbasename = os.path.basename(dlname) |
| 584 |
libdir = self.extract_libdir_field(la_file) |
| 585 |
if libdir is None: |
| 586 |
return dlbasename |
| 587 |
return os.path.join(libdir, dlbasename) |
| 588 |
# From the comments in extract_libtool(), older libtools had |
| 589 |
# a path rather than the raw dlname |
| 590 |
return os.path.basename(dlname) |
| 591 |
|
| 592 |
def get_variable(self, *, cmake: T.Optional[str] = None, pkgconfig: T.Optional[str] = None, |
| 593 |
configtool: T.Optional[str] = None, internal: T.Optional[str] = None, |
| 594 |
system: T.Optional[str] = None, default_value: T.Optional[str] = None, |
| 595 |
pkgconfig_define: PkgConfigDefineType = None) -> str: |
| 596 |
if pkgconfig: |
| 597 |
try: |
| 598 |
variable = self.pkgconfig.variable(self.name, pkgconfig, pkgconfig_define) |
| 599 |
if variable is not None: |
| 600 |
return variable |
| 601 |
except DependencyException: |
| 602 |
pass |
| 603 |
if default_value is not None: |
| 604 |
return default_value |
| 605 |
raise DependencyException(f'Could not get pkg-config variable and no default provided for {self!r}') |