util: introduce NDN_THROW

Refs: #4834
Change-Id: I35ff77a1d4e96caa17523cbdbb6f169390975d1b
diff --git a/.waf-tools/boost.py b/.waf-tools/boost.py
index d7e0107..4eddec7 100644
--- a/.waf-tools/boost.py
+++ b/.waf-tools/boost.py
@@ -145,7 +145,7 @@
 	opt.add_option('--boost-abi', type='string', default='', dest='boost_abi',
 				   help='''select libraries with tags (gd for debug, static is automatically added),
 				   see doc Boost, Getting Started, chapter 6.1''')
-	opt.add_option('--boost-linkage_autodetect', action="store_true", dest='boost_linkage_autodetect',
+	opt.add_option('--boost-linkage_autodetect', action='store_true', dest='boost_linkage_autodetect',
 				   help="auto-detect boost linkage options (don't get used to it / might break other stuff)")
 	opt.add_option('--boost-toolset', type='string',
 				   default='', dest='boost_toolset',
@@ -175,7 +175,7 @@
 		try:
 			txt = node.read()
 		except EnvironmentError:
-			Logs.error("Could not read the file %r" % node.abspath())
+			Logs.error('Could not read the file %r' % node.abspath())
 		else:
 			re_but1 = re.compile('^#define\\s+BOOST_LIB_VERSION\\s+"(.+)"', re.M)
 			m1 = re_but1.search(txt)
@@ -183,7 +183,7 @@
 			m2 = re_but2.search(txt)
 			if m1 and m2:
 				return (m1.group(1), m2.group(1))
-	return self.check_cxx(fragment=BOOST_VERSION_CODE, includes=[d], execute=True, define_ret=True).split(":")
+	return self.check_cxx(fragment=BOOST_VERSION_CODE, includes=[d], execute=True, define_ret=True).split(':')
 
 @conf
 def boost_get_includes(self, *k, **kw):
@@ -194,10 +194,10 @@
 		if self.__boost_get_version_file(d):
 			return d
 	if includes:
-		self.end_msg('headers not found in %s' % includes)
+		self.end_msg('headers not found in %s' % includes, 'YELLOW')
 		self.fatal('The configuration failed')
 	else:
-		self.end_msg('headers not found, please provide a --boost-includes argument (see help)')
+		self.end_msg('headers not found, please provide a --boost-includes argument (see help)', 'YELLOW')
 		self.fatal('The configuration failed')
 
 
@@ -240,10 +240,10 @@
 					break
 	if not path:
 		if libs:
-			self.end_msg('libs not found in %s' % libs)
+			self.end_msg('libs not found in %s' % libs, 'YELLOW')
 			self.fatal('The configuration failed')
 		else:
-			self.end_msg('libs not found, please provide a --boost-libs argument (see help)')
+			self.end_msg('libs not found, please provide a --boost-libs argument (see help)', 'YELLOW')
 			self.fatal('The configuration failed')
 
 	self.to_log('Found the boost path in %r with the libraries:' % path)
@@ -313,7 +313,7 @@
 					libs.append(format_lib_name(file.name))
 					break
 			else:
-				self.end_msg('lib %s not found in %s' % (lib, path.abspath()))
+				self.end_msg('lib %s not found in %s' % (lib, path.abspath()), 'YELLOW')
 				self.fatal('The configuration failed')
 		return libs
 
@@ -354,7 +354,7 @@
 	#      ... -mt is also the pthreads flag for HP/aCC
 	# -lpthread: GNU Linux, etc.
 	# --thread-safe: KAI C++
-	if Utils.unversioned_sys_platform() == "sunos":
+	if Utils.unversioned_sys_platform() == 'sunos':
 		# On Solaris (at least, for some versions), libc contains stubbed
 		# (non-functional) versions of the pthreads routines, so link-based
 		# tests will erroneously succeed.  (We need to link with -pthreads/-mt/
@@ -362,23 +362,22 @@
 		# a function called by this macro, so we could check for that, but
 		# who knows whether they'll stub that too in a future libc.)  So,
 		# we'll just look for -pthreads and -lpthread first:
-		boost_pthread_flags = ["-pthreads", "-lpthread", "-mt", "-pthread"]
+		boost_pthread_flags = ['-pthreads', '-lpthread', '-mt', '-pthread']
 	else:
-		boost_pthread_flags = ["", "-lpthreads", "-Kthread", "-kthread", "-llthread", "-pthread",
-							   "-pthreads", "-mthreads", "-lpthread", "--thread-safe", "-mt"]
+		boost_pthread_flags = ['', '-lpthreads', '-Kthread', '-kthread', '-llthread', '-pthread',
+							   '-pthreads', '-mthreads', '-lpthread', '--thread-safe', '-mt']
 
 	for boost_pthread_flag in boost_pthread_flags:
 		try:
 			self.env.stash()
 			self.env['CXXFLAGS_%s' % var] += [boost_pthread_flag]
 			self.env['LINKFLAGS_%s' % var] += [boost_pthread_flag]
-			self.check_cxx(code=PTHREAD_CODE, msg=None, use=var, execute=False)
-
+			self.check_cxx(code=PTHREAD_CODE, msg=None, use=var, execute=False, quiet=True)
 			self.end_msg(boost_pthread_flag)
 			return
 		except self.errors.ConfigurationError:
 			self.env.revert()
-	self.end_msg('None')
+	self.end_msg('none')
 
 @conf
 def check_boost(self, *k, **kw):
@@ -403,21 +402,24 @@
 
 	var = kw.get('uselib_store', 'BOOST')
 
-	self.find_program('dpkg-architecture', var='DPKG_ARCHITECTURE', mandatory=False)
-	if self.env.DPKG_ARCHITECTURE:
-		deb_host_multiarch = self.cmd_and_log([self.env.DPKG_ARCHITECTURE[0], '-qDEB_HOST_MULTIARCH'])
-		BOOST_LIBS.insert(0, '/usr/lib/%s' % deb_host_multiarch.strip())
+	if not self.env.DONE_FIND_BOOST_COMMON:
+		self.find_program('dpkg-architecture', var='DPKG_ARCHITECTURE', mandatory=False)
+		if self.env.DPKG_ARCHITECTURE:
+			deb_host_multiarch = self.cmd_and_log([self.env.DPKG_ARCHITECTURE[0], '-qDEB_HOST_MULTIARCH'])
+			BOOST_LIBS.insert(0, '/usr/lib/%s' % deb_host_multiarch.strip())
 
-	self.start_msg('Checking boost includes')
-	self.env['INCLUDES_%s' % var] = inc = self.boost_get_includes(**params)
-	versions = self.boost_get_version(inc)
-	self.env.BOOST_VERSION = versions[0]
-	self.env.BOOST_VERSION_NUMBER = int(versions[1])
-	self.end_msg("%d.%d.%d" % (int(versions[1]) / 100000,
-							   int(versions[1]) / 100 % 1000,
-							   int(versions[1]) % 100))
-	if Logs.verbose:
-		Logs.pprint('CYAN', '	path : %s' % self.env['INCLUDES_%s' % var])
+		self.start_msg('Checking boost includes')
+		self.env['INCLUDES_%s' % var] = inc = self.boost_get_includes(**params)
+		versions = self.boost_get_version(inc)
+		self.env.BOOST_VERSION = versions[0]
+		self.env.BOOST_VERSION_NUMBER = int(versions[1])
+		self.end_msg('%d.%d.%d' % (int(versions[1]) / 100000,
+								   int(versions[1]) / 100 % 1000,
+								   int(versions[1]) % 100))
+		if Logs.verbose:
+			Logs.pprint('CYAN', '	path : %s' % self.env['INCLUDES_%s' % var])
+
+		self.env.DONE_FIND_BOOST_COMMON = True
 
 	if not params['lib'] and not params['stlib']:
 		return
@@ -429,7 +431,7 @@
 	self.env['STLIBPATH_%s' % var] = [path]
 	self.env['LIB_%s' % var] = libs
 	self.env['STLIB_%s' % var] = stlibs
-	self.end_msg('ok')
+	self.end_msg(' '.join(libs + stlibs))
 	if Logs.verbose:
 		Logs.pprint('CYAN', '	path : %s' % path)
 		Logs.pprint('CYAN', '	shared libs : %s' % libs)
@@ -458,7 +460,7 @@
 			self.check_cxx(fragment=BOOST_LOG_CODE, use=var, execute=False)
 
 	if params.get('linkage_autodetect', False):
-		self.start_msg("Attempting to detect boost linkage flags")
+		self.start_msg('Attempting to detect boost linkage flags')
 		toolset = self.boost_get_toolset(kw.get('toolset', ''))
 		if toolset in ('vc',):
 			# disable auto-linking feature, causing error LNK1181
@@ -480,10 +482,10 @@
 			# we attempt to play with some known-to-work CXXFLAGS combinations
 			for cxxflags in (['/MD', '/EHsc'], []):
 				self.env.stash()
-				self.env["CXXFLAGS_%s" % var] += cxxflags
+				self.env['CXXFLAGS_%s' % var] += cxxflags
 				try:
 					try_link()
-					self.end_msg("ok: winning cxxflags combination: %s" % (self.env["CXXFLAGS_%s" % var]))
+					self.end_msg('ok: winning cxxflags combination: %s' % (self.env['CXXFLAGS_%s' % var]))
 					exc = None
 					break
 				except Errors.ConfigurationError as e:
@@ -491,17 +493,17 @@
 					exc = e
 
 			if exc is not None:
-				self.end_msg("Could not auto-detect boost linking flags combination, you may report it to boost.py author", ex=exc)
+				self.end_msg('Could not auto-detect boost linking flags combination, you may report it to boost.py author', ex=exc)
 				self.fatal('The configuration failed')
 		else:
-			self.end_msg("Boost linkage flags auto-detection not implemented (needed ?) for this toolchain")
+			self.end_msg('Boost linkage flags auto-detection not implemented (needed ?) for this toolchain')
 			self.fatal('The configuration failed')
 	else:
 		self.start_msg('Checking for boost linkage')
 		try:
 			try_link()
 		except Errors.ConfigurationError as e:
-			self.end_msg("Could not link against boost libraries using supplied options")
+			self.end_msg('Could not link against boost libraries using supplied options', 'YELLOW')
 			self.fatal('The configuration failed')
 		self.end_msg('ok')
 
diff --git a/ndn-cxx/util/exception.cpp b/ndn-cxx/util/exception.cpp
new file mode 100644
index 0000000..d143692
--- /dev/null
+++ b/ndn-cxx/util/exception.cpp
@@ -0,0 +1,45 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/*
+ * Copyright (c) 2013-2019 Regents of the University of California.
+ *
+ * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
+ *
+ * ndn-cxx library is free software: you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+ * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
+ *
+ * You should have received copies of the GNU General Public License and GNU Lesser
+ * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
+ * <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
+ */
+
+#include "ndn-cxx/util/exception.hpp"
+
+#include <sstream>
+
+namespace ndn {
+namespace exception {
+
+#ifdef NDN_CXX_HAVE_STACKTRACE
+std::string
+to_string(const errinfo_stacktrace& x)
+{
+  if (x.value().empty())
+    return "";
+
+  std::ostringstream out;
+  out << "===== Stacktrace =====\n"
+      << x.value()
+      << "======================\n";
+  return out.str();
+}
+#endif
+
+} // namespace exception
+} // namespace ndn
diff --git a/ndn-cxx/util/exception.hpp b/ndn-cxx/util/exception.hpp
new file mode 100644
index 0000000..1cdcc3b
--- /dev/null
+++ b/ndn-cxx/util/exception.hpp
@@ -0,0 +1,74 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/*
+ * Copyright (c) 2013-2019 Regents of the University of California.
+ *
+ * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
+ *
+ * ndn-cxx library is free software: you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+ * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
+ *
+ * You should have received copies of the GNU General Public License and GNU Lesser
+ * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
+ * <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
+ */
+
+#ifndef NDN_UTIL_EXCEPTION_HPP
+#define NDN_UTIL_EXCEPTION_HPP
+
+#include "ndn-cxx/detail/common.hpp"
+
+#include <cerrno>
+
+#include <boost/exception_ptr.hpp>
+#include <boost/exception/enable_current_exception.hpp>
+#include <boost/exception/enable_error_info.hpp>
+#include <boost/exception/errinfo_errno.hpp>
+#include <boost/exception/errinfo_nested_exception.hpp>
+
+#ifdef NDN_CXX_HAVE_STACKTRACE
+#include <boost/stacktrace/stacktrace.hpp>
+#endif
+
+namespace ndn {
+namespace exception {
+
+#ifdef NDN_CXX_HAVE_STACKTRACE
+using errinfo_stacktrace = boost::error_info<struct stacktrace, boost::stacktrace::stacktrace>;
+
+std::string
+to_string(const errinfo_stacktrace&);
+#endif
+
+} // namespace exception
+} // namespace ndn
+
+/** \cond */
+#ifdef NDN_CXX_HAVE_STACKTRACE
+#define NDN_DETAIL_THROW_STACKTRACE \
+  << ndn::exception::errinfo_stacktrace(boost::stacktrace::stacktrace())
+#else
+#define NDN_DETAIL_THROW_STACKTRACE
+#endif
+/** \endcond */
+
+#define NDN_THROW(e) \
+  throw boost::enable_current_exception(boost::enable_error_info(e)) \
+     << boost::throw_file(__FILE__) \
+     << boost::throw_line(__LINE__) \
+     << boost::throw_function(__func__) \
+     NDN_DETAIL_THROW_STACKTRACE
+
+#define NDN_THROW_ERRNO(e) \
+  NDN_THROW(e) << boost::errinfo_errno(errno)
+
+#define NDN_THROW_NESTED(e) \
+  NDN_THROW(e) << boost::errinfo_nested_exception(boost::current_exception())
+
+#endif // NDN_UTIL_EXCEPTION_HPP
diff --git a/tests/unit/util/exception.t.cpp b/tests/unit/util/exception.t.cpp
new file mode 100644
index 0000000..33884dc
--- /dev/null
+++ b/tests/unit/util/exception.t.cpp
@@ -0,0 +1,111 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/*
+ * Copyright (c) 2013-2019 Regents of the University of California.
+ *
+ * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
+ *
+ * ndn-cxx library is free software: you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+ * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
+ *
+ * You should have received copies of the GNU General Public License and GNU Lesser
+ * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
+ * <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
+ */
+
+#include "ndn-cxx/util/exception.hpp"
+
+#include "tests/boost-test.hpp"
+
+#include <boost/exception/diagnostic_information.hpp>
+#include <boost/exception/get_error_info.hpp>
+
+namespace ndn {
+namespace exception {
+namespace test {
+
+BOOST_AUTO_TEST_SUITE(Util)
+BOOST_AUTO_TEST_SUITE(TestException)
+
+BOOST_AUTO_TEST_CASE(Throw)
+{
+  auto f = [] { NDN_THROW(std::invalid_argument("test")); };
+
+  BOOST_CHECK_THROW(f(), boost::exception);
+  BOOST_CHECK_THROW(f(), std::exception);
+  BOOST_CHECK_THROW(f(), std::invalid_argument);
+
+  try {
+    f();
+  }
+  catch (const boost::exception& ex) {
+    BOOST_CHECK(boost::get_error_info<boost::throw_file>(ex) != nullptr);
+    BOOST_CHECK(boost::get_error_info<boost::throw_line>(ex) != nullptr);
+    BOOST_CHECK(boost::get_error_info<boost::throw_function>(ex) != nullptr);
+
+#ifdef NDN_CXX_HAVE_STACKTRACE
+    auto stack = boost::get_error_info<errinfo_stacktrace>(ex);
+    BOOST_REQUIRE(stack != nullptr);
+    auto info = boost::diagnostic_information(ex);
+    BOOST_TEST_MESSAGE(info);
+    BOOST_CHECK(stack->empty() || info.find("===== Stacktrace =====") != std::string::npos);
+#endif
+  }
+}
+
+BOOST_AUTO_TEST_CASE(ThrowErrno)
+{
+  auto f = [] {
+    errno = ERANGE;
+    NDN_THROW_ERRNO(std::out_of_range("test"));
+  };
+
+  BOOST_CHECK_THROW(f(), boost::exception);
+  BOOST_CHECK_THROW(f(), std::exception);
+  BOOST_CHECK_THROW(f(), std::out_of_range);
+
+  try {
+    f();
+  }
+  catch (const boost::exception& ex) {
+    auto errPtr = boost::get_error_info<boost::errinfo_errno>(ex);
+    BOOST_REQUIRE(errPtr != nullptr);
+    BOOST_CHECK_EQUAL(*errPtr, ERANGE);
+  }
+}
+
+BOOST_AUTO_TEST_CASE(ThrowNested)
+{
+  auto f = [] {
+    try {
+      NDN_THROW(std::overflow_error("inner"));
+    }
+    catch (...) {
+      NDN_THROW_NESTED(std::domain_error("outer"));
+    }
+  };
+
+  BOOST_CHECK_THROW(f(), boost::exception);
+  BOOST_CHECK_THROW(f(), std::exception);
+  BOOST_CHECK_THROW(f(), std::domain_error);
+
+  try {
+    f();
+  }
+  catch (const boost::exception& ex) {
+    BOOST_CHECK(boost::get_error_info<boost::errinfo_nested_exception>(ex) != nullptr);
+  }
+}
+
+BOOST_AUTO_TEST_SUITE_END() // TestException
+BOOST_AUTO_TEST_SUITE_END() // Util
+
+} // namespace test
+} // namespace exception
+} // namespace ndn
diff --git a/wscript b/wscript
index ee7a2c1..126ec40 100644
--- a/wscript
+++ b/wscript
@@ -23,13 +23,19 @@
                    help='Build examples')
 
     opt.add_option('--with-tests', action='store_true', default=False,
-                   help='Build unit tests')
+                   help='Build tests')
 
     opt.add_option('--without-tools', action='store_false', default=True, dest='with_tools',
                    help='Do not build tools')
 
-    opt.add_option('--without-sqlite-locking', action='store_false', default=True,
-                   dest='with_sqlite_locking',
+    stacktrace_choices = ['backtrace', 'addr2line', 'basic', 'noop']
+    opt.add_option('--with-stacktrace', action='store', default=None, choices=stacktrace_choices,
+                   help='Select the stacktrace backend implementation: '
+                        '%s [default=auto-detect]' % ', '.join(stacktrace_choices))
+    opt.add_option('--without-stacktrace', action='store_const', const='', dest='with_stacktrace',
+                   help='Disable stacktrace support')
+
+    opt.add_option('--without-sqlite-locking', action='store_false', default=True, dest='with_sqlite_locking',
                    help='Disable filesystem locking in sqlite3 database '
                         '(use unix-dot locking mechanism instead). '
                         'This option may be necessary if the home directory is hosted on NFS.')
@@ -70,9 +76,9 @@
                'pch', 'osx-frameworks', 'boost', 'openssl', 'sqlite3',
                'doxygen', 'sphinx_build'])
 
-    conf.env['WITH_TESTS'] = conf.options.with_tests
-    conf.env['WITH_TOOLS'] = conf.options.with_tools
-    conf.env['WITH_EXAMPLES'] = conf.options.with_examples
+    conf.env.WITH_TESTS = conf.options.with_tests
+    conf.env.WITH_TOOLS = conf.options.with_tools
+    conf.env.WITH_EXAMPLES = conf.options.with_examples
 
     conf.find_program('sh', var='SH', mandatory=True)
 
