Merge from default branch and add a needed include for utils SAMPLES_BRANCH
authorElio Maldonado <emaldona@redhat.com>
Sat, 10 Sep 2016 13:15:09 -0700
branchSAMPLES_BRANCH
changeset 12520 eae170937268175a75273704d872ec7d5c6e78d4
parent 11643 e00623942549a1f84added21316139574b48c69f (current diff)
parent 12519 39a0912554787c5a44b038327626fd02f41e53ce (diff)
child 15131 f976ec68d63a835a8817546a557496600bd04baa
push id1511
push useremaldona@redhat.com
push dateSat, 10 Sep 2016 20:15:23 +0000
Merge from default branch and add a needed include for utils
Makefile
circle.yml
cmd/checkcert/Makefile
cmd/checkcert/checkcert.c
cmd/checkcert/manifest.mn
cmd/libpkix/pkix/checker/test_certchainchecker.c
cmd/libpkix/pkix/store/test_store.c
cmd/libpkix/testutil/testutil.c
cmd/libpkix/testutil/testutil.h
cmd/libpkix/testutil/testutil_nss.c
cmd/libpkix/testutil/testutil_nss.h
coverage/cov.sh
coverage/report.sh
external_tests/ssl_gtest/ssl_prf_unittest.cc
lib/freebl/ecl/Makefile
lib/ssl/sslgathr.c
samples/utils/util.h
tests/memleak/memleak.sh
tests/pkcs11/netscape/suites/Makefile
tests/pkcs11/netscape/suites/config.mk
tests/pkcs11/netscape/suites/manifest.mn
tests/pkcs11/netscape/suites/security/Makefile
tests/pkcs11/netscape/suites/security/config.mk
tests/pkcs11/netscape/suites/security/manifest.mn
tests/pkcs11/netscape/suites/security/pkcs11/Makefile
tests/pkcs11/netscape/suites/security/pkcs11/config.mk
tests/pkcs11/netscape/suites/security/pkcs11/manifest.mn
tests/pkcs11/netscape/suites/security/pkcs11/pk11test.c
tests/pkcs11/netscape/suites/security/pkcs11/pk11test.h
tests/pkcs11/netscape/suites/security/pkcs11/pk11test.htp
tests/pkcs11/netscape/suites/security/pkcs11/pkcs11.h
tests/pkcs11/netscape/suites/security/pkcs11/pkcs11.reg
tests/pkcs11/netscape/suites/security/pkcs11/pkcs11.rep
tests/pkcs11/netscape/suites/security/pkcs11/rules.mk
tests/pkcs11/netscape/suites/security/ssl/Makefile
tests/pkcs11/netscape/suites/security/ssl/README
tests/pkcs11/netscape/suites/security/ssl/config.mk
tests/pkcs11/netscape/suites/security/ssl/manifest.mn
tests/pkcs11/netscape/suites/security/ssl/ssl.reg
tests/pkcs11/netscape/suites/security/ssl/sslc.c
tests/pkcs11/netscape/suites/security/ssl/sslc.h
tests/pkcs11/netscape/suites/security/ssl/ssls.c
tests/pkcs11/netscape/suites/security/ssl/ssls.h
tests/pkcs11/netscape/suites/security/ssl/sslt.c
tests/pkcs11/netscape/suites/security/ssl/sslt.h
tests/pkcs11/netscape/suites/security/ssl/sslt.htp
tests/pkcs11/netscape/suites/security/ssl/sslt.rep
tests/pkcs11/netscape/trivial/.cvsignore
tests/pkcs11/netscape/trivial/Makefile.in
tests/pkcs11/netscape/trivial/README.txt
tests/pkcs11/netscape/trivial/acconfig.h
tests/pkcs11/netscape/trivial/config.h.in
tests/pkcs11/netscape/trivial/configure
tests/pkcs11/netscape/trivial/configure.in
tests/pkcs11/netscape/trivial/install-sh
tests/pkcs11/netscape/trivial/trivial.c
tests/ssl_gtests/parsereport.sed
new file mode 100644
--- /dev/null
+++ b/.clang-format
@@ -0,0 +1,65 @@
+---
+Language:        Cpp
+# BasedOnStyle:  Mozilla
+AccessModifierOffset: -2
+AlignAfterOpenBracket: true
+AlignEscapedNewlinesLeft: false
+AlignOperands:   true
+AlignTrailingComments: true
+AllowAllParametersOfDeclarationOnNextLine: false
+AllowShortBlocksOnASingleLine: false
+AllowShortCaseLabelsOnASingleLine: false
+AllowShortIfStatementsOnASingleLine: false
+AllowShortLoopsOnASingleLine: false
+AllowShortFunctionsOnASingleLine: All
+AlwaysBreakAfterDefinitionReturnType: true
+AlwaysBreakTemplateDeclarations: false
+AlwaysBreakBeforeMultilineStrings: false
+BreakBeforeBinaryOperators: false
+BreakBeforeTernaryOperators: true
+BreakConstructorInitializersBeforeComma: false
+BinPackParameters: true
+BinPackArguments: true
+ColumnLimit:     0
+ConstructorInitializerAllOnOneLineOrOnePerLine: true
+ConstructorInitializerIndentWidth: 4
+DerivePointerAlignment: true
+ExperimentalAutoDetectBinPacking: false
+IndentCaseLabels: true
+IndentWrappedFunctionNames: false
+IndentFunctionDeclarationAfterType: false
+MaxEmptyLinesToKeep: 1
+KeepEmptyLinesAtTheStartOfBlocks: true
+NamespaceIndentation: None
+ObjCBlockIndentWidth: 2
+ObjCSpaceAfterProperty: true
+ObjCSpaceBeforeProtocolList: false
+PenaltyBreakBeforeFirstCallParameter: 19
+PenaltyBreakComment: 300
+PenaltyBreakString: 1000
+PenaltyBreakFirstLessLess: 120
+PenaltyExcessCharacter: 1000000
+PenaltyReturnTypeOnItsOwnLine: 200
+PointerAlignment: Right
+SpacesBeforeTrailingComments: 1
+Cpp11BracedListStyle: false
+Standard:        Cpp03
+IndentWidth:     4
+TabWidth:        8
+UseTab:          Never
+BreakBeforeBraces: Linux
+SpacesInParentheses: false
+SpacesInSquareBrackets: false
+SpacesInAngles:  false
+SpaceInEmptyParentheses: false
+SpacesInCStyleCastParentheses: false
+SpaceAfterCStyleCast: false
+SpacesInContainerLiterals: true
+SpaceBeforeAssignmentOperators: true
+ContinuationIndentWidth: 4
+CommentPragmas:  '^ IWYU pragma:'
+ForEachMacros:   [ foreach, Q_FOREACH, BOOST_FOREACH ]
+SpaceBeforeParens: ControlStatements
+DisableFormat:   false
+SortIncludes: false
+...
--- a/.hgtags
+++ b/.hgtags
@@ -1552,8 +1552,41 @@ af38c6ffbe4efafee3cf5920ebf0db6ce298f01e
 ae72d76f8d2472505b499c498191c3ce441b6a17 NSS_3_19_1_BETA1
 ae72d76f8d2472505b499c498191c3ce441b6a17 NSS_3_19_1_BETA1
 736d9f81295197d3ba63a4ece70f1c377d28e630 NSS_3_19_1_BETA1
 537d7fc8624c289e4f818a4c69847eaedecceccb NSS_3_19_1_RTM
 2b29dfe134a5fd5ba2c4e80074b7cf8fc2d36cfd NSS_3_19_2_BETA1
 97d30005dd7bb02b15bd2b8a27e2426c49d06d69 NSS_3_19_2_RTM
 6e60855257f0f3d34cb51cdd2aba1800b7834f7f NSS_3_21_Beta1
 dc5a3f75d9d5d0fc6dd5f5b60b5b9be693dbbc78 NSS_3_21_Beta2
+feae8cff7fed6f450b8136af59e7f50e448a5c12 NSS_3_21_Beta3
+507694132f6f0706e7b8e33dac63a560a89f67fc NSS_3_21_RTM
+d0d925b6cf323b4cd66fae401a8206bed5577575 NSS_3_22_BETA1
+72122a7dc17e04cf98faeb67acbcb382071cbd09 NSS_3_22_BETA2
+ee1254aeba3e9929858d24f071bafcabea32ad4a NSS_3_22_RTM
+4f727a27da000cf1b849af882924a88e8b1d9206 NSS_3_23_BETA1
+ed3747827ea71f232c5f66cced2149f68e8c5857 NSS_3_23_BETA2
+58a2646809529953052c1367545145da7c5709a3 NSS_3_23_BETA3
+b27bfeb21edb4a50ee2bb56ed06462ece461a4c1 NSS_3_23_BETA4
+1df3afde15aae0b28df289a0488af302ee06813e NSS_3_23_BETA5
+4bc07bbf4b40931dfda4d65b729ba198d697f96e NSS_3_23_BETA6
+0e6e8153513e40154dc1907c2aff318b5342e73e NSS_3_23_BETA7
+c603975b17e7c073314896c6ce6838508c55f5d8 NSS_3_23_BETA8
+612cfac63edfaaf2bbc7cf9a1b76bebd4975f3a6 NSS_3_23_RC0
+250e4280aaa157a248d9786d02b421d6f025eff6 NSS_3_24_BETA1
+c719ec5480969f921738bdac54faa264adb8fac1 NSS_3_24_BETA2
+04f19b705ec548943b28c01cda1ada2fdb030fd6 NSS_3_24_BETA1b
+04f19b705ec548943b28c01cda1ada2fdb030fd6 NSS_3_24_BETA3
+cb003099f3f0d1bd161720d5e7b7deedb611881d NSS_3_24_BETA4
+04f19b705ec548943b28c01cda1ada2fdb030fd6 NSS_3_24_BETA3
+0000000000000000000000000000000000000000 NSS_3_24_BETA3
+8b5c760a62d40c5a7aaad2d21f721637669f5c89 NSS_3_24_BETA5
+4084aa2e0c3e2a8b5138de9d03b40b51b7e97337 NSS_3_24_BETA6
+81ac6ae397ea23d1cf4fdc50e6e133e9815bbbec NSS_3_24_BETA7
+4346b9e3b7184975765f705805e54396cde5d7fc NSS_3_24_RC0
+bdf702cc0f766757d8221b1bb9a8a5a12f0183da NSS_3_25_BETA1
+2c9ec9e42631adeb82ee486a373313df9fcc05fb NSS_3_25_RC0
+98a35207af80f780de09b5e67570add9ca4b6e7e NSS_3.26_BETA1
+2530cf04ae825a678b2917376e50df6cace2ce81 NSS_3.26_BETA2
+929f77302ec909cbc1cb1d340549cee91d8d10aa NSS_3_26_RC0
+cc982d5a9904b9ec478eced92a3eea8ee0ee313a NSS_3_27_BETA1
+d36a5c8225914f92c12f8e182d83f5b4727d327b NSS_3_27_BETA2
+06ed5314230a8abc5436bdca2cc79e7de7f2828f NSS_3_27_BETA3
--- a/Makefile
+++ b/Makefile
@@ -21,17 +21,19 @@ include $(CORE_DEPTH)/coreconf/config.mk
 #######################################################################
 
 
 
 #######################################################################
 # (4) Include "local" platform-dependent assignments (OPTIONAL).      #
 #######################################################################
 
-
+ifdef NSS_DISABLE_GTESTS
+DIRS := $(filter-out external_tests,$(DIRS))
+endif
 
 #######################################################################
 # (5) Execute "global" rules. (OPTIONAL)                              #
 #######################################################################
 
 include $(CORE_DEPTH)/coreconf/rules.mk
 
 #######################################################################
@@ -76,17 +78,26 @@ NSPR_CONFIGURE_OPTS += --enable-win32-ta
 endif
 ifdef USE_DEBUG_RTL
 NSPR_CONFIGURE_OPTS += --enable-debug-rtl
 endif
 ifdef USE_STATIC_RTL
 NSPR_CONFIGURE_OPTS += --enable-static-rtl
 endif
 ifdef NS_USE_GCC
-NSPR_COMPILERS = CC=gcc CXX=g++
+NSPR_CONFIGURE_ENV = CC=gcc CXX=g++
+endif
+
+ifdef SANITIZER_CFLAGS
+ifdef BUILD_OPT
+NSPR_CONFIGURE_OPTS += --enable-debug-symbols
+endif
+NSPR_CONFIGURE_ENV += CFLAGS='$(SANITIZER_CFLAGS)' \
+                      CXXFLAGS='$(SANITIZER_CFLAGS)' \
+                      LDFLAGS='$(SANITIZER_LDFLAGS)'
 endif
 
 #
 # Some pwd commands on Windows (for example, the pwd
 # command in Cygwin) return a pathname that begins
 # with a (forward) slash.  When such a pathname is
 # passed to Windows build tools (for example, cl), it
 # is mistaken as a command-line option.  If that is the case,
@@ -103,17 +114,17 @@ ifeq ($(USEABSPATH),"YES")
 NSPR_PREFIX = $(shell pwd)/../dist/$(OBJDIR_NAME)
 else
 NSPR_PREFIX = $$(topsrcdir)/../dist/$(OBJDIR_NAME)
 endif
 
 $(NSPR_CONFIG_STATUS): $(NSPR_CONFIGURE)
 	mkdir -p $(CORE_DEPTH)/../nspr/$(OBJDIR_NAME)
 	cd $(CORE_DEPTH)/../nspr/$(OBJDIR_NAME) ; \
-	$(NSPR_COMPILERS) sh ../configure \
+	$(NSPR_CONFIGURE_ENV) sh ../configure \
 	$(NSPR_CONFIGURE_OPTS) \
 	--with-dist-prefix='$(NSPR_PREFIX)' \
 	--with-dist-includedir='$(NSPR_PREFIX)/include'
 
 build_nspr: $(NSPR_CONFIG_STATUS)
 	$(MAKE) -C $(CORE_DEPTH)/../nspr/$(OBJDIR_NAME)
 
 clobber_nspr: $(NSPR_CONFIG_STATUS)
--- a/automation/buildbot-slave/build.sh
+++ b/automation/buildbot-slave/build.sh
@@ -194,26 +194,26 @@ test_nss()
 	cd ${HGDIR}/nss/tests/remote
 	print_log "$ make test_android"
 	make test_android 2>&1 | tee ${LOG_TMP} | grep ${GREP_BUFFER} ": #"
 	OUTPUTFILE=${HGDIR}/tests_results/security/*.1/output.log
     else
 	print_log "$ cd ${HGDIR}/nss/tests"
 	cd ${HGDIR}/nss/tests
 	print_log "$ ./all.sh"
-	./all.sh 2>&1 | tee ${LOG_TMP} | grep ${GREP_BUFFER} ": #"
+	./all.sh 2>&1 | tee ${LOG_TMP} | egrep ${GREP_BUFFER} ": #|^\[.{10}\] "
 	OUTPUTFILE=${LOG_TMP}
     fi
 
     cat ${LOG_TMP} >> ${LOG_ALL}
     tail -n2 ${HGDIR}/tests_results/security/*.1/results.html | grep END_OF_TEST >> ${LOG_ALL}
     RET=$?
 
     print_log "######## details of detected failures (if any) ########"
-    grep -B50 FAIL ${OUTPUTFILE}
+    grep -B50 FAILED ${OUTPUTFILE}
     [ $? -eq 1 ] || RET=1
 
     print_result "NSS - tests - ${BITS} bits - ${OPT}" ${RET} 0
     return ${RET}
 }
 
 test_jss()
 {
@@ -283,24 +283,33 @@ prepare()
 {
     rm -rf ${OUTPUTDIR}.oldest >/dev/null 2>&1
     mv ${OUTPUTDIR}.older ${OUTPUTDIR}.oldest >/dev/null 2>&1
     mv ${OUTPUTDIR}.old ${OUTPUTDIR}.older >/dev/null 2>&1
     mv ${OUTPUTDIR}.last ${OUTPUTDIR}.old >/dev/null 2>&1
     mv ${OUTPUTDIR} ${OUTPUTDIR}.last >/dev/null 2>&1
     mkdir -p ${OUTPUTDIR}
 
+    # Remove temporary test files from previous jobs, that weren't cleaned up
+    # by move_results(), e.g. caused by unexpected interruptions.
+    rm -rf ${HGDIR}/tests_results/
+
+    cd ${HGDIR}/nss
+
     if [ -z "${NSS_DISABLE_ECC}" -a -n "${NSS_ECC_MORE_THAN_SUITE_B}" ]; then
-        cd ${HGDIR}/nss
         ECF="lib/freebl/ecl/ecl-curve.h"
 	print_log "hg revert -r NSS_3_11_1_RTM ${ECF}"
         hg revert -r NSS_3_11_1_RTM security/nss/${ECF}
         cp -f security/nss/${ECF} ${ECF}
     fi
 
+    if [ -n "${FEWER_STRESS_ITERATIONS}" ]; then
+        sed -i 's/-c_1000_/-c_500_/g' tests/ssl/sslstress.txt
+    fi
+
     return 0
 }
 
 move_results()
 {
     cd ${HGDIR}
     if [ -n "${TEST_NSS}" ]; then
 	mv -f tests_results ${OUTPUTDIR}
--- a/automation/buildbot-slave/startbuild.bat
+++ b/automation/buildbot-slave/startbuild.bat
@@ -1,12 +1,12 @@
 echo running > ..\buildbot-is-building
 
-echo running: "%MOZILLABUILD%\msys\bin\bash" -c "hg/tinder/buildbot/build.sh %*"
-"%MOZILLABUILD%\msys\bin\bash" -c "hg/tinder/buildbot/build.sh %*"
+echo running: "%MOZILLABUILD%\msys\bin\bash" -c "hg/nss/automation/buildbot-slave/build.sh %*"
+"%MOZILLABUILD%\msys\bin\bash" -c "hg/nss/automation/buildbot-slave/build.sh %*"
 
 if %errorlevel% neq 0 (
   set EXITCODE=1
 ) else (
   set EXITCODE=0
 )
 
 del ..\buildbot-is-building
new file mode 100644
--- /dev/null
+++ b/automation/release/nss-release-helper.py
@@ -0,0 +1,250 @@
+#!/usr/bin/python
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+import os
+import sys
+import datetime
+import shutil
+import glob
+from optparse import OptionParser
+from subprocess import check_call
+
+nssutil_h = "lib/util/nssutil.h"
+softkver_h = "lib/softoken/softkver.h"
+nss_h = "lib/nss/nss.h"
+nssckbi_h = "lib/ckfw/builtins/nssckbi.h"
+
+def check_call_noisy(cmd, *args, **kwargs):
+    print "Executing command:", cmd
+    check_call(cmd, *args, **kwargs)
+
+o = OptionParser(usage="client.py [options] remove_beta | set_beta | print_library_versions | print_root_ca_version | set_root_ca_version | set_version_to_minor_release | set_version_to_patch_release | set_release_candidate_number | set_4_digit_release_number | create_nss_release_archive")
+
+try:
+    options, args = o.parse_args()
+    action = args[0]
+except IndexError:
+    o.print_help()
+    sys.exit(2)
+
+def exit_with_failure(what):
+    print "failure: ", what
+    sys.exit(2)
+
+def check_files_exist():
+    if (not os.path.exists(nssutil_h) or not os.path.exists(softkver_h)
+        or not os.path.exists(nss_h) or not os.path.exists(nssckbi_h)):
+        exit_with_failure("cannot find expected header files, must run from inside NSS hg directory")
+
+def sed_inplace(sed_expression, filename):
+    backup_file = filename + '.tmp'
+    check_call_noisy(["sed", "-i.tmp", sed_expression, filename])
+    os.remove(backup_file)
+
+def toggle_beta_status(is_beta):
+    check_files_exist()
+    if (is_beta):
+        print "adding Beta status to version numbers"
+        sed_inplace('s/^\(#define *NSSUTIL_VERSION *\"[0-9.]\+\)\" *$/\\1 Beta\"/', nssutil_h)
+        sed_inplace('s/^\(#define *NSSUTIL_BETA *\)PR_FALSE *$/\\1PR_TRUE/', nssutil_h)
+        sed_inplace('s/^\(#define *SOFTOKEN_VERSION *\"[0-9.]\+\" *SOFTOKEN_ECC_STRING\) *$/\\1 \" Beta"/', softkver_h)
+        sed_inplace('s/^\(#define *SOFTOKEN_BETA *\)PR_FALSE *$/\\1PR_TRUE/', softkver_h)
+        sed_inplace('s/^\(#define *NSS_VERSION *\"[0-9.]\+\" *_NSS_CUSTOMIZED\) *$/\\1 \" Beta"/', nss_h)
+        sed_inplace('s/^\(#define *NSS_BETA *\)PR_FALSE *$/\\1PR_TRUE/', nss_h)
+    else:
+        print "removing Beta status from version numbers"
+        sed_inplace('s/^\(#define *NSSUTIL_VERSION *\"[0-9.]\+\) *Beta\" *$/\\1\"/', nssutil_h)
+        sed_inplace('s/^\(#define *NSSUTIL_BETA *\)PR_TRUE *$/\\1PR_FALSE/', nssutil_h)
+        sed_inplace('s/^\(#define *SOFTOKEN_VERSION *\"[0-9.]\+\" *SOFTOKEN_ECC_STRING\) *\" *Beta\" *$/\\1/', softkver_h)
+        sed_inplace('s/^\(#define *SOFTOKEN_BETA *\)PR_TRUE *$/\\1PR_FALSE/', softkver_h)
+        sed_inplace('s/^\(#define *NSS_VERSION *\"[0-9.]\+\" *_NSS_CUSTOMIZED\) *\" *Beta\" *$/\\1/', nss_h)
+        sed_inplace('s/^\(#define *NSS_BETA *\)PR_TRUE *$/\\1PR_FALSE/', nss_h)
+    print "please run 'hg stat' and 'hg diff' to verify the files have been verified correctly"
+
+def print_beta_versions():
+    check_call_noisy(["egrep", "#define *NSSUTIL_VERSION|#define *NSSUTIL_BETA", nssutil_h])
+    check_call_noisy(["egrep", "#define *SOFTOKEN_VERSION|#define *SOFTOKEN_BETA", softkver_h])
+    check_call_noisy(["egrep", "#define *NSS_VERSION|#define *NSS_BETA", nss_h])
+
+def remove_beta_status():
+    print "--- removing beta flags. Existing versions were:"
+    print_beta_versions()
+    toggle_beta_status(False)
+    print "--- finished modifications, new versions are:"
+    print_beta_versions()
+
+def set_beta_status():
+    print "--- adding beta flags. Existing versions were:"
+    print_beta_versions()
+    toggle_beta_status(True)
+    print "--- finished modifications, new versions are:"
+    print_beta_versions()
+
+def print_library_versions():
+    check_files_exist()
+    check_call_noisy(["egrep", "#define *NSSUTIL_VERSION|#define NSSUTIL_VMAJOR|#define *NSSUTIL_VMINOR|#define *NSSUTIL_VPATCH|#define *NSSUTIL_VBUILD|#define *NSSUTIL_BETA", nssutil_h])
+    check_call_noisy(["egrep", "#define *SOFTOKEN_VERSION|#define SOFTOKEN_VMAJOR|#define *SOFTOKEN_VMINOR|#define *SOFTOKEN_VPATCH|#define *SOFTOKEN_VBUILD|#define *SOFTOKEN_BETA", softkver_h])
+    check_call_noisy(["egrep", "#define *NSS_VERSION|#define NSS_VMAJOR|#define *NSS_VMINOR|#define *NSS_VPATCH|#define *NSS_VBUILD|#define *NSS_BETA", nss_h])
+
+def print_root_ca_version():
+    check_files_exist()
+    check_call_noisy(["grep", "define *NSS_BUILTINS_LIBRARY_VERSION", nssckbi_h])
+
+
+def ensure_arguments_after_action(how_many, usage):
+    if (len(sys.argv) != (2+how_many)):
+        exit_with_failure("incorrect number of arguments, expected parameters are:\n" + usage)
+
+def set_major_versions(major):
+    sed_inplace('s/^\(#define *NSSUTIL_VMAJOR *\).*$/\\1' + major + '/', nssutil_h)
+    sed_inplace('s/^\(#define *SOFTOKEN_VMAJOR *\).*$/\\1' + major + '/', softkver_h)
+    sed_inplace('s/^\(#define *NSS_VMAJOR *\).*$/\\1' + major + '/', nss_h)
+
+def set_minor_versions(minor):
+    sed_inplace('s/^\(#define *NSSUTIL_VMINOR *\).*$/\\1' + minor + '/', nssutil_h)
+    sed_inplace('s/^\(#define *SOFTOKEN_VMINOR *\).*$/\\1' + minor + '/', softkver_h)
+    sed_inplace('s/^\(#define *NSS_VMINOR *\).*$/\\1' + minor + '/', nss_h)
+
+def set_patch_versions(patch):
+    sed_inplace('s/^\(#define *NSSUTIL_VPATCH *\).*$/\\1' + patch + '/', nssutil_h)
+    sed_inplace('s/^\(#define *SOFTOKEN_VPATCH *\).*$/\\1' + patch + '/', softkver_h)
+    sed_inplace('s/^\(#define *NSS_VPATCH *\).*$/\\1' + patch + '/', nss_h)
+
+def set_build_versions(build):
+    sed_inplace('s/^\(#define *NSSUTIL_VBUILD *\).*$/\\1' + build + '/', nssutil_h)
+    sed_inplace('s/^\(#define *SOFTOKEN_VBUILD *\).*$/\\1' + build + '/', softkver_h)
+    sed_inplace('s/^\(#define *NSS_VBUILD *\).*$/\\1' + build + '/', nss_h)
+
+def set_full_lib_versions(version):
+    sed_inplace('s/^\(#define *NSSUTIL_VERSION *\"\)\([0-9.]\+\)\(.*\)$/\\1' + version + '\\3/', nssutil_h)
+    sed_inplace('s/^\(#define *SOFTOKEN_VERSION *\"\)\([0-9.]\+\)\(.*\)$/\\1' + version + '\\3/', softkver_h)
+    sed_inplace('s/^\(#define *NSS_VERSION *\"\)\([0-9.]\+\)\(.*\)$/\\1' + version + '\\3/', nss_h)
+
+def set_root_ca_version():
+    ensure_arguments_after_action(2, "major_version  minor_version")
+    major = args[1].strip()
+    minor = args[2].strip()
+    version = major + '.' + minor
+    sed_inplace('s/^\(#define *NSS_BUILTINS_LIBRARY_VERSION *\"\).*$/\\1' + version + '/', nssckbi_h)
+    sed_inplace('s/^\(#define *NSS_BUILTINS_LIBRARY_VERSION_MAJOR *\).*$/\\1' + major + '/', nssckbi_h)
+    sed_inplace('s/^\(#define *NSS_BUILTINS_LIBRARY_VERSION_MINOR *\).*$/\\1' + minor + '/', nssckbi_h)
+
+def set_all_lib_versions(version, major, minor, patch, build):
+    set_full_lib_versions(version)
+    set_major_versions(major)
+    set_minor_versions(minor)
+    set_patch_versions(patch)
+    set_build_versions(build)
+
+def set_version_to_minor_release():
+    ensure_arguments_after_action(2, "major_version  minor_version")
+    major = args[1].strip()
+    minor = args[2].strip()
+    version = major + '.' + minor
+    patch = "0"
+    build = "0"
+    set_all_lib_versions(version, major, minor, patch, build)
+
+def set_version_to_patch_release():
+    ensure_arguments_after_action(3, "major_version  minor_version  patch_release")
+    major = args[1].strip()
+    minor = args[2].strip()
+    patch = args[3].strip()
+    version = major + '.' + minor + '.' + patch
+    build = "0"
+    set_all_lib_versions(version, major, minor, patch, build)
+
+def set_release_candidate_number():
+    ensure_arguments_after_action(1, "release_candidate_number")
+    build = args[1].strip()
+    set_build_versions(build)
+
+def set_4_digit_release_number():
+    ensure_arguments_after_action(4, "major_version  minor_version  patch_release  4th_digit_release_number")
+    major = args[1].strip()
+    minor = args[2].strip()
+    patch = args[3].strip()
+    build = args[4].strip()
+    version = major + '.' + minor + '.' + patch + '.' + build
+    set_all_lib_versions(version, major, minor, patch, build)
+
+def create_nss_release_archive():
+    ensure_arguments_after_action(4, "nss_release_version  nss_hg_release_tag  nspr_release_version  path_to_stage_directory")
+    nssrel = args[1].strip() #e.g. 3.19.3
+    nssreltag = args[2].strip() #e.g. NSS_3_19_3_RTM
+    nsprrel = args[3].strip() #e.g. 4.10.8
+    stagedir = args[4].strip() #e.g. ../stage
+
+    nspr_tar = "nspr-" + nsprrel + ".tar.gz"
+    nsprtar_with_path= stagedir + "/v" + nsprrel + "/src/" + nspr_tar
+    if (not os.path.exists(nsprtar_with_path)):
+        exit_with_failure("cannot find nspr archive at expected location " + nsprtar_with_path)
+
+    nss_stagedir= stagedir + "/" + nssreltag + "/src"
+    if (os.path.exists(nss_stagedir)):
+        exit_with_failure("nss stage directory already exists: " + nss_stagedir)
+
+    nss_tar = "nss-" + nssrel + ".tar.gz"
+
+    check_call_noisy(["mkdir", "-p", nss_stagedir])
+    check_call_noisy(["hg", "archive", "-r", nssreltag, "--prefix=nss-" + nssrel + "/nss",
+                      stagedir + "/" + nssreltag + "/src/" + nss_tar, "-X", ".hgtags"])
+    check_call_noisy(["tar", "-xz", "-C", nss_stagedir, "-f", nsprtar_with_path])
+    print "changing to directory " + nss_stagedir
+    os.chdir(nss_stagedir)
+    check_call_noisy(["tar", "-xz", "-f", nss_tar])
+    check_call_noisy(["mv", "-i", "nspr-" + nsprrel + "/nspr", "nss-" + nssrel + "/"])
+    check_call_noisy(["rmdir", "nspr-" + nsprrel])
+
+    nss_nspr_tar = "nss-" + nssrel + "-with-nspr-" + nsprrel + ".tar.gz"
+
+    check_call_noisy(["tar", "-cz", "--remove-files", "-f", nss_nspr_tar, "nss-" + nssrel])
+    check_call("sha1sum " + nss_tar + " " + nss_nspr_tar + " > SHA1SUMS", shell=True)
+    check_call("sha256sum " + nss_tar + " " + nss_nspr_tar + " > SHA256SUMS", shell=True)
+    print "created directory " + nss_stagedir + " with files:"
+    check_call_noisy(["ls", "-l"])
+
+if action in ('remove_beta'):
+    remove_beta_status()
+
+elif action in ('set_beta'):
+    set_beta_status()
+
+elif action in ('print_library_versions'):
+    print_library_versions()
+
+elif action in ('print_root_ca_version'):
+    print_root_ca_version()
+
+elif action in ('set_root_ca_version'):
+    set_root_ca_version()
+
+# x.y version number - 2 parameters
+elif action in ('set_version_to_minor_release'):
+    set_version_to_minor_release()
+
+# x.y.z version number - 3 parameters
+elif action in ('set_version_to_patch_release'):
+    set_version_to_patch_release()
+
+# change the release candidate number, usually increased by one,
+# usually if previous release candiate had a bug
+# 1 parameter
+elif action in ('set_release_candidate_number'):
+    set_release_candidate_number()
+
+# use the build/release candiate number in the identifying version number
+# 4 parameters
+elif action in ('set_4_digit_release_number'):
+    set_4_digit_release_number()
+
+elif action in ('create_nss_release_archive'):
+    create_nss_release_archive()
+
+else:
+    o.print_help()
+    sys.exit(2)
+
+sys.exit(0)
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/decision_task.yml
@@ -0,0 +1,95 @@
+---
+version: 0
+metadata:
+  name: "NSS Continuous Integration"
+  description: "The Taskcluster task graph for the NSS tree"
+  owner: "mozilla-taskcluster-maintenance@mozilla.com"
+  source: {{{source}}}
+
+scopes:
+  # Note the below scopes are insecure however these get overriden on the server
+  # side to whatever scopes are set by mozilla-taskcluster.
+  - queue:*
+  - docker-worker:*
+  - scheduler:*
+
+# Available mustache parameters (see the mozilla-taskcluster source):
+#
+# - owner:          push user (email address)
+# - source:         URL of this YAML file
+# - url:            repository URL
+# - project:        alias for the destination repository (basename of
+#                   the repo url)
+# - level:          SCM level of the destination repository
+#                   (1 = try, 3 = core)
+# - revision:       (short) hg revision of the head of the push
+# - revision_hash:  (long) hg revision of the head of the push
+# - comment:        comment of the push
+# - pushlog_id:     id in the pushlog table of the repository
+#
+# and functions:
+# - as_slugid:      convert a label into a slugId
+# - from_now:       generate a timestamp at a fixed offset from now
+
+tasks:
+  - taskId: '{{#as_slugid}}decision task{{/as_slugid}}'
+    reruns: 3
+    task:
+      created: '{{now}}'
+      deadline: '{{#from_now}}1 day{{/from_now}}'
+      expires: '{{#from_now}}14 days{{/from_now}}'
+
+      metadata:
+        owner: mozilla-taskcluster-maintenance@mozilla.com
+        source: {{{source}}}
+        name: "NSS Decision Task"
+        description: |
+            The task that creates all of the other tasks in the task graph
+
+      workerType: "hg-worker"
+      provisionerId: "aws-provisioner-v1"
+
+      tags:
+        createdForUser: {{owner}}
+
+      routes:
+        - "tc-treeherder-stage.v2.{{project}}.{{revision}}.{{pushlog_id}}"
+        - "tc-treeherder.v2.{{project}}.{{revision}}.{{pushlog_id}}"
+
+      payload:
+        image: ttaubert/nss-decision:0.0.2
+
+        env:
+          TC_OWNER: {{owner}}
+          TC_SOURCE: {{{source}}}
+          TC_PROJECT: {{project}}
+          TC_COMMENT: '{{comment}}'
+          NSS_PUSHLOG_ID: '{{pushlog_id}}'
+          NSS_HEAD_REPOSITORY: '{{{url}}}'
+          NSS_HEAD_REVISION: '{{revision}}'
+
+        maxRunTime: 1800
+
+        command:
+          - bash
+          - -cx
+          - >
+            bin/checkout.sh &&
+            nss/automation/taskcluster/scripts/extend_task_graph.sh
+
+        artifacts:
+          public:
+            type: "directory"
+            path: "/home/worker/artifacts"
+            expires: "{{#from_now}}7 days{{/from_now}}"
+
+        graphs:
+          - /home/worker/artifacts/graph.json
+
+      extra:
+        treeherder:
+          symbol: D
+          build:
+            platform: nss-decision
+          machine:
+            platform: nss-decision
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/docker-arm/Dockerfile
@@ -0,0 +1,27 @@
+FROM armv7/armhf-ubuntu:16.04
+MAINTAINER Tim Taubert <ttaubert@mozilla.com>
+
+RUN useradd -d /home/worker -s /bin/bash -m worker
+WORKDIR /home/worker
+
+# Add build and test scripts.
+ADD bin /home/worker/bin
+RUN chmod +x /home/worker/bin/*
+
+# Install dependencies.
+ADD setup.sh /tmp/setup.sh
+RUN bash /tmp/setup.sh
+
+# Env variables.
+ENV HOME /home/worker
+ENV SHELL /bin/bash
+ENV USER worker
+ENV LOGNAME worker
+ENV HOSTNAME taskcluster-worker
+ENV LANG en_US.UTF-8
+ENV LC_ALL en_US.UTF-8
+ENV HOST localhost
+ENV DOMSUF localdomain
+
+# Set a default command for debugging.
+CMD ["/bin/bash", "--login"]
new file mode 100755
--- /dev/null
+++ b/automation/taskcluster/docker-arm/bin/checkout.sh
@@ -0,0 +1,20 @@
+#!/usr/bin/env bash
+
+set -v -e -x
+
+if [ $(id -u) = 0 ]; then
+    # Drop privileges by re-running this script.
+    exec su worker $0
+fi
+
+# Default values for testing.
+REVISION=${NSS_HEAD_REVISION:-default}
+REPOSITORY=${NSS_HEAD_REPOSITORY:-https://hg.mozilla.org/projects/nss}
+
+# Clone NSS.
+for i in 0 2 5; do
+    sleep $i
+    hg clone -r $REVISION $REPOSITORY nss && exit 0
+    rm -rf nss
+done
+exit 1
new file mode 100755
--- /dev/null
+++ b/automation/taskcluster/docker-arm/setup.sh
@@ -0,0 +1,39 @@
+#!/usr/bin/env bash
+
+set -v -e -x
+
+export DEBIAN_FRONTEND=noninteractive
+
+# Update.
+apt-get -y update
+apt-get -y dist-upgrade
+
+apt_packages=()
+apt_packages+=('build-essential')
+apt_packages+=('ca-certificates')
+apt_packages+=('curl')
+apt_packages+=('python-dev')
+apt_packages+=('python-pip')
+apt_packages+=('python-setuptools')
+apt_packages+=('zlib1g-dev')
+
+# Install packages.
+apt-get install -y --no-install-recommends ${apt_packages[@]}
+
+# Latest Mercurial.
+pip install --upgrade pip
+pip install Mercurial
+
+# Compiler options.
+update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-5 30
+update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-5 30
+
+locale-gen en_US.UTF-8
+dpkg-reconfigure locales
+
+# Cleanup.
+rm -rf ~/.ccache ~/.cache
+apt-get autoremove -y
+apt-get clean
+apt-get autoclean
+rm $0
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/docker-decision/Dockerfile
@@ -0,0 +1,27 @@
+FROM ubuntu:16.04
+MAINTAINER Tim Taubert <ttaubert@mozilla.com>
+
+RUN useradd -d /home/worker -s /bin/bash -m worker
+WORKDIR /home/worker
+
+# Add build and test scripts.
+ADD bin /home/worker/bin
+RUN chmod +x /home/worker/bin/*
+
+# Install dependencies.
+ADD setup.sh /tmp/setup.sh
+RUN bash /tmp/setup.sh
+
+# Env variables.
+ENV HOME /home/worker
+ENV SHELL /bin/bash
+ENV USER worker
+ENV LOGNAME worker
+ENV HOSTNAME taskcluster-worker
+ENV LANG en_US.UTF-8
+ENV LC_ALL en_US.UTF-8
+ENV HOST localhost
+ENV DOMSUF localdomain
+
+# Set a default command for debugging.
+CMD ["/bin/bash", "--login"]
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/docker-decision/bin/checkout.sh
@@ -0,0 +1,20 @@
+#!/usr/bin/env bash
+
+set -v -e -x
+
+if [ $(id -u) = 0 ]; then
+    # Drop privileges by re-running this script.
+    exec su worker $0
+fi
+
+# Default values for testing.
+REVISION=${NSS_HEAD_REVISION:-default}
+REPOSITORY=${NSS_HEAD_REPOSITORY:-https://hg.mozilla.org/projects/nss}
+
+# Clone NSS.
+for i in 0 2 5; do
+    sleep $i
+    hg clone -r $REVISION $REPOSITORY nss && exit 0
+    rm -rf nss
+done
+exit 1
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/docker-decision/setup.sh
@@ -0,0 +1,31 @@
+#!/usr/bin/env bash
+
+set -v -e -x
+
+# Update packages.
+export DEBIAN_FRONTEND=noninteractive
+apt-get -y update && apt-get -y upgrade
+
+# Need those to install newer packages below.
+apt-get install -y --no-install-recommends apt-utils curl ca-certificates
+
+# Latest Mercurial.
+apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 41BD8711B1F0EC2B0D85B91CF59CE3A8323293EE
+echo "deb http://ppa.launchpad.net/mercurial-ppa/releases/ubuntu xenial main" > /etc/apt/sources.list.d/mercurial.list
+
+# Install packages.
+apt-get -y update && apt-get install -y --no-install-recommends mercurial
+
+# Latest Node.JS.
+curl -sL https://deb.nodesource.com/setup_6.x | bash -
+apt-get install -y --no-install-recommends nodejs
+
+locale-gen en_US.UTF-8
+dpkg-reconfigure locales
+
+# Cleanup.
+rm -rf ~/.ccache ~/.cache
+apt-get autoremove -y
+apt-get clean
+apt-get autoclean
+rm $0
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/docker/Dockerfile
@@ -0,0 +1,27 @@
+FROM ubuntu:16.04
+MAINTAINER Tim Taubert <ttaubert@mozilla.com>
+
+RUN useradd -d /home/worker -s /bin/bash -m worker
+WORKDIR /home/worker
+
+# Add build and test scripts.
+ADD bin /home/worker/bin
+RUN chmod +x /home/worker/bin/*
+
+# Install dependencies.
+ADD setup.sh /tmp/setup.sh
+RUN bash /tmp/setup.sh
+
+# Env variables.
+ENV HOME /home/worker
+ENV SHELL /bin/bash
+ENV USER worker
+ENV LOGNAME worker
+ENV HOSTNAME taskcluster-worker
+ENV LANG en_US.UTF-8
+ENV LC_ALL en_US.UTF-8
+ENV HOST localhost
+ENV DOMSUF localdomain
+
+# Set a default command for debugging.
+CMD ["/bin/bash", "--login"]
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/docker/bin/checkout.sh
@@ -0,0 +1,20 @@
+#!/usr/bin/env bash
+
+set -v -e -x
+
+if [ $(id -u) = 0 ]; then
+    # Drop privileges by re-running this script.
+    exec su worker $0
+fi
+
+# Default values for testing.
+REVISION=${NSS_HEAD_REVISION:-default}
+REPOSITORY=${NSS_HEAD_REPOSITORY:-https://hg.mozilla.org/projects/nss}
+
+# Clone NSS.
+for i in 0 2 5; do
+    sleep $i
+    hg clone -r $REVISION $REPOSITORY nss && exit 0
+    rm -rf nss
+done
+exit 1
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/docker/setup.sh
@@ -0,0 +1,68 @@
+#!/usr/bin/env bash
+
+set -v -e -x
+
+# Update packages.
+export DEBIAN_FRONTEND=noninteractive
+apt-get -y update && apt-get -y upgrade
+
+# Need this to add keys for PPAs below.
+apt-get install -y --no-install-recommends apt-utils
+
+apt_packages=()
+apt_packages+=('build-essential')
+apt_packages+=('ca-certificates')
+apt_packages+=('curl')
+apt_packages+=('npm')
+apt_packages+=('git')
+apt_packages+=('ninja-build')
+apt_packages+=('pkg-config')
+apt_packages+=('zlib1g-dev')
+
+# 32-bit builds
+apt_packages+=('lib32z1-dev')
+apt_packages+=('gcc-multilib')
+apt_packages+=('g++-multilib')
+
+# Latest Mercurial.
+apt_packages+=('mercurial')
+apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 41BD8711B1F0EC2B0D85B91CF59CE3A8323293EE
+echo "deb http://ppa.launchpad.net/mercurial-ppa/releases/ubuntu xenial main" > /etc/apt/sources.list.d/mercurial.list
+
+# gcc 4.8 and 6
+apt_packages+=('g++-6')
+apt_packages+=('g++-4.8')
+apt_packages+=('g++-6-multilib')
+apt_packages+=('g++-4.8-multilib')
+apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 60C317803A41BA51845E371A1E9377A2BA9EF27F
+echo "deb http://ppa.launchpad.net/ubuntu-toolchain-r/test/ubuntu xenial main" > /etc/apt/sources.list.d/toolchain.list
+
+# Install packages.
+apt-get -y update
+apt-get install -y --no-install-recommends ${apt_packages[@]}
+
+# 32-bit builds
+ln -s /usr/include/x86_64-linux-gnu/zconf.h /usr/include
+
+# Install clang-3.8 into /usr/local/.
+curl http://llvm.org/releases/3.8.0/clang+llvm-3.8.0-x86_64-linux-gnu-ubuntu-16.04.tar.xz | tar xJv -C /usr/local --strip-components=1
+
+# Compiler options.
+update-alternatives --install /usr/bin/gcc gcc /usr/local/bin/clang 5
+update-alternatives --install /usr/bin/g++ g++ /usr/local/bin/clang++ 5
+update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.8 10
+update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-4.8 10
+update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-6 20
+update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-6 20
+update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-5 30
+update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-5 30
+
+locale-gen en_US.UTF-8
+dpkg-reconfigure locales
+
+# Cleanup.
+rm -rf ~/.ccache ~/.cache
+apt-get autoremove -y
+apt-get clean
+apt-get autoclean
+rm $0
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/arm/_build_base.yml
@@ -0,0 +1,40 @@
+---
+reruns: 2
+
+task:
+  created: !from_now 0
+  deadline: !from_now 24
+  provisionerId: localprovisioner
+  workerType: nss-rpi
+  schedulerId: task-graph-scheduler
+
+  metadata:
+    owner: !env TC_OWNER
+    source: !env TC_SOURCE
+
+  payload:
+    maxRunTime: 7200
+    image: ttaubert/nss-rpi-ci:0.0.3
+
+    artifacts:
+      public:
+        type: directory
+        path: /home/worker/artifacts
+        expires: !from_now 24
+
+    command:
+      - "/bin/bash"
+      - "-c"
+      - "bin/checkout.sh && nss/automation/taskcluster/scripts/build.sh"
+
+    env:
+      NSS_HEAD_REPOSITORY: !env NSS_HEAD_REPOSITORY
+      NSS_HEAD_REVISION: !env NSS_HEAD_REVISION
+      GCC_VERSION: gcc-5
+      GXX_VERSION: g++-5
+
+  extra:
+    treeherder:
+      tier: 3 # hide jobs by default
+      jobKind: build
+      symbol: B
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/arm/_test_base.yml
@@ -0,0 +1,27 @@
+---
+reruns: 2
+
+task:
+  created: !from_now 0
+  deadline: !from_now 24
+  provisionerId: localprovisioner
+  workerType: nss-rpi
+  schedulerId: task-graph-scheduler
+
+  metadata:
+    owner: !env TC_OWNER
+    source: !env TC_SOURCE
+
+  payload:
+    maxRunTime: 7200
+    image: ttaubert/nss-rpi-ci:0.0.3
+
+    command:
+      - "/bin/bash"
+      - "-c"
+      - "bin/checkout.sh && nss/automation/taskcluster/scripts/run_tests.sh"
+
+  extra:
+    treeherder:
+      tier: 3 # hide jobs by default
+      jobKind: test
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/arm/build32-debug.yml
@@ -0,0 +1,29 @@
+---
+- task:
+    metadata:
+      name: "Linux 32 (ARM, debug)"
+      description: "Linux 32 (ARM, debug)"
+
+    extra:
+      treeherder:
+        build:
+          platform: linux32
+        machine:
+          platform: linux32
+        collection:
+          arm-debug: true
+
+  tests:
+    - chains
+    - cipher
+    - crmf
+    - db
+    - ec
+    - fips
+    - gtests
+    - lowhash
+    - merge
+    - sdr
+    - smime
+    - ssl
+    - tools
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/build.js
@@ -0,0 +1,147 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+var fs = require("fs");
+var path = require("path");
+var merge = require("merge");
+var slugid = require("slugid");
+var flatmap = require("flatmap");
+
+var yaml = require("./yaml");
+var try_syntax = require("./try_syntax");
+var image_builder = require("./image_builder");
+
+// Default values for debugging.
+var TC_OWNER = process.env.TC_OWNER || "{{tc_owner}}";
+var TC_SOURCE = process.env.TC_SOURCE || "{{tc_source}}";
+var TC_PROJECT = process.env.TC_PROJECT || "{{tc_project}}";
+var TC_COMMENT = process.env.TC_COMMENT || "{{tc_comment}}";
+var NSS_PUSHLOG_ID = process.env.NSS_PUSHLOG_ID || "{{nss_pushlog_id}}";
+var NSS_HEAD_REVISION = process.env.NSS_HEAD_REVISION || "{{nss_head_rev}}";
+
+// Add base information to the given task.
+function decorateTask(task) {
+  // Assign random task id.
+  task.taskId = slugid.v4();
+
+  // TreeHerder routes.
+  task.task.routes = [
+    "tc-treeherder-stage.v2." + TC_PROJECT + "." + NSS_HEAD_REVISION + "." + NSS_PUSHLOG_ID,
+    "tc-treeherder.v2." + TC_PROJECT + "." + NSS_HEAD_REVISION + "." + NSS_PUSHLOG_ID
+  ];
+}
+
+// Generate all tasks for a given build.
+function generateBuildTasks(platform, file) {
+  var dir = path.join(__dirname, "./" + platform);
+
+  // Parse base definitions.
+  var buildBase = yaml.parse(path.join(dir, "_build_base.yml"), {});
+  var testBase = yaml.parse(path.join(dir, "_test_base.yml"), {});
+
+  return flatmap(yaml.parse(path.join(dir, file)), function (task) {
+    // Merge base build task definition with the current one.
+    var tasks = [task = merge.recursive(true, buildBase, task)];
+
+    // Add base info.
+    decorateTask(task);
+
+    // Generate test tasks.
+    if (task.tests) {
+      // The base definition for all tests of this platform.
+      var base = merge.recursive(true, {
+        requires: [task.taskId],
+
+        task: {
+          payload: {
+            env: {
+              TC_PARENT_TASK_ID: task.taskId
+            }
+          }
+        }
+      }, testBase);
+
+      // Generate and append test task definitions.
+      tasks = tasks.concat(flatmap(task.tests, function (name) {
+        return generateTestTasks(name, base, task);
+      }));
+
+      // |tests| is not part of the schema.
+      delete task.tests;
+    }
+
+    return tasks;
+  });
+}
+
+// Generate all tasks for a given test.
+function generateTestTasks(name, base, task) {
+  // Load test definitions.
+  var dir = path.join(__dirname, "./tests");
+  var tests = yaml.parse(path.join(dir, name + ".yml"));
+
+  return tests.map(function (test) {
+    // Merge test with base definition.
+    test = merge.recursive(true, base, test);
+
+    // Add base info.
+    decorateTask(test);
+
+    // We only want to carry over environment variables...
+    test.task.payload.env =
+      merge.recursive(true, task.task.payload.env,
+                            test.task.payload.env);
+
+    // ...and TreeHerder configuration data.
+    test.task.extra.treeherder =
+      merge.recursive(true, task.task.extra.treeherder,
+                            test.task.extra.treeherder);
+
+    return test;
+  });
+}
+
+// Generate all tasks for a given platform.
+function generatePlatformTasks(platform) {
+  var dir = path.join(__dirname, "./" + platform);
+  var buildBase = yaml.parse(path.join(dir, "_build_base.yml"), {});
+  var testBase = yaml.parse(path.join(dir, "_test_base.yml"), {});
+
+  // Parse all build tasks.
+  return flatmap(fs.readdirSync(dir), function (file) {
+    if (!file.startsWith("_") && file.endsWith(".yml")) {
+      var tasks = generateBuildTasks(platform, file);
+
+      // Convert env variables to strings.
+      tasks.forEach(function (task) {
+        var env = task.task.payload.env || {};
+        Object.keys(env).forEach(function (name) {
+          if (typeof(env[name]) != "undefined") {
+            env[name] = env[name] + "";
+          }
+        });
+      });
+
+      return tasks;
+    }
+  });
+}
+
+// Construct the task graph.
+var graph = {
+  tasks: flatmap(["linux", "windows", "arm", "tools"], generatePlatformTasks)
+};
+
+// Filter tasks when try syntax is given.
+if (TC_PROJECT == "nss-try") {
+  graph.tasks = try_syntax.filterTasks(graph.tasks, TC_COMMENT);
+}
+
+// Inject the image builder tasks and dependencies.
+image_builder.asyncTweakTasks(graph.tasks).then(function (tasks) {
+  graph.tasks = tasks;
+
+  // Output the final graph.
+  process.stdout.write(JSON.stringify(graph, null, 2));
+});
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/image_builder.js
@@ -0,0 +1,148 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+var fs = require("fs");
+var path = require("path");
+var crypto = require("crypto");
+var slugid = require("slugid");
+var flatmap = require("flatmap");
+var taskcluster = require("taskcluster-client");
+
+var yaml = require("./yaml");
+
+// Default values for debugging.
+var TC_PROJECT = process.env.TC_PROJECT || "{{tc_project}}";
+var NSS_PUSHLOG_ID = process.env.NSS_PUSHLOG_ID || "{{nss_pushlog_id}}";
+var NSS_HEAD_REVISION = process.env.NSS_HEAD_REVISION || "{{nss_head_rev}}";
+
+// Add base information to the given task.
+function decorateTask(task) {
+  // Assign random task id.
+  task.taskId = slugid.v4();
+
+  // TreeHerder routes.
+  task.task.routes = [
+    "tc-treeherder-stage.v2." + TC_PROJECT + "." + NSS_HEAD_REVISION + "." + NSS_PUSHLOG_ID,
+    "tc-treeherder.v2." + TC_PROJECT + "." + NSS_HEAD_REVISION + "." + NSS_PUSHLOG_ID
+  ];
+}
+
+// Compute the SHA-256 digest.
+function sha256(data) {
+  var hash = crypto.createHash("sha256");
+  hash.update(data);
+  return hash.digest("hex");
+}
+
+// Recursively collect a list of all files of a given directory.
+function collectFilesInDirectory(dir) {
+  return flatmap(fs.readdirSync(dir), function (entry) {
+    var entry_path = path.join(dir, entry);
+
+    if (fs.lstatSync(entry_path).isDirectory()) {
+      return collectFilesInDirectory(entry_path);
+    }
+
+    return [entry_path];
+  });
+}
+
+// Compute a context hash for the given context path.
+function computeContextHash(context_path) {
+  var root = path.join(__dirname, "../../..");
+  var dir = path.join(root, context_path);
+  var files = collectFilesInDirectory(dir).sort();
+  var hashes = files.map(function (file) {
+    return sha256(file + "|" + fs.readFileSync(file, "utf-8"));
+  });
+
+  return sha256(hashes.join(","));
+}
+
+// Generates the image-builder task description.
+function generateImageBuilderTask(context_path) {
+  var task = yaml.parse(path.join(__dirname, "image_builder.yml"), {});
+
+  // Add base info.
+  decorateTask(task);
+
+  // Add info for docker image building.
+  task.task.payload.env.CONTEXT_PATH = context_path;
+  task.task.payload.env.HASH = computeContextHash(context_path);
+
+  return task;
+}
+
+// Returns a Promise<bool> that tells whether the task with the given id
+// has a public/image.tar artifact with a ready-to-use docker image.
+function asyncTaskHasImageArtifact(taskId) {
+  var queue = new taskcluster.Queue();
+
+  return queue.listLatestArtifacts(taskId).then(function (result) {
+    return result.artifacts.some(function (artifact) {
+      return artifact.name == "public/image.tar";
+    });
+  }, function () {
+    return false;
+  });
+}
+
+// Returns a Promise<task-id|null> with either a task id or null, depending
+// on whether we could find a task in the given namespace with a docker image.
+function asyncFindTaskWithImageArtifact(ns) {
+  var index = new taskcluster.Index();
+
+  return index.findTask(ns).then(function (result) {
+    return asyncTaskHasImageArtifact(result.taskId).then(function (has_image) {
+      return has_image ? result.taskId : null;
+    });
+  }, function () {
+    return null;
+  });
+}
+
+// Tweak the given list of tasks by injecting the image-builder task
+// and setting the right dependencies where needed.
+function asyncTweakTasks(tasks) {
+  var id = "linux";
+  var cx_path = "automation/taskcluster/docker";
+  var hash = computeContextHash(cx_path);
+  var ns = "docker.images.v1." + TC_PROJECT + "." + id + ".hash." + hash;
+  var additional_tasks = [];
+
+  // Check whether the docker image was already built.
+  return asyncFindTaskWithImageArtifact(ns).then(function (taskId) {
+    var builder_task;
+
+    if (!taskId) {
+      // No docker image found, add a task to build one.
+      builder_task = generateImageBuilderTask(cx_path);
+      taskId = builder_task.taskId;
+
+      // Add a route so we can find the task later again.
+      builder_task.task.routes.push("index." + ns);
+      additional_tasks.push(builder_task);
+    }
+
+    tasks.forEach(function (task) {
+      if (task.task.payload.image == cx_path) {
+        task.task.payload.image = {
+          path: "public/image.tar",
+          type: "task-image",
+          taskId: taskId
+        };
+
+        // Add a dependency only for top-level tasks (builds & tools) and only
+        // if we added an image building task. Otherwise we don't need to wait.
+        if (builder_task && !task.requires) {
+          task.requires = [taskId];
+        }
+      }
+    });
+
+    return additional_tasks.concat(tasks);
+  });
+}
+
+module.exports.asyncTweakTasks = asyncTweakTasks;
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/image_builder.yml
@@ -0,0 +1,49 @@
+---
+reruns: 2
+
+task:
+  created: !from_now 0
+  deadline: !from_now 24
+  provisionerId: aws-provisioner-v1
+  workerType: hg-worker
+  schedulerId: task-graph-scheduler
+
+  metadata:
+    name: Image Builder
+    description: Image Builder
+    owner: !env TC_OWNER
+    source: !env TC_SOURCE
+
+  payload:
+    maxRunTime: 3600
+    image: taskcluster/image_builder:0.1.5
+
+    artifacts:
+      public/image.tar:
+        type: file
+        path: /artifacts/image.tar
+        expires: !from_now 8760
+
+    command:
+      - "/bin/bash"
+      - "-c"
+      - "/home/worker/bin/build_image.sh"
+
+    env:
+      HEAD_REPOSITORY: !env NSS_HEAD_REPOSITORY
+      BASE_REPOSITORY: !env NSS_HEAD_REPOSITORY
+      HEAD_REV: !env NSS_HEAD_REVISION
+      HEAD_REF: !env NSS_HEAD_REVISION
+      PROJECT: !env TC_PROJECT
+
+    features:
+      dind: true
+
+  extra:
+    treeherder:
+      build:
+        platform: nss-decision
+      machine:
+        platform: nss-decision
+      jobKind: build
+      symbol: I
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/linux/_build_base.yml
@@ -0,0 +1,39 @@
+---
+reruns: 2
+
+task:
+  created: !from_now 0
+  deadline: !from_now 24
+  provisionerId: aws-provisioner-v1
+  workerType: hg-worker
+  schedulerId: task-graph-scheduler
+
+  metadata:
+    owner: !env TC_OWNER
+    source: !env TC_SOURCE
+
+  payload:
+    maxRunTime: 3600
+    image: automation/taskcluster/docker
+
+    artifacts:
+      public:
+        type: directory
+        path: /home/worker/artifacts
+        expires: !from_now 24
+
+    command:
+      - "/bin/bash"
+      - "-c"
+      - "bin/checkout.sh && nss/automation/taskcluster/scripts/build.sh"
+
+    env:
+      NSS_HEAD_REPOSITORY: !env NSS_HEAD_REPOSITORY
+      NSS_HEAD_REVISION: !env NSS_HEAD_REVISION
+      GCC_VERSION: gcc-5
+      GXX_VERSION: g++-5
+
+  extra:
+    treeherder:
+      jobKind: build
+      symbol: B
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/linux/_test_base.yml
@@ -0,0 +1,26 @@
+---
+reruns: 2
+
+task:
+  created: !from_now 0
+  deadline: !from_now 24
+  provisionerId: aws-provisioner-v1
+  workerType: hg-worker
+  schedulerId: task-graph-scheduler
+
+  metadata:
+    owner: !env TC_OWNER
+    source: !env TC_SOURCE
+
+  payload:
+    maxRunTime: 3600
+    image: automation/taskcluster/docker
+
+    command:
+      - "/bin/bash"
+      - "-c"
+      - "bin/checkout.sh && nss/automation/taskcluster/scripts/run_tests.sh"
+
+  extra:
+    treeherder:
+      jobKind: test
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/linux/build32-debug.yml
@@ -0,0 +1,116 @@
+---
+- task:
+    metadata:
+      name: "Linux 32 (debug)"
+      description: "Linux 32 (debug)"
+
+    extra:
+      treeherder:
+        build:
+          platform: linux32
+        machine:
+          platform: linux32
+        collection:
+          debug: true
+
+  tests:
+    - chains
+    - cipher
+    - crmf
+    - db
+    - ec
+    - fips
+    - gtests
+    - lowhash
+    - merge
+    - sdr
+    - smime
+    - ssl
+    - tools
+
+- task:
+    metadata:
+      name: "Linux 32 (debug, clang-3.8)"
+      description: "Linux 32 (debug, clang-3.8)"
+
+    payload:
+      env:
+        GCC_VERSION: clang
+        GXX_VERSION: clang++
+
+    extra:
+      treeherder:
+        build:
+          platform: linux32
+        machine:
+          platform: linux32
+        collection:
+          debug: true
+        groupSymbol: Builds
+        groupName: Various builds
+        symbol: clang-3.8
+
+- task:
+    metadata:
+      name: "Linux 32 (debug, gcc-4.8)"
+      description: "Linux 32 (debug, gcc-4.8)"
+
+    payload:
+      env:
+        GCC_VERSION: gcc-4.8
+        GXX_VERSION: g++-4.8
+
+    extra:
+      treeherder:
+        build:
+          platform: linux32
+        machine:
+          platform: linux32
+        collection:
+          debug: true
+        groupSymbol: Builds
+        groupName: Various builds
+        symbol: gcc-4.8
+
+- task:
+    metadata:
+      name: "Linux 32 (debug, gcc-6.1)"
+      description: "Linux 32 (debug, gcc-6.1)"
+
+    payload:
+      env:
+        GCC_VERSION: gcc-6
+        GXX_VERSION: g++-6
+
+    extra:
+      treeherder:
+        build:
+          platform: linux32
+        machine:
+          platform: linux32
+        collection:
+          debug: true
+        groupSymbol: Builds
+        groupName: Various builds
+        symbol: gcc-6.1
+
+- task:
+    metadata:
+      name: "Linux 32 (debug, NSS_NO_PKCS11_BYPASS=1)"
+      description: "Linux 32 (debug, NSS_NO_PKCS11_BYPASS=1)"
+
+    payload:
+      env:
+        NSS_NO_PKCS11_BYPASS: 1
+
+    extra:
+      treeherder:
+        build:
+          platform: linux32
+        machine:
+          platform: linux32
+        collection:
+          debug: true
+        groupSymbol: Builds
+        groupName: Various builds
+        symbol: noPkcs11Bypass
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/linux/build32-opt.yml
@@ -0,0 +1,124 @@
+---
+- task:
+    metadata:
+      name: "Linux 32 (opt)"
+      description: "Linux 32 (opt)"
+
+    payload:
+      env:
+        BUILD_OPT: 1
+
+    extra:
+      treeherder:
+        build:
+          platform: linux32
+        machine:
+          platform: linux32
+        collection:
+          opt: true
+
+  tests:
+    - chains
+    - cipher
+    - crmf
+    - db
+    - ec
+    - fips
+    - gtests
+    - lowhash
+    - merge
+    - sdr
+    - smime
+    - ssl
+    - tools
+
+- task:
+    metadata:
+      name: "Linux 32 (opt, clang-3.8)"
+      description: "Linux 32 (opt, clang-3.8)"
+
+    payload:
+      env:
+        GCC_VERSION: clang
+        GXX_VERSION: clang++
+        BUILD_OPT: 1
+
+    extra:
+      treeherder:
+        build:
+          platform: linux32
+        machine:
+          platform: linux32
+        collection:
+          opt: true
+        groupSymbol: Builds
+        groupName: Various builds
+        symbol: clang-3.8
+
+- task:
+    metadata:
+      name: "Linux 32 (opt, gcc-4.8)"
+      description: "Linux 32 (opt, gcc-4.8)"
+
+    payload:
+      env:
+        GCC_VERSION: gcc-4.8
+        GXX_VERSION: g++-4.8
+        BUILD_OPT: 1
+
+    extra:
+      treeherder:
+        build:
+          platform: linux32
+        machine:
+          platform: linux32
+        collection:
+          opt: true
+        groupSymbol: Builds
+        groupName: Various builds
+        symbol: gcc-4.8
+
+- task:
+    metadata:
+      name: "Linux 32 (opt, gcc-6.1)"
+      description: "Linux 32 (opt, gcc-6.1)"
+
+    payload:
+      env:
+        GCC_VERSION: gcc-6
+        GXX_VERSION: g++-6
+        BUILD_OPT: 1
+
+    extra:
+      treeherder:
+        build:
+          platform: linux32
+        machine:
+          platform: linux32
+        collection:
+          opt: true
+        groupSymbol: Builds
+        groupName: Various builds
+        symbol: gcc-6.1
+
+- task:
+    metadata:
+      name: "Linux 32 (opt, NSS_NO_PKCS11_BYPASS=1)"
+      description: "Linux 32 (opt, NSS_NO_PKCS11_BYPASS=1)"
+
+    payload:
+      env:
+        NSS_NO_PKCS11_BYPASS: 1
+        BUILD_OPT: 1
+
+    extra:
+      treeherder:
+        build:
+          platform: linux32
+        machine:
+          platform: linux32
+        collection:
+          opt: true
+        groupSymbol: Builds
+        groupName: Various builds
+        symbol: noPkcs11Bypass
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/linux/build64-asan.yml
@@ -0,0 +1,38 @@
+---
+- task:
+    metadata:
+      name: "Linux 64 (ASan, debug)"
+      description: "Linux 64 (ASan, debug)"
+
+    payload:
+      env:
+        GCC_VERSION: clang
+        GXX_VERSION: clang++
+        NSS_DISABLE_ARENA_FREE_LIST: 1
+        NSS_DISABLE_UNLOAD: 1
+        USE_ASAN: 1
+        USE_64: 1
+
+    extra:
+      treeherder:
+        build:
+          platform: linux64
+        machine:
+          platform: linux64
+        collection:
+          asan: true
+
+  tests:
+    - chains
+    - cipher
+    - crmf
+    - db
+    - ec
+    - fips
+    - gtests
+    - lowhash
+    - merge
+    - sdr
+    - smime
+    - ssl
+    - tools
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/linux/build64-debug.yml
@@ -0,0 +1,146 @@
+---
+- task:
+    metadata:
+      name: "Linux 64 (debug)"
+      description: "Linux 64 (debug)"
+
+    payload:
+      env:
+        USE_64: 1
+
+    extra:
+      treeherder:
+        build:
+          platform: linux64
+        machine:
+          platform: linux64
+        collection:
+          debug: true
+
+  tests:
+    - chains
+    - cipher
+    - crmf
+    - db
+    - ec
+    - fips
+    - gtests
+    - lowhash
+    - merge
+    - sdr
+    - smime
+    - ssl
+    - tools
+
+- task:
+    metadata:
+      name: "Linux 64 (debug, clang-3.8)"
+      description: "Linux 64 (debug, clang-3.8)"
+
+    payload:
+      env:
+        GCC_VERSION: clang
+        GXX_VERSION: clang++
+        USE_64: 1
+
+    extra:
+      treeherder:
+        build:
+          platform: linux64
+        machine:
+          platform: linux64
+        collection:
+          debug: true
+        groupSymbol: Builds
+        groupName: Various builds
+        symbol: clang-3.8
+
+- task:
+    metadata:
+      name: "Linux 64 (debug, gcc-4.8)"
+      description: "Linux 64 (debug, gcc-4.8)"
+
+    payload:
+      env:
+        GCC_VERSION: gcc-4.8
+        GXX_VERSION: g++-4.8
+        USE_64: 1
+
+    extra:
+      treeherder:
+        build:
+          platform: linux64
+        machine:
+          platform: linux64
+        collection:
+          debug: true
+        groupSymbol: Builds
+        groupName: Various builds
+        symbol: gcc-4.8
+
+- task:
+    metadata:
+      name: "Linux 64 (debug, gcc-6.1)"
+      description: "Linux 64 (debug, gcc-6.1)"
+
+    payload:
+      env:
+        GCC_VERSION: gcc-6
+        GXX_VERSION: g++-6
+        USE_64: 1
+
+    extra:
+      treeherder:
+        build:
+          platform: linux64
+        machine:
+          platform: linux64
+        collection:
+          debug: true
+        groupSymbol: Builds
+        groupName: Various builds
+        symbol: gcc-6.1
+
+- task:
+    metadata:
+      name: "Linux 64 (debug, NSS_NO_PKCS11_BYPASS=1)"
+      description: "Linux 64 (debug, NSS_NO_PKCS11_BYPASS=1)"
+
+    payload:
+      env:
+        NSS_NO_PKCS11_BYPASS: 1
+        USE_64: 1
+
+    extra:
+      treeherder:
+        build:
+          platform: linux64
+        machine:
+          platform: linux64
+        collection:
+          debug: true
+        groupSymbol: Builds
+        groupName: Various builds
+        symbol: noPkcs11Bypass
+
+- task:
+    metadata:
+      name: "Linux 64 (debug, NSS_DISABLE_LIBPKIX=1)"
+      description: "Linux 64 (debug, NSS_DISABLE_LIBPKIX=1)"
+
+    payload:
+      env:
+        NSS_DISABLE_LIBPKIX: 1
+        USE_64: 1
+
+    extra:
+      treeherder:
+        build:
+          platform: linux64
+        machine:
+          platform: linux64
+        collection:
+          debug: true
+        groupSymbol: Builds
+        groupName: Various builds
+        symbol: noLibpkix
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/linux/build64-opt.yml
@@ -0,0 +1,129 @@
+---
+- task:
+    metadata:
+      name: "Linux 64 (opt)"
+      description: "Linux 64 (opt)"
+
+    payload:
+      env:
+        BUILD_OPT: 1
+        USE_64: 1
+
+    extra:
+      treeherder:
+        build:
+          platform: linux64
+        machine:
+          platform: linux64
+        collection:
+          opt: true
+
+  tests:
+    - chains
+    - cipher
+    - crmf
+    - db
+    - ec
+    - fips
+    - gtests
+    - lowhash
+    - merge
+    - sdr
+    - smime
+    - ssl
+    - tools
+
+- task:
+    metadata:
+      name: "Linux 64 (opt, clang-3.8)"
+      description: "Linux 64 (opt, clang-3.8)"
+
+    payload:
+      env:
+        GCC_VERSION: clang
+        GXX_VERSION: clang++
+        BUILD_OPT: 1
+        USE_64: 1
+
+    extra:
+      treeherder:
+        build:
+          platform: linux64
+        machine:
+          platform: linux64
+        collection:
+          opt: true
+        groupSymbol: Builds
+        groupName: Various builds
+        symbol: clang-3.8
+
+- task:
+    metadata:
+      name: "Linux 64 (opt, gcc-4.8)"
+      description: "Linux 64 (opt, gcc-4.8)"
+
+    payload:
+      env:
+        GCC_VERSION: gcc-4.8
+        GXX_VERSION: g++-4.8
+        BUILD_OPT: 1
+        USE_64: 1
+
+    extra:
+      treeherder:
+        build:
+          platform: linux64
+        machine:
+          platform: linux64
+        collection:
+          opt: true
+        groupSymbol: Builds
+        groupName: Various builds
+        symbol: gcc-4.8
+
+- task:
+    metadata:
+      name: "Linux 64 (opt, gcc-6.1)"
+      description: "Linux 64 (opt, gcc-6.1)"
+
+    payload:
+      env:
+        GCC_VERSION: gcc-6
+        GXX_VERSION: g++-6
+        BUILD_OPT: 1
+        USE_64: 1
+
+    extra:
+      treeherder:
+        build:
+          platform: linux64
+        machine:
+          platform: linux64
+        collection:
+          opt: true
+        groupSymbol: Builds
+        groupName: Various builds
+        symbol: gcc-6.1
+
+- task:
+    metadata:
+      name: "Linux 64 (opt, NSS_NO_PKCS11_BYPASS=1)"
+      description: "Linux 64 (opt, NSS_NO_PKCS11_BYPASS=1)"
+
+    payload:
+      env:
+        NSS_NO_PKCS11_BYPASS: 1
+        BUILD_OPT: 1
+        USE_64: 1
+
+    extra:
+      treeherder:
+        build:
+          platform: linux64
+        machine:
+          platform: linux64
+        collection:
+          opt: true
+        groupSymbol: Builds
+        groupName: Various builds
+        symbol: noPkcs11Bypass
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/package.json
@@ -0,0 +1,16 @@
+{
+  "name": "decision-task",
+  "version": "0.0.1",
+  "private": true,
+  "author": "Tim Taubert <ttaubert@mozilla.com>",
+  "description": "Decision Task for NSS",
+  "dependencies": {
+    "flatmap": "0.0.3",
+    "intersect": "^1.0.1",
+    "js-yaml": "^3.6.1",
+    "merge": "^1.2.0",
+    "minimist": "^1.2.0",
+    "slugid": "^1.1.0",
+    "taskcluster-client": "^1.2.1"
+  }
+}
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/tests/chains.yml
@@ -0,0 +1,14 @@
+---
+- task:
+    metadata:
+      name: Chains tests
+      description: Chains tests
+
+    payload:
+      maxRunTime: 14400
+      env:
+        NSS_TESTS: chains
+
+    extra:
+      treeherder:
+        symbol: Chains
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/tests/cipher.yml
@@ -0,0 +1,13 @@
+---
+- task:
+    metadata:
+      name: Cipher tests
+      description: Cipher tests
+
+    payload:
+      env:
+        NSS_TESTS: cipher
+
+    extra:
+      treeherder:
+        symbol: Cipher
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/tests/crmf.yml
@@ -0,0 +1,14 @@
+---
+- task:
+    metadata:
+      name: CRMF tests
+      description: CRMF tests
+
+    payload:
+      env:
+        ASAN_OPTIONS: detect_leaks=0
+        NSS_TESTS: crmf
+
+    extra:
+      treeherder:
+        symbol: CRMF
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/tests/db.yml
@@ -0,0 +1,13 @@
+---
+- task:
+    metadata:
+      name: DB tests
+      description: DB tests
+
+    payload:
+      env:
+        NSS_TESTS: dbtests
+
+    extra:
+      treeherder:
+        symbol: DB
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/tests/ec.yml
@@ -0,0 +1,13 @@
+---
+- task:
+    metadata:
+      name: EC tests
+      description: EC tests
+
+    payload:
+      env:
+        NSS_TESTS: ec
+
+    extra:
+      treeherder:
+        symbol: EC
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/tests/fips.yml
@@ -0,0 +1,14 @@
+---
+- task:
+    metadata:
+      name: FIPS tests
+      description: FIPS tests
+
+    payload:
+      env:
+        ASAN_OPTIONS: detect_leaks=0
+        NSS_TESTS: fips
+
+    extra:
+      treeherder:
+        symbol: FIPS
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/tests/gtests.yml
@@ -0,0 +1,13 @@
+---
+- task:
+    metadata:
+      name: GTests
+      description: GTests
+
+    payload:
+      env:
+        NSS_TESTS: ssl_gtests gtests
+
+    extra:
+      treeherder:
+        symbol: GTest
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/tests/lowhash.yml
@@ -0,0 +1,13 @@
+---
+- task:
+    metadata:
+      name: Lowhash tests
+      description: Lowhash tests
+
+    payload:
+      env:
+        NSS_TESTS: lowhash
+
+    extra:
+      treeherder:
+        symbol: Lowhash
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/tests/merge.yml
@@ -0,0 +1,13 @@
+---
+- task:
+    metadata:
+      name: Merge tests
+      description: Merge tests
+
+    payload:
+      env:
+        NSS_TESTS: merge
+
+    extra:
+      treeherder:
+        symbol: Merge
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/tests/sdr.yml
@@ -0,0 +1,13 @@
+---
+- task:
+    metadata:
+      name: SDR tests
+      description: SDR tests
+
+    payload:
+      env:
+        NSS_TESTS: sdr
+
+    extra:
+      treeherder:
+        symbol: SDR
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/tests/smime.yml
@@ -0,0 +1,13 @@
+---
+- task:
+    metadata:
+      name: S/MIME tests
+      description: S/MIME tests
+
+    payload:
+      env:
+        NSS_TESTS: smime
+
+    extra:
+      treeherder:
+        symbol: SMIME
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/tests/ssl.yml
@@ -0,0 +1,65 @@
+---
+- task:
+    metadata:
+      name: "SSL tests (standard)"
+      description: "SSL tests (standard)"
+
+    payload:
+      maxRunTime: 14400
+      env:
+        NSS_CYCLES: standard
+        NSS_TESTS: ssl
+
+    extra:
+      treeherder:
+        symbol: standard
+        groupSymbol: SSL
+        groupName: SSL tests
+
+- task:
+    metadata:
+      name: "SSL tests (pkix)"
+      description: "SSL tests (pkix)"
+
+    payload:
+      env:
+        NSS_CYCLES: pkix
+        NSS_TESTS: ssl
+
+    extra:
+      treeherder:
+        symbol: pkix
+        groupSymbol: SSL
+        groupName: SSL tests
+
+- task:
+    metadata:
+      name: "SSL tests (sharedb)"
+      description: "SSL tests (sharedb)"
+
+    payload:
+      env:
+        NSS_CYCLES: sharedb
+        NSS_TESTS: ssl
+
+    extra:
+      treeherder:
+        symbol: sharedb
+        groupSymbol: SSL
+        groupName: SSL tests
+
+- task:
+    metadata:
+      name: "SSL tests (upgradedb)"
+      description: "SSL tests (upgradedb)"
+
+    payload:
+      env:
+        NSS_CYCLES: upgradedb
+        NSS_TESTS: ssl
+
+    extra:
+      treeherder:
+        symbol: upgradedb
+        groupSymbol: SSL
+        groupName: SSL tests
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/tests/tools.yml
@@ -0,0 +1,13 @@
+---
+- task:
+    metadata:
+      name: Tools tests
+      description: Tools tests
+
+    payload:
+      env:
+        NSS_TESTS: tools
+
+    extra:
+      treeherder:
+        symbol: Tools
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/tools/_build_base.yml
@@ -0,0 +1,29 @@
+---
+reruns: 0
+
+task:
+  created: !from_now 0
+  deadline: !from_now 24
+  provisionerId: aws-provisioner-v1
+  workerType: hg-worker
+  schedulerId: task-graph-scheduler
+
+  metadata:
+    owner: !env TC_OWNER
+    source: !env TC_SOURCE
+
+  payload:
+    maxRunTime: 3600
+    image: automation/taskcluster/docker
+
+    env:
+      NSS_HEAD_REPOSITORY: !env NSS_HEAD_REPOSITORY
+      NSS_HEAD_REVISION: !env NSS_HEAD_REVISION
+
+  extra:
+    treeherder:
+      build:
+        platform: nss-tools
+      machine:
+        platform: nss-tools
+      jobKind: test
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/tools/clang-format.yml
@@ -0,0 +1,15 @@
+---
+- task:
+    metadata:
+      name: clang-format-3.8
+      description: clang-format-3.8
+
+    payload:
+      command:
+        - "/bin/bash"
+        - "-c"
+        - "bin/checkout.sh && nss/automation/taskcluster/scripts/run_clang_format.sh"
+
+    extra:
+      treeherder:
+        symbol: clang-format-3.8
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/tools/scan-build.yml
@@ -0,0 +1,26 @@
+---
+- task:
+    metadata:
+      name: scan-build-3.8
+      description: scan-build-3.8
+
+    payload:
+      artifacts:
+        public:
+          type: directory
+          path: /home/worker/artifacts
+          expires: !from_now 24
+
+      command:
+        - "/bin/bash"
+        - "-c"
+        - "bin/checkout.sh && nss/automation/taskcluster/scripts/run_scan_build.sh"
+
+      env:
+        GCC_VERSION: clang
+        GXX_VERSION: clang++
+        USE_64: 1
+
+    extra:
+      treeherder:
+        symbol: scan-build-3.8
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/try_syntax.js
@@ -0,0 +1,143 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+var intersect = require("intersect");
+var parse_args = require("minimist");
+
+function parseOptions(opts) {
+  opts = parse_args(opts.split(/\s+/), {
+    default: {build: "do", platform: "all", unittests: "none", tools: "none"},
+    alias: {b: "build", p: "platform", u: "unittests", t: "tools", e: "extra-builds"},
+    string: ["build", "platform", "unittests", "tools", "extra-builds"]
+  });
+
+  // Parse build types (d=debug, o=opt).
+  var builds = intersect(opts.build.split(""), ["d", "o"]);
+
+  // If the given value is nonsense default to debug and opt builds.
+  if (builds.length == 0) {
+    builds = ["d", "o"];
+  }
+
+  // Parse platforms.
+  var allPlatforms = ["linux", "linux64", "linux64-asan", "win64", "arm"];
+  var platforms = intersect(opts.platform.split(/\s*,\s*/), allPlatforms);
+
+  // If the given value is nonsense or "none" default to all platforms.
+  if (platforms.length == 0 && opts.platform != "none") {
+    platforms = allPlatforms;
+  }
+
+  // Parse unit tests.
+  var allUnitTests = ["crmf", "chains", "cipher", "db", "ec", "fips", "gtest",
+                      "lowhash", "merge", "sdr", "smime", "tools", "ssl"];
+  var unittests = intersect(opts.unittests.split(/\s*,\s*/), allUnitTests);
+
+  // If the given value is "all" run all tests.
+  // If it's nonsense then don't run any tests.
+  if (opts.unittests == "all") {
+    unittests = allUnitTests;
+  } else if (unittests.length == 0) {
+    unittests = [];
+  }
+
+  // Parse tools.
+  var allTools = ["clang-format", "scan-build"];
+  var tools = intersect(opts.tools.split(/\s*,\s*/), allTools);
+
+  // If the given value is "all" run all tools.
+  // If it's nonsense then don't run any tools.
+  if (opts.tools == "all") {
+    tools = allTools;
+  } else if (tools.length == 0) {
+    tools = [];
+  }
+
+  return {
+    builds: builds,
+    platforms: platforms,
+    unittests: unittests,
+    extra: (opts.e == "all"),
+    tools: tools
+  };
+}
+
+function filterTasks(tasks, comment) {
+  // Check for try syntax in changeset comment.
+  var match = comment.match(/^\s*try:\s*(.*)\s*$/);
+  if (!match) {
+    return tasks;
+  }
+
+  var opts = parseOptions(match[1]);
+
+  return tasks.filter(function (task) {
+    var env = task.task.payload.env || {};
+    var th = task.task.extra.treeherder;
+    var machine = th.machine.platform;
+    var coll = th.collection || {};
+    var found;
+
+    // Filter tools. We can immediately return here as those
+    // are not affected by platform or build type selectors.
+    if (machine == "nss-tools") {
+      return opts.tools.some(function (tool) {
+        var symbol = th.symbol.toLowerCase();
+        return symbol.startsWith(tool);
+      });
+    }
+
+    // Filter unit tests.
+    if (env.NSS_TESTS && env.TC_PARENT_TASK_ID) {
+      found = opts.unittests.some(function (test) {
+        var symbol = (th.groupSymbol || th.symbol).toLowerCase();
+        return symbol.startsWith(test);
+      });
+
+      if (!found) {
+        return false;
+      }
+    }
+
+    // Filter extra builds.
+    if (th.groupSymbol == "Builds" && !opts.extra) {
+      return false;
+    }
+
+    // Filter by platform.
+    found = opts.platforms.some(function (platform) {
+      var aliases = {
+        "linux": "linux32",
+        "linux64-asan": "linux64",
+        "win64": "windows2012-64",
+        "arm": "linux32"
+      };
+
+      // Check the platform name.
+      var keep = machine == (aliases[platform] || platform);
+
+      // Additional checks.
+      if (platform == "linux64-asan") {
+        keep &= coll.asan;
+      } else if (platform == "arm") {
+        keep &= (coll["arm-opt"] || coll["arm-debug"]);
+      } else {
+        keep &= (coll.opt || coll.debug);
+      }
+
+      return keep;
+    });
+
+    if (!found) {
+      return false;
+    }
+
+    // Finally, filter by build type.
+    var isDebug = coll.debug || coll.asan || coll["arm-debug"];
+    return (isDebug && opts.builds.indexOf("d") > -1) ||
+           (!isDebug && opts.builds.indexOf("o") > -1);
+  });
+}
+
+module.exports.filterTasks = filterTasks;
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/windows/_build_base.yml
@@ -0,0 +1,37 @@
+---
+reruns: 2
+
+task:
+  created: !from_now 0
+  deadline: !from_now 24
+  provisionerId: aws-provisioner-v1
+  workerType: nss-win2012r2
+  schedulerId: task-graph-scheduler
+
+  metadata:
+    owner: !env TC_OWNER
+    source: !env TC_SOURCE
+
+  payload:
+    maxRunTime: 3600
+
+    artifacts:
+      - type: directory
+        path: "public\\build"
+        expires: !from_now 24
+
+    command:
+      - "bash -c \"hg clone -r $NSS_HEAD_REVISION $NSS_HEAD_REPOSITORY nss || (sleep 2; hg clone -r $NSS_HEAD_REVISION $NSS_HEAD_REPOSITORY nss) || (sleep 5; hg clone -r $NSS_HEAD_REVISION $NSS_HEAD_REPOSITORY nss)\""
+      - "bash -c nss/automation/taskcluster/windows/build.sh"
+
+    env:
+      PATH: "c:\\mozilla-build\\python;c:\\mozilla-build\\msys\\local\\bin;c:\\mozilla-build\\7zip;c:\\mozilla-build\\info-zip;c:\\mozilla-build\\python\\Scripts;c:\\mozilla-build\\yasm;c:\\mozilla-build\\msys\\bin;c:\\Windows\\system32;c:\\mozilla-build\\upx391w;c:\\mozilla-build\\moztools-x64\\bin;c:\\mozilla-build\\wget"
+      NSS_HEAD_REPOSITORY: !env NSS_HEAD_REPOSITORY
+      NSS_HEAD_REVISION: !env NSS_HEAD_REVISION
+      DOMSUF: localdomain
+      HOST: localhost
+
+  extra:
+    treeherder:
+      jobKind: build
+      symbol: B
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/windows/_test_base.yml
@@ -0,0 +1,24 @@
+---
+reruns: 2
+
+task:
+  created: !from_now 0
+  deadline: !from_now 24
+  provisionerId: aws-provisioner-v1
+  workerType: nss-win2012r2
+  schedulerId: task-graph-scheduler
+
+  metadata:
+    owner: !env TC_OWNER
+    source: !env TC_SOURCE
+
+  payload:
+    maxRunTime: 3600
+
+    command:
+      - "hg clone -r %NSS_HEAD_REVISION% %NSS_HEAD_REPOSITORY% nss"
+      - "bash -c nss/automation/taskcluster/windows/run_tests.sh"
+
+  extra:
+    treeherder:
+      jobKind: test
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/windows/build64-debug.yml
@@ -0,0 +1,55 @@
+---
+- task:
+    metadata:
+      name: "Windows 2012 64 (debug)"
+      description: "Windows 2012 64 (debug)"
+
+    payload:
+      env:
+        USE_64: 1
+
+    extra:
+      treeherder:
+        build:
+          platform: windows2012-64
+        machine:
+          platform: windows2012-64
+        collection:
+          debug: true
+
+  tests:
+    - chains
+    - cipher
+    - crmf
+    - db
+    - ec
+    - fips
+    - gtests
+    - lowhash
+    - merge
+    - sdr
+    - smime
+    - ssl
+    - tools
+
+- task:
+    metadata:
+      name: "Windows 2012 64 (debug, NSS_NO_PKCS11_BYPASS=1)"
+      description: "Windows 2012 64 (debug, NSS_NO_PKCS11_BYPASS=1)"
+
+    payload:
+      env:
+        NSS_NO_PKCS11_BYPASS: 1
+        USE_64: 1
+
+    extra:
+      treeherder:
+        build:
+          platform: windows2012-64
+        machine:
+          platform: windows2012-64
+        collection:
+          debug: true
+        groupSymbol: Builds
+        groupName: Various builds
+        symbol: noPkcs11Bypass
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/windows/build64-opt.yml
@@ -0,0 +1,57 @@
+---
+- task:
+    metadata:
+      name: "Windows 2012 64 (opt)"
+      description: "Windows 2012 64 (opt)"
+
+    payload:
+      env:
+        BUILD_OPT: 1
+        USE_64: 1
+
+    extra:
+      treeherder:
+        build:
+          platform: windows2012-64
+        machine:
+          platform: windows2012-64
+        collection:
+          opt: true
+
+  tests:
+    - chains
+    - cipher
+    - crmf
+    - db
+    - ec
+    - fips
+    - gtests
+    - lowhash
+    - merge
+    - sdr
+    - smime
+    - ssl
+    - tools
+
+- task:
+    metadata:
+      name: "Windows 2012 64 (opt, NSS_NO_PKCS11_BYPASS=1)"
+      description: "Windows 2012 64 (opt, NSS_NO_PKCS11_BYPASS=1)"
+
+    payload:
+      env:
+        NSS_NO_PKCS11_BYPASS: 1
+        BUILD_OPT: 1
+        USE_64: 1
+
+    extra:
+      treeherder:
+        build:
+          platform: windows2012-64
+        machine:
+          platform: windows2012-64
+        collection:
+          opt: true
+        groupSymbol: Builds
+        groupName: Various builds
+        symbol: noPkcs11Bypass
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/graph/yaml.js
@@ -0,0 +1,51 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+var fs = require("fs");
+var yaml = require("js-yaml");
+
+// Register custom YAML types.
+var YAML_SCHEMA = yaml.Schema.create([
+  // Point in time at $now + x hours.
+  new yaml.Type('!from_now', {
+    kind: "scalar",
+
+    resolve: function (data) {
+      return true;
+    },
+
+    construct: function (data) {
+      var d = new Date();
+      d.setHours(d.getHours() + (data|0));
+      return d.toJSON();
+    }
+  }),
+
+  // Environment variables.
+  new yaml.Type('!env', {
+    kind: "scalar",
+
+    resolve: function (data) {
+      return true;
+    },
+
+    construct: function (data) {
+      return process.env[data] || "{{" + data.toLowerCase() + "}}";
+    }
+  })
+]);
+
+// Parse a given YAML file.
+function parse(file, fallback) {
+  // Return fallback if the file doesn't exist.
+  if (!fs.existsSync(file) && fallback) {
+    return fallback;
+  }
+
+  // Otherwise, read the file or fail.
+  var source = fs.readFileSync(file, "utf-8");
+  return yaml.load(source, {schema: YAML_SCHEMA});
+}
+
+module.exports.parse = parse;
new file mode 100755
--- /dev/null
+++ b/automation/taskcluster/scripts/build.sh
@@ -0,0 +1,29 @@
+#!/usr/bin/env bash
+
+set -v -e -x
+
+source $(dirname $0)/tools.sh
+
+if [[ $(id -u) -eq 0 ]]; then
+    # Set compiler.
+    switch_compilers
+
+    # Drop privileges by re-running this script.
+    exec su worker $0
+fi
+
+# Clone NSPR if needed.
+hg_clone https://hg.mozilla.org/projects/nspr nspr default
+
+# Build.
+make -C nss nss_build_all
+
+# Generate certificates.
+NSS_TESTS=cert NSS_CYCLES="standard pkix sharedb" $(dirname $0)/run_tests.sh
+
+# Reset test counter so that test runs pick up our certificates.
+echo 1 > tests_results/security/localhost
+
+# Package.
+mkdir artifacts
+tar cvfjh artifacts/dist.tar.bz2 dist tests_results
new file mode 100755
--- /dev/null
+++ b/automation/taskcluster/scripts/extend_task_graph.sh
@@ -0,0 +1,16 @@
+#!/usr/bin/env bash
+
+set -v -e -x
+
+if [ $(id -u) = 0 ]; then
+    # Drop privileges by re-running this script.
+    exec su worker $0
+fi
+
+mkdir -p /home/worker/artifacts
+
+# Install Node.JS dependencies.
+cd nss/automation/taskcluster/graph/ && npm install
+
+# Build the task graph definition.
+nodejs build.js > /home/worker/artifacts/graph.json
new file mode 100755
--- /dev/null
+++ b/automation/taskcluster/scripts/run_clang_format.sh
@@ -0,0 +1,61 @@
+#!/usr/bin/env bash
+
+set -v -e -x
+
+if [ $(id -u) -eq 0 ]; then
+    # Drop privileges by re-running this script.
+    exec su worker $0 "$@"
+fi
+
+# Apply clang-format 3.8 on the provided folder and verify that this doesn't change any file.
+# If any file differs after formatting, the script eventually exits with 1.
+# Any differences between formatted and unformatted files is printed to stdout to give a hint what's wrong.
+
+# Includes a default set of directories.
+
+apply=false
+if [ $1 = "--apply" ]; then
+    apply=true
+    shift
+fi
+
+if [ $# -gt 0 ]; then
+    dirs=("$@")
+else
+    top=$(dirname $0)/../../..
+    dirs=( \
+         "$top/cmd" \
+         "$top/lib/base" \
+         "$top/lib/certdb" \
+         "$top/lib/certhigh" \
+         "$top/lib/ckfw" \
+         "$top/lib/crmf" \
+         "$top/lib/cryptohi" \
+         "$top/lib/dbm" \
+         "$top/lib/dev" \
+         "$top/lib/freebl" \
+         "$top/lib/nss" \
+         "$top/lib/softoken" \
+         "$top/lib/ssl" \
+         "$top/lib/util" \
+         "$top/lib/sysinit" \
+         "$top/external_tests/common" \
+         "$top/external_tests/der_gtest" \
+         "$top/external_tests/pk11_gtest" \
+         "$top/external_tests/ssl_gtest" \
+         "$top/external_tests/util_gtest" \
+    )
+fi
+
+STATUS=0
+for dir in "${dirs[@]}"; do
+    for i in $(find "$dir" -type f \( -name '*.[ch]' -o -name '*.cc' \) -print); do
+        if $apply; then
+            clang-format -i "$i"
+        elif ! clang-format "$i" | diff -Naur "$i" -; then
+            echo "Sorry, $i is not formatted properly. Please use clang-format 3.8 on your patch before landing."
+            STATUS=1
+        fi
+    done
+done
+exit $STATUS
new file mode 100755
--- /dev/null
+++ b/automation/taskcluster/scripts/run_scan_build.sh
@@ -0,0 +1,51 @@
+#!/usr/bin/env bash
+
+set -v -e -x
+
+if [ $(id -u) = 0 ]; then
+    source $(dirname $0)/tools.sh
+
+    # Set compiler.
+    switch_compilers
+
+    # Drop privileges by re-running this script.
+    exec su worker $0 $@
+fi
+
+# Clone NSPR if needed.
+if [ ! -d "nspr" ]; then
+    hg clone https://hg.mozilla.org/projects/nspr
+fi
+
+# Build.
+cd nss && make nss_build_all
+
+# we run scan-build on these folders
+declare -a scan=("lib/ssl" "lib/freebl")
+# corresponds to the number of errors that are expected in the |scan| folder
+declare -a ignore=(1 0)
+
+for i in "${scan[@]}"
+do
+   echo "cleaning $i ..."
+   find "$i" -name "*.OBJ" | xargs rm -fr
+done
+
+# run scan-build
+scan-build -o /home/worker/artifacts/ make nss_build_all && cd ..
+
+# print errors we found
+set +v +x
+STATUS=0
+for i in "${!scan[@]}"
+do
+   n=$(grep -Rn "${scan[i]}" /home/worker/artifacts/*/report-*.html | wc -l)
+   if [ $n -ne ${ignore[$i]} ]; then
+     STATUS=1
+     echo "$(date '+%T') WARNING - TEST-UNEXPECTED-FAIL: ${scan[$i]} contains $n scan-build errors"
+   elif [ $n -ne 0 ]; then
+     echo "$(date '+%T') WARNING - TEST-UNEXPECTED-FAIL: ${scan[$i]} contains $n scan-build errors (nonfatal!)"
+   fi
+
+done
+exit $STATUS
new file mode 100755
--- /dev/null
+++ b/automation/taskcluster/scripts/run_tests.sh
@@ -0,0 +1,25 @@
+#!/usr/bin/env bash
+
+set -v -e -x
+
+if [ $(id -u) = 0 ]; then
+    source $(dirname $0)/tools.sh
+
+    # Set compiler.
+    switch_compilers
+
+    # Stupid Docker.
+    echo "127.0.0.1 localhost.localdomain" >> /etc/hosts
+
+    # Drop privileges by re-running this script.
+    exec su worker $0
+fi
+
+# Fetch artifact if needed.
+if [ ! -d "dist" ]; then
+    curl --retry 3 -Lo dist.tar.bz2 https://queue.taskcluster.net/v1/task/$TC_PARENT_TASK_ID/artifacts/public/dist.tar.bz2
+    tar xvjf dist.tar.bz2
+fi
+
+# Run tests.
+cd nss/tests && ./all.sh
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/scripts/tools.sh
@@ -0,0 +1,29 @@
+#!/usr/bin/env bash
+
+set -v -e -x
+
+switch_compilers() {
+    GCC=`which ${GCC_VERSION:-gcc-5}`
+    GXX=`which ${GXX_VERSION:-g++-5}`
+
+    if [ -e "$GCC" ] && [ -e "$GXX" ]; then
+        update-alternatives --set gcc $GCC
+        update-alternatives --set g++ $GXX
+    else
+        echo "Unknown compiler $GCC_VERSION/$GXX_VERSION."
+        exit 1
+    fi
+}
+
+# Usage: hg_clone repo dir [revision=@]
+hg_clone() {
+    repo=$1
+    dir=$2
+    rev=${3:-@}
+    for i in 0 2 5; do
+        sleep $i
+        hg clone -r "$rev" "$repo" "$dir" && return
+        rm -rf "$dir"
+    done
+    exit 1
+}
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/windows/build.sh
@@ -0,0 +1,21 @@
+#!/usr/bin/env bash
+
+set -v -e -x
+
+# Set up the toolchain.
+source $(dirname $0)/setup.sh
+
+# Clone NSPR.
+hg_clone https://hg.mozilla.org/projects/nspr nspr default
+
+# Build.
+make -C nss nss_build_all
+
+# Generate certificates.
+NSS_TESTS=cert NSS_CYCLES="standard pkix sharedb" nss/tests/all.sh
+
+# Reset test counter so that test runs pick up our certificates.
+echo 1 > tests_results/security/localhost
+
+# Package.
+7z a public/build/dist.7z dist tests_results
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/windows/releng.manifest
@@ -0,0 +1,10 @@
+[
+  {
+    "version": "Visual Studio 2015 Update 2 / SDK 10.0.10586.0/212",
+    "size": 332442800,
+    "digest": "995394a4a515c7cb0f8595f26f5395361a638870dd0bbfcc22193fe1d98a0c47126057d5999cc494f3f3eac5cb49160e79757c468f83ee5797298e286ef6252c",
+    "algorithm": "sha512",
+    "filename": "vs2015u2.zip",
+    "unpack": true
+  }
+]
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/windows/run_tests.sh
@@ -0,0 +1,13 @@
+#!/usr/bin/env bash
+
+set -v -e -x
+
+# Set up the toolchain.
+source $(dirname $0)/setup.sh
+
+# Fetch artifact.
+wget -t 3 --retry-connrefused -w 5 --random-wait https://queue.taskcluster.net/v1/task/$TC_PARENT_TASK_ID/artifacts/public/build/dist.7z -O dist.7z
+7z x dist.7z
+
+# Run tests.
+cd nss/tests && ./all.sh
new file mode 100644
--- /dev/null
+++ b/automation/taskcluster/windows/setup.sh
@@ -0,0 +1,30 @@
+#!/usr/bin/env bash
+
+set -v -e -x
+
+# Usage: hg_clone repo dir [revision=@]
+hg_clone() {
+    repo=$1
+    dir=$2
+    rev=${3:-@}
+    for i in 0 2 5; do
+        sleep $i
+        hg clone -r "$rev" "$repo" "$dir" && return
+        rm -rf "$dir"
+    done
+    exit 1
+}
+
+hg_clone https://hg.mozilla.org/build/tools tools default
+
+tools/scripts/tooltool/tooltool_wrapper.sh $(dirname $0)/releng.manifest https://api.pub.build.mozilla.org/tooltool/ non-existant-file.sh /c/mozilla-build/python/python.exe /c/builds/tooltool.py --authentication-file /c/builds/relengapi.tok -c /c/builds/tooltool_cache
+VSPATH="$(pwd)/vs2015u2"
+
+export WINDOWSSDKDIR="${VSPATH}/SDK"
+export WIN32_REDIST_DIR="${VSPATH}/VC/redist/x64/Microsoft.VC140.CRT"
+export WIN_UCRT_REDIST_DIR="${VSPATH}/SDK/Redist/ucrt/DLLs/x64"
+
+export PATH="${VSPATH}/VC/bin/amd64:${VSPATH}/VC/bin:${VSPATH}/SDK/bin/x64:${VSPATH}/VC/redist/x64/Microsoft.VC140.CRT:${VSPATH}/SDK/Redist/ucrt/DLLs/x64:${PATH}"
+
+export INCLUDE="${VSPATH}/VC/include:${VSPATH}/SDK/Include/10.0.10586.0/ucrt:${VSPATH}/SDK/Include/10.0.10586.0/shared:${VSPATH}/SDK/Include/10.0.10586.0/um"
+export LIB="${VSPATH}/VC/lib/amd64:${VSPATH}/SDK/lib/10.0.10586.0/ucrt/x64:${VSPATH}/SDK/lib/10.0.10586.0/um/x64"
new file mode 100755
--- /dev/null
+++ b/automation/travis/validate-formatting.sh
@@ -0,0 +1,18 @@
+#!/bin/bash
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+# Apply clang-format 3.8 on the provided folder and verify that this doesn't change any file.
+# If any file differs after formatting, the script eventually exits with 1.
+# Any differences between formatted and unformatted files is printed to stdout to give a hint what's wrong.
+
+STATUS=0
+for i in $(find $1 -type f -name '*.[ch]' -print); do
+  if ! clang-format-3.8 $i | diff $i -; then
+    echo "Sorry, $i is not formatted properly. Please use clang-format 3.8 on your patch before landing."
+    STATUS=1
+  fi
+done
+exit $STATUS
deleted file mode 100644
--- a/circle.yml
+++ /dev/null
@@ -1,18 +0,0 @@
-checkout:
-    post:
-        - cd ..; hg clone https://hg.mozilla.org/projects/nspr
-
-test:
-    override:
-        - make nss_build_all
-        - cd tests; NSS_TESTS=ssl_gtests NSS_CYCLES=standard ./all.sh
-
-machine:
-    environment:
-        { USE_64: 1,
-          NSS_ENABLE_TLS_1_3: 1,
-          NSS_BUILD_GTESTS: 1,
-        }
-    hosts:
-
-
--- a/cmd/Makefile
+++ b/cmd/Makefile
@@ -11,20 +11,24 @@ include manifest.mn
 include $(CORE_DEPTH)/coreconf/config.mk
 
 ifdef BUILD_LIBPKIX_TESTS
 DIRS += libpkix
 endif
 
 ifeq ($(NSS_BUILD_WITHOUT_SOFTOKEN),1)
 BLTEST_SRCDIR =
+ECPERF_SRCDIR =
+ECTEST_SRCDIR =
 FIPSTEST_SRCDIR =
 SHLIBSIGN_SRCDIR =
 else
 BLTEST_SRCDIR = bltest
+ECPERF_SRCDIR = ecperf
+ECTEST_SRCDIR = ectest
 FIPSTEST_SRCDIR = fipstest
 SHLIBSIGN_SRCDIR = shlibsign
 endif
 
 LOWHASHTEST_SRCDIR=
 ifeq ($(FREEBL_LOWHASH),1)
 LOWHASHTEST_SRCDIR = lowhashtest  # Add the lowhashtest directory to DIRS.
 endif
--- a/cmd/addbuiltin/addbuiltin.c
+++ b/cmd/addbuiltin/addbuiltin.c
@@ -13,148 +13,152 @@
 #include "secutil.h"
 #include "pk11func.h"
 
 #if defined(WIN32)
 #include <fcntl.h>
 #include <io.h>
 #endif
 
-void dumpbytes(unsigned char *buf, int len)
+void
+dumpbytes(unsigned char *buf, int len)
 {
     int i;
-    for (i=0; i < len; i++) {
-	if ((i !=0) && ((i & 0xf) == 0)) {
-	    printf("\n");
-	}
-	printf("\\%03o",buf[i]);
+    for (i = 0; i < len; i++) {
+        if ((i != 0) && ((i & 0xf) == 0)) {
+            printf("\n");
+        }
+        printf("\\%03o", buf[i]);
     }
     printf("\n");
 }
 
-char *getTrustString(unsigned int trust)
+char *
+getTrustString(unsigned int trust)
 {
     if (trust & CERTDB_TRUSTED) {
-	if (trust & CERTDB_TRUSTED_CA) {
-		return "CKT_NSS_TRUSTED_DELEGATOR";
-	} else {
-		return "CKT_NSS_TRUSTED";
-	}
+        if (trust & CERTDB_TRUSTED_CA) {
+            return "CKT_NSS_TRUSTED_DELEGATOR";
+        } else {
+            return "CKT_NSS_TRUSTED";
+        }
     } else {
-	if (trust & CERTDB_TRUSTED_CA) {
-		return "CKT_NSS_TRUSTED_DELEGATOR";
-	} else if (trust & CERTDB_VALID_CA) {
-		return "CKT_NSS_VALID_DELEGATOR";
-	} else if (trust & CERTDB_TERMINAL_RECORD) {
-		return "CKT_NSS_NOT_TRUSTED";
-	} else {
-		return "CKT_NSS_MUST_VERIFY_TRUST";
-	}
+        if (trust & CERTDB_TRUSTED_CA) {
+            return "CKT_NSS_TRUSTED_DELEGATOR";
+        } else if (trust & CERTDB_VALID_CA) {
+            return "CKT_NSS_VALID_DELEGATOR";
+        } else if (trust & CERTDB_TERMINAL_RECORD) {
+            return "CKT_NSS_NOT_TRUSTED";
+        } else {
+            return "CKT_NSS_MUST_VERIFY_TRUST";
+        }
     }
     return "CKT_NSS_TRUST_UNKNOWN"; /* not reached */
 }
 
 static const SEC_ASN1Template serialTemplate[] = {
-    { SEC_ASN1_INTEGER, offsetof(CERTCertificate,serialNumber) },
+    { SEC_ASN1_INTEGER, offsetof(CERTCertificate, serialNumber) },
     { 0 }
 };
 
-void print_crl_info(CERTName *name, SECItem *serial)
+void
+print_crl_info(CERTName *name, SECItem *serial)
 {
     PRBool saveWrapeState = SECU_GetWrapEnabled();
     SECU_EnableWrap(PR_FALSE);
 
     SECU_PrintNameQuotesOptional(stdout, name, "# Issuer", 0, PR_FALSE);
     printf("\n");
-    
+
     SECU_PrintInteger(stdout, serial, "# Serial Number", 0);
 
     SECU_EnableWrap(saveWrapeState);
 }
 
 static SECStatus
 ConvertCRLEntry(SECItem *sdder, PRInt32 crlentry, char *nickname)
 {
     int rv;
     PLArenaPool *arena = NULL;
     CERTSignedCrl *newCrl = NULL;
     CERTCrlEntry *entry;
-    
+
     CERTName *name = NULL;
     SECItem *derName = NULL;
     SECItem *serial = NULL;
-    
+
     rv = SEC_ERROR_NO_MEMORY;
     arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
     if (!arena)
-    	return rv;
+        return rv;
 
     newCrl = CERT_DecodeDERCrlWithFlags(arena, sdder, SEC_CRL_TYPE,
-					CRL_DECODE_DEFAULT_OPTIONS);
+                                        CRL_DECODE_DEFAULT_OPTIONS);
     if (!newCrl)
-    	return SECFailure;
-    
+        return SECFailure;
+
     name = &newCrl->crl.name;
     derName = &newCrl->crl.derName;
-    
+
     if (newCrl->crl.entries != NULL) {
-	PRInt32 iv = 0;
-	while ((entry = newCrl->crl.entries[iv++]) != NULL) {
-	    if (crlentry == iv) {
-		serial = &entry->serialNumber;
-		break;
-	    }
-	}
+        PRInt32 iv = 0;
+        while ((entry = newCrl->crl.entries[iv++]) != NULL) {
+            if (crlentry == iv) {
+                serial = &entry->serialNumber;
+                break;
+            }
+        }
     }
-    
+
     if (!name || !derName || !serial)
-    	return SECFailure;
-    
-    printf("\n# Distrust \"%s\"\n",nickname);
+        return SECFailure;
+
+    printf("\n# Distrust \"%s\"\n", nickname);
     print_crl_info(name, serial);
 
     printf("CKA_CLASS CK_OBJECT_CLASS CKO_NSS_TRUST\n");
     printf("CKA_TOKEN CK_BBOOL CK_TRUE\n");
     printf("CKA_PRIVATE CK_BBOOL CK_FALSE\n");
     printf("CKA_MODIFIABLE CK_BBOOL CK_FALSE\n");
-    printf("CKA_LABEL UTF8 \"%s\"\n",nickname);
-    
+    printf("CKA_LABEL UTF8 \"%s\"\n", nickname);
+
     printf("CKA_ISSUER MULTILINE_OCTAL\n");
-    dumpbytes(derName->data,derName->len);
+    dumpbytes(derName->data, derName->len);
     printf("END\n");
     printf("CKA_SERIAL_NUMBER MULTILINE_OCTAL\n");
     printf("\\002\\%03o", serial->len); /* 002: type integer; len >=3 digits */
-    dumpbytes(serial->data,serial->len);
+    dumpbytes(serial->data, serial->len);
     printf("END\n");
-    
+
     printf("CKA_TRUST_SERVER_AUTH CK_TRUST CKT_NSS_NOT_TRUSTED\n");
     printf("CKA_TRUST_EMAIL_PROTECTION CK_TRUST CKT_NSS_NOT_TRUSTED\n");
     printf("CKA_TRUST_CODE_SIGNING CK_TRUST CKT_NSS_NOT_TRUSTED\n");
     printf("CKA_TRUST_STEP_UP_APPROVED CK_BBOOL CK_FALSE\n");
 
-    PORT_FreeArena (arena, PR_FALSE);
+    PORT_FreeArena(arena, PR_FALSE);
     return rv;
 }
 
-void print_info(SECItem *sdder, CERTCertificate *c)
+void
+print_info(SECItem *sdder, CERTCertificate *c)
 {
     PRBool saveWrapeState = SECU_GetWrapEnabled();
     SECU_EnableWrap(PR_FALSE);
 
     SECU_PrintNameQuotesOptional(stdout, &c->issuer, "# Issuer", 0, PR_FALSE);
     printf("\n");
-    
+
     SECU_PrintInteger(stdout, &c->serialNumber, "# Serial Number", 0);
 
     SECU_PrintNameQuotesOptional(stdout, &c->subject, "# Subject", 0, PR_FALSE);
     printf("\n");
 
     SECU_PrintTimeChoice(stdout, &c->validity.notBefore, "# Not Valid Before", 0);
-    SECU_PrintTimeChoice(stdout, &c->validity.notAfter,  "# Not Valid After ", 0);
-    
+    SECU_PrintTimeChoice(stdout, &c->validity.notAfter, "# Not Valid After ", 0);
+
     SECU_PrintFingerprints(stdout, sdder, "# Fingerprint", 0);
 
     SECU_EnableWrap(saveWrapeState);
 }
 
 static SECStatus
 ConvertCertificate(SECItem *sdder, char *nickname, CERTCertTrust *trust,
                    PRBool excludeCert, PRBool excludeHash)
@@ -164,200 +168,199 @@ ConvertCertificate(SECItem *sdder, char 
     unsigned char sha1_hash[SHA1_LENGTH];
     unsigned char md5_hash[MD5_LENGTH];
     SECItem *serial = NULL;
     PRBool step_up = PR_FALSE;
     const char *trust_info;
 
     cert = CERT_DecodeDERCertificate(sdder, PR_FALSE, nickname);
     if (!cert) {
-	return SECFailure;
+        return SECFailure;
     }
-    serial = SEC_ASN1EncodeItem(NULL,NULL,cert,serialTemplate);
+    serial = SEC_ASN1EncodeItem(NULL, NULL, cert, serialTemplate);
     if (!serial) {
-	return SECFailure;
+        return SECFailure;
     }
-    
+
     if (!excludeCert) {
-	printf("\n#\n# Certificate \"%s\"\n#\n",nickname);
-	print_info(sdder, cert);
-	printf("CKA_CLASS CK_OBJECT_CLASS CKO_CERTIFICATE\n");
-	printf("CKA_TOKEN CK_BBOOL CK_TRUE\n");
-	printf("CKA_PRIVATE CK_BBOOL CK_FALSE\n");
-	printf("CKA_MODIFIABLE CK_BBOOL CK_FALSE\n");
-	printf("CKA_LABEL UTF8 \"%s\"\n",nickname);
-	printf("CKA_CERTIFICATE_TYPE CK_CERTIFICATE_TYPE CKC_X_509\n");
-	printf("CKA_SUBJECT MULTILINE_OCTAL\n");
-	dumpbytes(cert->derSubject.data,cert->derSubject.len);
-	printf("END\n");
-	printf("CKA_ID UTF8 \"0\"\n");
-	printf("CKA_ISSUER MULTILINE_OCTAL\n");
-	dumpbytes(cert->derIssuer.data,cert->derIssuer.len);
-	printf("END\n");
-	printf("CKA_SERIAL_NUMBER MULTILINE_OCTAL\n");
-	dumpbytes(serial->data,serial->len);
-	printf("END\n");
-	printf("CKA_VALUE MULTILINE_OCTAL\n");
-	dumpbytes(sdder->data,sdder->len);
-	printf("END\n");
+        printf("\n#\n# Certificate \"%s\"\n#\n", nickname);
+        print_info(sdder, cert);
+        printf("CKA_CLASS CK_OBJECT_CLASS CKO_CERTIFICATE\n");
+        printf("CKA_TOKEN CK_BBOOL CK_TRUE\n");
+        printf("CKA_PRIVATE CK_BBOOL CK_FALSE\n");
+        printf("CKA_MODIFIABLE CK_BBOOL CK_FALSE\n");
+        printf("CKA_LABEL UTF8 \"%s\"\n", nickname);
+        printf("CKA_CERTIFICATE_TYPE CK_CERTIFICATE_TYPE CKC_X_509\n");
+        printf("CKA_SUBJECT MULTILINE_OCTAL\n");
+        dumpbytes(cert->derSubject.data, cert->derSubject.len);
+        printf("END\n");
+        printf("CKA_ID UTF8 \"0\"\n");
+        printf("CKA_ISSUER MULTILINE_OCTAL\n");
+        dumpbytes(cert->derIssuer.data, cert->derIssuer.len);
+        printf("END\n");
+        printf("CKA_SERIAL_NUMBER MULTILINE_OCTAL\n");
+        dumpbytes(serial->data, serial->len);
+        printf("END\n");
+        printf("CKA_VALUE MULTILINE_OCTAL\n");
+        dumpbytes(sdder->data, sdder->len);
+        printf("END\n");
     }
-    
-    if ((trust->sslFlags | trust->emailFlags | trust->objectSigningFlags) 
-         == CERTDB_TERMINAL_RECORD)
-      trust_info = "Distrust";
+
+    if ((trust->sslFlags | trust->emailFlags | trust->objectSigningFlags) ==
+        CERTDB_TERMINAL_RECORD)
+        trust_info = "Distrust";
     else
-      trust_info = "Trust for";
-    
+        trust_info = "Trust for";
+
     printf("\n# %s \"%s\"\n", trust_info, nickname);
     print_info(sdder, cert);
 
     printf("CKA_CLASS CK_OBJECT_CLASS CKO_NSS_TRUST\n");
     printf("CKA_TOKEN CK_BBOOL CK_TRUE\n");
     printf("CKA_PRIVATE CK_BBOOL CK_FALSE\n");
     printf("CKA_MODIFIABLE CK_BBOOL CK_FALSE\n");
-    printf("CKA_LABEL UTF8 \"%s\"\n",nickname);
-    
+    printf("CKA_LABEL UTF8 \"%s\"\n", nickname);
+
     if (!excludeHash) {
-	PK11_HashBuf(SEC_OID_SHA1, sha1_hash, sdder->data, sdder->len);
-	printf("CKA_CERT_SHA1_HASH MULTILINE_OCTAL\n");
-	dumpbytes(sha1_hash,SHA1_LENGTH);
-	printf("END\n");
-	PK11_HashBuf(SEC_OID_MD5, md5_hash, sdder->data, sdder->len);
-	printf("CKA_CERT_MD5_HASH MULTILINE_OCTAL\n");
-	dumpbytes(md5_hash,MD5_LENGTH);
-	printf("END\n");
+        PK11_HashBuf(SEC_OID_SHA1, sha1_hash, sdder->data, sdder->len);
+        printf("CKA_CERT_SHA1_HASH MULTILINE_OCTAL\n");
+        dumpbytes(sha1_hash, SHA1_LENGTH);
+        printf("END\n");
+        PK11_HashBuf(SEC_OID_MD5, md5_hash, sdder->data, sdder->len);
+        printf("CKA_CERT_MD5_HASH MULTILINE_OCTAL\n");
+        dumpbytes(md5_hash, MD5_LENGTH);
+        printf("END\n");
     }
 
     printf("CKA_ISSUER MULTILINE_OCTAL\n");
-    dumpbytes(cert->derIssuer.data,cert->derIssuer.len);
+    dumpbytes(cert->derIssuer.data, cert->derIssuer.len);
     printf("END\n");
     printf("CKA_SERIAL_NUMBER MULTILINE_OCTAL\n");
-    dumpbytes(serial->data,serial->len);
+    dumpbytes(serial->data, serial->len);
     printf("END\n");
-    
+
     printf("CKA_TRUST_SERVER_AUTH CK_TRUST %s\n",
-				getTrustString(trust->sslFlags));
+           getTrustString(trust->sslFlags));
     printf("CKA_TRUST_EMAIL_PROTECTION CK_TRUST %s\n",
-				getTrustString(trust->emailFlags));
+           getTrustString(trust->emailFlags));
     printf("CKA_TRUST_CODE_SIGNING CK_TRUST %s\n",
-				getTrustString(trust->objectSigningFlags));
+           getTrustString(trust->objectSigningFlags));
 #ifdef notdef
     printf("CKA_TRUST_CLIENT_AUTH CK_TRUST CKT_NSS_TRUSTED\n");
     printf("CKA_TRUST_DIGITAL_SIGNATURE CK_TRUST CKT_NSS_TRUSTED_DELEGATOR\n");
     printf("CKA_TRUST_NON_REPUDIATION CK_TRUST CKT_NSS_TRUSTED_DELEGATOR\n");
     printf("CKA_TRUST_KEY_ENCIPHERMENT CK_TRUST CKT_NSS_TRUSTED_DELEGATOR\n");
     printf("CKA_TRUST_DATA_ENCIPHERMENT CK_TRUST CKT_NSS_TRUSTED_DELEGATOR\n");
     printf("CKA_TRUST_KEY_AGREEMENT CK_TRUST CKT_NSS_TRUSTED_DELEGATOR\n");
     printf("CKA_TRUST_KEY_CERT_SIGN CK_TRUST CKT_NSS_TRUSTED_DELEGATOR\n");
 #endif
-    
+
     step_up = (trust->sslFlags & CERTDB_GOVT_APPROVED_CA);
     printf("CKA_TRUST_STEP_UP_APPROVED CK_BBOOL %s\n",
-                step_up ? "CK_TRUE" : "CK_FALSE");
+           step_up ? "CK_TRUE" : "CK_FALSE");
 
     PORT_Free(sdder->data);
-    return(rv);
-
+    return (rv);
 }
 
-void printheader() {
+void
+printheader()
+{
     printf("# \n"
-"# This Source Code Form is subject to the terms of the Mozilla Public\n"
-"# License, v. 2.0. If a copy of the MPL was not distributed with this\n"
-"# file, You can obtain one at http://mozilla.org/MPL/2.0/.\n"
-     "#\n"
-     "CVS_ID \"@(#) $RCSfile$ $Revision$ $Date$\"\n"
-     "\n"
-     "#\n"
-     "# certdata.txt\n"
-     "#\n"
-     "# This file contains the object definitions for the certs and other\n"
-     "# information \"built into\" NSS.\n"
-     "#\n"
-     "# Object definitions:\n"
-     "#\n"
-     "#    Certificates\n"
-     "#\n"
-     "#  -- Attribute --          -- type --              -- value --\n"
-     "#  CKA_CLASS                CK_OBJECT_CLASS         CKO_CERTIFICATE\n"
-     "#  CKA_TOKEN                CK_BBOOL                CK_TRUE\n"
-     "#  CKA_PRIVATE              CK_BBOOL                CK_FALSE\n"
-     "#  CKA_MODIFIABLE           CK_BBOOL                CK_FALSE\n"
-     "#  CKA_LABEL                UTF8                    (varies)\n"
-     "#  CKA_CERTIFICATE_TYPE     CK_CERTIFICATE_TYPE     CKC_X_509\n"
-     "#  CKA_SUBJECT              DER+base64              (varies)\n"
-     "#  CKA_ID                   byte array              (varies)\n"
-     "#  CKA_ISSUER               DER+base64              (varies)\n"
-     "#  CKA_SERIAL_NUMBER        DER+base64              (varies)\n"
-     "#  CKA_VALUE                DER+base64              (varies)\n"
-     "#  CKA_NSS_EMAIL            ASCII7                  (unused here)\n"
-     "#\n"
-     "#    Trust\n"
-     "#\n"
-     "#  -- Attribute --              -- type --          -- value --\n"
-     "#  CKA_CLASS                    CK_OBJECT_CLASS     CKO_TRUST\n"
-     "#  CKA_TOKEN                    CK_BBOOL            CK_TRUE\n"
-     "#  CKA_PRIVATE                  CK_BBOOL            CK_FALSE\n"
-     "#  CKA_MODIFIABLE               CK_BBOOL            CK_FALSE\n"
-     "#  CKA_LABEL                    UTF8                (varies)\n"
-     "#  CKA_ISSUER                   DER+base64          (varies)\n"
-     "#  CKA_SERIAL_NUMBER            DER+base64          (varies)\n"
-     "#  CKA_CERT_HASH                binary+base64       (varies)\n"
-     "#  CKA_EXPIRES                  CK_DATE             (not used here)\n"
-     "#  CKA_TRUST_DIGITAL_SIGNATURE  CK_TRUST            (varies)\n"
-     "#  CKA_TRUST_NON_REPUDIATION    CK_TRUST            (varies)\n"
-     "#  CKA_TRUST_KEY_ENCIPHERMENT   CK_TRUST            (varies)\n"
-     "#  CKA_TRUST_DATA_ENCIPHERMENT  CK_TRUST            (varies)\n"
-     "#  CKA_TRUST_KEY_AGREEMENT      CK_TRUST            (varies)\n"
-     "#  CKA_TRUST_KEY_CERT_SIGN      CK_TRUST            (varies)\n"
-     "#  CKA_TRUST_CRL_SIGN           CK_TRUST            (varies)\n"
-     "#  CKA_TRUST_SERVER_AUTH        CK_TRUST            (varies)\n"
-     "#  CKA_TRUST_CLIENT_AUTH        CK_TRUST            (varies)\n"
-     "#  CKA_TRUST_CODE_SIGNING       CK_TRUST            (varies)\n"
-     "#  CKA_TRUST_EMAIL_PROTECTION   CK_TRUST            (varies)\n"
-     "#  CKA_TRUST_IPSEC_END_SYSTEM   CK_TRUST            (varies)\n"
-     "#  CKA_TRUST_IPSEC_TUNNEL       CK_TRUST            (varies)\n"
-     "#  CKA_TRUST_IPSEC_USER         CK_TRUST            (varies)\n"
-     "#  CKA_TRUST_TIME_STAMPING      CK_TRUST            (varies)\n"
-     "#  (other trust attributes can be defined)\n"
-     "#\n"
-     "\n"
-     "#\n"
-     "# The object to tell NSS that this is a root list and we don't\n"
-     "# have to go looking for others.\n"
-     "#\n"
-     "BEGINDATA\n"
-     "CKA_CLASS CK_OBJECT_CLASS CKO_NSS_BUILTIN_ROOT_LIST\n"
-     "CKA_TOKEN CK_BBOOL CK_TRUE\n"
-     "CKA_PRIVATE CK_BBOOL CK_FALSE\n"
-     "CKA_MODIFIABLE CK_BBOOL CK_FALSE\n"
-     "CKA_LABEL UTF8 \"Mozilla Builtin Roots\"\n");
+           "# This Source Code Form is subject to the terms of the Mozilla Public\n"
+           "# License, v. 2.0. If a copy of the MPL was not distributed with this\n"
+           "# file, You can obtain one at http://mozilla.org/MPL/2.0/.\n"
+           "#\n"
+           "# certdata.txt\n"
+           "#\n"
+           "# This file contains the object definitions for the certs and other\n"
+           "# information \"built into\" NSS.\n"
+           "#\n"
+           "# Object definitions:\n"
+           "#\n"
+           "#    Certificates\n"
+           "#\n"
+           "#  -- Attribute --          -- type --              -- value --\n"
+           "#  CKA_CLASS                CK_OBJECT_CLASS         CKO_CERTIFICATE\n"
+           "#  CKA_TOKEN                CK_BBOOL                CK_TRUE\n"
+           "#  CKA_PRIVATE              CK_BBOOL                CK_FALSE\n"
+           "#  CKA_MODIFIABLE           CK_BBOOL                CK_FALSE\n"
+           "#  CKA_LABEL                UTF8                    (varies)\n"
+           "#  CKA_CERTIFICATE_TYPE     CK_CERTIFICATE_TYPE     CKC_X_509\n"
+           "#  CKA_SUBJECT              DER+base64              (varies)\n"
+           "#  CKA_ID                   byte array              (varies)\n"
+           "#  CKA_ISSUER               DER+base64              (varies)\n"
+           "#  CKA_SERIAL_NUMBER        DER+base64              (varies)\n"
+           "#  CKA_VALUE                DER+base64              (varies)\n"
+           "#  CKA_NSS_EMAIL            ASCII7                  (unused here)\n"
+           "#\n"
+           "#    Trust\n"
+           "#\n"
+           "#  -- Attribute --              -- type --          -- value --\n"
+           "#  CKA_CLASS                    CK_OBJECT_CLASS     CKO_TRUST\n"
+           "#  CKA_TOKEN                    CK_BBOOL            CK_TRUE\n"
+           "#  CKA_PRIVATE                  CK_BBOOL            CK_FALSE\n"
+           "#  CKA_MODIFIABLE               CK_BBOOL            CK_FALSE\n"
+           "#  CKA_LABEL                    UTF8                (varies)\n"
+           "#  CKA_ISSUER                   DER+base64          (varies)\n"
+           "#  CKA_SERIAL_NUMBER            DER+base64          (varies)\n"
+           "#  CKA_CERT_HASH                binary+base64       (varies)\n"
+           "#  CKA_EXPIRES                  CK_DATE             (not used here)\n"
+           "#  CKA_TRUST_DIGITAL_SIGNATURE  CK_TRUST            (varies)\n"
+           "#  CKA_TRUST_NON_REPUDIATION    CK_TRUST            (varies)\n"
+           "#  CKA_TRUST_KEY_ENCIPHERMENT   CK_TRUST            (varies)\n"
+           "#  CKA_TRUST_DATA_ENCIPHERMENT  CK_TRUST            (varies)\n"
+           "#  CKA_TRUST_KEY_AGREEMENT      CK_TRUST            (varies)\n"
+           "#  CKA_TRUST_KEY_CERT_SIGN      CK_TRUST            (varies)\n"
+           "#  CKA_TRUST_CRL_SIGN           CK_TRUST            (varies)\n"
+           "#  CKA_TRUST_SERVER_AUTH        CK_TRUST            (varies)\n"
+           "#  CKA_TRUST_CLIENT_AUTH        CK_TRUST            (varies)\n"
+           "#  CKA_TRUST_CODE_SIGNING       CK_TRUST            (varies)\n"
+           "#  CKA_TRUST_EMAIL_PROTECTION   CK_TRUST            (varies)\n"
+           "#  CKA_TRUST_IPSEC_END_SYSTEM   CK_TRUST            (varies)\n"
+           "#  CKA_TRUST_IPSEC_TUNNEL       CK_TRUST            (varies)\n"
+           "#  CKA_TRUST_IPSEC_USER         CK_TRUST            (varies)\n"
+           "#  CKA_TRUST_TIME_STAMPING      CK_TRUST            (varies)\n"
+           "#  (other trust attributes can be defined)\n"
+           "#\n"
+           "\n"
+           "#\n"
+           "# The object to tell NSS that this is a root list and we don't\n"
+           "# have to go looking for others.\n"
+           "#\n"
+           "BEGINDATA\n"
+           "CKA_CLASS CK_OBJECT_CLASS CKO_NSS_BUILTIN_ROOT_LIST\n"
+           "CKA_TOKEN CK_BBOOL CK_TRUE\n"
+           "CKA_PRIVATE CK_BBOOL CK_FALSE\n"
+           "CKA_MODIFIABLE CK_BBOOL CK_FALSE\n"
+           "CKA_LABEL UTF8 \"Mozilla Builtin Roots\"\n");
 }
 
-static void Usage(char *progName)
+static void
+Usage(char *progName)
 {
     fprintf(stderr, "%s -t trust -n nickname [-i certfile] [-c] [-h]\n", progName);
-    fprintf(stderr, 
+    fprintf(stderr,
             "\tRead a der-encoded cert from certfile or stdin, and output\n"
             "\tit to stdout in a format suitable for the builtin root module.\n"
             "\tExample: %s -n MyCA -t \"C,C,C\" -i myca.der >> certdata.txt\n",
             progName);
     fprintf(stderr, "%s -D -n label [-i certfile]\n", progName);
-    fprintf(stderr, 
+    fprintf(stderr,
             "\tRead a der-encoded cert from certfile or stdin, and output\n"
             "\ta distrust record.\n"
-	    "\t(-D is equivalent to -t p,p,p -c -h)\n");
+            "\t(-D is equivalent to -t p,p,p -c -h)\n");
     fprintf(stderr, "%s -C -e crl-entry-number -n label [-i crlfile]\n", progName);
-    fprintf(stderr, 
+    fprintf(stderr,
             "\tRead a CRL from crlfile or stdin, and output\n"
             "\ta distrust record (issuer+serial).\n"
-	    "\t(-C implies -c -h)\n");
+            "\t(-C implies -c -h)\n");
     fprintf(stderr, "%-15s trust flags (cCTpPuw).\n", "-t trust");
-    fprintf(stderr, "%-15s nickname to assign to builtin cert, or\n", 
-                    "-n nickname");
+    fprintf(stderr, "%-15s nickname to assign to builtin cert, or\n",
+            "-n nickname");
     fprintf(stderr, "%-15s a label for the distrust record.\n", "");
     fprintf(stderr, "%-15s exclude the certificate (only add a trust record)\n", "-c");
     fprintf(stderr, "%-15s exclude hash from trust record\n", "-h");
     fprintf(stderr, "%-15s     (useful to distrust any matching issuer/serial)\n", "");
     fprintf(stderr, "%-15s     (not allowed when adding positive trust)\n", "");
     fprintf(stderr, "%-15s a CRL entry number, as shown by \"crlutil -S\"\n", "-e");
     fprintf(stderr, "%-15s input file to read (default stdin)\n", "-i file");
     fprintf(stderr, "%-15s     (pipe through atob if the cert is b64-encoded)\n", "");
@@ -371,175 +374,173 @@ enum {
     opt_Distrust,
     opt_ExcludeCert,
     opt_ExcludeHash,
     opt_DistrustCRL,
     opt_CRLEnry
 };
 
 static secuCommandFlag addbuiltin_options[] =
-{
-	{ /* opt_Input         */  'i', PR_TRUE,  0, PR_FALSE },
-	{ /* opt_Nickname      */  'n', PR_TRUE,  0, PR_FALSE },
-	{ /* opt_Trust         */  't', PR_TRUE,  0, PR_FALSE },
-        { /* opt_Distrust      */  'D', PR_FALSE, 0, PR_FALSE },
-        { /* opt_ExcludeCert   */  'c', PR_FALSE, 0, PR_FALSE },
-        { /* opt_ExcludeHash   */  'h', PR_FALSE, 0, PR_FALSE },
-        { /* opt_DistrustCRL   */  'C', PR_FALSE, 0, PR_FALSE },
-        { /* opt_CRLEnry       */  'e', PR_TRUE,  0, PR_FALSE },
-};
+    {
+      { /* opt_Input         */ 'i', PR_TRUE, 0, PR_FALSE },
+      { /* opt_Nickname      */ 'n', PR_TRUE, 0, PR_FALSE },
+      { /* opt_Trust         */ 't', PR_TRUE, 0, PR_FALSE },
+      { /* opt_Distrust      */ 'D', PR_FALSE, 0, PR_FALSE },
+      { /* opt_ExcludeCert   */ 'c', PR_FALSE, 0, PR_FALSE },
+      { /* opt_ExcludeHash   */ 'h', PR_FALSE, 0, PR_FALSE },
+      { /* opt_DistrustCRL   */ 'C', PR_FALSE, 0, PR_FALSE },
+      { /* opt_CRLEnry       */ 'e', PR_TRUE, 0, PR_FALSE },
+    };
 
-int main(int argc, char **argv)
+int
+main(int argc, char **argv)
 {
     SECStatus rv;
     char *nickname = NULL;
     char *trusts = NULL;
     char *progName;
     PRFileDesc *infile;
     CERTCertTrust trust = { 0 };
     SECItem derItem = { 0 };
     PRInt32 crlentry = 0;
     PRInt32 mutuallyExclusiveOpts = 0;
     PRBool decodeTrust = PR_FALSE;
 
     secuCommand addbuiltin = { 0 };
-    addbuiltin.numOptions = sizeof(addbuiltin_options)/sizeof(secuCommandFlag);
+    addbuiltin.numOptions = sizeof(addbuiltin_options) / sizeof(secuCommandFlag);
     addbuiltin.options = addbuiltin_options;
 
     progName = strrchr(argv[0], '/');
-    progName = progName ? progName+1 : argv[0];
+    progName = progName ? progName + 1 : argv[0];
 
     rv = SECU_ParseCommandLine(argc, argv, progName, &addbuiltin);
 
     if (rv != SECSuccess)
-	Usage(progName);
-    
+        Usage(progName);
+
     if (addbuiltin.options[opt_Trust].activated)
-      ++mutuallyExclusiveOpts;
+        ++mutuallyExclusiveOpts;
     if (addbuiltin.options[opt_Distrust].activated)
-      ++mutuallyExclusiveOpts;
+        ++mutuallyExclusiveOpts;
     if (addbuiltin.options[opt_DistrustCRL].activated)
-      ++mutuallyExclusiveOpts;
+        ++mutuallyExclusiveOpts;
 
     if (mutuallyExclusiveOpts != 1) {
         fprintf(stderr, "%s: you must specify exactly one of -t or -D or -C\n",
                 progName);
         Usage(progName);
     }
-    
+
     if (addbuiltin.options[opt_DistrustCRL].activated) {
-	if (!addbuiltin.options[opt_CRLEnry].activated) {
-	    fprintf(stderr, "%s: you must specify the CRL entry number.\n",
-		    progName);
-	    Usage(progName);
-	}
-	else {
-	    crlentry = atoi(addbuiltin.options[opt_CRLEnry].arg);
-	    if (crlentry < 1) {
-		fprintf(stderr, "%s: The CRL entry number must be > 0.\n",
-			progName);
-		Usage(progName);
-	    }
-	}
+        if (!addbuiltin.options[opt_CRLEnry].activated) {
+            fprintf(stderr, "%s: you must specify the CRL entry number.\n",
+                    progName);
+            Usage(progName);
+        } else {
+            crlentry = atoi(addbuiltin.options[opt_CRLEnry].arg);
+            if (crlentry < 1) {
+                fprintf(stderr, "%s: The CRL entry number must be > 0.\n",
+                        progName);
+                Usage(progName);
+            }
+        }
     }
 
     if (!addbuiltin.options[opt_Nickname].activated) {
         fprintf(stderr, "%s: you must specify parameter -n (a nickname or a label).\n",
                 progName);
         Usage(progName);
     }
 
     if (addbuiltin.options[opt_Input].activated) {
-	infile = PR_Open(addbuiltin.options[opt_Input].arg, PR_RDONLY, 00660);
-	if (!infile) {
-	    fprintf(stderr, "%s: failed to open input file.\n", progName);
-	    exit(1);
-	}
+        infile = PR_Open(addbuiltin.options[opt_Input].arg, PR_RDONLY, 00660);
+        if (!infile) {
+            fprintf(stderr, "%s: failed to open input file.\n", progName);
+            exit(1);
+        }
     } else {
 #if defined(WIN32)
-	/* If we're going to read binary data from stdin, we must put stdin
+        /* If we're going to read binary data from stdin, we must put stdin
 	** into O_BINARY mode or else incoming \r\n's will become \n's,
 	** and latin-1 characters will be altered.
 	*/
 
-	int smrv = _setmode(_fileno(stdin), _O_BINARY);
-	if (smrv == -1) {
-	    fprintf(stderr,
-	    "%s: Cannot change stdin to binary mode. Use -i option instead.\n",
-	            progName);
-	    exit(1);
-	}
+        int smrv = _setmode(_fileno(stdin), _O_BINARY);
+        if (smrv == -1) {
+            fprintf(stderr,
+                    "%s: Cannot change stdin to binary mode. Use -i option instead.\n",
+                    progName);
+            exit(1);
+        }
 #endif
-	infile = PR_STDIN;
+        infile = PR_STDIN;
     }
 
 #if defined(WIN32)
     /* We must put stdout into O_BINARY mode or else the output will include
     ** carriage returns.
     */
     {
-	int smrv = _setmode(_fileno(stdout), _O_BINARY);
-	if (smrv == -1) {
-	    fprintf(stderr, "%s: Cannot change stdout to binary mode.\n", progName);
-	    exit(1);
-	}
+        int smrv = _setmode(_fileno(stdout), _O_BINARY);
+        if (smrv == -1) {
+            fprintf(stderr, "%s: Cannot change stdout to binary mode.\n", progName);
+            exit(1);
+        }
     }
 #endif
 
     nickname = strdup(addbuiltin.options[opt_Nickname].arg);
-    
+
     NSS_NoDB_Init(NULL);
 
     if (addbuiltin.options[opt_Distrust].activated ||
         addbuiltin.options[opt_DistrustCRL].activated) {
-      addbuiltin.options[opt_ExcludeCert].activated = PR_TRUE;
-      addbuiltin.options[opt_ExcludeHash].activated = PR_TRUE;
+        addbuiltin.options[opt_ExcludeCert].activated = PR_TRUE;
+        addbuiltin.options[opt_ExcludeHash].activated = PR_TRUE;
     }
-    
+
     if (addbuiltin.options[opt_Distrust].activated) {
         trusts = strdup("p,p,p");
-	decodeTrust = PR_TRUE;
-    }
-    else if (addbuiltin.options[opt_Trust].activated) {
+        decodeTrust = PR_TRUE;
+    } else if (addbuiltin.options[opt_Trust].activated) {
         trusts = strdup(addbuiltin.options[opt_Trust].arg);
-	decodeTrust = PR_TRUE;
+        decodeTrust = PR_TRUE;
     }
-    
+
     if (decodeTrust) {
-	rv = CERT_DecodeTrustString(&trust, trusts);
-	if (rv) {
-	    fprintf(stderr, "%s: incorrectly formatted trust string.\n", progName);
-	    Usage(progName);
-	}
+        rv = CERT_DecodeTrustString(&trust, trusts);
+        if (rv) {
+            fprintf(stderr, "%s: incorrectly formatted trust string.\n", progName);
+            Usage(progName);
+        }
     }
-    
+
     if (addbuiltin.options[opt_Trust].activated &&
         addbuiltin.options[opt_ExcludeHash].activated) {
-	if ((trust.sslFlags | trust.emailFlags | trust.objectSigningFlags) 
-	    != CERTDB_TERMINAL_RECORD) {
-	    fprintf(stderr, "%s: Excluding the hash only allowed with distrust.\n", progName);
-	    Usage(progName);
-	}
+        if ((trust.sslFlags | trust.emailFlags | trust.objectSigningFlags) !=
+            CERTDB_TERMINAL_RECORD) {
+            fprintf(stderr, "%s: Excluding the hash only allowed with distrust.\n", progName);
+            Usage(progName);
+        }
     }
 
     SECU_FileToItem(&derItem, infile);
-    
+
     /*printheader();*/
-    
+
     if (addbuiltin.options[opt_DistrustCRL].activated) {
-	rv = ConvertCRLEntry(&derItem, crlentry, nickname);
+        rv = ConvertCRLEntry(&derItem, crlentry, nickname);
+    } else {
+        rv = ConvertCertificate(&derItem, nickname, &trust,
+                                addbuiltin.options[opt_ExcludeCert].activated,
+                                addbuiltin.options[opt_ExcludeHash].activated);
+        if (rv) {
+            fprintf(stderr, "%s: failed to convert certificate.\n", progName);
+            exit(1);
+        }
     }
-    else {
-	rv = ConvertCertificate(&derItem, nickname, &trust, 
-				addbuiltin.options[opt_ExcludeCert].activated,
-				addbuiltin.options[opt_ExcludeHash].activated);
-	if (rv) {
-	    fprintf(stderr, "%s: failed to convert certificate.\n", progName);
-	    exit(1);
-	}
-    }
-    
+
     if (NSS_Shutdown() != SECSuccess) {
         exit(1);
     }
 
-    return(SECSuccess);
+    return (SECSuccess);
 }
--- a/cmd/atob/atob.c
+++ b/cmd/atob/atob.c
@@ -4,167 +4,171 @@
 
 #include "plgetopt.h"
 #include "secutil.h"
 #include "nssb64.h"
 #include <errno.h>
 
 #if defined(XP_WIN) || (defined(__sun) && !defined(SVR4))
 #if !defined(WIN32)
-extern int fread(char *, size_t, size_t, FILE*);
-extern int fwrite(char *, size_t, size_t, FILE*);
+extern int fread(char *, size_t, size_t, FILE *);
+extern int fwrite(char *, size_t, size_t, FILE *);
 extern int fprintf(FILE *, char *, ...);
 #endif
 #endif
 
 #if defined(WIN32)
 #include "fcntl.h"
 #include "io.h"
 #endif
 
-static PRInt32 
-output_binary (void *arg, const unsigned char *obuf, PRInt32 size)
+static PRInt32
+output_binary(void *arg, const unsigned char *obuf, PRInt32 size)
 {
     FILE *outFile = arg;
     int nb;
 
     nb = fwrite(obuf, 1, size, outFile);
     if (nb != size) {
-	PORT_SetError(SEC_ERROR_IO);
-	return -1;
+        PORT_SetError(SEC_ERROR_IO);
+        return -1;
     }
 
     return nb;
 }
 
 static PRBool
 isBase64Char(char c)
 {
-    return ((c >= 'A' && c <= 'Z')
-	    || (c >= 'a' && c <= 'z')
-	    || (c >= '0' && c <= '9')
-	    || c == '+'
-	    || c == '/'
-	    || c == '=');
+    return ((c >= 'A' && c <= 'Z') ||
+            (c >= 'a' && c <= 'z') ||
+            (c >= '0' && c <= '9') ||
+            c == '+' || c == '/' ||
+            c == '=');
 }
 
 static SECStatus
 decode_file(FILE *outFile, FILE *inFile)
 {
     NSSBase64Decoder *cx;
     SECStatus status = SECFailure;
     char ibuf[4096];
     const char *ptr;
 
     cx = NSSBase64Decoder_Create(output_binary, outFile);
     if (!cx) {
-	return -1;
+        return -1;
     }
 
     for (;;) {
-	if (feof(inFile)) break;
-	if (!fgets(ibuf, sizeof(ibuf), inFile)) {
-	    if (ferror(inFile)) {
-		PORT_SetError(SEC_ERROR_IO);
-		goto loser;
-	    }
-	    /* eof */
-	    break;
-	}
-	for (ptr = ibuf; *ptr; ++ptr) {
-	    char c = *ptr;
-	    if (c == '\n' || c == '\r') {
-		break; /* found end of line */
-	    }
-	    if (!isBase64Char(c)) {
-	      ptr = ibuf; /* ignore line */
-	      break;
-	    }
-	}
-	if (ibuf == ptr) {
-	    continue; /* skip empty or non-base64 line */
-	}
+        if (feof(inFile))
+            break;
+        if (!fgets(ibuf, sizeof(ibuf), inFile)) {
+            if (ferror(inFile)) {
+                PORT_SetError(SEC_ERROR_IO);
+                goto loser;
+            }
+            /* eof */
+            break;
+        }
+        for (ptr = ibuf; *ptr; ++ptr) {
+            char c = *ptr;
+            if (c == '\n' || c == '\r') {
+                break; /* found end of line */
+            }
+            if (!isBase64Char(c)) {
+                ptr = ibuf; /* ignore line */
+                break;
+            }
+        }
+        if (ibuf == ptr) {
+            continue; /* skip empty or non-base64 line */
+        }
 
-	status = NSSBase64Decoder_Update(cx, ibuf, ptr-ibuf);
-	if (status != SECSuccess) goto loser;
+        status = NSSBase64Decoder_Update(cx, ibuf, ptr - ibuf);
+        if (status != SECSuccess)
+            goto loser;
     }
 
     return NSSBase64Decoder_Destroy(cx, PR_FALSE);
 
-  loser:
-    (void) NSSBase64Decoder_Destroy(cx, PR_TRUE);
+loser:
+    (void)NSSBase64Decoder_Destroy(cx, PR_TRUE);
     return status;
 }
 
-static void Usage(char *progName)
+static void
+Usage(char *progName)
 {
     fprintf(stderr,
-	    "Usage: %s [-i input] [-o output]\n",
-	    progName);
+            "Usage: %s [-i input] [-o output]\n",
+            progName);
     fprintf(stderr, "%-20s Define an input file to use (default is stdin)\n",
-	    "-i input");
+            "-i input");
     fprintf(stderr, "%-20s Define an output file to use (default is stdout)\n",
-	    "-o output");
+            "-o output");
     exit(-1);
 }
 
-int main(int argc, char **argv)
+int
+main(int argc, char **argv)
 {
     char *progName;
     SECStatus rv;
     FILE *inFile, *outFile;
     PLOptState *optstate;
     PLOptStatus status;
 
     inFile = 0;
     outFile = 0;
     progName = strrchr(argv[0], '/');
-    progName = progName ? progName+1 : argv[0];
+    progName = progName ? progName + 1 : argv[0];
 
     /* Parse command line arguments */
     optstate = PL_CreateOptState(argc, argv, "?hi:o:");
     while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
-	switch (optstate->option) {
-	  case '?':
-	  case 'h':
-	    Usage(progName);
-	    break;
+        switch (optstate->option) {
+            case '?':
+            case 'h':
+                Usage(progName);
+                break;
 
-	  case 'i':
-	    inFile = fopen(optstate->value, "r");
-	    if (!inFile) {
-		fprintf(stderr, "%s: unable to open \"%s\" for reading\n",
-			progName, optstate->value);
-		return -1;
-	    }
-	    break;
+            case 'i':
+                inFile = fopen(optstate->value, "r");
+                if (!inFile) {
+                    fprintf(stderr, "%s: unable to open \"%s\" for reading\n",
+                            progName, optstate->value);
+                    return -1;
+                }
+                break;
 
-	  case 'o':
-	    outFile = fopen(optstate->value, "wb");
-	    if (!outFile) {
-		fprintf(stderr, "%s: unable to open \"%s\" for writing\n",
-			progName, optstate->value);
-		return -1;
-	    }
-	    break;
-	}
+            case 'o':
+                outFile = fopen(optstate->value, "wb");
+                if (!outFile) {
+                    fprintf(stderr, "%s: unable to open \"%s\" for writing\n",
+                            progName, optstate->value);
+                    return -1;
+                }
+                break;
+        }
     }
-    if (!inFile) inFile = stdin;
+    if (!inFile)
+        inFile = stdin;
     if (!outFile) {
 #if defined(WIN32)
-	int smrv = _setmode(_fileno(stdout), _O_BINARY);
-	if (smrv == -1) {
-	    fprintf(stderr,
-	    "%s: Cannot change stdout to binary mode. Use -o option instead.\n",
-	            progName);
-	    return smrv;
-	}
+        int smrv = _setmode(_fileno(stdout), _O_BINARY);
+        if (smrv == -1) {
+            fprintf(stderr,
+                    "%s: Cannot change stdout to binary mode. Use -o option instead.\n",
+                    progName);
+            return smrv;
+        }
 #endif
-    	outFile = stdout;
+        outFile = stdout;
     }
     rv = decode_file(outFile, inFile);
     if (rv != SECSuccess) {
-	fprintf(stderr, "%s: lossage: error=%d errno=%d\n",
-		progName, PORT_GetError(), errno);
-	return -1;
+        fprintf(stderr, "%s: lossage: error=%d errno=%d\n",
+                progName, PORT_GetError(), errno);
+        return -1;
     }
     return 0;
 }
--- a/cmd/bltest/blapitest.c
+++ b/cmd/bltest/blapitest.c
@@ -18,390 +18,383 @@
 #include "softoken.h"
 #include "nspr.h"
 #include "secport.h"
 #include "secoid.h"
 #include "nssutil.h"
 
 #ifndef NSS_DISABLE_ECC
 #include "ecl-curve.h"
-SECStatus EC_DecodeParams(const SECItem *encodedParams, 
-	ECParams **ecparams);
+SECStatus EC_DecodeParams(const SECItem *encodedParams,
+                          ECParams **ecparams);
 SECStatus EC_CopyParams(PLArenaPool *arena, ECParams *dstParams,
-	      const ECParams *srcParams);
+                        const ECParams *srcParams);
 #endif
 
 char *progName;
 char *testdir = NULL;
 
 #define BLTEST_DEFAULT_CHUNKSIZE 4096
 
 #define WORDSIZE sizeof(unsigned long)
 
-#define CHECKERROR(rv, ln) \
-    if (rv) { \
-	PRErrorCode prerror = PR_GetError(); \
-	PR_fprintf(PR_STDERR, "%s: ERR %d (%s) at line %d.\n", progName, \
-	prerror, PORT_ErrorToString(prerror), ln); \
-	exit(-1); \
+#define CHECKERROR(rv, ln)                                               \
+    if (rv) {                                                            \
+        PRErrorCode prerror = PR_GetError();                             \
+        PR_fprintf(PR_STDERR, "%s: ERR %d (%s) at line %d.\n", progName, \
+                   prerror, PORT_ErrorToString(prerror), ln);            \
+        exit(-1);                                                        \
     }
 
 /* Macros for performance timing. */
 #define TIMESTART() \
     time1 = PR_IntervalNow();
 
-#define TIMEFINISH(time, reps) \
+#define TIMEFINISH(time, reps)                          \
     time2 = (PRIntervalTime)(PR_IntervalNow() - time1); \
-    time1 = PR_IntervalToMilliseconds(time2); \
-    time = ((double)(time1))/reps;
-
-#define TIMEMARK(seconds) \
-    time1 = PR_SecondsToInterval(seconds); \
-    { \
-        PRInt64 tmp; \
-        if (time2 == 0) { \
-            time2 = 1; \
-        } \
-        LL_DIV(tmp, time1, time2); \
-        if (tmp < 10) { \
-            if (tmp == 0) { \
-                opsBetweenChecks = 1; \
-            } else { \
+    time1 = PR_IntervalToMilliseconds(time2);           \
+    time = ((double)(time1)) / reps;
+
+#define TIMEMARK(seconds)                      \
+    time1 = PR_SecondsToInterval(seconds);     \
+    {                                          \
+        PRInt64 tmp;                           \
+        if (time2 == 0) {                      \
+            time2 = 1;                         \
+        }                                      \
+        LL_DIV(tmp, time1, time2);             \
+        if (tmp < 10) {                        \
+            if (tmp == 0) {                    \
+                opsBetweenChecks = 1;          \
+            } else {                           \
                 LL_L2I(opsBetweenChecks, tmp); \
-            } \
-        } else { \
-            opsBetweenChecks = 10; \
-        } \
-    } \
-    time2 = time1; \
+            }                                  \
+        } else {                               \
+            opsBetweenChecks = 10;             \
+        }                                      \
+    }                                          \
+    time2 = time1;                             \
     time1 = PR_IntervalNow();
 
 #define TIMETOFINISH() \
     PR_IntervalNow() - time1 >= time2
 
-static void Usage()
+static void
+Usage()
 {
 #define PRINTUSAGE(subject, option, predicate) \
     fprintf(stderr, "%10s %s\t%s\n", subject, option, predicate);
     fprintf(stderr, "\n");
     PRINTUSAGE(progName, "[-DEHSVR]", "List available cipher modes"); /* XXX */
     fprintf(stderr, "\n");
     PRINTUSAGE(progName, "-E -m mode ", "Encrypt a buffer");
-    PRINTUSAGE("",	"", "[-i plaintext] [-o ciphertext] [-k key] [-v iv]");
-    PRINTUSAGE("",	"", "[-b bufsize] [-g keysize] [-e exp] [-r rounds]");
-    PRINTUSAGE("",	"", "[-w wordsize] [-p repetitions | -5 time_interval]");
-    PRINTUSAGE("",	"", "[-4 th_num]");
-    PRINTUSAGE("",	"-m", "cipher mode to use");
-    PRINTUSAGE("",	"-i", "file which contains input buffer");
-    PRINTUSAGE("",	"-o", "file for output buffer");
-    PRINTUSAGE("",	"-k", "file which contains key");
-    PRINTUSAGE("",	"-v", "file which contains initialization vector");
-    PRINTUSAGE("",	"-b", "size of input buffer");
-    PRINTUSAGE("",	"-g", "key size (in bytes)");
-    PRINTUSAGE("",	"-p", "do performance test");
-    PRINTUSAGE("",	"-4", "run test in multithread mode. th_num number of parallel threads");
-    PRINTUSAGE("",	"-5", "run test for specified time interval(in seconds)");
-    PRINTUSAGE("",	"--aad", "File with contains additional auth data");
+    PRINTUSAGE("", "", "[-i plaintext] [-o ciphertext] [-k key] [-v iv]");
+    PRINTUSAGE("", "", "[-b bufsize] [-g keysize] [-e exp] [-r rounds]");
+    PRINTUSAGE("", "", "[-w wordsize] [-p repetitions | -5 time_interval]");
+    PRINTUSAGE("", "", "[-4 th_num]");
+    PRINTUSAGE("", "-m", "cipher mode to use");
+    PRINTUSAGE("", "-i", "file which contains input buffer");
+    PRINTUSAGE("", "-o", "file for output buffer");
+    PRINTUSAGE("", "-k", "file which contains key");
+    PRINTUSAGE("", "-v", "file which contains initialization vector");
+    PRINTUSAGE("", "-b", "size of input buffer");
+    PRINTUSAGE("", "-g", "key size (in bytes)");
+    PRINTUSAGE("", "-p", "do performance test");
+    PRINTUSAGE("", "-4", "run test in multithread mode. th_num number of parallel threads");
+    PRINTUSAGE("", "-5", "run test for specified time interval(in seconds)");
+    PRINTUSAGE("", "--aad", "File with contains additional auth data");
     PRINTUSAGE("(rsa)", "-e", "rsa public exponent");
     PRINTUSAGE("(rc5)", "-r", "number of rounds");
     PRINTUSAGE("(rc5)", "-w", "wordsize (32 or 64)");
     fprintf(stderr, "\n");
     PRINTUSAGE(progName, "-D -m mode", "Decrypt a buffer");
-    PRINTUSAGE("",	"", "[-i plaintext] [-o ciphertext] [-k key] [-v iv]");
-    PRINTUSAGE("",	"", "[-p repetitions | -5 time_interval] [-4 th_num]");
-    PRINTUSAGE("",	"-m", "cipher mode to use");
-    PRINTUSAGE("",	"-i", "file which contains input buffer");
-    PRINTUSAGE("",	"-o", "file for output buffer");
-    PRINTUSAGE("",	"-k", "file which contains key");
-    PRINTUSAGE("",	"-v", "file which contains initialization vector");
-    PRINTUSAGE("",	"-p", "do performance test");
-    PRINTUSAGE("",	"-4", "run test in multithread mode. th_num number of parallel threads");
-    PRINTUSAGE("",	"-5", "run test for specified time interval(in seconds)");
-    PRINTUSAGE("",	"--aad", "File with contains additional auth data");
+    PRINTUSAGE("", "", "[-i plaintext] [-o ciphertext] [-k key] [-v iv]");
+    PRINTUSAGE("", "", "[-p repetitions | -5 time_interval] [-4 th_num]");
+    PRINTUSAGE("", "-m", "cipher mode to use");
+    PRINTUSAGE("", "-i", "file which contains input buffer");
+    PRINTUSAGE("", "-o", "file for output buffer");
+    PRINTUSAGE("", "-k", "file which contains key");
+    PRINTUSAGE("", "-v", "file which contains initialization vector");
+    PRINTUSAGE("", "-p", "do performance test");
+    PRINTUSAGE("", "-4", "run test in multithread mode. th_num number of parallel threads");
+    PRINTUSAGE("", "-5", "run test for specified time interval(in seconds)");
+    PRINTUSAGE("", "--aad", "File with contains additional auth data");
     fprintf(stderr, "\n");
     PRINTUSAGE(progName, "-H -m mode", "Hash a buffer");
-    PRINTUSAGE("",	"", "[-i plaintext] [-o hash]");
-    PRINTUSAGE("",	"", "[-b bufsize]");
-    PRINTUSAGE("",	"", "[-p repetitions | -5 time_interval] [-4 th_num]");
-    PRINTUSAGE("",	"-m", "cipher mode to use");
-    PRINTUSAGE("",	"-i", "file which contains input buffer");
-    PRINTUSAGE("",	"-o", "file for hash");
-    PRINTUSAGE("",	"-b", "size of input buffer");
-    PRINTUSAGE("",	"-p", "do performance test");
-    PRINTUSAGE("",	"-4", "run test in multithread mode. th_num number of parallel threads");
-    PRINTUSAGE("",	"-5", "run test for specified time interval(in seconds)");
+    PRINTUSAGE("", "", "[-i plaintext] [-o hash]");
+    PRINTUSAGE("", "", "[-b bufsize]");
+    PRINTUSAGE("", "", "[-p repetitions | -5 time_interval] [-4 th_num]");
+    PRINTUSAGE("", "-m", "cipher mode to use");
+    PRINTUSAGE("", "-i", "file which contains input buffer");
+    PRINTUSAGE("", "-o", "file for hash");
+    PRINTUSAGE("", "-b", "size of input buffer");
+    PRINTUSAGE("", "-p", "do performance test");
+    PRINTUSAGE("", "-4", "run test in multithread mode. th_num number of parallel threads");
+    PRINTUSAGE("", "-5", "run test for specified time interval(in seconds)");
     fprintf(stderr, "\n");
     PRINTUSAGE(progName, "-S -m mode", "Sign a buffer");
-    PRINTUSAGE("",	"", "[-i plaintext] [-o signature] [-k key]");
-    PRINTUSAGE("",	"", "[-b bufsize]");
+    PRINTUSAGE("", "", "[-i plaintext] [-o signature] [-k key]");
+    PRINTUSAGE("", "", "[-b bufsize]");
 #ifndef NSS_DISABLE_ECC
-    PRINTUSAGE("",	"", "[-n curvename]");
+    PRINTUSAGE("", "", "[-n curvename]");
 #endif
-    PRINTUSAGE("",	"", "[-p repetitions | -5 time_interval] [-4 th_num]");
-    PRINTUSAGE("",	"-m", "cipher mode to use");
-    PRINTUSAGE("",	"-i", "file which contains input buffer");
-    PRINTUSAGE("",	"-o", "file for signature");
-    PRINTUSAGE("",	"-k", "file which contains key");
+    PRINTUSAGE("", "", "[-p repetitions | -5 time_interval] [-4 th_num]");
+    PRINTUSAGE("", "-m", "cipher mode to use");
+    PRINTUSAGE("", "-i", "file which contains input buffer");
+    PRINTUSAGE("", "-o", "file for signature");
+    PRINTUSAGE("", "-k", "file which contains key");
 #ifndef NSS_DISABLE_ECC
-    PRINTUSAGE("",	"-n", "name of curve for EC key generation; one of:");
-    PRINTUSAGE("",  "",   "  sect163k1, nistk163, sect163r1, sect163r2,");
-    PRINTUSAGE("",  "",   "  nistb163, sect193r1, sect193r2, sect233k1, nistk233,");
-    PRINTUSAGE("",  "",   "  sect233r1, nistb233, sect239k1, sect283k1, nistk283,");
-    PRINTUSAGE("",  "",   "  sect283r1, nistb283, sect409k1, nistk409, sect409r1,");
-    PRINTUSAGE("",  "",   "  nistb409, sect571k1, nistk571, sect571r1, nistb571,");
-    PRINTUSAGE("",  "",   "  secp160k1, secp160r1, secp160r2, secp192k1, secp192r1,");
-    PRINTUSAGE("",  "",   "  nistp192, secp224k1, secp224r1, nistp224, secp256k1,");
-    PRINTUSAGE("",  "",   "  secp256r1, nistp256, secp384r1, nistp384, secp521r1,");
-    PRINTUSAGE("",  "",   "  nistp521, prime192v1, prime192v2, prime192v3,");
-    PRINTUSAGE("",  "",   "  prime239v1, prime239v2, prime239v3, c2pnb163v1,");
-    PRINTUSAGE("",  "",   "  c2pnb163v2, c2pnb163v3, c2pnb176v1, c2tnb191v1,");
-    PRINTUSAGE("",  "",   "  c2tnb191v2, c2tnb191v3, c2onb191v4, c2onb191v5,");
-    PRINTUSAGE("",  "",   "  c2pnb208w1, c2tnb239v1, c2tnb239v2, c2tnb239v3,");
-    PRINTUSAGE("",  "",   "  c2onb239v4, c2onb239v5, c2pnb272w1, c2pnb304w1,");
-    PRINTUSAGE("",  "",   "  c2tnb359w1, c2pnb368w1, c2tnb431r1, secp112r1,");
-    PRINTUSAGE("",  "",   "  secp112r2, secp128r1, secp128r2, sect113r1, sect113r2,");
-    PRINTUSAGE("",  "",   "  sect131r1, sect131r2");
+    PRINTUSAGE("", "-n", "name of curve for EC key generation; one of:");
+    PRINTUSAGE("", "", "  sect163k1, nistk163, sect163r1, sect163r2,");
+    PRINTUSAGE("", "", "  nistb163, sect193r1, sect193r2, sect233k1, nistk233,");
+    PRINTUSAGE("", "", "  sect233r1, nistb233, sect239k1, sect283k1, nistk283,");
+    PRINTUSAGE("", "", "  sect283r1, nistb283, sect409k1, nistk409, sect409r1,");
+    PRINTUSAGE("", "", "  nistb409, sect571k1, nistk571, sect571r1, nistb571,");
+    PRINTUSAGE("", "", "  secp160k1, secp160r1, secp160r2, secp192k1, secp192r1,");
+    PRINTUSAGE("", "", "  nistp192, secp224k1, secp224r1, nistp224, secp256k1,");
+    PRINTUSAGE("", "", "  secp256r1, nistp256, secp384r1, nistp384, secp521r1,");
+    PRINTUSAGE("", "", "  nistp521, prime192v1, prime192v2, prime192v3,");
+    PRINTUSAGE("", "", "  prime239v1, prime239v2, prime239v3, c2pnb163v1,");
+    PRINTUSAGE("", "", "  c2pnb163v2, c2pnb163v3, c2pnb176v1, c2tnb191v1,");
+    PRINTUSAGE("", "", "  c2tnb191v2, c2tnb191v3, c2onb191v4, c2onb191v5,");
+    PRINTUSAGE("", "", "  c2pnb208w1, c2tnb239v1, c2tnb239v2, c2tnb239v3,");
+    PRINTUSAGE("", "", "  c2onb239v4, c2onb239v5, c2pnb272w1, c2pnb304w1,");
+    PRINTUSAGE("", "", "  c2tnb359w1, c2pnb368w1, c2tnb431r1, secp112r1,");
+    PRINTUSAGE("", "", "  secp112r2, secp128r1, secp128r2, sect113r1, sect113r2,");
+    PRINTUSAGE("", "", "  sect131r1, sect131r2");
 #endif
-    PRINTUSAGE("",	"-p", "do performance test");
-    PRINTUSAGE("",	"-4", "run test in multithread mode. th_num number of parallel threads");
-    PRINTUSAGE("",	"-5", "run test for specified time interval(in seconds)");
+    PRINTUSAGE("", "-p", "do performance test");
+    PRINTUSAGE("", "-4", "run test in multithread mode. th_num number of parallel threads");
+    PRINTUSAGE("", "-5", "run test for specified time interval(in seconds)");
     fprintf(stderr, "\n");
     PRINTUSAGE(progName, "-V -m mode", "Verify a signed buffer");
-    PRINTUSAGE("",	"", "[-i plaintext] [-s signature] [-k key]");
-    PRINTUSAGE("",	"", "[-p repetitions | -5 time_interval] [-4 th_num]");
-    PRINTUSAGE("",	"-m", "cipher mode to use");
-    PRINTUSAGE("",	"-i", "file which contains input buffer");
-    PRINTUSAGE("",	"-s", "file which contains signature of input buffer");
-    PRINTUSAGE("",	"-k", "file which contains key");
-    PRINTUSAGE("",	"-p", "do performance test");
-    PRINTUSAGE("",	"-4", "run test in multithread mode. th_num number of parallel threads");
-    PRINTUSAGE("",	"-5", "run test for specified time interval(in seconds)");
+    PRINTUSAGE("", "", "[-i plaintext] [-s signature] [-k key]");
+    PRINTUSAGE("", "", "[-p repetitions | -5 time_interval] [-4 th_num]");
+    PRINTUSAGE("", "-m", "cipher mode to use");
+    PRINTUSAGE("", "-i", "file which contains input buffer");
+    PRINTUSAGE("", "-s", "file which contains signature of input buffer");
+    PRINTUSAGE("", "-k", "file which contains key");
+    PRINTUSAGE("", "-p", "do performance test");
+    PRINTUSAGE("", "-4", "run test in multithread mode. th_num number of parallel threads");
+    PRINTUSAGE("", "-5", "run test for specified time interval(in seconds)");
     fprintf(stderr, "\n");
-    PRINTUSAGE(progName, "-N -m mode -b bufsize", 
-                                            "Create a nonce plaintext and key");
-    PRINTUSAGE("",      "", "[-g keysize] [-u cxreps]");
-    PRINTUSAGE("",	"-g", "key size (in bytes)");
-    PRINTUSAGE("",      "-u", "number of repetitions of context creation");
+    PRINTUSAGE(progName, "-N -m mode -b bufsize",
+               "Create a nonce plaintext and key");
+    PRINTUSAGE("", "", "[-g keysize] [-u cxreps]");
+    PRINTUSAGE("", "-g", "key size (in bytes)");
+    PRINTUSAGE("", "-u", "number of repetitions of context creation");
     fprintf(stderr, "\n");
-    PRINTUSAGE(progName, "-R [-g keysize] [-e exp]", 
-                                            "Test the RSA populate key function");
-    PRINTUSAGE("",      "", "[-r repetitions]");
-    PRINTUSAGE("",	"-g", "key size (in bytes)");
-    PRINTUSAGE("", 	"-e", "rsa public exponent");
-    PRINTUSAGE("", 	"-r", "repetitions of the test");
+    PRINTUSAGE(progName, "-R [-g keysize] [-e exp]",
+               "Test the RSA populate key function");
+    PRINTUSAGE("", "", "[-r repetitions]");
+    PRINTUSAGE("", "-g", "key size (in bytes)");
+    PRINTUSAGE("", "-e", "rsa public exponent");
+    PRINTUSAGE("", "-r", "repetitions of the test");
     fprintf(stderr, "\n");
     PRINTUSAGE(progName, "-F", "Run the FIPS self-test");
     fprintf(stderr, "\n");
     PRINTUSAGE(progName, "-T [-m mode1,mode2...]", "Run the BLAPI self-test");
     fprintf(stderr, "\n");
     exit(1);
 }
 
 /*  Helper functions for ascii<-->binary conversion/reading/writing */
 
 /* XXX argh */
 struct item_with_arena {
-    SECItem	*item;
+    SECItem *item;
     PLArenaPool *arena;
 };
 
 static PRInt32
 get_binary(void *arg, const unsigned char *ibuf, PRInt32 size)
 {
     struct item_with_arena *it = arg;
     SECItem *binary = it->item;
     SECItem *tmp;
     int index;
     if (binary->data == NULL) {
-	tmp = SECITEM_AllocItem(it->arena, NULL, size);
-	binary->data = tmp->data;
-	binary->len = tmp->len;
-	index = 0;
+        tmp = SECITEM_AllocItem(it->arena, NULL, size);
+        binary->data = tmp->data;
+        binary->len = tmp->len;
+        index = 0;
     } else {
-	SECITEM_ReallocItem(NULL, binary, binary->len, binary->len + size);
-	index = binary->len;
+        SECITEM_ReallocItem(NULL, binary, binary->len, binary->len + size);
+        index = binary->len;
     }
     PORT_Memcpy(&binary->data[index], ibuf, size);
     return binary->len;
 }
 
 static SECStatus
 atob(SECItem *ascii, SECItem *binary, PLArenaPool *arena)
 {
     SECStatus status;
     NSSBase64Decoder *cx;
     struct item_with_arena it;
     int len;
     binary->data = NULL;
     binary->len = 0;
     it.item = binary;
     it.arena = arena;
-    len = (strncmp((const char *)&ascii->data[ascii->len-2],"\r\n",2)) ?
-           ascii->len : ascii->len-2;
+    len = (strncmp((const char *)&ascii->data[ascii->len - 2], "\r\n", 2)) ? ascii->len
+                                                                           : ascii->len - 2;
     cx = NSSBase64Decoder_Create(get_binary, &it);
     status = NSSBase64Decoder_Update(cx, (const char *)ascii->data, len);
     status = NSSBase64Decoder_Destroy(cx, PR_FALSE);
     return status;
 }
 
 static PRInt32
 output_ascii(void *arg, const char *obuf, PRInt32 size)
 {
     PRFileDesc *outfile = arg;
     PRInt32 nb = PR_Write(outfile, obuf, size);
     if (nb != size) {
-	PORT_SetError(SEC_ERROR_IO);
-	return -1;
+        PORT_SetError(SEC_ERROR_IO);
+        return -1;
     }
     return nb;
 }
 
 static SECStatus
 btoa_file(SECItem *binary, PRFileDesc *outfile)
 {
     SECStatus status;
     NSSBase64Encoder *cx;
     if (binary->len == 0)
-	return SECSuccess;
+        return SECSuccess;
     cx = NSSBase64Encoder_Create(output_ascii, outfile);
     status = NSSBase64Encoder_Update(cx, binary->data, binary->len);
     status = NSSBase64Encoder_Destroy(cx, PR_FALSE);
     status = PR_Write(outfile, "\r\n", 2);
     return status;
 }
 
 SECStatus
 hex_from_2char(unsigned char *c2, unsigned char *byteval)
 {
     int i;
     unsigned char offset;
     *byteval = 0;
-    for (i=0; i<2; i++) {
-	if (c2[i] >= '0' && c2[i] <= '9') {
-	    offset = c2[i] - '0';
-	    *byteval |= offset << 4*(1-i);
-	} else if (c2[i] >= 'a' && c2[i] <= 'f') {
-	    offset = c2[i] - 'a';
-	    *byteval |= (offset + 10) << 4*(1-i);
-	} else if (c2[i] >= 'A' && c2[i] <= 'F') {
-	    offset = c2[i] - 'A';
-	    *byteval |= (offset + 10) << 4*(1-i);
-	} else {
-	    return SECFailure;
-	}
+    for (i = 0; i < 2; i++) {
+        if (c2[i] >= '0' && c2[i] <= '9') {
+            offset = c2[i] - '0';
+            *byteval |= offset << 4 * (1 - i);
+        } else if (c2[i] >= 'a' && c2[i] <= 'f') {
+            offset = c2[i] - 'a';
+            *byteval |= (offset + 10) << 4 * (1 - i);
+        } else if (c2[i] >= 'A' && c2[i] <= 'F') {
+            offset = c2[i] - 'A';
+            *byteval |= (offset + 10) << 4 * (1 - i);
+        } else {
+            return SECFailure;
+        }
     }
     return SECSuccess;
 }
 
 SECStatus
 char2_from_hex(unsigned char byteval, char *c2)
 {
     int i;
     unsigned char offset;
-    for (i=0; i<2; i++) {
-	offset = (byteval >> 4*(1-i)) & 0x0f;
-	if (offset < 10) {
-	    c2[i] = '0' + offset;
-	} else {
-	    c2[i] = 'A' + offset - 10;
-	}
+    for (i = 0; i < 2; i++) {
+        offset = (byteval >> 4 * (1 - i)) & 0x0f;
+        if (offset < 10) {
+            c2[i] = '0' + offset;
+        } else {
+            c2[i] = 'A' + offset - 10;
+        }
     }
     return SECSuccess;
 }
 
 void
 serialize_key(SECItem *it, int ni, PRFileDesc *file)
 {
     unsigned char len[4];
     int i;
     NSSBase64Encoder *cx;
     cx = NSSBase64Encoder_Create(output_ascii, file);
-    for (i=0; i<ni; i++, it++) {
-	len[0] = (it->len >> 24) & 0xff;
-	len[1] = (it->len >> 16) & 0xff;
-	len[2] = (it->len >>  8) & 0xff;
-	len[3] = (it->len	 & 0xff);
-	NSSBase64Encoder_Update(cx, len, 4);
-	NSSBase64Encoder_Update(cx, it->data, it->len);
+    for (i = 0; i < ni; i++, it++) {
+        len[0] = (it->len >> 24) & 0xff;
+        len[1] = (it->len >> 16) & 0xff;
+        len[2] = (it->len >> 8) & 0xff;
+        len[3] = (it->len & 0xff);
+        NSSBase64Encoder_Update(cx, len, 4);
+        NSSBase64Encoder_Update(cx, it->data, it->len);
     }
     NSSBase64Encoder_Destroy(cx, PR_FALSE);
     PR_Write(file, "\r\n", 2);
 }
 
 void
 key_from_filedata(PLArenaPool *arena, SECItem *it, int ns, int ni, SECItem *filedata)
 {
     int fpos = 0;
     int i, len;
     unsigned char *buf = filedata->data;
-    for (i=0; i<ni; i++) {
-	len  = (buf[fpos++] & 0xff) << 24;
-	len |= (buf[fpos++] & 0xff) << 16;
-	len |= (buf[fpos++] & 0xff) <<  8;
-	len |= (buf[fpos++] & 0xff);
-	if (ns <= i) {
-	    if (len > 0) {
-		it->len = len;
-		it->data = PORT_ArenaAlloc(arena, it->len);
-		PORT_Memcpy(it->data, &buf[fpos], it->len);
-	    } else {
-		it->len = 0;
-		it->data = NULL;
-	    }
-	    it++;
-	}
-	fpos += len;
+    for (i = 0; i < ni; i++) {
+        len = (buf[fpos++] & 0xff) << 24;
+        len |= (buf[fpos++] & 0xff) << 16;
+        len |= (buf[fpos++] & 0xff) << 8;
+        len |= (buf[fpos++] & 0xff);
+        if (ns <= i) {
+            if (len > 0) {
+                it->len = len;
+                it->data = PORT_ArenaAlloc(arena, it->len);
+                PORT_Memcpy(it->data, &buf[fpos], it->len);
+            } else {
+                it->len = 0;
+                it->data = NULL;
+            }
+            it++;
+        }
+        fpos += len;
     }
 }
 
 static RSAPrivateKey *
-rsakey_from_filedata(SECItem *filedata)
+rsakey_from_filedata(PLArenaPool *arena, SECItem *filedata)
 {
     RSAPrivateKey *key;
-    PLArenaPool *arena;
-    arena = PORT_NewArena(BLTEST_DEFAULT_CHUNKSIZE);
     key = (RSAPrivateKey *)PORT_ArenaZAlloc(arena, sizeof(RSAPrivateKey));
     key->arena = arena;
     key_from_filedata(arena, &key->version, 0, 9, filedata);
     return key;
 }
 
 static PQGParams *
-pqg_from_filedata(SECItem *filedata)
+pqg_from_filedata(PLArenaPool *arena, SECItem *filedata)
 {
     PQGParams *pqg;
-    PLArenaPool *arena;
-    arena = PORT_NewArena(BLTEST_DEFAULT_CHUNKSIZE);
     pqg = (PQGParams *)PORT_ArenaZAlloc(arena, sizeof(PQGParams));
     pqg->arena = arena;
     key_from_filedata(arena, &pqg->prime, 0, 3, filedata);
     return pqg;
 }
 
 static DSAPrivateKey *
-dsakey_from_filedata(SECItem *filedata)
+dsakey_from_filedata(PLArenaPool *arena, SECItem *filedata)
 {
     DSAPrivateKey *key;
-    PLArenaPool *arena;
-    arena = PORT_NewArena(BLTEST_DEFAULT_CHUNKSIZE);
     key = (DSAPrivateKey *)PORT_ArenaZAlloc(arena, sizeof(DSAPrivateKey));
     key->params.arena = arena;
     key_from_filedata(arena, &key->params.prime, 0, 5, filedata);
     return key;
 }
 
 #ifndef NSS_DISABLE_ECC
 static ECPrivateKey *
-eckey_from_filedata(SECItem *filedata)
+eckey_from_filedata(PLArenaPool *arena, SECItem *filedata)
 {
     ECPrivateKey *key;
-    PLArenaPool *arena;
     SECStatus rv;
     ECParams *tmpECParams = NULL;
-    arena = PORT_NewArena(BLTEST_DEFAULT_CHUNKSIZE);
     key = (ECPrivateKey *)PORT_ArenaZAlloc(arena, sizeof(ECPrivateKey));
     /* read and convert params */
     key->ecParams.arena = arena;
     key_from_filedata(arena, &key->ecParams.DEREncoding, 0, 1, filedata);
     rv = SECOID_Init();
     CHECKERROR(rv, __LINE__);
     rv = EC_DecodeParams(&key->ecParams.DEREncoding, &tmpECParams);
     CHECKERROR(rv, __LINE__);
@@ -415,130 +408,130 @@ eckey_from_filedata(SECItem *filedata)
     return key;
 }
 
 typedef struct curveNameTagPairStr {
     char *curveName;
     SECOidTag curveOidTag;
 } CurveNameTagPair;
 
-#define DEFAULT_CURVE_OID_TAG  SEC_OID_SECG_EC_SECP192R1
+#define DEFAULT_CURVE_OID_TAG SEC_OID_SECG_EC_SECP192R1
 /* #define DEFAULT_CURVE_OID_TAG  SEC_OID_SECG_EC_SECP160R1 */
 
 static CurveNameTagPair nameTagPair[] =
-{ 
-  { "sect163k1", SEC_OID_SECG_EC_SECT163K1},
-  { "nistk163", SEC_OID_SECG_EC_SECT163K1},
-  { "sect163r1", SEC_OID_SECG_EC_SECT163R1},
-  { "sect163r2", SEC_OID_SECG_EC_SECT163R2},
-  { "nistb163", SEC_OID_SECG_EC_SECT163R2},
-  { "sect193r1", SEC_OID_SECG_EC_SECT193R1},
-  { "sect193r2", SEC_OID_SECG_EC_SECT193R2},
-  { "sect233k1", SEC_OID_SECG_EC_SECT233K1},
-  { "nistk233", SEC_OID_SECG_EC_SECT233K1},
-  { "sect233r1", SEC_OID_SECG_EC_SECT233R1},
-  { "nistb233", SEC_OID_SECG_EC_SECT233R1},
-  { "sect239k1", SEC_OID_SECG_EC_SECT239K1},
-  { "sect283k1", SEC_OID_SECG_EC_SECT283K1},
-  { "nistk283", SEC_OID_SECG_EC_SECT283K1},
-  { "sect283r1", SEC_OID_SECG_EC_SECT283R1},
-  { "nistb283", SEC_OID_SECG_EC_SECT283R1},
-  { "sect409k1", SEC_OID_SECG_EC_SECT409K1},
-  { "nistk409", SEC_OID_SECG_EC_SECT409K1},
-  { "sect409r1", SEC_OID_SECG_EC_SECT409R1},
-  { "nistb409", SEC_OID_SECG_EC_SECT409R1},
-  { "sect571k1", SEC_OID_SECG_EC_SECT571K1},
-  { "nistk571", SEC_OID_SECG_EC_SECT571K1},
-  { "sect571r1", SEC_OID_SECG_EC_SECT571R1},
-  { "nistb571", SEC_OID_SECG_EC_SECT571R1},
-  { "secp160k1", SEC_OID_SECG_EC_SECP160K1},
-  { "secp160r1", SEC_OID_SECG_EC_SECP160R1},
-  { "secp160r2", SEC_OID_SECG_EC_SECP160R2},
-  { "secp192k1", SEC_OID_SECG_EC_SECP192K1},
-  { "secp192r1", SEC_OID_SECG_EC_SECP192R1},
-  { "nistp192", SEC_OID_SECG_EC_SECP192R1},
-  { "secp224k1", SEC_OID_SECG_EC_SECP224K1},
-  { "secp224r1", SEC_OID_SECG_EC_SECP224R1},
-  { "nistp224", SEC_OID_SECG_EC_SECP224R1},
-  { "secp256k1", SEC_OID_SECG_EC_SECP256K1},
-  { "secp256r1", SEC_OID_SECG_EC_SECP256R1},
-  { "nistp256", SEC_OID_SECG_EC_SECP256R1},
-  { "secp384r1", SEC_OID_SECG_EC_SECP384R1},
-  { "nistp384", SEC_OID_SECG_EC_SECP384R1},
-  { "secp521r1", SEC_OID_SECG_EC_SECP521R1},
-  { "nistp521", SEC_OID_SECG_EC_SECP521R1},
-
-  { "prime192v1", SEC_OID_ANSIX962_EC_PRIME192V1 },
-  { "prime192v2", SEC_OID_ANSIX962_EC_PRIME192V2 },
-  { "prime192v3", SEC_OID_ANSIX962_EC_PRIME192V3 },
-  { "prime239v1", SEC_OID_ANSIX962_EC_PRIME239V1 },
-  { "prime239v2", SEC_OID_ANSIX962_EC_PRIME239V2 },
-  { "prime239v3", SEC_OID_ANSIX962_EC_PRIME239V3 },
-
-  { "c2pnb163v1", SEC_OID_ANSIX962_EC_C2PNB163V1 },
-  { "c2pnb163v2", SEC_OID_ANSIX962_EC_C2PNB163V2 },
-  { "c2pnb163v3", SEC_OID_ANSIX962_EC_C2PNB163V3 },
-  { "c2pnb176v1", SEC_OID_ANSIX962_EC_C2PNB176V1 },
-  { "c2tnb191v1", SEC_OID_ANSIX962_EC_C2TNB191V1 },
-  { "c2tnb191v2", SEC_OID_ANSIX962_EC_C2TNB191V2 },
-  { "c2tnb191v3", SEC_OID_ANSIX962_EC_C2TNB191V3 },
-  { "c2onb191v4", SEC_OID_ANSIX962_EC_C2ONB191V4 },
-  { "c2onb191v5", SEC_OID_ANSIX962_EC_C2ONB191V5 },
-  { "c2pnb208w1", SEC_OID_ANSIX962_EC_C2PNB208W1 },
-  { "c2tnb239v1", SEC_OID_ANSIX962_EC_C2TNB239V1 },
-  { "c2tnb239v2", SEC_OID_ANSIX962_EC_C2TNB239V2 },
-  { "c2tnb239v3", SEC_OID_ANSIX962_EC_C2TNB239V3 },
-  { "c2onb239v4", SEC_OID_ANSIX962_EC_C2ONB239V4 },
-  { "c2onb239v5", SEC_OID_ANSIX962_EC_C2ONB239V5 },
-  { "c2pnb272w1", SEC_OID_ANSIX962_EC_C2PNB272W1 },
-  { "c2pnb304w1", SEC_OID_ANSIX962_EC_C2PNB304W1 },
-  { "c2tnb359v1", SEC_OID_ANSIX962_EC_C2TNB359V1 },
-  { "c2pnb368w1", SEC_OID_ANSIX962_EC_C2PNB368W1 },
-  { "c2tnb431r1", SEC_OID_ANSIX962_EC_C2TNB431R1 },
-
-  { "secp112r1", SEC_OID_SECG_EC_SECP112R1},
-  { "secp112r2", SEC_OID_SECG_EC_SECP112R2},
-  { "secp128r1", SEC_OID_SECG_EC_SECP128R1},
-  { "secp128r2", SEC_OID_SECG_EC_SECP128R2},
-
-  { "sect113r1", SEC_OID_SECG_EC_SECT113R1},
-  { "sect113r2", SEC_OID_SECG_EC_SECT113R2},
-  { "sect131r1", SEC_OID_SECG_EC_SECT131R1},
-  { "sect131r2", SEC_OID_SECG_EC_SECT131R2},
-};
-
-static SECItem * 
+    {
+      { "sect163k1", SEC_OID_SECG_EC_SECT163K1 },
+      { "nistk163", SEC_OID_SECG_EC_SECT163K1 },
+      { "sect163r1", SEC_OID_SECG_EC_SECT163R1 },
+      { "sect163r2", SEC_OID_SECG_EC_SECT163R2 },
+      { "nistb163", SEC_OID_SECG_EC_SECT163R2 },
+      { "sect193r1", SEC_OID_SECG_EC_SECT193R1 },
+      { "sect193r2", SEC_OID_SECG_EC_SECT193R2 },
+      { "sect233k1", SEC_OID_SECG_EC_SECT233K1 },
+      { "nistk233", SEC_OID_SECG_EC_SECT233K1 },
+      { "sect233r1", SEC_OID_SECG_EC_SECT233R1 },
+      { "nistb233", SEC_OID_SECG_EC_SECT233R1 },
+      { "sect239k1", SEC_OID_SECG_EC_SECT239K1 },
+      { "sect283k1", SEC_OID_SECG_EC_SECT283K1 },
+      { "nistk283", SEC_OID_SECG_EC_SECT283K1 },
+      { "sect283r1", SEC_OID_SECG_EC_SECT283R1 },
+      { "nistb283", SEC_OID_SECG_EC_SECT283R1 },
+      { "sect409k1", SEC_OID_SECG_EC_SECT409K1 },
+      { "nistk409", SEC_OID_SECG_EC_SECT409K1 },
+      { "sect409r1", SEC_OID_SECG_EC_SECT409R1 },
+      { "nistb409", SEC_OID_SECG_EC_SECT409R1 },
+      { "sect571k1", SEC_OID_SECG_EC_SECT571K1 },
+      { "nistk571", SEC_OID_SECG_EC_SECT571K1 },
+      { "sect571r1", SEC_OID_SECG_EC_SECT571R1 },
+      { "nistb571", SEC_OID_SECG_EC_SECT571R1 },
+      { "secp160k1", SEC_OID_SECG_EC_SECP160K1 },
+      { "secp160r1", SEC_OID_SECG_EC_SECP160R1 },
+      { "secp160r2", SEC_OID_SECG_EC_SECP160R2 },
+      { "secp192k1", SEC_OID_SECG_EC_SECP192K1 },
+      { "secp192r1", SEC_OID_SECG_EC_SECP192R1 },
+      { "nistp192", SEC_OID_SECG_EC_SECP192R1 },
+      { "secp224k1", SEC_OID_SECG_EC_SECP224K1 },
+      { "secp224r1", SEC_OID_SECG_EC_SECP224R1 },
+      { "nistp224", SEC_OID_SECG_EC_SECP224R1 },
+      { "secp256k1", SEC_OID_SECG_EC_SECP256K1 },
+      { "secp256r1", SEC_OID_SECG_EC_SECP256R1 },
+      { "nistp256", SEC_OID_SECG_EC_SECP256R1 },
+      { "secp384r1", SEC_OID_SECG_EC_SECP384R1 },
+      { "nistp384", SEC_OID_SECG_EC_SECP384R1 },
+      { "secp521r1", SEC_OID_SECG_EC_SECP521R1 },
+      { "nistp521", SEC_OID_SECG_EC_SECP521R1 },
+
+      { "prime192v1", SEC_OID_ANSIX962_EC_PRIME192V1 },
+      { "prime192v2", SEC_OID_ANSIX962_EC_PRIME192V2 },
+      { "prime192v3", SEC_OID_ANSIX962_EC_PRIME192V3 },
+      { "prime239v1", SEC_OID_ANSIX962_EC_PRIME239V1 },
+      { "prime239v2", SEC_OID_ANSIX962_EC_PRIME239V2 },
+      { "prime239v3", SEC_OID_ANSIX962_EC_PRIME239V3 },
+
+      { "c2pnb163v1", SEC_OID_ANSIX962_EC_C2PNB163V1 },
+      { "c2pnb163v2", SEC_OID_ANSIX962_EC_C2PNB163V2 },
+      { "c2pnb163v3", SEC_OID_ANSIX962_EC_C2PNB163V3 },
+      { "c2pnb176v1", SEC_OID_ANSIX962_EC_C2PNB176V1 },
+      { "c2tnb191v1", SEC_OID_ANSIX962_EC_C2TNB191V1 },
+      { "c2tnb191v2", SEC_OID_ANSIX962_EC_C2TNB191V2 },
+      { "c2tnb191v3", SEC_OID_ANSIX962_EC_C2TNB191V3 },
+      { "c2onb191v4", SEC_OID_ANSIX962_EC_C2ONB191V4 },
+      { "c2onb191v5", SEC_OID_ANSIX962_EC_C2ONB191V5 },
+      { "c2pnb208w1", SEC_OID_ANSIX962_EC_C2PNB208W1 },
+      { "c2tnb239v1", SEC_OID_ANSIX962_EC_C2TNB239V1 },
+      { "c2tnb239v2", SEC_OID_ANSIX962_EC_C2TNB239V2 },
+      { "c2tnb239v3", SEC_OID_ANSIX962_EC_C2TNB239V3 },
+      { "c2onb239v4", SEC_OID_ANSIX962_EC_C2ONB239V4 },
+      { "c2onb239v5", SEC_OID_ANSIX962_EC_C2ONB239V5 },
+      { "c2pnb272w1", SEC_OID_ANSIX962_EC_C2PNB272W1 },
+      { "c2pnb304w1", SEC_OID_ANSIX962_EC_C2PNB304W1 },
+      { "c2tnb359v1", SEC_OID_ANSIX962_EC_C2TNB359V1 },
+      { "c2pnb368w1", SEC_OID_ANSIX962_EC_C2PNB368W1 },
+      { "c2tnb431r1", SEC_OID_ANSIX962_EC_C2TNB431R1 },
+
+      { "secp112r1", SEC_OID_SECG_EC_SECP112R1 },
+      { "secp112r2", SEC_OID_SECG_EC_SECP112R2 },
+      { "secp128r1", SEC_OID_SECG_EC_SECP128R1 },
+      { "secp128r2", SEC_OID_SECG_EC_SECP128R2 },
+
+      { "sect113r1", SEC_OID_SECG_EC_SECT113R1 },
+      { "sect113r2", SEC_OID_SECG_EC_SECT113R2 },
+      { "sect131r1", SEC_OID_SECG_EC_SECT131R1 },
+      { "sect131r2", SEC_OID_SECG_EC_SECT131R2 },
+    };
+
+static SECItem *
 getECParams(const char *curve)
 {
     SECItem *ecparams;
     SECOidData *oidData = NULL;
     SECOidTag curveOidTag = SEC_OID_UNKNOWN; /* default */
     int i, numCurves;
 
     if (curve != NULL) {
-        numCurves = sizeof(nameTagPair)/sizeof(CurveNameTagPair);
-	for (i = 0; ((i < numCurves) && (curveOidTag == SEC_OID_UNKNOWN)); 
-	     i++) {
-	    if (PL_strcmp(curve, nameTagPair[i].curveName) == 0)
-	        curveOidTag = nameTagPair[i].curveOidTag;
-	}
+        numCurves = sizeof(nameTagPair) / sizeof(CurveNameTagPair);
+        for (i = 0; ((i < numCurves) && (curveOidTag == SEC_OID_UNKNOWN));
+             i++) {
+            if (PL_strcmp(curve, nameTagPair[i].curveName) == 0)
+                curveOidTag = nameTagPair[i].curveOidTag;
+        }
     }
 
     /* Return NULL if curve name is not recognized */
-    if ((curveOidTag == SEC_OID_UNKNOWN) || 
-	(oidData = SECOID_FindOIDByTag(curveOidTag)) == NULL) {
+    if ((curveOidTag == SEC_OID_UNKNOWN) ||
+        (oidData = SECOID_FindOIDByTag(curveOidTag)) == NULL) {
         fprintf(stderr, "Unrecognized elliptic curve %s\n", curve);
-	return NULL;
+        return NULL;
     }
 
     ecparams = SECITEM_AllocItem(NULL, NULL, (2 + oidData->oid.len));
 
-    /* 
+    /*
      * ecparams->data needs to contain the ASN encoding of an object ID (OID)
-     * representing the named curve. The actual OID is in 
+     * representing the named curve. The actual OID is in
      * oidData->oid.data so we simply prepend 0x06 and OID length
      */
     ecparams->data[0] = SEC_ASN1_OBJECT_ID;
     ecparams->data[1] = oidData->oid.len;
     memcpy(ecparams->data + 2, oidData->oid.data, oidData->oid.len);
 
     return ecparams;
 }
@@ -587,125 +580,138 @@ dump_rsakey(RSAPrivateKey *key)
     SECU_PrintInteger(stdout, &key->prime1, "CRT PRIME 1:", 0);
     SECU_PrintInteger(stdout, &key->prime2, "CRT PRIME 2:", 0);
     SECU_PrintInteger(stdout, &key->exponent1, "CRT EXP 1:", 0);
     SECU_PrintInteger(stdout, &key->exponent2, "CRT EXP 2:", 0);
     SECU_PrintInteger(stdout, &key->coefficient, "CRT COEFFICIENT:", 0);
 }
 
 typedef enum {
-    bltestBase64Encoded,       /* Base64 encoded ASCII */
-    bltestBinary,	       /* straight binary */
-    bltestHexSpaceDelim,       /* 0x12 0x34 0xab 0xCD ... */
-    bltestHexStream 	       /* 1234abCD ... */
+    bltestBase64Encoded, /* Base64 encoded ASCII */
+    bltestBinary,        /* straight binary */
+    bltestHexSpaceDelim, /* 0x12 0x34 0xab 0xCD ... */
+    bltestHexStream      /* 1234abCD ... */
 } bltestIOMode;
 
 typedef struct
 {
-    SECItem	   buf;
-    SECItem	   pBuf;
-    bltestIOMode   mode;
-    PRFileDesc*	   file;
+    SECItem buf;
+    SECItem pBuf;
+    bltestIOMode mode;
+    PRFileDesc *file;
 } bltestIO;
 
-typedef SECStatus (* bltestSymmCipherFn)(void *cx,
-					 unsigned char *output,
-					 unsigned int *outputLen,
-					 unsigned int maxOutputLen,
-					 const unsigned char *input,
-					 unsigned int inputLen);
-
-typedef SECStatus (* bltestPubKeyCipherFn)(void *key,
-					   SECItem *output,
-					   const SECItem *input);
-
-typedef SECStatus (* bltestHashCipherFn)(unsigned char *dest,
-					 const unsigned char *src,
-					 PRUint32 src_length);
+typedef SECStatus (*bltestSymmCipherFn)(void *cx,
+                                        unsigned char *output,
+                                        unsigned int *outputLen,
+                                        unsigned int maxOutputLen,
+                                        const unsigned char *input,
+                                        unsigned int inputLen);
+
+typedef SECStatus (*bltestAEADFn)(void *cx,
+                                  unsigned char *output,
+                                  unsigned int *outputLen,
+                                  unsigned int maxOutputLen,
+                                  const unsigned char *input,
+                                  unsigned int inputLen,
+                                  const unsigned char *nonce,
+                                  unsigned int nonceLen,
+                                  const unsigned char *ad,
+                                  unsigned int adLen);
+
+typedef SECStatus (*bltestPubKeyCipherFn)(void *key,
+                                          SECItem *output,
+                                          const SECItem *input);
+
+typedef SECStatus (*bltestHashCipherFn)(unsigned char *dest,
+                                        const unsigned char *src,
+                                        PRUint32 src_length);
 
 /* Note: Algorithms are grouped in order to support is_symmkeyCipher /
  * is_pubkeyCipher / is_hashCipher / is_sigCipher
  */
 typedef enum {
     bltestINVALID = -1,
-    bltestDES_ECB,	  /* Symmetric Key Ciphers */
-    bltestDES_CBC,	  /* .			   */
-    bltestDES_EDE_ECB,	  /* .			   */
-    bltestDES_EDE_CBC,	  /* .			   */
-    bltestRC2_ECB,	  /* .			   */
-    bltestRC2_CBC,	  /* .			   */
-    bltestRC4,		  /* .			   */
+    bltestDES_ECB,     /* Symmetric Key Ciphers */
+    bltestDES_CBC,     /* .            */
+    bltestDES_EDE_ECB, /* .            */
+    bltestDES_EDE_CBC, /* .            */
+    bltestRC2_ECB,     /* .            */
+    bltestRC2_CBC,     /* .            */
+    bltestRC4,         /* .            */
 #ifdef NSS_SOFTOKEN_DOES_RC5
-    bltestRC5_ECB,	  /* .			   */
-    bltestRC5_CBC,	  /* .			   */
+    bltestRC5_ECB, /* .            */
+    bltestRC5_CBC, /* .            */
 #endif
-    bltestAES_ECB,        /* .                     */
-    bltestAES_CBC,        /* .                     */
-    bltestAES_CTS,        /* .                     */
-    bltestAES_CTR,        /* .                     */
-    bltestAES_GCM,        /* .                     */
-    bltestCAMELLIA_ECB,   /* .                     */
-    bltestCAMELLIA_CBC,   /* .                     */
-    bltestSEED_ECB,       /* SEED algorithm	   */
-    bltestSEED_CBC,       /* SEED algorithm	   */
-    bltestRSA,            /* Public Key Ciphers    */
-    bltestRSA_OAEP,       /* . (Public Key Enc.)   */
-    bltestRSA_PSS,        /* . (Public Key Sig.)   */
+    bltestAES_ECB,      /* .                     */
+    bltestAES_CBC,      /* .                     */
+    bltestAES_CTS,      /* .                     */
+    bltestAES_CTR,      /* .                     */
+    bltestAES_GCM,      /* .                     */
+    bltestCAMELLIA_ECB, /* .                     */
+    bltestCAMELLIA_CBC, /* .                     */
+    bltestSEED_ECB,     /* SEED algorithm      */
+    bltestSEED_CBC,     /* SEED algorithm      */
+    bltestCHACHA20,     /* ChaCha20 + Poly1305   */
+    bltestRSA,          /* Public Key Ciphers    */
+    bltestRSA_OAEP,     /* . (Public Key Enc.)   */
+    bltestRSA_PSS,      /* . (Public Key Sig.)   */
 #ifndef NSS_DISABLE_ECC
-    bltestECDSA,          /* . (Public Key Sig.)   */
+    bltestECDSA, /* . (Public Key Sig.)   */
 #endif
-    bltestDSA,            /* . (Public Key Sig.)   */
-    bltestMD2,		  /* Hash algorithms	   */
-    bltestMD5,		  /* .			   */
-    bltestSHA1,           /* .			   */
-    bltestSHA224,         /* .			   */
-    bltestSHA256,         /* .			   */
-    bltestSHA384,         /* .			   */
-    bltestSHA512,         /* .			   */
+    bltestDSA,    /* . (Public Key Sig.)   */
+    bltestMD2,    /* Hash algorithms       */
+    bltestMD5,    /* .             */
+    bltestSHA1,   /* .             */
+    bltestSHA224, /* .             */
+    bltestSHA256, /* .             */
+    bltestSHA384, /* .             */
+    bltestSHA512, /* .             */
     NUMMODES
 } bltestCipherMode;
 
 static char *mode_strings[] =
-{
-    "des_ecb",
-    "des_cbc",
-    "des3_ecb",
-    "des3_cbc",
-    "rc2_ecb",
-    "rc2_cbc",
-    "rc4",
+    {
+      "des_ecb",
+      "des_cbc",
+      "des3_ecb",
+      "des3_cbc",
+      "rc2_ecb",
+      "rc2_cbc",
+      "rc4",
 #ifdef NSS_SOFTOKEN_DOES_RC5
-    "rc5_ecb",
-    "rc5_cbc",
+      "rc5_ecb",
+      "rc5_cbc",
 #endif
-    "aes_ecb",
-    "aes_cbc",
-    "aes_cts",
-    "aes_ctr",
-    "aes_gcm",
-    "camellia_ecb",
-    "camellia_cbc",
-    "seed_ecb",
-    "seed_cbc",
-    "rsa",
-    "rsa_oaep",
-    "rsa_pss",
+      "aes_ecb",
+      "aes_cbc",
+      "aes_cts",
+      "aes_ctr",
+      "aes_gcm",
+      "camellia_ecb",
+      "camellia_cbc",
+      "seed_ecb",
+      "seed_cbc",
+      "chacha20_poly1305",
+      "rsa",
+      "rsa_oaep",
+      "rsa_pss",
 #ifndef NSS_DISABLE_ECC
-    "ecdsa",
+      "ecdsa",
 #endif
-    /*"pqg",*/
-    "dsa",
-    "md2",
-    "md5",
-    "sha1",
-    "sha224",
-    "sha256",
-    "sha384",
-    "sha512",
-};
+      /*"pqg",*/
+      "dsa",
+      "md2",
+      "md5",
+      "sha1",
+      "sha224",
+      "sha256",
+      "sha384",
+      "sha512",
+    };
 
 typedef struct
 {
     bltestIO key;
     bltestIO iv;
 } bltestSymmKeyParams;
 
 typedef struct
@@ -713,349 +719,384 @@ typedef struct
     bltestSymmKeyParams sk; /* must be first */
     bltestIO aad;
 } bltestAuthSymmKeyParams;
 
 typedef struct
 {
     bltestIO key;
     bltestIO iv;
-    int	     rounds;
-    int	     wordsize;
+    int rounds;
+    int wordsize;
 } bltestRC5Params;
 
 typedef struct
 {
     bltestIO key;
     int keysizeInBits;
 
     /* OAEP & PSS */
     HASH_HashType hashAlg;
     HASH_HashType maskHashAlg;
-    bltestIO      seed; /* salt if PSS */
+    bltestIO seed; /* salt if PSS */
 } bltestRSAParams;
 
 typedef struct
 {
-    bltestIO   pqgdata;
+    bltestIO pqgdata;
     unsigned int keysize;
-    bltestIO   keyseed;
-    bltestIO   sigseed;
+    bltestIO keyseed;
+    bltestIO sigseed;
     PQGParams *pqg;
 } bltestDSAParams;
 
 #ifndef NSS_DISABLE_ECC
 typedef struct
 {
-    char      *curveName;
-    bltestIO   sigseed;
+    char *curveName;
+    bltestIO sigseed;
 } bltestECDSAParams;
 #endif
 
 typedef struct
 {
     bltestIO key;
-    void *   privKey;
-    void *   pubKey;
+    void *privKey;
+    void *pubKey;
     bltestIO sig; /* if doing verify, the signature (which may come
                    * from sigfile. */
 
     union {
         bltestRSAParams rsa;
         bltestDSAParams dsa;
 #ifndef NSS_DISABLE_ECC
         bltestECDSAParams ecdsa;
 #endif
     } cipherParams;
 } bltestAsymKeyParams;
 
 typedef struct
 {
-    bltestIO   key; /* unused */
-    PRBool     restart;
+    bltestIO key; /* unused */
+    PRBool restart;
 } bltestHashParams;
 
-typedef union
-{
-    bltestIO		key;
+typedef union {
+    bltestIO key;
     bltestSymmKeyParams sk;
     bltestAuthSymmKeyParams ask;
-    bltestRC5Params	rc5;
-    bltestAsymKeyParams	asymk;
-    bltestHashParams	hash;
+    bltestRC5Params rc5;
+    bltestAsymKeyParams asymk;
+    bltestHashParams hash;
 } bltestParams;
 
 typedef struct bltestCipherInfoStr bltestCipherInfo;
 
-struct  bltestCipherInfoStr {
+struct bltestCipherInfoStr {
     PLArenaPool *arena;
     /* link to next in multithreaded test */
     bltestCipherInfo *next;
-    PRThread         *cipherThread;
+    PRThread *cipherThread;
 
     /* MonteCarlo test flag*/
     PRBool mCarlo;
     /* cipher context */
     void *cx;
     /* I/O streams */
     bltestIO input;
     bltestIO output;
     /* Cipher-specific parameters */
     bltestParams params;
     /* Cipher mode */
-    bltestCipherMode  mode;
+    bltestCipherMode mode;
     /* Cipher function (encrypt/decrypt/sign/verify/hash) */
     union {
-	bltestSymmCipherFn   symmkeyCipher;
-	bltestPubKeyCipherFn pubkeyCipher;
-	bltestHashCipherFn   hashCipher;
+        bltestSymmCipherFn symmkeyCipher;
+        bltestAEADFn aeadCipher;
+        bltestPubKeyCipherFn pubkeyCipher;
+        bltestHashCipherFn hashCipher;
     } cipher;
     /* performance testing */
-    int   repetitionsToPerfom;
-    int   seconds;
-    int	  repetitions;
-    int   cxreps;
+    int repetitionsToPerfom;
+    int seconds;
+    int repetitions;
+    int cxreps;
     double cxtime;
     double optime;
 };
 
 PRBool
 is_symmkeyCipher(bltestCipherMode mode)
 {
     /* change as needed! */
     if (mode >= bltestDES_ECB && mode <= bltestSEED_CBC)
-	return PR_TRUE;
+        return PR_TRUE;
     return PR_FALSE;
 }
 
 PRBool
+is_aeadCipher(bltestCipherMode mode)
+{
+    /* change as needed! */
+    switch (mode) {
+        case bltestCHACHA20:
+            return PR_TRUE;
+        default:
+            return PR_FALSE;
+    }
+}
+
+PRBool
 is_authCipher(bltestCipherMode mode)
 {
     /* change as needed! */
-    if (mode == bltestAES_GCM)
-	return PR_TRUE;
-    return PR_FALSE;
+    switch (mode) {
+        case bltestAES_GCM:
+        case bltestCHACHA20:
+            return PR_TRUE;
+        default:
+            return PR_FALSE;
+    }
 }
 
-
 PRBool
 is_singleShotCipher(bltestCipherMode mode)
 {
     /* change as needed! */
-    if (mode == bltestAES_GCM)
-	return PR_TRUE;
-    if (mode == bltestAES_CTS)
-	return PR_TRUE;
-    return PR_FALSE;
+    switch (mode) {
+        case bltestAES_GCM:
+        case bltestAES_CTS:
+        case bltestCHACHA20:
+            return PR_TRUE;
+        default:
+            return PR_FALSE;
+    }
 }
 
 PRBool
 is_pubkeyCipher(bltestCipherMode mode)
 {
     /* change as needed! */
     if (mode >= bltestRSA && mode <= bltestDSA)
-	return PR_TRUE;
+        return PR_TRUE;
     return PR_FALSE;
 }
 
 PRBool
 is_hashCipher(bltestCipherMode mode)
 {
     /* change as needed! */
     if (mode >= bltestMD2 && mode <= bltestSHA512)
-	return PR_TRUE;
+        return PR_TRUE;
     return PR_FALSE;
 }
 
 PRBool
 is_sigCipher(bltestCipherMode mode)
 {
     /* change as needed! */
     if (mode >= bltestRSA_PSS && mode <= bltestDSA)
-       return PR_TRUE;
+        return PR_TRUE;
     return PR_FALSE;
 }
 
 PRBool
 cipher_requires_IV(bltestCipherMode mode)
 {
     /* change as needed! */
-    if (mode == bltestDES_CBC || mode == bltestDES_EDE_CBC ||
-	mode == bltestRC2_CBC || 
+    switch (mode) {
+        case bltestDES_CBC:
+        case bltestDES_EDE_CBC:
+        case bltestRC2_CBC:
 #ifdef NSS_SOFTOKEN_DOES_RC5
-	mode == bltestRC5_CBC ||
+        case bltestRC5_CBC:
 #endif
-	mode == bltestAES_CBC || mode == bltestAES_CTS || 
-	mode == bltestAES_CTR || mode == bltestAES_GCM ||
-	mode == bltestCAMELLIA_CBC || mode == bltestSEED_CBC)
-	return PR_TRUE;
-    return PR_FALSE;
+        case bltestAES_CBC:
+        case bltestAES_CTS:
+        case bltestAES_CTR:
+        case bltestAES_GCM:
+        case bltestCAMELLIA_CBC:
+        case bltestSEED_CBC:
+        case bltestCHACHA20:
+            return PR_TRUE;
+        default:
+            return PR_FALSE;
+    }
 }
 
 SECStatus finishIO(bltestIO *output, PRFileDesc *file);
 
 SECStatus
 setupIO(PLArenaPool *arena, bltestIO *input, PRFileDesc *file,
-	char *str, int numBytes)
+        char *str, int numBytes)
 {
     SECStatus rv = SECSuccess;
     SECItem fileData;
     SECItem *in;
     unsigned char *tok;
     unsigned int i, j;
 
     if (file && (numBytes == 0 || file == PR_STDIN)) {
-	/* grabbing data from a file */
-	rv = SECU_FileToItem(&fileData, file);
-	if (rv != SECSuccess)
-	    return SECFailure;
-	in = &fileData;
+        /* grabbing data from a file */
+        rv = SECU_FileToItem(&fileData, file);
+        if (rv != SECSuccess)
+            return SECFailure;
+        in = &fileData;
     } else if (str) {
-	/* grabbing data from command line */
-	fileData.data = (unsigned char *)str;
-	fileData.len = PL_strlen(str);
-	in = &fileData;
+        /* grabbing data from command line */
+        fileData.data = (unsigned char *)str;
+        fileData.len = PL_strlen(str);
+        in = &fileData;
     } else if (file) {
-	/* create nonce */
-	SECITEM_AllocItem(arena, &input->buf, numBytes);
-	RNG_GenerateGlobalRandomBytes(input->buf.data, numBytes);
-	return finishIO(input, file);
+        /* create nonce */
+        SECITEM_AllocItem(arena, &input->buf, numBytes);
+        RNG_GenerateGlobalRandomBytes(input->buf.data, numBytes);
+        return finishIO(input, file);
     } else {
-	return SECFailure;
+        return SECFailure;
     }
 
     switch (input->mode) {
-    case bltestBase64Encoded:
-	if (in->len == 0) {
-	    input->buf.data = NULL;
-	    input->buf.len = 0;
-	    break;
-	}
-	rv = atob(in, &input->buf, arena);
-	break;
-    case bltestBinary:
-	if (in->len == 0) {
-	    input->buf.data = NULL;
-	    input->buf.len = 0;
-	    break;
-	}
-	if (in->data[in->len-1] == '\n') --in->len;
-	if (in->data[in->len-1] == '\r') --in->len;
-	SECITEM_CopyItem(arena, &input->buf, in);
-	break;
-    case bltestHexSpaceDelim:
-	SECITEM_AllocItem(arena, &input->buf, in->len/5);
-	for (i=0, j=0; i<in->len; i+=5, j++) {
-	    tok = &in->data[i];
-	    if (tok[0] != '0' || tok[1] != 'x' || tok[4] != ' ')
-		/* bad hex token */
-		break;
-
-	    rv = hex_from_2char(&tok[2], input->buf.data + j);
-	    if (rv)
-		break;
-	}
-	break;
-    case bltestHexStream:
-	SECITEM_AllocItem(arena, &input->buf, in->len/2);
-	for (i=0, j=0; i<in->len; i+=2, j++) {
-	    tok = &in->data[i];
-	    rv = hex_from_2char(tok, input->buf.data + j);
-	    if (rv)
-		break;
-	}
-	break;
+        case bltestBase64Encoded:
+            if (in->len == 0) {
+                input->buf.data = NULL;
+                input->buf.len = 0;
+                break;
+            }
+            rv = atob(in, &input->buf, arena);
+            break;
+        case bltestBinary:
+            if (in->len == 0) {
+                input->buf.data = NULL;
+                input->buf.len = 0;
+                break;
+            }
+            if (in->data[in->len - 1] == '\n')
+                --in->len;
+            if (in->data[in->len - 1] == '\r')
+                --in->len;
+            SECITEM_CopyItem(arena, &input->buf, in);
+            if (rv != SECSuccess) {
+                return SECFailure;
+            }
+            break;
+        case bltestHexSpaceDelim:
+            SECITEM_AllocItem(arena, &input->buf, in->len / 5);
+            for (i = 0, j = 0; i < in->len; i += 5, j++) {
+                tok = &in->data[i];
+                if (tok[0] != '0' || tok[1] != 'x' || tok[4] != ' ')
+                    /* bad hex token */
+                    break;
+
+                rv = hex_from_2char(&tok[2], input->buf.data + j);
+                if (rv)
+                    break;
+            }
+            break;
+        case bltestHexStream:
+            SECITEM_AllocItem(arena, &input->buf, in->len / 2);
+            for (i = 0, j = 0; i < in->len; i += 2, j++) {
+                tok = &in->data[i];
+                rv = hex_from_2char(tok, input->buf.data + j);
+                if (rv)
+                    break;
+            }
+            break;
     }
 
     if (file)
-	SECITEM_FreeItem(&fileData, PR_FALSE);
+        SECITEM_FreeItem(&fileData, PR_FALSE);
     return rv;
 }
 
 SECStatus
 finishIO(bltestIO *output, PRFileDesc *file)
 {
     SECStatus rv = SECSuccess;
     PRInt32 nb;
     unsigned char byteval;
     SECItem *it;
     char hexstr[5];
     unsigned int i;
     if (output->pBuf.len > 0) {
-	it = &output->pBuf;
+        it = &output->pBuf;
     } else {
-	it = &output->buf;
+        it = &output->buf;
     }
     switch (output->mode) {
-    case bltestBase64Encoded:
-	rv = btoa_file(it, file);
-	break;
-    case bltestBinary:
-	nb = PR_Write(file, it->data, it->len);
-	rv = (nb == (PRInt32)it->len) ? SECSuccess : SECFailure;
-	break;
-    case bltestHexSpaceDelim:
-	hexstr[0] = '0';
-	hexstr[1] = 'x';
-	hexstr[4] = ' ';
-	for (i=0; i<it->len; i++) {
-	    byteval = it->data[i];
-	    rv = char2_from_hex(byteval, hexstr + 2);
-	    nb = PR_Write(file, hexstr, 5);
-	    if (rv)
-		break;
-	}
-	PR_Write(file, "\n", 1);
-	break;
-    case bltestHexStream:
-	for (i=0; i<it->len; i++) {
-	    byteval = it->data[i];
-	    rv = char2_from_hex(byteval, hexstr);
-	    if (rv)
-		break;
-	    nb = PR_Write(file, hexstr, 2);
-	}
-	PR_Write(file, "\n", 1);
-	break;
+        case bltestBase64Encoded:
+            rv = btoa_file(it, file);
+            break;
+        case bltestBinary:
+            nb = PR_Write(file, it->data, it->len);
+            rv = (nb == (PRInt32)it->len) ? SECSuccess : SECFailure;
+            break;
+        case bltestHexSpaceDelim:
+            hexstr[0] = '0';
+            hexstr[1] = 'x';
+            hexstr[4] = ' ';
+            for (i = 0; i < it->len; i++) {
+                byteval = it->data[i];
+                rv = char2_from_hex(byteval, hexstr + 2);
+                nb = PR_Write(file, hexstr, 5);
+                if (rv)
+                    break;
+            }
+            PR_Write(file, "\n", 1);
+            break;
+        case bltestHexStream:
+            for (i = 0; i < it->len; i++) {
+                byteval = it->data[i];
+                rv = char2_from_hex(byteval, hexstr);
+                if (rv)
+                    break;
+                nb = PR_Write(file, hexstr, 2);
+            }
+            PR_Write(file, "\n", 1);
+            break;
     }
     return rv;
 }
 
-void
+SECStatus
 bltestCopyIO(PLArenaPool *arena, bltestIO *dest, bltestIO *src)
 {
-    SECITEM_CopyItem(arena, &dest->buf, &src->buf);
+    if (SECITEM_CopyItem(arena, &dest->buf, &src->buf) != SECSuccess) {
+        return SECFailure;
+    }
     if (src->pBuf.len > 0) {
-	dest->pBuf.len = src->pBuf.len;
-	dest->pBuf.data = dest->buf.data + (src->pBuf.data - src->buf.data);
+        dest->pBuf.len = src->pBuf.len;
+        dest->pBuf.data = dest->buf.data + (src->pBuf.data - src->buf.data);
     }
     dest->mode = src->mode;
     dest->file = src->file;
+
+    return SECSuccess;
 }
 
 void
 misalignBuffer(PLArenaPool *arena, bltestIO *io, int off)
 {
     ptrdiff_t offset = (ptrdiff_t)io->buf.data % WORDSIZE;
     int length = io->buf.len;
     if (offset != off) {
-	SECITEM_ReallocItemV2(arena, &io->buf, length + 2*WORDSIZE);
-	/* offset may have changed? */
-	offset = (ptrdiff_t)io->buf.data % WORDSIZE;
-	if (offset != off) {
-	    memmove(io->buf.data + off, io->buf.data, length);
-	    io->pBuf.data = io->buf.data + off;
-	    io->pBuf.len = length;
-	} else {
-	    io->pBuf.data = io->buf.data;
-	    io->pBuf.len = length;
-	}
+        SECITEM_ReallocItemV2(arena, &io->buf, length + 2 * WORDSIZE);
+        /* offset may have changed? */
+        offset = (ptrdiff_t)io->buf.data % WORDSIZE;
+        if (offset != off) {
+            memmove(io->buf.data + off, io->buf.data, length);
+            io->pBuf.data = io->buf.data + off;
+            io->pBuf.len = length;
+        } else {
+            io->pBuf.data = io->buf.data;
+            io->pBuf.len = length;
+        }
     } else {
-	io->pBuf.data = io->buf.data;
-	io->pBuf.len = length;
+        io->pBuf.data = io->buf.data;
+        io->pBuf.len = length;
     }
 }
 
 SECStatus
 des_Encrypt(void *cx, unsigned char *output, unsigned int *outputLen,
             unsigned int maxOutputLen, const unsigned char *input,
             unsigned int inputLen)
 {
@@ -1122,75 +1163,97 @@ aes_Decrypt(void *cx, unsigned char *out
             unsigned int maxOutputLen, const unsigned char *input,
             unsigned int inputLen)
 {
     return AES_Decrypt((AESContext *)cx, output, outputLen, maxOutputLen,
                        input, inputLen);
 }
 
 SECStatus
+chacha20_poly1305_Encrypt(void *cx, unsigned char *output,
+                          unsigned int *outputLen, unsigned int maxOutputLen,
+                          const unsigned char *input, unsigned int inputLen,
+                          const unsigned char *nonce, unsigned int nonceLen,
+                          const unsigned char *ad, unsigned int adLen)
+{
+    return ChaCha20Poly1305_Seal((ChaCha20Poly1305Context *)cx, output,
+                                 outputLen, maxOutputLen, input, inputLen,
+                                 nonce, nonceLen, ad, adLen);
+}
+
+SECStatus
+chacha20_poly1305_Decrypt(void *cx, unsigned char *output,
+                          unsigned int *outputLen, unsigned int maxOutputLen,
+                          const unsigned char *input, unsigned int inputLen,
+                          const unsigned char *nonce, unsigned int nonceLen,
+                          const unsigned char *ad, unsigned int adLen)
+{
+    return ChaCha20Poly1305_Open((ChaCha20Poly1305Context *)cx, output,
+                                 outputLen, maxOutputLen, input, inputLen,
+                                 nonce, nonceLen, ad, adLen);
+}
+
+SECStatus
 camellia_Encrypt(void *cx, unsigned char *output, unsigned int *outputLen,
-		 unsigned int maxOutputLen, const unsigned char *input,
-		 unsigned int inputLen)
+                 unsigned int maxOutputLen, const unsigned char *input,
+                 unsigned int inputLen)
 {
     return Camellia_Encrypt((CamelliaContext *)cx, output, outputLen,
-			    maxOutputLen,
-			    input, inputLen);
+                            maxOutputLen,
+                            input, inputLen);
 }
 
 SECStatus
 camellia_Decrypt(void *cx, unsigned char *output, unsigned int *outputLen,
-		 unsigned int maxOutputLen, const unsigned char *input,
-		 unsigned int inputLen)
+                 unsigned int maxOutputLen, const unsigned char *input,
+                 unsigned int inputLen)
 {
     return Camellia_Decrypt((CamelliaContext *)cx, output, outputLen,
-			    maxOutputLen,
-			    input, inputLen);
+                            maxOutputLen,
+                            input, inputLen);
 }
 
 SECStatus
 seed_Encrypt(void *cx, unsigned char *output, unsigned int *outputLen,
-            unsigned int maxOutputLen, const unsigned char *input,
-            unsigned int inputLen)
+             unsigned int maxOutputLen, const unsigned char *input,
+             unsigned int inputLen)
 {
     return SEED_Encrypt((SEEDContext *)cx, output, outputLen, maxOutputLen,
-                       input, inputLen);
+                        input, inputLen);
 }
 
 SECStatus
 seed_Decrypt(void *cx, unsigned char *output, unsigned int *outputLen,
-            unsigned int maxOutputLen, const unsigned char *input,
-            unsigned int inputLen)
+             unsigned int maxOutputLen, const unsigned char *input,
+             unsigned int inputLen)
 {
     return SEED_Decrypt((SEEDContext *)cx, output, outputLen, maxOutputLen,
-                       input, inputLen);
+                        input, inputLen);
 }
 
 SECStatus
 rsa_PublicKeyOp(void *cx, SECItem *output, const SECItem *input)
 {
     bltestAsymKeyParams *params = (bltestAsymKeyParams *)cx;
     RSAPublicKey *pubKey = (RSAPublicKey *)params->pubKey;
     SECStatus rv = RSA_PublicKeyOp(pubKey, output->data, input->data);
     if (rv == SECSuccess) {
-        output->len = pubKey->modulus.data[0] ? pubKey->modulus.len :
-                                                pubKey->modulus.len - 1;
+        output->len = pubKey->modulus.data[0] ? pubKey->modulus.len : pubKey->modulus.len - 1;
     }
     return rv;
 }
 
 SECStatus
 rsa_PrivateKeyOp(void *cx, SECItem *output, const SECItem *input)
 {
     bltestAsymKeyParams *params = (bltestAsymKeyParams *)cx;
     RSAPrivateKey *privKey = (RSAPrivateKey *)params->privKey;
     SECStatus rv = RSA_PrivateKeyOp(privKey, output->data, input->data);
     if (rv == SECSuccess) {
-        output->len = privKey->modulus.data[0] ? privKey->modulus.len :
-                                                 privKey->modulus.len - 1;
+        output->len = privKey->modulus.data[0] ? privKey->modulus.len : privKey->modulus.len - 1;
     }
     return rv;
 }
 
 SECStatus
 rsa_signDigestPSS(void *cx, SECItem *output, const SECItem *input)
 {
     bltestAsymKeyParams *params = (bltestAsymKeyParams *)cx;
@@ -1266,20 +1329,20 @@ dsa_verifyDigest(void *cx, SECItem *outp
 
 #ifndef NSS_DISABLE_ECC
 SECStatus
 ecdsa_signDigest(void *cx, SECItem *output, const SECItem *input)
 {
     bltestAsymKeyParams *params = (bltestAsymKeyParams *)cx;
     if (params->cipherParams.ecdsa.sigseed.buf.len > 0) {
         return ECDSA_SignDigestWithSeed(
-                        (ECPrivateKey *)params->privKey,
-                        output, input,
-                        params->cipherParams.ecdsa.sigseed.buf.data,
-                        params->cipherParams.ecdsa.sigseed.buf.len);
+            (ECPrivateKey *)params->privKey,
+            output, input,
+            params->cipherParams.ecdsa.sigseed.buf.data,
+            params->cipherParams.ecdsa.sigseed.buf.len);
     }
     return ECDSA_SignDigest((ECPrivateKey *)params->privKey, output, input);
 }
 
 SECStatus
 ecdsa_verifyDigest(void *cx, SECItem *output, const SECItem *input)
 {
     bltestAsymKeyParams *params = (bltestAsymKeyParams *)cx;
@@ -1290,294 +1353,339 @@ ecdsa_verifyDigest(void *cx, SECItem *ou
 SECStatus
 bltest_des_init(bltestCipherInfo *cipherInfo, PRBool encrypt)
 {
     PRIntervalTime time1, time2;
     bltestSymmKeyParams *desp = &cipherInfo->params.sk;
     int minorMode;
     int i;
     switch (cipherInfo->mode) {
-    case bltestDES_ECB:	    minorMode = NSS_DES;	  break;
-    case bltestDES_CBC:	    minorMode = NSS_DES_CBC;	  break;
-    case bltestDES_EDE_ECB: minorMode = NSS_DES_EDE3;	  break;
-    case bltestDES_EDE_CBC: minorMode = NSS_DES_EDE3_CBC; break;
-    default:
-	return SECFailure;
+        case bltestDES_ECB:
+            minorMode = NSS_DES;
+            break;
+        case bltestDES_CBC:
+            minorMode = NSS_DES_CBC;
+            break;
+        case bltestDES_EDE_ECB:
+            minorMode = NSS_DES_EDE3;
+            break;
+        case bltestDES_EDE_CBC:
+            minorMode = NSS_DES_EDE3_CBC;
+            break;
+        default:
+            return SECFailure;
     }
-    cipherInfo->cx = (void*)DES_CreateContext(desp->key.buf.data,
-					      desp->iv.buf.data,
-					      minorMode, encrypt);
+    cipherInfo->cx = (void *)DES_CreateContext(desp->key.buf.data,
+                                               desp->iv.buf.data,
+                                               minorMode, encrypt);
     if (cipherInfo->cxreps > 0) {
-	DESContext **dummycx;
-	dummycx = PORT_Alloc(cipherInfo->cxreps * sizeof(DESContext *));
-	TIMESTART();
-	for (i=0; i<cipherInfo->cxreps; i++) {
-	    dummycx[i] = (void*)DES_CreateContext(desp->key.buf.data,
-					          desp->iv.buf.data,
-					          minorMode, encrypt);
-	}
-	TIMEFINISH(cipherInfo->cxtime, 1.0);
-	for (i=0; i<cipherInfo->cxreps; i++) {
-	    DES_DestroyContext(dummycx[i], PR_TRUE);
-	}
-	PORT_Free(dummycx);
+        DESContext **dummycx;
+        dummycx = PORT_Alloc(cipherInfo->cxreps * sizeof(DESContext *));
+        TIMESTART();
+        for (i = 0; i < cipherInfo->cxreps; i++) {
+            dummycx[i] = (void *)DES_CreateContext(desp->key.buf.data,
+                                                   desp->iv.buf.data,
+                                                   minorMode, encrypt);
+        }
+        TIMEFINISH(cipherInfo->cxtime, 1.0);
+        for (i = 0; i < cipherInfo->cxreps; i++) {
+            DES_DestroyContext(dummycx[i], PR_TRUE);
+        }
+        PORT_Free(dummycx);
     }
     if (encrypt)
-	cipherInfo->cipher.symmkeyCipher = des_Encrypt;
+        cipherInfo->cipher.symmkeyCipher = des_Encrypt;
     else
-	cipherInfo->cipher.symmkeyCipher = des_Decrypt;
+        cipherInfo->cipher.symmkeyCipher = des_Decrypt;
     return SECSuccess;
 }
 
 SECStatus
 bltest_rc2_init(bltestCipherInfo *cipherInfo, PRBool encrypt)
 {
     PRIntervalTime time1, time2;
     bltestSymmKeyParams *rc2p = &cipherInfo->params.sk;
     int minorMode;
     int i;
     switch (cipherInfo->mode) {
-    case bltestRC2_ECB: minorMode = NSS_RC2;	 break;
-    case bltestRC2_CBC: minorMode = NSS_RC2_CBC; break;
-    default:
-	return SECFailure;
+        case bltestRC2_ECB:
+            minorMode = NSS_RC2;
+            break;
+        case bltestRC2_CBC:
+            minorMode = NSS_RC2_CBC;
+            break;
+        default:
+            return SECFailure;
     }
-    cipherInfo->cx = (void*)RC2_CreateContext(rc2p->key.buf.data,
-					      rc2p->key.buf.len,
-					      rc2p->iv.buf.data,
-					      minorMode,
-					      rc2p->key.buf.len);
+    cipherInfo->cx = (void *)RC2_CreateContext(rc2p->key.buf.data,
+                                               rc2p->key.buf.len,
+                                               rc2p->iv.buf.data,
+                                               minorMode,
+                                               rc2p->key.buf.len);
     if (cipherInfo->cxreps > 0) {
-	RC2Context **dummycx;
-	dummycx = PORT_Alloc(cipherInfo->cxreps * sizeof(RC2Context *));
-	TIMESTART();
-	for (i=0; i<cipherInfo->cxreps; i++) {
-	    dummycx[i] = (void*)RC2_CreateContext(rc2p->key.buf.data,
-	                                          rc2p->key.buf.len,
-	                                          rc2p->iv.buf.data,
-	                                          minorMode,
-	                                          rc2p->key.buf.len);
-	}
-	TIMEFINISH(cipherInfo->cxtime, 1.0);
-	for (i=0; i<cipherInfo->cxreps; i++) {
-	    RC2_DestroyContext(dummycx[i], PR_TRUE);
-	}
-	PORT_Free(dummycx);
+        RC2Context **dummycx;
+        dummycx = PORT_Alloc(cipherInfo->cxreps * sizeof(RC2Context *));
+        TIMESTART();
+        for (i = 0; i < cipherInfo->cxreps; i++) {
+            dummycx[i] = (void *)RC2_CreateContext(rc2p->key.buf.data,
+                                                   rc2p->key.buf.len,
+                                                   rc2p->iv.buf.data,
+                                                   minorMode,
+                                                   rc2p->key.buf.len);
+        }
+        TIMEFINISH(cipherInfo->cxtime, 1.0);
+        for (i = 0; i < cipherInfo->cxreps; i++) {
+            RC2_DestroyContext(dummycx[i], PR_TRUE);
+        }
+        PORT_Free(dummycx);
     }
     if (encrypt)
-	cipherInfo->cipher.symmkeyCipher = rc2_Encrypt;
+        cipherInfo->cipher.symmkeyCipher = rc2_Encrypt;
     else
-	cipherInfo->cipher.symmkeyCipher = rc2_Decrypt;
+        cipherInfo->cipher.symmkeyCipher = rc2_Decrypt;
     return SECSuccess;
 }
 
 SECStatus
 bltest_rc4_init(bltestCipherInfo *cipherInfo, PRBool encrypt)
 {
     PRIntervalTime time1, time2;
     int i;
     bltestSymmKeyParams *rc4p = &cipherInfo->params.sk;
-    cipherInfo->cx = (void*)RC4_CreateContext(rc4p->key.buf.data,
-					      rc4p->key.buf.len);
+    cipherInfo->cx = (void *)RC4_CreateContext(rc4p->key.buf.data,
+                                               rc4p->key.buf.len);
     if (cipherInfo->cxreps > 0) {
-	RC4Context **dummycx;
-	dummycx = PORT_Alloc(cipherInfo->cxreps * sizeof(RC4Context *));
-	TIMESTART();
-	for (i=0; i<cipherInfo->cxreps; i++) {
-	    dummycx[i] = (void*)RC4_CreateContext(rc4p->key.buf.data,
-	                                          rc4p->key.buf.len);
-	}
-	TIMEFINISH(cipherInfo->cxtime, 1.0);
-	for (i=0; i<cipherInfo->cxreps; i++) {
-	    RC4_DestroyContext(dummycx[i], PR_TRUE);
-	}
-	PORT_Free(dummycx);
+        RC4Context **dummycx;
+        dummycx = PORT_Alloc(cipherInfo->cxreps * sizeof(RC4Context *));
+        TIMESTART();
+        for (i = 0; i < cipherInfo->cxreps; i++) {
+            dummycx[i] = (void *)RC4_CreateContext(rc4p->key.buf.data,
+                                                   rc4p->key.buf.len);
+        }
+        TIMEFINISH(cipherInfo->cxtime, 1.0);
+        for (i = 0; i < cipherInfo->cxreps; i++) {
+            RC4_DestroyContext(dummycx[i], PR_TRUE);
+        }
+        PORT_Free(dummycx);
     }
     if (encrypt)
-	cipherInfo->cipher.symmkeyCipher = rc4_Encrypt;
+        cipherInfo->cipher.symmkeyCipher = rc4_Encrypt;
     else
-	cipherInfo->cipher.symmkeyCipher = rc4_Decrypt;
+        cipherInfo->cipher.symmkeyCipher = rc4_Decrypt;
     return SECSuccess;
 }
 
 SECStatus
 bltest_rc5_init(bltestCipherInfo *cipherInfo, PRBool encrypt)
 {
 #ifdef NSS_SOFTOKEN_DOES_RC5
     PRIntervalTime time1, time2;
     bltestRC5Params *rc5p = &cipherInfo->params.rc5;
     int minorMode;
     switch (cipherInfo->mode) {
-    case bltestRC5_ECB: minorMode = NSS_RC5;	 break;
-    case bltestRC5_CBC: minorMode = NSS_RC5_CBC; break;
-    default:
-	return SECFailure;
+        case bltestRC5_ECB:
+            minorMode = NSS_RC5;
+            break;
+        case bltestRC5_CBC:
+            minorMode = NSS_RC5_CBC;
+            break;
+        default:
+            return SECFailure;
     }
     TIMESTART();
-    cipherInfo->cx = (void*)RC5_CreateContext(&rc5p->key.buf,
-					      rc5p->rounds, rc5p->wordsize,
-					      rc5p->iv.buf.data, minorMode);
+    cipherInfo->cx = (void *)RC5_CreateContext(&rc5p->key.buf,
+                                               rc5p->rounds, rc5p->wordsize,
+                                               rc5p->iv.buf.data, minorMode);
     TIMEFINISH(cipherInfo->cxtime, 1.0);
     if (encrypt)
-	cipherInfo->cipher.symmkeyCipher = RC5_Encrypt;
+        cipherInfo->cipher.symmkeyCipher = RC5_Encrypt;
     else
-	cipherInfo->cipher.symmkeyCipher = RC5_Decrypt;
+        cipherInfo->cipher.symmkeyCipher = RC5_Decrypt;
     return SECSuccess;
 #else
     return SECFailure;
 #endif
 }
 
 SECStatus
 bltest_aes_init(bltestCipherInfo *cipherInfo, PRBool encrypt)
 {
     bltestSymmKeyParams *aesp = &cipherInfo->params.sk;
     bltestAuthSymmKeyParams *gcmp = &cipherInfo->params.ask;
     int minorMode;
     int i;
-    int keylen   = aesp->key.buf.len;
+    int keylen = aesp->key.buf.len;
     unsigned int blocklen = AES_BLOCK_SIZE;
     PRIntervalTime time1, time2;
     unsigned char *params;
     int len;
     CK_AES_CTR_PARAMS ctrParams;
     CK_GCM_PARAMS gcmParams;
 
     params = aesp->iv.buf.data;
     switch (cipherInfo->mode) {
-    case bltestAES_ECB:	    minorMode = NSS_AES;	  break;
-    case bltestAES_CBC:	    minorMode = NSS_AES_CBC;	  break;
-    case bltestAES_CTS:	    minorMode = NSS_AES_CTS;	  break;
-    case bltestAES_CTR:	    
-	minorMode = NSS_AES_CTR;
-	ctrParams.ulCounterBits = 32;
-	len = PR_MIN(aesp->iv.buf.len, blocklen);
-	PORT_Memset(ctrParams.cb, 0, blocklen);
-	PORT_Memcpy(ctrParams.cb, aesp->iv.buf.data, len);
-	params = (unsigned char *)&ctrParams;
-	break;
-    case bltestAES_GCM:
-	minorMode = NSS_AES_GCM;
-	gcmParams.pIv = gcmp->sk.iv.buf.data;
-	gcmParams.ulIvLen = gcmp->sk.iv.buf.len;
-	gcmParams.pAAD = gcmp->aad.buf.data;
-	gcmParams.ulAADLen = gcmp->aad.buf.len;
-	gcmParams.ulTagBits = blocklen*8;
-	params = (unsigned char *)&gcmParams;
-	break;
-    default:
-	return SECFailure;
+        case bltestAES_ECB:
+            minorMode = NSS_AES;
+            break;
+        case bltestAES_CBC:
+            minorMode = NSS_AES_CBC;
+            break;
+        case bltestAES_CTS:
+            minorMode = NSS_AES_CTS;
+            break;
+        case bltestAES_CTR:
+            minorMode = NSS_AES_CTR;
+            ctrParams.ulCounterBits = 32;
+            len = PR_MIN(aesp->iv.buf.len, blocklen);
+            PORT_Memset(ctrParams.cb, 0, blocklen);
+            PORT_Memcpy(ctrParams.cb, aesp->iv.buf.data, len);
+            params = (unsigned char *)&ctrParams;
+            break;
+        case bltestAES_GCM:
+            minorMode = NSS_AES_GCM;
+            gcmParams.pIv = gcmp->sk.iv.buf.data;
+            gcmParams.ulIvLen = gcmp->sk.iv.buf.len;
+            gcmParams.pAAD = gcmp->aad.buf.data;
+            gcmParams.ulAADLen = gcmp->aad.buf.len;
+            gcmParams.ulTagBits = blocklen * 8;
+            params = (unsigned char *)&gcmParams;
+            break;
+        default:
+            return SECFailure;
     }
-    cipherInfo->cx = (void*)AES_CreateContext(aesp->key.buf.data,
-					      params,
-					      minorMode, encrypt, 
-                                              keylen, blocklen);
+    cipherInfo->cx = (void *)AES_CreateContext(aesp->key.buf.data,
+                                               params,
+                                               minorMode, encrypt,
+                                               keylen, blocklen);
     if (cipherInfo->cxreps > 0) {
-	AESContext **dummycx;
-	dummycx = PORT_Alloc(cipherInfo->cxreps * sizeof(AESContext *));
-	TIMESTART();
-	for (i=0; i<cipherInfo->cxreps; i++) {
-	    dummycx[i] = (void*)AES_CreateContext(aesp->key.buf.data,
-					          params,
-					          minorMode, encrypt,
-	                                          keylen, blocklen);
-	}
-	TIMEFINISH(cipherInfo->cxtime, 1.0);
-	for (i=0; i<cipherInfo->cxreps; i++) {
-	    AES_DestroyContext(dummycx[i], PR_TRUE);
-	}
-	PORT_Free(dummycx);
+        AESContext **dummycx;
+        dummycx = PORT_Alloc(cipherInfo->cxreps * sizeof(AESContext *));
+        TIMESTART();
+        for (i = 0; i < cipherInfo->cxreps; i++) {
+            dummycx[i] = (void *)AES_CreateContext(aesp->key.buf.data,
+                                                   params,
+                                                   minorMode, encrypt,
+                                                   keylen, blocklen);
+        }
+        TIMEFINISH(cipherInfo->cxtime, 1.0);
+        for (i = 0; i < cipherInfo->cxreps; i++) {
+            AES_DestroyContext(dummycx[i], PR_TRUE);
+        }
+        PORT_Free(dummycx);
     }
     if (encrypt)
-	cipherInfo->cipher.symmkeyCipher = aes_Encrypt;
+        cipherInfo->cipher.symmkeyCipher = aes_Encrypt;
     else
-	cipherInfo->cipher.symmkeyCipher = aes_Decrypt;
+        cipherInfo->cipher.symmkeyCipher = aes_Decrypt;
     return SECSuccess;
 }
 
 SECStatus
 bltest_camellia_init(bltestCipherInfo *cipherInfo, PRBool encrypt)
 {
     bltestSymmKeyParams *camelliap = &cipherInfo->params.sk;
     int minorMode;
     int i;
-    int keylen   = camelliap->key.buf.len;
+    int keylen = camelliap->key.buf.len;
     PRIntervalTime time1, time2;
-    
+
     switch (cipherInfo->mode) {
-    case bltestCAMELLIA_ECB:	    minorMode = NSS_CAMELLIA;	  break;
-    case bltestCAMELLIA_CBC:	    minorMode = NSS_CAMELLIA_CBC;  break;
-    default:
-	return SECFailure;
+        case bltestCAMELLIA_ECB:
+            minorMode = NSS_CAMELLIA;
+            break;
+        case bltestCAMELLIA_CBC:
+            minorMode = NSS_CAMELLIA_CBC;
+            break;
+        default:
+            return SECFailure;
     }
-    cipherInfo->cx = (void*)Camellia_CreateContext(camelliap->key.buf.data,
-						   camelliap->iv.buf.data,
-						   minorMode, encrypt, 
-						   keylen);
+    cipherInfo->cx = (void *)Camellia_CreateContext(camelliap->key.buf.data,
+                                                    camelliap->iv.buf.data,
+                                                    minorMode, encrypt,
+                                                    keylen);
     if (cipherInfo->cxreps > 0) {
-	CamelliaContext **dummycx;
-	dummycx = PORT_Alloc(cipherInfo->cxreps * sizeof(CamelliaContext *));
-	TIMESTART();
-	for (i=0; i<cipherInfo->cxreps; i++) {
-	    dummycx[i] = (void*)Camellia_CreateContext(camelliap->key.buf.data,
-						       camelliap->iv.buf.data,
-						       minorMode, encrypt,
-						       keylen);
-	}
-	TIMEFINISH(cipherInfo->cxtime, 1.0);
-	for (i=0; i<cipherInfo->cxreps; i++) {
-	    Camellia_DestroyContext(dummycx[i], PR_TRUE);
-	}
-	PORT_Free(dummycx);
+        CamelliaContext **dummycx;
+        dummycx = PORT_Alloc(cipherInfo->cxreps * sizeof(CamelliaContext *));
+        TIMESTART();
+        for (i = 0; i < cipherInfo->cxreps; i++) {
+            dummycx[i] = (void *)Camellia_CreateContext(camelliap->key.buf.data,
+                                                        camelliap->iv.buf.data,
+                                                        minorMode, encrypt,
+                                                        keylen);
+        }
+        TIMEFINISH(cipherInfo->cxtime, 1.0);
+        for (i = 0; i < cipherInfo->cxreps; i++) {
+            Camellia_DestroyContext(dummycx[i], PR_TRUE);
+        }
+        PORT_Free(dummycx);
     }
     if (encrypt)
-	cipherInfo->cipher.symmkeyCipher = camellia_Encrypt;
+        cipherInfo->cipher.symmkeyCipher = camellia_Encrypt;
     else
-	cipherInfo->cipher.symmkeyCipher = camellia_Decrypt;
+        cipherInfo->cipher.symmkeyCipher = camellia_Decrypt;
     return SECSuccess;
 }
 
 SECStatus
 bltest_seed_init(bltestCipherInfo *cipherInfo, PRBool encrypt)
 {
     PRIntervalTime time1, time2;
     bltestSymmKeyParams *seedp = &cipherInfo->params.sk;
     int minorMode;
     int i;
 
     switch (cipherInfo->mode) {
-    case bltestSEED_ECB:	minorMode = NSS_SEED;		break;
-    case bltestSEED_CBC:	minorMode = NSS_SEED_CBC;	break;
-    default:
-	return SECFailure;
+        case bltestSEED_ECB:
+            minorMode = NSS_SEED;
+            break;
+        case bltestSEED_CBC:
+            minorMode = NSS_SEED_CBC;
+            break;
+        default:
+            return SECFailure;
     }
-    cipherInfo->cx = (void*)SEED_CreateContext(seedp->key.buf.data,
-					      seedp->iv.buf.data,
-					      minorMode, encrypt);
+    cipherInfo->cx = (void *)SEED_CreateContext(seedp->key.buf.data,
+                                                seedp->iv.buf.data,
+                                                minorMode, encrypt);
     if (cipherInfo->cxreps > 0) {
-	SEEDContext **dummycx;
-	dummycx = PORT_Alloc(cipherInfo->cxreps * sizeof(SEEDContext *));
-	TIMESTART();
-	for (i=0; i<cipherInfo->cxreps; i++) {
-	    dummycx[i] = (void*)SEED_CreateContext(seedp->key.buf.data,
-					          seedp->iv.buf.data,
-					          minorMode, encrypt);
-	}
-	TIMEFINISH(cipherInfo->cxtime, 1.0);
-	for (i=0; i<cipherInfo->cxreps; i++) {
-	    SEED_DestroyContext(dummycx[i], PR_TRUE);
-	}
-	PORT_Free(dummycx);
+        SEEDContext **dummycx;
+        dummycx = PORT_Alloc(cipherInfo->cxreps * sizeof(SEEDContext *));
+        TIMESTART();
+        for (i = 0; i < cipherInfo->cxreps; i++) {
+            dummycx[i] = (void *)SEED_CreateContext(seedp->key.buf.data,
+                                                    seedp->iv.buf.data,
+                                                    minorMode, encrypt);
+        }
+        TIMEFINISH(cipherInfo->cxtime, 1.0);
+        for (i = 0; i < cipherInfo->cxreps; i++) {
+            SEED_DestroyContext(dummycx[i], PR_TRUE);
+        }
+        PORT_Free(dummycx);
     }
     if (encrypt)
-	cipherInfo->cipher.symmkeyCipher = seed_Encrypt;
+        cipherInfo->cipher.symmkeyCipher = seed_Encrypt;
     else
-	cipherInfo->cipher.symmkeyCipher = seed_Decrypt;
-	
-	return SECSuccess;
+        cipherInfo->cipher.symmkeyCipher = seed_Decrypt;
+
+    return SECSuccess;
+}
+
+SECStatus
+bltest_chacha20_init(bltestCipherInfo *cipherInfo, PRBool encrypt)
+{
+    const unsigned int tagLen = 16;
+    const bltestSymmKeyParams *sk = &cipherInfo->params.sk;
+    cipherInfo->cx = ChaCha20Poly1305_CreateContext(sk->key.buf.data,
+                                                    sk->key.buf.len, tagLen);
+
+    if (encrypt)
+        cipherInfo->cipher.aeadCipher = chacha20_poly1305_Encrypt;
+    else
+        cipherInfo->cipher.aeadCipher = chacha20_poly1305_Decrypt;
+    return SECSuccess;
 }
 
 SECStatus
 bltest_rsa_init(bltestCipherInfo *cipherInfo, PRBool encrypt)
 {
     int i;
     RSAPrivateKey **dummyKey;
     RSAPrivateKey *privKey;
@@ -1588,42 +1696,42 @@ bltest_rsa_init(bltestCipherInfo *cipher
     bltestRSAParams *rsap = &asymk->cipherParams.rsa;
 
     /* RSA key gen was done during parameter setup */
     cipherInfo->cx = asymk;
     privKey = (RSAPrivateKey *)asymk->privKey;
 
     /* For performance testing */
     if (cipherInfo->cxreps > 0) {
-	/* Create space for n private key objects */
-	dummyKey = (RSAPrivateKey **)PORT_Alloc(cipherInfo->cxreps *
-						sizeof(RSAPrivateKey *));
-	/* Time n keygens, storing in the array */
-	TIMESTART();
-	for (i=0; i<cipherInfo->cxreps; i++)
-	    dummyKey[i] = RSA_NewKey(rsap->keysizeInBits, 
-	                             &privKey->publicExponent);
-	TIMEFINISH(cipherInfo->cxtime, cipherInfo->cxreps);
-	/* Free the n key objects */
-	for (i=0; i<cipherInfo->cxreps; i++)
-	    PORT_FreeArena(dummyKey[i]->arena, PR_TRUE);
-	PORT_Free(dummyKey);
+        /* Create space for n private key objects */
+        dummyKey = (RSAPrivateKey **)PORT_Alloc(cipherInfo->cxreps *
+                                                sizeof(RSAPrivateKey *));
+        /* Time n keygens, storing in the array */
+        TIMESTART();
+        for (i = 0; i < cipherInfo->cxreps; i++)
+            dummyKey[i] = RSA_NewKey(rsap->keysizeInBits,
+                                     &privKey->publicExponent);
+        TIMEFINISH(cipherInfo->cxtime, cipherInfo->cxreps);
+        /* Free the n key objects */
+        for (i = 0; i < cipherInfo->cxreps; i++)
+            PORT_FreeArena(dummyKey[i]->arena, PR_TRUE);
+        PORT_Free(dummyKey);
     }
 
     if ((encrypt && !is_sigCipher(cipherInfo->mode)) ||
         (!encrypt && is_sigCipher(cipherInfo->mode))) {
-	/* Have to convert private key to public key.  Memory
-	 * is freed with private key's arena  */
-	pubKey = (RSAPublicKey *)PORT_ArenaAlloc(privKey->arena,
-						 sizeof(RSAPublicKey));
-	pubKey->modulus.len = privKey->modulus.len;
-	pubKey->modulus.data = privKey->modulus.data;
-	pubKey->publicExponent.len = privKey->publicExponent.len;
-	pubKey->publicExponent.data = privKey->publicExponent.data;
-	asymk->pubKey = (void *)pubKey;
+        /* Have to convert private key to public key.  Memory
+         * is freed with private key's arena  */
+        pubKey = (RSAPublicKey *)PORT_ArenaAlloc(privKey->arena,
+                                                 sizeof(RSAPublicKey));
+        pubKey->modulus.len = privKey->modulus.len;
+        pubKey->modulus.data = privKey->modulus.data;
+        pubKey->publicExponent.len = privKey->publicExponent.len;
+        pubKey->publicExponent.data = privKey->publicExponent.data;
+        asymk->pubKey = (void *)pubKey;
     }
     switch (cipherInfo->mode) {
         case bltestRSA:
             cipherInfo->cipher.pubkeyCipher = encrypt ? rsa_PublicKeyOp
                                                       : rsa_PrivateKeyOp;
             break;
         case bltestRSA_PSS:
             cipherInfo->cipher.pubkeyCipher = encrypt ? rsa_signDigestPSS
@@ -1638,18 +1746,18 @@ bltest_rsa_init(bltestCipherInfo *cipher
     }
     return SECSuccess;
 }
 
 SECStatus
 blapi_pqg_param_gen(unsigned int keysize, PQGParams **pqg, PQGVerify **vfy)
 {
     if (keysize < 1024) {
-	int j = PQG_PBITS_TO_INDEX(keysize);
-	return PQG_ParamGen(j, pqg, vfy);
+        int j = PQG_PBITS_TO_INDEX(keysize);
+        return PQG_ParamGen(j, pqg, vfy);
     }
     return PQG_ParamGenV2(keysize, 0, 0, pqg, vfy);
 }
 
 SECStatus
 bltest_pqg_init(bltestDSAParams *dsap)
 {
     SECStatus rv, res;
@@ -1670,136 +1778,137 @@ bltest_dsa_init(bltestCipherInfo *cipher
     PQGParams *dummypqg;
     PRIntervalTime time1, time2;
     bltestAsymKeyParams *asymk = &cipherInfo->params.asymk;
     bltestDSAParams *dsap = &asymk->cipherParams.dsa;
     PQGVerify *ignore = NULL;
     cipherInfo->cx = asymk;
     /* For performance testing */
     if (cipherInfo->cxreps > 0) {
-	/* Create space for n private key objects */
-	dummyKey = (DSAPrivateKey **)PORT_ZAlloc(cipherInfo->cxreps *
-	                                         sizeof(DSAPrivateKey *));
-	/* Time n keygens, storing in the array */
-	TIMESTART();
-	for (i=0; i<cipherInfo->cxreps; i++) {
-	    dummypqg = NULL;
-	    blapi_pqg_param_gen(dsap->keysize, &dummypqg, &ignore);
-	    DSA_NewKey(dummypqg, &dummyKey[i]);
-	}
-	TIMEFINISH(cipherInfo->cxtime, cipherInfo->cxreps);
-	/* Free the n key objects */
-	for (i=0; i<cipherInfo->cxreps; i++)
-	    PORT_FreeArena(dummyKey[i]->params.arena, PR_TRUE);
-	PORT_Free(dummyKey);
+        /* Create space for n private key objects */
+        dummyKey = (DSAPrivateKey **)PORT_ZAlloc(cipherInfo->cxreps *
+                                                 sizeof(DSAPrivateKey *));
+        /* Time n keygens, storing in the array */
+        TIMESTART();
+        for (i = 0; i < cipherInfo->cxreps; i++) {
+            dummypqg = NULL;
+            blapi_pqg_param_gen(dsap->keysize, &dummypqg, &ignore);
+            DSA_NewKey(dummypqg, &dummyKey[i]);
+        }
+        TIMEFINISH(cipherInfo->cxtime, cipherInfo->cxreps);
+        /* Free the n key objects */
+        for (i = 0; i < cipherInfo->cxreps; i++)
+            PORT_FreeArena(dummyKey[i]->params.arena, PR_TRUE);
+        PORT_Free(dummyKey);
     }
     if (!dsap->pqg && dsap->pqgdata.buf.len > 0) {
-	dsap->pqg = pqg_from_filedata(&dsap->pqgdata.buf);
+        dsap->pqg = pqg_from_filedata(cipherInfo->arena, &dsap->pqgdata.buf);
     }
     if (!asymk->privKey && asymk->key.buf.len > 0) {
-	asymk->privKey = dsakey_from_filedata(&asymk->key.buf);
+        asymk->privKey = dsakey_from_filedata(cipherInfo->arena, &asymk->key.buf);
     }
     if (encrypt) {
-	cipherInfo->cipher.pubkeyCipher = dsa_signDigest;
+        cipherInfo->cipher.pubkeyCipher = dsa_signDigest;
     } else {
-	/* Have to convert private key to public key.  Memory
-	 * is freed with private key's arena  */
-	DSAPublicKey *pubkey;
-	DSAPrivateKey *key = (DSAPrivateKey *)asymk->privKey;
-	pubkey = (DSAPublicKey *)PORT_ArenaZAlloc(key->params.arena,
-						  sizeof(DSAPublicKey));
-	pubkey->params.prime.len = key->params.prime.len;
-	pubkey->params.prime.data = key->params.prime.data;
-	pubkey->params.subPrime.len = key->params.subPrime.len;
-	pubkey->params.subPrime.data = key->params.subPrime.data;
-	pubkey->params.base.len = key->params.base.len;
-	pubkey->params.base.data = key->params.base.data;
-	pubkey->publicValue.len = key->publicValue.len;
-	pubkey->publicValue.data = key->publicValue.data;
-	asymk->pubKey = pubkey;
-	cipherInfo->cipher.pubkeyCipher = dsa_verifyDigest;
+        /* Have to convert private key to public key.  Memory
+         * is freed with private key's arena  */
+        DSAPublicKey *pubkey;
+        DSAPrivateKey *key = (DSAPrivateKey *)asymk->privKey;
+        pubkey = (DSAPublicKey *)PORT_ArenaZAlloc(key->params.arena,
+                                                  sizeof(DSAPublicKey));
+        pubkey->params.prime.len = key->params.prime.len;
+        pubkey->params.prime.data = key->params.prime.data;
+        pubkey->params.subPrime.len = key->params.subPrime.len;
+        pubkey->params.subPrime.data = key->params.subPrime.data;
+        pubkey->params.base.len = key->params.base.len;
+        pubkey->params.base.data = key->params.base.data;
+        pubkey->publicValue.len = key->publicValue.len;
+        pubkey->publicValue.data = key->publicValue.data;
+        asymk->pubKey = pubkey;
+        cipherInfo->cipher.pubkeyCipher = dsa_verifyDigest;
     }
     return SECSuccess;
 }
 
 #ifndef NSS_DISABLE_ECC
 SECStatus
 bltest_ecdsa_init(bltestCipherInfo *cipherInfo, PRBool encrypt)
 {
     int i;
     ECPrivateKey **dummyKey;
     PRIntervalTime time1, time2;
     bltestAsymKeyParams *asymk = &cipherInfo->params.asymk;
     cipherInfo->cx = asymk;
     /* For performance testing */
     if (cipherInfo->cxreps > 0) {
-	/* Create space for n private key objects */
-	dummyKey = (ECPrivateKey **)PORT_ZAlloc(cipherInfo->cxreps *
-	                                         sizeof(ECPrivateKey *));
-	/* Time n keygens, storing in the array */
-	TIMESTART();
-	for (i=0; i<cipherInfo->cxreps; i++) {
-	    EC_NewKey(&((ECPrivateKey *)asymk->privKey)->ecParams, &dummyKey[i]);
-	}
-	TIMEFINISH(cipherInfo->cxtime, cipherInfo->cxreps);
-	/* Free the n key objects */
-	for (i=0; i<cipherInfo->cxreps; i++)
-	    PORT_FreeArena(dummyKey[i]->ecParams.arena, PR_TRUE);
-	PORT_Free(dummyKey);
+        /* Create space for n private key objects */
+        dummyKey = (ECPrivateKey **)PORT_ZAlloc(cipherInfo->cxreps *
+                                                sizeof(ECPrivateKey *));
+        /* Time n keygens, storing in the array */
+        TIMESTART();
+        for (i = 0; i < cipherInfo->cxreps; i++) {
+            EC_NewKey(&((ECPrivateKey *)asymk->privKey)->ecParams, &dummyKey[i]);
+        }
+        TIMEFINISH(cipherInfo->cxtime, cipherInfo->cxreps);
+        /* Free the n key objects */
+        for (i = 0; i < cipherInfo->cxreps; i++)
+            PORT_FreeArena(dummyKey[i]->ecParams.arena, PR_TRUE);
+        PORT_Free(dummyKey);
     }
     if (!asymk->privKey && asymk->key.buf.len > 0) {
-        asymk->privKey = eckey_from_filedata(&asymk->key.buf);
+        asymk->privKey = eckey_from_filedata(cipherInfo->arena, &asymk->key.buf);
     }
     if (encrypt) {
-	cipherInfo->cipher.pubkeyCipher = ecdsa_signDigest;
+        cipherInfo->cipher.pubkeyCipher = ecdsa_signDigest;
     } else {
-	/* Have to convert private key to public key.  Memory
-	 * is freed with private key's arena  */
-	ECPublicKey *pubkey;
-	ECPrivateKey *key = (ECPrivateKey *)asymk->privKey;
-	pubkey = (ECPublicKey *)PORT_ArenaZAlloc(key->ecParams.arena,
-						  sizeof(ECPublicKey));
-	pubkey->ecParams.type = key->ecParams.type;
-	pubkey->ecParams.fieldID.size = key->ecParams.fieldID.size;
-	pubkey->ecParams.fieldID.type = key->ecParams.fieldID.type;
-	pubkey->ecParams.fieldID.u.prime.len = key->ecParams.fieldID.u.prime.len;
-	pubkey->ecParams.fieldID.u.prime.data = key->ecParams.fieldID.u.prime.data;
-	pubkey->ecParams.fieldID.k1 = key->ecParams.fieldID.k1;
-	pubkey->ecParams.fieldID.k2 = key->ecParams.fieldID.k2;
-	pubkey->ecParams.fieldID.k3 = key->ecParams.fieldID.k3;
-	pubkey->ecParams.curve.a.len = key->ecParams.curve.a.len;
-	pubkey->ecParams.curve.a.data = key->ecParams.curve.a.data;
-	pubkey->ecParams.curve.b.len = key->ecParams.curve.b.len;
-	pubkey->ecParams.curve.b.data = key->ecParams.curve.b.data;
-	pubkey->ecParams.curve.seed.len = key->ecParams.curve.seed.len;
-	pubkey->ecParams.curve.seed.data = key->ecParams.curve.seed.data;
-	pubkey->ecParams.base.len = key->ecParams.base.len;
-	pubkey->ecParams.base.data = key->ecParams.base.data;
-	pubkey->ecParams.order.len = key->ecParams.order.len;
-	pubkey->ecParams.order.data = key->ecParams.order.data;
-	pubkey->ecParams.cofactor = key->ecParams.cofactor;
-	pubkey->ecParams.DEREncoding.len = key->ecParams.DEREncoding.len;
-	pubkey->ecParams.DEREncoding.data = key->ecParams.DEREncoding.data;
-	pubkey->ecParams.name= key->ecParams.name;
-	pubkey->publicValue.len = key->publicValue.len;
-	pubkey->publicValue.data = key->publicValue.data;
-	asymk->pubKey = pubkey;
-	cipherInfo->cipher.pubkeyCipher = ecdsa_verifyDigest;
+        /* Have to convert private key to public key.  Memory
+     * is freed with private key's arena  */
+        ECPublicKey *pubkey;
+        ECPrivateKey *key = (ECPrivateKey *)asymk->privKey;
+        pubkey = (ECPublicKey *)PORT_ArenaZAlloc(key->ecParams.arena,
+                                                 sizeof(ECPublicKey));
+        pubkey->ecParams.type = key->ecParams.type;
+        pubkey->ecParams.fieldID.size = key->ecParams.fieldID.size;
+        pubkey->ecParams.fieldID.type = key->ecParams.fieldID.type;
+        pubkey->ecParams.fieldID.u.prime.len = key->ecParams.fieldID.u.prime.len;
+        pubkey->ecParams.fieldID.u.prime.data = key->ecParams.fieldID.u.prime.data;
+        pubkey->ecParams.fieldID.k1 = key->ecParams.fieldID.k1;
+        pubkey->ecParams.fieldID.k2 = key->ecParams.fieldID.k2;
+        pubkey->ecParams.fieldID.k3 = key->ecParams.fieldID.k3;
+        pubkey->ecParams.curve.a.len = key->ecParams.curve.a.len;
+        pubkey->ecParams.curve.a.data = key->ecParams.curve.a.data;
+        pubkey->ecParams.curve.b.len = key->ecParams.curve.b.len;
+        pubkey->ecParams.curve.b.data = key->ecParams.curve.b.data;
+        pubkey->ecParams.curve.seed.len = key->ecParams.curve.seed.len;
+        pubkey->ecParams.curve.seed.data = key->ecParams.curve.seed.data;
+        pubkey->ecParams.base.len = key->ecParams.base.len;
+        pubkey->ecParams.base.data = key->ecParams.base.data;
+        pubkey->ecParams.order.len = key->ecParams.order.len;
+        pubkey->ecParams.order.data = key->ecParams.order.data;
+        pubkey->ecParams.cofactor = key->ecParams.cofactor;
+        pubkey->ecParams.DEREncoding.len = key->ecParams.DEREncoding.len;
+        pubkey->ecParams.DEREncoding.data = key->ecParams.DEREncoding.data;
+        pubkey->ecParams.name = key->ecParams.name;
+        pubkey->publicValue.len = key->publicValue.len;
+        pubkey->publicValue.data = key->publicValue.data;
+        asymk->pubKey = pubkey;
+        cipherInfo->cipher.pubkeyCipher = ecdsa_verifyDigest;
     }
     return SECSuccess;
 }
 #endif
 
 /* XXX unfortunately, this is not defined in blapi.h */
 SECStatus
 md2_HashBuf(unsigned char *dest, const unsigned char *src, PRUint32 src_length)
 {
     unsigned int len;
     MD2Context *cx = MD2_NewContext();
-    if (cx == NULL) return SECFailure;
+    if (cx == NULL)
+        return SECFailure;
     MD2_Begin(cx);
     MD2_Update(cx, src, src_length);
     MD2_End(cx, dest, &len, MD2_LENGTH);
     MD2_DestroyContext(cx, PR_TRUE);
     return SECSuccess;
 }
 
 SECStatus
@@ -1808,36 +1917,36 @@ md2_restart(unsigned char *dest, const u
     MD2Context *cx, *cx_cpy;
     unsigned char *cxbytes;
     unsigned int len;
     unsigned int i, quarter;
     SECStatus rv = SECSuccess;
     cx = MD2_NewContext();
     MD2_Begin(cx);
     /* divide message by 4, restarting 3 times */
-    quarter = (src_length + 3)/ 4;
-    for (i=0; i < 4 && src_length > 0; i++) {
-	MD2_Update(cx, src + i*quarter, PR_MIN(quarter, src_length));
-	len = MD2_FlattenSize(cx);
-	cxbytes = PORT_Alloc(len);
-	MD2_Flatten(cx, cxbytes);
-	cx_cpy = MD2_Resurrect(cxbytes, NULL);
-	if (!cx_cpy) {
-	    PR_fprintf(PR_STDERR, "%s: MD2_Resurrect failed!\n", progName);
-	    goto finish;
-	}
-	rv = PORT_Memcmp(cx, cx_cpy, len);
-	if (rv) {
-	    MD2_DestroyContext(cx_cpy, PR_TRUE);
-	    PR_fprintf(PR_STDERR, "%s: MD2_restart failed!\n", progName);
-	    goto finish;
-	}
-	MD2_DestroyContext(cx_cpy, PR_TRUE);
-	PORT_Free(cxbytes);
-	src_length -= quarter;
+    quarter = (src_length + 3) / 4;
+    for (i = 0; i < 4 && src_length > 0; i++) {
+        MD2_Update(cx, src + i * quarter, PR_MIN(quarter, src_length));
+        len = MD2_FlattenSize(cx);
+        cxbytes = PORT_Alloc(len);
+        MD2_Flatten(cx, cxbytes);
+        cx_cpy = MD2_Resurrect(cxbytes, NULL);
+        if (!cx_cpy) {
+            PR_fprintf(PR_STDERR, "%s: MD2_Resurrect failed!\n", progName);
+            goto finish;
+        }
+        rv = PORT_Memcmp(cx, cx_cpy, len);
+        if (rv) {
+            MD2_DestroyContext(cx_cpy, PR_TRUE);
+            PR_fprintf(PR_STDERR, "%s: MD2_restart failed!\n", progName);
+            goto finish;
+        }
+        MD2_DestroyContext(cx_cpy, PR_TRUE);
+        PORT_Free(cxbytes);
+        src_length -= quarter;
     }
     MD2_End(cx, dest, &len, MD2_LENGTH);
 finish:
     MD2_DestroyContext(cx, PR_TRUE);
     return rv;
 }
 
 SECStatus
@@ -1846,37 +1955,37 @@ md5_restart(unsigned char *dest, const u
     SECStatus rv = SECSuccess;
     MD5Context *cx, *cx_cpy;
     unsigned char *cxbytes;
     unsigned int len;
     unsigned int i, quarter;
     cx = MD5_NewContext();
     MD5_Begin(cx);
     /* divide message by 4, restarting 3 times */
-    quarter = (src_length + 3)/ 4;
-    for (i=0; i < 4 && src_length > 0; i++) {
-	MD5_Update(cx, src + i*quarter, PR_MIN(quarter, src_length));
-	len = MD5_FlattenSize(cx);
-	cxbytes = PORT_Alloc(len);
-	MD5_Flatten(cx, cxbytes);
-	cx_cpy = MD5_Resurrect(cxbytes, NULL);
-	if (!cx_cpy) {
-	    PR_fprintf(PR_STDERR, "%s: MD5_Resurrect failed!\n", progName);
-	    rv = SECFailure;
-	    goto finish;
-	}
-	rv = PORT_Memcmp(cx, cx_cpy, len);
-	if (rv) {
-	    MD5_DestroyContext(cx_cpy, PR_TRUE);
-	    PR_fprintf(PR_STDERR, "%s: MD5_restart failed!\n", progName);
-	    goto finish;
-	}
-	MD5_DestroyContext(cx_cpy, PR_TRUE);
-	PORT_Free(cxbytes);
-	src_length -= quarter;
+    quarter = (src_length + 3) / 4;
+    for (i = 0; i < 4 && src_length > 0; i++) {
+        MD5_Update(cx, src + i * quarter, PR_MIN(quarter, src_length));
+        len = MD5_FlattenSize(cx);
+        cxbytes = PORT_Alloc(len);
+        MD5_Flatten(cx, cxbytes);
+        cx_cpy = MD5_Resurrect(cxbytes, NULL);
+        if (!cx_cpy) {
+            PR_fprintf(PR_STDERR, "%s: MD5_Resurrect failed!\n", progName);
+            rv = SECFailure;
+            goto finish;
+        }
+        rv = PORT_Memcmp(cx, cx_cpy, len);
+        if (rv) {
+            MD5_DestroyContext(cx_cpy, PR_TRUE);
+            PR_fprintf(PR_STDERR, "%s: MD5_restart failed!\n", progName);
+            goto finish;
+        }
+        MD5_DestroyContext(cx_cpy, PR_TRUE);
+        PORT_Free(cxbytes);
+        src_length -= quarter;
     }
     MD5_End(cx, dest, &len, MD5_LENGTH);
 finish:
     MD5_DestroyContext(cx, PR_TRUE);
     return rv;
 }
 
 SECStatus
@@ -1885,37 +1994,37 @@ sha1_restart(unsigned char *dest, const 
     SECStatus rv = SECSuccess;
     SHA1Context *cx, *cx_cpy;
     unsigned char *cxbytes;
     unsigned int len;
     unsigned int i, quarter;
     cx = SHA1_NewContext();
     SHA1_Begin(cx);
     /* divide message by 4, restarting 3 times */
-    quarter = (src_length + 3)/ 4;
-    for (i=0; i < 4 && src_length > 0; i++) {
-	SHA1_Update(cx, src + i*quarter, PR_MIN(quarter, src_length));
-	len = SHA1_FlattenSize(cx);
-	cxbytes = PORT_Alloc(len);
-	SHA1_Flatten(cx, cxbytes);
-	cx_cpy = SHA1_Resurrect(cxbytes, NULL);
-	if (!cx_cpy) {
-	    PR_fprintf(PR_STDERR, "%s: SHA1_Resurrect failed!\n", progName);
-	    rv = SECFailure;
-	    goto finish;
-	}
-	rv = PORT_Memcmp(cx, cx_cpy, len);
-	if (rv) {
-	    SHA1_DestroyContext(cx_cpy, PR_TRUE);
-	    PR_fprintf(PR_STDERR, "%s: SHA1_restart failed!\n", progName);
-	    goto finish;
-	}
-	SHA1_DestroyContext(cx_cpy, PR_TRUE);
-	PORT_Free(cxbytes);
-	src_length -= quarter;
+    quarter = (src_length + 3) / 4;
+    for (i = 0; i < 4 && src_length > 0; i++) {
+        SHA1_Update(cx, src + i * quarter, PR_MIN(quarter, src_length));
+        len = SHA1_FlattenSize(cx);
+        cxbytes = PORT_Alloc(len);
+        SHA1_Flatten(cx, cxbytes);
+        cx_cpy = SHA1_Resurrect(cxbytes, NULL);
+        if (!cx_cpy) {
+            PR_fprintf(PR_STDERR, "%s: SHA1_Resurrect failed!\n", progName);
+            rv = SECFailure;
+            goto finish;
+        }
+        rv = PORT_Memcmp(cx, cx_cpy, len);
+        if (rv) {
+            SHA1_DestroyContext(cx_cpy, PR_TRUE);
+            PR_fprintf(PR_STDERR, "%s: SHA1_restart failed!\n", progName);
+            goto finish;
+        }
+        SHA1_DestroyContext(cx_cpy, PR_TRUE);
+        PORT_Free(cxbytes);
+        src_length -= quarter;
     }
     SHA1_End(cx, dest, &len, MD5_LENGTH);
 finish:
     SHA1_DestroyContext(cx, PR_TRUE);
     return rv;
 }
 
 SECStatus
@@ -1925,37 +2034,37 @@ SHA224_restart(unsigned char *dest, cons
     SHA224Context *cx, *cx_cpy;
     unsigned char *cxbytes;
     unsigned int len;
     unsigned int i, quarter;
     cx = SHA224_NewContext();
     SHA224_Begin(cx);
     /* divide message by 4, restarting 3 times */
     quarter = (src_length + 3) / 4;
-    for (i=0; i < 4 && src_length > 0; i++) {
-	SHA224_Update(cx, src + i*quarter, PR_MIN(quarter, src_length));
-	len = SHA224_FlattenSize(cx);
-	cxbytes = PORT_Alloc(len);
-	SHA224_Flatten(cx, cxbytes);
-	cx_cpy = SHA224_Resurrect(cxbytes, NULL);
-	if (!cx_cpy) {
-	    PR_fprintf(PR_STDERR, "%s: SHA224_Resurrect failed!\n", progName);
-	    rv = SECFailure;
-	    goto finish;
-	}
-	rv = PORT_Memcmp(cx, cx_cpy, len);
-	if (rv) {
-	    SHA224_DestroyContext(cx_cpy, PR_TRUE);
-	    PR_fprintf(PR_STDERR, "%s: SHA224_restart failed!\n", progName);
-	    goto finish;
-	}
-	
-	SHA224_DestroyContext(cx_cpy, PR_TRUE);
-	PORT_Free(cxbytes);
-	src_length -= quarter;
+    for (i = 0; i < 4 && src_length > 0; i++) {
+        SHA224_Update(cx, src + i * quarter, PR_MIN(quarter, src_length));
+        len = SHA224_FlattenSize(cx);
+        cxbytes = PORT_Alloc(len);
+        SHA224_Flatten(cx, cxbytes);
+        cx_cpy = SHA224_Resurrect(cxbytes, NULL);
+        if (!cx_cpy) {
+            PR_fprintf(PR_STDERR, "%s: SHA224_Resurrect failed!\n", progName);
+            rv = SECFailure;
+            goto finish;
+        }
+        rv = PORT_Memcmp(cx, cx_cpy, len);
+        if (rv) {
+            SHA224_DestroyContext(cx_cpy, PR_TRUE);
+            PR_fprintf(PR_STDERR, "%s: SHA224_restart failed!\n", progName);
+            goto finish;
+        }
+
+        SHA224_DestroyContext(cx_cpy, PR_TRUE);
+        PORT_Free(cxbytes);
+        src_length -= quarter;
     }
     SHA224_End(cx, dest, &len, MD5_LENGTH);
 finish:
     SHA224_DestroyContext(cx, PR_TRUE);
     return rv;
 }
 
 SECStatus
@@ -1964,37 +2073,37 @@ SHA256_restart(unsigned char *dest, cons
     SECStatus rv = SECSuccess;
     SHA256Context *cx, *cx_cpy;
     unsigned char *cxbytes;
     unsigned int len;
     unsigned int i, quarter;
     cx = SHA256_NewContext();
     SHA256_Begin(cx);
     /* divide message by 4, restarting 3 times */
-    quarter = (src_length + 3)/ 4;
-    for (i=0; i < 4 && src_length > 0; i++) {
-	SHA256_Update(cx, src + i*quarter, PR_MIN(quarter, src_length));
-	len = SHA256_FlattenSize(cx);
-	cxbytes = PORT_Alloc(len);
-	SHA256_Flatten(cx, cxbytes);
-	cx_cpy = SHA256_Resurrect(cxbytes, NULL);
-	if (!cx_cpy) {
-	    PR_fprintf(PR_STDERR, "%s: SHA256_Resurrect failed!\n", progName);
-	    rv = SECFailure;
-	    goto finish;
-	}
-	rv = PORT_Memcmp(cx, cx_cpy, len);
-	if (rv) {
-	    SHA256_DestroyContext(cx_cpy, PR_TRUE);
-	    PR_fprintf(PR_STDERR, "%s: SHA256_restart failed!\n", progName);
-	    goto finish;
-	}
-	SHA256_DestroyContext(cx_cpy, PR_TRUE);
-	PORT_Free(cxbytes);
-	src_length -= quarter;
+    quarter = (src_length + 3) / 4;
+    for (i = 0; i < 4 && src_length > 0; i++) {
+        SHA256_Update(cx, src + i * quarter, PR_MIN(quarter, src_length));
+        len = SHA256_FlattenSize(cx);
+        cxbytes = PORT_Alloc(len);
+        SHA256_Flatten(cx, cxbytes);
+        cx_cpy = SHA256_Resurrect(cxbytes, NULL);
+        if (!cx_cpy) {
+            PR_fprintf(PR_STDERR, "%s: SHA256_Resurrect failed!\n", progName);
+            rv = SECFailure;
+            goto finish;
+        }
+        rv = PORT_Memcmp(cx, cx_cpy, len);
+        if (rv) {
+            SHA256_DestroyContext(cx_cpy, PR_TRUE);
+            PR_fprintf(PR_STDERR, "%s: SHA256_restart failed!\n", progName);
+            goto finish;
+        }
+        SHA256_DestroyContext(cx_cpy, PR_TRUE);
+        PORT_Free(cxbytes);
+        src_length -= quarter;
     }
     SHA256_End(cx, dest, &len, MD5_LENGTH);
 finish:
     SHA256_DestroyContext(cx, PR_TRUE);
     return rv;
 }
 
 SECStatus
@@ -2003,37 +2112,37 @@ SHA384_restart(unsigned char *dest, cons
     SECStatus rv = SECSuccess;
     SHA384Context *cx, *cx_cpy;
     unsigned char *cxbytes;
     unsigned int len;
     unsigned int i, quarter;
     cx = SHA384_NewContext();
     SHA384_Begin(cx);
     /* divide message by 4, restarting 3 times */
-    quarter = (src_length + 3)/ 4;
-    for (i=0; i < 4 && src_length > 0; i++) {
-	SHA384_Update(cx, src + i*quarter, PR_MIN(quarter, src_length));
-	len = SHA384_FlattenSize(cx);
-	cxbytes = PORT_Alloc(len);
-	SHA384_Flatten(cx, cxbytes);
-	cx_cpy = SHA384_Resurrect(cxbytes, NULL);
-	if (!cx_cpy) {
-	    PR_fprintf(PR_STDERR, "%s: SHA384_Resurrect failed!\n", progName);
-	    rv = SECFailure;
-	    goto finish;
-	}
-	rv = PORT_Memcmp(cx, cx_cpy, len);
-	if (rv) {
-	    SHA384_DestroyContext(cx_cpy, PR_TRUE);
-	    PR_fprintf(PR_STDERR, "%s: SHA384_restart failed!\n", progName);
-	    goto finish;
-	}
-	SHA384_DestroyContext(cx_cpy, PR_TRUE);
-	PORT_Free(cxbytes);
-	src_length -= quarter;
+    quarter = (src_length + 3) / 4;
+    for (i = 0; i < 4 && src_length > 0; i++) {
+        SHA384_Update(cx, src + i * quarter, PR_MIN(quarter, src_length));
+        len = SHA384_FlattenSize(cx);
+        cxbytes = PORT_Alloc(len);
+        SHA384_Flatten(cx, cxbytes);
+        cx_cpy = SHA384_Resurrect(cxbytes, NULL);
+        if (!cx_cpy) {
+            PR_fprintf(PR_STDERR, "%s: SHA384_Resurrect failed!\n", progName);
+            rv = SECFailure;
+            goto finish;
+        }
+        rv = PORT_Memcmp(cx, cx_cpy, len);
+        if (rv) {
+            SHA384_DestroyContext(cx_cpy, PR_TRUE);
+            PR_fprintf(PR_STDERR, "%s: SHA384_restart failed!\n", progName);
+            goto finish;
+        }
+        SHA384_DestroyContext(cx_cpy, PR_TRUE);
+        PORT_Free(cxbytes);
+        src_length -= quarter;
     }
     SHA384_End(cx, dest, &len, MD5_LENGTH);
 finish:
     SHA384_DestroyContext(cx, PR_TRUE);
     return rv;
 }
 
 SECStatus
@@ -2042,296 +2151,300 @@ SHA512_restart(unsigned char *dest, cons
     SECStatus rv = SECSuccess;
     SHA512Context *cx, *cx_cpy;
     unsigned char *cxbytes;
     unsigned int len;
     unsigned int i, quarter;
     cx = SHA512_NewContext();
     SHA512_Begin(cx);
     /* divide message by 4, restarting 3 times */
-    quarter = (src_length + 3)/ 4;
-    for (i=0; i < 4 && src_length > 0; i++) {
-	SHA512_Update(cx, src + i*quarter, PR_MIN(quarter, src_length));
-	len = SHA512_FlattenSize(cx);
-	cxbytes = PORT_Alloc(len);
-	SHA512_Flatten(cx, cxbytes);
-	cx_cpy = SHA512_Resurrect(cxbytes, NULL);
-	if (!cx_cpy) {
-	    PR_fprintf(PR_STDERR, "%s: SHA512_Resurrect failed!\n", progName);
-	    rv = SECFailure;
-	    goto finish;
-	}
-	rv = PORT_Memcmp(cx, cx_cpy, len);
-	if (rv) {
-	    SHA512_DestroyContext(cx_cpy, PR_TRUE);
-	    PR_fprintf(PR_STDERR, "%s: SHA512_restart failed!\n", progName);
-	    goto finish;
-	}
-	SHA512_DestroyContext(cx_cpy, PR_TRUE);
-	PORT_Free(cxbytes);
-	src_length -= quarter;
+    quarter = (src_length + 3) / 4;
+    for (i = 0; i < 4 && src_length > 0; i++) {
+        SHA512_Update(cx, src + i * quarter, PR_MIN(quarter, src_length));
+        len = SHA512_FlattenSize(cx);
+        cxbytes = PORT_Alloc(len);
+        SHA512_Flatten(cx, cxbytes);
+        cx_cpy = SHA512_Resurrect(cxbytes, NULL);
+        if (!cx_cpy) {
+            PR_fprintf(PR_STDERR, "%s: SHA512_Resurrect failed!\n", progName);
+            rv = SECFailure;
+            goto finish;
+        }
+        rv = PORT_Memcmp(cx, cx_cpy, len);
+        if (rv) {
+            SHA512_DestroyContext(cx_cpy, PR_TRUE);
+            PR_fprintf(PR_STDERR, "%s: SHA512_restart failed!\n", progName);
+            goto finish;
+        }
+        SHA512_DestroyContext(cx_cpy, PR_TRUE);
+        PORT_Free(cxbytes);
+        src_length -= quarter;
     }
     SHA512_End(cx, dest, &len, MD5_LENGTH);
 finish:
     SHA512_DestroyContext(cx, PR_TRUE);
     return rv;
 }
 
 SECStatus
 pubkeyInitKey(bltestCipherInfo *cipherInfo, PRFileDesc *file,
 #ifndef NSS_DISABLE_ECC
-	      int keysize, int exponent, char *curveName)
+              int keysize, int exponent, char *curveName)
 #else
-	      int keysize, int exponent)
+              int keysize, int exponent)
 #endif
 {
     int i;
     SECStatus rv = SECSuccess;
     bltestAsymKeyParams *asymk = &cipherInfo->params.asymk;
     bltestRSAParams *rsap;
     RSAPrivateKey **rsaKey = NULL;
     bltestDSAParams *dsap;
     DSAPrivateKey **dsaKey = NULL;
 #ifndef NSS_DISABLE_ECC
     SECItem *tmpECParamsDER;
     ECParams *tmpECParams = NULL;
     SECItem ecSerialize[3];
     ECPrivateKey **ecKey = NULL;
 #endif
     switch (cipherInfo->mode) {
-    case bltestRSA:
-    case bltestRSA_PSS:
-    case bltestRSA_OAEP:
-	rsap = &asymk->cipherParams.rsa;
-        rsaKey = (RSAPrivateKey **)&asymk->privKey;
-	if (keysize > 0) {
-	    SECItem expitem = { 0, 0, 0 };
-	    SECITEM_AllocItem(cipherInfo->arena, &expitem, sizeof(int));
-	    for (i = 1; i <= sizeof(int); i++)
-		expitem.data[i-1] = exponent >> (8*(sizeof(int) - i));
-	    *rsaKey = RSA_NewKey(keysize * 8, &expitem);
-	    serialize_key(&(*rsaKey)->version, 9, file);
-	    rsap->keysizeInBits = keysize * 8;
-	} else {
-	    setupIO(cipherInfo->arena, &asymk->key, file, NULL, 0);
-	    *rsaKey = rsakey_from_filedata(&asymk->key.buf);
-	    rsap->keysizeInBits = (*rsaKey)->modulus.len * 8;
-	}
-	break;
-    case bltestDSA:
-	dsap = &asymk->cipherParams.dsa;
-	dsaKey = (DSAPrivateKey **)&asymk->privKey;
-	if (keysize > 0) {
-	    dsap->keysize = keysize*8;
-	    if (!dsap->pqg)
-		bltest_pqg_init(dsap);
-	    rv = DSA_NewKey(dsap->pqg, dsaKey);
-	    CHECKERROR(rv, __LINE__);
-	    serialize_key(&(*dsaKey)->params.prime, 5, file);
-	} else {
-	    setupIO(cipherInfo->arena, &asymk->key, file, NULL, 0);
-	    *dsaKey = dsakey_from_filedata(&asymk->key.buf);
-	    dsap->keysize = (*dsaKey)->params.prime.len*8;
-	}
-	break;
+        case bltestRSA:
+        case bltestRSA_PSS:
+        case bltestRSA_OAEP:
+            rsap = &asymk->cipherParams.rsa;
+            rsaKey = (RSAPrivateKey **)&asymk->privKey;
+            if (keysize > 0) {
+                SECItem expitem = { 0, 0, 0 };
+                SECITEM_AllocItem(cipherInfo->arena, &expitem, sizeof(int));
+                for (i = 1; i <= sizeof(int); i++)
+                    expitem.data[i - 1] = exponent >> (8 * (sizeof(int) - i));
+                *rsaKey = RSA_NewKey(keysize * 8, &expitem);
+                serialize_key(&(*rsaKey)->version, 9, file);
+                rsap->keysizeInBits = keysize * 8;
+            } else {
+                setupIO(cipherInfo->arena, &asymk->key, file, NULL, 0);
+                *rsaKey = rsakey_from_filedata(cipherInfo->arena, &asymk->key.buf);
+                rsap->keysizeInBits = (*rsaKey)->modulus.len * 8;
+            }
+            break;
+        case bltestDSA:
+            dsap = &asymk->cipherParams.dsa;
+            dsaKey = (DSAPrivateKey **)&asymk->privKey;
+            if (keysize > 0) {
+                dsap->keysize = keysize * 8;
+                if (!dsap->pqg)
+                    bltest_pqg_init(dsap);
+                rv = DSA_NewKey(dsap->pqg, dsaKey);
+                CHECKERROR(rv, __LINE__);
+                serialize_key(&(*dsaKey)->params.prime, 5, file);
+            } else {
+                setupIO(cipherInfo->arena, &asymk->key, file, NULL, 0);
+                *dsaKey = dsakey_from_filedata(cipherInfo->arena, &asymk->key.buf);
+                dsap->keysize = (*dsaKey)->params.prime.len * 8;
+            }
+            break;
 #ifndef NSS_DISABLE_ECC
-    case bltestECDSA:
-	ecKey = (ECPrivateKey **)&asymk->privKey;
-	if (curveName != NULL) {
-	    tmpECParamsDER = getECParams(curveName);
-	    rv = SECOID_Init();
-	    CHECKERROR(rv, __LINE__);
-	    rv = EC_DecodeParams(tmpECParamsDER, &tmpECParams) == SECFailure;
-	    CHECKERROR(rv, __LINE__);
-	    rv = EC_NewKey(tmpECParams, ecKey);
-	    CHECKERROR(rv, __LINE__);
-	    ecSerialize[0].type = tmpECParamsDER->type;
-	    ecSerialize[0].data = tmpECParamsDER->data;
-	    ecSerialize[0].len  = tmpECParamsDER->len;
-	    ecSerialize[1].type = (*ecKey)->publicValue.type;
-	    ecSerialize[1].data = (*ecKey)->publicValue.data;
-	    ecSerialize[1].len  = (*ecKey)->publicValue.len;
-	    ecSerialize[2].type = (*ecKey)->privateValue.type;
-	    ecSerialize[2].data = (*ecKey)->privateValue.data;
-	    ecSerialize[2].len  = (*ecKey)->privateValue.len;
-	    serialize_key(&(ecSerialize[0]), 3, file);
-	    SECITEM_FreeItem(tmpECParamsDER, PR_TRUE);
-	    PORT_FreeArena(tmpECParams->arena, PR_TRUE);
-	    rv = SECOID_Shutdown();
-	    CHECKERROR(rv, __LINE__);
-	} else {
-	    setupIO(cipherInfo->arena, &asymk->key, file, NULL, 0);
-	    *ecKey = eckey_from_filedata(&asymk->key.buf);
-	}
-	break;
+        case bltestECDSA:
+            ecKey = (ECPrivateKey **)&asymk->privKey;
+            if (curveName != NULL) {
+                tmpECParamsDER = getECParams(curveName);
+                rv = SECOID_Init();
+                CHECKERROR(rv, __LINE__);
+                rv = EC_DecodeParams(tmpECParamsDER, &tmpECParams) == SECFailure;
+                CHECKERROR(rv, __LINE__);
+                rv = EC_NewKey(tmpECParams, ecKey);
+                CHECKERROR(rv, __LINE__);
+                ecSerialize[0].type = tmpECParamsDER->type;
+                ecSerialize[0].data = tmpECParamsDER->data;
+                ecSerialize[0].len = tmpECParamsDER->len;
+                ecSerialize[1].type = (*ecKey)->publicValue.type;
+                ecSerialize[1].data = (*ecKey)->publicValue.data;
+                ecSerialize[1].len = (*ecKey)->publicValue.len;
+                ecSerialize[2].type = (*ecKey)->privateValue.type;
+                ecSerialize[2].data = (*ecKey)->privateValue.data;
+                ecSerialize[2].len = (*ecKey)->privateValue.len;
+                serialize_key(&(ecSerialize[0]), 3, file);
+                SECITEM_FreeItem(tmpECParamsDER, PR_TRUE);
+                PORT_FreeArena(tmpECParams->arena, PR_TRUE);
+                rv = SECOID_Shutdown();
+                CHECKERROR(rv, __LINE__);
+            } else {
+                setupIO(cipherInfo->arena, &asymk->key, file, NULL, 0);
+                *ecKey = eckey_from_filedata(cipherInfo->arena, &asymk->key.buf);
+            }
+            break;
 #endif
-    default:
-	return SECFailure;
+        default:
+            return SECFailure;
     }
     return SECSuccess;
 }
 
 SECStatus
 cipherInit(bltestCipherInfo *cipherInfo, PRBool encrypt)
 {
     PRBool restart;
     int outlen;
     switch (cipherInfo->mode) {
-    case bltestDES_ECB:
-    case bltestDES_CBC:
-    case bltestDES_EDE_ECB:
-    case bltestDES_EDE_CBC:
-	SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
-			  cipherInfo->input.pBuf.len);
-	return bltest_des_init(cipherInfo, encrypt);
-	break;
-    case bltestRC2_ECB:
-    case bltestRC2_CBC:
-	SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
-			  cipherInfo->input.pBuf.len);
-	return bltest_rc2_init(cipherInfo, encrypt);
-	break;
-    case bltestRC4:
-	SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
-			  cipherInfo->input.pBuf.len);
-	return bltest_rc4_init(cipherInfo, encrypt);
-	break;
+        case bltestDES_ECB:
+        case bltestDES_CBC:
+        case bltestDES_EDE_ECB:
+        case bltestDES_EDE_CBC:
+            SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
+                              cipherInfo->input.pBuf.len);
+            return bltest_des_init(cipherInfo, encrypt);
+            break;
+        case bltestRC2_ECB:
+        case bltestRC2_CBC:
+            SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
+                              cipherInfo->input.pBuf.len);
+            return bltest_rc2_init(cipherInfo, encrypt);
+            break;
+        case bltestRC4:
+            SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
+                              cipherInfo->input.pBuf.len);
+            return bltest_rc4_init(cipherInfo, encrypt);
+            break;
 #ifdef NSS_SOFTOKEN_DOES_RC5
-    case bltestRC5_ECB:
-    case bltestRC5_CBC:
-	SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
-			  cipherInfo->input.pBuf.len);
+        case bltestRC5_ECB:
+        case bltestRC5_CBC:
+            SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
+                              cipherInfo->input.pBuf.len);
 #endif
-	return bltest_rc5_init(cipherInfo, encrypt);
-	break;
-    case bltestAES_ECB:
-    case bltestAES_CBC:
-    case bltestAES_CTS:
-    case bltestAES_CTR:
-    case bltestAES_GCM:
-	outlen = cipherInfo->input.pBuf.len;
-	if (cipherInfo->mode == bltestAES_GCM && encrypt) {
-	    outlen += 16;
-	}
-	SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, outlen);
-	return bltest_aes_init(cipherInfo, encrypt);
-	break;
-    case bltestCAMELLIA_ECB:
-    case bltestCAMELLIA_CBC:
-	SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
-			  cipherInfo->input.pBuf.len);
-	return bltest_camellia_init(cipherInfo, encrypt);
-	break;
-    case bltestSEED_ECB:
-    case bltestSEED_CBC:
-	SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
-			  cipherInfo->input.pBuf.len);
-	return bltest_seed_init(cipherInfo, encrypt);
-	break;
-    case bltestRSA:
-    case bltestRSA_OAEP:
-    case bltestRSA_PSS:
-	if (encrypt || cipherInfo->mode != bltestRSA_PSS) {
-		/* Don't allocate a buffer for PSS in verify mode, as no actual
-		 * output is produced. */
-		SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
-		                  RSA_MAX_MODULUS_BITS / 8);
-	}
-	return bltest_rsa_init(cipherInfo, encrypt);
-	break;
-    case bltestDSA:
-	if (encrypt) {
-		SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
-		                  DSA_MAX_SIGNATURE_LEN);
-	}
-	return bltest_dsa_init(cipherInfo, encrypt);
-	break;
+            return bltest_rc5_init(cipherInfo, encrypt);
+            break;
+        case bltestAES_ECB:
+        case bltestAES_CBC:
+        case bltestAES_CTS:
+        case bltestAES_CTR:
+        case bltestAES_GCM:
+            outlen = cipherInfo->input.pBuf.len;
+            if (cipherInfo->mode == bltestAES_GCM && encrypt) {
+                outlen += 16;
+            }
+            SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, outlen);
+            return bltest_aes_init(cipherInfo, encrypt);
+            break;
+        case bltestCAMELLIA_ECB:
+        case bltestCAMELLIA_CBC:
+            SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
+                              cipherInfo->input.pBuf.len);
+            return bltest_camellia_init(cipherInfo, encrypt);
+            break;
+        case bltestSEED_ECB:
+        case bltestSEED_CBC:
+            SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
+                              cipherInfo->input.pBuf.len);
+            return bltest_seed_init(cipherInfo, encrypt);
+            break;
+        case bltestCHACHA20:
+            outlen = cipherInfo->input.pBuf.len + (encrypt ? 16 : 0);
+            SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf, outlen);
+            return bltest_chacha20_init(cipherInfo, encrypt);
+            break;
+        case bltestRSA:
+        case bltestRSA_OAEP:
+        case bltestRSA_PSS:
+            if (encrypt || cipherInfo->mode != bltestRSA_PSS) {
+                /* Don't allocate a buffer for PSS in verify mode, as no actual
+         * output is produced. */
+                SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
+                                  RSA_MAX_MODULUS_BITS / 8);
+            }
+            return bltest_rsa_init(cipherInfo, encrypt);
+            break;
+        case bltestDSA:
+            if (encrypt) {
+                SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
+                                  DSA_MAX_SIGNATURE_LEN);
+            }
+            return bltest_dsa_init(cipherInfo, encrypt);
+            break;
 #ifndef NSS_DISABLE_ECC
-    case bltestECDSA:
-	if (encrypt) {
-		SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
-		                  2 * MAX_ECKEY_LEN);
-	}
-	return bltest_ecdsa_init(cipherInfo, encrypt);
-	break;
+        case bltestECDSA:
+            if (encrypt) {
+                SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
+                                  2 * MAX_ECKEY_LEN);
+            }
+            return bltest_ecdsa_init(cipherInfo, encrypt);
+            break;
 #endif
-    case bltestMD2:
-	restart = cipherInfo->params.hash.restart;
-	SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
-			  MD2_LENGTH);
-	cipherInfo->cipher.hashCipher = (restart) ? md2_restart : md2_HashBuf;
-	return SECSuccess;
-	break;
-    case bltestMD5:
-	restart = cipherInfo->params.hash.restart;
-	SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
-			  MD5_LENGTH);
-	cipherInfo->cipher.hashCipher = (restart) ? md5_restart : MD5_HashBuf;
-	return SECSuccess;
-	break;
-    case bltestSHA1:
-	restart = cipherInfo->params.hash.restart;
-	SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
-			  SHA1_LENGTH);
-	cipherInfo->cipher.hashCipher = (restart) ? sha1_restart : SHA1_HashBuf;
-	return SECSuccess;
-	break;
-    case bltestSHA224:
-	restart = cipherInfo->params.hash.restart;
-	SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
-			  SHA224_LENGTH);
-	cipherInfo->cipher.hashCipher = (restart) ? SHA224_restart 
-	                                          : SHA224_HashBuf;
-	return SECSuccess;
-	break;
-    case bltestSHA256:
-	restart = cipherInfo->params.hash.restart;
-	SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
-			  SHA256_LENGTH);
-	cipherInfo->cipher.hashCipher = (restart) ? SHA256_restart 
-	                                          : SHA256_HashBuf;
-	return SECSuccess;
-	break;
-    case bltestSHA384:
-	restart = cipherInfo->params.hash.restart;
-	SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
-			  SHA384_LENGTH);
-	cipherInfo->cipher.hashCipher = (restart) ? SHA384_restart 
-	                                          : SHA384_HashBuf;
-	return SECSuccess;
-	break;
-    case bltestSHA512:
-	restart = cipherInfo->params.hash.restart;
-	SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
-			  SHA512_LENGTH);
-	cipherInfo->cipher.hashCipher = (restart) ? SHA512_restart 
-	                                          : SHA512_HashBuf;
-	return SECSuccess;
-	break;
-    default:
-	return SECFailure;
+        case bltestMD2:
+            restart = cipherInfo->params.hash.restart;
+            SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
+                              MD2_LENGTH);
+            cipherInfo->cipher.hashCipher = (restart) ? md2_restart : md2_HashBuf;
+            return SECSuccess;
+            break;
+        case bltestMD5:
+            restart = cipherInfo->params.hash.restart;
+            SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
+                              MD5_LENGTH);
+            cipherInfo->cipher.hashCipher = (restart) ? md5_restart : MD5_HashBuf;
+            return SECSuccess;
+            break;
+        case bltestSHA1:
+            restart = cipherInfo->params.hash.restart;
+            SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
+                              SHA1_LENGTH);
+            cipherInfo->cipher.hashCipher = (restart) ? sha1_restart : SHA1_HashBuf;
+            return SECSuccess;
+            break;
+        case bltestSHA224:
+            restart = cipherInfo->params.hash.restart;
+            SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
+                              SHA224_LENGTH);
+            cipherInfo->cipher.hashCipher = (restart) ? SHA224_restart
+                                                      : SHA224_HashBuf;
+            return SECSuccess;
+            break;
+        case bltestSHA256:
+            restart = cipherInfo->params.hash.restart;
+            SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
+                              SHA256_LENGTH);
+            cipherInfo->cipher.hashCipher = (restart) ? SHA256_restart
+                                                      : SHA256_HashBuf;
+            return SECSuccess;
+            break;
+        case bltestSHA384:
+            restart = cipherInfo->params.hash.restart;
+            SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
+                              SHA384_LENGTH);
+            cipherInfo->cipher.hashCipher = (restart) ? SHA384_restart
+                                                      : SHA384_HashBuf;
+            return SECSuccess;
+            break;
+        case bltestSHA512:
+            restart = cipherInfo->params.hash.restart;
+            SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
+                              SHA512_LENGTH);
+            cipherInfo->cipher.hashCipher = (restart) ? SHA512_restart
+                                                      : SHA512_HashBuf;
+            return SECSuccess;
+            break;
+        default:
+            return SECFailure;
     }
     return SECSuccess;
 }
 
 SECStatus
 cipherDoOp(bltestCipherInfo *cipherInfo)
 {
     PRIntervalTime time1, time2;
     SECStatus rv = SECSuccess;
     int i;
     unsigned int len;
     unsigned int maxLen = cipherInfo->output.pBuf.len;
     unsigned char *dummyOut;
     dummyOut = PORT_Alloc(maxLen);
     if (is_symmkeyCipher(cipherInfo->mode)) {
         const unsigned char *input = cipherInfo->input.pBuf.data;
-        unsigned int inputLen = is_singleShotCipher(cipherInfo->mode) ?
-                 cipherInfo->input.pBuf.len :
-                 PR_MIN(cipherInfo->input.pBuf.len, 16);
+        unsigned int inputLen = is_singleShotCipher(cipherInfo->mode) ? cipherInfo->input.pBuf.len
+                                                                      : PR_MIN(cipherInfo->input.pBuf.len, 16);
         unsigned char *output = cipherInfo->output.pBuf.data;
         unsigned int outputLen = maxLen;
         unsigned int totalOutputLen = 0;
         TIMESTART();
         rv = (*cipherInfo->cipher.symmkeyCipher)(cipherInfo->cx,
                                                  output, &len, outputLen,
                                                  input, inputLen);
         CHECKERROR(rv, __LINE__);
@@ -2340,72 +2453,121 @@ cipherDoOp(bltestCipherInfo *cipherInfo)
             input += inputLen;
             inputLen = cipherInfo->input.pBuf.len - inputLen;
             output += len;
             outputLen -= len;
             rv = (*cipherInfo->cipher.symmkeyCipher)(cipherInfo->cx,
                                                      output, &len, outputLen,
                                                      input, inputLen);
             CHECKERROR(rv, __LINE__);
-	    totalOutputLen += len;
+            totalOutputLen += len;
         }
-	cipherInfo->output.pBuf.len = totalOutputLen;
+        cipherInfo->output.pBuf.len = totalOutputLen;
         TIMEFINISH(cipherInfo->optime, 1.0);
         cipherInfo->repetitions = 0;
         if (cipherInfo->repetitionsToPerfom != 0) {
             TIMESTART();
-            for (i=0; i<cipherInfo->repetitionsToPerfom; i++,
-                     cipherInfo->repetitions++) {
+            for (i = 0; i < cipherInfo->repetitionsToPerfom; i++,
+                cipherInfo->repetitions++) {
                 (*cipherInfo->cipher.symmkeyCipher)(cipherInfo->cx, dummyOut,
                                                     &len, maxLen,
                                                     cipherInfo->input.pBuf.data,
                                                     cipherInfo->input.pBuf.len);
-                
+
                 CHECKERROR(rv, __LINE__);
             }
         } else {
             int opsBetweenChecks = 0;
             TIMEMARK(cipherInfo->seconds);
-            while (! (TIMETOFINISH())) {
+            while (!(TIMETOFINISH())) {
                 int j = 0;
-                for (;j < opsBetweenChecks;j++) {
+                for (; j < opsBetweenChecks; j++) {
                     (*cipherInfo->cipher.symmkeyCipher)(
                         cipherInfo->cx, dummyOut, &len, maxLen,
                         cipherInfo->input.pBuf.data,
                         cipherInfo->input.pBuf.len);
                 }
                 cipherInfo->repetitions += j;
             }
         }
         TIMEFINISH(cipherInfo->optime, 1.0);
+    } else if (is_aeadCipher(cipherInfo->mode)) {
+        const unsigned char *input = cipherInfo->input.pBuf.data;
+        unsigned int inputLen = cipherInfo->input.pBuf.len;
+        unsigned char *output = cipherInfo->output.pBuf.data;
+        unsigned int outputLen;
+        bltestSymmKeyParams *sk = &cipherInfo->params.sk;
+        bltestAuthSymmKeyParams *ask = &cipherInfo->params.ask;
+
+        TIMESTART();
+        rv = (*cipherInfo->cipher.aeadCipher)(
+            cipherInfo->cx,
+            output, &outputLen, maxLen,
+            input, inputLen,
+            sk->iv.buf.data, sk->iv.buf.len,
+            ask->aad.buf.data, ask->aad.buf.len);
+        CHECKERROR(rv, __LINE__);
+        cipherInfo->output.pBuf.len = outputLen;
+        TIMEFINISH(cipherInfo->optime, 1.0);
+
+        cipherInfo->repetitions = 0;
+        if (cipherInfo->repetitionsToPerfom != 0) {
+            TIMESTART();
+            for (i = 0; i < cipherInfo->repetitionsToPerfom; i++,
+                cipherInfo->repetitions++) {
+                rv = (*cipherInfo->cipher.aeadCipher)(
+                    cipherInfo->cx,
+                    output, &outputLen, maxLen,
+                    input, inputLen,
+                    sk->iv.buf.data, sk->iv.buf.len,
+                    ask->aad.buf.data, ask->aad.buf.len);
+                CHECKERROR(rv, __LINE__);
+            }
+        } else {
+            int opsBetweenChecks = 0;
+            TIMEMARK(cipherInfo->seconds);
+            while (!(TIMETOFINISH())) {
+                int j = 0;
+                for (; j < opsBetweenChecks; j++) {
+                    (*cipherInfo->cipher.aeadCipher)(
+                        cipherInfo->cx,
+                        output, &outputLen, maxLen,
+                        input, inputLen,
+                        sk->iv.buf.data, sk->iv.buf.len,
+                        ask->aad.buf.data, ask->aad.buf.len);
+                }
+                cipherInfo->repetitions += j;
+            }
+        }
+        TIMEFINISH(cipherInfo->optime, 1.0);
     } else if (is_pubkeyCipher(cipherInfo->mode)) {
         TIMESTART();
         rv = (*cipherInfo->cipher.pubkeyCipher)(cipherInfo->cx,
                                                 &cipherInfo->output.pBuf,
                                                 &cipherInfo->input.pBuf);
         TIMEFINISH(cipherInfo->optime, 1.0);
         CHECKERROR(rv, __LINE__);
         cipherInfo->repetitions = 0;
         if (cipherInfo->repetitionsToPerfom != 0) {
             TIMESTART();
-            for (i=0; i<cipherInfo->repetitionsToPerfom;
+            for (i = 0; i < cipherInfo->repetitionsToPerfom;
                  i++, cipherInfo->repetitions++) {
                 SECItem dummy;
                 dummy.data = dummyOut;
                 dummy.len = maxLen;
-                (*cipherInfo->cipher.pubkeyCipher)(cipherInfo->cx, &dummy, 
+                (*cipherInfo->cipher.pubkeyCipher)(cipherInfo->cx, &dummy,
                                                    &cipherInfo->input.pBuf);
                 CHECKERROR(rv, __LINE__);
             }
         } else {
             int opsBetweenChecks = 0;
             TIMEMARK(cipherInfo->seconds);
-            while (! (TIMETOFINISH())) {
+            while (!(TIMETOFINISH())) {
                 int j = 0;
-                for (;j < opsBetweenChecks;j++) {
+                for (; j < opsBetweenChecks; j++) {
                     SECItem dummy;
                     dummy.data = dummyOut;
                     dummy.len = maxLen;
                     (*cipherInfo->cipher.pubkeyCipher)(cipherInfo->cx, &dummy,
                                                        &cipherInfo->input.pBuf);
                     CHECKERROR(rv, __LINE__);
                 }
                 cipherInfo->repetitions += j;
@@ -2417,29 +2579,29 @@ cipherDoOp(bltestCipherInfo *cipherInfo)
         rv = (*cipherInfo->cipher.hashCipher)(cipherInfo->output.pBuf.data,
                                               cipherInfo->input.pBuf.data,
                                               cipherInfo->input.pBuf.len);
         TIMEFINISH(cipherInfo->optime, 1.0);
         CHECKERROR(rv, __LINE__);
         cipherInfo->repetitions = 0;
         if (cipherInfo->repetitionsToPerfom != 0) {
             TIMESTART();
-            for (i=0; i<cipherInfo->repetitionsToPerfom;
+            for (i = 0; i < cipherInfo->repetitionsToPerfom;
                  i++, cipherInfo->repetitions++) {
                 (*cipherInfo->cipher.hashCipher)(dummyOut,
                                                  cipherInfo->input.pBuf.data,
                                                  cipherInfo->input.pBuf.len);
                 CHECKERROR(rv, __LINE__);
             }
         } else {
             int opsBetweenChecks = 0;
             TIMEMARK(cipherInfo->seconds);
-            while (! (TIMETOFINISH())) {
+            while (!(TIMETOFINISH())) {
                 int j = 0;
-                for (;j < opsBetweenChecks;j++) {
+                for (; j < opsBetweenChecks; j++) {
                     bltestIO *input = &cipherInfo->input;
                     (*cipherInfo->cipher.hashCipher)(dummyOut,
                                                      input->pBuf.data,
                                                      input->pBuf.len);
                     CHECKERROR(rv, __LINE__);
                 }
                 cipherInfo->repetitions += j;
             }
@@ -2451,83 +2613,89 @@ cipherDoOp(bltestCipherInfo *cipherInfo)
 }
 
 SECStatus
 cipherFinish(bltestCipherInfo *cipherInfo)
 {
     SECStatus rv = SECSuccess;
 
     switch (cipherInfo->mode) {
-    case bltestDES_ECB:
-    case bltestDES_CBC:
-    case bltestDES_EDE_ECB:
-    case bltestDES_EDE_CBC:
-	DES_DestroyContext((DESContext *)cipherInfo->cx, PR_TRUE);
-	break;
-    case bltestAES_GCM:
-    case bltestAES_ECB:
-    case bltestAES_CBC:
-    case bltestAES_CTS:
-    case bltestAES_CTR:
-	AES_DestroyContext((AESContext *)cipherInfo->cx, PR_TRUE);
-	break;
-    case bltestCAMELLIA_ECB:
-    case bltestCAMELLIA_CBC:
-	Camellia_DestroyContext((CamelliaContext *)cipherInfo->cx, PR_TRUE);
-	break;
-    case bltestSEED_ECB:
-    case bltestSEED_CBC:
-	SEED_DestroyContext((SEEDContext *)cipherInfo->cx, PR_TRUE);
-	break;
-    case bltestRC2_ECB:
-    case bltestRC2_CBC:
-	RC2_DestroyContext((RC2Context *)cipherInfo->cx, PR_TRUE);
-	break;
-    case bltestRC4:
-	RC4_DestroyContext((RC4Context *)cipherInfo->cx, PR_TRUE);
-	break;
+        case bltestDES_ECB:
+        case bltestDES_CBC:
+        case bltestDES_EDE_ECB:
+        case bltestDES_EDE_CBC:
+            DES_DestroyContext((DESContext *)cipherInfo->cx, PR_TRUE);
+            break;
+        case bltestAES_GCM:
+        case bltestAES_ECB:
+        case bltestAES_CBC:
+        case bltestAES_CTS:
+        case bltestAES_CTR:
+            AES_DestroyContext((AESContext *)cipherInfo->cx, PR_TRUE);
+            break;
+        case bltestCAMELLIA_ECB:
+        case bltestCAMELLIA_CBC:
+            Camellia_DestroyContext((CamelliaContext *)cipherInfo->cx, PR_TRUE);
+            break;
+        case bltestSEED_ECB:
+        case bltestSEED_CBC:
+            SEED_DestroyContext((SEEDContext *)cipherInfo->cx, PR_TRUE);
+            break;
+        case bltestCHACHA20:
+            ChaCha20Poly1305_DestroyContext((ChaCha20Poly1305Context *)
+                                                cipherInfo->cx,
+                                            PR_TRUE);
+            break;
+        case bltestRC2_ECB:
+        case bltestRC2_CBC:
+            RC2_DestroyContext((RC2Context *)cipherInfo->cx, PR_TRUE);
+            break;
+        case bltestRC4:
+            RC4_DestroyContext((RC4Context *)cipherInfo->cx, PR_TRUE);
+            break;
 #ifdef NSS_SOFTOKEN_DOES_RC5
-    case bltestRC5_ECB:
-    case bltestRC5_CBC:
-	RC5_DestroyContext((RC5Context *)cipherInfo->cx, PR_TRUE);
-	break;
+        case bltestRC5_ECB:
+        case bltestRC5_CBC:
+            RC5_DestroyContext((RC5Context *)cipherInfo->cx, PR_TRUE);
+            break;
 #endif
-    case bltestRSA:      /* keys are alloc'ed within cipherInfo's arena, */
-    case bltestRSA_PSS:  /* will be freed with it. */
-    case bltestRSA_OAEP:
-    case bltestDSA:
+        case bltestRSA:     /* keys are alloc'ed within cipherInfo's arena, */
+        case bltestRSA_PSS: /* will be freed with it. */
+        case bltestRSA_OAEP:
+        case bltestDSA:
 #ifndef NSS_DISABLE_ECC
-    case bltestECDSA:
+        case bltestECDSA:
 #endif
-    case bltestMD2: /* hash contexts are ephemeral */
-    case bltestMD5:
-    case bltestSHA1:
-    case bltestSHA224:
-    case bltestSHA256:
-    case bltestSHA384:
-    case bltestSHA512:
-	return SECSuccess;
-	break;
-    default:
-	return SECFailure;
+        case bltestMD2: /* hash contexts are ephemeral */
+        case bltestMD5:
+        case bltestSHA1:
+        case bltestSHA224:
+        case bltestSHA256:
+        case bltestSHA384:
+        case bltestSHA512:
+            return SECSuccess;
+            break;
+        default:
+            return SECFailure;
     }
     return rv;
 }
 
 void
 print_exponent(SECItem *exp)
 {
     int i;
     int e = 0;
     if (exp->len <= 4) {
-	for (i=exp->len; i >=0; --i) e |= exp->data[exp->len-i] << 8*(i-1);
-	fprintf(stdout, "%12d", e);
+        for (i = exp->len; i >= 0; --i)
+            e |= exp->data[exp->len - i] << 8 * (i - 1);
+        fprintf(stdout, "%12d", e);
     } else {
-	e = 8*exp->len;
-	fprintf(stdout, "~2**%-8d", e);
+        e = 8 * exp->len;
+        fprintf(stdout, "~2**%-8d", e);
     }
 }
 
 static void
 splitToReportUnit(PRInt64 res, int *resArr, int *del, int size)
 {
     PRInt64 remaining = res, tmp = 0;
     PRInt64 Ldel;
@@ -2536,168 +2704,166 @@ splitToReportUnit(PRInt64 res, int *resA
     while (remaining > 0 && ++i < size) {
         LL_I2L(Ldel, del[i]);
         LL_MOD(tmp, remaining, Ldel);
         LL_L2I(resArr[i], tmp);
         LL_DIV(remaining, remaining, Ldel);
     }
 }
 
-static char*
+static char *
 getHighUnitBytes(PRInt64 res)
 {
-    int spl[] = {0, 0, 0, 0};
-    int del[] = {1024, 1024, 1024, 1024};
-    char *marks[] = {"b", "Kb", "Mb", "Gb"};
+    int spl[] = { 0, 0, 0, 0 };
+    int del[] = { 1024, 1024, 1024, 1024 };
+    char *marks[] = { "b", "Kb", "Mb", "Gb" };
     int i = 3;
 
     splitToReportUnit(res, spl, del, 4);
 
-    for (;i>0;i--) {
+    for (; i > 0; i--) {
         if (spl[i] != 0) {
             break;
         }
     }
 
     return PR_smprintf("%d%s", spl[i], marks[i]);
 }
 
-
 static void
 printPR_smpString(const char *sformat, char *reportStr,
                   const char *nformat, PRInt64 rNum)
 {
     if (reportStr) {
         fprintf(stdout, sformat, reportStr);
         PR_smprintf_free(reportStr);
     } else {
         fprintf(stdout, nformat, rNum);
     }
 }
 
-static char*
+static char *
 getHighUnitOps(PRInt64 res)
 {
-    int spl[] = {0, 0, 0, 0};
-    int del[] = {1000, 1000, 1000, 1000};
-    char *marks[] = {"", "T", "M", "B"};
+    int spl[] = { 0, 0, 0, 0 };
+    int del[] = { 1000, 1000, 1000, 1000 };
+    char *marks[] = { "", "T", "M", "B" };
     int i = 3;
 
     splitToReportUnit(res, spl, del, 4);
 
-    for (;i>0;i--) {
+    for (; i > 0; i--) {
         if (spl[i] != 0) {
             break;
         }
     }
 
     return PR_smprintf("%d%s", spl[i], marks[i]);
 }
 
 void
 dump_performance_info(bltestCipherInfo *infoList, double totalTimeInt,
                       PRBool encrypt, PRBool cxonly)
 {
     bltestCipherInfo *info = infoList;
-    
+
     PRInt64 totalIn = 0;
     PRBool td = PR_TRUE;
 
-    int   repetitions = 0;
-    int   cxreps = 0;
+    int repetitions = 0;
+    int cxreps = 0;
     double cxtime = 0;
     double optime = 0;
     while (info != NULL) {
         repetitions += info->repetitions;
         cxreps += info->cxreps;
         cxtime += info->cxtime;
         optime += info->optime;
-        totalIn += (PRInt64) info->input.buf.len * (PRInt64) info->repetitions;
-        
+        totalIn += (PRInt64)info->input.buf.len * (PRInt64)info->repetitions;
+
         info = info->next;
     }
     info = infoList;
 
     fprintf(stdout, "#%9s", "mode");
     fprintf(stdout, "%12s", "in");
 print_td:
     switch (info->mode) {
-      case bltestDES_ECB:
-      case bltestDES_CBC:
-      case bltestDES_EDE_ECB:
-      case bltestDES_EDE_CBC:
-      case bltestAES_ECB:
-      case bltestAES_CBC:
-      case bltestAES_CTS:
-      case bltestAES_CTR:
-      case bltestAES_GCM:
-      case bltestCAMELLIA_ECB:
-      case bltestCAMELLIA_CBC:
-      case bltestSEED_ECB:
-      case bltestSEED_CBC:
-      case bltestRC2_ECB:
-      case bltestRC2_CBC:
-      case bltestRC4:
-          if (td)
-              fprintf(stdout, "%8s", "symmkey");
-          else
-              fprintf(stdout, "%8d", 8*info->params.sk.key.buf.len);
-          break;
+        case bltestDES_ECB:
+        case bltestDES_CBC:
+        case bltestDES_EDE_ECB:
+        case bltestDES_EDE_CBC:
+        case bltestAES_ECB:
+        case bltestAES_CBC:
+        case bltestAES_CTS:
+        case bltestAES_CTR:
+        case bltestAES_GCM:
+        case bltestCAMELLIA_ECB:
+        case bltestCAMELLIA_CBC:
+        case bltestSEED_ECB:
+        case bltestSEED_CBC:
+        case bltestRC2_ECB:
+        case bltestRC2_CBC:
+        case bltestRC4:
+            if (td)
+                fprintf(stdout, "%8s", "symmkey");
+            else
+                fprintf(stdout, "%8d", 8 * info->params.sk.key.buf.len);
+            break;
 #ifdef NSS_SOFTOKEN_DOES_RC5
-      case bltestRC5_ECB:
-      case bltestRC5_CBC:
-          if (info->params.sk.key.buf.len > 0)
-              printf("symmetric key(bytes)=%d,", info->params.sk.key.buf.len);
-          if (info->rounds > 0)
-              printf("rounds=%d,", info->params.rc5.rounds);
-          if (info->wordsize > 0)
-              printf("wordsize(bytes)=%d,", info->params.rc5.wordsize);
-          break;
+        case bltestRC5_ECB:
+        case bltestRC5_CBC:
+            if (info->params.sk.key.buf.len > 0)
+                printf("symmetric key(bytes)=%d,", info->params.sk.key.buf.len);
+            if (info->rounds > 0)
+                printf("rounds=%d,", info->params.rc5.rounds);
+            if (info->wordsize > 0)
+                printf("wordsize(bytes)=%d,", info->params.rc5.wordsize);
+            break;
 #endif
-      case bltestRSA:
-      case bltestRSA_PSS:
-      case bltestRSA_OAEP:
-          if (td) {
-              fprintf(stdout, "%8s", "rsa_mod");
-              fprintf(stdout, "%12s", "rsa_pe");
-          } else {
-              bltestAsymKeyParams *asymk = &info->params.asymk;
-              fprintf(stdout, "%8d", asymk->cipherParams.rsa.keysizeInBits);
-              print_exponent(
-                  &((RSAPrivateKey *)asymk->privKey)->publicExponent);
-          }
-          break;
-      case bltestDSA:
-          if (td) {
-              fprintf(stdout, "%8s", "pqg_mod");
-          } else {
-              fprintf(stdout, "%8d", info->params.asymk.cipherParams.dsa.keysize);
-          }
-          break;
+        case bltestRSA:
+        case bltestRSA_PSS:
+        case bltestRSA_OAEP:
+            if (td) {
+                fprintf(stdout, "%8s", "rsa_mod");
+                fprintf(stdout, "%12s", "rsa_pe");
+            } else {
+                bltestAsymKeyParams *asymk = &info->params.asymk;
+                fprintf(stdout, "%8d", asymk->cipherParams.rsa.keysizeInBits);
+                print_exponent(
+                    &((RSAPrivateKey *)asymk->privKey)->publicExponent);
+            }
+            break;
+        case bltestDSA:
+            if (td) {
+                fprintf(stdout, "%8s", "pqg_mod");
+            } else {
+                fprintf(stdout, "%8d", info->params.asymk.cipherParams.dsa.keysize);
+            }
+            break;
 #ifndef NSS_DISABLE_ECC
-      case bltestECDSA:
-          if (td) {
-              fprintf(stdout, "%12s", "ec_curve");
-          } else {
-              ECPrivateKey *key = (ECPrivateKey*)info->params.asymk.privKey;
-              ECCurveName curveName = key->ecParams.name;
-              fprintf(stdout, "%12s",
-                      ecCurve_map[curveName]? ecCurve_map[curveName]->text:
-                      "Unsupported curve");
-          }
-          break;
+        case bltestECDSA:
+            if (td) {
+                fprintf(stdout, "%12s", "ec_curve");
+            } else {
+                ECPrivateKey *key = (ECPrivateKey *)info->params.asymk.privKey;
+                ECCurveName curveName = key->ecParams.name;
+                fprintf(stdout, "%12s",
+                        ecCurve_map[curveName] ? ecCurve_map[curveName]->text : "Unsupported curve");
+            }
+            break;
 #endif
-      case bltestMD2:
-      case bltestMD5:
-      case bltestSHA1:
-      case bltestSHA256:
-      case bltestSHA384:
-      case bltestSHA512:
-      default:
-          break;
+        case bltestMD2:
+        case bltestMD5:
+        case bltestSHA1:
+        case bltestSHA256:
+        case bltestSHA384:
+        case bltestSHA512:
+        default:
+            break;
     }
     if (!td) {
         PRInt64 totalThroughPut;
 
         printPR_smpString("%8s", getHighUnitOps(repetitions),
                           "%8d", repetitions);
 
         printPR_smpString("%8s", getHighUnitOps(cxreps), "%8d", cxreps);
@@ -2708,293 +2874,306 @@ print_td:
 
         totalThroughPut = (PRInt64)(totalIn / totalTimeInt * 1000);
         printPR_smpString("%12s", getHighUnitBytes(totalThroughPut),
                           "%12d", totalThroughPut);
 
         fprintf(stdout, "\n");
         return;
     }
-    
+
     fprintf(stdout, "%8s", "opreps");
     fprintf(stdout, "%8s", "cxreps");
     fprintf(stdout, "%12s", "context");
     fprintf(stdout, "%12s", "op");
     fprintf(stdout, "%12s", "time(sec)");
     fprintf(stdout, "%12s", "thrgput");
     fprintf(stdout, "\n");
     fprintf(stdout, "%8s", mode_strings[info->mode]);
     fprintf(stdout, "_%c", (cxonly) ? 'c' : (encrypt) ? 'e' : 'd');
     printPR_smpString("%12s", getHighUnitBytes(totalIn), "%12d", totalIn);
-    
+
     td = !td;
     goto print_td;
 }
 
 void
 printmodes()
 {
     bltestCipherMode mode;
     int nummodes = sizeof(mode_strings) / sizeof(char *);
     fprintf(stderr, "%s: Available modes (specify with -m):\n", progName);
-    for (mode=0; mode<nummodes; mode++)
-	fprintf(stderr, "%s\n", mode_strings[mode]);
+    for (mode = 0; mode < nummodes; mode++)
+        fprintf(stderr, "%s\n", mode_strings[mode]);
 }
 
 bltestCipherMode
 get_mode(const char *modestring)
 {
     bltestCipherMode mode;
     int nummodes = sizeof(mode_strings) / sizeof(char *);
-    for (mode=0; mode<nummodes; mode++)
-	if (PL_strcmp(modestring, mode_strings[mode]) == 0)
-	    return mode;
+    for (mode = 0; mode < nummodes; mode++)
+        if (PL_strcmp(modestring, mode_strings[mode]) == 0)
+            return mode;
     fprintf(stderr, "%s: invalid mode: %s\n", progName, modestring);
     return bltestINVALID;
 }
 
 void
 load_file_data(PLArenaPool *arena, bltestIO *data,
-	       char *fn, bltestIOMode ioMode)
+               char *fn, bltestIOMode ioMode)
 {
     PRFileDesc *file;
     data->mode = ioMode;
     data->file = NULL; /* don't use -- not saving anything */
     data->pBuf.data = NULL;
     data->pBuf.len = 0;
     file = PR_Open(fn, PR_RDONLY, 00660);
     if (file) {
-	setupIO(arena, data, file, NULL, 0);
-	PR_Close(file);
+        setupIO(arena, data, file, NULL, 0);
+        PR_Close(file);
     }
 }
 
 HASH_HashType
 mode_str_to_hash_alg(const SECItem *modeStr)
 {
     bltestCipherMode mode;
-    char* tempModeStr = NULL;
+    char *tempModeStr = NULL;
     if (!modeStr || modeStr->len == 0)
         return HASH_AlgNULL;
     tempModeStr = PORT_Alloc(modeStr->len + 1);
     if (!tempModeStr)
         return HASH_AlgNULL;
     memcpy(tempModeStr, modeStr->data, modeStr->len);
     tempModeStr[modeStr->len] = '\0';
     mode = get_mode(tempModeStr);
     PORT_Free(tempModeStr);
     switch (mode) {
-        case bltestMD2:    return HASH_AlgMD2;
-        case bltestMD5:    return HASH_AlgMD5;
-        case bltestSHA1:   return HASH_AlgSHA1;
-        case bltestSHA224: return HASH_AlgSHA224;
-        case bltestSHA256: return HASH_AlgSHA256;
-        case bltestSHA384: return HASH_AlgSHA384;
-        case bltestSHA512: return HASH_AlgSHA512;
-        default: return HASH_AlgNULL;
+        case bltestMD2:
+            return HASH_AlgMD2;
+        case bltestMD5:
+            return HASH_AlgMD5;
+        case bltestSHA1:
+            return HASH_AlgSHA1;
+        case bltestSHA224:
+            return HASH_AlgSHA224;
+        case bltestSHA256:
+            return HASH_AlgSHA256;
+        case bltestSHA384:
+            return HASH_AlgSHA384;
+        case bltestSHA512:
+            return HASH_AlgSHA512;
+        default:
+            return HASH_AlgNULL;
     }
 }
 
 void
 get_params(PLArenaPool *arena, bltestParams *params,
-	   bltestCipherMode mode, int j)
+           bltestCipherMode mode, int j)
 {
     char filename[256];
     char *modestr = mode_strings[mode];
     bltestIO tempIO;
 
 #ifdef NSS_SOFTOKEN_DOES_RC5
     FILE *file;
     char *mark, *param, *val;
     int index = 0;
 #endif
     switch (mode) {
-    case bltestAES_GCM:
-	sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "aad", j);
-	load_file_data(arena, &params->ask.aad, filename, bltestBinary);
-    case bltestDES_CBC:
-    case bltestDES_EDE_CBC:
-    case bltestRC2_CBC:
-    case bltestAES_CBC:
-    case bltestAES_CTS:
-    case bltestAES_CTR:
-    case bltestCAMELLIA_CBC:
-    case bltestSEED_CBC: 
-	sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "iv", j);
-	load_file_data(arena, &params->sk.iv, filename, bltestBinary);
-    case bltestDES_ECB:
-    case bltestDES_EDE_ECB:
-    case bltestRC2_ECB:
-    case bltestRC4:
-    case bltestAES_ECB:
-    case bltestCAMELLIA_ECB:
-    case bltestSEED_ECB:
-	sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "key", j);
-	load_file_data(arena, &params->sk.key, filename, bltestBinary);
-	break;
+        case bltestAES_GCM:
+        case bltestCHACHA20:
+            sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "aad", j);
+            load_file_data(arena, &params->ask.aad, filename, bltestBinary);
+        case bltestDES_CBC:
+        case bltestDES_EDE_CBC:
+        case bltestRC2_CBC:
+        case bltestAES_CBC:
+        case bltestAES_CTS:
+        case bltestAES_CTR:
+        case bltestCAMELLIA_CBC:
+        case bltestSEED_CBC:
+            sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "iv", j);
+            load_file_data(arena, &params->sk.iv, filename, bltestBinary);
+        case bltestDES_ECB:
+        case bltestDES_EDE_ECB:
+        case bltestRC2_ECB:
+        case bltestRC4:
+        case bltestAES_ECB:
+        case bltestCAMELLIA_ECB:
+        case bltestSEED_ECB:
+            sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "key", j);
+            load_file_data(arena, &params->sk.key, filename, bltestBinary);
+            break;
 #ifdef NSS_SOFTOKEN_DOES_RC5
-    case bltestRC5_ECB:
-    case bltestRC5_CBC:
-	sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "iv", j);
-	load_file_data(arena, &params->sk.iv, filename, bltestBinary);
-	sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "key", j);
-	load_file_data(arena, &params->sk.key, filename, bltestBinary);
-	    sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr,
-			      "params", j);
-	file = fopen(filename, "r");
-	if (!file) return;
-	param = malloc(100);
-	len = fread(param, 1, 100, file);
-	while (index < len) {
-	    mark = PL_strchr(param, '=');
-	    *mark = '\0';
-	    val = mark + 1;
-	    mark = PL_strchr(val, '\n');
-	    *mark = '\0';
-	    if (PL_strcmp(param, "rounds") == 0) {
-		params->rc5.rounds = atoi(val);
-	    } else if (PL_strcmp(param, "wordsize") == 0) {
-		params->rc5.wordsize = atoi(val);
-	    }
-	    index += PL_strlen(param) + PL_strlen(val) + 2;
-	    param = mark + 1;
-	}
-	break;
+        case bltestRC5_ECB:
+        case bltestRC5_CBC:
+            sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "iv", j);
+            load_file_data(arena, &params->sk.iv, filename, bltestBinary);
+            sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "key", j);
+            load_file_data(arena, &params->sk.key, filename, bltestBinary);
+            sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr,
+                    "params", j);
+            file = fopen(filename, "r");
+            if (!file)
+                return;
+            param = malloc(100);
+            len = fread(param, 1, 100, file);
+            while (index < len) {
+                mark = PL_strchr(param, '=');
+                *mark = '\0';
+                val = mark + 1;
+                mark = PL_strchr(val, '\n');
+                *mark = '\0';
+                if (PL_strcmp(param, "rounds") == 0) {
+                    params->rc5.rounds = atoi(val);
+                } else if (PL_strcmp(param, "wordsize") == 0) {
+                    params->rc5.wordsize = atoi(val);
+                }
+                index += PL_strlen(param) + PL_strlen(val) + 2;
+                param = mark + 1;
+            }
+            break;
 #endif
-    case bltestRSA_PSS:
-	sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "ciphertext", j);
-	load_file_data(arena, &params->asymk.sig, filename, bltestBase64Encoded);
-	/* fall through */
-    case bltestRSA_OAEP:
-	sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "seed", j);
-	load_file_data(arena, &params->asymk.cipherParams.rsa.seed,
-	               filename, bltestBase64Encoded);
-
-	sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "hash", j);
-	load_file_data(arena, &tempIO, filename, bltestBinary);
-	params->asymk.cipherParams.rsa.hashAlg =
-	    mode_str_to_hash_alg(&tempIO.buf);
-
-	sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "maskhash", j);
-	load_file_data(arena, &tempIO, filename, bltestBinary);
-	params->asymk.cipherParams.rsa.maskHashAlg =
-	    mode_str_to_hash_alg(&tempIO.buf);
-	/* fall through */
-    case bltestRSA:
-	sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "key", j);
-	load_file_data(arena, &params->asymk.key, filename,
-	               bltestBase64Encoded);
-	params->asymk.privKey =
-	    (void *)rsakey_from_filedata(&params->asymk.key.buf);
-	break;
-    case bltestDSA:
-	sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "key", j);
-	load_file_data(arena, &params->asymk.key, filename, bltestBase64Encoded);
-	params->asymk.privKey =
-	     (void *)dsakey_from_filedata(&params->asymk.key.buf);
-	sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "pqg", j);
-	load_file_data(arena, &params->asymk.cipherParams.dsa.pqgdata, filename,
-	               bltestBase64Encoded);
-	params->asymk.cipherParams.dsa.pqg =
-	      pqg_from_filedata(&params->asymk.cipherParams.dsa.pqgdata.buf);
-	sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "keyseed", j);
-	load_file_data(arena, &params->asymk.cipherParams.dsa.keyseed, filename,
-	               bltestBase64Encoded);
-	sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "sigseed", j);
-	load_file_data(arena, &params->asymk.cipherParams.dsa.sigseed, filename,
-	               bltestBase64Encoded);
-	sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "ciphertext",j);
-	load_file_data(arena, &params->asymk.sig, filename, bltestBase64Encoded);
-	break;
+        case bltestRSA_PSS:
+            sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "ciphertext", j);
+            load_file_data(arena, &params->asymk.sig, filename, bltestBase64Encoded);
+        /* fall through */
+        case bltestRSA_OAEP:
+            sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "seed", j);
+            load_file_data(arena, &params->asymk.cipherParams.rsa.seed,
+                           filename, bltestBase64Encoded);
+
+            sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "hash", j);
+            load_file_data(arena, &tempIO, filename, bltestBinary);
+            params->asymk.cipherParams.rsa.hashAlg =
+                mode_str_to_hash_alg(&tempIO.buf);
+
+            sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "maskhash", j);
+            load_file_data(arena, &tempIO, filename, bltestBinary);
+            params->asymk.cipherParams.rsa.maskHashAlg =
+                mode_str_to_hash_alg(&tempIO.buf);
+        /* fall through */
+        case bltestRSA:
+            sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "key", j);
+            load_file_data(arena, &params->asymk.key, filename,
+                           bltestBase64Encoded);
+            params->asymk.privKey =
+                (void *)rsakey_from_filedata(arena, &params->asymk.key.buf);
+            break;
+        case bltestDSA:
+            sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "key", j);
+            load_file_data(arena, &params->asymk.key, filename, bltestBase64Encoded);
+            params->asymk.privKey =
+                (void *)dsakey_from_filedata(arena, &params->asymk.key.buf);
+            sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "pqg", j);
+            load_file_data(arena, &params->asymk.cipherParams.dsa.pqgdata, filename,
+                           bltestBase64Encoded);
+            params->asymk.cipherParams.dsa.pqg =
+                pqg_from_filedata(arena, &params->asymk.cipherParams.dsa.pqgdata.buf);
+            sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "keyseed", j);
+            load_file_data(arena, &params->asymk.cipherParams.dsa.keyseed, filename,
+                           bltestBase64Encoded);
+            sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "sigseed", j);
+            load_file_data(arena, &params->asymk.cipherParams.dsa.sigseed, filename,
+                           bltestBase64Encoded);
+            sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "ciphertext", j);
+            load_file_data(arena, &params->asymk.sig, filename, bltestBase64Encoded);
+            break;
 #ifndef NSS_DISABLE_ECC
-    case bltestECDSA:
-	sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "key", j);
-	load_file_data(arena, &params->asymk.key, filename, bltestBase64Encoded);
-	params->asymk.privKey =
-	      (void *)eckey_from_filedata(&params->asymk.key.buf);
-	sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "sigseed", j);
-	load_file_data(arena, &params->asymk.cipherParams.ecdsa.sigseed,
-	               filename, bltestBase64Encoded);
-	sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "ciphertext",j);
-	load_file_data(arena, &params->asymk.sig, filename, bltestBase64Encoded);
-	break;
+        case bltestECDSA:
+            sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "key", j);
+            load_file_data(arena, &params->asymk.key, filename, bltestBase64Encoded);
+            params->asymk.privKey =
+                (void *)eckey_from_filedata(arena, &params->asymk.key.buf);
+            sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "sigseed", j);
+            load_file_data(arena, &params->asymk.cipherParams.ecdsa.sigseed,
+                           filename, bltestBase64Encoded);
+            sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "ciphertext", j);
+            load_file_data(arena, &params->asymk.sig, filename, bltestBase64Encoded);
+            break;
 #endif
-    case bltestMD2:
-    case bltestMD5:
-    case bltestSHA1:
-    case bltestSHA224:
-    case bltestSHA256:
-    case bltestSHA384:
-    case bltestSHA512:
-	/*params->hash.restart = PR_TRUE;*/
-	params->hash.restart = PR_FALSE;
-	break;
-    default:
-	break;
+        case bltestMD2:
+        case bltestMD5:
+        case bltestSHA1:
+        case bltestSHA224:
+        case bltestSHA256:
+        case bltestSHA384:
+        case bltestSHA512:
+            /*params->hash.restart = PR_TRUE;*/
+            params->hash.restart = PR_FALSE;
+            break;
+        default:
+            break;
     }
 }
 
 SECStatus
 verify_self_test(bltestIO *result, bltestIO *cmp, bltestCipherMode mode,
-		 PRBool forward, SECStatus sigstatus)
+                 PRBool forward, SECStatus sigstatus)
 {
     PRBool equal;
     char *modestr = mode_strings[mode];
     equal = SECITEM_ItemsAreEqual(&result->pBuf, &cmp->buf);
     if (is_sigCipher(mode)) {
-	if (forward) {
-	    if (equal) {
-		printf("Signature self-test for %s passed.\n", modestr);
-	    } else {
-		printf("Signature self-test for %s failed!\n", modestr);
-	    }
-	    return equal ? SECSuccess : SECFailure;
-	} else {
-	    if (sigstatus == SECSuccess) {
-		printf("Verification self-test for %s passed.\n", modestr);
-	    } else {
-		printf("Verification self-test for %s failed!\n", modestr);
-	    }
-	    return sigstatus;
-	}
+        if (forward) {
+            if (equal) {
+                printf("Signature self-test for %s passed.\n", modestr);
+            } else {
+                printf("Signature self-test for %s failed!\n", modestr);
+            }
+            return equal ? SECSuccess : SECFailure;
+        } else {
+            if (sigstatus == SECSuccess) {
+                printf("Verification self-test for %s passed.\n", modestr);
+            } else {
+                printf("Verification self-test for %s failed!\n", modestr);
+            }
+            return sigstatus;
+        }
     } else if (is_hashCipher(mode)) {
-	if (equal) {
-	    printf("Hash self-test for %s passed.\n", modestr);
-	} else {
-	    printf("Hash self-test for %s failed!\n", modestr);
-	}
+        if (equal) {
+            printf("Hash self-test for %s passed.\n", modestr);
+        } else {
+            printf("Hash self-test for %s failed!\n", modestr);
+        }
     } else {
-	if (forward) {
-	    if (equal) {
-		printf("Encryption self-test for %s passed.\n", modestr);
-	    } else {
-		printf("Encryption self-test for %s failed!\n", modestr);
-	    }
-	} else {
-	    if (equal) {
-		printf("Decryption self-test for %s passed.\n", modestr);
-	    } else {
-		printf("Decryption self-test for %s failed!\n", modestr);
-	    }
-	}
+        if (forward) {
+            if (equal) {
+                printf("Encryption self-test for %s passed.\n", modestr);
+            } else {
+                printf("Encryption self-test for %s failed!\n", modestr);
+            }
+        } else {
+            if (equal) {
+                printf("Decryption self-test for %s passed.\n", modestr);
+            } else {
+                printf("Decryption self-test for %s failed!\n", modestr);
+            }
+        }
     }
     return equal ? SECSuccess : SECFailure;
 }
 
 static SECStatus
-ReadFileToItem(SECItem *dst, const char *filename)
+ReadFileToItem(PLArenaPool *arena, SECItem *dst, const char *filename)
 {
+    SECItem tmp = { siBuffer, NULL, 0 };
     PRFileDesc *file;
     SECStatus rv;
 
     file = PR_Open(filename, PR_RDONLY, 00660);
     if (!file) {
-	return SECFailure;
+        return SECFailure;
     }
-    rv = SECU_FileToItem(dst, file);
+    rv = SECU_FileToItem(&tmp, file);
+    rv |= SECITEM_CopyItem(arena, dst, &tmp);
+    SECITEM_FreeItem(&tmp, PR_FALSE);
     PR_Close(file);
     return rv;
 }
 
 static SECStatus
 blapi_selftest(bltestCipherMode *modes, int numModes, int inoff, int outoff,
                PRBool encrypt, PRBool decrypt)
 {
@@ -3009,164 +3188,170 @@ blapi_selftest(bltestCipherMode *modes, 
     SECItem item;
     SECStatus rv = SECSuccess, srv;
 
     PORT_Memset(&cipherInfo, 0, sizeof(cipherInfo));
     arena = PORT_NewArena(BLTEST_DEFAULT_CHUNKSIZE);
     cipherInfo.arena = arena;
 
     nummodes = (numModes == 0) ? NUMMODES : numModes;
-    for (i=0; i < nummodes; i++) {
-	if (numModes > 0)
-	    mode = modes[i];
-	else
-	    mode = i;
-	if (mode == bltestINVALID) {
-	    fprintf(stderr, "%s: Skipping invalid mode.\n",progName);
-	    continue;
-	}
-	modestr = mode_strings[mode];
-	cipherInfo.mode = mode;
-	params = &cipherInfo.params;
-	/* get the number of tests in the directory */
-	sprintf(filename, "%s/tests/%s/%s", testdir, modestr, "numtests");
-	if (ReadFileToItem(&item, filename) != SECSuccess) {
-	    fprintf(stderr, "%s: Cannot read file %s.\n", progName, filename);
-	    rv = SECFailure;
-	    continue;
-	}
-	/* loop over the tests in the directory */
-	numtests = 0;
-	for (j=0; j<item.len; j++) {
-	    if (!isdigit(item.data[j])) {
-		break;
-	    }
-	    numtests *= 10;
-	    numtests += (int) (item.data[j] - '0');
-	}
-	for (j=0; j<numtests; j++) {
-	    sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr,
-	            "plaintext", j);
-	    load_file_data(arena, &pt, filename,
-	                   is_sigCipher(mode) ? bltestBase64Encoded
-	                                      : bltestBinary);
-	    sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr,
-	            "ciphertext", j);
-	    load_file_data(arena, &ct, filename, bltestBase64Encoded);
-
-	    get_params(arena, params, mode, j);
-	    /* Forward Operation (Encrypt/Sign/Hash)
-	    ** Align the input buffer (plaintext) according to request
-	    ** then perform operation and compare to ciphertext
-	    */
-	    if (encrypt) {
-		bltestCopyIO(arena, &cipherInfo.input, &pt);
-		misalignBuffer(arena, &cipherInfo.input, inoff);
-		memset(&cipherInfo.output.buf, 0, sizeof cipherInfo.output.buf);
-		rv |= cipherInit(&cipherInfo, PR_TRUE);
-		misalignBuffer(arena, &cipherInfo.output, outoff);
-		rv |= cipherDoOp(&cipherInfo);
-		rv |= cipherFinish(&cipherInfo);
-		rv |= verify_self_test(&cipherInfo.output, 
-		                       &ct, mode, PR_TRUE, SECSuccess);
-		/* If testing hash, only one op to test */
-		if (is_hashCipher(mode))
-		    continue;
-		if (is_sigCipher(mode)) {
-		    /* Verify operations support detached signature files. For
-		    ** consistency between tests that run Sign/Verify back to
-		    ** back (eg: self-tests) and tests that are only running
-		    ** verify operations, copy the output into the sig buf,
-		    ** and then copy the sig buf back out when verifying. For
-		    ** self-tests, this is unnecessary copying, but for
-		    ** verify-only operations, this ensures that the output
-		    ** buffer is properly configured
-		    */
-		    bltestCopyIO(arena, &params->asymk.sig, &cipherInfo.output);
-		}
-	    }
-	    if (!decrypt)
-		continue;
-	    /* Reverse Operation (Decrypt/Verify)
-	    ** Align the input buffer (ciphertext) according to request
-	    ** then perform operation and compare to plaintext
-	    */
-	    if (is_sigCipher(mode)) {
-		bltestCopyIO(arena, &cipherInfo.input, &pt);
-		bltestCopyIO(arena, &cipherInfo.output, &params->asymk.sig);
-	    } else {
-		bltestCopyIO(arena, &cipherInfo.input, &ct);
-		memset(&cipherInfo.output.buf, 0, sizeof cipherInfo.output.buf);
-	    }
-	    misalignBuffer(arena, &cipherInfo.input, inoff);
-	    rv |= cipherInit(&cipherInfo, PR_FALSE);
-	    misalignBuffer(arena, &cipherInfo.output, outoff);
-	    srv = SECSuccess;
-	    srv |= cipherDoOp(&cipherInfo);
-	    rv |= cipherFinish(&cipherInfo);
-	    rv |= verify_self_test(&cipherInfo.output, 
-	                           &pt, mode, PR_FALSE, srv);
-	}
+    for (i = 0; i < nummodes; i++) {
+        if (numModes > 0)
+            mode = modes[i];
+        else
+            mode = i;
+        if (mode == bltestINVALID) {
+            fprintf(stderr, "%s: Skipping invalid mode.\n", progName);
+            continue;
+        }
+        modestr = mode_strings[mode];
+        cipherInfo.mode = mode;
+        params = &cipherInfo.params;
+        /* get the number of tests in the directory */
+        sprintf(filename, "%s/tests/%s/%s", testdir, modestr, "numtests");
+        if (ReadFileToItem(arena, &item, filename) != SECSuccess) {
+            fprintf(stderr, "%s: Cannot read file %s.\n", progName, filename);
+            rv = SECFailure;
+            continue;
+        }
+        /* loop over the tests in the directory */
+        numtests = 0;
+        for (j = 0; j < item.len; j++) {
+            if (!isdigit(item.data[j])) {
+                break;
+            }
+            numtests *= 10;
+            numtests += (int)(item.data[j] - '0');
+        }
+        for (j = 0; j < numtests; j++) {
+            sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr,
+                    "plaintext", j);
+            load_file_data(arena, &pt, filename,
+                           is_sigCipher(mode) ? bltestBase64Encoded
+                                              : bltestBinary);
+            sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr,
+                    "ciphertext", j);
+            load_file_data(arena, &ct, filename, bltestBase64Encoded);
+
+            get_params(arena, params, mode, j);
+            /* Forward Operation (Encrypt/Sign/Hash)
+            ** Align the input buffer (plaintext) according to request
+            ** then perform operation and compare to ciphertext
+            */
+            if (encrypt) {
+                rv |= bltestCopyIO(arena, &cipherInfo.input, &pt);
+                misalignBuffer(arena, &cipherInfo.input, inoff);
+                memset(&cipherInfo.output.buf, 0, sizeof cipherInfo.output.buf);
+                rv |= cipherInit(&cipherInfo, PR_TRUE);
+                misalignBuffer(arena, &cipherInfo.output, outoff);
+                rv |= cipherDoOp(&cipherInfo);
+                rv |= cipherFinish(&cipherInfo);
+                rv |= verify_self_test(&cipherInfo.output,
+                                       &ct, mode, PR_TRUE, SECSuccess);
+                /* If testing hash, only one op to test */
+                if (is_hashCipher(mode))
+                    continue;
+                if (is_sigCipher(mode)) {
+                    /* Verify operations support detached signature files. For
+                    ** consistency between tests that run Sign/Verify back to
+                    ** back (eg: self-tests) and tests that are only running
+                    ** verify operations, copy the output into the sig buf,
+                    ** and then copy the sig buf back out when verifying. For
+                    ** self-tests, this is unnecessary copying, but for
+                    ** verify-only operations, this ensures that the output
+                    ** buffer is properly configured
+                    */
+                    rv |= bltestCopyIO(arena, &params->asymk.sig, &cipherInfo.output);
+                }
+            }
+            if (!decrypt)
+                continue;
+            /* Reverse Operation (Decrypt/Verify)
+            ** Align the input buffer (ciphertext) according to request
+            ** then perform operation and compare to plaintext
+            */
+            if (is_sigCipher(mode)) {
+                rv |= bltestCopyIO(arena, &cipherInfo.input, &pt);
+                rv |= bltestCopyIO(arena, &cipherInfo.output, &params->asymk.sig);
+            } else {
+                rv |= bltestCopyIO(arena, &cipherInfo.input, &ct);
+                memset(&cipherInfo.output.buf, 0, sizeof cipherInfo.output.buf);
+            }
+            misalignBuffer(arena, &cipherInfo.input, inoff);
+            rv |= cipherInit(&cipherInfo, PR_FALSE);
+            misalignBuffer(arena, &cipherInfo.output, outoff);
+            srv = SECSuccess;
+            srv |= cipherDoOp(&cipherInfo);
+            rv |= cipherFinish(&cipherInfo);
+            rv |= verify_self_test(&cipherInfo.output,
+                                   &pt, mode, PR_FALSE, srv);
+        }
     }
+    PORT_FreeArena(arena, PR_FALSE);
     return rv;
 }
 
 SECStatus
 dump_file(bltestCipherMode mode, char *filename)
 {
     bltestIO keydata;
     PLArenaPool *arena = NULL;
     arena = PORT_NewArena(BLTEST_DEFAULT_CHUNKSIZE);
+    if (!arena) {
+        return SECFailure;
+    }
     if (mode == bltestRSA || mode == bltestRSA_PSS || mode == bltestRSA_OAEP) {
-	RSAPrivateKey *key;
-	load_file_data(arena, &keydata, filename, bltestBase64Encoded);
-	key = rsakey_from_filedata(&keydata.buf);
-	dump_rsakey(key);
+        RSAPrivateKey *key;
+        load_file_data(arena, &keydata, filename, bltestBase64Encoded);
+        key = rsakey_from_filedata(arena, &keydata.buf);
+        dump_rsakey(key);
     } else if (mode == bltestDSA) {
 #if 0
-	PQGParams *pqg;
-	get_file_data(filename, &item, PR_TRUE);
-	pqg = pqg_from_filedata(&item);
-	dump_pqg(pqg);
+    PQGParams *pqg;
+    get_file_data(filename, &item, PR_TRUE);
+    pqg = pqg_from_filedata(&item);
+    dump_pqg(pqg);
 #endif
-	DSAPrivateKey *key;
-	load_file_data(arena, &keydata, filename, bltestBase64Encoded);
-	key = dsakey_from_filedata(&keydata.buf);
-	dump_dsakey(key);
+        DSAPrivateKey *key;
+        load_file_data(arena, &keydata, filename, bltestBase64Encoded);
+        key = dsakey_from_filedata(arena, &keydata.buf);
+        dump_dsakey(key);
 #ifndef NSS_DISABLE_ECC
     } else if (mode == bltestECDSA) {
-	ECPrivateKey *key;
-	load_file_data(arena, &keydata, filename, bltestBase64Encoded);
-	key = eckey_from_filedata(&keydata.buf);
-	dump_eckey(key);
+        ECPrivateKey *key;
+        load_file_data(arena, &keydata, filename, bltestBase64Encoded);
+        key = eckey_from_filedata(arena, &keydata.buf);
+        dump_eckey(key);
 #endif
     }
     PORT_FreeArena(arena, PR_FALSE);
     return SECFailure;
 }
 
-void ThreadExecTest(void *data)
+void
+ThreadExecTest(void *data)
 {
-    bltestCipherInfo *cipherInfo = (bltestCipherInfo*)data;
+    bltestCipherInfo *cipherInfo = (bltestCipherInfo *)data;
 
     if (cipherInfo->mCarlo == PR_TRUE) {
         int mciter;
-        for (mciter=0; mciter<10000; mciter++) {
+        for (mciter = 0; mciter < 10000; mciter++) {
             cipherDoOp(cipherInfo);
             memcpy(cipherInfo->input.buf.data,
                    cipherInfo->output.buf.data,
                    cipherInfo->input.buf.len);
         }
     } else {
         cipherDoOp(cipherInfo);
     }
     cipherFinish(cipherInfo);
 }
 
-static void rsaPrivKeyReset(RSAPrivateKey *tstKey)
+static void
+rsaPrivKeyReset(RSAPrivateKey *tstKey)
 {
     PLArenaPool *arena;
 
     tstKey->version.data = NULL;
     tstKey->version.len = 0;
     tstKey->modulus.data = NULL;
     tstKey->modulus.len = 0;
     tstKey->publicExponent.data = NULL;
@@ -3182,176 +3367,174 @@ static void rsaPrivKeyReset(RSAPrivateKe
     tstKey->exponent2.data = NULL;
     tstKey->exponent2.len = 0;
     tstKey->coefficient.data = NULL;
     tstKey->coefficient.len = 0;
 
     arena = tstKey->arena;
     tstKey->arena = NULL;
     if (arena) {
-	PORT_FreeArena(arena, PR_TRUE);
+        PORT_FreeArena(arena, PR_TRUE);
     }
 }
 
-
-#define RSA_TEST_EQUAL(comp) \
-    if (!SECITEM_ItemsAreEqual(&(src->comp),&(dest->comp))) { \
-	fprintf(stderr, "key->" #comp " not equal"); \
-	if (src->comp.len != dest->comp.len) { \
-	    fprintf(stderr, "src_len = %d, dest_len = %d",  \
-					src->comp.len, dest->comp.len); \
-	} \
-	fprintf(stderr, "\n"); \
-	areEqual = PR_FALSE; \
+#define RSA_TEST_EQUAL(comp)                                   \
+    if (!SECITEM_ItemsAreEqual(&(src->comp), &(dest->comp))) { \
+        fprintf(stderr, "key->" #comp " not equal");           \
+        if (src->comp.len != dest->comp.len) {                 \
+            fprintf(stderr, "src_len = %d, dest_len = %d",     \
+                    src->comp.len, dest->comp.len);            \
+        }                                                      \
+        fprintf(stderr, "\n");                                 \
+        areEqual = PR_FALSE;                                   \
     }
-	    
-
-static PRBool rsaPrivKeysAreEqual(RSAPrivateKey *src, RSAPrivateKey *dest)
+
+static PRBool
+rsaPrivKeysAreEqual(RSAPrivateKey *src, RSAPrivateKey *dest)
 {
     PRBool areEqual = PR_TRUE;
     RSA_TEST_EQUAL(modulus)
     RSA_TEST_EQUAL(publicExponent)
     RSA_TEST_EQUAL(privateExponent)
     RSA_TEST_EQUAL(prime1)
     RSA_TEST_EQUAL(prime2)
     RSA_TEST_EQUAL(exponent1)
     RSA_TEST_EQUAL(exponent2)
     RSA_TEST_EQUAL(coefficient)
     if (!areEqual) {
-	fprintf(stderr, "original key:\n");
-	dump_rsakey(src);
-	fprintf(stderr, "recreated key:\n");
-	dump_rsakey(dest);
+        fprintf(stderr, "original key:\n");
+        dump_rsakey(src);
+        fprintf(stderr, "recreated key:\n");
+        dump_rsakey(dest);
     }
     return areEqual;
 }
 
 /*
  * Test the RSA populate command to see that it can really build
  * keys from it's components.
  */
-static int doRSAPopulateTest(unsigned int keySize, unsigned long exponent)
+static int
+doRSAPopulateTest(unsigned int keySize, unsigned long exponent)
 {
     RSAPrivateKey *srcKey;
     RSAPrivateKey tstKey = { 0 };
     SECItem expitem = { 0, 0, 0 };
     SECStatus rv;
     unsigned char pubExp[4];
     int expLen = 0;
     int failed = 0;
     int i;
 
-    for (i=0; i < sizeof(unsigned long); i++) {
-	int shift = (sizeof(unsigned long) - i -1 ) * 8;
-	if (expLen || (exponent && ((unsigned long)0xffL << shift))) {
-	    pubExp[expLen] = (unsigned char) ((exponent >> shift) & 0xff);
-	    expLen++;
+    for (i = 0; i < sizeof(unsigned long); i++) {
+        int shift = (sizeof(unsigned long) - i - 1) * 8;
+        if (expLen || (exponent && ((unsigned long)0xffL << shift))) {
+            pubExp[expLen] = (unsigned char)((exponent >> shift) & 0xff);
+            expLen++;
         }
     }
 
     expitem.data = pubExp;
     expitem.len = expLen;
 
     srcKey = RSA_NewKey(keySize, &expitem);
     if (srcKey == NULL) {
-	fprintf(stderr, "RSA Key Gen failed");
-	return -1;
+        fprintf(stderr, "RSA Key Gen failed");
+        return -1;
     }
 
     /* test the basic case - most common, public exponent, modulus, prime */
     tstKey.arena = NULL;
     rsaPrivKeyReset(&tstKey);
 
     tstKey.publicExponent = srcKey->publicExponent;
     tstKey.modulus = srcKey->modulus;
     tstKey.prime1 = srcKey->prime1;
 
     rv = RSA_PopulatePrivateKey(&tstKey);
     if (rv != SECSuccess) {
-	fprintf(stderr, "RSA Populate failed: pubExp mod p\n");
-	failed = 1;
+        fprintf(stderr, "RSA Populate failed: pubExp mod p\n");
+        failed = 1;
     } else if (!rsaPrivKeysAreEqual(&tstKey, srcKey)) {
-	fprintf(stderr, "RSA Populate key mismatch: pubExp mod p\n");
-	failed = 1;
+        fprintf(stderr, "RSA Populate key mismatch: pubExp mod p\n");
+        failed = 1;
     }
 
     /* test the basic2 case, public exponent, modulus, prime2 */
     rsaPrivKeyReset(&tstKey);
 
     tstKey.publicExponent = srcKey->publicExponent;
     tstKey.modulus = srcKey->modulus;
     tstKey.prime1 = srcKey->prime2; /* test with q in the prime1 position */
 
     rv = RSA_PopulatePrivateKey(&tstKey);
     if (rv != SECSuccess) {
-	fprintf(stderr, "RSA Populate failed: pubExp mod q\n");
-	failed = 1;
+        fprintf(stderr, "RSA Populate failed: pubExp mod q\n");
+        failed = 1;
     } else if (!rsaPrivKeysAreEqual(&tstKey, srcKey)) {
-	fprintf(stderr, "RSA Populate key mismatch: pubExp mod q\n");
-	failed = 1;
+        fprintf(stderr, "RSA Populate key mismatch: pubExp mod q\n");
+        failed = 1;
     }
 
     /* test the medium case, private exponent, prime1, prime2 */
     rsaPrivKeyReset(&tstKey);
 
     tstKey.privateExponent = srcKey->privateExponent;
     tstKey.prime1 = srcKey->prime2; /* purposefully swap them to make */
     tstKey.prime2 = srcKey->prime1; /* sure populated swaps them back */
 
     rv = RSA_PopulatePrivateKey(&tstKey);
     if (rv != SECSuccess) {
-	fprintf(stderr, "RSA Populate failed: privExp p q\n");
-	failed = 1;
+        fprintf(stderr, "RSA Populate failed: privExp p q\n");
+        failed = 1;
     } else if (!rsaPrivKeysAreEqual(&tstKey, srcKey)) {
-	fprintf(stderr, "RSA Populate key mismatch: privExp  p q\n");
-	failed = 1;
+        fprintf(stderr, "RSA Populate key mismatch: privExp  p q\n");
+        failed = 1;
     }
 
     /* test the advanced case, public exponent, private exponent, prime2 */
     rsaPrivKeyReset(&tstKey);
 
     tstKey.privateExponent = srcKey->privateExponent;
     tstKey.publicExponent = srcKey->publicExponent;
     tstKey.prime2 = srcKey->prime2; /* use q in the prime2 position */
 
     rv = RSA_PopulatePrivateKey(&tstKey);
     if (rv != SECSuccess) {
-	fprintf(stderr, "RSA Populate failed: pubExp privExp q\n");
-	fprintf(stderr, " - not fatal\n");
-	/* it's possible that we can't uniquely determine the original key
-	 * from just the exponents and prime. Populate returns an error rather
-	 * than return the wrong key. */
+        fprintf(stderr, "RSA Populate failed: pubExp privExp q\n");
+        fprintf(stderr, " - not fatal\n");
+        /* it's possible that we can't uniquely determine the original key
+     * from just the exponents and prime. Populate returns an error rather
+     * than return the wrong key. */
     } else if (!rsaPrivKeysAreEqual(&tstKey, srcKey)) {
-	/* if we returned a key, it *must* be correct */
-	fprintf(stderr, "RSA Populate key mismatch: pubExp privExp  q\n");
-	rv = RSA_PrivateKeyCheck(&tstKey);
-	failed = 1;
+        /* if we returned a key, it *must* be correct */
+        fprintf(stderr, "RSA Populate key mismatch: pubExp privExp  q\n");
+        rv = RSA_PrivateKeyCheck(&tstKey);
+        failed = 1;
     }
 
     /* test the advanced case2, public exponent, private exponent, modulus */
     rsaPrivKeyReset(&tstKey);
 
     tstKey.privateExponent = srcKey->privateExponent;
     tstKey.publicExponent = srcKey->publicExponent;
     tstKey.modulus = srcKey->modulus;
 
     rv = RSA_PopulatePrivateKey(&tstKey);
     if (rv != SECSuccess) {
-	fprintf(stderr, "RSA Populate failed: pubExp privExp mod\n");
-	failed = 1;
+        fprintf(stderr, "RSA Populate failed: pubExp privExp mod\n");
+        failed = 1;
     } else if (!rsaPrivKeysAreEqual(&tstKey, srcKey)) {
-	fprintf(stderr, "RSA Populate key mismatch: pubExp privExp  mod\n");
-	failed = 1;
+        fprintf(stderr, "RSA Populate key mismatch: pubExp privExp  mod\n");
+        failed = 1;
     }
 
     return failed ? -1 : 0;
 }
 
-
-
 /* bltest commands */
 enum {
     cmd_Decrypt = 0,
     cmd_Encrypt,
     cmd_FIPS,
     cmd_Hash,
     cmd_Nonce,
     cmd_Dump,
@@ -3396,261 +3579,260 @@ enum {
     opt_OutputOffset,
     opt_MonteCarlo,
     opt_ThreadNum,
     opt_SecondsToRun,
     opt_CmdLine
 };
 
 static secuCommandFlag bltest_commands[] =
-{
-    { /* cmd_Decrypt	*/ 'D', PR_FALSE, 0, PR_FALSE },
-    { /* cmd_Encrypt	*/ 'E', PR_FALSE, 0, PR_FALSE },
-    { /* cmd_FIPS	*/ 'F', PR_FALSE, 0, PR_FALSE },
-    { /* cmd_Hash	*/ 'H', PR_FALSE, 0, PR_FALSE },
-    { /* cmd_Nonce      */ 'N', PR_FALSE, 0, PR_FALSE },
-    { /* cmd_Dump	*/ 'P', PR_FALSE, 0, PR_FALSE },
-    { /* cmd_RSAPopulate*/ 'R', PR_FALSE, 0, PR_FALSE },
-    { /* cmd_Sign	*/ 'S', PR_FALSE, 0, PR_FALSE },
-    { /* cmd_SelfTest	*/ 'T', PR_FALSE, 0, PR_FALSE },
-    { /* cmd_Verify	*/ 'V', PR_FALSE, 0, PR_FALSE }
-};
+    {
+      { /* cmd_Decrypt */ 'D', PR_FALSE, 0, PR_FALSE },
+      { /* cmd_Encrypt */ 'E', PR_FALSE, 0, PR_FALSE },
+      { /* cmd_FIPS */ 'F', PR_FALSE, 0, PR_FALSE },
+      { /* cmd_Hash */ 'H', PR_FALSE, 0, PR_FALSE },
+      { /* cmd_Nonce */ 'N', PR_FALSE, 0, PR_FALSE },
+      { /* cmd_Dump */ 'P', PR_FALSE, 0, PR_FALSE },
+      { /* cmd_RSAPopulate */ 'R', PR_FALSE, 0, PR_FALSE },
+      { /* cmd_Sign */ 'S', PR_FALSE, 0, PR_FALSE },
+      { /* cmd_SelfTest */ 'T', PR_FALSE, 0, PR_FALSE },
+      { /* cmd_Verify */ 'V', PR_FALSE, 0, PR_FALSE }
+    };
 
 static secuCommandFlag bltest_options[] =
-{
-    { /* opt_B64	  */ 'a', PR_FALSE, 0, PR_FALSE },
-    { /* opt_BufSize	  */ 'b', PR_TRUE,  0, PR_FALSE },
-    { /* opt_Restart	  */ 'c', PR_FALSE, 0, PR_FALSE },
-    { /* opt_SelfTestDir  */ 'd', PR_TRUE,  0, PR_FALSE },
-    { /* opt_Exponent	  */ 'e', PR_TRUE,  0, PR_FALSE },
-    { /* opt_SigFile      */ 'f', PR_TRUE,  0, PR_FALSE },
-    { /* opt_KeySize	  */ 'g', PR_TRUE,  0, PR_FALSE },
-    { /* opt_Hex	  */ 'h', PR_FALSE, 0, PR_FALSE },
-    { /* opt_Input	  */ 'i', PR_TRUE,  0, PR_FALSE },
-    { /* opt_PQGFile	  */ 'j', PR_TRUE,  0, PR_FALSE },
-    { /* opt_Key	  */ 'k', PR_TRUE,  0, PR_FALSE },
-    { /* opt_HexWSpc	  */ 'l', PR_FALSE, 0, PR_FALSE },
-    { /* opt_Mode	  */ 'm', PR_TRUE,  0, PR_FALSE },
+    {
+      { /* opt_B64 */ 'a', PR_FALSE, 0, PR_FALSE },
+      { /* opt_BufSize */ 'b', PR_TRUE, 0, PR_FALSE },
+      { /* opt_Restart */ 'c', PR_FALSE, 0, PR_FALSE },
+      { /* opt_SelfTestDir */ 'd', PR_TRUE, 0, PR_FALSE },
+      { /* opt_Exponent */ 'e', PR_TRUE, 0, PR_FALSE },
+      { /* opt_SigFile */ 'f', PR_TRUE, 0, PR_FALSE },
+      { /* opt_KeySize */ 'g', PR_TRUE, 0, PR_FALSE },
+      { /* opt_Hex */ 'h', PR_FALSE, 0, PR_FALSE },
+      { /* opt_Input */ 'i', PR_TRUE, 0, PR_FALSE },
+      { /* opt_PQGFile */ 'j', PR_TRUE, 0, PR_FALSE },
+      { /* opt_Key */ 'k', PR_TRUE, 0, PR_FALSE },
+      { /* opt_HexWSpc */ 'l', PR_FALSE, 0, PR_FALSE },
+      { /* opt_Mode */ 'm', PR_TRUE, 0, PR_FALSE },
 #ifndef NSS_DISABLE_ECC
-    { /* opt_CurveName	  */ 'n', PR_TRUE,  0, PR_FALSE },
+      { /* opt_CurveName */ 'n', PR_TRUE, 0, PR_FALSE },
 #endif
-    { /* opt_Output	  */ 'o', PR_TRUE,  0, PR_FALSE },
-    { /* opt_Repetitions  */ 'p', PR_TRUE,  0, PR_FALSE },
-    { /* opt_ZeroBuf	  */ 'q', PR_FALSE, 0, PR_FALSE },
-    { /* opt_Rounds	  */ 'r', PR_TRUE,  0, PR_FALSE },
-    { /* opt_Seed	  */ 's', PR_TRUE,  0, PR_FALSE },
-    { /* opt_SigSeedFile  */ 't', PR_TRUE,  0, PR_FALSE },
-    { /* opt_CXReps       */ 'u', PR_TRUE,  0, PR_FALSE },
-    { /* opt_IV		  */ 'v', PR_TRUE,  0, PR_FALSE },
-    { /* opt_WordSize	  */ 'w', PR_TRUE,  0, PR_FALSE },
-    { /* opt_UseSeed	  */ 'x', PR_FALSE, 0, PR_FALSE },
-    { /* opt_UseSigSeed	  */ 'y', PR_FALSE, 0, PR_FALSE },
-    { /* opt_SeedFile	  */ 'z', PR_FALSE, 0, PR_FALSE },
-    { /* opt_AAD	  */  0 , PR_TRUE,  0, PR_FALSE, "aad" },
-    { /* opt_InputOffset  */ '1', PR_TRUE,  0, PR_FALSE },
-    { /* opt_OutputOffset */ '2', PR_TRUE,  0, PR_FALSE },
-    { /* opt_MonteCarlo   */ '3', PR_FALSE, 0, PR_FALSE },
-    { /* opt_ThreadNum    */ '4', PR_TRUE,  0, PR_FALSE },
-    { /* opt_SecondsToRun */ '5', PR_TRUE,  0, PR_FALSE },
-    { /* opt_CmdLine	  */ '-', PR_FALSE, 0, PR_FALSE }
-};
-
-int main(int argc, char **argv)
+      { /* opt_Output */ 'o', PR_TRUE, 0, PR_FALSE },
+      { /* opt_Repetitions */ 'p', PR_TRUE, 0, PR_FALSE },
+      { /* opt_ZeroBuf */ 'q', PR_FALSE, 0, PR_FALSE },
+      { /* opt_Rounds */ 'r', PR_TRUE, 0, PR_FALSE },
+      { /* opt_Seed */ 's', PR_TRUE, 0, PR_FALSE },
+      { /* opt_SigSeedFile */ 't', PR_TRUE, 0, PR_FALSE },
+      { /* opt_CXReps */ 'u', PR_TRUE, 0, PR_FALSE },
+      { /* opt_IV */ 'v', PR_TRUE, 0, PR_FALSE },
+      { /* opt_WordSize */ 'w', PR_TRUE, 0, PR_FALSE },
+      { /* opt_UseSeed */ 'x', PR_FALSE, 0, PR_FALSE },
+      { /* opt_UseSigSeed */ 'y', PR_FALSE, 0, PR_FALSE },
+      { /* opt_SeedFile */ 'z', PR_FALSE, 0, PR_FALSE },
+      { /* opt_AAD */ 0, PR_TRUE, 0, PR_FALSE, "aad" },
+      { /* opt_InputOffset */ '1', PR_TRUE, 0, PR_FALSE },
+      { /* opt_OutputOffset */ '2', PR_TRUE, 0, PR_FALSE },
+      { /* opt_MonteCarlo */ '3', PR_FALSE, 0, PR_FALSE },
+      { /* opt_ThreadNum */ '4', PR_TRUE, 0, PR_FALSE },
+      { /* opt_SecondsToRun */ '5', PR_TRUE, 0, PR_FALSE },
+      { /* opt_CmdLine */ '-', PR_FALSE, 0, PR_FALSE }
+    };
+
+int
+main(int argc, char **argv)
 {
     SECStatus rv = SECFailure;
 
-    double              totalTime = 0.0;
-    PRIntervalTime      time1, time2;
-    PRFileDesc          *outfile = NULL;
-    bltestCipherInfo    *cipherInfoListHead, *cipherInfo = NULL;
-    bltestIOMode        ioMode;
-    int                 bufsize, exponent, curThrdNum;
+    double totalTime = 0.0;
+    PRIntervalTime time1, time2;
+    PRFileDesc *outfile = NULL;
+    bltestCipherInfo *cipherInfoListHead, *cipherInfo = NULL;
+    bltestIOMode ioMode;
+    int bufsize, exponent, curThrdNum;
 #ifndef NSS_DISABLE_ECC
-    char		*curveName = NULL;
+    char *curveName = NULL;
 #endif
-    int			 i, commandsEntered;
-    int			 inoff, outoff;
-    int                  threads = 1;
+    int i, commandsEntered;
+    int inoff, outoff;
+    int threads = 1;
 
     secuCommand bltest;
     bltest.numCommands = sizeof(bltest_commands) / sizeof(secuCommandFlag);
     bltest.numOptions = sizeof(bltest_options) / sizeof(secuCommandFlag);
     bltest.commands = bltest_commands;
     bltest.options = bltest_options;
 
     progName = strrchr(argv[0], '/');
-    if (!progName) 
-	progName = strrchr(argv[0], '\\');
-    progName = progName ? progName+1 : argv[0];
+    if (!progName)
+        progName = strrchr(argv[0], '\\');
+    progName = progName ? progName + 1 : argv[0];
 
     rv = NSS_InitializePRErrorTable();
     if (rv != SECSuccess) {
-	SECU_PrintPRandOSError(progName);
-	return -1;
+        SECU_PrintPRandOSError(progName);
+        return -1;
     }
     rv = RNG_RNGInit();
     if (rv != SECSuccess) {
-	SECU_PrintPRandOSError(progName);
-	return -1;
+        SECU_PrintPRandOSError(progName);
+        return -1;
     }
     rv = BL_Init();
     if (rv != SECSuccess) {
-	SECU_PrintPRandOSError(progName);
-	return -1;
+        SECU_PrintPRandOSError(progName);
+        return -1;
     }
     RNG_SystemInfoForRNG();
 
-
     rv = SECU_ParseCommandLine(argc, argv, progName, &bltest);
     if (rv == SECFailure) {
-	fprintf(stderr, "%s: command line parsing error!\n", progName);
-	goto print_usage;
+        fprintf(stderr, "%s: command line parsing error!\n", progName);
+        goto print_usage;
     }
     rv = SECFailure;
 
     cipherInfo = PORT_ZNew(bltestCipherInfo);
     cipherInfoListHead = cipherInfo;
 
     /* Check the number of commands entered on the command line. */
     commandsEntered = 0;
-    for (i=0; i<bltest.numCommands; i++)
-	if (bltest.commands[i].activated)
-	    commandsEntered++;
+    for (i = 0; i < bltest.numCommands; i++)
+        if (bltest.commands[i].activated)
+            commandsEntered++;
 
     if (commandsEntered > 1 &&
-	!(commandsEntered == 2 && bltest.commands[cmd_SelfTest].activated)) {
-	fprintf(stderr, "%s: one command at a time!\n", progName);
+        !(commandsEntered == 2 && bltest.commands[cmd_SelfTest].activated)) {
+        fprintf(stderr, "%s: one command at a time!\n", progName);
         goto print_usage;
     }
 
     if (commandsEntered == 0) {
-	fprintf(stderr, "%s: you must enter a command!\n", progName);
+        fprintf(stderr, "%s: you must enter a command!\n", progName);
         goto print_usage;
     }
 
-
     if (bltest.commands[cmd_Sign].activated)
-	bltest.commands[cmd_Encrypt].activated = PR_TRUE;
+        bltest.commands[cmd_Encrypt].activated = PR_TRUE;
     if (bltest.commands[cmd_Verify].activated)
-	bltest.commands[cmd_Decrypt].activated = PR_TRUE;
+        bltest.commands[cmd_Decrypt].activated = PR_TRUE;
     if (bltest.commands[cmd_Hash].activated)
-	bltest.commands[cmd_Encrypt].activated = PR_TRUE;
+        bltest.commands[cmd_Encrypt].activated = PR_TRUE;
 
     inoff = outoff = 0;
     if (bltest.options[opt_InputOffset].activated)
-	inoff = PORT_Atoi(bltest.options[opt_InputOffset].arg);
+        inoff = PORT_Atoi(bltest.options[opt_InputOffset].arg);
     if (bltest.options[opt_OutputOffset].activated)
-	outoff = PORT_Atoi(bltest.options[opt_OutputOffset].arg);
-
-    testdir = (bltest.options[opt_SelfTestDir].activated) ? 
-                 strdup(bltest.options[opt_SelfTestDir].arg) : ".";
+        outoff = PORT_Atoi(bltest.options[opt_OutputOffset].arg);
+
+    testdir = (bltest.options[opt_SelfTestDir].activated) ? strdup(bltest.options[opt_SelfTestDir].arg)
+                                                          : ".";
 
     /*
      * Handle three simple cases first
      */
 
     /* test the RSA_PopulatePrivateKey function */
     if (bltest.commands[cmd_RSAPopulate].activated) {
-	unsigned int keySize = 1024;
-	unsigned long exponent = 65537;
-	int rounds = 1;
-	int ret = -1;
-	
-	if (bltest.options[opt_KeySize].activated) {
-	    keySize = PORT_Atoi(bltest.options[opt_KeySize].arg);
-	}
-	if (bltest.options[opt_Rounds].activated) {
-	    rounds = PORT_Atoi(bltest.options[opt_Rounds].arg);
-	}
-	if (bltest.options[opt_Exponent].activated) {
-	    exponent = PORT_Atoi(bltest.options[opt_Exponent].arg);
-	}
-
-	for (i=0; i < rounds; i++) {
-	    printf("Running RSA Populate test round %d\n",i);
-	    ret = doRSAPopulateTest(keySize,exponent);
-	    if (ret != 0) {
-		break;
-	    }
-	}
-	if (ret != 0) {
-	    fprintf(stderr,"RSA Populate test round %d: FAILED\n",i);
-	}
-	return ret;
+        unsigned int keySize = 1024;
+        unsigned long exponent = 65537;
+        int rounds = 1;
+        int ret = -1;
+
+        if (bltest.options[opt_KeySize].activated) {
+            keySize = PORT_Atoi(bltest.options[opt_KeySize].arg);
+        }
+        if (bltest.options[opt_Rounds].activated) {
+            rounds = PORT_Atoi(bltest.options[opt_Rounds].arg);
+        }
+        if (bltest.options[opt_Exponent].activated) {
+            exponent = PORT_Atoi(bltest.options[opt_Exponent].arg);
+        }
+
+        for (i = 0; i < rounds; i++) {
+            printf("Running RSA Populate test round %d\n", i);
+            ret = doRSAPopulateTest(keySize, exponent);
+            if (ret != 0) {
+                break;
+            }
+        }
+        if (ret != 0) {
+            fprintf(stderr, "RSA Populate test round %d: FAILED\n", i);
+        }
+        return ret;
     }
 
     /* Do BLAPI self-test */
     if (bltest.commands[cmd_SelfTest].activated) {
-	PRBool encrypt = PR_TRUE, decrypt = PR_TRUE;
-	/* user may specified a set of ciphers to test.  parse them. */
-	bltestCipherMode modesToTest[NUMMODES];
-	int numModesToTest = 0;
-	char *tok, *str;
-	str = bltest.options[opt_Mode].arg;
-	while (str) {
-	    tok = strchr(str, ',');
-	    if (tok) *tok = '\0';
-	    modesToTest[numModesToTest++] = get_mode(str);
-	    if (tok) {
-		*tok = ',';
-		str = tok + 1;
-	    } else {
-		break;
-	    }
-	}
-	if (bltest.commands[cmd_Decrypt].activated &&
-	    !bltest.commands[cmd_Encrypt].activated)
-	    encrypt = PR_FALSE;
-	if (bltest.commands[cmd_Encrypt].activated &&
-	    !bltest.commands[cmd_Decrypt].activated)
-	    decrypt = PR_FALSE;
-	rv = blapi_selftest(modesToTest, numModesToTest, inoff, outoff,
-	                    encrypt, decrypt);
-	PORT_Free(cipherInfo);
-	return rv == SECSuccess ? 0 : 1;
+        PRBool encrypt = PR_TRUE, decrypt = PR_TRUE;
+        /* user may specified a set of ciphers to test.  parse them. */
+        bltestCipherMode modesToTest[NUMMODES];
+        int numModesToTest = 0;
+        char *tok, *str;
+        str = bltest.options[opt_Mode].arg;
+        while (str) {
+            tok = strchr(str, ',');
+            if (tok)
+                *tok = '\0';
+            modesToTest[numModesToTest++] = get_mode(str);
+            if (tok) {
+                *tok = ',';
+                str = tok + 1;
+            } else {
+                break;
+            }
+        }
+        if (bltest.commands[cmd_Decrypt].activated &&
+            !bltest.commands[cmd_Encrypt].activated)
+            encrypt = PR_FALSE;
+        if (bltest.commands[cmd_Encrypt].activated &&
+            !bltest.commands[cmd_Decrypt].activated)
+            decrypt = PR_FALSE;
+        rv = blapi_selftest(modesToTest, numModesToTest, inoff, outoff,
+                            encrypt, decrypt);
+        PORT_Free(cipherInfo);
+        return rv == SECSuccess ? 0 : 1;
     }
 
     /* Do FIPS self-test */
     if (bltest.commands[cmd_FIPS].activated) {
-	CK_RV ckrv = sftk_fipsPowerUpSelfTest();
-	fprintf(stdout, "CK_RV: %ld.\n", ckrv);
+        CK_RV ckrv = sftk_FIPSEntryOK();
+        fprintf(stdout, "CK_RV: %ld.\n", ckrv);
         PORT_Free(cipherInfo);
         if (ckrv == CKR_OK)
             return SECSuccess;
         return SECFailure;
     }
 
     /*
      * Check command line arguments for Encrypt/Decrypt/Hash/Sign/Verify
      */
 
     if ((bltest.commands[cmd_Decrypt].activated ||
-	 bltest.commands[cmd_Verify].activated) &&
-	bltest.options[opt_BufSize].activated) {
-	fprintf(stderr, "%s: Cannot use a nonce as input to decrypt/verify.\n",
-			 progName);
+         bltest.commands[cmd_Verify].activated) &&
+        bltest.options[opt_BufSize].activated) {
+        fprintf(stderr, "%s: Cannot use a nonce as input to decrypt/verify.\n",
+                progName);
         goto print_usage;
     }
 
     if (bltest.options[opt_Mode].activated) {
-	cipherInfo->mode = get_mode(bltest.options[opt_Mode].arg);
-	if (cipherInfo->mode == bltestINVALID) {
+        cipherInfo->mode = get_mode(bltest.options[opt_Mode].arg);
+        if (cipherInfo->mode == bltestINVALID) {
             goto print_usage;
-	}
+        }
     } else {
-	fprintf(stderr, "%s: You must specify a cipher mode with -m.\n",
-			 progName);
+        fprintf(stderr, "%s: You must specify a cipher mode with -m.\n",
+                progName);
         goto print_usage;
     }
 
-    
     if (bltest.options[opt_Repetitions].activated &&
         bltest.options[opt_SecondsToRun].activated) {
         fprintf(stderr, "%s: Operation time should be defined in either "
-                "repetitions(-p) or seconds(-5) not both",
+                        "repetitions(-p) or seconds(-5) not both",
                 progName);
         goto print_usage;
     }
 
     if (bltest.options[opt_Repetitions].activated) {
         cipherInfo->repetitionsToPerfom =
             PORT_Atoi(bltest.options[opt_Repetitions].arg);
     } else {
@@ -3658,17 +3840,16 @@ int main(int argc, char **argv)
     }
 
     if (bltest.options[opt_SecondsToRun].activated) {
         cipherInfo->seconds = PORT_Atoi(bltest.options[opt_SecondsToRun].arg);
     } else {
         cipherInfo->seconds = 0;
     }
 
-
     if (bltest.options[opt_CXReps].activated) {
         cipherInfo->cxreps = PORT_Atoi(bltest.options[opt_CXReps].arg);
     } else {
         cipherInfo->cxreps = 0;
     }
 
     if (bltest.options[opt_ThreadNum].activated) {
         threads = PORT_Atoi(bltest.options[opt_ThreadNum].arg);
@@ -3680,57 +3861,59 @@ int main(int argc, char **argv)
     /* Dump a file (rsakey, dsakey, etc.) */
     if (bltest.commands[cmd_Dump].activated) {
         rv = dump_file(cipherInfo->mode, bltest.options[opt_Input].arg);
         PORT_Free(cipherInfo);
         return rv;
     }
 
     /* default input mode is binary */
-    ioMode = (bltest.options[opt_B64].activated)     ? bltestBase64Encoded :
-	     (bltest.options[opt_Hex].activated)     ? bltestHexStream :
-	     (bltest.options[opt_HexWSpc].activated) ? bltestHexSpaceDelim :
-						       bltestBinary;
+    ioMode = (bltest.options[opt_B64].activated)
+                 ? bltestBase64Encoded
+                 : (bltest.options[opt_Hex].activated)
+                       ? bltestHexStream
+                       : (bltest.options[opt_HexWSpc].activated) ? bltestHexSpaceDelim
+                                                                 : bltestBinary;
 
     if (bltest.options[opt_Exponent].activated)
-	exponent = PORT_Atoi(bltest.options[opt_Exponent].arg);
+        exponent = PORT_Atoi(bltest.options[opt_Exponent].arg);
     else
-	exponent = 65537;
+        exponent = 65537;
 
 #ifndef NSS_DISABLE_ECC
     if (bltest.options[opt_CurveName].activated)
-	curveName = PORT_Strdup(bltest.options[opt_CurveName].arg);
+        curveName = PORT_Strdup(bltest.options[opt_CurveName].arg);
     else
-	curveName = NULL;
+        curveName = NULL;
 #endif
 
     if (bltest.commands[cmd_Verify].activated &&
         !bltest.options[opt_SigFile].activated) {
         fprintf(stderr, "%s: You must specify a signature file with -f.\n",
                 progName);
 
-print_usage:
+    print_usage:
         if (cipherInfo) {
             PORT_Free(cipherInfo);
         }
         Usage();
     }
 
     if (bltest.options[opt_MonteCarlo].activated) {
         cipherInfo->mCarlo = PR_TRUE;
     } else {
         cipherInfo->mCarlo = PR_FALSE;
     }
 
-    for (curThrdNum = 0;curThrdNum < threads;curThrdNum++) {
-        int            keysize = 0;
-        PRFileDesc     *file = NULL, *infile;
-        bltestParams   *params;
-        char           *instr = NULL;
-        PLArenaPool    *arena;
+    for (curThrdNum = 0; curThrdNum < threads; curThrdNum++) {
+        int keysize = 0;
+        PRFileDesc *file = NULL, *infile;
+        bltestParams *params;
+        char *instr = NULL;
+        PLArenaPool *arena;
 
         if (curThrdNum > 0) {
             bltestCipherInfo *newCInfo = PORT_ZNew(bltestCipherInfo);
             if (!newCInfo) {
                 fprintf(stderr, "%s: Can not allocate  memory.\n", progName);
                 goto exit_point;
             }
             newCInfo->mode = cipherInfo->mode;
@@ -3744,50 +3927,51 @@ print_usage:
         }
         arena = PORT_NewArena(BLTEST_DEFAULT_CHUNKSIZE);
         if (!arena) {
             fprintf(stderr, "%s: Can not allocate memory.\n", progName);
             goto exit_point;
         }
         cipherInfo->arena = arena;
         params = &cipherInfo->params;
-        
+
         /* Set up an encryption key. */
         keysize = 0;
         file = NULL;
-        if (is_symmkeyCipher(cipherInfo->mode)) {
-            char *keystr = NULL;  /* if key is on command line */
+        if (is_symmkeyCipher(cipherInfo->mode) ||
+            is_aeadCipher(cipherInfo->mode)) {
+            char *keystr = NULL; /* if key is on command line */
             if (bltest.options[opt_Key].activated) {
                 if (bltest.options[opt_CmdLine].activated) {
                     keystr = bltest.options[opt_Key].arg;
                 } else {
                     file = PR_Open(bltest.options[opt_Key].arg,
                                    PR_RDONLY, 00660);
                 }
             } else {
                 if (bltest.options[opt_KeySize].activated)
                     keysize = PORT_Atoi(bltest.options[opt_KeySize].arg);
                 else
                     keysize = 8; /* use 64-bit default (DES) */
                 /* save the random key for reference */
-                file = PR_Open("tmp.key", PR_WRONLY|PR_CREATE_FILE, 00660);
+                file = PR_Open("tmp.key", PR_WRONLY | PR_CREATE_FILE, 00660);
             }
             params->key.mode = ioMode;
             setupIO(cipherInfo->arena, &params->key, file, keystr, keysize);
             if (file)
                 PR_Close(file);
         } else if (is_pubkeyCipher(cipherInfo->mode)) {
             if (bltest.options[opt_Key].activated) {
                 file = PR_Open(bltest.options[opt_Key].arg, PR_RDONLY, 00660);
             } else {
                 if (bltest.options[opt_KeySize].activated)
                     keysize = PORT_Atoi(bltest.options[opt_KeySize].arg);
                 else
                     keysize = 64; /* use 512-bit default */
-                file = PR_Open("tmp.key", PR_WRONLY|PR_CREATE_FILE, 00660);
+                file = PR_Open("tmp.key", PR_WRONLY | PR_CREATE_FILE, 00660);
             }
             params->key.mode = bltestBase64Encoded;
 #ifndef NSS_DISABLE_ECC
             pubkeyInitKey(cipherInfo, file, keysize, exponent, curveName);
 #else
             pubkeyInitKey(cipherInfo, file, keysize, exponent);
 #endif
             PR_Close(file);
@@ -3808,17 +3992,17 @@ print_usage:
                 if (bltest.options[opt_CmdLine].activated) {
                     ivstr = bltest.options[opt_IV].arg;
                 } else {
                     file = PR_Open(bltest.options[opt_IV].arg,
                                    PR_RDONLY, 00660);
                 }
             } else {
                 /* save the random iv for reference */
-                file = PR_Open("tmp.iv", PR_WRONLY|PR_CREATE_FILE, 00660);
+                file = PR_Open("tmp.iv", PR_WRONLY | PR_CREATE_FILE, 00660);
             }
             memset(&skp->iv, 0, sizeof skp->iv);
             skp->iv.mode = ioMode;
             setupIO(cipherInfo->arena, &skp->iv, file, ivstr, keysize);
             if (file) {
                 PR_Close(file);
             }
         }
@@ -3841,29 +4025,29 @@ print_usage:
             }
             memset(&askp->aad, 0, sizeof askp->aad);
             askp->aad.mode = ioMode;
             setupIO(cipherInfo->arena, &askp->aad, file, aadstr, 0);
             if (file) {
                 PR_Close(file);
             }
         }
-        
+
         if (bltest.commands[cmd_Verify].activated) {
             file = PR_Open(bltest.options[opt_SigFile].arg, PR_RDONLY, 00660);
             if (is_sigCipher(cipherInfo->mode)) {
                 memset(&params->asymk.sig, 0, sizeof(bltestIO));
                 params->asymk.sig.mode = ioMode;
                 setupIO(cipherInfo->arena, &params->asymk.sig, file, NULL, 0);
             }
             if (file) {
                 PR_Close(file);
             }
         }
-        
+
         if (bltest.options[opt_PQGFile].activated) {
             file = PR_Open(bltest.options[opt_PQGFile].arg, PR_RDONLY, 00660);
             params->asymk.cipherParams.dsa.pqgdata.mode = bltestBase64Encoded;
             setupIO(cipherInfo->arena, &params->asymk.cipherParams.dsa.pqgdata,
                     file, NULL, 0);
             if (file) {
                 PR_Close(file);
             }
@@ -3871,20 +4055,20 @@ print_usage:
 
         /* Set up the input buffer */
         if (bltest.options[opt_Input].activated) {
             if (bltest.options[opt_CmdLine].activated) {
                 instr = bltest.options[opt_Input].arg;
                 infile = NULL;
             } else {
                 /* form file name from testdir and input arg. */
-                char * filename = bltest.options[opt_Input].arg;
-                if (bltest.options[opt_SelfTestDir].activated && 
+                char *filename = bltest.options[opt_Input].arg;
+                if (bltest.options[opt_SelfTestDir].activated &&
                     testdir && filename && filename[0] != '/') {
-                    filename = PR_smprintf("%s/tests/%s/%s", testdir, 
+                    filename = PR_smprintf("%s/tests/%s/%s", testdir,
                                            mode_strings[cipherInfo->mode],
                                            filename);
                     if (!filename) {
                         fprintf(stderr, "%s: Can not allocate memory.\n",
                                 progName);
                         goto exit_point;
                     }
                     infile = PR_Open(filename, PR_RDONLY, 00660);
@@ -3895,44 +4079,44 @@ print_usage:
             }
         } else if (bltest.options[opt_BufSize].activated) {
             /* save the random plaintext for reference */
             char *tmpFName = PR_smprintf("tmp.in.%d", curThrdNum);
             if (!tmpFName) {
                 fprintf(stderr, "%s: Can not allocate memory.\n", progName);
                 goto exit_point;
             }
-            infile = PR_Open(tmpFName, PR_WRONLY|PR_CREATE_FILE, 00660);
+            infile = PR_Open(tmpFName, PR_WRONLY | PR_CREATE_FILE, 00660);
             PR_smprintf_free(tmpFName);
         } else {
             infile = PR_STDIN;
         }
         if (!infile) {
             fprintf(stderr, "%s: Failed to open input file.\n", progName);