-
Notifications
You must be signed in to change notification settings - Fork 0
/
configure.py
executable file
·3470 lines (2705 loc) · 132 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 python
"""
Configuration program for botan
(C) 2009-2020 Jack Lloyd
(C) 2015,2016,2017 Simon Warta (Kullo GmbH)
Botan is released under the Simplified BSD License (see license.txt)
This script is regularly tested with CPython 2.7 and 3.5, and
occasionally tested with CPython 2.6 and PyPy 4.
Support for CPython 2.6 will be dropped eventually, but is kept up for as
long as reasonably convenient.
CPython 2.5 and earlier are not supported.
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 needs this, and nothing else minds
"""
return os.path.normpath(source).replace('\\', '/')
def parse_version_file(version_path):
version_file = open(version_path)
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(object):
"""
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 e:
logging.debug('Error getting rev from %s - %s', cmdname, e.strerror)
return 'unknown'
class SourcePaths(object):
"""
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(object): # pylint: disable=too-many-instance-attributes
"""
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.include_dir = os.path.join(self.build_dir, 'include')
self.botan_include_dir = os.path.join(self.include_dir, 'botan')
self.internal_include_dir = os.path.join(self.botan_include_dir, 'internal')
self.external_include_dir = os.path.join(self.include_dir, 'external')
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_path(s) for s in 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_path(s) for s in find_sources_in(source_paths.src_dir, 'cli')]
self.cli_headers = [normalize_source_path(s) for s in find_headers_in(source_paths.src_dir, 'cli')]
self.test_sources = [normalize_source_path(s) for s in find_sources_in(source_paths.src_dir, 'tests')]
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.botan_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]
if self.fuzzer_output_dir:
out += [self.fuzzobj_dir]
out += [self.fuzzer_output_dir]
return out
def format_include_paths(self, cc, external_includes):
dash_i = cc.add_include_dir_option
output = dash_i + self.include_dir
if self.external_headers:
output += ' ' + dash_i + self.external_include_dir
for external_include in external_includes:
output += ' ' + dash_i + external_include
return output
def src_info(self, typ):
if typ == 'lib':
return (self.lib_sources, self.libobj_dir)
elif typ == 'cli':
return (self.cli_sources, self.cliobj_dir)
elif typ == 'test':
return (self.test_sources, self.testobj_dir)
elif typ == 'fuzzer':
return (self.fuzzer_sources, self.fuzzobj_dir)
else:
raise InternalError("Unknown src info type '%s'" % (typ))
ACCEPTABLE_BUILD_TARGETS = ["static", "shared", "cli", "tests", "bogo_shim"]
def process_command_line(args): # pylint: disable=too-many-locals,too-many-statements
"""
Handle command line options
Do not use logging in this method as command line options need to be
available before logging is setup.
"""
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')
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')
build_group.add_option('--with-debug-info', action='store_true', default=False, dest='with_debug_info',
help='include debug symbols')
build_group.add_option('--with-sanitizers', action='store_true', default=False, dest='with_sanitizers',
help='enable ASan/UBSan checks')
build_group.add_option('--enable-sanitizers', metavar='SAN', default='',
help='enable specific sanitizers')
build_group.add_option('--with-stack-protector', dest='with_stack_protector',
action='store_false', default=None, help=optparse.SUPPRESS_HELP)
build_group.add_option('--without-stack-protector', dest='with_stack_protector',
action='store_false', help='disable stack smashing protections')
build_group.add_option('--with-coverage', action='store_true', default=False, dest='with_coverage',
help='add coverage info and disable opts')
build_group.add_option('--with-coverage-info', action='store_true', default=False, dest='with_coverage_info',
help='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)
build_group.add_option('--with-valgrind', help='use valgrind API',
dest='with_valgrind', action='store_true', default=False)
# Cmake option is hidden as it should not be used by end users
build_group.add_option('--with-cmake', action='store_true',
default=False, help=optparse.SUPPRESS_HELP)
build_group.add_option('--unsafe-fuzzer-mode', action='store_true', default=False,
help='Disable essential checks for testing')
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')
build_group.add_option('--test-mode', action='store_true', default=False,
help=optparse.SUPPRESS_HELP)
build_group.add_option('--with-debug-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('--with-pkg-config', action='store_true', default=None,
help=optparse.SUPPRESS_HELP)
build_group.add_option('--without-pkg-config', dest='with_pkg_config', action='store_false',
help=optparse.SUPPRESS_HELP)
build_group.add_option('--boost-library-name', dest='boost_libnames', default=[],
help="file name of some boost library to link", action='append')
docs_group = optparse.OptionGroup(parser, 'Documentation Options')
docs_group.add_option('--with-documentation', action='store_true',
help=optparse.SUPPRESS_HELP)
docs_group.add_option('--without-documentation', action='store_false',
default=True, dest='with_documentation',
help='Skip building/installing documentation')
docs_group.add_option('--with-sphinx', action='store_true',
default=None, help='Use Sphinx')
docs_group.add_option('--without-sphinx', action='store_false',
dest='with_sphinx', help=optparse.SUPPRESS_HELP)
docs_group.add_option('--with-pdf', action='store_true',
default=False, help='Use Sphinx to generate PDF doc')
docs_group.add_option('--without-pdf', action='store_false',
dest='with_pdf', help=optparse.SUPPRESS_HELP)
docs_group.add_option('--with-rst2man', action='store_true',
default=None, help='Use rst2man to generate man page')
docs_group.add_option('--without-rst2man', action='store_false',
dest='with_rst2man', help=optparse.SUPPRESS_HELP)
docs_group.add_option('--with-doxygen', action='store_true',
default=False, help='Use Doxygen')
docs_group.add_option('--without-doxygen', action='store_false',
dest='with_doxygen', help=optparse.SUPPRESS_HELP)
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')
# 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')
mods_group.add_option('--with-everything', help=optparse.SUPPRESS_HELP,
action='store_true', default=False)
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
if options.with_coverage:
options.with_coverage_info = True
options.no_optimizations = 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(object):
pass
class LexerError(InternalError):
def __init__(self, msg, lexfile, line):
super(LexerError, self).__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), 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(object):
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':
(obj_dir, self.basename) = os.path.split(dirname)
if os.access(os.path.join(obj_dir, 'info.txt'), os.R_OK):
self.parent_module = os.path.basename(obj_dir)
else:
self.parent_module = None
else:
self.basename = basename.replace('.txt', '')
class ModuleInfo(InfoObject):
"""
Represents the information about a particular module
"""
def __init__(self, infofile):
# pylint: disable=too-many-statements
super(ModuleInfo, self).__init__(infofile)
lex = lex_me_harder(
infofile,
['header:internal', 'header:public', 'header:external', 'requires',
'os_features', 'arch', 'isa', 'cc', 'comment', 'warning'],
['defines', 'libs', 'frameworks'],
{
'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
# 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)
@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:
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:
if isa.find(':') == -1:
isas.append(isa)
elif isa.startswith(arch + ':'):
isas.append(isa[len(arch)+1:])
return isas
def defines(self):
return [(key + ' ' + value) for key, value in self._defines.items()]
def compatible_cpu(self, archinfo, options):
arch_name = archinfo.basename
cpu_name = options.arch
if self.endian != 'any':
if self.endian != options.with_endian:
return False
for isa in self.isa:
if isa.find(':') > 0:
(arch, isa) = isa.split(':')
if arch != arch_name:
continue
if isa in options.disable_intrinsics:
return False # explicitly disabled
if isa not in archinfo.isa_extensions:
return False
if self.arch != []:
if arch_name not in self.arch and cpu_name not in self.arch:
return False
return True
def compatible_os(self, os_data, options):
if not self.os_features:
return True
def has_all(needed, provided):
for n in needed: