Bug 575620, landing NSS 3.12.7 beta 2
authorKai Engert <kaie@kuix.de>
Mon, 19 Jul 2010 07:45:52 +0200
changeset 47913 1eca030187260e8153609fedab672c5489cf8178
parent 47912 3687d3cf317639c7839a780acb4b7a06757ea4ae
child 47914 e15f9edaa78f4de7cde9c6d74b88ceacc2416524
push idunknown
push userunknown
push dateunknown
bugs575620
milestone2.0b2pre
Bug 575620, landing NSS 3.12.7 beta 2 r=wtc
security/coreconf/HP-UX.mk
security/coreconf/Linux.mk
security/coreconf/WIN32.mk
security/coreconf/jniregen.pl
security/coreconf/location.mk
security/coreconf/outofdate.pl
security/coreconf/rules.mk
security/nss/TAG-INFO
security/nss/cmd/bltest/blapitest.c
security/nss/cmd/certutil/certext.c
security/nss/cmd/certutil/certutil.c
security/nss/cmd/certutil/keystuff.c
security/nss/cmd/crlutil/crlutil.c
security/nss/cmd/lib/SECerrs.h
security/nss/cmd/lib/secutil.c
security/nss/cmd/libpkix/pkix/checker/test_certchainchecker.c
security/nss/cmd/libpkix/pkix/store/test_store.c
security/nss/cmd/libpkix/testutil/testutil.c
security/nss/cmd/libpkix/testutil/testutil.h
security/nss/cmd/libpkix/testutil/testutil_nss.c
security/nss/cmd/libpkix/testutil/testutil_nss.h
security/nss/cmd/modutil/pk11.c
security/nss/cmd/pk11mode/pk11mode.c
security/nss/cmd/pk11util/pk11util.c
security/nss/cmd/pk12util/pk12util.c
security/nss/cmd/platlibs.mk
security/nss/cmd/selfserv/selfserv.c
security/nss/cmd/signtool/javascript.c
security/nss/cmd/signtool/signtool.c
security/nss/cmd/signtool/zip.c
security/nss/cmd/strsclnt/strsclnt.c
security/nss/lib/base/arena.c
security/nss/lib/certdb/alg1485.c
security/nss/lib/certdb/cert.h
security/nss/lib/certdb/certdb.c
security/nss/lib/certdb/certi.h
security/nss/lib/certdb/certt.h
security/nss/lib/certdb/crl.c
security/nss/lib/certdb/genname.c
security/nss/lib/certhigh/certvfy.c
security/nss/lib/certhigh/certvfypkix.c
security/nss/lib/certhigh/ocsp.c
security/nss/lib/ckfw/capi/crsa.c
security/nss/lib/ckfw/nssmkey/mobject.c
security/nss/lib/ckfw/token.c
security/nss/lib/ckfw/wrap.c
security/nss/lib/crmf/crmf.h
security/nss/lib/crmf/crmfdec.c
security/nss/lib/cryptohi/keythi.h
security/nss/lib/cryptohi/sechash.c
security/nss/lib/cryptohi/seckey.c
security/nss/lib/cryptohi/secvfy.c
security/nss/lib/dev/devslot.c
security/nss/lib/dev/devtoken.c
security/nss/lib/dev/devutil.c
security/nss/lib/freebl/Makefile
security/nss/lib/freebl/camellia.c
security/nss/lib/freebl/config.mk
security/nss/lib/freebl/freebl.rc
security/nss/lib/freebl/intel-aes.s
security/nss/lib/freebl/manifest.mn
security/nss/lib/freebl/mpi/mpi-priv.h
security/nss/lib/freebl/mpi/mpi.c
security/nss/lib/freebl/mpi/mpmontg.c
security/nss/lib/freebl/shvfy.c
security/nss/lib/freebl/unix_rand.c
security/nss/lib/jar/jar.c
security/nss/lib/jar/jarfile.c
security/nss/lib/jar/jarver.c
security/nss/lib/libpkix/include/pkix.h
security/nss/lib/libpkix/include/pkix_certsel.h
security/nss/lib/libpkix/include/pkix_certstore.h
security/nss/lib/libpkix/include/pkix_checker.h
security/nss/lib/libpkix/include/pkix_crlsel.h
security/nss/lib/libpkix/include/pkix_errorstrings.h
security/nss/lib/libpkix/include/pkix_params.h
security/nss/lib/libpkix/include/pkix_pl_pki.h
security/nss/lib/libpkix/include/pkix_pl_system.h
security/nss/lib/libpkix/include/pkix_results.h
security/nss/lib/libpkix/include/pkix_revchecker.h
security/nss/lib/libpkix/include/pkix_sample_modules.h
security/nss/lib/libpkix/include/pkix_util.h
security/nss/lib/libpkix/include/pkixt.h
security/nss/lib/libpkix/pkix/certsel/pkix_certselector.c
security/nss/lib/libpkix/pkix/certsel/pkix_certselector.h
security/nss/lib/libpkix/pkix/certsel/pkix_comcertselparams.c
security/nss/lib/libpkix/pkix/certsel/pkix_comcertselparams.h
security/nss/lib/libpkix/pkix/checker/pkix_basicconstraintschecker.c
security/nss/lib/libpkix/pkix/checker/pkix_basicconstraintschecker.h
security/nss/lib/libpkix/pkix/checker/pkix_certchainchecker.c
security/nss/lib/libpkix/pkix/checker/pkix_certchainchecker.h
security/nss/lib/libpkix/pkix/checker/pkix_expirationchecker.c
security/nss/lib/libpkix/pkix/checker/pkix_expirationchecker.h
security/nss/lib/libpkix/pkix/checker/pkix_namechainingchecker.c
security/nss/lib/libpkix/pkix/checker/pkix_namechainingchecker.h
security/nss/lib/libpkix/pkix/checker/pkix_nameconstraintschecker.c
security/nss/lib/libpkix/pkix/checker/pkix_nameconstraintschecker.h
security/nss/lib/libpkix/pkix/checker/pkix_policychecker.c
security/nss/lib/libpkix/pkix/checker/pkix_policychecker.h
security/nss/lib/libpkix/pkix/checker/pkix_revocationchecker.c
security/nss/lib/libpkix/pkix/checker/pkix_revocationchecker.h
security/nss/lib/libpkix/pkix/checker/pkix_signaturechecker.c
security/nss/lib/libpkix/pkix/checker/pkix_signaturechecker.h
security/nss/lib/libpkix/pkix/checker/pkix_targetcertchecker.c
security/nss/lib/libpkix/pkix/checker/pkix_targetcertchecker.h
security/nss/lib/libpkix/pkix/crlsel/pkix_comcrlselparams.c
security/nss/lib/libpkix/pkix/crlsel/pkix_comcrlselparams.h
security/nss/lib/libpkix/pkix/crlsel/pkix_crlselector.c
security/nss/lib/libpkix/pkix/crlsel/pkix_crlselector.h
security/nss/lib/libpkix/pkix/params/pkix_buildparams.c
security/nss/lib/libpkix/pkix/params/pkix_buildparams.h
security/nss/lib/libpkix/pkix/params/pkix_procparams.c
security/nss/lib/libpkix/pkix/params/pkix_procparams.h
security/nss/lib/libpkix/pkix/params/pkix_resourcelimits.c
security/nss/lib/libpkix/pkix/params/pkix_resourcelimits.h
security/nss/lib/libpkix/pkix/params/pkix_trustanchor.c
security/nss/lib/libpkix/pkix/params/pkix_trustanchor.h
security/nss/lib/libpkix/pkix/params/pkix_valparams.c
security/nss/lib/libpkix/pkix/params/pkix_valparams.h
security/nss/lib/libpkix/pkix/results/pkix_buildresult.c
security/nss/lib/libpkix/pkix/results/pkix_buildresult.h
security/nss/lib/libpkix/pkix/results/pkix_policynode.c
security/nss/lib/libpkix/pkix/results/pkix_policynode.h
security/nss/lib/libpkix/pkix/results/pkix_valresult.c
security/nss/lib/libpkix/pkix/results/pkix_valresult.h
security/nss/lib/libpkix/pkix/results/pkix_verifynode.c
security/nss/lib/libpkix/pkix/results/pkix_verifynode.h
security/nss/lib/libpkix/pkix/store/pkix_store.c
security/nss/lib/libpkix/pkix/store/pkix_store.h
security/nss/lib/libpkix/pkix/top/pkix_build.c
security/nss/lib/libpkix/pkix/top/pkix_build.h
security/nss/lib/libpkix/pkix/top/pkix_lifecycle.c
security/nss/lib/libpkix/pkix/top/pkix_lifecycle.h
security/nss/lib/libpkix/pkix/top/pkix_validate.c
security/nss/lib/libpkix/pkix/top/pkix_validate.h
security/nss/lib/libpkix/pkix/util/pkix_error.c
security/nss/lib/libpkix/pkix/util/pkix_error.h
security/nss/lib/libpkix/pkix/util/pkix_list.c
security/nss/lib/libpkix/pkix/util/pkix_list.h
security/nss/lib/libpkix/pkix/util/pkix_tools.c
security/nss/lib/libpkix/pkix/util/pkix_tools.h
security/nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_colcertstore.c
security/nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_colcertstore.h
security/nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_httpcertstore.c
security/nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_nsscontext.c
security/nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_nsscontext.h
security/nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_pk11certstore.c
security/nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_pk11certstore.h
security/nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_cert.c
security/nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_crl.c
security/nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_nameconstraints.c
security/nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_bigint.c
security/nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_bigint.h
security/nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_bytearray.c
security/nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_bytearray.h
security/nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_common.c
security/nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_common.h
security/nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_hashtable.c
security/nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_hashtable.h
security/nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_lifecycle.c
security/nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_lifecycle.h
security/nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_mem.c
security/nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_mem.h
security/nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_monitorlock.c
security/nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_monitorlock.h
security/nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_mutex.c
security/nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_mutex.h
security/nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_object.c
security/nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_object.h
security/nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_oid.c
security/nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_oid.h
security/nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_primhash.c
security/nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_primhash.h
security/nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_rwlock.c
security/nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_rwlock.h
security/nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_string.c
security/nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_string.h
security/nss/lib/manifest.mn
security/nss/lib/nss/nss.def
security/nss/lib/nss/nss.h
security/nss/lib/nss/nssinit.c
security/nss/lib/pk11wrap/debug_module.c
security/nss/lib/pk11wrap/pk11akey.c
security/nss/lib/pk11wrap/pk11auth.c
security/nss/lib/pk11wrap/pk11cert.c
security/nss/lib/pk11wrap/pk11cxt.c
security/nss/lib/pk11wrap/pk11err.c
security/nss/lib/pk11wrap/pk11load.c
security/nss/lib/pk11wrap/pk11merge.c
security/nss/lib/pk11wrap/pk11nobj.c
security/nss/lib/pk11wrap/pk11pub.h
security/nss/lib/pk11wrap/pk11skey.c
security/nss/lib/pk11wrap/pk11slot.c
security/nss/lib/pk11wrap/pk11util.c
security/nss/lib/pkcs12/p12d.c
security/nss/lib/pkcs12/p12dec.c
security/nss/lib/pkcs7/p7common.c
security/nss/lib/pkcs7/p7local.c
security/nss/lib/pki/certificate.c
security/nss/lib/pki/cryptocontext.c
security/nss/lib/pki/nsspki.h
security/nss/lib/pki/nsspkit.h
security/nss/lib/pki/pki3hack.c
security/nss/lib/pki/pkibase.c
security/nss/lib/pki/trustdomain.c
security/nss/lib/pki1/Makefile
security/nss/lib/pki1/atav.c
security/nss/lib/pki1/config.mk
security/nss/lib/pki1/genname.c
security/nss/lib/pki1/gnseq.c
security/nss/lib/pki1/manifest.mn
security/nss/lib/pki1/name.c
security/nss/lib/pki1/nsspki1.h
security/nss/lib/pki1/nsspki1t.h
security/nss/lib/pki1/oid.c
security/nss/lib/pki1/oiddata.c
security/nss/lib/pki1/oiddata.h
security/nss/lib/pki1/oidgen.perl
security/nss/lib/pki1/oids.txt
security/nss/lib/pki1/pki1.h
security/nss/lib/pki1/pki1t.h
security/nss/lib/pki1/rdn.c
security/nss/lib/pki1/rdnseq.c
security/nss/lib/smime/cms.h
security/nss/lib/smime/cmsasn1.c
security/nss/lib/smime/cmscipher.c
security/nss/lib/smime/cmssiginfo.c
security/nss/lib/softoken/config.mk
security/nss/lib/softoken/legacydb/nssdbm.rc
security/nss/lib/softoken/sftkdb.c
security/nss/lib/softoken/sftkpars.c
security/nss/lib/softoken/softkver.h
security/nss/lib/softoken/softokn.rc
security/nss/lib/ssl/ssl3con.c
security/nss/lib/ssl/ssl3ecc.c
security/nss/lib/ssl/ssl3ext.c
security/nss/lib/ssl/ssl3prot.h
security/nss/lib/ssl/sslcon.c
security/nss/lib/ssl/sslerr.h
security/nss/lib/ssl/sslgathr.c
security/nss/lib/ssl/sslmutex.c
security/nss/lib/ssl/sslsnce.c
security/nss/lib/ssl/sslsock.c
security/nss/lib/util/nssilock.c
security/nss/lib/util/nssutil.def
security/nss/lib/util/nssutil.h
security/nss/lib/util/portreg.c
security/nss/lib/util/secdig.h
security/nss/lib/util/secerr.h
security/nss/lib/util/secoid.c
security/nss/lib/util/secoidt.h
security/nss/lib/util/secport.c
security/nss/lib/zlib/deflate.h
security/nss/manifest.mn
security/nss/tests/cert/cert.sh
security/nss/tests/chains/scenarios/anypolicywithlevel.cfg
security/nss/tests/dbtests/dbtests.sh
security/nss/tests/libpkix/certs/OCSPCA1.cert
security/nss/tests/libpkix/certs/OCSPCA1.p12
security/nss/tests/libpkix/certs/OCSPCA2.cert
security/nss/tests/libpkix/certs/OCSPCA2.p12
security/nss/tests/libpkix/certs/OCSPCA3.cert
security/nss/tests/libpkix/certs/OCSPCA3.p12
security/nss/tests/libpkix/certs/OCSPEE11.cert
security/nss/tests/libpkix/certs/OCSPEE12.cert
security/nss/tests/libpkix/certs/OCSPEE13.cert
security/nss/tests/libpkix/certs/OCSPEE14.cert
security/nss/tests/libpkix/certs/OCSPEE15.cert
security/nss/tests/libpkix/certs/OCSPEE21.cert
security/nss/tests/libpkix/certs/OCSPEE22.cert
security/nss/tests/libpkix/certs/OCSPEE23.cert
security/nss/tests/libpkix/certs/OCSPEE31.cert
security/nss/tests/libpkix/certs/OCSPEE32.cert
security/nss/tests/libpkix/certs/OCSPEE33.cert
security/nss/tests/libpkix/certs/OCSPRoot.cert
security/nss/tests/libpkix/certs/OCSPRoot.p12
security/nss/tests/libpkix/certs/PayPalEE.cert
security/nss/tests/memleak/ignored
security/nss/tests/pkcs11/netscape/suites/security/pkcs11/pk11test.h
security/nss/tests/pkcs11/netscape/suites/security/ssl/sslt.c
security/nss/tests/pkcs11/netscape/suites/security/ssl/sslt.h
security/nss/tests/pkcs11/netscape/trivial/trivial.c
--- a/security/coreconf/HP-UX.mk
+++ b/security/coreconf/HP-UX.mk
@@ -51,17 +51,20 @@ ifeq ($(OS_TEST),ia64)
 	endif
 	DLL_SUFFIX = so
 else
 	CPU_ARCH = hppa
 	DLL_SUFFIX = sl
 endif
 CC         = cc
 CCC        = CC
-OS_CFLAGS  += -Ae $(DSO_CFLAGS) -DHPUX -D$(CPU_ARCH) -D_HPUX_SOURCE -D_USE_BIG_FDS
+ifndef NS_USE_GCC
+OS_CFLAGS  += -Ae
+endif
+OS_CFLAGS  += $(DSO_CFLAGS) -DHPUX -D$(CPU_ARCH) -D_HPUX_SOURCE -D_USE_BIG_FDS
 
 ifeq ($(DEFAULT_IMPL_STRATEGY),_PTH)
 	USE_PTHREADS = 1
 	ifeq ($(CLASSIC_NSPR),1)
 		USE_PTHREADS =
 		IMPL_STRATEGY = _CLASSIC
 	endif
 	ifeq ($(PTHREADS_USER),1)
@@ -71,26 +74,43 @@ ifeq ($(DEFAULT_IMPL_STRATEGY),_PTH)
 endif
 
 ifdef PTHREADS_USER
 	OS_CFLAGS	+= -D_POSIX_C_SOURCE=199506L
 endif
 
 LDFLAGS			= -z -Wl,+s
 
+ifdef NS_USE_GCC
+LD = $(CC)
+endif
 MKSHLIB			= $(LD) $(DSO_LDOPTS) $(RPATH)
 ifdef MAPFILE
+ifndef NS_USE_GCC
 MKSHLIB += -c $(MAPFILE)
+else
+MKSHLIB += -Wl,-c,$(MAPFILE)
+endif
 endif
 PROCESS_MAP_FILE = grep -v ';+' $< | grep -v ';-' | \
          sed -e 's; DATA ;;' -e 's,;;,,' -e 's,;.*,,' -e 's,^,+e ,' > $@
 
+ifndef NS_USE_GCC
 DSO_LDOPTS		= -b +h $(notdir $@)
 RPATH			= +b '$$ORIGIN'
+else
+DSO_LDOPTS		= -shared -Wl,+h,$(notdir $@)
+RPATH			= -Wl,+b,'$$ORIGIN'
+endif
 ifneq ($(OS_TEST),ia64)
 # pa-risc
 ifndef USE_64
 RPATH			=
 endif
 endif
 
 # +Z generates position independent code for use in shared libraries.
+ifndef NS_USE_GCC
 DSO_CFLAGS = +Z
+else
+DSO_CFLAGS = -fPIC
+ASFLAGS   += -x assembler-with-cpp
+endif
--- a/security/coreconf/Linux.mk
+++ b/security/coreconf/Linux.mk
@@ -153,16 +153,27 @@ LDFLAGS			+= $(ARCHFLAG)
 # INCLUDES += -I/usr/include -Y/usr/include/linux
 G++INCLUDES		= -I/usr/include/g++
 
 #
 # Always set CPU_TAG on Linux, WINCE.
 #
 CPU_TAG = _$(CPU_ARCH)
 
+#
+# On Linux 2.6 or later, build libfreebl3.so with no NSPR and libnssutil3.so
+# dependencies by default.  Set FREEBL_NO_DEPEND to 0 in the environment to
+# override this.
+#
+ifeq (2.6,$(firstword $(sort 2.6 $(OS_RELEASE))))
+ifndef FREEBL_NO_DEPEND
+FREEBL_NO_DEPEND = 1
+endif
+endif
+
 USE_SYSTEM_ZLIB = 1
 ZLIB_LIBS = -lz
 
 # The -rpath '$$ORIGIN' linker option instructs this library to search for its
 # dependencies in the same directory where it resides.
 ifeq ($(BUILD_SUN_PKG), 1)
 ifeq ($(USE_64), 1)
 RPATH = -Wl,-rpath,'$$ORIGIN:/opt/sun/private/lib64:/opt/sun/private/lib'
--- a/security/coreconf/WIN32.mk
+++ b/security/coreconf/WIN32.mk
@@ -138,17 +138,17 @@ else # !NS_USE_GCC
 		LDFLAGS += -DEBUG -OPT:REF
 	endif
     else
 	#
 	# Define USE_DEBUG_RTL if you want to use the debug runtime library
 	# (RTL) in the debug build
 	#
 	ifdef USE_DEBUG_RTL
-		OS_CFLAGS += -MDd
+		OS_CFLAGS += -MDd -DUSE_DEBUG_RTL -D_CRTDBG_MAP_ALLOC
 	else
 		OS_CFLAGS += -MD
 	endif
 	OPTIMIZER += -Zi -Fd$(OBJDIR)/ -Od
 	NULLSTRING :=
 	SPACE      := $(NULLSTRING) # end of the line
 	USERNAME   := $(subst $(SPACE),_,$(USERNAME))
 	USERNAME   := $(subst -,_,$(USERNAME))
@@ -172,17 +172,17 @@ endif # !MSVC6
 endif # NS_USE_GCC
 
 ifdef USE_64
 DEFINES += -DWIN64
 else
 DEFINES += -DWIN32
 endif
 
-ifeq ($(CPU_ARCH), x386)
+ifeq (,$(filter-out x386 x86_64,$(CPU_ARCH)))
 ifdef USE_64
 	DEFINES += -D_AMD64_
 else
 	DEFINES += -D_X86_
 endif
 endif
 ifeq ($(CPU_ARCH), ALPHA)
 	DEFINES += -D_ALPHA_=1
--- a/security/coreconf/jniregen.pl
+++ b/security/coreconf/jniregen.pl
@@ -39,17 +39,17 @@
 # Input: -d dir -j javahcmd foo1 foo2 . . .
 #        Compares generated "_jni/foo1.h" file with "foo1.class", and
 #        generated "_jni/foo2.h" file with "foo2.class", etc.
 #        (NOTE:  unlike its closely related cousin, outofdate.pl,
 #                the "-d dir" must always be specified)
 #        Runs the javahcmd on all files that are different.
 #
 # Returns: list of headers which are OLDER than corresponding class
-#          files (non-existant class files are considered to be real old :-)
+#          files (non-existent class files are considered to be real old :-)
 
 my $javah = "";
 my $classdir = "";
 
 while(1) {
     if ($ARGV[0] eq '-d') {
         $classdir = $ARGV[1];
         $classdir .= "/";
--- a/security/coreconf/location.mk
+++ b/security/coreconf/location.mk
@@ -94,9 +94,13 @@ endif
 ifdef SOFTOKEN_INCLUDE_DIR
     INCLUDES += -I$(SOFTOKEN_INCLUDE_DIR)
 endif
 
 ifndef SOFTOKEN_LIB_DIR
     SOFTOKEN_LIB_DIR = $(DIST)/lib
 endif
 
+ifndef SQLITE_LIB_NAME
+    SQLITE_LIB_NAME = sqlite3
+endif
+
 MK_LOCATION = included
--- a/security/coreconf/outofdate.pl
+++ b/security/coreconf/outofdate.pl
@@ -35,17 +35,17 @@
 # the terms of any one of the MPL, the GPL or the LGPL.
 #
 # ***** END LICENSE BLOCK *****
 
 #Input: [-d dir] foo1.java foo2.java
 #Compares with: foo1.class foo2.class (if -d specified, checks in 'dir', 
 #  otherwise assumes .class files in same directory as .java files)
 #Returns: list of input arguments which are newer than corresponding class
-#files (non-existant class files are considered to be real old :-)
+#files (non-existent class files are considered to be real old :-)
 
 $found = 1;
 
 if ($ARGV[0] eq '-d') {
     $classdir = $ARGV[1];
     $classdir .= "/";
     shift;
     shift;
--- a/security/coreconf/rules.mk
+++ b/security/coreconf/rules.mk
@@ -917,17 +917,17 @@ endif
 ifdef MKDEPENDENCIES
 
 # For Windows, $(MKDEPENDENCIES) must be -included before including rules.mk
 
 $(MKDEPENDENCIES)::
 	@$(MAKE_OBJDIR)
 	touch $(MKDEPENDENCIES) 
 	chmod u+w $(MKDEPENDENCIES) 
-#on NT, the preceeding touch command creates a read-only file !?!?!
+#on NT, the preceding touch command creates a read-only file !?!?!
 #which is why we have to explicitly chmod it.
 	$(MKDEPEND) -p$(OBJDIR_NAME)/ -o'$(OBJ_SUFFIX)' -f$(MKDEPENDENCIES) \
 $(NOMD_CFLAGS) $(YOPT) $(CSRCS) $(CPPSRCS) $(ASFILES)
 
 $(MKDEPEND):: $(MKDEPEND_DIR)/*.c $(MKDEPEND_DIR)/*.h
 	cd $(MKDEPEND_DIR); $(MAKE)
 
 ifdef OBJS
new file mode 100644
--- /dev/null
+++ b/security/nss/TAG-INFO
@@ -0,0 +1,1 @@
+NSS_3_12_7_BETA2
--- a/security/nss/cmd/bltest/blapitest.c
+++ b/security/nss/cmd/bltest/blapitest.c
@@ -56,17 +56,17 @@
 #ifdef NSS_ENABLE_ECC
 #include "ecl-curve.h"
 SECStatus EC_DecodeParams(const SECItem *encodedParams, 
 	ECParams **ecparams);
 SECStatus EC_CopyParams(PRArenaPool *arena, ECParams *dstParams,
 	      const ECParams *srcParams);
 #endif
 
-/* Temporary - add debugging ouput on windows for RSA to track QA failure */
+/* Temporary - add debugging output on windows for RSA to track QA failure */
 #ifdef _WIN32
 #define TRACK_BLTEST_BUG
     char __bltDBG[] = "BLTEST DEBUG";
 #endif
 
 char *progName;
 char *testdir = NULL;
 
--- a/security/nss/cmd/certutil/certext.c
+++ b/security/nss/cmd/certutil/certext.c
@@ -95,18 +95,18 @@ Gets_s(char *buff, size_t size) {
     }
     return str;
 }
 
 
 static SECStatus
 PrintChoicesAndGetAnswer(char* str, char* rBuff, int rSize)
 {
-    fprintf(stdout, str);
-    fprintf(stdout, " > ");
+    fputs(str, stdout);
+    fputs(" > ", stdout);
     fflush (stdout);
     if (Gets_s(rBuff, rSize) == NULL) {
         PORT_SetError(SEC_ERROR_INPUT_LEN);
         return SECFailure;
     }
     return SECSuccess;
 }
 
--- a/security/nss/cmd/certutil/certutil.c
+++ b/security/nss/cmd/certutil/certutil.c
@@ -346,17 +346,17 @@ CertReq(SECKEYPrivateKey *privk, SECKEYP
 	PR_fprintf(outFile, "Email: %s\n", email);
 	PR_fprintf(outFile, "Organization: %s\n", org);
 	PR_fprintf(outFile, "State: %s\n", state);
 	PR_fprintf(outFile, "Country: %s\n\n", country);
 
 	PR_fprintf(outFile, "%s\n", NS_CERTREQ_HEADER);
 	numBytes = PR_Write(outFile, obuf, total);
 	if (numBytes != total) {
-	    SECU_PrintSystemError(progName, "write error");
+	    SECU_PrintError(progName, "write error");
 	    return SECFailure;
 	}
 	PR_fprintf(outFile, "\n%s\n", NS_CERTREQ_TRAILER);
     } else {
 	numBytes = PR_Write(outFile, result.data, result.len);
 	if (numBytes != (int)result.len) {
 	    SECU_PrintSystemError(progName, "write error");
 	    return SECFailure;
@@ -986,16 +986,18 @@ Usage(char *progName)
 	progName);
     FPS "\t%s -O -n cert-name [-X] [-d certdir] [-P dbprefix]\n", progName);
     FPS "\t%s -R -s subj -o cert-request-file [-d certdir] [-P dbprefix] [-p phone] [-a]\n"
 	"\t\t [-7 emailAddrs] [-k key-type-or-id] [-h token-name] [-f pwfile] [-g key-size]\n",
 	progName);
     FPS "\t%s -V -n cert-name -u usage [-b time] [-e] \n"
 	"\t\t[-X] [-d certdir] [-P dbprefix]\n",
 	progName);
+    FPS "Usage:  %s -W [-d certdir] [-f pwfile] [-@newpwfile]\n",
+	progName);
     FPS "\t%s -S -n cert-name -s subj [-c issuer-name | -x]  -t trustargs\n"
 	"\t\t [-k key-type-or-id] [-q key-params] [-h token-name] [-g key-size]\n"
         "\t\t [-m serial-number] [-w warp-months] [-v months-valid]\n"
 	"\t\t [-f pwfile] [-d certdir] [-P dbprefix]\n"
         "\t\t [-p phone] [-1] [-2] [-3] [-4] [-5] [-6] [-7 emailAddrs]\n"
         "\t\t [-8 DNS-names]\n"
         "\t\t [--extAIA] [--extSIA] [--extCP] [--extPM] [--extPC] [--extIA]\n"
         "\t\t [--extSKID]\n", progName);
@@ -1306,16 +1308,25 @@ static void LongUsage(char *progName)
     FPS "%-20s Cert database directory (default is ~/.netscape)\n",
 	"   -d certdir");
     FPS "%-20s Cert & Key database prefix\n",
 	"   -P dbprefix");
     FPS "%-20s force the database to open R/W\n",
 	"   -X");
     FPS "\n");
 
+    FPS "%-15s Change the key database password\n",
+	"-W");
+    FPS "%-20s cert and key database directory\n",
+	"   -d certdir");
+    FPS "%-20s Specify a file with the current password\n",
+	"   -f pwfile");
+    FPS "%-20s Specify a file with the new password in two lines\n",
+	"   -@ newpwfile");
+
     FPS "%-15s Upgrade an old database and merge it into a new one\n",
 	"--upgrade-merge");
     FPS "%-20s Cert database directory to merge into (default is ~/.netscape)\n",
 	"   -d certdir");
     FPS "%-20s Cert & Key database prefix of the target database\n",
 	"   -P dbprefix");
     FPS "%-20s Specify the password file for the target database\n",
 	"   -f pwfile");
@@ -2885,51 +2896,75 @@ shutdown:
      * to allow white space in a command line argument.  The
      * double quote character cannot be escaped and quoting cannot
      * be nested in this version.
      * - each line in the batch file is limited to 512 characters
     */
 
     if ((SECSuccess == rv) && certutil.commands[cmd_Batch].activated) {
 	FILE* batchFile = NULL;
-        char nextcommand[512];
+        char *nextcommand = NULL;
+	PRInt32 cmd_len = 0, buf_size = 0;
+	static const int increment = 512;
+
         if (!certutil.options[opt_InputFile].activated ||
             !certutil.options[opt_InputFile].arg) {
 	    PR_fprintf(PR_STDERR,
 	               "%s:  no batch input file specified.\n",
 	               progName);
 	    return 255;
         }
         batchFile = fopen(certutil.options[opt_InputFile].arg, "r");
         if (!batchFile) {
 	    PR_fprintf(PR_STDERR,
 	               "%s:  unable to open \"%s\" for reading (%ld, %ld).\n",
 	               progName, certutil.options[opt_InputFile].arg,
 	               PR_GetError(), PR_GetOSError());
 	    return 255;
         }
         /* read and execute command-lines in a loop */
-        while ( (SECSuccess == rv ) &&
-                fgets(nextcommand, sizeof(nextcommand), batchFile)) {
-            /* we now need to split the command into argc / argv format */
-            char* commandline = PORT_Strdup(nextcommand);
+        while ( SECSuccess == rv ) {
             PRBool invalid = PR_FALSE;
             int newargc = 2;
             char* space = NULL;
             char* nextarg = NULL;
             char** newargv = NULL;
-            char* crlf = PORT_Strrchr(commandline, '\n');
+            char* crlf;
+
+	    if (cmd_len + increment > buf_size) {
+	        char * new_buf;
+		buf_size += increment;
+	        new_buf = PORT_Realloc(nextcommand, buf_size);
+		if (!new_buf) {
+		    PR_fprintf(PR_STDERR, "%s: PORT_Realloc(%ld) failed\n",
+			       progName, buf_size);
+		    break;
+		}
+		nextcommand = new_buf;
+		nextcommand[cmd_len] = '\0';
+	    }
+	    if (!fgets(nextcommand + cmd_len, buf_size - cmd_len, batchFile)) {
+		break;
+	    }
+            crlf = PORT_Strrchr(nextcommand, '\n');
             if (crlf) {
                 *crlf = '\0';
             }
+	    cmd_len = strlen(nextcommand);
+	    if (cmd_len && nextcommand[cmd_len - 1] == '\\') {
+	        nextcommand[--cmd_len] = '\0';
+		continue;
+	    }
+
+            /* we now need to split the command into argc / argv format */
 
             newargv = PORT_Alloc(sizeof(char*)*(newargc+1));
             newargv[0] = progName;
-            newargv[1] = commandline;
-            nextarg = commandline;
+            newargv[1] = nextcommand;
+            nextarg = nextcommand;
             while ((space = PORT_Strpbrk(nextarg, " \f\n\r\t\v")) ) {
                 while (isspace(*space) ) {
                     *space = '\0';
                     space ++;
                 }
                 if (*space == '\0') {
                     break;
                 } else if (*space != '\"') {
@@ -2956,18 +2991,20 @@ shutdown:
                 PR_fprintf(PR_STDERR, "Missing closing quote in batch command :\n%s\nNot executed.\n",
                            nextcommand);
                 rv = SECFailure;
             } else {
                 if (0 != certutil_main(newargc, newargv, PR_FALSE) )
                     rv = SECFailure;
             }
             PORT_Free(newargv);
-            PORT_Free(commandline);
+	    cmd_len = 0;
+	    nextcommand[0] = '\0';
         }
+	PORT_Free(nextcommand);
         fclose(batchFile);
     }
 
     if ((initialized == PR_TRUE) && NSS_Shutdown() != SECSuccess) {
         exit(1);
     }
     if (rv == SECSuccess) {
 	return 0;
--- a/security/nss/cmd/certutil/keystuff.c
+++ b/security/nss/cmd/certutil/keystuff.c
@@ -103,17 +103,17 @@ UpdateRNG(void)
     FPS "creation of your key.  One of the easiest ways to create a\n");
     FPS "random seed is to use the timing of keystrokes on a keyboard.\n");
     FPS "\n");
     FPS "To begin, type keys on the keyboard until this progress meter\n");
     FPS "is full.  DO NOT USE THE AUTOREPEAT FUNCTION ON YOUR KEYBOARD!\n");
     FPS "\n");
     FPS "\n");
     FPS "Continue typing until the progress meter is full:\n\n");
-    FPS meter);
+    FPS "%s", meter);
     FPS "\r|");
 
     /* turn off echo on stdin & return on 1 char instead of NL */
     fd = fileno(stdin);
 
 #if defined(XP_UNIX)
     tcgetattr(fd, &tio);
     orig_lflag = tio.c_lflag;
--- a/security/nss/cmd/crlutil/crlutil.c
+++ b/security/nss/cmd/crlutil/crlutil.c
@@ -557,17 +557,17 @@ UpdateCrl(CERTSignedCrl *signCrl, PRFile
 	goto loser;
     }
 
   loser:
     /* CommitExtensionsAndEntries is partially responsible for freeing
      * up memory that was used for CRL generation. Should be called regardless
      * of previouse call status, but only after initialization of
      * crlGenData was done. It will commit all changes that was done before
-     * an error has occured.
+     * an error has occurred.
      */
     if (SECSuccess != CRLGEN_CommitExtensionsAndEntries(crlGenData)) {
         SECU_PrintError(progName, "crl generation failed");
         rv = SECFailure;
     }
     CRLGEN_FinalizeCrlGeneration(crlGenData);    
     return rv;
 }
--- a/security/nss/cmd/lib/SECerrs.h
+++ b/security/nss/cmd/lib/SECerrs.h
@@ -540,17 +540,17 @@ ER3(SEC_ERROR_BAD_LDAP_RESPONSE,    		(S
 
 ER3(SEC_ERROR_FAILED_TO_ENCODE_DATA,    		(SEC_ERROR_BASE + 164),
 "Failed to encode data with ASN1 encoder")
 
 ER3(SEC_ERROR_BAD_INFO_ACCESS_LOCATION,    		(SEC_ERROR_BASE + 165),
 "Bad information access location in cert extension")
 
 ER3(SEC_ERROR_LIBPKIX_INTERNAL,      		(SEC_ERROR_BASE + 166),
-"Libpkix internal error occured during cert validation.")
+"Libpkix internal error occurred during cert validation.")
 
 ER3(SEC_ERROR_PKCS11_GENERAL_ERROR,      		(SEC_ERROR_BASE + 167),
 "A PKCS #11 module returned CKR_GENERAL_ERROR, indicating that an unrecoverable error has occurred.")
 
 ER3(SEC_ERROR_PKCS11_FUNCTION_FAILED,      		(SEC_ERROR_BASE + 168),
 "A PKCS #11 module returned CKR_FUNCTION_FAILED, indicating that the requested function could not be performed.  Trying the same operation again might succeed.")
 
 ER3(SEC_ERROR_PKCS11_DEVICE_ERROR,      		(SEC_ERROR_BASE + 169),
--- a/security/nss/cmd/lib/secutil.c
+++ b/security/nss/cmd/lib/secutil.c
@@ -1058,17 +1058,17 @@ secu_PrintTime(FILE *out, int64 time, ch
 	return;
 
     if (m != NULL) {
 	SECU_Indent(out, level);
 	fprintf(out, "%s: ", m);
     }
 
     if (PR_FormatTime(timeString, 256, "%a %b %d %H:%M:%S %Y", &printableTime)) {
-        fprintf(out, timeString);
+        fputs(timeString, out);
     }
 
     if (m != NULL)
 	fprintf(out, "\n");
 
     PORT_Free(timeString);
 }
 
@@ -2839,17 +2839,17 @@ SECU_PrintCRLInfo(FILE *out, CERTCrl *cr
     SECU_PrintTimeChoice(out, &(crl->lastUpdate), "This Update", level + 1);
     if (crl->nextUpdate.data && crl->nextUpdate.len) /* is optional */
 	SECU_PrintTimeChoice(out, &(crl->nextUpdate), "Next Update", level + 1);
     
     if (crl->entries != NULL) {
 	iv = 0;
 	while ((entry = crl->entries[iv++]) != NULL) {
 	    sprintf(om, "Entry (%x):\n", iv); 
-	    SECU_Indent(out, level + 1); fprintf(out, om);
+	    SECU_Indent(out, level + 1); fputs(om, out);
 	    SECU_PrintInteger(out, &(entry->serialNumber), "Serial Number",
 			      level + 2);
 	    SECU_PrintTimeChoice(out, &(entry->revocationDate), 
 	                         "Revocation Date", level + 2);
 	    SECU_PrintExtensions(out, entry->extensions, 
 	                         "Entry Extensions", level + 2);
 	}
     }
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
--- a/security/nss/cmd/modutil/pk11.c
+++ b/security/nss/cmd/modutil/pk11.c
@@ -288,17 +288,17 @@ AddModule(char *moduleName, char *libFil
 		  SECMOD_PubMechFlagstoInternal(mechanisms),
 		  SECMOD_PubCipherFlagstoInternal(ciphers),
 		  modparms, NULL );
 
     if(status != SECSuccess) {
 	char* errtxt=NULL;
 	PRInt32 copied = 0;
 	if (PR_GetErrorTextLength()) {
-	    errtxt = PR_Malloc(PR_GetErrorTextLength());
+	    errtxt = PR_Malloc(PR_GetErrorTextLength() + 1);
 	    copied = PR_GetErrorText(errtxt);
 	}
 	if (copied && errtxt) {
 	    PR_fprintf(PR_STDERR, errStrings[ADD_MODULE_FAILED_ERR], 
 		       moduleName, errtxt);
 	    PR_Free(errtxt);
 	} else {
 	    PR_fprintf(PR_STDERR, errStrings[ADD_MODULE_FAILED_ERR], 
--- a/security/nss/cmd/pk11mode/pk11mode.c
+++ b/security/nss/cmd/pk11mode/pk11mode.c
@@ -3704,17 +3704,17 @@ CK_RV PKM_FindAllObjects(CK_FUNCTION_LIS
         crv = pFunctionList->C_GetAttributeValue(h, o, pT2, nAttributes);
         switch ( crv ) {
         case CKR_OK:
         case CKR_ATTRIBUTE_SENSITIVE:
         case CKR_ATTRIBUTE_TYPE_INVALID:
         case CKR_BUFFER_TOO_SMALL:
             break;
         default:
-            PKM_Error(  "C_GetAtributeValue(%lu, %lu, {existant attribute"
+            PKM_Error(  "C_GetAtributeValue(%lu, %lu, {existent attribute"
                         " types}, %lu) returned 0x%08X, %-26s\n",
                         h, o, nAttributes, crv, PKM_CK_RVtoStr(crv));
             return crv;
         }
 
         for ( l = 0; l < nAttributes; l++ ) {
             attName = getNameFromAttribute(pT2[l].type);
             if (!attName) attName = "unknown attribute";
--- a/security/nss/cmd/pk11util/pk11util.c
+++ b/security/nss/cmd/pk11util/pk11util.c
@@ -40,17 +40,17 @@
 
 #if defined(WIN32)
 #undef __STDC__
 #include "fcntl.h"
 #include "io.h"
 #include <fcntl.h>
 #else
 #include <unistd.h>
-#include <sys/fcntl.h>
+#include <fcntl.h>
 #endif
 
 #include "secutil.h"
 
 
 #include "nspr.h"
 #include "prtypes.h"
 #include "prtime.h"
--- a/security/nss/cmd/pk12util/pk12util.c
+++ b/security/nss/cmd/pk12util/pk12util.c
@@ -29,16 +29,21 @@
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
+#ifdef _CRTDBG_MAP_ALLOC
+#include <stdlib.h>
+#include <crtdbg.h>
+#endif
+
 #include "nspr.h"
 #include "secutil.h"
 #include "pk11func.h"
 #include "pkcs12.h"
 #include "p12plcy.h"
 #include "pk12util.h"
 #include "nss.h"
 #include "secport.h"
@@ -477,16 +482,17 @@ done:
     PR_Close(p12cxt->file);
     p12cxt->file = NULL;
     /* PK11_FreeSlot(slot); */
     p12u_DestroyContext(&p12cxt, PR_FALSE);
 
     if (pwitem) {
 	SECITEM_ZfreeItem(pwitem, PR_TRUE);
     }
+    SECITEM_ZfreeItem(&p12file, PR_FALSE);
     return p12dcx;
 }
 
 /*
  * given a filename for pkcs12 file, imports certs and keys
  *
  * Change: altitude
  *  I've changed this function so that it takes the keydb and pkcs12 file
@@ -555,21 +561,21 @@ static void
 p12u_DoPKCS12ExportErrors()
 {
     int error_value;
 
     error_value = PORT_GetError();
     if ((error_value == SEC_ERROR_PKCS12_UNABLE_TO_EXPORT_KEY) ||
 	(error_value == SEC_ERROR_PKCS12_UNABLE_TO_LOCATE_OBJECT_BY_NAME) ||
 	(error_value == SEC_ERROR_PKCS12_UNABLE_TO_WRITE)) {
-	fprintf(stderr, SECU_ErrorStringRaw((int16)error_value));
+	fputs(SECU_ErrorStringRaw((int16)error_value), stderr);
     } else if(error_value == SEC_ERROR_USER_CANCELLED) {
 	;
     } else {
-	fprintf(stderr, SECU_ErrorStringRaw(SEC_ERROR_EXPORTING_CERTIFICATES));
+	fputs(SECU_ErrorStringRaw(SEC_ERROR_EXPORTING_CERTIFICATES), stderr);
     }
 }
 
 static void
 p12u_WriteToExportFile(void *arg, const char *buf, unsigned long len)
 {
     p12uContext *p12cxt = arg;
     int writeLen;
@@ -973,18 +979,22 @@ main(int argc, char **argv)
     char *export_file = NULL;
     char *dbprefix = "";
     SECStatus rv;
     SECOidTag cipher = 
             SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_3KEY_TRIPLE_DES_CBC;
     SECOidTag certCipher;
     int keyLen = 0;
     int certKeyLen = 0;
+    secuCommand pk12util;
 
-    secuCommand pk12util;
+#ifdef _CRTDBG_MAP_ALLOC
+    _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
+#endif
+
     pk12util.numCommands = 0;
     pk12util.commands = 0;
     pk12util.numOptions = sizeof(pk12util_options) / sizeof(secuCommandFlag);
     pk12util.options = pk12util_options;
 
     progName = strrchr(argv[0], '/');
     progName = progName ? progName+1 : argv[0];
 
@@ -1119,10 +1129,12 @@ done:
 	PORT_ZFree(slotPw.data, PL_strlen(slotPw.data));
     if (p12FilePw.data != NULL)
 	PORT_ZFree(p12FilePw.data, PL_strlen(p12FilePw.data));
     if (slot) 
     	PK11_FreeSlot(slot);
     if (NSS_Shutdown() != SECSuccess) {
 	pk12uErrno = 1;
     }
+    PR_Cleanup();
+    PL_ArenaFinish();
     return pk12uErrno;
 }
--- a/security/nss/cmd/platlibs.mk
+++ b/security/nss/cmd/platlibs.mk
@@ -75,18 +75,16 @@ ifeq ($(USE_64), 1)
 EXTRA_SHARED_LIBS += \
 -Wl,+b,'$$ORIGIN/../../lib/pa20_64:$$ORIGIN/../../lib/64:$$ORIGIN/../lib'
 else
 EXTRA_SHARED_LIBS += -Wl,+b,'$$ORIGIN/../lib'
 endif
 endif
 endif
 
-SQLITE=-lsqlite3
-
 ifdef NSS_DISABLE_DBM
 DBMLIB = $(NULL)
 else
 DBMLIB = $(DIST)/lib/$(LIB_PREFIX)dbm.$(LIB_SUFFIX) 
 endif
 
 ifdef USE_STATIC_LIBS
 
@@ -105,17 +103,16 @@ PKIXLIB = \
 	$(DIST)/lib/$(LIB_PREFIX)pkixchecker.$(LIB_SUFFIX) \
 	$(DIST)/lib/$(LIB_PREFIX)pkixpki.$(LIB_SUFFIX) \
 	$(DIST)/lib/$(LIB_PREFIX)pkixtop.$(LIB_SUFFIX) \
 	$(DIST)/lib/$(LIB_PREFIX)pkixresults.$(LIB_SUFFIX) \
 	$(DIST)/lib/$(LIB_PREFIX)pkixcertsel.$(LIB_SUFFIX)
 
 # can't do this in manifest.mn because OS_ARCH isn't defined there.
 ifeq (,$(filter-out WINNT WINCE,$(OS_ARCH))) 
-SQLITE = $(LIB_PREFIX)sqlite3.$(LIB_SUFFIX)
 
 EXTRA_LIBS += \
 	$(DIST)/lib/$(LIB_PREFIX)smime.$(LIB_SUFFIX) \
 	$(DIST)/lib/$(LIB_PREFIX)ssl.$(LIB_SUFFIX) \
 	$(DIST)/lib/$(LIB_PREFIX)nss.$(LIB_SUFFIX) \
 	$(DIST)/lib/$(LIB_PREFIX)ssl.$(LIB_SUFFIX) \
 	$(DIST)/lib/$(LIB_PREFIX)sectool.$(LIB_SUFFIX) \
 	$(DIST)/lib/$(LIB_PREFIX)pkcs12.$(LIB_SUFFIX) \
@@ -126,17 +123,17 @@ EXTRA_LIBS += \
 	$(DIST)/lib/$(LIB_PREFIX)certdb.$(LIB_SUFFIX) \
 	$(DIST)/lib/$(LIB_PREFIX)softokn.$(LIB_SUFFIX) \
 	$(CRYPTOLIB) \
 	$(DIST)/lib/$(LIB_PREFIX)nsspki.$(LIB_SUFFIX) \
 	$(DIST)/lib/$(LIB_PREFIX)nssdev.$(LIB_SUFFIX) \
 	$(DIST)/lib/$(LIB_PREFIX)nssb.$(LIB_SUFFIX) \
 	$(PKIXLIB) \
 	$(DBMLIB) \
-	$(DIST)/lib/$(SQLITE) \
+	$(DIST)/lib/$(LIB_PREFIX)$(SQLITE_LIB_NAME).$(LIB_SUFFIX) \
 	$(DIST)/lib/$(LIB_PREFIX)nssutil3.$(LIB_SUFFIX) \
 	$(NSPR_LIB_DIR)/$(NSPR31_LIB_PREFIX)plc4.$(LIB_SUFFIX) \
 	$(NSPR_LIB_DIR)/$(NSPR31_LIB_PREFIX)plds4.$(LIB_SUFFIX) \
 	$(NSPR_LIB_DIR)/$(NSPR31_LIB_PREFIX)nspr4.$(LIB_SUFFIX) \
 	$(NULL)
 
 # $(PROGRAM) has NO explicit dependencies on $(OS_LIBS)
 #OS_LIBS += \
@@ -175,17 +172,17 @@ EXTRA_LIBS += \
 ifeq ($(OS_ARCH), AIX) 
 EXTRA_SHARED_LIBS += -brtl 
 endif
 
 # $(PROGRAM) has NO explicit dependencies on $(EXTRA_SHARED_LIBS)
 # $(EXTRA_SHARED_LIBS) come before $(OS_LIBS), except on AIX.
 EXTRA_SHARED_LIBS += \
 	-L$(DIST)/lib \
-	$(SQLITE) \
+	-l$(SQLITE_LIB_NAME) \
 	-L$(NSSUTIL_LIB_DIR) \
 	-lnssutil3 \
 	-L$(NSPR_LIB_DIR) \
 	-lplc4 \
 	-lplds4 \
 	-lnspr4 \
 	$(NULL)
 endif
--- a/security/nss/cmd/selfserv/selfserv.c
+++ b/security/nss/cmd/selfserv/selfserv.c
@@ -730,18 +730,18 @@ logger(void *arg)
     for (;;) {
         /* OK, implementing a new sleep algorithm here... always sleep 
          * for 1 second but print out info at the user-specified interval.
          * This way, we don't overflow all of our PR_Atomic* functions and 
          * we don't have to use locks. 
          */
         PR_Sleep(logPeriodTicks);
         secondsElapsed++;
-        totalPeriodBytes +=  PR_AtomicSet(&loggerBytes, 0);
-        totalPeriodBytesTCP += PR_AtomicSet(&loggerBytesTCP, 0);
+        totalPeriodBytes +=  PR_ATOMIC_SET(&loggerBytes, 0);
+        totalPeriodBytesTCP += PR_ATOMIC_SET(&loggerBytesTCP, 0);
         if (secondsElapsed != logPeriod) {
             continue;
         }
         /* when we reach the user-specified logging interval, print out all
          * data 
          */
         secondsElapsed = 0;
         latestTime = PR_IntervalNow();
@@ -1344,27 +1344,27 @@ handle_connection(
 	if (rv < 0) {
 	    errWarn("PR_Writev");
 	    break;
 	}
 
         /* Send testBulkTotal chunks to the client. Unlimited if 0. */
         if (testBulk) {
             while (0 < (rv = PR_Write(ssl_sock, testBulkBuf, testBulkSize))) {
-                PR_AtomicAdd(&loggerBytes, rv);
-                PR_AtomicIncrement(&bulkSentChunks);
+                PR_ATOMIC_ADD(&loggerBytes, rv);
+                PR_ATOMIC_INCREMENT(&bulkSentChunks);
                 if ((bulkSentChunks > testBulkTotal) && (testBulkTotal != 0))
                     break;
             }
 
             /* There was a write error, so close this connection. */
             if (bulkSentChunks <= testBulkTotal) {
                 errWarn("PR_Write");
             }
-            PR_AtomicDecrement(&loggerOps);
+            PR_ATOMIC_DECREMENT(&loggerOps);
             break;
         }
     } while (0);
 
 cleanup:
     if (ssl_sock) {
         PR_Close(ssl_sock);
     } else if (tcp_sock) {
@@ -1439,17 +1439,17 @@ do_accepts(
 	    }
 	    stopping = 1;
 	    break;
 	}
 
         VLOG(("selfserv: do_accept: Got connection\n"));
 
         if (logStats) {
-            PR_AtomicIncrement(&loggerOps);
+            PR_ATOMIC_INCREMENT(&loggerOps);
         }
 
 	PZ_Lock(qLock);
 	while (PR_CLIST_IS_EMPTY(&freeJobs) && !stopping) {
             PZ_WaitCondVar(freeListNotEmptyCv, PR_INTERVAL_NO_TIMEOUT);
 	}
 	if (stopping) {
 	    PZ_Unlock(qLock);
@@ -1553,47 +1553,47 @@ logWritev (
     const PRIOVec  *iov,
     PRInt32         size, 
     PRIntervalTime  timeout )
 {
     PRInt32 rv = (fd->lower->methods->writev)(fd->lower, iov, size, 
         timeout);
     /* Add the amount written, but not if there's an error */
     if (rv > 0) 
-        PR_AtomicAdd(&loggerBytesTCP, rv);
+        PR_ATOMIC_ADD(&loggerBytesTCP, rv);
     return rv;
 }
     
 PRInt32 PR_CALLBACK 
 logWrite (
     PRFileDesc  *fd, 
     const void  *buf, 
     PRInt32      amount)
 {   
     PRInt32 rv = (fd->lower->methods->write)(fd->lower, buf, amount);
     /* Add the amount written, but not if there's an error */
     if (rv > 0) 
-        PR_AtomicAdd(&loggerBytesTCP, rv);
+        PR_ATOMIC_ADD(&loggerBytesTCP, rv);
     
     return rv;
 }
 
 PRInt32 PR_CALLBACK 
 logSend (
     PRFileDesc     *fd, 
     const void     *buf, 
     PRInt32         amount, 
     PRIntn          flags, 
     PRIntervalTime  timeout)
 {
     PRInt32 rv = (fd->lower->methods->send)(fd->lower, buf, amount, 
         flags, timeout);
     /* Add the amount written, but not if there's an error */
     if (rv > 0) 
-        PR_AtomicAdd(&loggerBytesTCP, rv);
+        PR_ATOMIC_ADD(&loggerBytesTCP, rv);
     return rv;
 }
  
 void initLoggingLayer(void)
 {   
     /* get a new layer ID */
     log_layer_id = PR_GetUniqueIdentity("Selfserv Logging");
     if (log_layer_id == PR_INVALID_IO_LAYER)
--- a/security/nss/cmd/signtool/javascript.c
+++ b/security/nss/cmd/signtool/javascript.c
@@ -1520,17 +1520,17 @@ extract_js(char *filename)
 		 * in relation to style= attributes.
 		 * Apparently, these can't flow across lines, so the start and
 		 * end line will be the same.  That helps matters.
 		 */
 		entityEnd = pairp->value;
 		while ( entityEnd && 
 		    (entityStart = PL_strstr(entityEnd, "&{")) /*}*/ != NULL) {
 		    entityStart += 2; /* point at beginning of actual entity */
-		    entityEnd = PL_strstr(entityStart, /*{*/ "}");
+		    entityEnd = PL_strchr(entityStart, '}');
 		    if (entityEnd) {
 			/* Put this item on the entity list */
 			*entityEnd = '\0';
 			entityItem = CreateTextItem(PL_strdup(entityStart),
 					    pairp->valueLine, pairp->valueLine);
 			*entityEnd = /* { */ '}';
 			if (entityListTail) {
 			    entityListTail->next = entityItem;
@@ -1829,17 +1829,17 @@ copyinto (char *from, char *to)
 	    goto finish;
 	}
     }
 
     if ((outfp = PR_Open(to, PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE, 0777))
          == NULL) {
 	char	*errBuf = NULL;
 
-	errBuf = PR_Malloc(PR_GetErrorTextLength());
+	errBuf = PR_Malloc(PR_GetErrorTextLength() + 1);
 	PR_fprintf(errorFD, "ERROR: Unable to open \"%s\" for writing.\n", to);
 	if (PR_GetErrorText(errBuf)) {
 	    PR_fprintf(errorFD, "Cause: %s\n", errBuf);
 	}
 	if (errBuf) {
 	    PR_Free(errBuf);
 	}
 	errorCount++;
--- a/security/nss/cmd/signtool/signtool.c
+++ b/security/nss/cmd/signtool/signtool.c
@@ -728,18 +728,18 @@ ProcessOneOpt(OPT_TYPE type, char *arg)
 	zipfile = PL_strdup(arg);
 	ate = 1;
 	break;
     case GENKEY_OPT:
 	if (genkey) {
 	    PR_fprintf(errorFD, errStrings[DUPLICATE_OPTION_ERR],
 	         				"generate (-G)");
 	    warningCount++;
-	    PR_Free(zipfile); 
-	    zipfile = NULL;
+	    PR_Free(genkey); 
+	    genkey = NULL;
 	}
 	if (!arg) {
 	    PR_fprintf(errorFD, errStrings[OPTION_NEEDS_ARG_ERR],
 	         				"generate (-G)");
 	    errorCount++;
 	    goto loser;
 	}
 	genkey = PL_strdup(arg);
--- a/security/nss/cmd/signtool/zip.c
+++ b/security/nss/cmd/signtool/zip.c
@@ -69,17 +69,17 @@ JzipOpen(char *filename, char *comment)
 			(prtime.tm_sec & 0x3f);
 
     zipfile->fp = NULL;
     if (filename  && 
         (zipfile->fp = PR_Open(filename,
         PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE, 0777)) == NULL) {
 	char	*nsprErr;
 	if (PR_GetErrorTextLength()) {
-	    nsprErr = PR_Malloc(PR_GetErrorTextLength());
+	    nsprErr = PR_Malloc(PR_GetErrorTextLength() + 1);
 	    PR_GetErrorText(nsprErr);
 	} else {
 	    nsprErr = NULL;
 	}
 	PR_fprintf(errorFD, "%s: can't open output jar, %s.%s\n",
 	     PROGRAM_NAME,
 	    filename, nsprErr ? nsprErr : "");
 	if (nsprErr) 
@@ -189,17 +189,17 @@ JzipAdd(char *fullname, char *filename, 
     zipfp = zipfile->fp;
     if (!zipfp)
 	return - 1;
 
 
     if ( (readfp = PR_Open(fullname, PR_RDONLY, 0777)) == NULL) {
 	char	*nsprErr;
 	if (PR_GetErrorTextLength()) {
-	    nsprErr = PR_Malloc(PR_GetErrorTextLength());
+	    nsprErr = PR_Malloc(PR_GetErrorTextLength() + 1);
 	    PR_GetErrorText(nsprErr);
 	} else {
 	    nsprErr = NULL;
 	}
 	PR_fprintf(errorFD, "%s: %s\n", fullname, nsprErr ? nsprErr :
 	    "");
 	errorCount++;
 	if (nsprErr) 
@@ -220,17 +220,17 @@ JzipAdd(char *fullname, char *filename, 
 	inputSize = PR_Available(readfp);
 
 	endOfJar = PR_Seek(zipfp, 0L, PR_SEEK_CUR);
 
 	if (PR_Write(zipfp, "abcde", 5) < 5) {
 	    char	*nsprErr;
 
 	    if (PR_GetErrorTextLength()) {
-		nsprErr = PR_Malloc(PR_GetErrorTextLength());
+		nsprErr = PR_Malloc(PR_GetErrorTextLength() + 1);
 		PR_GetErrorText(nsprErr);
 	    } else {
 		nsprErr = NULL;
 	    }
 	    PR_fprintf(errorFD, "Writing to zip file: %s\n",
 	        nsprErr ? nsprErr : "");
 	    if (nsprErr) 
 		PR_Free(nsprErr);
@@ -310,34 +310,34 @@ JzipAdd(char *fullname, char *filename, 
      */
 
     local_size_pos = PR_Seek(zipfp, 0, PR_SEEK_CUR) + 18;
     /* File header */
     if (PR_Write(zipfp, &entry->local, sizeof(struct ZipLocal ))
          < sizeof(struct ZipLocal )) {
 	char	*nsprErr;
 	if (PR_GetErrorTextLength()) {
-	    nsprErr = PR_Malloc(PR_GetErrorTextLength());
+	    nsprErr = PR_Malloc(PR_GetErrorTextLength() + 1);
 	    PR_GetErrorText(nsprErr);
 	} else {
 	    nsprErr = NULL;
 	}
 	PR_fprintf(errorFD, "Writing zip data: %s\n", nsprErr ? nsprErr :
 	    "");
 	if (nsprErr) 
 	    PR_Free(nsprErr);
 	errorCount++;
 	exit(ERRX);
     }
 
     /* File Name */
     if ( PR_Write(zipfp, filename, strlen(filename)) < strlen(filename)) {
 	char	*nsprErr;
 	if (PR_GetErrorTextLength()) {
-	    nsprErr = PR_Malloc(PR_GetErrorTextLength());
+	    nsprErr = PR_Malloc(PR_GetErrorTextLength() + 1);
 	    PR_GetErrorText(nsprErr);
 	} else {
 	    nsprErr = NULL;
 	}
 	PR_fprintf(errorFD, "Writing zip data: %s\n", nsprErr ? nsprErr :
 	    "");
 	if (nsprErr) 
 	    PR_Free(nsprErr);
@@ -377,17 +377,17 @@ JzipAdd(char *fullname, char *filename, 
 	    if (err != Z_OK) {
 		handle_zerror(err, zstream.msg);
 		exit(ERRX);
 	    }
 	    if (zstream.avail_out <= 0) {
 		if ( PR_Write(zipfp, outbuf, BUFSIZ) < BUFSIZ) {
 		    char	*nsprErr;
 		    if (PR_GetErrorTextLength()) {
-			nsprErr = PR_Malloc(PR_GetErrorTextLength());
+			nsprErr = PR_Malloc(PR_GetErrorTextLength() + 1);
 			PR_GetErrorText(nsprErr);
 		    } else {
 			nsprErr = NULL;
 		    }
 		    PR_fprintf(errorFD, "Writing zip data: %s\n",
 					nsprErr ? nsprErr : "");
 		    if (nsprErr) 
 			PR_Free(nsprErr);
@@ -409,17 +409,17 @@ JzipAdd(char *fullname, char *filename, 
 	    /* output buffer full, repeat */
 	} else {
 	    handle_zerror(err, zstream.msg);
 	    exit(ERRX);
 	}
 	if ( PR_Write(zipfp, outbuf, BUFSIZ) < BUFSIZ) {
 	    char	*nsprErr;
 	    if (PR_GetErrorTextLength()) {
-		nsprErr = PR_Malloc(PR_GetErrorTextLength());
+		nsprErr = PR_Malloc(PR_GetErrorTextLength() + 1);
 		PR_GetErrorText(nsprErr);
 	    } else {
 		nsprErr = NULL;
 	    }
 	    PR_fprintf(errorFD, "Writing zip data: %s\n",
 				nsprErr ? nsprErr : "");
 	    if (nsprErr) 
 		PR_Free(nsprErr);
@@ -431,17 +431,17 @@ JzipAdd(char *fullname, char *filename, 
     }
 
     /* If there's any output left, write it out. */
     if (zstream.next_out != outbuf) {
 	if ( PR_Write(zipfp, outbuf, zstream.next_out - outbuf) <
 	    zstream.next_out - outbuf) {
 	    char	*nsprErr;
 	    if (PR_GetErrorTextLength()) {
-		nsprErr = PR_Malloc(PR_GetErrorTextLength());
+		nsprErr = PR_Malloc(PR_GetErrorTextLength() + 1);
 		PR_GetErrorText(nsprErr);
 	    } else {
 		nsprErr = NULL;
 	    }
 	    PR_fprintf(errorFD, "Writing zip data: %s\n",
 				nsprErr ? nsprErr : "");
 	    if (nsprErr) 
 		PR_Free(nsprErr);
@@ -453,45 +453,45 @@ JzipAdd(char *fullname, char *filename, 
     }
 
     /* Now that we know the compressed size, write this to the headers */
     longtox(zstream.total_in, entry->local.orglen);
     longtox(zstream.total_out, entry->local.size);
     if (PR_Seek(zipfp, local_size_pos, PR_SEEK_SET) == -1) {
 	char	*nsprErr;
 	if (PR_GetErrorTextLength()) {
-	    nsprErr = PR_Malloc(PR_GetErrorTextLength());
+	    nsprErr = PR_Malloc(PR_GetErrorTextLength() + 1);
 	    PR_GetErrorText(nsprErr);
 	} else {
 	    nsprErr = NULL;
 	}
 	PR_fprintf(errorFD, "Accessing zip file: %s\n", nsprErr ? nsprErr : "");
 	if (nsprErr) 
 	    PR_Free(nsprErr);
 	errorCount++;
 	exit(ERRX);
     }
     if ( PR_Write(zipfp, entry->local.size, 8) != 8) {
 	char	*nsprErr;
 	if (PR_GetErrorTextLength()) {
-	    nsprErr = PR_Malloc(PR_GetErrorTextLength());
+	    nsprErr = PR_Malloc(PR_GetErrorTextLength() + 1);
 	    PR_GetErrorText(nsprErr);
 	} else {
 	    nsprErr = NULL;
 	}
 	PR_fprintf(errorFD, "Writing zip data: %s\n", nsprErr ? nsprErr : "");
 	if (nsprErr) 
 	    PR_Free(nsprErr);
 	errorCount++;
 	exit(ERRX);
     }
     if (PR_Seek(zipfp, 0L, PR_SEEK_END) == -1) {
 	char	*nsprErr;
 	if (PR_GetErrorTextLength()) {
-	    nsprErr = PR_Malloc(PR_GetErrorTextLength());
+	    nsprErr = PR_Malloc(PR_GetErrorTextLength() + 1);
 	    PR_GetErrorText(nsprErr);
 	} else {
 	    nsprErr = NULL;
 	}
 	PR_fprintf(errorFD, "Accessing zip file: %s\n", 
 			    nsprErr ? nsprErr : "");
 	if (nsprErr) 
 	    PR_Free(nsprErr);
@@ -554,17 +554,17 @@ JzipClose(ZIPfile *zipfile)
     while (pe) {
 	entrycount++;
 
 	/* Write central directory info */
 	if ( PR_Write(zipfp, &pe->central, sizeof(struct ZipCentral ))
 	     < sizeof(struct ZipCentral )) {
 	    char	*nsprErr;
 	    if (PR_GetErrorTextLength()) {
-		nsprErr = PR_Malloc(PR_GetErrorTextLength());
+		nsprErr = PR_Malloc(PR_GetErrorTextLength() + 1);
 		PR_GetErrorText(nsprErr);
 	    } else {
 		nsprErr = NULL;
 	    }
 	    PR_fprintf(errorFD, "Writing zip data: %s\n",
 				nsprErr ? nsprErr : "");
 	    if (nsprErr) 
 		PR_Free(nsprErr);
@@ -572,17 +572,17 @@ JzipClose(ZIPfile *zipfile)
 	    exit(ERRX);
 	}
 
 	/* Write filename */
 	if ( PR_Write(zipfp, pe->filename, strlen(pe->filename))
 	     < strlen(pe->filename)) {
 	    char	*nsprErr;
 	    if (PR_GetErrorTextLength()) {
-		nsprErr = PR_Malloc(PR_GetErrorTextLength());
+		nsprErr = PR_Malloc(PR_GetErrorTextLength() + 1);
 		PR_GetErrorText(nsprErr);
 	    } else {
 		nsprErr = NULL;
 	    }
 	    PR_fprintf(errorFD, "Writing zip data: %s\n",
 				nsprErr ? nsprErr : "");
 	    if (nsprErr) 
 		PR_Free(nsprErr);
@@ -591,17 +591,17 @@ JzipClose(ZIPfile *zipfile)
 	}
 
 	/* Write file comment */
 	if (pe->comment) {
 	    if ( PR_Write(zipfp, pe->comment, strlen(pe->comment))
 	         < strlen(pe->comment)) {
 		char	*nsprErr;
 		if (PR_GetErrorTextLength()) {
-		    nsprErr = PR_Malloc(PR_GetErrorTextLength());
+		    nsprErr = PR_Malloc(PR_GetErrorTextLength() + 1);
 		    PR_GetErrorText(nsprErr);
 		} else {
 		    nsprErr = NULL;
 		}
 		PR_fprintf(errorFD, "Writing zip data: %s\n",
 					    nsprErr ? nsprErr : "");
 		if (nsprErr) 
 		    PR_Free(nsprErr);
@@ -634,17 +634,17 @@ JzipClose(ZIPfile *zipfile)
     if (zipfile->comment) {
 	inttox(strlen(zipfile->comment), zipend.commentfield_len);
     }
 
     /* Write out ZipEnd xtructure */
     if ( PR_Write(zipfp, &zipend, sizeof(zipend)) < sizeof(zipend)) {
 	char	*nsprErr;
 	if (PR_GetErrorTextLength()) {
-	    nsprErr = PR_Malloc(PR_GetErrorTextLength());
+	    nsprErr = PR_Malloc(PR_GetErrorTextLength() + 1);
 	    PR_GetErrorText(nsprErr);
 	} else {
 	    nsprErr = NULL;
 	}
 	PR_fprintf(errorFD, "Writing zip data: %s\n", 
 			    nsprErr ? nsprErr : "");
 	if (nsprErr) 
 	    PR_Free(nsprErr);
@@ -653,17 +653,17 @@ JzipClose(ZIPfile *zipfile)
     }
 
     /* Write out Zipfile comment */
     if (zipfile->comment) {
 	if ( PR_Write(zipfp, zipfile->comment, strlen(zipfile->comment))
 	     < strlen(zipfile->comment)) {
 	    char	*nsprErr;
 	    if (PR_GetErrorTextLength()) {
-		nsprErr = PR_Malloc(PR_GetErrorTextLength());
+		nsprErr = PR_Malloc(PR_GetErrorTextLength() + 1);
 		PR_GetErrorText(nsprErr);
 	    } else {
 		nsprErr = NULL;
 	    }
 	    PR_fprintf(errorFD, "Writing zip data: %s\n",
 				nsprErr ? nsprErr : "");
 	    if (nsprErr) 
 		PR_Free(nsprErr);
--- a/security/nss/cmd/strsclnt/strsclnt.c
+++ b/security/nss/cmd/strsclnt/strsclnt.c
@@ -261,17 +261,17 @@ mySSLAuthCertificate(void *arg, PRFileDe
     }
     peerCert = SSL_PeerCertificate(fd);
 
     PRINTF("strsclnt: Subject: %s\nstrsclnt: Issuer : %s\n", 
            peerCert->subjectName, peerCert->issuerName); 
     /* invoke the "default" AuthCert handler. */
     rv = SSL_AuthCertificate(arg, fd, checkSig, isServer);
 
-    PR_AtomicIncrement(&certsTested);
+    PR_ATOMIC_INCREMENT(&certsTested);
     if (rv == SECSuccess) {
 	fputs("strsclnt: -- SSL: Server Certificate Validated.\n", stderr);
     }
     CERT_DestroyCertificate(peerCert);
     /* error, if any, will be displayed by the Bad Cert Handler. */
     return rv;  
 }
 
@@ -727,17 +727,17 @@ handle_connection( PRFileDesc *ssl_sock,
 
 #ifdef USE_SOCK_PEER_ID
 
 PRInt32 lastFullHandshakePeerID;
 
 void
 myHandshakeCallback(PRFileDesc *socket, void *arg) 
 {
-    PR_AtomicSet(&lastFullHandshakePeerID, (PRInt32) arg);
+    PR_ATOMIC_SET(&lastFullHandshakePeerID, (PRInt32) arg);
 }
 
 #endif
 
 /* one copy of this function is launched in a separate thread for each
 ** connection to be made.
 */
 int
@@ -833,28 +833,28 @@ retry:
 	return SECSuccess;
     }
     if (fullhs != NO_FULLHS_PERCENTAGE) {
 #ifdef USE_SOCK_PEER_ID
         char sockPeerIDString[512];
         static PRInt32 sockPeerID = 0; /* atomically incremented */
         PRInt32 thisPeerID;
 #endif
-        PRInt32 savid = PR_AtomicIncrement(&globalconid);
+        PRInt32 savid = PR_ATOMIC_INCREMENT(&globalconid);
         PRInt32 conid = 1 + (savid - 1) % 100;
         /* don't change peer ID on the very first handshake, which is always
            a full, so the session gets stored into the client cache */
         if ( (savid != 1) &&
             ( ( (savid <= total_connections_rounded_down_to_hundreds) &&
                 (conid <= fullhs) ) ||
               (conid*100 <= total_connections_modulo_100*fullhs ) ) ) 
 #ifdef USE_SOCK_PEER_ID
         {
             /* force a full handshake by changing the socket peer ID */
-            thisPeerID = PR_AtomicIncrement(&sockPeerID);
+            thisPeerID = PR_ATOMIC_INCREMENT(&sockPeerID);
         } else {
             /* reuse previous sockPeerID for restart handhsake */
             thisPeerID = lastFullHandshakePeerID;
         }
         PR_snprintf(sockPeerIDString, sizeof(sockPeerIDString), "ID%d",
                     thisPeerID);
         SSL_SetSockPeerID(ssl_sock, sockPeerIDString);
         SSL_HandshakeCallback(ssl_sock, myHandshakeCallback, (void*)thisPeerID);
@@ -864,25 +864,25 @@ retry:
 #endif
     }
     rv = SSL_ResetHandshake(ssl_sock, /* asServer */ 0);
     if (rv != SECSuccess) {
 	errWarn("SSL_ResetHandshake");
 	goto done;
     }
 
-    PR_AtomicIncrement(&numConnected);
+    PR_ATOMIC_INCREMENT(&numConnected);
 
     if (bigBuf.data != NULL) {
 	result = handle_fdx_connection( ssl_sock, tid);
     } else {
 	result = handle_connection( ssl_sock, tid);
     }
 
-    PR_AtomicDecrement(&numConnected);
+    PR_ATOMIC_DECREMENT(&numConnected);
 
 done:
     if (ssl_sock) {
 	PR_Close(ssl_sock);
     } else if (tcp_sock) {
 	PR_Close(tcp_sock);
     }
     return SECSuccess;
--- a/security/nss/lib/base/arena.c
+++ b/security/nss/lib/base/arena.c
@@ -30,17 +30,17 @@
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifdef DEBUG
-static const char CVS_ID[] = "@(#) $RCSfile: arena.c,v $ $Revision: 1.12 $ $Date: 2008/05/13 01:22:35 $";
+static const char CVS_ID[] = "@(#) $RCSfile: arena.c,v $ $Revision: 1.13 $ $Date: 2010/03/15 08:29:31 $";
 #endif /* DEBUG */
 
 /*
  * arena.c
  *
  * This contains the implementation of NSS's thread-safe arenas.
  */
 
@@ -1021,16 +1021,17 @@ nss_ZFreeIf
 
 NSS_EXTERN void *
 nss_ZRealloc
 (
   void *pointer,
   PRUint32 newSize
 )
 {
+  NSSArena *arena;
   struct pointer_header *h, *new_h;
   PRUint32 my_newSize = newSize + sizeof(struct pointer_header);
   void *rv;
 
   if( my_newSize < sizeof(struct pointer_header) ) {
     /* Wrapped */
     nss_SetError(NSS_ERROR_NO_MEMORY);
     return (void *)NULL;
@@ -1046,17 +1047,18 @@ nss_ZRealloc
 
   /* Check any magic here */
 
   if( newSize == h->size ) {
     /* saves thrashing */
     return pointer;
   }
 
-  if( (NSSArena *)NULL == h->arena ) {
+  arena = h->arena;
+  if (!arena) {
     /* Heap */
     new_h = (struct pointer_header *)PR_Calloc(1, my_newSize);
     if( (struct pointer_header *)NULL == new_h ) {
       nss_SetError(NSS_ERROR_NO_MEMORY);
       return (void *)NULL;
     }
 
     new_h->arena = (NSSArena *)NULL;
@@ -1075,32 +1077,32 @@ nss_ZRealloc
     h->size = 0;
     PR_Free(h);
 
     return rv;
   } else {
     void *p;
     /* Arena */
 #ifdef NSSDEBUG
-    if( PR_SUCCESS != nssArena_verifyPointer(h->arena) ) {
+    if (PR_SUCCESS != nssArena_verifyPointer(arena)) {
       return (void *)NULL;
     }
 #endif /* NSSDEBUG */
 
-    if( (PRLock *)NULL == h->arena->lock ) {
+    if (!arena->lock) {
       /* Just got destroyed.. so this pointer is invalid */
       nss_SetError(NSS_ERROR_INVALID_POINTER);
       return (void *)NULL;
     }
-    PR_Lock(h->arena->lock);
+    PR_Lock(arena->lock);
 
 #ifdef ARENA_THREADMARK
-    if( (PRThread *)NULL != h->arena->marking_thread ) {
-      if( PR_GetCurrentThread() != h->arena->marking_thread ) {
-        PR_Unlock(h->arena->lock);
+    if (arena->marking_thread) {
+      if (PR_GetCurrentThread() != arena->marking_thread) {
+        PR_Unlock(arena->lock);
         nss_SetError(NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD);
         return (void *)NULL;
       }
     }
 #endif /* ARENA_THREADMARK */
 
     if( newSize < h->size ) {
       /*
@@ -1112,39 +1114,39 @@ nss_ZRealloc
        * it now."  We'll zero the leftover part, of course.  And
        * in fact we might as well *not* adjust h->size-- this way,
        * if the user reallocs back up to something not greater than
        * the original size, then voila, there's the memory!  This
        * way a thrash big/small/big/small doesn't burn up the arena.
        */
       char *extra = &((char *)pointer)[ newSize ];
       (void)nsslibc_memset(extra, 0, (h->size - newSize));
-      PR_Unlock(h->arena->lock);
+      PR_Unlock(arena->lock);
       return pointer;
     }
 
-    PR_ARENA_ALLOCATE(p, &h->arena->pool, my_newSize);
+    PR_ARENA_ALLOCATE(p, &arena->pool, my_newSize);
     if( (void *)NULL == p ) {
-      PR_Unlock(h->arena->lock);
+      PR_Unlock(arena->lock);
       nss_SetError(NSS_ERROR_NO_MEMORY);
       return (void *)NULL;
     }
 
     new_h = (struct pointer_header *)p;
-    new_h->arena = h->arena;
+    new_h->arena = arena;
     new_h->size = newSize;
     rv = (void *)((char *)new_h + sizeof(struct pointer_header));
     if (rv != pointer) {
 	(void)nsslibc_memcpy(rv, pointer, h->size);
 	(void)nsslibc_memset(pointer, 0, h->size);
     }
     (void)nsslibc_memset(&((char *)rv)[ h->size ], 0, (newSize - h->size));
     h->arena = (NSSArena *)NULL;
     h->size = 0;
-    PR_Unlock(new_h->arena->lock);
+    PR_Unlock(arena->lock);
     return rv;
   }
   /*NOTREACHED*/
 }
 
 PRStatus 
 nssArena_Shutdown(void)
 {
--- a/security/nss/lib/certdb/alg1485.c
+++ b/security/nss/lib/certdb/alg1485.c
@@ -596,17 +596,17 @@ AppendStr(stringBuf *bufp, char *str)
 
 typedef enum {
     minimalEscape = 0,		/* only hex escapes, and " and \ */
     minimalEscapeAndQuote,	/* as above, plus quoting        */
     fullEscape                  /* no quoting, full escaping     */
 } EQMode;
 
 /* Some characters must be escaped as a hex string, e.g. c -> \nn .
- * Others must be escaped by preceeding with a '\', e.g. c -> \c , but
+ * Others must be escaped by preceding with a '\', e.g. c -> \c , but
  * there are certain "special characters" that may be handled by either
  * escaping them, or by enclosing the entire attribute value in quotes.
  * A NULL value for pEQMode implies selecting minimalEscape mode.
  * Some callers will do quoting when needed, others will not.
  * If a caller selects minimalEscapeAndQuote, and the string does not
  * need quoting, then this function changes it to minimalEscape.
  */
 static int
--- a/security/nss/lib/certdb/cert.h
+++ b/security/nss/lib/certdb/cert.h
@@ -32,17 +32,17 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 /*
  * cert.h - public data structures and prototypes for the certificate library
  *
- * $Id: cert.h,v 1.79 2010/01/14 22:15:23 alexei.volkov.bugs%sun.com Exp $
+ * $Id: cert.h,v 1.80 2010/04/30 07:47:47 nelson%bolyard.com Exp $
  */
 
 #ifndef _CERT_H_
 #define _CERT_H_
 
 #include "utilrename.h"
 #include "plarena.h"
 #include "plhash.h"
@@ -1287,16 +1287,20 @@ CERT_SortCBValidity(CERTCertificate *cer
 		    void *arg);
 
 SECStatus
 CERT_CheckForEvilCert(CERTCertificate *cert);
 
 CERTGeneralName *
 CERT_GetCertificateNames(CERTCertificate *cert, PLArenaPool *arena);
 
+CERTGeneralName *
+CERT_GetConstrainedCertificateNames(CERTCertificate *cert, PLArenaPool *arena,
+                                    PRBool includeSubjectCommonName);
+
 char *
 CERT_GetNickName(CERTCertificate   *cert, CERTCertDBHandle *handle, PLArenaPool *nicknameArena);
 
 /*
  * Creates or adds to a list of all certs with a give subject name, sorted by
  * validity time, newest first.  Invalid certs are considered older than
  * valid certs. If validOnly is set, do not include invalid certs on list.
  */
--- a/security/nss/lib/certdb/certdb.c
+++ b/security/nss/lib/certdb/certdb.c
@@ -34,17 +34,17 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 /*
  * Certificate handling code
  *
- * $Id: certdb.c,v 1.102 2010/02/10 02:00:57 wtc%google.com Exp $
+ * $Id: certdb.c,v 1.104 2010/04/25 00:44:55 nelson%bolyard.com Exp $
  */
 
 #include "nssilock.h"
 #include "prmon.h"
 #include "prtime.h"
 #include "cert.h"
 #include "certi.h"
 #include "secder.h"
@@ -564,17 +564,17 @@ cert_GetCertType(CERTCertificate *cert)
     if (cert->nsCertType) {
         /* once set, no need to recalculate */
         return SECSuccess;
     }
     nsCertType = cert_ComputeCertType(cert);
 
     /* Assert that it is safe to cast &cert->nsCertType to "PRInt32 *" */
     PORT_Assert(sizeof(cert->nsCertType) == sizeof(PRInt32));
-    PR_AtomicSet((PRInt32 *)&cert->nsCertType, nsCertType);
+    PR_ATOMIC_SET((PRInt32 *)&cert->nsCertType, nsCertType);
     return SECSuccess;
 }
 
 PRUint32
 cert_ComputeCertType(CERTCertificate *cert)
 {
     SECStatus rv;
     SECItem tmpitem;
@@ -1824,23 +1824,17 @@ CERT_GetValidDNSPatternsFromCert(CERTCer
 
         /* failure to produce output */
         PORT_FreeArena(arena, PR_FALSE);
         return NULL;
       }
     }
 
     /* no SAN extension or no names found in extension */
-    /* now try the NS cert name extension first, then the common name */
-    singleName = 
-      CERT_FindNSStringExtension(cert, SEC_OID_NS_CERT_EXT_SSL_SERVER_NAME);
-    if (!singleName) {
-      singleName = CERT_GetCommonName(&cert->subject);
-    }
-
+    singleName = CERT_GetCommonName(&cert->subject);
     if (singleName) {
       nickNames->numnicknames = 1;
       nickNames->nicknames = PORT_ArenaAlloc(arena, sizeof(char *));
       if (nickNames->nicknames) {
         *nickNames->nicknames = PORT_ArenaStrdup(arena, singleName);
       }
       PORT_Free(singleName);
 
@@ -1879,21 +1873,17 @@ CERT_VerifyCertName(CERTCertificate *cer
 
     /* Per RFC 2818, if the SubjectAltName extension is present, it must
     ** be used as the cert's identity.
     */
     rv = cert_VerifySubjectAltName(cert, hn);
     if (rv == SECSuccess || PORT_GetError() != SEC_ERROR_EXTENSION_NOT_FOUND)
     	return rv;
 
-    /* try the cert extension first, then the common name */
-    cn = CERT_FindNSStringExtension(cert, SEC_OID_NS_CERT_EXT_SSL_SERVER_NAME);
-    if ( !cn ) {
-	cn = CERT_GetCommonName(&cert->subject);
-    }
+    cn = CERT_GetCommonName(&cert->subject);
     if ( cn ) {
 	rv = cert_TestHostName(cn, hn);
 	PORT_Free(cn);
     } else 
 	PORT_SetError(SSL_ERROR_BAD_CERT_DOMAIN);
     return rv;
 }
 
--- a/security/nss/lib/certdb/certi.h
+++ b/security/nss/lib/certdb/certi.h
@@ -31,17 +31,17 @@
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 /*
  * certi.h - private data structures for the certificate library
  *
- * $Id: certi.h,v 1.31 2009/07/31 18:35:30 christophe.ravel.bugs%sun.com Exp $
+ * $Id: certi.h,v 1.34 2010/05/21 00:43:51 wtc%google.com Exp $
  */
 #ifndef _CERTI_H_
 #define _CERTI_H_
 
 #include "certt.h"
 #include "nssrwlkt.h"
 
 /*
@@ -145,17 +145,17 @@ struct CachedCrlStr {
 */
 
 struct CRLDPCacheStr {
 #ifdef DPC_RWLOCK
     NSSRWLock* lock;
 #else
     PRLock* lock;
 #endif
-    CERTCertificate* issuer;    /* cert issuer 
+    CERTCertificate* issuer;    /* issuer cert
                                    XXX there may be multiple issuer certs,
                                        with different validity dates. Also
                                        need to deal with SKID/AKID . See
                                        bugzilla 217387, 233118 */
     SECItem* subject;           /* DER of issuer subject */
     SECItem* distributionPoint; /* DER of distribution point. This may be
                                    NULL when distribution points aren't
                                    in use (ie. the CA has a single CRL).
@@ -173,19 +173,19 @@ struct CRLDPCacheStr {
 #if 0
     /* for future use */
     PRInt32 numdeltas;      /* number of delta CRLs used for the cache */
     CachedCrl** deltas;     /* delta CRLs used for the cache */
 #endif
     /* cache invalidity bitflag */
     PRUint16 invalid;       /* this state will be set if either
              CRL_CACHE_INVALID_CRLS or CRL_CACHE_LAST_FETCH_FAILED is set.
-             In those cases, all certs are considered revoked as a
-             security precaution. The invalid state can only be cleared
-             during an update if all error states are cleared */
+             In those cases, all certs are considered to have unknown status.
+             The invalid state can only be cleared during an update if all
+             error states are cleared */
     PRBool refresh;        /* manual refresh from tokens has been forced */
     PRBool mustchoose;     /* trigger reselection algorithm, for case when
                               RAM CRL objects are dropped from the cache */
     PRTime lastfetch;      /* time a CRL token fetch was last performed */
     PRTime lastcheck;      /* time CRL token objects were last checked for
                               existence */
 };
 
@@ -276,25 +276,16 @@ SECStatus AcquireDPCache(CERTCertificate
 
 /* check if a particular SN is in the CRL cache and return its entry */
 dpcacheStatus DPCache_Lookup(CRLDPCache* cache, SECItem* sn,
                              CERTCrlEntry** returned);
 
 /* release a DPCache object that was previously acquired */
 void ReleaseDPCache(CRLDPCache* dpcache, PRBool writeLocked);
 
-/* this function assumes the caller holds a lock on the DPCache */
-SECStatus DPCache_GetAllCRLs(CRLDPCache* dpc, PRArenaPool* arena,
-                             CERTSignedCrl*** crls, PRUint16* status);
-
-/* this function assumes the caller holds a lock on the DPCache */
-SECStatus DPCache_GetCRLEntry(CRLDPCache* cache, PRBool readlocked,
-                              CERTSignedCrl* crl, SECItem* sn,
-                              CERTCrlEntry** returned);
-
 /*
  * map Stan errors into NSS errors
  * This function examines the stan error stack and automatically sets
  * PORT_SetError(); to the appropriate SEC_ERROR value.
  */
 void CERT_MapStanError();
 
 /* Interface function for libpkix cert validation engine:
@@ -386,10 +377,18 @@ SECStatus cert_AcquireNamedCRLCache(Name
  * acquired, and the entry is only valid until cache is released.
  */
 SECStatus cert_FindCRLByGeneralName(NamedCRLCache* ncc,
                                     const SECItem* canonicalizedName,
                                     NamedCRLCacheEntry** retEntry);
 
 SECStatus cert_ReleaseNamedCRLCache(NamedCRLCache* ncc);
 
+/* This is private for now.  Maybe shoule be public. */
+CERTGeneralName *
+cert_GetSubjectAltNameList(CERTCertificate *cert, PRArenaPool *arena);
+
+/* Count DNS names and IP addresses in a list of GeneralNames */
+PRUint32
+cert_CountDNSPatterns(CERTGeneralName *firstName);
+
 #endif /* _CERTI_H_ */
 
--- a/security/nss/lib/certdb/certt.h
+++ b/security/nss/lib/certdb/certt.h
@@ -31,17 +31,17 @@
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 /*
  * certt.h - public data structures for the certificate library
  *
- * $Id: certt.h,v 1.52 2009/05/29 18:10:38 alexei.volkov.bugs%sun.com Exp $
+ * $Id: certt.h,v 1.54 2010/06/18 00:34:22 wtc%google.com Exp $
  */
 #ifndef _CERTT_H_
 #define _CERTT_H_
 
 #include "prclist.h"
 #include "pkcs11t.h"
 #include "seccomon.h"
 #include "secmodt.h"
@@ -248,17 +248,17 @@ struct CERTCertificateStr {
     char *emailAddr;
     CERTCertDBHandle *dbhandle;
     SECItem subjectKeyID;	/* x509v3 subject key identifier */
     PRBool keyIDGenerated;	/* was the keyid generated? */
     unsigned int keyUsage;	/* what uses are allowed for this cert */
     unsigned int rawKeyUsage;	/* value of the key usage extension */
     PRBool keyUsagePresent;	/* was the key usage extension present */
     PRUint32 nsCertType;	/* value of the ns cert type extension */
-				/* must be 32-bit for PR_AtomicSet */
+				/* must be 32-bit for PR_ATOMIC_SET */
 
     /* these values can be set by the application to bypass certain checks
      * or to keep the cert in memory for an entire session.
      * XXX - need an api to set these
      */
     PRBool keepSession;			/* keep this cert for entire session*/
     PRBool timeOK;			/* is the bad validity time ok? */
     CERTOKDomainName *domainOK;		/* these domain names are ok */
@@ -906,17 +906,18 @@ typedef enum {
 				 * freed. */
    cert_pi_certList        = 3, /* specify the chain to validate against. If
 				 * this value is given, then the path 
 				 * construction step in the validation is 
 				 * skipped. Specified in value.pointer.chain */
    cert_pi_policyOID       = 4, /* validate certificate for policy OID.
 				 * Specified in value.array.oids. Cert must
 				 * be good for at least one OID in order
-				 * to validate. Default is no policyOID */
+				 * to validate. Default is that the user is not
+				 * concerned about certificate policy. */
    cert_pi_policyFlags     = 5, /* flags for each policy specified in policyOID.
 				 * Specified in value.scalar.ul. Policy flags
 				 * apply to all specified oids. 
 				 * Use CERT_POLICY_FLAG_* macros below. If not
 				 * specified policy flags default to 0 */
    cert_pi_keyusage        = 6, /* specify what the keyusages the certificate 
 				 * will be evaluated against, specified in
 				 * value.scalar.ui. The cert must validate for
--- a/security/nss/lib/certdb/crl.c
+++ b/security/nss/lib/certdb/crl.c
@@ -32,17 +32,17 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 /*
  * Moved from secpkcs7.c
  *
- * $Id: crl.c,v 1.68 2009/08/10 22:25:44 julien.pierre.boogz%sun.com Exp $
+ * $Id: crl.c,v 1.71 2010/05/21 00:43:51 wtc%google.com Exp $
  */
  
 #include "cert.h"
 #include "certi.h"
 #include "secder.h"
 #include "secasn1.h"
 #include "secoid.h"
 #include "certdb.h"
@@ -837,27 +837,27 @@ loser:
     PORT_FreeArena(arena, PR_FALSE);
     return(crl);
 }
 
 CERTSignedCrl* SEC_DupCrl(CERTSignedCrl* acrl)
 {
     if (acrl)
     {
-        PR_AtomicIncrement(&acrl->referenceCount);
+        PR_ATOMIC_INCREMENT(&acrl->referenceCount);
         return acrl;
     }
     return NULL;
 }
 
 SECStatus
 SEC_DestroyCrl(CERTSignedCrl *crl)
 {
     if (crl) {
-	if (PR_AtomicDecrement(&crl->referenceCount) < 1) {
+	if (PR_ATOMIC_DECREMENT(&crl->referenceCount) < 1) {
 	    if (crl->slot) {
 		PK11_FreeSlot(crl->slot);
 	    }
             if (GetOpaqueCRLFields(crl) &&
                 PR_TRUE == GetOpaqueCRLFields(crl)->heapDER) {
                 SECITEM_FreeItem(crl->derCrl, PR_TRUE);
             }
             if (crl->arena) {
@@ -1634,18 +1634,18 @@ static SECStatus CERT_VerifyCRL(
 
 /* verify a CRL and update cache state */
 static SECStatus CachedCrl_Verify(CRLDPCache* cache, CachedCrl* crlobject,
                           PRTime vfdate, void* wincx)
 {
     /*  Check if it is an invalid CRL
         if we got a bad CRL, we want to cache it in order to avoid
         subsequent fetches of this same identical bad CRL. We set
-        the cache to the invalid state to ensure that all certs
-        on this DP are considered revoked from now on. The cache
+        the cache to the invalid state to ensure that all certs on this
+        DP are considered to have unknown status from now on. The cache
         object will remain in this state until the bad CRL object
         is removed from the token it was fetched from. If the cause
         of the failure is that we didn't have the issuer cert to
         verify the signature, this state can be cleared when
         the issuer certificate becomes available if that causes the
         signature to verify */
 
     if (!cache || !crlobject)
@@ -1821,18 +1821,17 @@ dpcacheStatus DPCache_Lookup(CRLDPCache*
     {
         PORT_SetError(SEC_ERROR_INVALID_ARGS);
         /* no cache or SN to look up, or no way to return entry */
         return dpcacheCallerError;
     }
     *returned = NULL;
     if (0 != cache->invalid)
     {
-        /* the cache contains a bad CRL, or there was a CRL fetching error.
-           consider all certs revoked as a security measure */
+        /* the cache contains a bad CRL, or there was a CRL fetching error. */
         PORT_SetError(SEC_ERROR_CRL_INVALID);
         return dpcacheInvalidCacheError;
     }
     if (!cache->selected)
     {
         /* no CRL means no entry to return. This is OK, except for
          * NIST policy */
         return dpcacheEmpty;
@@ -2789,22 +2788,19 @@ cert_CheckCertRevocationStatus(CERTCerti
             status = certRevocationStatusUnknown;
             break;
 
         case dpcacheNoEntry:
             status = certRevocationStatusValid;
             break;
 
         case dpcacheInvalidCacheError:
-            /* t of zero may have caused the CRL cache to fail to verify
-             * a CRL. treat it as unknown */
-            if (!t)
-            {
-                status = certRevocationStatusUnknown;
-            }
+            /* treat it as unknown and let the caller decide based on
+               the policy */
+            status = certRevocationStatusUnknown;
             break;
 
         default:
             /* leave status as revoked */
             break;
     }
 
     ReleaseDPCache(dpcache, lockedwrite);
@@ -3461,100 +3457,8 @@ static SECStatus CachedCrl_Compare(Cache
         */
         if (b->crl->derCrl == a->crl->derCrl)
         {
             *isDupe = PR_TRUE;
         }
     }
     return SECSuccess;
 }
-
-/* this function assumes the caller holds a read lock on the DPCache */
-SECStatus DPCache_GetAllCRLs(CRLDPCache* dpc, PRArenaPool* arena,
-                             CERTSignedCrl*** crls, PRUint16* status)
-{
-    CERTSignedCrl** allcrls;
-    PRUint32 index;
-    if (!dpc || !crls || !status)
-    {
-        PORT_SetError(SEC_ERROR_INVALID_ARGS);
-        return SECFailure;
-    }
-
-    *status = dpc->invalid;
-    *crls = NULL;
-    if (!dpc->ncrls)
-    {
-        /* no CRLs to return */
-        return SECSuccess;
-    }
-    allcrls = PORT_ArenaZNewArray(arena, CERTSignedCrl*, dpc->ncrls +1);
-    if (!allcrls)
-    {
-        return SECFailure;
-    }
-    for (index=0; index < dpc->ncrls ; index ++) {
-        CachedCrl* cachedcrl = dpc->crls[index];
-        if (!cachedcrl || !cachedcrl->crl)
-        {
-            PORT_Assert(0); /* this should never happen */
-            continue;
-        }
-        allcrls[index] = SEC_DupCrl(cachedcrl->crl);
-    }
-    *crls = allcrls;
-    return SECSuccess;
-}
-
-static CachedCrl* DPCache_FindCRL(CRLDPCache* cache, CERTSignedCrl* crl)
-{
-    PRUint32 index;
-    CachedCrl* cachedcrl = NULL;
-    for (index=0; index < cache->ncrls ; index ++) {
-        cachedcrl = cache->crls[index];
-        if (!cachedcrl || !cachedcrl->crl)
-        {
-            PORT_Assert(0); /* this should never happen */
-            continue;
-        }
-        if (cachedcrl->crl == crl) {
-            break;
-        }
-    }
-    return cachedcrl;
-}
-
-/* this function assumes the caller holds a lock on the DPCache */
-SECStatus DPCache_GetCRLEntry(CRLDPCache* cache, PRBool readlocked,
-                              CERTSignedCrl* crl, SECItem* sn,
-                              CERTCrlEntry** returned)
-{
-    CachedCrl* cachedcrl = NULL;
-    if (!cache || !crl || !sn || !returned)
-    {
-        PORT_Assert(0);
-        PORT_SetError(SEC_ERROR_INVALID_ARGS);
-        return SECFailure;
-    }
-    *returned = NULL;
-    /* first, we need to find the CachedCrl* that matches this CERTSignedCRL */
-    cachedcrl = DPCache_FindCRL(cache, crl);
-    if (!cachedcrl) {
-        PORT_SetError(SEC_ERROR_CRL_NOT_FOUND);
-        return SECFailure;
-    }
-
-    if (cachedcrl->unbuildable) {
-        /* this CRL could not be fully decoded */
-        PORT_SetError(SEC_ERROR_BAD_DER);
-        return SECFailure;
-    }
-    /* now, make sure it has a hash table. Otherwise, we'll need to build one */
-    if (!cachedcrl->entries || !cachedcrl->prebuffer) {
-        DPCache_LockWrite();
-        CachedCrl_Populate(cachedcrl);
-        DPCache_UnlockWrite();
-    }
-
-    /* finally, get the CRL entry */       
-    return CachedCrl_GetEntry(cachedcrl, sn, returned);
-}
-
--- a/security/nss/lib/certdb/genname.c
+++ b/security/nss/lib/certdb/genname.c
@@ -37,16 +37,17 @@
 #include "plarena.h"
 #include "seccomon.h"
 #include "secitem.h"
 #include "secoidt.h"
 #include "secasn1.h"
 #include "secder.h"
 #include "certt.h"
 #include "cert.h"
+#include "certi.h"
 #include "xconst.h"
 #include "secerr.h"
 #include "secoid.h"
 #include "prprf.h"
 #include "genname.h"
 
 SEC_ASN1_MKSUB(SEC_AnyTemplate)
 SEC_ASN1_MKSUB(SEC_IntegerTemplate)
@@ -1077,27 +1078,41 @@ cert_ExtractDNEmailAddrs(CERTGeneralName
     /* TODO: unmark arena */
     return SECSuccess;
 
 loser:
     /* TODO: release arena back to mark */
     return SECFailure;
 }
 
-/* This function is called by CERT_VerifyCertChain to extract all
-** names from a cert in preparation for a name constraints test.
+/* Extract all names except Subject Common Name from a cert 
+** in preparation for a name constraints test.
 */
 CERTGeneralName *
 CERT_GetCertificateNames(CERTCertificate *cert, PRArenaPool *arena)
 {
+    return CERT_GetConstrainedCertificateNames(cert, arena, PR_FALSE);
+}
+
+/* This function is called by CERT_VerifyCertChain to extract all
+** names from a cert in preparation for a name constraints test.
+*/
+CERTGeneralName *
+CERT_GetConstrainedCertificateNames(CERTCertificate *cert, PRArenaPool *arena,
+                                    PRBool includeSubjectCommonName)
+{
     CERTGeneralName  *DN;
-    CERTGeneralName  *altName         = NULL;
-    SECItem          altNameExtension = {siBuffer, NULL, 0 };
+    CERTGeneralName  *SAN;
+    PRUint32         numDNSNames = 0;
     SECStatus        rv;
 
+    if (!arena) {
+    	PORT_SetError(SEC_ERROR_INVALID_ARGS);
+	return NULL;
+    }
     /* TODO: mark arena */
     DN = CERT_NewGeneralName(arena, certDirectoryName);
     if (DN == NULL) {
 	goto loser;
     }
     rv = CERT_CopyName(arena, &DN->name.directoryName, &cert->subject);
     if (rv != SECSuccess) {
 	goto loser;
@@ -1109,32 +1124,41 @@ CERT_GetCertificateNames(CERTCertificate
     /* Extract email addresses from DN, construct CERTGeneralName structs 
     ** for them, add them to the name list 
     */
     rv = cert_ExtractDNEmailAddrs(DN, arena);
     if (rv != SECSuccess)
         goto loser;
 
     /* Now extract any GeneralNames from the subject name names extension. */
-    rv = CERT_FindCertExtension(cert, SEC_OID_X509_SUBJECT_ALT_NAME, 
-				&altNameExtension);
-    if (rv == SECSuccess) {
-	altName = CERT_DecodeAltNameExtension(arena, &altNameExtension);
-	rv = altName ? SECSuccess : SECFailure;
+    SAN = cert_GetSubjectAltNameList(cert, arena);
+    if (SAN) {
+	numDNSNames = cert_CountDNSPatterns(SAN);
+	DN = cert_CombineNamesLists(DN, SAN);
     }
-    if (rv != SECSuccess && PORT_GetError() == SEC_ERROR_EXTENSION_NOT_FOUND)
-	rv = SECSuccess;
-    if (altNameExtension.data)
-	SECITEM_FreeItem(&altNameExtension, PR_FALSE);
-    if (rv != SECSuccess)
-        goto loser;
-    DN = cert_CombineNamesLists(DN, altName);
-
-    /* TODO: unmark arena */
-    return DN;
+    if (!numDNSNames && includeSubjectCommonName) {
+	char *cn = CERT_GetCommonName(&cert->subject);
+	if (cn) {
+	    CERTGeneralName *CN = CERT_NewGeneralName(arena, certDNSName);
+	    if (CN) {
+		SECItem cnItem = {siBuffer, NULL, 0};
+		cnItem.data = (unsigned char *)cn;
+		cnItem.len  = strlen(cn);
+		rv = SECITEM_CopyItem(arena, &CN->name.other, &cnItem);
+		if (rv == SECSuccess) {
+		    DN = cert_CombineNamesLists(DN, CN);
+	        }
+	    }
+	    PORT_Free(cn);
+	}
+    }
+    if (rv == SECSuccess) {
+	/* TODO: unmark arena */
+	return DN;
+    }
 loser:
     /* TODO: release arena to mark */
     return NULL;
 }
 
 /* Returns SECSuccess if name matches constraint per RFC 3280 rules for 
 ** URI name constraints.  SECFailure otherwise.
 ** If the constraint begins with a dot, it is a domain name, otherwise
--- a/security/nss/lib/certhigh/certvfy.c
+++ b/security/nss/lib/certhigh/certvfy.c
@@ -433,18 +433,18 @@ cert_VerifyFortezzaV1Cert(CERTCertDBHand
     if (key->keyType != fortezzaKey) {
     	SECKEY_DestroyPublicKey(key);
 	/* CA Cert not fortezza */
     	PORT_SetError(SEC_ERROR_NOT_FORTEZZA_ISSUER);
 	return SECFailure;
     }
 
     /* get the privilege mask */
-    if (key->u.fortezza.DSSpriviledge.len > 0) {
-	priv = key->u.fortezza.DSSpriviledge.data[0];
+    if (key->u.fortezza.DSSprivilege.len > 0) {
+	priv = key->u.fortezza.DSSprivilege.data[0];
     }
 
     /*
      * make sure the CA's keys are OK
      */
             
     rv = SEC_CheckKRL(handle, key, NULL, t, wincx);
     SECKEY_DestroyPublicKey(key);
@@ -598,17 +598,20 @@ cert_VerifyCertChainOld(CERTCertDBHandle
 	 * certifcates (except leaf (EE) certs, root CAs, and self-issued
 	 * intermediate CAs) to be verified against the name constraints 
 	 * extension of the issuer certificate. 
 	 */
 	if (subjectCertIsSelfIssued == PR_FALSE) {
 	    CERTGeneralName *subjectNameList;
 	    int subjectNameListLen;
 	    int i;
-	    subjectNameList    = CERT_GetCertificateNames(subjectCert, arena);
+	    PRBool getSubjectCN = (!count && certUsage == certUsageSSLServer);
+	    subjectNameList = 
+	    	CERT_GetConstrainedCertificateNames(subjectCert, arena,
+		                                    getSubjectCN);
 	    if (!subjectNameList)
 		goto loser;
 	    subjectNameListLen = CERT_GetNamesLength(subjectNameList);
 	    if (!subjectNameListLen)
 		goto loser;
 	    if (certsListLen <= namesCount + subjectNameListLen) {
 		CERTCertificate **tmpCertsList;
 		certsListLen = (namesCount + subjectNameListLen) * 2;
--- a/security/nss/lib/certhigh/certvfypkix.c
+++ b/security/nss/lib/certhigh/certvfypkix.c
@@ -1219,17 +1219,17 @@ cert_VerifyCertChainPkix(
     fnStackNameArr[0] = "cert_VerifyCertChainPkix";
     fnStackInvCountArr[0] = 0;
     PKIX_Boolean abortOnLeak = 
         (PR_GetEnv("PKIX_OBJECT_LEAK_TEST_ABORT_ON_LEAK") == NULL) ?
                                                    PKIX_FALSE : PKIX_TRUE;
     runningLeakTest = PKIX_TRUE;
 
     /* Prevent multi-threaded run of object leak test */
-    fnInvLocalCount = PR_AtomicIncrement(&parallelFnInvocationCount);
+    fnInvLocalCount = PR_ATOMIC_INCREMENT(&parallelFnInvocationCount);
     PORT_Assert(fnInvLocalCount == 1);
 
 do {
     rv = SECFailure;
     plContext = NULL;
     procParams = NULL;
     result = NULL;
     verifyNode = NULL;
@@ -1322,17 +1322,17 @@ cleanup:
     errorFnStackString = NULL;
     if (abortOnLeak) {
         PORT_Assert(leakedObjNum == 0);
     }
 
 } while (errorGenerated);
 
     runningLeakTest = PKIX_FALSE; 
-    PR_AtomicDecrement(&parallelFnInvocationCount);
+    PR_ATOMIC_DECREMENT(&parallelFnInvocationCount);
     usePKIXValidationEngine = savedUsePkixEngFlag;
 #endif /* PKIX_OBJECT_LEAK_TEST */
 
     return rv;
 }
 
 PKIX_CertSelector *
 cert_GetTargetCertConstraints(CERTCertificate *target, void *plContext) 
@@ -1512,17 +1512,17 @@ setRevocationMethod(PKIX_RevocationCheck
                     PKIX_Boolean verifyResponderUsages,
                     PKIX_Boolean isLeafTest,
                     void *plContext)
 {
     PKIX_UInt32 methodFlags = 0;
     PKIX_Error *error = NULL;
     int priority = 0;
     
-    if (revTest->number_of_defined_methods < certRevMethod) {
+    if (revTest->number_of_defined_methods <= certRevMethod) {
         return NULL;
     }
     if (revTest->preferred_methods) {
         int i = 0;
         for (;i < revTest->number_of_preferred_methods;i++) {
             if (revTest->preferred_methods[i] == certRevMethod) 
                 break;
         }
@@ -1731,16 +1731,17 @@ cert_pkixSetParam(PKIX_ProcessingParams 
                 PKIX_ProcessingParams_SetUseAIAForCertFetching(procParams,
                                      (PRBool)(param->value.scalar.b != 0),
                                                                plContext);
             break;
             
         default:
             PORT_SetError(errCode);
             r = SECFailure;
+            break;
     }
 
     if (policyOIDList != NULL)
         PKIX_PL_Object_DecRef((PKIX_PL_Object *)policyOIDList, plContext);
 
     if (date != NULL) 
         PKIX_PL_Object_DecRef((PKIX_PL_Object *)date, plContext);
 
@@ -2054,17 +2055,17 @@ SECStatus CERT_PKIXVerifyCert(
     fnStackNameArr[0] = "CERT_PKIXVerifyCert";
     fnStackInvCountArr[0] = 0;
     PKIX_Boolean abortOnLeak = 
         (PR_GetEnv("PKIX_OBJECT_LEAK_TEST_ABORT_ON_LEAK") == NULL) ?
                                                    PKIX_FALSE : PKIX_TRUE;
     runningLeakTest = PKIX_TRUE;
 
     /* Prevent multi-threaded run of object leak test */
-    fnInvLocalCount = PR_AtomicIncrement(&parallelFnInvocationCount);
+    fnInvLocalCount = PR_ATOMIC_INCREMENT(&parallelFnInvocationCount);
     PORT_Assert(fnInvLocalCount == 1);
 
 do {
     r = SECFailure;
     error = NULL;
     procParams = NULL;
     buildResult = NULL;
     nbioContext = NULL;  /* for non-blocking IO */
@@ -2263,14 +2264,14 @@ cleanup:
     errorFnStackString = NULL;
     if (abortOnLeak) {
         PORT_Assert(leakedObjNum == 0);
     }
     
 } while (errorGenerated);
 
     runningLeakTest = PKIX_FALSE; 
-    PR_AtomicDecrement(&parallelFnInvocationCount);
+    PR_ATOMIC_DECREMENT(&parallelFnInvocationCount);
     usePKIXValidationEngine = savedUsePkixEngFlag;
 #endif /* PKIX_OBJECT_LEAK_TEST */
 
     return r;
 }
--- a/security/nss/lib/certhigh/ocsp.c
+++ b/security/nss/lib/certhigh/ocsp.c
@@ -34,17 +34,17 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 /*
  * Implementation of OCSP services, for both client and server.
  * (XXX, really, mostly just for client right now, but intended to do both.)
  *
- * $Id: ocsp.c,v 1.64 2010/02/01 20:09:31 wtc%google.com Exp $
+ * $Id: ocsp.c,v 1.65 2010/06/07 19:03:27 kaie%kuix.de Exp $
  */
 
 #include "prerror.h"
 #include "prprf.h"
 #include "plarena.h"
 #include "prnetdb.h"
 
 #include "seccomon.h"
@@ -5184,17 +5184,17 @@ cert_ProcessOCSPResponse(CERTCertDBHandl
                          CERTOCSPResponse *response, 
                          CERTOCSPCertID   *certID,
                          CERTCertificate  *signerCert,
                          int64             time,
                          PRBool           *certIDWasConsumed,
                          SECStatus        *cacheUpdateStatus)
 {
     SECStatus rv;
-    SECStatus rv_cache;
+    SECStatus rv_cache = SECSuccess;
     CERTOCSPSingleResponse *single = NULL;
 
     rv = ocsp_GetVerifiedSingleResponseForCertID(handle, response, certID, 
                                                  signerCert, time, &single);
     if (rv == SECSuccess) {
         /*
          * Check whether the status says revoked, and if so 
          * how that compares to the time value passed into this routine.
--- a/security/nss/lib/ckfw/capi/crsa.c
+++ b/security/nss/lib/ckfw/capi/crsa.c
@@ -31,17 +31,17 @@
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifdef DEBUG
-static const char CVS_ID[] = "@(#) $RCSfile: crsa.c,v $ $Revision: 1.3 $ $Date: 2005/11/15 00:13:58 $";
+static const char CVS_ID[] = "@(#) $RCSfile: crsa.c,v $ $Revision: 1.4 $ $Date: 2010/04/25 23:37:40 $";
 #endif /* DEBUG */
 
 #include "ckcapi.h"
 #include "secdert.h"
 
 #define SSL3_SHAMD5_HASH_SIZE  36 /* LEN_MD5 (16) + LEN_SHA1 (20) */
 
 /*
@@ -545,17 +545,17 @@ ckcapi_mdCryptoOperationRSASign_UpdateFi
    * ray, or a broken processor, verify that it is valid... */
   rc = CryptVerifySignature(hHash, output->data, output->size, 
                             iOperation->hKey, NULL, 0);
   if (!rc) {
     goto loser;
   }
 
   /* OK, Microsoft likes to do things completely differently than anyone
-   * else. We need to reverse the data we recieved here */
+   * else. We need to reverse the data we received here */
   ckcapi_ReverseData(output);
   CryptDestroyHash(hHash);
   return CKR_OK;
 
 loser:
   /* map the microsoft error */
   if (CKR_OK == error) {
     msError = GetLastError();
--- a/security/nss/lib/ckfw/nssmkey/mobject.c
+++ b/security/nss/lib/ckfw/nssmkey/mobject.c
@@ -31,17 +31,17 @@
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 #ifdef DEBUG
-static const char CVS_ID[] = "@(#) $RCSfile: mobject.c,v $ $Revision: 1.4 $ $Date: 2009/02/25 18:38:04 $";
+static const char CVS_ID[] = "@(#) $RCSfile: mobject.c,v $ $Revision: 1.5 $ $Date: 2010/04/25 23:37:40 $";
 #endif /* DEBUG */
 
 #include "ckmk.h"
 #include "nssbase.h"
 
 #include "secdert.h" /* for DER_INTEGER */
 #include "string.h"
 
@@ -847,17 +847,17 @@ ckmk_FetchPrivKeyAttribute
   case CKA_MODULUS:
     if (0 == item->modulus.size) {
       ckmk_fetchModulus(io);
     }
     return &item->modulus;
   case CKA_PUBLIC_EXPONENT:
     return &ckmk_emptyItem;
 #ifdef notdef
-  /* the following are sensitive attributes. We could implment them for 
+  /* the following are sensitive attributes. We could implement them for 
    * sensitive keys using the key export function, but it's better to
    * just support wrap through this token. That will more reliably allow us
    * to export any private key that is truly exportable.
    */
   case CKA_PRIVATE_EXPONENT:
     CKMK_HANDLE_DATA_ITEM(io, kSecPrivateExponentItemAttr, privateExponent, 
                           item, *pError)
   case CKA_PRIME_1:
--- a/security/nss/lib/ckfw/token.c
+++ b/security/nss/lib/ckfw/token.c
@@ -30,17 +30,17 @@
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifdef DEBUG
-static const char CVS_ID[] = "@(#) $RCSfile: token.c,v $ $Revision: 1.13 $ $Date: 2009/02/09 07:55:53 $";
+static const char CVS_ID[] = "@(#) $RCSfile: token.c,v $ $Revision: 1.16 $ $Date: 2010/03/15 06:07:56 $";
 #endif /* DEBUG */
 
 /*
  * token.c
  *
  * This file implements the NSSCKFWToken type and methods.
  */
 
@@ -385,19 +385,19 @@ nssCKFWToken_Destroy
   nssCKFWHash_Destroy(fwToken->sessions);
 
   /* session objects go away when their sessions are removed */
   if (fwToken->sessionObjectHash) {
     nssCKFWHash_Destroy(fwToken->sessionObjectHash);
   }
 
   /* free up the token objects */
-  nssCKFWHash_Iterate(fwToken->mdObjectHash, nss_ckfwtoken_object_iterator, 
+  if (fwToken->mdObjectHash) {
+    nssCKFWHash_Iterate(fwToken->mdObjectHash, nss_ckfwtoken_object_iterator, 
                                                                 (void *)NULL);
-  if (fwToken->mdObjectHash) {
     nssCKFWHash_Destroy(fwToken->mdObjectHash);
   }
   if (fwToken->mdMechanismHash) {
     nssCKFWHash_Destroy(fwToken->mdMechanismHash);
   }
 
   nssCKFWSlot_ClearToken(fwToken->fwSlot);
   
--- a/security/nss/lib/ckfw/wrap.c
+++ b/security/nss/lib/ckfw/wrap.c
@@ -30,17 +30,17 @@
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifdef DEBUG
-static const char CVS_ID[] = "@(#) $RCSfile: wrap.c,v $ $Revision: 1.18 $ $Date: 2009/02/09 07:55:53 $";
+static const char CVS_ID[] = "@(#) $RCSfile: wrap.c,v $ $Revision: 1.20 $ $Date: 2010/04/03 18:27:29 $";
 #endif /* DEBUG */
 
 /*
  * wrap.c
  *
  * This file contains the routines that actually implement the cryptoki
  * API, using the internal APIs of the NSS Cryptoki Framework.  There is
  * one routine here for every cryptoki routine.  For linking reasons
@@ -201,17 +201,17 @@ NSSCKFWC_Initialize
   if( CKR_OK != error ) {
     goto loser;
   }
 
   *pFwInstance = nssCKFWInstance_Create(pInitArgs, locking_state, mdInstance, &error);
   if (!*pFwInstance) {
     goto loser;
   }
-  PR_AtomicIncrement(&liveInstances);
+  PR_ATOMIC_INCREMENT(&liveInstances);
   return CKR_OK;
 
  loser:
   switch( error ) {
   case CKR_ARGUMENTS_BAD:
   case CKR_CANT_LOCK:
   case CKR_CRYPTOKI_ALREADY_INITIALIZED:
   case CKR_FUNCTION_FAILED:
@@ -254,17 +254,17 @@ NSSCKFWC_Finalize
 
   /* In any case */
   *pFwInstance = (NSSCKFWInstance *)NULL;
 
  loser:
   switch( error ) {
   PRInt32 remainingInstances;
   case CKR_OK:
-    remainingInstances = PR_AtomicDecrement(&liveInstances);
+    remainingInstances = PR_ATOMIC_DECREMENT(&liveInstances);
     if (!remainingInstances) {
 	nssArena_Shutdown();
     }
     break;
   case CKR_CRYPTOKI_NOT_INITIALIZED:
   case CKR_FUNCTION_FAILED:
   case CKR_GENERAL_ERROR:
   case CKR_HOST_MEMORY:
@@ -1772,16 +1772,19 @@ NSSCKFWC_SetOperationState
   } else {
     aKey = nssCKFWInstance_ResolveObjectHandle(fwInstance, hAuthenticationKey);
     if (!aKey) {
       error = CKR_KEY_HANDLE_INVALID;
       goto loser;
     }
   }
 
+  state.data = pOperationState;
+  state.size = ulOperationStateLen;
+
   error = nssCKFWSession_SetOperationState(fwSession, &state, eKey, aKey);
   if( CKR_OK != error ) {
     goto loser;
   }
 
   return CKR_OK;
 
  loser:
--- a/security/nss/lib/crmf/crmf.h
+++ b/security/nss/lib/crmf/crmf.h
@@ -78,21 +78,21 @@ extern SECStatus
  *    fn
  *        A Callback function that the ASN1 encoder calls whenever
  *        the encoder wants to write out some DER encoded bytes.
  *    arg
  *        An opaque pointer that gets passed to the function fn.
  * OUTPUT:
  *    The function fn will be called, probably multiple times whenever 
  *    the ASN1 encoder wants to write out DER-encoded bytes.  Look at the 
- *    comments in crmft.h where the CRMFEncoderOuputCallback type is
+ *    comments in crmft.h where the CRMFEncoderOutputCallback type is
  *    defined for information on proper behavior of the funciton fn.
  * RETURN:
  *    SECSuccess if encoding was successful.  Any other return value 
- *    indicates an error occured during encoding.
+ *    indicates an error occurred during encoding.
  */
 extern SECStatus CRMF_EncodeCertRequest (CRMFCertRequest           *inCertReq,
 					 CRMFEncoderOutputCallback  fn,
 					 void                      *arg);
 /*
  * FUNCTION: CRMF_EncodeCertReqMessages
  * INPUTS:
  *    inCertReqMsgs
@@ -110,17 +110,17 @@ extern SECStatus CRMF_EncodeCertRequest 
  * NOTES:
  *    The parameter inCertReqMsgs needs to be an array with a NULL pointer
  *    to signal the end of messages.  An array in the form of 
  *    {m1, m2, m3, NULL, m4, ...} will only encode the messages m1, m2, and
  *    m3.  All messages from m4 on will not be looked at by the library.
  *
  * OUTPUT:
  *    The function fn will be called, probably multiple times.  Look at the 
- *    comments in crmft.h where the CRMFEncoderOuputCallback type is
+ *    comments in crmft.h where the CRMFEncoderOutputCallback type is
  *    defined for information on proper behavior of the funciton fn.
  *
  * RETURN:
  * SECSuccess if encoding the Certificate Request Messages was successful. 
  * Any other return value indicates an error occurred while encoding the
  * certificate request messages.
  */
 extern SECStatus 
--- a/security/nss/lib/crmf/crmfdec.c
+++ b/security/nss/lib/crmf/crmfdec.c
@@ -130,25 +130,27 @@ crmf_decode_process_popoprivkey(CRMFCert
     popoPrivKey->messageChoice = crmf_get_messagechoice_from_der(derPOP);
     if (popoPrivKey->messageChoice == crmfNoMessage) {
         return SECFailure;
     }
     /* If we ever encounter BER encodings of this, we'll get in trouble*/
     switch (popoPrivKey->messageChoice) {
     case crmfThisMessage:
     case crmfDHMAC:
+        privKeyDer.type = derPOP->type;
         privKeyDer.data = &derPOP->data[5];
 	privKeyDer.len  = derPOP->len - 5;
 	break;
     case crmfSubsequentMessage:
+        privKeyDer.type = derPOP->type;
         privKeyDer.data = &derPOP->data[4];
 	privKeyDer.len  = derPOP->len - 4;
 	break;
     default:
-        rv = SECFailure;
+        return SECFailure;
     }
 
     rv = SECITEM_CopyItem(inCertReqMsg->poolp, 
 			  &popoPrivKey->message.subsequentMessage,
 			  &privKeyDer);
 
     if (rv != SECSuccess) {
         return rv;
--- a/security/nss/lib/cryptohi/keythi.h
+++ b/security/nss/lib/cryptohi/keythi.h
@@ -37,24 +37,40 @@
 #ifndef _KEYTHI_H_
 #define _KEYTHI_H_ 1
 
 #include "plarena.h"
 #include "pkcs11t.h"
 #include "secmodt.h"
 #include "prclist.h"
 
+/*
+** RFC 4055 specifies three different RSA key types.
+**
+** rsaKey maps to keys with SEC_OID_PKCS1_RSA_ENCRYPTION and can be used for
+** both encryption and signatures with old (PKCS #1 v1.5) and new (PKCS #1
+** v2.1) padding schemes.
+**
+** rsaPssKey maps to keys with SEC_OID_PKCS1_RSA_PSS_SIGNATURE and may only
+** be used for signatures with PSS padding (PKCS #1 v2.1).
+**
+** rsaOaepKey maps to keys with SEC_OID_PKCS1_RSA_OAEP_ENCRYPTION and may only
+** be used for encryption with OAEP padding (PKCS #1 v2.1).
+*/ 
+
 typedef enum { 
     nullKey = 0, 
     rsaKey = 1, 
     dsaKey = 2, 
     fortezzaKey = 3,
     dhKey = 4, 
     keaKey = 5,
-    ecKey = 6
+    ecKey = 6,
+    rsaPssKey = 7,
+    rsaOaepKey = 8
 } KeyType;
 
 /*
 ** Template Definitions
 **/
 
 SEC_BEGIN_PROTOS
 extern const SEC_ASN1Template SECKEY_RSAPublicKeyTemplate[];
@@ -153,16 +169,18 @@ struct SECKEYFortezzaPublicKeyStr {
     SECItem KEApriviledge;
     SECItem DSSpriviledge;
     SECItem KEAKey;
     SECItem DSSKey;
     SECKEYPQGParams params;
     SECKEYPQGParams keaParams;
 };
 typedef struct SECKEYFortezzaPublicKeyStr SECKEYFortezzaPublicKey;
+#define KEAprivilege KEApriviledge /* corrected spelling */
+#define DSSprivilege DSSpriviledge /* corrected spelling */
 
 struct SECKEYDiffPQGParamsStr {
     SECKEYPQGParams DiffKEAParams;
     SECKEYPQGParams DiffDSAParams;
 };
 typedef struct SECKEYDiffPQGParamsStr SECKEYDiffPQGParams;
 
 struct SECKEYPQGDualParamsStr {
--- a/security/nss/lib/cryptohi/sechash.c
+++ b/security/nss/lib/cryptohi/sechash.c
@@ -230,17 +230,17 @@ HASH_GetHashOidTagByHMACOidTag(SECOidTag
     return hashOid;
 }
 
 SECOidTag
 HASH_GetHMACOidTagByHashOidTag(SECOidTag hashOid)
 {
     SECOidTag hmacOid = SEC_OID_UNKNOWN;
 
-    switch(hmacOid) {
+    switch(hashOid) {
     /* no oid exists for HMAC_MD2 */
     /* NSS does not define a oid for HMAC_MD4 */
     case SEC_OID_SHA1:   hmacOid = SEC_OID_HMAC_SHA1;   break;
     case SEC_OID_SHA256: hmacOid = SEC_OID_HMAC_SHA256; break;
     case SEC_OID_SHA384: hmacOid = SEC_OID_HMAC_SHA384; break;
     case SEC_OID_SHA512: hmacOid = SEC_OID_HMAC_SHA512; break;
     default:             hmacOid = SEC_OID_UNKNOWN;   
 	PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
--- a/security/nss/lib/cryptohi/seckey.c
+++ b/security/nss/lib/cryptohi/seckey.c
@@ -222,17 +222,27 @@ SECKEY_CreateRSAPrivateKey(int keySizeIn
 ** another token, and the high cost of moving "sensitive" keys, we attempt
 ** to create this key pair without the "sensitive" attribute, but revert to 
 ** creating a "sensitive" key if necessary.
 */
 SECKEYPrivateKey *
 SECKEY_CreateDHPrivateKey(SECKEYDHParams *param, SECKEYPublicKey **pubk, void *cx)
 {
     SECKEYPrivateKey *privk;
-    PK11SlotInfo *slot = PK11_GetBestSlot(CKM_DH_PKCS_KEY_PAIR_GEN,cx);
+    PK11SlotInfo *slot;
+
+    if (!param || !param->base.data || !param->prime.data ||
+        param->prime.len < 512/8 || param->base.len == 0 || 
+        param->base.len > param->prime.len + 1 || 
+	(param->base.len == 1 && param->base.data[0] == 0)) {
+	PORT_SetError(SEC_ERROR_INVALID_ARGS);
+	return NULL;
+    }
+
+    slot = PK11_GetBestSlot(CKM_DH_PKCS_KEY_PAIR_GEN,cx);
     if (!slot) {
 	return NULL;
     }
 
     privk = PK11_GenerateKeyPair(slot, CKM_DH_PKCS_KEY_PAIR_GEN, param, 
                                  pubk, PR_FALSE, PR_FALSE, cx);
     if (!privk) 
 	privk = PK11_GenerateKeyPair(slot, CKM_DH_PKCS_KEY_PAIR_GEN, param, 
@@ -869,24 +879,24 @@ SECKEY_FortezzaDecodeCertKey(PRArenaPool
 	}
 	PORT_Memcpy(pubk->u.fortezza.clearance.data,clearptr,
 					pubk->u.fortezza.clearance.len);
 
 	/* KEAPrivilege (the string up to the first byte with the hi-bit on */
 	clearptr = rawptr;
 	while ((rawptr < end) && (*rawptr++ & 0x80));
 	if (rawptr >= end) { return SECFailure; }
-	pubk->u.fortezza.KEApriviledge.len = rawptr - clearptr;
-	pubk->u.fortezza.KEApriviledge.data = 
-		(unsigned char*)PORT_ArenaZAlloc(arena,pubk->u.fortezza.KEApriviledge.len);
-	if (pubk->u.fortezza.KEApriviledge.data == NULL) {
+	pubk->u.fortezza.KEAprivilege.len = rawptr - clearptr;
+	pubk->u.fortezza.KEAprivilege.data = 
+		(unsigned char*)PORT_ArenaZAlloc(arena,pubk->u.fortezza.KEAprivilege.len);
+	if (pubk->u.fortezza.KEAprivilege.data == NULL) {
 		return SECFailure;
 	}
-	PORT_Memcpy(pubk->u.fortezza.KEApriviledge.data,clearptr,
-				pubk->u.fortezza.KEApriviledge.len);
+	PORT_Memcpy(pubk->u.fortezza.KEAprivilege.data,clearptr,
+				pubk->u.fortezza.KEAprivilege.len);
 
 
 	/* now copy the key. The next to bytes are the key length, and the
 	 * key follows */
 	pubk->u.fortezza.KEAKey.len = (*rawptr << 8) | rawptr[1];
 
 	rawptr += 2;
 	if (rawptr+pubk->u.fortezza.KEAKey.len > end) { return SECFailure; }
@@ -901,43 +911,43 @@ SECKEY_FortezzaDecodeCertKey(PRArenaPool
 
 	/* shared key */
 	if (rawptr >= end) {
 	    pubk->u.fortezza.DSSKey.len = pubk->u.fortezza.KEAKey.len;
 	    /* this depends on the fact that we are going to get freed with an
 	     * ArenaFree call. We cannot free DSSKey and KEAKey separately */
 	    pubk->u.fortezza.DSSKey.data=
 					pubk->u.fortezza.KEAKey.data;
-	    pubk->u.fortezza.DSSpriviledge.len = 
-				pubk->u.fortezza.KEApriviledge.len;
-	    pubk->u.fortezza.DSSpriviledge.data =
-			pubk->u.fortezza.DSSpriviledge.data;
+	    pubk->u.fortezza.DSSprivilege.len = 
+				pubk->u.fortezza.KEAprivilege.len;
+	    pubk->u.fortezza.DSSprivilege.data =
+			pubk->u.fortezza.DSSprivilege.data;
 	    goto done;
 	}
 		
 
 	/* DSS Version is next */
 	pubk->u.fortezza.DSSversion = *rawptr++;
 
 	if (*rawptr++ != 2) {
 		return SECFailure;
 	}
 
 	/* DSSPrivilege (the string up to the first byte with the hi-bit on */
 	clearptr = rawptr;
 	while ((rawptr < end) && (*rawptr++ & 0x80));
 	if (rawptr >= end) { return SECFailure; }
-	pubk->u.fortezza.DSSpriviledge.len = rawptr - clearptr;
-	pubk->u.fortezza.DSSpriviledge.data = 
-		(unsigned char*)PORT_ArenaZAlloc(arena,pubk->u.fortezza.DSSpriviledge.len);
-	if (pubk->u.fortezza.DSSpriviledge.data == NULL) {
+	pubk->u.fortezza.DSSprivilege.len = rawptr - clearptr;
+	pubk->u.fortezza.DSSprivilege.data = 
+		(unsigned char*)PORT_ArenaZAlloc(arena,pubk->u.fortezza.DSSprivilege.len);
+	if (pubk->u.fortezza.DSSprivilege.data == NULL) {
 		return SECFailure;
 	}
-	PORT_Memcpy(pubk->u.fortezza.DSSpriviledge.data,clearptr,
-				pubk->u.fortezza.DSSpriviledge.len);
+	PORT_Memcpy(pubk->u.fortezza.DSSprivilege.data,clearptr,
+				pubk->u.fortezza.DSSprivilege.len);
 
 	/* finally copy the DSS key. The next to bytes are the key length,
 	 *  and the key follows */
 	pubk->u.fortezza.DSSKey.len = (*rawptr << 8) | rawptr[1];
 
 	rawptr += 2;
 	if (rawptr+pubk->u.fortezza.DSSKey.len > end){ return SECFailure; }
 	pubk->u.fortezza.DSSKey.data = 
@@ -960,16 +970,22 @@ KeyType
 seckey_GetKeyType (SECOidTag tag) {
     KeyType keyType;
 
     switch (tag) {
       case SEC_OID_X500_RSA_ENCRYPTION:
       case SEC_OID_PKCS1_RSA_ENCRYPTION:
 	keyType = rsaKey;
 	break;
+      case SEC_OID_PKCS1_RSA_PSS_SIGNATURE:
+	keyType = rsaPssKey;
+	break;
+      case SEC_OID_PKCS1_RSA_OAEP_ENCRYPTION:
+	keyType = rsaOaepKey;
+	break;
       case SEC_OID_ANSIX9_DSA_SIGNATURE:
 	keyType = dsaKey;
 	break;
       case SEC_OID_MISSI_KEA_DSS_OLD:
       case SEC_OID_MISSI_KEA_DSS:
       case SEC_OID_MISSI_DSS_OLD:
       case SEC_OID_MISSI_DSS:  
 	keyType = fortezzaKey;
@@ -1461,38 +1477,43 @@ SECKEY_ECParamsToBasePointOrderLen(const
 unsigned
 SECKEY_PublicKeyStrength(const SECKEYPublicKey *pubk)
 {
     unsigned char b0;
     unsigned size;
 
     /* interpret modulus length as key strength... in
      * fortezza that's the public key length */
-
+    if (!pubk)
+    	goto loser;
     switch (pubk->keyType) {
     case rsaKey:
+	if (!pubk->u.rsa.modulus.data) break;
     	b0 = pubk->u.rsa.modulus.data[0];
     	return b0 ? pubk->u.rsa.modulus.len : pubk->u.rsa.modulus.len - 1;
     case dsaKey:
+	if (!pubk->u.dsa.publicValue.data) break;
     	b0 = pubk->u.dsa.publicValue.data[0];
     	return b0 ? pubk->u.dsa.publicValue.len :
 	    pubk->u.dsa.publicValue.len - 1;
     case dhKey:
+	if (!pubk->u.dh.publicValue.data) break;
     	b0 = pubk->u.dh.publicValue.data[0];
     	return b0 ? pubk->u.dh.publicValue.len :
 	    pubk->u.dh.publicValue.len - 1;
     case fortezzaKey:
 	return PR_MAX(pubk->u.fortezza.KEAKey.len, pubk->u.fortezza.DSSKey.len);
     case ecKey:
 	/* Get the key size in bits and adjust */
 	size =	SECKEY_ECParamsToKeySize(&pubk->u.ec.DEREncodedParams);
 	return (size + 7)/8;
     default:
 	break;
     }
+loser:
     PORT_SetError(SEC_ERROR_INVALID_KEY);
     return 0;
 }
 
 /* returns key strength in bits */
 unsigned
 SECKEY_PublicKeyStrengthInBits(const SECKEYPublicKey *pubk)
 {
@@ -1649,21 +1670,21 @@ SECKEY_CopyPublicKey(const SECKEYPublicK
       case fortezzaKey:
           copyk->u.fortezza.KEAversion = pubk->u.fortezza.KEAversion;
           copyk->u.fortezza.DSSversion = pubk->u.fortezza.DSSversion;
           PORT_Memcpy(copyk->u.fortezza.KMID, pubk->u.fortezza.KMID,
                       sizeof(pubk->u.fortezza.KMID));
           rv = SECITEM_CopyItem(arena, &copyk->u.fortezza.clearance, 
                                 &pubk->u.fortezza.clearance);
           if (rv != SECSuccess) break;
-          rv = SECITEM_CopyItem(arena, &copyk->u.fortezza.KEApriviledge, 
-                                &pubk->u.fortezza.KEApriviledge);
+          rv = SECITEM_CopyItem(arena, &copyk->u.fortezza.KEAprivilege, 
+                                &pubk->u.fortezza.KEAprivilege);
           if (rv != SECSuccess) break;
-          rv = SECITEM_CopyItem(arena, &copyk->u.fortezza.DSSpriviledge, 
-                                &pubk->u.fortezza.DSSpriviledge);
+          rv = SECITEM_CopyItem(arena, &copyk->u.fortezza.DSSprivilege, 
+                                &pubk->u.fortezza.DSSprivilege);
           if (rv != SECSuccess) break;
           rv = SECITEM_CopyItem(arena, &copyk->u.fortezza.KEAKey, 
                                 &pubk->u.fortezza.KEAKey);
           if (rv != SECSuccess) break;
           rv = SECITEM_CopyItem(arena, &copyk->u.fortezza.DSSKey, 
                                 &pubk->u.fortezza.DSSKey);
           if (rv != SECSuccess) break;
           rv = SECITEM_CopyItem(arena, &copyk->u.fortezza.params.prime, 
--- a/security/nss/lib/cryptohi/secvfy.c
+++ b/security/nss/lib/cryptohi/secvfy.c
@@ -32,17 +32,17 @@
  * under the terms of either the GPL or the LGPL, and not to allow others to
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
-/* $Id: secvfy.c,v 1.23 2010/02/10 00:49:43 wtc%google.com Exp $ */
+/* $Id: secvfy.c,v 1.24 2010/06/23 02:13:56 wtc%google.com Exp $ */
 
 #include <stdio.h>
 #include "cryptohi.h"
 #include "sechash.h"
 #include "keyhi.h"
 #include "secasn1.h"
 #include "secoid.h"
 #include "pk11func.h"
@@ -232,16 +232,17 @@ sec_DecodeSigAlg(const SECKEYPublicKey *
         *hashalg = SEC_OID_MD5;
 	break;
       case SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION:
       case SEC_OID_ISO_SHA_WITH_RSA_SIGNATURE:
       case SEC_OID_ISO_SHA1_WITH_RSA_SIGNATURE:
         *hashalg = SEC_OID_SHA1;
 	break;
       case SEC_OID_PKCS1_RSA_ENCRYPTION:
+      case SEC_OID_PKCS1_RSA_PSS_SIGNATURE:
         *hashalg = SEC_OID_UNKNOWN; /* get it from the RSA signature */
 	break;
 
       case SEC_OID_ANSIX962_ECDSA_SHA256_SIGNATURE:
       case SEC_OID_PKCS1_SHA256_WITH_RSA_ENCRYPTION:
 	*hashalg = SEC_OID_SHA256;
 	break;
       case SEC_OID_ANSIX962_ECDSA_SHA384_SIGNATURE:
@@ -322,16 +323,19 @@ sec_DecodeSigAlg(const SECKEYPublicKey *
       case SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION:
       case SEC_OID_ISO_SHA_WITH_RSA_SIGNATURE:
       case SEC_OID_ISO_SHA1_WITH_RSA_SIGNATURE:
       case SEC_OID_PKCS1_SHA256_WITH_RSA_ENCRYPTION:
       case SEC_OID_PKCS1_SHA384_WITH_RSA_ENCRYPTION:
       case SEC_OID_PKCS1_SHA512_WITH_RSA_ENCRYPTION:
 	*encalg = SEC_OID_PKCS1_RSA_ENCRYPTION;
 	break;
+      case SEC_OID_PKCS1_RSA_PSS_SIGNATURE:
+	*encalg = SEC_OID_PKCS1_RSA_PSS_SIGNATURE;
+	break;
 
       /* what about normal DSA? */
       case SEC_OID_ANSIX9_DSA_SIGNATURE_WITH_SHA1_DIGEST:
       case SEC_OID_BOGUS_DSA_SIGNATURE_WITH_SHA1_DIGEST:
 	*encalg = SEC_OID_ANSIX9_DSA_SIGNATURE;
 	break;
       case SEC_OID_MISSI_DSS:
       case SEC_OID_MISSI_KEA_DSS:
@@ -373,35 +377,37 @@ vfy_CreateContext(const SECKEYPublicKey 
 	SECOidTag encAlg, SECOidTag hashAlg, SECOidTag *hash, void *wincx)
 {
     VFYContext *cx;
     SECStatus rv;
     unsigned int sigLen;
     KeyType type;
 
     /* make sure the encryption algorithm matches the key type */
+    /* RSA-PSS algorithm can be used with both rsaKey and rsaPssKey */
     type = seckey_GetKeyType(encAlg);
-    if (key->keyType != type) {
+    if ((key->keyType != type) &&
+	((key->keyType != rsaKey) || (type != rsaPssKey))) {
 	PORT_SetError(SEC_ERROR_PKCS7_KEYALG_MISMATCH);
 	return NULL;
     }
 
     cx = (VFYContext*) PORT_ZAlloc(sizeof(VFYContext));
     if (cx == NULL) {
 	goto loser;
     }
 
     cx->wincx = wincx;
     cx->hasSignature = (sig != NULL);
     cx->encAlg = encAlg;
     cx->hashAlg = hashAlg;
     cx->key = SECKEY_CopyPublicKey(key);
     rv = SECSuccess;
     if (sig) {
-	switch (key->keyType) {
+	switch (type) {
 	case rsaKey:
 	    rv = DecryptSigBlock(&cx->hashAlg, cx->u.buffer, &cx->rsadigestlen,
 			HASH_LENGTH_MAX, cx->key, sig, (char*)wincx);
 	    if (cx->hashAlg != hashAlg && hashAlg != SEC_OID_UNKNOWN) {
 		PORT_SetError(SEC_ERROR_BAD_SIGNATURE);
 		rv = SECFailure;	
 	    }
 	    break;
--- a/security/nss/lib/dev/devslot.c
+++ b/security/nss/lib/dev/devslot.c
@@ -30,17 +30,17 @@
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifdef DEBUG
-static const char CVS_ID[] = "@(#) $RCSfile: devslot.c,v $ $Revision: 1.26 $ $Date: 2010/01/08 02:00:58 $";
+static const char CVS_ID[] = "@(#) $RCSfile: devslot.c,v $ $Revision: 1.27 $ $Date: 2010/04/03 18:27:30 $";
 #endif /* DEBUG */
 
 #include "pkcs11.h"
 
 #ifndef DEVM_H
 #include "devm.h"
 #endif /* DEVM_H */
 
@@ -65,17 +65,17 @@ static PRIntervalTime s_token_delay_time
 static const CK_FLAGS s_ck_readonly_flags = CKF_SERIAL_SESSION;
 
 NSS_IMPLEMENT PRStatus
 nssSlot_Destroy (
   NSSSlot *slot
 )
 {
     if (slot) {
-	if (PR_AtomicDecrement(&slot->base.refCount) == 0) {
+	if (PR_ATOMIC_DECREMENT(&slot->base.refCount) == 0) {
 	    PZ_DestroyLock(slot->base.lock);
 	    return nssArena_Destroy(slot->base.arena);
 	}
     }
     return PR_SUCCESS;
 }
 
 void
@@ -102,17 +102,17 @@ NSSSlot_Destroy (
     (void)nssSlot_Destroy(slot);
 }
 
 NSS_IMPLEMENT NSSSlot *
 nssSlot_AddRef (
   NSSSlot *slot
 )
 {
-    PR_AtomicIncrement(&slot->base.refCount);
+    PR_ATOMIC_INCREMENT(&slot->base.refCount);
     return slot;
 }
 
 NSS_IMPLEMENT NSSUTF8 *
 nssSlot_GetName (
   NSSSlot *slot
 )
 {
--- a/security/nss/lib/dev/devtoken.c
+++ b/security/nss/lib/dev/devtoken.c
@@ -30,17 +30,17 @@
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifdef DEBUG
-static const char CVS_ID[] = "@(#) $RCSfile: devtoken.c,v $ $Revision: 1.53 $ $Date: 2010/01/08 02:00:58 $";
+static const char CVS_ID[] = "@(#) $RCSfile: devtoken.c,v $ $Revision: 1.54 $ $Date: 2010/04/03 18:27:30 $";
 #endif /* DEBUG */
 
 #include "pkcs11.h"
 
 #ifndef DEVM_H
 #include "devm.h"
 #endif /* DEVM_H */
 
@@ -60,17 +60,17 @@ extern const NSSError NSS_ERROR_PKCS11;
 #define OBJECT_STACK_SIZE 16
 
 NSS_IMPLEMENT PRStatus
 nssToken_Destroy (
   NSSToken *tok
 )
 {
     if (tok) {
-	if (PR_AtomicDecrement(&tok->base.refCount) == 0) {
+	if (PR_ATOMIC_DECREMENT(&tok->base.refCount) == 0) {
 	    PZ_DestroyLock(tok->base.lock);
 	    nssTokenObjectCache_Destroy(tok->cache);
 	    /* The token holds the first/last reference to the slot.
 	     * When the token is actually destroyed, that ref must go too.
 	     */
 	    (void)nssSlot_Destroy(tok->slot);
 	    return nssArena_Destroy(tok->base.arena);
 	}
@@ -94,17 +94,17 @@ NSSToken_Destroy (
     (void)nssToken_Destroy(tok);
 }
 
 NSS_IMPLEMENT NSSToken *
 nssToken_AddRef (
   NSSToken *tok
 )
 {
-    PR_AtomicIncrement(&tok->base.refCount);
+    PR_ATOMIC_INCREMENT(&tok->base.refCount);
     return tok;
 }
 
 NSS_IMPLEMENT NSSSlot *
 nssToken_GetSlot (
   NSSToken *tok
 )
 {
--- a/security/nss/lib/dev/devutil.c
+++ b/security/nss/lib/dev/devutil.c
@@ -30,17 +30,17 @@
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifdef DEBUG
-static const char CVS_ID[] = "@(#) $RCSfile: devutil.c,v $ $Revision: 1.33 $ $Date: 2008/11/19 20:44:35 $";
+static const char CVS_ID[] = "@(#) $RCSfile: devutil.c,v $ $Revision: 1.35 $ $Date: 2010/04/11 05:57:47 $";
 #endif /* DEBUG */
 
 #ifndef DEVM_H
 #include "devm.h"
 #endif /* DEVM_H */
 
 #ifndef CKHELPER_H
 #include "ckhelper.h"
@@ -259,16 +259,17 @@ nssTokenObjectCache_Create (
 	goto loser;
     }
     rvCache->doObjectType[cachedCerts] = cacheCerts;
     rvCache->doObjectType[cachedTrust] = cacheTrust;
     rvCache->doObjectType[cachedCRLs] = cacheCRLs;
     rvCache->token = token; /* cache goes away with token */
     return rvCache;
 loser:
+    nssTokenObjectCache_Destroy(rvCache);
     return (nssTokenObjectCache *)NULL;
 }
 
 static void
 clear_cache (
   nssTokenObjectCache *cache
 )
 {
@@ -304,17 +305,19 @@ nssTokenObjectCache_Clear (
 
 NSS_IMPLEMENT void
 nssTokenObjectCache_Destroy (
   nssTokenObjectCache *cache
 )
 {
     if (cache) {
 	clear_cache(cache);
-	PZ_DestroyLock(cache->lock);
+	if (cache->lock) {
+	    PZ_DestroyLock(cache->lock);
+	}
 	nss_ZFreeIf(cache);
     }
 }
 
 NSS_IMPLEMENT PRBool
 nssTokenObjectCache_HaveObjectClass (
   nssTokenObjectCache *cache,
   CK_OBJECT_CLASS objclass
@@ -731,21 +734,17 @@ find_objects_in_array (
 	    if (!objects[oi]) {
 		goto loser;
 	    }
 	}
     }
     nssArena_Destroy(arena);
     return objects;
 loser:
-    if (objects) {
-	for (--oi; oi>=0; --oi) {
-	    nssCryptokiObject_Destroy(objects[oi]);
-	}
-    }
+    nssCryptokiObjectArray_Destroy(objects);
     nssArena_Destroy(arena);
     return (nssCryptokiObject **)NULL;
 }
 
 NSS_IMPLEMENT nssCryptokiObject **
 nssTokenObjectCache_FindObjectsByTemplate (
   nssTokenObjectCache *cache,
   CK_OBJECT_CLASS objclass,
--- a/security/nss/lib/freebl/Makefile
+++ b/security/nss/lib/freebl/Makefile
@@ -55,31 +55,31 @@ include $(CORE_DEPTH)/coreconf/config.mk
 #######################################################################
 
 
 
 #######################################################################
 # (4) Include "local" platform-dependent assignments (OPTIONAL).      #
 #######################################################################
 
--include config.mk
+include config.mk
 
 # default for all platforms
 # unset this on those that have multiple freebl libraries
 FREEBL_BUILD_SINGLE_SHLIB = 1
 
 ifdef USE_64
 	DEFINES += -DNSS_USE_64
 endif
 
 ifdef USE_ABI32_FPU
 	DEFINES += -DNSS_USE_ABI32_FPU
 endif
 
-ifdef FREEBL_NO_DEPEND
+ifeq ($(FREEBL_NO_DEPEND),1)
 	DEFINES += -DFREEBL_NO_DEPEND
 endif
 # NSS_X86 means the target is a 32-bits x86 CPU architecture
 # NSS_X64 means the target is a 64-bits x64 CPU architecture
 # NSS_X86_OR_X64 means the target is either x86 or x64
 ifeq (,$(filter-out x386 x86 x86_64,$(CPU_ARCH)))
         DEFINES += -DNSS_X86_OR_X64
 ifdef USE_64
--- a/security/nss/lib/freebl/camellia.c
+++ b/security/nss/lib/freebl/camellia.c
@@ -31,17 +31,17 @@
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 /*
- * $Id: camellia.c,v 1.2 2008/11/18 19:48:22 rrelyea%redhat.com Exp $
+ * $Id: camellia.c,v 1.3 2010/04/30 00:10:53 wtc%google.com Exp $
  */
 
 #ifdef FREEBL_NO_DEPEND
 #include "stubs.h"
 #endif
 
 #include "prinit.h"
 #include "prerr.h"
@@ -67,23 +67,25 @@
 #define CAMELLIA_SIGMA6L (0xB05688C2L)
 #define CAMELLIA_SIGMA6R (0xB3E6C1FDL)
 
 /*
  *  macros
  */
 
 
-#if defined(_MSC_VER)
+#if defined(_MSC_VER) && defined(NSS_X86_OR_X64)
+
+/* require a little-endian CPU that allows unaligned access */
 
 # define SWAP(x) (_lrotl(x, 8) & 0x00ff00ff | _lrotr(x, 8) & 0xff00ff00)
 # define GETU32(p) SWAP(*((PRUint32 *)(p)))
 # define PUTU32(ct, st) {*((PRUint32 *)(ct)) = SWAP((st));}
 
-#else /* not MS-VC */
+#else /* not MSVC or not x86/x64 */
 
 # define GETU32(pt)					\
     (((PRUint32)(pt)[0] << 24)				\
      ^ ((PRUint32)(pt)[1] << 16)			\
      ^ ((PRUint32)(pt)[2] <<  8)			\
      ^ ((PRUint32)(pt)[3]))
 
 # define PUTU32(ct, st)  {				\
--- a/security/nss/lib/freebl/config.mk
+++ b/security/nss/lib/freebl/config.mk
@@ -60,16 +60,25 @@ ALL_TRASH :=    $(TARGETS) $(OBJS) $(OBJ
 #
 # override these variables to prevent building a DSO/DLL.
   TARGETS        = $(LIBRARY)
   SHARED_LIBRARY =
   IMPORT_LIBRARY =
   PROGRAM        =
 
 else
+
+ifeq ($(FREEBL_NO_DEPEND),1)
+LOWHASH_SRCS = stubs.c nsslowhash.c
+LOWHASH_EXPORTS = nsslowhash.h
+MAPFILE_SOURCE = freebl_hash.def
+else
+MAPFILE_SOURCE = freebl.def
+endif
+
 # This is a recursive child make. We build the shared lib.
 
 TARGETS      = $(SHARED_LIBRARY)
 LIBRARY      =
 IMPORT_LIBRARY =
 PROGRAM      =
 
 ifeq ($(OS_TARGET), SunOS)
@@ -80,18 +89,22 @@ ifeq (,$(filter-out WIN%,$(OS_TARGET)))
 
 # don't want the 32 in the shared library name
 SHARED_LIBRARY = $(OBJDIR)/$(DLL_PREFIX)$(LIBRARY_NAME)$(LIBRARY_VERSION).$(DLL_SUFFIX)
 
 RES     = $(OBJDIR)/$(LIBRARY_NAME).res
 RESNAME = freebl.rc
 
 ifndef WINCE
+ifdef NS_USE_GCC
+OS_LIBS += -lshell32
+else
 OS_LIBS += shell32.lib
 endif
+endif
 
 ifdef NS_USE_GCC
 EXTRA_SHARED_LIBS += \
 	-L$(DIST)/lib \
 	-L$(NSSUTIL_LIB_DIR) \
 	-lnssutil3 \
 	-L$(NSPR_LIB_DIR) \
 	-lnspr4 \
@@ -100,27 +113,27 @@ else # ! NS_USE_GCC
 EXTRA_SHARED_LIBS += \
 	$(DIST)/lib/nssutil3.lib \
 	$(NSPR_LIB_DIR)/$(NSPR31_LIB_PREFIX)nspr4.lib \
 	$(NULL)
 endif # NS_USE_GCC
 
 else
 
-ifndef FREEBL_NO_DEPEND
+ifeq ($(FREEBL_NO_DEPEND),1)
+#drop pthreads as well
+OS_PTHREAD=
+else
 EXTRA_SHARED_LIBS += \
 	-L$(DIST)/lib \
 	-L$(NSSUTIL_LIB_DIR) \
 	-lnssutil3 \
 	-L$(NSPR_LIB_DIR) \
 	-lnspr4 \
 	$(NULL)
-else
-#drop pthreads as well
-OS_PTHREAD=
 endif
 endif
 
 ifeq ($(OS_ARCH), Darwin)
 EXTRA_SHARED_LIBS += -dylib_file @executable_path/libplc4.dylib:$(DIST)/lib/libplc4.dylib -dylib_file @executable_path/libplds4.dylib:$(DIST)/lib/libplds4.dylib
 endif
 
 endif
--- a/security/nss/lib/freebl/freebl.rc
+++ b/security/nss/lib/freebl/freebl.rc
@@ -66,18 +66,18 @@
 #define MY_INTERNAL_NAME MY_LIBNAME SOFTOKEN_VMAJOR_STR
 
 /////////////////////////////////////////////////////////////////////////////
 //
 // Version-information resource
 //
 
 VS_VERSION_INFO VERSIONINFO
- FILEVERSION SOFTOKEN_VMAJOR,SOFTOKEN_VMINOR,SOFTOKEN_VPATCH,0
- PRODUCTVERSION SOFTOKEN_VMAJOR,SOFTOKEN_VMINOR,SOFTOKEN_VPATCH,0
+ FILEVERSION SOFTOKEN_VMAJOR,SOFTOKEN_VMINOR,SOFTOKEN_VPATCH,SOFTOKEN_VBUILD
+ PRODUCTVERSION SOFTOKEN_VMAJOR,SOFTOKEN_VMINOR,SOFTOKEN_VPATCH,SOFTOKEN_VBUILD
  FILEFLAGSMASK VS_FFI_FILEFLAGSMASK
  FILEFLAGS MY_FILEFLAGS_2
  FILEOS MY_FILEOS
  FILETYPE VFT_DLL
  FILESUBTYPE 0x0L // not used
 
 BEGIN
     BLOCK "StringFileInfo"
--- a/security/nss/lib/freebl/intel-aes.s
+++ b/security/nss/lib/freebl/intel-aes.s
@@ -1111,17 +1111,24 @@ intel_aes_encrypt_init_256:
 	call key_expansion256
 	.byte 0x66,0x0f,0x3a,0xdf,0xd3,0x08	/* aeskeygenassist $0x08, %xmm3, %xmm2 */
 	call key_expansion256
 	.byte 0x66,0x0f,0x3a,0xdf,0xd3,0x10	/* aeskeygenassist $0x10, %xmm3, %xmm2 */
 	call key_expansion256
 	.byte 0x66,0x0f,0x3a,0xdf,0xd3,0x20	/* aeskeygenassist $0x20, %xmm3, %xmm2 */
 	call key_expansion256
 	.byte 0x66,0x0f,0x3a,0xdf,0xd3,0x40	/* aeskeygenassist $0x40, %xmm3, %xmm2 */
-	call key_expansion256
+	pxor	%xmm6, %xmm6
+	pshufd	$0xff, %xmm2, %xmm2
+	shufps	$0x10, %xmm1, %xmm6
+	pxor	%xmm6, %xmm1
+	shufps	$0x8c, %xmm1, %xmm6
+	pxor	%xmm2, %xmm1
+	pxor	%xmm6, %xmm1
+	movdqu	%xmm1, (%rsi)
 
 	ret
 	.size intel_aes_encrypt_init_256, .-intel_aes_encrypt_init_256
 
 
 /* in %rdi : the key
    in %rsi : buffer for expanded key
 */
@@ -1169,36 +1176,43 @@ intel_aes_decrypt_init_256:
 	movdqu	%xmm5, -16(%rsi)
 	.byte 0x66,0x0f,0x3a,0xdf,0xd3,0x20	/* aeskeygenassist $0x20, %xmm3, %xmm2 */
 	call key_expansion256
 	.byte 0x66,0x0f,0x38,0xdb,0xe1	/* aesimc	%xmm1, %xmm4 */
 	.byte 0x66,0x0f,0x38,0xdb,0xeb	/* aesimc	%xmm3, %xmm5 */
 	movdqu	%xmm4, -32(%rsi)
 	movdqu	%xmm5, -16(%rsi)
 	.byte 0x66,0x0f,0x3a,0xdf,0xd3,0x40	/* aeskeygenassist $0x40, %xmm3, %xmm2 */
-	call key_expansion256
+	pxor	%xmm6, %xmm6
+	pshufd	$0xff, %xmm2, %xmm2
+	shufps	$0x10, %xmm1, %xmm6
+	pxor	%xmm6, %xmm1
+	shufps	$0x8c, %xmm1, %xmm6
+	pxor	%xmm2, %xmm1
+	pxor	%xmm6, %xmm1
+	movdqu	%xmm1, (%rsi)
 
 	ret
 	.size intel_aes_decrypt_init_256, .-intel_aes_decrypt_init_256
 
 
 	.type key_expansion256,@function
 	.align	16
 key_expansion256:
 	movd	%eax, %xmm6
 	pshufd	$0xff, %xmm2, %xmm2
 	shufps	$0x10, %xmm1, %xmm6
 	pxor	%xmm6, %xmm1
 	shufps	$0x8c, %xmm1, %xmm6
 	pxor	%xmm2, %xmm1
 	pxor	%xmm6, %xmm1
 	movdqu	%xmm1, (%rsi)
+
 	addq	$16, %rsi
 	.byte 0x66,0x0f,0x3a,0xdf,0xe1,0x00	/* aeskeygenassist $0, %xmm1, %xmm4 */
-
 	pshufd	$0xaa, %xmm4, %xmm4
 	shufps	$0x10, %xmm3, %xmm6
 	pxor	%xmm6, %xmm3
 	shufps	$0x8c, %xmm3, %xmm6
 	pxor	%xmm4, %xmm3
 	pxor	%xmm6, %xmm3
 	movdqu	%xmm3, (%rsi)
 	addq	$16, %rsi
--- a/security/nss/lib/freebl/manifest.mn
+++ b/security/nss/lib/freebl/manifest.mn
@@ -65,23 +65,16 @@ ifdef FREEBL_CHILD_BUILD
   endif
 endif
 
 # if the library name contains _, we prefix the version with _
 ifneq (,$(findstring _,$(LIBRARY_NAME)))
   LIBRARY_VERSION := _$(LIBRARY_VERSION)
 endif
 
-ifdef FREEBL_NO_DEPEND
-LOWHASH_SRCS = stubs.c nsslowhash.c
-LOWHASH_EXPORTS = nsslowhash.h
-MAPFILE_SOURCE = freebl_hash.def
-else
-MAPFILE_SOURCE = freebl.def
-endif
 MAPFILE = $(OBJDIR)/$(LIBRARY_NAME).def
 
 SOFTOKEN_LIBRARY_VERSION = 3
 
 DEFINES += -DSHLIB_SUFFIX=\"$(DLL_SUFFIX)\" -DSHLIB_PREFIX=\"$(DLL_PREFIX)\" \
 	-DSHLIB_VERSION=\"$(LIBRARY_VERSION)\" \
 	-DSOFTOKEN_SHLIB_VERSION=\"$(SOFTOKEN_LIBRARY_VERSION)\"
 
--- a/security/nss/lib/freebl/mpi/mpi-priv.h
+++ b/security/nss/lib/freebl/mpi/mpi-priv.h
@@ -37,17 +37,17 @@
  * under the terms of either the GPL or the LGPL, and not to allow others to
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
-/* $Id: mpi-priv.h,v 1.21 2009/03/19 02:26:48 julien.pierre.boogz%sun.com Exp $ */
+/* $Id: mpi-priv.h,v 1.23 2010/05/02 22:36:41 nelson%bolyard.com Exp $ */
 #ifndef _MPI_PRIV_H_
 #define _MPI_PRIV_H_ 1
 
 #include "mpi.h"
 #include <stdlib.h>
 #include <string.h>
 #include <ctype.h>
 
--- a/security/nss/lib/freebl/mpi/mpi.c
+++ b/security/nss/lib/freebl/mpi/mpi.c
@@ -35,17 +35,17 @@
  * under the terms of either the GPL or the LGPL, and not to allow others to
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
-/* $Id: mpi.c,v 1.45 2006/09/29 20:12:21 alexei.volkov.bugs%sun.com Exp $ */
+/* $Id: mpi.c,v 1.47 2010/05/02 22:36:41 nelson%bolyard.com Exp $ */
 
 #include "mpi-priv.h"
 #if defined(OSF1)
 #include <c_asm.h>
 #endif
 
 #if MP_LOGTAB
 /*
--- a/security/nss/lib/freebl/mpi/mpmontg.c
+++ b/security/nss/lib/freebl/mpi/mpmontg.c
@@ -31,17 +31,17 @@
  * under the terms of either the GPL or the LGPL, and not to allow others to
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
-/* $Id: mpmontg.c,v 1.20 2006/08/29 02:41:38 nelson%bolyard.com Exp $ */
+/* $Id: mpmontg.c,v 1.22 2010/05/02 22:36:41 nelson%bolyard.com Exp $ */
 
 /* This file implements moduluar exponentiation using Montgomery's
  * method for modular reduction.  This file implements the method
  * described as "Improvement 1" in the paper "A Cryptogrpahic Library for
  * the Motorola DSP56000" by Stephen R. Dusse' and Burton S. Kaliski Jr.
  * published in "Advances in Cryptology: Proceedings of EUROCRYPT '90"
  * "Lecture Notes in Computer Science" volume 473, 1991, pg 230-244,
  * published by Springer Verlag.
--- a/security/nss/lib/freebl/shvfy.c
+++ b/security/nss/lib/freebl/shvfy.c
@@ -29,17 +29,17 @@
  * under the terms of either the GPL or the LGPL, and not to allow others to
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
-/* $Id: shvfy.c,v 1.11 2008/11/18 19:48:24 rrelyea%redhat.com Exp $ */
+/* $Id: shvfy.c,v 1.13 2010/04/29 00:17:52 rrelyea%redhat.com Exp $ */
 
 #ifdef FREEBL_NO_DEPEND
 #include "stubs.h"
 #endif
 
 #include "shsign.h"
 #include "prlink.h"
 #include "prio.h"
--- a/security/nss/lib/freebl/unix_rand.c
+++ b/security/nss/lib/freebl/unix_rand.c
@@ -935,21 +935,23 @@ void RNG_SystemInfoForRNG(void)
 	RNG_FileForRNG(*cp);
 
 /*
  * Bug 100447: On BSD/OS 4.2 and 4.3, we have problem calling safe_popen
  * in a pthreads environment.  Therefore, we call safe_popen last and on
  * BSD/OS we do not call safe_popen when we succeeded in getting data
  * from /dev/urandom.
  *
- * Bug 174993: LINUX provides /dev/urandom, don't fork netstat
- * if data has been gathered successfully
+ * Bug 174993: On platforms providing /dev/urandom, don't fork netstat
+ * either, if data has been gathered successfully.
  */
 
-#if defined(BSDI) || defined(LINUX)
+#if defined(BSDI) || defined(FREEBSD) || defined(NETBSD) \
+    || defined(OPENBSD) || defined(DARWIN) || defined(LINUX) \
+    || defined(HPUX)
     if (bytes)
         return;
 #endif
 
 #ifdef SOLARIS
 
 /*
  * On Solaris, NSS may be initialized automatically from libldap in
--- a/security/nss/lib/jar/jar.c
+++ b/security/nss/lib/jar/jar.c
@@ -39,16 +39,17 @@
  *
  *  Jarnature.
  *  Routines common to signing and validating.
  *
  */
 
 #include "jar.h"
 #include "jarint.h"
+#include "portreg.h"
 
 static void 
 jar_destroy_list (ZZList *list);
 
 static int 
 jar_find_first_cert(JAR_Signer *signer, int type, JAR_Item **it);
 
 /*
@@ -385,33 +386,34 @@ int JAR_find_next (JAR_Context *ctx, JAR
 	    break;
 
 	case jarTypePhy:
 	    list = jar->phy;
 	    break;
 
 	case jarTypeSF:      /* signer, not jar */
 	    PORT_Assert( signer != NULL );
-	    list = signer->sf;
+	    list = signer ? signer->sf : NULL;
 	    break;
 
 	case jarTypeMF:
 	    list = jar->hashes;
 	    break;
 
 	case jarTypeOwner:
 	    list = jar->signers;
 	    break;
 
 	case jarTypeMeta:
 	    list = jar->metainfo;
 	    break;
 
 	default:
 	    PORT_Assert( 1 != 2 );
+	    list = NULL;
 	    break;
 	}
 	if (list == NULL) {
 	    *it = NULL;
 	    return -1;
 	}
 	/* When looping over lists of lists, advance to the next signer. 
 	   This is done when multiple signers are possible. */
@@ -438,23 +440,27 @@ int JAR_find_next (JAR_Context *ctx, JAR
 		break;
 
 	    case jarTypeSign:
 		ctx->next = ZZ_ListHead (signer->certs);
 		break;
 	    }
 	}
 	PORT_Assert( ctx->next != NULL );
+	if (ctx->next == NULL) {
+	    *it = NULL;
+	    return -1;
+	}
 	while (!ZZ_ListIterDone (list, ctx->next)) {
 	    *it = ctx->next->thing;
 	    ctx->next = ctx->next->next;
 	    if (!*it || (*it)->type != finding)
 		continue;
 	    if (ctx->pattern && *ctx->pattern) {
-		if (PORT_Strcmp ((*it)->pathname, ctx->pattern))
+		if (PORT_RegExpSearch ((*it)->pathname, ctx->pattern))
 		    continue;
 	    }
 	    /* We have a valid match. If this is a jarTypeSign
 	       return the certificate instead.. */
 	    if (ctx->finding == jarTypeSign) {
 		JAR_Item *itt;
 
 		/* just the first one for now */
--- a/security/nss/lib/jar/jarfile.c
+++ b/security/nss/lib/jar/jarfile.c
@@ -742,18 +742,17 @@ jar_listzip(JAR *jar, JAR_FILE fp)
 	    if (phy == NULL) {
 		err = JAR_ERR_MEMORY;
 		goto loser;
 	    }
 
 	    /* We will index any file that comes our way, but when it comes
 	       to actually extraction, compression must be 0 or 8 */
 	    compression = x86ShortToUint32(Local->method);
-	    phy->compression = 
-	    	(compression >= 0 && compression <= 255) ? compression : 222;
+	    phy->compression = (compression <= 255) ? compression : 222;
 		/* XXX 222 is bad magic. */
 
 	    phy->offset = pos + (sizeof *Local) + filename_len + extra_len;
 	    phy->length = x86LongToUint32(Local->size);
 	    phy->uncompressed_length = x86LongToUint32(Local->orglen);
 
 	    dosdate (date, Local->date);
 	    dostime (time, Local->time);
--- a/security/nss/lib/jar/jarver.c
+++ b/security/nss/lib/jar/jarver.c
@@ -74,23 +74,16 @@ static JAR_Digest *jar_get_mf_digest(JAR
 
 static int
 jar_parse_digital_signature(char *raw_manifest, JAR_Signer *signer,
 			    long length, JAR *jar);
 
 static int
 jar_add_cert(JAR *jar, JAR_Signer *signer, int type, CERTCertificate *cert);
 
-static CERTCertificate *
-jar_get_certificate(JAR *jar, long keylen, void *key, int *result);
-
-static char * jar_cert_element(char *name, char *tag, int occ);
-
-static char *jar_choose_nickname(CERTCertificate *cert);
-
 static char *jar_basename(const char *path);
 
 static int
 jar_signal(int status, JAR *jar, const char *metafile, char *pathname);
 
 #ifdef DEBUG
 static int jar_insanity_check(char *data, long length);
 #endif
@@ -384,17 +377,18 @@ jar_parse_any(JAR *jar, int type, JAR_Si
 
 	/* For SF files, this metadata may be the digests
 	       of the MF file, still in the "met" structure. */
 
 	if (type == jarTypeSF) {
 	    if (!PORT_Strcasecmp(line, "MD5-Digest"))
 		sf_md5 = (char *) met->info;
 
-	    if (!PORT_Strcasecmp(line, "SHA1-Digest") || !PORT_Strcasecmp (line, "SHA-Digest"))
+	    if (!PORT_Strcasecmp(line, "SHA1-Digest") || 
+	        !PORT_Strcasecmp(line, "SHA-Digest"))
 		sf_sha1 = (char *) met->info;
 	}
 
 	if (type != jarTypeMF) {
 	    PORT_Free(met->header);
 	    if (type != jarTypeSF) {
 		PORT_Free(met->info);
 	    }
@@ -883,389 +877,21 @@ JAR_verify_digest(JAR *jar, const char *
 		result2 = memcmp (dig->sha1, shindig->sha1, SHA1_LENGTH);
 	    }
 	    return (result1 == 0 && result2 == 0) ? 0 : JAR_ERR_HASH;
 	}
     }
     return JAR_ERR_PNF;
 }
 
-/*
- *  J A R _ c e r t _ a t t r i b u t e
- *
- *  Return the named certificate attribute from the
- *  certificate specified by the given key.
- *
- */
-int PR_CALLBACK
-JAR_cert_attribute(JAR *jar, jarCert attrib, long keylen, void *key,
-		   void **result, unsigned long *length)
-{
-    int status = 0;
-    char *ret = NULL;
-    CERTCertificate *cert;
-    CERTCertDBHandle *certdb;
-    JAR_Digest *dig;
-    SECItem hexme;
-
-    *length = 0;
-
-    if (attrib == 0 || key == 0)
-	return JAR_ERR_GENERAL;
-
-    if (attrib == jarCertJavaHack) {
-	cert = (CERTCertificate *) NULL;
-	certdb = JAR_open_database();
-
-	if (certdb) {
-	    cert = CERT_FindCertByNickname (certdb, key);
-	    if (cert) {
-		*length = cert->certKey.len;
-		*result = (void *) PORT_ZAlloc(*length);
-		if (*result)
-		    PORT_Memcpy(*result, cert->certKey.data, *length);
-		else {
-		    JAR_close_database (certdb);
-		    return JAR_ERR_MEMORY;
-		}
-	    }
-	    JAR_close_database (certdb);
-	}
-	return cert ? 0 : JAR_ERR_GENERAL;
-    }
-
-    if (jar && jar->pkcs7 == 0)
-	return JAR_ERR_GENERAL;
-
-    cert = jar_get_certificate(jar, keylen, key, &status);
-    if (cert == NULL || status < 0)
-	return JAR_ERR_GENERAL;
-
-#define SEP " <br> "
-#define SEPLEN (PORT_Strlen(SEP))
-
-    switch (attrib) {
-    case jarCertCompany:
-	ret = cert->subjectName;
-
-	/* This is pretty ugly looking but only used
-		 here for this one purpose. */
-	if (ret) {
-	    int retlen = 0;
-
-	    char *cer_ou1, *cer_ou2, *cer_ou3;
-	    char *cer_cn, *cer_e, *cer_o, *cer_l;
-
-	    cer_cn  = CERT_GetCommonName (&cert->subject);
-	    cer_e   = CERT_GetCertEmailAddress (&cert->subject);
-	    cer_ou3 = jar_cert_element(ret, "OU=", 3);
-	    cer_ou2 = jar_cert_element(ret, "OU=", 2);
-	    cer_ou1 = jar_cert_element(ret, "OU=", 1);
-	    cer_o   = CERT_GetOrgName (&cert->subject);
-	    cer_l   = CERT_GetCountryName (&cert->subject);
 
-	    if (cer_cn)
-		retlen += SEPLEN + PORT_Strlen(cer_cn);
-	    if (cer_e)
-		retlen += SEPLEN + PORT_Strlen(cer_e);
-	    if (cer_ou1)
-		retlen += SEPLEN + PORT_Strlen(cer_ou1);
-	    if (cer_ou2)
-		retlen += SEPLEN + PORT_Strlen(cer_ou2);
-	    if (cer_ou3)
-		retlen += SEPLEN + PORT_Strlen(cer_ou3);
-	    if (cer_o)
-		retlen += SEPLEN + PORT_Strlen(cer_o);
-	    if (cer_l)
-		retlen += SEPLEN + PORT_Strlen(cer_l);
 
-	    ret = (char *) PORT_ZAlloc(1 + retlen);
-
-	    if (cer_cn)  {
-		PORT_Strcpy(ret, cer_cn);
-		PORT_Strcat(ret, SEP);
-	    }
-	    if (cer_e)	 {
-		PORT_Strcat(ret, cer_e);
-		PORT_Strcat(ret, SEP);
-	    }
-	    if (cer_ou1) {
-		PORT_Strcat(ret, cer_ou1);
-		PORT_Strcat(ret, SEP);
-	    }
-	    if (cer_ou2) {
-		PORT_Strcat(ret, cer_ou2);
-		PORT_Strcat(ret, SEP);
-	    }
-	    if (cer_ou3) {
-		PORT_Strcat(ret, cer_ou3);
-		PORT_Strcat(ret, SEP);
-	    }
-	    if (cer_o)	 {
-		PORT_Strcat(ret, cer_o);
-		PORT_Strcat(ret, SEP);
-	    }
-	    if (cer_l)
-		PORT_Strcat(ret, cer_l);
-
-	    /* return here to avoid unsightly memory leak */
-	    *result = ret;
-	    *length = PORT_Strlen(ret);
-	    CERT_DestroyCertificate(cert);
-	    return 0;
-	}
-	break;
-
-    case jarCertCA:
-	ret = cert->issuerName;
-	if (ret) {
-	    int retlen = 0;
-
-	    char *cer_ou1, *cer_ou2, *cer_ou3;
-	    char *cer_cn, *cer_e, *cer_o, *cer_l;
-
-	    /* This is pretty ugly looking but only used
-		       here for this one purpose. */
-
-	    cer_cn  = CERT_GetCommonName (&cert->issuer);
-	    cer_e   = CERT_GetCertEmailAddress (&cert->issuer);
-	    cer_ou3 = jar_cert_element(ret, "OU=", 3);
-	    cer_ou2 = jar_cert_element(ret, "OU=", 2);
-	    cer_ou1 = jar_cert_element(ret, "OU=", 1);
-	    cer_o   = CERT_GetOrgName (&cert->issuer);
-	    cer_l   = CERT_GetCountryName (&cert->issuer);
-
-	    if (cer_cn)
-		retlen += SEPLEN + PORT_Strlen(cer_cn);
-	    if (cer_e)
-		retlen += SEPLEN + PORT_Strlen(cer_e);
-	    if (cer_ou1)
-		retlen += SEPLEN + PORT_Strlen(cer_ou1);
-	    if (cer_ou2)
-		retlen += SEPLEN + PORT_Strlen(cer_ou2);
-	    if (cer_ou3)
-		retlen += SEPLEN + PORT_Strlen(cer_ou3);
-	    if (cer_o)
-		retlen += SEPLEN + PORT_Strlen(cer_o);
-	    if (cer_l)
-		retlen += SEPLEN + PORT_Strlen(cer_l);
-
-	    ret = (char *) PORT_ZAlloc(1 + retlen);
 
-	    if (cer_cn)  {
-		PORT_Strcpy(ret, cer_cn);
-		PORT_Strcat(ret, SEP);
-	    }
-	    if (cer_e)	 {
-		PORT_Strcat(ret, cer_e);
-		PORT_Strcat(ret, SEP);
-	    }
-	    if (cer_ou1) {
-		PORT_Strcat(ret, cer_ou1);
-		PORT_Strcat(ret, SEP);
-	    }
-	    if (cer_ou2) {
-		PORT_Strcat(ret, cer_ou2);
-		PORT_Strcat(ret, SEP);
-	    }
-	    if (cer_ou3) {
-		PORT_Strcat(ret, cer_ou3);
-		PORT_Strcat(ret, SEP);
-	    }
-	    if (cer_o)	 {
-		PORT_Strcat(ret, cer_o);
-		PORT_Strcat(ret, SEP);
-	    }
-	    if (cer_l)
-		PORT_Strcat(ret, cer_l);
-
-	    /* return here to avoid unsightly memory leak */
-	    *result = ret;
-	    *length = PORT_Strlen(ret);
-	    CERT_DestroyCertificate(cert);
-	    return 0;
-	}
-	break;
-
-    case jarCertSerial:
-	ret = CERT_Hexify (&cert->serialNumber, 1);
-	break;
-
-    case jarCertExpires:
-	ret = DER_UTCDayToAscii (&cert->validity.notAfter);
-	break;
-
-    case jarCertNickname:
-	ret = jar_choose_nickname(cert);
-	break;
-
-    case jarCertFinger:
-	dig = JAR_calculate_digest((char *) cert->derCert.data,
-				   cert->derCert.len);
-	if (dig) {
-	    hexme.len = sizeof (dig->md5);
-	    hexme.data = dig->md5;
-	    ret = CERT_Hexify (&hexme, 1);
-	}
-	break;
-
-    default:
-	CERT_DestroyCertificate(cert);
-	return JAR_ERR_GENERAL;
-    }
-
-    *result = ret ? PORT_Strdup(ret) : NULL;
-    *length = ret ? PORT_Strlen(ret) : 0;
-    CERT_DestroyCertificate(cert);
-    return 0;
-}
-
-/*
- *  j a r  _ c e r t _ e l e m e n t
- *
- *  Retrieve an element from an x400ish ascii
- *  designator, in a hackish sort of way. The right
- *  thing would probably be to sort AVATags.
- *
- */
-static char *
-jar_cert_element(char *name, char *tag, int occ)
-{
-    if (name && tag) {
-	char *s;
-	int found = 0;
-	while (occ--) {
-	    if (PORT_Strstr(name, tag)) {
-		name = PORT_Strstr(name, tag) + PORT_Strlen (tag);
-		found = 1;
-	    } else {
-		name = PORT_Strstr(name, "=");
-		if (name == NULL) return NULL;
-		found = 0;
-	    }
-	}
-	if (!found)
-	    return NULL;
-
-	/* must mangle only the copy */
-	name = PORT_Strdup(name);
-
-	/* advance to next equal */
-	for (s = name; *s && *s != '='; s++)
-	    /* yip */ ;
-
-	/* back up to previous comma */
-	while (s > name && *s != ',')
-	    s--;
 
-	/* zap the whitespace and return */
-	*s = 0;
-    }
-    return name;
-}
 
-/*
- *  j a r _ c h o o s e _ n i c k n a m e
- *
- *  Attempt to determine a suitable nickname for
- *  a certificate with a computer-generated "tmpcertxxx"
- *  nickname. It needs to be something a user can
- *  understand, so try a few things.
- *
- */
-static char *
-jar_choose_nickname(CERTCertificate *cert)
-{
-    char *cert_cn;
-    char *cert_o;
-    char *cert_cn_o;
-    int cn_o_length;
-
-    /* is the existing name ok */
-    if (cert->nickname && PORT_Strncmp(cert->nickname, "tmpcert", 7))
-	return PORT_Strdup(cert->nickname);
-
-    /* Try the CN */
-    cert_cn = CERT_GetCommonName(&cert->subject);
-    if (cert_cn) {
-	CERTCertificate *cert1;
-	/* check for duplicate nickname */
-	cert1 = CERT_FindCertByNickname(CERT_GetDefaultCertDB(), cert_cn);
-	if (cert1 == NULL)
-	    return cert_cn;
-        CERT_DestroyCertificate(cert1); cert1 = NULL;
-
-	/* Try the CN plus O */
-	cert_o = CERT_GetOrgName (&cert->subject);
-	/* XXX: Get Yer Magic Numbers here! */
-	cn_o_length = PORT_Strlen(cert_cn) + 3 + PORT_Strlen (cert_o) + 20;
-	cert_cn_o = (char*)PORT_ZAlloc(cn_o_length);
-	PR_snprintf(cert_cn_o, cn_o_length, "%s's %s Certificate",
-		    cert_cn, cert_o);
-
-	cert1 = CERT_FindCertByNickname(CERT_GetDefaultCertDB(), cert_cn_o);
-	if (cert1 == NULL) {
-	    PORT_Free(cert_cn_o);
-	    return cert_cn;
-	}
-	CERT_DestroyCertificate(cert1); cert1 = NULL;
-	PORT_Free(cert_cn_o);
-    }
-
-    /* If all that failed, use the ugly nickname */
-    return cert->nickname ? PORT_Strdup(cert->nickname) : NULL;
-}
-
-/*
- *  J A R _ s t a s h _ c e r t
- *
- *  Stash the certificate pointed to by this
- *  fingerprint, in persistent storage somewhere.
- *
- */
-int PR_CALLBACK
-JAR_stash_cert(JAR *jar, long keylen, void *key)
-{
-    int result = 0;
-    char *nickname;
-    CERTCertTrust trust;
-    CERTCertDBHandle *certdb;
-    CERTCertificate *cert, *newcert;
-
-    cert = jar_get_certificate(jar, keylen, key, &result);
-    if (cert == NULL)
-	return JAR_ERR_GENERAL;
-
-    if ((certdb = JAR_open_database()) == NULL)
-	return JAR_ERR_GENERAL;
-
-    /* Attempt to give a name to the newish certificate */
-    nickname = jar_choose_nickname(cert);
-    newcert = CERT_FindCertByNickname(certdb, nickname);
-    if (newcert && newcert->isperm) {
-	/* already in permanent database */
-	CERT_DestroyCertificate(newcert);
-	JAR_close_database (certdb);
-	return 0;
-    }
-    if (newcert) {
-	CERT_DestroyCertificate(cert);
-	cert = newcert;
-    }
-    if (nickname != NULL) {
-	PORT_Memset((void *) &trust, 0, sizeof(trust));
-	if (CERT_AddTempCertToPerm (cert, nickname, &trust) != SECSuccess) {
-	    /* XXX might want to call PORT_GetError here */
-	    result = JAR_ERR_GENERAL;
-	}
-    }
-    CERT_DestroyCertificate(cert);
-    JAR_close_database(certdb);
-    return result;
-}
 
 /*
  *  J A R _ f e t c h _ c e r t
  *
  *  Given an opaque identifier of a certificate,
  *  return the full certificate.
  *
  * The new function, which retrieves by key.
@@ -1517,64 +1143,16 @@ JAR_open_database(void)
  *
  */
 int 
 JAR_close_database(CERTCertDBHandle *certdb)
 {
     return 0;
 }
 
-/*
- *  j a r _ g e t _ c e r t i f i c a t e
- *
- *  Return a new reference to the certificate indicated
- *  by a given fingerprint, or NULL if not found.
- *  Error code is returned in result.
- *  Caller must destroy this reference, if it is non-NULL!
- */
-static CERTCertificate *
-jar_get_certificate(JAR *jar, long keylen, void *key, int *result)
-{
-    int found = 0;
-    JAR_Item *it;
-    JAR_Cert *fing = NULL;
-    JAR_Context *ctx;
-
-    if (jar == NULL) {
-	CERTCertificate * cert = JAR_fetch_cert(keylen, key);
-	*result = (cert == NULL) ? JAR_ERR_GENERAL : 0;
-	return cert;
-    }
-
-    ctx = JAR_find (jar, NULL, jarTypeSign);
-    while (JAR_find_next (ctx, &it) >= 0) {
-	fing = (JAR_Cert *) it->data;
-	if (keylen != fing->length)
-	    continue;
-
-	PORT_Assert( keylen < 0xFFFF );
-	if (!PORT_Memcmp(fing->key, key, keylen)) {
-	    found = 1;
-	    break;
-	}
-    }
-
-    JAR_find_end (ctx);
-    if (found == 0) {
-	*result = JAR_ERR_GENERAL;
-	return NULL;
-    }
-
-    PORT_Assert(fing != NULL);
-    *result = 0;
-    /* XXX: is this a new reference or not?  
-     * If not, then this needs to be changed to call CERT_DupCertificate! 
-     */
-    return fing->cert;
-}
 
 /*
  *  j a r _ s i g n a l
  *
  *  Nonfatal errors come here to callback Java.
  *
  */
 static int
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
--- a/security/nss/lib/libpkix/include/pkix_errorstrings.h
+++ b/security/nss/lib/libpkix/include/pkix_errorstrings.h
@@ -108,17 +108,17 @@ PKIX_ERRORENTRY(BYTEARRAYTOHEXSTRINGFAIL
 PKIX_ERRORENTRY(BYTEARRAYTOSTRINGFAILED,PKIX_PL_ByteArray_ToString failed,0),
 PKIX_ERRORENTRY(CACHECERTADDFAILED,pkix_CacheCert_Add failed,0),
 PKIX_ERRORENTRY(CACHECERTCHAINADDFAILED,pkix_CacheCertChain_Add failed,0),
 PKIX_ERRORENTRY(CACHECERTCHAINLOOKUPFAILED,pkix_CacheCertChain_Lookup failed,0),
 PKIX_ERRORENTRY(CACHECERTCHAINREMOVEFAILED,pkix_CacheCertChain_Remove failed,0),
 PKIX_ERRORENTRY(CACHECRLENTRYADDFAILED,pkix_CacheCrlEntry_Add failed,0),
 PKIX_ERRORENTRY(CACHECRLENTRYLOOKUPFAILED,pkix_CacheCrlEntry_Lookup failed,0),
 PKIX_ERRORENTRY(CALLOCFAILED,PKIX_PL_Calloc failed,0),
-PKIX_ERRORENTRY(CANNOTAQUIRECRLDER,PKIX_PL_CRL_AquireDerCrl failed,0),
+PKIX_ERRORENTRY(CANNOTAQUIRECRLDER,Failed to get DER CRL,0),
 PKIX_ERRORENTRY(CANNOTCONVERTCERTUSAGETOPKIXKEYANDEKUSAGES, Fail to convert certificate usage to pkix KU and EKU,0),
 PKIX_ERRORENTRY(CANNOTOPENCOLLECTIONCERTSTORECONTEXTDIRECTORY,Cannot open CollectionCertStoreContext directory,0),
 PKIX_ERRORENTRY(CANTCREATESTRING,Cannot create PKIX_PL_String,0),
 PKIX_ERRORENTRY(CANTDECODEBINDRESPONSEFROMSERVER,Cannot decode BIND response from server,SEC_ERROR_BAD_LDAP_RESPONSE),
 PKIX_ERRORENTRY(CANTDECODESEARCHRESPONSEFROMSERVER,Cannot decode SEARCH response from server,SEC_ERROR_BAD_LDAP_RESPONSE),
 PKIX_ERRORENTRY(CANTENABLEREVOCATIONWITHOUTCERTSTORE,Cannot enable Revocation without CertStore,SEC_ERROR_INVALID_ARGS),
 PKIX_ERRORENTRY(CANTLOADLIBSMIME,Cannot load smime3 library,0),
 PKIX_ERRORENTRY(CANTREREGISTERSYSTEMTYPE,Cannot reregister system type,0),
@@ -308,16 +308,17 @@ PKIX_ERRORENTRY(COMCERTSELPARAMSSETBASIC
 PKIX_ERRORENTRY(COMCERTSELPARAMSSETCERTIFICATEFAILED,PKIX_ComCertSelParams_SetCertificate failed,0),
 PKIX_ERRORENTRY(COMCERTSELPARAMSSETCERTIFICATEVALIDFAILED,PKIX_ComCertSelParams_SetCertificateValid failed,0),
 PKIX_ERRORENTRY(COMCERTSELPARAMSSETEXTKEYUSAGEFAILED,PKIX_ComCertSelParams_SetExtendedKeyUsage failed,0),
 PKIX_ERRORENTRY(COMCERTSELPARAMSSETKEYUSAGEFAILED,PKIX_ComCertSelParams_SetKeyUsage failed,0),
 PKIX_ERRORENTRY(COMCERTSELPARAMSSETLEAFCERTFLAGFAILED,PKIX_ComCertSelParams_SetLeafCertFlag failed,0),
 PKIX_ERRORENTRY(COMCERTSELPARAMSSETNISTPOLICYENABLEDFAILED,PKIX_ComCertSelParams_SetNISTPolicyEnabled failed,0),
 PKIX_ERRORENTRY(COMCERTSELPARAMSSETPATHTONAMESFAILED,PKIX_ComCertSelParams_SetPathToNames failed,0),
 PKIX_ERRORENTRY(COMCERTSELPARAMSSETSUBJECTFAILED,PKIX_ComCertSelParams_SetSubject failed,0),
+PKIX_ERRORENTRY(COMCERTSELPARAMSSETSUBJKEYIDENTIFIERFAILED,PKIX_ComCertSelParams_SetSubjKeyIdentifier failed,0),
 PKIX_ERRORENTRY(COMCRLSELPARAMSADDISSUERNAMEFAILED,PKIX_ComCRLSelParams_AddIssuerName failed,0),
 PKIX_ERRORENTRY(COMCRLSELPARAMSCREATEFAILED,PKIX_ComCRLSelParams_Create failed,0),
 PKIX_ERRORENTRY(COMCRLSELPARAMSEQUALSFAILED,pkix_ComCRLSelParams_Equals failed,0),
 PKIX_ERRORENTRY(COMCRLSELPARAMSGETDATEANDTIMEFAILED,PKIX_ComCRLSelParams_GetDateAndTime failed,0),
 PKIX_ERRORENTRY(COMCRLSELPARAMSGETISSUERNAMESFAILED,PKIX_ComCRLSelParams_GetIssuerNames failed,0),
 PKIX_ERRORENTRY(COMCRLSELPARAMSGETMAXCRLNUMBERFAILED,PKIX_ComCRLSelParams_GetMaxCRLNumber failed,0),
 PKIX_ERRORENTRY(COMCRLSELPARAMSGETMINCRLNUMBERFAILED,PKIX_ComCRLSelParams_GetMinCRLNumber failed,0),
 PKIX_ERRORENTRY(COMCRLSELPARAMSGETNISTPOLICYENABLEDFAILED,PKIX_ComCRLSelParams_GetNISTPolicyEnabled failed,0),
@@ -540,17 +541,17 @@ PKIX_ERRORENTRY(FIRSTOBJECTNOTPROCESSING
 PKIX_ERRORENTRY(FIRSTOBJECTNOTPUBLICKEY,FirstObject is not a PublicKey,0),
 PKIX_ERRORENTRY(FIRSTOBJECTNOTRESOURCELIMITS,FirstObject is not a ResourceLimits,0),
 PKIX_ERRORENTRY(FIRSTOBJECTNOTSTRING,FirstObject is not a String,0),
 PKIX_ERRORENTRY(FIRSTOBJECTNOTTRUSTANCHOR,FirstObject is not a TrustAnchor,0),
 PKIX_ERRORENTRY(FIRSTOBJECTNOTVALIDATEPARAMS,FirstObject is not a ValidateParams,0),
 PKIX_ERRORENTRY(FIRSTOBJECTNOTVALIDATERESULT,FirstObject is not a ValidateResult,0),
 PKIX_ERRORENTRY(FIRSTOBJECTNOTVERIFYNODE,FirstObject is not a VerifyNode,0),
 PKIX_ERRORENTRY(FIRSTPUBKEYTYPENULLKEY,firstPubKeyType is nullKey,0),
-PKIX_ERRORENTRY(FUNCTIONMUSTNOTBEUSED,Function MUST not be used,SEC_ERROR_INVALID_ARGS),
+PKIX_ERRORENTRY(FUNCTIONMUSTNOTBEUSED,Function MUST not be used,SEC_ERROR_LIBPKIX_INTERNAL),
 PKIX_ERRORENTRY(FORWARDBUILDERSTATEDUMPSTATEFAILED,pkix_ForwardBuilderState_DumpState failed,0),
 PKIX_ERRORENTRY(FORWARDBUILDERSTATEISIOPENDINGFAILED,pkix_ForwardBuilderState_IsIOPending failed,0),
 PKIX_ERRORENTRY(FORWARDBUILDSTATECREATEFAILED,pkix_ForwardBuildState_Create failed,0),
 PKIX_ERRORENTRY(FREEFAILED,PKIX_PL_Free failed,0),
 PKIX_ERRORENTRY(GENERALNAMECREATEFAILED,pkix_pl_GeneralName_Create failed,0),
 PKIX_ERRORENTRY(GENERALNAMEGETNSSGENERALNAMEFAILED,pkix_pl_GeneralName_GetNssGeneralName failed,0),
 PKIX_ERRORENTRY(GENERALNAMESTRINGMISSINGDOUBLESLASH,GeneralName string missing double slash,SEC_ERROR_BAD_INFO_ACCESS_LOCATION),
 PKIX_ERRORENTRY(GENERALNAMESTRINGMISSINGLOCATIONTYPE,GeneralName string missing location type,SEC_ERROR_BAD_INFO_ACCESS_LOCATION),
@@ -900,16 +901,17 @@ PKIX_ERRORENTRY(POLICYNODEISCRITICALFAIL
 PKIX_ERRORENTRY(POLICYNODEPRUNEFAILED,pkix_PolicyNode_Prune failed,0),
 PKIX_ERRORENTRY(POLICYTREETOOIDSFAILED,Failed to convert policy tree to oid,0),
 PKIX_ERRORENTRY(PORTARENAALLOCFAILED,PORT Arena Allocation failed, 0),
 PKIX_ERRORENTRY(PORTUCS2UTF8CONVERSIONFAILED,PORT_UCS2_UTF8Conversion failed.,SEC_ERROR_INVALID_ARGS),
 PKIX_ERRORENTRY(PRACCEPTFAILED,PR_Accept failed,0),
 PKIX_ERRORENTRY(PRBINDFAILED,PR_Bind failed,0),
 PKIX_ERRORENTRY(PRCONNECTCONTINUEFAILED,PR_ConnectContinue failed,0),
 PKIX_ERRORENTRY(PRCONNECTFAILED,PR_Connect failed,0),
+PKIX_ERRORENTRY(PRECONDITIONFAILED,Function precondition failed,SEC_ERROR_LIBPKIX_INTERNAL),
 PKIX_ERRORENTRY(PRENUMERATEHOSTENTFAILED,PR_EnumerateHostEnt failed.,0),
 PKIX_ERRORENTRY(PRGETHOSTBYNAMEREJECTSHOSTNAMEARGUMENT,PR_GetHostByName rejects hostname argument.,0),
 PKIX_ERRORENTRY(PRIMHASHTABLEADDFAILED,pkix_pl_PrimHashTable_Add failed,0),
 PKIX_ERRORENTRY(PRIMHASHTABLECREATEFAILED,pkix_pl_PrimHashTable_Create failed,0),
 PKIX_ERRORENTRY(PRIMHASHTABLEDESTROYFAILED,pkix_pl_PrimHashTable_Destroy failed,0),
 PKIX_ERRORENTRY(PRIMHASHTABLEGETBUCKETSIZEFAILED,pkix_pl_PrimHashTable_GetBucketSize failed,0),
 PKIX_ERRORENTRY(PRIMHASHTABLELOOKUPFAILED,pkix_pl_PrimHashTable_Lookup failed,0),
 PKIX_ERRORENTRY(PRIMHASHTABLEREMOVEFAILED,pkix_pl_PrimHashTable_Remove failed,0),
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
--- a/security/nss/lib/libpkix/pkix/certsel/pkix_certselector.c
+++ b/security/nss/lib/libpkix/pkix/certsel/pkix_certselector.c
@@ -819,18 +819,19 @@ cleanup:
 }
 
 /*
  * FUNCTION: pkix_CertSelector_Match_SubjKeyId
  * DESCRIPTION:
  *
  *  Determines whether the bytes at subjKeyId in "params" matches with the
  *  Subject Key Identifier pointed to by "cert". If the subjKeyId in params is
- *  set to NULL, no checking is done and the Cert is considered a match. If
- *  the Cert does not match, an Error pointer is returned.
+ *  set to NULL or the Cert doesn't have a Subject Key Identifier, no checking
+ *  is done and the Cert is considered a match. If the Cert does not match, an
+ *  Error pointer is returned.
  *
  * PARAMETERS:
  *  "params"
  *      Address of ComCertSelParams whose subjKeyId field is used.
  *      Must be non-NULL.
  *  "cert"
  *      Address of Cert that is to be matched. Must be non-NULL.
  *  "pResult"
@@ -865,28 +866,27 @@ pkix_CertSelector_Match_SubjKeyId(
 
         if (selSubjKeyId != NULL) {
 
                 PKIX_CHECK(PKIX_PL_Cert_GetSubjectKeyIdentifier
                     (cert, &certSubjKeyId, plContext),
                     PKIX_CERTGETSUBJECTKEYIDENTIFIERFAILED);
 
                 if (certSubjKeyId == NULL) {
-                    *pResult = PKIX_FALSE;
-                    PKIX_ERROR(PKIX_CERTSELECTORMATCHSUBJKEYIDFAILED);
+                    goto cleanup;
                 }
 
                 PKIX_CHECK(PKIX_PL_Object_Equals
                            ((PKIX_PL_Object *)selSubjKeyId,
                             (PKIX_PL_Object *)certSubjKeyId,
                             &equals,
                             plContext),
                            PKIX_OBJECTEQUALSFAILED);
                 
-                if (equals != PKIX_TRUE) {
+                if (equals == PKIX_FALSE) {
                     *pResult = PKIX_FALSE;
                     PKIX_ERROR(PKIX_CERTSELECTORMATCHSUBJKEYIDFAILED);
                 }
         }
 
 cleanup:
 
         PKIX_DECREF(selSubjKeyId);
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
--- a/security/nss/lib/libpkix/pkix/checker/pkix_policychecker.c
+++ b/security/nss/lib/libpkix/pkix/checker/pkix_policychecker.c
@@ -420,16 +420,17 @@ pkix_PolicyCheckerState_Create(
         PKIX_Boolean initialAnyPolicyInhibit,
         PKIX_UInt32 numCerts,
         PKIX_PolicyCheckerState **pCheckerState,
         void *plContext)
 {
         PKIX_PolicyCheckerState *checkerState = NULL;
         PKIX_PolicyNode *policyNode = NULL;
         PKIX_List *anyPolicyList = NULL;
+        PKIX_Boolean initialPoliciesIsEmpty = PKIX_FALSE;
 
         PKIX_ENTER(CERTPOLICYCHECKERSTATE, "pkix_PolicyCheckerState_Create");
         PKIX_NULLCHECK_TWO(initialPolicies, pCheckerState);
 
         PKIX_CHECK(PKIX_PL_Object_Alloc
                 (PKIX_CERTPOLICYCHECKERSTATE_TYPE,
                 sizeof (PKIX_PolicyCheckerState),
                 (PKIX_PL_Object **)&checkerState,
@@ -469,22 +470,31 @@ pkix_PolicyCheckerState_Create(
                 PKIX_OIDCREATEFAILED);
 
         /* Create an initial policy set from argument supplied */
         PKIX_INCREF(initialPolicies);
         checkerState->userInitialPolicySet = initialPolicies;
         PKIX_INCREF(initialPolicies);
         checkerState->mappedUserInitialPolicySet = initialPolicies;
 
-        PKIX_CHECK(pkix_List_Contains
+        PKIX_CHECK(PKIX_List_IsEmpty
                 (initialPolicies,
-                (PKIX_PL_Object *)(checkerState->anyPolicyOID),
-                &(checkerState->initialIsAnyPolicy),
+                &initialPoliciesIsEmpty,
                 plContext),
-                PKIX_LISTCONTAINSFAILED);
+                PKIX_LISTISEMPTYFAILED);
+        if (initialPoliciesIsEmpty) {
+                checkerState->initialIsAnyPolicy = PKIX_TRUE;
+        } else {
+                PKIX_CHECK(pkix_List_Contains
+                        (initialPolicies,
+                        (PKIX_PL_Object *)(checkerState->anyPolicyOID),
+                        &(checkerState->initialIsAnyPolicy),
+                        plContext),
+                        PKIX_LISTCONTAINSFAILED);
+        }
 
         checkerState->policyQualifiersRejected =
                 policyQualifiersRejected;
         checkerState->initialExplicitPolicy = initialExplicitPolicy;
         checkerState->explicitPolicy =
                 (initialExplicitPolicy? 0: numCerts + 1);
         checkerState->initialAnyPolicyInhibit = initialAnyPolicyInhibit;
         checkerState->inhibitAnyPolicy =
@@ -867,17 +877,17 @@ static PKIX_Error *
 pkix_PolicyChecker_MakeMutableCopy(
         PKIX_List *list,
         PKIX_List **pMutableCopy,
         void *plContext)
 {
         PKIX_List *newList = NULL;
         PKIX_UInt32 listLen = 0;
         PKIX_UInt32 listIx = 0;
-        PKIX_PL_Object *object;
+        PKIX_PL_Object *object = NULL;
 
         PKIX_ENTER(CERTCHAINCHECKER, "pkix_PolicyChecker_MakeMutableCopy");
         PKIX_NULLCHECK_TWO(list, pMutableCopy);
 
         PKIX_CHECK(PKIX_List_Create(&newList, plContext),
                 PKIX_LISTCREATEFAILED);
 
         PKIX_CHECK(PKIX_List_GetLength(list, &listLen, plContext),
@@ -1661,16 +1671,24 @@ pkix_PolicyChecker_CalculateIntersection
         PKIX_PolicyNode *child = NULL;
         PKIX_List *children = NULL; /* PolicyNodes */
         PKIX_List *policyQualifiers = NULL;
 
         PKIX_ENTER
                 (CERTCHAINCHECKER,
                 "pkix_PolicyChecker_CalculateIntersection");
 
+        /*
+         * We call this function if the valid_policy_tree is not NULL and
+         * the user-initial-policy-set is not any-policy.
+         */
+        if (!state->validPolicyTree || state->initialIsAnyPolicy) {
+                PKIX_ERROR(PKIX_PRECONDITIONFAILED);
+        }
+
         PKIX_NULLCHECK_FOUR(currentNode, state, nominees, pShouldBePruned);
 
         PKIX_CHECK(PKIX_PolicyNode_GetValidPolicy
                 (currentNode, &currentPolicy, plContext),
                 PKIX_POLICYNODEGETVALIDPOLICYFAILED);
 
         PKIX_NULLCHECK_TWO(state->anyPolicyOID, currentPolicy);
 
@@ -1910,17 +1928,20 @@ pkix_PolicyChecker_PolicyMapProcessing(
         PKIX_UInt32 polX = 0;
         PKIX_PL_OID *policyOID = NULL;
         PKIX_List *newMappedPolicies = NULL;  /* OIDs */
         PKIX_List *subjectDomainPolicies = NULL;  /* OIDs */
 
         PKIX_ENTER
                 (CERTCHAINCHECKER,
                 "pkix_PolicyChecker_PolicyMapProcessing");
-        PKIX_NULLCHECK_THREE(policyMaps, state, state->userInitialPolicySet);
+        PKIX_NULLCHECK_THREE
+                (policyMaps,
+                state,
+                state->mappedUserInitialPolicySet);
 
         /*
          * For each policy in mappedUserInitialPolicySet, if it is not mapped,
          * append it to new policySet; if it is mapped, append its
          * subjectDomainPolicies to new policySet. When done, this new
          * policySet will replace mappedUserInitialPolicySet.
          */
         PKIX_CHECK(PKIX_List_Create
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
--- a/security/nss/lib/libpkix/pkix/crlsel/pkix_comcrlselparams.c
+++ b/security/nss/lib/libpkix/pkix/crlsel/pkix_comcrlselparams.c
@@ -381,17 +381,17 @@ cleanup:
  */
 static PKIX_Error *
 pkix_ComCRLSelParams_Duplicate(
         PKIX_PL_Object *object,
         PKIX_PL_Object **pNewObject,
         void *plContext)
 {
         PKIX_ComCRLSelParams *old;
-        PKIX_ComCRLSelParams *new;
+        PKIX_ComCRLSelParams *new = NULL;
 
         PKIX_ENTER(COMCRLSELPARAMS, "pkix_ComCRLSelParams_Duplicate");
         PKIX_NULLCHECK_TWO(object, pNewObject);
 
         PKIX_CHECK(pkix_CheckType(object, PKIX_COMCRLSELPARAMS_TYPE, plContext),
                     PKIX_OBJECTNOTCOMCRLSELPARAMS);
 
         old = (PKIX_ComCRLSelParams *)object;
old mode 100644
new mode 100755
old mode 100644
new mode 100755
--- a/security/nss/lib/libpkix/pkix/crlsel/pkix_crlselector.c
+++ b/security/nss/lib/libpkix/pkix/crlsel/pkix_crlselector.c
@@ -326,17 +326,17 @@ cleanup:
  */
 static PKIX_Error *
 pkix_CRLSelector_Duplicate(
         PKIX_PL_Object *object,
         PKIX_PL_Object **pNewObject,
         void *plContext)
 {
         PKIX_CRLSelector *old;
-        PKIX_CRLSelector *new;
+        PKIX_CRLSelector *new = NULL;
 
         PKIX_ENTER(CRLSELECTOR, "pkix_CRLSelector_Duplicate");
         PKIX_NULLCHECK_TWO(object, pNewObject);
 
         PKIX_CHECK(pkix_CheckType
                     (object, PKIX_CRLSELECTOR_TYPE, plContext),
                     PKIX_OBJECTNOTCRLSELECTOR);
 
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
--- a/security/nss/lib/libpkix/pkix/top/pkix_build.c
+++ b/security/nss/lib/libpkix/pkix/top/pkix_build.c
@@ -1457,36 +1457,47 @@ cleanup:
 static PKIX_Error *
 pkix_Build_BuildSelectorAndParams(
         PKIX_ForwardBuilderState *state,
         void *plContext)
 {
         PKIX_ComCertSelParams *certSelParams = NULL;
         PKIX_CertSelector *certSel = NULL;
         PKIX_PL_X500Name *currentIssuer = NULL;
+        PKIX_PL_ByteArray *authKeyId = NULL;
         PKIX_PL_Date *testDate = NULL;
         PKIX_CertSelector *callerCertSelector = NULL;
         PKIX_ComCertSelParams *callerComCertSelParams = NULL;
         PKIX_UInt32 reqKu = 0;
         PKIX_List   *reqEkuOids = NULL;
 
         PKIX_ENTER(BUILD, "pkix_Build_BuildSelectorAndParams");
         PKIX_NULLCHECK_THREE(state, state->prevCert, state->traversedSubjNames);
 
         PKIX_CHECK(PKIX_PL_Cert_GetIssuer
                 (state->prevCert, &currentIssuer, plContext),
                 PKIX_CERTGETISSUERFAILED);
 
+        PKIX_CHECK(PKIX_PL_Cert_GetAuthorityKeyIdentifier
+                (state->prevCert, &authKeyId, plContext),
+                PKIX_CERTGETAUTHORITYKEYIDENTIFIERFAILED);
+
         PKIX_CHECK(PKIX_ComCertSelParams_Create(&certSelParams, plContext),
                 PKIX_COMCERTSELPARAMSCREATEFAILED);
 
         PKIX_CHECK(PKIX_ComCertSelParams_SetSubject
                 (certSelParams, currentIssuer, plContext),
                 PKIX_COMCERTSELPARAMSSETSUBJECTFAILED);
 
+        if (authKeyId != NULL) {
+            PKIX_CHECK(PKIX_ComCertSelParams_SetSubjKeyIdentifier
+                    (certSelParams, authKeyId, plContext),
+                    PKIX_COMCERTSELPARAMSSETSUBJKEYIDENTIFIERFAILED);
+        }
+
         PKIX_INCREF(state->buildConstants.testDate);
         testDate = state->buildConstants.testDate;
 
         PKIX_CHECK(PKIX_ComCertSelParams_SetCertificateValid
                 (certSelParams, testDate, plContext),
                 PKIX_COMCERTSELPARAMSSETCERTIFICATEVALIDFAILED);
 
         PKIX_CHECK(PKIX_ComCertSelParams_SetBasicConstraints
@@ -1543,16 +1554,17 @@ pkix_Build_BuildSelectorAndParams(
                 PKIX_LISTCREATEFAILED);
 
         state->certStoreIndex = 0;
 
 cleanup:
         PKIX_DECREF(certSelParams);
         PKIX_DECREF(certSel);
         PKIX_DECREF(currentIssuer);
+        PKIX_DECREF(authKeyId);
         PKIX_DECREF(testDate);
         PKIX_DECREF(reqEkuOids);
         PKIX_DECREF(callerComCertSelParams);
         PKIX_DECREF(callerCertSelector);
 
         PKIX_RETURN(BUILD);
 }
 
@@ -2217,19 +2229,19 @@ pkix_BuildForwardDepthFirstSearch(
                     if (pkixErrorClass == PKIX_FATAL_ERROR) {
                         goto fatal;
                     }
                     PKIX_DECREF(finalError);
                     finalError = pkixErrorResult;
                     pkixErrorResult = NULL;
                     if (state->verifyNode != NULL) {
                         /* state->verifyNode is the object that contains a list
-                         * of verifyNodes. verifyNodes contains cert chain build
-                         * failures that occured on this level of chian building.
-                         * Here, creating new verify node
+                         * of verifyNodes. verifyNodes contains cert chain
+                         * build failures that occurred on this level of chain
+                         * building.  Here, creating new verify node
                          * to log the failure and adding it to the list. */
                         PKIX_CHECK_FATAL(pkix_VerifyNode_Create
                                          (state->prevCert,
                                           0, NULL,
                                           &verifyNode,
                                           plContext),
                                          PKIX_VERIFYNODECREATEFAILED);
                         PKIX_CHECK_FATAL(pkix_VerifyNode_SetError
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
--- a/security/nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_cert.c
+++ b/security/nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_cert.c
@@ -3177,19 +3177,20 @@ PKIX_PL_Cert_CheckNameConstraints(
         if (nameConstraints != NULL) {
 
                 arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
                 if (arena == NULL) {
                         PKIX_ERROR(PKIX_OUTOFMEMORY);
                 }
 
                 /* This NSS call returns both Subject and  Subject Alt Names */
-                PKIX_CERT_DEBUG("\t\tCalling CERT_GetCertificateNames\n");
-                nssSubjectNames = CERT_GetCertificateNames
-                        (cert->nssCert, arena);
+                PKIX_CERT_DEBUG
+                    ("\t\tCalling CERT_GetConstrainedCertificateNames\n");
+                nssSubjectNames = CERT_GetConstrainedCertificateNames
+                        (cert->nssCert, arena, PR_TRUE);
 
                 PKIX_CHECK(pkix_pl_CertNameConstraints_CheckNameSpaceNssNames
                         (nssSubjectNames,
                         nameConstraints,
                         &checkPass,
                         plContext),
                         PKIX_CERTNAMECONSTRAINTSCHECKNAMESPACENSSNAMESFAILED);
 
--- a/security/nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_crl.c
+++ b/security/nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_crl.c
@@ -572,21 +572,23 @@ pkix_pl_CRL_Hashcode(
                     PKIX_OBJECTNOTCRL);
 
         crl = (PKIX_PL_CRL *)object;
         if (crl->adoptedDerCrl) {
             crlDer = crl->adoptedDerCrl;
         } else if (crl->nssSignedCrl && crl->nssSignedCrl->derCrl) { 
             crlDer = crl->nssSignedCrl->derCrl;
         }
+        if (!crlDer || !crlDer->data) {
+            PKIX_ERROR(PKIX_CANNOTAQUIRECRLDER);
+        }
 
-        if (crlDer->data)
-            PKIX_CHECK(pkix_hash(crlDer->data, crlDer->len,
-                                 &certHash, plContext),
-                       PKIX_ERRORINHASH);
+        PKIX_CHECK(pkix_hash(crlDer->data, crlDer->len,
+                             &certHash, plContext),
+                   PKIX_ERRORINHASH);
 
         *pHashcode = certHash;
 
 cleanup:
 
         PKIX_RETURN(CRL);
 }
 
--- a/security/nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_nameconstraints.c
+++ b/security/nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_nameconstraints.c
@@ -272,17 +272,17 @@ cleanup:
 
         PKIX_RETURN(CERTNAMECONSTRAINTS);
 }
 
 /*
  * FUNCTION: pkix_pl_CertNameConstraints_CheckNameSpaceNssNames
  * DESCRIPTION:
  *
- *  This function checks if CERTGeneral names in "nssSubjectNames" complies
+ *  This function checks if CERTGeneralNames in "nssSubjectNames" comply
  *  with the permitted and excluded names in "nameConstraints". It returns
  *  PKIX_TRUE in "pCheckPass", if the Names satify the name space of the
  *  permitted list and if the Names are not in the excluded list. Otherwise,
  *  it returns PKIX_FALSE.
  *
  * PARAMETERS
  *  "nssSubjectNames"
  *      List of CERTGeneralName that nameConstraints verification is based on.
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
--- a/security/nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_mutex.c
+++ b/security/nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_mutex.c
@@ -130,17 +130,17 @@ PKIX_PL_Mutex_Create(
                     sizeof (PKIX_PL_Mutex),
                     (PKIX_PL_Object **)&mutex,
                     plContext),
                     PKIX_COULDNOTCREATELOCKOBJECT);
 
         PKIX_MUTEX_DEBUG("\tCalling PR_NewLock).\n");
         mutex->lock = PR_NewLock();
 
-        /* If an error occured in NSPR, report it here */
+        /* If an error occurred in NSPR, report it here */
         if (mutex->lock == NULL) {
                 PKIX_DECREF(mutex);
                 PKIX_ERROR_ALLOC_ERROR();
         }
 
         *pNewLock = mutex;
 
 cleanup:
old mode 100644
new mode 100755
old mode 100644
new mode 100755
--- a/security/nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_object.c
+++ b/security/nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_object.c
@@ -628,17 +628,17 @@ PKIX_PL_Object_Alloc(
         PKIX_OBJECT_DEBUG("\tShifting object pointer).\n");
 
 
         /* Return a pointer to the user data. Need to offset by object size */
         *pObject = object + 1;
         object = NULL;
 
         /* Atomically increment object counter */
-        PR_AtomicIncrement(&ctEntry->objCounter);
+        PR_ATOMIC_INCREMENT(&ctEntry->objCounter);
 
 cleanup:
 
         PKIX_FREE(object);
 
         PKIX_RETURN(OBJECT);
 }
 
@@ -827,17 +827,17 @@ PKIX_PL_Object_IncRef(
                 goto cleanup;
         }
 
         /* Shift pointer from user data to object header */
         PKIX_CHECK(pkix_pl_Object_GetHeader(object, &objectHeader, plContext),
                     PKIX_RECEIVEDCORRUPTEDOBJECTARGUMENT);
 
         /* This object should never have zero references */
-        refCount = PR_AtomicIncrement(&objectHeader->references);
+        refCount = PR_ATOMIC_INCREMENT(&objectHeader->references);
 
         if (refCount <= 1) {
                 PKIX_THROW(FATAL, PKIX_OBJECTWITHNONPOSITIVEREFERENCES);
         }
 
 cleanup:
 
         PKIX_RETURN(OBJECT);
@@ -873,17 +873,17 @@ PKIX_PL_Object_DecRef(
         if (object == (PKIX_PL_Object*)PKIX_ALLOC_ERROR()) {
                 goto cleanup;
         }
 
         /* Shift pointer from user data to object header */
         PKIX_CHECK(pkix_pl_Object_GetHeader(object, &objectHeader, plContext),
                     PKIX_RECEIVEDCORRUPTEDOBJECTARGUMENT);
 
-        refCount = PR_AtomicDecrement(&objectHeader->references);
+        refCount = PR_ATOMIC_DECREMENT(&objectHeader->references);
 
         if (refCount == 0) {
             PKIX_PL_DestructorCallback destructor = NULL;
             pkix_ClassTable_Entry *ctEntry = NULL;
             PKIX_UInt32 objType = objectHeader->type;
             
             /* first, special handling for system types */
             if (objType >= PKIX_NUMTYPES){
@@ -925,17 +925,17 @@ PKIX_PL_Object_DecRef(
                 if (pkixErrorResult) {
                     pkixErrorClass = PKIX_FATAL_ERROR;
                     PKIX_DoAddError(stdVarsPtr, pkixErrorResult, plContext);
                     pkixErrorResult = NULL;
                 }
             }
             
             /* Atomically decrement object counter */
-            PR_AtomicDecrement(&ctEntry->objCounter);
+            PR_ATOMIC_DECREMENT(&ctEntry->objCounter);
             
             /* pkix_pl_Object_Destroy assumes the lock is held */
             /* It will call unlock and destroy the object */
             pkixErrorResult = pkix_pl_Object_Destroy(object, plContext);
             goto cleanup;
         }
 
         if (refCount < 0) {
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
old mode 100644
new mode 100755
--- a/security/nss/lib/manifest.mn
+++ b/security/nss/lib/manifest.mn
@@ -44,17 +44,17 @@ DEPTH      = ../..
 #  stan (not a separate dll yet)
 #  libpkix (not a separate dll)
 #  nss base (traditional)
 #  ssl
 #  smime
 #  ckfw (builtins module)
 #  crmf jar (not dll's)
 DIRS =  util freebl $(SQLITE_SRCDIR) softoken \
-	base dev pki pki1 \
+	base dev pki \
 	libpkix \
 	certdb certhigh pk11wrap cryptohi nss \
 	$(ZLIB_SRCDIR) ssl \
 	pkcs12 pkcs7 smime \
 	crmf jar \
 	ckfw $(SYSINIT_SRCDIR) \
 	$(NULL)
 
--- a/security/nss/lib/nss/nss.def
+++ b/security/nss/lib/nss/nss.def
@@ -992,8 +992,14 @@ SECMOD_GetSkipFirstFlag;
 ;+NSS_3.12.6 { 	# NSS 3.12.6 release
 ;+    global:
 CERT_CacheOCSPResponseFromSideChannel;
 CERT_DistNamesFromCertList;
 CERT_DupDistNames;
 ;+    local:
 ;+       *;
 ;+};
+;+NSS_3.12.7 { 	# NSS 3.12.7 release
+;+    global:
+CERT_GetConstrainedCertificateNames;
+;+    local:
+;+       *;
+;+};
--- a/security/nss/lib/nss/nss.h
+++ b/security/nss/lib/nss/nss.h
@@ -31,17 +31,17 @@
  * under the terms of either the GPL or the LGPL, and not to allow others to
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
-/* $Id: nss.h,v 1.78 2010/03/02 02:53:04 christophe.ravel.bugs%sun.com Exp $ */
+/* $Id: nss.h,v 1.80 2010/04/25 23:37:32 nelson%bolyard.com Exp $ */
 
 #ifndef __nss_h_
 #define __nss_h_
 
 /* The private macro _NSS_ECC_STRING is for NSS internal use only. */
 #ifdef NSS_ENABLE_ECC
 #ifdef NSS_ECC_MORE_THAN_SUITE_B
 #define _NSS_ECC_STRING " Extended ECC"
@@ -61,22 +61,22 @@
 
 /*
  * NSS's major version, minor version, patch level, build number, and whether
  * this is a beta release.
  *
  * The format of the version string should be
  *     "<major version>.<minor version>[.<patch level>[.<build number>]][ <ECC>][ <Beta>]"
  */
-#define NSS_VERSION  "3.12.6.2" _NSS_ECC_STRING _NSS_CUSTOMIZED
+#define NSS_VERSION  "3.12.7.0" _NSS_ECC_STRING _NSS_CUSTOMIZED " Beta"
 #define NSS_VMAJOR   3
 #define NSS_VMINOR   12
-#define NSS_VPATCH   6
-#define NSS_VBUILD   2
-#define NSS_BETA     PR_FALSE
+#define NSS_VPATCH   7
+#define NSS_VBUILD   0
+#define NSS_BETA     PR_TRUE
 
 #ifndef RC_INVOKED
 
 #include "seccomon.h"
 
 typedef struct NSSInitParametersStr NSSInitParameters;
 
 /*
@@ -240,17 +240,17 @@ extern SECStatus NSS_InitReadWrite(const
  *                      future to trigger better cooperation between PKCS#11
  *                      modules used by both NSS and the Java SunPKCS11
  *                      provider. This should occur after a new flag is defined
  *                      for C_Initialize by the PKCS#11 working group.
  *      NSS_INIT_COOPERATE - Sets 4 recommended options for applications that
  *                      use both NSS and the Java SunPKCS11 provider.
  *
  * Also NOTE: This is not the recommended method for initializing NSS. 
- * The prefered method is NSS_init().
+ * The preferred method is NSS_init().
  */
 #define NSS_INIT_READONLY	0x1
 #define NSS_INIT_NOCERTDB	0x2
 #define NSS_INIT_NOMODDB	0x4
 #define NSS_INIT_FORCEOPEN	0x8
 #define NSS_INIT_NOROOTINIT     0x10
 #define NSS_INIT_OPTIMIZESPACE  0x20
 #define NSS_INIT_PK11THREADSAFE   0x40
--- a/security/nss/lib/nss/nssinit.c
+++ b/security/nss/lib/nss/nssinit.c
@@ -31,17 +31,17 @@
  * under the terms of either the GPL or the LGPL, and not to allow others to
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
-/* $Id: nssinit.c,v 1.105 2010/01/22 02:10:54 wtc%google.com Exp $ */
+/* $Id: nssinit.c,v 1.106 2010/04/03 20:06:00 nelson%bolyard.com Exp $ */
 
 #include <ctype.h>
 #include <string.h>
 #include "seccomon.h"
 #include "prinit.h"
 #include "prprf.h"
 #include "prmem.h"
 #include "cert.h"
@@ -575,42 +575,42 @@ nss_Init(const char *configdir, const ch
         pk11_setGlobalOptions(noSingleThreadedModules,
                               allowAlreadyInitializedModules,
                               dontFinalizeModules);
     }
 
     if (initContextPtr) {
 	*initContextPtr = PORT_ZNew(NSSInitContext);
 	if (*initContextPtr == NULL) {
-	    return SECFailure;
+	    goto loser;
 	}
 	/*
 	 * For traditional NSS_Init, we used the PK11_Configure() call to set
 	 * globals. with InitContext, we pass those strings in as parameters.
 	 *
 	 * This allows old NSS_Init calls to work as before, while at the same
 	 * time new calls and old calls will not interfere with each other.
 	 */
         if (initParams) {
 	    if (initParams->length < sizeof(NSSInitParameters)) {
 		PORT_SetError(SEC_ERROR_INVALID_ARGS);
-		return SECFailure;
+		goto loser;
 	    }
 	    configStrings = nss_MkConfigString(initParams->manufactureID,
 		initParams->libraryDescription,
 		initParams->cryptoTokenDescription,
 		initParams->dbTokenDescription,
 		initParams->cryptoSlotDescription,
 		initParams->dbSlotDescription,
 		initParams->FIPSSlotDescription,
 		initParams->FIPSTokenDescription,
 		initParams->minPWLen);
 	    if (configStrings == NULL) {
 		PORT_SetError(SEC_ERROR_NO_MEMORY);
-		return SECFailure;
+		goto loser;
 	    }
 	    configName = initParams->libraryDescription;
 	    passwordRequired = initParams->passwordRequired;
 	}
     } else {
 	configStrings = pk11_config_strings;
 	configName = pk11_config_name;
 	passwordRequired = pk11_password_required;
--- a/security/nss/lib/pk11wrap/debug_module.c
+++ b/security/nss/lib/pk11wrap/debug_module.c
@@ -897,22 +897,22 @@ int nssdbg_prof_size = sizeof(nssdbg_pro
 
 static void nssdbg_finish_time(PRInt32 fun_number, PRIntervalTime start)
 {
     PRIntervalTime ival;
     PRIntervalTime end = PR_IntervalNow();
 
     ival = end-start;
     /* sigh, lie to PRAtomic add and say we are using signed values */
-    PR_AtomicAdd((PRInt32 *)&nssdbg_prof_data[fun_number].time, (PRInt32)ival);
+    PR_ATOMIC_ADD((PRInt32 *)&nssdbg_prof_data[fun_number].time, (PRInt32)ival);
 }
 
 static void nssdbg_start_time(PRInt32 fun_number, PRIntervalTime *start)
 {
-    PR_AtomicIncrement((PRInt32 *)&nssdbg_prof_data[fun_number].calls);
+    PR_ATOMIC_INCREMENT((PRInt32 *)&nssdbg_prof_data[fun_number].calls);
     *start = PR_IntervalNow();
 }
 
 #define COMMON_DEFINITIONS \
     CK_RV rv; \
     PRIntervalTime start
 
 CK_RV NSSDBGC_Initialize(
@@ -1207,17 +1207,17 @@ CK_RV NSSDBGC_OpenSession(
   CK_FLAGS              flags,
   CK_VOID_PTR           pApplication,
   CK_NOTIFY             Notify,
   CK_SESSION_HANDLE_PTR phSession
 )
 {
     COMMON_DEFINITIONS;
 
-    PR_AtomicIncrement((PRInt32 *)&numOpenSessions);
+    PR_ATOMIC_INCREMENT((PRInt32 *)&numOpenSessions);
     maxOpenSessions = PR_MAX(numOpenSessions, maxOpenSessions);
     PR_LOG(modlog, 1, ("C_OpenSession"));
     PR_LOG(modlog, 3, (fmt_slotID, slotID));
     PR_LOG(modlog, 3, (fmt_flags, flags));
     PR_LOG(modlog, 3, ("  pApplication = 0x%p", pApplication));
     PR_LOG(modlog, 3, ("  Notify = 0x%x", Notify));
     PR_LOG(modlog, 3, ("  phSession = 0x%p", phSession));
     nssdbg_start_time(FUNC_C_OPENSESSION,&start);
@@ -1233,17 +1233,17 @@ CK_RV NSSDBGC_OpenSession(
 }
 
 CK_RV NSSDBGC_CloseSession(
   CK_SESSION_HANDLE hSession
 )
 {
     COMMON_DEFINITIONS;
 
-    PR_AtomicDecrement((PRInt32 *)&numOpenSessions);
+    PR_ATOMIC_DECREMENT((PRInt32 *)&numOpenSessions);
     PR_LOG(modlog, 1, ("C_CloseSession"));
     log_handle(3, fmt_hSession, hSession);
     nssdbg_start_time(FUNC_C_CLOSESESSION,&start);
     rv = module_functions->C_CloseSession(hSession);
     nssdbg_finish_time(FUNC_C_CLOSESESSION,start);
     log_rv(rv);
     return rv;
 }
--- a/security/nss/lib/pk11wrap/pk11akey.c
+++ b/security/nss/lib/pk11wrap/pk11akey.c
@@ -1149,16 +1149,21 @@ PK11_GenerateKeyPairWithOpFlags(PK11Slot
 	(PK11_ATTR_TOKEN | PK11_ATTR_SESSION
 	| PK11_ATTR_MODIFIABLE | PK11_ATTR_UNMODIFIABLE);
 
     if (pk11_BadAttrFlags(attrFlags)) {
 	PORT_SetError( SEC_ERROR_INVALID_ARGS );
 	return NULL;
     }
 
+    if (!param) {
+        PORT_SetError( SEC_ERROR_INVALID_ARGS );
+        return NULL;
+    }
+
     /*
      * The opFlags and opFlagMask parameters allow us to control the
      * settings of the key usage attributes (CKA_ENCRYPT and friends).
      * opFlagMask is set to one if the flag is specified in opFlags and 
      *  zero if it is to take on a default value calculated by 
      *  PK11_GenerateKeyPairWithOpFlags.
      * opFlags specifies the actual value of the flag 1 or 0. 
      *   Bits not corresponding to one bits in opFlagMask should be zero.
--- a/security/nss/lib/pk11wrap/pk11auth.c
+++ b/security/nss/lib/pk11wrap/pk11auth.c
@@ -474,31 +474,27 @@ done:
 /*
  * Change an existing user password
  */
 SECStatus
 PK11_ChangePW(PK11SlotInfo *slot, const char *oldpw, const char *newpw)
 {
     CK_RV crv;
     SECStatus rv = SECFailure;
-    int newLen;
-    int oldLen;
+    int newLen = 0;
+    int oldLen = 0;
     CK_SESSION_HANDLE rwsession;
 
     /* use NULL values to trigger the protected authentication path */
-    if (slot->protectedAuthPath) {
-	if (newpw == NULL) newLen = 0;
-	if (oldpw == NULL) oldLen = 0;
-    } else {
+    if (!slot->protectedAuthPath) {
 	if (newpw == NULL) newpw = "";
 	if (oldpw == NULL) oldpw = "";
-	newLen = PORT_Strlen(newpw);
-	oldLen = PORT_Strlen(oldpw);
     }
-
+    if (newpw) newLen = PORT_Strlen(newpw);
+    if (oldpw) oldLen = PORT_Strlen(oldpw);
 
     /* get a rwsession */
     rwsession = PK11_GetRWSession(slot);
     if (rwsession == CK_INVALID_SESSION) {
     	PORT_SetError(SEC_ERROR_BAD_DATA);
     	return rv;
     }
 
--- a/security/nss/lib/pk11wrap/pk11cert.c
+++ b/security/nss/lib/pk11wrap/pk11cert.c
@@ -2472,28 +2472,35 @@ PK11_ListCertsInSlot(PK11SlotInfo *slot)
     }
 
     return certs;
 }
 
 PK11SlotList *
 PK11_GetAllSlotsForCert(CERTCertificate *cert, void *arg)
 {
-    NSSCertificate *c = STAN_GetNSSCertificate(cert);
-    /* add multiple instances to the cert list */
     nssCryptokiObject **ip;
-    nssCryptokiObject **instances = nssPKIObject_GetInstances(&c->object);
     PK11SlotList *slotList;
+    NSSCertificate *c;
+    nssCryptokiObject **instances;
     PRBool found = PR_FALSE;
 
     if (!cert) {
 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
 	return NULL;
     }
 
+    c = STAN_GetNSSCertificate(cert);
+    if (!c) {
+	CERT_MapStanError();
+	return NULL;
+    }
+
+    /* add multiple instances to the cert list */
+    instances = nssPKIObject_GetInstances(&c->object);
     if (!instances) {
 	PORT_SetError(SEC_ERROR_NO_TOKEN);
 	return NULL;
     }
 
     slotList = PK11_NewSlotList();
     if (!slotList) {
 	nssCryptokiObjectArray_Destroy(instances);
--- a/security/nss/lib/pk11wrap/pk11cxt.c
+++ b/security/nss/lib/pk11wrap/pk11cxt.c
@@ -244,17 +244,18 @@ static PK11Context *pk11_CreateNewContex
      PK11SlotInfo *slot, CK_ATTRIBUTE_TYPE operation, PK11SymKey *symKey,
 							     SECItem *param)
 {
     CK_MECHANISM mech_info;
     PK11Context *context;
     SECStatus rv;
 	
     PORT_Assert(slot != NULL);
-    if (!slot || (!symKey && operation != CKA_DIGEST)) {
+    if (!slot || (!symKey && ((operation != CKA_DIGEST) || 
+	                      (type == CKM_SKIPJACK_CBC64)))) {
 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
 	return NULL;
     }
     context = (PK11Context *) PORT_Alloc(sizeof(PK11Context));
     if (context == NULL) {
 	return NULL;
     }
 
--- a/security/nss/lib/pk11wrap/pk11err.c
+++ b/security/nss/lib/pk11wrap/pk11err.c
@@ -99,21 +99,23 @@ PK11_MapError(CK_RV rv) {
 	MAPERROR(CKR_MECHANISM_PARAM_INVALID, SEC_ERROR_BAD_DATA)
 	MAPERROR(CKR_NO_EVENT, SEC_ERROR_NO_EVENT)
 	MAPERROR(CKR_OBJECT_HANDLE_INVALID, SEC_ERROR_BAD_DATA)
 	MAPERROR(CKR_OPERATION_ACTIVE, SEC_ERROR_LIBRARY_FAILURE)
 	MAPERROR(CKR_OPERATION_NOT_INITIALIZED,SEC_ERROR_LIBRARY_FAILURE )
 	MAPERROR(CKR_PIN_INCORRECT, SEC_ERROR_BAD_PASSWORD)
 	MAPERROR(CKR_PIN_INVALID, SEC_ERROR_INVALID_PASSWORD)
 	MAPERROR(CKR_PIN_LEN_RANGE, SEC_ERROR_INVALID_PASSWORD)
+	MAPERROR(CKR_PIN_EXPIRED, SEC_ERROR_EXPIRED_PASSWORD)
+	MAPERROR(CKR_PIN_LOCKED, SEC_ERROR_LOCKED_PASSWORD)
 	MAPERROR(CKR_SESSION_CLOSED, SEC_ERROR_LIBRARY_FAILURE)
 	MAPERROR(CKR_SESSION_COUNT, SEC_ERROR_NO_MEMORY) /* XXXX? */
 	MAPERROR(CKR_SESSION_HANDLE_INVALID, SEC_ERROR_BAD_DATA)
 	MAPERROR(CKR_SESSION_PARALLEL_NOT_SUPPORTED, SEC_ERROR_LIBRARY_FAILURE)
-	MAPERROR(CKR_SESSION_READ_ONLY, SEC_ERROR_LIBRARY_FAILURE)
+	MAPERROR(CKR_SESSION_READ_ONLY, SEC_ERROR_READ_ONLY)
 	MAPERROR(CKR_SIGNATURE_INVALID, SEC_ERROR_BAD_SIGNATURE)
 	MAPERROR(CKR_SIGNATURE_LEN_RANGE, SEC_ERROR_BAD_SIGNATURE)
 	MAPERROR(CKR_TEMPLATE_INCOMPLETE, SEC_ERROR_BAD_DATA)
 	MAPERROR(CKR_TEMPLATE_INCONSISTENT, SEC_ERROR_BAD_DATA)
 	MAPERROR(CKR_TOKEN_NOT_PRESENT, SEC_ERROR_NO_TOKEN)
 	MAPERROR(CKR_TOKEN_NOT_RECOGNIZED, SEC_ERROR_IO)
 	MAPERROR(CKR_TOKEN_WRITE_PROTECTED, SEC_ERROR_READ_ONLY)
 	MAPERROR(CKR_UNWRAPPING_KEY_HANDLE_INVALID, SEC_ERROR_INVALID_KEY)
--- a/security/nss/lib/pk11wrap/pk11load.c
+++ b/security/nss/lib/pk11wrap/pk11load.c
@@ -134,19 +134,19 @@ PRBool pk11_getFinalizeModulesOption(voi
 static SECStatus
 secmod_handleReload(SECMODModule *oldModule, SECMODModule *newModule)
 {
     PK11SlotInfo *slot;
     char *modulespec;
     char *newModuleSpec;
     char **children;
     CK_SLOT_ID *ids;
-    SECStatus rv;
-    SECMODConfigList *conflist;
-    int count = 0;
+    SECMODConfigList *conflist = NULL;
+    SECStatus         rv       = SECFailure;
+    int               count    = 0;
 
     /* first look for tokens= key words from the module spec */
     modulespec = newModule->libraryParams;
     newModuleSpec = secmod_ParseModuleSpecForTokens(PR_TRUE,
 				newModule->isFIPS, modulespec, &children, &ids);
     if (!newModuleSpec) {
 	return SECFailure;
     }
@@ -401,17 +401,17 @@ secmod_LoadPKCS11Module(SECMODModule *mo
     /*
      * Loads softoken as a dynamic library,
      * even though the rest of NSS assumes this as the "internal" module.
      */
     if (!softokenLib && 
         PR_SUCCESS != PR_CallOnce(&loadSoftokenOnce, &softoken_LoadDSO))
         return SECFailure;
 
-    PR_AtomicIncrement(&softokenLoadCount);
+    PR_ATOMIC_INCREMENT(&softokenLoadCount);
 
     if (mod->isFIPS) {
         entry = (CK_C_GetFunctionList) 
                     PR_FindSymbol(softokenLib, "FC_GetFunctionList");
     } else {
         entry = (CK_C_GetFunctionList) 
                     PR_FindSymbol(softokenLib, "NSC_GetFunctionList");
     }
@@ -587,17 +587,17 @@ SECMOD_UnloadModule(SECMODModule *mod) {
     }
     mod->moduleID = 0;
     mod->loaded = PR_FALSE;
     
     /* do we want the semantics to allow unloading the internal library?
      * if not, we should change this to SECFailure and move it above the
      * mod->loaded = PR_FALSE; */
     if (mod->internal) {
-        if (0 == PR_AtomicDecrement(&softokenLoadCount)) {
+        if (0 == PR_ATOMIC_DECREMENT(&softokenLoadCount)) {
           if (softokenLib) {
               disableUnload = PR_GetEnv("NSS_DISABLE_UNLOAD");
               if (!disableUnload) {
                   PRStatus status = PR_UnloadLibrary(softokenLib);
                   PORT_Assert(PR_SUCCESS == status);
               }
               softokenLib = NULL;
           }
--- a/security/nss/lib/pk11wrap/pk11merge.c
+++ b/security/nss/lib/pk11wrap/pk11merge.c
@@ -316,17 +316,17 @@ done:
 
 /*
  * we need to find a unique CKA_ID.
  *  The basic idea is to just increment the lowest byte.
  *  This code also handles the following corner cases:
  *   1) the single byte overflows. On overflow we increment the next byte up 
  *    and so forth until we have overflowed the entire CKA_ID.
  *   2) If we overflow the entire CKA_ID we expand it by one byte.
- *   3) the CKA_ID is non-existant, we create a new one with one byte.
+ *   3) the CKA_ID is non-existent, we create a new one with one byte.
  *    This means no matter what CKA_ID is passed, the result of this function 
  *    is always a new CKA_ID, and this function will never return the same 
  *    CKA_ID the it has returned in the passed.
  */
 static SECStatus
 pk11_incrementID(PRArenaPool *arena, CK_ATTRIBUTE *ptemplate)
 {
     unsigned char *buf = ptemplate->pValue;
--- a/security/nss/lib/pk11wrap/pk11nobj.c
+++ b/security/nss/lib/pk11wrap/pk11nobj.c
@@ -111,17 +111,17 @@ pk11_HandleTrustObject(PK11SlotInfo *slo
   if( CK_INVALID_HANDLE == tobjID ) {
     return PR_FALSE;
   }
 
   arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
   if( NULL == arena ) return PR_FALSE;
 
   /* Unfortunately, it seems that PK11_GetAttributes doesn't deal
-   * well with nonexistant attributes.  I guess we have to check 
+   * well with nonexistent attributes.  I guess we have to check 
    * the trust info fields one at a time.
    */
 
   /* We could verify CKA_CERT_HASH here */
 
   /* We could verify CKA_EXPIRES here */
 
 
--- a/security/nss/lib/pk11wrap/pk11pub.h
+++ b/security/nss/lib/pk11wrap/pk11pub.h
@@ -209,17 +209,17 @@ int PK11_GetBestKeyLength(PK11SlotInfo *
  *         will fail.
  *   certPrefix - Cert prefix for this token.
  *   keyPrefix - Prefix for the key database for this token. (if not specified,
  *         certPrefix will be used).
  *   tokenDescription - The label value for this token returned in the
  *         CK_TOKEN_INFO structure with an internationalize string (UTF8).
  *         This value will be truncated at 32 bytes (no NULL, partial UTF8
  *         characters dropped). You should specify a user friendly name here
- *         as this is the value the token will be refered to in most
+ *         as this is the value the token will be referred to in most
  *         application UI's. You should make sure tokenDescription is unique.
  *   slotDescription - The slotDescription value for this token returned
  *         in the CK_SLOT_INFO structure with an internationalize string
  *         (UTF8). This value will be truncated at 64 bytes (no NULL, partial
  *         UTF8 characters dropped). This name will not change after the
  *         database is closed. It should have some number to make this unique.
  *   minPWLen - minimum password length for this token.
  *   flags - comma separated list of flag values, parsed case-insensitive.
--- a/security/nss/lib/pk11wrap/pk11skey.c
+++ b/security/nss/lib/pk11wrap/pk11skey.c
@@ -212,17 +212,17 @@ pk11_CreateSymKey(PK11SlotInfo *slot, CK
  * destroy a symetric key
  */
 void
 PK11_FreeSymKey(PK11SymKey *symKey)
 {
     PK11SlotInfo *slot;
     PRBool freeit = PR_TRUE;
 
-    if (PR_AtomicDecrement(&symKey->refCount) == 0) {
+    if (PR_ATOMIC_DECREMENT(&symKey->refCount) == 0) {
 	PK11SymKey *parent = symKey->parent;
 
 	symKey->parent = NULL;
 	if ((symKey->owner) && symKey->objectID != CK_INVALID_HANDLE) {
 	    pk11_EnterKeyMonitor(symKey);
 	    (void) PK11_GETTAB(symKey->slot)->
 		C_DestroyObject(symKey->session, symKey->objectID);
 	    pk11_ExitKeyMonitor(symKey);
@@ -274,17 +274,17 @@ PK11_FreeSymKey(PK11SymKey *symKey)
 	    PK11_FreeSymKey(parent);
 	}
     }
 }
 
 PK11SymKey *
 PK11_ReferenceSymKey(PK11SymKey *symKey)
 {
-    PR_AtomicIncrement(&symKey->refCount);
+    PR_ATOMIC_INCREMENT(&symKey->refCount);
     return symKey;
 }
 
 /*
  * Accessors
  */
 CK_MECHANISM_TYPE
 PK11_GetMechanism(PK11SymKey *symKey)
@@ -1149,23 +1149,28 @@ PK11_PubWrapSymKey(CK_MECHANISM_TYPE typ
     CK_ULONG len =  wrappedKey->len;
     PK11SymKey *newKey = NULL;
     CK_OBJECT_HANDLE id;
     CK_MECHANISM mechanism;
     PRBool owner = PR_TRUE;
     CK_SESSION_HANDLE session;
     CK_RV crv;
 
+    if (symKey == NULL) {
+	PORT_SetError( SEC_ERROR_INVALID_ARGS );
+	return SECFailure;
+    }
+
     /* if this slot doesn't support the mechanism, go to a slot that does */
     newKey = pk11_ForceSlot(symKey,type,CKA_ENCRYPT);
     if (newKey != NULL) {
 	symKey = newKey;
     }
 
-    if ((symKey == NULL) || (symKey->slot == NULL)) {
+    if (symKey->slot == NULL) {
 	PORT_SetError( SEC_ERROR_NO_MODULE );
 	return SECFailure;
     }
 
     slot = symKey->slot;
     mechanism.mechanism = pk11_mapWrapKeyType(pubKey->keyType);
     mechanism.pParameter = NULL;
     mechanism.ulParameterLen = 0;
--- a/security/nss/lib/pk11wrap/pk11slot.c
+++ b/security/nss/lib/pk11wrap/pk11slot.c
@@ -413,17 +413,17 @@ PK11_NewSlotInfo(SECMODModule *mod)
     slot->nssToken = NULL;
     return slot;
 }
     
 /* create a new reference to a slot so it doesn't go away */
 PK11SlotInfo *
 PK11_ReferenceSlot(PK11SlotInfo *slot)
 {
-    PR_AtomicIncrement(&slot->refCount);
+    PR_ATOMIC_INCREMENT(&slot->refCount);
     return slot;
 }
 
 /* Destroy all info on a slot we have built up */
 void
 PK11_DestroySlot(PK11SlotInfo *slot)
 {
    /* free up the cached keys and sessions */
@@ -455,17 +455,17 @@ PK11_DestroySlot(PK11SlotInfo *slot)
    PORT_Free(slot);
 }
 
 
 /* We're all done with the slot, free it */
 void
 PK11_FreeSlot(PK11SlotInfo *slot)
 {
-    if (PR_AtomicDecrement(&slot->refCount) == 0) {
+    if (PR_ATOMIC_DECREMENT(&slot->refCount) == 0) {
 	PK11_DestroySlot(slot);
     }
 }
 
 void
 PK11_EnterSlotMonitor(PK11SlotInfo *slot) {
     PZ_Lock(slot->sessionLock);
 }
--- a/security/nss/lib/pk11wrap/pk11util.c
+++ b/security/nss/lib/pk11wrap/pk11util.c
@@ -1435,17 +1435,17 @@ SECMOD_OpenNewSlot(SECMODModule *mod, co
  *         will fail.
  *   certPrefix - Cert prefix for this token.
  *   keyPrefix - Prefix for the key database for this token. (if not specified,
  *         certPrefix will be used).
  *   tokenDescription - The label value for this token returned in the 
  *         CK_TOKEN_INFO structure with an internationalize string (UTF8). 
  *         This value will be truncated at 32 bytes (no NULL, partial UTF8 
  *         characters dropped). You should specify a user friendly name here
- *         as this is the value the token will be refered to in most 
+ *         as this is the value the token will be referred to in most 
  *         application UI's. You should make sure tokenDescription is unique.
  *   slotDescription - The slotDescription value for this token returned 
  *         in the CK_SLOT_INFO structure with an internationalize string 
  *         (UTF8). This value will be truncated at 64 bytes (no NULL, partial 
  *         UTF8 characters dropped). This name will not change after the 
  *         database is closed. It should have some number to make this unique.
  *   minPWLen - minimum password length for this token.
  *   flags - comma separated list of flag values, parsed case-insensitive.
--- a/security/nss/lib/pkcs12/p12d.c
+++ b/security/nss/lib/pkcs12/p12d.c
@@ -53,41 +53,47 @@
 #include "p12local.h"
 #include "secder.h"
 #include "secport.h"
 
 #include "certdb.h"
 
 #include "prcpucfg.h"
 
+/* This belongs in secport.h */
+#define PORT_ArenaGrowArray(poolp, oldptr, type, oldnum, newnum) \
+    (type *)PORT_ArenaGrow((poolp), (oldptr), \
+			   (oldnum) * sizeof(type), (newnum) * sizeof(type))
+
+
 typedef struct sec_PKCS12SafeContentsContextStr sec_PKCS12SafeContentsContext;
 
 /* Opaque structure for decoding SafeContents.  These are used
  * for each authenticated safe as well as any nested safe contents.
  */
 struct sec_PKCS12SafeContentsContextStr {
     /* the parent decoder context */
     SEC_PKCS12DecoderContext *p12dcx;
 
     /* memory arena to allocate space from */
     PRArenaPool *arena;
 
     /* decoder context and destination for decoding safe contents */
-    SEC_ASN1DecoderContext *safeContentsDcx;
+    SEC_ASN1DecoderContext *safeContentsA1Dcx;
     sec_PKCS12SafeContents safeContents;
 
     /* information for decoding safe bags within the safe contents.
      * these variables are updated for each safe bag decoded.
      */
-    SEC_ASN1DecoderContext *currentSafeBagDcx;
+    SEC_ASN1DecoderContext *currentSafeBagA1Dcx;
     sec_PKCS12SafeBag *currentSafeBag;
     PRBool skipCurrentSafeBag;
 
     /* if the safe contents is nested, the parent is pointed to here. */
-    sec_PKCS12SafeContentsContext *nestedCtx;
+    sec_PKCS12SafeContentsContext *nestedSafeContentsCtx;
 };
 
 /* opaque decoder context structure.  information for decoding a pkcs 12
  * PDU are stored here as well as decoding pointers for intermediary 
  * structures which are part of the PKCS 12 PDU.  Upon a successful
  * decode, the safe bags containing certificates and keys encountered.
  */  
 struct SEC_PKCS12DecoderContextStr {
@@ -96,64 +102,74 @@ struct SEC_PKCS12DecoderContextStr {
     void *wincx;
     PRBool error;
     int errorValue;
 
     /* password */
     SECItem *pwitem;
 
     /* used for decoding the PFX structure */
-    SEC_ASN1DecoderContext *pfxDcx;
-    sec_PKCS12PFXItem pfx;
+    SEC_ASN1DecoderContext 	*pfxA1Dcx;
+    sec_PKCS12PFXItem 		pfx;
 
     /* safe bags found during decoding */  
-    sec_PKCS12SafeBag **safeBags;
-    unsigned int safeBagCount;
+    sec_PKCS12SafeBag 		**safeBags;
+    unsigned int 		safeBagCount;
 
     /* state variables for decoding authenticated safes. */
-    SEC_PKCS7DecoderContext *currentASafeP7Dcx;
-    SEC_ASN1DecoderContext *aSafeDcx;
-    SEC_PKCS7DecoderContext *aSafeP7Dcx;
+    SEC_PKCS7DecoderContext 	*currentASafeP7Dcx;
+    SEC_ASN1DecoderContext 	*aSafeA1Dcx;
+    SEC_PKCS7DecoderContext 	*aSafeP7Dcx;
+    SEC_PKCS7ContentInfo 	*aSafeCinfo;
     sec_PKCS12AuthenticatedSafe authSafe;
-    SEC_PKCS7ContentInfo *aSafeCinfo;
-    sec_PKCS12SafeContents safeContents;
+    sec_PKCS12SafeContents 	safeContents;
 
     /* safe contents info */
-    unsigned int safeContentsCnt;
+    unsigned int 		safeContentsCnt;
     sec_PKCS12SafeContentsContext **safeContentsList;
 
     /* HMAC info */
-    sec_PKCS12MacData	macData;
-    SEC_ASN1DecoderContext *hmacDcx;
+    sec_PKCS12MacData		macData;
 
     /* routines for reading back the data to be hmac'd */
-    digestOpenFn dOpen;
-    digestCloseFn dClose;
-    digestIOFn dRead, dWrite;
-    void *dArg;
+    digestOpenFn 		dOpen;
+    digestCloseFn 		dClose;
+    digestIOFn 			dRead, dWrite;
+    void 			*dArg;
 
     /* helper functions */
-    SECKEYGetPasswordKey pwfn;
-    void *pwfnarg;
-    PRBool swapUnicodeBytes;
+    SECKEYGetPasswordKey 	pwfn;
+    void 			*pwfnarg;
+    PRBool 			swapUnicodeBytes;
 
     /* import information */
-    PRBool bagsVerified;
+    PRBool 			bagsVerified;
 
     /* buffer management for the default callbacks implementation */
     void        *buffer;      /* storage area */
     PRInt32     filesize;     /* actual data size */
     PRInt32     allocated;    /* total buffer size allocated */
     PRInt32     currentpos;   /* position counter */
     SECPKCS12TargetTokenCAs tokenCAs;
     sec_PKCS12SafeBag **keyList;/* used by ...IterateNext() */
     unsigned int iteration;
     SEC_PKCS12DecoderItem decitem;
 };
 
+/* forward declarations of functions that are used when decoding
+ * safeContents bags which are nested and when decoding the 
+ * authenticatedSafes.
+ */
+static SECStatus
+sec_pkcs12_decoder_begin_nested_safe_contents(sec_PKCS12SafeContentsContext 
+							*safeContentsCtx);
+static SECStatus
+sec_pkcs12_decoder_finish_nested_safe_contents(sec_PKCS12SafeContentsContext
+							*safeContentsCtx);
+
 
 /* make sure that the PFX version being decoded is a version
  * which we support.
  */
 static PRBool
 sec_pkcs12_proper_version(sec_PKCS12PFXItem *pfx)
 {
     /* if no version, assume it is not supported */
@@ -167,18 +183,17 @@ sec_pkcs12_proper_version(sec_PKCS12PFXI
 
     return PR_TRUE;
 }
 
 /* retrieve the key for decrypting the safe contents */ 
 static PK11SymKey *
 sec_pkcs12_decoder_get_decrypt_key(void *arg, SECAlgorithmID *algid)
 {
-    SEC_PKCS12DecoderContext *p12dcx =
-	(SEC_PKCS12DecoderContext *) arg;
+    SEC_PKCS12DecoderContext *p12dcx = (SEC_PKCS12DecoderContext *) arg;
     PK11SlotInfo *slot;
     PK11SymKey *bulkKey;
 
     if(!p12dcx) {
 	return NULL;
     }
 
     /* if no slot specified, use the internal key slot */
@@ -251,37 +266,33 @@ sec_pkcs12_decoder_init_new_safe_bag(sec
 
     p12dcx = safeContentsCtx->p12dcx;
     mark = PORT_ArenaMark(p12dcx->arena);
 
     /* allocate a new safe bag, if bags already exist, grow the 
      * list of bags, otherwise allocate a new list.  the list is
      * NULL terminated.
      */
-    if(p12dcx->safeBagCount) {
-	p12dcx->safeBags = 
-	    (sec_PKCS12SafeBag**)PORT_ArenaGrow(p12dcx->arena,p12dcx->safeBags,
-			(p12dcx->safeBagCount + 1) * sizeof(sec_PKCS12SafeBag *),
-			(p12dcx->safeBagCount + 2) * sizeof(sec_PKCS12SafeBag *));
-    } else {
-	p12dcx->safeBags = (sec_PKCS12SafeBag**)PORT_ArenaZAlloc(p12dcx->arena,
-					    2 * sizeof(sec_PKCS12SafeBag *));
-    }
+    p12dcx->safeBags = (!p12dcx->safeBagCount)
+	? PORT_ArenaZNewArray(p12dcx->arena, sec_PKCS12SafeBag *, 2)
+        : PORT_ArenaGrowArray(p12dcx->arena, p12dcx->safeBags,
+				sec_PKCS12SafeBag *, p12dcx->safeBagCount + 1,
+				p12dcx->safeBagCount + 2);
+
     if(!p12dcx->safeBags) {
 	p12dcx->errorValue = PORT_GetError();
 	goto loser;
     }
 
     /* append the bag to the end of the list and update the reference
      * in the safeContentsCtx.
      */
     p12dcx->safeBags[p12dcx->safeBagCount] = 
     safeContentsCtx->currentSafeBag = 
-        (sec_PKCS12SafeBag*)PORT_ArenaZAlloc(p12dcx->arena,
-					     sizeof(sec_PKCS12SafeBag));
+			    PORT_ArenaZNew(p12dcx->arena, sec_PKCS12SafeBag);
     if(!safeContentsCtx->currentSafeBag) {
 	p12dcx->errorValue = PORT_GetError();
 	goto loser;
     }
     p12dcx->safeBags[++p12dcx->safeBagCount] = NULL;
 
     safeContentsCtx->currentSafeBag->slot = safeContentsCtx->p12dcx->slot;
     safeContentsCtx->currentSafeBag->pwitem = safeContentsCtx->p12dcx->pwitem;
@@ -328,51 +339,36 @@ sec_pkcs12_decoder_safe_bag_update(void 
      */
     if(!safeContentsCtx || !safeContentsCtx->p12dcx 
 		|| safeContentsCtx->p12dcx->error 
 		|| safeContentsCtx->skipCurrentSafeBag) {
 	return;
     }
     p12dcx = safeContentsCtx->p12dcx;
 
-    rv = SEC_ASN1DecoderUpdate(safeContentsCtx->currentSafeBagDcx, data, len);
+    rv = SEC_ASN1DecoderUpdate(safeContentsCtx->currentSafeBagA1Dcx, data, len);
     if(rv != SECSuccess) {
 	p12dcx->errorValue = PORT_GetError();
 	goto loser;
     }
 
     return;
 
 loser:
     /* set the error, and finish the decoder context.  because there 
      * is not a way of returning an error message, it may be worth
      * while to do a check higher up and finish any decoding contexts
      * that are still open.
      */
     p12dcx->error = PR_TRUE;
-    SEC_ASN1DecoderFinish(safeContentsCtx->currentSafeBagDcx);
-    safeContentsCtx->currentSafeBagDcx = NULL;
+    SEC_ASN1DecoderFinish(safeContentsCtx->currentSafeBagA1Dcx);
+    safeContentsCtx->currentSafeBagA1Dcx = NULL;
     return;
 }
 
-/* forward declarations of functions that are used when decoding
- * safeContents bags which are nested and when decoding the 
- * authenticatedSafes.
- */
-static SECStatus
-sec_pkcs12_decoder_begin_nested_safe_contents(sec_PKCS12SafeContentsContext 
-							*safeContentsCtx);
-static SECStatus
-sec_pkcs12_decoder_finish_nested_safe_contents(sec_PKCS12SafeContentsContext
-							*safeContentsCtx);
-static void
-sec_pkcs12_decoder_safe_bag_update(void *arg, const char *data, 
-				   unsigned long len, int depth, 
-				   SEC_ASN1EncodingPart data_kind);
-
 /* notify function for decoding safeBags.  This function is
  * used to filter safeBag types which are not supported,
  * initiate the decoding of nested safe contents, and decode
  * safeBags in general.  this function is set when the decoder
  * context for the safeBag is first created.
  */
 static void
 sec_pkcs12_decoder_safe_bag_notify(void *arg, PRBool before,
@@ -466,64 +462,65 @@ sec_pkcs12_decoder_safe_contents_notify(
 	return;
     }
     p12dcx = safeContentsCtx->p12dcx;
 
     /* if we are done with the current safeBag, then we need to
      * finish the context and set the state variables appropriately.
      */
     if(!before) {
-	SEC_ASN1DecoderClearFilterProc(safeContentsCtx->safeContentsDcx);
-	SEC_ASN1DecoderFinish(safeContentsCtx->currentSafeBagDcx);
-	safeContentsCtx->currentSafeBagDcx = NULL;
+	SEC_ASN1DecoderClearFilterProc(safeContentsCtx->safeContentsA1Dcx);
+	SEC_ASN1DecoderFinish(safeContentsCtx->currentSafeBagA1Dcx);
+	safeContentsCtx->currentSafeBagA1Dcx = NULL;
 	safeContentsCtx->skipCurrentSafeBag = PR_FALSE;
     } else {
 	/* we are starting a new safe bag.  we need to allocate space
 	 * for the bag and initialize the decoding context.
 	 */
 	rv = sec_pkcs12_decoder_init_new_safe_bag(safeContentsCtx);
 	if(rv != SECSuccess) {
 	    goto loser;
 	}
 
 	/* set up the decoder context */
-	safeContentsCtx->currentSafeBagDcx = SEC_ASN1DecoderStart(p12dcx->arena,
-						safeContentsCtx->currentSafeBag,
-						sec_PKCS12SafeBagTemplate);
-	if(!safeContentsCtx->currentSafeBagDcx) {
+	safeContentsCtx->currentSafeBagA1Dcx = 
+		SEC_ASN1DecoderStart(p12dcx->arena,
+				     safeContentsCtx->currentSafeBag,
+				     sec_PKCS12SafeBagTemplate);
+	if(!safeContentsCtx->currentSafeBagA1Dcx) {
 	    p12dcx->errorValue = PORT_GetError();
 	    goto loser;
 	}
 
 	/* set the notify and filter procs so that the safe bag
 	 * data gets sent to the proper location when decoding.
 	 */
-	SEC_ASN1DecoderSetNotifyProc(safeContentsCtx->currentSafeBagDcx, 
+	SEC_ASN1DecoderSetNotifyProc(safeContentsCtx->currentSafeBagA1Dcx, 
 				 sec_pkcs12_decoder_safe_bag_notify, 
 				 safeContentsCtx);
-	SEC_ASN1DecoderSetFilterProc(safeContentsCtx->safeContentsDcx, 
+	SEC_ASN1DecoderSetFilterProc(safeContentsCtx->safeContentsA1Dcx, 
 				 sec_pkcs12_decoder_safe_bag_update, 
 				 safeContentsCtx, PR_TRUE);
     }
 
     return;
 
 loser:
     /* in the event of an error, we want to close the decoding
      * context and clear the filter and notify procedures.
      */
     p12dcx->error = PR_TRUE;
 
-    if(safeContentsCtx->currentSafeBagDcx) {
-	SEC_ASN1DecoderFinish(safeContentsCtx->currentSafeBagDcx);
-	safeContentsCtx->currentSafeBagDcx = NULL;
+    if(safeContentsCtx->currentSafeBagA1Dcx) {
+	SEC_ASN1DecoderFinish(safeContentsCtx->currentSafeBagA1Dcx);
+	safeContentsCtx->currentSafeBagA1Dcx = NULL;
     }
 
-    SEC_ASN1DecoderClearNotifyProc(safeContentsCtx->safeContentsDcx);
-    SEC_ASN1DecoderClearFilterProc(safeContentsCtx->safeContentsDcx);
+    SEC_ASN1DecoderClearNotifyProc(safeContentsCtx->safeContentsA1Dcx);
+    SEC_ASN1DecoderClearFilterProc(safeContentsCtx->safeContentsA1Dcx);
 
     return;
 }
 
 /* initialize the safeContents for decoding.  this routine
  * is used for authenticatedSafes as well as nested safeContents.
  */
 static sec_PKCS12SafeContentsContext *
@@ -535,38 +532,30 @@ sec_pkcs12_decoder_safe_contents_init_de
 
     if(!p12dcx || p12dcx->error) {
 	return NULL;
     }
 
     /* allocate a new safeContents list or grow the existing list and
      * append the new safeContents onto the end.
      */
-    if(!p12dcx->safeContentsCnt) {
-	p12dcx->safeContentsList = 
-	    (sec_PKCS12SafeContentsContext**)PORT_ArenaZAlloc(p12dcx->arena, 
-	       			 2 * sizeof(sec_PKCS12SafeContentsContext *));
-    } else {
-	p12dcx->safeContentsList = 
-	   (sec_PKCS12SafeContentsContext **) PORT_ArenaGrow(p12dcx->arena,
-			p12dcx->safeContentsList,
-			(1 + p12dcx->safeContentsCnt) * 
-				sizeof(sec_PKCS12SafeContentsContext *),
-			(2 + p12dcx->safeContentsCnt) * 
-				sizeof(sec_PKCS12SafeContentsContext *));
-    }
+    p12dcx->safeContentsList = (!p12dcx->safeContentsCnt) 
+	? PORT_ArenaZNewArray(p12dcx->arena, sec_PKCS12SafeContentsContext *, 2)
+	: PORT_ArenaGrowArray(p12dcx->arena, p12dcx->safeContentsList,
+			        sec_PKCS12SafeContentsContext *,
+			        1 + p12dcx->safeContentsCnt,
+			        2 + p12dcx->safeContentsCnt);
+
     if(!p12dcx->safeContentsList) {
 	p12dcx->errorValue = PORT_GetError();
 	goto loser;
     }
 
     p12dcx->safeContentsList[p12dcx->safeContentsCnt] = safeContentsCtx = 
-        (sec_PKCS12SafeContentsContext*)PORT_ArenaZAlloc(
-					p12dcx->arena,
-					sizeof(sec_PKCS12SafeContentsContext));
+        PORT_ArenaZNew(p12dcx->arena, sec_PKCS12SafeContentsContext);
     if(!p12dcx->safeContentsList[p12dcx->safeContentsCnt]) {
 	p12dcx->errorValue = PORT_GetError();
 	goto loser;
     }
     p12dcx->safeContentsList[++p12dcx->safeContentsCnt] = NULL;
 
     /* set up the state variables */
     safeContentsCtx->p12dcx = p12dcx;
@@ -577,41 +566,41 @@ sec_pkcs12_decoder_safe_contents_init_de
      */
     if(nestedSafe == PR_TRUE) {
 	theTemplate = sec_PKCS12NestedSafeContentsDecodeTemplate;
     } else {
 	theTemplate = sec_PKCS12SafeContentsDecodeTemplate;
     }
 
     /* start the decoder context */
-    safeContentsCtx->safeContentsDcx = SEC_ASN1DecoderStart(p12dcx->arena, 
+    safeContentsCtx->safeContentsA1Dcx = SEC_ASN1DecoderStart(p12dcx->arena, 
 					&safeContentsCtx->safeContents,
 					theTemplate);
 	
-    if(!safeContentsCtx->safeContentsDcx) {
+    if(!safeContentsCtx->safeContentsA1Dcx) {
 	p12dcx->errorValue = PORT_GetError();
 	goto loser;
     }
 
     /* set the safeContents notify procedure to look for
      * and start the decode of safeBags.
      */
-    SEC_ASN1DecoderSetNotifyProc(safeContentsCtx->safeContentsDcx, 
+    SEC_ASN1DecoderSetNotifyProc(safeContentsCtx->safeContentsA1Dcx, 
 				sec_pkcs12_decoder_safe_contents_notify,
 				safeContentsCtx);
 
     return safeContentsCtx;
 
 loser:
     /* in the case of an error, we want to finish the decoder
      * context and set the error flag.
      */
-    if(safeContentsCtx && safeContentsCtx->safeContentsDcx) {
-	SEC_ASN1DecoderFinish(safeContentsCtx->safeContentsDcx);
-	safeContentsCtx->safeContentsDcx = NULL;
+    if(safeContentsCtx && safeContentsCtx->safeContentsA1Dcx) {
+	SEC_ASN1DecoderFinish(safeContentsCtx->safeContentsA1Dcx);
+	safeContentsCtx->safeContentsA1Dcx = NULL;
     }
 
     p12dcx->error = PR_TRUE;
 
     return NULL;
 }
 
 /* wrapper for updating safeContents.  this is set as the filter of
@@ -625,71 +614,74 @@ sec_pkcs12_decoder_nested_safe_contents_
     sec_PKCS12SafeContentsContext *safeContentsCtx = 
         (sec_PKCS12SafeContentsContext *)arg;
     SEC_PKCS12DecoderContext *p12dcx;
     SECStatus rv;
 
     /* check for an error */
     if(!safeContentsCtx || !safeContentsCtx->p12dcx 
 			|| safeContentsCtx->p12dcx->error
-			|| !safeContentsCtx->safeContentsDcx) {
+			|| !safeContentsCtx->safeContentsA1Dcx) {
 	return;
     }
 
     /* no need to update if no data sent in */
     if(!len || !buf) {
 	return;
     }
 
     /* update the decoding context */
     p12dcx = safeContentsCtx->p12dcx;
-    rv = SEC_ASN1DecoderUpdate(safeContentsCtx->safeContentsDcx, buf, len);
+    rv = SEC_ASN1DecoderUpdate(safeContentsCtx->safeContentsA1Dcx, buf, len);
     if(rv != SECSuccess) {
 	p12dcx->errorValue = PORT_GetError();
 	goto loser;
     }
 
     return;
 
 loser:
     /* handle any errors.  If a decoding context is open, close it. */
     p12dcx->error = PR_TRUE;
-    if(safeContentsCtx->safeContentsDcx) {
-	SEC_ASN1DecoderFinish(safeContentsCtx->safeContentsDcx);
-	safeContentsCtx->safeContentsDcx = NULL;
+    if(safeContentsCtx->safeContentsA1Dcx) {
+	SEC_ASN1DecoderFinish(safeContentsCtx->safeContentsA1Dcx);
+	safeContentsCtx->safeContentsA1Dcx = NULL;
     }
 }
 
 /* whenever a new safeContentsSafeBag is encountered, we need
  * to init a safeContentsContext.  
  */
 static SECStatus  
 sec_pkcs12_decoder_begin_nested_safe_contents(sec_PKCS12SafeContentsContext 
 							*safeContentsCtx)
 {
     /* check for an error */
     if(!safeContentsCtx || !safeContentsCtx->p12dcx || 
 		safeContentsCtx->p12dcx->error) {
 	return SECFailure;
     }
 
-    safeContentsCtx->nestedCtx = sec_pkcs12_decoder_safe_contents_init_decode(
-						safeContentsCtx->p12dcx,
-						PR_TRUE);
-    if(!safeContentsCtx->nestedCtx) {
+    safeContentsCtx->nestedSafeContentsCtx = 
+    	sec_pkcs12_decoder_safe_contents_init_decode(safeContentsCtx->p12dcx,
+						     PR_TRUE);
+    if(!safeContentsCtx->nestedSafeContentsCtx) {
 	return SECFailure;
     }
 
     /* set up new filter proc */
-    SEC_ASN1DecoderSetNotifyProc(safeContentsCtx->nestedCtx->safeContentsDcx,
+    SEC_ASN1DecoderSetNotifyProc(
+                     safeContentsCtx->nestedSafeContentsCtx->safeContentsA1Dcx,
 				 sec_pkcs12_decoder_safe_contents_notify,
-				 safeContentsCtx->nestedCtx);
-    SEC_ASN1DecoderSetFilterProc(safeContentsCtx->currentSafeBagDcx,
+				 safeContentsCtx->nestedSafeContentsCtx);
+
+    SEC_ASN1DecoderSetFilterProc(safeContentsCtx->currentSafeBagA1Dcx,
 				 sec_pkcs12_decoder_nested_safe_contents_update,
-				 safeContentsCtx->nestedCtx, PR_TRUE);
+				 safeContentsCtx->nestedSafeContentsCtx, 
+				 PR_TRUE);
 
     return SECSuccess;
 }
 
 /* when the safeContents is done decoding, we need to reset the
  * proper filter and notify procs and close the decoding context 
  */
 static SECStatus
@@ -698,21 +690,23 @@ sec_pkcs12_decoder_finish_nested_safe_co
 {
     /* check for error */
     if(!safeContentsCtx || !safeContentsCtx->p12dcx || 
 		safeContentsCtx->p12dcx->error) {
 	return SECFailure;
     }
 
     /* clean up */	
-    SEC_ASN1DecoderClearFilterProc(safeContentsCtx->currentSafeBagDcx);
-    SEC_ASN1DecoderClearNotifyProc(safeContentsCtx->nestedCtx->safeContentsDcx);
-    SEC_ASN1DecoderFinish(safeContentsCtx->nestedCtx->safeContentsDcx);
-    safeContentsCtx->nestedCtx->safeContentsDcx = NULL;
-    safeContentsCtx->nestedCtx = NULL;
+    SEC_ASN1DecoderClearFilterProc(safeContentsCtx->currentSafeBagA1Dcx);
+    SEC_ASN1DecoderClearNotifyProc(
+                    safeContentsCtx->nestedSafeContentsCtx->safeContentsA1Dcx);
+    SEC_ASN1DecoderFinish(
+                    safeContentsCtx->nestedSafeContentsCtx->safeContentsA1Dcx);
+    safeContentsCtx->nestedSafeContentsCtx->safeContentsA1Dcx = NULL;
+    safeContentsCtx->nestedSafeContentsCtx = NULL;
 
     return SECSuccess;
 }
 
 /* wrapper for updating safeContents.  This is used when decoding
  * the nested safeContents and any authenticatedSafes.
  */
 static void
@@ -722,40 +716,40 @@ sec_pkcs12_decoder_safe_contents_callbac
     SECStatus rv;
     sec_PKCS12SafeContentsContext *safeContentsCtx = 
         (sec_PKCS12SafeContentsContext *)arg;
     SEC_PKCS12DecoderContext *p12dcx;
 
     /* check for error */  
     if(!safeContentsCtx || !safeContentsCtx->p12dcx 
 		|| safeContentsCtx->p12dcx->error
-		|| !safeContentsCtx->safeContentsDcx) {
+		|| !safeContentsCtx->safeContentsA1Dcx) {
 	return;
     }
     p12dcx = safeContentsCtx->p12dcx;
 
     /* update the decoder */
-    rv = SEC_ASN1DecoderUpdate(safeContentsCtx->safeContentsDcx, buf, len);
+    rv = SEC_ASN1DecoderUpdate(safeContentsCtx->safeContentsA1Dcx, buf, len);
     if(rv != SECSuccess) {
 	/* if we fail while trying to decode a 'safe', it's probably because
 	 * we didn't have the correct password. */
 	PORT_SetError(SEC_ERROR_BAD_PASSWORD);
 	p12dcx->errorValue = SEC_ERROR_PKCS12_CORRUPT_PFX_STRUCTURE;
 	SEC_PKCS7DecoderAbort(p12dcx->currentASafeP7Dcx,SEC_ERROR_BAD_PASSWORD);
 	goto loser;
     }
 
     return;
 
 loser:
     /* set the error and finish the context */
     p12dcx->error = PR_TRUE;
-    if(safeContentsCtx->safeContentsDcx) {
-	SEC_ASN1DecoderFinish(safeContentsCtx->safeContentsDcx);
-	safeContentsCtx->safeContentsDcx = NULL;
+    if(safeContentsCtx->safeContentsA1Dcx) {
+	SEC_ASN1DecoderFinish(safeContentsCtx->safeContentsA1Dcx);
+	safeContentsCtx->safeContentsA1Dcx = NULL;
     }
 
     return;
 }
 
 /* this is a wrapper for the ASN1 decoder to call SEC_PKCS7DecoderUpdate
  */
 static void
@@ -801,30 +795,38 @@ sec_pkcs12_decoder_asafes_notify(void *a
 				safeContentsCtx, 
 				p12dcx->pwfn, p12dcx->pwfnarg,
 				sec_pkcs12_decoder_get_decrypt_key, p12dcx,
 				sec_pkcs12_decoder_decryption_allowed);
 	if(!p12dcx->currentASafeP7Dcx) {
 	    p12dcx->errorValue = PORT_GetError();
 	    goto loser;
 	}
-	SEC_ASN1DecoderSetFilterProc(p12dcx->aSafeDcx, 
+	SEC_ASN1DecoderSetFilterProc(p12dcx->aSafeA1Dcx, 
 				     sec_pkcs12_decoder_wrap_p7_update,
 				     p12dcx->currentASafeP7Dcx, PR_TRUE);
     }
 
     if(!before) {
 	/* if one is being decoded, finish the decode */
 	if(p12dcx->currentASafeP7Dcx != NULL) {
-	    if(!SEC_PKCS7DecoderFinish(p12dcx->currentASafeP7Dcx)) {
-		p12dcx->currentASafeP7Dcx = NULL;
+	    SEC_PKCS7ContentInfo * cinfo;
+	    unsigned int cnt = p12dcx->safeContentsCnt - 1;
+	    safeContentsCtx = p12dcx->safeContentsList[cnt];
+	    if (safeContentsCtx->safeContentsA1Dcx) {
+		SEC_ASN1DecoderFinish(safeContentsCtx->safeContentsA1Dcx);
+		safeContentsCtx->safeContentsA1Dcx = NULL;
+	    }
+	    cinfo = SEC_PKCS7DecoderFinish(p12dcx->currentASafeP7Dcx);
+	    p12dcx->currentASafeP7Dcx = NULL;
+	    if(!cinfo) {
 		p12dcx->errorValue = PORT_GetError();
 		goto loser;
 	    }
-	    p12dcx->currentASafeP7Dcx = NULL;
+	    SEC_PKCS7DestroyContentInfo(cinfo); /* don't leak it */
 	}
     }
 
 
     return;
 
 loser:
     /* set the error flag */
@@ -843,17 +845,17 @@ sec_pkcs12_decoder_asafes_callback(void 
     SEC_PKCS12DecoderContext *p12dcx = (SEC_PKCS12DecoderContext *)arg;
     SECStatus rv;
 
     if(!p12dcx || p12dcx->error) {
 	return;
     }
 
     /* update the context */
-    rv = SEC_ASN1DecoderUpdate(p12dcx->aSafeDcx, buf, len);
+    rv = SEC_ASN1DecoderUpdate(p12dcx->aSafeA1Dcx, buf, len);
     if(rv != SECSuccess) {
 	p12dcx->errorValue = PORT_GetError();
 	p12dcx->error = PR_TRUE;
 	goto loser;
     }
 
     /* if we are writing to a file, write out the new information */
     if(p12dcx->dWrite) {
@@ -865,42 +867,42 @@ sec_pkcs12_decoder_asafes_callback(void 
 	}
     }
 
     return;
 
 loser:
     /* set the error flag */
     p12dcx->error = PR_TRUE;
-    SEC_ASN1DecoderFinish(p12dcx->aSafeDcx);
-    p12dcx->aSafeDcx = NULL;
+    SEC_ASN1DecoderFinish(p12dcx->aSafeA1Dcx);
+    p12dcx->aSafeA1Dcx = NULL;
 
     return;
 }
    
 /* start the decode of an authenticatedSafe contentInfo.
  */ 
 static SECStatus
 sec_pkcs12_decode_start_asafes_cinfo(SEC_PKCS12DecoderContext *p12dcx)
 {
     if(!p12dcx || p12dcx->error) {
 	return SECFailure;
     }
 
     /* start the decode context */
-    p12dcx->aSafeDcx = SEC_ASN1DecoderStart(p12dcx->arena, 
+    p12dcx->aSafeA1Dcx = SEC_ASN1DecoderStart(p12dcx->arena, 
     					&p12dcx->authSafe,
     					sec_PKCS12AuthenticatedSafeTemplate);
-    if(!p12dcx->aSafeDcx) {
+    if(!p12dcx->aSafeA1Dcx) {
 	p12dcx->errorValue = PORT_GetError();
    	goto loser;
     }
 
     /* set the notify function */
-    SEC_ASN1DecoderSetNotifyProc(p12dcx->aSafeDcx,
+    SEC_ASN1DecoderSetNotifyProc(p12dcx->aSafeA1Dcx,
     				 sec_pkcs12_decoder_asafes_notify, p12dcx);
 
     /* begin the authSafe decoder context */
     p12dcx->aSafeP7Dcx = SEC_PKCS7DecoderStart(
     				sec_pkcs12_decoder_asafes_callback, p12dcx,
     				p12dcx->pwfn, p12dcx->pwfnarg, NULL, NULL, NULL);
     if(!p12dcx->aSafeP7Dcx) {
 	p12dcx->errorValue = PORT_GetError();
@@ -914,19 +916,19 @@ sec_pkcs12_decode_start_asafes_cinfo(SEC
 	goto loser;
     }
 
     return SECSuccess;
 
 loser:
     p12dcx->error = PR_TRUE;
 
-    if(p12dcx->aSafeDcx) {
-	SEC_ASN1DecoderFinish(p12dcx->aSafeDcx);
-	p12dcx->aSafeDcx = NULL;
+    if(p12dcx->aSafeA1Dcx) {
+	SEC_ASN1DecoderFinish(p12dcx->aSafeA1Dcx);
+	p12dcx->aSafeA1Dcx = NULL;
     } 
 
     if(p12dcx->aSafeP7Dcx) {
 	SEC_PKCS7DecoderFinish(p12dcx->aSafeP7Dcx);
 	p12dcx->aSafeP7Dcx = NULL;
     }
 
     return SECFailure;
@@ -979,18 +981,18 @@ sec_pkcs12_decoder_pfx_notify_proc(void 
 {
     SECStatus rv;
     SEC_PKCS12DecoderContext *p12dcx = (SEC_PKCS12DecoderContext*)arg;
 
     /* if an error occurs, clear the notifyProc and the filterProc 
      * and continue. 
      */
     if(p12dcx->error) {
-	SEC_ASN1DecoderClearNotifyProc(p12dcx->pfxDcx);
-	SEC_ASN1DecoderClearFilterProc(p12dcx->pfxDcx);
+	SEC_ASN1DecoderClearNotifyProc(p12dcx->pfxA1Dcx);
+	SEC_ASN1DecoderClearFilterProc(p12dcx->pfxA1Dcx);
 	return;
     }
 
     if(before && (dest == &p12dcx->pfx.encodedAuthSafe)) {
 
 	/* we want to make sure this is a version we support */
 	if(!sec_pkcs12_proper_version(&p12dcx->pfx)) {
 	    p12dcx->errorValue = SEC_ERROR_PKCS12_UNSUPPORTED_VERSION;
@@ -999,34 +1001,34 @@ sec_pkcs12_decoder_pfx_notify_proc(void 
 
 	/* start the decode of the aSafes cinfo... */
 	rv = sec_pkcs12_decode_start_asafes_cinfo(p12dcx);
 	if(rv != SECSuccess) {
 	    goto loser;
 	}
 
 	/* set the filter proc to update the authenticated safes. */
-	SEC_ASN1DecoderSetFilterProc(p12dcx->pfxDcx,
+	SEC_ASN1DecoderSetFilterProc(p12dcx->pfxA1Dcx,
 				     sec_pkcs12_decode_asafes_cinfo_update,
 				     p12dcx, PR_TRUE);
     }
 
     if(!before && (dest == &p12dcx->pfx.encodedAuthSafe)) {
 
 	/* we are done decoding the authenticatedSafes, so we need to 
 	 * finish the decoderContext and clear the filter proc
 	 * and close the hmac callback, if present
 	 */
 	p12dcx->aSafeCinfo = SEC_PKCS7DecoderFinish(p12dcx->aSafeP7Dcx);
 	p12dcx->aSafeP7Dcx = NULL;
 	if(!p12dcx->aSafeCinfo) {
 	    p12dcx->errorValue = PORT_GetError();
 	    goto loser;
 	}
-	SEC_ASN1DecoderClearFilterProc(p12dcx->pfxDcx);
+	SEC_ASN1DecoderClearFilterProc(p12dcx->pfxA1Dcx);
 	if(p12dcx->dClose && ((*p12dcx->dClose)(p12dcx->dArg, PR_FALSE) 
 				!= SECSuccess)) {
 	    p12dcx->errorValue = PORT_GetError();
 	    goto loser;
 	}
 
     }
 
@@ -1180,17 +1182,17 @@ SEC_PKCS12DecoderStart(SECItem *pwitem, 
     PRArenaPool *arena;
 
     arena = PORT_NewArena(2048); /* different size? */
     if(!arena) {
 	return NULL;	/* error is already set */
     }
 
     /* allocate the decoder context and set the state variables */
-    p12dcx = (SEC_PKCS12DecoderContext*)PORT_ArenaZAlloc(arena, sizeof(SEC_PKCS12DecoderContext));
+    p12dcx = PORT_ArenaZNew(arena, SEC_PKCS12DecoderContext);
     if(!p12dcx) {
 	goto loser;	/* error is already set */
     }
 
     if (!dOpen && !dClose && !dRead && !dWrite && !dArg) {
         /* use default implementations */
         dOpen = p12u_DigestOpen;
         dClose = p12u_DigestClose;
@@ -1211,24 +1213,24 @@ SEC_PKCS12DecoderStart(SECItem *pwitem, 
     p12dcx->swapUnicodeBytes = PR_FALSE;
 #endif
     p12dcx->errorValue = 0;
     p12dcx->error = PR_FALSE;
 
     /* start the decoding of the PFX and set the notify proc
      * for the PFX item.
      */
-    p12dcx->pfxDcx = SEC_ASN1DecoderStart(p12dcx->arena, &p12dcx->pfx,
+    p12dcx->pfxA1Dcx = SEC_ASN1DecoderStart(p12dcx->arena, &p12dcx->pfx,
     					  sec_PKCS12PFXItemTemplate);
-    if(!p12dcx->pfxDcx) {
+    if(!p12dcx->pfxA1Dcx) {
 	PK11_FreeSlot(p12dcx->slot);
 	goto loser;
     }
 
-    SEC_ASN1DecoderSetNotifyProc(p12dcx->pfxDcx, 
+    SEC_ASN1DecoderSetNotifyProc(p12dcx->pfxA1Dcx, 
 				 sec_pkcs12_decoder_pfx_notify_proc,
     				 p12dcx); 
     
     /* set up digest functions */
     p12dcx->dOpen = dOpen;
     p12dcx->dWrite = dWrite;
     p12dcx->dClose = dClose;
     p12dcx->dRead = dRead;
@@ -1275,17 +1277,17 @@ SEC_PKCS12DecoderUpdate(SEC_PKCS12Decode
     SECStatus rv;
 
     if(!p12dcx || p12dcx->error) {
 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
 	return SECFailure;
     }
 
     /* update the PFX decoder context */
-    rv = SEC_ASN1DecoderUpdate(p12dcx->pfxDcx, (const char *)data, len);
+    rv = SEC_ASN1DecoderUpdate(p12dcx->pfxA1Dcx, (const char *)data, len);
     if(rv != SECSuccess) {
 	p12dcx->errorValue = SEC_ERROR_PKCS12_CORRUPT_PFX_STRUCTURE;
 	goto loser;
     }
 
     return SECSuccess;
 
 loser:
@@ -1377,17 +1379,17 @@ sec_pkcs12_decoder_verify_mac(SEC_PKCS12
     if(p12dcx->dOpen && ((*p12dcx->dOpen)(p12dcx->dArg, PR_TRUE) 
 			!= SECSuccess)) {
 	goto loser;
     }
 
     /* read the data back IN_BUF_LEN bytes at a time and recompute
      * the hmac.  if fewer bytes are read than are requested, it is
      * assumed that the end of file has been reached. if bytesRead
-     * is returned as -1, then an error occured reading from the 
+     * is returned as -1, then an error occurred reading from the 
      * file.
      */
     do {
 	bytesRead = (*p12dcx->dRead)(p12dcx->dArg, buf, IN_BUF_LEN);
 	if (bytesRead < 0) {
 	    PORT_SetError(SEC_ERROR_PKCS12_UNABLE_TO_READ);
 	    goto loser;
 	}
@@ -1452,95 +1454,125 @@ loser:
  *
  * 	p12dcx - the decoder context 
  */
 SECStatus
 SEC_PKCS12DecoderVerify(SEC_PKCS12DecoderContext *p12dcx)
 {
     SECStatus rv = SECSuccess;
 
-    /* make sure that no errors have occured... */
+    /* make sure that no errors have occurred... */
     if(!p12dcx) {
 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
 	return SECFailure;
     }
     if(p12dcx->error) {
 	/* error code is already set! PORT_SetError(p12dcx->errorValue); */
 	return SECFailure;
     }
 
-    rv = SEC_ASN1DecoderFinish(p12dcx->pfxDcx);
-    p12dcx->pfxDcx = NULL;
+    rv = SEC_ASN1DecoderFinish(p12dcx->pfxA1Dcx);
+    p12dcx->pfxA1Dcx = NULL;
     if(rv != SECSuccess) {
 	return rv;
     }
 
     /* check the signature or the mac depending on the type of
      * integrity used.
      */
     if(p12dcx->pfx.encodedMacData.len) {
 	rv = SEC_ASN1DecodeItem(p12dcx->arena, &p12dcx->macData,
 				sec_PKCS12MacDataTemplate,
 				&p12dcx->pfx.encodedMacData);
 	if(rv == SECSuccess) {
 	    return sec_pkcs12_decoder_verify_mac(p12dcx);
 	}
-    } else {
-	if(SEC_PKCS7VerifySignature(p12dcx->aSafeCinfo, certUsageEmailSigner,
-				    PR_FALSE)) {
-	    return SECSuccess;
-	} else {
-	    PORT_SetError(SEC_ERROR_PKCS12_INVALID_MAC);
-	}
-    }
-
+	return rv;
+    } 
+    if (SEC_PKCS7VerifySignature(p12dcx->aSafeCinfo, certUsageEmailSigner, 
+                                 PR_FALSE)) {
+	return SECSuccess;
+    } 
+    PORT_SetError(SEC_ERROR_PKCS12_INVALID_MAC);
     return SECFailure;
 }
 
 /* SEC_PKCS12DecoderFinish
  *	Free any open ASN1 or PKCS7 decoder contexts and then
  *	free the arena pool which everything should be allocated
  *	from.  This function should be called upon completion of
  *	decoding and installing of a pfx pdu.  This should be
  *	called even if an error occurs.
  *
  *	p12dcx - the decoder context
  */
 void
 SEC_PKCS12DecoderFinish(SEC_PKCS12DecoderContext *p12dcx)
 {
+    unsigned int i;
+
     if(!p12dcx) {
 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
 	return;
     }
 
-    if(p12dcx->pfxDcx) {
-	SEC_ASN1DecoderFinish(p12dcx->pfxDcx);
-	p12dcx->pfxDcx = NULL;
+    if(p12dcx->pfxA1Dcx) {
+	SEC_ASN1DecoderFinish(p12dcx->pfxA1Dcx);
+	p12dcx->pfxA1Dcx = NULL;
+    }
+
+    if(p12dcx->aSafeA1Dcx) {
+	SEC_ASN1DecoderFinish(p12dcx->aSafeA1Dcx);
+	p12dcx->aSafeA1Dcx = NULL;
     }
 
-    if(p12dcx->aSafeDcx) {
-	SEC_ASN1DecoderFinish(p12dcx->aSafeDcx);
-	p12dcx->aSafeDcx = NULL;
+    /* cleanup any old ASN1 decoder contexts */
+    for (i = 0; i < p12dcx->safeContentsCnt; ++i) {
+	sec_PKCS12SafeContentsContext *safeContentsCtx, *nested;
+	safeContentsCtx = p12dcx->safeContentsList[i];
+	if (safeContentsCtx) {
+	    nested = safeContentsCtx->nestedSafeContentsCtx;
+	    while (nested) {
+		if (nested->safeContentsA1Dcx) {
+		    SEC_ASN1DecoderFinish(nested->safeContentsA1Dcx);
+		    nested->safeContentsA1Dcx = NULL;
+		}
+		nested = nested->nestedSafeContentsCtx;
+	    }
+	    if (safeContentsCtx->safeContentsA1Dcx) {
+		SEC_ASN1DecoderFinish(safeContentsCtx->safeContentsA1Dcx);
+		safeContentsCtx->safeContentsA1Dcx = NULL;
+	    }
+	}
     }
 
-    if(p12dcx->currentASafeP7Dcx) {
-	SEC_PKCS7DecoderFinish(p12dcx->currentASafeP7Dcx);
-	p12dcx->currentASafeP7Dcx = NULL;
+    if (p12dcx->currentASafeP7Dcx &&
+	p12dcx->currentASafeP7Dcx != p12dcx->aSafeP7Dcx) {
+	SEC_PKCS7ContentInfo * cinfo;
+	cinfo = SEC_PKCS7DecoderFinish(p12dcx->currentASafeP7Dcx);
+	if (cinfo) {
+	    SEC_PKCS7DestroyContentInfo(cinfo); /* don't leak it */
+	}
     }
+    p12dcx->currentASafeP7Dcx = NULL;
 
     if(p12dcx->aSafeP7Dcx) {
-	SEC_PKCS7DecoderFinish(p12dcx->aSafeP7Dcx);
+	SEC_PKCS7ContentInfo * cinfo;
+	cinfo = SEC_PKCS7DecoderFinish(p12dcx->aSafeP7Dcx);
+	if (cinfo) {
+	    SEC_PKCS7DestroyContentInfo(cinfo);
+	}
+	p12dcx->aSafeP7Dcx = NULL;
     }
 
-    if(p12dcx->hmacDcx) {
-	SEC_ASN1DecoderFinish(p12dcx->hmacDcx);
-	p12dcx->hmacDcx = NULL;
+    if(p12dcx->aSafeCinfo) {
+	SEC_PKCS7DestroyContentInfo(p12dcx->aSafeCinfo);
+	p12dcx->aSafeCinfo = NULL;
     }
-    
+
     if (p12dcx->decitem.type != 0 && p12dcx->decitem.der != NULL) {
         SECITEM_FreeItem(p12dcx->decitem.der, PR_TRUE);
     }
     if (p12dcx->decitem.friendlyName != NULL) {
         SECITEM_FreeItem(p12dcx->decitem.friendlyName, PR_TRUE);
     }
 
     if(p12dcx->slot) {
@@ -1567,73 +1599,62 @@ sec_pkcs12_decoder_set_attribute_value(s
     }
 
     oid = SECOID_FindOIDByTag(attributeType);
     if(!oid) {
 	return SECFailure;
     }
 
     if(!bag->attribs) {
-	bag->attribs = (sec_PKCS12Attribute**)PORT_ArenaZAlloc(bag->arena, 
-					sizeof(sec_PKCS12Attribute *) * 2);
+	bag->attribs = 
+		PORT_ArenaZNewArray(bag->arena, sec_PKCS12Attribute *, 2);
     } else {
-	while(bag->attribs[i]) i++;
-	bag->attribs = (sec_PKCS12Attribute **)PORT_ArenaGrow(bag->arena, 
-				      bag->attribs, 
-				      (i + 1) * sizeof(sec_PKCS12Attribute *),
-				      (i + 2) * sizeof(sec_PKCS12Attribute *));
+	while(bag->attribs[i]) 
+	    i++;
+	bag->attribs = PORT_ArenaGrowArray(bag->arena, bag->attribs, 
+				           sec_PKCS12Attribute *, i + 1, i + 2);
     }
 
     if(!bag->attribs) {
 	return SECFailure;
     }
 
-    bag->attribs[i] = (sec_PKCS12Attribute*)PORT_ArenaZAlloc(bag->arena, 
-						  sizeof(sec_PKCS12Attribute));
+    bag->attribs[i] = PORT_ArenaZNew(bag->arena, sec_PKCS12Attribute);
     if(!bag->attribs) {
 	return SECFailure;
     }
 
-    bag->attribs[i]->attrValue = (SECItem**)PORT_ArenaZAlloc(bag->arena, 
-						  sizeof(SECItem *) * 2);
+    bag->attribs[i]->attrValue = PORT_ArenaZNewArray(bag->arena, SECItem *, 2);
     if(!bag->attribs[i]->attrValue) {
 	return SECFailure;
     }
 
     bag->attribs[i+1] = NULL;
     bag->attribs[i]->attrValue[0] = attrValue;
     bag->attribs[i]->attrValue[1] = NULL;
 
-    if(SECITEM_CopyItem(bag->arena, &bag->attribs[i]->attrType, &oid->oid)
-			!= SECSuccess) {
-	return SECFailure;
-    }
-
-    return SECSuccess;
+    return SECITEM_CopyItem(bag->arena, &bag->attribs[i]->attrType, &oid->oid);
 }
 
 static SECItem *
 sec_pkcs12_get_attribute_value(sec_PKCS12SafeBag *bag,
 			       SECOidTag attributeType)
 {
-    int i = 0;
+    int i;
 
     if(!bag->attribs) {
 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
 	return NULL;
     }
 
-    while(bag->attribs[i] != NULL) {
-	if(SECOID_FindOIDTag(&bag->attribs[i]->attrType) 
-			== attributeType) {
+    for (i = 0; bag->attribs[i] != NULL; i++) {
+	if (SECOID_FindOIDTag(&bag->attribs[i]->attrType) == attributeType) {
 	    return bag->attribs[i]->attrValue[0];
 	}
-	i++;
     }
-
     return NULL;
 }
 
 /* For now, this function will merely remove any ":"
  * in the nickname which the PK11 functions may have
  * placed there.  This will keep dual certs from appearing
  * twice under "Your" certificates when imported onto smart
  * cards.  Once with the name "Slot:Cert" and another with
@@ -1676,17 +1697,21 @@ sec_pkcs12_get_nickname(sec_PKCS12SafeBa
     SECItem *src, *dest;
 
     if(!bag) {
 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
 	return NULL;
     }
 
     src = sec_pkcs12_get_attribute_value(bag, SEC_OID_PKCS9_FRIENDLY_NAME);
-    if(!src) {
+
+    /* The return value src is 16-bit Unicode characters, in big-endian format.
+     * Check if it is NULL or empty name.
+     */
+    if(!src || !src->data || src->len < 2 || (!src->data[0] && !src->data[1])) {
 	return NULL;
     }
 
     dest = (SECItem*)PORT_ZAlloc(sizeof(SECItem));
     if(!dest) { 
 	goto loser;
     }
     if(!sec_pkcs12_convert_item_to_unicode(NULL, dest, src, PR_FALSE, 
@@ -1706,91 +1731,83 @@ loser:
     bag->problem = PR_TRUE;
     bag->error = PORT_GetError();
     return NULL;
 }
 
 static SECStatus
 sec_pkcs12_set_nickname(sec_PKCS12SafeBag *bag, SECItem *name)
 {
-    int i = 0;
     sec_PKCS12Attribute *attr = NULL;
     SECOidData *oid = SECOID_FindOIDByTag(SEC_OID_PKCS9_FRIENDLY_NAME);
 
     if(!bag || !bag->arena || !name) {
 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
 	return SECFailure;
     }
 	
     if(!bag->attribs) {
 	if(!oid) {
 	    goto loser;
 	}
 
-	bag->attribs = (sec_PKCS12Attribute**)PORT_ArenaZAlloc(bag->arena, 
-					     sizeof(sec_PKCS12Attribute *)*2);
+	bag->attribs = 
+	    PORT_ArenaZNewArray(bag->arena, sec_PKCS12Attribute *, 2);
 	if(!bag->attribs) {
 	    goto loser;
 	}
-	bag->attribs[0] = (sec_PKCS12Attribute*)PORT_ArenaZAlloc(bag->arena, 
-						  sizeof(sec_PKCS12Attribute));
+	bag->attribs[0] = PORT_ArenaZNew(bag->arena, sec_PKCS12Attribute);
 	if(!bag->attribs[0]) {
 	    goto loser;
 	}
 	bag->attribs[1] = NULL;
 
 	attr = bag->attribs[0];
 	if(SECITEM_CopyItem(bag->arena, &attr->attrType, &oid->oid) 
 			!= SECSuccess) {
 	    goto loser;
 	}
     } else {
-	while(bag->attribs[i]) {
+	int i;
+	for (i = 0; bag->attribs[i]; i++) {
 	    if(SECOID_FindOIDTag(&bag->attribs[i]->attrType)
 			== SEC_OID_PKCS9_FRIENDLY_NAME) {
 		attr = bag->attribs[i];
 		break;
 	    }
-	    i++;
 	}
 	if(!attr) {
 	    if(!oid) {
 		goto loser;
 	    }
-	    bag->attribs = (sec_PKCS12Attribute **)PORT_ArenaGrow(bag->arena, 
-								  bag->attribs,
-					(i+1) * sizeof(sec_PKCS12Attribute *),
-					(i+2) * sizeof(sec_PKCS12Attribute *));
+	    bag->attribs = PORT_ArenaGrowArray(bag->arena, bag->attribs,
+					       sec_PKCS12Attribute *, i+1, i+2);
 	    if(!bag->attribs) {
 		goto loser;
 	    }
-	    bag->attribs[i] = 
-	        (sec_PKCS12Attribute *)PORT_ArenaZAlloc(bag->arena, 
-						  sizeof(sec_PKCS12Attribute));
+	    bag->attribs[i] = PORT_ArenaZNew(bag->arena, sec_PKCS12Attribute);
 	    if(!bag->attribs[i]) {
 		goto loser;
 	    }
 	    bag->attribs[i+1] = NULL;
 	    attr = bag->attribs[i];
 	    if(SECITEM_CopyItem(bag->arena, &attr->attrType, &oid->oid) 
 				!= SECSuccess) {
 		goto loser;
 	    }
 	}
     }
 
     PORT_Assert(attr);
     if(!attr->attrValue) {
-	attr->attrValue = (SECItem **)PORT_ArenaZAlloc(bag->arena, 
-						       sizeof(SECItem *) * 2);
+	attr->attrValue = PORT_ArenaZNewArray(bag->arena, SECItem *, 2);
 	if(!attr->attrValue) {
 	    goto loser;
 	}
-	attr->attrValue[0] = (SECItem*)PORT_ArenaZAlloc(bag->arena, 
-							sizeof(SECItem));
+	attr->attrValue[0] = PORT_ArenaZNew(bag->arena, SECItem);
 	if(!attr->attrValue[0]) {
 	    goto loser;
 	}
 	attr->attrValue[1] = NULL;
     }
 
     name->len = PORT_Strlen((char *)name->data);
     if(!sec_pkcs12_convert_item_to_unicode(bag->arena, attr->attrValue[0],
@@ -1985,32 +2002,28 @@ gatherNicknames(CERTCertificate *cert, v
 	    if(SECITEM_CompareItem(nickArg->nickList[i], &tempNick) 
 				== SECEqual) {
 		return SECSuccess;
 	    }
 	}
     }
 
     /* add the nickname to the list */
-    if(nickArg->nNicks == 0) {
-	nickArg->nickList = (SECItem **)PORT_ArenaZAlloc(nickArg->arena, 
-					     2 * sizeof(SECItem *));
-    } else {
-	nickArg->nickList = (SECItem **)PORT_ArenaGrow(nickArg->arena,
-				nickArg->nickList, 
-				(nickArg->nNicks + 1) * sizeof(SECItem *),
-				(nickArg->nNicks + 2) * sizeof(SECItem *));
-    }
+    nickArg->nickList = (nickArg->nNicks == 0) 
+	? PORT_ArenaZNewArray(nickArg->arena, SECItem *, 2)
+	: PORT_ArenaGrowArray(nickArg->arena, nickArg->nickList, SECItem *, 
+	                      nickArg->nNicks + 1, nickArg->nNicks + 2);
+
     if(!nickArg->nickList) {
 	nickArg->error = SEC_ERROR_NO_MEMORY;
 	return SECFailure;
     }
 
     nickArg->nickList[nickArg->nNicks] = 
-        (SECItem *)PORT_ArenaZAlloc(nickArg->arena, sizeof(SECItem));
+				    PORT_ArenaZNew(nickArg->arena, SECItem);
     if(!nickArg->nickList[nickArg->nNicks]) {
 	nickArg->error = PORT_GetError();
 	return SECFailure;
     }
     
 
     if(SECITEM_CopyItem(nickArg->arena, nickArg->nickList[nickArg->nNicks],
 			&tempNick) != SECSuccess) {
@@ -2051,18 +2064,17 @@ sec_pkcs12_get_existing_nick_for_dn(sec_
 	goto loser;
     }
 
     arena = PORT_NewArena(1024);
     if(!arena) {
 	returnDn = NULL;
 	goto loser;
     }
-    nickArg = (struct certNickInfo *)PORT_ArenaZAlloc(arena, 
-						 sizeof(struct certNickInfo));
+    nickArg = PORT_ArenaZNew(arena, struct certNickInfo);
     if(!nickArg) {
 	returnDn = NULL;
 	goto loser;
     }
     nickArg->error = 0;
     nickArg->nNicks = 0;
     nickArg->nickList = NULL;
     nickArg->arena = arena;
@@ -2508,25 +2520,22 @@ sec_pkcs12_add_item_to_bag_list(sec_PKCS
     int i = 0;
 
     if(!bagList || !bag) {
 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
 	return SECFailure;
     }
 
     if(!(*bagList)) {
-	newBagList = (sec_PKCS12SafeBag **)PORT_ArenaZAlloc(bag->arena, 
-				      sizeof(sec_PKCS12SafeBag *) * 2);
+	newBagList = PORT_ArenaZNewArray(bag->arena, sec_PKCS12SafeBag *, 2);
     } else {
 	while((*bagList)[i]) 
 	    i++;
-	newBagList = (sec_PKCS12SafeBag **)PORT_ArenaGrow(bag->arena, 
-	                        *bagList,
-				sizeof(sec_PKCS12SafeBag *) * (i + 1),
-				sizeof(sec_PKCS12SafeBag *) * (i + 2));
+	newBagList = PORT_ArenaGrowArray(bag->arena, *bagList,
+				         sec_PKCS12SafeBag *, i + 1, i + 2);
     }
 
     if(!newBagList) {
 	PORT_SetError(SEC_ERROR_NO_MEMORY);
 	return SECFailure;
     }
 
     newBagList[i]   = bag;
@@ -3137,25 +3146,21 @@ static SECStatus
 sec_pkcs12_decoder_append_bag_to_context(SEC_PKCS12DecoderContext *p12dcx,
 					 sec_PKCS12SafeBag *bag)
 {
     if(!p12dcx || p12dcx->error) {
 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
 	return SECFailure;
     }
 
-    if(!p12dcx->safeBagCount) {
-	p12dcx->safeBags = (sec_PKCS12SafeBag **)PORT_ArenaZAlloc(p12dcx->arena, 
-					    sizeof(sec_PKCS12SafeBag *) * 2);
-    } else {
-	p12dcx->safeBags = 
-	  (sec_PKCS12SafeBag **)PORT_ArenaGrow(p12dcx->arena, p12dcx->safeBags,
-		     (p12dcx->safeBagCount + 1) * sizeof(sec_PKCS12SafeBag *),
-		     (p12dcx->safeBagCount + 2) * sizeof(sec_PKCS12SafeBag *));
-    }
+    p12dcx->safeBags = !p12dcx->safeBagCount 
+	? PORT_ArenaZNewArray(p12dcx->arena, sec_PKCS12SafeBag *, 2)
+	: PORT_ArenaGrowArray(p12dcx->arena, p12dcx->safeBags, 
+	                      sec_PKCS12SafeBag *, p12dcx->safeBagCount + 1, 
+			      p12dcx->safeBagCount + 2);
 
     if(!p12dcx->safeBags) {
 	PORT_SetError(SEC_ERROR_NO_MEMORY);
 	return SECFailure;
     }
 
     p12dcx->safeBags[p12dcx->safeBagCount] = bag;
     p12dcx->safeBags[p12dcx->safeBagCount+1] = NULL;
@@ -3173,19 +3178,18 @@ sec_pkcs12_decoder_convert_old_key(SEC_P
     SECOidTag keyTag;
     SECItem *keyID, *nickName, *newNickName;
 
     if(!p12dcx || p12dcx->error || !key) {
 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
 	return NULL;
     }
 
-    newNickName =(SECItem *)PORT_ArenaZAlloc(p12dcx->arena, sizeof(SECItem));
-    keyBag = (sec_PKCS12SafeBag *)PORT_ArenaZAlloc(p12dcx->arena, 
-						   sizeof(sec_PKCS12SafeBag));
+    newNickName = PORT_ArenaZNew(p12dcx->arena, SECItem);
+    keyBag      = PORT_ArenaZNew(p12dcx->arena, sec_PKCS12SafeBag);
     if(!keyBag || !newNickName) {
 	return NULL;
     }
 
     keyBag->swapUnicodeBytes = p12dcx->swapUnicodeBytes;
     keyBag->slot = p12dcx->slot;
     keyBag->arena = p12dcx->arena;
     keyBag->pwitem = p12dcx->pwitem;
@@ -3275,17 +3279,17 @@ sec_pkcs12_decoder_create_cert(SEC_PKCS1
     SECItem *keyId;
     SECStatus rv;
 
     if(!p12dcx || p12dcx->error || !derCert) {
 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
 	return NULL;
     }
 
-    keyId = (SECItem *)PORT_ArenaZAlloc(p12dcx->arena, sizeof(SECItem));
+    keyId = PORT_ArenaZNew(p12dcx->arena, SECItem);
     if(!keyId) {
 	return NULL;
     }
 
     digest = sec_pkcs12_compute_thumbprint(derCert);
     if(!digest) {
 	return NULL;
     }
@@ -3293,33 +3297,31 @@ sec_pkcs12_decoder_create_cert(SEC_PKCS1
     rv = SECITEM_CopyItem(p12dcx->arena, keyId, &digest->digest);
     SGN_DestroyDigestInfo(digest);
     if(rv != SECSuccess) {
 	PORT_SetError(SEC_ERROR_NO_MEMORY);
 	return NULL;
     }
 
     oid = SECOID_FindOIDByTag(SEC_OID_PKCS12_V1_CERT_BAG_ID);
-    certBag = (sec_PKCS12SafeBag *)PORT_ArenaZAlloc(p12dcx->arena, 
-						    sizeof(sec_PKCS12SafeBag));
+    certBag = PORT_ArenaZNew(p12dcx->arena, sec_PKCS12SafeBag);
     if(!certBag || !oid || (SECITEM_CopyItem(p12dcx->arena, 
 			&certBag->safeBagType, &oid->oid) != SECSuccess)) {
 	return NULL;
     }
 
     certBag->slot = p12dcx->slot;
     certBag->pwitem = p12dcx->pwitem;
     certBag->swapUnicodeBytes = p12dcx->swapUnicodeBytes;
     certBag->arena = p12dcx->arena;
     certBag->tokenCAs = p12dcx->tokenCAs;
 
     oid = SECOID_FindOIDByTag(SEC_OID_PKCS9_X509_CERT);
     certBag->safeBagContent.certBag = 
-        (sec_PKCS12CertBag *)PORT_ArenaZAlloc(p12dcx->arena, 
-					      sizeof(sec_PKCS12CertBag));
+			PORT_ArenaZNew(p12dcx->arena, sec_PKCS12CertBag);
     if(!certBag->safeBagContent.certBag || !oid ||
 			(SECITEM_CopyItem(p12dcx->arena, 
 				 &certBag->safeBagContent.certBag->bagID,
 				 &oid->oid) != SECSuccess)) {
 	return NULL;
     }
       
     if(SECITEM_CopyItem(p12dcx->arena, 
@@ -3352,18 +3354,17 @@ sec_pkcs12_decoder_convert_old_cert(SEC_
     derCertList = SEC_PKCS7GetCertificateList(&oldCert->value.x509->certOrCRL);
     if(!derCertList) {
 	return NULL;
     }
 
     i = 0;
     while(derCertList[i]) i++;
 
-    certList = (sec_PKCS12SafeBag **)PORT_ArenaZAlloc(p12dcx->arena, 
-				(i + 1) * sizeof(sec_PKCS12SafeBag *));
+    certList = PORT_ArenaZNewArray(p12dcx->arena, sec_PKCS12SafeBag *, (i + 1));
     if(!certList) {
 	return NULL;
     }
 
     for(j = 0; j < i; j++) {
 	certList[j] = sec_pkcs12_decoder_create_cert(p12dcx, derCertList[j]);
 	if(!certList[j]) {
 	    return NULL;
@@ -3526,18 +3527,17 @@ sec_PKCS12ConvertOldSafeToNew(PRArenaPoo
 	return NULL;
     }
 
     if(!safe && !baggage) {
 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
 	return NULL;
     }
 
-    p12dcx = (SEC_PKCS12DecoderContext *)PORT_ArenaZAlloc(arena, 
-					    sizeof(SEC_PKCS12DecoderContext));
+    p12dcx = PORT_ArenaZNew(arena, SEC_PKCS12DecoderContext);
     if(!p12dcx) {
 	return NULL;
     }
 
     p12dcx->arena = arena;
     p12dcx->slot = PK11_ReferenceSlot(slot);
     p12dcx->wincx = wincx;
     p12dcx->error = PR_FALSE;
--- a/security/nss/lib/pkcs12/p12dec.c
+++ b/security/nss/lib/pkcs12/p12dec.c
@@ -291,17 +291,17 @@ sec_pkcs12_convert_old_auth_safe(SEC_PKC
 	    nEspvk++;
 	}
     }
 
     return rv;
 }    
 
 /* decodes the authenticated safe item.  a return of NULL indicates
- * an error.  however, the error will have occured either in memory
+ * an error.  however, the error will have occurred either in memory
  * allocation or in decoding the authenticated safe.
  *
  * if an old PFX item has been found, we want to convert the
  * old authenticated safe to the new one.
  */
 static SEC_PKCS12AuthenticatedSafe *
 sec_pkcs12_decode_authenticated_safe(SEC_PKCS12PFXItem *pfx) 
 {
@@ -455,17 +455,17 @@ sec_pkcs12_validate_auth_safe(SEC_PKCS12
     }
 
     return valid;
 }
 
 /* retrieves the authenticated safe item from the PFX item
  *  before returning the authenticated safe, the validity of the
  *  authenticated safe is checked and if valid, returned.
- * a return of NULL indicates that an error occured.
+ * a return of NULL indicates that an error occurred.
  */
 static SEC_PKCS12AuthenticatedSafe *
 sec_pkcs12_get_auth_safe(SEC_PKCS12PFXItem *pfx)
 {
     SEC_PKCS12AuthenticatedSafe *asafe;
     PRBool valid_safe;
 
     if(pfx == NULL) {
--- a/security/nss/lib/pkcs7/p7common.c
+++ b/security/nss/lib/pkcs7/p7common.c
@@ -33,17 +33,17 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 /*
  * PKCS7 implementation -- the exported parts that are used whether
  * creating or decoding.
  *
- * $Id: p7common.c,v 1.7 2008/02/03 06:08:48 nelson%bolyard.com Exp $
+ * $Id: p7common.c,v 1.8 2010/04/04 20:50:52 nelson%bolyard.com Exp $
  */
 
 #include "p7local.h"
 
 #include "cert.h"
 #include "secitem.h"
 #include "secoid.h"
 #include "pk11func.h"
@@ -336,16 +336,17 @@ SEC_PKCS7SetContent(SEC_PKCS7ContentInfo
 		    const char *buf, 
 		    unsigned long len)
 {
     SECOidTag cinfo_type;
     SECStatus rv;
     SECItem content;
     SECOidData *contentTypeTag = NULL;
 
+    content.type = siBuffer;
     content.data = (unsigned char *)buf;
     content.len = len;
 
     cinfo_type = SEC_PKCS7ContentType(cinfo);
 
     /* set inner content */
     switch(cinfo_type)
     {
--- a/security/nss/lib/pkcs7/p7local.c
+++ b/security/nss/lib/pkcs7/p7local.c
@@ -35,17 +35,17 @@
  * ***** END LICENSE BLOCK ***** */
 
 /*
  * Support routines for PKCS7 implementation, none of which are exported.
  * This file should only contain things that are needed by both the
  * encoding/creation side *and* the decoding/decryption side.  Anything
  * else should be static routines in the appropriate file.
  *
- * $Id: p7local.c,v 1.13 2008/05/30 03:39:46 nelson%bolyard.com Exp $
+ * $Id: p7local.c,v 1.14 2010/03/15 07:25:14 nelson%bolyard.com Exp $
  */
 
 #include "p7local.h"
 
 #include "cryptohi.h" 
 #include "secasn1.h"
 #include "secoid.h"
 #include "secitem.h"
@@ -99,18 +99,18 @@ SEC_ASN1_MKSUB(SEC_SetOfAnyTemplate)
  */
 sec_PKCS7CipherObject *
 sec_PKCS7CreateDecryptObject (PK11SymKey *key, SECAlgorithmID *algid)
 {
     sec_PKCS7CipherObject *result;
     SECOidTag algtag;
     void *ciphercx;
     CK_MECHANISM_TYPE cryptoMechType;
-    SECItem *param;
     PK11SlotInfo *slot;
+    SECItem *param = NULL;
 
     result = (struct sec_pkcs7_cipher_object*)
       PORT_ZAlloc (sizeof(struct sec_pkcs7_cipher_object));
     if (result == NULL)
 	return NULL;
 
     ciphercx = NULL;
     algtag = SECOID_GetAlgorithmTag (algid);
@@ -122,16 +122,17 @@ sec_PKCS7CreateDecryptObject (PK11SymKey
 	if (!pwitem) {
 	    PORT_Free(result);
 	    return NULL;
 	}
 
 	cryptoMechType = PK11_GetPBECryptoMechanism(algid, &param, pwitem);
 	if (cryptoMechType == CKM_INVALID_MECHANISM) {
 	    PORT_Free(result);
+	    SECITEM_FreeItem(param,PR_TRUE);
 	    return NULL;
 	}
     } else {
 	cryptoMechType = PK11_AlgtagToMechanism(algtag);
 	param = PK11_ParamFromAlgid(algid);
 	if (param == NULL) {
 	    PORT_Free(result);
 	    return NULL;
@@ -173,21 +174,21 @@ sec_PKCS7CreateDecryptObject (PK11SymKey
  * have two simple cover functions which call it. 
  */
 sec_PKCS7CipherObject *
 sec_PKCS7CreateEncryptObject (PRArenaPool *poolp, PK11SymKey *key,
 			      SECOidTag algtag, SECAlgorithmID *algid)
 {
     sec_PKCS7CipherObject *result;
     void *ciphercx;
-    SECItem *param;
     SECStatus rv;
     CK_MECHANISM_TYPE cryptoMechType;
+    PK11SlotInfo *slot;
+    SECItem *param = NULL;
     PRBool needToEncodeAlgid = PR_FALSE;
-    PK11SlotInfo *slot;
 
     result = (struct sec_pkcs7_cipher_object*)
 	      PORT_ZAlloc (sizeof(struct sec_pkcs7_cipher_object));
     if (result == NULL)
 	return NULL;
 
     ciphercx = NULL;
     if (SEC_PKCS5IsAlgorithmPBEAlg(algid)) {
@@ -197,16 +198,17 @@ sec_PKCS7CreateEncryptObject (PRArenaPoo
 	if (!pwitem) {
 	    PORT_Free(result);
 	    return NULL;
 	}
 
 	cryptoMechType = PK11_GetPBECryptoMechanism(algid, &param, pwitem);
 	if (cryptoMechType == CKM_INVALID_MECHANISM) {
 	    PORT_Free(result);
+	    SECITEM_FreeItem(param,PR_TRUE);
 	    return NULL;
 	}
     } else {
 	cryptoMechType = PK11_AlgtagToMechanism(algtag);
 	param = PK11_GenerateNewParam(cryptoMechType, key);
 	if (param == NULL) {
 	    PORT_Free(result);
 	    return NULL;
--- a/security/nss/lib/pki/certificate.c
+++ b/security/nss/lib/pki/certificate.c
@@ -30,17 +30,17 @@
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifdef DEBUG
-static const char CVS_ID[] = "@(#) $RCSfile: certificate.c,v $ $Revision: 1.66 $ $Date: 2009/02/09 07:51:27 $";
+static const char CVS_ID[] = "@(#) $RCSfile: certificate.c,v $ $Revision: 1.67 $ $Date: 2010/04/03 18:27:32 $";
 #endif /* DEBUG */
 
 #ifndef NSSPKI_H
 #include "nsspki.h"
 #endif /* NSSPKI_H */
 
 #ifndef PKIT_H
 #include "pkit.h"
@@ -138,17 +138,17 @@ nssCertificate_Destroy (
 	PR_ASSERT(c->object.refCount > 0);
 
 	/* --- LOCK storage --- */
 	if (cc) {
 	    nssCertificateStore_Lock(cc->certStore, &lockTrace);
 	} else {
 	    nssTrustDomain_LockCertCache(td);
 	}
-	if (PR_AtomicDecrement(&c->object.refCount) == 0) {
+	if (PR_ATOMIC_DECREMENT(&c->object.refCount) == 0) {
 	    /* --- remove cert and UNLOCK storage --- */
 	    if (cc) {
 		nssCertificateStore_RemoveCertLOCKED(cc->certStore, c);
 		nssCertificateStore_Unlock(cc->certStore, &lockTrace,
                                            &unlockTrace);
 	    } else {
 		nssTrustDomain_RemoveCertFromCacheLOCKED(td, c);
 		nssTrustDomain_UnlockCertCache(td);
--- a/security/nss/lib/pki/cryptocontext.c
+++ b/security/nss/lib/pki/cryptocontext.c
@@ -30,33 +30,31 @@
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifdef DEBUG
-static const char CVS_ID[] = "@(#) $RCSfile: cryptocontext.c,v $ $Revision: 1.18 $ $Date: 2007/11/16 05:29:27 $";
+static const char CVS_ID[] = "@(#) $RCSfile: cryptocontext.c,v $ $Revision: 1.19 $ $Date: 2010/05/21 00:02:48 $";
 #endif /* DEBUG */
 
 #ifndef DEV_H
 #include "dev.h"
 #endif /* DEV_H */
 
 #ifndef PKIM_H
 #include "pkim.h"
 #endif /* PKIM_H */
 
 #ifndef PKISTORE_H
 #include "pkistore.h"
 #endif /* PKISTORE_H */
 
-#include "pki1t.h"
-
 extern const NSSError NSS_ERROR_NOT_FOUND;
 extern const NSSError NSS_ERROR_INVALID_ARGUMENT;
 
 NSS_IMPLEMENT NSSCryptoContext *
 nssCryptoContext_Create (
   NSSTrustDomain *td,
   NSSCallback *uhhOpt
 )
--- a/security/nss/lib/pki/nsspki.h
+++ b/security/nss/lib/pki/nsspki.h
@@ -33,37 +33,33 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef NSSPKI_H
 #define NSSPKI_H
 
 #ifdef DEBUG
-static const char NSSPKI_CVS_ID[] = "@(#) $RCSfile: nsspki.h,v $ $Revision: 1.12 $ $Date: 2007/07/11 04:47:42 $";
+static const char NSSPKI_CVS_ID[] = "@(#) $RCSfile: nsspki.h,v $ $Revision: 1.13 $ $Date: 2010/05/21 00:02:48 $";
 #endif /* DEBUG */
 
 /*
  * nsspki.h
  *
  * This file prototypes the methods of the top-level PKI objects.
  */
 
 #ifndef NSSDEVT_H
 #include "nssdevt.h"
 #endif /* NSSDEVT_H */
 
 #ifndef NSSPKIT_H
 #include "nsspkit.h"
 #endif /* NSSPKIT_H */
 
-#ifndef NSSPKI1_H
-#include "nsspki1.h"
-#endif /* NSSPKI1_H */
-
 #ifndef BASE_H
 #include "base.h"
 #endif /* BASE_H */
 
 PR_BEGIN_EXTERN_C
 
 /*
  * A note about interfaces
--- a/security/nss/lib/pki/nsspkit.h
+++ b/security/nss/lib/pki/nsspkit.h
@@ -33,17 +33,17 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef NSSPKIT_H
 #define NSSPKIT_H
 
 #ifdef DEBUG
-static const char NSSPKIT_CVS_ID[] = "@(#) $RCSfile: nsspkit.h,v $ $Revision: 1.6 $ $Date: 2005/01/20 02:25:49 $";
+static const char NSSPKIT_CVS_ID[] = "@(#) $RCSfile: nsspkit.h,v $ $Revision: 1.8 $ $Date: 2010/05/21 00:02:48 $";
 #endif /* DEBUG */
 
 /*
  * nsspkit.h
  *
  * This file defines the types of the top-level PKI objects.
  */
 
@@ -77,17 +77,17 @@ typedef struct NSSCertificateStr NSSCert
  * A ``User'' certificate is one for which the private key is available.
  * People speak of "using my certificate to sign my email" and "using
  * my certificate to authenticate to (or login to) the server"; for
  * simple operations, we support that simplification by implementing
  * private-key crypto operations as methods on this type.
  *
  * The current design only weakly distinguishes between certificates
  * and user certificates: as far as the compiler goes they're 
- * interchangable; debug libraries only have one common pointer-tracker;
+ * interchangeable; debug libraries only have one common pointer-tracker;
  * etc.  However, attempts to do private-key operations on a certificate
  * for which the private key is not available will fail.
  *
  * Open design question: should these types be more firmly separated?
  */
 
 typedef NSSCertificate NSSUserCertificate;
 
@@ -164,16 +164,25 @@ typedef struct NSSTrustDomainStr NSSTrus
  */
 
 typedef struct NSSCryptoContextStr NSSCryptoContext;
 
 /*
  * fgmr others
  */
 
+/*
+ * OBJECT IDENTIFIER
+ *
+ * This is the basic OID that crops up everywhere.
+ */
+
+struct NSSOIDStr;  /* unused opaque structure */
+typedef struct NSSOIDStr NSSOID;
+
 /* 
  * NSSTime
  *
  * Unfortunately, we need an "exceptional" value to indicate
  * an error upon return, or "no value" on input.  Note that zero
  * is a perfectly valid value for both time_t and PRTime.
  *
  * If we were to create a "range" object, with two times for
--- a/security/nss/lib/pki/pki3hack.c
+++ b/security/nss/lib/pki/pki3hack.c
@@ -30,17 +30,17 @@
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifdef DEBUG
-static const char CVS_ID[] = "@(#) $RCSfile: pki3hack.c,v $ $Revision: 1.98 $ $Date: 2009/10/01 17:14:02 $";
+static const char CVS_ID[] = "@(#) $RCSfile: pki3hack.c,v $ $Revision: 1.100 $ $Date: 2010/05/18 19:38:40 $";
 #endif /* DEBUG */
 
 /*
  * Hacks to integrate NSS 3.4 and NSS 4.0 certificates.
  */
 
 #ifndef NSSPKI_H
 #include "nsspki.h"
@@ -104,17 +104,17 @@ STAN_InitTokenForSlotInfo(NSSTrustDomain
 	if (!td) {
 	    /* we're called while still initting. slot will get added
 	     * appropriately through normal init processes */
 	    return PR_SUCCESS;
 	}
     }
     token = nssToken_CreateFromPK11SlotInfo(td, slot);
     PK11Slot_SetNSSToken(slot, token);
-    /* Don't add non-existent token to TD's token list */
+    /* Don't add nonexistent token to TD's token list */
     if (token) {
 	NSSRWLock_LockWrite(td->tokensLock);
 	nssList_Add(td->tokenList, token);
 	NSSRWLock_UnlockWrite(td->tokensLock);
     }
     return PR_SUCCESS;
 }
 
@@ -812,17 +812,17 @@ fill_CERTCertificateFields(NSSCertificat
     /* pointer back */
     cc->nssCertificate = c;
     if (trust) {
 	/* force the cert type to be recomputed to include trust info */
 	PRUint32 nsCertType = cert_ComputeCertType(cc);
 
 	/* Assert that it is safe to cast &cc->nsCertType to "PRInt32 *" */
 	PORT_Assert(sizeof(cc->nsCertType) == sizeof(PRInt32));
-	PR_AtomicSet((PRInt32 *)&cc->nsCertType, nsCertType);
+	PR_ATOMIC_SET((PRInt32 *)&cc->nsCertType, nsCertType);
     }
 }
 
 static CERTCertificate *
 stan_GetCERTCertificate(NSSCertificate *c, PRBool forceUpdate)
 {
     nssDecodedCert *dc = NULL;
     CERTCertificate *cc = NULL;
--- a/security/nss/lib/pki/pkibase.c
+++ b/security/nss/lib/pki/pkibase.c
@@ -30,17 +30,17 @@
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifdef DEBUG
-static const char CVS_ID[] = "@(#) $RCSfile: pkibase.c,v $ $Revision: 1.31 $ $Date: 2009/04/17 19:28:07 $";
+static const char CVS_ID[] = "@(#) $RCSfile: pkibase.c,v $ $Revision: 1.33 $ $Date: 2010/04/03 18:27:32 $";
 #endif /* DEBUG */
 
 #ifndef DEV_H
 #include "dev.h"
 #endif /* DEV_H */
 
 #ifndef PKIM_H
 #include "pkim.h"
@@ -147,17 +147,17 @@ nssPKIObject_Create (
     if (PR_SUCCESS != nssPKIObject_NewLock(object, lockType)) {
 	goto loser;
     }
     if (instanceOpt) {
 	if (nssPKIObject_AddInstance(object, instanceOpt) != PR_SUCCESS) {
 	    goto loser;
 	}
     }
-    PR_AtomicIncrement(&object->refCount);
+    PR_ATOMIC_INCREMENT(&object->refCount);
     if (mark) {
 	nssArena_Unmark(arena, mark);
     }
     return object;
 loser:
     if (mark) {
 	nssArena_Release(arena, mark);
     } else {
@@ -168,33 +168,33 @@ loser:
 
 NSS_IMPLEMENT PRBool
 nssPKIObject_Destroy (
   nssPKIObject *object
 )
 {
     PRUint32 i;
     PR_ASSERT(object->refCount > 0);
-    if (PR_AtomicDecrement(&object->refCount) == 0) {
+    if (PR_ATOMIC_DECREMENT(&object->refCount) == 0) {
 	for (i=0; i<object->numInstances; i++) {
 	    nssCryptokiObject_Destroy(object->instances[i]);
 	}
 	nssPKIObject_DestroyLock(object);
 	nssArena_Destroy(object->arena);
 	return PR_TRUE;
     }
     return PR_FALSE;
 }
 
 NSS_IMPLEMENT nssPKIObject *
 nssPKIObject_AddRef (
   nssPKIObject *object
 )
 {
-    PR_AtomicIncrement(&object->refCount);
+    PR_ATOMIC_INCREMENT(&object->refCount);
     return object;
 }
 
 NSS_IMPLEMENT PRStatus
 nssPKIObject_AddInstance (
   nssPKIObject *object,
   nssCryptokiObject *instance
 )
@@ -505,16 +505,21 @@ nssCertificateArray_FindBestCertificate 
 		haveUsageMatch = PR_TRUE;
 		continue;
 	    }
 	    /* this cert match as well as any cert we've found so far, 
 	     * defer to time/policies 
 	     * */
 	}
 	bestdc = nssCertificate_GetDecoding(bestCert);
+	if (!bestdc) {
+	    nssCertificate_Destroy(bestCert);
+	    bestCert = nssCertificate_AddRef(c);
+	    continue;
+	}
 	/* time */
 	if (bestdc->isValidAtTime(bestdc, time)) {
 	    /* The current best cert is valid at time */
 	    if (!dc->isValidAtTime(dc, time)) {
 		/* If the new cert isn't valid at time, it's not better */
 		continue;
 	    }
 	} else {
@@ -1242,17 +1247,19 @@ NSSTime_Now (
 NSS_IMPLEMENT NSSTime *
 NSSTime_SetPRTime (
   NSSTime *timeOpt,
   PRTime prTime
 )
 {
     NSSTime *rvTime;
     rvTime = (timeOpt) ? timeOpt : nss_ZNEW(NULL, NSSTime);
-    rvTime->prTime = prTime;
+    if (rvTime) {
+        rvTime->prTime = prTime;
+    }
     return rvTime;
 }
 
 NSS_IMPLEMENT PRTime
 NSSTime_GetPRTime (
   NSSTime *time
 )
 {
--- a/security/nss/lib/pki/trustdomain.c
+++ b/security/nss/lib/pki/trustdomain.c
@@ -30,31 +30,27 @@
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifdef DEBUG
-static const char CVS_ID[] = "@(#) $RCSfile: trustdomain.c,v $ $Revision: 1.61 $ $Date: 2010/02/10 02:04:32 $";
+static const char CVS_ID[] = "@(#) $RCSfile: trustdomain.c,v $ $Revision: 1.62 $ $Date: 2010/05/21 00:02:48 $";
 #endif /* DEBUG */
 
 #ifndef DEV_H
 #include "dev.h"
 #endif /* DEV_H */
 
 #ifndef PKIM_H
 #include "pkim.h"
 #endif /* PKIM_H */
 
-#ifndef PKI1T_H
-#include "pki1t.h"
-#endif /* PKI1T_H */
-
 #include "cert.h"
 #include "pki3hack.h"
 #include "pk11pub.h"
 #include "nssrwlk.h"
 
 #define NSSTRUSTDOMAIN_DEFAULT_CACHE_SIZE 32
 
 extern const NSSError NSS_ERROR_NOT_FOUND;
deleted file mode 100644
--- a/security/nss/lib/pki1/Makefile
+++ /dev/null
@@ -1,50 +0,0 @@
-# 
-# ***** BEGIN LICENSE BLOCK *****
-# Version: MPL 1.1/GPL 2.0/LGPL 2.1
-#
-# The contents of this file are subject to the Mozilla Public License Version
-# 1.1 (the "License"); you may not use this file except in compliance with
-# the License. You may obtain a copy of the License at
-# http://www.mozilla.org/MPL/
-#
-# Software distributed under the License is distributed on an "AS IS" basis,
-# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
-# for the specific language governing rights and limitations under the
-# License.
-#
-# The Original Code is the Netscape security libraries.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1994-2000
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#
-# Alternatively, the contents of this file may be used under the terms of
-# either the GNU General Public License Version 2 or later (the "GPL"), or
-# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
-# in which case the provisions of the GPL or the LGPL are applicable instead
-# of those above. If you wish to allow use of your version of this file only
-# under the terms of either the GPL or the LGPL, and not to allow others to
-# use your version of this file under the terms of the MPL, indicate your
-# decision by deleting the provisions above and replace them with the notice
-# and other provisions required by the GPL or the LGPL. If you do not delete
-# the provisions above, a recipient may use your version of this file under
-# the terms of any one of the MPL, the GPL or the LGPL.
-#
-# ***** END LICENSE BLOCK *****
-MAKEFILE_CVS_ID = "@(#) $RCSfile: Makefile,v $ $Revision: 1.10 $ $Date: 2007/05/09 00:09:36 $"
-
-include manifest.mn
-include $(CORE_DEPTH)/coreconf/config.mk
-include config.mk
-include $(CORE_DEPTH)/coreconf/rules.mk
-
-# Generate oiddata.h and oiddata.c.
-oidgen: oidgen.perl oids.txt
-	rm -f oiddata.c oiddata.h
-	$(PERL) oidgen.perl oiddata.c oiddata.h oids.txt
-
-export::  private_export 
-
deleted file mode 100644
--- a/security/nss/lib/pki1/atav.c
+++ /dev/null
@@ -1,1824 +0,0 @@
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is the Netscape security libraries.
- *
- * The Initial Developer of the Original Code is
- * Netscape Communications Corporation.
- * Portions created by the Initial Developer are Copyright (C) 1994-2000
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-#ifdef DEBUG
-static const char CVS_ID[] = "@(#) $RCSfile: atav.c,v $ $Revision: 1.8 $ $Date: 2005/01/20 02:25:49 $";
-#endif /* DEBUG */
-
-/*
- * atav.c
- *
- * This file contains the implementation of the PKIX part-1 object
- * AttributeTypeAndValue.
- */
-
-#ifndef NSSBASE_H
-#include "nssbase.h"
-#endif /* NSSBASE_H */
-
-#ifndef ASN1_H
-#include "asn1.h"
-#endif /* ASN1_H */
-
-#ifndef PKI1_H
-#include "pki1.h"
-#endif /* PKI1_H */
-
-/*
- * AttributeTypeAndValue
- *
- * From draft-ietf-pkix-ipki-part1-10:
- *
- *  AttributeTypeAndValue           ::=     SEQUENCE {
- *          type            ATTRIBUTE.&id ({SupportedAttributes}),
- *          value   ATTRIBUTE.&Type ({SupportedAttributes}{@type})}
- *  
- *  -- ATTRIBUTE information object class specification
- *  --  Note: This has been greatly simplified for PKIX !!
- *  
- *  ATTRIBUTE               ::=     CLASS {
- *          &Type,
- *          &id                     OBJECT IDENTIFIER UNIQUE }
- *  WITH SYNTAX {
- *          WITH SYNTAX &Type ID &id }
- *  
- * What this means is that the "type" of the value is determined by
- * the value of the oid.  If we hide the structure, our accessors
- * can (at least in debug builds) assert value semantics beyond what
- * the compiler can provide.  Since these things are only used in
- * RelativeDistinguishedNames, and since RDNs always contain a SET
- * of these things, we don't lose anything by hiding the structure
- * (and its size).
- */
-
-struct NSSATAVStr {
-  NSSBER ber;
-  const NSSOID *oid;
-  NSSUTF8 *value;
-  nssStringType stringForm;
-};
-
-/*
- * NSSATAV
- *
- * The public "methods" regarding this "object" are:
- *
- *  NSSATAV_CreateFromBER   -- constructor
- *  NSSATAV_CreateFromUTF8  -- constructor
- *  NSSATAV_Create          -- constructor
- *
- *  NSSATAV_Destroy
- *  NSSATAV_GetDEREncoding
- *  NSSATAV_GetUTF8Encoding
- *  NSSATAV_GetType
- *  NSSATAV_GetValue
- *  NSSATAV_Compare
- *  NSSATAV_Duplicate
- *
- * The non-public "methods" regarding this "object" are:
- *
- *  nssATAV_CreateFromBER   -- constructor
- *  nssATAV_CreateFromUTF8  -- constructor
- *  nssATAV_Create          -- constructor
- *
- *  nssATAV_Destroy
- *  nssATAV_GetDEREncoding
- *  nssATAV_GetUTF8Encoding
- *  nssATAV_GetType
- *  nssATAV_GetValue
- *  nssATAV_Compare
- *  nssATAV_Duplicate
- *
- * In debug builds, the following non-public call is also available:
- *
- *  nssATAV_verifyPointer
- */
-
-/*
- * NSSATAV_CreateFromBER
- * 
- * This routine creates an NSSATAV by decoding a BER- or DER-encoded
- * ATAV.  If the optional arena argument is non-null, the memory used 
- * will be obtained from that arena; otherwise, the memory will be 
- * obtained from the heap.  This routine may return NULL upon error, 
- * in which case it will have created an error stack.
- *
- * The error may be one of the following values:
- *  NSS_ERROR_INVALID_BER
- *  NSS_ERROR_NO_MEMORY
- *
- * Return value:
- *  NULL upon error
- *  A pointer to an NSSATAV upon success
- */
-
-NSS_IMPLEMENT NSSATAV *
-NSSATAV_CreateFromBER
-(
-  NSSArena *arenaOpt,
-  NSSBER *berATAV
-)
-{
-  nss_ClearErrorStack();
-
-#ifdef DEBUG
-  if( (NSSArena *)NULL != arenaOpt ) {
-    if( PR_SUCCESS != nssArena_verifyPointer(arenaOpt) ) {
-      return (NSSATAV *)NULL;
-    }
-  }
-
-  /* 
-   * NSSBERs can be created by the user, 
-   * so no pointer-tracking can be checked.
-   */
-
-  if( (NSSBER *)NULL == berATAV ) {
-    nss_SetError(NSS_ERROR_INVALID_BER);
-    return (NSSATAV *)NULL;
-  }
-
-  if( (void *)NULL == berATAV->data ) {
-    nss_SetError(NSS_ERROR_INVALID_BER);
-    return (NSSATAV *)NULL;
-  }
-#endif /* DEBUG */
-
-  return nssATAV_CreateFromBER(arenaOpt, berATAV);
-}
-
-/*
- * NSSATAV_CreateFromUTF8
- *
- * This routine creates an NSSATAV by decoding a UTF8 string in the
- * "equals" format, e.g., "c=US."  If the optional arena argument is 
- * non-null, the memory used will be obtained from that arena; 
- * otherwise, the memory will be obtained from the heap.  This routine
- * may return NULL upon error, in which case it will have created an
- * error stack.
- *
- * The error may be one of the following values:
- *  NSS_ERROR_UNKNOWN_ATTRIBUTE
- *  NSS_ERROR_INVALID_STRING
- *  NSS_ERROR_NO_MEMORY
- *
- * Return value:
- *  NULL upon error
- *  A pointer to an NSSATAV upon success
- */
-
-NSS_IMPLEMENT NSSATAV *
-NSSATAV_CreateFromUTF8
-(
-  NSSArena *arenaOpt,
-  NSSUTF8 *stringATAV
-)
-{
-  nss_ClearErrorStack();
-
-#ifdef DEBUG
-  if( (NSSArena *)NULL != arenaOpt ) {
-    if( PR_SUCCESS != nssArena_verifyPointer(arenaOpt) ) {
-      return (NSSATAV *)NULL;
-    }
-  }
-
-  /*
-   * NSSUTF8s can be created by the user,
-   * so no pointer-tracking can be checked.
-   */
-
-  if( (NSSUTF8 *)NULL == stringATAV ) {
-    nss_SetError(NSS_ERROR_INVALID_UTF8);
-    return (NSSATAV *)NULL;
-  }
-#endif /* DEBUG */
-
-  return nssATAV_CreateFromUTF8(arenaOpt, stringATAV);
-}
-
-/*
- * NSSATAV_Create
- *
- * This routine creates an NSSATAV from the specified NSSOID and the
- * specified data. If the optional arena argument is non-null, the 
- * memory used will be obtained from that arena; otherwise, the memory
- * will be obtained from the heap.If the specified data length is zero, 
- * the data is assumed to be terminated by first zero byte; this allows 
- * UTF8 strings to be easily specified.  This routine may return NULL 
- * upon error, in which case it will have created an error stack.
- *
- * The error may be one of the following values:
- *  NSS_ERROR_INVALID_ARENA
- *  NSS_ERROR_INVALID_NSSOID
- *  NSS_ERROR_INVALID_POINTER
- *  NSS_ERROR_NO_MEMORY
- *
- * Return value:
- *  NULL upon error
- *  A pointer to an NSSATAV upon success
- */
-
-NSS_IMPLEMENT NSSATAV *
-NSSATAV_Create
-(
-  NSSArena *arenaOpt,
-  const NSSOID *oid,
-  const void *data,
-  PRUint32 length
-)
-{
-  nss_ClearErrorStack();
-
-#ifdef DEBUG
-  if( (NSSArena *)NULL != arenaOpt ) {
-    if( PR_SUCCESS != nssArena_verifyPointer(arenaOpt) ) {
-      return (NSSATAV *)NULL;
-    }
-  }
-
-  if( PR_SUCCESS != nssOID_verifyPointer(oid) ) {
-    return (NSSATAV *)NULL;
-  }
-
-  if( (const void *)NULL == data ) {
-    nss_SetError(NSS_ERROR_INVALID_POINTER);
-    return (NSSATAV *)NULL;
-  }
-#endif /* DEBUG */
-
-  return nssATAV_Create(arenaOpt, oid, data, length);
-}
-
-/*
- * NSSATAV_Destroy
- *
- * This routine will destroy an ATAV object.  It should eventually be
- * called on all ATAVs created without an arena.  While it is not 
- * necessary to call it on ATAVs created within an arena, it is not an
- * error to do so.  This routine returns a PRStatus value; if
- * successful, it will return PR_SUCCESS.  If unsuccessful, it will
- * create an error stack and return PR_FAILURE.
- *
- * The error may be one of the following values:
- *  NSS_ERROR_INVALID_ATAV
- *  
- * Return value:
- *  PR_FAILURE upon error
- *  PR_SUCCESS upon success
- */
-
-NSS_IMPLEMENT PRStatus
-NSSATAV_Destroy
-(
-  NSSATAV *atav
-)
-{
-  nss_ClearErrorStack();
-
-#ifdef DEBUG
-  if( PR_SUCCESS != nssATAV_verifyPointer(atav) ) {
-    return PR_FAILURE;
-  }
-#endif /* DEBUG */
-
-  return nssATAV_Destroy(atav);
-}
-
-/*
- * NSSATAV_GetDEREncoding
- *
- * This routine will DER-encode an ATAV object. If the optional arena
- * argument is non-null, the memory used will be obtained from that
- * arena; otherwise, the memory will be obtained from the heap.  This
- * routine may return null upon error, in which case it will have 
- * created an error stack.
- *
- * The error may be one of the following values:
- *  NSS_ERROR_INVALID_ATAV
- *  NSS_ERROR_NO_MEMORY
- *
- * Return value:
- *  NULL upon error
- *  The DER encoding of this NSSATAV
- */
-
-NSS_IMPLEMENT NSSDER *
-NSSATAV_GetDEREncoding
-(
-  NSSATAV *atav,
-  NSSArena *arenaOpt
-)
-{
-  nss_ClearErrorStack();
-
-#ifdef DEBUG
-  if( PR_SUCCESS != nssATAV_verifyPointer(atav) ) {
-    return (NSSDER *)NULL;
-  }
-
-  if( (NSSArena *)NULL != arenaOpt ) {
-    if( PR_SUCCESS != nssArena_verifyPointer(arenaOpt) ) {
-      return (NSSDER *)NULL;
-    }
-  }
-#endif /* DEBUG */
-
-  return nssATAV_GetDEREncoding(atav, arenaOpt);
-}
-
-/*
- * NSSATAV_GetUTF8Encoding
- *
- * This routine returns a UTF8 string containing a string 
- * representation of the ATAV in "equals" notation (e.g., "o=Acme").  
- * If the optional arena argument is non-null, the memory used will be
- * obtained from that arena; otherwise, the memory will be obtained 
- * from the heap.  This routine may return null upon error, in which 
- * case it will have created an error stack.
- *
- * The error may be one of the following values:
- *  NSS_ERROR_INVALID_ATAV
- *  NSS_ERROR_NO_MEMORY
- *
- * Return value:
- *  NULL upon error
- *  A pointer to a UTF8 string containing the "equals" encoding of the 
- *      ATAV
- */
-
-NSS_IMPLEMENT NSSUTF8 *
-NSSATAV_GetUTF8Encoding
-(
-  NSSATAV *atav,
-  NSSArena *arenaOpt
-)
-{
-  nss_ClearErrorStack();
-
-#ifdef DEBUG
-  if( PR_SUCCESS != nssATAV_verifyPointer(atav) ) {
-    return (NSSUTF8 *)NULL;
-  }
-
-  if( (NSSArena *)NULL != arenaOpt ) {
-    if( PR_SUCCESS != nssArena_verifyPointer(arenaOpt) ) {
-      return (NSSUTF8 *)NULL;
-    }
-  }
-#endif /* DEBUG */
-
-  return nssATAV_GetUTF8Encoding(atav, arenaOpt);
-}
-
-/*
- * NSSATAV_GetType
- *
- * This routine returns the NSSOID corresponding to the attribute type
- * in the specified ATAV.  This routine may return NSS_OID_UNKNOWN 
- * upon error, in which case it will have created an error stack.
- *
- * The error may be one of the following values:
- *  NSS_ERROR_INVALID_ATAV
- *
- * Return value:
- *  NSS_OID_UNKNOWN upon error
- *  An element of enum NSSOIDenum upon success
- */
-
-NSS_IMPLEMENT const NSSOID *
-NSSATAV_GetType
-(
-  NSSATAV *atav
-)
-{
-  nss_ClearErrorStack();
-
-#ifdef DEBUG
-  if( PR_SUCCESS != nssATAV_verifyPointer(atav) ) {
-    return (NSSOID *)NULL;
-  }
-#endif /* DEBUG */
-
-  return nssATAV_GetType(atav);
-}
-
-/*
- * NSSATAV_GetValue
- *
- * This routine returns a string containing the attribute value
- * in the specified ATAV.  If the optional arena argument is non-null,
- * the memory used will be obtained from that arena; otherwise, the
- * memory will be obtained from the heap.  This routine may return
- * NULL upon error, in which case it will have created an error stack.
- *
- * The error may be one of the following values:
- *  NSS_ERROR_INVALID_ATAV
- *  NSS_ERROR_NO_MEMORY
- *
- * Return value:
- *  NULL upon error
- *  A pointer to an NSSItem containing the attribute value.
- */
-
-NSS_IMPLEMENT NSSUTF8 *
-NSSATAV_GetValue
-(
-  NSSATAV *atav,
-  NSSArena *arenaOpt
-)
-{
-  nss_ClearErrorStack();
-
-#ifdef DEBUG
-  if( PR_SUCCESS != nssATAV_verifyPointer(atav) ) {
-    return (NSSUTF8 *)NULL;
-  }
-
-  if( (NSSArena *)NULL != arenaOpt ) {
-    if( PR_SUCCESS != nssArena_verifyPointer(arenaOpt) ) {
-      return (NSSUTF8 *)NULL;
-    }
-  }
-#endif /* DEBUG */
-
-  return nssATAV_GetValue(atav, arenaOpt);
-}
-
-/*
- * NSSATAV_Compare
- *
- * This routine compares two ATAVs for equality.  For two ATAVs to be
- * equal, the attribute types must be the same, and the attribute 
- * values must have equal length and contents.  The result of the 
- * comparison will be stored at the location pointed to by the "equalp"
- * variable, which must point to a valid PRBool.  This routine may 
- * return PR_FAILURE upon error, in which case it will have created an
- * error stack.
- *
- * The error may be one of the following values:
- *  NSS_ERROR_INVALID_ATAV
- *  NSS_ERROR_INVALID_ARGUMENT
- *
- * Return value:
- *  PR_FAILURE on error
- *  PR_SUCCESS upon a successful comparison (equal or not)
- */
-
-NSS_IMPLEMENT PRStatus
-NSSATAV_Compare
-(
-  NSSATAV *atav1,
-  NSSATAV *atav2,
-  PRBool *equalp
-)
-{
-  nss_ClearErrorStack();
-
-#ifdef DEBUG
-  if( PR_SUCCESS != nssATAV_verifyPointer(atav1) ) {
-    return PR_FAILURE;
-  }
-
-  if( PR_SUCCESS != nssATAV_verifyPointer(atav2) ) {
-    return PR_FAILURE;
-  }
-
-  if( (PRBool *)NULL == equalp ) {
-    nss_SetError(NSS_ERROR_INVALID_ARGUMENT);
-    return PR_FAILURE;
-  }
-#endif /* DEBUG */
-
-  return nssATAV_Compare(atav1, atav2, equalp);
-}
-
-/*
- * NSSATAV_Duplicate
- *
- * This routine duplicates the specified ATAV.  If the optional arena 
- * argument is non-null, the memory required will be obtained from
- * that arena; otherwise, the memory will be obtained from the heap.  
- * This routine may return NULL upon error, in which case it will have 
- * created an error stack.
- *
- * The error may be one of the following values:
- *  NSS_ERROR_INVALID_ATAV
- *  NSS_ERROR_NO_MEMORY
- *
- * Return value:
- *  NULL on error
- *  A pointer to a new ATAV
- */
-
-NSS_IMPLEMENT NSSATAV *
-NSSATAV_Duplicate
-(
-  NSSATAV *atav,
-  NSSArena *arenaOpt
-)
-{
-  nss_ClearErrorStack();
-
-#ifdef DEBUG
-  if( PR_SUCCESS != nssATAV_verifyPointer(atav) ) {
-    return (NSSATAV *)NULL;
-  }
-
-  if( (NSSArena *)NULL != arenaOpt ) {
-    if( PR_SUCCESS != nssArena_verifyPointer(arenaOpt) ) {
-      return (NSSATAV *)NULL;
-    }
-  }
-#endif /* DEBUG */
-
-  return nssATAV_Duplicate(atav, arenaOpt);
-}
-
-/*
- * The pointer-tracking code
- */
-
-#ifdef DEBUG
-extern const NSSError NSS_ERROR_INTERNAL_ERROR;
-
-static nssPointerTracker atav_pointer_tracker;
-
-static PRStatus
-atav_add_pointer
-(
-  const NSSATAV *atav
-)
-{
-  PRStatus rv;
-
-  rv = nssPointerTracker_initialize(&atav_pointer_tracker);
-  if( PR_SUCCESS != rv ) {
-    return rv;
-  }
-
-  rv = nssPointerTracker_add(&atav_pointer_tracker, atav);
-  if( PR_SUCCESS != rv ) {
-    NSSError e = NSS_GetError();
-    if( NSS_ERROR_NO_MEMORY != e ) {
-      nss_SetError(NSS_ERROR_INTERNAL_ERROR);
-    }
-
-    return rv;
-  }
-
-  return PR_SUCCESS;
-}
-
-static PRStatus
-atav_remove_pointer
-(
-  const NSSATAV *atav
-)
-{
-  PRStatus rv;
-
-  rv = nssPointerTracker_remove(&atav_pointer_tracker, atav);
-  if( PR_SUCCESS != rv ) {
-    nss_SetError(NSS_ERROR_INTERNAL_ERROR);
-  }
-
-  return rv;
-}
-
-/*
- * nssATAV_verifyPointer
- *
- * This method is only present in debug builds.
- *
- * If the specified pointer is a valid pointer to an NSSATAV object,
- * this routine will return PR_SUCCESS.  Otherwise, it will put an
- * error on the error stack and return PR_FAILRUE.
- *
- * The error may be one of the following values:
- *  NSS_ERROR_INVALID_NSSATAV
- *  NSS_ERROR_NO_MEMORY
- *
- * Return value:
- *  PR_SUCCESS if the pointer is valid
- *  PR_FAILURE if it isn't
- */
-
-NSS_IMPLEMENT PRStatus
-nssATAV_verifyPointer
-(
-  NSSATAV *atav
-)
-{
-  PRStatus rv;
-
-  rv = nssPointerTracker_initialize(&atav_pointer_tracker);
-  if( PR_SUCCESS != rv ) {
-    return PR_FAILURE;
-  }
-
-  rv = nssPointerTracker_verify(&atav_pointer_tracker, atav);
-  if( PR_SUCCESS != rv ) {
-    nss_SetError(NSS_ERROR_INVALID_ATAV);
-    return PR_FAILURE;
-  }
-
-  return PR_SUCCESS;
-}
-#endif /* DEBUG */
-
-typedef struct {
-  NSSBER oid;
-  NSSBER value;
-} atav_holder;
-
-static const nssASN1Template nss_atav_template[] = {
-  { nssASN1_SEQUENCE, 0, NULL, sizeof(atav_holder) },
-  { nssASN1_OBJECT_ID, nsslibc_offsetof(atav_holder, oid), NULL, 0 },
-  { nssASN1_ANY, nsslibc_offsetof(atav_holder, value), NULL, 0 },
-  { 0, 0, NULL, 0 }
-};
-
-/*
- * There are several common attributes, with well-known type aliases
- * and value semantics.  This table lists the ones we recognize.
- */
-
-struct nss_attribute_data_str {
-  const NSSOID **oid;
-  nssStringType stringType;
-  PRUint32 minStringLength;
-  PRUint32 maxStringLength; /* zero for no limit */
-};
-
-static const struct nss_attribute_data_str nss_attribute_data[] = {
-  { &NSS_OID_X520_NAME,                     
-    nssStringType_DirectoryString, 1, 32768 },
-  { &NSS_OID_X520_COMMON_NAME,              
-    nssStringType_DirectoryString, 1,    64 },
-  { &NSS_OID_X520_SURNAME,                  
-    nssStringType_DirectoryString, 1,    40 },
-  { &NSS_OID_X520_GIVEN_NAME,               
-    nssStringType_DirectoryString, 1,    16 },
-  { &NSS_OID_X520_INITIALS,                 
-    nssStringType_DirectoryString, 1,     5 },
-  { &NSS_OID_X520_GENERATION_QUALIFIER,     
-    nssStringType_DirectoryString, 1,     3 },
-  { &NSS_OID_X520_DN_QUALIFIER,             
-    nssStringType_PrintableString, 1,     0 },
-  { &NSS_OID_X520_COUNTRY_NAME,             
-    nssStringType_PrintableString, 2,     2 },
-  { &NSS_OID_X520_LOCALITY_NAME,            
-    nssStringType_DirectoryString, 1,   128 },
-  { &NSS_OID_X520_STATE_OR_PROVINCE_NAME,   
-    nssStringType_DirectoryString, 1,   128 },
-  { &NSS_OID_X520_ORGANIZATION_NAME,        
-    nssStringType_DirectoryString, 1,    64 },
-  { &NSS_OID_X520_ORGANIZATIONAL_UNIT_NAME, 
-    nssStringType_DirectoryString, 1,
-    /*
-     * Note, draft #11 defines both "32" and "64" for this maximum,
-     * in two separate places.  Until it's settled, "conservative
-     * in what you send."  We're always liberal in what we accept.
-     */
-                                         32 },
-  { &NSS_OID_X520_TITLE,                    
-    nssStringType_DirectoryString, 1,    64 },
-  { &NSS_OID_RFC1274_EMAIL,                 
-    nssStringType_PHGString,       1,   128 }
-};
-
-PRUint32 nss_attribute_data_quantity = 
-  (sizeof(nss_attribute_data)/sizeof(nss_attribute_data[0]));
-
-static nssStringType
-nss_attr_underlying_string_form
-(
-  nssStringType type,
-  void *data
-)
-{
-  if( nssStringType_DirectoryString == type ) {
-    PRUint8 tag = *(PRUint8 *)data;
-    switch( tag & nssASN1_TAGNUM_MASK ) {
-    case 20:
-      /*
-       * XXX fgmr-- we have to accept Latin-1 for Teletex; (see
-       * below) but is T61 a suitable value for "Latin-1"?
-       */
-      return nssStringType_TeletexString;
-    case 19:
-      return nssStringType_PrintableString;
-    case 28:
-      return nssStringType_UniversalString;
-    case 30:
-      return nssStringType_BMPString;
-    case 12:
-      return nssStringType_UTF8String;
-    default:
-      return nssStringType_Unknown;
-    }
-  }
-
-  return type;
-}
-    
-
-/*
- * This routine decodes the attribute value, in a type-specific way.
- *
- */
-
-static NSSUTF8 *
-nss_attr_to_utf8
-(
-  NSSArena *arenaOpt,
-  const NSSOID *oid,
-  NSSItem *item,
-  nssStringType *stringForm
-)
-{
-  NSSUTF8 *rv = (NSSUTF8 *)NULL;
-  PRUint32 i;
-  const struct nss_attribute_data_str *which = 
-    (struct nss_attribute_data_str *)NULL;
-  PRUint32 len = 0;
-
-  for( i = 0; i < nss_attribute_data_quantity; i++ ) {
-    if( *(nss_attribute_data[ i ].oid) == oid ) {
-      which = &nss_attribute_data[i];
-      break;
-    }
-  }
-
-  if( (struct nss_attribute_data_str *)NULL == which ) {
-    /* Unknown OID.  Encode it as hex. */
-    PRUint8 *c;
-    PRUint8 *d = (PRUint8 *)item->data;
-    PRUint32 amt = item->size;
-
-    if( item->size >= 0x7FFFFFFF ) {
-      nss_SetError(NSS_ERROR_INVALID_STRING);
-      return (NSSUTF8 *)NULL;