Debian Codegraph @

mesonbuild/dependencies/boost.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2013-2020 The Meson development team
3
4 from __future__ import annotations
5
6 import re
7 import dataclasses
8 import functools
9 import typing as T
10 from pathlib import Path
11
12 from .. import mlog
13 from .. import mesonlib
14 from ..options import OptionKey
15
16 from .base import DependencyException, SystemDependency
17 from .detect import packages
18 from .pkgconfig import PkgConfigDependency
19 from .misc import threads_factory
20
21 if T.TYPE_CHECKING:
22 from ..envconfig import Properties
23 from ..environment import Environment
24 from .base import DependencyObjectKWs
25
26 # On windows 3 directory layouts are supported:
27 # * The default layout (versioned) installed:
28 # - $BOOST_ROOT/include/boost-x_x/boost/*.hpp
29 # - $BOOST_ROOT/lib/*.lib
30 # * The non-default layout (system) installed:
31 # - $BOOST_ROOT/include/boost/*.hpp
32 # - $BOOST_ROOT/lib/*.lib
33 # * The pre-built binaries from sf.net:
34 # - $BOOST_ROOT/boost/*.hpp
35 # - $BOOST_ROOT/lib<arch>-<compiler>/*.lib where arch=32/64 and compiler=msvc-14.1
36 #
37 # Note that we should also try to support:
38 # mingw-w64 / Windows : libboost_<module>-mt.a (location = <prefix>/mingw64/lib/)
39 # libboost_<module>-mt.dll.a
40 #
41 # The `modules` argument accept library names. This is because every module that
42 # has libraries to link against also has multiple options regarding how to
43 # link. See for example:
44 # * http://www.boost.org/doc/libs/1_65_1/libs/test/doc/html/boost_test/usage_variants.html
45 # * http://www.boost.org/doc/libs/1_65_1/doc/html/stacktrace/configuration_and_build.html
46 # * http://www.boost.org/doc/libs/1_65_1/libs/math/doc/html/math_toolkit/main_tr1.html
47
48 # **On Unix**, official packaged versions of boost libraries follow the following schemes:
49 #
50 # Linux / Debian: libboost_<module>.so -> libboost_<module>.so.1.66.0
51 # Linux / Red Hat: libboost_<module>.so -> libboost_<module>.so.1.66.0
52 # Linux / OpenSuse: libboost_<module>.so -> libboost_<module>.so.1.66.0
53 # Win / Cygwin: libboost_<module>.dll.a (location = /usr/lib)
54 # libboost_<module>.a
55 # cygboost_<module>_1_64.dll (location = /usr/bin)
56 # Win / VS: boost_<module>-vc<ver>-mt[-gd]-<arch>-1_67.dll (location = C:/local/boost_1_67_0)
57 # Mac / homebrew: libboost_<module>.dylib + libboost_<module>-mt.dylib (location = /usr/local/lib)
58 # Mac / macports: libboost_<module>.dylib + libboost_<module>-mt.dylib (location = /opt/local/lib)
59 #
60 # It's not clear that any other abi tags (e.g. -gd) are used in official packages.
61 #
62 # On Linux systems, boost libs have multithreading support enabled, but without the -mt tag.
63 #
64 # Boost documentation recommends using complex abi tags like "-lboost_regex-gcc34-mt-d-1_36".
65 # (See http://www.boost.org/doc/libs/1_66_0/more/getting_started/unix-variants.html#library-naming)
66 # However, its not clear that any Unix distribution follows this scheme.
67 # Furthermore, the boost documentation for unix above uses examples from windows like
68 # "libboost_regex-vc71-mt-d-x86-1_34.lib", so apparently the abi tags may be more aimed at windows.
69 #
70 # We follow the following strategy for finding modules:
71 # A) Detect potential boost root directories (uses also BOOST_ROOT env var)
72 # B) Foreach candidate
73 # 1. Look for the boost headers (boost/version.pp)
74 # 2. Find all boost libraries
75 # 2.1 Add all libraries in lib*
76 # 2.2 Filter out non boost libraries
77 # 2.3 Filter the remaining libraries based on the meson requirements (static/shared, etc.)
78 # 2.4 Ensure that all libraries have the same boost tag (and are thus compatible)
79 # 3. Select the libraries matching the requested modules
80
81 @dataclasses.dataclass(eq=False, order=False)
82 class UnknownFileException(Exception):
83 path: Path
84
85 @functools.total_ordering
86 class BoostIncludeDir():
87 def __init__(self, path: Path, version_int: int):
88 self.path = path
89 self.version_int = version_int
90 major = int(self.version_int / 100000)
91 minor = int((self.version_int / 100) % 1000)
92 patch = int(self.version_int % 100)
93 self.version = f'{major}.{minor}.{patch}'
94 self.version_lib = f'{major}_{minor}'
95
96 def __repr__(self) -> str:
97 return f'<BoostIncludeDir: {self.version} -- {self.path}>'
98
99 def __lt__(self, other: object) -> bool:
100 if isinstance(other, BoostIncludeDir):
101 return (self.version_int, self.path) < (other.version_int, other.path)
102 return NotImplemented
103
104 @functools.total_ordering
105 class BoostLibraryFile():
106 # Python libraries are special because of the included
107 # minor version in the module name.
108 boost_python_libs = ['boost_python', 'boost_numpy']
109 reg_python_mod_split = re.compile(r'(boost_[a-zA-Z]+)([0-9]*)')
110
111 reg_abi_tag = re.compile(r'^s?g?y?d?p?n?$')
112 reg_ver_tag = re.compile(r'^[0-9_]+$')
113
114 def __init__(self, path: Path):
115 self.path = path
116 self.name = self.path.name
117
118 # Initialize default properties
119 self.static = False
120 self.toolset = ''
121 self.arch = ''
122 self.version_lib = ''
123 self.mt = True
124
125 self.runtime_static = False
126 self.runtime_debug = False
127 self.python_debug = False
128 self.debug = False
129 self.stlport = False
130 self.deprecated_iostreams = False
131
132 # Post process the library name
133 name_parts = self.name.split('.')
134 self.basename = name_parts[0]
135 self.suffixes = name_parts[1:]
136 self.vers_raw = [x for x in self.suffixes if x.isdigit()]
137 self.suffixes = [x for x in self.suffixes if not x.isdigit()]
138 self.nvsuffix = '.'.join(self.suffixes) # Used for detecting the library type
139 self.nametags = self.basename.split('-')
140 self.mod_name = self.nametags[0]
141 if self.mod_name.startswith('lib'):
142 self.mod_name = self.mod_name[3:]
143
144 # Set library version if possible
145 if len(self.vers_raw) >= 2:
146 self.version_lib = '{}_{}'.format(self.vers_raw[0], self.vers_raw[1])
147
148 # Detecting library type
149 if self.nvsuffix in {'so', 'dll', 'dll.a', 'dll.lib', 'dylib'}:
150 self.static = False
151 elif self.nvsuffix in {'a', 'lib'}:
152 self.static = True
153 else:
154 raise UnknownFileException(self.path)
155
156 # boost_.lib is the dll import library
157 if self.basename.startswith('boost_') and self.nvsuffix == 'lib':
158 self.static = False
159
160 # Process tags
161 tags = self.nametags[1:]
162 # Filter out the python version tag and fix modname
163 if self.is_python_lib():
164 tags = self.fix_python_name(tags)
165 if not tags:
166 return
167
168 # Without any tags mt is assumed, however, an absence of mt in the name
169 # with tags present indicates that the lib was built without mt support
170 self.mt = False
171 for i in tags:
172 if i == 'mt':
173 self.mt = True
174 elif len(i) == 3 and i[1:] in {'32', '64'}:
175 self.arch = i
176 elif BoostLibraryFile.reg_abi_tag.match(i):
177 self.runtime_static = 's' in i
178 self.runtime_debug = 'g' in i
179 self.python_debug = 'y' in i
180 self.debug = 'd' in i
181 self.stlport = 'p' in i
182 self.deprecated_iostreams = 'n' in i
183 elif BoostLibraryFile.reg_ver_tag.match(i):
184 self.version_lib = i
185 else:
186 self.toolset = i
187
188 def __repr__(self) -> str:
189 return f'<LIB: {self.abitag} {self.mod_name:<32} {self.path}>'
190
191 def __lt__(self, other: object) -> bool:
192 if isinstance(other, BoostLibraryFile):
193 return (
194 self.mod_name, self.static, self.version_lib, self.arch,
195 not self.mt, not self.runtime_static,
196 not self.debug, self.runtime_debug, self.python_debug,
197 self.stlport, self.deprecated_iostreams,
198 self.name,
199 ) < (
200 other.mod_name, other.static, other.version_lib, other.arch,
201 not other.mt, not other.runtime_static,
202 not other.debug, other.runtime_debug, other.python_debug,
203 other.stlport, other.deprecated_iostreams,
204 other.name,
205 )
206 return NotImplemented
207
208 def __eq__(self, other: object) -> bool:
209 if isinstance(other, BoostLibraryFile):
210 return self.name == other.name
211 return NotImplemented
212
213 def __hash__(self) -> int:
214 return hash(self.name)
215
216 @property
217 def abitag(self) -> str:
218 abitag = ''
219 abitag += 'S' if self.static else '-'
220 abitag += 'M' if self.mt else '-'
221 abitag += ' '
222 abitag += 's' if self.runtime_static else '-'
223 abitag += 'g' if self.runtime_debug else '-'
224 abitag += 'y' if self.python_debug else '-'
225 abitag += 'd' if self.debug else '-'
226 abitag += 'p' if self.stlport else '-'
227 abitag += 'n' if self.deprecated_iostreams else '-'
228 abitag += ' ' + (self.arch or '???')
229 abitag += ' ' + (self.toolset or '?')
230 abitag += ' ' + (self.version_lib or 'x_xx')
231 return abitag
232
233 def is_boost(self) -> bool:
234 return any(self.name.startswith(x) for x in ['libboost_', 'boost_'])
235
236 def is_python_lib(self) -> bool:
237 return any(self.mod_name.startswith(x) for x in BoostLibraryFile.boost_python_libs)
238
239 def fix_python_name(self, tags: T.List[str]) -> T.List[str]:
240 # Handle the boost_python naming madness.
241 # See https://github.com/mesonbuild/meson/issues/4788 for some distro
242 # specific naming variations.
243 other_tags: T.List[str] = []
244
245 # Split the current modname into the base name and the version
246 m_cur = BoostLibraryFile.reg_python_mod_split.match(self.mod_name)
247 cur_name = m_cur.group(1)
248 cur_vers = m_cur.group(2)
249
250 # Update the current version string if the new version string is longer
251 def update_vers(new_vers: str) -> None:
252 nonlocal cur_vers
253 new_vers = new_vers.replace('_', '')
254 new_vers = new_vers.replace('.', '')
255 if not new_vers.isdigit():
256 return
257 if len(new_vers) > len(cur_vers):
258 cur_vers = new_vers
259
260 for i in tags:
261 if i.startswith('py'):
262 update_vers(i[2:])
263 elif i.isdigit():
264 update_vers(i)
265 elif len(i) >= 3 and i[0].isdigit() and i[2].isdigit() and i[1] == '.':
266 update_vers(i)
267 else:
268 other_tags += [i]
269
270 self.mod_name = cur_name + cur_vers
271 return other_tags
272
273 def mod_name_matches(self, mod_name: str) -> bool:
274 if self.mod_name == mod_name:
275 return True
276 if not self.is_python_lib():
277 return False
278
279 m_cur = BoostLibraryFile.reg_python_mod_split.match(self.mod_name)
280 m_arg = BoostLibraryFile.reg_python_mod_split.match(mod_name)
281
282 if not m_cur or not m_arg:
283 return False
284
285 if m_cur.group(1) != m_arg.group(1):
286 return False
287
288 cur_vers = m_cur.group(2)
289 arg_vers = m_arg.group(2)
290
291 # Always assume python 2 if nothing is specified
292 if not arg_vers:
293 arg_vers = '2'
294
295 return cur_vers.startswith(arg_vers)
296
297 def version_matches(self, version_lib: str) -> bool:
298 # If no version tag is present, assume that it fits
299 if not self.version_lib or not version_lib:
300 return True
301 return self.version_lib == version_lib
302
303 def arch_matches(self, arch: str) -> bool:
304 # If no version tag is present, assume that it fits
305 if not self.arch or not arch:
306 return True
307 return self.arch == arch
308
309 def vscrt_matches(self, vscrt: str) -> bool:
310 # If no vscrt tag present, assume that it fits ['/MD', '/MDd', '/MT', '/MTd']
311 if not vscrt:
312 return True
313 if vscrt in {'/MD', '-MD'}:
314 return not self.runtime_static and not self.runtime_debug
315 elif vscrt in {'/MDd', '-MDd'}:
316 return not self.runtime_static and self.runtime_debug
317 elif vscrt in {'/MT', '-MT'}:
318 return (self.runtime_static or not self.static) and not self.runtime_debug
319 elif vscrt in {'/MTd', '-MTd'}:
320 return (self.runtime_static or not self.static) and self.runtime_debug
321
322 mlog.warning(f'Boost: unknown vscrt tag {vscrt}. This may cause the compilation to fail. Please consider reporting this as a bug.', once=True)
323 return True
324
325 def get_compiler_args(self) -> T.List[str]:
326 args: T.List[str] = []
327 if self.mod_name in boost_libraries:
328 libdef = boost_libraries[self.mod_name]
329 if self.static:
330 args += libdef.static
331 else:
332 args += libdef.shared
333 if self.mt:
334 args += libdef.multi
335 else:
336 args += libdef.single
337 return args
338
339 def get_link_args(self) -> T.List[str]:
340 return [self.path.as_posix()]
341
342 class BoostDependency(SystemDependency):
343 def __init__(self, name: str, environment: Environment, kwargs: DependencyObjectKWs) -> None:
344 kwargs['language'] = 'cpp'
345 super().__init__(name, environment, kwargs)
346 buildtype = environment.coredata.optstore.get_value_for(OptionKey('buildtype'))
347 assert isinstance(buildtype, str)
348 self.debug = buildtype.startswith('debug')
349 self.multithreading = kwargs.get('threading', 'multi') == 'multi'
350
351 self.boost_root: T.Optional[Path] = None
352 self.explicit_static = kwargs.get('static') is not None
353
354 # Extract and validate modules
355 self.modules = kwargs.get('modules', [])
356 for i in self.modules:
357 if i.startswith('boost_'):
358 raise DependencyException('Boost modules must be passed without the boost_ prefix')
359
360 self.modules_found: T.List[str] = []
361 self.modules_missing: T.List[str] = []
362
363 # Do we need threads?
364 if 'thread' in self.modules:
365 if not self._add_sub_dependency(threads_factory(environment, {'native': self.for_machine})):
366 self.is_found = False
367 return
368
369 # Try figuring out the architecture tag
370 self.arch = environment.machines[self.for_machine].cpu_family
371 self.arch = boost_arch_map.get(self.arch, None)
372
373 # First, look for paths specified in a machine file
374 props = self.env.properties[self.for_machine]
375 if any(x in self.env.properties[self.for_machine] for x in
376 ['boost_includedir', 'boost_librarydir', 'boost_root']):
377 self.detect_boost_machine_file(props)
378 return
379
380 # Finally, look for paths from .pc files and from searching the filesystem
381 self.detect_roots()
382
383 def check_and_set_roots(self, roots: T.List[Path], use_system: bool) -> None:
384 roots = list(mesonlib.OrderedSet(roots))
385 for j in roots:
386 # 1. Look for the boost headers (boost/version.hpp)
387 mlog.debug(f'Checking potential boost root {j.as_posix()}')
388 inc_dirs = self.detect_inc_dirs(j)
389 inc_dirs = sorted(inc_dirs, reverse=True) # Prefer the newer versions
390
391 # Early abort when boost is not found
392 if not inc_dirs:
393 continue
394
395 lib_dirs = self.detect_lib_dirs(j, use_system)
396 self.is_found = self.run_check(inc_dirs, lib_dirs)
397 if self.is_found:
398 self.boost_root = j
399 break
400
401 def detect_boost_machine_file(self, props: 'Properties') -> None:
402 """Detect boost with values in the machine file or environment.
403
404 The machine file values are defaulted to the environment values.
405 """
406 # XXX: if we had a TypedDict we wouldn't need this
407 incdir = props.get('boost_includedir')
408 assert incdir is None or isinstance(incdir, str)
409 libdir = props.get('boost_librarydir')
410 assert libdir is None or isinstance(libdir, str)
411
412 if incdir and libdir:
413 inc_dir = Path(incdir)
414 lib_dir = Path(libdir)
415
416 if not inc_dir.is_absolute() or not lib_dir.is_absolute():
417 raise DependencyException('Paths given for boost_includedir and boost_librarydir in machine file must be absolute')
418
419 mlog.debug('Trying to find boost with:')
420 mlog.debug(f' - boost_includedir = {inc_dir}')
421 mlog.debug(f' - boost_librarydir = {lib_dir}')
422
423 return self.detect_split_root(inc_dir, lib_dir)
424
425 elif incdir or libdir:
426 raise DependencyException('Both boost_includedir *and* boost_librarydir have to be set in your machine file (one is not enough)')
427
428 rootdir = props.get('boost_root')
429 # It shouldn't be possible to get here without something in boost_root
430 assert rootdir
431
432 raw_paths = mesonlib.stringlistify(rootdir)
433 paths = [Path(x) for x in raw_paths]
434 if paths and any(not x.is_absolute() for x in paths):
435 raise DependencyException('boost_root path given in machine file must be absolute')
436
437 self.check_and_set_roots(paths, use_system=False)
438
439 def run_check(self, inc_dirs: T.List[BoostIncludeDir], lib_dirs: T.List[Path]) -> bool:
440 mlog.debug(' - potential library dirs: {}'.format([x.as_posix() for x in lib_dirs]))
441 mlog.debug(' - potential include dirs: {}'.format([x.path.as_posix() for x in inc_dirs]))
442
443 must_have_library = ['boost_python']
444
445 # 2. Find all boost libraries
446 libs: T.List[BoostLibraryFile] = []
447 for i in lib_dirs:
448 libs = self.detect_libraries(i)
449 if libs:
450 mlog.debug(f' - found boost library dir: {i}')
451 # mlog.debug(' - raw library list:')
452 # for j in libs:
453 # mlog.debug(' - {}'.format(j))
454 break
455 libs = sorted(set(libs))
456
457 any_libs_found = len(libs) > 0
458 if not any_libs_found:
459 return False
460
461 modules = ['boost_' + x for x in self.modules]
462 for inc in inc_dirs:
463 mlog.debug(f' - found boost {inc.version} include dir: {inc.path}')
464 f_libs = self.filter_libraries(libs, inc.version_lib)
465
466 mlog.debug(' - filtered library list:')
467 for j in f_libs:
468 mlog.debug(f' - {j}')
469
470 # 3. Select the libraries matching the requested modules
471 not_found_as_libs: T.List[str] = []
472 selected_modules: T.List[BoostLibraryFile] = []
473 for mod in modules:
474 found = False
475 for l in f_libs:
476 if l.mod_name_matches(mod):
477 selected_modules += [l]
478 found = True
479 break
480 if not found:
481 not_found_as_libs += [mod]
482
483 # If a lib is not found, but an include directory exists,
484 # assume it is a header only module.
485 not_found: T.List[str] = []
486 for boost_modulename in not_found_as_libs:
487 assert boost_modulename.startswith('boost_')
488 if boost_modulename in must_have_library:
489 not_found.append(boost_modulename)
490 continue
491 include_subdir = boost_modulename.replace('boost_', 'boost/', 1)
492 headerdir_found = False
493 for inc_dir in inc_dirs:
494 if (inc_dir.path / include_subdir).is_dir():
495 headerdir_found = True
496 break
497 if not headerdir_found:
498 not_found.append(boost_modulename)
499
500 # log the result
501 mlog.debug(' - found:')
502 comp_args: T.List[str] = []
503 link_args: T.List[str] = []
504 for j in selected_modules:
505 c_args = j.get_compiler_args()
506 l_args = j.get_link_args()
507 mlog.debug(' - {:<24} link={} comp={}'.format(j.mod_name, str(l_args), str(c_args)))
508 comp_args += c_args
509 link_args += l_args
510
511 comp_args = list(mesonlib.OrderedSet(comp_args))
512 link_args = list(mesonlib.OrderedSet(link_args))
513
514 self.modules_found = [x.mod_name for x in selected_modules]
515 self.modules_found = [x[6:] for x in self.modules_found]
516 self.modules_found = sorted(set(self.modules_found))
517 self.modules_missing = not_found
518 self.modules_missing = [x[6:] for x in self.modules_missing]
519 self.modules_missing = sorted(set(self.modules_missing))
520
521 # if we found all modules we are done
522 if not not_found:
523 self.version = inc.version
524 self.compile_args = ['-I' + inc.path.as_posix()]
525 self.compile_args += comp_args
526 self.compile_args += self._extra_compile_args()
527 self.compile_args = list(mesonlib.OrderedSet(self.compile_args))
528 self.link_args = link_args
529 mlog.debug(f' - final compile args: {self.compile_args}')
530 mlog.debug(f' - final link args: {self.link_args}')
531 return True
532
533 # in case we missed something log it and try again
534 mlog.debug(' - NOT found:')
535 for mod in not_found:
536 mlog.debug(f' - {mod}')
537
538 return False
539
540 def detect_inc_dirs(self, root: Path) -> T.List[BoostIncludeDir]:
541 candidates: T.List[Path] = []
542 inc_root = root / 'include'
543
544 candidates += [root / 'boost']
545 candidates += [inc_root / 'boost']
546 if inc_root.is_dir():
547 for i in inc_root.iterdir():
548 if not i.is_dir() or not i.name.startswith('boost-'):
549 continue
550 candidates += [i / 'boost']
551 candidates = [x for x in candidates if x.is_dir()]
552 candidates = [x / 'version.hpp' for x in candidates]
553 candidates = [x for x in candidates if x.exists()]
554 return [self._include_dir_from_version_header(x) for x in candidates]
555
556 def detect_lib_dirs(self, root: Path, use_system: bool) -> T.List[Path]:
557 # First check the system include paths. Only consider those within the
558 # given root path
559
560 if use_system:
561 system_dirs_t = self.clib_compiler.get_library_dirs()
562 system_dirs = [Path(x) for x in system_dirs_t]
563 system_dirs = [x.resolve() for x in system_dirs if x.exists()]
564 system_dirs = [x for x in system_dirs if mesonlib.path_is_in_root(x, root)]
565 system_dirs = list(mesonlib.OrderedSet(system_dirs))
566
567 if system_dirs:
568 return system_dirs
569
570 # No system include paths were found --> fall back to manually looking
571 # for library dirs in root
572 dirs: T.List[Path] = []
573 subdirs: T.List[Path] = []
574 for i in root.iterdir():
575 if i.is_dir() and i.name.startswith('lib'):
576 dirs += [i]
577
578 # Some distros put libraries not directly inside /usr/lib but in /usr/lib/x86_64-linux-gnu
579 for i in dirs:
580 for j in i.iterdir():
581 if j.is_dir() and j.name.endswith('-linux-gnu'):
582 subdirs += [j]
583
584 # Filter out paths that don't match the target arch to avoid finding
585 # the wrong libraries. See https://github.com/mesonbuild/meson/issues/7110
586 if not self.arch:
587 return dirs + subdirs
588
589 arch_list_32 = ['32', 'i386']
590 arch_list_64 = ['64']
591
592 raw_list = dirs + subdirs
593 no_arch = [x for x in raw_list if not any(y in x.name for y in arch_list_32 + arch_list_64)]
594
595 matching_arch: T.List[Path] = []
596 if '32' in self.arch:
597 matching_arch = [x for x in raw_list if any(y in x.name for y in arch_list_32)]
598 elif '64' in self.arch:
599 matching_arch = [x for x in raw_list if any(y in x.name for y in arch_list_64)]
600
601 return sorted(matching_arch) + sorted(no_arch)
602
603 def filter_libraries(self, libs: T.List[BoostLibraryFile], lib_vers: str) -> T.List[BoostLibraryFile]:
604 # MSVC is very picky with the library tags
605 vscrt = ''
606 try:
607 crt_val = self.env.coredata.optstore.get_value_for('b_vscrt')
608 assert isinstance(crt_val, str)
609 vscrt = self.clib_compiler.get_crt_compile_args(crt_val)[0]
610 except (KeyError, IndexError, AttributeError):
611 pass
612
613 # mlog.debug(' - static: {}'.format(self.static))
614 # mlog.debug(' - not explicit static: {}'.format(not self.explicit_static))
615 # mlog.debug(' - mt: {}'.format(self.multithreading))
616 # mlog.debug(' - version: {}'.format(lib_vers))
617 # mlog.debug(' - arch: {}'.format(self.arch))
618 # mlog.debug(' - vscrt: {}'.format(vscrt))
619 libs = [x for x in libs if x.static == self.static or not self.explicit_static]
620 libs = [x for x in libs if x.mt == self.multithreading]
621 if not self.env.machines[self.for_machine].is_openbsd():
622 libs = [x for x in libs if x.version_matches(lib_vers)]
623 libs = [x for x in libs if x.arch_matches(self.arch)]
624 libs = [x for x in libs if x.vscrt_matches(vscrt)]
625 libs = [x for x in libs if x.nvsuffix != 'dll'] # Only link to import libraries
626
627 # Only filter by debug when we are building in release mode. Debug
628 # libraries are automatically preferred through sorting otherwise.
629 if not self.debug:
630 libs = [x for x in libs if not x.debug]
631
632 # Take the abitag from the first library and filter by it. This
633 # ensures that we have a set of libraries that are always compatible.
634 if not libs:
635 return []
636 abitag = libs[0].abitag
637 libs = [x for x in libs if x.abitag == abitag]
638
639 # Assume that we are building against the latest Python version
640 # and that the other ones are only there for backwards compatibility.
641 # https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=1141440
642 no_python_libs = []
643 python_libs = []
644 for l in libs:
645 if l.is_python_lib():
646 python_libs.append(l)
647 else:
648 no_python_libs.append(l)
649 sorted_pylibs = sorted(python_libs, key=lambda l: l.name, reverse=True)
650 libs = no_python_libs + sorted_pylibs[:1]
651
652 return libs
653
654 def detect_libraries(self, libdir: Path) -> T.List[BoostLibraryFile]:
655 libs: T.Set[BoostLibraryFile] = set()
656 for i in libdir.iterdir():
657 if not i.is_file():
658 continue
659 if not any(i.name.startswith(x) for x in ['libboost_', 'boost_']):
660 continue
661 # Windows binaries from SourceForge ship with PDB files alongside
662 # DLLs (#8325). Ignore them.
663 if i.name.endswith('.pdb'):
664 continue
665
666 try:
667 libs.add(BoostLibraryFile(i.resolve()))
668 except UnknownFileException as e:
669 mlog.warning('Boost: ignoring unknown file {} under lib directory'.format(e.path.name))
670
671 return [x for x in libs if x.is_boost()] # Filter out no boost libraries
672
673 def detect_split_root(self, inc_dir: Path, lib_dir: Path) -> None:
674 boost_inc_dir = None
675 for j in [inc_dir / 'version.hpp', inc_dir / 'boost' / 'version.hpp']:
676 if j.is_file():
677 boost_inc_dir = self._include_dir_from_version_header(j)
678 break
679 if not boost_inc_dir:
680 self.is_found = False
681 return
682
683 self.is_found = self.run_check([boost_inc_dir], [lib_dir])
684
685 def detect_roots(self) -> None:
686 roots: T.List[Path] = []
687
688 # Try getting the BOOST_ROOT from a boost.pc if it exists. This primarily
689 # allows BoostDependency to find boost from Conan. See #5438
690 try:
691 boost_pc = PkgConfigDependency('boost', self.env, {'required': False, 'native': self.for_machine})
692 if boost_pc.found():
693 boost_lib_dir = boost_pc.get_variable(pkgconfig='libdir')
694 boost_inc_dir = boost_pc.get_variable(pkgconfig='includedir')
695 if boost_lib_dir and boost_inc_dir:
696 mlog.debug('Trying to find boost with:')
697 mlog.debug(f' - boost_includedir = {Path(boost_inc_dir)}')
698 mlog.debug(f' - boost_librarydir = {Path(boost_lib_dir)}')
699
700 self.detect_split_root(Path(boost_inc_dir), Path(boost_lib_dir))
701 return
702 else:
703 boost_root = boost_pc.get_variable(pkgconfig='prefix')
704 if boost_root:
705 roots += [Path(boost_root)]
706 except DependencyException:
707 pass
708
709 # Add roots from system paths
710 inc_paths = [Path(x) for x in self.clib_compiler.get_default_include_dirs()]
711 inc_paths = [x.parent for x in inc_paths if x.exists()]
712 inc_paths = [x.resolve() for x in inc_paths]
713 roots += inc_paths
714
715 m = self.env.machines[self.for_machine]
716 # Add system paths
717 if m.is_windows():
718 # Where boost built from source actually installs it
719 c_root = Path('C:/Boost')
720 if c_root.is_dir():
721 roots += [c_root]
722
723 # Where boost documentation says it should be
724 prog_files = Path('C:/Program Files/boost')
725 # Where boost prebuilt binaries are
726 local_boost = Path('C:/local')
727
728 candidates: T.List[Path] = []
729 if prog_files.is_dir():
730 candidates += [*prog_files.iterdir()]
731 if local_boost.is_dir():
732 candidates += [*local_boost.iterdir()]
733
734 roots += [x for x in candidates if x.name.lower().startswith('boost') and x.is_dir()]
735 else:
736 tmp: T.List[Path] = []
737
738 # Add some default system paths
739 if m.is_darwin():
740 tmp.extend([
741 Path('/opt/homebrew/'), # for Apple Silicon MacOS
742 Path('/usr/local/opt/boost'), # for Intel Silicon MacOS
743 ])
744 tmp += [Path('/opt/local')]
745 tmp += [Path('/usr/local')]
746 tmp += [Path('/usr')]
747
748 # Cleanup paths
749 tmp = [x for x in tmp if x.is_dir()]
750 tmp = [x.resolve() for x in tmp]
751 roots += tmp
752
753 self.check_and_set_roots(roots, use_system=True)
754
755 def log_details(self) -> str:
756 res = ''
757 if self.modules_found:
758 res += 'found: ' + ', '.join(self.modules_found)
759 if self.modules_missing:
760 if res:
761 res += ' | '
762 res += 'missing: ' + ', '.join(self.modules_missing)
763 return res
764
765 def log_info(self) -> str:
766 if self.boost_root:
767 return self.boost_root.as_posix()
768 return ''
769
770 def _include_dir_from_version_header(self, hfile: Path) -> BoostIncludeDir:
771 # Extract the version with a regex. Using clib_compiler.get_define would
772 # also work, however, this is slower (since it the compiler has to be
773 # invoked) and overkill since the layout of the header is always the same.
774 assert hfile.exists()
775 raw = hfile.read_text(encoding='utf-8')
776 m = re.search(r'#define\s+BOOST_VERSION\s+([0-9]+)', raw)
777 if not m:
778 mlog.debug(f'Failed to extract version information from {hfile}')
779 return BoostIncludeDir(hfile.parents[1], 0)
780 return BoostIncludeDir(hfile.parents[1], int(m.group(1)))
781
782 def _extra_compile_args(self) -> T.List[str]:
783 # BOOST_ALL_DYN_LINK should not be required with the known defines below
784 return ['-DBOOST_ALL_NO_LIB'] # Disable automatic linking
785
786 packages['boost'] = BoostDependency
787
788 # See https://www.boost.org/doc/libs/1_72_0/more/getting_started/unix-variants.html#library-naming
789 # See https://mesonbuild.com/Reference-tables.html#cpu-families
790 boost_arch_map = {
791 'aarch64': 'a64',
792 'arc': 'a32',
793 'arm': 'a32',
794 'ia64': 'i64',
795 'mips': 'm32',
796 'mips64': 'm64',
797 'ppc': 'p32',
798 'ppc64': 'p64',
799 'sparc': 's32',
800 'sparc64': 's64',
801 'x86': 'x32',
802 'x86_64': 'x64',
803 }
804
805
806 #### ---- BEGIN GENERATED ---- ####
807 # #
808 # Generated with tools/boost_names.py:
809 # - boost version: 1.73.0
810 # - modules found: 159
811 # - libraries found: 43
812 #
813
814 class BoostLibrary():
815 def __init__(self, name: str, shared: T.List[str], static: T.List[str], single: T.List[str], multi: T.List[str]):
816 self.name = name
817 self.shared = shared
818 self.static = static
819 self.single = single
820 self.multi = multi
821
822 class BoostModule():
823 def __init__(self, name: str, key: str, desc: str, libs: T.List[str]):
824 self.name = name
825 self.key = key
826 self.desc = desc
827 self.libs = libs
828
829
830 # dict of all know libraries with additional compile options
831 boost_libraries = {
832 'boost_atomic': BoostLibrary(
833 name='boost_atomic',
834 shared=['-DBOOST_ATOMIC_DYN_LINK=1'],
835 static=['-DBOOST_ATOMIC_STATIC_LINK=1'],
836 single=[],
837 multi=[],
838 ),
839 'boost_chrono': BoostLibrary(
840 name='boost_chrono',
841 shared=['-DBOOST_CHRONO_DYN_LINK=1'],
842 static=['-DBOOST_CHRONO_STATIC_LINK=1'],
843 single=['-DBOOST_CHRONO_THREAD_DISABLED'],
844 multi=[],
845 ),
846 'boost_container': BoostLibrary(
847 name='boost_container',
848 shared=['-DBOOST_CONTAINER_DYN_LINK=1'],
849 static=['-DBOOST_CONTAINER_STATIC_LINK=1'],
850 single=[],
851 multi=[],
852 ),
853 'boost_context': BoostLibrary(
854 name='boost_context',
855 shared=['-DBOOST_CONTEXT_DYN_LINK=1'],
856 static=[],
857 single=[],
858 multi=[],
859 ),
860 'boost_contract': BoostLibrary(
861 name='boost_contract',
862 shared=['-DBOOST_CONTRACT_DYN_LINK'],
863 static=['-DBOOST_CONTRACT_STATIC_LINK'],
864 single=['-DBOOST_CONTRACT_DISABLE_THREADS'],
865 multi=[],
866 ),
867 'boost_coroutine': BoostLibrary(
868 name='boost_coroutine',
869 shared=['-DBOOST_COROUTINES_DYN_LINK=1'],
870 static=[],
871 single=[],
872 multi=[],
873 ),
874 'boost_date_time': BoostLibrary(
875 name='boost_date_time',
876 shared=['-DBOOST_DATE_TIME_DYN_LINK=1'],
877 static=[],
878 single=[],
879 multi=[],
880 ),
881 'boost_exception': BoostLibrary(
882 name='boost_exception',
883 shared=[],
884 static=[],
885 single=[],
886 multi=[],
887 ),
888 'boost_fiber': BoostLibrary(
889 name='boost_fiber',
890 shared=['-DBOOST_FIBERS_DYN_LINK=1'],
891 static=[],
892 single=[],
893 multi=[],
894 ),
895 'boost_fiber_numa': BoostLibrary(
896 name='boost_fiber_numa',
897 shared=['-DBOOST_FIBERS_DYN_LINK=1'],
898 static=[],
899 single=[],
900 multi=[],
901 ),
902 'boost_filesystem': BoostLibrary(
903 name='boost_filesystem',
904 shared=['-DBOOST_FILESYSTEM_DYN_LINK=1'],
905 static=['-DBOOST_FILESYSTEM_STATIC_LINK=1'],
906 single=[],
907 multi=[],
908 ),
909 'boost_graph': BoostLibrary(
910 name='boost_graph',
911 shared=[],
912 static=[],
913 single=[],
914 multi=[],
915 ),
916 'boost_iostreams': BoostLibrary(
917 name='boost_iostreams',
918 shared=['-DBOOST_IOSTREAMS_DYN_LINK=1'],
919 static=[],
920 single=[],
921 multi=[],
922 ),
923 'boost_locale': BoostLibrary(
924 name='boost_locale',
925 shared=[],
926 static=[],
927 single=[],
928 multi=[],
929 ),
930 'boost_log': BoostLibrary(
931 name='boost_log',
932 shared=['-DBOOST_LOG_DYN_LINK=1'],
933 static=[],
934 single=['-DBOOST_LOG_NO_THREADS'],
935 multi=[],
936 ),
937 'boost_log_setup': BoostLibrary(
938 name='boost_log_setup',
939 shared=['-DBOOST_LOG_SETUP_DYN_LINK=1'],
940 static=[],
941 single=['-DBOOST_LOG_NO_THREADS'],
942 multi=[],
943 ),
944 'boost_math_c99': BoostLibrary(
945 name='boost_math_c99',
946 shared=[],
947 static=[],
948 single=[],
949 multi=[],
950 ),
951 'boost_math_c99f': BoostLibrary(
952 name='boost_math_c99f',
953 shared=[],
954 static=[],
955 single=[],
956 multi=[],
957 ),
958 'boost_math_c99l': BoostLibrary(
959 name='boost_math_c99l',
960 shared=[],
961 static=[],
962 single=[],
963 multi=[],
964 ),
965 'boost_math_tr1': BoostLibrary(
966 name='boost_math_tr1',
967 shared=[],
968 static=[],
969 single=[],
970 multi=[],
971 ),
972 'boost_math_tr1f': BoostLibrary(
973 name='boost_math_tr1f',
974 shared=[],
975 static=[],
976 single=[],
977 multi=[],
978 ),
979 'boost_math_tr1l': BoostLibrary(
980 name='boost_math_tr1l',
981 shared=[],
982 static=[],
983 single=[],
984 multi=[],
985 ),
986 'boost_mpi': BoostLibrary(
987 name='boost_mpi',
988 shared=[],
989 static=[],
990 single=[],
991 multi=[],
992 ),
993 'boost_nowide': BoostLibrary(
994 name='boost_nowide',
995 shared=['-DBOOST_NOWIDE_DYN_LINK=1'],
996 static=[],
997 single=[],
998 multi=[],
999 ),
1000 'boost_prg_exec_monitor': BoostLibrary(
1001 name='boost_prg_exec_monitor',
1002 shared=['-DBOOST_TEST_DYN_LINK=1'],
1003 static=[],
1004 single=[],
1005 multi=[],
1006 ),
1007 'boost_program_options': BoostLibrary(
1008 name='boost_program_options',
1009 shared=[],
1010 static=[],
1011 single=[],
1012 multi=[],
1013 ),
1014 'boost_random': BoostLibrary(
1015 name='boost_random',
1016 shared=['-DBOOST_RANDOM_DYN_LINK'],
1017 static=[],
1018 single=[],
1019 multi=[],
1020 ),
1021 'boost_regex': BoostLibrary(
1022 name='boost_regex',
1023 shared=[],
1024 static=[],
1025 single=[],
1026 multi=[],
1027 ),
1028 'boost_serialization': BoostLibrary(
1029 name='boost_serialization',
1030 shared=[],
1031 static=[],
1032 single=[],
1033 multi=[],
1034 ),
1035 'boost_stacktrace_addr2line': BoostLibrary(
1036 name='boost_stacktrace_addr2line',
1037 shared=[],
1038 static=[],
1039 single=[],
1040 multi=[],
1041 ),
1042 'boost_stacktrace_backtrace': BoostLibrary(
1043 name='boost_stacktrace_backtrace',
1044 shared=[],
1045 static=[],
1046 single=[],
1047 multi=[],
1048 ),
1049 'boost_stacktrace_basic': BoostLibrary(
1050 name='boost_stacktrace_basic',
1051 shared=[],
1052 static=[],
1053 single=[],
1054 multi=[],
1055 ),
1056 'boost_stacktrace_noop': BoostLibrary(
1057 name='boost_stacktrace_noop',
1058 shared=[],
1059 static=[],
1060 single=[],
1061 multi=[],
1062 ),
1063 'boost_stacktrace_windbg': BoostLibrary(
1064 name='boost_stacktrace_windbg',
1065 shared=[],
1066 static=[],
1067 single=[],
1068 multi=[],
1069 ),
1070 'boost_stacktrace_windbg_cached': BoostLibrary(
1071 name='boost_stacktrace_windbg_cached',
1072 shared=[],
1073 static=[],
1074 single=[],
1075 multi=[],
1076 ),
1077 'boost_system': BoostLibrary(
1078 name='boost_system',
1079 shared=['-DBOOST_SYSTEM_DYN_LINK=1'],
1080 static=['-DBOOST_SYSTEM_STATIC_LINK=1'],
1081 single=[],
1082 multi=[],
1083 ),
1084 'boost_test_exec_monitor': BoostLibrary(
1085 name='boost_test_exec_monitor',
1086 shared=['-DBOOST_TEST_DYN_LINK=1'],
1087 static=[],
1088 single=[],
1089 multi=[],
1090 ),
1091 'boost_thread': BoostLibrary(
1092 name='boost_thread',
1093 shared=['-DBOOST_THREAD_BUILD_DLL=1', '-DBOOST_THREAD_USE_DLL=1'],
1094 static=['-DBOOST_THREAD_BUILD_LIB=1', '-DBOOST_THREAD_USE_LIB=1'],
1095 single=[],
1096 multi=[],
1097 ),
1098 'boost_timer': BoostLibrary(
1099 name='boost_timer',
1100 shared=['-DBOOST_TIMER_DYN_LINK=1'],
1101 static=['-DBOOST_TIMER_STATIC_LINK=1'],
1102 single=[],
1103 multi=[],
1104 ),
1105 'boost_type_erasure': BoostLibrary(
1106 name='boost_type_erasure',
1107 shared=['-DBOOST_TYPE_ERASURE_DYN_LINK'],
1108 static=[],
1109 single=[],
1110 multi=[],
1111 ),
1112 'boost_unit_test_framework': BoostLibrary(
1113 name='boost_unit_test_framework',
1114 shared=['-DBOOST_TEST_DYN_LINK=1'],
1115 static=[],
1116 single=[],
1117 multi=[],
1118 ),
1119 'boost_wave': BoostLibrary(
1120 name='boost_wave',
1121 shared=[],
1122 static=[],
1123 single=[],
1124 multi=[],
1125 ),
1126 'boost_wserialization': BoostLibrary(
1127 name='boost_wserialization',
1128 shared=[],
1129 static=[],
1130 single=[],
1131 multi=[],
1132 ),
1133 }
1134
1135 # #
1136 #### ---- END GENERATED ---- ####