| 1 |
# SPDX-License-Identifier: Apache-2.0 |
| 2 |
# Copyright 2012-2020 The Meson development team |
| 3 |
# Copyright © 2020-2023 Intel Corporation |
| 4 |
|
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
from functools import lru_cache |
| 8 |
import collections |
| 9 |
import enum |
| 10 |
import os |
| 11 |
import re |
| 12 |
import typing as T |
| 13 |
|
| 14 |
if T.TYPE_CHECKING: |
| 15 |
from .linkers import StaticLinker |
| 16 |
from .compilers import Compiler |
| 17 |
|
| 18 |
# execinfo is a compiler lib on BSD |
| 19 |
UNIXY_COMPILER_INTERNAL_LIBS = ['m', 'c', 'pthread', 'dl', 'rt', 'execinfo'] |
| 20 |
|
| 21 |
|
| 22 |
class Dedup(enum.Enum): |
| 23 |
|
| 24 |
"""What kind of deduplication can be done to compiler args. |
| 25 |
|
| 26 |
OVERRIDDEN - Whether an argument can be 'overridden' by a later argument. |
| 27 |
For example, -DFOO defines FOO and -UFOO undefines FOO. In this case, |
| 28 |
we can safely remove the previous occurrence and add a new one. The |
| 29 |
same is true for include paths and library paths with -I and -L. |
| 30 |
UNIQUE - Arguments that once specified cannot be undone, such as `-c` or |
| 31 |
`-pipe`. New instances of these can be completely skipped. |
| 32 |
NO_DEDUP - When it matters where or how many times on the command-line |
| 33 |
a particular argument is present. This can matter for symbol |
| 34 |
resolution in static or shared libraries, so we cannot de-dup or |
| 35 |
reorder them. |
| 36 |
""" |
| 37 |
|
| 38 |
NO_DEDUP = 0 |
| 39 |
UNIQUE = 1 |
| 40 |
OVERRIDDEN = 2 |
| 41 |
|
| 42 |
|
| 43 |
class CompilerArgs(T.MutableSequence[str]): |
| 44 |
''' |
| 45 |
List-like class that manages a list of compiler arguments. Should be used |
| 46 |
while constructing compiler arguments from various sources. Can be |
| 47 |
operated with ordinary lists, so this does not need to be used |
| 48 |
everywhere. |
| 49 |
|
| 50 |
All arguments must be inserted and stored in GCC-style (-lfoo, -Idir, etc) |
| 51 |
and can converted to the native type of each compiler by using the |
| 52 |
.to_native() method to which you must pass an instance of the compiler or |
| 53 |
the compiler class. |
| 54 |
|
| 55 |
New arguments added to this class (either with .append(), .extend(), or +=) |
| 56 |
are added in a way that ensures that they override previous arguments. |
| 57 |
For example: |
| 58 |
|
| 59 |
>>> a = ['-Lfoo', '-lbar'] |
| 60 |
>>> a += ['-Lpho', '-lbaz'] |
| 61 |
>>> print(a) |
| 62 |
['-Lpho', '-Lfoo', '-lbar', '-lbaz'] |
| 63 |
|
| 64 |
Arguments will also be de-duped if they can be de-duped safely. |
| 65 |
|
| 66 |
Note that because of all this, this class is not commutative and does not |
| 67 |
preserve the order of arguments if it is safe to not. For example: |
| 68 |
>>> ['-Ifoo', '-Ibar'] + ['-Ifez', '-Ibaz', '-Werror'] |
| 69 |
['-Ifez', '-Ibaz', '-Ifoo', '-Ibar', '-Werror'] |
| 70 |
>>> ['-Ifez', '-Ibaz', '-Werror'] + ['-Ifoo', '-Ibar'] |
| 71 |
['-Ifoo', '-Ibar', '-Ifez', '-Ibaz', '-Werror'] |
| 72 |
|
| 73 |
''' |
| 74 |
# Arg prefixes that override by prepending instead of appending |
| 75 |
prepend_prefixes: T.Tuple[str, ...] = () |
| 76 |
|
| 77 |
# Arg prefixes and standalone args that must be de-duped by returning 2 |
| 78 |
dedup2_prefixes: T.Tuple[str, ...] = () |
| 79 |
dedup2_suffixes: T.Tuple[str, ...] = () |
| 80 |
dedup2_args: T.Tuple[str, ...] = () |
| 81 |
|
| 82 |
# Arg prefixes and standalone args that must be de-duped by returning 1 |
| 83 |
# |
| 84 |
# NOTE: not thorough. A list of potential corner cases can be found in |
| 85 |
# https://github.com/mesonbuild/meson/pull/4593#pullrequestreview-182016038 |
| 86 |
dedup1_prefixes: T.Tuple[str, ...] = () |
| 87 |
dedup1_suffixes = ('.lib', '.dll', '.so', '.dylib', '.a') |
| 88 |
# Match a .so of the form path/to/libfoo.so.0.1.0 |
| 89 |
# Only UNIX shared libraries require this. Others have a fixed extension. |
| 90 |
dedup1_regex = re.compile(r'([\/\\]|\A)lib.*\.so(\.[0-9]+)?(\.[0-9]+)?(\.[0-9]+)?$') |
| 91 |
dedup1_args: T.Tuple[str, ...] = () |
| 92 |
# In generate_link() we add external libs without de-dup, but we must |
| 93 |
# *always* de-dup these because they're special arguments to the linker |
| 94 |
# TODO: these should probably move too |
| 95 |
always_dedup_args = tuple('-l' + lib for lib in UNIXY_COMPILER_INTERNAL_LIBS) |
| 96 |
|
| 97 |
def __init__(self, compiler: T.Union['Compiler', 'StaticLinker'], |
| 98 |
iterable: T.Optional[T.Iterable[str]] = None): |
| 99 |
self.compiler = compiler |
| 100 |
|
| 101 |
if isinstance(iterable, CompilerArgs): |
| 102 |
iterable.flush_pre_post() |
| 103 |
# list(iter(x)) is over two times slower than list(x), so |
| 104 |
# pass the underlying list to list() directly, instead of an iterator |
| 105 |
iterable = iterable._container |
| 106 |
self._container: T.List[str] = list(iterable) if iterable is not None else [] |
| 107 |
|
| 108 |
self.pre: T.Deque[str] = collections.deque() |
| 109 |
self.post: T.List[str] = [] |
| 110 |
self.needs_override_check: bool = False |
| 111 |
|
| 112 |
# Flush the saved pre and post list into the _container list |
| 113 |
# |
| 114 |
# This correctly deduplicates the entries after _can_dedup definition |
| 115 |
# Note: This function is designed to work without delete operations, as deletions are worsening the performance a lot. |
| 116 |
def flush_pre_post(self) -> None: |
| 117 |
if not self.needs_override_check: |
| 118 |
if self.pre: |
| 119 |
self._container[0:0] = self.pre |
| 120 |
self.pre.clear() |
| 121 |
if self.post: |
| 122 |
self._container.extend(self.post) |
| 123 |
self.post.clear() |
| 124 |
return |
| 125 |
|
| 126 |
new: T.List[str] = [] |
| 127 |
pre_flush_set: T.Set[str] = set() |
| 128 |
post_flush: T.Deque[str] = collections.deque() |
| 129 |
post_flush_set: T.Set[str] = set() |
| 130 |
|
| 131 |
#The two lists are here walked from the front to the back, in order to not need removals for deduplication |
| 132 |
for a in self.pre: |
| 133 |
dedup = self._can_dedup(a) |
| 134 |
if a not in pre_flush_set: |
| 135 |
new.append(a) |
| 136 |
if dedup is Dedup.OVERRIDDEN: |
| 137 |
pre_flush_set.add(a) |
| 138 |
for a in reversed(self.post): |
| 139 |
dedup = self._can_dedup(a) |
| 140 |
if a not in post_flush_set: |
| 141 |
post_flush.appendleft(a) |
| 142 |
if dedup is Dedup.OVERRIDDEN: |
| 143 |
post_flush_set.add(a) |
| 144 |
|
| 145 |
#pre and post will overwrite every element that is in the container |
| 146 |
#only copy over args that are in _container but not in the post flush or pre flush set |
| 147 |
for a in self._container: |
| 148 |
if a not in post_flush_set and a not in pre_flush_set: |
| 149 |
new.append(a) |
| 150 |
new.extend(post_flush) |
| 151 |
|
| 152 |
self._container = new |
| 153 |
self.pre.clear() |
| 154 |
self.post.clear() |
| 155 |
self.needs_override_check = False |
| 156 |
|
| 157 |
def __iter__(self) -> T.Iterator[str]: |
| 158 |
# see also __init__, where this method is essentially inlined |
| 159 |
self.flush_pre_post() |
| 160 |
return iter(self._container) |
| 161 |
|
| 162 |
@T.overload # noqa: F811 |
| 163 |
def __getitem__(self, index: int) -> str: # noqa: F811 |
| 164 |
pass |
| 165 |
|
| 166 |
@T.overload # noqa: F811 |
| 167 |
def __getitem__(self, index: slice) -> T.MutableSequence[str]: # noqa: F811 |
| 168 |
pass |
| 169 |
|
| 170 |
def __getitem__(self, index: T.Union[int, slice]) -> T.Union[str, T.MutableSequence[str]]: # noqa: F811 |
| 171 |
self.flush_pre_post() |
| 172 |
return self._container[index] |
| 173 |
|
| 174 |
@T.overload # noqa: F811 |
| 175 |
def __setitem__(self, index: int, value: str) -> None: # noqa: F811 |
| 176 |
pass |
| 177 |
|
| 178 |
@T.overload # noqa: F811 |
| 179 |
def __setitem__(self, index: slice, value: T.Iterable[str]) -> None: # noqa: F811 |
| 180 |
pass |
| 181 |
|
| 182 |
def __setitem__(self, index: T.Union[int, slice], value: T.Union[str, T.Iterable[str]]) -> None: # noqa: F811 |
| 183 |
self.flush_pre_post() |
| 184 |
self._container[index] = value # type: ignore # TODO: fix 'Invalid index type' and 'Incompatible types in assignment' errors |
| 185 |
|
| 186 |
def __delitem__(self, index: T.Union[int, slice]) -> None: |
| 187 |
self.flush_pre_post() |
| 188 |
del self._container[index] |
| 189 |
|
| 190 |
def __len__(self) -> int: |
| 191 |
return len(self._container) + len(self.pre) + len(self.post) |
| 192 |
|
| 193 |
def insert(self, index: int, value: str) -> None: |
| 194 |
self.flush_pre_post() |
| 195 |
self._container.insert(index, value) |
| 196 |
|
| 197 |
def copy(self) -> 'CompilerArgs': |
| 198 |
self.flush_pre_post() |
| 199 |
return type(self)(self.compiler, self._container.copy()) |
| 200 |
|
| 201 |
@classmethod |
| 202 |
@lru_cache(maxsize=None) |
| 203 |
def _can_dedup(cls, arg: str) -> Dedup: |
| 204 |
"""Returns whether the argument can be safely de-duped. |
| 205 |
|
| 206 |
In addition to these, we handle library arguments specially. |
| 207 |
With GNU ld, we surround library arguments with -Wl,--start/end-group |
| 208 |
to recursively search for symbols in the libraries. This is not needed |
| 209 |
with other linkers. |
| 210 |
""" |
| 211 |
|
| 212 |
# Argument prefixes that are actually not used as a prefix must never |
| 213 |
# be deduplicated because they are defined by what comes _after_ them. |
| 214 |
# Thus deduping this: |
| 215 |
# -D FOO -D BAR |
| 216 |
# would yield either |
| 217 |
# -D FOO BAR |
| 218 |
# or |
| 219 |
# FOO -D BAR |
| 220 |
# both of which are invalid. |
| 221 |
if arg in cls.dedup1_prefixes or arg in cls.dedup2_prefixes: |
| 222 |
return Dedup.NO_DEDUP |
| 223 |
if arg in cls.dedup2_args or \ |
| 224 |
arg.startswith(cls.dedup2_prefixes) or \ |
| 225 |
arg.endswith(cls.dedup2_suffixes): |
| 226 |
return Dedup.OVERRIDDEN |
| 227 |
if arg in cls.dedup1_args or \ |
| 228 |
arg.startswith(cls.dedup1_prefixes) or \ |
| 229 |
arg.endswith(cls.dedup1_suffixes) or \ |
| 230 |
re.search(cls.dedup1_regex, arg): |
| 231 |
return Dedup.UNIQUE |
| 232 |
return Dedup.NO_DEDUP |
| 233 |
|
| 234 |
@classmethod |
| 235 |
@lru_cache(maxsize=None) |
| 236 |
def _should_prepend(cls, arg: str) -> bool: |
| 237 |
return arg.startswith(cls.prepend_prefixes) |
| 238 |
|
| 239 |
def to_native(self, copy: bool = False) -> T.List[str]: |
| 240 |
# Check if we need to add --start/end-group for circular dependencies |
| 241 |
# between static libraries, and for recursively searching for symbols |
| 242 |
# needed by static libraries that are provided by object files or |
| 243 |
# shared libraries. |
| 244 |
self.flush_pre_post() |
| 245 |
if copy: |
| 246 |
new = self.copy() |
| 247 |
else: |
| 248 |
new = self |
| 249 |
return self.compiler.unix_args_to_native(new._container) |
| 250 |
|
| 251 |
def append_direct(self, arg: str) -> None: |
| 252 |
''' |
| 253 |
Append the specified argument without any reordering or de-dup except |
| 254 |
for absolute paths to libraries, etc, which can always be de-duped |
| 255 |
safely. |
| 256 |
''' |
| 257 |
self.flush_pre_post() |
| 258 |
if os.path.isabs(arg): |
| 259 |
self.append(arg) |
| 260 |
else: |
| 261 |
self._container.append(arg) |
| 262 |
|
| 263 |
def extend_direct(self, iterable: T.Iterable[str]) -> None: |
| 264 |
''' |
| 265 |
Extend using the elements in the specified iterable without any |
| 266 |
reordering or de-dup except for absolute paths where the order of |
| 267 |
include search directories is not relevant |
| 268 |
''' |
| 269 |
self.flush_pre_post() |
| 270 |
for elem in iterable: |
| 271 |
self.append_direct(elem) |
| 272 |
|
| 273 |
def extend_preserving_lflags(self, iterable: T.Iterable[str]) -> None: |
| 274 |
normal_flags = [] |
| 275 |
lflags = [] |
| 276 |
for i in iterable: |
| 277 |
if i not in self.always_dedup_args and (i.startswith('-l') or i.startswith('-L')): |
| 278 |
lflags.append(i) |
| 279 |
else: |
| 280 |
normal_flags.append(i) |
| 281 |
self.extend(normal_flags) |
| 282 |
self.extend_direct(lflags) |
| 283 |
|
| 284 |
def __add__(self, args: T.Iterable[str]) -> 'CompilerArgs': |
| 285 |
self.flush_pre_post() |
| 286 |
new = self.copy() |
| 287 |
new += args |
| 288 |
return new |
| 289 |
|
| 290 |
def __iadd__(self, args: T.Iterable[str]) -> 'CompilerArgs': |
| 291 |
''' |
| 292 |
Add two CompilerArgs while taking into account overriding of arguments |
| 293 |
and while preserving the order of arguments as much as possible |
| 294 |
''' |
| 295 |
tmp_pre: T.Deque[str] = collections.deque() |
| 296 |
if not isinstance(args, collections.abc.Iterable): |
| 297 |
raise TypeError(f'can only concatenate Iterable[str] (not "{args}") to CompilerArgs') |
| 298 |
for arg in args: |
| 299 |
# If the argument can be de-duped, do it either by removing the |
| 300 |
# previous occurrence of it and adding a new one, or not adding the |
| 301 |
# new occurrence. |
| 302 |
dedup = self._can_dedup(arg) |
| 303 |
if dedup is Dedup.UNIQUE: |
| 304 |
# Argument already exists and adding a new instance is useless |
| 305 |
if arg in self._container or arg in self.pre or arg in self.post: |
| 306 |
continue |
| 307 |
elif dedup is Dedup.OVERRIDDEN: |
| 308 |
self.needs_override_check = True |
| 309 |
if self._should_prepend(arg): |
| 310 |
tmp_pre.appendleft(arg) |
| 311 |
else: |
| 312 |
self.post.append(arg) |
| 313 |
self.pre.extendleft(tmp_pre) |
| 314 |
#pre and post is going to be merged later before a iter call |
| 315 |
return self |
| 316 |
|
| 317 |
def __radd__(self, args: T.Iterable[str]) -> 'CompilerArgs': |
| 318 |
self.flush_pre_post() |
| 319 |
new = type(self)(self.compiler, args) |
| 320 |
new += self |
| 321 |
return new |
| 322 |
|
| 323 |
def __eq__(self, other: object) -> T.Union[bool]: |
| 324 |
self.flush_pre_post() |
| 325 |
# Only allow equality checks against other CompilerArgs and lists instances |
| 326 |
if isinstance(other, CompilerArgs): |
| 327 |
return self.compiler == other.compiler and self._container == other._container |
| 328 |
elif isinstance(other, list): |
| 329 |
return self._container == other |
| 330 |
return NotImplemented |
| 331 |
|
| 332 |
def append(self, arg: str) -> None: |
| 333 |
self += [arg] |
| 334 |
|
| 335 |
def extend(self, args: T.Iterable[str]) -> None: |
| 336 |
self += args |
| 337 |
|
| 338 |
def __repr__(self) -> str: |
| 339 |
self.flush_pre_post() |
| 340 |
return f'CompilerArgs({self.compiler!r}, {self._container!r})' |