@@ -85,7 +91,7 @@
     if conf.check_cxx(msg='Checking for netlink', define_name='HAVE_NETLINK', mandatory=False,
                       header_name=['linux/if_addr.h', 'linux/if_link.h',
                                    'linux/netlink.h', 'linux/rtnetlink.h', 'linux/genetlink.h']):
-        conf.env['HAVE_NETLINK'] = True
+        conf.env.HAVE_NETLINK = True
         conf.check_cxx(msg='Checking for NETLINK_EXT_ACK', define_name='HAVE_NETLINK_EXT_ACK', mandatory=False,
                        fragment='''#include <linux/netlink.h>
                                    int main() { return NETLINK_EXT_ACK; }''')
@@ -98,47 +104,54 @@
     conf.check_sqlite3(mandatory=True)
     conf.check_openssl(mandatory=True, atleast_version=0x1000200f) # 1.0.2
 
-    USED_BOOST_LIBS = ['system', 'filesystem', 'date_time', 'iostreams',
-                       'program_options', 'chrono', 'thread', 'log', 'log_setup']
+    boost_libs = ['system', 'filesystem', 'date_time', 'iostreams',
+                  'program_options', 'chrono', 'thread', 'log', 'log_setup']
 
-    if conf.env['WITH_TESTS']:
-        USED_BOOST_LIBS += ['unit_test_framework']
-        conf.define('HAVE_TESTS', 1)
+    stacktrace_backend = conf.options.with_stacktrace
+    if stacktrace_backend is None:
+        # auto-detect
+        for candidate in ['backtrace', 'basic']:
+            try:
+                conf.check_boost(lib='stacktrace_%s' % candidate, mt=True)
+            except conf.errors.ConfigurationError:
+                continue
+            stacktrace_backend = candidate
+            break
+    if stacktrace_backend:
+        conf.env.HAVE_STACKTRACE = True
+        conf.env.append_unique('DEFINES_BOOST', ['BOOST_STACKTRACE_DYN_LINK'])
+        boost_libs.append('stacktrace_%s' % stacktrace_backend)
 
-    conf.check_boost(lib=USED_BOOST_LIBS, mandatory=True, mt=True)
+    if conf.env.WITH_TESTS:
+        boost_libs.append('unit_test_framework')
+
+    conf.check_boost(lib=boost_libs, mt=True)
     if conf.env.BOOST_VERSION_NUMBER < 105800:
         conf.fatal('Minimum required Boost version is 1.58.0\n'
                    'Please upgrade your distribution or manually install a newer version of Boost'
                    ' (https://redmine.named-data.net/projects/nfd/wiki/Boost_FAQ)')
 
-    if not conf.options.with_sqlite_locking:
-        conf.define('DISABLE_SQLITE3_FS_LOCKING', 1)
-
-    if conf.env['HAVE_OSX_FRAMEWORKS']:
-        conf.env['WITH_OSX_KEYCHAIN'] = conf.options.with_osx_keychain
-        if conf.options.with_osx_keychain:
-            conf.define('WITH_OSX_KEYCHAIN', 1)
-    else:
-        conf.env['WITH_OSX_KEYCHAIN'] = False
-
     conf.check_compiler_flags()
 
     # Loading "late" to prevent tests from being compiled with profiling flags
     conf.load('coverage')
-
     conf.load('sanitizers')
 
-    conf.define('SYSCONFDIR', conf.env['SYSCONFDIR'])
-
     if not conf.env.enable_static:
         # If there happens to be a static library, waf will put the corresponding -L flags
         # before dynamic library flags.  This can result in compilation failure when the
         # system has a different version of the ndn-cxx library installed.
-        conf.env['STLIBPATH'] = ['.'] + conf.env['STLIBPATH']
+        conf.env.prepend_value('STLIBPATH', ['.'])
 
-    # config file will contain all defines that were added using conf.define('xxx'...)
-    # Everything that was added directly to conf.env['DEFINES'] will not appear in the
-    # config file and will be added using compiler directives in the command line.
+    conf.define_cond('HAVE_STACKTRACE', conf.env.HAVE_STACKTRACE)
+    conf.define_cond('HAVE_TESTS', conf.env.WITH_TESTS)
+    conf.define_cond('WITH_OSX_KEYCHAIN', conf.env.HAVE_OSX_FRAMEWORKS and conf.options.with_osx_keychain)
+    conf.define_cond('DISABLE_SQLITE3_FS_LOCKING', not conf.options.with_sqlite_locking)
+    conf.define('SYSCONFDIR', conf.env.SYSCONFDIR)
+    # The config header will contain all defines that were added using conf.define()
+    # or conf.define_cond().  Everything that was added directly to conf.env.DEFINES
+    # will not appear in the config header, but will instead be passed directly to the
+    # compiler on the command line.
     conf.write_config_header('ndn-cxx/detail/config.hpp', define_prefix='NDN_CXX_')
 
 def build(bld):
