-
Notifications
You must be signed in to change notification settings - Fork 559
/
configure.py
executable file
·3671 lines (2867 loc) · 142 KB
/
configure.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Configuration program for botan
(C) 2009-2020 Jack Lloyd
(C) 2015,2016,2017 Simon Warta (Kullo GmbH)
(C) 2019-2022 René Meusel (neXenio GmbH, Rohde & Schwarz Cybersecurity GmbH)
Botan is released under the Simplified BSD License (see license.txt)
This script is regularly tested with CPython 3.x, and
occasionally tested PyPy 4.
On Jython target detection does not work (use --os and --cpu).
"""
import collections
import copy
import json
import sys
import os
import os.path
import platform
import re
import shlex
import shutil
import subprocess
import traceback
import logging
import time
import errno
import optparse # pylint: disable=deprecated-module
# An error caused by and to be fixed by the user, e.g. invalid command line argument
class UserError(Exception):
pass
# An error caused by bugs in this script or when reading/parsing build data files
# Those are not expected to be fixed by the user of this script
class InternalError(Exception):
pass
def flatten(l):
return sum(l, [])
def normalize_source_path(source):
"""
cmake and some versions of make need this, and nothing else minds
"""
return os.path.normpath(source).replace('\\', '/')
def normalize_source_paths(sources):
return [normalize_source_path(p) for p in sources]
def parse_version_file(version_path):
version_file = open(version_path, encoding='utf8')
key_and_val = re.compile(r"([a-z_]+) = ([a-zA-Z0-9:\-\']+)")
results = {}
for line in version_file.readlines():
if not line or line[0] == '#':
continue
match = key_and_val.match(line)
if match:
key = match.group(1)
val = match.group(2)
if val == 'None':
val = None
elif val.startswith("'") and val.endswith("'"):
val = val[1:len(val)-1]
else:
val = int(val)
results[key] = val
return results
class Version:
"""
Version information are all static members
"""
data = {}
@staticmethod
def get_data():
if not Version.data:
root_dir = os.path.dirname(os.path.realpath(__file__))
Version.data = parse_version_file(os.path.join(root_dir, 'src/build-data/version.txt'))
suffix = Version.data["release_suffix"]
if suffix != "":
suffix_re = re.compile('-(alpha|beta|rc)[0-9]+')
if not suffix_re.match(suffix):
raise Exception("Unexpected version suffix '%s'" % (suffix))
return Version.data
@staticmethod
def major():
return Version.get_data()["release_major"]
@staticmethod
def minor():
return Version.get_data()["release_minor"]
@staticmethod
def patch():
return Version.get_data()["release_patch"]
@staticmethod
def suffix():
return Version.get_data()["release_suffix"]
@staticmethod
def packed():
# Used on macOS for dylib versioning
return Version.major() * 1000 + Version.minor()
@staticmethod
def so_rev():
return Version.get_data()["release_so_abi_rev"]
@staticmethod
def release_type():
return Version.get_data()["release_type"]
@staticmethod
def datestamp():
return Version.get_data()["release_datestamp"]
@staticmethod
def as_string():
return '%d.%d.%d%s' % (Version.major(), Version.minor(), Version.patch(), Version.suffix())
@staticmethod
def vc_rev():
# Lazy load to ensure _local_repo_vc_revision() does not run before logger is set up
if Version.get_data()["release_vc_rev"] is None:
Version.data["release_vc_rev"] = Version._local_repo_vc_revision()
return Version.get_data()["release_vc_rev"]
@staticmethod
def _local_repo_vc_revision():
vc_command = ['git', 'rev-parse', 'HEAD']
cmdname = vc_command[0]
try:
vc = subprocess.Popen(
vc_command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
(stdout, stderr) = vc.communicate()
if vc.returncode != 0:
logging.debug('Error getting rev from %s - %d (%s)',
cmdname, vc.returncode, stderr)
return 'unknown'
rev = str(stdout).strip()
logging.debug('%s reported revision %s', cmdname, rev)
return '%s:%s' % (cmdname, rev)
except OSError as ex:
logging.debug('Error getting rev from %s - %s', cmdname, ex.strerror)
return 'unknown'
class SourcePaths:
"""
A collection of paths defined by the project structure and
independent of user configurations.
All paths are relative to the base_dir, which may be relative as well (e.g. ".")
"""
def __init__(self, base_dir):
self.base_dir = base_dir
self.doc_dir = os.path.join(self.base_dir, 'doc')
self.src_dir = os.path.join(self.base_dir, 'src')
# dirs in src/
self.build_data_dir = os.path.join(self.src_dir, 'build-data')
self.configs_dir = os.path.join(self.src_dir, 'configs')
self.lib_dir = os.path.join(self.src_dir, 'lib')
self.python_dir = os.path.join(self.src_dir, 'python')
self.scripts_dir = os.path.join(self.src_dir, 'scripts')
# subdirs of src/
self.test_data_dir = os.path.join(self.src_dir, 'tests/data')
self.sphinx_config_dir = os.path.join(self.configs_dir, 'sphinx')
class BuildPaths:
"""
Constructor
"""
def __init__(self, source_paths, options, modules):
self.build_dir = os.path.join(options.with_build_dir, 'build')
self.libobj_dir = os.path.join(self.build_dir, 'obj', 'lib')
self.cliobj_dir = os.path.join(self.build_dir, 'obj', 'cli')
self.testobj_dir = os.path.join(self.build_dir, 'obj', 'test')
self.doc_output_dir = os.path.join(self.build_dir, 'docs')
self.handbook_output_dir = os.path.join(self.doc_output_dir, 'handbook')
self.doc_output_dir_doxygen = os.path.join(self.doc_output_dir, 'doxygen') if options.with_doxygen else None
self.doc_module_info = os.path.join(self.build_dir, 'module_info') if options.with_doxygen else None
# We split the header include paths into 'public', 'internal' and 'external'
# to allow for better control over what is exposed to each compilation unit.
# For instance, the examples should only see the public headers, while the
# test suite should see both public and internal headers.
self.include_dir = os.path.join(self.build_dir, 'include')
self.public_include_basedir = os.path.join(self.include_dir, 'public')
self.internal_include_basedir = os.path.join(self.include_dir, 'internal')
self.external_include_dir = os.path.join(self.include_dir, 'external')
self.public_include_dir = os.path.join(self.public_include_basedir, 'botan')
self.internal_include_dir = os.path.join(self.internal_include_basedir, 'botan', 'internal')
self.internal_headers = sorted(flatten([m.internal_headers() for m in modules]))
self.external_headers = sorted(flatten([m.external_headers() for m in modules]))
# this is overwritten if amalgamation is used
self.lib_sources = normalize_source_paths(sorted(flatten([mod.sources() for mod in modules])))
self.public_headers = sorted(flatten([m.public_headers() for m in modules]))
def find_sources_in(basedir, srcdir):
for (dirpath, _, filenames) in os.walk(os.path.join(basedir, srcdir)):
for filename in filenames:
if filename.endswith('.cpp') and not filename.startswith('.'):
yield os.path.join(dirpath, filename)
def find_headers_in(basedir, srcdir):
for (dirpath, _, filenames) in os.walk(os.path.join(basedir, srcdir)):
for filename in filenames:
if filename.endswith('.h') and not filename.startswith('.'):
yield os.path.join(dirpath, filename)
self.cli_sources = normalize_source_paths(find_sources_in(source_paths.src_dir, 'cli'))
self.cli_headers = normalize_source_paths(find_headers_in(source_paths.src_dir, 'cli'))
self.test_sources = normalize_source_paths(find_sources_in(source_paths.src_dir, 'tests'))
if 'examples' in options.build_targets:
self.example_sources = normalize_source_paths(find_sources_in(source_paths.src_dir, 'examples'))
self.example_output_dir = os.path.join(self.build_dir, 'examples')
self.example_obj_dir = os.path.join(self.build_dir, 'obj', 'examples')
else:
self.example_sources = None
self.example_output_dir = None
self.example_obj_dir = None
if options.build_fuzzers:
self.fuzzer_sources = list(find_sources_in(source_paths.src_dir, 'fuzzer'))
self.fuzzer_output_dir = os.path.join(self.build_dir, 'fuzzer')
self.fuzzobj_dir = os.path.join(self.build_dir, 'obj', 'fuzzer')
else:
self.fuzzer_sources = None
self.fuzzer_output_dir = None
self.fuzzobj_dir = None
def build_dirs(self):
out = [
self.libobj_dir,
self.cliobj_dir,
self.testobj_dir,
self.public_include_dir,
self.internal_include_dir,
self.external_include_dir,
self.handbook_output_dir,
]
if self.doc_output_dir_doxygen:
out += [self.doc_output_dir_doxygen, self.doc_module_info]
if self.fuzzer_output_dir:
out += [self.fuzzobj_dir, self.fuzzer_output_dir]
if self.example_output_dir:
out += [self.example_obj_dir, self.example_output_dir]
return out
def format_public_include_flags(self, cc):
return cc.add_include_dir_option + ' ' + normalize_source_path(self.public_include_basedir)
def format_internal_include_flags(self, cc):
return cc.add_include_dir_option + ' ' + normalize_source_path(self.internal_include_basedir)
def format_external_include_flags(self, cc, external_includes):
dash_isystem = cc.add_system_include_dir_option
output = ''
if self.external_headers:
output += ' ' + dash_isystem + ' ' + normalize_source_path(self.external_include_dir)
for external_include in external_includes:
output += ' ' + dash_isystem + ' ' + normalize_source_path(external_include)
return output
def src_info(self, typ):
if typ == 'lib':
return (self.lib_sources, self.libobj_dir)
if typ == 'cli':
return (self.cli_sources, self.cliobj_dir)
if typ == 'test':
return (self.test_sources, self.testobj_dir)
if typ == 'fuzzer':
return (self.fuzzer_sources, self.fuzzobj_dir)
if typ == 'examples':
return (self.example_sources, self.example_obj_dir)
raise InternalError("Unknown src info type '%s'" % (typ))
ACCEPTABLE_BUILD_TARGETS = ["static", "shared", "cli", "tests", "bogo_shim", "examples", "ct_selftest"]
def process_command_line(args):
"""
Handle command line options
Do not use logging in this method as command line options need to be
available before logging is setup.
"""
def define_option_pair(group, verb, nverb, what, default, msg=optparse.SUPPRESS_HELP):
dest = '%s_%s' % (verb, what.replace('-', '_'))
# always show the help for the option that switches away from the default
with_help = msg if not default else optparse.SUPPRESS_HELP
without_help = msg if default else optparse.SUPPRESS_HELP
group.add_option('--%s-%s' % (verb, what),
dest=dest,
action='store_true',
default=default,
help=with_help)
group.add_option('--%s-%s' % (nverb, what),
dest=dest,
action='store_false',
help=without_help)
def add_with_without_pair(group, what, default, msg=optparse.SUPPRESS_HELP):
define_option_pair(group, 'with', 'without', what, default, msg)
def add_enable_disable_pair(group, what, default, msg=optparse.SUPPRESS_HELP):
define_option_pair(group, 'enable', 'disable', what, default, msg)
parser = optparse.OptionParser(
formatter=optparse.IndentedHelpFormatter(max_help_position=50),
version=Version.as_string())
parser.add_option('--verbose', action='store_true', default=False,
help='Show debug messages')
parser.add_option('--quiet', action='store_true', default=False,
help='Show only warnings and errors')
target_group = optparse.OptionGroup(parser, 'Target options')
target_group.add_option('--cpu', help='set the target CPU architecture')
target_group.add_option('--os', help='set the target operating system')
target_group.add_option('--cc', dest='compiler', help='set the desired build compiler')
target_group.add_option('--cc-min-version', dest='cc_min_version', default=None,
metavar='MAJOR.MINOR',
help='Set the minimal version of the target compiler. ' \
'Use --cc-min-version=0.0 to support all compiler versions. ' \
'Default is auto detection.')
target_group.add_option('--cc-bin', dest='compiler_binary', metavar='BINARY',
help='set path to compiler binary')
target_group.add_option('--cc-abi-flags', metavar='FLAGS', default='',
help='set compiler ABI flags')
target_group.add_option('--cxxflags', metavar='FLAGS', default=None,
help='override all compiler flags')
target_group.add_option('--extra-cxxflags', metavar='FLAGS', default=[], action='append',
help='set extra compiler flags')
target_group.add_option('--ldflags', metavar='FLAGS',
help='set linker flags', default=None)
target_group.add_option('--extra-libs', metavar='LIBS',
help='specify extra libraries to link against', default='')
target_group.add_option('--ar-command', dest='ar_command', metavar='AR', default=None,
help='set path to static archive creator')
target_group.add_option('--ar-options', dest='ar_options', metavar='AR_OPTIONS', default=None,
help='set options for ar')
target_group.add_option('--msvc-runtime', metavar='RT', default=None,
help='specify MSVC runtime (MT, MD, MTd, MDd)')
target_group.add_option('--compiler-cache',
help='specify a compiler cache to use')
target_group.add_option('--with-endian', metavar='ORDER', default=None,
help='override byte order guess')
target_group.add_option('--with-os-features', action='append', metavar='FEAT',
help='specify OS features to use')
target_group.add_option('--without-os-features', action='append', metavar='FEAT',
help='specify OS features to disable')
add_with_without_pair(target_group, 'compilation-database', True, 'disable compile_commands.json')
isa_extensions = [
'SSE2', 'SSSE3', 'SSE4.1', 'SSE4.2', 'AVX2', 'BMI2', 'RDRAND', 'RDSEED',
'AES-NI', 'SHA-NI',
'AltiVec', 'NEON', 'ARMv8 Crypto', 'POWER Crypto']
for isa_extn_name in isa_extensions:
isa_extn = isa_extn_name.lower().replace(' ', '')
target_group.add_option('--disable-%s' % (isa_extn),
help='disable %s intrinsics' % (isa_extn_name),
action='append_const',
const=isa_extn.replace('-', '').replace('.', '').replace(' ', ''),
dest='disable_intrinsics')
build_group = optparse.OptionGroup(parser, 'Build options')
build_group.add_option('--system-cert-bundle', metavar='PATH', default=None,
help='set path to trusted CA bundle')
add_with_without_pair(build_group, 'debug-info', False, 'include debug symbols')
add_with_without_pair(build_group, 'sanitizers', False, 'enable ASan/UBSan checks')
add_enable_disable_pair(build_group, 'asm', True, 'disable inline assembly')
build_group.add_option('--enable-sanitizers', metavar='SAN', default='',
help='enable specific sanitizers')
add_with_without_pair(build_group, 'stack-protector', True, 'disable stack smashing protections')
add_with_without_pair(build_group, 'coverage-info', False, 'add coverage info')
build_group.add_option('--enable-shared-library', dest='build_shared_lib',
action='store_true', default=None,
help=optparse.SUPPRESS_HELP)
build_group.add_option('--disable-shared-library', dest='build_shared_lib',
action='store_false',
help='disable building shared library')
build_group.add_option('--enable-static-library', dest='build_static_lib',
action='store_true', default=None,
help=optparse.SUPPRESS_HELP)
build_group.add_option('--disable-static-library', dest='build_static_lib',
action='store_false',
help='disable building static library')
build_group.add_option('--optimize-for-size', dest='optimize_for_size',
action='store_true', default=False,
help='optimize for code size')
build_group.add_option('--no-optimizations', dest='no_optimizations',
action='store_true', default=False,
help='disable all optimizations (for debugging)')
build_group.add_option('--debug-mode', action='store_true', default=False, dest='debug_mode',
help='enable debug info, disable optimizations')
build_group.add_option('--amalgamation', dest='amalgamation',
default=False, action='store_true',
help='use amalgamation to build')
build_group.add_option('--name-amalgamation', metavar='NAME', default='botan_all',
help='specify alternate name for amalgamation files')
build_group.add_option('--with-build-dir', metavar='DIR', default='',
help='setup the build in DIR')
build_group.add_option('--with-external-includedir', metavar='DIR', default=[],
help='use DIR for external includes', action='append')
build_group.add_option('--with-external-libdir', metavar='DIR', default=[],
help='use DIR for external libs', action='append')
build_group.add_option('--define-build-macro', metavar='DEFINE', default=[],
help='set compile-time pre-processor definition like KEY[=VALUE]', action='append')
build_group.add_option('--with-sysroot-dir', metavar='DIR', default='',
help='use DIR for system root while cross-compiling')
link_methods = ['symlink', 'hardlink', 'copy']
build_group.add_option('--link-method', default=None, metavar='METHOD',
choices=link_methods,
help='choose how links to include headers are created (%s)' % ', '.join(link_methods))
build_group.add_option('--with-local-config',
dest='local_config', metavar='FILE',
help='include the contents of FILE into build.h')
build_group.add_option('--distribution-info', metavar='STRING',
help='distribution specific version',
default='unspecified')
build_group.add_option('--maintainer-mode', dest='maintainer_mode',
action='store_true', default=False,
help=optparse.SUPPRESS_HELP)
build_group.add_option('--werror-mode', dest='werror_mode',
action='store_true', default=False,
help="Prohibit compiler warnings")
build_group.add_option('--no-store-vc-rev', action='store_true', default=False,
help=optparse.SUPPRESS_HELP)
build_group.add_option('--no-install-python-module', action='store_true', default=False,
help='skip installing Python module')
build_group.add_option('--with-python-versions', dest='python_version',
metavar='N.M',
default='%d.%d' % (sys.version_info[0], sys.version_info[1]),
help='where to install botan2.py (def %default)')
build_group.add_option('--disable-cc-tests', dest='enable_cc_tests',
default=True, action='store_false',
help=optparse.SUPPRESS_HELP)
add_with_without_pair(build_group, 'valgrind', False, 'use valgrind API')
build_group.add_option('--unsafe-fuzzer-mode', action='store_true', default=False,
help=optparse.SUPPRESS_HELP)
build_group.add_option('--build-fuzzers', dest='build_fuzzers',
metavar='TYPE', default=None,
help='Build fuzzers (afl, libfuzzer, klee, test)')
build_group.add_option('--with-fuzzer-lib', metavar='LIB', default=None, dest='fuzzer_lib',
help='additionally link in LIB')
add_with_without_pair(build_group, 'debug-asserts', default=False)
build_group.add_option('--unsafe-terminate-on-asserts', action='store_true', default=False,
help=optparse.SUPPRESS_HELP)
build_group.add_option('--build-targets', default=None, dest="build_targets", action='append',
help="build specific targets and tools (%s)" % ', '.join(ACCEPTABLE_BUILD_TARGETS))
build_group.add_option('--build-tool', default='make',
help="specify the build tool (make, ninja)")
add_with_without_pair(build_group, 'pkg-config', default=None)
add_with_without_pair(build_group, 'cmake-config', default=True)
docs_group = optparse.OptionGroup(parser, 'Documentation Options')
add_with_without_pair(docs_group, 'documentation', True, 'skip building/installing documentation')
add_with_without_pair(docs_group, 'sphinx', None, 'run Sphinx to generate docs')
add_with_without_pair(docs_group, 'pdf', False, 'run Sphinx to generate PDF doc')
add_with_without_pair(docs_group, 'rst2man', None, 'run rst2man to generate man page')
add_with_without_pair(docs_group, 'doxygen', False, 'run Doxygen')
mods_group = optparse.OptionGroup(parser, 'Module selection')
mods_group.add_option('--module-policy', dest='module_policy',
help="module policy file (see src/build-data/policy)",
metavar='POL', default=None)
mods_group.add_option('--enable-modules', dest='enabled_modules',
metavar='MODS', action='append',
help='enable specific modules')
mods_group.add_option('--disable-modules', dest='disabled_modules',
metavar='MODS', action='append',
help='disable specific modules')
mods_group.add_option('--no-autoload', action='store_true', default=False,
help=optparse.SUPPRESS_HELP)
mods_group.add_option('--minimized-build', action='store_true', dest='no_autoload',
help='minimize build')
add_enable_disable_pair(mods_group, 'experimental-features', False,
'enable building of experimental features and modules')
add_enable_disable_pair(mods_group, 'deprecated-features', True,
'disable building of deprecated features and modules')
# Should be derived from info.txt but this runs too early
third_party = ['boost', 'bzip2', 'lzma', 'commoncrypto', 'sqlite3', 'zlib', 'tpm']
for mod in third_party:
mods_group.add_option('--with-%s' % (mod),
help=('use %s' % (mod)) if mod in third_party else optparse.SUPPRESS_HELP,
action='append_const',
const=mod,
dest='enabled_modules')
mods_group.add_option('--without-%s' % (mod),
help=optparse.SUPPRESS_HELP,
action='append_const',
const=mod,
dest='disabled_modules')
install_group = optparse.OptionGroup(parser, 'Installation options')
install_group.add_option('--program-suffix', metavar='SUFFIX',
help='append string to program names')
install_group.add_option('--library-suffix', metavar='SUFFIX', default='',
help='append string to library names')
install_group.add_option('--prefix', metavar='DIR',
help='set the install prefix')
install_group.add_option('--docdir', metavar='DIR',
help='set the doc install dir')
install_group.add_option('--bindir', metavar='DIR',
help='set the binary install dir')
install_group.add_option('--libdir', metavar='DIR',
help='set the library install dir')
install_group.add_option('--mandir', metavar='DIR',
help='set the install dir for man pages')
install_group.add_option('--includedir', metavar='DIR',
help='set the include file install dir')
info_group = optparse.OptionGroup(parser, 'Informational')
info_group.add_option('--list-modules', dest='list_modules',
action='store_true',
help='list available modules and exit')
info_group.add_option('--list-os-features', dest='list_os_features',
action='store_true',
help='list available OS features and exit')
parser.add_option_group(target_group)
parser.add_option_group(build_group)
parser.add_option_group(docs_group)
parser.add_option_group(mods_group)
parser.add_option_group(install_group)
parser.add_option_group(info_group)
# These exist only for autoconf compatibility (requested by zw for mtn)
compat_with_autoconf_options = [
'datadir',
'datarootdir',
'dvidir',
'exec-prefix',
'htmldir',
'infodir',
'libexecdir',
'localedir',
'localstatedir',
'oldincludedir',
'pdfdir',
'psdir',
'sbindir',
'sharedstatedir',
'sysconfdir'
]
for opt in compat_with_autoconf_options:
parser.add_option('--' + opt, help=optparse.SUPPRESS_HELP)
(options, args) = parser.parse_args(args)
if args != []:
raise UserError('Unhandled option(s): ' + ' '.join(args))
if options.with_endian not in [None, 'little', 'big']:
raise UserError('Bad value to --with-endian "%s"' % (options.with_endian))
if options.debug_mode:
options.no_optimizations = True
options.with_debug_info = True
def parse_multiple_enable(modules):
if modules is None:
return []
return sorted({m for m in flatten([s.split(',') for s in modules]) if m != ''})
options.enabled_modules = parse_multiple_enable(options.enabled_modules)
options.disabled_modules = parse_multiple_enable(options.disabled_modules)
options.with_os_features = parse_multiple_enable(options.with_os_features)
options.without_os_features = parse_multiple_enable(options.without_os_features)
options.disable_intrinsics = parse_multiple_enable(options.disable_intrinsics)
return options
def take_options_from_env(options):
# Take some values from environment, if not set on command line
def update_from_env(val, var, name):
if val is None:
val = os.getenv(var)
if val is not None:
logging.info('Implicit --%s=%s due to environment variable %s', name, val, var)
return val
if os.getenv('CXX') and options.compiler_binary is None and options.compiler is not None:
logging.info('CXX environment variable is set which will override compiler path')
options.ar_command = update_from_env(options.ar_command, 'AR', 'ar-command')
options.ar_options = update_from_env(options.ar_options, 'AR_OPTIONS', 'ar-options')
options.compiler_binary = update_from_env(options.compiler_binary, 'CXX', 'cc-bin')
options.cxxflags = update_from_env(options.cxxflags, 'CXXFLAGS', 'cxxflags')
options.ldflags = update_from_env(options.ldflags, 'LDFLAGS', 'ldflags')
class LexResult:
pass
class LexerError(InternalError):
def __init__(self, msg, lexfile, line):
super().__init__(msg)
self.msg = msg
self.lexfile = lexfile
self.line = line
def __str__(self):
return '%s at %s:%d' % (self.msg, self.lexfile, self.line)
def parse_lex_dict(as_list, map_name, infofile):
if len(as_list) % 3 != 0:
raise InternalError("Lex dictionary has invalid format (input not divisible by 3): %s" % as_list)
result = {}
for key, sep, value in [as_list[3*i:3*i+3] for i in range(0, len(as_list)//3)]:
if sep != '->':
raise InternalError("Map %s in %s has invalid format" % (map_name, infofile))
if key in result:
raise InternalError("Duplicate map entry %s in map %s file %s" % (key, map_name, infofile))
result[key] = value
return result
def lex_me_harder(infofile, allowed_groups, allowed_maps, name_val_pairs):
"""
Generic lexer function for info.txt and src/build-data files
"""
out = LexResult()
# Format as a nameable Python variable
def py_var(group):
return group.replace(':', '_')
lexer = shlex.shlex(open(infofile, encoding='utf8'), infofile, posix=True)
lexer.wordchars += '=:.<>/,-!?+*' # handle various funky chars in info.txt
groups = allowed_groups + allowed_maps
for group in groups:
out.__dict__[py_var(group)] = []
for (key, val) in name_val_pairs.items():
out.__dict__[key] = val
def lexed_tokens(): # Convert to an iterator
while True:
token = lexer.get_token()
if token != lexer.eof:
yield token
else:
return
for token in lexed_tokens():
match = re.match('<(.*)>', token)
# Check for a grouping
if match is not None:
group = match.group(1)
if group not in groups:
raise LexerError('Unknown group "%s"' % (group),
infofile, lexer.lineno)
end_marker = '</' + group + '>'
token = lexer.get_token()
while token != end_marker:
out.__dict__[py_var(group)].append(token)
token = lexer.get_token()
if token is None:
raise LexerError('Group "%s" not terminated' % (group),
infofile, lexer.lineno)
elif token in name_val_pairs.keys():
if isinstance(out.__dict__[token], list):
out.__dict__[token].append(lexer.get_token())
else:
out.__dict__[token] = lexer.get_token()
else: # No match -> error
raise LexerError('Bad token "%s"' % (token), infofile, lexer.lineno)
for group in allowed_maps:
out.__dict__[group] = parse_lex_dict(out.__dict__[group], group, infofile)
return out
class InfoObject:
def __init__(self, infofile):
"""
Constructor sets members `infofile`, `lives_in`, `parent_module` and `basename`
"""
self.infofile = infofile
(dirname, basename) = os.path.split(infofile)
self.lives_in = dirname
if basename == 'info.txt':
(next_dir, self.basename) = os.path.split(dirname)
self.parent_module = None
obj_dir = ''
while next_dir != obj_dir:
obj_dir = next_dir
if os.access(os.path.join(obj_dir, 'info.txt'), os.R_OK):
self.parent_module = os.path.basename(obj_dir)
break
(next_dir, _) = os.path.split(obj_dir)
if os.path.basename(next_dir) == 'src':
break
else:
self.basename = basename.replace('.txt', '')
class ModuleInfo(InfoObject):
"""
Represents the information about a particular module
"""
def __init__(self, infofile):
super().__init__(infofile)
lex = lex_me_harder(
infofile,
['header:internal', 'header:public', 'header:external', 'requires',
'os_features', 'arch', 'isa', 'cc', 'comment', 'warning'],
['defines', 'libs', 'frameworks', 'module_info'],
{
'load_on': 'auto',
'endian': 'any',
})
def check_header_duplicates(header_list_public, header_list_internal):
pub_header = set(header_list_public)
int_header = set(header_list_internal)
if not pub_header.isdisjoint(int_header):
logging.error("Module %s has same header in public and internal sections",
self.infofile)
check_header_duplicates(lex.header_public, lex.header_internal)
all_source_files = []
all_header_files = []
for fspath in os.listdir(self.lives_in):
if fspath.endswith('.cpp'):
all_source_files.append(fspath)
elif fspath.endswith('.h'):
all_header_files.append(fspath)
self.source = all_source_files
# If not entry for the headers, all are assumed internal
if lex.header_internal == [] and lex.header_public == []:
self.header_public = []
self.header_internal = list(all_header_files)
else:
self.header_public = lex.header_public
self.header_internal = lex.header_internal
self.header_external = lex.header_external
def convert_lib_list(libs):
out = {}
for (os_name, lib_list) in libs.items():
out[os_name] = lib_list.split(',')
return out
def combine_lines(c):
return ' '.join(c) if c else None
# Convert remaining lex result to members
self.arch = lex.arch
self.cc = lex.cc
self.comment = combine_lines(lex.comment)
self._defines = lex.defines
self._validate_defines_content(self._defines)
self.frameworks = convert_lib_list(lex.frameworks)
self.libs = convert_lib_list(lex.libs)
self.load_on = lex.load_on
self.isa = lex.isa
self.os_features = lex.os_features
self.requires = lex.requires
self.warning = combine_lines(lex.warning)
self.endian = lex.endian
self._parse_module_info(lex)
# Modify members
self.source = [normalize_source_path(os.path.join(self.lives_in, s)) for s in self.source]
self.header_internal = [os.path.join(self.lives_in, s) for s in self.header_internal]
self.header_public = [os.path.join(self.lives_in, s) for s in self.header_public]
self.header_external = [os.path.join(self.lives_in, s) for s in self.header_external]
# Filesystem read access check
for src in self.source + self.header_internal + self.header_public + self.header_external:
if not os.access(src, os.R_OK):
logging.error("Missing file %s in %s", src, infofile)
# Check for duplicates
def intersect_check(type_a, list_a, type_b, list_b):
intersection = set.intersection(set(list_a), set(list_b))
if intersection:
logging.error('Headers %s marked both %s and %s', ' '.join(intersection), type_a, type_b)
intersect_check('public', self.header_public, 'internal', self.header_internal)
intersect_check('public', self.header_public, 'external', self.header_external)
intersect_check('external', self.header_external, 'internal', self.header_internal)
# Check module type constraints
source_file_count = len(all_source_files) + len(all_header_files)
if self.is_virtual() and source_file_count > 0:
logging.error("Module '%s' is virtual but contains %d source code files", self.basename, source_file_count)
def _parse_module_info(self, lex):
info = lex.module_info
if "name" not in info:
raise InternalError("Module '%s' does not contain a <module_info> section with at least a documentation-friendly 'name' definition" % self.basename)
self.name = info["name"]
self.brief = info.get("brief") # possibly None
self.type = info.get("type") or "Public"
self.lifecycle = info.get("lifecycle") or "Stable"
if self.type not in ["Public", "Internal", "Virtual"]:
raise InternalError("Module '%s' has an unknown type: %s" % (self.basename, self.type))
if self.lifecycle not in ["Stable", "Experimental", "Deprecated"]:
raise InternalError("Module '%s' has an unknown lifecycle status: %s" % (self.basename, self.lifecycle))
@staticmethod
def _validate_defines_content(defines):
for key, value in defines.items():
if not re.match('^[0-9A-Za-z_]{3,30}$', key):
raise InternalError('Module defines key has invalid format: "%s"' % key)
if not re.match('^20[0-9]{6}$', value):
raise InternalError('Module defines value has invalid format: "%s" (should be YYYYMMDD)' % value)
year = int(value[0:4])
month = int(value[4:6])
day = int(value[6:])
if year < 2013 or month == 0 or month > 12 or day == 0 or day > 31:
raise InternalError('Module defines value has invalid format: "%s" (should be YYYYMMDD)' % value)
def cross_check(self, arch_info, cc_info, all_os_features, all_isa_extn):
for feat in set(flatten([o.split(',') for o in self.os_features])):
if feat not in all_os_features:
logging.error("Module %s uses an OS feature (%s) which no OS supports", self.infofile, feat)
for supp_cc in self.cc:
if supp_cc not in cc_info:
if supp_cc.startswith('!') and supp_cc[1:] in cc_info:
continue
colon_idx = supp_cc.find(':')
# a versioned compiler dependency
if colon_idx > 0 and supp_cc[0:colon_idx] in cc_info:
pass
else:
raise InternalError('Module %s mentions unknown compiler %s' % (self.infofile, supp_cc))
for supp_arch in self.arch:
if supp_arch not in arch_info:
raise InternalError('Module %s mentions unknown arch %s' % (self.infofile, supp_arch))
def known_isa(isa):
if isa in all_isa_extn:
return True
compound_isa = isa.split(':')
if len(compound_isa) == 2 and compound_isa[0] in arch_info and compound_isa[1] in all_isa_extn:
return True
return False
for isa in self.isa:
if not known_isa(isa):
raise InternalError('Module %s uses unknown ISA extension %s' % (self.infofile, isa))
def sources(self):
return self.source
def public_headers(self):
return self.header_public
def internal_headers(self):
return self.header_internal
def external_headers(self):
return self.header_external
def isas_needed(self, arch):
isas = []
for isa in self.isa: