Debian Codegraph @

SConstruct

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 #SConstruct
2 # vim: set fenc=utf-8 sw=4 ts=4 :
3 # 7a84b3f307ac6f72fd440e55b149d7c2c942dfaf
4
5 # needed imports
6 from collections import (defaultdict, Counter as collections_counter)
7 import collections.abc
8 from dataclasses import dataclass
9 import base64
10 import binascii
11 import errno
12 import itertools
13 import shlex
14 import subprocess
15 import sys
16 import typing
17 import os
18 import SCons.Util
19 import SCons.Script
20 from functools import cached_property
21
22 # Disable injecting tools into default namespace
23 SCons.Defaults.DefaultEnvironment(tools = [])
24
25 def message(program, msg: str):
26 print(f'{program.program_message_prefix}: {msg}')
27
28 def get_Werror_sequence(active_cxxflags: list[str], warning_flags: collections.abc.Sequence[str]) -> list[str]:
29 # The leading -W is passed in each element in warning_flags so that if
30 # -Werror is already set, the warning_flags can be returned as-is. This
31 # also means that the warning flag is written in the caller as it will be
32 # on the command line, so users who grep for `-Wfoo` will find where
33 # `-Wfoo` is set. If the `-W` were composed in this function and the
34 # caller passed `foo`, then a search for `-Wfoo` would find nothing.
35 if active_cxxflags and '-Werror' in active_cxxflags:
36 # Make both paths return a Python list.
37 return list(warning_flags)
38 # When an option is converted to `-Werror=foo` form, the leading `-W` from
39 # the caller must be stripped off to avoid producing `-Werror=-Wfoo`.
40 return [f'-Werror={warning[2:]}' for warning in warning_flags]
41
42 class StaticSubprocess:
43 # This class contains utility functions for calling subprocesses
44 # that are expected to return the same output for every call. The
45 # output is cached after the first call, so that callers can request
46 # the output again later without causing the program to be run again.
47 #
48 # Suitable programs are not required to depend solely on the
49 # parameters, but are assumed to depend only on state that is
50 # unlikely to change in the brief time that SConstruct runs. For
51 # example, a tool might be upgraded by the system administrator,
52 # changing its version string. However, we assume nobody upgrades
53 # their tools in the middle of an SConstruct run. Results are not
54 # cached to persistent storage, so an upgrade performed after one
55 # SConstruct run, but before the next, will not cause any
56 # inconsistencies.
57 shlex_split = shlex.split
58
59 @dataclass(eq=False)
60 class CachedCall:
61 out: bytes
62 err: bytes
63 returncode: int
64
65 @dataclass(eq=False)
66 class CachedVersionCall:
67 version_head: str
68 def __init__(self, out: bytes, err: bytes, returncode: int):
69 oe = out or err
70 self.version_head = oe.splitlines()[0].decode() if not returncode and oe else None
71
72 # @staticmethod delayed so that default arguments pick up the
73 # undecorated form.
74 def pcall(args: list[bytes | str], stderr=None, CachedCall=CachedCall, _call_cache: dict[str, CachedCall]={}) -> CachedCall:
75 # Use repr since callers may construct the same argument
76 # list independently.
77 ## >>> a = ['git', '--version']
78 ## >>> b = ['git', '--version']
79 ## >>> a is b
80 ## False
81 ## >>> id(a) == id(b)
82 ## False
83 ## >>> a == b
84 ## True
85 ## >>> repr(a) == repr(b)
86 ## True
87 a = repr(args)
88 c = _call_cache.get(a)
89 if c is not None:
90 return c
91 p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=stderr)
92 (o, e) = p.communicate()
93 _call_cache[a] = c = CachedCall(o, e, p.wait())
94 return c
95 def qcall(args: str, stderr=None, _pcall=pcall, _shlex_split=shlex_split) -> CachedCall:
96 return _pcall(_shlex_split(args),stderr)
97 @classmethod
98 def get_version_head(cls, cmd: bytes | str, _pcall=pcall, _shlex_split=shlex_split) -> str:
99 # If cmd is bytes, then it is output from a program and should
100 # not be reparsed.
101 return _pcall(([cmd] if isinstance(cmd, bytes) else _shlex_split(cmd)) + ['--version'], stderr=subprocess.PIPE, CachedCall=cls.CachedVersionCall).version_head
102 pcall = staticmethod(pcall)
103 qcall = staticmethod(qcall)
104 shlex_split = staticmethod(shlex_split)
105
106 class ToolchainInformation(StaticSubprocess):
107 @staticmethod
108 def get_tool_path(env: SCons.Environment, tool: str, _qcall=StaticSubprocess.qcall):
109 # Include $LINKFLAGS since -fuse-ld=gold influences the path
110 # printed for the linker.
111 tool = env.subst(f'$CXX $CXXFLAGS $LINKFLAGS -print-prog-name={tool}')
112 return tool, _qcall(tool).out.strip()
113 @staticmethod
114 def show_partial_environ(env: SCons.Environment, user_settings, f: collections.abc.Callable[[str], None], msgprefix: str, append_newline='\n'):
115 f(f'{msgprefix}: CHOST: {(user_settings.CHOST)!r}{append_newline}')
116 for v in (
117 'CXX',
118 'CPPDEFINES',
119 'CPPPATH',
120 'CPPFLAGS',
121 'CXXFLAGS',
122 'LIBS',
123 'LINKFLAGS',
124 ) + (
125 (
126 'RC',
127 'RCFLAGS',
128 ) if user_settings.host_platform == 'win32' else (
129 'FRAMEWORKPATH',
130 'FRAMEWORKS',
131 ) if user_settings.host_platform == 'darwin' else (
132 )
133 ):
134 f(f'{msgprefix}: {v}: {(env.get(v, None))!r}{append_newline}')
135 penv = env['ENV']
136 for v in (
137 'CCACHE_PREFIX',
138 'DISTCC_HOSTS',
139 ):
140 f(f'{msgprefix}: ${v}: {(penv.get(v, None))!r}{append_newline}')
141
142 class Git(StaticSubprocess):
143 @dataclass(eq=False)
144 class ComputedExtraVersion:
145 describe: str
146 status: str
147 diffstat_HEAD: str
148 revparse_HEAD: str
149 __slots__ = ('describe', 'status', 'diffstat_HEAD', 'revparse_HEAD')
150 UnknownExtraVersion = (
151 # If the string is alphanumeric, then `git archive` has rewritten the
152 # string to be a commit ID. Use that commit ID as a guessed default
153 # when Git is not available to resolve a current commit ID.
154 ComputedExtraVersion('', None, None, 'archive_7a84b3f307ac6f72fd440e55b149d7c2c942dfaf') if '7a84b3f307ac6f72fd440e55b149d7c2c942dfaf'.isalnum() else
155 # Otherwise, assume that this is a checked-in copy.
156 ComputedExtraVersion(None, None, None, None)
157 )
158 # None until computed, then ComputedExtraVersion once cached.
159 __computed_extra_version: typing.ClassVar[None | ComputedExtraVersion] = None
160 __path_git: typing.ClassVar[None | list[str]] = None
161 # `__pcall_missing_git`, `__pcall_found_git`, and `pcall` must have
162 # compatible signatures. In any given run, there will be at most
163 # one call to `pcall`, which then patches itself out of the call
164 # chain. A run will call either __pcall_missing_git or
165 # __pcall_found_git (depending on whether $GIT is blank), but never
166 # both in the same run.
167 @classmethod
168 def __pcall_missing_git(cls, args: list[str], stderr=None, _missing_git=StaticSubprocess.CachedCall(None, None, 1)):
169 return _missing_git
170 @classmethod
171 def __pcall_found_git(cls, args: list[str], stderr=None, _pcall=StaticSubprocess.pcall):
172 return _pcall(cls.__path_git + args, stderr=stderr)
173 @classmethod
174 def pcall(cls, args: list[str], stderr=None):
175 git = cls.__path_git
176 if git is None:
177 cls.__path_git = git = cls.shlex_split(os.environ.get('GIT', 'git'))
178 cls.pcall = f = cls.__pcall_found_git if git else cls.__pcall_missing_git
179 return f(args, stderr)
180 def spcall(cls, args: list[str], stderr=None):
181 g = cls.pcall(args, stderr)
182 if g.returncode:
183 return None
184 return g.out
185 @classmethod
186 def compute_extra_version(cls, _spcall=spcall) -> ComputedExtraVersion:
187 c = cls.__computed_extra_version
188 if c is None:
189 v = cls.__compute_extra_version()
190 cls.__computed_extra_version = c = cls.ComputedExtraVersion(
191 v,
192 _spcall(cls, ['status', '--short', '--branch']).decode(),
193 _spcall(cls, ['diff', '--stat', 'HEAD']).decode(),
194 _spcall(cls, ['rev-parse', 'HEAD']).rstrip().decode(),
195 ) if v is not None else cls.UnknownExtraVersion
196 return c
197 # Run `git describe --tags --abbrev=12`.
198 # On failure, return None.
199 # On success, return a string containing:
200 # first line of output of describe
201 # '*' if there are unstaged changes else ''
202 # '+' if there are staged changes else ''
203 @classmethod
204 def __compute_extra_version(cls) -> None | str:
205 try:
206 g = cls.pcall(['describe', '--tags', '--abbrev=12'], stderr=subprocess.PIPE)
207 except OSError as e:
208 if e.errno == errno.ENOENT:
209 return None
210 raise
211 if g.returncode:
212 return None
213 _pcall = cls.pcall
214 return (g.out.splitlines()[0] + \
215 (b'*' if _pcall(['diff', '--quiet']).returncode else b'') + \
216 (b'+' if _pcall(['diff', '--quiet', '--cached']).returncode else b'')
217 ).decode()
218
219 class ConfigureTests:
220 @dataclass(eq=False)
221 class _Collector:
222 record: collections.abc.Callable[['ConfigureTest'], None]
223
224 @dataclass(eq=False, slots=True)
225 class RecordedTest:
226 name: str
227 desc: str
228 # predicate is a sequence of zero-or-more functions that take a
229 # UserSettings object as the only argument. A recorded test is
230 # only passed to the SConf logic if at most zero predicates return
231 # a false-like value.
232 #
233 # Callers use this to exclude from execution tests which make no
234 # sense in the current environment, such as a Windows-specific test
235 # when building for a Linux target.
236 predicate: tuple[collections.abc.Callable[['UserSettings'], bool]] = ()
237
238 def __call__(self, f: collections.abc.Callable) -> collections.abc.Callable:
239 desc = None
240 doc = getattr(f, '__doc__', None)
241 if doc is not None:
242 doc = doc.rstrip().splitlines()
243 if doc and doc[-1].startswith("help:"):
244 desc = doc[-1][5:]
245 self.record(self.RecordedTest(f.__name__, desc))
246 return f
247
248 class Collector(_Collector):
249 tests: collections.abc.MutableSequence[collections.abc.Callable[['ConfigureTest'], None]]
250 def __init__(self):
251 # An unguarded collector maintains a list of tests, and adds
252 # to the list as the decorator is called on individual
253 # functions.
254 self.tests = tests = []
255 super().__init__(tests.append)
256
257 class GuardedCollector(_Collector):
258 __guard: tuple[collections.abc.Callable[['UserSettings'], bool]]
259 def __init__(self, collector, guard: collections.abc.Callable[['UserSettings'], bool]):
260 # A guarded collector delegates to the list maintained by
261 # the input collector, instead of keeping a list of its own.
262 super().__init__(collector.record)
263 # `guard` is a single function, but the predicate handling
264 # expects a sequence of functions, so store a single-element
265 # tuple.
266 self.__guard = guard,
267 self.__RecordedTest = collector.RecordedTest
268 def RecordedTest(self, name: str, desc: str, predicate=()):
269 # Record a test with both the guard of this GuardedCollector
270 # and any guards from the input collector objects, which may
271 # in turn be instances of GuardedCollector with predicates
272 # of their own.
273 return self.__RecordedTest(name, desc, self.__guard + predicate)
274
275 class CxxRequiredFeature:
276 __slots__ = ('main', 'name', 'text')
277 name: str
278 text: str
279 main: str
280 def __init__(self, name: str, text: str, main: str = ''):
281 self.name = name
282 # Avoid generating consecutive underscores if the input
283 # string has multiple adjacent unacceptable characters.
284 # Pass alphanumeric characters through as-is. Escape
285 # non-alphanumeric by converting them to the hexadecimal
286 # representation of their ordinal value.
287 name = {'N' : f'test_{"".join(c if c.isalnum() else f"_{(ord(c)):x}" for c in name)}'}
288 self.text = text % name
289 self.main = f'{{{(main % name)}}}\n' if main else ''
290 class Cxx11RequiredFeature(CxxRequiredFeature):
291 std: int = 11
292 class Cxx14RequiredFeature(CxxRequiredFeature):
293 std: int = 14
294 class Cxx17RequiredFeature(CxxRequiredFeature):
295 std: int = 17
296 class Cxx20RequiredFeature(CxxRequiredFeature):
297 std: int = 20
298 class CxxRequiredFeatures:
299 __slots__ = ('features', 'main', 'text')
300 features: list['CxxRequiredFeature']
301 main: str
302 text: str
303 def __init__(self, features: list['CxxRequiredFeature']):
304 self.features = features
305 s = '/* C++{} {} */\n{}'.format
306 self.main = '\n'.join((s(f.std, f.name, f.main) for f in features if f.main))
307 self.text = '\n'.join((s(f.std, f.name, f.text) for f in features if f.text))
308 class PCHAction:
309 def __init__(self,context):
310 self._context = context
311 def __call__(self,text,ext):
312 # Ignore caller-supplied text, since _Test always includes a
313 # definition of main(). Using the caller-supplied text
314 # would provide one main() in the PCH and another in the
315 # test which includes the PCH.
316 env = self._context.env
317 s = env['OBJSUFFIX']
318 env['OBJSUFFIX'] = '.h.gch'
319 result = self._context.TryCompile('''
320 /* Define this here. Use it in the file which includes the PCH. If the
321 * compiler skips including the PCH, and does not fail for that reason
322 * alone, then it will fail when the symbol is used in the later test,
323 * since the only definition comes from the PCH.
324 */
325 #define dxx_compiler_supports_pch
326 ''', ext)
327 env['OBJSUFFIX'] = s
328 return result
329 class PreservedEnvironment:
330 # One empty list for all the defaults. The comprehension
331 # creates copies, so it is safe for the default value to be
332 # shared.
333 def __init__(self, env: SCons.Environment, keyviews, _l=[]):
334 self.flags = {k: env.get(k, _l).copy() for k in itertools.chain.from_iterable(keyviews)}
335 def restore(self, env: SCons.Environment):
336 env.Replace(**self.flags)
337 def __getitem__(self, name: str):
338 return self.flags.__getitem__(name)
339 class ForceVerboseLog(PreservedEnvironment):
340 def __init__(self, env: SCons.Environment):
341 # Force verbose output to sconf.log
342 self.flags = {}
343 for k in (
344 'CXXCOMSTR',
345 'LINKCOMSTR',
346 ):
347 try:
348 # env is like a dict, but does not have .pop(), so
349 # emulate it with a lookup + delete.
350 self.flags[k] = env[k]
351 del env[k]
352 except KeyError:
353 pass
354 class pkgconfig:
355 def _get_pkg_config_exec_path(context, msgprefix: str, pkgconfig: str):
356 Display = context.Display
357 if not pkgconfig:
358 Display(f'{msgprefix}: pkg-config disabled by user settings\n')
359 return pkgconfig
360 if os.sep in pkgconfig:
361 # Split early, so that the user can pass a command with
362 # arguments. Convert to tuple so that the value is not
363 # modified later.
364 pkgconfig = tuple(StaticSubprocess.shlex_split(pkgconfig))
365 Display(f'{msgprefix}: using pkg-config at user specified path {pkgconfig!r}\n')
366 return pkgconfig
367 join = os.path.join
368 # No path specified, search in $PATH
369 for p in os.environ.get('PATH', '').split(os.pathsep):
370 fp = join(p, pkgconfig)
371 try:
372 os.close(os.open(fp, os.O_RDONLY))
373 except OSError as e:
374 # Ignore on permission errors. If pkg-config is
375 # runnable but not readable, the user must
376 # specify its path.
377 if e.errno == errno.ENOENT or e.errno == errno.EACCES:
378 continue
379 raise
380 Display(f'{msgprefix}: using pkg-config at discovered path {fp}\n')
381 return (fp,)
382 Display(f'{msgprefix}: no usable pkg-config {pkgconfig!r} found in $PATH\n')
383 def __get_pkg_config_path(context,message,user_settings,display_name,
384 _get_pkg_config_exec_path=_get_pkg_config_exec_path,
385 _cache={}):
386 pkgconfig = user_settings.PKG_CONFIG
387 if pkgconfig is None:
388 CHOST = user_settings.CHOST
389 pkgconfig = f'{CHOST}-pkg-config' if CHOST else 'pkg-config'
390 if sys.platform == 'win32':
391 pkgconfig += '.exe'
392 path = _cache.get(pkgconfig, _cache)
393 if path is _cache:
394 _cache[pkgconfig] = path = _get_pkg_config_exec_path(context, message, pkgconfig)
395 return path
396 @staticmethod
397 def merge(context, message: str, user_settings, pkgconfig_name: str, display_name: str, guess_flags: dict,
398 __get_pkg_config_path=__get_pkg_config_path,
399 _cache: dict = {}) -> dict:
400 Display = context.Display
401 Display(f'{message}: checking {display_name} pkg-config {pkgconfig_name}\n')
402 pkgconfig = __get_pkg_config_path(context, message, user_settings, display_name)
403 if not pkgconfig:
404 Display(f'{message}: skipping {display_name} pkg-config; using default flags {guess_flags!r}\n')
405 return guess_flags
406 cmd = pkgconfig + ('--cflags', '--libs', pkgconfig_name)
407 flags = _cache.get(cmd, None)
408 if flags is not None:
409 Display(f'{message}: reusing {display_name} settings from `{shlex.join(cmd)}`: {flags!r}\n')
410 return flags
411 mv_cmd = pkgconfig + ('--modversion', pkgconfig_name)
412 try:
413 Display(f'{message}: reading {pkgconfig_name} version from `{shlex.join(mv_cmd)}`\n')
414 v = StaticSubprocess.pcall(mv_cmd, stderr=subprocess.PIPE)
415 if v.err:
416 for l in v.err.splitlines():
417 Display(f'{message}: pkg-config error: {display_name}: {l.decode()}\n')
418 if v.returncode:
419 Display(f'{message}: pkg-config failed: {display_name}: {v.returncode}; using default flags {guess_flags!r}\n')
420 return guess_flags
421 if v.out:
422 displayed_version = v.out.splitlines()[0]
423 try:
424 displayed_version = displayed_version.decode()
425 except UnicodeDecodeError:
426 pass
427 Display(f'{message}: {display_name} version: {displayed_version!r}\n')
428 except OSError as o:
429 Display(f'''{message}: failed with error {repr(o.message) if o.errno is None else f'{o.errno} ("{o.strerror}")'}; using default flags for {pkgconfig_name!r}: {guess_flags!r}\n''')
430 flags = guess_flags
431 else:
432 Display(f'{message}: reading {display_name} settings from `{shlex.join(cmd)}`\n')
433 try:
434 v = StaticSubprocess.pcall(cmd, stderr=subprocess.PIPE)
435 if v.err:
436 for l in v.err.splitlines():
437 Display(f'{message}: pkg-config error: {display_name}: {l.decode()}\n')
438 if v.returncode:
439 Display(f'{message}: pkg-config failed: {display_name}: {v.returncode}; using default flags {guess_flags!r}\n')
440 return guess_flags
441 out = v.out
442 flags = {
443 k:v for k,v in context.env.ParseFlags(' ' + out.decode()).items()
444 if v and (k[0] in 'CL')
445 }
446 Display(f'{message}: {display_name} settings: {flags!r}\n')
447 # Write the full output to the SCons log for later review.
448 # Omit it from `Display` since it is rarely necessary to
449 # see it during the build.
450 context.Log(f'{message}: {display_name} settings full output: {out!r}\n')
451 except OSError as o:
452 Display(f'''{message}: failed with error {repr(o.message) if o.errno is None else f'{o.errno} ("{o.strerror}")'}; using default flags for {pkgconfig_name!r}: {guess_flags!r}\n''')
453 flags = guess_flags
454 _cache[cmd] = flags
455 return flags
456
457 # Force test to report failure
458 sconf_force_failure = 'force-failure'
459 # Force test to report success, and modify flags like it
460 # succeeded
461 sconf_force_success = 'force-success'
462 # Force test to report success, do not modify flags
463 sconf_assume_success = 'assume-success'
464 expect_sconf_success = 'success'
465 expect_sconf_failure = 'failure'
466 _implicit_test = Collector()
467 _custom_test = Collector()
468 _guarded_test_windows = GuardedCollector(_custom_test, lambda user_settings: user_settings.host_platform == 'win32')
469 _guarded_test_darwin = GuardedCollector(_custom_test, lambda user_settings: user_settings.host_platform == 'darwin')
470 implicit_tests = _implicit_test.tests
471 custom_tests = _custom_test.tests
472 comment_not_supported = '/* not supported */'
473 __python_import_struct = None
474 __cxx_std_required_features = CxxRequiredFeatures([
475 # As of this writing, <gcc-12 is already unsupported, but some
476 # platforms, such as Ubuntu 22.04, still try to use gcc-11 by default.
477 # Use this test both to verify that Class Template Argument Deduction
478 # is generally supported, since it is used in the game, and to exclude
479 # an unsupported compiler that does not accept CTAD in one of the
480 # contexts the game uses.
481 Cxx20RequiredFeature('class template argument deduction', '''
482 struct Outer_%(N)s
483 {
484 template <typename byte_type>
485 struct Inner
486 {
487 constexpr Inner(byte_type &)
488 {
489 }
490 };
491 /* <gcc-12 does not allow declaring a deduction guide in the immediately
492 * enclosing scope:
493 ```
494 error: deduction guide 'Outer_test_class_20template_20argument
495 _20deduction::Inner(byte_type&) -> Outer_test_class_20template_20argument_20deduction::Inner<byte_type>' must be declared at namespace scope
496 ```
497 */
498 template <typename byte_type>
499 Inner(byte_type &) -> Inner<byte_type>;
500 };
501 '''),
502 Cxx20RequiredFeature('abbreviated function templates', '''
503 void f_%(N)s(auto &&)
504 {
505 }
506 ''',
507 '''
508 f_%(N)s(0);
509 f_%(N)s(0u);
510 f_%(N)s("");
511 f_%(N)s(nullptr);
512 '''),
513 Cxx20RequiredFeature('explicitly defaulted operator==', '''
514 struct A_%(N)s
515 {
516 int a;
517 constexpr bool operator==(const A_%(N)s &) const = default;
518 };
519 ''',
520 '''
521 constexpr A_%(N)s a1{0};
522 constexpr A_%(N)s a2{0};
523 static_assert(a1 == a2);
524 static_assert(!(a1 != a2));
525 '''),
526 Cxx20RequiredFeature('std::make_unique_for_overwrite', '''
527 #include <memory>
528 ''', '''
529 std::make_unique_for_overwrite<int>();
530 std::make_unique_for_overwrite<int[]>(1);
531 '''),
532 Cxx20RequiredFeature('requires clause', '''
533 template <typename T>
534 requires(sizeof(T) >= 1)
535 void f_%(N)s(T)
536 {
537 }
538 ''',
539 '''
540 f_%(N)s('a');
541 '''),
542 Cxx20RequiredFeature('std::ranges', '''
543 #include <algorithm>
544 #include <ranges>
545
546 struct test_borrowed_range {};
547
548 template <>
549 constexpr bool std::ranges::enable_borrowed_range<test_borrowed_range> = true;
550
551 template <std::ranges::range R>
552 static void requires_range(R &) {}
553
554 template <std::ranges::input_range R>
555 static void requires_input_range(R &) {}
556
557 template <std::ranges::borrowed_range R>
558 static void requires_borrowed_range(R &&) {}
559 ''',
560 '''
561 int a[3]{1, 2, 3};
562 int b[2]{4, 5};
563 const std::ranges::subrange c(b);
564 const std::ranges::subrange<int *> c2(b);
565 (void)c2;
566 const auto m{[](int i) { return i * 2; }};
567 (void)(std::ranges::find(a, argc) == a);
568 (void)(std::ranges::find(a, argc, m) == a);
569 (void)(std::ranges::find(std::ranges::begin(b), std::ranges::end(b), argc) == a);
570 (void)(std::ranges::find(std::ranges::begin(b), std::ranges::end(b), argc, m) == a);
571 const auto predicate{[](int i) { return i == 3; }};
572 (void)(std::ranges::find_if(b, predicate) == b);
573 (void)(std::ranges::find_if(std::ranges::begin(b), std::ranges::end(b), predicate) == b);
574 (void)(std::ranges::remove_if(b, predicate).begin() == b);
575 (void)(std::ranges::equal_range(b, int{4}, {}).begin() == b);
576 requires_range(a);
577 requires_input_range(a);
578 requires_borrowed_range(a);
579 return 0;
580 '''),
581 Cxx20RequiredFeature('std::span', '''
582 #include <span>
583
584 void sd_%(N)s(std::span<const char>);
585 void ss_%(N)s(std::span<const char, 2>);
586
587 void sd_%(N)s(std::span<const char>)
588 {
589 }
590
591 void ss_%(N)s(std::span<const char, 2>)
592 {
593 }
594 ''',
595 '''
596 sd_%(N)s("ab");
597 ss_%(N)s("a");
598 '''),
599 Cxx17RequiredFeature('constexpr if', '''
600 template <bool b>
601 int f_%(N)s()
602 {
603 if constexpr (b)
604 return 1;
605 else
606 return 0;
607 }
608 ''',
609 '''
610 f_%(N)s<false>();
611 '''),
612 Cxx17RequiredFeature('fold expressions', '''
613 static inline void g_%(N)s(int) {}
614 template <int... i>
615 void f_%(N)s()
616 {
617 (g_%(N)s(i), ...);
618 (g_%(N)s(i), ..., (void)0);
619 ((void)0, ..., g_%(N)s(i));
620 }
621 ''',
622 '''
623 f_%(N)s<0, 1, 2, 3>();
624 '''),
625 Cxx17RequiredFeature('structured binding declarations', '',
626 '''
627 int a_%(N)s[2] = {0, 1};
628 auto &&[b_%(N)s, c_%(N)s] = a_%(N)s;
629 (void)b_%(N)s;
630 (void)c_%(N)s;
631 '''),
632 Cxx17RequiredFeature('attribute [[fallthrough]]', '''
633 static inline void f_%(N)s() {}
634 ''',
635 '''
636 switch (argc)
637 {
638 case 1:
639 f_%(N)s();
640 [[fallthrough]];
641 case 2:
642 f_%(N)s();
643 break;
644 }
645 '''),
646 Cxx17RequiredFeature('attribute [[nodiscard]]', '''
647 [[nodiscard]]
648 static int f_%(N)s()
649 {
650 return 0;
651 }
652 ''',
653 '''
654 auto i_%(N)s = f_%(N)s();
655 (void)i_%(N)s;
656 '''),
657 Cxx14RequiredFeature('template variables', '''
658 template <unsigned U_%(N)s>
659 int a_%(N)s = U_%(N)s + 1;
660 ''', ''),
661 Cxx14RequiredFeature('std::exchange', '''
662 #include <utility>
663 ''', '''
664 argc |= std::exchange(argc, 5);
665 '''),
666 Cxx14RequiredFeature('std::index_sequence', '''
667 #include <utility>
668 ''', '''
669 std::integer_sequence<int, 0> integer_%(N)s = std::make_integer_sequence<int, 1>();
670 (void)integer_%(N)s;
671 std::index_sequence<0> index_%(N)s = std::make_index_sequence<1>();
672 (void)index_%(N)s;
673 '''),
674 Cxx14RequiredFeature('std::make_unique', '''
675 #include <memory>
676 ''', '''
677 std::make_unique<int>(0);
678 std::make_unique<int[]>(1);
679 '''),
680 Cxx11RequiredFeature('std::addressof', '''
681 #include <memory>
682 ''', '''
683 struct A_%(N)s
684 {
685 void operator&() = delete;
686 };
687 A_%(N)s i_%(N)s;
688 (void)std::addressof(i_%(N)s);
689 '''),
690 Cxx11RequiredFeature('constexpr', '''
691 struct %(N)s {};
692 static constexpr %(N)s get_%(N)s(){return {};}
693 ''', '''
694 get_%(N)s();
695 '''),
696 Cxx11RequiredFeature('nullptr', '''
697 #include <cstddef>
698 std::nullptr_t %(N)s1 = nullptr;
699 int *%(N)s2 = nullptr;
700 ''', '''
701 %(N)s2 = %(N)s1;
702 '''),
703 Cxx11RequiredFeature('explicit operator bool', '''
704 struct %(N)s {
705 explicit operator bool();
706 };
707 '''),
708 Cxx11RequiredFeature('explicitly deleted functions', '''
709 void b_%(N)s(int c) = delete;
710 ''', '''
711 struct A_%(N)s
712 {
713 void a(int b) = delete;
714 };
715 A_%(N)s i_%(N)s;
716 (void)i_%(N)s;
717 '''),
718 Cxx11RequiredFeature('template aliases', '''
719 using %(N)s_typedef = int;
720 template <typename>
721 struct %(N)s_struct;
722 template <typename T>
723 using %(N)s_alias = %(N)s_struct<T>;
724 ''', '''
725 %(N)s_struct<int> *a = nullptr;
726 %(N)s_alias<int> *b = a;
727 %(N)s_typedef *c = nullptr;
728 (void)b;
729 (void)c;
730 '''),
731 Cxx11RequiredFeature('trailing function return type', '''
732 auto %(N)s()->int;
733 '''),
734 Cxx11RequiredFeature('class scope static constexpr assignment', '''
735 struct %(N)s_instance {
736 };
737 struct %(N)s_container {
738 static constexpr %(N)s_instance a = {};
739 };
740 '''),
741 Cxx11RequiredFeature('braced base class initialization', '''
742 struct %(N)s_base {
743 int a;
744 };
745 struct %(N)s_derived : %(N)s_base {
746 %(N)s_derived(int e) : %(N)s_base{e} {}
747 };
748 '''),
749 Cxx11RequiredFeature('std::array', '''
750 #include <array>
751 ''', '''
752 std::array<int,2>b;
753 b[0]=1;
754 '''
755 ),
756 Cxx11RequiredFeature('std::begin(), std::end()', '''
757 #include <array>
758 ''', f'''
759 char ac[1];
760 std::array<char, 1> as;
761 {(''.join([f""" {{
762 auto s = std::{f}({a});
763 (void)s;
764 }}
765 """ for f in ('begin', 'end') for a in ('ac', 'as')]
766 )
767 )}
768 '''),
769 Cxx11RequiredFeature('range-based for', '''
770 #include "compiler-range_for.h"
771 ''', '''
772 int b[2];
773 range_for(int&c,b)c=0;
774 '''
775 ),
776 Cxx11RequiredFeature('<type_traits>', '''
777 #include <type_traits>
778 ''', '''
779 typename std::conditional<sizeof(argc) == sizeof(int),int,long>::type a = 0;
780 typename std::conditional<sizeof(argc) != sizeof(int),int,long>::type b = 0;
781 (void)a;
782 (void)b;
783 '''
784 ),
785 Cxx11RequiredFeature('std::unordered_map::emplace', '''
786 #include <unordered_map>
787 ''', '''
788 std::unordered_map<int,int> m;
789 m.emplace(0, 0);
790 '''
791 ),
792 Cxx11RequiredFeature('reference qualified methods', '''
793 struct %(N)s {
794 int a()const &{return 1;}
795 int a()const &&{return 2;}
796 };
797 ''', '''
798 %(N)s a;
799 auto b = a.a() != %(N)s().a();
800 (void)b;
801 '''
802 ),
803 Cxx11RequiredFeature('inheriting constructors', '''
804 /* Test for bug where clang + libc++ + constructor inheritance causes a
805 * compilation failure when returning nullptr.
806 *
807 * Works: gcc
808 * Works: clang + gcc libstdc++
809 * Works: old clang + old libc++ (cutoff date unknown).
810 * Works: new clang + new libc++ + unique_ptr<T>
811 * Fails: new clang + new libc++ + unique_ptr<T[]> (v3.6.0 confirmed broken).
812
813 memory:2676:32: error: no type named 'type' in 'std::__1::enable_if<false, std::__1::unique_ptr<int [], std::__1::default_delete<int []> >::__nat>'; 'enable_if' cannot be used to disable this declaration
814 typename enable_if<__same_or_less_cv_qualified<_Pp, pointer>::value, __nat>::type = __nat()) _NOEXCEPT
815 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
816 .sconf_temp/conftest_43.cpp:26:11: note: in instantiation of member function 'std::__1::unique_ptr<int [], std::__1::default_delete<int []> >::unique_ptr' requested here
817 using B::B;
818 ^
819 .sconf_temp/conftest_43.cpp:30:2: note: while substituting deduced template arguments into function template 'I' [with _Pp = I]
820 return nullptr;
821 ^
822 */
823 #include <memory>
824 class I%(N)s : std::unique_ptr<int[]>
825 {
826 public:
827 typedef std::unique_ptr<int[]> b%(N)s;
828 using b%(N)s::b%(N)s;
829 };
830 I%(N)s a%(N)s();
831 I%(N)s a%(N)s()
832 {
833 return nullptr;
834 }
835 ''', '''
836 I%(N)s i = a%(N)s();
837 (void)i;
838 '''
839 ),
840 ])
841 def __init__(self,msgprefix,user_settings,platform_settings):
842 self.msgprefix = msgprefix
843 self.user_settings = user_settings
844 self.platform_settings = platform_settings
845 self.successful_flags = defaultdict(list)
846 self._sconf_results = []
847 self.__tool_versions = []
848 self.__defined_macros = ''
849 # Some tests check the functionality of the compiler's
850 # optimizer.
851 #
852 # When LTO is used, the optimizer is deferred to link time.
853 # Force all tests to be Link tests when LTO is enabled.
854 self.Compile = self.Link if user_settings.lto else self._Compile
855 self.custom_tests = tuple(t for t in self.custom_tests if all(predicate(user_settings) for predicate in t.predicate))
856 def _quote_macro_value(v: str) -> str:
857 return v.strip().replace('\n', ' \\\n')
858 def _check_sconf_forced(self, calling_function: str) -> tuple:
859 return self._check_forced(calling_function), self._check_expected(calling_function)
860 @staticmethod
861 def _find_calling_sconf_function():
862 try:
863 1//0
864 except ZeroDivisionError:
865 frame = sys.exc_info()[2].tb_frame.f_back.f_back
866 while frame is not None:
867 co_name = frame.f_code.co_name
868 if co_name[:6] == 'check_':
869 return co_name[6:]
870 frame = frame.f_back
871 # This assertion is hit if a test is asked to deduce its caller
872 # (calling_function=None), but no function in the call stack appears to
873 # be a checking function.
874 assert False, "SConf caller not specified and no acceptable caller in stack."
875 def _check_forced(self, name: str) -> str:
876 # This getattr will raise AttributeError if called for a function which
877 # is not a registered test. Tests must be registered as an implicit
878 # test (in implicit_tests, usually by applying the @_implicit_test
879 # decorator) or a custom test (in custom_tests, usually by applying the
880 # @_custom_test decorator).
881 #
882 # Unregistered tests are never documented and cannot be overridden by
883 # the user.
884 return getattr(self.user_settings, f'sconf_{name}')
885 def _check_expected(self, name: str):
886 # The remarks for _check_forced apply here too.
887 r = getattr(self.user_settings, f'expect_sconf_{name}')
888 if r is not None:
889 if r == self.expect_sconf_success:
890 return 1
891 if r == self.expect_sconf_failure:
892 return 0
893 return r
894 def _check_macro(self, context, macro_name: str, macro_value: str, test: str, _comment_not_supported: str = comment_not_supported, **kwargs):
895 self._define_macro(context, macro_name, macro_value if (
896 self.Compile(context, text=f'''
897 #define {macro_name} {macro_value}
898 {test}
899 ''', **kwargs)
900 ) else _comment_not_supported)
901 def _define_macro(self, context, macro_name: str, macro_value: str) -> None:
902 context.sconf.Define(macro_name, macro_value)
903 self.__defined_macros += f'#define {macro_name} {macro_value}\n'
904 implicit_tests.append(_implicit_test.RecordedTest('check_ccache_distcc_ld_works', "assume ccache, distcc, C++ compiler, and C++ linker work"))
905 implicit_tests.append(_implicit_test.RecordedTest('check_ccache_ld_works', "assume ccache, C++ compiler, and C++ linker work"))
906 implicit_tests.append(_implicit_test.RecordedTest('check_distcc_ld_works', "assume distcc, C++ compiler, and C++ linker work"))
907 implicit_tests.append(_implicit_test.RecordedTest('check_ld_works', "assume C++ compiler and linker work"))
908 implicit_tests.append(_implicit_test.RecordedTest('check_ld_blank_libs_works', "assume C++ compiler and linker work with empty $LIBS"))
909 implicit_tests.append(_implicit_test.RecordedTest('check_ld_blank_libs_ldflags_works', "assume C++ compiler and linker work with empty $LIBS and empty $LDFLAGS"))
910 implicit_tests.append(_implicit_test.RecordedTest('check_cxx_blank_cxxflags_works', "assume C++ compiler works with empty $CXXFLAGS"))
911 # This must be the first custom test. This test verifies the compiler
912 # works and disables any use of ccache/distcc for the duration of the
913 # configure run.
914 #
915 # SCons caches configuration results and tests are usually very small, so
916 # ccache will provide limited benefit.
917 #
918 # Some tests are expected to raise a compiler error. If distcc is used
919 # and DISTCC_FALLBACK prevents local retries, then distcc interprets a
920 # compiler error as an indication that the volunteer which served that
921 # compile is broken and should be blacklisted. Suppress use of distcc for
922 # all tests to avoid spurious blacklist entries.
923 #
924 # During the main build, compiling remotely can allow more jobs to run in
925 # parallel. Tests are serialized by SCons, so distcc is helpful during
926 # testing only if compiling remotely is faster than compiling locally.
927 # This may be true for embedded systems that distcc to desktops, but will
928 # not be true for desktops or laptops that distcc to similar sized
929 # machines.
930 @_custom_test
931 def check_cxx_works(self,context):
932 """
933 help:assume C++ compiler works
934 """
935 # Use !r to print the tuple in an unambiguous form.
936 context.Log(f'scons: dxx: version: {(Git.compute_extra_version(),)!r}\n')
937 cenv = context.env
938 penv = cenv['ENV']
939 self.__cxx_com_prefix = cenv['CXXCOM']
940 # Require ccache to run the next stage, but allow it to write the
941 # result to cache. This lets the test validate that ccache fails for
942 # an unusable CCACHE_DIR and also validate that the next stage handles
943 # the input correctly. Without this, a cached result may hide that
944 # the next stage compiler (or wrapper) worked when a prior run
945 # performed the test, but is now broken.
946 CCACHE_RECACHE = penv.get('CCACHE_RECACHE', None)
947 penv['CCACHE_RECACHE'] = '1'
948 most_recent_error = self._check_cxx_works(context)
949 if most_recent_error is not None:
950 raise SCons.Errors.StopError(most_recent_error)
951 if CCACHE_RECACHE is None:
952 del penv['CCACHE_RECACHE']
953 else:
954 penv['CCACHE_RECACHE'] = CCACHE_RECACHE
955 # If ccache/distcc are in use, disable them during testing.
956 # This assignment is also done in _check_cxx_works, but only on an
957 # error path. Repeat it here so that it is effective on the success
958 # path. It cannot be moved above the call to _check_cxx_works because
959 # some tests in _check_cxx_works rely on its original value.
960 cenv['CXXCOM'] = cenv._dxx_cxxcom_no_prefix
961 self._check_cxx_conformance_level(context)
962 def _show_tool_version(self, context, tool: str, desc: str, save_tool_version: bool = True):
963 # These version results are not used for anything, but are
964 # collected here so that users who post only a build log will
965 # still supply at least some useful information.
966 #
967 # This is split into two lines so that the first line is printed
968 # before the function call required to format the string for the
969 # second line.
970 Display = context.Display
971 Display(f'{self.msgprefix}: checking version of {desc} {tool!r} ... ')
972 try:
973 v = StaticSubprocess.get_version_head(tool)
974 except OSError as e:
975 if e.errno == errno.ENOENT or e.errno == errno.EACCES:
976 Display(f'error: {e.strerror}\n')
977 raise SCons.Errors.StopError(f'Failed to run {tool!r}.')
978 raise
979 if save_tool_version:
980 self.__tool_versions.append((tool, v))
981 Display(f'{v!r}\n')
982 def _show_indirect_tool_version(self,context, CXX: str, tool: str, desc: str):
983 Display = context.Display
984 Display(f'{self.msgprefix}: checking path to {desc} ... ')
985 tool, name = ToolchainInformation.get_tool_path(context.env, tool)
986 self.__tool_versions.append((tool, name))
987 if not name:
988 # Strange, but not fatal for this to fail.
989 Display(f'! {name!r}\n')
990 return
991 Display(f'{name!r}\n')
992 self._show_tool_version(context,name,desc)
993 def _check_cxx_works(self,context,_crc32=binascii.crc32):
994 # Test whether the compiler+linker+optional wrapper(s) work. If
995 # anything fails, a StopError is guaranteed on return. However, to
996 # help the user, this function pushes through all the combinations and
997 # reports the StopError for the least complicated issue. If both the
998 # compiler and the linker fail, the compiler will be reported, since
999 # the linker might work once the compiler is fixed.
1000 #
1001 # If a test fails, then the pending StopError allows this function to
1002 # safely modify the construction environment and process environment
1003 # without reverting its changes.
1004 most_recent_error = None
1005 Link = self.Link
1006 cenv = context.env
1007 user_settings = self.user_settings
1008 use_distcc = user_settings.distcc
1009 use_ccache = user_settings.ccache
1010 text = '''
1011 /* When compiling using gcc, defining a virtual function requires linking to a
1012 * symbol from gcc libstdc++. If the linker is `gcc`, rather than `g++`, (which
1013 * can happen if the user sets `CXX=gcc`), then libstdc++ is not linked, and the
1014 * build fails with an error like:
1015
1016 ```
1017 undefined reference to `vtable for __cxxabiv1::__class_type_info'
1018 ```
1019
1020 * Test for that combination here, so that the test will report that the C++
1021 * linker does not work, rather than waiting for the user to get a link
1022 * failure in the game binary at the end of the build.
1023 */
1024 struct test_virtual_function_supported
1025 {
1026 virtual void a();
1027 };
1028
1029 void test_virtual_function_supported::a() {}
1030 '''
1031 if user_settings.show_tool_version:
1032 CXX = cenv['CXX']
1033 self._show_tool_version(context, CXX, 'C++ compiler')
1034 if user_settings.show_assembler_version:
1035 self._show_indirect_tool_version(context, CXX, 'as', 'assembler')
1036 if user_settings.show_linker_version:
1037 self._show_indirect_tool_version(context, CXX, 'ld', 'linker')
1038 if use_distcc:
1039 self._show_tool_version(context, use_distcc, 'distcc', False)
1040 if use_ccache:
1041 self._show_tool_version(context, use_ccache, 'ccache', False)
1042 # Use C++ single line comment so that it is guaranteed to extend
1043 # to the end of the line. repr ensures that embedded newlines
1044 # will be escaped and that the final character will not be a
1045 # backslash.
1046 self.__commented_tool_versions = s = ''.join(f'// {tool!r} => {value!r}\n' for tool, value in self.__tool_versions)
1047 self.__tool_versions = f'''
1048 /* This test is always false. Use a non-trivial condition to
1049 * discourage external text scanners from recognizing that the block
1050 * is never compiled. This is intended to encourage SCons to generate a new
1051 * test if any of the tools have changed their version identifier.
1052 */
1053 #if 1 < -1
1054 {_crc32(s.encode()):08x}
1055 {s}
1056 #endif
1057 '''
1058 ToolchainInformation.show_partial_environ(cenv, user_settings, context.Display, self.msgprefix)
1059 if use_ccache:
1060 if use_distcc:
1061 if Link(context, text=text, msg='whether ccache, distcc, C++ compiler, and linker work', calling_function='ccache_distcc_ld_works'):
1062 return
1063 most_recent_error = 'ccache and C++ linker work, but distcc does not work.'
1064 # Disable distcc so that the next call to self.Link tests only
1065 # ccache+linker.
1066 del cenv['ENV']['CCACHE_PREFIX']
1067 if Link(context, text=text, msg='whether ccache, C++ compiler, and linker work', calling_function='ccache_ld_works'):
1068 return most_recent_error
1069 most_recent_error = 'C++ linker works, but ccache does not work.'
1070 elif use_distcc:
1071 if Link(context, text=text, msg='whether distcc, C++ compiler, and linker work', calling_function='distcc_ld_works'):
1072 return
1073 most_recent_error = 'C++ linker works, but distcc does not work.'
1074 else:
1075 # This assertion fails if the environment's $CXXCOM was modified
1076 # to use a prefix, but both user_settings.ccache and
1077 # user_settings.distcc evaluate to false.
1078 assert cenv._dxx_cxxcom_no_prefix is cenv['CXXCOM'], "Unexpected prefix in $CXXCOM."
1079 # If ccache/distcc are in use, then testing with one or both of them
1080 # failed. Disable them so that the next test can check whether the
1081 # local linker works.
1082 #
1083 # If they are not in use, this assignment is a no-op.
1084 cenv['CXXCOM'] = cenv._dxx_cxxcom_no_prefix
1085 if Link(context, text=text, msg='whether C++ compiler and linker work', calling_function='ld_works'):
1086 # If ccache or distcc are in use, this block is only reached
1087 # when one or both of them failed. `most_recent_error` will
1088 # be a description of the failure. If neither are in use,
1089 # `most_recent_error` will be None.
1090 return most_recent_error
1091 # Force only compile, even if LTO is enabled.
1092 elif self._Compile(context, text=text, msg='whether C++ compiler works', calling_function='cxx_works'):
1093 specified_LIBS = 'or ' if cenv.get('LIBS') else ''
1094 if specified_LIBS:
1095 cenv['LIBS'] = []
1096 if Link(context, text=text, msg='whether C++ compiler and linker work with blank $LIBS', calling_function='ld_blank_libs_works'):
1097 # Using $LIBS="" allowed the test to succeed. $LIBS
1098 # specifies one or more unusable libraries. Usually
1099 # this is because it specifies a library which does
1100 # not exist or is an incompatible architecture.
1101 return 'C++ compiler works. C++ linker works with blank $LIBS. C++ linker does not work with specified $LIBS.'
1102 if cenv['LINKFLAGS']:
1103 cenv['LINKFLAGS'] = []
1104 if Link(context, text=text, msg='whether C++ compiler and linker work with blank $LIBS and blank $LDFLAGS', calling_function='ld_blank_libs_ldflags_works'):
1105 # Using LINKFLAGS="" allowed the test to succeed.
1106 # To avoid bloat, there is no further test to see
1107 # whether the link will work with user-specified
1108 # LIBS after LINKFLAGS is cleared. The user must
1109 # fix at least one problem anyway. If the user is
1110 # unlucky, fixing LINKFLAGS will result in a
1111 # different error on the next run. If the user is
1112 # lucky, fixing LINKFLAGS will allow the build to
1113 # run.
1114 return 'C++ compiler works. C++ linker works with blank $LIBS and blank $LDFLAGS. C++ linker does not work with blank $LIBS and specified $LDFLAGS.'
1115 return f'C++ compiler works. C++ linker does not work with specified {specified_LIBS}blank $LIBS and specified $LINKFLAGS. C++ linker does not work with blank $LIBS and blank $LINKFLAGS.'
1116 else:
1117 if cenv['CXXFLAGS']:
1118 cenv['CXXFLAGS'] = []
1119 if self._Compile(context, text=text, msg='whether C++ compiler works with blank $CXXFLAGS', calling_function='cxx_blank_cxxflags_works'):
1120 return 'C++ compiler works with blank $CXXFLAGS. C++ compiler does not work with specified $CXXFLAGS.'
1121 return 'C++ compiler does not work.'
1122 implicit_tests.append(_implicit_test.RecordedTest('check_cxx20', "assume C++ compiler supports C++20"))
1123 def _check_cxx_conformance_level(self, context):
1124 # Testing the compiler option parser only needs Compile, even when LTO
1125 # is enabled.
1126 Compile = self._Compile
1127 for level in (
1128 # List standards in descending order of preference.
1129 #
1130 # C++20 is required, so list it last.
1131 20,
1132 ):
1133 opt = f'-std=gnu++{level}'
1134 if Compile(context, text='', msg=f'whether C++ compiler accepts {opt}', successflags={'CXXFLAGS': (opt,)}, calling_function=f'cxx{level}'):
1135 return
1136 raise SCons.Errors.StopError('C++ compiler does not accept any supported C++ -std option.')
1137 def _Test(self,context,text,msg,action,main='',ext='.cpp',testflags={},successflags={},skipped=None,successmsg=None,failuremsg=None,expect_failure=False,calling_function=None,__flags_Werror = {'CXXFLAGS' : ['-Werror']}):
1138 if calling_function is None:
1139 calling_function = self._find_calling_sconf_function()
1140 context.Message(f'{self.msgprefix}: checking {msg}...')
1141 if skipped is not None:
1142 context.Result(f'(skipped){skipped}')
1143 if self.user_settings.record_sconf_results:
1144 self._sconf_results.append((calling_function, 'skipped'))
1145 return
1146 env_flags = self.PreservedEnvironment(context.env, (successflags.keys(), testflags.keys(), __flags_Werror.keys(), ('CPPDEFINES',)))
1147 context.env.MergeFlags(successflags)
1148 forced, expected = self._check_sconf_forced(calling_function)
1149 caller_modified_env_flags = self.PreservedEnvironment(context.env, (testflags.keys(), __flags_Werror.keys()))
1150 # Always pass -Werror to configure tests.
1151 context.env.Append(**__flags_Werror)
1152 context.env.Append(**testflags)
1153 # If forced is None, run the test. Otherwise, skip the test and
1154 # take an action determined by the value of forced.
1155 if forced is None:
1156 r = action(f'''
1157 {self.__tool_versions}
1158 {self.__defined_macros}
1159 {text}
1160
1161 #undef main /* avoid -Dmain=SDL_main from libSDL (and, on some platforms, from libSDL2) */
1162 '''
1163 # As a special case, a caller may set main=None to prevent generating the
1164 # `main()` function. This is only useful when the included headers or
1165 # expanded macros from `text` provide a definition of `main`.
1166 f'''{
1167 '' if main is None else
1168 f"""
1169 int main(int argc,char**argv)
1170 {{
1171 (void)argc;(void)argv;
1172 {main}
1173 ;
1174 }}
1175 """
1176 }
1177 ''', ext)
1178 # Some tests check that the compiler rejects an input.
1179 # SConf considers the result a failure when the compiler
1180 # rejects the input. For tests that consider a rejection to
1181 # be the good result, this conditional flips the sense of
1182 # the result so that a compiler rejection is reported as
1183 # success.
1184 if expect_failure:
1185 r = not r
1186 context.Result((successmsg if r else failuremsg) or r)
1187 if expected is not None and r != expected:
1188 raise SCons.Errors.StopError(f'Expected and actual results differ. Test should {"succeed" if expected else "fail"}, but it did not.')
1189 else:
1190 choices = (self.sconf_force_failure, self.sconf_force_success, self.sconf_assume_success)
1191 if forced not in choices:
1192 try:
1193 forced = choices[int(forced)]
1194 except ValueError:
1195 raise SCons.Errors.UserError(f'Unknown force value for sconf_{co_name[6:]}: {forced}')
1196 except IndexError:
1197 raise SCons.Errors.UserError(f'Out of range force value for sconf_{co_name[6:]}: {forced}')
1198 if forced == self.sconf_force_failure:
1199 # Pretend the test returned a failure result
1200 r = False
1201 elif forced == self.sconf_force_success or forced == self.sconf_assume_success:
1202 # Pretend the test succeeded. Forced success modifies
1203 # the environment as if the test had run and succeeded.
1204 # Assumed success modifies the environment as if the
1205 # test had run and failed.
1206 #
1207 # The latter is used when the user arranges for the
1208 # environment to be correct. For example, if the
1209 # compiler understands C++20, but uses a non-standard
1210 # name for the option, the user would set assume-success
1211 # and add the appropriate option to CXXFLAGS.
1212 r = True
1213 else:
1214 raise SCons.Errors.UserError(f'Unknown force value for sconf_{co_name[6:]}: {forced}')
1215 # Flip the sense of the forced value, so that users can
1216 # treat "force-failure" as force-bad-result regardless of
1217 # whether the bad result is that the compiler rejected good
1218 # input or that the compiler accepted bad input.
1219 if expect_failure:
1220 r = not r
1221 context.Result(f'(forced){("(inverted)" if expect_failure else "")}{forced}')
1222 # On success, revert to base flags + successflags
1223 # On failure, revert to base flags
1224 if r and forced != self.sconf_assume_success:
1225 caller_modified_env_flags.restore(context.env)
1226 context.env.Replace(CPPDEFINES=env_flags['CPPDEFINES'])
1227 f = self.successful_flags
1228 # Move most CPPDEFINES to the generated header, so that
1229 # command lines are shorter.
1230 for k, v in successflags.items():
1231 if k == 'CPPDEFINES':
1232 continue
1233 f[k].extend(v)
1234 d = successflags.get('CPPDEFINES', None)
1235 if d:
1236 append_CPPDEFINE = f['CPPDEFINES'].append
1237 Define = context.sconf.Define
1238 for v in d:
1239 # v is 'NAME' for -DNAME
1240 # v is ('NAME', 'VALUE') for -DNAME=VALUE
1241 d = (v, None) if isinstance(v, str) else v
1242 if d[0] in ('_REENTRANT',):
1243 # Blacklist defines that must not be moved to the
1244 # configuration header.
1245 append_CPPDEFINE(v)
1246 continue
1247 Define(d[0], d[1])
1248 else:
1249 env_flags.restore(context.env)
1250 self._sconf_results.append((calling_function, r))
1251 return r
1252 def _Compile(self,context,_Test=_Test,**kwargs):
1253 return _Test(self, context,action=context.TryCompile, **kwargs)
1254 def Link(self,context,_Test=_Test,**kwargs):
1255 return _Test(self, context,action=context.TryLink, **kwargs)
1256 # Compile and link a program that uses a system library. On
1257 # success, return None. On failure, return a tuple indicating which
1258 # stage failed and providing a text error message to show to the
1259 # user. Some callers handle failure by retrying with other options.
1260 # Others abort the SConf run.
1261 def _soft_check_system_library(self,context,header,main,lib,pretext='',text='',successflags={},testflags={}):
1262 include = pretext + ''.join([f'#include <{h}>\n' for h in header])
1263 header = header[-1]
1264 # Test library. On success, good. On failure, test header to
1265 # give the user more help.
1266 if self.Link(context, text=include + text, main=main, msg=f'for usable library {lib}', successflags=successflags, testflags=testflags):
1267 return
1268 # If linking failed, an error report is inevitable. Probe
1269 # progressively simpler configurations to help the user trace
1270 # the problem.
1271 successflags = successflags.copy()
1272 successflags.update(testflags)
1273 Compile = self.Compile
1274 if Compile(context, text=include + text, main=main, msg=f'for usable header {header}', testflags=successflags):
1275 # If this Compile succeeds, then the test program can be
1276 # compiled, but it cannot be linked. The required library
1277 # may be missing or broken.
1278 return (0, f'Header {header} is usable, but library {lib} is not usable.')
1279 if Compile(context, text=include, main=main and '', msg=f'whether compiler can parse header {header}', testflags=successflags):
1280 # If this Compile succeeds, then the test program cannot be
1281 # compiled, but the header can be used with an empty test
1282 # program. Either the test program is broken or it relies
1283 # on the header working differently than the used header
1284 # actually works.
1285 return (1, f'Header {header} is parseable, but cannot compile the test program.')
1286 CXXFLAGS = successflags.setdefault('CXXFLAGS', [])
1287 CXXFLAGS.append('-E')
1288 if Compile(context, text=include, main=main and '', msg=f'whether preprocessor can parse header {header}', testflags=successflags):
1289 # If this Compile succeeds, then the used header can be
1290 # preprocessed, but cannot be compiled as C++ even with an
1291 # empty test program. The header likely has a C++ syntax
1292 # error or assumes prerequisite headers will be included by
1293 # the calling program.
1294 return (2, f'Header {header} exists, but cannot compile an empty program.')
1295 CXXFLAGS.extend(('-M', '-MG'))
1296 # If the header exists and is accepted by the preprocessor, an
1297 # earlier test would have returned and this Compile would not be
1298 # reached. Therefore, this Compile runs only if the header:
1299 # - Is directly missing
1300 # - Is indirectly missing (present, but includes a missing
1301 # header)
1302 # - Is present, but rejected by the preprocessor (such as from
1303 # an active `#error`)
1304 if Compile(context, text=include, main=main and '', msg=f'whether preprocessor can locate header {header} (and supporting headers)', expect_failure=True, testflags=successflags):
1305 # If this Compile succeeds, then the header does not exist,
1306 # or exists and includes (possibly through layers of
1307 # indirection) a header which does not exist. Passing `-MG`
1308 # makes non-existent headers legal, but still rejects
1309 # headers with `#error` and similar constructs.
1310 #
1311 # `expect_failure=True` inverts it to a failure in the
1312 # logged output and in the Python value returned from
1313 # `Compile(...)`.
1314 # - Compile success means that the header was not found,
1315 # which is not an error when `-MG` is passed, but was an
1316 # error in earlier tests.
1317 # - Compile failure means that the header was found, but
1318 # unusable, which is an error even when `-MG` is passed.
1319 # This can happen if the header contains `#error`
1320 # directives that are not preprocessed out.
1321 # Therefore, use `expect_failure=True` so that "success"
1322 # (header not found) prints "no" ("cannot locate header")
1323 # and "failure" (header found, but unusable) prints "yes"
1324 # ("can locate header"). This keeps the confusing double
1325 # negatives confined to the code and this comment. User
1326 # visible log messages are clear.
1327 #
1328 # Compile failure (unusable) is converted to a True return
1329 # by `expect_failure=True`, so the guarded path should
1330 # return "unusable" and the fallthrough path should return
1331 # "missing".
1332 return (3, f'Header {header} is unusable.')
1333 return (4, f'Header {header} is missing or includes a missing supporting header.')
1334 # Compile and link a program that uses a system library. On
1335 # success, return None. On failure, abort the SConf run.
1336 def _check_system_library(self,*args,**kwargs):
1337 e = self._soft_check_system_library(*args, **kwargs)
1338 if e:
1339 raise SCons.Errors.StopError(e[1])
1340 # User settings tests are hidden because they do not respect sconf_*
1341 # overrides, so the user should not be offered an override.
1342 @_custom_test
1343 def _check_user_settings_endian(self,context,__endian_names=('little', 'big')):
1344 cls = self.__class__
1345 endian = self.user_settings.host_endian
1346 if endian is None:
1347 struct = cls.__python_import_struct
1348 if struct is None:
1349 import struct
1350 cls.__python_import_struct = struct
1351 a = struct.pack('cccc', b'1', b'2', b'3', b'4')
1352 unpack = struct.unpack
1353 i = unpack('i', a)
1354 if i == unpack('<i', a):
1355 endian = 0
1356 elif i == unpack('>i', a):
1357 endian = 1
1358 else:
1359 raise SCons.Errors.UserError(f"Unknown host endian: unpack('i', {a!r}) == {i!r}; set host_endian='big' or host_endian='little' as appropriate.")
1360 else:
1361 if endian == __endian_names[0]:
1362 endian = 0
1363 else:
1364 endian = 1
1365 context.Result(f'{self.msgprefix}: checking endian to use...{__endian_names[endian]}')
1366 self._define_macro(context, 'DXX_WORDS_BIGENDIAN', endian)
1367
1368 @_custom_test
1369 def _check_user_settings_words_need_alignment(self,context):
1370 self._result_check_user_setting(context, self.user_settings.words_need_alignment, 'word alignment fixups', cpp_defines_with_condition_value=('DXX_WORDS_NEED_ALIGNMENT',))
1371
1372 @_custom_test
1373 def _check_user_settings_opengl(self,context):
1374 user_settings = self.user_settings
1375 Result = context.Result
1376 _define_macro = self._define_macro
1377 _define_macro(context, 'DXX_USE_OGL', int(user_settings.opengl))
1378 _define_macro(context, 'DXX_USE_OGLES', int(user_settings.opengles))
1379 Result(f'''{self.msgprefix}: building with {
1380 "OpenGL ES" if user_settings.opengles else
1381 "OpenGL" if user_settings.opengl else
1382 "software renderer"
1383 }''')
1384
1385 def _result_check_user_setting(self, context, condition, label, cpp_defines_if_enabled: typing.Optional[tuple[tuple]]=None, cpp_defines_with_condition_value: typing.Optional[tuple[str]]=None, int=int):
1386 assert cpp_defines_if_enabled or cpp_defines_with_condition_value
1387 if cpp_defines_if_enabled and condition:
1388 for d in cpp_defines_if_enabled:
1389 assert isinstance(d[0], str), repr(d)
1390 self.successful_flags['CPPDEFINES'].extend(cpp_defines_if_enabled)
1391 if cpp_defines_with_condition_value:
1392 for d in cpp_defines_with_condition_value:
1393 assert isinstance(d, str)
1394 self._define_macro(context, d, int(condition))
1395 context.Result(f'{self.msgprefix}: checking whether to enable {label}...{"yes" if condition else "no"}')
1396
1397 @_custom_test
1398 def _check_user_settings_debug(self,context,_CPPDEFINES=(('NDEBUG',), ('RELEASE',))):
1399 self._result_check_user_setting(context, not self.user_settings.debug, 'release options', cpp_defines_if_enabled=_CPPDEFINES)
1400
1401 @_custom_test
1402 def _check_user_settings_memdebug(self,context,_CPPDEFINES=('DXX_USE_DEBUG_MEMORY_ALLOCATOR',)):
1403 self._result_check_user_setting(context, self.user_settings.memdebug, 'memory allocation tracking', cpp_defines_with_condition_value=_CPPDEFINES)
1404
1405 @_custom_test
1406 def _check_user_settings_editor(self,context,_CPPDEFINES=('DXX_USE_EDITOR',)):
1407 self._result_check_user_setting(context, self.user_settings.editor, 'level editor', cpp_defines_with_condition_value=_CPPDEFINES)
1408
1409 @_custom_test
1410 def _check_user_settings_ipv6(self,context,_CPPDEFINES=('DXX_USE_IPv6',)):
1411 self._result_check_user_setting(context, self.user_settings.ipv6, 'IPv6 support', cpp_defines_with_condition_value=_CPPDEFINES)
1412
1413 @_custom_test
1414 def _check_user_settings_stereo_render(self,context,_CPPDEFINES=('DXX_USE_STEREOSCOPIC_RENDER',)):
1415 self._result_check_user_setting(context, self.user_settings.use_stereo_render, 'stereoscopic rendering', cpp_defines_with_condition_value=_CPPDEFINES)
1416
1417 @_custom_test
1418 def _check_user_settings_udp(self,context,_CPPDEFINES=('DXX_USE_MULTIPLAYER', 'DXX_USE_UDP',)):
1419 self._result_check_user_setting(context, self.user_settings.use_udp, 'multiplayer over UDP', cpp_defines_with_condition_value=_CPPDEFINES)
1420
1421 @_custom_test
1422 def _check_user_settings_tracker(self,context,_CPPDEFINES=('DXX_USE_TRACKER',)):
1423 use_tracker = self.user_settings.use_udp and self.user_settings.use_tracker
1424 self._result_check_user_setting(context, use_tracker, 'UDP game tracker', cpp_defines_with_condition_value=_CPPDEFINES)
1425
1426 @_implicit_test
1427 def check_libpng(self,context,
1428 _header=(
1429 'cstdint',
1430 'png.h',
1431 ),
1432 _guess_flags={'LIBS' : ['png']},
1433 _text='''
1434 namespace {
1435 struct d_screenshot
1436 {
1437 png_struct *png_ptr;
1438 png_info *info_ptr = nullptr;
1439 static void png_error_cb(png_struct *, const char *) {}
1440 static void png_warn_cb(png_struct *, const char *) {}
1441 static void png_write_cb(png_struct *, uint8_t *, png_size_t) {}
1442 static void png_flush_cb(png_struct *) {}
1443 };
1444 }
1445 ''',
1446 _main='''
1447 d_screenshot ss;
1448 ss.png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, &ss, &d_screenshot::png_error_cb, &d_screenshot::png_warn_cb);
1449 png_set_write_fn(ss.png_ptr, &ss, &d_screenshot::png_write_cb, &d_screenshot::png_flush_cb);
1450 ss.info_ptr = png_create_info_struct(ss.png_ptr);
1451 #ifdef PNG_tIME_SUPPORTED
1452 png_time pt;
1453 pt.year = 2018;
1454 pt.month = 1;
1455 pt.day = 1;
1456 pt.hour = 1;
1457 pt.minute = 1;
1458 pt.second = 1;
1459 png_set_tIME(ss.png_ptr, ss.info_ptr, &pt);
1460 #endif
1461 #if DXX_USE_OGL
1462 const auto color_type{PNG_COLOR_TYPE_RGB};
1463 #else
1464 png_set_PLTE(ss.png_ptr, ss.info_ptr, reinterpret_cast<const png_color *>(&ss), 256 * 3);
1465 const auto color_type{PNG_COLOR_TYPE_PALETTE};
1466 #endif
1467 png_set_IHDR(ss.png_ptr, ss.info_ptr, 1, 1, 8, color_type, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1468 #ifdef PNG_TEXT_SUPPORTED
1469 png_text text_fields[1] = {};
1470 png_set_text(ss.png_ptr, ss.info_ptr, text_fields, 1);
1471 #endif
1472 png_write_info(ss.png_ptr, ss.info_ptr);
1473 png_byte *row_pointers[1024]{};
1474 png_write_rows(ss.png_ptr, row_pointers, 1024);
1475 png_write_end(ss.png_ptr, ss.info_ptr);
1476 png_destroy_write_struct(&ss.png_ptr, &ss.info_ptr);
1477 '''):
1478 successflags = self.pkgconfig.merge(context, self.msgprefix, self.user_settings, 'libpng', 'libpng', _guess_flags)
1479 return self._soft_check_system_library(context, header=_header, main=_main, lib='png', text=_text, successflags=successflags)
1480
1481 @_custom_test
1482 def _check_user_settings_adldmidi(self,context):
1483 user_settings = self.user_settings
1484 adlmidi = user_settings.adlmidi
1485 if adlmidi == 'none':
1486 adlmidi_load_type = 'disabled'
1487 elif adlmidi == 'runtime':
1488 adlmidi_load_type = 'load dynamically'
1489 else:
1490 return
1491 context.Result(f'{self.msgprefix}: checking how to handle ADL MIDI...{adlmidi_load_type}')
1492 Define = context.sconf.Define
1493 Define('DXX_USE_ADLMIDI', int(user_settings._enable_adlmidi()))
1494
1495 @_custom_test
1496 def _check_user_settings_screenshot(self,context):
1497 user_settings = self.user_settings
1498 screenshot_mode = user_settings.screenshot
1499 if screenshot_mode == 'png':
1500 screenshot_format_type = screenshot_mode
1501 elif screenshot_mode == 'legacy':
1502 screenshot_format_type = 'tga' if user_settings.opengl else 'pcx'
1503 elif screenshot_mode == 'none':
1504 screenshot_format_type = 'screenshot support disabled'
1505 else:
1506 return
1507 context.Result(f'{self.msgprefix}: checking how to format screenshots...{screenshot_format_type}')
1508 Define = context.sconf.Define
1509 Define('DXX_USE_SCREENSHOT_FORMAT_PNG', int(screenshot_mode == 'png'))
1510 Define('DXX_USE_SCREENSHOT_FORMAT_LEGACY', int(screenshot_mode == 'legacy'))
1511 Define('DXX_USE_SCREENSHOT', int(screenshot_mode != 'none'))
1512 if screenshot_mode == 'png':
1513 e = self.check_libpng(context)
1514 if e:
1515 raise SCons.Errors.StopError(e[1] + ' Set screenshot=legacy to remove screenshot libpng requirement or set screenshot=none to remove screenshot support.')
1516
1517 # Require _WIN32_WINNT >= 0x0501 to enable getaddrinfo
1518 # Require _WIN32_WINNT >= 0x0600 to enable some useful AI_* flags
1519 @_guarded_test_windows
1520 def _check_user_CPPDEFINES__WIN32_WINNT(self,context,_msg='%s: checking whether to define _WIN32_WINNT...%s',_CPPDEFINES_WIN32_WINNT=('_WIN32_WINNT', 0x600)):
1521 env = context.env
1522 for f in env['CPPDEFINES']:
1523 # Ignore the case that an element is a string with this
1524 # value, since that would not define the macro to a
1525 # useful value. In CPPDEFINES, only a tuple of
1526 # (name,number) is useful for macro _WIN32_WINNT.
1527 if f[0] == '_WIN32_WINNT':
1528 f = f[1]
1529 context.Result(_msg % (self.msgprefix, 'no, already set in CPPDEFINES as %s' % (f'{f:#x}' if isinstance(f, int) else f'{f!r}',)))
1530 return
1531 for f in env['CPPFLAGS']:
1532 if f.startswith('-D_WIN32_WINNT='):
1533 context.Result(_msg % (self.msgprefix, f'no, already set in CPPFLAGS as {f!r}'))
1534 return
1535 context.Result(_msg % (self.msgprefix, f'yes, define _WIN32_WINNT={_CPPDEFINES_WIN32_WINNT[1]:#x}'))
1536 self.successful_flags['CPPDEFINES'].append(_CPPDEFINES_WIN32_WINNT)
1537 self.__defined_macros += f'#define {_CPPDEFINES_WIN32_WINNT[0]} {_CPPDEFINES_WIN32_WINNT[1]}\n'
1538
1539 @_guarded_test_windows
1540 def check_dbghelp_header(self,context,_CPPDEFINES=('DXX_ENABLE_WINDOWS_MINIDUMP',)):
1541 windows_minidump = self.user_settings.windows_minidump
1542 self._result_check_user_setting(context, windows_minidump, 'minidump on exception', cpp_defines_if_enabled=_CPPDEFINES)
1543 if not windows_minidump:
1544 return
1545 include_dbghelp_header = '''
1546 // <dbghelp.h> assumes that <windows.h> was included earlier and fails
1547 // to parse if this assumption is false
1548 #include <windows.h>
1549 #include <dbghelp.h>
1550 '''
1551 if self.Compile(context, text=include_dbghelp_header + '''
1552 #include <stdexcept>
1553
1554 using MiniDumpWriteDump_type = decltype(MiniDumpWriteDump);
1555 MiniDumpWriteDump_type *pMiniDumpWriteDump;
1556
1557 [[noreturn]]
1558 static void terminate_handler()
1559 {
1560 MINIDUMP_EXCEPTION_INFORMATION mei;
1561 MINIDUMP_USER_STREAM musa[1];
1562 MINIDUMP_USER_STREAM_INFORMATION musi;
1563 EXCEPTION_POINTERS ep;
1564 mei.ExceptionPointers = &ep;
1565 musi.UserStreamCount = 1;
1566 musi.UserStreamArray = musa;
1567 (*pMiniDumpWriteDump)(GetCurrentProcess(), GetCurrentProcessId(), GetCurrentProcess(), MiniDumpWithFullMemory, &mei, &musi, nullptr);
1568 ExitProcess(0);
1569 }
1570 ''', main='''
1571 std::set_terminate(&terminate_handler);
1572 ''', msg='for usable header dbghelp.h'):
1573 return
1574 errtext = "Header dbghelp.h is parseable but cannot compile the test program." \
1575 if self.Compile(context, text=include_dbghelp_header, msg='for parseable header dbghelp.h') \
1576 else "Header dbghelp.h is missing or unusable."
1577 raise SCons.Errors.StopError(errtext + " Upgrade the Windows API header package or disable minidump support.")
1578 @_custom_test
1579 def check_libphysfs(self,context,_header=('physfs.h',)):
1580 main = '''
1581 PHYSFS_File *f;
1582 char b[1] = {0};
1583 if (!PHYSFS_init(""))
1584 return 1;
1585 {
1586 const char *r = PHYSFS_getRealDir("");
1587 (void)r;
1588 }
1589 PHYSFS_isDirectory("");
1590 {
1591 const char *sep = PHYSFS_getDirSeparator();
1592 (void)sep;
1593 }
1594 {
1595 const char *dir = PHYSFS_getBaseDir();
1596 (void)dir;
1597 }
1598 {
1599 const char *dir = PHYSFS_getUserDir();
1600 (void)dir;
1601 }
1602 f = PHYSFS_openWrite("a");
1603 PHYSFS_sint64 w{PHYSFS_writeBytes(f, b, 1)};
1604 (void)w;
1605 PHYSFS_close(f);
1606 f = PHYSFS_openRead("a");
1607 PHYSFS_sint64 rb{PHYSFS_readBytes(f, b, 1)};
1608 (void)rb;
1609 PHYSFS_close(f);
1610 PHYSFS_mount("", nullptr, 0);
1611 PHYSFS_unmount("");
1612 PHYSFS_delete("");
1613 '''
1614 l = ['physfs']
1615 guess_flags = {'LIBS' : l}
1616 # If pkg-config is not available, or the `physfs.pc` file is not
1617 # usable, then `successflags is guess_flags`. Otherwise,
1618 # `successflags` is derived from the output of `pkg-config`.
1619 successflags = self.pkgconfig.merge(context, self.msgprefix, self.user_settings, 'physfs', 'physfs', guess_flags)
1620 e = self._soft_check_system_library(context, header=_header, main=main, lib='physfs', successflags=successflags)
1621 if not e:
1622 # If the test succeeded outright, return.
1623 return
1624 if e[0] == 0 and successflags is guess_flags:
1625 # If the header is usable, but the link test failed, and the link
1626 # test was done using `guess_flags`, then speculatively add zlib to
1627 # the link line and retry. This is a convenience for users who (1)
1628 # use a physfs that depends on zlib and (2) do not use a pkg-config
1629 # file, so they have no place to express the dependency on zlib.
1630 # For users who use pkg-config, the pkg-config output is assumed to
1631 # be correct, and this speculative retry is skipped.
1632 context.Display(f'{self.msgprefix}: physfs header usable; adding zlib and retesting library\n')
1633 # `l is guess_flags['LIBS']` and `successflags is guess_flags`, so
1634 # `l is successflags['LIBS']`. Therefore, this `append` modifies
1635 # the value of `successflags`.
1636 l.append('z')
1637 e = self._soft_check_system_library(context, header=_header, main=main, lib='physfs', successflags=successflags)
1638 if e:
1639 raise SCons.Errors.StopError(e[1])
1640
1641 # SDL-only builds do not need GL utility functions
1642 # OpenGLES builds do not use the GL utility functions
1643 @GuardedCollector(_custom_test, lambda user_settings: user_settings.opengl and not user_settings.opengles)
1644 def check_glu(self,context):
1645 ogllibs = self.platform_settings.ogllibs
1646 self._check_system_library(context, header=['OpenGL/glu.h' if self.user_settings.host_platform == 'darwin' else 'GL/glu.h'], main='''
1647 gluPerspective(90.0,1.0,0.1,5000.0);
1648 gluBuild2DMipmaps (GL_TEXTURE_2D, 0, 1, 1, 1, GL_UNSIGNED_BYTE, nullptr);
1649 ''', lib=ogllibs, testflags={'LIBS': ogllibs})
1650
1651 @_custom_test
1652 def _check_SDL(self,context):
1653 if self.user_settings.sdl2:
1654 check_libSDL = self.check_libSDL2
1655 check_SDL_image = self.check_SDL2_image
1656 check_SDL_mixer = self.check_SDL2_mixer
1657 else:
1658 check_libSDL = self.check_libSDL
1659 check_SDL_image = self.check_SDL_image
1660 check_SDL_mixer = self.check_SDL_mixer
1661 check_libSDL(context)
1662 check_SDL_image(context)
1663 check_SDL_mixer(context)
1664
1665 @_implicit_test
1666 def check_libSDL(self,context,_guess_flags={
1667 'LIBS' : ['SDL'] if sys.platform != 'darwin' else [],
1668 }):
1669 self._check_libSDL(context, '', _guess_flags)
1670
1671 @_implicit_test
1672 def check_libSDL2(self,context,_guess_flags={
1673 'LIBS' : ['SDL2'] if sys.platform != 'darwin' else [],
1674 }):
1675 if not self.user_settings.opengl:
1676 raise SCons.Errors.StopError('Rebirth does not support SDL2 without OpenGL. Set opengl=1 or sdl2=0.')
1677 self._check_libSDL(context, '2', _guess_flags)
1678
1679 def _check_libSDL(self,context,sdl2,guess_flags):
1680 user_settings = self.user_settings
1681 successflags = self.pkgconfig.merge(context, self.msgprefix, user_settings, f'sdl{sdl2}', f'SDL{sdl2}', guess_flags).copy()
1682 if user_settings.max_joysticks:
1683 # If joysticks are enabled, but all possible inputs are
1684 # disabled, then disable joystick support.
1685 if not (user_settings.max_axes_per_joystick or user_settings.max_buttons_per_joystick or user_settings.max_hats_per_joystick):
1686 user_settings.max_joysticks = 0
1687 elif not user_settings.max_buttons_per_joystick:
1688 user_settings.max_hats_per_joystick = 0
1689 else:
1690 # If joysticks are disabled, then disable all possible
1691 # inputs.
1692 user_settings.max_axes_per_joystick = user_settings.max_buttons_per_joystick = user_settings.max_hats_per_joystick = 0
1693 successflags['CPPDEFINES'] = CPPDEFINES = successflags.get('CPPDEFINES', []).copy()
1694 # use Redbook if at least one of the following applies
1695 # 1. we are on SDL1
1696 # 2. we are building for a platform for which we have a custom CD implementation (currently only win32)
1697 use_redbook = int(not sdl2 or user_settings.host_platform == 'win32')
1698 CPPDEFINES.extend((
1699 ('DXX_MAX_JOYSTICKS', user_settings.max_joysticks),
1700 ('DXX_MAX_AXES_PER_JOYSTICK', user_settings.max_axes_per_joystick),
1701 ('DXX_MAX_BUTTONS_PER_JOYSTICK', user_settings.max_buttons_per_joystick),
1702 ('DXX_MAX_HATS_PER_JOYSTICK', user_settings.max_hats_per_joystick),
1703 ('DXX_USE_SDL_REDBOOK_AUDIO', use_redbook),
1704 ))
1705 context.Display(f'{self.msgprefix}: checking whether to enable joystick support...{"yes" if user_settings.max_joysticks else "no"}\n')
1706 # SDL2 removed CD-rom support.
1707 init_cdrom = '0' if sdl2 else 'SDL_INIT_CDROM'
1708 error_text_opengl_mismatch = f'Rebirth configured with OpenGL enabled, but SDL{sdl2} configured with OpenGL disabled. Disable Rebirth OpenGL or install an SDL{sdl2} with OpenGL enabled.'
1709 test_opengl = (f'''
1710 #if !((SDL_MAJOR_VERSION == 1) && (SDL_MINOR_VERSION == 2) && (SDL_PATCHLEVEL >= 50))
1711 #ifndef SDL_VIDEO_OPENGL
1712 #error "{error_text_opengl_mismatch}"
1713 #endif
1714 #endif
1715 ''') if user_settings.opengl else ''
1716 main = '''
1717 SDL_RWops *ops = reinterpret_cast<SDL_RWops *>(argv);
1718 #if DXX_MAX_JOYSTICKS
1719 #ifdef SDL_JOYSTICK_DISABLED
1720 #error "Rebirth configured with joystick support enabled, but SDL{sdl2} configured with joystick support disabled. Disable Rebirth joystick support or install an SDL{sdl2} with joystick support enabled."
1721 #endif
1722 #define DXX_SDL_INIT_JOYSTICK SDL_INIT_JOYSTICK |
1723 #else
1724 #define DXX_SDL_INIT_JOYSTICK
1725 #endif
1726 SDL_Init(DXX_SDL_INIT_JOYSTICK {init_cdrom} | SDL_INIT_VIDEO | SDL_INIT_AUDIO);
1727 {test_opengl}
1728 #if DXX_MAX_JOYSTICKS
1729 auto n = SDL_NumJoysticks();
1730 (void)n;
1731 #endif
1732 SDL_QuitSubSystem(SDL_INIT_VIDEO);
1733 SDL_FreeRW(ops);
1734 SDL_Quit();
1735 '''
1736 e = self._soft_check_system_library(context,header=['SDL.h'],main=main.format(init_cdrom=init_cdrom, sdl2=sdl2, test_opengl=test_opengl),
1737 lib=f'SDL{sdl2} with{"" if test_opengl else "out"} OpenGL', successflags=successflags
1738 )
1739 if not e:
1740 return
1741 if test_opengl:
1742 e2 = self._soft_check_system_library(context,header=['SDL.h'],main=main.format(init_cdrom=init_cdrom, sdl2=sdl2, test_opengl=''),
1743 lib=f'SDL{sdl2} without OpenGL', successflags=successflags
1744 )
1745 if not e2 and e[0] == 1:
1746 e = (None, error_text_opengl_mismatch)
1747 raise SCons.Errors.StopError(e[1])
1748
1749 @_implicit_test
1750 def check_SDL_image(self,context):
1751 self._check_SDL_image(context, '')
1752
1753 @_implicit_test
1754 def check_SDL2_image(self,context):
1755 self._check_SDL_image(context, '2')
1756
1757 def _check_SDL_image(self,context,sdl2):
1758 self._check_SDL_addon_library(context, sdl2, 'SDL%s_image', 'DXX_USE_SDLIMAGE', self.user_settings.sdlimage, '''
1759 IMG_Init(0);
1760 SDL_RWops *rw = reinterpret_cast<SDL_RWops *>(argv);
1761 SDL_Surface *s = IMG_LoadPCX_RW(rw);
1762 (void)s;
1763 IMG_Quit();
1764 ''')
1765
1766 # SDL_mixer/SDL2_mixer use the same -I line as SDL/SDL2
1767 @_implicit_test
1768 def check_SDL_mixer(self,context):
1769 self._check_SDL_mixer(context, '')
1770
1771 @_implicit_test
1772 def check_SDL2_mixer(self,context):
1773 self._check_SDL_mixer(context, '2')
1774
1775 def _check_SDL_mixer(self,context,sdl2):
1776 self._check_SDL_addon_library(context, sdl2, 'SDL%s_mixer', 'DXX_USE_SDLMIXER', self.user_settings.sdlmixer, '''
1777 int i = Mix_Init(MIX_INIT_FLAC | MIX_INIT_OGG);
1778 (void)i;
1779 Mix_Pause(0);
1780 Mix_ResumeMusic();
1781 Mix_Quit();
1782 ''')
1783
1784 def _check_SDL_addon_library(self,context,sdl2,library_format_name,macro_name,use_addon,main):
1785 library_name = library_format_name % sdl2
1786 self._define_macro(context, macro_name, int(use_addon))
1787 context.Display(f'{self.msgprefix}: checking whether to use {library_name}...{"yes" if use_addon else "no"}\n')
1788 if not use_addon:
1789 return
1790 user_settings = self.user_settings
1791 guess_flags = {
1792 'LIBS' : [library_name] if sys.platform != 'darwin' else [],
1793 }
1794 successflags = self.pkgconfig.merge(context, self.msgprefix, user_settings, library_name, library_name, guess_flags)
1795 if user_settings.host_platform == 'darwin' and user_settings.macos_add_frameworks:
1796 successflags = successflags.copy()
1797 successflags['FRAMEWORKS'] = [library_name]
1798 relative_headers = f'Library/Frameworks/{library_name}.framework/Headers'
1799 successflags['CPPPATH'] = [h for h in (os.path.join(os.getenv("HOME"), relative_headers), f'/{relative_headers}') if os.path.isdir(h)]
1800 # SDL2 headers still use SDL_*.h for their filename, not
1801 # SDL2_*.h, so expanded library_format_name with an explicitly
1802 # blank insert, regardless of whether building for SDL1 or SDL2.
1803 self._check_system_library(context, header=['%s.h' % (library_format_name % '')], main=main, lib=library_name, successflags=successflags)
1804
1805 @_custom_test
1806 def check_attribute_error(self,context):
1807 """
1808 Test whether the compiler accepts and properly implements gcc's function
1809 attribute [__attribute__((__error__))][1].
1810
1811 A proper implementation will compile correctly if the function is
1812 declared and, after optimizations are applied, the function is not
1813 called. If this function attribute is not supported, then
1814 DXX_ALWAYS_ERROR_FUNCTION results in link-time errors, rather than
1815 compile-time errors.
1816
1817 This test will report failure if the optimizer does not remove the call
1818 to the marked function.
1819
1820 [1]: https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#index-g_t_0040code_007berror_007d-function-attribute-3097
1821
1822 help:assume compiler supports __attribute__((error))
1823 """
1824 self._check_function_dce_attribute(context, 'error')
1825 context.sconf.config_h_text += '''
1826 #ifndef DXX_SCONF_NO_INCLUDES
1827 dxx_compiler_attribute_error("must never be called")
1828 void DXX_ALWAYS_ERROR_FUNCTION(const char *);
1829 #endif
1830 '''
1831 def _check_function_dce_attribute(self,context,attribute):
1832 __attribute__ = f'__{attribute}__'
1833 f = f'''
1834 void a()__attribute__(({__attribute__}("a called")));
1835 '''
1836 macro_name = f'dxx_compiler_attribute_{attribute}(M)'
1837 Compile = self.Compile
1838 Define = context.sconf.Define
1839 if Compile(context, text=f, main='if("0"[0]==\'1\')a();', msg=f'whether compiler optimizes function __attribute__(({__attribute__}))'):
1840 Define(f'DXX_HAVE_ATTRIBUTE_{attribute.upper()}')
1841 macro_value = f'__attribute__(({__attribute__}(M)))'
1842 else:
1843 Compile(context, text=f, msg=f'whether compiler accepts function __attribute__(({__attribute__}))') and \
1844 Compile(context, text=f, main='a();', msg=f'whether compiler understands function __attribute__(({__attribute__}))', expect_failure=True)
1845 macro_value = self.comment_not_supported
1846 Define(macro_name, macro_value)
1847 self.__defined_macros += f'#define {macro_name} {macro_value}\n'
1848
1849 @_custom_test
1850 def check_builtin_bswap(self,context,
1851 _main='''
1852 (void)__builtin_bswap64(static_cast<uint64_t>(argc));
1853 (void)__builtin_bswap32(static_cast<uint32_t>(argc));
1854 (void)__builtin_bswap16(static_cast<uint16_t>(argc));
1855 ''',
1856 _successflags_bswap={'CPPDEFINES' : ['DXX_HAVE_BUILTIN_BSWAP']},
1857 ):
1858 """
1859 Test whether the compiler accepts the gcc byte swapping intrinsic
1860 functions. These functions may be optimized into architecture-specific
1861 swap instructions when the idiomatic swap is not.
1862
1863 u16 = (u16 << 8) | (u16 >> 8);
1864
1865 The 16-bit ([__builtin_bswap16][3]), 32-bit ([__builtin_bswap32][1]),
1866 and 64-bit ([__builtin_bswap64][2]) versions are present in all
1867 supported versions of gcc.
1868
1869 [1]: https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html#index-g_t_005f_005fbuiltin_005fbswap32-4135
1870 [2]: https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html#index-g_t_005f_005fbuiltin_005fbswap64-4136
1871 [3]: https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html#index-g_t_005f_005fbuiltin_005fbswap16-4134
1872 """
1873 include = '''
1874 #include <cstdint>
1875 '''
1876 self.Compile(context, text=include, main=_main, msg='whether compiler implements __builtin_bswap{16,32,64} functions', successflags=_successflags_bswap)
1877
1878 implicit_tests.append(_implicit_test.RecordedTest('check_optimize_builtin_constant_p', "assume compiler optimizes __builtin_constant_p"))
1879
1880 @_custom_test
1881 def check_builtin_constant_p(self,context):
1882 """
1883 Test whether the compiler accepts and properly implements gcc's
1884 intrinsic [__builtin_constant_p][1]. A proper implementation will
1885 compile correctly if the intrinsic is recognized and, after
1886 optimizations are applied, the intrinsic returns true for a constant
1887 input and that return value is used to optimize away dead code.
1888 If this intrinsic is not supported, or if applying optimizations
1889 does not make the intrinsic report true, then the test reports
1890 failure. A failure here disables some compile-time sanity checks.
1891
1892 This test is known to fail when optimizations are disabled. The failure
1893 is not a bug in the test or in the compiler.
1894
1895 [1]: https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html#index-g_t_005f_005fbuiltin_005fconstant_005fp-4082
1896
1897 help:assume compiler supports compile-time __builtin_constant_p
1898 """
1899 f = '''
1900 /*
1901 * Begin `timekeeping.i` from gcc bug #72785, comment #0. This block
1902 * provokes gcc-7 into generating a call to ____ilog2_NaN, which then
1903 * fails to link when ____ilog2_NaN is intentionally undefined.
1904 *
1905 * Older versions of gcc declare the expression to be false in
1906 * this case, and do not generate the call to ____ilog2_NaN. This looks
1907 * fragile since b is provably non-zero (`b` = `a` if `a` is not zero,
1908 * else = `c` = `1`, so `b` is non-zero regardless of the path used in
1909 * the ternary operator), but the specific non-zero value is not
1910 * provable. However, this matches the testcase posted in gcc's
1911 * Bugzilla and produces the desired results on each of gcc-5 (enable),
1912 * gcc-6 (enable), and gcc-7 (disable).
1913 */
1914 int a, b;
1915 int ____ilog2_NaN();
1916 static void by(void) {
1917 int c = 1;
1918 b = a ?: c;
1919 __builtin_constant_p(b) ? b ? ____ilog2_NaN() : 0 : 0;
1920 }
1921 /*
1922 * End `timekeeping.i`.
1923 */
1924 int c(int);
1925 static int x(int y){
1926 return __builtin_constant_p(y) ? 1 : %s;
1927 }
1928 '''
1929 main = '''
1930 /*
1931 ** Tell the compiler not to make any assumptions about the value of
1932 ** `a`. In LTO mode, the compiler would otherwise prove that it
1933 ** knows there are no writes to `a` and therefore prove that `a`
1934 ** must be zero. That proof then causes it to compile `by()` as:
1935 **
1936 ** b = 0 ? 0 : 1;
1937 ** __builtin_constant_p(1) ? 1 ? ____ilog2_NaN() : 0 : 0;
1938 **
1939 ** That then generates a reference to the intentionally undefined
1940 ** ____ilog2_NaN, causing the test to report failure. Prevent this
1941 ** by telling the compiler that it cannot prove the value of `a`,
1942 ** forcing it not to propagate a zero `a` into `by()`.
1943 **/
1944 asm("" : "=rm" (a));
1945 by();
1946 return x(1) + x(2);
1947 '''
1948 Define = context.sconf.Define
1949 if self.Link(context, text=f % 'c(y)', main=main, msg='whether compiler optimizes __builtin_constant_p', calling_function='optimize_builtin_constant_p'):
1950 Define('DXX_HAVE_BUILTIN_CONSTANT_P')
1951 Define('DXX_CONSTANT_TRUE(E)', '(__builtin_constant_p((E)) && (E))')
1952 dxx_builtin_constant_p = '__builtin_constant_p(A)'
1953 else:
1954 # This is present because it may be useful to see in the
1955 # debug log. It is not expected to modify the build
1956 # environment.
1957 self.Compile(context, text=f % '2', main=main, msg='whether compiler accepts __builtin_constant_p')
1958 dxx_builtin_constant_p = '((void)(A),0)'
1959 Define('dxx_builtin_constant_p(A)', dxx_builtin_constant_p)
1960
1961 @_custom_test
1962 def check_builtin_expect(self,context):
1963 """
1964 Test whether the compiler accepts gcc's intrinsic
1965 [__builtin_expect][1]. This intrinsic is a hint to the optimizer,
1966 which it may ignore. The test does not try to detect whether the
1967 optimizer respects such hints.
1968
1969 When this test succeeds, conditional tests can hint to the optimizer
1970 which path should be considered hot.
1971
1972 [1]: https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html#index-g_t_005f_005fbuiltin_005fexpect-4083
1973 """
1974 main = '''
1975 return __builtin_expect(argc == 1, 1) ? 1 : 0;
1976 '''
1977 if self.Compile(context, text='', main=main, msg='whether compiler accepts __builtin_expect'):
1978 likely = '__builtin_expect(!!(A), 1)'
1979 unlikely = '__builtin_expect(!!(A), 0)'
1980 else:
1981 likely = unlikely = '(!!(A))'
1982 Define = context.sconf.Define
1983 Define('likely(A)', likely)
1984 Define('unlikely(A)', unlikely)
1985
1986 @_custom_test
1987 def check_builtin_file(self,context):
1988 context.sconf.Define('DXX_HAVE_CXX_BUILTIN_FILE_LINE',
1989 self.Compile(context, text='''
1990 static void f(const char * = __builtin_FILE(), unsigned = __builtin_LINE())
1991 {
1992 struct A
1993 {
1994 unsigned line{__builtin_LINE()};
1995 };
1996 static_assert(A{}.line == __LINE__);
1997 }
1998 ''', main='f();', msg='whether compiler accepts __builtin_FILE, __builtin_LINE'))
1999
2000 @_custom_test
2001 def check_builtin_object_size(self,context):
2002 """
2003 Test whether the compiler accepts and optimizes gcc's intrinsic
2004 [__builtin_object_size][1]. If this intrinsic is optimized,
2005 compile-time checks can verify that the caller-specified constant
2006 size of a variable does not exceed the compiler-determined size of
2007 the variable. If the compiler cannot determine the size of the
2008 variable, no compile-time check is done.
2009
2010 [1]: https://gcc.gnu.org/onlinedocs/gcc/Object-Size-Checking.html#index-g_t_005f_005fbuiltin_005fobject_005fsize-3657
2011
2012 help:assume compiler supports __builtin_object_size
2013 """
2014 f = '''
2015 /* a() is never defined. An optimizing compiler will eliminate the
2016 * attempt to call it, allowing the Link to succeed. A non-optimizing
2017 * compiler will emit the call, and the Link will fail.
2018 */
2019 int a();
2020 static inline int a(char *c){
2021 return __builtin_object_size(c,0) == 4 ? 1 : %s;
2022 }
2023 '''
2024 main = '''
2025 char c[4];
2026 return a(c);
2027 '''
2028 r = self.Link(context, text=f % 'a()', main=main, msg='whether compiler optimizes __builtin_object_size')
2029 context.sconf.Define('DXX_HAVE_BUILTIN_OBJECT_SIZE', int(r))
2030 if not r:
2031 # This test is only to provide additional information in the
2032 # configure log. The result does not influence the build.
2033 self.Compile(context, text=f % '2', main=main, msg='whether compiler accepts __builtin_object_size')
2034
2035 @_custom_test
2036 def check_embedded_compound_statement(self,context,
2037 _compound_statement_native=('', ''),
2038 _compound_statement_emulated=('[&]', '()')
2039 ):
2040 """
2041 Test whether the compiler implements gcc's [statement expression][1]
2042 extension. If this extension is present, statements can be used where
2043 expressions are expected. If it is absent, it is emulated by defining,
2044 calling, and then discarding a lambda function. The compiler produces
2045 better error messages for errors in statement expressions than for
2046 errors in lambdas, so prefer statement expressions when they are
2047 available.
2048
2049 [1]: https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html
2050 """
2051 f = '''
2052 return ({ 1 + 2; });
2053 '''
2054 t = _compound_statement_native if self.Compile(context, text='', main=f, msg='whether compiler understands embedded compound statements') else _compound_statement_emulated
2055 Define = context.sconf.Define
2056 Define('DXX_BEGIN_COMPOUND_STATEMENT', t[0])
2057 Define('DXX_END_COMPOUND_STATEMENT', t[1])
2058
2059 @_custom_test
2060 def check_attribute_always_inline(self,context):
2061 """
2062 help:assume compiler supports [[gnu::always_inline]]
2063 """
2064 macro_name = 'dxx_compiler_attribute_always_inline()'
2065 macro_value = '[[gnu::always_inline]]'
2066 self._check_macro(context,macro_name=macro_name,macro_value=macro_value,test=f'{macro_name} static inline void a(){{}}', main='a();', msg='for C++ function attribute [[gnu::always_inline]]')
2067
2068 @GuardedCollector(_custom_test, lambda user_settings: user_settings.memdebug)
2069 def check_attribute_alloc_size(self,context):
2070 """
2071 help:assume compiler supports __attribute__((alloc_size))
2072 """
2073 macro_name = 'dxx_compiler_attribute_alloc_size(A,...)'
2074 macro_value = '__attribute__((alloc_size(A, ## __VA_ARGS__)))'
2075 self._check_macro(context,macro_name=macro_name,macro_value=macro_value,test="""
2076 char*a(int)dxx_compiler_attribute_alloc_size(1);
2077 char*b(int,int)dxx_compiler_attribute_alloc_size(1,2);
2078 """, msg='for function __attribute__((alloc_size))')
2079 @_custom_test
2080 def check_attribute_cold(self,context):
2081 """
2082 Test whether the compiler accepts the C++ function attribute
2083 [[gnu::cold]]. Use this to annotate functions which are
2084 rarely called, such as error reporting functions.
2085 """
2086 macro_name = 'dxx_compiler_attribute_cold'
2087 macro_value = '[[gnu::cold]]'
2088 self._check_macro(context,macro_name=macro_name,macro_value=macro_value,test="""
2089 dxx_compiler_attribute_cold char*a(int);
2090 """, msg='for C++ function attribute [[gnu::cold]]')
2091 @_custom_test
2092 def check_attribute_format_arg(self,context):
2093 """
2094 help:assume compiler supports __attribute__((format_arg))
2095 """
2096 macro_name = 'dxx_compiler_attribute_format_arg(A)'
2097 macro_value = '__attribute__((format_arg(A)))'
2098 self._check_macro(context,macro_name=macro_name,macro_value=macro_value,test="""
2099 char*a(char*)dxx_compiler_attribute_format_arg(1);
2100 """, msg='for function __attribute__((format_arg))')
2101 @_custom_test
2102 def check_attribute_format_printf(self,context):
2103 """
2104 help:assume compiler supports __attribute__((format(printf)))
2105 """
2106 macro_name = 'dxx_compiler_attribute_format_printf(A,B)'
2107 macro_value = '__attribute__((format(printf,A,B)))'
2108 self._check_macro(context,macro_name=macro_name,macro_value=macro_value,test="""
2109 int a(char*,...)dxx_compiler_attribute_format_printf(1,2);
2110 int b(char*)dxx_compiler_attribute_format_printf(1,0);
2111 """, msg='for function __attribute__((format(printf)))')
2112 @GuardedCollector(_custom_test, lambda user_settings: user_settings.memdebug)
2113 def check_attribute_malloc(self,context):
2114 """
2115 help:assume compiler supports __attribute__((malloc))
2116 """
2117 macro_name = 'dxx_compiler_attribute_malloc()'
2118 macro_value = '__attribute__((malloc))'
2119 self._check_macro(context,macro_name=macro_name,macro_value=macro_value,test="""
2120 int *a()dxx_compiler_attribute_malloc();
2121 """, msg='for function __attribute__((malloc))')
2122 @_custom_test
2123 def check_attribute_nonnull(self,context):
2124 """
2125 help:assume compiler supports __attribute__((nonnull))
2126 """
2127 macro_name = 'dxx_compiler_attribute_nonnull(...)'
2128 macro_value = '__attribute__((nonnull __VA_ARGS__))'
2129 self._check_macro(context,macro_name=macro_name,macro_value=macro_value,test="""
2130 int a(int*)dxx_compiler_attribute_nonnull();
2131 int b(int*)dxx_compiler_attribute_nonnull((1));
2132 """, msg='for function __attribute__((nonnull))')
2133
2134 @_custom_test
2135 def check_attribute_used(self,context):
2136 """
2137 help:assume compiler supports __attribute__((used))
2138 """
2139 macro_name = 'dxx_compiler_attribute_used'
2140 macro_value = '__attribute__((used))'
2141 self._check_macro(context,macro_name=macro_name,macro_value=macro_value,test="""
2142 static void a()dxx_compiler_attribute_used;
2143 static void a(){}
2144 """, msg='for function __attribute__((used))')
2145 @_custom_test
2146 def check_attribute_unused(self,context):
2147 """
2148 help:assume compiler supports __attribute__((unused))
2149 """
2150 macro_name = 'dxx_compiler_attribute_unused'
2151 macro_value = '__attribute__((unused))'
2152 self._check_macro(context,macro_name=macro_name,macro_value=macro_value,test="""
2153 dxx_compiler_attribute_unused
2154 static void a(){}
2155 """, msg='for function __attribute__((unused))', successflags={'CXXFLAGS' : get_Werror_sequence(context.env['CXXFLAGS'], ('-Wunused',))})
2156
2157 @_custom_test
2158 def check_cxx11_static_assert(self,context,_f='''
2159 static_assert(%(expr)s, "global");
2160 struct A
2161 {
2162 static const bool value = %(expr)s;
2163 static_assert(%(expr)s, "class literal");
2164 static_assert(A::value, "class static");
2165 A()
2166 {
2167 static_assert(%(expr)s, "constructor literal");
2168 static_assert(value, "constructor static");
2169 }
2170 };
2171 template <typename>
2172 struct B
2173 {
2174 static const bool value = %(expr)s;
2175 static_assert(%(expr)s, "template class literal");
2176 static_assert(value, "template class static");
2177 B(A a)
2178 {
2179 static_assert(%(expr)s, "constructor literal");
2180 static_assert(value, "constructor self static");
2181 static_assert(A::value, "constructor static");
2182 static_assert(a.value, "constructor member");
2183 }
2184 template <typename R>
2185 B(B<R> &&)
2186 {
2187 static_assert(%(expr)s, "template constructor literal");
2188 static_assert(value, "template constructor self static");
2189 static_assert(B<R>::value, "template constructor static");
2190 }
2191 };
2192 template <typename T>
2193 static void f(B<T> b)
2194 {
2195 static_assert(%(expr)s, "template function literal");
2196 static_assert(B<T>::value, "template function static");
2197 static_assert(b.value, "template function member");
2198 }
2199 void f(A a);
2200 void f(A a)
2201 {
2202 static_assert(%(expr)s, "function literal");
2203 static_assert(A::value, "function static");
2204 static_assert(a.value, "function member");
2205 f(B<long>(B<int>(a)));
2206 }
2207 '''
2208 ,_msg='for C++11 intrinsic static_assert when %s',_tdict={'expr' : 'true&&true'},_fdict={'expr' : 'false||false'}):
2209 """
2210 help:assume compiler supports C++ intrinsic static_assert
2211 """
2212 _Compile = self.Compile
2213 if not (_Compile(context, text=_f % _tdict, main='f(A());', msg=_msg % 'true') and \
2214 _Compile(context, text=_f % _fdict, main='f(A());', msg=_msg % 'false', expect_failure=True)):
2215 raise SCons.Errors.StopError('C++ compiler does not support tested versions of C++11 static_assert.')
2216
2217 @_custom_test
2218 def check_namespace_disambiguate(self,context,_successflags={'CPPDEFINES' : ['DXX_HAVE_CXX_DISAMBIGUATE_USING_NAMESPACE']}):
2219 '''
2220 Test how the compiler handles the ambiguity of a namespace at top level scope
2221 and a class with the same name in an inner scope.
2222
2223 - gcc (all tested versions) treat `A` as a namespace, and find the variable
2224 declared in that namespace.
2225 - clang (all tested versions) treat `A` as ambiguous and fail the compilation.
2226
2227 The gcc behavior is useful to allow selectively poisoning the dcx/dsx
2228 namespaces when used in the wrong scope, without breaking legitimate accesses
2229 to them. Therefore, when the compiler can handle this ambiguity,
2230 `common/include/dsx-ns.h` forward declares appropriate ambiguous names.
2231 See the comments in that header for more details.
2232
2233 help:assume compiler can disambiguate classes and namespaces
2234 '''
2235 self.Compile(context, text='''
2236 namespace A
2237 {
2238 int a;
2239 }
2240 using namespace A;
2241 namespace B
2242 {
2243 class A;
2244 }
2245 using namespace B;
2246 ''', main='return A::a;', msg='whether compiler handles classes from "using namespace"', successflags=_successflags)
2247
2248 @_custom_test
2249 def check_cxx_std_required_features(self,context,_features=__cxx_std_required_features):
2250 # First test all the features at once. If all work, then done.
2251 # If any fail, then the configure run will stop.
2252 _Compile = self.Compile
2253 if _Compile(context, text=_features.text, main=_features.main, msg='for required C++11, C++14, C++17, C++20 standard features'):
2254 return
2255 # Some failed. Run each test separately and report to the user
2256 # which ones failed.
2257 failures = tuple(f.name for f in _features.features if not _Compile(context, text=f.text, main=f.main, msg=f'for C++{f.std} {f.name}'))
2258 raise SCons.Errors.StopError((f'C++ compiler does not support {", ".join(failures)}.'
2259 ) if failures else 'C++ compiler supports each feature individually, but not all of them together. Please report this as a bug in the Rebirth configure script.')
2260
2261 def _show_pch_count_message(self,context,which,user_setting):
2262 count = user_setting if user_setting else 0
2263 context.Display(f'{self.msgprefix}: checking when to pre-compile {which} headers...{f"""if used at least {count} time{"s" if count > 1 else ""}""" if count > 0 else "never"}\n')
2264 return count > 0
2265
2266 implicit_tests.append(_implicit_test.RecordedTest('check_pch_compile', "assume C++ compiler can create pre-compiled headers"))
2267 implicit_tests.append(_implicit_test.RecordedTest('check_pch_use', "assume C++ compiler can use pre-compiled headers"))
2268
2269 @_custom_test
2270 def _check_pch(self,context,
2271 _Test=_Test,
2272 _testflags_compile_pch={'CXXFLAGS' : ['-x', 'c++-header']},
2273 _testflags_use_pch={'CXXFLAGS' : ['-Winvalid-pch', '-include', None]}
2274 ):
2275 self.pch_flags = None
2276 # Always evaluate both
2277 co = self._show_pch_count_message(context, 'own', self.user_settings.pch)
2278 cs = self._show_pch_count_message(context, 'system', self.user_settings.syspch)
2279 context.did_show_result = True
2280 if not co and not cs:
2281 return
2282 context.Display(f'{self.msgprefix}: checking when to compute pre-compiled header input *pch.cpp...{"if missing" if self.user_settings.pch_cpp_assume_unchanged else "always"}\n')
2283 result = _Test(self, context, action=self.PCHAction(context), text='', msg='whether compiler can create pre-compiled headers', testflags=_testflags_compile_pch, calling_function='pch_compile')
2284 if not result:
2285 raise SCons.Errors.StopError("C++ compiler cannot create pre-compiled headers.")
2286 _testflags_use_pch = _testflags_use_pch.copy()
2287 _testflags_use_pch['CXXFLAGS'][-1] = str(context.lastTarget)[:-4]
2288 result = self.Compile(context, text='''
2289 /* This symbol is defined in the PCH. If the PCH is included, this
2290 * symbol will preprocess away to nothing. If the PCH is not included,
2291 * then the compiler is not using PCHs as expected.
2292 */
2293 dxx_compiler_supports_pch
2294 ''', msg='whether compiler uses pre-compiled headers', testflags=_testflags_use_pch, calling_function='pch_use')
2295 if not result:
2296 raise SCons.Errors.StopError("C++ compiler cannot use pre-compiled headers.")
2297 self.pch_flags = _testflags_compile_pch
2298
2299 @_custom_test
2300 def check_deep_tuple(self,context):
2301 text = '''
2302 #include <tuple>
2303 static inline std::tuple<{type}> make() {{
2304 return std::make_tuple({value});
2305 }}
2306 static void a(){{
2307 std::tuple<{type}> t = make();
2308 (void)t;
2309 }}
2310 '''
2311 count = 20
2312 Compile = self.Compile
2313 if Compile(context, text=text.format(type=','.join(('int',)*count), value=','.join(('0',)*count)), main='a()', msg='whether compiler handles 20-element tuples'):
2314 return
2315 count = 2
2316 raise SCons.Errors.StopError(
2317 "Compiler cannot handle tuples of 20 elements. Raise the template instantiation depth." \
2318 if Compile(context, text=text.format(type=','.join(('int',)*count), value=','.join(('0',)*count)), main='a()', msg='whether compiler handles 2-element tuples') \
2319 else "Compiler cannot handle tuples of 2 elements."
2320 )
2321
2322 @_implicit_test
2323 def check_poison_valgrind(self,context):
2324 '''
2325 help:add Valgrind annotations; wipe certain freed memory when running under Valgrind
2326 '''
2327 context.Message(f'{self.msgprefix}: checking whether to use Valgrind poisoning...')
2328 r = 'valgrind' in self.user_settings.poison
2329 context.Result(r)
2330 self._define_macro(context, 'DXX_HAVE_POISON_VALGRIND', int(r))
2331 if not r:
2332 return
2333 text = '''
2334 #define DXX_HAVE_POISON 1
2335 #include "compiler-poison.h"
2336 '''
2337 main = '''
2338 DXX_MAKE_MEM_UNDEFINED(std::span<int, 1>(&argc, 1));
2339 '''
2340 if self.Compile(context, text=text, main=main, msg='whether Valgrind memcheck header works'):
2341 return True
2342 raise SCons.Errors.StopError("Valgrind poison requested, but <valgrind/memcheck.h> does not work.")
2343
2344 @_implicit_test
2345 def check_poison_overwrite(self,context):
2346 '''
2347 help:always wipe certain freed memory
2348 '''
2349 context.Message(f'{self.msgprefix}: checking whether to use overwrite poisoning...')
2350 r = 'overwrite' in self.user_settings.poison
2351 context.Result(r)
2352 self._define_macro(context, 'DXX_HAVE_POISON_OVERWRITE', int(r))
2353 return r
2354
2355 @_custom_test
2356 def _check_poison_method(self,context,
2357 _methods=(check_poison_overwrite, check_poison_valgrind),
2358 poison=0
2359 ):
2360 # Always run both checks. The user may want a program that
2361 # always uses overwrite poisoning and, when running under
2362 # Valgrind, marks the memory as undefined.
2363 for f in _methods:
2364 if f(self, context):
2365 poison = 1
2366 self._define_macro(context, 'DXX_HAVE_POISON', poison)
2367 implicit_tests.append(_implicit_test.RecordedTest('check_size_type_size', "assume size_t is formatted as `size_t`"))
2368 implicit_tests.append(_implicit_test.RecordedTest('check_size_type_long', "assume size_t is formatted as `unsigned long`"))
2369 implicit_tests.append(_implicit_test.RecordedTest('check_size_type_int', "assume size_t is formatted as `unsigned int`"))
2370 implicit_tests.append(_implicit_test.RecordedTest('check_size_type_I64', "assume size_t is formatted as `unsigned I64`"))
2371
2372 @_custom_test
2373 def _check_size_type_format_modifier(self,context,_text_format='''
2374 #include <cstddef>
2375 #define DXX_PRI_size_type {}
2376 dxx_compiler_attribute_format_printf(1, 2)
2377 void f(const char *, ...);
2378 void f(const char *, ...)
2379 {{
2380 }}
2381 '''.format,_main='''
2382 std::size_t s = 0;
2383 f("%" DXX_PRI_size_type, s);
2384 '''):
2385 '''
2386 The test must declare a custom function to call with this format string.
2387 gcc has hardcoded knowledge about how printf works, but that knowledge
2388 on Mingw64 differs from the processing of
2389 __attribute__((format(printf,...))). Mingw64 requires I64u for
2390 __attribute__((format)) functions, but llu for printf. Mingw32 is
2391 consistent in its use of u. Linux gcc is consistent in its use of
2392 lu.
2393
2394 -- cut --
2395 #include <cstdio>
2396 #include <cstddef>
2397 __attribute__((format(printf,1,2))) void f(const char *,...);
2398 void a() {
2399 std::size_t b = 0;
2400 printf("%I64u", b);
2401 f("%I64u", b);
2402 printf("%llu", b);
2403 f("%llu", b);
2404 printf("%lu", b);
2405 f("%lu", b);
2406 printf("%u", b);
2407 f("%u", b);
2408 }
2409 -- cut --
2410
2411 $ x86_64-w64-mingw32-g++-5.4.0 -x c++ -S -Wformat -o /dev/null -
2412 <stdin>: In function 'void a()':
2413 <stdin>:6:19: warning: format '%u' expects argument of type 'unsigned int', but argument 2 has type 'std::size_t {aka long long unsigned int}' [-Wformat=]
2414 <stdin>:9:13: warning: unknown conversion type character 'l' in format [-Wformat=]
2415 <stdin>:9:13: warning: too many arguments for format [-Wformat-extra-args]
2416 <stdin>:10:17: warning: format '%lu' expects argument of type 'long unsigned int', but argument 2 has type 'std::size_t {aka long long unsigned int}' [-Wformat=]
2417 <stdin>:11:12: warning: format '%lu' expects argument of type 'long unsigned int', but argument 2 has type 'std::size_t {aka long long unsigned int}' [-Wformat=]
2418 <stdin>:12:16: warning: format '%u' expects argument of type 'unsigned int', but argument 2 has type 'std::size_t {aka long long unsigned int}' [-Wformat=]
2419 <stdin>:13:11: warning: format '%u' expects argument of type 'unsigned int', but argument 2 has type 'std::size_t {aka long long unsigned int}' [-Wformat=]
2420
2421 $ i686-w64-mingw32-g++-5.4.0 -x c++ -S -Wformat -o /dev/null -
2422 <stdin>: In function 'void a()':
2423 <stdin>:7:14: warning: format '%I64u' expects argument of type 'long long unsigned int', but argument 2 has type 'std::size_t {aka unsigned int}' [-Wformat=]
2424 <stdin>:8:18: warning: format '%llu' expects argument of type 'long long unsigned int', but argument 2 has type 'std::size_t {aka unsigned int}' [-Wformat=]
2425 <stdin>:9:13: warning: unknown conversion type character 'l' in format [-Wformat=]
2426 <stdin>:9:13: warning: too many arguments for format [-Wformat-extra-args]
2427 <stdin>:10:17: warning: format '%lu' expects argument of type 'long unsigned int', but argument 2 has type 'std::size_t {aka unsigned int}' [-Wformat=]
2428 <stdin>:11:12: warning: format '%lu' expects argument of type 'long unsigned int', but argument 2 has type 'std::size_t {aka unsigned int}' [-Wformat=]
2429
2430 $ mingw32-g++-5.4.0 -x c++ -S -Wformat -o /dev/null -
2431 <stdin>: In function 'void a()':
2432 <stdin>:6:19: warning: format '%I64u' expects argument of type 'long long unsigned int', but argument 2 has type 'std::size_t {aka unsigned int}' [-Wformat=]
2433 <stdin>:7:14: warning: format '%I64u' expects argument of type 'long long unsigned int', but argument 2 has type 'std::size_t {aka unsigned int}' [-Wformat=]
2434 <stdin>:8:18: warning: unknown conversion type character 'l' in format [-Wformat=]
2435 <stdin>:8:18: warning: too many arguments for format [-Wformat-extra-args]
2436 <stdin>:9:13: warning: unknown conversion type character 'l' in format [-Wformat=]
2437 <stdin>:9:13: warning: too many arguments for format [-Wformat-extra-args]
2438 <stdin>:10:17: warning: format '%lu' expects argument of type 'long unsigned int', but argument 2 has type 'std::size_t {aka unsigned int}' [-Wformat=]
2439 <stdin>:11:12: warning: format '%lu' expects argument of type 'long unsigned int', but argument 2 has type 'std::size_t {aka unsigned int}' [-Wformat=]
2440
2441 $ x86_64-pc-linux-gnu-g++-5.4.0 -x c++ -S -Wformat -o /dev/null -
2442 <stdin>: In function 'void a()':
2443 <stdin>:6:19: warning: format '%u' expects argument of type 'unsigned int', but argument 2 has type 'std::size_t {aka long unsigned int}' [-Wformat=]
2444 <stdin>:7:14: warning: format '%u' expects argument of type 'unsigned int', but argument 2 has type 'std::size_t {aka long unsigned int}' [-Wformat=]
2445 <stdin>:8:18: warning: format '%llu' expects argument of type 'long long unsigned int', but argument 2 has type 'std::size_t {aka long unsigned int}' [-Wformat=]
2446 <stdin>:9:13: warning: format '%llu' expects argument of type 'long long unsigned int', but argument 2 has type 'std::size_t {aka long unsigned int}' [-Wformat=]
2447 <stdin>:12:16: warning: format '%u' expects argument of type 'unsigned int', but argument 2 has type 'std::size_t {aka long unsigned int}' [-Wformat=]
2448 <stdin>:13:11: warning: format '%u' expects argument of type 'unsigned int', but argument 2 has type 'std::size_t {aka long unsigned int}' [-Wformat=]
2449
2450 '''
2451 # Test types in order of decreasing probability.
2452 for DXX_PRI_size_type, calling_function in (
2453 # Linux
2454 ('z', 'size_type_size'),
2455 ('l', 'size_type_long'),
2456 # Win64
2457 ('I64', 'size_type_I64'),
2458 # Win32
2459 ('', 'size_type_int'),
2460 ):
2461 f = f'"{DXX_PRI_size_type}u"'
2462 if self.Compile(context, text=_text_format(f), main=_main, msg=f'whether to format std::size_t with "%{DXX_PRI_size_type}u"', calling_function=calling_function):
2463 context.sconf.Define('DXX_PRI_size_type', f)
2464 return
2465 raise SCons.Errors.StopError("C++ compiler rejects all candidate format strings for std::size_t.")
2466 implicit_tests.append(_implicit_test.RecordedTest('check_compiler_accepts_useless_cast', "assume compiler accepts -Wuseless-cast"))
2467
2468 @_custom_test
2469 def check_compiler_useless_cast(self,context):
2470 Compile = self.Compile
2471 flags = {'CXXFLAGS' : get_Werror_sequence(context.env['CXXFLAGS'], ('-Wuseless-cast',))}
2472 if Compile(context, text='''
2473 /*
2474 * SDL on Raspbian provokes a warning from -Wuseless-cast
2475 *
2476 * Reported-by: derhass <https://github.com/dxx-rebirth/dxx-rebirth/issues/257>
2477 */
2478 #include <SDL_endian.h>
2479
2480 ''', main='''
2481 return SDL_Swap32(argc);
2482 ''', msg='whether compiler argument -Wuseless-cast works with SDL', successflags=flags):
2483 return
2484 # <=clang-16 does not understand -Wuseless-cast
2485 # This test does not influence the compile environment, but is
2486 # run to distinguish in the output whether the failure is
2487 # because the compiler does not accept -Wuseless-cast or because
2488 # SDL's headers provoke a warning from -Wuseless-cast.
2489 Compile(context, text='', main='', msg='whether compiler accepts -Wuseless-cast', testflags=flags, calling_function='compiler_accepts_useless_cast')
2490
2491 @_custom_test
2492 def check_compiler_ptrdiff_cast_int(self,context):
2493 context.sconf.Define('DXX_ptrdiff_cast_int', 'static_cast<int>'
2494 if self.Compile(context, text='''
2495 #include <cstdio>
2496 ''', main='''
2497 char a[8];
2498 snprintf(a, sizeof(a), "%.*s", static_cast<int>(&argv[0][1] - &argv[0][0]), "0");
2499 ''', msg='whether to cast operator-(T*,T*) to int')
2500 else '',
2501 '''
2502 For mingw32-gcc-5.4.0 and x86_64-pc-linux-gnu-gcc-5.4.0, gcc defines
2503 `long operator-(T *, T *)`.
2504
2505 For mingw32, gcc reports a useless cast converting `long` to `int`.
2506 For x86_64-pc-linux-gnu, gcc does not report a useless cast converting
2507 `long` to `int`.
2508
2509 Various parts of the code take the difference of two pointers, then cast
2510 it to `int` to be passed as a parameter to `snprintf` field width
2511 conversion `.*`. The field width conversion is defined to take `int`,
2512 so the cast is necessary to avoid a warning from `-Wformat` on
2513 x86_64-pc-linux-gnu, but is not necessary on mingw32. However, the cast
2514 causes a -Wuseless-cast warning on mingw32. Resolve these conflicting
2515 requirements by defining a macro that expands to `static_cast<int>` on
2516 platforms where the cast is required and expands to nothing on platforms
2517 where the cast is useless.
2518 '''
2519 )
2520
2521 @_custom_test
2522 def check_compiler_size_t_cast_unsigned_int(self,context):
2523 context.sconf.Define('DXX_size_t_cast_unsigned_int', 'static_cast<unsigned>'
2524 if self.Compile(context, text='''
2525 #include <cstddef>
2526 ''', main='''
2527 std::size_t i{1000};
2528 unsigned u{static_cast<unsigned>(i)};
2529 (void)u;
2530 ''', msg='whether to cast std::size_t to unsigned int')
2531 else '')
2532
2533 @_custom_test
2534 def check_strcasecmp_present(self,context,_successflags={'CPPDEFINES' : ['DXX_HAVE_STRCASECMP']}):
2535 main = '''
2536 return !strcasecmp(argv[0], argv[0] + 1) && !strncasecmp(argv[0] + 1, argv[0], 1);
2537 '''
2538 self.Compile(context, text='#include <cstring>', main=main, msg='for strcasecmp', successflags=_successflags)
2539
2540 @_custom_test
2541 def check_getaddrinfo_present(self,context,_successflags={'CPPDEFINES' : ['DXX_HAVE_GETADDRINFO']}):
2542 self.Compile(context, text='''
2543 #ifdef WIN32
2544 #include <winsock2.h>
2545 #include <ws2tcpip.h>
2546 #else
2547 #include <sys/types.h>
2548 #include <sys/socket.h>
2549 #include <netdb.h>
2550 #endif
2551 ''', main='''
2552 addrinfo *res = nullptr;
2553 addrinfo hints{};
2554 #ifdef AI_NUMERICSERV
2555 /* Test that it is defined to a term that can be used with bit-or */
2556 hints.ai_flags |= AI_NUMERICSERV;
2557 #endif
2558 #if DXX_USE_IPv6
2559 hints.ai_flags |= AI_V4MAPPED | AI_ALL;
2560 #endif
2561 int i = getaddrinfo("", "", &hints, &res);
2562 (void)i;
2563 freeaddrinfo(res);
2564 return 0;
2565 ''', msg='for getaddrinfo', successflags=_successflags)
2566
2567 @_guarded_test_windows
2568 def check_inet_ntop_present(self,context,_successflags={'CPPDEFINES' : ['DXX_HAVE_INET_NTOP']}):
2569 # Linux and OS X have working inet_ntop on all supported
2570 # platforms. Only Windows sometimes lacks support for this
2571 # function.
2572 if self.Compile(context, text='''
2573 #include <winsock2.h>
2574 #include <ws2tcpip.h>
2575 ''', main='''
2576 struct sockaddr_in sai;
2577 char dbuf[64];
2578 return inet_ntop(AF_INET, &sai.sin_addr, dbuf, sizeof(dbuf)) ? 0 : 1;
2579 ''', msg='for inet_ntop', successflags=_successflags):
2580 return
2581 if self.user_settings.ipv6:
2582 raise SCons.Errors.StopError("IPv6 enabled and inet_ntop not available: disable IPv6 or upgrade headers to support inet_ntop.")
2583
2584 @_custom_test
2585 def check_timespec_present(self,context,_successflags={'CPPDEFINES' : ['DXX_HAVE_STRUCT_TIMESPEC']}):
2586 self.Compile(context, text='''
2587 #include <time.h>
2588 ''', main='''
2589 struct timespec ts;
2590 (void)ts;
2591 return 0;
2592 ''', msg='for struct timespec', successflags=_successflags)
2593
2594 @_custom_test
2595 def check_warn_implicit_fallthrough(self,context,_successflags={'CXXFLAGS' : ['-Wimplicit-fallthrough=5']}):
2596 main = '''
2597 int a = 1;
2598 switch (argc) {
2599 case 1:
2600 ++ a;
2601 [[fallthrough]];
2602 case 2:
2603 ++ a;
2604 break;
2605 }
2606 (void)a;
2607 '''
2608 sconf = context.sconf
2609 self.Compile(context, text='', main=main, msg='whether compiler accepts -Wimplicit-fallthrough=5', successflags=_successflags)
2610
2611 @_custom_test
2612 def check_compiler_overzealous_unused_lambda_capture(self,context):
2613 '''
2614 <clang-5: untested
2615 >clang-8: untested
2616 >=clang-5 && <=clang-8: when -Wunused is passed, clang will warn when a lambda captures by reference a local variable that is itself a reference, regardless of whether the lambda body uses the captured value. The warning is:
2617
2618 ```
2619 similar/main/object.cpp:1060:13: error: lambda capture 'vmobjptr' is not required to be captured for this use [-Werror,-Wunused-lambda-capture]
2620 auto l = [&vmobjptr, &r, &num_to_free](bool (*predicate)(const vcobjptr_t)) -> bool {
2621 ```
2622
2623 <gcc-8 require such variables to be captured and will fail the build if the capture is removed.
2624 >=gcc-8 permit the variable not to be captured, and will not warn regardless of whether it is captured.
2625
2626 Test whether the compiler warns for this case and, if it does, tell it
2627 not to warn. Once support is removed for gcc versions which require the
2628 capture, this test can be dropped and the warning reinstated.
2629
2630 If clang learns to treat -Wunused-lambda-capture (by way of -Wunused) as
2631 a request to warn only about captures that are _actually_ unused, rather
2632 than also those that are used but not required, this test will stop
2633 disabling the warning on clang. Since this quirk was discussed when the
2634 warning was added[1], and the warning was added in its current form
2635 anyway, it seems unlikely this will be fixed soon.
2636
2637 [1]: https://marc.info/?l=cfe-commits&m=148494796318826&w=2
2638 |: https://marc.info/?l=cfe-commits&m=148509467111194&w=2
2639 |: https://marc.info/?l=cfe-commits&m=148520882106501&w=2
2640 '''
2641 if not self.Compile(context, text='''
2642 int a;
2643 ''', main='''
2644 auto &b = a;
2645 [&b]() {
2646 ++b;
2647 }();
2648 ''', msg='whether compiler allows lambda capture of local references'):
2649 self.successful_flags['CXXFLAGS'].append('-Wno-unused-lambda-capture')
2650
2651 @_custom_test
2652 def check_compiler_overzealous_warn_extension_string_literal_operator_template(self,context):
2653 '''
2654 String literal operator templates are a GNU extension. GCC accepts them
2655 without complaint in mode `-std=gnu++14` (or later). Clang warns that
2656 the template is a GNU extension, even when given `-std=gnu++14`, which
2657 requests C++14 with GNU extensions. Since warnings are normally treated
2658 as errors, this breaks the build. If the warning is suppressed, Clang
2659 can compile the file correctly.
2660
2661 Test for whether the compiler will accept a string literal operator
2662 template with the default options and, if not, add the clang option to
2663 suppress the warning.
2664 '''
2665 if not self.Compile(context, text='''
2666 template <typename T, T... v>
2667 struct literal_as_type {};
2668
2669 template <typename T, T... v>
2670 constexpr literal_as_type<T, v...> operator""_literal_as_type();
2671 ''', main='''
2672 auto b = decltype("a"_literal_as_type){};
2673 (void)b;
2674 ''', msg='whether compiler accepts string literal operator templates'):
2675 self.successful_flags['CXXFLAGS'].append('-Wno-gnu-string-literal-operator-template')
2676
2677 @_custom_test
2678 def check_compiler_overzealous_braced_scalar_init(self,context,_text='''
2679 /* clang-16 issues a spurious -Wbraced-scalar-init warning if the result
2680 * is returned anonymously.
2681
2682 ```
2683 error: braces around scalar initializer [-Werror,-Wbraced-scalar-init]
2684 ```
2685
2686 * Removing the braces allows an implicit narrowing of the result, which would
2687 * be a trap for a future maintenance programmer.
2688 *
2689 * gcc accepts the anonymous brace-initialized result.
2690 */
2691 unsigned f(unsigned i);
2692 unsigned f(unsigned i)
2693 {
2694 return {i + 1};
2695 }
2696
2697 unsigned g(unsigned i);
2698 unsigned g(unsigned i)
2699 {
2700 ++i;
2701 return {i};
2702 }
2703 ''',_main='''
2704 f({5});
2705 g({6});
2706 ''',successflags={'CXXFLAGS' : ['-Wno-braced-scalar-init']}):
2707 if self.Compile(context, text=_text, main=_main, msg='whether compiler accepts braced variables as function arguments and return values'):
2708 return
2709 if self.Compile(context, text=_text, main=_main, msg='whether compiler accepts -Wno-braced-scalar-init', successflags=successflags):
2710 return
2711 raise SCons.Errors.StopError("C++ compiler rejects braced scalar initialization, even with `-Wno-braced-scalar-init`.")
2712
2713 __preferred_compiler_options = (
2714 # Support for option '-fstrict-flex-arrays':
2715 # <=gcc-12: no
2716 # >=gcc-13: yes
2717 # <=clang-16: no
2718 # >=clang-17: untested
2719 '-fstrict-flex-arrays',
2720 '-fvisibility=hidden',
2721 '-Wduplicated-branches',
2722 '-Wduplicated-cond',
2723 '-Wstrict-flex-arrays',
2724 '-Wsuggest-attribute=noreturn',
2725 '-Wsuggest-final-types',
2726 '-Wsuggest-override',
2727 '-Wlogical-op',
2728 '-Wold-style-cast',
2729 '-Wredundant-decls',
2730 )
2731 __preferred_win32_linker_options = (
2732 '-Wl,--large-address-aware',
2733 '-Wl,--dynamicbase',
2734 '-Wl,--nxcompat',
2735 )
2736 # No build directives can modify the process environment, so
2737 # modifying this at class scope is safe. Either every build will
2738 # have $SOURCE_DATE_EPOCH set or every build will have it clear.
2739 if os.getenv('SOURCE_DATE_EPOCH') is None:
2740 __preferred_win32_linker_options += ('-Wl,--insert-timestamp',)
2741 def __mangle_compiler_option_name(opt):
2742 return f'check_compiler_option{opt.replace("-", "_").replace("=", "_")}'
2743 def __mangle_linker_option_name(opt):
2744 return f'check_linker_option{opt.replace("-", "_").replace(",", "_")}'
2745 @_custom_test
2746 def check_preferred_compiler_options(self,context,
2747 ccopts=list(__preferred_compiler_options),
2748 ldopts=(),
2749 _text='''
2750 /* clang on OS X incorrectly diagnoses mistakes in Apple system headers
2751 * even when -Wsystem-headers is not specified. Include one known buggy
2752 * header here, so that the compilation will fail and the compiler will be
2753 * marked as not supporting -Wold-style-cast.
2754 */
2755 #if defined(__APPLE__) && defined(__MACH__)
2756 #include <ApplicationServices/ApplicationServices.h>
2757 #endif
2758
2759 #include <SDL.h>
2760 ''',
2761 _mangle_compiler_option_name=__mangle_compiler_option_name,
2762 _mangle_linker_option_name=__mangle_linker_option_name
2763 ):
2764 if self.user_settings.host_platform == 'win32':
2765 ldopts = self.__preferred_win32_linker_options
2766 Compile = self.Compile
2767 Link = self.Link
2768 f, desc = (Link, 'linker') if ldopts else (Compile, 'compiler')
2769 if f(context, text=_text, main='''
2770 ''', msg=f'whether {desc} accepts preferred options', successflags={'CXXFLAGS' : ccopts, 'LINKFLAGS' : ldopts}, calling_function=f'preferred_{desc}_options'):
2771 # Everything is supported. Skip individual tests.
2772 return
2773 # Compiler+linker together failed. Check if compiler alone will work.
2774 if f is Compile or not Compile(context, text=_text, main='', msg='whether compiler accepts preferred options', successflags={'CXXFLAGS' : ccopts}):
2775 # Compiler alone failed.
2776 # Run down the individual compiler options to find any that work.
2777 for opt in ccopts:
2778 Compile(context, text=_text, main='', msg=f'whether compiler accepts option {opt}', successflags={'CXXFLAGS' : (opt,)}, calling_function=_mangle_compiler_option_name(opt)[6:])
2779 # Run down the individual linker options to find any that work.
2780 for opt in ldopts:
2781 Link(context, text=_text, main='', msg=f'whether linker accepts option {opt}', successflags={'LINKFLAGS' : (opt,)}, calling_function=_mangle_linker_option_name(opt)[6:])
2782 @classmethod
2783 def register_preferred_compiler_options(cls,
2784 ccopts = ('-Wextra',) + __preferred_compiler_options,
2785 # Always register target-specific tests on the class. Individual
2786 # targets will decide whether to run the tests.
2787 ldopts = __preferred_win32_linker_options,
2788 RecordedTest = Collector.RecordedTest,
2789 record = implicit_tests.append,
2790 _mangle_compiler_option_name=__mangle_compiler_option_name,
2791 _mangle_linker_option_name=__mangle_linker_option_name
2792 ):
2793 del cls.register_preferred_compiler_options
2794 record(RecordedTest('check_preferred_linker_options', 'assume linker accepts preferred options'))
2795 mangle = _mangle_compiler_option_name
2796 for opt in ccopts:
2797 record(RecordedTest(mangle(opt), f'assume compiler accepts {opt}'))
2798 mangle = _mangle_linker_option_name
2799 for opt in ldopts:
2800 record(RecordedTest(mangle(opt), f'assume linker accepts {opt}'))
2801 assert cls.custom_tests[0].name == cls.check_cxx_works.__name__, cls.custom_tests[0].name
2802 assert cls.custom_tests[-1].name == cls._cleanup_configure_test_state.__name__, cls.custom_tests[-1].name
2803
2804 @_implicit_test
2805 def check_boost_test(self,context):
2806 self._check_system_library(context, header=('boost/test/unit_test.hpp',), pretext='''
2807 #define BOOST_TEST_DYN_LINK
2808 #define BOOST_TEST_MODULE Rebirth
2809 ''', main=None, lib='Boost.Test', text='''
2810 BOOST_AUTO_TEST_CASE(f)
2811 {
2812 BOOST_TEST(true);
2813 }
2814 ''', testflags={'LIBS' : ['boost_unit_test_framework']})
2815
2816 @_custom_test
2817 def _check_boost_test_required(self,context):
2818 register_runtime_test_link_targets = self.user_settings.register_runtime_test_link_targets
2819 context.Display(f'{self.msgprefix}: checking whether to build runtime tests...')
2820 context.Result(register_runtime_test_link_targets)
2821 if register_runtime_test_link_targets:
2822 self.check_boost_test(context)
2823
2824 # dylibbundler is used to embed libraries into macOS app bundles,
2825 # however it's only meaningful for macOS builds, and, for those,
2826 # only required when frameworks are not used for the build. Builds
2827 # should not fail on other operating system targets if it's absent.
2828 @GuardedCollector(_guarded_test_darwin, lambda user_settings: user_settings.macos_bundle_libs and not user_settings.macos_add_frameworks)
2829 def _check_dylibbundler(self, context, _common_error_text='; dylibbundler is required for compilation for a macOS target when not using frameworks and bundling libraries. Set macos_bundle_libs=False or macos_add_frameworks=True, or install dylibbundler.'):
2830 if sys.platform != 'darwin':
2831 raise SCons.Errors.StopError(f'dylibbundler can only be run on macOS build hosts')
2832 context.Display(f'{self.msgprefix}: checking whether dylibbundler is installed and accepts -h...')
2833 try:
2834 p = StaticSubprocess.pcall(('dylibbundler', '-h'), stderr=subprocess.PIPE)
2835 except FileNotFoundError as e:
2836 context.Result(f'no; {e}')
2837 raise SCons.Errors.StopError(f'dylibbundler not found{_common_error_text}')
2838 expected = b'dylibbundler is a utility'
2839 first_output_line = p.out.splitlines()
2840 if first_output_line:
2841 first_output_line = first_output_line[0]
2842 # This test allows the expected text to appear anywhere in the
2843 # output. Only the first line of output will be shown to SCons'
2844 # stdout. The full output will be written to the SConf log.
2845 if p.returncode:
2846 reason = f'successful exit, but return code was {p.returncode}'
2847 elif expected not in p.out:
2848 reason = f'output to contain {expected.decode()!r}, but first line of output was: {first_output_line!r}'
2849 else:
2850 context.Result(f'yes; {first_output_line}')
2851 return
2852 context.Result(f'no; expected {reason}')
2853 context.Log(f'''scons: dylibbundler return code: {p.returncode!r}
2854 scons: dylibbundler stdout: {p.out!r}
2855 scons: dylibbundler stderr: {p.err!r}
2856 ''')
2857 raise SCons.Errors.StopError('`dylibbundler -h` failed to return expected output; dylibbundler is required for compilation for a macOS target when not using frameworks. Set macos_bundle_libs=False or macos_add_frameworks=False (and handle the libraries manually), or install dylibbundler.')
2858
2859 # This must be the last custom test. It does not test the environment,
2860 # but is responsible for reversing test-environment-specific changes made
2861 # by check_cxx_works.
2862 @_custom_test
2863 def _cleanup_configure_test_state(self,context):
2864 sconf = context.sconf
2865 sconf.config_h_text = self.__commented_tool_versions + sconf.config_h_text
2866 context.env['CXXCOM'] = self.__cxx_com_prefix
2867 context.did_show_result = True
2868 ToolchainInformation.show_partial_environ(context.env, self.user_settings, context.Display, self.msgprefix)
2869
2870 ConfigureTests.register_preferred_compiler_options()
2871
2872 @dataclass(eq=False, slots=True)
2873 class LazyObjectConstructor:
2874 class LazyObjectState:
2875 def __init__(self, sources: collections.abc.Sequence[str], transform_env=None, StaticObject_hook=None, transform_target=None):
2876 # `sources` must be non-empty, since it would have no use if
2877 # it was empty.
2878 #
2879 # Every element in `sources` must be a string. Verify this
2880 # with an assertion that directly checks that the sequence
2881 # is not empty and indirectly, by way of attribute lookup,
2882 # checks that the elements are string-like.
2883 assert([s.encode for s in sources]), "sources must be a non-empty list of strings"
2884 self.sources = sources
2885 self.transform_env = transform_env
2886 self.StaticObject_hook = StaticObject_hook
2887 # If transform_target is not used, let references to
2888 # `self.transform_target` fall through to
2889 # `cls.transform_target`.
2890 if transform_target:
2891 self.transform_target = transform_target
2892
2893 @staticmethod
2894 def transform_target(_, name, _splitext=os.path.splitext):
2895 return _splitext(name)[0]
2896
2897 def __lazy_objects(self, source: collections.abc.Sequence[LazyObjectState],
2898 cache={}
2899 ) -> tuple['SCons.Environment.StaticObject']:
2900 env = self.env
2901 # Use id because name needs to be hashable and have a 1-to-1
2902 # mapping to source.
2903 name = (id(env), id(source))
2904 value = cache.get(name)
2905 if value is None:
2906 prepare_target_name = '{}{}'.format
2907 StaticObject = env.StaticObject
2908 OBJSUFFIX = env['OBJSUFFIX']
2909 builddir = self.builddir
2910 value = []
2911 append = value.append
2912 for s in source:
2913 transform_target = s.transform_target
2914 transform_env = s.transform_env
2915 StaticObject_hook = s.StaticObject_hook
2916 StaticObject_kwargs = {} if transform_env is None else transform_env(self, env)
2917 for srcname in s.sources:
2918 target = builddir.File(prepare_target_name(transform_target(self, srcname), OBJSUFFIX))
2919 s = StaticObject(target=target, source=srcname,
2920 **StaticObject_kwargs
2921 )
2922 append(s)
2923 if StaticObject_hook is not None:
2924 StaticObject_hook(self, env, srcname, target, s)
2925 # Convert to a tuple so that attempting to modify a cached
2926 # result raises an error.
2927 cache[name] = value = tuple(value)
2928 return value
2929
2930 def create_lazy_object_states_getter(states: collections.abc.Sequence[LazyObjectState], __lazy_objects=__lazy_objects):
2931 def get_objects(self):
2932 return __lazy_objects(self, states)
2933 return get_objects
2934
2935 @staticmethod
2936 def create_lazy_object_getter(sources: collections.abc.Sequence[str], __LazyObjectState=LazyObjectState, __create_lazy_object_states_getter=create_lazy_object_states_getter):
2937 return __create_lazy_object_states_getter((__LazyObjectState(sources=sources),))
2938
2939 create_lazy_object_states_getter = staticmethod(create_lazy_object_states_getter)
2940
2941 class FilterHelpText:
2942 _sconf_align = None
2943 def __init__(self):
2944 self.visible_arguments = []
2945 def FormatVariableHelpText(self, env, opt, help, default, actual, aliases):
2946 if not opt in self.visible_arguments:
2947 return ''
2948 if not self._sconf_align:
2949 self._sconf_align = len(max((s for s in self.visible_arguments if s[:6] == 'sconf_'), key=len))
2950 l = []
2951 if default is not None:
2952 if isinstance(default, str) and not default.isalnum():
2953 default = f'"{default}"'
2954 l.append(f'default: {default}')
2955 actual = getattr(self, opt, None)
2956 if actual is not None:
2957 if isinstance(actual, str) and not actual.isalnum():
2958 actual = f'"{actual}"'
2959 l.append(f'current: {actual}')
2960 return f' {opt:{self._sconf_align if opt[:6] == "sconf_" else 15}} {help}{f""" [{"; ".join(l)}]""" if l else ""}\n'
2961
2962 class PCHManager:
2963 @dataclass(eq=False)
2964 class ScannedFile:
2965 candidates: defaultdict(set)
2966
2967 syspch_cpp_filename: str | None = None
2968 ownpch_cpp_filename: str | None = None
2969 syspch_object_node: typing.Union['StaticObject', None] = None
2970 ownpch_object_node: typing.Union['StaticObject', None] = None
2971 required_pch_object_node: typing.Union['StaticObject', None] = None
2972
2973 # Compile on first use, so that non-PCH builds skip the compile
2974 _re_preproc_match: collections.abc.Callable[[bytes], 're.Match'] = None
2975 _re_include_match: collections.abc.Callable[[bytes], 're.Match'] = None
2976 _re_singleline_comments_sub: collections.abc.Callable[[bytes, bytes], bytes] = None
2977 # Source files are tracked at class scope because all builds share
2978 # the same source tree.
2979 _cls_scanned_files: dict[str, ScannedFile] = None
2980
2981 _instance_scanned_files: dict['fs.File', ScannedFile]
2982 pch_CXXFLAGS: list[str]
2983
2984 # Import required modules when the first PCHManager is created.
2985 @classmethod
2986 def __initialize_cls_static_variables(cls):
2987 from re import compile as c
2988 # Match C preprocessor directives that start with i or e,
2989 # capture any arguments, and allow no arguments. This accepts:
2990 # - #if
2991 # - #ifdef
2992 # - #ifndef
2993 # - #else
2994 # - #endif
2995 # - #include
2996 # - #error
2997 cls._re_preproc_match = c(br'#\s*([ie]\w+)(?:\s+(.*))?').match
2998 # Capture the argument in a #include statement, including the
2999 # angle brackets or quotes.
3000 #
3001 # Rebirth currently has no computed includes, so ignore computed
3002 # includes.
3003 cls._re_include_match = c(br'(<[^>]+>|"[^"]+")').match
3004 # Strip a single-line C++ style comment ("// Text") and any
3005 # preceding whitespace. The C preprocessor will discard these
3006 # when compiling the header. Discarding them from the
3007 # environment Value will prevent rebuilding pch.cpp when the
3008 # only change is in such a comment.
3009 cls._re_singleline_comments_sub = c(br'\s*//.*').sub
3010 # dict with key=filename with path, value=ScannedFile
3011 cls._cls_scanned_files = {}
3012 from tempfile import mkstemp
3013 cls._tempfile_mkstemp = staticmethod(mkstemp)
3014
3015 def __init__(self,program,configure_pch_flags,common_pch_manager):
3016 if self._re_preproc_match is None:
3017 self.__initialize_cls_static_variables()
3018 assert self._re_preproc_match is not None
3019 self.user_settings = user_settings = program.user_settings
3020 assert user_settings.syspch or user_settings.pch or not configure_pch_flags
3021 self.env = env = program.env
3022 # dict with key=fs.File, value=ScannedFile
3023 self._instance_scanned_files = {}
3024 self._common_pch_manager = common_pch_manager
3025 syspch_cpp_filename = ownpch_cpp_filename = None
3026 syspch_object_node = None
3027 CXXFLAGS = env['CXXFLAGS'] + (configure_pch_flags['CXXFLAGS'] if configure_pch_flags else [])
3028 File = env.File
3029 builddir = program.builddir
3030 pch_subdir_node = builddir.Dir(program.srcdir)
3031 if user_settings.syspch:
3032 self.syspch_cpp_node = pch_subdir_node.File('syspch.cpp')
3033 self.syspch_cpp_filename = syspch_cpp_filename = str(self.syspch_cpp_node)
3034 self.required_pch_object_node = self.syspch_object_node = syspch_object_node = env.StaticObject(target=f'{syspch_cpp_filename}.gch', source=self.syspch_cpp_node, CXXCOM=env._dxx_cxxcom_no_ccache_prefix, CXXFLAGS=CXXFLAGS)
3035 if user_settings.pch:
3036 self.ownpch_cpp_node = pch_subdir_node.File('ownpch.cpp')
3037 self.ownpch_cpp_filename = ownpch_cpp_filename = str(self.ownpch_cpp_node)
3038 if syspch_object_node:
3039 CXXFLAGS += ['-include', syspch_cpp_node, '-Winvalid-pch']
3040 self.required_pch_object_node = self.ownpch_object_node = ownpch_object_node = env.StaticObject(target=f'{ownpch_cpp_filename}.gch', source=self.ownpch_cpp_node, CXXCOM=env._dxx_cxxcom_no_ccache_prefix, CXXFLAGS=CXXFLAGS)
3041 env.Depends(ownpch_object_node, builddir.File('dxxsconf.h'))
3042 if syspch_object_node:
3043 env.Depends(ownpch_object_node, syspch_object_node)
3044 if not configure_pch_flags:
3045 return
3046 self.pch_CXXFLAGS = ['-include', self.ownpch_cpp_node or syspch_cpp_node, '-Winvalid-pch']
3047 # If assume unchanged and the file exists, set __files_included
3048 # to a dummy value. This bypasses scanning source files and
3049 # guarantees that the text of pch.cpp is not changed. SCons
3050 # will still recompile pch.cpp into a new .gch file if pch.cpp
3051 # includes files that SCons recognizes as changed.
3052 if user_settings.pch_cpp_assume_unchanged and \
3053 (not syspch_cpp_filename or os.path.exists(syspch_cpp_filename)) and \
3054 (not ownpch_cpp_filename or os.path.exists(ownpch_cpp_filename)):
3055 self.__files_included = True
3056 else:
3057 # collections.defaultdict with key from ScannedFile.candidates,
3058 # value is a collections.Counter with key=tuple of preprocessor
3059 # guards, value=count of times this header was included under
3060 # that set of guards.
3061 self.__files_included = defaultdict(collections_counter)
3062 self.__env_Program = env.Program
3063 self.__env_StaticObject = env.StaticObject
3064 env.Program = self.Program
3065 env.StaticObject = self.StaticObject
3066
3067 def record_file(self,env,source_file):
3068 # Every scanned file goes into self._cls_scanned_files to
3069 # prevent duplicate scanning from multiple targets.
3070 f = self._cls_scanned_files.get(source_file, None)
3071 if f is None:
3072 self._cls_scanned_files[source_file] = f = self.scan_file(env, source_file)
3073 self._instance_scanned_files[source_file] = f
3074 return f
3075
3076 # Scan a file for preprocessor directives related to conditional
3077 # compilation and file inclusion.
3078 #
3079 # The #include directives found are eventually written to pch.cpp
3080 # with their original preprocessor guards in place. Since the
3081 # preprocessor guards are kept and the C preprocessor will evaluate
3082 # them when compiling the header, this scanner does not attempt to
3083 # track which branches are true and which are false.
3084 #
3085 # This scanner makes no attempt to normalize guard conditions. It
3086 # considers each of these examples to be distinct guards, even
3087 # though a full preprocessor will produce the same result for each:
3088 #
3089 # #if 1
3090 # #if 2
3091 # #if 3 < 5
3092 #
3093 # or:
3094 #
3095 # #ifdef A
3096 # #if defined(A)
3097 # #if (defined(A))
3098 # #if !!defined(A)
3099 #
3100 # or:
3101 #
3102 # #ifndef A
3103 # #else
3104 # #endif
3105 #
3106 # #ifdef A
3107 # #endif
3108 #
3109 # Include directives are followed only if the calling file will not
3110 # be part of the output pch.cpp. When the calling file will be in
3111 # pch.cpp, then the C preprocessor will include the called file, so
3112 # there is no need to scan it for other headers to include.
3113 #
3114 # This scanner completely ignores pragmas, #define, #undef, and
3115 # computed includes.
3116 @classmethod
3117 def scan_file(cls,env,source_filenode):
3118 match_preproc_directive = cls._re_preproc_match
3119 match_include_directive = cls._re_include_match
3120 preceding_line = None
3121 lines_since_preprocessor = None
3122 # defaultdict with key=name of header to include, value=set of
3123 # preprocessor guards under which an include was seen. Set is
3124 # used because duplicate inclusions from a single source file
3125 # should not adjust the usage counter.
3126 candidates = defaultdict(set)
3127 # List of currently active preprocessor guards
3128 guard = []
3129 header_search_path = None
3130 os_path_join = os.path.join
3131 os_path_exists = os.path.exists
3132 for line in map(bytes.strip, source_filenode.get_contents().splitlines()):
3133 if preceding_line is not None:
3134 # Basic support for line continuation.
3135 line = b'%s %s' % (preceding_line[:-1], line)
3136 preceding_line = None
3137 elif not line.startswith(b'#'):
3138 # Allow unlimited non-preprocessor lines before the
3139 # first preprocessor line. Once one preprocessor line
3140 # is found, track how many lines since the most recent
3141 # preprocessor line was seen. If too many
3142 # non-preprocessor lines appear in a row, assume the
3143 # scanner is now down in source text and move to the
3144 # next file.
3145 if lines_since_preprocessor is not None:
3146 lines_since_preprocessor += 1
3147 if lines_since_preprocessor > 50:
3148 break
3149 continue
3150 lines_since_preprocessor = 0
3151 # Joined lines are rare. Ignore complicated quoting.
3152 if line.endswith(b'\\'):
3153 preceding_line = line
3154 continue
3155 m = match_preproc_directive(line)
3156 if not m:
3157 # Not a preprocessor directive or not a directive that
3158 # this scanner handles.
3159 continue
3160 directive = m.group(1)
3161 if directive == b'include':
3162 m = match_include_directive(m.group(2))
3163 if not m:
3164 # This directive is probably a computed include.
3165 continue
3166 name = m.group(1)
3167 bare_name = name[1:-1]
3168 if name.startswith(b'"'):
3169 # Canonicalize paths to non-system headers
3170 if name == b'"dxxsconf.h"':
3171 # Ignore generated header here. PCH generation
3172 # will insert it in the right order.
3173 continue
3174 if not name.endswith(b'.h"'):
3175 # Exclude non-header files from PCH.
3176 #
3177 # Starting in gcc-7, static functions defined in
3178 # valptridx.tcc generate -Wunused-function
3179 # warnings if the including file does not
3180 # instantiate any templates that use the static
3181 # function.
3182 continue
3183 if header_search_path is None:
3184 header_search_path = [
3185 d.encode() for d in ([os.path.dirname(str(source_filenode))] + env['CPPPATH'])
3186 # Filter out SDL paths
3187 if not d.startswith('/')
3188 ]
3189 name = None
3190 for d in header_search_path:
3191 effective_name = os_path_join(d, bare_name)
3192 if os_path_exists(effective_name):
3193 name = effective_name
3194 break
3195 else:
3196 # name is None if:
3197 # - A system header was included using quotes.
3198 #
3199 # - A game-specific header was included in a
3200 # shared file. A game-specific preprocessor
3201 # guard will prevent the preprocessor from
3202 # including the file, but the PCH scan logic
3203 # looks inside branches that the C preprocessor
3204 # will evaluate as false.
3205 continue
3206 name = env.File(name.decode())
3207 candidates[name].add(tuple(guard))
3208 elif directive == b'endif':
3209 while guard:
3210 g = guard.pop()
3211 if g == b'#else':
3212 # guard should always be True here, but test to
3213 # avoid ugly errors if scanning an ill-formed
3214 # source file.
3215 if guard:
3216 guard.pop()
3217 break
3218 if not g.startswith(b'#elif '):
3219 break
3220 elif directive == b'else':
3221 # #else is handled separately because it has no
3222 # arguments
3223 guard.append(b'#%s' % (directive))
3224 elif directive in (
3225 b'elif',
3226 b'if',
3227 b'ifdef',
3228 b'ifndef',
3229 ):
3230 guard.append(b'#%s %s' % (directive, m.group(2)))
3231 elif directive not in (b'error',):
3232 raise SCons.Errors.StopError(f'Scanning {source_filenode!s} found unhandled C preprocessor directive {directive!r}')
3233 return cls.ScannedFile(candidates)
3234
3235 def _compute_pch_text(self):
3236 self._compute_indirect_includes()
3237 own_header_inclusion_threshold = self.user_settings.pch
3238 sys_header_inclusion_threshold = self.user_settings.syspch
3239 configured_threshold = 0x7fffffff if self.user_settings.pch_cpp_exact_counts else None
3240 # defaultdict with key=name of tuple of active preprocessor
3241 # guards, value=tuple of (included file, count of times file was
3242 # seen with this set of guards, count of times file would be
3243 # included with this set of guards defined).
3244 syscpp_includes = defaultdict(list)
3245 owncpp_includes = defaultdict(list) if own_header_inclusion_threshold else None
3246 for included_file, usage_dict in self.__files_included.items():
3247 if isinstance(included_file, (bytes, str)):
3248 # System header
3249 cpp_includes = syscpp_includes
3250 name = (included_file.encode() if isinstance(included_file, str) else included_file)
3251 threshold = own_header_inclusion_threshold if sys_header_inclusion_threshold is None else sys_header_inclusion_threshold
3252 else:
3253 # Own header
3254 cpp_includes = owncpp_includes
3255 name = b'"%s"' % (str(included_file).encode())
3256 threshold = own_header_inclusion_threshold
3257 if not threshold:
3258 continue
3259 count_threshold = configured_threshold or threshold
3260 g = usage_dict.get((), 0)
3261 # As a special case, if this header is included
3262 # without any preprocessor guards, ignore all the
3263 # conditional includes.
3264 guards = \
3265 [((), g)] if (g >= threshold) else \
3266 sorted(usage_dict.items(), reverse=True)
3267 while guards:
3268 preprocessor_guard_directives, local_count_seen = guards.pop()
3269 total_count_seen = local_count_seen
3270 if total_count_seen < count_threshold:
3271 # If not eligible on its own, add in the count from
3272 # preprocessor guards that are always true when this
3273 # set of guards is true. Since the scanner does not
3274 # normalize preprocessor directives, this is a
3275 # conservative count of always-true guards.
3276 g = preprocessor_guard_directives
3277 while g and total_count_seen < count_threshold:
3278 g = g[:-1]
3279 total_count_seen += usage_dict.get(g, 0)
3280 if total_count_seen < threshold:
3281 # If still not eligible, skip.
3282 continue
3283 cpp_includes[preprocessor_guard_directives].append((name, local_count_seen, total_count_seen))
3284
3285 if syscpp_includes:
3286 self.__generated_syspch_lines = self._compute_pch_generated_lines(syscpp_includes)
3287 if owncpp_includes:
3288 self.__generated_ownpch_lines = self._compute_pch_generated_lines(owncpp_includes)
3289
3290 def _compute_pch_generated_lines(self,cpp_includes):
3291 generated_pch_lines = []
3292 # Append guarded #include directives for files which passed the
3293 # usage threshold above. This loop could try to combine related
3294 # preprocessor guards, but:
3295 # - The C preprocessor handles the noncombined guards correctly.
3296 # - As a native program optimized for text processing, the C
3297 # preprocessor almost certainly handles guard checking faster
3298 # than this script could handle guard merging.
3299 # - This loop runs whenever pch.cpp might be regenerated, even
3300 # if the result eventually shows that pch.cpp has not changed.
3301 # The C preprocessor will only run over the file when it is
3302 # actually changed and is processed to build a new .gch file.
3303 for preprocessor_guard_directives, included_file_tuples in sorted(cpp_includes.items()):
3304 generated_pch_lines.append(b'')
3305 generated_pch_lines.extend(preprocessor_guard_directives)
3306 # local_count_seen is the direct usage count for this
3307 # combination of preprocessor_guard_directives.
3308 #
3309 # total_count_seen is the sum of local_count_seen and all
3310 # guards that are a superset of this
3311 # preprocessor_guard_directives. The total stops counting
3312 # when it reaches threshold, so it may undercount actual
3313 # usage.
3314 for (name, local_count_seen, total_count_seen) in sorted(included_file_tuples):
3315 assert(isinstance(name, bytes)), repr(name)
3316 generated_pch_lines.append(b'#include %s\t// %u %u' % (name, local_count_seen, total_count_seen))
3317 # d[2] == l if d is '#else' or d is '#elif'
3318 # Only generate #endif when d is a '#if*' directive, since
3319 # '#else/#elif' do not introduce a new scope.
3320 generated_pch_lines.extend(b'#endif' for d in preprocessor_guard_directives if d[2:3] != b'l')
3321 return generated_pch_lines
3322
3323 def _compute_indirect_includes(self):
3324 own_header_inclusion_threshold = None if self.user_settings.pch_cpp_exact_counts else self.user_settings.pch
3325 # Count how many times each header is used for each preprocessor
3326 # guard combination. After the outer loop finishes,
3327 # files_included is a dictionary that maps the name of the
3328 # include file to a collections.counter instance. The mapped
3329 # counter maps a preprocessor guard to a count of how many times
3330 # it was used.
3331 #
3332 # Given:
3333 #
3334 # a.cpp
3335 # #include "a.h"
3336 # #ifdef A
3337 # #include "b.h"
3338 # #endif
3339 #
3340 # b.cpp
3341 # #include "b.h"
3342 #
3343 # files_included = {
3344 # 'a.h' : { () : 1 }
3345 # 'b.h' : {
3346 # ('#ifdef A',) : 1, # From a.cpp
3347 # () : 1, # From b.cpp
3348 # }
3349 # }
3350 files_included = self.__files_included
3351 for scanned_file in self._instance_scanned_files.values():
3352 for included_file, guards in scanned_file.candidates.items():
3353 i = files_included[included_file]
3354 for g in guards:
3355 i[g] += 1
3356 # If own_header_inclusion_threshold == 1, then every header
3357 # found will be listed in pch.cpp, so any indirect headers will
3358 # be included by the C preprocessor.
3359 if own_header_inclusion_threshold == 1:
3360 return
3361 # For each include file which is below the threshold, scan it
3362 # for includes which may end up above the threshold.
3363 File = self.env.File
3364 includes_to_check = sorted(files_included.iterkeys(), key=str)
3365 while includes_to_check:
3366 included_file = includes_to_check.pop()
3367 if isinstance(included_file, (bytes, str)):
3368 # System headers are str. Internal headers are
3369 # fs.File.
3370 continue
3371 guards = files_included[included_file]
3372 unconditional_use_count = guards.get((), 0)
3373 if unconditional_use_count >= own_header_inclusion_threshold and own_header_inclusion_threshold:
3374 # Header will be unconditionally included in the PCH.
3375 continue
3376 f = self.record_file(self.env, File(included_file))
3377 for nested_included_file, nested_guards in sorted(f.candidates.items(), key=str):
3378 if not isinstance(included_file, (bytes, str)) and not nested_included_file in files_included:
3379 # If the header is a system header, it will be
3380 # str. Skip system headers.
3381 #
3382 # Otherwise, if it has not been seen before,
3383 # append it to includes_to_check for recursive
3384 # scanning.
3385 includes_to_check.append(nested_included_file)
3386 i = files_included[nested_included_file]
3387 # If the nested header is included
3388 # unconditionally, skip the generator.
3389 for g in (nested_guards if unconditional_use_count else (a + b for a in guards for b in nested_guards)):
3390 i[g] += 1
3391
3392 @classmethod
3393 def write_pch_inclusion_file(cls,target,source,env):
3394 target = str(target[0])
3395 dn, bn = os.path.split(target)
3396 fd, path = cls._tempfile_mkstemp(suffix='', prefix=f'{bn}.', dir=dn, text=True)
3397 # source[0].get_contents() returns the comment-stripped form
3398 os.write(fd, source[0].__generated_pch_text)
3399 os.close(fd)
3400 os.rename(path, target)
3401
3402 def StaticObject(self,target,source,CXXFLAGS=None,*args,**kwargs):
3403 env = self.env
3404 source = env.File(source)
3405 o = self.__env_StaticObject(target=target, source=source, CXXFLAGS=self.pch_CXXFLAGS + (env['CXXFLAGS'] if CXXFLAGS is None else CXXFLAGS), *args, **kwargs)
3406 # Force an order dependency on the .gch file. It is never
3407 # referenced by the command line or the source files, so SCons
3408 # may not recognize it as an input.
3409 env.Requires(o, self.required_pch_object_node)
3410 if self.__files_included is not True:
3411 self.record_file(env, source)
3412 return o
3413
3414 def Program(self,*args,**kwargs):
3415 self._register_pch_commands()
3416 if self._common_pch_manager:
3417 self._common_pch_manager._register_pch_commands()
3418 return self.__env_Program(*args, **kwargs)
3419
3420 def _register_pch_commands(self):
3421 if self.__files_included:
3422 # Common code calls this function once for each game which
3423 # uses it. Only one call is necessary for proper operation.
3424 # Ignore all later calls.
3425 return
3426 self._compute_pch_text()
3427 syspch_lines = self.__generated_syspch_lines
3428 pch_begin_banner_template = b'''
3429 // BEGIN PCH GENERATED FILE
3430 // %r
3431 // Threshold=%u
3432
3433 // SConf generated header
3434 #include "dxxsconf.h"
3435 '''
3436 pch_end_banner = (b'''
3437 // END PCH GENERATED FILE
3438 ''',)
3439 if self.syspch_object_node:
3440 self._register_write_pch_inclusion(self.syspch_cpp_node,
3441 (
3442 (pch_begin_banner_template % (self.syspch_cpp_filename, self.user_settings.syspch),),
3443 syspch_lines,
3444 pch_end_banner,
3445 )
3446 )
3447 # ownpch.cpp will include syspch.cpp.gch from the command
3448 # line, so clear syspch_lines to avoid repeating system
3449 # includes in ownpch.cpp
3450 syspch_lines = ()
3451 if self.ownpch_object_node:
3452 self._register_write_pch_inclusion(self.ownpch_cpp_node,
3453 (
3454 (pch_begin_banner_template % (self.ownpch_cpp_filename, self.user_settings.pch),),
3455 (b'// System headers' if syspch_lines else b'',),
3456 syspch_lines,
3457 (b'''
3458 // Own headers
3459 ''',),
3460 self.__generated_ownpch_lines,
3461 pch_end_banner,
3462 )
3463 )
3464
3465 def _register_write_pch_inclusion(self,node,lineseq):
3466 # The contents of pch.cpp are taken from the iterables in
3467 # lineseq. Set the contents as an input Value instead of
3468 # listing file nodes, so that pch.cpp is not rebuilt if a change
3469 # to a source file does not change what headers are listed in
3470 # pch.cpp.
3471 #
3472 # Strip C++ single line comments so that changes in comments are
3473 # ignored when deciding whether pch.cpp needs to be rebuilt.
3474 env = self.env
3475 text = b'\n'.join(itertools.chain.from_iterable(lineseq))
3476 v = env.Value(self._re_singleline_comments_sub(b'', text))
3477 v.__generated_pch_text = text
3478 # Use env.Command instead of env.Textfile or env.Substfile since
3479 # the latter use their input both for freshness and as a data
3480 # source. This Command writes the commented form of the Value
3481 # to the file, but uses a comment-stripped form for SCons
3482 # freshness checking.
3483 env.Command(node, v, self.write_pch_inclusion_file)
3484
3485 class DXXCommon(LazyObjectConstructor):
3486 # version number
3487 VERSION_MAJOR: typing.Final[int] = 0
3488 VERSION_MINOR: typing.Final[int] = 61
3489 VERSION_MICRO: typing.Final[int] = 0
3490 DXX_VERSION_SEQ: typing.Final[str] = ','.join([str(VERSION_MAJOR), str(VERSION_MINOR), str(VERSION_MICRO)])
3491 pch_manager = None
3492 # dict compilation_database_dict_fn_to_entries:
3493 # key: str: name of JSON file to which the data will be written
3494 # value: tuple: (SCons.Environment, list_of_entries_to_write)
3495 # The first environment to use the named JSON file will be stored as
3496 # the environment in the tuple, and later used to provide
3497 # env.Textfile for all the entries written to the file. When other
3498 # environments write to the same JSON file, they will append their
3499 # entries to the original list, and reuse the initial environment.
3500 # Since the build system does not customize env.Textfile, any
3501 # instance of it should be equally good. This design permits
3502 # writing all the records for a build into a single file, even
3503 # though the build will use multiple SCons.Environment instances to
3504 # compile its source files.
3505 compilation_database_dict_fn_to_entries: dict[str, tuple[SCons.Environment, list]] = {}
3506
3507 @dataclass(eq=False)
3508 class RuntimeTest(LazyObjectConstructor):
3509 target: str
3510 source: collections.abc.Sequence[str]
3511 nodefaultlibs: bool = True
3512 def __init__(self, target: str, source: collections.abc.Sequence[str]):
3513 self.target = target
3514 self.source = LazyObjectConstructor.create_lazy_object_getter(source)
3515
3516 @cached_property
3517 def program_message_prefix(self):
3518 return f'{self.PROGRAM_NAME}.{self.program_instance}'
3519
3520 @cached_property
3521 def builddir(self):
3522 return self.env.Dir(self.user_settings.builddir)
3523
3524 # Settings which affect how the files are compiled
3525 class UserBuildSettings:
3526 class IntVariable:
3527 def __new__(cls,key,help,default):
3528 return (key, help, default, cls._validator, int)
3529 @staticmethod
3530 def _validator(key, value, env):
3531 try:
3532 int(value)
3533 return True
3534 except ValueError:
3535 raise SCons.Errors.UserError(f'Invalid value for integer-only option {key}: {value}.')
3536 class UIntVariable(IntVariable):
3537 @staticmethod
3538 def _validator(key, value, env):
3539 try:
3540 if int(value) < 0:
3541 raise ValueError
3542 return True
3543 except ValueError:
3544 raise SCons.Errors.UserError(f'Invalid value for unsigned-integer-only option {key}: {value}.')
3545 # Paths for the Videocore libs/includes on the Raspberry Pi
3546 RPI_DEFAULT_VC_PATH: str = '/opt/vc'
3547 default_OGLES_LIB: str = 'GLES_CM'
3548 default_EGL_LIB: str = 'EGL'
3549 _default_prefix: str = '/usr'
3550 __stdout_is_not_a_tty: bool | None = None
3551 __has_git_dir: bool | None = None
3552 def default_poison(self):
3553 return 'overwrite' if self.debug else 'none'
3554 def default_builddir(self):
3555 builddir_prefix = self.builddir_prefix
3556 builddir_suffix = self.builddir_suffix
3557 if builddir_prefix is not None or builddir_suffix is not None:
3558 fields = [
3559 self.host_platform,
3560 os.path.basename(self.CXX) if self.CXX else None,
3561 ]
3562 compiler_flags = [(getattr(self, attr) or '').strip() for attr in ('CPPFLAGS', 'CXXFLAGS')]
3563 compiler_flags.append(str(not not self.sharepath))
3564 compiler_flags = '\n'.join(compiler_flags)
3565 if compiler_flags:
3566 # Mix in CRC of compiler flags to get reasonable uniqueness
3567 # when flags are changed. This allows multiple builds with
3568 # varying flags to be built without overwriting each
3569 # other's outputs. A full hash is unnecessary here, since
3570 # an accidental collision is unlikely, and the only
3571 # negative consequence of such a collision is that the
3572 # build will overwrite objects that would need to be built
3573 # again later when the flags are switched back.
3574 fields.append(f'{(binascii.crc32(compiler_flags.encode())):08x}')
3575 if self.pch:
3576 fields.append(f'p{self.pch}')
3577 elif self.syspch:
3578 fields.append(f'sp{self.syspch}')
3579 fields.append(''.join(a[1] if getattr(self, a[0]) else (a[2] if len(a) > 2 else '')
3580 for a in (
3581 ('debug', 'dbg'),
3582 ('lto', 'lto'),
3583 ('editor', 'ed'),
3584 ('opengl', 'ogl', 'sdl'),
3585 ('opengles', 'es'),
3586 ('raspberrypi', 'rpi'),
3587 )))
3588 default_builddir = (builddir_prefix or '') + '-'.join([f for f in fields if f])
3589 if builddir_suffix is not None:
3590 default_builddir += builddir_suffix
3591 else:
3592 default_builddir = 'build/'
3593 return default_builddir
3594 def default_memdebug(self):
3595 return self.debug
3596 # automatic setup for raspberrypi
3597 def default_opengles(self):
3598 if self.raspberrypi in ('yes',):
3599 return True
3600 return False
3601 def default_sdl2(self):
3602 if self.raspberrypi in ('mesa',) or self.host_platform == 'darwin':
3603 return True
3604 return False
3605 @classmethod
3606 def default_verbosebuild(cls):
3607 # Enable verbosebuild when the output is not directed to a
3608 # terminal. When output is not a terminal, it is likely
3609 # either a pager or a log file, both of which can readily
3610 # handle the very long lines generated by verbose mode.
3611 r = cls.__stdout_is_not_a_tty
3612 if r is None:
3613 isatty = getattr(sys.stdout, 'isatty', None)
3614 # If isatty is None, then assume output is a TTY.
3615 cls.__stdout_is_not_a_tty = r = False if isatty is None else not isatty()
3616 return r
3617 def default_words_need_alignment(self):
3618 if self.raspberrypi in ('yes', 'mesa'):
3619 return True
3620 return False
3621 def default_use_stereo_render(self):
3622 return self.opengl and not self.opengles
3623 def selected_OGLES_LIB(self):
3624 if self.raspberrypi == 'yes':
3625 return 'brcmGLESv2'
3626 return self.default_OGLES_LIB
3627 def selected_EGL_LIB(self):
3628 if self.raspberrypi == 'yes':
3629 return 'brcmEGL'
3630 return self.default_EGL_LIB
3631 def need_dynamic_library_load(self):
3632 return self.adlmidi == 'runtime'
3633 def _enable_adlmidi(self):
3634 return self.adlmidi != 'none'
3635
3636 def __default_DATA_DIR(self):
3637 platform_settings_type = self._program.get_platform_settings_type(self.host_platform)
3638 sharepath = platform_settings_type.sharepath
3639 if sharepath is None:
3640 return None
3641 return sharepath(prefix=self.prefix, program_target=self._program.target)
3642
3643 def _generic_variable(key,help,default):
3644 return (key, help, default)
3645 def __get_configure_tests(tests,_filter=lambda s: s.name[0] != '_'):
3646 # Construct combined list on first use, then cache it
3647 # forever.
3648 try:
3649 return tests.__configure_tests
3650 except AttributeError:
3651 # Freeze the results into a tuple, to prevent accidental
3652 # modification later.
3653 #
3654 # In Python 3, filter returns an iterable that is
3655 # exhausted after one full traversal. Since this object
3656 # is intended to be retained and reused, the first
3657 # traversal must copy the results into a container that
3658 # can be walked multiple times. A tuple serves this
3659 # purpose, in addition to freezing the contents.
3660 tests.__configure_tests = c = tuple(filter(_filter, tests.implicit_tests + tests.custom_tests))
3661 return c
3662 @classmethod
3663 def __get_has_git_dir(cls):
3664 r = cls.__has_git_dir
3665 if r is None:
3666 # SConstruct is always at the top of the repository.
3667 # The user might have run `scons` from elsewhere and
3668 # used `-f` to indicate this file, but a false negative
3669 # is acceptable here.
3670 cls.__has_git_dir = r = os.path.exists(os.environ.get('GIT_DIR', '.git'))
3671 return r
3672 def _options(self,
3673 __get_configure_tests=__get_configure_tests,
3674 generic_variable=_generic_variable,
3675 BoolVariable=BoolVariable,
3676 EnumVariable=EnumVariable,
3677 conftests=ConfigureTests,
3678 getenv=os.environ.get
3679 ):
3680 tests = __get_configure_tests(conftests)
3681 expect_sconf_tuple = ('0', '1', conftests.expect_sconf_success, conftests.expect_sconf_failure)
3682 sconf_tuple = ('0', '1', '2', conftests.sconf_force_failure, conftests.sconf_force_success, conftests.sconf_assume_success)
3683 sys_platform = sys.platform
3684 for platform in ('linux', 'freebsd', 'openbsd'):
3685 if sys_platform.startswith(platform):
3686 sys_platform = platform
3687 break
3688 return (
3689 {
3690 'variable': EnumVariable,
3691 'arguments': [
3692 (f'expect_sconf_{t.name[6:]}',
3693 None,
3694 None,
3695 {'allowed_values' : expect_sconf_tuple}
3696 ) for t in tests
3697 ],
3698 },
3699 {
3700 'variable': EnumVariable,
3701 'arguments': [
3702 (f'sconf_{t.name[6:]}',
3703 None,
3704 t.desc or f'assume result of {t.name}',
3705 {'allowed_values' : sconf_tuple}
3706 ) for t in tests
3707 ],
3708 },
3709 {
3710 'variable': EnumVariable,
3711 'arguments': (
3712 ('host_platform',
3713 sys_platform,
3714 'cross-compile to specified platform',
3715 {
3716 'map': {'msys':'win32'},
3717 'allowed_values' : ('darwin', 'linux', 'freebsd', 'openbsd', 'win32', 'haiku1'),
3718 }
3719 ),
3720 ('raspberrypi', None, 'build for Raspberry Pi (automatically selects opengles)', {'ignorecase': 2, 'map': {'1':'yes', 'true':'yes', '0':'no', 'false':'no'}, 'allowed_values': ('yes', 'no', 'mesa')}),
3721 ),
3722 },
3723 {
3724 'variable': BoolVariable,
3725 'arguments': (
3726 ('record_sconf_results', False, 'write sconf results to dxxsconf.h'),
3727 ('git_describe_version', self.__get_has_git_dir(), 'include git --describe in extra_version'),
3728 ('git_status', True, 'include git status'),
3729 ('versid_depend_all', False, 'rebuild vers_id.cpp if any object file changes'),
3730 ),
3731 },
3732 {
3733 'variable': generic_variable,
3734 'arguments': (
3735 ('rpi_vc_path', self.RPI_DEFAULT_VC_PATH, 'directory for RPi VideoCore libraries'),
3736 ('opengles_lib', self.selected_OGLES_LIB, 'name of the OpenGL ES library to link against'),
3737 ('egl_lib', self.selected_EGL_LIB, 'name of the OpenGL ES Graphics Library to link against'),
3738 ('prefix', self._default_prefix, 'installation prefix directory (Linux only)'),
3739 ('sharepath', self.__default_DATA_DIR, 'directory for shared game data'),
3740 ),
3741 },
3742 {
3743 'variable': self.UIntVariable,
3744 'arguments': (
3745 ('lto', 0, 'enable gcc link time optimization'),
3746 ('pch', None, 'pre-compile own headers used at least this many times'),
3747 ('syspch', None, 'pre-compile system headers used at least this many times'),
3748 ('max_joysticks', 8, 'maximum number of usable joysticks'),
3749 ('max_axes_per_joystick', 128, 'maximum number of axes per joystick'),
3750 ('max_buttons_per_joystick', 128, 'maximum number of buttons per joystick'),
3751 ('max_hats_per_joystick', 4, 'maximum number of hats per joystick'),
3752 ),
3753 },
3754 {
3755 'variable': BoolVariable,
3756 'arguments': (
3757 ('pch_cpp_assume_unchanged', False, 'assume text of *pch.cpp is unchanged'),
3758 ('pch_cpp_exact_counts', False, None),
3759 ('check_header_includes', False, 'compile test each header (developer option)'),
3760 ('debug', False, 'build DEBUG binary which includes asserts, debugging output, cheats and more output'),
3761 ('memdebug', self.default_memdebug, 'build with malloc tracking'),
3762 ('opengl', True, 'build with OpenGL support'),
3763 ('opengles', self.default_opengles, 'build with OpenGL ES support'),
3764 ('editor', False, 'include editor into build (!EXPERIMENTAL!)'),
3765 ('sdl2', self.default_sdl2, 'use libSDL2+SDL2_mixer (!EXPERIMENTAL!)'),
3766 # Build with SDL_Image support for PCX file support
3767 # Currently undocumented because the user experience
3768 # without PCX support is ugly, so this should always
3769 # be left enabled.
3770 ('sdlimage', True, None),
3771 ('sdlmixer', True, 'build with SDL_Mixer support for sound and music (includes external music support)'),
3772 ('ipv6', False, 'enable UDP/IPv6 for multiplayer'),
3773 ('use_udp', True, 'enable UDP support'),
3774 ('use_tracker', True, 'enable Tracker support (requires UDP)'),
3775 ('verbosebuild', self.default_verbosebuild, 'print out all compiler/linker messages during building'),
3776 # This is only examined for Mac OS X targets.
3777 #
3778 # Some users, particularly those who install
3779 # dependencies via Homebrew, may have the required C
3780 # headers and libraries available, but not packaged
3781 # as a Framework. Such users should set
3782 # macos_add_frameworks=False, and (if the required
3783 # headers and libraries are not in a default search
3784 # location), use the standard C search path
3785 # directives to tell the compiler where to find the
3786 # required files.
3787 #
3788 # For users who have the framework installed in the
3789 # standard place, if macos_add_frameworks=True,
3790 # SCons should find the headers and libraries
3791 # automatically.
3792 ('macos_add_frameworks', True, 'add required frameworks to CPPPATH, FRAMEWORKS, and FRAMEWORKPATH search variables (MacOS only); Homebrew users may want macos_add_frameworks=False'),
3793 # This is only examined for Mac OS X targets.
3794 #
3795 # dylibbundler can have issues on some systems, so
3796 # it is an optional step. If used (and successful),
3797 # dylibbundler includes required libraries in the
3798 # generated app bundle and updates the executable
3799 # to reference them within the bundle.
3800 ('macos_bundle_libs', False, 'bundle required libs into app bundle using dylibbundler'),
3801 # This is only examined for Windows targets, so
3802 # there is no need to make the default value depend
3803 # on the host_platform.
3804 ('windows_minidump', True, 'generate a minidump on unhandled C++ exception (Windows only)'),
3805 ('words_need_alignment', self.default_words_need_alignment, 'align words at load (needed for many non-x86 systems)'),
3806 ('register_compile_target', True, 'report compile targets to SCons core'),
3807 ('register_cpp_output_targets', None, None),
3808 ('register_runtime_test_link_targets', False, None),
3809 ('enable_build_failure_summary', True, 'print failed nodes and their commands'),
3810 ('wrap_PHYSFS_read', False, None),
3811 ('wrap_PHYSFS_write', False, None),
3812 # This is intentionally undocumented. If a bug
3813 # report includes a log with this set to False, the
3814 # reporter will be asked to provide a log with the
3815 # value set to True. Try to prevent the extra round
3816 # trip by hiding the option.
3817 ('show_tool_version', True, None),
3818 # Only applicable if show_tool_version=True
3819 ('show_assembler_version', True, None),
3820 ('show_linker_version', True, None),
3821 ),
3822 },
3823 {
3824 'variable': BoolVariable,
3825 'arguments': (
3826 ('use_stereo_render', self.default_use_stereo_render, 'enable stereoscopic rendering'),
3827 ),
3828 },
3829 {
3830 'variable': generic_variable,
3831 'arguments': (
3832 ('CHOST', getenv('CHOST'), 'CHOST of output'),
3833 ('CXX', getenv('CXX'), 'C++ compiler command'),
3834 ('PKG_CONFIG', getenv('PKG_CONFIG'), 'PKG_CONFIG to run (Linux only)'),
3835 ('RC', getenv('RC'), 'Windows resource compiler command'),
3836 ('extra_version', None, 'text to append to version, such as VCS identity'),
3837 ('ccache', None, 'path to ccache'),
3838 ('compilation_database', None, None),
3839 ('distcc', None, 'path to distcc'),
3840 ('distcc_hosts', getenv('DISTCC_HOSTS'), 'hosts to distribute compilation'),
3841 # This is only examined for Mac OS X targets.
3842 #
3843 # This option signs a bundle (and the libraries
3844 # if embedded with macos_bundle_libs) with the
3845 # designated code signing identity. To use it,
3846 # pass the common name of the certificate in the
3847 # Keychain you wish to use to sign the bundle and
3848 # libraries (as applicable).
3849 ('macos_code_signing_identity', None, 'sign app bundle and embedded libs (if applicable) with this identity'),
3850 # This is only examined for Mac OS X targets.
3851 #
3852 # This option specifies a Keychain item to use
3853 # for credentials when submitting a signed app
3854 # bundle for notarization. If this is not specified,
3855 # then specifying an Apple ID and team ID is required.
3856 # For details about storing credentials in a
3857 # compatible Keychain entry, see the store-credentials
3858 # example at:
3859 # https://developer.apple.com/documentation/security/notarizing_macos_software_before_distribution/customizing_the_notarization_workflow
3860 ('macos_notarization_keychain_item', None, 'keychain item for notarization credentials'),
3861 # This is only examined for Mac OS X targets.
3862 #
3863 # An Apple ID to be used for notarization submissions.
3864 # If a valid Keychain item is not used, then this is
3865 # required.
3866 ('macos_notarization_apple_id', None, 'Apple ID for notarization submissions'),
3867 # This is only examined for Mac OS X targets.
3868 #
3869 # The Apple team ID to use for notarization submissions.
3870 # If a valid Keychain item is not used, then this is
3871 # required.
3872 ('macos_notarization_team_id', None, 'Apple team ID for notarization submissions'),
3873 # This is only examined for Mac OS X targets.
3874 #
3875 # The Apple app-specific password to use for
3876 # notarization submissions. If a valid Keychain item
3877 # is not used, then this will be used if provided.
3878 # Otherwise, the submission process will provide an
3879 # interactive prompt for the password.
3880 ('macos_notarization_password', None, 'Apple app-specific password for notarization submissions'),
3881 ),
3882 },
3883 {
3884 'variable': generic_variable,
3885 'stack': ' ',
3886 'arguments': (
3887 ('CPPFLAGS', getenv('CPPFLAGS'), 'C preprocessor flags'),
3888 ('CXXFLAGS', getenv('CXXFLAGS'), 'C++ compiler flags'),
3889 ('LINKFLAGS', getenv('LDFLAGS'), 'Linker flags'),
3890 ('LIBS', getenv('LIBS'), 'Libraries to link'),
3891 # These are intentionally undocumented. They are
3892 # meant for developers who know the implications of
3893 # using them.
3894 ('CPPFLAGS_unchecked', None, None),
3895 ('CXXFLAGS_unchecked', None, None),
3896 ('LINKFLAGS_unchecked', None, None),
3897 # Flags that are injected into the compilation
3898 # database, but which are not used in the actual
3899 # compilation. Use this to work around clang's
3900 # inability to find its own headers when invoked
3901 # from custom tools.
3902 ('CXXFLAGS_compilation_database', None, None),
3903 ),
3904 },
3905 {
3906 'variable': EnumVariable,
3907 'arguments': (
3908 ('host_endian', None, 'endianness of host platform', {'allowed_values' : ('little', 'big')}),
3909 ('adlmidi', 'none', 'include ADL MIDI support (none: disabled; runtime: dynamically load at runtime)', {'allowed_values' : ('none', 'runtime')}),
3910 ('screenshot', 'png', 'screenshot file format', {'allowed_values' : ('none', 'legacy', 'png')}),
3911 ),
3912 },
3913 {
3914 'variable': ListVariable,
3915 'arguments': (
3916 ('poison', self.default_poison, 'method for poisoning free memory', {'names' : ('valgrind', 'overwrite')}),
3917 ),
3918 },
3919 {
3920 'variable': generic_variable,
3921 'arguments': (
3922 ('builddir_prefix', None, 'prefix to generated build directory'),
3923 ('builddir_suffix', None, 'suffix to generated build directory'),
3924 # This must be last so that default_builddir will
3925 # have access to other properties.
3926 ('builddir', self.default_builddir, 'build in specified directory'),
3927 ),
3928 },
3929 )
3930 _generic_variable = staticmethod(_generic_variable)
3931
3932 @staticmethod
3933 def _names(name,prefix):
3934 return [f'{p}{"_" if p else ""}{name}' for p in prefix]
3935
3936 def __init__(self,program=None):
3937 self._program = program
3938
3939 def register_variables(self,prefix,variables,filtered_help):
3940 self.known_variables = []
3941 append_known_variable = self.known_variables.append
3942 add_variable = variables.Add
3943 for grp in self._options():
3944 variable = grp['variable']
3945 stack = grp.get('stack', None)
3946 for opt in grp['arguments']:
3947 (name,value,help) = opt[0:3]
3948 kwargs = opt[3] if len(opt) > 3 else {}
3949 if name not in variables.keys():
3950 if help is not None:
3951 filtered_help.visible_arguments.append(name)
3952 add_variable(variable(key=name, help=help, default=None if callable(value) else value, **kwargs))
3953 names = self._names(name, prefix)
3954 for n in names:
3955 if n not in variables.keys():
3956 add_variable(variable(key=n, help=help, default=None, **kwargs))
3957 if not name in names:
3958 names.append(name)
3959 append_known_variable((names, name, value, stack))
3960 if stack:
3961 for n in names:
3962 add_variable(self._generic_variable(key=f'{n}_stop', help=None, default=None))
3963 def read_variables(self,program,variables,d):
3964 verbose_settings_init = os.getenv('DXX_SCONS_DEBUG_USER_SETTINGS')
3965 for (namelist,cname,dvalue,stack) in self.known_variables:
3966 value = None
3967 found_value = False
3968 for n in namelist:
3969 try:
3970 v = d[n]
3971 found_value = True
3972 if stack:
3973 if callable(v):
3974 if verbose_settings_init:
3975 message(program, f'append to stackable {cname!r} from {n!r} by call to {v!r}({dvalue!r}, {value!r}, {stack!r})')
3976 value = v(dvalue=dvalue, value=value, stack=stack)
3977 else:
3978 if value:
3979 value = (value, v)
3980 if verbose_settings_init:
3981 message(program, f'append to stackable {cname!r} from {n!r} by join of {stack!r}.join({value!r})')
3982 value = stack.join(value)
3983 else:
3984 if verbose_settings_init:
3985 message(program, f'assign to stackable {cname!r} from {n!r} value {v!r}')
3986 value = v
3987 stop = f'{n}_stop'
3988 if d.get(stop, None):
3989 if verbose_settings_init:
3990 message(program, f'terminating search early due to presence of {stop}')
3991 break
3992 continue
3993 if verbose_settings_init:
3994 message(program, f'assign to non-stackable {cname!r} from {n!r} value {v!r}')
3995 value = v
3996 break
3997 except KeyError as e:
3998 pass
3999 if not found_value:
4000 if callable(dvalue):
4001 value = dvalue()
4002 if verbose_settings_init:
4003 message(program, f'assign to {cname!r} by default value {value!r} from call {dvalue!r}')
4004 else:
4005 value = dvalue
4006 if verbose_settings_init:
4007 message(program, f'assign to {cname!r} by default value {value!r} from direct')
4008 setattr(self, cname, value)
4009 if self.builddir != '' and self.builddir[-1:] != '/':
4010 self.builddir += '/'
4011 def clone(self):
4012 clone = DXXCommon.UserBuildSettings(None)
4013 for grp in clone._options():
4014 for o in grp['arguments']:
4015 name = o[0]
4016 value = getattr(self, name)
4017 setattr(clone, name, value)
4018 return clone
4019 class UserInstallSettings:
4020 def _options(self):
4021 return (
4022 {
4023 'variable': self._generic_variable,
4024 'arguments': (
4025 ('program_name', None, 'name of built program'),
4026 ),
4027 },
4028 {
4029 'variable': BoolVariable,
4030 'arguments': (
4031 ('register_install_target', True, 'report install target to SCons core'),
4032 ),
4033 },
4034 )
4035 class UserSettings(UserBuildSettings,UserInstallSettings):
4036 def _options(self):
4037 return DXXCommon.UserBuildSettings._options(self) + DXXCommon.UserInstallSettings._options(self)
4038 # Base class for platform-specific settings processing
4039 class _PlatformSettings:
4040 tools = ('g++', 'gnulink')
4041 ogllibs = []
4042 platform_objects = ()
4043 sharepath = None
4044
4045 def __init__(self,program,user_settings):
4046 self.__program = program
4047 self.user_settings = user_settings
4048
4049 @property
4050 def builddir(self):
4051 return self.__program.builddir
4052
4053 @property
4054 def env(self):
4055 return self.__program.env
4056
4057 # Settings to apply to mingw32 builds
4058 class Win32PlatformSettings(_PlatformSettings):
4059 ogllibs = ['opengl32', 'glu32']
4060 tools = ('mingw',)
4061 def adjust_environment(self,program,env):
4062 env.Append(
4063 CPPDEFINES = ['_WIN32', 'WIN32_LEAN_AND_MEAN'],
4064 LINKFLAGS = ['-mwindows'],
4065 )
4066 class DarwinPlatformSettings(_PlatformSettings):
4067 # Darwin targets include Objective-C (not Objective-C++) code to
4068 # access Apple-specific functionality. Add 'gcc' to the target
4069 # list to support this.
4070 #
4071 # Darwin targets need a special linker, because OS X uses
4072 # frameworks instead of standard libraries. Using `gnulink`
4073 # omits framework-related arguments, causing the linker to skip
4074 # including required libraries. SCons's `applelink` target
4075 # understands these quirks and ensures that framework-related
4076 # arguments are included.
4077 tools = ('gcc', 'g++', 'applelink')
4078 def adjust_environment(self,program,env):
4079 if self.user_settings.sdl2 == False:
4080 raise SCons.Errors.StopError('macOS builds do not support SDL 1.2.')
4081 macos_add_frameworks = self.user_settings.macos_add_frameworks
4082 if macos_add_frameworks:
4083 # The user may or may not have a private installation of
4084 # frameworks. If there are no private frameworks, then
4085 # the path to the private frameworks should not be
4086 # added, because some versions of the tools issue a
4087 # diagnostic for searching a non-existant path.
4088 library_frameworks = os.path.join(os.getenv("HOME"), 'Library/Frameworks')
4089 if os.path.isdir(library_frameworks):
4090 # The private framework directory exists. Check
4091 # whether the user has a private copy of the SDL
4092 # framework.
4093 env.Append(FRAMEWORKPATH = [library_frameworks])
4094 SDL_private_framework = os.path.join(library_frameworks, 'SDL.framework/Headers')
4095 if os.path.isdir(SDL_private_framework):
4096 # Yes, so add its headers to the C preprocessor
4097 # path.
4098 env.Append(CPPPATH = [SDL_private_framework])
4099 # else No, so omit the non-existant directory from
4100 # the C preprocessor path.
4101 # Check whether a system-wide SDL framework is
4102 # available.
4103 SDL_system_framework = '/Library/Frameworks/SDL.framework/Headers'
4104 if os.path.isdir(SDL_system_framework):
4105 env.Append(CPPPATH = [SDL_system_framework])
4106 env.Append(
4107 CPPDEFINES = ['__unix__'],
4108 FRAMEWORKS = ['ApplicationServices', 'Cocoa'],
4109 LINKFLAGS = ['-Wl,-rpath,@loader_path/../Frameworks'], # Allow libraries & frameworks to go in app bundle
4110 )
4111 if macos_add_frameworks:
4112 env.Append(FRAMEWORKS = ['SDL'])
4113 if self.user_settings.opengl or self.user_settings.opengles:
4114 env.Append(
4115 CPPDEFINES = [('GL_SILENCE_DEPRECATION',)],
4116 FRAMEWORKS = ['OpenGL'],
4117 )
4118 # Settings to apply to Linux builds
4119 class LinuxPlatformSettings(_PlatformSettings):
4120 sharepath = '{prefix}/share/games/{program_target}'.format
4121 @property
4122 def ogllibs(self):
4123 user_settings = self.user_settings
4124 return [user_settings.opengles_lib, user_settings.egl_lib] if user_settings.opengles else ['GL', 'GLU']
4125 @staticmethod
4126 def get_platform_objects(_empty=()):
4127 return _empty
4128 def adjust_environment(self,program,env):
4129 env.Append(
4130 CXXFLAGS = ['-pthread'],
4131 )
4132
4133 class HaikuPlatformSettings(LinuxPlatformSettings):
4134 def adjust_environment(self,program,env):
4135 # Note: the lack of super() is deliberate. Haiku does not want the
4136 # environment changes that LinuxPlatformSettings.adjust_environment
4137 # would provide, so there is no call to the base class method.
4138 env.Append(
4139 LIBS = ['network'],
4140 )
4141
4142 def __init__(self,user_settings,__program_instance=itertools.count(1)):
4143 self.program_instance = next(__program_instance)
4144 self.user_settings = user_settings
4145
4146 @staticmethod
4147 def __get_found_includes(node, env, scanner, path):
4148 # Always call the original and always return at
4149 # least what it returned. If this node is in the
4150 # whitelist, then also apply the hook logic.
4151 # Otherwise, this is a pass-through.
4152 r = node.__get_found_includes(env, scanner, path)
4153 return (r + [env.File(env['DXX_EFFECTIVE_SOURCE'])]) \
4154 if node in node._dxx_node_header_target_set else r
4155
4156 def create_header_targets(self,__shared_header_file_list=[],__shared_cpp_dict={}):
4157 env = self.env
4158 builddir = self.builddir
4159 check_header_includes = __shared_cpp_dict.get(builddir)
4160 if check_header_includes is None:
4161 # Generate the list once, on first use. Any other targets
4162 # will reuse it.
4163 #
4164 # Touch the file into existence. It contains only a comment, but
4165 # must exist and have an extension of '.cpp'.
4166 check_header_includes = env.Textfile(target=builddir.File('check_header_includes.cpp'), source=env.Value('''
4167 /* This file is always empty. It is only present to act as the source
4168 * file for SCons targets that test individual headers.
4169 */
4170 '''))
4171 __shared_cpp_dict[builddir] = check_header_includes
4172 # This is ugly, but all other known methods are worse. The
4173 # object file needs to depend on the header that created it
4174 # and recursively depend on headers that contributed to the
4175 # header that created it. Adding a dependency using
4176 # env.Depend creates the first-level dependency, but does
4177 # not recurse into the header. Overriding
4178 # get_found_includes will cause SCons to recurse in the
4179 # desired way.
4180 #
4181 # Calling get_found_includes requires parameters that are
4182 # not easily obtained here. There does not appear to be a
4183 # way to patch the node's dependency list to insert the
4184 # header other than to override get_found_includes.
4185 #
4186 # Newer SCons applied a performance optimization based on
4187 # using Python __slots__. Using __slots__ makes it a
4188 # runtime error to overwrite get_found_includes on the
4189 # instance, so overwrite the class method instead. However,
4190 # some instances of the class may not want this hook, so
4191 # keep a whitelist of nodes for which the hook is active.
4192 c = check_header_includes[0].__class__
4193 # If the attribute is missing, this is the first time that
4194 # an env.Textfile has been created for this purpose. Create
4195 # the attribute so that subsequent passes do not add extra
4196 # copies of the same hook.
4197 #
4198 # Since a flag attribute is needed anyway, make it useful by
4199 # storing the hook whitelist in it.
4200 if not hasattr(c, '_dxx_node_header_target_set'):
4201 c._dxx_node_header_target_set = set()
4202 c.__get_found_includes = c.get_found_includes
4203 c.get_found_includes = self.__get_found_includes
4204 # Update the whitelist here, outside the hasattr block.
4205 # This is necessary so that the hook is created once, but
4206 # every env.Textfile created by this block is whitelisted.
4207 c._dxx_node_header_target_set.add(check_header_includes[0])
4208 if not __shared_header_file_list:
4209 headers = Git.pcall(['ls-files', '-z', '--', '*.h']).out
4210 if not headers:
4211 g = Git.pcall(['--version'], stderr=subprocess.STDOUT)
4212 raise SCons.Errors.StopError(
4213 "`git ls-files` failed. `git --version` failed. Check that Git is installed." \
4214 if g.returncode else \
4215 "`git ls-files` failed, but `git --version` works. Check that scons is run from a Git repository."
4216 )
4217 # Filter out OS X related directories. Files in those
4218 # directories assume they are only ever built on OS X, so
4219 # they unconditionally include headers specific to OS X.
4220 excluded_directories = (
4221 'common/arch/cocoa/',
4222 )
4223 # Use `.extend()` instead of assignment because
4224 # `__shared_header_file_list` is shared among all invocations of
4225 # this function. An assignment would redirect the name
4226 # `__shared_header_file_list` to a non-shared copy of the list,
4227 # forcing future calls to generate their own list.
4228 __shared_header_file_list.extend([h for h in headers.decode().split('\0') if h and not h.startswith(excluded_directories)])
4229 if not __shared_header_file_list:
4230 raise SCons.Errors.StopError("`git ls-files` found headers, but none can be checked.")
4231 Depends = env.Depends
4232 StaticObject = env.StaticObject
4233 CPPFLAGS_template = env['CPPFLAGS']
4234 CPPFLAGS_no_sconf = CPPFLAGS_template + ['-g0', '-include', '$DXX_EFFECTIVE_SOURCE']
4235 CPPFLAGS_with_sconf = ['-include', 'dxxsconf.h'] + CPPFLAGS_no_sconf
4236 CXXCOMSTR = env.__header_check_output_COMSTR
4237 CXXFLAGS = env['CXXFLAGS']
4238 target = os.path.join(
4239 str(builddir.Dir(self.srcdir).Dir('check_header_includes')),
4240 f'${{DXX_EFFECTIVE_SOURCE}}{env["OBJSUFFIX"]}'
4241 )
4242 for name in __shared_header_file_list:
4243 if not name:
4244 continue
4245 if self.srcdir == 'common' and not name.startswith('common/'):
4246 # Skip game-specific headers when testing common
4247 continue
4248 if self.srcdir[0] == 'd' and name[0] == 'd' and not name.startswith(self.srcdir):
4249 # Skip d1 in d2 and d2 in d1
4250 continue
4251 # Compiler feature headers cannot include dxxsconf.h because
4252 # it confuses the dependency resolver when SConf runs.
4253 # Calling code must include dxxsconf.h before including the
4254 # compiler feature header, so add the inclusion here.
4255 #
4256 # For best test coverage, only headers that must avoid
4257 # including dxxsconf.h receive an implicit include. Any
4258 # header which needs dxxsconf.h and can include it without
4259 # side effects must do so.
4260 StaticObject(target=target,
4261 CPPFLAGS=CPPFLAGS_with_sconf if name[:24] == 'common/include/compiler-' else CPPFLAGS_no_sconf,
4262 CXXCOMSTR=CXXCOMSTR,
4263 CXXFLAGS=CXXFLAGS,
4264 DXX_EFFECTIVE_SOURCE=name,
4265 source=check_header_includes)
4266
4267 def _cpp_output_StaticObject(self,target=None,source=None,DXX_EFFECTIVE_SOURCE='$SOURCE',*args,**kwargs):
4268 CPPFLAGS = kwargs.get('CPPFLAGS', None)
4269 CXXFLAGS = kwargs.get('CXXFLAGS', None)
4270 env = self.env
4271 OBJSUFFIX = env['OBJSUFFIX']
4272 StaticObject = env.__cpp_output_StaticObject
4273 StaticObject(
4274 target=f'{target.removesuffix(OBJSUFFIX)}.i',
4275 source=source, OBJSUFFIX='.i',
4276 # Bypass ccache
4277 CXXCOM=env._dxx_cxxcom_no_prefix,
4278 CPPFLAGS=(env['CPPFLAGS'] if CPPFLAGS is None else CPPFLAGS),
4279 CXXFLAGS=(env['CXXFLAGS'] if CXXFLAGS is None else CXXFLAGS) + ['-E'],
4280 CXXCOMSTR=env.__generate_cpp_output_COMSTR,
4281 DXX_EFFECTIVE_SOURCE=DXX_EFFECTIVE_SOURCE,
4282 )
4283 return StaticObject(target=target, source=source, DXX_EFFECTIVE_SOURCE=DXX_EFFECTIVE_SOURCE, *args, **kwargs)
4284
4285 def _compilation_database_StaticObject(self,target=None,source=None,*args,**kwargs):
4286 env = self.env
4287 StaticObject = env.__compilation_database_StaticObject
4288 objects = StaticObject(target=target, source=source, *args, **kwargs)
4289 # Exclude ccache/distcc from the persisted command line. Store
4290 # `directory` as the directory of the `SConstruct` file.
4291 # Calls to `str` are necessary here to coerce SCons.Node objects
4292 # into strings that `json.dumps` can handle.
4293 # Prefer $DXX_EFFECTIVE_SOURCE if available, so that entries written
4294 # for check_header_includes=1 will name the specific header being
4295 # checked, not the dummy file `check_header_includes.cpp`.
4296 relative_file_path = str(kwargs.get('DXX_EFFECTIVE_SOURCE', source))
4297 # clang documentation is silent on whether this must be
4298 # absolute, but `clang-check` refuses to find files when this is
4299 # relative.
4300 directory = env.Dir('.').get_abspath()
4301 CXXFLAGS_compilation_database = self.user_settings.CXXFLAGS_compilation_database
4302 _dxx_cxxcom_no_prefix = env._dxx_cxxcom_no_prefix
4303 if CXXFLAGS_compilation_database:
4304 _dxx_cxxcom_no_prefix = _dxx_cxxcom_no_prefix.replace('$CXXFLAGS', '$CXXFLAGS $CXXFLAGS_compilation_database')
4305 kwargs['CXXFLAGS_compilation_database'] = CXXFLAGS_compilation_database
4306 self._compilation_database_entries.extend([
4307 {
4308 'command' : env.Override(kwargs).subst(_dxx_cxxcom_no_prefix, target=[o], source=source),
4309 'directory' : directory,
4310 'file' : relative_file_path,
4311 'output' : str(o),
4312 }
4313 for o in objects])
4314 return objects
4315
4316 def _compilation_database_Program(self,target=None,source=None,*args,**kwargs):
4317 env = self.env
4318 Program = env.__compilation_database_Program
4319 objects = Program(target=target, source=source, *args, **kwargs)
4320 source = [s[0] for s in source] if source else []
4321 directory = env.Dir('.').get_abspath()
4322 self._compilation_database_entries.extend([
4323 {
4324 'command' : env.Override(kwargs).subst(env['LINKCOM'], target=[o], source=source),
4325 'directory' : directory,
4326 # The `'file'` key is mandatory.
4327 # `clang/lib/Tooling/JSONCompilationDatabase.cpp` will reject a
4328 # database that has any entries which lack a `'file'` key. The
4329 # `'file'` key does not make sense for an output executable, so
4330 # invent a plausible looking string. This should be safe,
4331 # since clang cannot usefully target an output executable, so
4332 # it should never need to interpret this `'file'` value. This
4333 # dictionary entry is only present as a convenience to other
4334 # tools which may want to use the compilation database to know
4335 # the link flags.
4336 'file' : str(list(map(str, source))),
4337 'output' : str(o),
4338 }
4339 for o in objects])
4340 return objects
4341
4342 def create_special_target_nodes(self,archive):
4343 env = self.env
4344 StaticObject = env.StaticObject
4345 env._rebirth_nopch_StaticObject = StaticObject
4346 user_settings = self.user_settings
4347 if user_settings.register_cpp_output_targets:
4348 env.__cpp_output_StaticObject = StaticObject
4349 env.StaticObject = StaticObject = self._cpp_output_StaticObject
4350 compilation_database = user_settings.compilation_database
4351 if compilation_database:
4352 env.__compilation_database_StaticObject = StaticObject
4353 env.StaticObject = self._compilation_database_StaticObject
4354 env.__compilation_database_Program = env.Program
4355 env.Program = self._compilation_database_Program
4356 # Only set self._compilation_database_entries if collection
4357 # of the compilation database is enabled.
4358 try:
4359 compilation_database_entries = self.compilation_database_dict_fn_to_entries[compilation_database][1]
4360 except KeyError:
4361 compilation_database_entries = []
4362 self.compilation_database_dict_fn_to_entries[compilation_database] = (env, compilation_database_entries)
4363 self._compilation_database_entries = compilation_database_entries
4364
4365 if user_settings.check_header_includes:
4366 # Create header targets before creating the PCHManager, so that
4367 # create_header_targets() does not call the PCHManager
4368 # StaticObject hook.
4369 self.create_header_targets()
4370 if user_settings.register_runtime_test_link_targets:
4371 self._register_runtime_test_link_targets()
4372 configure_pch_flags = archive.configure_pch_flags
4373 if configure_pch_flags or env.GetOption('clean'):
4374 self.pch_manager = PCHManager(self, configure_pch_flags, archive.pch_manager)
4375
4376 @staticmethod
4377 def _quote_cppdefine(s,f=repr,b2a_hex=binascii.b2a_hex):
4378 r = ''
4379 prior = False
4380 for c in f(s):
4381 # No xdigit support in str
4382 if c in '+,-./:=_' or (c.isalnum() and not (prior and (c.isdigit() or c in 'abcdefABCDEF'))):
4383 r += c
4384 elif c == '\n':
4385 r += r'\n'
4386 else:
4387 r += rf'\\x{b2a_hex(c.encode()).decode()}'
4388 prior = True
4389 continue
4390 prior = False
4391 return f'\\"{r}\\"'
4392
4393 @staticmethod
4394 def _quote_cppdefine_as_char_initializer(k,v):
4395 # - Format the input as `name=value`
4396 # - map(ord, formatted_string) to produce a map object that yields an
4397 # iterable of integers representing the character codes of the
4398 # formatted string
4399 # - map(str, inner_map) to convert the iterable of integers to an
4400 # iterable of strings, where each string is the decimal digits of an
4401 # input integer
4402 # - ','.join(outer_map) to convert the iterable of strings to a
4403 # comma-separated string
4404 return f'DESCENT_{k}', ','.join(map(str, map(ord, f'{k}={v!r}')))
4405
4406 @staticmethod
4407 def _encode_cppdefine_for_identifier(s,b32encode=base64.b32encode):
4408 # Identifiers cannot contain `=`; `z` is not generated by
4409 # b32encode, so use it in place of the pad character.
4410 if not s:
4411 return s
4412 return (b32encode(s.encode()) \
4413 .rstrip() \
4414 .decode() \
4415 .replace('=', 'z') \
4416 )
4417
4418 def prepare_environment(self):
4419 # Prettier build messages......
4420 # Move target to end of C++ source command
4421 target_string = ' -o $TARGET'
4422 env = self.env
4423 user_settings = self.user_settings
4424 # Expand $CXX immediately.
4425 # $CCFLAGS is never used. Remove it.
4426 cxxcom = env['CXXCOM'] \
4427 .replace('$CXX ', f'{env["CXX"]} ') \
4428 .replace('$CCFLAGS ', '')
4429 if target_string + ' ' in cxxcom:
4430 cxxcom = f'{cxxcom.replace(target_string, "")}{target_string}'
4431 env._dxx_cxxcom_no_prefix = cxxcom
4432 distcc_path = user_settings.distcc
4433 distcc_cxxcom = f'{distcc_path} {cxxcom}' if distcc_path else cxxcom
4434 env._dxx_cxxcom_no_ccache_prefix = distcc_cxxcom
4435 ccache_path = user_settings.ccache
4436 # Add ccache/distcc only for compile, not link
4437 if ccache_path:
4438 cxxcom = f'{ccache_path} {cxxcom}'
4439 if distcc_path is not None:
4440 penv = self.env['ENV']
4441 if distcc_path:
4442 penv['CCACHE_PREFIX'] = distcc_path
4443 elif distcc_path is not None:
4444 penv.pop('CCACHE_PREFIX', None)
4445 elif distcc_path:
4446 cxxcom = distcc_cxxcom
4447 # Expand $LINK immediately.
4448 linkcom = env['LINKCOM'].replace('$LINK ', f'{env["LINK"]} ')
4449 # Move target to end of link command
4450 if target_string + ' ' in linkcom:
4451 linkcom = f'{linkcom.replace(target_string, "")}{target_string}'
4452 # Add $CXXFLAGS to link command
4453 cxxflags = '$CXXFLAGS '
4454 if ' ' + cxxflags not in linkcom:
4455 linkflags = '$LINKFLAGS'
4456 linkcom = linkcom.replace(linkflags, cxxflags + linkflags)
4457 env.Replace(
4458 CXXCOM = cxxcom,
4459 LINKCOM = linkcom,
4460 )
4461 # Custom DISTCC_HOSTS per target
4462 distcc_hosts = user_settings.distcc_hosts
4463 if distcc_hosts is not None:
4464 env['ENV']['DISTCC_HOSTS'] = distcc_hosts
4465 if user_settings.verbosebuild:
4466 env.__header_check_output_COMSTR = None
4467 env.__generate_cpp_output_COMSTR = None
4468 else:
4469 target = self.target[:3]
4470 nonblank_builddir = user_settings.builddir or '.'
4471 env.__header_check_output_COMSTR = f'CHK {target} {nonblank_builddir} $DXX_EFFECTIVE_SOURCE'
4472 env.__generate_cpp_output_COMSTR = f'CPP {target} {nonblank_builddir} $DXX_EFFECTIVE_SOURCE'
4473 env.Replace(
4474 CXXCOMSTR = f'CXX {target} {nonblank_builddir} $SOURCE',
4475 # `builddir` is implicit since $TARGET is the full path to
4476 # the output
4477 LINKCOMSTR = f'LD {target} $TARGET',
4478 RCCOMSTR = f'RC {target} {nonblank_builddir} $SOURCE',
4479 )
4480 del nonblank_builddir
4481
4482 cxxflags = [
4483 '-ftabstop=4',
4484 '-Wall',
4485 '-Wformat=2',
4486 '-Wextra',
4487 '-Wmissing-braces',
4488 '-Wmissing-include-dirs',
4489 '-Wuninitialized',
4490 '-Wundef',
4491 '-Wpointer-arith',
4492 '-Wcast-qual',
4493 '-Wmissing-declarations',
4494 '-Wvla',
4495 ]
4496 if self.user_settings.lto:
4497 # clang does not support `=N` syntax, so use the bare form `-flto`
4498 # for `user_settings.lto=1`. This allows `lto=1` to do the right
4499 # thing for clang users. gcc effectively treats `-flto` as
4500 # `-flto=1`.
4501 #
4502 # Users who set `user_settings.lto=2` (or higher) need a compiler that
4503 # understands the `=N` syntax. This script makes no attempt to
4504 # detect whether the compiler understands that syntax.
4505 #
4506 # The list of flags is prepended to the compiler options, so a
4507 # user-specified CXXFLAGS can override `-flto` later, if needed.
4508 cxxflags.append(f'-flto={self.user_settings.lto}' if self.user_settings.lto > 1 else '-flto')
4509 env.Prepend(CXXFLAGS = cxxflags)
4510 env.Append(
4511 CXXFLAGS = ['-funsigned-char'],
4512 CPPPATH = ['common/include', 'common/main', '.'],
4513 CPPFLAGS = SCons.Util.CLVar('-Wno-sign-compare'),
4514 CPPDEFINES = [
4515 # PhysFS 2.1 and later deprecate functions PHYSFS_read,
4516 # PHYSFS_write, which Rebirth uses extensively. PhysFS 2.0
4517 # does not implement the new non-deprecated functions.
4518 # Disable the deprecation error until PhysFS 2.0 support is
4519 # removed.
4520 ('PHYSFS_DEPRECATED', ''),
4521 # Every file that sees `CGameArg` must know whether a sharepath
4522 # exists. Most files do not need to know the value of
4523 # sharepath. Pass only its existence, so that changing the
4524 # sharepath does not needlessly rebuild those files.
4525 ('DXX_USE_SHAREPATH', int(not not user_settings.sharepath)),
4526 ],
4527 )
4528 add_flags = defaultdict(list)
4529 if user_settings.builddir:
4530 add_flags['CPPPATH'].append(user_settings.builddir)
4531 if user_settings.editor:
4532 add_flags['CPPPATH'].append('common/include/editor')
4533 CLVar = SCons.Util.CLVar
4534 for flags in ('CPPFLAGS', 'CXXFLAGS', 'LIBS', 'LINKFLAGS'):
4535 value = getattr(self.user_settings, flags)
4536 if value is not None:
4537 add_flags[flags] = CLVar(value)
4538 env.Append(**add_flags)
4539
4540 @cached_property
4541 def platform_settings(self):
4542 # windows or *nix?
4543 platform_name = self.user_settings.host_platform
4544 try:
4545 machine = os.uname()[4]
4546 except AttributeError:
4547 machine = None
4548 message(self, f'compiling on {sys.platform!r}/{machine!r} for {platform_name!r} into {self.user_settings.builddir or "."}{f" with prefix list {self._argument_prefix_list}" if self._argument_prefix_list else ""}')
4549 return self.get_platform_settings_type(platform_name)(self, self.user_settings)
4550
4551 @classmethod
4552 def get_platform_settings_type(cls,platform_name):
4553 # By happy accident, LinuxPlatformSettings produces the desired
4554 # result on OpenBSD, so there is no need for specific handling
4555 # of `platform_name == 'openbsd'`.
4556 return (
4557 cls.Win32PlatformSettings if platform_name == 'win32' else (
4558 cls.DarwinPlatformSettings if platform_name == 'darwin' else
4559 cls.HaikuPlatformSettings if platform_name == 'haiku1' else
4560 cls.LinuxPlatformSettings
4561 )
4562 )
4563
4564 @cached_property
4565 def env(self):
4566 platform_settings = self.platform_settings
4567 # Acquire environment object...
4568 user_settings = self.user_settings
4569 # Get traditional compiler environment variables
4570 kw = {}
4571 chost_aware_tools = ('CXX', 'RC')
4572 for cc in chost_aware_tools:
4573 value = getattr(user_settings, cc)
4574 if value is not None:
4575 kw[cc] = value
4576 tools = platform_settings.tools + ('textfile',)
4577 if user_settings.register_runtime_test_link_targets:
4578 tools += 'ar',
4579 env = Environment(ENV = os.environ, tools = tools, **kw)
4580 CHOST = user_settings.CHOST
4581 if CHOST:
4582 denv = None
4583 for cc in chost_aware_tools:
4584 if cc in kw:
4585 # If the user set a value, that value is always
4586 # used.
4587 continue
4588 if denv is None:
4589 # Lazy load denv, so that its creation can be skipped if
4590 # the user set all the required values.
4591 denv = Environment(tools = tools)
4592 # If the option in the base environment, ignoring both
4593 # user_settings and the process environment, matches the
4594 # option in the customized environment, then assume that
4595 # this is an SCons default, not a user-chosen value.
4596 #
4597 # Override SCons default values with a CHOST qualified form.
4598 # Keep user-chosen values as the user set them.
4599 value = denv.get(cc)
4600 if value and env.get(cc) == value:
4601 env[cc] = f'{CHOST}-{value}'
4602 platform_settings.adjust_environment(self, env)
4603 return env
4604
4605 def process_user_settings(self):
4606 env = self.env
4607 user_settings = self.user_settings
4608
4609 # Insert default CXXFLAGS. User-specified CXXFLAGS, if any, are
4610 # appended to this list and will override these defaults. The
4611 # defaults are present to ensure that a user who does not set
4612 # any options gets a good default experience.
4613 env.Prepend(CXXFLAGS = ['-g', '-O2'])
4614 # Raspberry Pi?
4615 if user_settings.raspberrypi == 'yes':
4616 rpi_vc_path = user_settings.rpi_vc_path
4617 message(self, f'Raspberry Pi: using VideoCore libs in {rpi_vc_path!r}')
4618 env.Append(
4619 CPPDEFINES = ['RPI'],
4620 # use CPPFLAGS -isystem instead of CPPPATH because these those header files
4621 # are not very clean and would trigger some warnings we usually consider as
4622 # errors. Using them as system headers will make gcc ignoring any warnings.
4623 CPPFLAGS = [
4624 f'-isystem{rpi_vc_path}/include',
4625 f'-isystem{rpi_vc_path}/include/interface/vcos/pthreads',
4626 f'-isystem{rpi_vc_path}/include/interface/vmcs_host/linux',
4627 ],
4628 LIBPATH = f'{rpi_vc_path}/lib',
4629 LIBS = ['bcm_host'],
4630 )
4631
4632 def _register_runtime_test_link_targets(self):
4633 runtime_test_boost_tests = self.runtime_test_boost_tests
4634 if not runtime_test_boost_tests:
4635 return
4636 env = self.env
4637 user_settings = self.user_settings
4638 builddir = env.Dir(user_settings.builddir).Dir(self.srcdir)
4639 library = env.Library(builddir.File(f'{env["LIBPREFIX"]}{self.srcdir}{env["LIBSUFFIX"]}'), self.get_library_objects())
4640 for test in runtime_test_boost_tests:
4641 LIBS = [] if test.nodefaultlibs else env['LIBS'].copy()
4642 LIBS.extend((
4643 'boost_unit_test_framework',
4644 library,
4645 ))
4646 env.Program(target=builddir.File(test.target), source=test.source(self), LIBS=LIBS)
4647
4648 runtime_test_boost_tests: collections.abc.Sequence[RuntimeTest] = None
4649
4650 class DXXArchive(DXXCommon):
4651 PROGRAM_NAME: typing.Final[str] = 'DXX-Archive'
4652 _argument_prefix_list = None
4653 srcdir: typing.Final[str] = 'common'
4654 target: typing.Final[str] = 'dxx-common'
4655
4656 get_library_objects = DXXCommon.create_lazy_object_getter((
4657 'common/maths/fixc.cpp',
4658 'common/maths/tables.cpp',
4659 'common/maths/vecmat.cpp',
4660 ))
4661
4662 RuntimeTest = DXXCommon.RuntimeTest
4663 runtime_test_boost_tests = (
4664 RuntimeTest('test-enumerate', (
4665 'common/unittest/enumerate.cpp',
4666 )),
4667 RuntimeTest('test-serial', (
4668 'common/unittest/serial.cpp',
4669 )),
4670 RuntimeTest('test-partial-range', (
4671 'common/unittest/partial_range.cpp',
4672 )),
4673 RuntimeTest('test-valptridx-range', (
4674 'common/unittest/valptridx-range.cpp',
4675 )),
4676 RuntimeTest('test-vecmat', (
4677 'common/unittest/vecmat.cpp',
4678 )),
4679 RuntimeTest('test-xrange', (
4680 'common/unittest/xrange.cpp',
4681 )),
4682 RuntimeTest('test-zip', (
4683 'common/unittest/zip.cpp',
4684 )),
4685 )
4686 del RuntimeTest
4687
4688 def get_objects_common(self,
4689 __get_objects_common=DXXCommon.create_lazy_object_getter((
4690 'common/2d/2dsline.cpp',
4691 'common/2d/bitblt.cpp',
4692 'common/2d/bitmap.cpp',
4693 'common/2d/box.cpp',
4694 'common/2d/canvas.cpp',
4695 'common/2d/circle.cpp',
4696 'common/2d/disc.cpp',
4697 'common/2d/gpixel.cpp',
4698 'common/2d/line.cpp',
4699 'common/2d/palette.cpp',
4700 'common/2d/pixel.cpp',
4701 'common/2d/rect.cpp',
4702 'common/2d/rle.cpp',
4703 'common/2d/scalec.cpp',
4704 'common/3d/draw.cpp',
4705 'common/3d/globvars.cpp',
4706 'common/3d/instance.cpp',
4707 'common/3d/matrix.cpp',
4708 'common/3d/points.cpp',
4709 'common/3d/rod.cpp',
4710 'common/3d/setup.cpp',
4711 'common/arch/sdl/event.cpp',
4712 'common/arch/sdl/joy.cpp',
4713 'common/arch/sdl/key.cpp',
4714 'common/arch/sdl/mouse.cpp',
4715 'common/arch/sdl/timer.cpp',
4716 'common/arch/sdl/window.cpp',
4717 'common/main/cglobal.cpp',
4718 'common/main/cli.cpp',
4719 'common/main/cmd.cpp',
4720 'common/main/cvar.cpp',
4721 'common/main/piggy.cpp',
4722 'common/maths/rand.cpp',
4723 'common/mem/mem.cpp',
4724 'common/misc/error.cpp',
4725 'common/misc/hash.cpp',
4726 'common/misc/hmp.cpp',
4727 'common/misc/ignorecase.cpp',
4728 'common/misc/physfsrwops.cpp',
4729 'common/misc/physfsx.cpp',
4730 'common/misc/strutil.cpp',
4731 'common/misc/vgrphys.cpp',
4732 'common/misc/vgwphys.cpp',
4733 )), \
4734 __get_objects_use_adlmidi=DXXCommon.create_lazy_object_getter((
4735 'common/music/adlmidi_dynamic.cpp',
4736 )),
4737 __get_objects_use_sdl1=DXXCommon.create_lazy_object_getter((
4738 'common/arch/sdl/rbaudio.cpp',
4739 ))
4740 ):
4741 value = list(__get_objects_common(self))
4742 extend = value.extend
4743 extend(self.get_library_objects())
4744 user_settings = self.user_settings
4745 if user_settings._enable_adlmidi():
4746 extend(__get_objects_use_adlmidi(self))
4747 if not user_settings.sdl2:
4748 extend(__get_objects_use_sdl1(self))
4749 extend(self.platform_settings.get_platform_objects())
4750 return value
4751
4752 get_objects_editor = DXXCommon.create_lazy_object_getter((
4753 'common/editor/autosave.cpp',
4754 'common/editor/func.cpp',
4755 'common/ui/button.cpp',
4756 'common/ui/checkbox.cpp',
4757 'common/ui/dialog.cpp',
4758 'common/ui/file.cpp',
4759 'common/ui/gadget.cpp',
4760 'common/ui/icon.cpp',
4761 'common/ui/inputbox.cpp',
4762 'common/ui/keypad.cpp',
4763 'common/ui/keypress.cpp',
4764 'common/ui/listbox.cpp',
4765 'common/ui/menu.cpp',
4766 'common/ui/menubar.cpp',
4767 'common/ui/message.cpp',
4768 'common/ui/radio.cpp',
4769 'common/ui/scroll.cpp',
4770 'common/ui/ui.cpp',
4771 'common/ui/uidraw.cpp',
4772 'common/ui/userbox.cpp',
4773 ))
4774 # for non-ogl
4775 get_objects_arch_sdl = DXXCommon.create_lazy_object_getter((
4776 'common/3d/clipper.cpp',
4777 'common/texmap/ntmap.cpp',
4778 'common/texmap/scanline.cpp',
4779 'common/texmap/tmapflat.cpp',
4780 ))
4781 # for ogl
4782 get_objects_arch_ogl = DXXCommon.create_lazy_object_getter((
4783 'common/arch/ogl/ogl_extensions.cpp',
4784 'common/arch/ogl/ogl_sync.cpp',
4785 ))
4786 get_objects_arch_sdlmixer = DXXCommon.create_lazy_object_getter((
4787 'common/arch/sdl/digi_mixer_music.cpp',
4788 'common/arch/sdl/jukebox.cpp',
4789 ))
4790 class Win32PlatformSettings(DXXCommon.Win32PlatformSettings):
4791 __get_platform_objects = LazyObjectConstructor.create_lazy_object_getter((
4792 'common/arch/win32/except.cpp',
4793 'common/arch/win32/messagebox.cpp',
4794 ))
4795 __get_sdl2_objects = LazyObjectConstructor.create_lazy_object_getter((
4796 'common/arch/win32/rbaudio.cpp',
4797 ))
4798 def get_platform_objects(self):
4799 result = self.__get_platform_objects()
4800 if self.user_settings.sdl2:
4801 result += self.__get_sdl2_objects()
4802 return result
4803
4804 class DarwinPlatformSettings(DXXCommon.DarwinPlatformSettings):
4805 get_platform_objects = LazyObjectConstructor.create_lazy_object_getter((
4806 'common/arch/cocoa/messagebox.mm',
4807 ))
4808
4809 class LinuxPlatformSettings(DXXCommon.LinuxPlatformSettings):
4810 __get_sdl2_objects = LazyObjectConstructor.create_lazy_object_getter((
4811 'common/arch/sdl/messagebox.cpp',
4812 ))
4813 def get_platform_objects(self):
4814 result = ()
4815 if self.user_settings.sdl2:
4816 result += self.__get_sdl2_objects()
4817 return result
4818
4819 def __init__(self,user_settings):
4820 user_settings = user_settings.clone()
4821 super().__init__(user_settings)
4822 if not user_settings.register_compile_target:
4823 return
4824 self.prepare_environment()
4825 self.process_user_settings()
4826 self.configure_environment()
4827 self.create_special_target_nodes(self)
4828
4829 def configure_environment(self):
4830 user_settings = self.user_settings
4831 builddir = user_settings.builddir or '.'
4832 env = self.env
4833 try:
4834 builddir = env.Dir(builddir)
4835 except TypeError as e:
4836 raise SCons.Errors.StopError(e.args[0])
4837 tests = ConfigureTests(self.program_message_prefix, user_settings, self.platform_settings)
4838 log_file = builddir.File('sconf.log')
4839 conf = env.Configure(custom_tests = {
4840 k.name:getattr(tests, k.name) for k in tests.custom_tests
4841 },
4842 conf_dir=builddir.Dir('.sconf_temp'),
4843 log_file=log_file,
4844 config_h=builddir.File('dxxsconf.h'),
4845 clean=False,
4846 help=False
4847 )
4848 self.configure_added_environment_flags = tests.successful_flags
4849 self.configure_pch_flags = None
4850 if not conf.env:
4851 return
4852 cc_env_strings = tests.ForceVerboseLog(conf.env)
4853 try:
4854 for k in tests.custom_tests:
4855 getattr(conf, k.name)()
4856 except SCons.Errors.StopError as e:
4857 raise SCons.Errors.StopError(f'{e.args[0]} See {log_file} for details.', *e.args[1:])
4858 cc_env_strings.restore(conf.env)
4859 if user_settings.pch:
4860 conf.Define('DXX_VERSION_SEQ', self.DXX_VERSION_SEQ)
4861 if user_settings.record_sconf_results:
4862 conf.config_h_text += f'''
4863 /*
4864 SConf test results
4865 ---
4866 {''.join(f"""check_{n}={v}
4867 """ for n,v in tests._sconf_results)}
4868 */
4869 '''
4870 conf.Finish()
4871 self.configure_pch_flags = tests.pch_flags
4872 add_flags = self.configure_added_environment_flags
4873 CLVar = SCons.Util.CLVar
4874 for flags in ('CPPFLAGS', 'CXXFLAGS', 'LINKFLAGS'):
4875 value = getattr(user_settings, f'{flags}_unchecked')
4876 if value:
4877 add_flags[flags] += CLVar(value)
4878 # Wrapping PHYSFS_readBytes / PHYSFS_writeBytes is only useful when
4879 # Valgrind poisoning is enabled. If Valgrind poisoning is not
4880 # enabled, the wrappers are not built (unless the appropriate
4881 # preprocessor define is added to $CPPFLAGS by the user). The
4882 # link will fail if wrapping is enabled, Valgrind poisoning is
4883 # disabled, and the preprocessor define is not set.
4884 #
4885 # Only $LINKFLAGS are set here. The preprocessor define is only
4886 # relevant to 2 source files, both of which delegate it to
4887 # header common/misc/vg-wrap-physfs.h, so omit it from the
4888 # general options to avoid unnecessary rebuilds of other source
4889 # files.
4890 if user_settings.wrap_PHYSFS_read:
4891 add_flags['LINKFLAGS'].extend((
4892 '-Wl,--wrap,PHYSFS_readBytes',
4893 '-Wl,--wrap,PHYSFS_readSBE16',
4894 '-Wl,--wrap,PHYSFS_readSBE32',
4895 '-Wl,--wrap,PHYSFS_readSLE16',
4896 '-Wl,--wrap,PHYSFS_readSLE32',
4897 '-Wl,--wrap,PHYSFS_readULE16',
4898 '-Wl,--wrap,PHYSFS_readULE32',
4899 ))
4900 if user_settings.wrap_PHYSFS_write:
4901 add_flags['LINKFLAGS'].extend((
4902 '-Wl,--wrap,PHYSFS_writeBytes',
4903 '-Wl,--wrap,PHYSFS_writeSBE16',
4904 '-Wl,--wrap,PHYSFS_writeSBE32',
4905 '-Wl,--wrap,PHYSFS_writeSLE16',
4906 '-Wl,--wrap,PHYSFS_writeSLE32',
4907 '-Wl,--wrap,PHYSFS_writeULE16',
4908 '-Wl,--wrap,PHYSFS_writeULE32',
4909 ))
4910 env.MergeFlags(add_flags)
4911
4912 class DXXProgram(DXXCommon):
4913 LazyObjectState = DXXCommon.LazyObjectState
4914 def _generate_kconfig_ui_table(program, env, source: typing.Final[str], target, kconfig_static_object: 'StaticObject') -> None:
4915 builddir = program.builddir.Dir(program.target)
4916 # Bypass ccache, if any, since this is a preprocess only
4917 # call.
4918 CXXFLAGS = env['CXXFLAGS']
4919 CXXFLAGS = CXXFLAGS.copy() if CXXFLAGS else []
4920 CXXFLAGS.append('-E')
4921 CPPDEFINES = env['CPPDEFINES']
4922 CPPDEFINES = CPPDEFINES.copy() if CPPDEFINES else []
4923 CPPDEFINES.extend((
4924 # Define these tokens to themselves so that
4925 # `#ifndef` does not try to redefine them.
4926 ('DXX_KCONFIG_UI_ENUM', 'DXX_KCONFIG_UI_ENUM'),
4927 ('DXX_KCONFIG_UI_LABEL', 'DXX_KCONFIG_UI_LABEL'),
4928 # Define this token to itself so that instances of
4929 # the kc_item structure are defined in the output
4930 # file.
4931 ('kc_item', 'kc_item'),
4932 ))
4933 cpp_kconfig_udlr = env._rebirth_nopch_StaticObject(target=str(target)[:-1] + 'ui-table.i', source=source[:-3] + 'ui-table.cpp', CPPDEFINES=CPPDEFINES, CXXCOM=env._dxx_cxxcom_no_ccache_prefix, CXXFLAGS=CXXFLAGS)
4934 generated_udlr_header = builddir.File('kconfig.udlr.h')
4935 generate_kconfig_udlr = env.File('similar/main/generate-kconfig-udlr.py')
4936 env.Command(generated_udlr_header, [cpp_kconfig_udlr, generate_kconfig_udlr], [[sys.executable, generate_kconfig_udlr, '$SOURCE', '$TARGET']])
4937 env.Depends(kconfig_static_object, generated_udlr_header)
4938
4939 static_archive_construction = {}
4940
4941 def _apply_target_name(self,name):
4942 return os.path.join(os.path.dirname(name), f'.{self.target}.{os.path.splitext(os.path.basename(name))[0]}')
4943
4944 def _apply_env_version_seq(self,env,_empty={}):
4945 if self.user_settings.pch:
4946 return _empty
4947 CPPDEFINES = env['CPPDEFINES']
4948 CPPDEFINES = CPPDEFINES.copy() if CPPDEFINES else []
4949 CPPDEFINES.append(('DXX_VERSION_SEQ', self.DXX_VERSION_SEQ))
4950 return {
4951 'CPPDEFINES' : CPPDEFINES
4952 }
4953
4954 get_objects_similar_arch_ogl = DXXCommon.create_lazy_object_states_getter((LazyObjectState(sources=(
4955 'similar/arch/ogl/gr.cpp',
4956 'similar/arch/ogl/ogl.cpp',
4957 ),
4958 transform_target=_apply_target_name,
4959 ),
4960 ))
4961 get_objects_similar_arch_sdl = DXXCommon.create_lazy_object_states_getter((LazyObjectState(sources=(
4962 'similar/arch/sdl/gr.cpp',
4963 ),
4964 transform_target=_apply_target_name,
4965 ),
4966 ))
4967 get_objects_similar_arch_sdlmixer = DXXCommon.create_lazy_object_states_getter((LazyObjectState(sources=(
4968 'similar/arch/sdl/digi_mixer.cpp',
4969 ),
4970 transform_target=_apply_target_name,
4971 ),
4972 ))
4973 __get_objects_common = DXXCommon.create_lazy_object_states_getter((LazyObjectState(sources=(
4974 'similar/2d/font.cpp',
4975 'similar/2d/palette.cpp',
4976 'similar/2d/pcx.cpp',
4977 'similar/3d/interp.cpp',
4978 'similar/arch/sdl/digi.cpp',
4979 'similar/arch/sdl/digi_audio.cpp',
4980 'similar/arch/sdl/init.cpp',
4981 'similar/main/ai.cpp',
4982 'similar/main/aipath.cpp',
4983 'similar/main/automap.cpp',
4984 'similar/main/bm.cpp',
4985 'similar/main/cntrlcen.cpp',
4986 'similar/main/collide.cpp',
4987 'similar/main/config.cpp',
4988 'similar/main/console.cpp',
4989 'similar/main/controls.cpp',
4990 'similar/main/credits.cpp',
4991 'similar/main/digiobj.cpp',
4992 'similar/main/effects.cpp',
4993 'similar/main/endlevel.cpp',
4994 'similar/main/fireball.cpp',
4995 'similar/main/fuelcen.cpp',
4996 'similar/main/fvi.cpp',
4997 'similar/main/game.cpp',
4998 'similar/main/gamecntl.cpp',
4999 'similar/main/gamefont.cpp',
5000 'similar/main/gamemine.cpp',
5001 'similar/main/gamerend.cpp',
5002 'similar/main/gamesave.cpp',
5003 'similar/main/gameseg.cpp',
5004 'similar/main/gameseq.cpp',
5005 'similar/main/gauges.cpp',
5006 'similar/main/hostage.cpp',
5007 'similar/main/hud.cpp',
5008 'similar/main/iff.cpp',
5009 'similar/main/kmatrix.cpp',
5010 'similar/main/laser.cpp',
5011 'similar/main/lighting.cpp',
5012 'similar/main/menu.cpp',
5013 'similar/main/mglobal.cpp',
5014 'similar/main/mission.cpp',
5015 'similar/main/morph.cpp',
5016 'similar/main/newdemo.cpp',
5017 'similar/main/newmenu.cpp',
5018 'similar/main/object.cpp',
5019 'similar/main/paging.cpp',
5020 'similar/main/physics.cpp',
5021 'similar/main/piggy.cpp',
5022 'similar/main/player.cpp',
5023 'similar/main/polyobj.cpp',
5024 'similar/main/powerup.cpp',
5025 'similar/main/render.cpp',
5026 'similar/main/robot.cpp',
5027 'similar/main/scores.cpp',
5028 'similar/main/segment.cpp',
5029 'similar/main/slew.cpp',
5030 'similar/main/songs.cpp',
5031 'similar/main/state.cpp',
5032 'similar/main/switch.cpp',
5033 'similar/main/terrain.cpp',
5034 'similar/main/texmerge.cpp',
5035 'similar/main/text.cpp',
5036 'similar/main/titles.cpp',
5037 'similar/main/vclip.cpp',
5038 'similar/main/wall.cpp',
5039 'similar/main/weapon.cpp',
5040 'similar/misc/args.cpp',
5041 ),
5042 transform_target=_apply_target_name,
5043 ), LazyObjectState(sources=(
5044 'similar/main/inferno.cpp',
5045 ),
5046 transform_env = lambda self, env: {
5047 'CPPDEFINES' : tuple(itertools.chain(env['CPPDEFINES'], env.__dxx_CPPDEFINE_SHAREPATH, env.__dxx_CPPDEFINE_git_version))
5048 },
5049 transform_target=_apply_target_name,
5050 ), LazyObjectState(sources=(
5051 'similar/main/kconfig.cpp',
5052 ),
5053 StaticObject_hook=_generate_kconfig_ui_table,
5054 transform_target=_apply_target_name,
5055 ), LazyObjectState(sources=(
5056 'similar/misc/physfsx.cpp',
5057 ),
5058 transform_env = lambda self, env: {
5059 'CPPDEFINES' : tuple(itertools.chain(env['CPPDEFINES'], env.__dxx_CPPDEFINE_SHAREPATH))
5060 },
5061 transform_target=_apply_target_name,
5062 ), LazyObjectState(sources=(
5063 'similar/main/playsave.cpp',
5064 ),
5065 transform_env=_apply_env_version_seq,
5066 transform_target=_apply_target_name,
5067 ),
5068 ))
5069 get_objects_editor = DXXCommon.create_lazy_object_states_getter((LazyObjectState(sources=(
5070 'similar/editor/centers.cpp',
5071 'similar/editor/curves.cpp',
5072 'similar/main/dumpmine.cpp',
5073 'similar/editor/eglobal.cpp',
5074 'similar/editor/elight.cpp',
5075 'similar/editor/eobject.cpp',
5076 'similar/editor/eswitch.cpp',
5077 'similar/editor/group.cpp',
5078 'similar/editor/info.cpp',
5079 'similar/editor/kbuild.cpp',
5080 'similar/editor/kcurve.cpp',
5081 'similar/editor/kfuncs.cpp',
5082 'similar/editor/kgame.cpp',
5083 'similar/editor/khelp.cpp',
5084 'similar/editor/kmine.cpp',
5085 'similar/editor/ksegmove.cpp',
5086 'similar/editor/ksegsel.cpp',
5087 'similar/editor/ksegsize.cpp',
5088 'similar/editor/ktmap.cpp',
5089 'similar/editor/kview.cpp',
5090 'similar/editor/med.cpp',
5091 'similar/editor/meddraw.cpp',
5092 'similar/editor/medmisc.cpp',
5093 'similar/editor/medrobot.cpp',
5094 'similar/editor/medsel.cpp',
5095 'similar/editor/medwall.cpp',
5096 'similar/editor/mine.cpp',
5097 'similar/editor/objpage.cpp',
5098 'similar/editor/segment.cpp',
5099 'similar/editor/seguvs.cpp',
5100 'similar/editor/texpage.cpp',
5101 'similar/editor/texture.cpp',
5102 ),
5103 transform_target=_apply_target_name,
5104 ),
5105 ))
5106
5107 class UserSettings(DXXCommon.UserSettings):
5108 @property
5109 def BIN_DIR(self):
5110 # installation path
5111 return f'{self.prefix}/games'
5112 # Settings to apply to mingw32 builds
5113 class Win32PlatformSettings(DXXCommon.Win32PlatformSettings):
5114 def adjust_environment(self,program,env):
5115 super().adjust_environment(program, env)
5116 rcdir = 'similar/arch/win32'
5117 j = os.path.join
5118 resfile = env.RES(target=j(program.user_settings.builddir, rcdir, f'{program.target}.res{env["OBJSUFFIX"]}'), source=j(rcdir, 'dxx-rebirth.rc'))
5119 Depends = env.Depends
5120 File = env.File
5121 Depends(resfile, File(j(rcdir, 'dxx-rebirth.manifest')))
5122 Depends(resfile, File(j(rcdir, f'{program.target}.ico')))
5123 self.platform_objects = [resfile]
5124 env.Prepend(
5125 CXXFLAGS = ['-fno-omit-frame-pointer'],
5126 RCFLAGS = [f'-D{d[0]}={d[1]}' for d in program.env_CPPDEFINES] + ['-D' f'DXX_VERSION_SEQ={program.DXX_VERSION_SEQ}'],
5127 )
5128 env.Append(
5129 LIBS = ['wsock32', 'ws2_32', 'winmm', 'mingw32'],
5130 )
5131 # Settings to apply to Apple builds
5132 class DarwinPlatformSettings(DXXCommon.DarwinPlatformSettings):
5133 def adjust_environment(self,program,env):
5134 super().adjust_environment(program, env)
5135 VERSION = f'{program.VERSION_MAJOR}.{program.VERSION_MINOR}'
5136 if (program.VERSION_MICRO):
5137 VERSION += f'.{program.VERSION_MICRO}'
5138 env.Replace(
5139 VERSION_NUM = VERSION,
5140 VERSION_NAME = f'{program.PROGRAM_NAME} v{VERSION}',
5141 )
5142 # Settings to apply to Linux builds
5143 class LinuxPlatformSettings(DXXCommon.LinuxPlatformSettings):
5144 def __init__(self,program,user_settings):
5145 super().__init__(program, user_settings)
5146 if user_settings.sharepath and user_settings.sharepath[-1] != '/':
5147 user_settings.sharepath += '/'
5148 def adjust_environment(self,program,env):
5149 super().adjust_environment(program, env)
5150 user_settings = self.user_settings
5151 if user_settings.need_dynamic_library_load():
5152 env.Append(LIBS = ['dl'])
5153
5154 def get_objects_common(self,
5155 __get_objects_common=__get_objects_common,
5156 __get_objects_multiplayer=DXXCommon.create_lazy_object_states_getter((LazyObjectState(sources=(
5157 'similar/main/multi.cpp',
5158 'similar/main/multibot.cpp',
5159 ),
5160 transform_target=_apply_target_name,
5161 ),
5162 )),
5163 __get_objects_use_udp=DXXCommon.create_lazy_object_states_getter((LazyObjectState(sources=(
5164 'similar/main/net_udp.cpp',
5165 ),
5166 transform_env= _apply_env_version_seq,
5167 transform_target=_apply_target_name,
5168 ),
5169 ))
5170 ):
5171 value = list(__get_objects_common(self))
5172 extend = value.extend
5173 if self.user_settings.use_udp:
5174 extend(__get_objects_multiplayer(self))
5175 extend(__get_objects_use_udp(self))
5176 extend(self.platform_settings.platform_objects)
5177 return value
5178
5179 def __init__(self,prefix,variables,filtered_help):
5180 self.variables = variables
5181 self._argument_prefix_list = prefix
5182 user_settings = self.UserSettings(program=self)
5183 super().__init__(user_settings)
5184 compute_extra_version = Git.compute_extra_version()
5185 git_describe_version = compute_extra_version.describe
5186 extra_version = f'v{self.VERSION_MAJOR}.{self.VERSION_MINOR}.{self.VERSION_MICRO}'
5187 if git_describe_version and not (extra_version == git_describe_version or extra_version[1:] == git_describe_version):
5188 extra_version += ' ' + git_describe_version
5189 print(f'===== {self.PROGRAM_NAME} {extra_version} {compute_extra_version.revparse_HEAD} =====')
5190 user_settings.register_variables(prefix, variables, filtered_help)
5191
5192 # Run `init()`, but decorate any exception that occurs with a description
5193 # of the profile for this instance. This allows the user to see which
5194 # profile triggered the exception.
5195 def init_with_decoration(self, substenv):
5196 try:
5197 self.init(substenv)
5198 except Exception as e:
5199 # Patch the exception's arguments instead of using Python exception
5200 # chaining. Using `raise Exception('') from e` causes SCons not to
5201 # show the traceback for `e`.
5202 a = e.args or ()
5203 e.args = (f'Failed to initialize profile {self._argument_prefix_list!r}{f": {a[0]}" if a else ""}',) + a[1:]
5204 raise
5205
5206 def init(self,substenv):
5207 user_settings = self.user_settings
5208 user_settings.read_variables(self, self.variables, substenv)
5209 archive = DXXProgram.static_archive_construction.get(user_settings.builddir, None)
5210 if archive is None:
5211 DXXProgram.static_archive_construction[user_settings.builddir] = archive = DXXArchive(user_settings)
5212 if user_settings.register_compile_target:
5213 self.prepare_environment(archive)
5214 self.process_user_settings()
5215 self.register_program()
5216 if user_settings.enable_build_failure_summary:
5217 self._register_build_failure_hook(archive)
5218 return self.variables.GenerateHelpText(self.env)
5219
5220 def prepare_environment(self,archive):
5221 super().prepare_environment()
5222 env = self.env
5223 env.MergeFlags(archive.configure_added_environment_flags)
5224 self.create_special_target_nodes(archive)
5225 sharepath = self.user_settings.sharepath
5226 env.__dxx_CPPDEFINE_SHAREPATH = (
5227 ('DXX_SHAREPATH', self._quote_cppdefine(sharepath, f=str)),
5228 ) if sharepath else ()
5229 SCons.Script.Main.progress_display(f'{self.program_message_prefix}: default sharepath is {(sharepath or None)!r}')
5230 CPPDEFINES = list(self.env_CPPDEFINES)
5231 # For PRIi64
5232 CPPDEFINES.append(('__STDC_FORMAT_MACROS',))
5233 env.Append(
5234 CPPDEFINES = CPPDEFINES,
5235 CPPPATH = [os.path.join(self.srcdir, 'main')],
5236 LIBS = ['m'],
5237 )
5238
5239 def register_program(self):
5240 user_settings = self.user_settings
5241 exe_target = user_settings.program_name
5242 if not exe_target:
5243 exe_target = os.path.join(self.srcdir, self.target)
5244 if user_settings.editor:
5245 exe_target += '-editor'
5246 env = self.env
5247 PROGSUFFIX = env['PROGSUFFIX']
5248 if PROGSUFFIX and not exe_target.endswith(PROGSUFFIX):
5249 exe_target += PROGSUFFIX
5250 exe_target = self.builddir.File(exe_target)
5251 if user_settings.register_compile_target:
5252 exe_target = self._register_program(exe_target)
5253 ToolchainInformation.show_partial_environ(env, user_settings, SCons.Script.Main.progress_display, self.program_message_prefix, append_newline='')
5254 if user_settings.register_install_target:
5255 bundledir = self._register_install(self.shortname, exe_target)
5256 if user_settings.macos_code_signing_identity is not None:
5257 self._macos_sign_and_notarize_bundle(self.shortname, bundledir)
5258
5259 def _register_program(self,exe_target):
5260 env = self.env
5261 user_settings = self.user_settings
5262 static_archive_construction = self.static_archive_construction[user_settings.builddir]
5263 objects = static_archive_construction.get_objects_common()
5264 git_describe_version = Git.compute_extra_version() if user_settings.git_describe_version else Git.UnknownExtraVersion
5265 env.__dxx_CPPDEFINE_git_version = (
5266 ('DXX_git_commit', git_describe_version.revparse_HEAD),
5267 ('DXX_git_describe', self._encode_cppdefine_for_identifier(git_describe_version.describe))
5268 )
5269 objects.extend(self.get_objects_common())
5270 if user_settings.sdlmixer:
5271 objects.extend(static_archive_construction.get_objects_arch_sdlmixer())
5272 objects.extend(self.get_objects_similar_arch_sdlmixer())
5273 if user_settings.opengl or user_settings.opengles:
5274 env.Append(LIBS = self.platform_settings.ogllibs)
5275 static_objects_arch = static_archive_construction.get_objects_arch_ogl
5276 objects_similar_arch = self.get_objects_similar_arch_ogl
5277 else:
5278 static_objects_arch = static_archive_construction.get_objects_arch_sdl
5279 objects_similar_arch = self.get_objects_similar_arch_sdl
5280 objects.extend(static_objects_arch())
5281 objects.extend(objects_similar_arch())
5282 if user_settings.editor:
5283 objects.extend(self.get_objects_editor())
5284 objects.extend(static_archive_construction.get_objects_editor())
5285 versid_build_environ = ['CXX', 'CPPFLAGS', 'CXXFLAGS', 'LINKFLAGS']
5286 versid_cppdefines = env['CPPDEFINES'].copy()
5287 extra_version = user_settings.extra_version
5288 # Possible results:
5289 # extra_version is unset, git is available: use only git
5290 # extra_version is unset, git is not available: use version from SConstruct
5291 # extra_version is set, git is available: use "extra_version git_version"
5292 # extra_version is set, git is not available: use "extra_version"
5293 git_describe_version_describe_output = git_describe_version.describe
5294 if extra_version is None:
5295 extra_version = git_describe_version_describe_output or f'v{self.VERSION_MAJOR}.{self.VERSION_MINOR}{f".{self.VERSION_MICRO}" if self.VERSION_MICRO else ""}'
5296 else:
5297 if git_describe_version_describe_output:
5298 extra_version = f'{extra_version} {git_describe_version_describe_output}'
5299 # else use only extra_version as it was set in user_settings
5300 get_version_head = StaticSubprocess.get_version_head
5301 ld_path = ToolchainInformation.get_tool_path(env, 'ld')[1]
5302 _quote_cppdefine_as_char_initializer = self._quote_cppdefine_as_char_initializer
5303 versid_cppdefines.extend([_quote_cppdefine_as_char_initializer(k, env.get(k, '')) for k in versid_build_environ])
5304 if extra_version:
5305 # VERSION_EXTRA is special. Format it as a string so that
5306 # it can be pasted into g_descent_version (in vers_id.cpp)
5307 # and look normal when printed as part of the startup
5308 # banner. Since it is pasted into g_descent_version, it is
5309 # NOT included in versid_build_environ as an independent
5310 # field.
5311 versid_cppdefines.append(('DESCENT_VERSION_EXTRA', ','.join(map(str, map(ord, extra_version)))))
5312 versid_cppdefines.extend((
5313 _quote_cppdefine_as_char_initializer('CXX_version', get_version_head(env['CXX'])),
5314 _quote_cppdefine_as_char_initializer('LINK', ld_path.decode()),
5315 _quote_cppdefine_as_char_initializer('git_status', git_describe_version.status),
5316 _quote_cppdefine_as_char_initializer('git_diffstat', git_describe_version.diffstat_HEAD),
5317 ))
5318 if ld_path:
5319 versid_cppdefines.append(
5320 _quote_cppdefine_as_char_initializer('LINK_version', get_version_head(ld_path))
5321 )
5322 versid_build_environ.append('LINK_version')
5323 versid_build_environ.extend((
5324 'CXX_version',
5325 'LINK',
5326 'git_status',
5327 'git_diffstat',
5328 ))
5329 versid_cppdefines.append(('DXX_RBE"(A)"', f'"{"".join([f"A({k})" for k in versid_build_environ])}"'))
5330 versid_environ = self.env['ENV'].copy()
5331 # Direct mode conflicts with __TIME__
5332 versid_environ['CCACHE_NODIRECT'] = 1
5333 versid_cpp = 'similar/main/vers_id.cpp'
5334 versid_obj = env.StaticObject(target=f'{user_settings.builddir}{self._apply_target_name(versid_cpp)}{self.env["OBJSUFFIX"]}', source=versid_cpp, CPPDEFINES=versid_cppdefines, ENV=versid_environ)
5335 Depends = env.Depends
5336 # If $SOURCE_DATE_EPOCH is set, add its value as a shadow
5337 # dependency to ensure that vers_id.cpp is rebuilt if
5338 # $SOURCE_DATE_EPOCH on this run differs from $SOURCE_DATE_EPOCH
5339 # on last run. If it is unset, use None for this test, so that
5340 # unset differs from all valid values. Using a fixed value for
5341 # unset means that vers_id.cpp will not be rebuilt for this
5342 # dependency if $SOURCE_DATE_EPOCH was previously unset and is
5343 # currently unset, regardless of when it was most recently
5344 # built, but vers_id.cpp will be rebuilt if the user changes
5345 # $SOURCE_DATE_EPOCH and reruns scons.
5346 #
5347 # The process environment is not modified, so the default None
5348 # is never seen by tools that would reject it.
5349 Depends(versid_obj, env.Value(os.getenv('SOURCE_DATE_EPOCH')))
5350 if user_settings.versid_depend_all:
5351 # Optional fake dependency to force vers_id to rebuild so
5352 # that it picks up the latest timestamp.
5353 Depends(versid_obj, objects)
5354 objects.append(versid_obj)
5355 # finally building program...
5356 return env.Program(target=exe_target, source = objects)
5357
5358 def _show_build_failure_summary():
5359 build_failures = SCons.Script.GetBuildFailures()
5360 if not build_failures:
5361 # If all targets built successfully, return.
5362 return
5363 reportable_failures = []
5364 total = 0
5365 for f in build_failures:
5366 if not f:
5367 continue
5368 e = f.executor
5369 if not e:
5370 continue
5371 total += 1
5372 e = e.get_build_env()
5373 # Test whether the build environment for this failure is one for
5374 # which failures should be reported. If the attribute is present,
5375 # a report is desired. If the attribute is absent, then this
5376 # failure should not be reported, but this method was called
5377 # because some other build environment was marked to report
5378 # failures.
5379 try:
5380 e.__show_build_failure_summary
5381 except AttributeError:
5382 continue
5383 reportable_failures.append(f)
5384 if not total:
5385 # If no failed targets had a usable executor, then nothing useful
5386 # can be reported. Return silently.
5387 return
5388 print(f'Failed target count: total={total}; targets with enable_build_failure_summary=1: {len(reportable_failures)}')
5389 if reportable_failures:
5390 # If all the failures were in profiles that do not report failures,
5391 # then `reportable_failures` is empty.
5392 #
5393 # Sacrifice some precision on the command so that the printed
5394 # output is valid shell input.
5395 print(f'''Failed node list:
5396 {"""
5397 """.join(str(f.node) for f in reportable_failures)}
5398 Failed command list:
5399 {"""
5400 """.join(" ".join(f.command) if isinstance(f.command, list) else f.command for f in reportable_failures)}''')
5401
5402 def _register_build_failure_hook(self,archive,show_build_failure_summary=[_show_build_failure_summary]):
5403 # Always mark the environment as report-enabled.
5404 # Only register the atexit hook once.
5405 env = self.env
5406 env.__show_build_failure_summary = None
5407 archive.env.__show_build_failure_summary = None
5408 if not show_build_failure_summary:
5409 return
5410 from atexit import register
5411 register(show_build_failure_summary.pop())
5412
5413 def _register_install(self,dxxstr,exe_node):
5414 env = self.env
5415 if self.user_settings.host_platform != 'darwin':
5416 install_dir = self.user_settings.BIN_DIR
5417 env.Install(install_dir, exe_node)
5418 env.Alias('install', install_dir)
5419 else:
5420 syspath = sys.path.copy()
5421 cocoa = 'common/arch/cocoa'
5422 sys.path += [cocoa]
5423 import tool_bundle
5424 sys.path = syspath
5425 tool_bundle.TOOL_BUNDLE(env)
5426 # bundledir is an SCons.Environment.Dir corresponding to the
5427 # first argument passed to MakeBundle, after any adjustments
5428 # made inside MakeBundle.
5429 #
5430 # appfile is an SCons.Environment.File corresponding to the
5431 # game executable copied into the `.app` directory.
5432 bundledir, appfile = env.MakeBundle(os.path.join(self.user_settings.builddir, f'{self.PROGRAM_NAME}.app'), exe_node,
5433 f'free.{dxxstr}-rebirth', os.path.join(cocoa, 'Info.plist'),
5434 typecode='APPL', creator='DCNT',
5435 icon_file=os.path.join(cocoa, f'{dxxstr}-rebirth.icns'),
5436 resources=[[os.path.join(self.srcdir, s), s] for s in ['English.lproj/InfoPlist.strings']])
5437 if self.user_settings.macos_bundle_libs and not self.user_settings.macos_add_frameworks:
5438 message(self, f'Bundling libraries for {bundledir!s}')
5439 # If the user has set $PATH, use it in preference to the
5440 # built-in SCons path.
5441 dylibenv = env['ENV']
5442 user_environment_path = os.environ.get('PATH')
5443 if user_environment_path:
5444 dylibenv = dylibenv.copy()
5445 dylibenv['PATH'] = user_environment_path
5446 env.Command(target=bundledir.Dir('Contents/libs'),
5447 source=appfile,
5448 action="dylibbundler -od -b -x $SOURCE -d $TARGET",
5449 ENV = dylibenv)
5450 return bundledir
5451
5452 def _macos_sign_and_notarize_bundle(self,dxxstr,bundledir):
5453 if self.user_settings.host_platform != 'darwin' or bundledir is None:
5454 return
5455 env = self.env
5456 compressed_bundle = env.File(os.path.join(self.user_settings.builddir, f'{self.PROGRAM_NAME}.zip'))
5457 if self.user_settings.macos_notarization_keychain_item is not None:
5458 env.Command(target=compressed_bundle,
5459 source=bundledir,
5460 action=[['common/arch/macos/notarize_dxx_bundles.zsh', '--signing-identity', self.user_settings.macos_code_signing_identity, '--notarization-keychain-profile', self.user_settings.macos_notarization_keychain_item, '--binary-name', f'{dxxstr}-rebirth', '--app-bundle-path', '$SOURCE', '--zip-path', '$TARGET']])
5461 elif self.user_settings.macos_notarization_apple_id is not None and self.user_settings.macos_notarization_team_id is not None:
5462 if self.user_settings.macos_notarization_password is None:
5463 env.Command(target=compressed_bundle,
5464 source=bundledir,
5465 action=[['common/arch/macos/notarize_dxx_bundles.zsh', '--signing-identity', self.user_settings.macos_code_signing_identity, '--apple-id', self.user_settings.macos_notarization_apple_id, '--team-id', self.user_settings.macos_notarization_team_id, '--binary-name', f'{dxxstr}-rebirth', '--app-bundle-path', '$SOURCE', '--zip-path', '$TARGET']])
5466 else:
5467 notarization_password_env = env['ENV'].copy()
5468 notarization_password_env['DXX_NOTARIZATION_PASSWORD'] = self.user_settings.macos_notarization_password
5469 env.Command(target=compressed_bundle,
5470 source=bundledir,
5471 action=[['common/arch/macos/notarize_dxx_bundles.zsh', '--signing-identity', self.user_settings.macos_code_signing_identity, '--apple-id', self.user_settings.macos_notarization_apple_id, '--team-id', self.user_settings.macos_notarization_team_id, '--binary-name', f'{dxxstr}-rebirth', '--app-bundle-path', '$SOURCE', '--zip-path', '$TARGET']],
5472 ENV = notarization_password_env)
5473 else:
5474 raise SCons.Errors.StopError('Either macos_notarization_keychain_item or both macos_notarization_apple_id and macos_notarization_team_id must be specified for notarization')
5475
5476 class D1XProgram(DXXProgram):
5477 LazyObjectState = DXXProgram.LazyObjectState
5478 PROGRAM_NAME: typing.Final[str] = 'D1X-Rebirth'
5479 target: typing.Final[str]
5480 srcdir: typing.Final[str] = 'd1x-rebirth'
5481 target = srcdir
5482 shortname: typing.Final[str] = 'd1x'
5483 env_CPPDEFINES: typing.Final[tuple] = ('DXX_BUILD_DESCENT', 1),
5484
5485 # general source files
5486 def get_objects_common(self,
5487 __get_dxx_objects_common=DXXProgram.get_objects_common, \
5488 __get_dsx_objects_common=DXXCommon.create_lazy_object_states_getter((LazyObjectState(sources=(
5489 'd1x-rebirth/main/custom.cpp',
5490 'd1x-rebirth/main/snddecom.cpp',
5491 ),
5492 ),
5493 LazyObjectState(sources=(
5494 # In Descent 1, bmread.cpp is used for both the regular
5495 # build and the editor build.
5496 #
5497 # In Descent 2, bmread.cpp is only used for the editor
5498 # build.
5499 #
5500 # Handle that inconsistency by defining it in the
5501 # per-program lookup (D1XProgram, D2XProgram), not in the
5502 # shared program lookup (DXXProgram).
5503 'similar/main/bmread.cpp',
5504 ),
5505 transform_target=DXXProgram._apply_target_name,
5506 ),
5507 ))
5508 ) -> collections.abc.MutableSequence['StaticObject']:
5509 value = __get_dxx_objects_common(self)
5510 value.extend(__get_dsx_objects_common(self))
5511 return value
5512
5513 # for editor
5514 def get_objects_editor(self,
5515 __get_dxx_objects_editor=DXXProgram.get_objects_editor,
5516 __get_dsx_objects_editor=DXXCommon.create_lazy_object_getter((
5517 'd1x-rebirth/editor/ehostage.cpp',
5518 ),
5519 )) -> collections.abc.MutableSequence['StaticObject']:
5520 value = list(__get_dxx_objects_editor(self))
5521 value.extend(__get_dsx_objects_editor(self))
5522 return value
5523
5524 class D2XProgram(DXXProgram):
5525 LazyObjectState = DXXProgram.LazyObjectState
5526 PROGRAM_NAME: typing.Final[str] = 'D2X-Rebirth'
5527 target: typing.Final[str]
5528 srcdir: typing.Final[str] = 'd2x-rebirth'
5529 target = srcdir
5530 shortname: typing.Final[str] = 'd2x'
5531 env_CPPDEFINES: typing.Final[tuple] = ('DXX_BUILD_DESCENT', 2),
5532
5533 # general source files
5534 def get_objects_common(self,
5535 __get_dxx_objects_common=DXXProgram.get_objects_common, \
5536 __get_dsx_objects_common=DXXCommon.create_lazy_object_getter((
5537 'd2x-rebirth/libmve/decoder8.cpp',
5538 'd2x-rebirth/libmve/decoder16.cpp',
5539 'd2x-rebirth/libmve/mve_audio.cpp',
5540 'd2x-rebirth/libmve/mvelib.cpp',
5541 'd2x-rebirth/libmve/mveplay.cpp',
5542 'd2x-rebirth/main/escort.cpp',
5543 'd2x-rebirth/main/gamepal.cpp',
5544 'd2x-rebirth/main/movie.cpp',
5545 ))) -> collections.abc.MutableSequence['StaticObject']:
5546 value = __get_dxx_objects_common(self)
5547 value.extend(__get_dsx_objects_common(self))
5548 return value
5549
5550 # for editor
5551 def get_objects_editor(self,
5552 __get_dxx_objects_editor=DXXProgram.get_objects_editor, \
5553 __get_dsx_objects_editor=DXXCommon.create_lazy_object_states_getter((LazyObjectState(sources=(
5554 # See comment by D1XProgram reference to bmread.cpp for why
5555 # this is here instead of in the usual handling for similar
5556 # files.
5557 'similar/main/bmread.cpp',
5558 ),
5559 transform_target=DXXProgram._apply_target_name,
5560 ),
5561 ))) -> collections.abc.MutableSequence['StaticObject']:
5562 value = list(__get_dxx_objects_editor(self))
5563 value.extend(__get_dsx_objects_editor(self))
5564 return value
5565
5566 def register_program(program, other_program, variables, filtered_help, append, _itertools_product=itertools.product) -> None:
5567 s = program.shortname
5568 l = [v for (k,v) in ARGLIST if k == s or k == 'dxx'] or (other_program.shortname not in ARGUMENTS,)
5569 # Legacy case: build one configuration.
5570 if len(l) == 1:
5571 try:
5572 if not int(l[0]):
5573 # If the user specifies an integer that evaluates to
5574 # False, this configuration is disabled. This allows
5575 # the user to build only one game, instead of both.
5576 return
5577 # Coerce to an empty string, then reuse the case for stacked
5578 # profiles. This is slightly less efficient, but reduces
5579 # maintenance by not having multiple sites that call
5580 # program().
5581 l = '',
5582 except ValueError:
5583 # If not an integer, treat this as a configuration profile.
5584 pass
5585 seen = set()
5586 add_seen = seen.add
5587 for e in l:
5588 for prefix in _itertools_product(*[v.split('+') for v in e.split(',')]):
5589 duplicates = set()
5590 # This would be simpler if set().add(V) returned the result
5591 # of `V not in self`, as seen before the add. Instead, it
5592 # always returns None.
5593 #
5594 # Test for presence, then add if not present. add() always
5595 # returns None, which coerces to False in boolean context.
5596 # This is slightly inefficient since we know the right hand
5597 # side will always be True after negation, so we ought to be
5598 # able to skip testing its truth value. However, the
5599 # alternative is to use a wrapper function that checks
5600 # membership, adds the value, and returns the result of the
5601 # test. Calling such a function is even less efficient.
5602 #
5603 # In most cases, this loop is not run often enough for the
5604 # efficiency to matter.
5605 prefix = tuple([
5606 p for p in prefix \
5607 if (p not in duplicates and not duplicates.add(p))
5608 ])
5609 if prefix in seen:
5610 continue
5611 add_seen(prefix)
5612 append(program(tuple((f'{s}{p and "_"}{p}' for p in prefix)) + prefix, variables, filtered_help))
5613
5614 def main(register_program,_d1xp=D1XProgram,_d2xp=D2XProgram):
5615 if os.path.isdir('build'):
5616 SConsignFile('build/.sconsign')
5617 variables = Variables([v for k, v in ARGLIST if k == 'site'] or ['site-local.py'], ARGUMENTS)
5618 filtered_help = FilterHelpText()
5619 dxx = []
5620 register_program(_d1xp, _d2xp, variables, filtered_help, dxx.append)
5621 register_program(_d2xp, _d1xp, variables, filtered_help, dxx.append)
5622 substenv = SCons.Environment.SubstitutionEnvironment()
5623 variables.FormatVariableHelpText = filtered_help.FormatVariableHelpText
5624 variables.Update(substenv)
5625 # show some help when running scons -h
5626 Help("""DXX-Rebirth, SConstruct file help:
5627
5628 Type 'scons' to build the binary.
5629 Type 'scons install' to build (if it hasn't been done) and install.
5630 Type 'scons -c' to clean up.
5631
5632 Extra options (add them to command line, like 'scons extraoption=value'):
5633 d1x=[0/1] Disable/enable D1X-Rebirth
5634 d1x=prefix-list Enable D1X-Rebirth with prefix-list modifiers
5635 d2x=[0/1] Disable/enable D2X-Rebirth
5636 d2x=prefix-list Enable D2X-Rebirth with prefix-list modifiers
5637 dxx=VALUE Equivalent to d1x=VALUE d2x=VALUE
5638 """ + \
5639 ''.join([f'{d.program_message_prefix}:\n{d.init_with_decoration(substenv)}' for d in dxx])
5640 )
5641 if not dxx:
5642 return
5643 compilation_database_dict_fn_to_entries = DXXCommon.compilation_database_dict_fn_to_entries
5644 if compilation_database_dict_fn_to_entries:
5645 import json
5646 for fn, entry_tuple in compilation_database_dict_fn_to_entries.items():
5647 env, entries = entry_tuple
5648 e = env.Entry(fn)
5649 # clang tools search for this specific filename. As a
5650 # convenience to the caller, if the target is a directory,
5651 # assume this filename in the named directory. If the
5652 # caller wishes to generate the file under some other name,
5653 # that will be respected, though clang tools may refuse to
5654 # see it.
5655 if e.isdir() or fn.endswith('/'):
5656 e = e.File('compile_commands.json')
5657 # Sort by key so that dictionary ordering changes do not
5658 # cause unnecessary regeneration of the file.
5659 env.Textfile(target=e, source=env.Value(json.dumps(entries, indent=4, sort_keys=True)))
5660
5661 unknown = variables.UnknownVariables()
5662 # Delete known unregistered variables
5663 unknown.pop('d1x', None)
5664 unknown.pop('d2x', None)
5665 unknown.pop('dxx', None)
5666 unknown.pop('site', None)
5667 ignore_unknown_variables = unknown.pop('ignore_unknown_variables', '0')
5668 if unknown:
5669 # Protect user from misspelled options by reporting an error.
5670 # Provide a way for the user to override the check, which might
5671 # be necessary if the user is setting an option that is only
5672 # understood by older (or newer) versions of SConstruct.
5673 try:
5674 ignore_unknown_variables = int(ignore_unknown_variables)
5675 except ValueError:
5676 ignore_unknown_variables = False
5677 j = f'''Unknown values specified on command line.{
5678 ''.join((f"""
5679 {k}""" for k in unknown.keys()))
5680 }'''
5681 if not ignore_unknown_variables:
5682 raise SCons.Errors.StopError(j +
5683 '\nRemove unknown values or set ignore_unknown_variables=1 to continue.')
5684 print(f'''warning: {j}
5685 Build will continue, but these values have no effect.
5686 ''')
5687
5688 main(register_program)
5689
5690 # Local Variables:
5691 # tab-width: 4
5692 # End: