-
Notifications
You must be signed in to change notification settings - Fork 21
/
wscript
1755 lines (1491 loc) · 69.4 KB
/
wscript
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
## -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
# python lib modules
from __future__ import print_function
import sys
import shutil
import types
import optparse
import os.path
import re
import shlex
import subprocess
import textwrap
import fileinput
import glob
from utils import read_config_file
# WAF modules
from waflib import Utils, Scripting, Configure, Build, Options, TaskGen, Context, Task, Logs, Errors
from waflib.Errors import WafError
# local modules
import wutils
# By default, all modules will be enabled, examples will be disabled,
# and tests will be disabled.
modules_enabled = ['all_modules']
examples_enabled = False
tests_enabled = False
# GCC minimum version requirements for C++11 support
gcc_min_version = (4, 9, 2)
# Bug 2181: clang warnings about unused local typedefs and potentially
# evaluated expressions affecting darwin clang/LLVM version 7.0.0 (Xcode 7)
# or clang/LLVM version 3.6 or greater. We must make this platform-specific.
darwin_clang_version_warn_unused_local_typedefs = (7, 0, 0)
darwin_clang_version_warn_potentially_evaluated = (7, 0, 0)
clang_version_warn_unused_local_typedefs = (3, 6, 0)
clang_version_warn_potentially_evaluated = (3, 6, 0)
# Get the information out of the NS-3 configuration file.
config_file_exists = False
(config_file_exists, modules_enabled, examples_enabled, tests_enabled) = read_config_file()
sys.path.insert(0, os.path.abspath('waf-tools'))
try:
import cflags # override the build profiles from waf
finally:
sys.path.pop(0)
cflags.profiles = {
# profile name: [optimization_level, warnings_level, debug_level]
'debug': [0, 2, 3],
'optimized': [3, 2, 1],
'release': [3, 2, 0],
}
cflags.default_profile = 'debug'
Configure.autoconfig = 0
# the following two variables are used by the target "waf dist"
with open("VERSION", "rt") as f:
VERSION = f.read().strip()
APPNAME = 'ns'
wutils.VERSION = VERSION
wutils.APPNAME = APPNAME
# we don't use VNUM anymore (see bug #1327 for details)
wutils.VNUM = None
# these variables are mandatory ('/' are converted automatically)
top = '.'
out = 'build'
def load_env():
bld_cls = getattr(Utils.g_module, 'build_context', Utils.Context)
bld_ctx = bld_cls()
bld_ctx.load_dirs(os.path.abspath(os.path.join (srcdir,'..')),
os.path.abspath(os.path.join (srcdir,'..', blddir)))
bld_ctx.load_envs()
env = bld_ctx.get_env()
return env
def get_files(base_dir):
retval = []
reference=os.path.dirname(base_dir)
for root, dirs, files in os.walk(base_dir):
if root.find('.hg') != -1:
continue
for file in files:
if file.find('.hg') != -1:
continue
fullname = os.path.join(root,file)
# we can't use os.path.relpath because it's new in python 2.6
relname = fullname.replace(reference + '/','')
retval.append([fullname,relname])
return retval
def dist_hook():
import tarfile
shutil.rmtree("doc/html", True)
shutil.rmtree("doc/latex", True)
shutil.rmtree("nsc", True)
# Print the sorted list of module names in columns.
def print_module_names(names):
"""Print the list of module names in 3 columns."""
for i, name in enumerate(sorted(names)):
if i % 3 == 2 or i == len(names) - 1:
print(name)
else:
print(name.ljust(25), end=' ')
# return types of some APIs differ in Python 2/3 (type string vs class bytes)
# This method will decode('utf-8') a byte object in Python 3,
# and do nothing in Python 2
def maybe_decode(input):
if sys.version_info < (3,):
return input
else:
try:
return input.decode('utf-8')
except:
sys.exc_clear()
return input
def options(opt):
# options provided by the modules
opt.load('md5_tstamp')
opt.load('compiler_c')
opt.load('compiler_cxx')
opt.load('cflags')
opt.load('gnu_dirs')
opt.load('boost', tooldir=['waf-tools'])
opt.add_option('--check-config',
help=('Print the current configuration.'),
action="store_true", default=False,
dest="check_config")
opt.add_option('--cwd',
help=('Set the working directory for a program.'),
action="store", type="string", default=None,
dest='cwd_launch')
opt.add_option('--enable-gcov',
help=('Enable code coverage analysis.'
' WARNING: this option only has effect '
'with the configure command.'),
action="store_true", default=False,
dest='enable_gcov')
opt.add_option('--no-task-lines',
help=("Don't print task lines, i.e. messages saying which tasks are being executed by WAF."
" Coupled with a single -v will cause WAF to output only the executed commands,"
" just like 'make' does by default."),
action="store_true", default=False,
dest='no_task_lines')
opt.add_option('--lcov-report',
help=('Generate a code coverage report '
'(use this option after configuring with --enable-gcov and running a program)'),
action="store_true", default=False,
dest='lcov_report')
opt.add_option('--lcov-zerocounters',
help=('Zero the lcov counters'
'(use this option before rerunning a program, when generating repeated lcov reports)'),
action="store_true", default=False,
dest='lcov_zerocounters')
opt.add_option('--run',
help=('Run a locally built program; argument can be a program name,'
' or a command starting with the program name.'),
type="string", default='', dest='run')
opt.add_option('--run-no-build',
help=('Run a locally built program without rebuilding the project; argument can be a program name,'
' or a command starting with the program name.'),
type="string", default='', dest='run_no_build')
opt.add_option('--visualize',
help=('Modify --run arguments to enable the visualizer'),
action="store_true", default=False, dest='visualize')
opt.add_option('--command-template',
help=('Template of the command used to run the program given by --run;'
' It should be a shell command string containing %s inside,'
' which will be replaced by the actual program.'),
type="string", default=None, dest='command_template')
opt.add_option('--pyrun',
help=('Run a python program using locally built ns3 python module;'
' argument is the path to the python program, optionally followed'
' by command-line options that are passed to the program.'),
type="string", default='', dest='pyrun')
opt.add_option('--pyrun-no-build',
help=('Run a python program using locally built ns3 python module without rebuilding the project;'
' argument is the path to the python program, optionally followed'
' by command-line options that are passed to the program.'),
type="string", default='', dest='pyrun_no_build')
opt.add_option('--gdb',
help=('Change the default command template to run programs and unit tests with gdb'),
action="store_true", default=False,
dest='gdb')
opt.add_option('--valgrind',
help=('Change the default command template to run programs and unit tests with valgrind'),
action="store_true", default=False,
dest='valgrind')
opt.add_option('--shell',
help=('DEPRECATED (run ./waf shell)'),
action="store_true", default=False,
dest='shell')
opt.add_option('--enable-sudo',
help=('Use sudo to setup suid bits on ns3 executables.'),
dest='enable_sudo', action='store_true',
default=False)
opt.add_option('--enable-tests',
help=('Build the ns-3 tests.'),
dest='enable_tests', action='store_true',
default=False)
opt.add_option('--disable-tests',
help=('Do not build the ns-3 tests.'),
dest='disable_tests', action='store_true',
default=False)
opt.add_option('--enable-examples',
help=('Build the ns-3 examples.'),
dest='enable_examples', action='store_true',
default=False)
opt.add_option('--disable-examples',
help=('Do not build the ns-3 examples.'),
dest='disable_examples', action='store_true',
default=False)
opt.add_option('--check',
help=('DEPRECATED (run ./test.py)'),
default=False, dest='check', action="store_true")
opt.add_option('--enable-static',
help=('Compile NS-3 statically: works only on linux, without python'),
dest='enable_static', action='store_true',
default=False)
opt.add_option('--enable-mpi',
help=('Compile NS-3 with MPI and distributed simulation support'),
dest='enable_mpi', action='store_true',
default=False)
opt.add_option('--doxygen-no-build',
help=('Run doxygen to generate html documentation from source comments, '
'but do not wait for ns-3 to finish the full build.'),
action="store_true", default=False,
dest='doxygen_no_build')
opt.add_option('--docset',
help=('Create Docset, without building. This requires the docsetutil tool from Xcode 9.2 or earlier. See Bugzilla 2196 for more details.'),
action="store_true", default=False,
dest="docset_build")
opt.add_option('--enable-des-metrics',
help=('Log all events in a json file with the name of the executable (which must call CommandLine::Parse(argc, argv)'),
action="store_true", default=False,
dest='enable_desmetrics')
opt.add_option('--cxx-standard',
help=('Compile NS-3 with the given C++ standard'),
type='string', dest='cxx_standard')
opt.add_option('--enable-asserts',
help=('Enable the asserts regardless of the compile mode'),
action="store_true", default=False,
dest='enable_asserts')
opt.add_option('--enable-logs',
help=('Enable the logs regardless of the compile mode'),
action="store_true", default=False,
dest='enable_logs')
# options provided in subdirectories
opt.recurse('src')
opt.recurse('bindings/python')
opt.recurse('src/internet')
opt.recurse('contrib')
def _check_compilation_flag(conf, flag, mode='cxx', linkflags=None):
"""
Checks if the C++ compiler accepts a certain compilation flag or flags
flag: can be a string or a list of strings
"""
l = []
if flag:
l.append(flag)
if isinstance(linkflags, list):
l.extend(linkflags)
else:
if linkflags:
l.append(linkflags)
if len(l) > 1:
flag_str = 'flags ' + ' '.join(l)
else:
flag_str = 'flag ' + ' '.join(l)
if len(flag_str) > 28:
flag_str = flag_str[:28] + "..."
conf.start_msg('Checking for compilation %s support' % (flag_str,))
env = conf.env.derive()
retval = False
if mode == 'cc':
mode = 'c'
if mode == 'cxx':
env.append_value('CXXFLAGS', flag)
else:
env.append_value('CFLAGS', flag)
if linkflags is not None:
env.append_value("LINKFLAGS", linkflags)
try:
retval = conf.check(compiler=mode, fragment='int main() { return 0; }', features='c', env=env)
except Errors.ConfigurationError:
ok = False
else:
ok = (retval == True)
conf.end_msg(ok)
return ok
def report_optional_feature(conf, name, caption, was_enabled, reason_not_enabled):
conf.env.append_value('NS3_OPTIONAL_FEATURES', [(name, caption, was_enabled, reason_not_enabled)])
def check_optional_feature(conf, name):
for (name1, caption, was_enabled, reason_not_enabled) in conf.env.NS3_OPTIONAL_FEATURES:
if name1 == name:
return was_enabled
raise KeyError("Feature %r not declared yet" % (name,))
# starting with waf 1.6, conf.check() becomes fatal by default if the
# test fails, this alternative method makes the test non-fatal, as it
# was in waf <= 1.5
def _check_nonfatal(conf, *args, **kwargs):
try:
return conf.check(*args, **kwargs)
except conf.errors.ConfigurationError:
return None
# Write a summary of optional features status
def print_config(env, phase='configure'):
if phase == 'configure':
profile = get_build_profile(env)
else:
profile = get_build_profile()
print("---- Summary of optional NS-3 features:")
print("%-30s: %s%s%s" % ("Build profile", Logs.colors('GREEN'),
profile, Logs.colors('NORMAL')))
bld = wutils.bld
print("%-30s: %s%s%s" % ("Build directory", Logs.colors('GREEN'),
Options.options.out, Logs.colors('NORMAL')))
for (name, caption, was_enabled, reason_not_enabled) in sorted(env['NS3_OPTIONAL_FEATURES'], key=lambda s : s[1]):
if was_enabled:
status = 'enabled'
color = 'GREEN'
else:
status = 'not enabled (%s)' % reason_not_enabled
color = 'RED'
print("%-30s: %s%s%s" % (caption, Logs.colors(color), status, Logs.colors('NORMAL')))
# Checking for boost headers and libraries
#
# There are four cases:
# A. Only need headers, and they are required
# B. Also need compiled libraries, and they are required
# C. Only use headers, but they are not required
# D. Use compiled libraries, but they are not required
#
# A. If you only need includes there are just two steps:
#
# A1. Add this in your module wscript configure function:
#
# if not conf.require_boost_incs('my-module', 'my module caption'):
# return
#
# A2. Do step FINAL below.
#
# B. If you also need some compiled boost libraries there are
# three steps (instead of the above):
#
# B1. Declare the libraries you need by adding to your module wscript:
#
# REQUIRED_BOOST_LIBS = ['lib1', 'lib2'...]
#
# def required_boost_libs(conf):
# conf.env['REQUIRED_BOOST_LIBS'] += REQUIRED_BOOST_LIBS
#
# B2. Check that the libs are present in your module wscript configure function:
#
# if conf.missing_boost_libs('my-module', 'my module caption', REQUIRED_BOOST_LIBS):
# return
#
# B3. Do step FINAL below.
#
# Finally,
#
# FINAL. Add boost to your module wscript build function:
#
# # Assuming you have
# # module = bld.create_ns3_module('my-module')
# module.use.append('BOOST')
#
# If your use of boost is optional it's even simpler.
#
# C. For optional headers only, the two steps above are modified a little:
#
# C1. Add this to your module wscript configure function:
#
# conf.require_boost_incs('my-module', 'my module caption', required=False)
# # Continue with config, adjusting for missing boost
#
# C2. Modify step FINAL as follows
#
# if bld.env['INCLUDES_BOOST']:
# module.use.append('BOOST')
#
# D. For compiled boost libraries
#
# D1. Do B1 above to declare the libraries you would like to use
#
# D2. If you need to take action at configure time,
# add to your module wscript configure function:
#
# missing_boost_libs = conf.missing_boost_libs('my-module', 'my module caption', REQUIRED_BOOST_LIBS, required=False)
# # Continue with config, adjusting for missing boost libs
#
# At this point you can inspect missing_boost_libs to see
# what libs were found and do the right thing.
# See below for preprocessor symbols which will be available
# in your source files.
#
# D3. If any of your libraries are present add to your
# module wscript build function:
#
# missing_boost_libs = bld.missing_boost_libs('lib-opt', REQUIRED_BOOST_LIBS)
# # Continue with build, adjusting for missing boost libs
#
# At this point you can inspect missing_boost_libs to see
# what libs were found and do the right thing.
#
# In all cases you can test for boost in your code with
#
# #ifdef HAVE_BOOST
#
# Each boost compiled library will be indicated with a 'HAVE_BOOST_<lib>'
# preprocessor symbol, which you can test. For example, for the boost
# Signals2 library:
#
# #ifdef HAVE_BOOST_SIGNALS2
#
def require_boost_incs(conf, module, caption, required=True):
conf.to_log('boost: %s wants incs, required: %s' % (module, required))
if conf.env['INCLUDES_BOOST']:
conf.to_log('boost: %s: have boost' % module)
return True
elif not required:
conf.to_log('boost: %s: no boost, but not required' % module)
return False
else:
conf.to_log('boost: %s: no boost, but required' % module)
conf.report_optional_feature(module, caption, False,
"boost headers required but not found")
# Add this module to the list of modules that won't be built
# if they are enabled.
conf.env['MODULES_NOT_BUILT'].append(module)
return False
# Report any required boost libs which are missing
# Return values of truthy are bad; falsey is good:
# If all are present return False (non missing)
# If boost not present, or no libs return True
# If some libs present, return the list of missing libs
def conf_missing_boost_libs(conf, module, caption, libs, required= True):
conf.to_log('boost: %s wants %s, required: %s' % (module, libs, required))
if not conf.require_boost_incs(module, caption, required):
# No headers found, so the libs aren't there either
return libs
missing_boost_libs = [lib for lib in libs if lib not in conf.boost_libs]
if required and missing_boost_libs:
if not conf.env['LIB_BOOST']:
conf.to_log('boost: %s requires libs, but none found' % module)
conf.report_optional_feature(module, caption, False,
"No boost libraries were found")
else:
conf.to_log('boost: %s requires libs, but missing %s' % (module, missing_boost_libs))
conf.report_optional_feature(module, caption, False,
"Required boost libraries not found, missing: %s" % missing_boost_libs)
# Add this module to the list of modules that won't be built
# if they are enabled.
conf.env['MODULES_NOT_BUILT'].append(module)
return missing_boost_libs
# Required libraries were found, or are not required
return missing_boost_libs
def get_boost_libs(libs):
names = set()
for lib in libs:
if lib.startswith("boost_"):
lib = lib[6:]
if lib.endswith("-mt"):
lib = lib[:-3]
names.add(lib)
return names
def configure_boost(conf):
conf.to_log('boost: loading conf')
conf.load('boost')
# Find Boost libraries by modules
conf.to_log('boost: scanning for required libs')
conf.env['REQUIRED_BOOST_LIBS'] = []
for modules_dir in ['src', 'contrib']:
conf.recurse (modules_dir, name="get_required_boost_libs", mandatory=False)
# Check for any required boost libraries
if conf.env['REQUIRED_BOOST_LIBS'] is not []:
conf.env['REQUIRED_BOOST_LIBS'] = list(set(conf.env['REQUIRED_BOOST_LIBS']))
conf.to_log("boost: libs required: %s" % conf.env['REQUIRED_BOOST_LIBS'])
conf.check_boost(lib=' '.join (conf.env['REQUIRED_BOOST_LIBS']), mandatory=False, required=False)
if not conf.env['LIB_BOOST']:
conf.env['LIB_BOOST'] = []
else:
# Check with no libs, so we find the includes
conf.check_boost(mandatory=False, required=False)
conf.to_log('boost: checking if we should define HAVE_BOOST')
if conf.env['INCLUDES_BOOST']:
conf.to_log('boost: defining HAVE_BOOST')
conf.env.append_value ('CPPFLAGS', '-DHAVE_BOOST')
# Some boost libraries may have been found.
# Add preprocessor symbols for them
conf.to_log('boost: checking which libs are present')
if conf.env['LIB_BOOST']:
conf.boost_libs = get_boost_libs(conf.env['LIB_BOOST'])
for lib in conf.boost_libs:
msg='boost: lib present: ' + lib
if lib in conf.env['REQUIRED_BOOST_LIBS']:
have = '-DHAVE_BOOST_' + lib.upper()
conf.to_log('%s, requested, adding %s' % (msg, have))
conf.env.append_value('CPPFLAGS', have)
else:
conf.to_log('%s, not required, ignoring' % msg)
boost_libs_missing = [lib for lib in conf.env['REQUIRED_BOOST_LIBS'] if lib not in conf.boost_libs]
for lib in boost_libs_missing:
conf.to_log('boost: lib missing: %s' % lib)
def bld_missing_boost_libs (bld, module, libs):
missing_boost_libs = [lib for lib in libs if lib not in bld.boost_libs]
return missing_boost_libs
def configure(conf):
# Waf does not work correctly if the absolute path contains whitespaces
if (re.search(r"\s", os.getcwd ())):
conf.fatal('Waf does not support whitespace in the path to current working directory: %s' % os.getcwd())
conf.load('relocation', tooldir=['waf-tools'])
# attach some extra methods
conf.check_nonfatal = types.MethodType(_check_nonfatal, conf)
conf.check_compilation_flag = types.MethodType(_check_compilation_flag, conf)
conf.report_optional_feature = types.MethodType(report_optional_feature, conf)
conf.check_optional_feature = types.MethodType(check_optional_feature, conf)
conf.require_boost_incs = types.MethodType(require_boost_incs, conf)
conf.missing_boost_libs = types.MethodType(conf_missing_boost_libs, conf)
conf.boost_libs = set()
conf.env['NS3_OPTIONAL_FEATURES'] = []
conf.load('compiler_c')
cc_string = '.'.join(conf.env['CC_VERSION'])
conf.msg('Checking for cc version',cc_string,'GREEN')
conf.load('compiler_cxx')
conf.load('cflags', tooldir=['waf-tools'])
conf.load('command', tooldir=['waf-tools'])
conf.load('gnu_dirs')
conf.load('clang_compilation_database', tooldir=['waf-tools'])
env = conf.env
if Options.options.enable_gcov:
env['GCOV_ENABLED'] = True
env.append_value('CCFLAGS', '-fprofile-arcs')
env.append_value('CCFLAGS', '-ftest-coverage')
env.append_value('CXXFLAGS', '-fprofile-arcs')
env.append_value('CXXFLAGS', '-ftest-coverage')
env.append_value('LINKFLAGS', '-lgcov')
env.append_value('LINKFLAGS', '-coverage')
if Options.options.build_profile == 'debug':
env.append_value('DEFINES', 'NS3_BUILD_PROFILE_DEBUG')
env.append_value('DEFINES', 'NS3_ASSERT_ENABLE')
env.append_value('DEFINES', 'NS3_LOG_ENABLE')
if Options.options.build_profile == 'release':
env.append_value('DEFINES', 'NS3_BUILD_PROFILE_RELEASE')
if Options.options.build_profile == 'optimized':
env.append_value('DEFINES', 'NS3_BUILD_PROFILE_OPTIMIZED')
if Options.options.enable_logs:
env.append_unique('DEFINES', 'NS3_LOG_ENABLE')
if Options.options.enable_asserts:
env.append_unique('DEFINES', 'NS3_ASSERT_ENABLE')
env['PLATFORM'] = sys.platform
env['BUILD_PROFILE'] = Options.options.build_profile
if Options.options.build_profile == "release":
env['BUILD_SUFFIX'] = ''
else:
env['BUILD_SUFFIX'] = '-'+Options.options.build_profile
env['APPNAME'] = wutils.APPNAME
env['VERSION'] = wutils.VERSION
if conf.env['CXX_NAME'] in ['gcc']:
if tuple(map(int, conf.env['CC_VERSION'])) < gcc_min_version:
conf.fatal('gcc version %s older than minimum supported version %s' %
('.'.join(conf.env['CC_VERSION']), '.'.join(map(str, gcc_min_version))))
if conf.env['CXX_NAME'] in ['gcc', 'icc']:
if Options.options.build_profile == 'release':
env.append_value('CXXFLAGS', '-fomit-frame-pointer')
if Options.options.build_profile == 'optimized':
if conf.check_compilation_flag('-march=native'):
env.append_value('CXXFLAGS', '-march=native')
env.append_value('CXXFLAGS', '-fstrict-overflow')
if conf.env['CXX_NAME'] in ['gcc']:
env.append_value('CXXFLAGS', '-Wstrict-overflow=2')
if sys.platform == 'win32':
env.append_value("LINKFLAGS", "-Wl,--enable-runtime-pseudo-reloc")
env.append_value("CXXFLAGS", "-D_USE_MATH_DEFINES -D__WIN32__ -DNOMINMAX -DWIN32_LEAN_AND_MEAN")
elif sys.platform == 'cygwin':
env.append_value("LINKFLAGS", "-Wl,--enable-auto-import")
cxx = env['CXX']
cxx_check_libstdcxx = cxx + ['-print-file-name=libstdc++.so']
p = subprocess.Popen(cxx_check_libstdcxx, stdout=subprocess.PIPE)
libstdcxx_output = maybe_decode(p.stdout.read().strip())
libstdcxx_location = os.path.dirname(libstdcxx_output)
p.wait()
if libstdcxx_location:
conf.env.append_value('NS3_MODULE_PATH', libstdcxx_location)
if Utils.unversioned_sys_platform() in ['linux']:
if conf.check_compilation_flag('-Wl,--soname=foo'):
env['WL_SONAME_SUPPORTED'] = True
# bug 2181 on clang warning suppressions
if conf.env['CXX_NAME'] in ['clang']:
if Utils.unversioned_sys_platform() == 'darwin':
if tuple(map(int, conf.env['CC_VERSION'])) >= darwin_clang_version_warn_unused_local_typedefs:
env.append_value('CXXFLAGS', '-Wno-unused-local-typedefs')
if tuple(map(int, conf.env['CC_VERSION'])) >= darwin_clang_version_warn_potentially_evaluated:
env.append_value('CXXFLAGS', '-Wno-potentially-evaluated-expression')
else:
if tuple(map(int, conf.env['CC_VERSION'])) >= clang_version_warn_unused_local_typedefs:
env.append_value('CXXFLAGS', '-Wno-unused-local-typedefs')
if tuple(map(int, conf.env['CC_VERSION'])) >= clang_version_warn_potentially_evaluated:
env.append_value('CXXFLAGS', '-Wno-potentially-evaluated-expression')
env['ENABLE_STATIC_NS3'] = False
if Options.options.enable_static:
if Utils.unversioned_sys_platform() == 'darwin':
if conf.check_compilation_flag(flag=[], linkflags=['-Wl,-all_load']):
conf.report_optional_feature("static", "Static build", True, '')
env['ENABLE_STATIC_NS3'] = True
else:
conf.report_optional_feature("static", "Static build", False,
"Link flag -Wl,-all_load does not work")
else:
if conf.check_compilation_flag(flag=[], linkflags=['-Wl,--whole-archive,-Bstatic', '-Wl,-Bdynamic,--no-whole-archive']):
conf.report_optional_feature("static", "Static build", True, '')
env['ENABLE_STATIC_NS3'] = True
else:
conf.report_optional_feature("static", "Static build", False,
"Link flag -Wl,--whole-archive,-Bstatic does not work")
# Checks if environment variable specifies the C++ language standard and/or
# if the user has specified the standard via the -cxx-standard argument
# to 'waf configure'. The following precedence and behavior is implemented:
# 1) if user does not specify anything, Waf will use the default standard
# configured for ns-3, which is configured below
# 2) if user specifies the '-cxx-standard' option, it will be used instead
# of the default.
# Example: ./waf configure --cxx-standard=-std=c++14
# 3) if user specifies the C++ standard via the CXXFLAGS environment
# variable, it will be used instead of the default.
# Example: CXXFLAGS="-std=c++14" ./waf configure
# 4) if user specifies both the CXXFLAGS environment variable and the
# -cxx-standard argument, the latter will take precedence and a warning
# will be emitted in the configure output if there were conflicting
# standards between the two.
# Example: CXXFLAGS="-std=c++14" ./waf configure --cxx-standard=-std=c++17
# (in the above scenario, Waf will use c++17 but warn about it)
# Note: If the C++ standard is not recognized, configuration will error exit
cxx_standard = ""
cxx_standard_env = ""
for flag in env['CXXFLAGS']:
if flag[:5] == "-std=":
cxx_standard_env = flag
if not cxx_standard_env and Options.options.cxx_standard:
cxx_standard = Options.options.cxx_standard
env.append_value('CXXFLAGS', cxx_standard)
elif cxx_standard_env and not Options.options.cxx_standard:
cxx_standard = cxx_standard_env
# No need to change CXXFLAGS
elif cxx_standard_env and Options.options.cxx_standard and cxx_standard_env != Options.options.cxx_standard:
Logs.warn("user-specified --cxx-standard (" +
Options.options.cxx_standard + ") does not match the value in CXXFLAGS (" + cxx_standard_env + "); Waf will use the --cxx-standard value")
cxx_standard = Options.options.cxx_standard
env['CXXFLAGS'].remove(cxx_standard_env)
env.append_value('CXXFLAGS', cxx_standard)
elif cxx_standard_env and Options.options.cxx_standard and cxx_standard_env == Options.options.cxx_standard:
cxx_standard = Options.options.cxx_standard
# No need to change CXXFLAGS
elif not cxx_standard and not Options.options.cxx_standard:
cxx_standard = "-std=c++11"
env.append_value('CXXFLAGS', cxx_standard)
if not conf.check_compilation_flag(cxx_standard):
raise Errors.ConfigurationError("Exiting because C++ standard value " + cxx_standard + " is not recognized")
# Handle boost
configure_boost(conf)
# Set this so that the lists won't be printed at the end of this
# configure command.
conf.env['PRINT_BUILT_MODULES_AT_END'] = False
conf.env['MODULES_NOT_BUILT'] = []
conf.recurse('bindings/python')
conf.recurse('src')
conf.recurse('contrib')
# Set the list of enabled modules.
if Options.options.enable_modules:
# Use the modules explicitly enabled.
_enabled_mods = []
_enabled_contrib_mods = []
for mod in Options.options.enable_modules.split(','):
if mod in conf.env['NS3_MODULES'] and mod.startswith('ns3-'):
_enabled_mods.append(mod)
elif 'ns3-' + mod in conf.env['NS3_MODULES']:
_enabled_mods.append('ns3-' + mod)
elif mod in conf.env['NS3_CONTRIBUTED_MODULES'] and mod.startswith('ns3-'):
_enabled_contrib_mods.append(mod)
elif 'ns3-' + mod in conf.env['NS3_CONTRIBUTED_MODULES']:
_enabled_contrib_mods.append('ns3-' + mod)
conf.env['NS3_ENABLED_MODULES'] = _enabled_mods
conf.env['NS3_ENABLED_CONTRIBUTED_MODULES'] = _enabled_contrib_mods
else:
# Use the enabled modules list from the ns3 configuration file.
if modules_enabled[0] == 'all_modules':
# Enable all modules if requested.
conf.env['NS3_ENABLED_MODULES'] = conf.env['NS3_MODULES']
conf.env['NS3_ENABLED_CONTRIBUTED_MODULES'] = conf.env['NS3_CONTRIBUTED_MODULES']
else:
# Enable the modules from the list.
_enabled_mods = []
_enabled_contrib_mods = []
for mod in modules_enabled:
if mod in conf.env['NS3_MODULES'] and mod.startswith('ns3-'):
_enabled_mods.append(mod)
elif 'ns3-' + mod in conf.env['NS3_MODULES']:
_enabled_mods.append('ns3-' + mod)
elif mod in conf.env['NS3_CONTRIBUTED_MODULES'] and mod.startswith('ns3-'):
_enabled_contrib_mods.append(mod)
elif 'ns3-' + mod in conf.env['NS3_CONTRIBUTED_MODULES']:
_enabled_contrib_mods.append('ns3-' + mod)
conf.env['NS3_ENABLED_MODULES'] = _enabled_mods
conf.env['NS3_ENABLED_CONTRIBUTED_MODULES'] = _enabled_contrib_mods
# Add the template module to the list of enabled modules that
# should not be built if this is a static build on Darwin. They
# don't work there for the template module, and this is probably
# because the template module has no source files.
if conf.env['ENABLE_STATIC_NS3'] and sys.platform == 'darwin':
conf.env['MODULES_NOT_BUILT'].append('template')
# Remove these modules from the list of enabled modules.
for not_built in conf.env['MODULES_NOT_BUILT']:
not_built_name = 'ns3-' + not_built
if not_built_name in conf.env['NS3_ENABLED_MODULES']:
conf.env['NS3_ENABLED_MODULES'].remove(not_built_name)
if not conf.env['NS3_ENABLED_MODULES']:
raise WafError('Exiting because the ' + not_built + ' module can not be built and it was the only one enabled.')
elif not_built_name in conf.env['NS3_ENABLED_CONTRIBUTED_MODULES']:
conf.env['NS3_ENABLED_CONTRIBUTED_MODULES'].remove(not_built_name)
# for suid bits
try:
conf.find_program('sudo', var='SUDO')
except WafError:
pass
why_not_sudo = "because we like it"
if Options.options.enable_sudo and conf.env['SUDO']:
env['ENABLE_SUDO'] = True
else:
env['ENABLE_SUDO'] = False
if Options.options.enable_sudo:
why_not_sudo = "program sudo not found"
else:
why_not_sudo = "option --enable-sudo not selected"
conf.report_optional_feature("ENABLE_SUDO", "Use sudo to set suid bit", env['ENABLE_SUDO'], why_not_sudo)
# Decide if tests will be built or not.
if Options.options.enable_tests:
# Tests were explicitly enabled.
env['ENABLE_TESTS'] = True
why_not_tests = "option --enable-tests selected"
elif Options.options.disable_tests:
# Tests were explicitly disabled.
env['ENABLE_TESTS'] = False
why_not_tests = "option --disable-tests selected"
else:
# Enable tests based on the ns3 configuration file.
env['ENABLE_TESTS'] = tests_enabled
if config_file_exists:
why_not_tests = "based on configuration file"
elif tests_enabled:
why_not_tests = "defaults to enabled"
else:
why_not_tests = "defaults to disabled"
conf.report_optional_feature("ENABLE_TESTS", "Tests", env['ENABLE_TESTS'], why_not_tests)
# Decide if examples will be built or not.
if Options.options.enable_examples:
# Examples were explicitly enabled.
env['ENABLE_EXAMPLES'] = True
why_not_examples = "option --enable-examples selected"
elif Options.options.disable_examples:
# Examples were explicitly disabled.
env['ENABLE_EXAMPLES'] = False
why_not_examples = "option --disable-examples selected"
else:
# Enable examples based on the ns3 configuration file.
env['ENABLE_EXAMPLES'] = examples_enabled
if config_file_exists:
why_not_examples = "based on configuration file"
elif examples_enabled:
why_not_examples = "defaults to enabled"
else:
why_not_examples = "defaults to disabled"
conf.report_optional_feature("ENABLE_EXAMPLES", "Examples", env['ENABLE_EXAMPLES'],
why_not_examples)
try:
for dir in os.listdir('examples'):
if dir.startswith('.') or dir == 'CVS':
continue
conf.env.append_value('EXAMPLE_DIRECTORIES', dir)
except OSError:
return
env['VALGRIND_FOUND'] = False
try:
conf.find_program('valgrind', var='VALGRIND')
env['VALGRIND_FOUND'] = True
except WafError:
pass
# These flags are used for the implicitly dependent modules.
if env['ENABLE_STATIC_NS3']:
if sys.platform == 'darwin':
env.STLIB_MARKER = '-Wl,-all_load'
else:
env.STLIB_MARKER = '-Wl,--whole-archive,-Bstatic'
env.SHLIB_MARKER = '-Wl,-Bdynamic,--no-whole-archive'
have_gsl = conf.check_cfg(package='gsl', args=['--cflags', '--libs'],
uselib_store='GSL', mandatory=False)
conf.env['ENABLE_GSL'] = have_gsl
conf.report_optional_feature("GSL", "GNU Scientific Library (GSL)",
conf.env['ENABLE_GSL'],
"GSL not found")
conf.find_program('libgcrypt-config', var='LIBGCRYPT_CONFIG', msg="libgcrypt-config", mandatory=False)
if env.LIBGCRYPT_CONFIG:
conf.check_cfg(path=env.LIBGCRYPT_CONFIG, msg="Checking for libgcrypt", args='--cflags --libs', package='',
define_name="HAVE_GCRYPT", global_define=True, uselib_store='GCRYPT', mandatory=False)
conf.report_optional_feature("libgcrypt", "Gcrypt library",
conf.env.HAVE_GCRYPT, "libgcrypt not found: you can use libgcrypt-config to find its location.")
why_not_desmetrics = "defaults to disabled"
if Options.options.enable_desmetrics:
conf.env['ENABLE_DES_METRICS'] = True
env.append_value('DEFINES', 'ENABLE_DES_METRICS')
why_not_desmetrics = "option --enable-des-metrics selected"
conf.report_optional_feature("DES Metrics", "DES Metrics event collection", conf.env['ENABLE_DES_METRICS'], why_not_desmetrics)
# for compiling C code, copy over the CXX* flags
conf.env.append_value('CCFLAGS', conf.env['CXXFLAGS'])
def add_gcc_flag(flag):
if env['COMPILER_CXX'] == 'g++' and 'CXXFLAGS' not in os.environ:
if conf.check_compilation_flag(flag, mode='cxx'):
env.append_value('CXXFLAGS', flag)
if env['COMPILER_CC'] == 'gcc' and 'CCFLAGS' not in os.environ:
if conf.check_compilation_flag(flag, mode='cc'):
env.append_value('CCFLAGS', flag)
add_gcc_flag('-fstrict-aliasing')
add_gcc_flag('-Wstrict-aliasing')
try:
conf.find_program('doxygen', var='DOXYGEN')
except WafError:
pass
# append user defined flags after all our ones
for (confvar, envvar) in [['CCFLAGS', 'CCFLAGS_EXTRA'],
['CXXFLAGS', 'CXXFLAGS_EXTRA'],
['LINKFLAGS', 'LINKFLAGS_EXTRA'],
['LINKFLAGS', 'LDFLAGS_EXTRA']]:
if envvar in os.environ:
value = shlex.split(os.environ[envvar])
conf.env.append_value(confvar, value)
print_config(env)
class SuidBuild_task(Task.Task):
"""task that makes a binary Suid
"""
after = ['cxxprogram', 'cxxshlib', 'cxxstlib']
def __init__(self, *args, **kwargs):
super(SuidBuild_task, self).__init__(*args, **kwargs)
self.m_display = 'build-suid'
try:
program_obj = wutils.find_program(self.generator.name, self.generator.env)
except ValueError as ex:
raise WafError(str(ex))
program_node = program_obj.path.find_or_declare(program_obj.target)
self.filename = program_node.get_bld().abspath()
def run(self):
print('setting suid bit on executable ' + self.filename, file=sys.stderr)
if subprocess.Popen(['sudo', 'chown', 'root', self.filename]).wait():
return 1
if subprocess.Popen(['sudo', 'chmod', 'u+s', self.filename]).wait():
return 1
return 0
def runnable_status(self):
"RUN_ME SKIP_ME or ASK_LATER"
try:
st = os.stat(self.filename)
except OSError:
return Task.ASK_LATER
if st.st_uid == 0:
return Task.SKIP_ME
else:
return Task.RUN_ME
def create_suid_program(bld, name):
grp = bld.current_group
bld.add_group() # this to make sure no two sudo tasks run at the same time
program = bld(features='cxx cxxprogram')
program.is_ns3_program = True
program.module_deps = list()
program.name = name
program.target = "%s%s-%s%s" % (wutils.APPNAME, wutils.VERSION, name, bld.env.BUILD_SUFFIX)
if bld.env['ENABLE_SUDO']:
program.create_task("SuidBuild_task")
bld.set_group(grp)
return program