@@ -158,7 +171,7 @@
         VERSION_MINOR=VERSION_SPLIT[1],
         VERSION_PATCH=VERSION_SPLIT[2])
 
-    if bld.env['HAVE_OSX_FRAMEWORKS']:
+    if bld.env.HAVE_OSX_FRAMEWORKS:
         # Need to disable precompiled headers for Objective-C++ code
         bld(features=['cxx'],
             target='ndn-cxx-mm-objects',
@@ -179,11 +192,11 @@
         export_includes='.',
         install_path='${LIBDIR}')
 
-    if bld.env['HAVE_OSX_FRAMEWORKS']:
+    if bld.env.HAVE_OSX_FRAMEWORKS:
         libndn_cxx['source'] += bld.path.ant_glob('ndn-cxx/**/*-osx.cpp')
         libndn_cxx['use'] += ' OSX_COREFOUNDATION OSX_SECURITY OSX_SYSTEMCONFIGURATION OSX_FOUNDATION OSX_COREWLAN'
 
-    if bld.env['HAVE_NETLINK']:
+    if bld.env.HAVE_NETLINK:
         libndn_cxx['source'] += bld.path.ant_glob('ndn-cxx/**/*netlink*.cpp')
 
     # In case we want to make it optional later
@@ -221,7 +234,7 @@
             pkgconfig_defines += Utils.to_list(bld.env['DEFINES_%s' % lib])
 
     EXTRA_FRAMEWORKS = ''
