Darth_Malgus

NS3 with crypto++ Help needed

Sep 25th, 2023
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 65.07 KB | None | 0 0
  1. So here I have done till now...
  2.  
  3. 1. Downloaded the source code of crypto++ 8.8.0 lib from https://github.com/weidai11/cryptopp/releases/tag/CRYPTOPP_8_8_0.
  4. 2. I unzipped the file in a folder known as cryptopp & I moved that folder to contrib as /home/hex/ns-allinone-3.31/ns-3.31/contrib/cryptopp
  5. 4. I made a wscript file inside the cryptopp folder located as /home/hex/ns-allinone-3.31/ns-3.31/contrib/cryptopp/wscript.
  6. 5. Its code is as follows:
  7.  
  8.  
  9. def build(bld):
  10.  
  11.     module = bld.create_ns3_module('CryptoPP', ['cryptlib'])
  12.  
  13.     module.source = [
  14.  'aes.cpp',
  15.         'arc4.cpp',
  16.         'autocfg.cpp',
  17.         'basecode.cpp',
  18.         'cbcmac.cpp',
  19.         'ccm.cpp',
  20.         'channels.cpp',
  21.         'cmd5.cpp',
  22.         'cpu.cpp',
  23.         'crc.cpp',  
  24.         'cryptlib.cpp',
  25.         'default.cpp',
  26.         'des.cpp',
  27.         'dh.cpp',
  28.         'dsa.cpp',
  29.         'ec2n.cpp',
  30.         'eccrypto.cpp',
  31.         'ecp.cpp',
  32.         'elgamal.cpp',
  33.         'eprecomp.cpp',
  34.         'esign.cpp',
  35.         'files.cpp',
  36.         'fipstest.cpp',
  37.         'gcm.cpp',
  38.         'gf2n.cpp',
  39.         'hex.cpp',
  40.         'hmac.cpp',
  41.         'integer.cpp',
  42.         'iterhash.cpp',
  43.         'misc.cpp',
  44.         'modarith.cpp',
  45.         'modes.cpp',
  46.         'mqueue.cpp',
  47.         'nbtheory.cpp',
  48.         'oaep.cpp',
  49.         'osrng.cpp',
  50.         'panama.cpp',
  51.         'pch.cpp',
  52.         'pkcspad.cpp',
  53.         'pubkey.cpp',
  54.         'queue.cpp',
  55.         'rabin.cpp',
  56.         'randpool.cpp',
  57.         'rc2.cpp',
  58.         'rc5.cpp',
  59.         'rc6.cpp',
  60.         'rijndael.cpp',
  61.         'rng.cpp',
  62.         'rsa.cpp',
  63.         'rw.cpp',
  64.         'safer.cpp',
  65.         'seal.cpp',
  66.         'serpent.cpp',
  67.         'shacal2.cpp',
  68.         'sha.cpp',
  69.         'sha3.cpp',
  70.         'shm.cpp',
  71.         'skipjack.cpp',
  72.         'socketft.cpp',
  73.         'sosemanuk.cpp',      
  74.         'square.cpp',
  75.         'tea.cpp',
  76.         'tpm.cpp',
  77.         'ttmac.cpp',
  78.         'tweetnacl.cpp',
  79.         'whrlpool.cpp',
  80.         'xtrcrypt.cpp',
  81.         'xts.cpp',
  82.         'zdeflate.cpp',
  83.         'zlib.cpp'
  84.         # Add other sources
  85.     ]
  86.  
  87.     module.use = ['cryptlib']
  88.  
  89.     module.headers = [
  90.       'aes.h',
  91.         'AlignedAllocate.h',
  92.         'algparam.h',
  93.         'aria.h',
  94.         'asn.h',
  95.         'base32.h',
  96.         'base64.h',
  97.         'basecode.h',
  98.         'bench.h',
  99.         'blake2.h',
  100.         'blowfish.h',
  101.         'camellia.h',
  102.         'cast.h',
  103.         'cbcmac.h',        
  104.         'ccm.h',
  105.         'channels.h',        
  106.         'cmac.h',
  107.         'cpu.h',
  108.         'crc.h',
  109.         'cryptlib.h',
  110.         'des.h',
  111.         'dh.h',
  112.         'dll.h',
  113.         'dsa.h',
  114.         'ec2n.h',
  115.         'eccrypto.h',
  116.         'ecp.h',        
  117.         'elgamal.h',
  118.         'emsa2.h',
  119.         'eprecomp.h',
  120.         'esign.h',
  121.         'files.h',
  122.         'filters.h',
  123.         'fips140.h',
  124.         'gcm.h',
  125.         'gf2n.h',
  126.         'gfpcrypt.h',
  127.         'gost.h',
  128.         'gzip.h',
  129.         'hex.h',        
  130.         'hmac.h',
  131.         'integer.h',
  132.         'iterhash.h',
  133.         'kalyna.h',
  134.         'keccak.h',
  135.         'mars.h',
  136.         'md2.h',
  137.         'md4.h',
  138.         'md5.h',
  139.         'misc.h',
  140.         'modarith.h',
  141.         'modes.h',
  142.         'mqueue.h',
  143.         'nbtheory.h',
  144.         'oaep.h',
  145.         'osrng.h',
  146.         'panama.h',
  147.         'pch.h',
  148.         'pkcspad.h',
  149.         'pubkey.h',
  150.         'queue.h',
  151.         'rabin.h',
  152.         'randpool.h',
  153.         'rc2.h',
  154.         'rc5.h',
  155.         'rc6.h',
  156.         'rijndael.h',
  157.         'rng.h',
  158.         'rsa.h',
  159.         'rw.h',
  160.         'safer.h',
  161.         'seckey.h',
  162.         'seal.h',
  163.         'serpent.h',
  164.         'sha.h',
  165.         'sha3.h',
  166.         'shacal2.h',
  167.         'shark.h',
  168.         'skipjack.h',
  169.         'smartptr.h',
  170.         'sosemanuk.h',
  171.         'square.h',
  172.         'tea.h',
  173.         'trdlocal.h',
  174.         'ttmac.h',
  175.         'tweetnacl.h',        
  176.         'whrlpool.h',
  177.         'winpipes.h',
  178.         'xtrcrypt.h',
  179.         'xts.h',
  180.         'zdeflate.h',
  181.         'zinflate.h',
  182.         # Add other public headers
  183.     ]
  184.  
  185.     obj_test = bld.create_ns3_module_test_library('CryptoPP')
  186.  
  187.     obj_test.source = [
  188.         'crypto_test.cc',
  189.     ]
  190.  
  191.     obj_test.use = ['CryptoPP', 'cryptlib']
  192.  
  193.     headers = bld(features='ns3header')
  194.     headers.module = 'CryptoPP'
  195.     headers.source = module.headers
  196.  
  197.     bld.ns3_python_bindings()
  198.  
  199. Now what changes should I make to this wscript & the wscript located at /home/hex/ns-allinone-3.31/ns-3.31/wscript, whose code is given below.
  200.  
  201. ## -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
  202.  
  203. # python lib modules
  204. from __future__ import print_function
  205. import sys
  206. import shutil
  207. import types
  208. import optparse
  209. import os.path
  210. import re
  211. import shlex
  212. import subprocess
  213. import textwrap
  214. import fileinput
  215. import glob
  216.  
  217. from utils import read_config_file
  218.  
  219.  
  220. # WAF modules
  221. from waflib import Utils, Scripting, Configure, Build, Options, TaskGen, Context, Task, Logs, Errors
  222. from waflib.Errors import WafError
  223.  
  224.  
  225. # local modules
  226. import wutils
  227.  
  228.  
  229. # By default, all modules will be enabled, examples will be disabled,
  230. # and tests will be disabled.
  231. modules_enabled  = ['all_modules']
  232. examples_enabled = False
  233. tests_enabled    = False
  234.  
  235. # GCC minimum version requirements for C++11 support
  236. gcc_min_version = (4, 9, 2)
  237.  
  238. # Bug 2181:  clang warnings about unused local typedefs and potentially
  239. # evaluated expressions affecting darwin clang/LLVM version 7.0.0 (Xcode 7)
  240. # or clang/LLVM version 3.6 or greater.  We must make this platform-specific.
  241. darwin_clang_version_warn_unused_local_typedefs = (7, 0, 0)
  242. darwin_clang_version_warn_potentially_evaluated = (7, 0, 0)
  243. clang_version_warn_unused_local_typedefs = (3, 6, 0)
  244. clang_version_warn_potentially_evaluated = (3, 6, 0)
  245.  
  246. # Get the information out of the NS-3 configuration file.
  247. config_file_exists = False
  248. (config_file_exists, modules_enabled, examples_enabled, tests_enabled) = read_config_file()
  249.  
  250. sys.path.insert(0, os.path.abspath('waf-tools'))
  251. try:
  252.     import cflags # override the build profiles from waf
  253. finally:
  254.     sys.path.pop(0)
  255.  
  256. cflags.profiles = {
  257.     # profile name: [optimization_level, warnings_level, debug_level]
  258.     'debug':     [0, 2, 3],
  259.     'optimized': [3, 2, 1],
  260.     'release':   [3, 2, 0],
  261.     }
  262. cflags.default_profile = 'debug'
  263.  
  264. Configure.autoconfig = 0
  265.  
  266. # the following two variables are used by the target "waf dist"
  267. VERSION = open("VERSION", "rt").read().strip()
  268. APPNAME = 'ns'
  269.  
  270. wutils.VERSION = VERSION
  271. wutils.APPNAME = APPNAME
  272.  
  273. # we don't use VNUM anymore (see bug #1327 for details)
  274. wutils.VNUM = None
  275.  
  276. # these variables are mandatory ('/' are converted automatically)
  277. top = '.'
  278. out = 'build'
  279.  
  280. def load_env():
  281.     bld_cls = getattr(Utils.g_module, 'build_context', Utils.Context)
  282.     bld_ctx = bld_cls()
  283.     bld_ctx.load_dirs(os.path.abspath(os.path.join (srcdir,'..')),
  284.                       os.path.abspath(os.path.join (srcdir,'..', blddir)))
  285.     bld_ctx.load_envs()
  286.     env = bld_ctx.get_env()
  287.     return env
  288.  
  289. def get_files(base_dir):
  290.     retval = []
  291.     reference=os.path.dirname(base_dir)
  292.     for root, dirs, files in os.walk(base_dir):
  293.         if root.find('.hg') != -1:
  294.             continue
  295.         for file in files:
  296.             if file.find('.hg') != -1:
  297.                 continue
  298.             fullname = os.path.join(root,file)
  299.             # we can't use os.path.relpath because it's new in python 2.6
  300.             relname = fullname.replace(reference + '/','')
  301.             retval.append([fullname,relname])
  302.     return retval
  303.  
  304.  
  305. def dist_hook():
  306.     import tarfile
  307.     shutil.rmtree("doc/html", True)
  308.     shutil.rmtree("doc/latex", True)
  309.     shutil.rmtree("nsc", True)
  310.  
  311. # Print the sorted list of module names in columns.
  312. def print_module_names(names):
  313.     """Print the list of module names in 3 columns."""
  314.     for i, name in enumerate(sorted(names)):
  315.         if i % 3 == 2 or i == len(names) - 1:
  316.           print(name)
  317.         else:
  318.           print(name.ljust(25), end=' ')
  319.  
  320. # return types of some APIs differ in Python 2/3 (type string vs class bytes)
  321. # This method will decode('utf-8') a byte object in Python 3,
  322. # and do nothing in Python 2
  323. def maybe_decode(input):
  324.     if sys.version_info < (3,):
  325.         return input
  326.     else:
  327.         try:
  328.             return input.decode('utf-8')
  329.         except:
  330.             sys.exc_clear()
  331.             return input
  332.  
  333. def options(opt):
  334.     # options provided by the modules
  335.     opt.load('md5_tstamp')
  336.     opt.load('compiler_c')
  337.     opt.load('compiler_cxx')
  338.     opt.load('cflags')
  339.     opt.load('gnu_dirs')
  340.  
  341.     opt.add_option('--check-config',
  342.                    help=('Print the current configuration.'),
  343.                    action="store_true", default=False,
  344.                    dest="check_config")
  345.    
  346.     opt.add_option('--cwd',
  347.                    help=('Set the working directory for a program.'),
  348.                    action="store", type="string", default=None,
  349.                    dest='cwd_launch')
  350.  
  351.     opt.add_option('--enable-gcov',
  352.                    help=('Enable code coverage analysis.'
  353.                          ' WARNING: this option only has effect '
  354.                          'with the configure command.'),
  355.                    action="store_true", default=False,
  356.                    dest='enable_gcov')
  357.  
  358.     opt.add_option('--no-task-lines',
  359.                    help=("Don't print task lines, i.e. messages saying which tasks are being executed by WAF."
  360.                          "  Coupled with a single -v will cause WAF to output only the executed commands,"
  361.                          " just like 'make' does by default."),
  362.                    action="store_true", default=False,
  363.                    dest='no_task_lines')
  364.  
  365.     opt.add_option('--lcov-report',
  366.                    help=('Generate a code coverage report '
  367.                          '(use this option after configuring with --enable-gcov and running a program)'),
  368.                    action="store_true", default=False,
  369.                    dest='lcov_report')
  370.  
  371.     opt.add_option('--lcov-zerocounters',
  372.                    help=('Zero the lcov counters'
  373.                          '(use this option before rerunning a program, when generating repeated lcov reports)'),
  374.                    action="store_true", default=False,
  375.                    dest='lcov_zerocounters')
  376.  
  377.     opt.add_option('--run',
  378.                    help=('Run a locally built program; argument can be a program name,'
  379.                          ' or a command starting with the program name.'),
  380.                    type="string", default='', dest='run')
  381.     opt.add_option('--run-no-build',
  382.                    help=('Run a locally built program without rebuilding the project; argument can be a program name,'
  383.                          ' or a command starting with the program name.'),
  384.                    type="string", default='', dest='run_no_build')
  385.     opt.add_option('--visualize',
  386.                    help=('Modify --run arguments to enable the visualizer'),
  387.                    action="store_true", default=False, dest='visualize')
  388.     opt.add_option('--command-template',
  389.                    help=('Template of the command used to run the program given by --run;'
  390.                          ' It should be a shell command string containing %s inside,'
  391.                          ' which will be replaced by the actual program.'),
  392.                    type="string", default=None, dest='command_template')
  393.     opt.add_option('--pyrun',
  394.                    help=('Run a python program using locally built ns3 python module;'
  395.                          ' argument is the path to the python program, optionally followed'
  396.                          ' by command-line options that are passed to the program.'),
  397.                    type="string", default='', dest='pyrun')
  398.     opt.add_option('--pyrun-no-build',
  399.                    help=('Run a python program using locally built ns3 python module without rebuilding the project;'
  400.                          ' argument is the path to the python program, optionally followed'
  401.                          ' by command-line options that are passed to the program.'),
  402.                    type="string", default='', dest='pyrun_no_build')
  403.     opt.add_option('--gdb',
  404.                    help=('Change the default command template to run programs and unit tests with gdb'),
  405.                    action="store_true", default=False,
  406.                    dest='gdb')
  407.     opt.add_option('--valgrind',
  408.                    help=('Change the default command template to run programs and unit tests with valgrind'),
  409.                    action="store_true", default=False,
  410.                    dest='valgrind')
  411.     opt.add_option('--shell',
  412.                    help=('DEPRECATED (run ./waf shell)'),
  413.                    action="store_true", default=False,
  414.                    dest='shell')
  415.     opt.add_option('--enable-sudo',
  416.                    help=('Use sudo to setup suid bits on ns3 executables.'),
  417.                    dest='enable_sudo', action='store_true',
  418.                    default=False)
  419.     opt.add_option('--enable-tests',
  420.                    help=('Build the ns-3 tests.'),
  421.                    dest='enable_tests', action='store_true',
  422.                    default=False)
  423.     opt.add_option('--disable-tests',
  424.                    help=('Do not build the ns-3 tests.'),
  425.                    dest='disable_tests', action='store_true',
  426.                    default=False)
  427.     opt.add_option('--enable-examples',
  428.                    help=('Build the ns-3 examples.'),
  429.                    dest='enable_examples', action='store_true',
  430.                    default=False)
  431.     opt.add_option('--disable-examples',
  432.                    help=('Do not build the ns-3 examples.'),
  433.                    dest='disable_examples', action='store_true',
  434.                    default=False)
  435.     opt.add_option('--check',
  436.                    help=('DEPRECATED (run ./test.py)'),
  437.                    default=False, dest='check', action="store_true")
  438.     opt.add_option('--enable-static',
  439.                    help=('Compile NS-3 statically: works only on linux, without python'),
  440.                    dest='enable_static', action='store_true',
  441.                    default=False)
  442.     opt.add_option('--enable-mpi',
  443.                    help=('Compile NS-3 with MPI and distributed simulation support'),
  444.                    dest='enable_mpi', action='store_true',
  445.                    default=False)
  446.     opt.add_option('--doxygen-no-build',
  447.                    help=('Run doxygen to generate html documentation from source comments, '
  448.                          'but do not wait for ns-3 to finish the full build.'),
  449.                    action="store_true", default=False,
  450.                    dest='doxygen_no_build')
  451.     opt.add_option('--docset',
  452.                    help=('Create Docset, without building. This requires the docsetutil tool from Xcode 9.2 or earlier. See Bugzilla 2196 for more details.'),
  453.                    action="store_true", default=False,
  454.                    dest="docset_build")
  455.     opt.add_option('--enable-des-metrics',
  456.                    help=('Log all events in a json file with the name of the executable (which must call CommandLine::Parse(argc, argv)'),
  457.                    action="store_true", default=False,
  458.                    dest='enable_desmetrics')
  459.     opt.add_option('--cxx-standard',
  460.                    help=('Compile NS-3 with the given C++ standard'),
  461.                    type='string', default='-std=c++11', dest='cxx_standard')
  462.  
  463.     # options provided in subdirectories
  464.     opt.recurse('src')
  465.     opt.recurse('bindings/python')
  466.     opt.recurse('src/internet')
  467.     # New Code
  468.     opt.recurse('contrib/cryptopp')
  469.     # New Code
  470.     opt.recurse('contrib')
  471.  
  472. def _check_compilation_flag(conf, flag, mode='cxx', linkflags=None):
  473.     """
  474.    Checks if the C++ compiler accepts a certain compilation flag or flags
  475.    flag: can be a string or a list of strings
  476.    """
  477.     l = []
  478.     if flag:
  479.         l.append(flag)
  480.     if isinstance(linkflags, list):
  481.         l.extend(linkflags)
  482.     else:
  483.         if linkflags:
  484.             l.append(linkflags)
  485.     if len(l) > 1:
  486.         flag_str = 'flags ' + ' '.join(l)
  487.     else:
  488.         flag_str = 'flag ' + ' '.join(l)
  489.     if len(flag_str) > 28:
  490.         flag_str = flag_str[:28] + "..."
  491.  
  492.     conf.start_msg('Checking for compilation %s support' % (flag_str,))
  493.     env = conf.env.derive()
  494.  
  495.     retval = False
  496.     if mode == 'cc':
  497.         mode = 'c'
  498.  
  499.     if mode == 'cxx':
  500.         env.append_value('CXXFLAGS', flag)
  501.     else:
  502.         env.append_value('CFLAGS', flag)
  503.  
  504.     if linkflags is not None:
  505.         env.append_value("LINKFLAGS", linkflags)
  506.  
  507.     try:
  508.         retval = conf.check(compiler=mode, fragment='int main() { return 0; }', features='c', env=env)
  509.     except Errors.ConfigurationError:
  510.         ok = False
  511.     else:
  512.         ok = (retval == True)
  513.     conf.end_msg(ok)
  514.     return ok
  515.  
  516.  
  517. def report_optional_feature(conf, name, caption, was_enabled, reason_not_enabled):
  518.     conf.env.append_value('NS3_OPTIONAL_FEATURES', [(name, caption, was_enabled, reason_not_enabled)])
  519.  
  520.  
  521. def check_optional_feature(conf, name):
  522.     for (name1, caption, was_enabled, reason_not_enabled) in conf.env.NS3_OPTIONAL_FEATURES:
  523.         if name1 == name:
  524.             return was_enabled
  525.     raise KeyError("Feature %r not declared yet" % (name,))
  526.  
  527.  
  528. # starting with waf 1.6, conf.check() becomes fatal by default if the
  529. # test fails, this alternative method makes the test non-fatal, as it
  530. # was in waf <= 1.5
  531. def _check_nonfatal(conf, *args, **kwargs):
  532.     try:
  533.         return conf.check(*args, **kwargs)
  534.     except conf.errors.ConfigurationError:
  535.         return None
  536.  
  537. # Write a summary of optional features status
  538. def print_config(env, phase='configure'):
  539.     if phase == 'configure':
  540.         profile = get_build_profile(env)
  541.     else:
  542.         profile = get_build_profile()
  543.        
  544.     print("---- Summary of optional NS-3 features:")
  545.     print("%-30s: %s%s%s" % ("Build profile", Logs.colors('GREEN'),
  546.                              profile, Logs.colors('NORMAL')))
  547.     bld = wutils.bld
  548.     print("%-30s: %s%s%s" % ("Build directory", Logs.colors('GREEN'),
  549.                              Options.options.out, Logs.colors('NORMAL')))
  550.    
  551.    
  552.     for (name, caption, was_enabled, reason_not_enabled) in sorted(env['NS3_OPTIONAL_FEATURES'], key=lambda s : s[1]):
  553.         if was_enabled:
  554.             status = 'enabled'
  555.             color = 'GREEN'
  556.         else:
  557.             status = 'not enabled (%s)' % reason_not_enabled
  558.             color = 'RED'
  559.         print("%-30s: %s%s%s" % (caption, Logs.colors(color), status, Logs.colors('NORMAL')))
  560.  
  561. def configure(conf):
  562.     conf.load('relocation', tooldir=['waf-tools'])
  563.  
  564.     # attach some extra methods
  565.     conf.check_nonfatal = types.MethodType(_check_nonfatal, conf)
  566.     conf.check_compilation_flag = types.MethodType(_check_compilation_flag, conf)
  567.     conf.report_optional_feature = types.MethodType(report_optional_feature, conf)
  568.     conf.check_optional_feature = types.MethodType(check_optional_feature, conf)
  569.     conf.env['NS3_OPTIONAL_FEATURES'] = []
  570.  
  571.     conf.load('compiler_c')
  572.     cc_string = '.'.join(conf.env['CC_VERSION'])
  573.     conf.msg('Checking for cc version',cc_string,'GREEN')
  574.     conf.load('compiler_cxx')
  575.     conf.load('cflags', tooldir=['waf-tools'])
  576.     conf.load('command', tooldir=['waf-tools'])
  577.     conf.load('gnu_dirs')
  578.     conf.load('clang_compilation_database', tooldir=['waf-tools'])
  579.  
  580.     env = conf.env
  581.  
  582.     if Options.options.enable_gcov:
  583.         env['GCOV_ENABLED'] = True
  584.         env.append_value('CCFLAGS', '-fprofile-arcs')
  585.         env.append_value('CCFLAGS', '-ftest-coverage')
  586.         env.append_value('CXXFLAGS', '-fprofile-arcs')
  587.         env.append_value('CXXFLAGS', '-ftest-coverage')
  588.         env.append_value('LINKFLAGS', '-lgcov')
  589.         env.append_value('LINKFLAGS', '-coverage')
  590.  
  591.     if Options.options.build_profile == 'debug':
  592.         env.append_value('DEFINES', 'NS3_BUILD_PROFILE_DEBUG')
  593.         env.append_value('DEFINES', 'NS3_ASSERT_ENABLE')
  594.         env.append_value('DEFINES', 'NS3_LOG_ENABLE')
  595.  
  596.     if Options.options.build_profile == 'release':
  597.         env.append_value('DEFINES', 'NS3_BUILD_PROFILE_RELEASE')
  598.  
  599.     if Options.options.build_profile == 'optimized':
  600.         env.append_value('DEFINES', 'NS3_BUILD_PROFILE_OPTIMIZED')
  601.  
  602.     env['PLATFORM'] = sys.platform
  603.     env['BUILD_PROFILE'] = Options.options.build_profile
  604.     if Options.options.build_profile == "release":
  605.         env['BUILD_SUFFIX'] = ''
  606.     else:
  607.         env['BUILD_SUFFIX'] = '-'+Options.options.build_profile
  608.    
  609.     env['APPNAME'] = wutils.APPNAME
  610.     env['VERSION'] = wutils.VERSION
  611.  
  612.     if conf.env['CXX_NAME'] in ['gcc']:
  613.         if tuple(map(int, conf.env['CC_VERSION'])) < gcc_min_version:
  614.             conf.fatal('gcc version %s older than minimum supported version %s' %
  615.                        ('.'.join(conf.env['CC_VERSION']), '.'.join(map(str, gcc_min_version))))
  616.  
  617.     if conf.env['CXX_NAME'] in ['gcc', 'icc']:
  618.         if Options.options.build_profile == 'release':
  619.             env.append_value('CXXFLAGS', '-fomit-frame-pointer')
  620.         if Options.options.build_profile == 'optimized':
  621.             if conf.check_compilation_flag('-march=native'):
  622.                 env.append_value('CXXFLAGS', '-march=native')
  623.             env.append_value('CXXFLAGS', '-fstrict-overflow')
  624.             if conf.env['CXX_NAME'] in ['gcc']:
  625.                 env.append_value('CXXFLAGS', '-Wstrict-overflow=2')
  626.  
  627.         if sys.platform == 'win32':
  628.             env.append_value("LINKFLAGS", "-Wl,--enable-runtime-pseudo-reloc")
  629.         elif sys.platform == 'cygwin':
  630.             env.append_value("LINKFLAGS", "-Wl,--enable-auto-import")
  631.  
  632.         cxx = env['CXX']
  633.         cxx_check_libstdcxx = cxx + ['-print-file-name=libstdc++.so']
  634.         p = subprocess.Popen(cxx_check_libstdcxx, stdout=subprocess.PIPE)
  635.         libstdcxx_output = maybe_decode(p.stdout.read().strip())
  636.         libstdcxx_location = os.path.dirname(libstdcxx_output)
  637.         p.wait()
  638.         if libstdcxx_location:
  639.             conf.env.append_value('NS3_MODULE_PATH', libstdcxx_location)
  640.  
  641.         if Utils.unversioned_sys_platform() in ['linux']:
  642.             if conf.check_compilation_flag('-Wl,--soname=foo'):
  643.                 env['WL_SONAME_SUPPORTED'] = True
  644.  
  645.     # bug 2181 on clang warning suppressions
  646.     if conf.env['CXX_NAME'] in ['clang']:
  647.         if Utils.unversioned_sys_platform() == 'darwin':
  648.             if tuple(map(int, conf.env['CC_VERSION'])) >= darwin_clang_version_warn_unused_local_typedefs:
  649.                 env.append_value('CXXFLAGS', '-Wno-unused-local-typedefs')
  650.             if tuple(map(int, conf.env['CC_VERSION'])) >= darwin_clang_version_warn_potentially_evaluated:
  651.                 env.append_value('CXXFLAGS', '-Wno-potentially-evaluated-expression')
  652.         else:
  653.             if tuple(map(int, conf.env['CC_VERSION'])) >= clang_version_warn_unused_local_typedefs:
  654.                 env.append_value('CXXFLAGS', '-Wno-unused-local-typedefs')
  655.             if tuple(map(int, conf.env['CC_VERSION'])) >= clang_version_warn_potentially_evaluated:
  656.                 env.append_value('CXXFLAGS', '-Wno-potentially-evaluated-expression')
  657.     env['ENABLE_STATIC_NS3'] = False
  658.     if Options.options.enable_static:
  659.         if Utils.unversioned_sys_platform() == 'darwin':
  660.             if conf.check_compilation_flag(flag=[], linkflags=['-Wl,-all_load']):
  661.                 conf.report_optional_feature("static", "Static build", True, '')
  662.                 env['ENABLE_STATIC_NS3'] = True
  663.             else:
  664.                 conf.report_optional_feature("static", "Static build", False,
  665.                                              "Link flag -Wl,-all_load does not work")
  666.         else:
  667.             if conf.check_compilation_flag(flag=[], linkflags=['-Wl,--whole-archive,-Bstatic', '-Wl,-Bdynamic,--no-whole-archive']):
  668.                 conf.report_optional_feature("static", "Static build", True, '')
  669.                 env['ENABLE_STATIC_NS3'] = True
  670.             else:
  671.                 conf.report_optional_feature("static", "Static build", False,
  672.                                              "Link flag -Wl,--whole-archive,-Bstatic does not work")
  673.  
  674.     # Enables C++-11 support by default, unless user specified another option
  675.     # Warn the user if the CXX Standard flag provided was not recognized  
  676.     if conf.check_compilation_flag(Options.options.cxx_standard):
  677.         env.append_value('CXXFLAGS', Options.options.cxx_standard)
  678.     else:
  679.         Logs.warn("CXX Standard flag " + Options.options.cxx_standard + " was not recognized, using compiler's default")
  680.  
  681.     # Find Boost libraries by modules
  682.     conf.env['REQUIRED_BOOST_LIBS'] = []
  683.     for modules_dir in ['src', 'contrib']:
  684.         conf.recurse (modules_dir, name="get_required_boost_libs", mandatory=False)
  685.  
  686.     if conf.env['REQUIRED_BOOST_LIBS'] is not []:
  687.         conf.load('boost')
  688.         conf.check_boost(lib=' '.join (conf.env['REQUIRED_BOOST_LIBS']), mandatory=False)
  689.         if not conf.env['LIB_BOOST']:
  690.             conf.check_boost(lib=' '.join (conf.env['REQUIRED_BOOST_LIBS']), libpath="/usr/lib64", mandatory=False)
  691.             if not conf.env['LIB_BOOST']:
  692.                 conf.env['LIB_BOOST'] = []
  693.  
  694.     # Set this so that the lists won't be printed at the end of this
  695.     # configure command.
  696.     conf.env['PRINT_BUILT_MODULES_AT_END'] = False
  697.  
  698.     conf.env['MODULES_NOT_BUILT'] = []
  699.  
  700.     conf.recurse('bindings/python')
  701.  
  702.     conf.recurse('src')
  703.     # New Code
  704.     opt.recurse('contrib/cryptopp')
  705.     # New Code
  706.     conf.recurse('contrib')
  707.  
  708.     # Set the list of enabled modules.
  709.     if Options.options.enable_modules:
  710.         # Use the modules explicitly enabled.
  711.         _enabled_mods = []
  712.         _enabled_contrib_mods = []
  713.         for mod in Options.options.enable_modules.split(','):
  714.             if mod in conf.env['NS3_MODULES'] and mod.startswith('ns3-'):
  715.                 _enabled_mods.append(mod)
  716.             elif 'ns3-' + mod in conf.env['NS3_MODULES']:
  717.                 _enabled_mods.append('ns3-' + mod)
  718.             elif mod in conf.env['NS3_CONTRIBUTED_MODULES'] and mod.startswith('ns3-'):
  719.                 _enabled_contrib_mods.append(mod)
  720.             elif 'ns3-' + mod in conf.env['NS3_CONTRIBUTED_MODULES']:
  721.                 _enabled_contrib_mods.append('ns3-' + mod)
  722.         conf.env['NS3_ENABLED_MODULES'] = _enabled_mods
  723.         conf.env['NS3_ENABLED_CONTRIBUTED_MODULES'] = _enabled_contrib_mods
  724.        
  725.     else:
  726.         # Use the enabled modules list from the ns3 configuration file.
  727.         if modules_enabled[0] == 'all_modules':
  728.             # Enable all modules if requested.
  729.             conf.env['NS3_ENABLED_MODULES'] = conf.env['NS3_MODULES']
  730.             conf.env['NS3_ENABLED_CONTRIBUTED_MODULES'] = conf.env['NS3_CONTRIBUTED_MODULES']
  731.         else:
  732.             # Enable the modules from the list.
  733.             _enabled_mods = []
  734.             _enabled_contrib_mods = []
  735.             for mod in modules_enabled:
  736.                 if mod in conf.env['NS3_MODULES'] and mod.startswith('ns3-'):
  737.                     _enabled_mods.append(mod)
  738.                 elif 'ns3-' + mod in conf.env['NS3_MODULES']:
  739.                     _enabled_mods.append('ns3-' + mod)
  740.                 elif mod in conf.env['NS3_CONTRIBUTED_MODULES'] and mod.startswith('ns3-'):
  741.                     _enabled_contrib_mods.append(mod)
  742.                 elif 'ns3-' + mod in conf.env['NS3_CONTRIBUTED_MODULES']:
  743.                     _enabled_contrib_mods.append('ns3-' + mod)
  744.             conf.env['NS3_ENABLED_MODULES'] = _enabled_mods
  745.             conf.env['NS3_ENABLED_CONTRIBUTED_MODULES'] = _enabled_contrib_mods
  746.  
  747.     # Add the template module to the list of enabled modules that
  748.     # should not be built if this is a static build on Darwin.  They
  749.     # don't work there for the template module, and this is probably
  750.     # because the template module has no source files.
  751.     if conf.env['ENABLE_STATIC_NS3'] and sys.platform == 'darwin':
  752.         conf.env['MODULES_NOT_BUILT'].append('template')
  753.  
  754.     # Remove these modules from the list of enabled modules.
  755.     for not_built in conf.env['MODULES_NOT_BUILT']:
  756.         not_built_name = 'ns3-' + not_built
  757.         if not_built_name in conf.env['NS3_ENABLED_MODULES']:
  758.             conf.env['NS3_ENABLED_MODULES'].remove(not_built_name)
  759.             if not conf.env['NS3_ENABLED_MODULES']:
  760.                 raise WafError('Exiting because the ' + not_built + ' module can not be built and it was the only one enabled.')
  761.         elif not_built_name in conf.env['NS3_ENABLED_CONTRIBUTED_MODULES']:
  762.             conf.env['NS3_ENABLED_CONTRIBUTED_MODULES'].remove(not_built_name)
  763.  
  764.     # for suid bits
  765.     try:
  766.         conf.find_program('sudo', var='SUDO')
  767.     except WafError:
  768.         pass
  769.  
  770.     why_not_sudo = "because we like it"
  771.     if Options.options.enable_sudo and conf.env['SUDO']:
  772.         env['ENABLE_SUDO'] = True
  773.     else:
  774.         env['ENABLE_SUDO'] = False
  775.         if Options.options.enable_sudo:
  776.             why_not_sudo = "program sudo not found"
  777.         else:
  778.             why_not_sudo = "option --enable-sudo not selected"
  779.  
  780.     conf.report_optional_feature("ENABLE_SUDO", "Use sudo to set suid bit", env['ENABLE_SUDO'], why_not_sudo)
  781.  
  782.     # Decide if tests will be built or not.
  783.     if Options.options.enable_tests:
  784.         # Tests were explicitly enabled.
  785.         env['ENABLE_TESTS'] = True
  786.         why_not_tests = "option --enable-tests selected"
  787.     elif Options.options.disable_tests:
  788.         # Tests were explicitly disabled.
  789.         env['ENABLE_TESTS'] = False
  790.         why_not_tests = "option --disable-tests selected"
  791.     else:
  792.         # Enable tests based on the ns3 configuration file.
  793.         env['ENABLE_TESTS'] = tests_enabled
  794.         if config_file_exists:
  795.             why_not_tests = "based on configuration file"
  796.         elif tests_enabled:
  797.             why_not_tests = "defaults to enabled"
  798.         else:
  799.             why_not_tests = "defaults to disabled"
  800.  
  801.     conf.report_optional_feature("ENABLE_TESTS", "Tests", env['ENABLE_TESTS'], why_not_tests)
  802.  
  803.     # Decide if examples will be built or not.
  804.     if Options.options.enable_examples:
  805.         # Examples were explicitly enabled.
  806.         env['ENABLE_EXAMPLES'] = True
  807.         why_not_examples = "option --enable-examples selected"
  808.     elif Options.options.disable_examples:
  809.         # Examples were explicitly disabled.
  810.         env['ENABLE_EXAMPLES'] = False
  811.         why_not_examples = "option --disable-examples selected"
  812.     else:
  813.         # Enable examples based on the ns3 configuration file.
  814.         env['ENABLE_EXAMPLES'] = examples_enabled
  815.         if config_file_exists:
  816.             why_not_examples = "based on configuration file"
  817.         elif examples_enabled:
  818.             why_not_examples = "defaults to enabled"
  819.         else:
  820.             why_not_examples = "defaults to disabled"
  821.  
  822.     conf.report_optional_feature("ENABLE_EXAMPLES", "Examples", env['ENABLE_EXAMPLES'],
  823.                                  why_not_examples)
  824.     try:
  825.         for dir in os.listdir('examples'):
  826.             if dir.startswith('.') or dir == 'CVS':
  827.                 continue
  828.             conf.env.append_value('EXAMPLE_DIRECTORIES', dir)
  829.     except OSError:
  830.         return
  831.  
  832.     env['VALGRIND_FOUND'] = False
  833.     try:
  834.         conf.find_program('valgrind', var='VALGRIND')
  835.         env['VALGRIND_FOUND'] = True
  836.     except WafError:
  837.         pass
  838.  
  839.     # These flags are used for the implicitly dependent modules.
  840.     if env['ENABLE_STATIC_NS3']:
  841.         if sys.platform == 'darwin':
  842.             env.STLIB_MARKER = '-Wl,-all_load'
  843.         else:
  844.             env.STLIB_MARKER = '-Wl,--whole-archive,-Bstatic'
  845.             env.SHLIB_MARKER = '-Wl,-Bdynamic,--no-whole-archive'
  846.  
  847.  
  848.     have_gsl = conf.check_cfg(package='gsl', args=['--cflags', '--libs'],
  849.                               uselib_store='GSL', mandatory=False)
  850.     conf.env['ENABLE_GSL'] = have_gsl
  851.     conf.report_optional_feature("GSL", "GNU Scientific Library (GSL)",
  852.                                  conf.env['ENABLE_GSL'],
  853.                                  "GSL not found")
  854.  
  855.     conf.find_program('libgcrypt-config', var='LIBGCRYPT_CONFIG', msg="libgcrypt-config", mandatory=False)
  856.     if env.LIBGCRYPT_CONFIG:
  857.         conf.check_cfg(path=env.LIBGCRYPT_CONFIG, msg="Checking for libgcrypt", args='--cflags --libs', package='',
  858.                                      define_name="HAVE_GCRYPT", global_define=True, uselib_store='GCRYPT', mandatory=False)
  859.     conf.report_optional_feature("libgcrypt", "Gcrypt library",
  860.                                  conf.env.HAVE_GCRYPT, "libgcrypt not found: you can use libgcrypt-config to find its location.")
  861.  
  862.     why_not_desmetrics = "defaults to disabled"
  863.     if Options.options.enable_desmetrics:
  864.         conf.env['ENABLE_DES_METRICS'] = True
  865.         env.append_value('DEFINES', 'ENABLE_DES_METRICS')
  866.         why_not_desmetrics = "option --enable-des-metrics selected"
  867.     conf.report_optional_feature("DES Metrics", "DES Metrics event collection", conf.env['ENABLE_DES_METRICS'], why_not_desmetrics)
  868.  
  869.  
  870.     # for compiling C code, copy over the CXX* flags
  871.     conf.env.append_value('CCFLAGS', conf.env['CXXFLAGS'])
  872.  
  873.     def add_gcc_flag(flag):
  874.         if env['COMPILER_CXX'] == 'g++' and 'CXXFLAGS' not in os.environ:
  875.             if conf.check_compilation_flag(flag, mode='cxx'):
  876.                 env.append_value('CXXFLAGS', flag)
  877.         if env['COMPILER_CC'] == 'gcc' and 'CCFLAGS' not in os.environ:
  878.             if conf.check_compilation_flag(flag, mode='cc'):
  879.                 env.append_value('CCFLAGS', flag)
  880.  
  881.     add_gcc_flag('-fstrict-aliasing')
  882.     add_gcc_flag('-Wstrict-aliasing')
  883.  
  884.     try:
  885.         conf.find_program('doxygen', var='DOXYGEN')
  886.     except WafError:
  887.         pass
  888.  
  889.     # append user defined flags after all our ones
  890.     for (confvar, envvar) in [['CCFLAGS', 'CCFLAGS_EXTRA'],
  891.                               ['CXXFLAGS', 'CXXFLAGS_EXTRA'],
  892.                               ['LINKFLAGS', 'LINKFLAGS_EXTRA'],
  893.                               ['LINKFLAGS', 'LDFLAGS_EXTRA']]:
  894.         if envvar in os.environ:
  895.             value = shlex.split(os.environ[envvar])
  896.             conf.env.append_value(confvar, value)
  897.  
  898.     print_config(env)
  899.    
  900.  
  901. class SuidBuild_task(Task.Task):
  902.     """task that makes a binary Suid
  903.    """
  904.     after = ['cxxprogram', 'cxxshlib', 'cxxstlib']
  905.     def __init__(self, *args, **kwargs):
  906.         super(SuidBuild_task, self).__init__(*args, **kwargs)
  907.         self.m_display = 'build-suid'
  908.         try:
  909.             program_obj = wutils.find_program(self.generator.name, self.generator.env)
  910.         except ValueError as ex:
  911.             raise WafError(str(ex))
  912.         program_node = program_obj.path.find_or_declare(program_obj.target)
  913.         self.filename = program_node.get_bld().abspath()
  914.  
  915.  
  916.     def run(self):
  917.         print('setting suid bit on executable ' + self.filename, file=sys.stderr)
  918.         if subprocess.Popen(['sudo', 'chown', 'root', self.filename]).wait():
  919.             return 1
  920.         if subprocess.Popen(['sudo', 'chmod', 'u+s', self.filename]).wait():
  921.             return 1
  922.         return 0
  923.  
  924.     def runnable_status(self):
  925.         "RUN_ME SKIP_ME or ASK_LATER"
  926.         try:
  927.             st = os.stat(self.filename)
  928.         except OSError:
  929.             return Task.ASK_LATER
  930.         if st.st_uid == 0:
  931.             return Task.SKIP_ME
  932.         else:
  933.             return Task.RUN_ME
  934.  
  935. def create_suid_program(bld, name):
  936.     grp = bld.current_group
  937.     bld.add_group() # this to make sure no two sudo tasks run at the same time
  938.     program = bld(features='cxx cxxprogram')
  939.     program.is_ns3_program = True
  940.     program.module_deps = list()
  941.     program.name = name
  942.     program.target = "%s%s-%s%s" % (wutils.APPNAME, wutils.VERSION, name, bld.env.BUILD_SUFFIX)
  943.  
  944.     if bld.env['ENABLE_SUDO']:
  945.         program.create_task("SuidBuild_task")
  946.  
  947.     bld.set_group(grp)
  948.  
  949.     return program
  950.  
  951. def create_ns3_program(bld, name, dependencies=('core',)):
  952.     program = bld(features='cxx cxxprogram')
  953.  
  954.     program.is_ns3_program = True
  955.     program.name = name
  956.     program.target = "%s%s-%s%s" % (wutils.APPNAME, wutils.VERSION, name, bld.env.BUILD_SUFFIX)
  957.     # Each of the modules this program depends on has its own library.
  958.     program.ns3_module_dependencies = ['ns3-'+dep for dep in dependencies]
  959.     program.includes = "#"
  960.     program.use = program.ns3_module_dependencies
  961.     if program.env['ENABLE_STATIC_NS3']:
  962.         if sys.platform == 'darwin':
  963.             program.env.STLIB_MARKER = '-Wl,-all_load'
  964.         else:
  965.             program.env.STLIB_MARKER = '-Wl,-Bstatic,--whole-archive'
  966.             program.env.SHLIB_MARKER = '-Wl,-Bdynamic,--no-whole-archive'
  967.     else:
  968.         if program.env.DEST_BINFMT == 'elf':
  969.             # All ELF platforms are impacted but only the gcc compiler has a flag to fix it.
  970.             if 'gcc' in (program.env.CXX_NAME, program.env.CC_NAME):
  971.                 program.env.append_value ('SHLIB_MARKER', '-Wl,--no-as-needed')
  972.  
  973.     return program
  974.  
  975. def register_ns3_script(bld, name, dependencies=('core',)):
  976.     ns3_module_dependencies = ['ns3-'+dep for dep in dependencies]
  977.     bld.env.append_value('NS3_SCRIPT_DEPENDENCIES', [(name, ns3_module_dependencies)])
  978.  
  979. def add_examples_programs(bld):
  980.     env = bld.env
  981.     if env['ENABLE_EXAMPLES']:
  982.         # Add a define, so this is testable from code
  983.         env.append_value('DEFINES', 'NS3_ENABLE_EXAMPLES')
  984.  
  985.         try:
  986.             for dir in os.listdir('examples'):
  987.                 if dir.startswith('.') or dir == 'CVS':
  988.                     continue
  989.                 if os.path.isdir(os.path.join('examples', dir)):
  990.                     bld.recurse(os.path.join('examples', dir))
  991.         except OSError:
  992.             return
  993.  
  994. def add_scratch_programs(bld):
  995.     all_modules = [mod[len("ns3-"):] for mod in bld.env['NS3_ENABLED_MODULES'] + bld.env['NS3_ENABLED_CONTRIBUTED_MODULES']]
  996.  
  997.     try:
  998.         for filename in os.listdir("scratch"):
  999.             if filename.startswith('.') or filename == 'CVS':
  1000.                 continue
  1001.             if os.path.isdir(os.path.join("scratch", filename)):
  1002.                 obj = bld.create_ns3_program(filename, all_modules)
  1003.                 obj.path = obj.path.find_dir('scratch').find_dir(filename)
  1004.                 obj.source = obj.path.ant_glob('*.cc')
  1005.                 obj.target = filename
  1006.                 obj.name = obj.target
  1007.                 obj.install_path = None
  1008.             elif filename.endswith(".cc"):
  1009.                 name = filename[:-len(".cc")]
  1010.                 obj = bld.create_ns3_program(name, all_modules)
  1011.                 obj.path = obj.path.find_dir('scratch')
  1012.                 obj.source = filename
  1013.                 obj.target = name
  1014.                 obj.name = obj.target
  1015.                 obj.install_path = None
  1016.     except OSError:
  1017.         return
  1018.  
  1019. def _get_all_task_gen(self):
  1020.     for group in self.groups:
  1021.         for taskgen in group:
  1022.             yield taskgen
  1023.  
  1024.  
  1025. # ok, so WAF does not provide an API to prevent an
  1026. # arbitrary taskgen from running; we have to muck around with
  1027. # WAF internal state, something that might stop working if
  1028. # WAF is upgraded...
  1029. def _exclude_taskgen(self, taskgen):
  1030.     for group in self.groups:
  1031.         for tg1 in group:
  1032.             if tg1 is taskgen:
  1033.                 group.remove(tg1)
  1034.                 break
  1035.         else:
  1036.             continue
  1037.         break
  1038.  
  1039.  
  1040. def _find_ns3_module(self, name):
  1041.     for obj in _get_all_task_gen(self):
  1042.         # disable the modules themselves
  1043.         if hasattr(obj, "is_ns3_module") and obj.name == name:
  1044.             return obj
  1045.     raise KeyError(name)
  1046.  
  1047. # Parse the waf lockfile generated by latest 'configure' operation
  1048. def get_build_profile(env=None):
  1049.     if env:
  1050.         return Options.options.build_profile
  1051.  
  1052.     lockfile = os.environ.get('WAFLOCK', '.lock-waf_%s_build' % sys.platform)
  1053.     with open(lockfile, "r") as f:
  1054.         for line in f:
  1055.             if line.startswith("options ="):
  1056.                 _, val = line.split('=', 1)
  1057.                 for x in val.split(','):
  1058.                     optkey, optval = x.split(':')
  1059.                     if (optkey.lstrip() == '\'build_profile\''):
  1060.                         return str(optval.lstrip()).replace("'","")
  1061.  
  1062.     return "not found"
  1063.  
  1064. def build(bld):
  1065.     env = bld.env
  1066.  
  1067.     if Options.options.check_config:
  1068.         print_config(env, 'build')
  1069.     else:
  1070.         if Options.options.check_profile:
  1071.             profile = get_build_profile()
  1072.             print("Build profile: %s" % profile)
  1073.        
  1074.     if Options.options.check_profile or Options.options.check_config:
  1075.         raise SystemExit(0)
  1076.         return
  1077.  
  1078.     # If --enabled-modules option was given, then print a warning
  1079.     # message and exit this function.
  1080.     if Options.options.enable_modules:
  1081.         Logs.warn("No modules were built.  Use waf configure --enable-modules to enable modules.")
  1082.         return
  1083.  
  1084.     bld.env['NS3_MODULES_WITH_TEST_LIBRARIES'] = []
  1085.     bld.env['NS3_ENABLED_MODULE_TEST_LIBRARIES'] = []
  1086.     bld.env['NS3_SCRIPT_DEPENDENCIES'] = []
  1087.     bld.env['NS3_RUNNABLE_PROGRAMS'] = []
  1088.     bld.env['NS3_RUNNABLE_SCRIPTS'] = []
  1089.  
  1090.     wutils.bld = bld
  1091.     if Options.options.no_task_lines:
  1092.         from waflib import Runner
  1093.         def null_printout(s):
  1094.             pass
  1095.         Runner.printout = null_printout
  1096.  
  1097.     Options.cwd_launch = bld.path.abspath()
  1098.     bld.create_ns3_program = types.MethodType(create_ns3_program, bld)
  1099.     bld.register_ns3_script = types.MethodType(register_ns3_script, bld)
  1100.     bld.create_suid_program = types.MethodType(create_suid_program, bld)
  1101.     bld.__class__.all_task_gen = property(_get_all_task_gen)
  1102.     bld.exclude_taskgen = types.MethodType(_exclude_taskgen, bld)
  1103.     bld.find_ns3_module = types.MethodType(_find_ns3_module, bld)
  1104.  
  1105.     # Clean documentation build directories; other cleaning happens later
  1106.     if bld.cmd == 'clean':
  1107.         _cleandocs()
  1108.  
  1109.     # process subfolders from here
  1110.     bld.recurse('src')
  1111.     bld.recurse('contrib')
  1112.  
  1113.     # If modules have been enabled, then set lists of enabled modules
  1114.     # and enabled module test libraries.
  1115.     if env['NS3_ENABLED_MODULES'] or env['NS3_ENABLED_CONTRIBUTED_MODULES']:
  1116.  
  1117.         modules = env['NS3_ENABLED_MODULES']
  1118.         contribModules = env['NS3_ENABLED_CONTRIBUTED_MODULES']
  1119.  
  1120.         # Find out about additional modules that need to be enabled
  1121.         # due to dependency constraints.
  1122.         changed = True
  1123.         while changed:
  1124.             changed = False
  1125.             for module in modules + contribModules:
  1126.                 module_obj = bld.get_tgen_by_name(module)
  1127.                 if module_obj is None:
  1128.                     raise ValueError("module %s not found" % module)
  1129.                 # Each enabled module has its own library.
  1130.                 for dep in module_obj.use:
  1131.                     if not dep.startswith('ns3-'):
  1132.                         continue
  1133.                     if dep not in modules and dep not in contribModules:
  1134.                         if dep in env['NS3_MODULES']:
  1135.                             modules.append(dep)
  1136.                             changed = True
  1137.                         elif dep in env['NS3_CONTRIBUTED_MODULES']:
  1138.                             contribModules.append(dep)
  1139.                             changed = True
  1140.                         else:
  1141.                             Logs.error("Error:  Cannot find dependency \'" + dep[4:] + "\' of module \'"
  1142.                                        + module[4:] + "\'; check the module wscript for errors.")
  1143.                             raise SystemExit(1)
  1144.  
  1145.         env['NS3_ENABLED_MODULES'] = modules
  1146.  
  1147.         env['NS3_ENABLED_CONTRIBUTED_MODULES'] = contribModules
  1148.  
  1149.         # If tests are being built, then set the list of the enabled
  1150.         # module test libraries.
  1151.         if env['ENABLE_TESTS']:
  1152.             for (mod, testlib) in bld.env['NS3_MODULES_WITH_TEST_LIBRARIES']:
  1153.                 if mod in bld.env['NS3_ENABLED_MODULES'] or mod in bld.env['NS3_ENABLED_CONTRIBUTED_MODULES']:
  1154.                     bld.env.append_value('NS3_ENABLED_MODULE_TEST_LIBRARIES', testlib)
  1155.  
  1156.     add_examples_programs(bld)
  1157.     add_scratch_programs(bld)
  1158.  
  1159.     if env['NS3_ENABLED_MODULES'] or env['NS3_ENABLED_CONTRIBUTED_MODULES']:
  1160.         modules = env['NS3_ENABLED_MODULES']
  1161.         contribModules = env['NS3_ENABLED_CONTRIBUTED_MODULES']
  1162.  
  1163.         # Exclude the programs other misc task gens that depend on disabled modules
  1164.         for obj in list(bld.all_task_gen):
  1165.  
  1166.             # check for ns3moduleheader_taskgen
  1167.             if 'ns3moduleheader' in getattr(obj, "features", []):
  1168.                 if ("ns3-%s" % obj.module) not in modules and ("ns3-%s" % obj.module) not in contribModules:
  1169.                     obj.mode = 'remove' # tell it to remove headers instead of installing
  1170.  
  1171.             # check for programs
  1172.             if hasattr(obj, 'ns3_module_dependencies'):
  1173.                 # this is an NS-3 program (bld.create_ns3_program)
  1174.                 program_built = True
  1175.                 for dep in obj.ns3_module_dependencies:
  1176.                     if dep not in modules and dep not in contribModules: # prog. depends on a module that isn't enabled?
  1177.                         bld.exclude_taskgen(obj)
  1178.                         program_built = False
  1179.                         break
  1180.  
  1181.                 # Add this program to the list if all of its
  1182.                 # dependencies will be built.
  1183.                 if program_built:
  1184.                     object_name = "%s%s-%s%s" % (wutils.APPNAME, wutils.VERSION,
  1185.                                                   obj.name, bld.env.BUILD_SUFFIX)
  1186.  
  1187.                     # Get the relative path to the program from the
  1188.                     # launch directory.
  1189.                     launch_dir = os.path.abspath(Context.launch_dir)
  1190.                     object_relative_path = os.path.join(
  1191.                         wutils.relpath(obj.path.get_bld().abspath(), launch_dir),
  1192.                         object_name)
  1193.  
  1194.                     bld.env.append_value('NS3_RUNNABLE_PROGRAMS', object_relative_path)
  1195.  
  1196.             # disable the modules themselves
  1197.             if hasattr(obj, "is_ns3_module") and obj.name not in modules and obj.name not in contribModules:
  1198.                 bld.exclude_taskgen(obj) # kill the module
  1199.  
  1200.             # disable the module test libraries
  1201.             if hasattr(obj, "is_ns3_module_test_library"):
  1202.                 if not env['ENABLE_TESTS'] or ((obj.module_name not in modules) and (obj.module_name not in contribModules)) :
  1203.                     bld.exclude_taskgen(obj) # kill the module test library
  1204.  
  1205.             # disable the ns3header_taskgen
  1206.             if 'ns3header' in getattr(obj, "features", []):
  1207.                 if ("ns3-%s" % obj.module) not in modules and ("ns3-%s" % obj.module) not in contribModules:
  1208.                     obj.mode = 'remove' # tell it to remove headers instead of installing
  1209.  
  1210.             # disable the ns3privateheader_taskgen
  1211.             if 'ns3privateheader' in getattr(obj, "features", []):
  1212.                 if ("ns3-%s" % obj.module) not in modules and ("ns3-%s" % obj.module) not in contribModules:
  1213.  
  1214.                     obj.mode = 'remove' # tell it to remove headers instead of installing
  1215.  
  1216.             # disable pcfile taskgens for disabled modules
  1217.             if 'ns3pcfile' in getattr(obj, "features", []):
  1218.                 if obj.module not in bld.env.NS3_ENABLED_MODULES and obj.module not in bld.env.NS3_ENABLED_CONTRIBUTED_MODULES:
  1219.                     bld.exclude_taskgen(obj)
  1220.  
  1221.             # disable python bindings for disabled modules
  1222.             if 'pybindgen' in obj.name:
  1223.                 if ("ns3-%s" % obj.module) not in modules and ("ns3-%s" % obj.module) not in contribModules:
  1224.                     bld.exclude_taskgen(obj)
  1225.             if 'pyext' in getattr(obj, "features", []):
  1226.                 if ("ns3-%s" % obj.module) not in modules and ("ns3-%s" % obj.module) not in contribModules:
  1227.                     bld.exclude_taskgen(obj)
  1228.  
  1229.  
  1230.     if env['NS3_ENABLED_MODULES']:
  1231.         env['NS3_ENABLED_MODULES'] = list(modules)
  1232.  
  1233.     if env['NS3_ENABLED_CONTRIBUTED_MODULES']:
  1234.         env['NS3_ENABLED_CONTRIBUTED_MODULES'] = list(contribModules)
  1235.  
  1236.     # Determine which scripts will be runnable.
  1237.     for (script, dependencies) in bld.env['NS3_SCRIPT_DEPENDENCIES']:
  1238.         script_runnable = True
  1239.         for dep in dependencies:
  1240.             if dep not in modules and dep not in contribModules:
  1241.                 script_runnable = False
  1242.                 break
  1243.  
  1244.         # Add this script to the list if all of its dependencies will
  1245.         # be built.
  1246.         if script_runnable:
  1247.             bld.env.append_value('NS3_RUNNABLE_SCRIPTS', script)
  1248.  
  1249.     bld.recurse('bindings/python')
  1250.  
  1251.     # Process this subfolder here after the lists of enabled modules
  1252.     # and module test libraries have been set.
  1253.     bld.recurse('utils')
  1254.  
  1255.     # Set this so that the lists will be printed at the end of this
  1256.     # build command.
  1257.     bld.env['PRINT_BUILT_MODULES_AT_END'] = True
  1258.  
  1259.     # Do not print the modules built if build command was "clean"
  1260.     if bld.cmd == 'clean':
  1261.         bld.env['PRINT_BUILT_MODULES_AT_END'] = False
  1262.  
  1263.     if Options.options.run:
  1264.         # Check that the requested program name is valid
  1265.         program_name, dummy_program_argv = wutils.get_run_program(Options.options.run, wutils.get_command_template(env))
  1266.  
  1267.         # When --run'ing a program, tell WAF to only build that program,
  1268.         # nothing more; this greatly speeds up compilation when all you
  1269.         # want to do is run a test program.
  1270.         Options.options.targets += ',' + os.path.basename(program_name)
  1271.         if getattr(Options.options, "visualize", False):
  1272.             program_obj = wutils.find_program(program_name, bld.env)
  1273.             program_obj.use.append('ns3-visualizer')
  1274.         for gen in bld.all_task_gen:
  1275.             if type(gen).__name__ in ['ns3header_taskgen', 'ns3privateheader_taskgen', 'ns3moduleheader_taskgen']:
  1276.                 gen.post()
  1277.  
  1278.     if Options.options.run or Options.options.pyrun:
  1279.         bld.env['PRINT_BUILT_MODULES_AT_END'] = False
  1280.  
  1281.     if Options.options.doxygen_no_build:
  1282.         _doxygen(bld, skip_pid=True)
  1283.         raise SystemExit(0)
  1284.  
  1285.     if Options.options.run_no_build:
  1286.         # Check that the requested program name is valid
  1287.         program_name, dummy_program_argv = wutils.get_run_program(Options.options.run_no_build, wutils.get_command_template(bld.env))
  1288.         # Run the program
  1289.         wutils.run_program(Options.options.run_no_build, bld.env, wutils.get_command_template(bld.env), visualize=Options.options.visualize)
  1290.         raise SystemExit(0)
  1291.  
  1292.     if Options.options.pyrun_no_build:
  1293.         wutils.run_python_program(Options.options.pyrun_no_build, bld.env,
  1294.                                   visualize=Options.options.visualize)
  1295.         raise SystemExit(0)
  1296.  
  1297. def _cleandir(name):
  1298.     try:
  1299.         shutil.rmtree(name)
  1300.     except:
  1301.         pass
  1302.  
  1303. def _cleandocs():
  1304.     _cleandir('doc/html')
  1305.     _cleandir('doc/html-warn')
  1306.     _cleandir('doc/manual/build')
  1307.     _cleandir('doc/manual/source-temp')
  1308.     _cleandir('doc/tutorial/build')
  1309.     _cleandir('doc/models/build')
  1310.     _cleandir('doc/models/source-temp')
  1311.  
  1312. # 'distclean' typically only cleans out build/ directory
  1313. # Here we clean out any build or documentation artifacts not in build/
  1314. def distclean(ctx):
  1315.     _cleandocs()
  1316.     # Now call waf's normal distclean
  1317.     Scripting.distclean(ctx)
  1318.  
  1319. def shutdown(ctx):
  1320.     bld = wutils.bld
  1321.     if wutils.bld is None:
  1322.         return
  1323.     env = bld.env
  1324.  
  1325.     # Only print the lists if a build was done.
  1326.     if (env['PRINT_BUILT_MODULES_AT_END']):
  1327.  
  1328.         # Print the list of built modules.
  1329.         print()
  1330.         print('Modules built:')
  1331.         names_without_prefix = []
  1332.         for name in env['NS3_ENABLED_MODULES'] + env['NS3_ENABLED_CONTRIBUTED_MODULES']:
  1333.             name1 = name[len('ns3-'):]
  1334.             if name not in env.MODULAR_BINDINGS_MODULES:
  1335.                 name1 += " (no Python)"
  1336.             names_without_prefix.append(name1)
  1337.         print_module_names(names_without_prefix)
  1338.         print()
  1339.  
  1340.         # Print the list of enabled modules that were not built.
  1341.         if env['MODULES_NOT_BUILT']:
  1342.             print('Modules not built (see ns-3 tutorial for explanation):')
  1343.             print_module_names(env['MODULES_NOT_BUILT'])
  1344.             print()
  1345.  
  1346.         # Set this so that the lists won't be printed until the next
  1347.         # build is done.
  1348.         bld.env['PRINT_BUILT_MODULES_AT_END'] = False
  1349.  
  1350.     # Write the build status file.
  1351.     build_status_file = os.path.join(bld.out_dir, 'build-status.py')
  1352.     out = open(build_status_file, 'w')
  1353.     out.write('#! /usr/bin/env python3\n')
  1354.     out.write('\n')
  1355.     out.write('# Programs that are runnable.\n')
  1356.     out.write('ns3_runnable_programs = ' + str(env['NS3_RUNNABLE_PROGRAMS']) + '\n')
  1357.     out.write('\n')
  1358.     out.write('# Scripts that are runnable.\n')
  1359.     out.write('ns3_runnable_scripts = ' + str(env['NS3_RUNNABLE_SCRIPTS']) + '\n')
  1360.     out.write('\n')
  1361.     out.close()
  1362.  
  1363.     if Options.options.lcov_report:
  1364.         lcov_report(bld)
  1365.  
  1366.     if Options.options.lcov_zerocounters:
  1367.         lcov_zerocounters(bld)
  1368.  
  1369.     if Options.options.run:
  1370.         wutils.run_program(Options.options.run, env, wutils.get_command_template(env),
  1371.                            visualize=Options.options.visualize)
  1372.         raise SystemExit(0)
  1373.  
  1374.     if Options.options.pyrun:
  1375.         wutils.run_python_program(Options.options.pyrun, env,
  1376.                                   visualize=Options.options.visualize)
  1377.         raise SystemExit(0)
  1378.  
  1379.     if Options.options.shell:
  1380.         raise WafError("Please run `./waf shell' now, instead of `./waf --shell'")
  1381.  
  1382.     if Options.options.check:
  1383.         raise WafError("Please run `./test.py' now, instead of `./waf --check'")
  1384.  
  1385.     check_shell(bld)
  1386.  
  1387.  
  1388.  
  1389. class CheckContext(Context.Context):
  1390.     """run the equivalent of the old ns-3 unit tests using test.py"""
  1391.     cmd = 'check'
  1392.     def execute(self):
  1393.         # first we execute the build
  1394.         bld = Context.create_context("build")
  1395.         bld.options = Options.options # provided for convenience
  1396.         bld.cmd = "build"
  1397.         bld.execute()
  1398.        
  1399.         wutils.bld = bld
  1400.         wutils.run_python_program("test.py -n -c core", bld.env)
  1401.  
  1402. def check_shell(bld):
  1403.     if ('NS3_MODULE_PATH' not in os.environ) or ('NS3_EXECUTABLE_PATH' not in os.environ):
  1404.         return
  1405.     env = bld.env
  1406.     correct_modpath = os.pathsep.join(env['NS3_MODULE_PATH'])
  1407.     found_modpath = os.environ['NS3_MODULE_PATH']
  1408.     correct_execpath = os.pathsep.join(env['NS3_EXECUTABLE_PATH'])
  1409.     found_execpath = os.environ['NS3_EXECUTABLE_PATH']
  1410.     if (found_modpath != correct_modpath) or (correct_execpath != found_execpath):
  1411.         msg = ("Detected shell (./waf shell) with incorrect configuration\n"
  1412.                "=========================================================\n"
  1413.                "Possible reasons for this problem:\n"
  1414.                "  1. You switched to another ns-3 tree from inside this shell\n"
  1415.                "  2. You switched ns-3 debug level (waf configure --debug)\n"
  1416.                "  3. You modified the list of built ns-3 modules\n"
  1417.                "You should correct this situation before running any program.  Possible solutions:\n"
  1418.                "  1. Exit this shell, and start a new one\n"
  1419.                "  2. Run a new nested shell")
  1420.         raise WafError(msg)
  1421.  
  1422.  
  1423. class Ns3ShellContext(Context.Context):
  1424.     """run a shell with an environment suitably modified to run locally built programs"""
  1425.     cmd = 'shell'
  1426.    
  1427.     def execute(self):
  1428.         # first we execute the build
  1429.         bld = Context.create_context("build")
  1430.         bld.options = Options.options # provided for convenience
  1431.         bld.cmd = "build"
  1432.         bld.execute()
  1433.  
  1434.         # Set this so that the lists won't be printed when the user
  1435.         # exits the shell.
  1436.         bld.env['PRINT_BUILT_MODULES_AT_END'] = False
  1437.        
  1438.         if sys.platform == 'win32':
  1439.             shell = os.environ.get("COMSPEC", "cmd.exe")
  1440.         else:
  1441.             shell = os.environ.get("SHELL", "/bin/sh")
  1442.  
  1443.         env = bld.env
  1444.         os_env = {
  1445.             'NS3_MODULE_PATH': os.pathsep.join(env['NS3_MODULE_PATH']),
  1446.             'NS3_EXECUTABLE_PATH': os.pathsep.join(env['NS3_EXECUTABLE_PATH']),
  1447.             }
  1448.         wutils.run_argv([shell], env, os_env)
  1449.  
  1450.  
  1451. def _print_introspected_doxygen(bld):
  1452.     env = wutils.bld.env
  1453.     proc_env = wutils.get_proc_env()
  1454.     try:
  1455.         program_obj = wutils.find_program('print-introspected-doxygen', env)
  1456.     except ValueError:
  1457.         Logs.warn("print-introspected-doxygen does not exist")
  1458.         raise SystemExit(1)
  1459.         return
  1460.  
  1461.     prog = program_obj.path.find_or_declare(program_obj.target).get_bld().abspath()
  1462.  
  1463.     if not os.path.exists(prog):
  1464.         Logs.error("print-introspected-doxygen has not been built yet."
  1465.                    " You need to build ns-3 at least once before "
  1466.                    "generating doxygen docs...")
  1467.         raise SystemExit(1)
  1468.  
  1469.     Logs.info("Running print-introspected-doxygen")
  1470.  
  1471.     # Create a header file with the introspected information.
  1472.     doxygen_out = open(os.path.join('doc', 'introspected-doxygen.h'), 'w')
  1473.     if subprocess.Popen([prog], stdout=doxygen_out, env=proc_env).wait():
  1474.         raise SystemExit(1)
  1475.     doxygen_out.close()
  1476.  
  1477.     # Create a text file with the introspected information.
  1478.     text_out = open(os.path.join('doc', 'ns3-object.txt'), 'w')
  1479.     if subprocess.Popen([prog, '--output-text'], stdout=text_out, env=proc_env).wait():
  1480.         raise SystemExit(1)
  1481.     text_out.close()
  1482.  
  1483.     # Gather the CommandLine doxy
  1484.     # test.py appears not to create or keep the output directory
  1485.     # if no real tests are run, so we just stuff all the
  1486.     # .command-line output files into testpy-output/
  1487.     # NS_COMMANDLINE_INTROSPECTION=".." test.py --nowaf --constrain=example
  1488.     Logs.info("Running CommandLine introspection")
  1489.     proc_env['NS_COMMANDLINE_INTROSPECTION'] = '..'
  1490.     subprocess.run(["./test.py", "--nowaf", "--constrain=example"],
  1491.                    env=proc_env, stdout=subprocess.DEVNULL)
  1492.    
  1493.     doxygen_out = os.path.join('doc', 'introspected-command-line.h')
  1494.     try:
  1495.         os.remove(doxygen_out)
  1496.     except OSError as e:
  1497.         pass
  1498.  
  1499.     with open(doxygen_out, 'w') as out_file:
  1500.         lines="""
  1501. /* This file is automatically generated by
  1502. CommandLine::PrintDoxygenUsage() from the CommandLine configuration
  1503. in various example programs.  Do not edit this file!  Edit the
  1504. CommandLine configuration in those files instead.
  1505. */\n
  1506. """
  1507.         out_file.write(lines)
  1508.     out_file.close()
  1509.  
  1510.     with open(doxygen_out,'a') as outfile:
  1511.         for in_file in glob.glob('testpy-output/*.command-line'):
  1512.             with open(in_file,'r') as infile:
  1513.                 outfile.write(infile.read())
  1514.                
  1515. def _doxygen(bld, skip_pid=False):
  1516.     env = wutils.bld.env
  1517.     proc_env = wutils.get_proc_env()
  1518.  
  1519.     if not env['DOXYGEN']:
  1520.         Logs.error("waf configure did not detect doxygen in the system -> cannot build api docs.")
  1521.         raise SystemExit(1)
  1522.         return
  1523.  
  1524.     if not skip_pid:
  1525.         _print_introspected_doxygen(bld)
  1526.  
  1527.     _getVersion()
  1528.     doxygen_config = os.path.join('doc', 'doxygen.conf')
  1529.     if subprocess.Popen(env['DOXYGEN'] + [doxygen_config]).wait():
  1530.         Logs.error("Doxygen build returned an error.")
  1531.         raise SystemExit(1)
  1532.  
  1533. def _docset(bld):
  1534.     # Get the doxygen config
  1535.     doxyfile = os.path.join('doc', 'doxygen.conf')
  1536.     Logs.info("docset: reading " + doxyfile)
  1537.     doxygen_config = open(doxyfile, 'r')
  1538.     doxygen_config_contents = doxygen_config.read()
  1539.     doxygen_config.close()
  1540.  
  1541.     # Create the output directory
  1542.     docset_path = os.path.join('doc', 'docset')
  1543.     Logs.info("docset: checking for output directory " + docset_path)
  1544.     if not os.path.exists(docset_path):
  1545.         Logs.info("docset: creating output directory " + docset_path)
  1546.         os.mkdir(docset_path)
  1547.  
  1548.     doxyfile = os.path.join('doc', 'doxygen.docset.conf')
  1549.     doxygen_config = open(doxyfile, 'w')
  1550.     Logs.info("docset: writing doxygen conf " + doxyfile)
  1551.     doxygen_config.write(doxygen_config_contents)
  1552.     doxygen_config.write(
  1553.         """
  1554.        HAVE_DOT = NO
  1555.        GENERATE_DOCSET = YES
  1556.        DISABLE_INDEX = YES
  1557.        SEARCHENGINE = NO
  1558.        GENERATE_TREEVIEW = NO
  1559.        OUTPUT_DIRECTORY=""" + docset_path + "\n"
  1560.         )
  1561.     doxygen_config.close()
  1562.  
  1563.     # Run Doxygen manually, so as to avoid build
  1564.     Logs.info("docset: running doxygen")
  1565.     env = wutils.bld.env
  1566.     _getVersion()
  1567.     if subprocess.Popen(env['DOXYGEN'] + [doxyfile]).wait():
  1568.         Logs.error("Doxygen docset build returned an error.")
  1569.         raise SystemExit(1)
  1570.  
  1571.     # Build docset
  1572.     docset_path = os.path.join(docset_path, 'html')
  1573.     Logs.info("docset: Running docset Make")
  1574.     if subprocess.Popen(["make"], cwd=docset_path).wait():
  1575.         Logs.error("Docset make returned and error.")
  1576.         raise SystemExit(1)
  1577.  
  1578.     # Additional steps from
  1579.     #   https://github.com/Kapeli/Dash-User-Contributions/tree/master/docsets/ns-3
  1580.     docset_out = os.path.join(docset_path, 'org.nsnam.ns3.docset')
  1581.     icons = os.path.join('doc', 'ns3_html_theme', 'static')
  1582.     shutil.copy(os.path.join(icons, 'ns-3-bars-16x16.png'),
  1583.                 os.path.join(docset_out, 'icon.png'))
  1584.     shutil.copy(os.path.join(icons, 'ns-3-bars-32x32.png'),
  1585.                 os.path.join(docset_out, '[email protected]'))
  1586.     shutil.copy(os.path.join(docset_path, 'Info.plist'),
  1587.                 os.path.join(docset_out, 'Contents'))
  1588.     shutil.move(docset_out, os.path.join('doc', 'ns-3.docset'))
  1589.  
  1590.     print("Docset built successfully.")
  1591.    
  1592.  
  1593. def _getVersion():
  1594.     """update the ns3_version.js file, when building documentation"""
  1595.  
  1596.     prog = "doc/ns3_html_theme/get_version.sh"
  1597.     if subprocess.Popen([prog]).wait() :
  1598.         Logs.error(prog + " returned an error")
  1599.         raise SystemExit(1)
  1600.  
  1601. class Ns3DoxygenContext(Context.Context):
  1602.     """do a full build, generate the introspected doxygen and then the doxygen"""
  1603.     cmd = 'doxygen'
  1604.     def execute(self):
  1605.         # first we execute the build
  1606.         bld = Context.create_context("build")
  1607.         bld.options = Options.options # provided for convenience
  1608.         bld.cmd = "build"
  1609.         bld.execute()
  1610.         _doxygen(bld)
  1611.  
  1612. class Ns3SphinxContext(Context.Context):
  1613.     """build the Sphinx documentation: manual, tutorial, models"""
  1614.    
  1615.     cmd = 'sphinx'
  1616.  
  1617.     def sphinx_build(self, path):
  1618.         print()
  1619.         print("[waf] Building sphinx docs for " + path)
  1620.         if subprocess.Popen(["make", "SPHINXOPTS=-N", "-k",
  1621.                              "html", "singlehtml", "latexpdf" ],
  1622.                             cwd=path).wait() :
  1623.             Logs.error("Sphinx build of " + path + " returned an error.")
  1624.             raise SystemExit(1)
  1625.  
  1626.     def execute(self):
  1627.         _getVersion()
  1628.         for sphinxdir in ["manual", "models", "tutorial"] :
  1629.             self.sphinx_build(os.path.join("doc", sphinxdir))
  1630.      
  1631.  
  1632. class Ns3DocContext(Context.Context):
  1633.     """build all the documentation: doxygen, manual, tutorial, models"""
  1634.    
  1635.     cmd = 'docs'
  1636.  
  1637.     def execute(self):
  1638.         steps = ['doxygen', 'sphinx']
  1639.         Options.commands = steps + Options.commands
  1640.        
  1641.    
  1642. def lcov_report(bld):
  1643.     env = bld.env
  1644.  
  1645.     if not env['GCOV_ENABLED']:
  1646.         raise WafError("project not configured for code coverage;"
  1647.                        " reconfigure with --enable-gcov")
  1648.     try:
  1649.         subprocess.call(["lcov", "--help"], stdout=subprocess.DEVNULL)
  1650.     except OSError as e:
  1651.         if e.errno == os.errno.ENOENT:
  1652.             raise WafError("Error: lcov program not found")
  1653.         else:
  1654.             raise
  1655.     try:
  1656.         subprocess.call(["genhtml", "--help"], stdout=subprocess.DEVNULL)
  1657.     except OSError as e:
  1658.         if e.errno == os.errno.ENOENT:
  1659.             raise WafError("Error: genhtml program not found")
  1660.         else:
  1661.             raise
  1662.     os.chdir(out)
  1663.     try:
  1664.         lcov_report_dir = 'lcov-report'
  1665.         create_dir_command = "rm -rf " + lcov_report_dir
  1666.         create_dir_command += " && mkdir " + lcov_report_dir + ";"
  1667.  
  1668.         if subprocess.Popen(create_dir_command, shell=True).wait():
  1669.             raise SystemExit(1)
  1670.  
  1671.         info_file = os.path.join(lcov_report_dir, 'report.info')
  1672.         lcov_command = "lcov -c -d . -o " + info_file
  1673.         lcov_command += " -b " + os.getcwd()
  1674.         if subprocess.Popen(lcov_command, shell=True).wait():
  1675.             raise SystemExit(1)
  1676.  
  1677.         genhtml_command = "genhtml -o " + lcov_report_dir
  1678.         genhtml_command += " " + info_file
  1679.         if subprocess.Popen(genhtml_command, shell=True).wait():
  1680.             raise SystemExit(1)
  1681.     finally:
  1682.         os.chdir("..")
  1683.  
  1684. def lcov_zerocounters(bld):
  1685.     env = bld.env
  1686.  
  1687.     if not env['GCOV_ENABLED']:
  1688.         raise WafError("project not configured for code coverage;"
  1689.                        " reconfigure with --enable-gcov")
  1690.     try:
  1691.         subprocess.call(["lcov", "--help"], stdout=subprocess.DEVNULL)
  1692.     except OSError as e:
  1693.         if e.errno == os.errno.ENOENT:
  1694.             raise WafError("Error: lcov program not found")
  1695.         else:
  1696.             raise
  1697.  
  1698.     os.chdir(out)
  1699.     lcov_clear_command = "lcov -d . --zerocounters"
  1700.     if subprocess.Popen(lcov_clear_command, shell=True).wait():
  1701.         raise SystemExit(1)
  1702.     os.chdir("..")
  1703.  
  1704.  
  1705. Please contact at adityatiwari1208@gmail.com if any suggestions are there.
Tags: NS3
Add Comment
Please, Sign In to add comment