-    if bld.env['HAVE_OSX_FRAMEWORKS']:
+    if bld.env.HAVE_OSX_FRAMEWORKS:
         EXTRA_FRAMEWORKS = '-framework CoreFoundation -framework Security -framework SystemConfiguration -framework Foundation -framework CoreWLAN'
 
     def uniq(alist):
@@ -243,13 +256,13 @@
          EXTRA_CXXFLAGS=' '.join(uniq(pkgconfig_cxxflags)) + ' ' + ' '.join([('-D%s' % i) for i in uniq(pkgconfig_defines)]),
          EXTRA_FRAMEWORKS=EXTRA_FRAMEWORKS)
 
-    if bld.env['WITH_TESTS']:
+    if bld.env.WITH_TESTS:
         bld.recurse('tests')
 
-    if bld.env['WITH_TOOLS']:
+    if bld.env.WITH_TOOLS:
         bld.recurse('tools')
 
-    if bld.env['WITH_EXAMPLES']:
+    if bld.env.WITH_EXAMPLES:
         bld.recurse('examples')
 
     headers = bld.path.ant_glob('ndn-cxx/**/*.hpp',
@@ -258,20 +271,20 @@
                                       'ndn-cxx/**/*-sqlite3.hpp',
                                       'ndn-cxx/**/impl/**/*'])
 
-    if bld.env['HAVE_OSX_FRAMEWORKS']:
+    if bld.env.HAVE_OSX_FRAMEWORKS:
         headers += bld.path.ant_glob('ndn-cxx/**/*-osx.hpp', excl='ndn-cxx/**/impl/**/*')
 
-    if bld.env['HAVE_NETLINK']:
+    if bld.env.HAVE_NETLINK:
         headers += bld.path.ant_glob('ndn-cxx/**/*netlink*.hpp', excl='ndn-cxx/**/impl/**/*')
 
     # In case we want to make it optional later
     headers += bld.path.ant_glob('ndn-cxx/**/*-sqlite3.hpp', excl='ndn-cxx/**/impl/**/*')
 
-    bld.install_files(bld.env['INCLUDEDIR'], headers, relative_trick=True)
+    bld.install_files(bld.env.INCLUDEDIR, headers, relative_trick=True)
 
     # Install generated headers
     for filename in ['ndn-cxx/detail/config.hpp', 'ndn-cxx/version.hpp']:
-        bld.install_files('%s/%s' % (bld.env['INCLUDEDIR'], os.path.dirname(filename)),
+        bld.install_files('%s/%s' % (bld.env.INCLUDEDIR, os.path.dirname(filename)),
                           bld.path.find_resource(filename))
 
     bld.install_files('${SYSCONFDIR}/ndn', 'client.conf.sample')